@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.
@@ -0,0 +1,630 @@
1
+ import { columns, field, text, ui } from '../features.js';
2
+ import { defaultCredentialName, defaultRoleName, defaultUserName } from './display-names.js';
3
+ import { signLabels } from './provider.js';
4
+ const root = '/community';
5
+ const accountBase = `${root}/accounts`;
6
+ const activityBase = `${root}/activity`;
7
+ const userBase = `${root}/users`;
8
+ const credentialsPath = `${root}/credentials`;
9
+ const title = '游戏社区';
10
+ const idOf = (input) => text(input, 'id', '账号 ID');
11
+ const accountHref = (id) => `${accountBase}/${encodeURIComponent(id)}`;
12
+ const activityHref = (id) => `${activityBase}/${encodeURIComponent(id)}`;
13
+ const userHref = (id) => `${userBase}/${encodeURIComponent(id)}`;
14
+ const credentialHref = (id) => `${credentialsPath}/${encodeURIComponent(id)}`;
15
+ const sign = { id: 'community.run', label: '签到', visibleWhen: { key: 'canSign', equals: true } };
16
+ const refreshActivity = { id: 'community.activity.refresh', label: '刷新游戏信息', visibleWhen: { key: 'enabled', equals: true } };
17
+ const toggleRole = { id: 'community.toggle', label: '切换启用' };
18
+ const signColumns = [
19
+ ...columns(['name', '角色'], ['game', '游戏'], ['serverLabel', '区服']), { key: 'enabled', label: '启用', toggle: toggleRole.id },
20
+ ...columns(['dailyAt', '每日签到时间'], ['status', '最近签到'], ['message', '结果']),
21
+ ];
22
+ const activityColumns = columns(['name', '角色'], ['game', '游戏'], ['provider', '渠道'], ['activityStatus', '更新状态'], ['activityTime', '数据采集时间'], ['activitySummary', '数据摘要']);
23
+ const credentialColumns = columns(['name', '凭据'], ['channel', '渠道'], ['roleCount', '游戏角色数']);
24
+ const credentialActions = [{ label: '管理', href: `${credentialsPath}/{id}` }];
25
+ const roleActions = [sign, { label: '管理', href: `${accountBase}/{id}` }];
26
+ const officialLogin = new Map([
27
+ ['miyoushe', 'https://www.miyoushe.com/'],
28
+ ['skland', 'https://www.skland.com/'],
29
+ ['cloud-genshin', 'https://ys.mihoyo.com/cloud/'],
30
+ ['kuro', 'https://www.kurobbs.com/'],
31
+ ['taygedo', 'https://www.tajiduo.com/'],
32
+ ]);
33
+ function loginLinks(channel) {
34
+ const href = officialLogin.get(channel.id);
35
+ return href ? [{ label: `打开${channel.title}官方登录`, href, external: true }] : [];
36
+ }
37
+ function decode(segment) {
38
+ try {
39
+ return decodeURIComponent(segment);
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ }
45
+ function credentialForm(channel, options = {}) {
46
+ const { existing, user, users, legacyProfile } = options;
47
+ const fields = [field('name', '凭据称呼', { required: true }), field('credential', '社区凭据', {
48
+ kind: 'password', required: !existing,
49
+ hint: existing ? `${channel.credentialHint} 留空将保留当前凭据。` : channel.credentialHint,
50
+ })];
51
+ if (!existing && !user && users?.length)
52
+ fields.unshift(field('userId', '所属用户', {
53
+ kind: 'select', options: users.map(user => ({ label: user.name, value: user.id })),
54
+ hint: '留空会创建同名用户。',
55
+ }));
56
+ return {
57
+ type: 'form', title: '社区凭据配置', action: 'community.credential.save', submitLabel: '保存凭据',
58
+ successHref: existing ? credentialHref(existing.id) : `${credentialsPath}/{id}${legacyProfile ? `/roles/new/${encodeURIComponent(legacyProfile.id)}` : ''}`,
59
+ fixed: { channelId: channel.id, ...(user ? { userId: user.id } : {}), ...(existing ? { id: existing.id } : {}) },
60
+ fields,
61
+ initial: { name: existing?.name ?? defaultCredentialName(channel.title) },
62
+ };
63
+ }
64
+ function roleForm(profile, credential, existing, alternatives = []) {
65
+ const fields = [field('name', '角色称呼', { required: true })];
66
+ if (profile.roleRequired)
67
+ fields.push(field('roleUid', '角色 UID', { required: true }));
68
+ let defaultServer;
69
+ if (profile.serverRequired) {
70
+ if (profile.serverOptions?.length) {
71
+ const options = [...profile.serverOptions];
72
+ if (existing?.server && !options.some(option => option.value === existing.server)) {
73
+ options.push({ label: existing.server, value: existing.server });
74
+ }
75
+ defaultServer = existing?.server ?? options[0]?.value;
76
+ fields.push(field('server', '区服', {
77
+ kind: 'select', required: true, options, default: defaultServer,
78
+ hint: profile.serverHint ?? '请选择该角色所属的区服。',
79
+ }));
80
+ }
81
+ else {
82
+ fields.push(field('server', '区服', {
83
+ required: true, hint: profile.serverHint ?? '填写社区渠道使用的区服标识。',
84
+ }));
85
+ }
86
+ }
87
+ if (alternatives.length > 1)
88
+ fields.unshift(field('credentialId', '所属凭据', {
89
+ kind: 'select', required: true,
90
+ options: alternatives.map(item => ({ label: item.userName ? `${item.userName} · ${item.name}` : item.name, value: item.id })),
91
+ }));
92
+ return {
93
+ type: 'form', title: '游戏角色配置', action: 'community.save', submitLabel: '保存角色',
94
+ successHref: existing ? accountHref(existing.id) : credentialHref(credential.id),
95
+ fixed: { profileId: profile.id, ...(existing ? { id: existing.id } : { credentialId: credential.id }) },
96
+ fields,
97
+ initial: existing ? {
98
+ name: existing.name, credentialId: credential.id, roleUid: existing.roleUid, server: existing.server,
99
+ } : { name: defaultRoleName(profile.title), server: defaultServer },
100
+ };
101
+ }
102
+ function profileChoices(channel, base) {
103
+ return {
104
+ type: 'choices', title: '支持的游戏',
105
+ items: channel.profiles.map(profile => ({
106
+ label: profile.title, href: `${base}/${encodeURIComponent(profile.id)}`,
107
+ ...(profile.activity ? { tag: '支持游戏信息' } : {}),
108
+ })),
109
+ };
110
+ }
111
+ function userForm(user) {
112
+ return {
113
+ type: 'form', title: '社区用户配置', action: 'community.user.save', submitLabel: '保存用户',
114
+ successHref: user ? userHref(user.id) : `${userBase}/{id}`,
115
+ fixed: user ? { id: user.id } : undefined, initial: { name: user?.name ?? defaultUserName },
116
+ fields: [field('name', '用户称呼', { required: true })],
117
+ };
118
+ }
119
+ export function communityPages(ctx, community, publish = () => { }) {
120
+ const registry = ui(ctx);
121
+ const account = (id) => id ? community.list().find(row => row.id === id) : undefined;
122
+ const profile = (id) => id ? community.profiles().find(entry => entry.id === id) : undefined;
123
+ const channel = (id) => community.channels().find(entry => entry.id === id);
124
+ const accounts = (input) => {
125
+ const id = text(input, 'id', '账号 ID', false);
126
+ const userId = text(input, 'userId', '用户 ID', false);
127
+ const credentialId = text(input, 'credentialId', '凭据 ID', false);
128
+ const known = new Set(community.profiles().map(profile => profile.id));
129
+ return community.list().filter(row => (!id || row.id === id) && (!userId || row.userId === userId)
130
+ && (!credentialId || row.credentialId === credentialId))
131
+ .map(row => ({ ...row, canSign: row.enabled && row.canSign && known.has(row.profileId) }));
132
+ };
133
+ const resolveQrContext = (path) => {
134
+ const updateMatch = /^\/community\/credentials\/([^/]+)\/qr$/.exec(path);
135
+ if (updateMatch) {
136
+ const credentialId = decode(updateMatch[1]);
137
+ const stored = credentialId ? community.credential(credentialId) : undefined;
138
+ const selected = stored ? channel(stored.channelId) : undefined;
139
+ if (!stored || !selected || !community.supportsQrLogin(selected.id))
140
+ return;
141
+ const parent = credentialHref(stored.id);
142
+ return {
143
+ mode: 'update',
144
+ channelId: selected.id,
145
+ channel: selected.title,
146
+ credential: { id: stored.id, name: stored.name, userId: stored.userId, userName: stored.userName },
147
+ users: [],
148
+ parent,
149
+ manualHref: `${parent}/edit`,
150
+ title: `扫码更新 · ${stored.name}`,
151
+ description: '重新扫码后将自动替换并加密保存此凭据,原有游戏角色与签到计划保持不变。',
152
+ };
153
+ }
154
+ const userMatch = /^\/community\/users\/([^/]+)\/credentials\/([^/]+)\/qr$/.exec(path);
155
+ if (userMatch) {
156
+ const userId = decode(userMatch[1]);
157
+ const user = userId ? community.user(userId) : undefined;
158
+ const rawId = decode(userMatch[2]);
159
+ const selected = channel(rawId);
160
+ const legacyProfile = selected ? undefined : profile(rawId);
161
+ const item = selected ?? community.channels().find(entry => entry.profiles.some(entryProfile => entryProfile.id === legacyProfile?.id));
162
+ if (!user || !item || !community.supportsQrLogin(item.id))
163
+ return;
164
+ const manualHref = `${userHref(user.id)}/credentials/${encodeURIComponent(rawId ?? item.id)}`;
165
+ return {
166
+ mode: 'create',
167
+ channelId: item.id,
168
+ channel: item.title,
169
+ user: { id: user.id, name: user.name },
170
+ users: [],
171
+ legacyProfileId: legacyProfile?.id,
172
+ parent: manualHref,
173
+ manualHref,
174
+ title: `${item.title}扫码登录`,
175
+ description: '使用官方手机客户端扫描二维码,确认后自动获取并加密保存凭据。',
176
+ };
177
+ }
178
+ const newMatch = /^\/community\/(?:credentials|accounts)\/new\/([^/]+)\/qr$/.exec(path);
179
+ if (newMatch) {
180
+ const rawId = decode(newMatch[1]);
181
+ const selected = channel(rawId);
182
+ const legacyProfile = selected ? undefined : profile(rawId);
183
+ const item = selected ?? community.channels().find(entry => entry.profiles.some(entryProfile => entryProfile.id === legacyProfile?.id));
184
+ if (!item || !community.supportsQrLogin(item.id))
185
+ return;
186
+ const manualHref = path.slice(0, -3);
187
+ return {
188
+ mode: 'create',
189
+ channelId: item.id,
190
+ channel: item.title,
191
+ users: community.users().map(user => ({ id: user.id, name: user.name })),
192
+ legacyProfileId: legacyProfile?.id,
193
+ parent: manualHref,
194
+ manualHref,
195
+ title: `${item.title}扫码登录`,
196
+ description: '使用官方手机客户端扫描二维码,确认后自动获取并加密保存凭据。',
197
+ };
198
+ }
199
+ };
200
+ const createCredential = (path, base, parent, user) => {
201
+ if (path === base)
202
+ return {
203
+ id: 'community-new', path, nav: false, parent, title: '添加社区凭据', icon: 'community',
204
+ components: [{
205
+ type: 'choices', title: '社区渠道',
206
+ items: community.channels().map(item => ({ label: item.title, href: `${base}/${encodeURIComponent(item.id)}` })),
207
+ }],
208
+ };
209
+ if (!path.startsWith(`${base}/`))
210
+ return;
211
+ const rest = path.slice(base.length + 1);
212
+ if (rest.endsWith('/qr')) {
213
+ const qr = resolveQrContext(path);
214
+ if (!qr)
215
+ return;
216
+ return {
217
+ id: 'community-credential-qr', path, nav: false, parent: qr.parent, title: qr.title, icon: 'community',
218
+ description: qr.description, view: 'builtin:community-qr',
219
+ links: [{ label: '改为手动填写', href: qr.manualHref }], components: [],
220
+ };
221
+ }
222
+ const id = decode(rest);
223
+ const selected = channel(id);
224
+ const legacyProfile = selected ? undefined : profile(id);
225
+ const item = selected ?? community.channels().find(entry => entry.profiles.some(profile => profile.id === legacyProfile?.id));
226
+ if (!item)
227
+ return;
228
+ const links = [
229
+ ...(community.supportsQrLogin(item.id) ? [{ label: '扫码登录获取凭据', href: `${path}/qr`, primary: true }] : []),
230
+ ...(loginLinks(item) ?? []),
231
+ ];
232
+ return {
233
+ id: 'community-credential-new', path, nav: false, parent: base, title: `添加${item.title}凭据`, icon: 'community',
234
+ description: community.supportsQrLogin(item.id)
235
+ ? '推荐使用扫码登录自动获取并加密保存凭据,也可以在官网登录后手动填写。'
236
+ : '官网登录后,请回到这里填写授权凭据。',
237
+ links, components: [credentialForm(item, { user, users: user ? undefined : community.users(), legacyProfile })],
238
+ };
239
+ };
240
+ const workbench = () => {
241
+ const known = new Set(community.profiles().map(item => item.id));
242
+ const rolesByCredential = new Map();
243
+ for (const row of community.list()) {
244
+ const record = community.activity(row.id);
245
+ const enriched = {
246
+ ...row,
247
+ canSign: row.enabled && row.canSign && known.has(row.profileId),
248
+ supportsSign: row.canSign,
249
+ lastAttemptTime: record?.time,
250
+ activityNote: record?.message,
251
+ metrics: record?.metrics ?? [],
252
+ };
253
+ const list = rolesByCredential.get(row.credentialId);
254
+ if (list)
255
+ list.push(enriched);
256
+ else
257
+ rolesByCredential.set(row.credentialId, [enriched]);
258
+ }
259
+ return {
260
+ gachaEnabled: community.gachaEnabled,
261
+ channels: community.channels().map(item => ({
262
+ id: item.id,
263
+ title: item.title,
264
+ credentialHint: item.credentialHint,
265
+ supportsQr: community.supportsQrLogin(item.id),
266
+ supportsSync: community.supportsRoleSync(item.id),
267
+ officialLoginUrl: officialLogin.get(item.id),
268
+ profiles: item.profiles.map(itemProfile => ({
269
+ id: itemProfile.id,
270
+ title: itemProfile.title,
271
+ roleRequired: Boolean(itemProfile.roleRequired),
272
+ serverRequired: Boolean(itemProfile.serverRequired),
273
+ serverHint: itemProfile.serverHint,
274
+ serverOptions: itemProfile.serverOptions,
275
+ canReadActivity: Boolean(itemProfile.activity),
276
+ })),
277
+ })),
278
+ users: community.users().map(user => ({ id: user.id, name: user.name, credentialCount: user.credentialCount })),
279
+ credentials: community.credentials().map(stored => ({
280
+ ...stored,
281
+ supportsQr: community.supportsQrLogin(stored.channelId),
282
+ supportsSync: community.supportsRoleSync(stored.channelId),
283
+ officialLoginUrl: officialLogin.get(stored.channelId),
284
+ roles: rolesByCredential.get(stored.id) ?? [],
285
+ })),
286
+ };
287
+ };
288
+ registry.scope(ctx, {
289
+ id: 'community', path: root, title, icon: 'community',
290
+ description: '按平台凭据管理名下多游戏与多区服角色,集中查看每日签到与实时便笺。',
291
+ view: 'builtin:community',
292
+ links: [{ label: '添加用户', href: `${userBase}/new` }],
293
+ components: [],
294
+ }, {
295
+ 'community.workbench': workbench,
296
+ 'community.list': () => community.list(),
297
+ 'community.users': () => community.users().map(user => ({ ...user, providerSummary: user.providers.join('、') })),
298
+ 'community.credentials': input => community.credentials(text(input, 'userId', '用户 ID', false) || undefined),
299
+ 'community.accounts': accounts,
300
+ 'community.activity-list': input => {
301
+ const id = text(input, 'id', '账号 ID', false);
302
+ const rows = community.list().filter(row => row.canReadActivity && (!id || row.id === id));
303
+ return id ? rows.map(row => {
304
+ const record = community.activity(row.id);
305
+ return { ...row, lastAttemptTime: record?.time, activityNote: record?.message };
306
+ }) : rows;
307
+ },
308
+ 'community.activity-metrics': input => community.activity(idOf(input))?.metrics ?? [],
309
+ 'community.qr.context': input => {
310
+ const path = text(input, 'path', '页面路径');
311
+ const context = resolveQrContext(path);
312
+ if (!context)
313
+ throw new Error('当前页面不支持扫码登录');
314
+ return context;
315
+ },
316
+ }, {
317
+ 'community.qr.start': input => community.startQrLogin({
318
+ id: text(input, 'id', '凭据 ID', false) || undefined,
319
+ userId: text(input, 'userId', '用户 ID', false) || undefined,
320
+ channelId: text(input, 'channelId', '社区渠道', false) || undefined,
321
+ name: text(input, 'name', '凭据称呼', false) || undefined,
322
+ }),
323
+ 'community.qr.poll': async (input) => {
324
+ const result = await community.pollQrLogin(text(input, 'sessionId', '扫码会话 ID'));
325
+ if (result.status === 'confirmed')
326
+ publish();
327
+ return result;
328
+ },
329
+ 'community.qr.cancel': input => {
330
+ community.cancelQrLogin(text(input, 'sessionId', '扫码会话 ID'));
331
+ return { ok: true };
332
+ },
333
+ 'community.credential.sync-roles': async (input) => {
334
+ const result = await community.syncCredentialRoles(text(input, 'id', '凭据 ID'));
335
+ if (result.added > 0)
336
+ publish();
337
+ return result;
338
+ },
339
+ 'community.user.save': input => community.saveUser({
340
+ id: text(input, 'id', '用户 ID', false) || undefined,
341
+ name: text(input, 'name', '用户称呼'),
342
+ }),
343
+ 'community.user.remove': input => {
344
+ if (input.confirmed !== true)
345
+ throw new Error('请确认删除社区用户');
346
+ community.removeUser(text(input, 'id', '用户 ID'));
347
+ },
348
+ 'community.credential.save': input => community.saveCredential({
349
+ id: text(input, 'id', '凭据 ID', false) || undefined,
350
+ userId: text(input, 'userId', '用户 ID', false) || undefined,
351
+ channelId: text(input, 'channelId', '社区渠道', false) || undefined,
352
+ name: text(input, 'name', '凭据称呼'),
353
+ credential: text(input, 'credential', '社区凭据', false) || undefined,
354
+ }),
355
+ 'community.credential.remove': input => {
356
+ if (input.confirmed !== true)
357
+ throw new Error('请确认删除社区凭据');
358
+ community.removeCredential(text(input, 'id', '凭据 ID'));
359
+ },
360
+ 'community.save': input => community.save({
361
+ id: text(input, 'id', '账号 ID', false) || undefined,
362
+ credentialId: text(input, 'credentialId', '凭据 ID', false) || undefined,
363
+ userId: text(input, 'userId', '用户 ID', false) || undefined,
364
+ profileId: text(input, 'profileId', '游戏', false) || undefined,
365
+ name: text(input, 'name', '角色称呼'),
366
+ credential: text(input, 'credential', '社区凭据', false) || undefined,
367
+ roleUid: text(input, 'roleUid', '角色 UID', false) || undefined,
368
+ server: text(input, 'server', '区服', false) || undefined,
369
+ }),
370
+ 'community.run': async (input) => {
371
+ const result = await community.run(idOf(input));
372
+ return {
373
+ status: signLabels[result.status], time: result.time, summary: result.message, gainSeconds: result.gainSeconds,
374
+ message: result.status === 'failed' || result.status === 'verification' ? '已记录签到结果' : result.message,
375
+ };
376
+ },
377
+ 'community.run-all': async () => {
378
+ const rows = await community.runAll();
379
+ if (rows.length)
380
+ publish();
381
+ const failed = rows.filter(row => row.status === 'failed' || row.status === 'verification').length;
382
+ return { processed: rows.length, failed, message: rows.length ? `已处理 ${rows.length} 项签到,${failed} 项需检查` : '没有启用的社区签到项目' };
383
+ },
384
+ [toggleRole.id]: input => {
385
+ const { value } = input;
386
+ if (value !== undefined && typeof value !== 'boolean')
387
+ throw new Error('启用状态必须为布尔值');
388
+ return community.toggle(idOf(input), value);
389
+ },
390
+ 'community.schedule': input => community.schedule(idOf(input), input.daily === true ? text(input, 'time', '签到时间') : undefined),
391
+ 'community.remove': input => {
392
+ if (input.confirmed !== true)
393
+ throw new Error('请确认删除社区账号');
394
+ community.remove(idOf(input));
395
+ },
396
+ 'community.activity.refresh': async (input) => {
397
+ const result = await community.refreshActivity(idOf(input));
398
+ return { status: result.status, time: result.time, message: result.status === 'success' ? '游戏信息已更新' : '已记录游戏信息更新结果' };
399
+ },
400
+ });
401
+ if (community.gachaEnabled)
402
+ registry.scope(ctx, {
403
+ id: 'community-gacha', path: '/community/gacha', parent: root, title: '明日方舟寻访记录', icon: 'community', nav: false,
404
+ view: 'builtin:community-gacha', components: [],
405
+ }, {
406
+ 'community.gacha.roles': () => community.gachaRoles(),
407
+ 'community.gacha.records': input => community.queryGacha(idOf(input), text(input, 'pool', '寻访卡池', false), Number(input.page ?? 1)),
408
+ }, {
409
+ 'community.gacha.sync': async (input) => {
410
+ const result = await community.syncGacha(idOf(input));
411
+ if (result.added)
412
+ publish();
413
+ return result;
414
+ },
415
+ });
416
+ registry.pageRoutes(ctx, path => {
417
+ if (path === credentialsPath)
418
+ return {
419
+ id: 'community-credentials', path, nav: false, parent: root, title: '账号与凭据', icon: 'community',
420
+ description: '管理社区用户、扫码或手动绑定的渠道凭据,并同步游戏角色。',
421
+ links: [{ label: '添加用户', href: `${userBase}/new` }, { label: '添加凭据', href: `${credentialsPath}/new`, primary: true }],
422
+ components: [{
423
+ type: 'table', title: '社区凭据', query: 'community.credentials',
424
+ columns: [...columns(['userName', '所属用户']), ...credentialColumns], rowActions: credentialActions,
425
+ }, {
426
+ type: 'table', title: '社区用户', query: 'community.users',
427
+ columns: columns(['name', '用户'], ['providerSummary', '社区渠道'], ['credentialCount', '凭据数量']),
428
+ rowActions: [{ label: '管理凭据', href: `${userBase}/{id}` }],
429
+ }],
430
+ };
431
+ const newCredential = createCredential(path, `${credentialsPath}/new`, credentialsPath)
432
+ ?? createCredential(path, `${accountBase}/new`, credentialsPath);
433
+ if (newCredential)
434
+ return newCredential;
435
+ const credentialMatch = /^\/community\/credentials\/([^/]+)(?:\/(.*))?$/.exec(path);
436
+ if (credentialMatch) {
437
+ const credentialId = decode(credentialMatch[1]);
438
+ const stored = credentialId ? community.credential(credentialId) : undefined;
439
+ if (!stored)
440
+ return;
441
+ const selected = channel(stored.channelId);
442
+ const parent = credentialHref(stored.id);
443
+ const newRolePath = `${parent}/roles/new`;
444
+ const child = credentialMatch[2];
445
+ const descriptor = { path, nav: false, icon: 'community', description: stored.userName ? `${stored.channel} · 用户:${stored.userName}` : stored.channel };
446
+ if (!child) {
447
+ const onlyGame = selected?.profiles.length === 1 ? selected.profiles[0] : undefined;
448
+ return {
449
+ ...descriptor, id: 'community-credential', parent: credentialsPath, title: stored.name,
450
+ links: [
451
+ ...(selected?.profiles.length ? [{ label: '添加游戏角色', primary: true,
452
+ href: onlyGame ? `${newRolePath}/${encodeURIComponent(onlyGame.id)}` : newRolePath }] : []),
453
+ ...(selected && community.supportsQrLogin(selected.id) ? [{ label: '扫码更新凭据', href: `${parent}/qr` }] : []),
454
+ ...(selected ? [{ label: '编辑凭据', href: `${parent}/edit` }] : []),
455
+ ...(stored.roleCount ? [] : [{ label: '删除凭据', href: `${parent}/remove` }]),
456
+ ],
457
+ components: [
458
+ ...(selected && community.supportsRoleSync(selected.id) ? [{
459
+ type: 'form', title: '同步绑定角色', action: 'community.credential.sync-roles',
460
+ submitLabel: '一键同步绑定角色', fixed: { id: stored.id }, fields: [],
461
+ }] : []),
462
+ {
463
+ type: 'table', title: '游戏角色', query: 'community.accounts', queryInput: { credentialId: stored.id },
464
+ columns: signColumns, rowActions: roleActions,
465
+ },
466
+ ],
467
+ };
468
+ }
469
+ if (child === 'qr' && selected && community.supportsQrLogin(selected.id)) {
470
+ const qr = resolveQrContext(path);
471
+ return {
472
+ ...descriptor, id: 'community-credential-qr', parent, title: qr.title,
473
+ description: qr.description, view: 'builtin:community-qr',
474
+ links: [{ label: '改为手动填写', href: qr.manualHref }], components: [],
475
+ };
476
+ }
477
+ if (child === 'edit' && selected)
478
+ return {
479
+ ...descriptor, id: 'community-credential-edit', parent, title: '编辑社区凭据',
480
+ links: [
481
+ ...(community.supportsQrLogin(selected.id) ? [{ label: '扫码更新凭据', href: `${parent}/qr`, primary: true }] : []),
482
+ ...(loginLinks(selected) ?? []),
483
+ ],
484
+ components: [credentialForm(selected, { existing: stored })],
485
+ };
486
+ if (child === 'remove' && !stored.roleCount)
487
+ return {
488
+ ...descriptor, id: 'community-credential-remove', parent, title: '删除社区凭据', components: [{
489
+ type: 'form', title: '确认删除', action: 'community.credential.remove', submitLabel: '删除凭据', successHref: credentialsPath,
490
+ fixed: { id: stored.id }, fields: [field('confirmed', `确认删除凭据「${stored.name}」`, { kind: 'boolean' })],
491
+ }],
492
+ };
493
+ if (child === 'roles/new' && selected)
494
+ return {
495
+ ...descriptor, id: 'community-role-new', parent, title: '添加游戏角色',
496
+ components: [profileChoices(selected, newRolePath)],
497
+ };
498
+ if (child.startsWith('roles/new/') && selected) {
499
+ const profileId = decode(child.slice('roles/new/'.length));
500
+ const game = selected.profiles.find(profile => profile.id === profileId);
501
+ if (game)
502
+ return {
503
+ ...descriptor, id: 'community-role-profile', parent: selected.profiles.length === 1 ? parent : newRolePath,
504
+ title: `添加${game.title}角色`, components: [roleForm(game, stored)],
505
+ };
506
+ }
507
+ return;
508
+ }
509
+ if (path === `${userBase}/new`)
510
+ return {
511
+ id: 'community-user-new', path, nav: false, parent: credentialsPath, title: '添加社区用户', icon: 'community',
512
+ components: [userForm()],
513
+ };
514
+ const userMatch = /^\/community\/users\/([^/]+)(?:\/(.*))?$/.exec(path);
515
+ if (userMatch) {
516
+ const id = decode(userMatch[1]);
517
+ const user = id && community.user(id);
518
+ if (!user)
519
+ return;
520
+ const parent = userHref(user.id);
521
+ const base = `${parent}/credentials`;
522
+ switch (userMatch[2]) {
523
+ case undefined: return {
524
+ id: 'community-user', path, nav: false, parent: credentialsPath, title: user.name, icon: 'community',
525
+ links: [{ label: '添加凭据', href: base, primary: true }, { label: '编辑用户', href: `${parent}/edit` },
526
+ ...(user.credentialCount ? [] : [{ label: '删除用户', href: `${parent}/remove` }])],
527
+ components: [{
528
+ type: 'table', title: '社区凭据', query: 'community.credentials', queryInput: { userId: user.id },
529
+ columns: credentialColumns, rowActions: credentialActions,
530
+ }, {
531
+ type: 'table', title: '游戏角色', query: 'community.accounts', queryInput: { userId: user.id },
532
+ columns: [...columns(['credentialName', '所属凭据']), ...signColumns], rowActions: roleActions,
533
+ }],
534
+ };
535
+ case 'edit': return {
536
+ id: 'community-user-edit', path, nav: false, parent, title: '编辑社区用户', icon: 'community',
537
+ components: [userForm(user)],
538
+ };
539
+ case 'remove': return user.credentialCount ? undefined : {
540
+ id: 'community-user-remove', path, nav: false, parent, title: '删除社区用户', icon: 'community',
541
+ components: [{
542
+ type: 'form', title: '确认删除', action: 'community.user.remove', submitLabel: '删除用户', successHref: credentialsPath,
543
+ fixed: { id: user.id }, fields: [field('confirmed', `确认删除用户「${user.name}」`, { kind: 'boolean' })],
544
+ }],
545
+ };
546
+ default: return createCredential(path, base, parent, user);
547
+ }
548
+ }
549
+ if (path === activityBase) {
550
+ return {
551
+ id: 'community-activity', path, nav: false, parent: root, title: '游戏信息', icon: 'community',
552
+ description: '查看各游戏角色最近一次获取的体力与日常进度。',
553
+ components: [{
554
+ type: 'table', title: '可查询游戏信息的账号', query: 'community.activity-list',
555
+ columns: [...columns(['userName', '所属用户']), ...activityColumns],
556
+ rowActions: [{ label: '查看数据', href: `${activityBase}/{id}` }, refreshActivity],
557
+ }],
558
+ };
559
+ }
560
+ const activity = /^\/community\/activity\/([^/]+)$/.exec(path);
561
+ if (activity) {
562
+ const entry = account(decode(activity[1]));
563
+ if (!entry?.canReadActivity)
564
+ return;
565
+ return {
566
+ id: 'community-activity-detail', path, nav: false, parent: activityBase, title: `${entry.name} · 游戏信息`, icon: 'community',
567
+ description: `${entry.game} · ${entry.provider}`,
568
+ links: [{ label: '账号与签到', href: accountHref(entry.id) }],
569
+ components: [
570
+ { type: 'metrics', title: '游戏数据', query: 'community.activity-metrics', queryInput: { id: entry.id } },
571
+ { type: 'table', title: '更新记录', query: 'community.activity-list', queryInput: { id: entry.id },
572
+ columns: columns(['activityStatus', '更新状态'], ['lastAttemptTime', '最近尝试'], ['activityTime', '当前数据采集时间'], ['activityNote', '结果']), rowActions: [refreshActivity] },
573
+ ],
574
+ };
575
+ }
576
+ const match = /^\/community\/accounts\/([^/]+)(?:\/(edit|schedule|remove))?$/.exec(path);
577
+ const entry = match && account(decode(match[1]));
578
+ if (!match || !entry)
579
+ return;
580
+ const provider = profile(entry.profileId);
581
+ const parent = accountHref(entry.id);
582
+ const stored = community.credential(entry.credentialId);
583
+ const descriptor = { path, nav: false, icon: 'community', description: `${entry.game} · ${entry.provider}` };
584
+ switch (match[2]) {
585
+ case 'edit': {
586
+ if (!provider || !stored)
587
+ return;
588
+ const alternatives = community.credentials().filter(item => item.channelId === stored.channelId)
589
+ .sort((a, b) => Number(b.userId === stored.userId) - Number(a.userId === stored.userId));
590
+ return {
591
+ ...descriptor, id: 'community-account-edit', parent, title: '编辑游戏角色',
592
+ components: [roleForm(provider, stored, entry, alternatives)],
593
+ };
594
+ }
595
+ case 'schedule': return !entry.canSign ? undefined : {
596
+ ...descriptor, id: 'community-account-schedule', parent, title: '每日签到计划', components: [{
597
+ type: 'form', title: '自动签到', action: 'community.schedule', submitLabel: '保存计划', successHref: parent,
598
+ fixed: { id: entry.id }, initial: { daily: Boolean(entry.dailyAt), time: entry.dailyAt },
599
+ fields: [
600
+ field('daily', '启用每日自动签到', { kind: 'boolean' }),
601
+ field('time', '签到时间(北京时间,HH:MM)', {
602
+ required: true, visibleWhen: { key: 'daily', equals: true },
603
+ hint: '每日自动尝试一次。后端在设定时间后启动时会补跑。',
604
+ }),
605
+ ],
606
+ }],
607
+ };
608
+ case 'remove': return {
609
+ ...descriptor, id: 'community-account-remove', parent, title: '删除游戏角色', components: [{
610
+ type: 'form', title: '确认删除', action: 'community.remove', submitLabel: '删除角色', successHref: root,
611
+ fixed: { id: entry.id }, fields: [field('confirmed', '确认删除此角色及其签到和游戏信息记录', { kind: 'boolean' })],
612
+ }],
613
+ };
614
+ default: return {
615
+ ...descriptor, id: 'community-account', parent: root, title: entry.name, links: [
616
+ ...(provider && stored ? [{ label: '编辑角色', href: `${parent}/edit`, primary: true }] : []),
617
+ ...(entry.canSign ? [{ label: '每日签到计划', href: `${parent}/schedule` }] : []),
618
+ ...(entry.canReadActivity ? [{ label: '游戏信息', href: activityHref(entry.id) }] : []),
619
+ { label: '删除角色', href: `${parent}/remove` },
620
+ ],
621
+ components: [{
622
+ type: 'table', title: '签到状态', query: 'community.accounts', queryInput: { id: entry.id },
623
+ columns: [...columns(['userName', '所属用户'], ['credentialName', '所属凭据']), ...signColumns.slice(1), ...columns(['time', '签到时间']),
624
+ ...(entry.roleUid ? columns(['roleUid', '角色 UID']) : [])],
625
+ rowActions: [sign, toggleRole],
626
+ }],
627
+ };
628
+ }
629
+ });
630
+ }