@auto-mas/auto-mas-plugin-community 0.0.0-stage → 0.2.1
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/dist/LICENSE +661 -0
- package/dist/client/THIRD-PARTY-LICENSES.md +440 -0
- package/dist/client/index.js +45677 -0
- package/dist/client/style.css +2 -0
- package/dist/index.js +1 -0
- package/dist/server/builtin-plugins/community.js +4 -0
- package/dist/server/community/arknights-gacha.js +195 -0
- package/dist/server/community/cloud-genshin.js +80 -0
- package/dist/server/community/des.js +158 -0
- package/dist/server/community/display-names.js +7 -0
- package/dist/server/community/index.js +788 -0
- package/dist/server/community/kuro.js +121 -0
- package/dist/server/community/miyoushe-device.js +108 -0
- package/dist/server/community/miyoushe-qr.js +484 -0
- package/dist/server/community/miyoushe.js +633 -0
- package/dist/server/community/pages.js +630 -0
- package/dist/server/community/provider.js +63 -0
- package/dist/server/community/qrcode.js +365 -0
- package/dist/server/community/skland-qr.js +267 -0
- package/dist/server/community/skland.js +422 -0
- package/dist/server/community/taygedo.js +189 -0
- package/dist/server/community/vault.js +65 -0
- package/dist/server/features.js +31 -0
- package/dist/server/schema.js +353 -0
- package/package.json +43 -6
- package/README.md +0 -3
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { Schema } from '../schema.js';
|
|
3
|
+
import { cloudGenshinProvider } from './cloud-genshin.js';
|
|
4
|
+
import { ArknightsGacha } from './arknights-gacha.js';
|
|
5
|
+
import { createMiyousheQrLogin, pollMiyousheQrLogin } from './miyoushe-qr.js';
|
|
6
|
+
import { discoverMiyousheRoles, miyousheProviders } from './miyoushe.js';
|
|
7
|
+
import { discoverKuroRoles, kuroProviders } from './kuro.js';
|
|
8
|
+
import { communityPages } from './pages.js';
|
|
9
|
+
import { ProviderError, signLabels } from './provider.js';
|
|
10
|
+
import { renderQrSvgDataUrl } from './qrcode.js';
|
|
11
|
+
import { createSklandQrLogin, pollSklandQrLogin } from './skland-qr.js';
|
|
12
|
+
import { discoverSklandRoles, sklandProviders } from './skland.js';
|
|
13
|
+
import { discoverTaygedoRoles, refreshTaygedoCredential, taygedoProviders } from './taygedo.js';
|
|
14
|
+
import { CredentialVault } from './vault.js';
|
|
15
|
+
const accountTable = 'community-accounts';
|
|
16
|
+
const userTable = 'community-users';
|
|
17
|
+
const credentialTable = 'community-credentials';
|
|
18
|
+
const resultTable = 'community-results';
|
|
19
|
+
const activityTable = 'community-activity';
|
|
20
|
+
const activityLabels = { success: '已获取', failed: '查询失败', verification: '需要验证', unavailable: '暂不可用' };
|
|
21
|
+
const Config = Schema.object({ arknightsGacha: Schema.boolean().default(false).description('在游戏社区启用明日方舟寻访记录') });
|
|
22
|
+
const availableChannels = [
|
|
23
|
+
{ id: 'cloud-genshin', title: '云原神', credentialHint: cloudGenshinProvider.credentialHint, profiles: [cloudGenshinProvider] },
|
|
24
|
+
{ id: 'miyoushe', title: '米游社', credentialHint: miyousheProviders[0].credentialHint, profiles: miyousheProviders, discover: discoverMiyousheRoles },
|
|
25
|
+
{ id: 'skland', title: '森空岛', credentialHint: '提供已授权森空岛会话的 cred、signToken、dId(JSON)。', profiles: sklandProviders, discover: discoverSklandRoles },
|
|
26
|
+
{ id: 'kuro', title: '库街区', credentialHint: kuroProviders[0].credentialHint, profiles: kuroProviders, discover: discoverKuroRoles },
|
|
27
|
+
{ id: 'taygedo', title: '塔吉多', credentialHint: taygedoProviders[0].credentialHint, profiles: taygedoProviders,
|
|
28
|
+
discover: discoverTaygedoRoles, refreshCredential: refreshTaygedoCredential },
|
|
29
|
+
];
|
|
30
|
+
const channelsById = new Map(availableChannels.map(channel => [channel.id, channel]));
|
|
31
|
+
const channelsByProfile = new Map(availableChannels.flatMap(channel => channel.profiles.map(profile => [profile.id, channel])));
|
|
32
|
+
const availableProfiles = availableChannels.flatMap(channel => channel.profiles);
|
|
33
|
+
const profilesById = new Map(availableProfiles.map(profile => [profile.id, profile]));
|
|
34
|
+
const shanghai = new Intl.DateTimeFormat('en-GB', {
|
|
35
|
+
timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
|
|
36
|
+
});
|
|
37
|
+
const qrChannels = new Set(['miyoushe', 'skland']);
|
|
38
|
+
const qrSessionTtlMs = 5 * 60 * 1000;
|
|
39
|
+
const maxQrSessions = 16;
|
|
40
|
+
function profileFor(id = cloudGenshinProvider.id) {
|
|
41
|
+
const profile = profilesById.get(id);
|
|
42
|
+
if (!profile)
|
|
43
|
+
throw new Error('该游戏社区暂不支持');
|
|
44
|
+
return profile;
|
|
45
|
+
}
|
|
46
|
+
function providerClock(now) {
|
|
47
|
+
const parts = Object.fromEntries(shanghai.formatToParts(now).map(({ type, value }) => [type, value]));
|
|
48
|
+
return { day: `${parts.year}-${parts.month}-${parts.day}`, time: `${parts.hour}:${parts.minute}` };
|
|
49
|
+
}
|
|
50
|
+
export class CommunitySignIn {
|
|
51
|
+
gachaEnabled;
|
|
52
|
+
gacha;
|
|
53
|
+
vault;
|
|
54
|
+
store;
|
|
55
|
+
request;
|
|
56
|
+
clock;
|
|
57
|
+
pause;
|
|
58
|
+
abort = new AbortController();
|
|
59
|
+
updating = new Set();
|
|
60
|
+
credentialUpdates = new Set();
|
|
61
|
+
running = new Map();
|
|
62
|
+
credentialSigning = new Set();
|
|
63
|
+
reading = new Map();
|
|
64
|
+
qrSessions = new Map();
|
|
65
|
+
sweeping;
|
|
66
|
+
manualBatch;
|
|
67
|
+
reportBatch = () => { };
|
|
68
|
+
constructor(dataDir, store, request = fetch, clock = () => new Date(), pause, gachaEnabled = false) {
|
|
69
|
+
this.gachaEnabled = gachaEnabled;
|
|
70
|
+
this.gacha = new ArknightsGacha(store);
|
|
71
|
+
this.vault = new CredentialVault(dataDir);
|
|
72
|
+
this.store = store;
|
|
73
|
+
this.request = request;
|
|
74
|
+
this.clock = clock;
|
|
75
|
+
this.pause = pause;
|
|
76
|
+
const legacy = store.list(accountTable).filter(account => !account.userId || !account.credentialId || account.credential);
|
|
77
|
+
if (legacy.length)
|
|
78
|
+
store.transaction(() => {
|
|
79
|
+
for (const { credential, ...account } of legacy) {
|
|
80
|
+
const userId = account.userId || account.id;
|
|
81
|
+
const credentialId = account.credentialId || account.id;
|
|
82
|
+
if (!store.get(userTable, userId))
|
|
83
|
+
store.put(userTable, { id: userId, name: account.name });
|
|
84
|
+
if (credential && !store.get(credentialTable, credentialId)) {
|
|
85
|
+
const profileId = account.profileId ?? cloudGenshinProvider.id;
|
|
86
|
+
const channelId = channelsByProfile.get(profileId)?.id ?? profileId;
|
|
87
|
+
// The previous vault encrypted this ciphertext with the game entry ID as its associated data.
|
|
88
|
+
store.put(credentialTable, { id: account.id, name: account.name, userId, channelId, credential });
|
|
89
|
+
store.put(accountTable, { ...account, userId, credentialId: account.id });
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
store.put(accountTable, { ...account, userId, credentialId });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
account(id) {
|
|
98
|
+
const entry = this.store.get(accountTable, id);
|
|
99
|
+
if (!entry)
|
|
100
|
+
throw new Error('社区账号不存在');
|
|
101
|
+
return entry;
|
|
102
|
+
}
|
|
103
|
+
mutable(id) {
|
|
104
|
+
if (this.abort.signal.aborted)
|
|
105
|
+
throw new Error('游戏社区已停用');
|
|
106
|
+
const credentialId = this.store.get(accountTable, id)?.credentialId;
|
|
107
|
+
if (this.roleBusy(id) || (credentialId && (this.credentialUpdates.has(credentialId) || this.credentialSigning.has(credentialId)))) {
|
|
108
|
+
throw new Error('该游戏角色或关联凭据正在处理,请稍后重试');
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
roleBusy(id) {
|
|
112
|
+
return this.running.has(id) || this.updating.has(id) || this.reading.has(id) || this.gacha.busy(id);
|
|
113
|
+
}
|
|
114
|
+
credentialRecord(id) {
|
|
115
|
+
const credential = this.store.get(credentialTable, id);
|
|
116
|
+
if (!credential)
|
|
117
|
+
throw new Error('社区凭据不存在');
|
|
118
|
+
return credential;
|
|
119
|
+
}
|
|
120
|
+
rolesForCredential(id) {
|
|
121
|
+
return this.store.list(accountTable).filter(account => account.credentialId === id);
|
|
122
|
+
}
|
|
123
|
+
ensureCredentialAvailable(id) {
|
|
124
|
+
if (this.credentialUpdates.has(id) || this.credentialSigning.has(id))
|
|
125
|
+
throw new Error('该社区凭据正在处理,请稍后重试');
|
|
126
|
+
}
|
|
127
|
+
mutableCredential(id) {
|
|
128
|
+
this.abort.signal.throwIfAborted();
|
|
129
|
+
this.ensureCredentialAvailable(id);
|
|
130
|
+
const attached = this.rolesForCredential(id);
|
|
131
|
+
if (attached.some(account => this.roleBusy(account.id)))
|
|
132
|
+
throw new Error('关联游戏角色正在处理,请稍后重试');
|
|
133
|
+
return attached;
|
|
134
|
+
}
|
|
135
|
+
exposeCredential(credential, roleCount) {
|
|
136
|
+
return {
|
|
137
|
+
id: credential.id, userId: credential.userId, userName: this.store.get(userTable, credential.userId)?.name,
|
|
138
|
+
name: credential.name, channelId: credential.channelId, channel: channelsById.get(credential.channelId)?.title ?? '暂不可用', roleCount,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
expose(account) {
|
|
142
|
+
const latest = this.store.get(resultTable, account.id);
|
|
143
|
+
const activity = this.store.get(activityTable, account.id);
|
|
144
|
+
const profile = profilesById.get(account.profileId ?? cloudGenshinProvider.id);
|
|
145
|
+
const serverLabel = account.server
|
|
146
|
+
? (profile?.serverOptions?.find(option => option.value === account.server)?.label ?? account.server)
|
|
147
|
+
: undefined;
|
|
148
|
+
return {
|
|
149
|
+
id: account.id, name: account.name, userId: account.userId, userName: this.store.get(userTable, account.userId)?.name,
|
|
150
|
+
credentialId: account.credentialId, credentialName: this.store.get(credentialTable, account.credentialId)?.name,
|
|
151
|
+
profileId: account.profileId ?? cloudGenshinProvider.id, game: profile?.title ?? '未知游戏',
|
|
152
|
+
provider: profile?.platform ?? '暂不可用', roleUid: account.roleUid, server: account.server, serverLabel, enabled: Boolean(account.enabled),
|
|
153
|
+
dailyAt: account.dailyAt, status: latest && signLabels[latest.status], time: latest?.time, message: latest?.message,
|
|
154
|
+
canSign: !!profile && profile.supportsSign !== false,
|
|
155
|
+
canReadActivity: !!profile?.activity, activityStatus: activity ? activityLabels[activity.status] : undefined,
|
|
156
|
+
activityTime: activity?.snapshotTime, activitySummary: activity?.metrics.map(metric => `${metric.label} ${metric.value}`).join(' · '),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
profiles() { return availableProfiles; }
|
|
160
|
+
channels() { return availableChannels; }
|
|
161
|
+
supportsQrLogin(channelId) {
|
|
162
|
+
return typeof channelId === 'string' && qrChannels.has(channelId);
|
|
163
|
+
}
|
|
164
|
+
supportsRoleSync(channelId) { return Boolean(channelsById.get(channelId)?.discover); }
|
|
165
|
+
onBatch(callback) { this.reportBatch = callback; }
|
|
166
|
+
gachaRoles() {
|
|
167
|
+
this.assertGacha();
|
|
168
|
+
return this.store.list(accountTable).filter(account => account.profileId === 'skland-arknights' && !!account.roleUid)
|
|
169
|
+
.map(account => ({ id: account.id, label: `${account.name} · ${account.roleUid}`, enabled: account.enabled }));
|
|
170
|
+
}
|
|
171
|
+
assertGacha() {
|
|
172
|
+
if (!this.gachaEnabled)
|
|
173
|
+
throw new Error('明日方舟寻访记录尚未启用');
|
|
174
|
+
}
|
|
175
|
+
gachaRole(id) {
|
|
176
|
+
this.assertGacha();
|
|
177
|
+
const account = this.account(id);
|
|
178
|
+
const roleUid = account.roleUid;
|
|
179
|
+
if (account.profileId !== 'skland-arknights' || !roleUid)
|
|
180
|
+
throw new Error('请选择已绑定的明日方舟角色');
|
|
181
|
+
return { id, roleUid, server: account.server, enabled: account.enabled, account };
|
|
182
|
+
}
|
|
183
|
+
queryGacha(id, pool, page) {
|
|
184
|
+
return this.gacha.query(this.gachaRole(id), pool, page);
|
|
185
|
+
}
|
|
186
|
+
syncGacha(id) {
|
|
187
|
+
const role = this.gachaRole(id);
|
|
188
|
+
if (!role.enabled)
|
|
189
|
+
throw new Error('该游戏角色已停用');
|
|
190
|
+
if (!this.gacha.busy(id))
|
|
191
|
+
this.mutable(id);
|
|
192
|
+
return this.gacha.sync(role, () => this.reveal(this.targetRecord(role.account)), this.providerContext());
|
|
193
|
+
}
|
|
194
|
+
pruneQrSessions(nowMs = this.clock().getTime()) {
|
|
195
|
+
for (const [id, session] of this.qrSessions) {
|
|
196
|
+
if (session.expiresAt <= nowMs)
|
|
197
|
+
this.qrSessions.delete(id);
|
|
198
|
+
}
|
|
199
|
+
while (this.qrSessions.size >= maxQrSessions) {
|
|
200
|
+
const oldest = this.qrSessions.keys().next().value;
|
|
201
|
+
if (!oldest)
|
|
202
|
+
break;
|
|
203
|
+
this.qrSessions.delete(oldest);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
async startQrLogin(input) {
|
|
207
|
+
this.abort.signal.throwIfAborted();
|
|
208
|
+
const existing = input.id !== undefined ? this.credentialRecord(input.id) : undefined;
|
|
209
|
+
const channelId = existing?.channelId ?? input.channelId;
|
|
210
|
+
if (!this.supportsQrLogin(channelId))
|
|
211
|
+
throw new Error('该社区渠道暂不支持扫码登录');
|
|
212
|
+
const channel = channelsById.get(channelId);
|
|
213
|
+
const userId = existing?.userId ?? input.userId;
|
|
214
|
+
if (userId !== undefined && !this.store.get(userTable, userId))
|
|
215
|
+
throw new Error('社区用户不存在');
|
|
216
|
+
const name = (input.name ?? existing?.name ?? channel.title).trim();
|
|
217
|
+
if (!name || name.length > 100)
|
|
218
|
+
throw new Error('请输入不超过 100 个字符的凭据备注');
|
|
219
|
+
if (existing)
|
|
220
|
+
this.mutableCredential(existing.id);
|
|
221
|
+
const context = this.providerContext();
|
|
222
|
+
const challenge = channelId === 'miyoushe'
|
|
223
|
+
? await createMiyousheQrLogin(context)
|
|
224
|
+
: await createSklandQrLogin(context);
|
|
225
|
+
this.abort.signal.throwIfAborted();
|
|
226
|
+
const qrImage = renderQrSvgDataUrl(challenge.qrUrl);
|
|
227
|
+
const nowMs = this.clock().getTime();
|
|
228
|
+
this.pruneQrSessions(nowMs);
|
|
229
|
+
const sessionId = randomUUID();
|
|
230
|
+
const expiresAt = nowMs + qrSessionTtlMs;
|
|
231
|
+
this.qrSessions.set(sessionId, {
|
|
232
|
+
id: sessionId, channelId, credentialId: existing?.id, userId, name, expiresAt, challenge,
|
|
233
|
+
});
|
|
234
|
+
return { sessionId, channelId, channel: channel.title, qrImage, expiresAt: new Date(expiresAt).toISOString() };
|
|
235
|
+
}
|
|
236
|
+
async pollQrLogin(sessionId) {
|
|
237
|
+
this.abort.signal.throwIfAborted();
|
|
238
|
+
const session = this.qrSessions.get(sessionId);
|
|
239
|
+
if (!session)
|
|
240
|
+
return { status: 'expired', message: '扫码会话已失效,请重新生成二维码' };
|
|
241
|
+
if (session.polling)
|
|
242
|
+
return session.polling;
|
|
243
|
+
if (this.clock().getTime() > session.expiresAt) {
|
|
244
|
+
this.qrSessions.delete(sessionId);
|
|
245
|
+
return { status: 'expired', message: '二维码已过期,请重新生成' };
|
|
246
|
+
}
|
|
247
|
+
const task = (async () => {
|
|
248
|
+
const context = this.providerContext();
|
|
249
|
+
const outcome = session.channelId === 'miyoushe'
|
|
250
|
+
? await pollMiyousheQrLogin(context, session.challenge)
|
|
251
|
+
: await pollSklandQrLogin(context, session.challenge);
|
|
252
|
+
this.abort.signal.throwIfAborted();
|
|
253
|
+
if (!this.qrSessions.has(sessionId))
|
|
254
|
+
return { status: 'canceled', message: '扫码会话已取消' };
|
|
255
|
+
if (outcome.status !== 'confirmed') {
|
|
256
|
+
if (outcome.status === 'expired' || outcome.status === 'canceled')
|
|
257
|
+
this.qrSessions.delete(sessionId);
|
|
258
|
+
return { status: outcome.status, ...(outcome.message ? { message: outcome.message } : {}) };
|
|
259
|
+
}
|
|
260
|
+
this.qrSessions.delete(sessionId);
|
|
261
|
+
const saved = await this.saveCredential({
|
|
262
|
+
id: session.credentialId,
|
|
263
|
+
userId: session.userId,
|
|
264
|
+
channelId: session.channelId,
|
|
265
|
+
name: session.name,
|
|
266
|
+
credential: outcome.credential,
|
|
267
|
+
});
|
|
268
|
+
return { status: 'confirmed', credentialId: saved.id, credentialName: saved.name, message: '扫码登录成功,凭据已加密保存' };
|
|
269
|
+
})();
|
|
270
|
+
session.polling = task;
|
|
271
|
+
try {
|
|
272
|
+
return await task;
|
|
273
|
+
}
|
|
274
|
+
finally {
|
|
275
|
+
if (this.qrSessions.get(sessionId) === session)
|
|
276
|
+
session.polling = undefined;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
cancelQrLogin(sessionId) {
|
|
280
|
+
this.qrSessions.delete(sessionId);
|
|
281
|
+
}
|
|
282
|
+
async syncCredentialRoles(credentialId) {
|
|
283
|
+
this.abort.signal.throwIfAborted();
|
|
284
|
+
const record = this.credentialRecord(credentialId);
|
|
285
|
+
const channel = channelsById.get(record.channelId);
|
|
286
|
+
if (!channel?.discover)
|
|
287
|
+
throw new Error('该社区渠道暂不支持自动同步绑定角色');
|
|
288
|
+
this.mutableCredential(record.id);
|
|
289
|
+
this.credentialUpdates.add(record.id);
|
|
290
|
+
let discovered;
|
|
291
|
+
try {
|
|
292
|
+
const context = this.providerContext();
|
|
293
|
+
const discover = channel.discover;
|
|
294
|
+
const { value, current, secret } = await this.withCredential(record, channel.refreshCredential, input => discover(input, context));
|
|
295
|
+
if (value.updatedCredential && value.updatedCredential !== secret)
|
|
296
|
+
await this.replaceCredential(current, value.updatedCredential);
|
|
297
|
+
discovered = value.roles;
|
|
298
|
+
this.abort.signal.throwIfAborted();
|
|
299
|
+
}
|
|
300
|
+
finally {
|
|
301
|
+
this.credentialUpdates.delete(record.id);
|
|
302
|
+
}
|
|
303
|
+
let added = 0;
|
|
304
|
+
let skipped = 0;
|
|
305
|
+
for (const role of discovered) {
|
|
306
|
+
const duplicate = this.rolesForCredential(record.id).some(existing => (existing.profileId ?? cloudGenshinProvider.id) === role.profileId
|
|
307
|
+
&& (existing.roleUid ?? '') === role.roleUid && (existing.server ?? '') === role.server);
|
|
308
|
+
if (duplicate) {
|
|
309
|
+
skipped++;
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
await this.save({
|
|
313
|
+
credentialId: record.id,
|
|
314
|
+
profileId: role.profileId,
|
|
315
|
+
roleUid: role.roleUid,
|
|
316
|
+
server: role.server,
|
|
317
|
+
name: role.name,
|
|
318
|
+
});
|
|
319
|
+
added++;
|
|
320
|
+
}
|
|
321
|
+
const message = discovered.length === 0
|
|
322
|
+
? '未在官方接口查询到该凭据下已绑定的游戏角色'
|
|
323
|
+
: added > 0
|
|
324
|
+
? `已同步 ${added} 个新角色${skipped ? `,跳过 ${skipped} 个已有角色` : ''}`
|
|
325
|
+
: `已存在全部 ${skipped} 个绑定角色,无需重复添加`;
|
|
326
|
+
return { discovered: discovered.length, added, skipped, message };
|
|
327
|
+
}
|
|
328
|
+
credentials(userId) {
|
|
329
|
+
const counts = new Map();
|
|
330
|
+
for (const { credentialId } of this.store.list(accountTable))
|
|
331
|
+
counts.set(credentialId, (counts.get(credentialId) ?? 0) + 1);
|
|
332
|
+
return this.store.list(credentialTable)
|
|
333
|
+
.filter(credential => userId === undefined || credential.userId === userId)
|
|
334
|
+
.map(credential => this.exposeCredential(credential, counts.get(credential.id) ?? 0));
|
|
335
|
+
}
|
|
336
|
+
credential(id) {
|
|
337
|
+
const credential = this.store.get(credentialTable, id);
|
|
338
|
+
return credential && this.exposeCredential(credential, this.rolesForCredential(id).length);
|
|
339
|
+
}
|
|
340
|
+
async saveCredential(input) {
|
|
341
|
+
const name = input.name.trim();
|
|
342
|
+
if (!name || name.length > 100)
|
|
343
|
+
throw new Error('请输入不超过 100 个字符的凭据备注');
|
|
344
|
+
const existing = input.id !== undefined ? this.credentialRecord(input.id) : undefined;
|
|
345
|
+
const id = existing?.id ?? randomUUID();
|
|
346
|
+
const owner = input.userId ?? existing?.userId;
|
|
347
|
+
const userId = owner ?? id;
|
|
348
|
+
const channel = channelsById.get(input.channelId ?? existing?.channelId ?? '');
|
|
349
|
+
if (!channel)
|
|
350
|
+
throw new Error('请选择支持的社区渠道');
|
|
351
|
+
if (owner !== undefined && !this.store.get(userTable, owner))
|
|
352
|
+
throw new Error('社区用户不存在');
|
|
353
|
+
const attached = this.mutableCredential(id);
|
|
354
|
+
const channelChanged = existing !== undefined && channel.id !== existing.channelId;
|
|
355
|
+
if (existing && attached.length && (channelChanged || userId !== existing.userId)) {
|
|
356
|
+
throw new Error('请先移除或重新关联该凭据下的游戏角色');
|
|
357
|
+
}
|
|
358
|
+
this.credentialUpdates.add(id);
|
|
359
|
+
try {
|
|
360
|
+
const replacement = input.credential ? channel.profiles[0].validateCredential(input.credential) : undefined;
|
|
361
|
+
if (channelChanged && !replacement)
|
|
362
|
+
throw new Error('更换社区渠道时请填写相应的凭据');
|
|
363
|
+
const credential = replacement ? await this.vault.seal(id, replacement) : existing?.credential;
|
|
364
|
+
if (!credential)
|
|
365
|
+
throw new Error('请输入已授权的社区凭据');
|
|
366
|
+
this.abort.signal.throwIfAborted();
|
|
367
|
+
return this.store.transaction(() => {
|
|
368
|
+
if (owner === undefined)
|
|
369
|
+
this.store.put(userTable, { id: userId, name });
|
|
370
|
+
else if (!this.store.get(userTable, owner))
|
|
371
|
+
throw new Error('社区用户不存在');
|
|
372
|
+
return this.exposeCredential(this.store.put(credentialTable, { id, userId, channelId: channel.id, name, credential }), attached.length);
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
finally {
|
|
376
|
+
this.credentialUpdates.delete(id);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
removeCredential(id) {
|
|
380
|
+
this.credentialRecord(id);
|
|
381
|
+
if (this.mutableCredential(id).length)
|
|
382
|
+
throw new Error('请先移除或重新关联该凭据下的游戏角色');
|
|
383
|
+
this.store.remove(credentialTable, id);
|
|
384
|
+
}
|
|
385
|
+
users() {
|
|
386
|
+
const users = this.store.list(userTable);
|
|
387
|
+
const summaries = new Map(users.map(({ id, name }) => [id, { id, name, credentialCount: 0, providers: new Set() }]));
|
|
388
|
+
for (const credential of this.store.list(credentialTable)) {
|
|
389
|
+
const summary = summaries.get(credential.userId);
|
|
390
|
+
if (!summary)
|
|
391
|
+
continue;
|
|
392
|
+
summary.credentialCount++;
|
|
393
|
+
const channel = channelsById.get(credential.channelId);
|
|
394
|
+
if (channel)
|
|
395
|
+
summary.providers.add(channel.title);
|
|
396
|
+
}
|
|
397
|
+
return [...summaries.values()].map(summary => ({ ...summary, providers: [...summary.providers] }));
|
|
398
|
+
}
|
|
399
|
+
user(id) {
|
|
400
|
+
return this.users().find(user => user.id === id);
|
|
401
|
+
}
|
|
402
|
+
saveUser(input) {
|
|
403
|
+
this.abort.signal.throwIfAborted();
|
|
404
|
+
const name = input.name.trim();
|
|
405
|
+
if (!name || name.length > 100)
|
|
406
|
+
throw new Error('请输入不超过 100 个字符的用户称呼');
|
|
407
|
+
if (input.id !== undefined && !this.store.get(userTable, input.id))
|
|
408
|
+
throw new Error('社区用户不存在');
|
|
409
|
+
const id = input.id ?? randomUUID();
|
|
410
|
+
this.store.put(userTable, { id, name });
|
|
411
|
+
return this.user(id);
|
|
412
|
+
}
|
|
413
|
+
removeUser(id) {
|
|
414
|
+
this.abort.signal.throwIfAborted();
|
|
415
|
+
const user = this.user(id);
|
|
416
|
+
if (!user)
|
|
417
|
+
throw new Error('社区用户不存在');
|
|
418
|
+
if (user.credentialCount)
|
|
419
|
+
throw new Error('请先移动或删除该用户的社区凭据');
|
|
420
|
+
this.store.remove(userTable, id);
|
|
421
|
+
}
|
|
422
|
+
list() {
|
|
423
|
+
return this.store.list(accountTable).map(account => this.expose(account));
|
|
424
|
+
}
|
|
425
|
+
removeUnusedImplicitCredential(id) {
|
|
426
|
+
const credential = this.store.get(credentialTable, id);
|
|
427
|
+
if (credential?.implicit && this.rolesForCredential(id).length === 0)
|
|
428
|
+
this.store.remove(credentialTable, id);
|
|
429
|
+
}
|
|
430
|
+
async save(input) {
|
|
431
|
+
const name = input.name.trim();
|
|
432
|
+
if (!name || name.length > 100)
|
|
433
|
+
throw new Error('请输入不超过 100 个字符的称呼');
|
|
434
|
+
const existing = input.id !== undefined ? this.account(input.id) : undefined;
|
|
435
|
+
const id = existing?.id ?? randomUUID();
|
|
436
|
+
const selected = input.credentialId !== undefined ? this.credentialRecord(input.credentialId) : undefined;
|
|
437
|
+
const owner = input.userId ?? selected?.userId ?? existing?.userId;
|
|
438
|
+
if (owner !== undefined && !this.store.get(userTable, owner))
|
|
439
|
+
throw new Error('社区用户不存在');
|
|
440
|
+
const userId = owner ?? id;
|
|
441
|
+
this.mutable(id);
|
|
442
|
+
if (selected)
|
|
443
|
+
this.ensureCredentialAvailable(selected.id);
|
|
444
|
+
this.updating.add(id);
|
|
445
|
+
let lockingCredential;
|
|
446
|
+
try {
|
|
447
|
+
const previousProfile = existing?.profileId ?? cloudGenshinProvider.id;
|
|
448
|
+
const selectedChannel = selected && channelsById.get(selected.channelId);
|
|
449
|
+
const selectedProfile = selectedChannel?.profiles.length === 1 ? selectedChannel.profiles[0].id : undefined;
|
|
450
|
+
const profile = profileFor(input.profileId ?? (existing ? previousProfile : selectedProfile));
|
|
451
|
+
const channel = channelsByProfile.get(profile.id);
|
|
452
|
+
const changingProfile = !!existing && profile.id !== previousProfile;
|
|
453
|
+
const isCloud = channel.id === 'cloud-genshin';
|
|
454
|
+
const roleUid = isCloud ? undefined : (input.roleUid?.trim() ?? (changingProfile ? undefined : existing?.roleUid)) || undefined;
|
|
455
|
+
const server = isCloud ? undefined : (input.server?.trim() ?? (changingProfile ? undefined : existing?.server)) || undefined;
|
|
456
|
+
if ((profile.roleRequired || roleUid) && !/^\d{1,32}$/u.test(roleUid ?? ''))
|
|
457
|
+
throw new Error('请输入有效的游戏角色 UID');
|
|
458
|
+
if ((profile.serverRequired || server) && !/^[\w-]{1,40}$/u.test(server ?? ''))
|
|
459
|
+
throw new Error('请输入有效的服务器标识');
|
|
460
|
+
profile.validateRole?.({ roleUid, server });
|
|
461
|
+
if (selected && input.credential)
|
|
462
|
+
throw new Error('已有凭据请在社区凭据页面更新');
|
|
463
|
+
const previous = existing && this.store.get(credentialTable, existing.credentialId);
|
|
464
|
+
const replacement = input.credential ? profile.validateCredential(input.credential) : undefined;
|
|
465
|
+
let credential = selected ?? previous;
|
|
466
|
+
let credentialChange;
|
|
467
|
+
if (replacement) {
|
|
468
|
+
const reusable = previous?.implicit && this.rolesForCredential(previous.id).every(role => role.id === id) ? previous : undefined;
|
|
469
|
+
const credentialId = reusable?.id ?? (existing ? randomUUID() : id);
|
|
470
|
+
if (reusable) {
|
|
471
|
+
lockingCredential = reusable.id;
|
|
472
|
+
this.credentialUpdates.add(lockingCredential);
|
|
473
|
+
}
|
|
474
|
+
const sealed = await this.vault.seal(credentialId, replacement);
|
|
475
|
+
credential = credentialChange = { id: credentialId, userId, name: reusable?.name ?? name, channelId: channel.id, credential: sealed, implicit: true };
|
|
476
|
+
}
|
|
477
|
+
if (!credential)
|
|
478
|
+
throw new Error('请选择或填写已授权的社区凭据');
|
|
479
|
+
if (credential.channelId !== channel.id)
|
|
480
|
+
throw new Error('所选凭据不支持该游戏的社区渠道');
|
|
481
|
+
if (credential.userId !== userId) {
|
|
482
|
+
if (selected || this.rolesForCredential(credential.id).some(role => role.id !== id)) {
|
|
483
|
+
throw new Error('请选择目标用户自己的同渠道社区凭据');
|
|
484
|
+
}
|
|
485
|
+
credentialChange = { ...credential, userId };
|
|
486
|
+
}
|
|
487
|
+
const credentialId = credential.id;
|
|
488
|
+
const changedTarget = changingProfile || roleUid !== existing?.roleUid || server !== existing?.server;
|
|
489
|
+
this.abort.signal.throwIfAborted();
|
|
490
|
+
return this.store.transaction(() => {
|
|
491
|
+
if (owner !== undefined) {
|
|
492
|
+
if (!this.store.get(userTable, userId))
|
|
493
|
+
throw new Error('社区用户不存在');
|
|
494
|
+
}
|
|
495
|
+
else {
|
|
496
|
+
this.store.put(userTable, { id: userId, name });
|
|
497
|
+
}
|
|
498
|
+
const duplicate = this.rolesForCredential(credentialId).some(role => role.id !== id && (role.profileId ?? cloudGenshinProvider.id) === profile.id
|
|
499
|
+
&& (isCloud || role.roleUid === roleUid && role.server === server));
|
|
500
|
+
if (duplicate)
|
|
501
|
+
throw new Error('该凭据已添加同一个游戏角色');
|
|
502
|
+
if (credentialChange)
|
|
503
|
+
this.store.put(credentialTable, credentialChange);
|
|
504
|
+
if (changedTarget) {
|
|
505
|
+
this.store.remove(resultTable, id);
|
|
506
|
+
this.store.remove(activityTable, id);
|
|
507
|
+
}
|
|
508
|
+
const account = this.store.put(accountTable, { ...existing, id, userId, credentialId, name, profileId: profile.id, roleUid,
|
|
509
|
+
server, enabled: input.enabled ?? existing?.enabled ?? true,
|
|
510
|
+
lastScheduledDay: changedTarget ? undefined : existing?.lastScheduledDay });
|
|
511
|
+
return this.expose(account);
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
finally {
|
|
515
|
+
if (lockingCredential)
|
|
516
|
+
this.credentialUpdates.delete(lockingCredential);
|
|
517
|
+
this.updating.delete(id);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
toggle(id, enabled) {
|
|
521
|
+
this.mutable(id);
|
|
522
|
+
const account = this.account(id);
|
|
523
|
+
return this.expose(this.store.put(accountTable, { ...account, enabled: enabled ?? !account.enabled }));
|
|
524
|
+
}
|
|
525
|
+
schedule(id, time) {
|
|
526
|
+
if (time !== undefined && !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(time))
|
|
527
|
+
throw new Error('请输入 24 小时制时间,例如 09:15');
|
|
528
|
+
this.mutable(id);
|
|
529
|
+
const account = this.account(id);
|
|
530
|
+
if (time && profileFor(account.profileId).supportsSign === false)
|
|
531
|
+
throw new Error('该游戏社区项目仅支持查询');
|
|
532
|
+
return this.expose(this.store.put(accountTable, { ...account, dailyAt: time }));
|
|
533
|
+
}
|
|
534
|
+
remove(id) {
|
|
535
|
+
this.mutable(id);
|
|
536
|
+
const account = this.account(id);
|
|
537
|
+
this.store.transaction(() => {
|
|
538
|
+
this.store.remove(accountTable, id);
|
|
539
|
+
this.store.remove(resultTable, id);
|
|
540
|
+
this.store.remove(activityTable, id);
|
|
541
|
+
this.gacha.remove(id);
|
|
542
|
+
this.removeUnusedImplicitCredential(account.credentialId);
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
targetRecord(account) {
|
|
546
|
+
const record = this.store.get(credentialTable, account.credentialId);
|
|
547
|
+
const profileId = account.profileId ?? cloudGenshinProvider.id;
|
|
548
|
+
if (!record || record.userId !== account.userId || channelsByProfile.get(profileId)?.id !== record.channelId) {
|
|
549
|
+
throw new ProviderError('该游戏角色尚未关联有效的社区凭据', 'unavailable');
|
|
550
|
+
}
|
|
551
|
+
return record;
|
|
552
|
+
}
|
|
553
|
+
async reveal(record) {
|
|
554
|
+
const credential = await this.vault.reveal(record.id, record.credential).catch(() => undefined);
|
|
555
|
+
this.abort.signal.throwIfAborted();
|
|
556
|
+
if (!credential)
|
|
557
|
+
throw new ProviderError('无法读取社区凭据,请重新配置', 'unavailable');
|
|
558
|
+
return credential;
|
|
559
|
+
}
|
|
560
|
+
async target(account) {
|
|
561
|
+
return { credential: await this.reveal(this.targetRecord(account)), roleUid: account.roleUid, server: account.server };
|
|
562
|
+
}
|
|
563
|
+
async replaceCredential(record, next) {
|
|
564
|
+
const sealed = await this.vault.seal(record.id, next);
|
|
565
|
+
this.abort.signal.throwIfAborted();
|
|
566
|
+
const current = this.credentialRecord(record.id);
|
|
567
|
+
if (current.credential.nonce !== record.credential.nonce || current.channelId !== record.channelId) {
|
|
568
|
+
throw new ProviderError('社区凭据已经变更,请重新操作');
|
|
569
|
+
}
|
|
570
|
+
return this.store.put(credentialTable, { ...current, credential: sealed });
|
|
571
|
+
}
|
|
572
|
+
async withCredential(record, refresh, operation) {
|
|
573
|
+
const secret = await this.reveal(record);
|
|
574
|
+
try {
|
|
575
|
+
return { value: await operation(secret), current: record, secret };
|
|
576
|
+
}
|
|
577
|
+
catch (error) {
|
|
578
|
+
if (!refresh || !(error instanceof ProviderError) || error.status !== 'unavailable')
|
|
579
|
+
throw error;
|
|
580
|
+
const replacement = await refresh(secret, this.providerContext());
|
|
581
|
+
const current = await this.replaceCredential(record, replacement);
|
|
582
|
+
return { value: await operation(replacement), current, secret: replacement };
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
providerContext() {
|
|
586
|
+
return { request: this.request, signal: this.abort.signal, now: this.clock(), pause: this.pause };
|
|
587
|
+
}
|
|
588
|
+
async sign(account, day) {
|
|
589
|
+
let outcome;
|
|
590
|
+
try {
|
|
591
|
+
const profile = profileFor(account.profileId);
|
|
592
|
+
const context = this.providerContext();
|
|
593
|
+
const response = await this.withCredential(this.targetRecord(account), profile.refreshCredential, credential => profile.sign({ credential, roleUid: account.roleUid, server: account.server }, context));
|
|
594
|
+
outcome = response.value;
|
|
595
|
+
}
|
|
596
|
+
catch (error) {
|
|
597
|
+
const known = error instanceof ProviderError;
|
|
598
|
+
outcome = { status: known && error.status === 'verification' ? 'verification' : 'failed',
|
|
599
|
+
message: known ? error.message : '社区签到失败,请检查账号配置和网络' };
|
|
600
|
+
}
|
|
601
|
+
this.abort.signal.throwIfAborted();
|
|
602
|
+
return this.store.put(resultTable, { id: account.id, day, time: this.clock().toISOString(), ...outcome });
|
|
603
|
+
}
|
|
604
|
+
activity(id) {
|
|
605
|
+
this.account(id);
|
|
606
|
+
return this.store.get(activityTable, id);
|
|
607
|
+
}
|
|
608
|
+
async refreshActivity(id) {
|
|
609
|
+
const pending = this.reading.get(id);
|
|
610
|
+
if (pending)
|
|
611
|
+
return pending;
|
|
612
|
+
this.mutable(id);
|
|
613
|
+
const account = this.account(id);
|
|
614
|
+
if (!account.enabled)
|
|
615
|
+
throw new Error('该社区账号已停用');
|
|
616
|
+
const profile = profileFor(account.profileId);
|
|
617
|
+
if (!profile.activity)
|
|
618
|
+
throw new Error('该游戏的社区接口暂不提供游戏内信息');
|
|
619
|
+
const action = this.readActivity(account, profile.activity);
|
|
620
|
+
this.reading.set(id, action);
|
|
621
|
+
try {
|
|
622
|
+
return await action;
|
|
623
|
+
}
|
|
624
|
+
finally {
|
|
625
|
+
this.reading.delete(id);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
async readActivity(account, read) {
|
|
629
|
+
const previous = this.activity(account.id);
|
|
630
|
+
let result;
|
|
631
|
+
try {
|
|
632
|
+
const metrics = await read(await this.target(account), this.providerContext());
|
|
633
|
+
if (!metrics.length)
|
|
634
|
+
throw new ProviderError('上游没有返回该角色的游戏内信息', 'unavailable');
|
|
635
|
+
result = { status: 'success', snapshotTime: this.clock().toISOString(), metrics };
|
|
636
|
+
}
|
|
637
|
+
catch (error) {
|
|
638
|
+
result = { status: error instanceof ProviderError ? error.status : 'failed', snapshotTime: previous?.snapshotTime,
|
|
639
|
+
metrics: previous?.metrics ?? [], message: error instanceof ProviderError ? error.message : '刷新游戏内信息失败,请检查账号配置和网络' };
|
|
640
|
+
}
|
|
641
|
+
this.abort.signal.throwIfAborted();
|
|
642
|
+
return this.store.put(activityTable, { ...result, id: account.id, time: this.clock().toISOString() });
|
|
643
|
+
}
|
|
644
|
+
async run(id) {
|
|
645
|
+
const pending = this.running.get(id);
|
|
646
|
+
if (pending)
|
|
647
|
+
return pending;
|
|
648
|
+
this.mutable(id);
|
|
649
|
+
const account = this.account(id);
|
|
650
|
+
if (!account.enabled)
|
|
651
|
+
throw new Error('该社区账号已停用');
|
|
652
|
+
if (profileFor(account.profileId).supportsSign === false)
|
|
653
|
+
throw new Error('该游戏社区项目仅支持查询');
|
|
654
|
+
const { day } = providerClock(this.clock());
|
|
655
|
+
const latest = this.store.get(resultTable, id);
|
|
656
|
+
if (latest?.day === day && ['success', 'already'].includes(latest.status)) {
|
|
657
|
+
return { ...latest, status: 'already', message: '该账号当天已完成签到' };
|
|
658
|
+
}
|
|
659
|
+
const action = this.sign(account, day);
|
|
660
|
+
this.credentialSigning.add(account.credentialId);
|
|
661
|
+
this.running.set(id, action);
|
|
662
|
+
try {
|
|
663
|
+
return await action;
|
|
664
|
+
}
|
|
665
|
+
finally {
|
|
666
|
+
this.running.delete(id);
|
|
667
|
+
this.credentialSigning.delete(account.credentialId);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
async batchRow(account) {
|
|
671
|
+
const profile = profileFor(account.profileId);
|
|
672
|
+
const base = { id: account.id, name: account.name, game: profile.title, platform: profile.platform };
|
|
673
|
+
try {
|
|
674
|
+
const result = await this.run(account.id);
|
|
675
|
+
return { ...base, status: result.status, message: result.message };
|
|
676
|
+
}
|
|
677
|
+
catch (error) {
|
|
678
|
+
this.abort.signal.throwIfAborted();
|
|
679
|
+
return { ...base, status: 'failed', message: error instanceof Error ? error.message : '签到未能执行' };
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
finishBatch(rows, source) {
|
|
683
|
+
if (!rows.length || this.abort.signal.aborted)
|
|
684
|
+
return;
|
|
685
|
+
const title = source === 'manual' ? '游戏社区手动签到汇总' : '游戏社区每日签到汇总';
|
|
686
|
+
const successful = rows.filter(row => row.status === 'success').length;
|
|
687
|
+
const already = rows.filter(row => row.status === 'already').length;
|
|
688
|
+
const verification = rows.filter(row => row.status === 'verification').length;
|
|
689
|
+
const failed = rows.length - successful - already - verification;
|
|
690
|
+
const text = [`成功 ${successful} · 已签到 ${already} · 失败 ${failed} · 需验证 ${verification}`,
|
|
691
|
+
...rows.map(row => `${row.platform} / ${row.game} · ${row.name}:${signLabels[row.status]} · ${row.message}`)].join('\n');
|
|
692
|
+
this.reportBatch({ id: randomUUID(), type: 'community', title, text, failed: failed + verification > 0, time: this.clock().toISOString(),
|
|
693
|
+
payload: { type: 'community.sign.finished', source, successful, already, failed, verification, rows } });
|
|
694
|
+
}
|
|
695
|
+
async runAll() {
|
|
696
|
+
this.abort.signal.throwIfAborted();
|
|
697
|
+
if (this.manualBatch)
|
|
698
|
+
return this.manualBatch;
|
|
699
|
+
const action = (async () => {
|
|
700
|
+
if (this.sweeping)
|
|
701
|
+
await this.sweeping;
|
|
702
|
+
const rows = [];
|
|
703
|
+
for (const { id } of this.store.list(accountTable)) {
|
|
704
|
+
this.abort.signal.throwIfAborted();
|
|
705
|
+
const account = this.store.get(accountTable, id);
|
|
706
|
+
const profile = profilesById.get(account?.profileId ?? cloudGenshinProvider.id);
|
|
707
|
+
if (!account?.enabled || !profile || profile.supportsSign === false)
|
|
708
|
+
continue;
|
|
709
|
+
rows.push(await this.batchRow(account));
|
|
710
|
+
}
|
|
711
|
+
return rows;
|
|
712
|
+
})();
|
|
713
|
+
this.manualBatch = action;
|
|
714
|
+
try {
|
|
715
|
+
const rows = await action;
|
|
716
|
+
this.finishBatch(rows, 'manual');
|
|
717
|
+
return rows;
|
|
718
|
+
}
|
|
719
|
+
finally {
|
|
720
|
+
if (this.manualBatch === action)
|
|
721
|
+
this.manualBatch = undefined;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
async scheduleDue() {
|
|
725
|
+
const rows = [];
|
|
726
|
+
for (const { id } of this.store.list(accountTable)) {
|
|
727
|
+
if (this.abort.signal.aborted)
|
|
728
|
+
break;
|
|
729
|
+
const account = this.store.get(accountTable, id);
|
|
730
|
+
const profile = profilesById.get(account?.profileId ?? cloudGenshinProvider.id);
|
|
731
|
+
const { day, time } = providerClock(this.clock());
|
|
732
|
+
if (!account?.enabled || !account.dailyAt || time < account.dailyAt || account.lastScheduledDay === day
|
|
733
|
+
|| this.roleBusy(id) || this.credentialUpdates.has(account.credentialId) || this.credentialSigning.has(account.credentialId)
|
|
734
|
+
|| !profile || profile.supportsSign === false)
|
|
735
|
+
continue;
|
|
736
|
+
this.store.put(accountTable, { ...account, lastScheduledDay: day });
|
|
737
|
+
rows.push(await this.batchRow(account));
|
|
738
|
+
}
|
|
739
|
+
this.finishBatch(rows, 'scheduled');
|
|
740
|
+
return rows.length > 0;
|
|
741
|
+
}
|
|
742
|
+
async tickSchedule() {
|
|
743
|
+
if (this.abort.signal.aborted || this.manualBatch)
|
|
744
|
+
return false;
|
|
745
|
+
if (this.sweeping)
|
|
746
|
+
return this.sweeping;
|
|
747
|
+
const sweep = this.scheduleDue();
|
|
748
|
+
this.sweeping = sweep;
|
|
749
|
+
try {
|
|
750
|
+
return await sweep;
|
|
751
|
+
}
|
|
752
|
+
finally {
|
|
753
|
+
this.sweeping = undefined;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
async close() {
|
|
757
|
+
this.abort.abort(new Error('游戏社区已停用'));
|
|
758
|
+
const qrPolls = [...this.qrSessions.values()].map(session => session.polling).filter(Boolean);
|
|
759
|
+
this.qrSessions.clear();
|
|
760
|
+
await Promise.allSettled([...this.running.values(), ...this.reading.values(), this.sweeping, this.manualBatch, this.gacha.settle(), ...qrPolls]);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
export function createCommunityFeature(dataDir, publish = () => { }) {
|
|
764
|
+
return {
|
|
765
|
+
id: 'community', name: '游戏社区', description: '多游戏签到、体力与日常进度',
|
|
766
|
+
component: { Config, inject: ['mas.ui', 'mas.store'], apply(ctx, config) {
|
|
767
|
+
const community = new CommunitySignIn(dataDir, ctx.get('mas.store'), fetch, undefined, undefined, config.arknightsGacha);
|
|
768
|
+
community.onBatch(notification => {
|
|
769
|
+
void ctx.parallel('mas/community-signed', notification).catch(() => ctx.logger.warn('无法提交游戏社区签到汇总'));
|
|
770
|
+
});
|
|
771
|
+
ctx.effect(() => {
|
|
772
|
+
let stopped = false;
|
|
773
|
+
const tick = () => void community.tickSchedule().then(changed => {
|
|
774
|
+
if (changed && !stopped)
|
|
775
|
+
publish();
|
|
776
|
+
}).catch(() => {
|
|
777
|
+
if (!stopped)
|
|
778
|
+
ctx.logger.warn('无法完成社区签到调度');
|
|
779
|
+
});
|
|
780
|
+
const timer = setInterval(tick, 30000);
|
|
781
|
+
timer.unref();
|
|
782
|
+
tick();
|
|
783
|
+
return async () => { stopped = true; clearInterval(timer); await community.close(); };
|
|
784
|
+
});
|
|
785
|
+
communityPages(ctx, community, publish);
|
|
786
|
+
} },
|
|
787
|
+
};
|
|
788
|
+
}
|