one-model-router 0.0.10 → 0.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/package.json +1 -1
- package/src/admin.js +941 -941
- package/src/balances.js +61 -61
- package/src/boot.js +117 -117
- package/src/channels/buddy.js +2031 -2031
- package/src/channels/cline.js +753 -753
- package/src/channels/codearts.js +2051 -2051
- package/src/channels/comate.js +830 -830
- package/src/channels/doubaowork.js +1784 -1784
- package/src/channels/freebuff.js +1316 -1316
- package/src/channels/gemini.js +1721 -1721
- package/src/channels/index.js +270 -270
- package/src/channels/joycode.js +936 -936
- package/src/channels/kimi.js +572 -572
- package/src/channels/lobsterai.js +1226 -1226
- package/src/channels/loomy.js +1032 -1032
- package/src/channels/miaoshou.js +1396 -1396
- package/src/channels/mimo.js +474 -474
- package/src/channels/minimax.js +1451 -1451
- package/src/channels/qoder-wasm.js +434 -434
- package/src/channels/qoder.js +1619 -1619
- package/src/channels/raccoon.js +1842 -1842
- package/src/channels/tabbit.js +1457 -1457
- package/src/channels/trae.js +1405 -1405
- package/src/channels/zcode-global.js +35 -35
- package/src/channels/zcode.js +2085 -2085
- package/src/checkin.js +496 -496
- package/src/credits.js +464 -464
- package/src/crypto.js +132 -132
- package/src/free-models.js +683 -683
- package/src/gateway.js +596 -578
- package/src/health.js +86 -86
- package/src/model-key.js +35 -35
- package/src/paths.js +96 -96
- package/src/probe.js +318 -318
- package/src/providers/builtin.js +626 -626
- package/src/providers/index.js +483 -457
- package/src/providers/kilo.js +111 -111
- package/src/providers/last-good.js +69 -69
- package/src/providers/modelsdev.js +242 -242
- package/src/providers/openai-compat.js +312 -312
- package/src/providers/opencode/bun-fetch.js +226 -226
- package/src/providers/opencode/lane.js +186 -186
- package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
- package/src/providers/opencode/o2a/asset-source.js +43 -43
- package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
- package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
- package/src/providers/opencode/o2a/entry.js +17 -17
- package/src/providers/opencode/o2a/gateway-body.js +42 -42
- package/src/providers/opencode/o2a/headers.js +133 -133
- package/src/providers/opencode/o2a/identity.js +148 -148
- package/src/providers/opencode/o2a/official-prompt.js +191 -191
- package/src/providers/opencode/o2a/official-tools.js +110 -110
- package/src/providers/opencode/o2a/tool-renames.js +217 -217
- package/src/providers/opencode/o2a/toolshape.js +418 -418
- package/src/providers/opencode/o2a/version.js +37 -37
- package/src/providers/opencode/upstream.js +403 -403
- package/src/providers/opencode/wire.js +496 -496
- package/src/providers/opencode.js +652 -652
- package/src/router.js +629 -629
- package/src/server.js +33 -33
- package/src/store.js +467 -467
- package/src/sync/index.js +1529 -1529
- package/src/sync/login-preload.cjs +52 -52
- package/src/sync/noise.js +141 -141
- package/src/sync/relay-http.js +176 -176
- package/src/sync/remote-host.js +818 -818
- package/src/sync/remote-http.js +112 -112
- package/src/sync/remote-login.js +657 -657
- package/src/sync/remote-pairing.js +204 -204
- package/src/sync/remote-protocol.js +321 -321
- package/src/sync/snapshot.js +211 -211
- package/src/util.js +334 -334
- package/web/app.js +3972 -3972
- package/web/index.html +32 -32
- package/web/style.css +971 -971
package/src/checkin.js
CHANGED
|
@@ -1,496 +1,496 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 渠道原生自动签到:UTC+8 每日一次、启动延迟调度、按渠道记账。
|
|
3
|
-
*
|
|
4
|
-
* 执行体直接复用 credits.js 的 claimAllProviders()(逐渠道顺序领取,单渠道
|
|
5
|
-
* 失败不中断)。「哪些渠道能签到」由渠道自身是否实现 claimCredits 派生
|
|
6
|
-
* (creditsCapabilities),不另维护名单;zcode/zcode-global 已实现基础领取
|
|
7
|
-
*(需 captcha 时手动处理)、raccoon 的「领取」是 GET setting_info 触发的
|
|
8
|
-
* 每日积分发放/有效期延长(见 channels/raccoon.js);gemini/cline 在本项目里
|
|
9
|
-
* 根本没有 claimCredits,claimAllProviders 自动跳过,不存在「有代价的调用」。
|
|
10
|
-
*
|
|
11
|
-
* ⚠️ 记账口径(按渠道,不能用全局 claimed+alreadyClaimed 代替):
|
|
12
|
-
* 每轮把每个渠道结算成 channelClaimState 三态(见 credits.js):
|
|
13
|
-
* covered —— 能证明「今天这一轮已被处理」,当天不再跑;
|
|
14
|
-
* pending —— 稍后要重试(渠道声明 pending,或本轮出错);
|
|
15
|
-
* terminal —— 终态(未开通/无活动),今天不必再跑。
|
|
16
|
-
* lastDate 只在至少一个渠道 covered 时才写(表示「今天确实结算过」);
|
|
17
|
-
* 同时把 pending 渠道 id 存进文档,之后的自检**只重跑这些渠道**。
|
|
18
|
-
* Qoder 每日 10:00(UTC+8)才刷新,刷新前那轮返回 pending —— 若按全局
|
|
19
|
-
* coversToday 记账,trae 等渠道一领到就写 lastDate,10 点后的 Qoder 新额度
|
|
20
|
-
* 整天漏领(不可逆方向);按渠道记 pending 才能到点补领。
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
import { loadSettings, loadCheckin, saveCheckin, emitRuntimeEvent } from './store.js'
|
|
24
|
-
import { claimAllProviders, describeChannel, channelClaimState, claimUnitTotals, claimNoteText, claimAccountRows } from './credits.js'
|
|
25
|
-
import { CHANNELS } from './channels/index.js'
|
|
26
|
-
import { utc8Date } from './util.js'
|
|
27
|
-
|
|
28
|
-
/** channelClaimState 的合法取值(sanitize 用;定义在 credits.js)。 */
|
|
29
|
-
const CHANNEL_STATES = new Set(['covered', 'pending', 'terminal'])
|
|
30
|
-
/** 逐账号领取展示态(定义在 credits.js 的 claimAccountRows)。 */
|
|
31
|
-
const ACCOUNT_STATES = new Set(['claimed', 'already', 'pending', 'inactive', 'failed'])
|
|
32
|
-
const CHANNEL_IDS = CHANNELS.map(ch => ch.meta.id)
|
|
33
|
-
/** 渠道 id → 展示名(表格「渠道名」列的回填用)。 */
|
|
34
|
-
const CHANNEL_LABELS = new Map(CHANNELS.map(ch => [ch.meta.id, ch.meta.label]))
|
|
35
|
-
/** 待重试渠道的最小重试间隔(自检 15 分钟一次,pending 通常要等到渠道刷新点)。 */
|
|
36
|
-
const PENDING_RETRY_GAP_MS = 30 * 60_000
|
|
37
|
-
|
|
38
|
-
// ── 文档(data/checkin.json 的 auto 段;读写者只有本文件与状态接口)─────────
|
|
39
|
-
|
|
40
|
-
/** 旧文档没有 pending 字段;未知渠道 id 一律丢弃,避免引用已删渠道。 */
|
|
41
|
-
function sanitizeProviders(value) {
|
|
42
|
-
if (!Array.isArray(value)) return []
|
|
43
|
-
const known = new Set(CHANNEL_IDS)
|
|
44
|
-
const out = []
|
|
45
|
-
for (const item of value) {
|
|
46
|
-
if (typeof item !== 'string' || item.length === 0) continue
|
|
47
|
-
if (!known.has(item)) continue
|
|
48
|
-
if (out.includes(item)) continue
|
|
49
|
-
out.push(item)
|
|
50
|
-
if (out.length >= 24) break
|
|
51
|
-
}
|
|
52
|
-
return out
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* 旧文档的兼容回读:老记录只有 provider/text/state,表格列从 text 里补。
|
|
57
|
-
* 积分 —— 从「1 个 +100积分」「2 个 +94.54MToken, +100积分」里解析;
|
|
58
|
-
* 备注 —— 取第一个逗号之后的说明(如「今天的每日活动尚未刷新…」);
|
|
59
|
-
* 时间 —— 用那一轮的 lastAt。
|
|
60
|
-
*/
|
|
61
|
-
function legacyChannelFields(text, lastAt) {
|
|
62
|
-
const credit = { token: 0, credit: 0 }
|
|
63
|
-
for (const match of text.matchAll(/([+-]?\d+(?:\.\d+)?)\s*([MK]?)(积分|Token)/g)) {
|
|
64
|
-
const value = Number(match[1]) * (match[2] === 'M' ? 1e6 : match[2] === 'K' ? 1e3 : 1)
|
|
65
|
-
if (!Number.isFinite(value)) continue
|
|
66
|
-
if (match[3] === 'Token') credit.token += value
|
|
67
|
-
else credit.credit += value
|
|
68
|
-
}
|
|
69
|
-
const comma = text.indexOf(',')
|
|
70
|
-
let note = comma >= 0 ? text.slice(comma + 1).trim() : ''
|
|
71
|
-
// 「1 个今天已领」没有逗号:这种也要落到备注里(与 claimNoteText 同口径)
|
|
72
|
-
if (note === '' && text.includes('今天已领')) note = '今天已领'
|
|
73
|
-
return { credit, at: lastAt, note }
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/** 逐账号领取明细(小程序渠道详情页按账号归位展示):只留展示字段,丢弃脏项。 */
|
|
77
|
-
function sanitizeClaimAccounts(value) {
|
|
78
|
-
if (!Array.isArray(value)) return []
|
|
79
|
-
const out = []
|
|
80
|
-
for (const item of value) {
|
|
81
|
-
if (item === null || typeof item !== 'object' || Array.isArray(item)) continue
|
|
82
|
-
const accountId = typeof item.accountId === 'string' ? item.accountId.slice(0, 80) : ''
|
|
83
|
-
if (accountId === '' || !ACCOUNT_STATES.has(item.state)) continue
|
|
84
|
-
out.push({
|
|
85
|
-
accountId,
|
|
86
|
-
label: typeof item.label === 'string' ? item.label.slice(0, 60) : '',
|
|
87
|
-
state: item.state,
|
|
88
|
-
gain: typeof item.gain === 'string' ? item.gain.slice(0, 40) : '',
|
|
89
|
-
// 所得数值口径(小程序按单位分组求和用);无所得时归零并清掉单位
|
|
90
|
-
gainUnit: item.gainValue > 0 && (item.gainUnit === 'token' || item.gainUnit === 'credit') ? item.gainUnit : '',
|
|
91
|
-
gainValue: item.gainValue > 0 && Number.isFinite(item.gainValue) ? item.gainValue : 0,
|
|
92
|
-
note: typeof item.note === 'string' ? item.note.slice(0, 120) : '',
|
|
93
|
-
at: typeof item.at === 'number' && Number.isFinite(item.at) && item.at > 0 ? item.at : 0,
|
|
94
|
-
})
|
|
95
|
-
if (out.length >= 24) break
|
|
96
|
-
}
|
|
97
|
-
return out
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
function sanitizeAuto(raw) {
|
|
101
|
-
const doc = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
|
102
|
-
const ms = value => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0)
|
|
103
|
-
const num = value => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
|
|
104
|
-
const lastAt = ms(doc.lastAt)
|
|
105
|
-
const channels = []
|
|
106
|
-
if (Array.isArray(doc.channels)) {
|
|
107
|
-
for (const item of doc.channels) {
|
|
108
|
-
if (item === null || typeof item !== 'object' || Array.isArray(item)) continue
|
|
109
|
-
if (typeof item.provider !== 'string' || item.provider.length === 0) continue
|
|
110
|
-
const state = CHANNEL_STATES.has(item.state) ? item.state : ''
|
|
111
|
-
const text = typeof item.text === 'string' ? item.text.slice(0, 120) : ''
|
|
112
|
-
// 老记录没有 label/credit/at/note:按渠道注册表与旧文本补齐。
|
|
113
|
-
const legacy = legacyChannelFields(text, lastAt)
|
|
114
|
-
const hasCredit = item.credit !== undefined || item.claimed !== undefined
|
|
115
|
-
channels.push({
|
|
116
|
-
provider: item.provider,
|
|
117
|
-
label: typeof item.label === 'string'
|
|
118
|
-
? item.label.slice(0, 60)
|
|
119
|
-
: (CHANNEL_LABELS.get(item.provider) ?? ''),
|
|
120
|
-
text,
|
|
121
|
-
// 面板表格列:领取所得(分单位)/ 领取时间 / 备注
|
|
122
|
-
credit: hasCredit
|
|
123
|
-
? { token: num(item.credit?.token), credit: num(item.credit?.credit) }
|
|
124
|
-
: legacy.credit,
|
|
125
|
-
claimed: num(item.claimed),
|
|
126
|
-
at: ms(item.at) || legacy.at,
|
|
127
|
-
note: typeof item.note === 'string' ? item.note.slice(0, 120) : legacy.note,
|
|
128
|
-
// 逐账号领取情况(小程序详情页把这条拆到各账号行内展示)
|
|
129
|
-
accounts: sanitizeClaimAccounts(item.accounts),
|
|
130
|
-
...state !== '' ? { state } : {},
|
|
131
|
-
})
|
|
132
|
-
if (channels.length >= 24) break
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
return {
|
|
136
|
-
lastDate: typeof doc.lastDate === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(doc.lastDate) ? doc.lastDate : '',
|
|
137
|
-
lastAt: ms(doc.lastAt),
|
|
138
|
-
lastResult: typeof doc.lastResult === 'string' ? doc.lastResult : '',
|
|
139
|
-
channels,
|
|
140
|
-
pending: sanitizeProviders(doc.pending),
|
|
141
|
-
dismissedRunAt: ms(doc.dismissedRunAt),
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
function loadAutoDoc() {
|
|
146
|
-
return sanitizeAuto(loadCheckin().auto)
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
function saveAutoDoc(auto) {
|
|
150
|
-
saveCheckin({ auto })
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
// ── 状态 ─────────────────────────────────────────────────────────────────────
|
|
154
|
-
|
|
155
|
-
let running = false
|
|
156
|
-
let inflight = null
|
|
157
|
-
let log = () => {}
|
|
158
|
-
|
|
159
|
-
export function autoCheckinEnabled() {
|
|
160
|
-
return loadSettings().checkin?.enabled !== false
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/** 面板状态(enabled 实时读 settings;ranToday 供调度与 UI 共用)。 */
|
|
164
|
-
export function autoCheckinState(nowMs = Date.now()) {
|
|
165
|
-
const auto = loadAutoDoc()
|
|
166
|
-
const today = utc8Date(nowMs)
|
|
167
|
-
return {
|
|
168
|
-
enabled: autoCheckinEnabled(),
|
|
169
|
-
lastDate: auto.lastDate,
|
|
170
|
-
ranToday: auto.lastDate !== '' && auto.lastDate === today,
|
|
171
|
-
running,
|
|
172
|
-
lastResult: auto.lastResult,
|
|
173
|
-
lastAt: auto.lastAt,
|
|
174
|
-
// 今天结算后仍要重试的渠道(如 Qoder 10:00 刷新前那一轮)
|
|
175
|
-
pending: auto.pending.map(item => item),
|
|
176
|
-
channels: auto.channels.map(entry => ({ ...entry })),
|
|
177
|
-
// 面板据此决定要不要渲染那行常驻状态文字
|
|
178
|
-
dismissed: auto.lastAt > 0 && auto.dismissedRunAt === auto.lastAt,
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/** 关闭常驻状态文字(记的是这一轮 lastAt;新一轮跑完 lastAt 变了会自动回来)。 */
|
|
183
|
-
export function dismissAutoCheckin() {
|
|
184
|
-
const auto = loadAutoDoc()
|
|
185
|
-
saveAutoDoc({ ...auto, dismissedRunAt: auto.lastAt })
|
|
186
|
-
const state = autoCheckinState()
|
|
187
|
-
emitRuntimeEvent('auto-checkin', state)
|
|
188
|
-
return state
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
/**
|
|
192
|
-
* 手动领取(小程序「签到领积分」)记账:把这一轮结果写进 auto 文档的对应渠道条目
|
|
193
|
-
* (含逐账号明细),供小程序渠道详情页按账号展示;不动 lastDate(那是自动签到
|
|
194
|
-
* 「今日已结算」的标记),只把 pending 清单按本轮结算状态对齐。
|
|
195
|
-
*/
|
|
196
|
-
export function recordChannelClaim(providerId, result, nowMs = Date.now()) {
|
|
197
|
-
const auto = loadAutoDoc()
|
|
198
|
-
const summary = result?.summary && typeof result.summary === 'object' ? result.summary : null
|
|
199
|
-
const state = channelClaimState(summary)
|
|
200
|
-
const entry = {
|
|
201
|
-
provider: providerId,
|
|
202
|
-
label: CHANNEL_LABELS.get(providerId) ?? '',
|
|
203
|
-
text: summary ? describeChannel(summary) : '出错',
|
|
204
|
-
credit: claimUnitTotals(summary),
|
|
205
|
-
claimed: summary?.claimed ?? 0,
|
|
206
|
-
at: nowMs,
|
|
207
|
-
note: claimNoteText(summary, state, ''),
|
|
208
|
-
state,
|
|
209
|
-
accounts: claimAccountRows(result?.results, nowMs),
|
|
210
|
-
}
|
|
211
|
-
const pending = state === 'pending'
|
|
212
|
-
? (auto.pending.includes(providerId) ? auto.pending : [...auto.pending, providerId])
|
|
213
|
-
: auto.pending.filter(id => id !== providerId)
|
|
214
|
-
saveAutoDoc({ ...auto, channels: mergeChannels(auto.channels, [entry]), pending })
|
|
215
|
-
const next = autoCheckinState(nowMs)
|
|
216
|
-
emitRuntimeEvent('auto-checkin', next)
|
|
217
|
-
return next
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// ── 执行 ─────────────────────────────────────────────────────────────────────
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* 本轮各渠道的记账结果:covered 计数 + 待重试清单。
|
|
224
|
-
* 用 entry.state(claimAllProviders 已按 channelClaimState 结算好),
|
|
225
|
-
* 出错渠道 state 也是 pending —— 网络抖一下不会让当天彻底放弃。
|
|
226
|
-
*/
|
|
227
|
-
function settleRun(result, at) {
|
|
228
|
-
let covered = 0
|
|
229
|
-
const pending = []
|
|
230
|
-
const channels = []
|
|
231
|
-
for (const entry of result.providers ?? []) {
|
|
232
|
-
const state = CHANNEL_STATES.has(entry?.state) ? entry.state : channelClaimState(entry?.summary)
|
|
233
|
-
if (state === 'covered') covered += 1
|
|
234
|
-
if (state === 'pending' && !pending.includes(entry.provider)) pending.push(entry.provider)
|
|
235
|
-
const summary = entry.ok ? entry.summary : null
|
|
236
|
-
channels.push({
|
|
237
|
-
provider: entry.provider,
|
|
238
|
-
label: typeof entry.label === 'string' ? entry.label : '',
|
|
239
|
-
text: entry.ok ? describeChannel(entry.summary) : '出错',
|
|
240
|
-
credit: claimUnitTotals(summary),
|
|
241
|
-
claimed: summary?.claimed ?? 0,
|
|
242
|
-
at,
|
|
243
|
-
note: claimNoteText(summary, state, entry.message),
|
|
244
|
-
state,
|
|
245
|
-
accounts: claimAccountRows(entry.ok ? entry.results : [], at),
|
|
246
|
-
})
|
|
247
|
-
}
|
|
248
|
-
return { covered, pending, channels }
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
/**
|
|
252
|
-
* 跑一轮领取。only 缺省跑全部渠道;传了只跑这些(重试 pending 渠道用)。
|
|
253
|
-
* 记不记 lastDate 看有没有渠道 covered;pending 渠道无论记不记都要保存,
|
|
254
|
-
* 否则「全 pending」那轮会被下次自检当成已结算而漏掉。
|
|
255
|
-
*/
|
|
256
|
-
async function performRun(only = null) {
|
|
257
|
-
const options = only === null ? {} : { only }
|
|
258
|
-
const result = await claimAllProviders(options)
|
|
259
|
-
const now = Date.now()
|
|
260
|
-
const settled = settleRun(result, now)
|
|
261
|
-
const marked = settled.covered > 0
|
|
262
|
-
saveAutoDoc({
|
|
263
|
-
lastDate: marked ? utc8Date(now) : loadAutoDoc().lastDate,
|
|
264
|
-
lastAt: now,
|
|
265
|
-
lastResult: result.result ?? '',
|
|
266
|
-
channels: only === null ? settled.channels : mergeChannels(loadAutoDoc().channels, settled.channels),
|
|
267
|
-
pending: settled.pending,
|
|
268
|
-
// 新一轮跑完要清掉上一次的「已关闭」标记,否则用户关过一次后,
|
|
269
|
-
// 明天的新结果会被旧标记静默藏住(dismissed 判据是 lastAt 相等)。
|
|
270
|
-
dismissedRunAt: 0,
|
|
271
|
-
})
|
|
272
|
-
const state = autoCheckinState(now)
|
|
273
|
-
emitRuntimeEvent('auto-checkin', state)
|
|
274
|
-
return { marked, result, state }
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
/** 重试只覆盖本轮跑过的渠道,其余渠道沿用上一轮的记录。 */
|
|
278
|
-
function mergeChannels(previous, current) {
|
|
279
|
-
const merged = previous.map(entry => ({ ...entry }))
|
|
280
|
-
for (const entry of current) {
|
|
281
|
-
const index = merged.findIndex(item => item.provider === entry.provider)
|
|
282
|
-
if (index >= 0) merged[index] = entry
|
|
283
|
-
else merged.push(entry)
|
|
284
|
-
}
|
|
285
|
-
return merged.slice(0, 24)
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/**
|
|
289
|
-
* 到点才跑:开关打开 且 今天(UTC+8)还没全部结算。
|
|
290
|
-
* 判定是「已记账 且 没有待重试渠道」—— 有 pending 时只重跑那些渠道,
|
|
291
|
-
* 让 Qoder 这类 10:00 才刷新的活动当天能补领,而不重领其他渠道。
|
|
292
|
-
* 重试间隔放宽到 30 分钟(自检本身 15 分钟一次):刷新前的 pending 会一直
|
|
293
|
-
* 存在到刷新点,没必要每次自检都打一遍上游。
|
|
294
|
-
*/
|
|
295
|
-
export function runIfDue(nowMs = Date.now()) {
|
|
296
|
-
if (inflight) return inflight
|
|
297
|
-
if (!autoCheckinEnabled()) return Promise.resolve()
|
|
298
|
-
const auto = loadAutoDoc()
|
|
299
|
-
const today = utc8Date(nowMs)
|
|
300
|
-
const settledToday = auto.lastDate !== '' && auto.lastDate === today
|
|
301
|
-
const retry = settledToday ? auto.pending.map(item => item) : null
|
|
302
|
-
if (settledToday && retry.length === 0) return Promise.resolve()
|
|
303
|
-
if (retry !== null && auto.lastAt > 0 && nowMs - auto.lastAt < PENDING_RETRY_GAP_MS) return Promise.resolve()
|
|
304
|
-
running = true
|
|
305
|
-
log(
|
|
306
|
-
retry === null
|
|
307
|
-
? 'auto check-in: due, running all channels'
|
|
308
|
-
: `auto check-in: retrying pending channels: ${retry.join(', ')}`,
|
|
309
|
-
)
|
|
310
|
-
const task = performRun(retry)
|
|
311
|
-
.then(out => {
|
|
312
|
-
const pending = out.state.pending ?? []
|
|
313
|
-
const tail = pending.length > 0 ? `,待重试:${pending.join(', ')}` : ''
|
|
314
|
-
log(`auto check-in finished${out.marked ? '' : '(未记入今日)'}: ${out.result?.result ?? ''}${tail}`)
|
|
315
|
-
})
|
|
316
|
-
.catch(error => log(`auto check-in failed: ${error?.message ?? error}`))
|
|
317
|
-
.finally(() => {
|
|
318
|
-
running = false
|
|
319
|
-
inflight = null
|
|
320
|
-
})
|
|
321
|
-
inflight = task
|
|
322
|
-
return task
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
// ── 智能调度 ────────────────────────────────────────────────────────────────
|
|
326
|
-
|
|
327
|
-
/**
|
|
328
|
-
* 渠道刷新时间配置(UTC+8)。
|
|
329
|
-
*
|
|
330
|
-
* 格式:{ channelId: { hour: number, minute: number, randomMinutes: number } }
|
|
331
|
-
* hour/minite: 每日执行时间(北京时间)
|
|
332
|
-
* randomMinutes: 随机延迟范围(分钟),用于避免集中请求
|
|
333
|
-
*/
|
|
334
|
-
const CHANNEL_SCHEDULE = {
|
|
335
|
-
// Qoder 国内版 - 北京时间 10:00 刷新,随机延迟 0-5 分钟
|
|
336
|
-
'qodercn': { hour: 10, minute: 0, randomMinutes: 5 },
|
|
337
|
-
// Qoder 国际版 - 北京时间 10:00 刷新,随机延迟 0-5 分钟
|
|
338
|
-
'qoder': { hour: 10, minute: 0, randomMinutes: 5 },
|
|
339
|
-
// ZCode 国内版 - 北京时间 19:00 刷新,随机延迟 0-10 分钟(与国际版同上游同活动)
|
|
340
|
-
'zcode': { hour: 19, minute: 0, randomMinutes: 10 },
|
|
341
|
-
// ZCode Global - 北京时间 19:00 刷新,随机延迟 0-10 分钟
|
|
342
|
-
'zcode-global': { hour: 19, minute: 0, randomMinutes: 10 },
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
/** 获取某渠道的下次执行时间(毫秒时间戳)。 */
|
|
346
|
-
function getNextChannelRunTime(channelId) {
|
|
347
|
-
const config = CHANNEL_SCHEDULE[channelId]
|
|
348
|
-
if (!config) return null
|
|
349
|
-
|
|
350
|
-
const now = new Date()
|
|
351
|
-
const target = new Date(now)
|
|
352
|
-
target.setHours(config.hour, config.minute, 0, 0)
|
|
353
|
-
|
|
354
|
-
// 如果今天已过,安排到明天
|
|
355
|
-
if (now > target) {
|
|
356
|
-
target.setDate(target.getDate() + 1)
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
// 添加随机延迟
|
|
360
|
-
const randomDelay = Math.random() * config.randomMinutes * 60_000
|
|
361
|
-
return target.getTime() + randomDelay
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
/** 检查是否有渠道需要智能调度执行。 */
|
|
365
|
-
function hasScheduledChannels(auto) {
|
|
366
|
-
const pending = auto.pending ?? []
|
|
367
|
-
const covered = new Set()
|
|
368
|
-
|
|
369
|
-
// 从 channels 数组中提取 covered 状态的渠道
|
|
370
|
-
for (const ch of auto.channels ?? []) {
|
|
371
|
-
if (ch.state === 'covered') {
|
|
372
|
-
covered.add(ch.provider)
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
// 检查 pending 或未覆盖的渠道是否有 scheduled 配置
|
|
377
|
-
const allChannelIds = new Set([...pending, ...CHANNEL_IDS])
|
|
378
|
-
for (const id of allChannelIds) {
|
|
379
|
-
if (!covered.has(id) && CHANNEL_SCHEDULE[id]) {
|
|
380
|
-
return true
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
return false
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
/** 计算距离下次 scheduled 执行的等待时间(毫秒)。 */
|
|
388
|
-
function getWaitTimeForScheduledChannels(auto) {
|
|
389
|
-
const now = Date.now()
|
|
390
|
-
let minWaitTime = Infinity
|
|
391
|
-
|
|
392
|
-
const pending = auto.pending ?? []
|
|
393
|
-
const covered = new Set()
|
|
394
|
-
for (const ch of auto.channels ?? []) {
|
|
395
|
-
if (ch.state === 'covered') {
|
|
396
|
-
covered.add(ch.provider)
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
const allChannelIds = new Set([...pending, ...CHANNEL_IDS])
|
|
401
|
-
for (const id of allChannelIds) {
|
|
402
|
-
if (!covered.has(id) && CHANNEL_SCHEDULE[id]) {
|
|
403
|
-
const nextRun = getNextChannelRunTime(id)
|
|
404
|
-
if (nextRun) {
|
|
405
|
-
const waitTime = nextRun - now
|
|
406
|
-
minWaitTime = Math.min(minWaitTime, waitTime)
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
return minWaitTime === Infinity ? null : minWaitTime
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
/**
|
|
415
|
-
* 启动智能调度:根据渠道刷新时间动态调整自检周期。
|
|
416
|
-
* 如果有 pending 渠道且都是 scheduled 类型,则等到对应时间再执行。
|
|
417
|
-
*/
|
|
418
|
-
export function startSmartScheduler({ log: logger = () => {} } = {}) {
|
|
419
|
-
stopScheduler()
|
|
420
|
-
log = logger
|
|
421
|
-
|
|
422
|
-
const delayMs = parseDelayMs(loadSettings().checkin?.delayMs)
|
|
423
|
-
|
|
424
|
-
// 首次延迟执行
|
|
425
|
-
delayTimer = setTimeout(() => {
|
|
426
|
-
delayTimer = null
|
|
427
|
-
void runIfDue()
|
|
428
|
-
}, delayMs)
|
|
429
|
-
delayTimer.unref?.()
|
|
430
|
-
|
|
431
|
-
// 周期性自检,但根据 scheduled 情况动态调整间隔
|
|
432
|
-
periodicTimer = setInterval(() => {
|
|
433
|
-
const auto = loadAutoDoc()
|
|
434
|
-
|
|
435
|
-
// 检查是否有需要智能调度的渠道
|
|
436
|
-
if (hasScheduledChannels(auto)) {
|
|
437
|
-
const waitTime = getWaitTimeForScheduledChannels(auto)
|
|
438
|
-
|
|
439
|
-
if (waitTime !== null && waitTime > 0 && waitTime < 30 * 60_000) {
|
|
440
|
-
// 有 scheduled 渠道且等待时间在 30 分钟内,延长本次循环
|
|
441
|
-
log(`智能调度:等待 ${Math.round(waitTime / 60_000)} 分钟后执行 scheduled 渠道`)
|
|
442
|
-
|
|
443
|
-
// 设置一个短期定时器,在等待后检查
|
|
444
|
-
setTimeout(() => {
|
|
445
|
-
const updatedAuto = loadAutoDoc()
|
|
446
|
-
// 重新检查状态,可能已被手动触发或其他渠道覆盖
|
|
447
|
-
if (hasScheduledChannels(updatedAuto)) {
|
|
448
|
-
void runIfDue()
|
|
449
|
-
}
|
|
450
|
-
}, waitTime)
|
|
451
|
-
return
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
// 默认 15 分钟检查
|
|
456
|
-
runIfDue().catch(() => {})
|
|
457
|
-
}, 15 * 60_000)
|
|
458
|
-
periodicTimer.unref?.()
|
|
459
|
-
|
|
460
|
-
log(`智能调度器已启动(初始延迟 ${delayMs}ms, 周期 15min)`)
|
|
461
|
-
return { delayMs }
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
// ── 调度 ─────────────────────────────────────────────────────────────────────
|
|
465
|
-
|
|
466
|
-
let delayTimer = null
|
|
467
|
-
let periodicTimer = null
|
|
468
|
-
|
|
469
|
-
function parseDelayMs(raw) {
|
|
470
|
-
// ⚠️ 0 合法(立刻跑),不能用 `Number(x) || 默认`(0 是 falsy 会被吞)。
|
|
471
|
-
const parsed = Number(raw)
|
|
472
|
-
return Number.isFinite(parsed) && parsed >= 0 ? parsed : 15_000
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
/** 启动调度:延迟后若到期则跑一轮;之后每 15 分钟自检(跨天 / 长驻进程)。 */
|
|
476
|
-
export function startScheduler({ log: logger = () => {} } = {}) {
|
|
477
|
-
stopScheduler()
|
|
478
|
-
log = logger
|
|
479
|
-
const delayMs = parseDelayMs(loadSettings().checkin?.delayMs)
|
|
480
|
-
delayTimer = setTimeout(() => {
|
|
481
|
-
delayTimer = null
|
|
482
|
-
void runIfDue()
|
|
483
|
-
}, delayMs)
|
|
484
|
-
delayTimer.unref?.()
|
|
485
|
-
periodicTimer = setInterval(() => {
|
|
486
|
-
runIfDue().catch(() => {})
|
|
487
|
-
}, 15 * 60_000)
|
|
488
|
-
periodicTimer.unref?.()
|
|
489
|
-
log(`auto check-in scheduler started (delay ${delayMs}ms, period 15min)`)
|
|
490
|
-
return { delayMs }
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
export function stopScheduler() {
|
|
494
|
-
if (delayTimer) { clearTimeout(delayTimer); delayTimer = null }
|
|
495
|
-
if (periodicTimer) { clearInterval(periodicTimer); periodicTimer = null }
|
|
496
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* 渠道原生自动签到:UTC+8 每日一次、启动延迟调度、按渠道记账。
|
|
3
|
+
*
|
|
4
|
+
* 执行体直接复用 credits.js 的 claimAllProviders()(逐渠道顺序领取,单渠道
|
|
5
|
+
* 失败不中断)。「哪些渠道能签到」由渠道自身是否实现 claimCredits 派生
|
|
6
|
+
* (creditsCapabilities),不另维护名单;zcode/zcode-global 已实现基础领取
|
|
7
|
+
*(需 captcha 时手动处理)、raccoon 的「领取」是 GET setting_info 触发的
|
|
8
|
+
* 每日积分发放/有效期延长(见 channels/raccoon.js);gemini/cline 在本项目里
|
|
9
|
+
* 根本没有 claimCredits,claimAllProviders 自动跳过,不存在「有代价的调用」。
|
|
10
|
+
*
|
|
11
|
+
* ⚠️ 记账口径(按渠道,不能用全局 claimed+alreadyClaimed 代替):
|
|
12
|
+
* 每轮把每个渠道结算成 channelClaimState 三态(见 credits.js):
|
|
13
|
+
* covered —— 能证明「今天这一轮已被处理」,当天不再跑;
|
|
14
|
+
* pending —— 稍后要重试(渠道声明 pending,或本轮出错);
|
|
15
|
+
* terminal —— 终态(未开通/无活动),今天不必再跑。
|
|
16
|
+
* lastDate 只在至少一个渠道 covered 时才写(表示「今天确实结算过」);
|
|
17
|
+
* 同时把 pending 渠道 id 存进文档,之后的自检**只重跑这些渠道**。
|
|
18
|
+
* Qoder 每日 10:00(UTC+8)才刷新,刷新前那轮返回 pending —— 若按全局
|
|
19
|
+
* coversToday 记账,trae 等渠道一领到就写 lastDate,10 点后的 Qoder 新额度
|
|
20
|
+
* 整天漏领(不可逆方向);按渠道记 pending 才能到点补领。
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { loadSettings, loadCheckin, saveCheckin, emitRuntimeEvent } from './store.js'
|
|
24
|
+
import { claimAllProviders, describeChannel, channelClaimState, claimUnitTotals, claimNoteText, claimAccountRows } from './credits.js'
|
|
25
|
+
import { CHANNELS } from './channels/index.js'
|
|
26
|
+
import { utc8Date } from './util.js'
|
|
27
|
+
|
|
28
|
+
/** channelClaimState 的合法取值(sanitize 用;定义在 credits.js)。 */
|
|
29
|
+
const CHANNEL_STATES = new Set(['covered', 'pending', 'terminal'])
|
|
30
|
+
/** 逐账号领取展示态(定义在 credits.js 的 claimAccountRows)。 */
|
|
31
|
+
const ACCOUNT_STATES = new Set(['claimed', 'already', 'pending', 'inactive', 'failed'])
|
|
32
|
+
const CHANNEL_IDS = CHANNELS.map(ch => ch.meta.id)
|
|
33
|
+
/** 渠道 id → 展示名(表格「渠道名」列的回填用)。 */
|
|
34
|
+
const CHANNEL_LABELS = new Map(CHANNELS.map(ch => [ch.meta.id, ch.meta.label]))
|
|
35
|
+
/** 待重试渠道的最小重试间隔(自检 15 分钟一次,pending 通常要等到渠道刷新点)。 */
|
|
36
|
+
const PENDING_RETRY_GAP_MS = 30 * 60_000
|
|
37
|
+
|
|
38
|
+
// ── 文档(data/checkin.json 的 auto 段;读写者只有本文件与状态接口)─────────
|
|
39
|
+
|
|
40
|
+
/** 旧文档没有 pending 字段;未知渠道 id 一律丢弃,避免引用已删渠道。 */
|
|
41
|
+
function sanitizeProviders(value) {
|
|
42
|
+
if (!Array.isArray(value)) return []
|
|
43
|
+
const known = new Set(CHANNEL_IDS)
|
|
44
|
+
const out = []
|
|
45
|
+
for (const item of value) {
|
|
46
|
+
if (typeof item !== 'string' || item.length === 0) continue
|
|
47
|
+
if (!known.has(item)) continue
|
|
48
|
+
if (out.includes(item)) continue
|
|
49
|
+
out.push(item)
|
|
50
|
+
if (out.length >= 24) break
|
|
51
|
+
}
|
|
52
|
+
return out
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 旧文档的兼容回读:老记录只有 provider/text/state,表格列从 text 里补。
|
|
57
|
+
* 积分 —— 从「1 个 +100积分」「2 个 +94.54MToken, +100积分」里解析;
|
|
58
|
+
* 备注 —— 取第一个逗号之后的说明(如「今天的每日活动尚未刷新…」);
|
|
59
|
+
* 时间 —— 用那一轮的 lastAt。
|
|
60
|
+
*/
|
|
61
|
+
function legacyChannelFields(text, lastAt) {
|
|
62
|
+
const credit = { token: 0, credit: 0 }
|
|
63
|
+
for (const match of text.matchAll(/([+-]?\d+(?:\.\d+)?)\s*([MK]?)(积分|Token)/g)) {
|
|
64
|
+
const value = Number(match[1]) * (match[2] === 'M' ? 1e6 : match[2] === 'K' ? 1e3 : 1)
|
|
65
|
+
if (!Number.isFinite(value)) continue
|
|
66
|
+
if (match[3] === 'Token') credit.token += value
|
|
67
|
+
else credit.credit += value
|
|
68
|
+
}
|
|
69
|
+
const comma = text.indexOf(',')
|
|
70
|
+
let note = comma >= 0 ? text.slice(comma + 1).trim() : ''
|
|
71
|
+
// 「1 个今天已领」没有逗号:这种也要落到备注里(与 claimNoteText 同口径)
|
|
72
|
+
if (note === '' && text.includes('今天已领')) note = '今天已领'
|
|
73
|
+
return { credit, at: lastAt, note }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 逐账号领取明细(小程序渠道详情页按账号归位展示):只留展示字段,丢弃脏项。 */
|
|
77
|
+
function sanitizeClaimAccounts(value) {
|
|
78
|
+
if (!Array.isArray(value)) return []
|
|
79
|
+
const out = []
|
|
80
|
+
for (const item of value) {
|
|
81
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) continue
|
|
82
|
+
const accountId = typeof item.accountId === 'string' ? item.accountId.slice(0, 80) : ''
|
|
83
|
+
if (accountId === '' || !ACCOUNT_STATES.has(item.state)) continue
|
|
84
|
+
out.push({
|
|
85
|
+
accountId,
|
|
86
|
+
label: typeof item.label === 'string' ? item.label.slice(0, 60) : '',
|
|
87
|
+
state: item.state,
|
|
88
|
+
gain: typeof item.gain === 'string' ? item.gain.slice(0, 40) : '',
|
|
89
|
+
// 所得数值口径(小程序按单位分组求和用);无所得时归零并清掉单位
|
|
90
|
+
gainUnit: item.gainValue > 0 && (item.gainUnit === 'token' || item.gainUnit === 'credit') ? item.gainUnit : '',
|
|
91
|
+
gainValue: item.gainValue > 0 && Number.isFinite(item.gainValue) ? item.gainValue : 0,
|
|
92
|
+
note: typeof item.note === 'string' ? item.note.slice(0, 120) : '',
|
|
93
|
+
at: typeof item.at === 'number' && Number.isFinite(item.at) && item.at > 0 ? item.at : 0,
|
|
94
|
+
})
|
|
95
|
+
if (out.length >= 24) break
|
|
96
|
+
}
|
|
97
|
+
return out
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function sanitizeAuto(raw) {
|
|
101
|
+
const doc = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
|
102
|
+
const ms = value => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0)
|
|
103
|
+
const num = value => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
|
|
104
|
+
const lastAt = ms(doc.lastAt)
|
|
105
|
+
const channels = []
|
|
106
|
+
if (Array.isArray(doc.channels)) {
|
|
107
|
+
for (const item of doc.channels) {
|
|
108
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) continue
|
|
109
|
+
if (typeof item.provider !== 'string' || item.provider.length === 0) continue
|
|
110
|
+
const state = CHANNEL_STATES.has(item.state) ? item.state : ''
|
|
111
|
+
const text = typeof item.text === 'string' ? item.text.slice(0, 120) : ''
|
|
112
|
+
// 老记录没有 label/credit/at/note:按渠道注册表与旧文本补齐。
|
|
113
|
+
const legacy = legacyChannelFields(text, lastAt)
|
|
114
|
+
const hasCredit = item.credit !== undefined || item.claimed !== undefined
|
|
115
|
+
channels.push({
|
|
116
|
+
provider: item.provider,
|
|
117
|
+
label: typeof item.label === 'string'
|
|
118
|
+
? item.label.slice(0, 60)
|
|
119
|
+
: (CHANNEL_LABELS.get(item.provider) ?? ''),
|
|
120
|
+
text,
|
|
121
|
+
// 面板表格列:领取所得(分单位)/ 领取时间 / 备注
|
|
122
|
+
credit: hasCredit
|
|
123
|
+
? { token: num(item.credit?.token), credit: num(item.credit?.credit) }
|
|
124
|
+
: legacy.credit,
|
|
125
|
+
claimed: num(item.claimed),
|
|
126
|
+
at: ms(item.at) || legacy.at,
|
|
127
|
+
note: typeof item.note === 'string' ? item.note.slice(0, 120) : legacy.note,
|
|
128
|
+
// 逐账号领取情况(小程序详情页把这条拆到各账号行内展示)
|
|
129
|
+
accounts: sanitizeClaimAccounts(item.accounts),
|
|
130
|
+
...state !== '' ? { state } : {},
|
|
131
|
+
})
|
|
132
|
+
if (channels.length >= 24) break
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
lastDate: typeof doc.lastDate === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(doc.lastDate) ? doc.lastDate : '',
|
|
137
|
+
lastAt: ms(doc.lastAt),
|
|
138
|
+
lastResult: typeof doc.lastResult === 'string' ? doc.lastResult : '',
|
|
139
|
+
channels,
|
|
140
|
+
pending: sanitizeProviders(doc.pending),
|
|
141
|
+
dismissedRunAt: ms(doc.dismissedRunAt),
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function loadAutoDoc() {
|
|
146
|
+
return sanitizeAuto(loadCheckin().auto)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function saveAutoDoc(auto) {
|
|
150
|
+
saveCheckin({ auto })
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// ── 状态 ─────────────────────────────────────────────────────────────────────
|
|
154
|
+
|
|
155
|
+
let running = false
|
|
156
|
+
let inflight = null
|
|
157
|
+
let log = () => {}
|
|
158
|
+
|
|
159
|
+
export function autoCheckinEnabled() {
|
|
160
|
+
return loadSettings().checkin?.enabled !== false
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** 面板状态(enabled 实时读 settings;ranToday 供调度与 UI 共用)。 */
|
|
164
|
+
export function autoCheckinState(nowMs = Date.now()) {
|
|
165
|
+
const auto = loadAutoDoc()
|
|
166
|
+
const today = utc8Date(nowMs)
|
|
167
|
+
return {
|
|
168
|
+
enabled: autoCheckinEnabled(),
|
|
169
|
+
lastDate: auto.lastDate,
|
|
170
|
+
ranToday: auto.lastDate !== '' && auto.lastDate === today,
|
|
171
|
+
running,
|
|
172
|
+
lastResult: auto.lastResult,
|
|
173
|
+
lastAt: auto.lastAt,
|
|
174
|
+
// 今天结算后仍要重试的渠道(如 Qoder 10:00 刷新前那一轮)
|
|
175
|
+
pending: auto.pending.map(item => item),
|
|
176
|
+
channels: auto.channels.map(entry => ({ ...entry })),
|
|
177
|
+
// 面板据此决定要不要渲染那行常驻状态文字
|
|
178
|
+
dismissed: auto.lastAt > 0 && auto.dismissedRunAt === auto.lastAt,
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 关闭常驻状态文字(记的是这一轮 lastAt;新一轮跑完 lastAt 变了会自动回来)。 */
|
|
183
|
+
export function dismissAutoCheckin() {
|
|
184
|
+
const auto = loadAutoDoc()
|
|
185
|
+
saveAutoDoc({ ...auto, dismissedRunAt: auto.lastAt })
|
|
186
|
+
const state = autoCheckinState()
|
|
187
|
+
emitRuntimeEvent('auto-checkin', state)
|
|
188
|
+
return state
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* 手动领取(小程序「签到领积分」)记账:把这一轮结果写进 auto 文档的对应渠道条目
|
|
193
|
+
* (含逐账号明细),供小程序渠道详情页按账号展示;不动 lastDate(那是自动签到
|
|
194
|
+
* 「今日已结算」的标记),只把 pending 清单按本轮结算状态对齐。
|
|
195
|
+
*/
|
|
196
|
+
export function recordChannelClaim(providerId, result, nowMs = Date.now()) {
|
|
197
|
+
const auto = loadAutoDoc()
|
|
198
|
+
const summary = result?.summary && typeof result.summary === 'object' ? result.summary : null
|
|
199
|
+
const state = channelClaimState(summary)
|
|
200
|
+
const entry = {
|
|
201
|
+
provider: providerId,
|
|
202
|
+
label: CHANNEL_LABELS.get(providerId) ?? '',
|
|
203
|
+
text: summary ? describeChannel(summary) : '出错',
|
|
204
|
+
credit: claimUnitTotals(summary),
|
|
205
|
+
claimed: summary?.claimed ?? 0,
|
|
206
|
+
at: nowMs,
|
|
207
|
+
note: claimNoteText(summary, state, ''),
|
|
208
|
+
state,
|
|
209
|
+
accounts: claimAccountRows(result?.results, nowMs),
|
|
210
|
+
}
|
|
211
|
+
const pending = state === 'pending'
|
|
212
|
+
? (auto.pending.includes(providerId) ? auto.pending : [...auto.pending, providerId])
|
|
213
|
+
: auto.pending.filter(id => id !== providerId)
|
|
214
|
+
saveAutoDoc({ ...auto, channels: mergeChannels(auto.channels, [entry]), pending })
|
|
215
|
+
const next = autoCheckinState(nowMs)
|
|
216
|
+
emitRuntimeEvent('auto-checkin', next)
|
|
217
|
+
return next
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// ── 执行 ─────────────────────────────────────────────────────────────────────
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* 本轮各渠道的记账结果:covered 计数 + 待重试清单。
|
|
224
|
+
* 用 entry.state(claimAllProviders 已按 channelClaimState 结算好),
|
|
225
|
+
* 出错渠道 state 也是 pending —— 网络抖一下不会让当天彻底放弃。
|
|
226
|
+
*/
|
|
227
|
+
function settleRun(result, at) {
|
|
228
|
+
let covered = 0
|
|
229
|
+
const pending = []
|
|
230
|
+
const channels = []
|
|
231
|
+
for (const entry of result.providers ?? []) {
|
|
232
|
+
const state = CHANNEL_STATES.has(entry?.state) ? entry.state : channelClaimState(entry?.summary)
|
|
233
|
+
if (state === 'covered') covered += 1
|
|
234
|
+
if (state === 'pending' && !pending.includes(entry.provider)) pending.push(entry.provider)
|
|
235
|
+
const summary = entry.ok ? entry.summary : null
|
|
236
|
+
channels.push({
|
|
237
|
+
provider: entry.provider,
|
|
238
|
+
label: typeof entry.label === 'string' ? entry.label : '',
|
|
239
|
+
text: entry.ok ? describeChannel(entry.summary) : '出错',
|
|
240
|
+
credit: claimUnitTotals(summary),
|
|
241
|
+
claimed: summary?.claimed ?? 0,
|
|
242
|
+
at,
|
|
243
|
+
note: claimNoteText(summary, state, entry.message),
|
|
244
|
+
state,
|
|
245
|
+
accounts: claimAccountRows(entry.ok ? entry.results : [], at),
|
|
246
|
+
})
|
|
247
|
+
}
|
|
248
|
+
return { covered, pending, channels }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* 跑一轮领取。only 缺省跑全部渠道;传了只跑这些(重试 pending 渠道用)。
|
|
253
|
+
* 记不记 lastDate 看有没有渠道 covered;pending 渠道无论记不记都要保存,
|
|
254
|
+
* 否则「全 pending」那轮会被下次自检当成已结算而漏掉。
|
|
255
|
+
*/
|
|
256
|
+
async function performRun(only = null) {
|
|
257
|
+
const options = only === null ? {} : { only }
|
|
258
|
+
const result = await claimAllProviders(options)
|
|
259
|
+
const now = Date.now()
|
|
260
|
+
const settled = settleRun(result, now)
|
|
261
|
+
const marked = settled.covered > 0
|
|
262
|
+
saveAutoDoc({
|
|
263
|
+
lastDate: marked ? utc8Date(now) : loadAutoDoc().lastDate,
|
|
264
|
+
lastAt: now,
|
|
265
|
+
lastResult: result.result ?? '',
|
|
266
|
+
channels: only === null ? settled.channels : mergeChannels(loadAutoDoc().channels, settled.channels),
|
|
267
|
+
pending: settled.pending,
|
|
268
|
+
// 新一轮跑完要清掉上一次的「已关闭」标记,否则用户关过一次后,
|
|
269
|
+
// 明天的新结果会被旧标记静默藏住(dismissed 判据是 lastAt 相等)。
|
|
270
|
+
dismissedRunAt: 0,
|
|
271
|
+
})
|
|
272
|
+
const state = autoCheckinState(now)
|
|
273
|
+
emitRuntimeEvent('auto-checkin', state)
|
|
274
|
+
return { marked, result, state }
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** 重试只覆盖本轮跑过的渠道,其余渠道沿用上一轮的记录。 */
|
|
278
|
+
function mergeChannels(previous, current) {
|
|
279
|
+
const merged = previous.map(entry => ({ ...entry }))
|
|
280
|
+
for (const entry of current) {
|
|
281
|
+
const index = merged.findIndex(item => item.provider === entry.provider)
|
|
282
|
+
if (index >= 0) merged[index] = entry
|
|
283
|
+
else merged.push(entry)
|
|
284
|
+
}
|
|
285
|
+
return merged.slice(0, 24)
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* 到点才跑:开关打开 且 今天(UTC+8)还没全部结算。
|
|
290
|
+
* 判定是「已记账 且 没有待重试渠道」—— 有 pending 时只重跑那些渠道,
|
|
291
|
+
* 让 Qoder 这类 10:00 才刷新的活动当天能补领,而不重领其他渠道。
|
|
292
|
+
* 重试间隔放宽到 30 分钟(自检本身 15 分钟一次):刷新前的 pending 会一直
|
|
293
|
+
* 存在到刷新点,没必要每次自检都打一遍上游。
|
|
294
|
+
*/
|
|
295
|
+
export function runIfDue(nowMs = Date.now()) {
|
|
296
|
+
if (inflight) return inflight
|
|
297
|
+
if (!autoCheckinEnabled()) return Promise.resolve()
|
|
298
|
+
const auto = loadAutoDoc()
|
|
299
|
+
const today = utc8Date(nowMs)
|
|
300
|
+
const settledToday = auto.lastDate !== '' && auto.lastDate === today
|
|
301
|
+
const retry = settledToday ? auto.pending.map(item => item) : null
|
|
302
|
+
if (settledToday && retry.length === 0) return Promise.resolve()
|
|
303
|
+
if (retry !== null && auto.lastAt > 0 && nowMs - auto.lastAt < PENDING_RETRY_GAP_MS) return Promise.resolve()
|
|
304
|
+
running = true
|
|
305
|
+
log(
|
|
306
|
+
retry === null
|
|
307
|
+
? 'auto check-in: due, running all channels'
|
|
308
|
+
: `auto check-in: retrying pending channels: ${retry.join(', ')}`,
|
|
309
|
+
)
|
|
310
|
+
const task = performRun(retry)
|
|
311
|
+
.then(out => {
|
|
312
|
+
const pending = out.state.pending ?? []
|
|
313
|
+
const tail = pending.length > 0 ? `,待重试:${pending.join(', ')}` : ''
|
|
314
|
+
log(`auto check-in finished${out.marked ? '' : '(未记入今日)'}: ${out.result?.result ?? ''}${tail}`)
|
|
315
|
+
})
|
|
316
|
+
.catch(error => log(`auto check-in failed: ${error?.message ?? error}`))
|
|
317
|
+
.finally(() => {
|
|
318
|
+
running = false
|
|
319
|
+
inflight = null
|
|
320
|
+
})
|
|
321
|
+
inflight = task
|
|
322
|
+
return task
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ── 智能调度 ────────────────────────────────────────────────────────────────
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* 渠道刷新时间配置(UTC+8)。
|
|
329
|
+
*
|
|
330
|
+
* 格式:{ channelId: { hour: number, minute: number, randomMinutes: number } }
|
|
331
|
+
* hour/minite: 每日执行时间(北京时间)
|
|
332
|
+
* randomMinutes: 随机延迟范围(分钟),用于避免集中请求
|
|
333
|
+
*/
|
|
334
|
+
const CHANNEL_SCHEDULE = {
|
|
335
|
+
// Qoder 国内版 - 北京时间 10:00 刷新,随机延迟 0-5 分钟
|
|
336
|
+
'qodercn': { hour: 10, minute: 0, randomMinutes: 5 },
|
|
337
|
+
// Qoder 国际版 - 北京时间 10:00 刷新,随机延迟 0-5 分钟
|
|
338
|
+
'qoder': { hour: 10, minute: 0, randomMinutes: 5 },
|
|
339
|
+
// ZCode 国内版 - 北京时间 19:00 刷新,随机延迟 0-10 分钟(与国际版同上游同活动)
|
|
340
|
+
'zcode': { hour: 19, minute: 0, randomMinutes: 10 },
|
|
341
|
+
// ZCode Global - 北京时间 19:00 刷新,随机延迟 0-10 分钟
|
|
342
|
+
'zcode-global': { hour: 19, minute: 0, randomMinutes: 10 },
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** 获取某渠道的下次执行时间(毫秒时间戳)。 */
|
|
346
|
+
function getNextChannelRunTime(channelId) {
|
|
347
|
+
const config = CHANNEL_SCHEDULE[channelId]
|
|
348
|
+
if (!config) return null
|
|
349
|
+
|
|
350
|
+
const now = new Date()
|
|
351
|
+
const target = new Date(now)
|
|
352
|
+
target.setHours(config.hour, config.minute, 0, 0)
|
|
353
|
+
|
|
354
|
+
// 如果今天已过,安排到明天
|
|
355
|
+
if (now > target) {
|
|
356
|
+
target.setDate(target.getDate() + 1)
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// 添加随机延迟
|
|
360
|
+
const randomDelay = Math.random() * config.randomMinutes * 60_000
|
|
361
|
+
return target.getTime() + randomDelay
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** 检查是否有渠道需要智能调度执行。 */
|
|
365
|
+
function hasScheduledChannels(auto) {
|
|
366
|
+
const pending = auto.pending ?? []
|
|
367
|
+
const covered = new Set()
|
|
368
|
+
|
|
369
|
+
// 从 channels 数组中提取 covered 状态的渠道
|
|
370
|
+
for (const ch of auto.channels ?? []) {
|
|
371
|
+
if (ch.state === 'covered') {
|
|
372
|
+
covered.add(ch.provider)
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// 检查 pending 或未覆盖的渠道是否有 scheduled 配置
|
|
377
|
+
const allChannelIds = new Set([...pending, ...CHANNEL_IDS])
|
|
378
|
+
for (const id of allChannelIds) {
|
|
379
|
+
if (!covered.has(id) && CHANNEL_SCHEDULE[id]) {
|
|
380
|
+
return true
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
return false
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** 计算距离下次 scheduled 执行的等待时间(毫秒)。 */
|
|
388
|
+
function getWaitTimeForScheduledChannels(auto) {
|
|
389
|
+
const now = Date.now()
|
|
390
|
+
let minWaitTime = Infinity
|
|
391
|
+
|
|
392
|
+
const pending = auto.pending ?? []
|
|
393
|
+
const covered = new Set()
|
|
394
|
+
for (const ch of auto.channels ?? []) {
|
|
395
|
+
if (ch.state === 'covered') {
|
|
396
|
+
covered.add(ch.provider)
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const allChannelIds = new Set([...pending, ...CHANNEL_IDS])
|
|
401
|
+
for (const id of allChannelIds) {
|
|
402
|
+
if (!covered.has(id) && CHANNEL_SCHEDULE[id]) {
|
|
403
|
+
const nextRun = getNextChannelRunTime(id)
|
|
404
|
+
if (nextRun) {
|
|
405
|
+
const waitTime = nextRun - now
|
|
406
|
+
minWaitTime = Math.min(minWaitTime, waitTime)
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
return minWaitTime === Infinity ? null : minWaitTime
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* 启动智能调度:根据渠道刷新时间动态调整自检周期。
|
|
416
|
+
* 如果有 pending 渠道且都是 scheduled 类型,则等到对应时间再执行。
|
|
417
|
+
*/
|
|
418
|
+
export function startSmartScheduler({ log: logger = () => {} } = {}) {
|
|
419
|
+
stopScheduler()
|
|
420
|
+
log = logger
|
|
421
|
+
|
|
422
|
+
const delayMs = parseDelayMs(loadSettings().checkin?.delayMs)
|
|
423
|
+
|
|
424
|
+
// 首次延迟执行
|
|
425
|
+
delayTimer = setTimeout(() => {
|
|
426
|
+
delayTimer = null
|
|
427
|
+
void runIfDue()
|
|
428
|
+
}, delayMs)
|
|
429
|
+
delayTimer.unref?.()
|
|
430
|
+
|
|
431
|
+
// 周期性自检,但根据 scheduled 情况动态调整间隔
|
|
432
|
+
periodicTimer = setInterval(() => {
|
|
433
|
+
const auto = loadAutoDoc()
|
|
434
|
+
|
|
435
|
+
// 检查是否有需要智能调度的渠道
|
|
436
|
+
if (hasScheduledChannels(auto)) {
|
|
437
|
+
const waitTime = getWaitTimeForScheduledChannels(auto)
|
|
438
|
+
|
|
439
|
+
if (waitTime !== null && waitTime > 0 && waitTime < 30 * 60_000) {
|
|
440
|
+
// 有 scheduled 渠道且等待时间在 30 分钟内,延长本次循环
|
|
441
|
+
log(`智能调度:等待 ${Math.round(waitTime / 60_000)} 分钟后执行 scheduled 渠道`)
|
|
442
|
+
|
|
443
|
+
// 设置一个短期定时器,在等待后检查
|
|
444
|
+
setTimeout(() => {
|
|
445
|
+
const updatedAuto = loadAutoDoc()
|
|
446
|
+
// 重新检查状态,可能已被手动触发或其他渠道覆盖
|
|
447
|
+
if (hasScheduledChannels(updatedAuto)) {
|
|
448
|
+
void runIfDue()
|
|
449
|
+
}
|
|
450
|
+
}, waitTime)
|
|
451
|
+
return
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// 默认 15 分钟检查
|
|
456
|
+
runIfDue().catch(() => {})
|
|
457
|
+
}, 15 * 60_000)
|
|
458
|
+
periodicTimer.unref?.()
|
|
459
|
+
|
|
460
|
+
log(`智能调度器已启动(初始延迟 ${delayMs}ms, 周期 15min)`)
|
|
461
|
+
return { delayMs }
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// ── 调度 ─────────────────────────────────────────────────────────────────────
|
|
465
|
+
|
|
466
|
+
let delayTimer = null
|
|
467
|
+
let periodicTimer = null
|
|
468
|
+
|
|
469
|
+
function parseDelayMs(raw) {
|
|
470
|
+
// ⚠️ 0 合法(立刻跑),不能用 `Number(x) || 默认`(0 是 falsy 会被吞)。
|
|
471
|
+
const parsed = Number(raw)
|
|
472
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : 15_000
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** 启动调度:延迟后若到期则跑一轮;之后每 15 分钟自检(跨天 / 长驻进程)。 */
|
|
476
|
+
export function startScheduler({ log: logger = () => {} } = {}) {
|
|
477
|
+
stopScheduler()
|
|
478
|
+
log = logger
|
|
479
|
+
const delayMs = parseDelayMs(loadSettings().checkin?.delayMs)
|
|
480
|
+
delayTimer = setTimeout(() => {
|
|
481
|
+
delayTimer = null
|
|
482
|
+
void runIfDue()
|
|
483
|
+
}, delayMs)
|
|
484
|
+
delayTimer.unref?.()
|
|
485
|
+
periodicTimer = setInterval(() => {
|
|
486
|
+
runIfDue().catch(() => {})
|
|
487
|
+
}, 15 * 60_000)
|
|
488
|
+
periodicTimer.unref?.()
|
|
489
|
+
log(`auto check-in scheduler started (delay ${delayMs}ms, period 15min)`)
|
|
490
|
+
return { delayMs }
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
export function stopScheduler() {
|
|
494
|
+
if (delayTimer) { clearTimeout(delayTimer); delayTimer = null }
|
|
495
|
+
if (periodicTimer) { clearInterval(periodicTimer); periodicTimer = null }
|
|
496
|
+
}
|