koishi-plugin-oni-sync-bot 0.9.3 → 0.10.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/lib/index.js CHANGED
@@ -35,20 +35,49 @@ __export(src_exports, {
35
35
  name: () => name
36
36
  });
37
37
  module.exports = __toCommonJS(src_exports);
38
- var import_koishi11 = require("koishi");
39
38
  var import_path = require("path");
40
39
 
40
+ // src/config.ts
41
+ var import_koishi = require("koishi");
42
+ var SiteConfig = import_koishi.Schema.object({
43
+ domain: import_koishi.Schema.string().description("你的短链域名(必填,如:klei.vip)").default("klei.vip"),
44
+ main_site: import_koishi.Schema.string().description("主站域名(必填,如:oxygennotincluded.wiki.gg)").default("oxygennotincluded.wiki.gg/zh"),
45
+ bwiki_site: import_koishi.Schema.string().description("镜像站域名(必填,如:wiki.biligame.com)").default("wiki.biligame.com/oni")
46
+ });
47
+ var AccountConfig = import_koishi.Schema.object({
48
+ ggUsername: import_koishi.Schema.string().description("WIKIGG 用户名").default("1"),
49
+ ggPassword: import_koishi.Schema.string().description("WIKIGG 密码").default("1"),
50
+ bwikiusername: import_koishi.Schema.string().description("bwiki用户名").default("1"),
51
+ bwikipassword: import_koishi.Schema.string().description("bwiki密码").default("1")
52
+ });
53
+ var NotifyConfig = import_koishi.Schema.object({
54
+ logsUrl: import_koishi.Schema.string().description("日志查看地址").default("https://klei.vip/onilogs"),
55
+ notifyGroupIds: import_koishi.Schema.array(import_koishi.Schema.string()).description(
56
+ '增量更新同步成功时通知的群频道ID列表,如 ["group:123456"],留空则不发送通知'
57
+ ).default([]),
58
+ notifyBotPlatform: import_koishi.Schema.string().description("通知 bot 的平台标识,默认 qq").default("qq")
59
+ });
60
+ var ScheduleConfig = import_koishi.Schema.object({
61
+ updateCron: import_koishi.Schema.string().description("页面缓存自动更新 cron 表达式(默认每天凌晨 2 点)").default("0 2 * * *")
62
+ });
63
+ var Config = import_koishi.Schema.intersect([
64
+ AccountConfig,
65
+ SiteConfig,
66
+ NotifyConfig,
67
+ ScheduleConfig
68
+ ]);
69
+
41
70
  // src/services/wikiBotService.ts
42
- var import_koishi2 = require("koishi");
71
+ var import_koishi4 = require("koishi");
43
72
  var import_mwn = require("mwn");
44
73
 
45
74
  // src/utils/tools.ts
46
- var import_koishi = require("koishi");
75
+ var import_koishi2 = require("koishi");
47
76
  var import_pinyin_pro = require("pinyin-pro");
48
77
  var CROSS_SITE_LINK_REGEX = /\[\[(en|ru|pt-br):[^\]]*\]\]/g;
49
78
  var DEV_TEXT_REGEX = /(?<!\w)Dev:/g;
50
79
  var MODULE_NAMESPACE_PREFIX = "Module:Dev/";
51
- var logger = new import_koishi.Logger("oni-sync");
80
+ var logger = new import_koishi2.Logger("oni-sync");
52
81
  function clean_page_text(text) {
53
82
  const textWithoutCrossLink = text.replace(CROSS_SITE_LINK_REGEX, "");
54
83
  const textWithReplacedDev = textWithoutCrossLink.replace(
@@ -95,9 +124,10 @@ async function getAndProcessPageContent(site, pageTitle) {
95
124
  rvlimit: 1
96
125
  });
97
126
  if (queryRes && queryRes.query && queryRes.query.pages) {
98
- const pageIds = Object.keys(queryRes.query.pages);
127
+ const pages = queryRes.query.pages;
128
+ const pageIds = Object.keys(pages);
99
129
  if (pageIds.length > 0) {
100
- const page = queryRes.query.pages[pageIds[0]];
130
+ const page = pages[pageIds[0]];
101
131
  if (page.revisions && page.revisions.length > 0) {
102
132
  rawText = page.revisions[0].content || "";
103
133
  }
@@ -146,19 +176,17 @@ function getErrorMessage(error) {
146
176
  }
147
177
  __name(getErrorMessage, "getErrorMessage");
148
178
  function formatWikiTime(isoString) {
149
- try {
150
- const date = new Date(isoString);
151
- if (Number.isNaN(date.getTime())) return isoString;
152
- const pad = /* @__PURE__ */ __name((n) => String(n).padStart(2, "0"), "pad");
153
- const y = date.getFullYear();
154
- const m = pad(date.getMonth() + 1);
155
- const d = pad(date.getDate());
156
- const hh = pad((date.getUTCHours() + 8) % 24);
157
- const mm = pad(date.getUTCMinutes());
158
- return `${y}-${m}-${d} ${hh}:${mm}`;
159
- } catch {
160
- return isoString;
161
- }
179
+ const date = new Date(isoString);
180
+ if (Number.isNaN(date.getTime())) return isoString;
181
+ const BEIJING_OFFSET_MS = 8 * 60 * 60 * 1e3;
182
+ const beijing = new Date(date.getTime() + BEIJING_OFFSET_MS);
183
+ const pad = /* @__PURE__ */ __name((n) => String(n).padStart(2, "0"), "pad");
184
+ const y = beijing.getUTCFullYear();
185
+ const m = pad(beijing.getUTCMonth() + 1);
186
+ const d = pad(beijing.getUTCDate());
187
+ const hh = pad(beijing.getUTCHours());
188
+ const mm = pad(beijing.getUTCMinutes());
189
+ return `${y}-${m}-${d} ${hh}:${mm}`;
162
190
  }
163
191
  __name(formatWikiTime, "formatWikiTime");
164
192
  function normalizeChannelId(rawId) {
@@ -200,15 +228,103 @@ function stripImagePrefix(fileName) {
200
228
  }
201
229
  __name(stripImagePrefix, "stripImagePrefix");
202
230
 
231
+ // src/utils/async.ts
232
+ var import_koishi3 = require("koishi");
233
+ async function withRetry(fn, options = {}) {
234
+ const { attempts = 3, delayMs = 1e3, onRetry } = options;
235
+ if (!Number.isInteger(attempts) || attempts < 1) {
236
+ throw new RangeError(`attempts 必须是 >= 1 的整数,收到 ${attempts}`);
237
+ }
238
+ let lastError;
239
+ for (let attempt = 1; attempt <= attempts; attempt++) {
240
+ try {
241
+ return await fn();
242
+ } catch (error) {
243
+ lastError = error;
244
+ if (attempt >= attempts) break;
245
+ onRetry?.(error, attempt, attempts);
246
+ if (delayMs > 0) await (0, import_koishi3.sleep)(delayMs);
247
+ }
248
+ }
249
+ throw lastError;
250
+ }
251
+ __name(withRetry, "withRetry");
252
+
253
+ // src/services/reloginAwareProxy.ts
254
+ function isAssertUserFailed(error) {
255
+ return typeof error === "object" && error !== null && error.code === "assertuserfailed";
256
+ }
257
+ __name(isAssertUserFailed, "isAssertUserFailed");
258
+ var METHODS_TO_SKIP = /* @__PURE__ */ new Set(["cookieJar", "setRequestOptions"]);
259
+ function memberOf(bot, prop) {
260
+ return bot[prop];
261
+ }
262
+ __name(memberOf, "memberOf");
263
+ function createReloginAwareProxy(options) {
264
+ const { getBot, relogin, label } = options;
265
+ const invokeWithRelogin = /* @__PURE__ */ __name(async (invoke) => {
266
+ try {
267
+ return await invoke(getBot());
268
+ } catch (error) {
269
+ if (!isAssertUserFailed(error)) throw error;
270
+ await relogin();
271
+ return await invoke(getBot());
272
+ }
273
+ }, "invokeWithRelogin");
274
+ return new Proxy({}, {
275
+ get: /* @__PURE__ */ __name((_target, prop) => {
276
+ const value = memberOf(getBot(), prop);
277
+ if (typeof value !== "function") return value;
278
+ if (typeof prop === "string" && METHODS_TO_SKIP.has(prop)) {
279
+ return value.bind(getBot());
280
+ }
281
+ if (prop === "continuedQueryGen") {
282
+ return (...args) => {
283
+ const createIterator = /* @__PURE__ */ __name((callArgs) => {
284
+ const bot = getBot();
285
+ const generate = memberOf(bot, "continuedQueryGen");
286
+ return generate.apply(bot, callArgs)[Symbol.asyncIterator]();
287
+ }, "createIterator");
288
+ let iterator = createIterator(args);
289
+ return {
290
+ [Symbol.asyncIterator]() {
291
+ return this;
292
+ },
293
+ async next() {
294
+ try {
295
+ return await iterator.next();
296
+ } catch (error) {
297
+ if (!isAssertUserFailed(error)) throw error;
298
+ await relogin();
299
+ iterator = createIterator(args);
300
+ return await iterator.next();
301
+ }
302
+ }
303
+ };
304
+ };
305
+ }
306
+ return (...args) => invokeWithRelogin((bot) => {
307
+ const method = memberOf(bot, prop);
308
+ if (typeof method !== "function") {
309
+ throw new Error(`${label} bot 缺少方法 ${String(prop)}`);
310
+ }
311
+ const call = method;
312
+ return call.apply(bot, args);
313
+ });
314
+ }, "get")
315
+ });
316
+ }
317
+ __name(createReloginAwareProxy, "createReloginAwareProxy");
318
+
203
319
  // src/services/wikiBotService.ts
204
- var WikiBotService = class _WikiBotService extends import_koishi2.Service {
320
+ var WikiBotService = class _WikiBotService extends import_koishi4.Service {
205
321
  static {
206
322
  __name(this, "WikiBotService");
207
323
  }
208
324
  static inject = [];
209
325
  ggbot = null;
210
326
  bwikibot = null;
211
- isReady = false;
327
+ botProxies = { gg: null, bwiki: null };
212
328
  botConfig;
213
329
  static USER_AGENT = `OniSyncBot/1.0 (https://klei.vip; Charles@klei.vip)`;
214
330
  static MAX_RETRIES = 3;
@@ -217,6 +333,24 @@ var WikiBotService = class _WikiBotService extends import_koishi2.Service {
217
333
  super(ctx, "wikiBot", true);
218
334
  this.botConfig = config;
219
335
  }
336
+ /** 站点显示名,避免到处写 `site === "gg" ? "WIKIGG" : "bwiki"` */
337
+ static siteLabel(site) {
338
+ return site === "gg" ? "WIKIGG" : "bwiki";
339
+ }
340
+ botOf(site) {
341
+ return site === "gg" ? this.ggbot : this.bwikibot;
342
+ }
343
+ setBot(site, bot) {
344
+ if (site === "gg") {
345
+ this.ggbot = bot;
346
+ } else {
347
+ this.bwikibot = bot;
348
+ }
349
+ }
350
+ siteConfigOf(site) {
351
+ const sites = this.getSitesConfig();
352
+ return site === "gg" ? sites.gg : sites.bwiki;
353
+ }
220
354
  getSitesConfig() {
221
355
  return {
222
356
  gg: {
@@ -235,20 +369,17 @@ var WikiBotService = class _WikiBotService extends import_koishi2.Service {
235
369
  }
236
370
  };
237
371
  }
238
- delay(ms) {
239
- return new Promise((resolve2) => setTimeout(resolve2, ms));
240
- }
241
- async loginWithRetry(siteConfig, attempt = 1) {
372
+ async loginWithRetry(siteConfig) {
242
373
  try {
243
- const bot = await this.login(siteConfig);
244
- return bot;
374
+ return await withRetry(() => this.login(siteConfig), {
375
+ attempts: _WikiBotService.MAX_RETRIES,
376
+ delayMs: _WikiBotService.RETRY_DELAY,
377
+ onRetry: /* @__PURE__ */ __name((error, attempt, attempts) => logger.debug(
378
+ `${siteConfig.name} 登录失败,重试中 (${attempt}/${attempts}): ${getErrorMessage(error)}`
379
+ ), "onRetry")
380
+ });
245
381
  } catch (error) {
246
- const errorMsg = getErrorMessage(error);
247
- if (attempt < _WikiBotService.MAX_RETRIES) {
248
- await this.delay(_WikiBotService.RETRY_DELAY);
249
- return this.loginWithRetry(siteConfig, attempt + 1);
250
- }
251
- logger.error(`❌ ${siteConfig.name} 登录失败`, errorMsg);
382
+ logger.error(`❌ ${siteConfig.name} 登录失败`, getErrorMessage(error));
252
383
  throw error;
253
384
  }
254
385
  }
@@ -283,21 +414,9 @@ var WikiBotService = class _WikiBotService extends import_koishi2.Service {
283
414
  }
284
415
  async start() {
285
416
  try {
286
- const sitesConfig = this.getSitesConfig();
287
- try {
288
- this.ggbot = await this.loginWithRetry(sitesConfig.gg);
289
- logger.info("✅ WIKIGG 登录成功");
290
- } catch (error) {
291
- this.ggbot = null;
292
- }
293
- try {
294
- this.bwikibot = await this.loginWithRetry(sitesConfig.bwiki);
295
- logger.info("✅ bwiki 登录成功");
296
- } catch (error) {
297
- this.bwikibot = null;
298
- }
299
- this.isReady = this.ggbot !== null || this.bwikibot !== null;
300
- if (!this.isReady) {
417
+ const ggOk = await this.loginSite("gg");
418
+ const bwikiOk = await this.loginSite("bwiki");
419
+ if (!ggOk && !bwikiOk) {
301
420
  logger.error("❌ WikiBotService 初始化失败,两个 Wiki 均无法登录");
302
421
  }
303
422
  } catch (error) {
@@ -306,181 +425,114 @@ var WikiBotService = class _WikiBotService extends import_koishi2.Service {
306
425
  }
307
426
  }
308
427
  stop() {
309
- this.isReady = false;
310
428
  this.ggbot = null;
311
429
  this.bwikibot = null;
312
- this.ggbotProxy = null;
313
- this.bwikibotProxy = null;
430
+ this.botProxies = { gg: null, bwiki: null };
314
431
  }
315
432
  async relogin() {
316
- const sitesConfig = this.getSitesConfig();
317
- let ggSuccess = false;
318
- let bwikiSuccess = false;
319
- try {
320
- this.ggbot = await this.loginWithRetry(sitesConfig.gg);
321
- ggSuccess = true;
322
- logger.info("✅ WIKIGG 重新登录成功");
323
- } catch (error) {
324
- this.ggbot = null;
433
+ const gg = await this.loginSite("gg", true);
434
+ const bwiki = await this.loginSite("bwiki", true);
435
+ return { gg, bwiki };
436
+ }
437
+ /**
438
+ * 确保两个站点都已登录:任一未就绪时先尝试重新登录。
439
+ * 就绪状态属于本服务的职责,调用方只消费结果。
440
+ */
441
+ async ensureReady() {
442
+ if (!this.isGGBotReady() || !this.isBWikiBotReady()) {
443
+ logger.warn("检测到部分机器人未就绪,尝试重新登录...");
444
+ try {
445
+ await this.relogin();
446
+ } catch (error) {
447
+ logger.error("重新登录失败:", getErrorMessage(error));
448
+ }
325
449
  }
450
+ return { gg: this.isGGBotReady(), bwiki: this.isBWikiBotReady() };
451
+ }
452
+ /** 登录单个站点;失败不抛错、只返回是否成功(顺序调用以保持原有时序) */
453
+ async loginSite(site, isRelogin = false) {
454
+ const label = _WikiBotService.siteLabel(site);
326
455
  try {
327
- this.bwikibot = await this.loginWithRetry(sitesConfig.bwiki);
328
- bwikiSuccess = true;
329
- logger.info("✅ bwiki 重新登录成功");
456
+ this.setBot(site, await this.loginWithRetry(this.siteConfigOf(site)));
457
+ logger.info(`✅ ${label} ${isRelogin ? "重新" : ""}登录成功`);
458
+ return true;
330
459
  } catch (error) {
331
- this.bwikibot = null;
460
+ this.setBot(site, null);
461
+ return false;
332
462
  }
333
- this.isReady = this.ggbot !== null || this.bwikibot !== null;
334
- return { gg: ggSuccess, bwiki: bwikiSuccess };
335
463
  }
336
464
  async reloginSite(site) {
337
- const siteName = site === "gg" ? "WIKIGG" : "bwiki";
338
- const sitesConfig = this.getSitesConfig();
339
- const siteConfig = site === "gg" ? sitesConfig.gg : sitesConfig.bwiki;
465
+ const label = _WikiBotService.siteLabel(site);
340
466
  try {
341
- const bot = await this.loginWithRetry(siteConfig);
342
- if (site === "gg") {
343
- this.ggbot = bot;
344
- } else {
345
- this.bwikibot = bot;
346
- }
347
- logger.info(`✅ ${siteName} 自动重新登录成功`);
467
+ this.setBot(site, await this.loginWithRetry(this.siteConfigOf(site)));
468
+ logger.info(`✅ ${label} 自动重新登录成功`);
348
469
  } catch (error) {
349
- if (site === "gg") {
350
- this.ggbot = null;
351
- } else {
352
- this.bwikibot = null;
353
- }
470
+ this.setBot(site, null);
354
471
  throw error;
355
472
  }
356
473
  }
474
+ /** 两个站点是否至少有一个可用(派生状态,不需要手工同步) */
475
+ get isReady() {
476
+ return this.ggbot !== null || this.bwikibot !== null;
477
+ }
357
478
  isGGBotReady() {
358
- return this.ggbot !== null;
479
+ return this.botOf("gg") !== null;
359
480
  }
360
481
  isBWikiBotReady() {
361
- return this.bwikibot !== null;
482
+ return this.botOf("bwiki") !== null;
362
483
  }
363
484
  createBotProxy(site) {
364
- const self = this;
365
- const METHODS_TO_SKIP = /* @__PURE__ */ new Set(["cookieJar", "setRequestOptions"]);
366
- const getCurrentBot = /* @__PURE__ */ __name(() => {
367
- const bot = site === "gg" ? self.ggbot : self.bwikibot;
368
- if (!bot) {
369
- throw new Error(
370
- `${site === "gg" ? "WIKIGG" : "bwiki"} bot 尚未就绪,请检查登录配置或查看日志`
371
- );
372
- }
373
- return bot;
374
- }, "getCurrentBot");
375
- return new Proxy({}, {
376
- get(_target, prop) {
377
- const propKey = prop;
378
- const currentBot = getCurrentBot();
379
- const value = currentBot[propKey];
380
- if (typeof value !== "function") {
381
- return value;
382
- }
383
- if (METHODS_TO_SKIP.has(prop)) {
384
- return value.bind(currentBot);
385
- }
386
- if (prop === "continuedQueryGen") {
387
- return function(...args) {
388
- let activeBot = getCurrentBot();
389
- let activeMethod = activeBot.continuedQueryGen;
390
- let activeIterator = activeMethod.apply(activeBot, args)[Symbol.asyncIterator]();
391
- return {
392
- [Symbol.asyncIterator]() {
393
- return this;
394
- },
395
- async next() {
396
- try {
397
- return await activeIterator.next();
398
- } catch (error) {
399
- if (error.code === "assertuserfailed") {
400
- await self.reloginSite(site);
401
- activeBot = getCurrentBot();
402
- activeMethod = activeBot.continuedQueryGen;
403
- const newGen = activeMethod.apply(activeBot, args);
404
- activeIterator = newGen[Symbol.asyncIterator]();
405
- return await activeIterator.next();
406
- }
407
- throw error;
408
- }
409
- }
410
- };
411
- };
485
+ const label = _WikiBotService.siteLabel(site);
486
+ return createReloginAwareProxy({
487
+ getBot: /* @__PURE__ */ __name(() => {
488
+ const bot = this.botOf(site);
489
+ if (!bot) {
490
+ throw new Error(`${label} bot 尚未就绪,请检查登录配置或查看日志`);
412
491
  }
413
- return async function(...args) {
414
- let executeBot = getCurrentBot();
415
- let method = executeBot[propKey];
416
- if (typeof method !== "function") {
417
- throw new Error(
418
- `${site === "gg" ? "WIKIGG" : "bwiki"} bot 缺少方法 ${String(prop)}`
419
- );
420
- }
421
- try {
422
- return await method.apply(executeBot, args);
423
- } catch (error) {
424
- if (error.code === "assertuserfailed") {
425
- await self.reloginSite(site);
426
- executeBot = getCurrentBot();
427
- method = executeBot[propKey];
428
- if (typeof method !== "function") {
429
- throw new Error(
430
- `${site === "gg" ? "WIKIGG" : "bwiki"} 新 bot 缺少方法 ${String(prop)}`
431
- );
432
- }
433
- return await method.apply(executeBot, args);
434
- }
435
- throw error;
436
- }
437
- };
438
- }
492
+ return bot;
493
+ }, "getBot"),
494
+ relogin: /* @__PURE__ */ __name(() => this.reloginSite(site), "relogin"),
495
+ label
439
496
  });
440
497
  }
441
- ggbotProxy = null;
442
- bwikibotProxy = null;
498
+ /** WIKIGG 客户端(透明处理登录过期) */
443
499
  getGGBot() {
444
- if (!this.ggbot) {
445
- throw new Error("WIKIGG bot 尚未就绪,请检查登录配置或查看日志");
446
- }
447
- if (!this.ggbotProxy) {
448
- this.ggbotProxy = this.createBotProxy("gg");
449
- }
450
- return this.ggbotProxy;
500
+ return this.getBot("gg");
451
501
  }
502
+ /** bwiki 客户端(透明处理登录过期) */
452
503
  getBWikiBot() {
453
- if (!this.bwikibot) {
454
- throw new Error("bwiki bot 尚未就绪,请检查登录配置或查看日志");
504
+ return this.getBot("bwiki");
505
+ }
506
+ getBot(site) {
507
+ if (!this.botOf(site)) {
508
+ throw new Error(
509
+ `${_WikiBotService.siteLabel(site)} bot 尚未就绪,请检查登录配置或查看日志`
510
+ );
455
511
  }
456
- if (!this.bwikibotProxy) {
457
- this.bwikibotProxy = this.createBotProxy("bwiki");
512
+ let proxy = this.botProxies[site];
513
+ if (!proxy) {
514
+ proxy = this.createBotProxy(site);
515
+ this.botProxies[site] = proxy;
458
516
  }
459
- return this.bwikibotProxy;
517
+ return proxy;
460
518
  }
461
519
  };
462
- ((WikiBotService2) => {
463
- WikiBotService2.Config = import_koishi2.Schema.object({
464
- ggUsername: import_koishi2.Schema.string().description("WIKIGG 用户名").default("1"),
465
- ggPassword: import_koishi2.Schema.string().description("WIKIGG 密码").default("1"),
466
- bwikiusername: import_koishi2.Schema.string().description("bwiki用户名").default("1"),
467
- bwikipassword: import_koishi2.Schema.string().description("bwiki密码").default("1")
468
- });
469
- })(WikiBotService || (WikiBotService = {}));
470
520
 
471
521
  // src/services/consoleLogProvider.ts
472
- var import_koishi3 = require("koishi");
522
+ var import_koishi5 = require("koishi");
473
523
  var import_plugin_console = require("@koishijs/plugin-console");
474
- var logBuffer = [];
475
- var PublicLogProvider = class extends import_plugin_console.DataService {
476
- static {
477
- __name(this, "PublicLogProvider");
478
- }
479
- constructor(ctx) {
524
+ var MAX_RECORDS = 1e3;
525
+ var LOG_SCOPE = "oni-sync";
526
+ var ConsoleLogData = class extends import_plugin_console.DataService {
527
+ constructor(ctx, buffer) {
480
528
  super(ctx, "onilogs", { authority: 0 });
529
+ this.buffer = buffer;
530
+ }
531
+ static {
532
+ __name(this, "ConsoleLogData");
481
533
  }
482
534
  async get() {
483
- return logBuffer;
535
+ return this.buffer;
484
536
  }
485
537
  };
486
538
  var ConsoleLogProvider = class {
@@ -488,23 +540,28 @@ var ConsoleLogProvider = class {
488
540
  __name(this, "ConsoleLogProvider");
489
541
  }
490
542
  static inject = ["console"];
543
+ /**
544
+ * 日志缓冲。刻意做成实例状态而非模块级变量:
545
+ * 模块级可变数组是全进程共享的单例,多实例或热重载时会互相串数据。
546
+ */
547
+ buffer = [];
491
548
  constructor(ctx) {
492
- ctx.plugin(PublicLogProvider);
549
+ ctx.plugin(ConsoleLogData, this.buffer);
493
550
  const target = {
494
551
  colors: 0,
495
552
  record: /* @__PURE__ */ __name((record) => {
496
- if (record.name !== "oni-sync") return;
497
- logBuffer.push(record);
498
- if (logBuffer.length > 1e3) {
499
- logBuffer = logBuffer.slice(-1e3);
553
+ if (record.name !== LOG_SCOPE) return;
554
+ this.buffer.push(record);
555
+ if (this.buffer.length > MAX_RECORDS) {
556
+ this.buffer.splice(0, this.buffer.length - MAX_RECORDS);
500
557
  }
501
- ctx.get("console")?.patch("onilogs", logBuffer);
558
+ ctx.get("console")?.patch("onilogs", this.buffer);
502
559
  }, "record")
503
560
  };
504
- import_koishi3.Logger.targets.push(target);
561
+ import_koishi5.Logger.targets.push(target);
505
562
  ctx.on("dispose", () => {
506
- const index = import_koishi3.Logger.targets.indexOf(target);
507
- if (index > -1) import_koishi3.Logger.targets.splice(index, 1);
563
+ const index = import_koishi5.Logger.targets.indexOf(target);
564
+ if (index > -1) import_koishi5.Logger.targets.splice(index, 1);
508
565
  });
509
566
  }
510
567
  };
@@ -528,7 +585,6 @@ var DatabaseExtension = class {
528
585
  };
529
586
 
530
587
  // src/plugins/routeRedirect.ts
531
- var import_koishi4 = require("koishi");
532
588
  var RouteRedirect = class {
533
589
  static {
534
590
  __name(this, "RouteRedirect");
@@ -575,810 +631,872 @@ var RouteRedirect = class {
575
631
  });
576
632
  }
577
633
  };
578
- ((RouteRedirect2) => {
579
- RouteRedirect2.Config = import_koishi4.Schema.object({
580
- domain: import_koishi4.Schema.string().description("你的短链域名(必填,如:klei.vip)").default("klei.vip"),
581
- main_site: import_koishi4.Schema.string().description("主站域名(必填,如:oxygennotincluded.wiki.gg)").default("oxygennotincluded.wiki.gg/zh"),
582
- bwiki_site: import_koishi4.Schema.string().description("镜像站域名(必填,如:wiki.biligame.com)").default("wiki.biligame.com/oni")
583
- });
584
- })(RouteRedirect || (RouteRedirect = {}));
585
-
586
- // src/plugins/syncCommands.ts
587
- var import_koishi8 = require("koishi");
588
-
589
- // src/sync/pageSync.ts
590
- var import_koishi6 = require("koishi");
591
634
 
592
635
  // src/sync/imgSync.ts
593
- var import_koishi5 = require("koishi");
594
636
  var import_node_fetch = __toESM(require("node-fetch"));
595
637
  var import_form_data = __toESM(require("form-data"));
596
- var CONFIG = {
597
- IGNORED_IMAGES: [],
598
- SYNC_INTERVAL_SUCCESS: 3e3,
599
- SYNC_INTERVAL_FAILED: 5e3,
600
- UPLOAD_COMMENT: "从 WikiGG 自动同步转存",
601
- UPLOAD_TEXT: "== 授权说明 ==\n本文件从 WikiGG 转存,遵循原站点授权协议。"
638
+ var DEFAULT_OPTIONS = {
639
+ ignoredImages: [],
640
+ intervalSuccess: 3e3,
641
+ intervalFailed: 5e3,
642
+ uploadComment: "从 WikiGG 自动同步转存",
643
+ uploadText: "== 授权说明 ==\n本文件从 WikiGG 转存,遵循原站点授权协议。"
602
644
  };
603
- async function getImageInfo(site, fileName) {
604
- try {
605
- const normalizedTitle = normalizeImageTitle(fileName);
606
- const response = await site.query({
607
- action: "query",
608
- titles: normalizedTitle,
609
- prop: "imageinfo",
610
- iiprop: "url|sha1|size|mime"
611
- });
612
- const pages = response.query?.pages || {};
613
- const page = Object.values(pages)[0];
614
- if (!page || page.missing || !page.imageinfo || page.imageinfo.length === 0) {
615
- return null;
616
- }
617
- const imageInfo = page.imageinfo[0];
618
- return {
619
- url: imageInfo.url,
620
- sha1: imageInfo.sha1,
621
- size: imageInfo.size
622
- };
623
- } catch (error) {
624
- const errorMsg = getErrorMessage(error);
625
- logger.error(`[GetImageInfo] 获取 ${fileName} 信息失败:`, errorMsg);
626
- return null;
645
+ var ImageSyncer = class {
646
+ constructor(source, target, deps = {}) {
647
+ this.source = source;
648
+ this.target = target;
649
+ this.options = { ...DEFAULT_OPTIONS, ...deps.options };
627
650
  }
628
- }
629
- __name(getImageInfo, "getImageInfo");
630
- async function deleteOldVersions(bot, fileName) {
631
- try {
632
- const normalizedTitle = normalizeImageTitle(fileName);
633
- const response = await bot.query({
634
- action: "query",
635
- titles: normalizedTitle,
636
- prop: "revisions",
637
- rvprop: "ids|timestamp",
638
- rvlimit: "max",
639
- rvdir: "newer"
640
- // 按时间正序排列,最新的在最后
641
- });
642
- const pages = response.query?.pages || {};
643
- const page = Object.values(pages)[0];
644
- if (!page || !page.revisions || page.revisions.length <= 1) {
645
- return;
646
- }
647
- const revisionIds = page.revisions.slice(0, -1).map((rev) => rev.revid);
648
- const token = await bot.getCsrfToken();
649
- for (const revid of revisionIds) {
650
- try {
651
- await bot.rawRequest({
652
- method: "POST",
653
- url: bot.options.apiUrl,
654
- data: {
655
- action: "delete",
656
- title: fileName,
657
- revid,
658
- token,
659
- reason: "自动清理旧版本,只保留最新同步版本",
660
- format: "json"
661
- }
662
- });
663
- logger.info(`[SyncImg] 🗑️ 删除旧版本 ${revid} 成功`);
664
- } catch (error) {
665
- const errorMsg = getErrorMessage(error);
666
- logger.error(`[SyncImg] ❌ 删除旧版本 ${revid} 失败:`, errorMsg);
651
+ static {
652
+ __name(this, "ImageSyncer");
653
+ }
654
+ options;
655
+ async getImageInfo(site, fileName) {
656
+ try {
657
+ const normalizedTitle = normalizeImageTitle(fileName);
658
+ const response = await site.query({
659
+ action: "query",
660
+ titles: normalizedTitle,
661
+ prop: "imageinfo",
662
+ iiprop: "url|sha1|size|mime"
663
+ });
664
+ const pages = response.query?.pages || {};
665
+ const page = Object.values(pages)[0];
666
+ if (!page || page.missing || !page.imageinfo || page.imageinfo.length === 0) {
667
+ return null;
667
668
  }
669
+ const imageInfo = page.imageinfo[0];
670
+ return {
671
+ url: imageInfo.url,
672
+ sha1: imageInfo.sha1,
673
+ size: imageInfo.size
674
+ };
675
+ } catch (error) {
676
+ const errorMsg = getErrorMessage(error);
677
+ logger.error(`[GetImageInfo] 获取 ${fileName} 信息失败:`, errorMsg);
678
+ return null;
668
679
  }
669
- } catch (error) {
670
- const errorMsg = getErrorMessage(error);
671
- logger.error(`[SyncImg] ❌ 获取版本信息失败:`, errorMsg);
672
- }
673
- }
674
- __name(deleteOldVersions, "deleteOldVersions");
675
- async function syncSingleImage(sourceBot, targetBot, fileName, config) {
676
- if (CONFIG.IGNORED_IMAGES.includes(fileName)) {
677
- logger.info(`[SyncImg] 🚫 图片 ${fileName} 在忽略列表,跳过`);
678
- return { success: true, reason: "ignored" };
679
680
  }
680
- const bareFileName = stripImagePrefix(fileName);
681
- try {
682
- logger.info(`[SyncImg] 🚀 开始处理: ${bareFileName}`);
683
- const sourceImageInfo = await getImageInfo(sourceBot, bareFileName);
684
- if (!sourceImageInfo) {
685
- logger.info(`[SyncImg] ❌ 源站未找到图片: ${fileName}`);
686
- return { success: false, reason: "source_missing" };
687
- }
688
- const targetImageInfo = await getImageInfo(targetBot, bareFileName);
689
- logger.info(`原图片sha1: ${sourceImageInfo.sha1}`);
690
- logger.info(`目标图片sha1: ${targetImageInfo?.sha1}`);
691
- if (targetImageInfo && targetImageInfo.sha1 === sourceImageInfo.sha1) {
692
- logger.info(`[SyncImg] 🟡 图片 ${fileName} 已存在且内容一致,跳过`);
693
- return { success: true, reason: "no_change" };
694
- }
695
- logger.info(`[SyncImg] 📥 下载图片: ${sourceImageInfo.url}`);
696
- const imageResponse = await (0, import_node_fetch.default)(sourceImageInfo.url, {
697
- headers: {
698
- "User-Agent": "OniSyncBot/1.0 (https://klei.vip; Charles@klei.vip)"
681
+ async deleteOldVersions(bot, fileName) {
682
+ try {
683
+ const normalizedTitle = normalizeImageTitle(fileName);
684
+ const response = await bot.query({
685
+ action: "query",
686
+ titles: normalizedTitle,
687
+ prop: "revisions",
688
+ rvprop: "ids|timestamp",
689
+ rvlimit: "max",
690
+ rvdir: "newer"
691
+ // 按时间正序排列,最新的在最后
692
+ });
693
+ const pages = response.query?.pages || {};
694
+ const page = Object.values(pages)[0];
695
+ if (!page || !page.revisions || page.revisions.length <= 1) {
696
+ return;
699
697
  }
700
- });
701
- if (!imageResponse.ok) {
702
- throw new Error(`图片下载失败,HTTP状态码: ${imageResponse.status}`);
703
- }
704
- const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
705
- logger.info(
706
- `[SyncImg] 📤 上传图片: ${bareFileName} (大小: ${(imageBuffer.length / 1024).toFixed(1)} KB)`
707
- );
708
- const token = await targetBot.getCsrfToken();
709
- const form = new import_form_data.default();
710
- form.append("action", "upload");
711
- form.append("filename", bareFileName);
712
- form.append("text", CONFIG.UPLOAD_TEXT);
713
- form.append("comment", CONFIG.UPLOAD_COMMENT);
714
- form.append("token", token);
715
- form.append("ignorewarnings", "0");
716
- form.append("format", "json");
717
- form.append("file", imageBuffer, {
718
- filename: bareFileName,
719
- contentType: imageResponse.headers.get("content-type") || "application/octet-stream"
720
- });
721
- const rawResponse = await targetBot.rawRequest({
722
- method: "POST",
723
- url: targetBot.options.apiUrl,
724
- data: form,
725
- headers: {
726
- ...form.getHeaders()
727
- // "X-authkey": `${getSitesConfig(config).huiji.uakey}`,
698
+ const revisionIds = page.revisions.slice(0, -1).map((rev) => rev.revid);
699
+ const token = await bot.getCsrfToken();
700
+ for (const revid of revisionIds) {
701
+ try {
702
+ await bot.rawRequest({
703
+ method: "POST",
704
+ url: bot.options.apiUrl,
705
+ data: {
706
+ action: "delete",
707
+ title: fileName,
708
+ revid,
709
+ token,
710
+ reason: "自动清理旧版本,只保留最新同步版本",
711
+ format: "json"
712
+ }
713
+ });
714
+ logger.info(`[SyncImg] 🗑️ 删除旧版本 ${revid} 成功`);
715
+ } catch (error) {
716
+ const errorMsg = getErrorMessage(error);
717
+ logger.error(`[SyncImg] ❌ 删除旧版本 ${revid} 失败:`, errorMsg);
718
+ }
728
719
  }
729
- });
730
- const responseData = rawResponse.data;
731
- if (responseData.upload && responseData.upload.result === "Success") {
732
- logger.info(`[SyncImg] ✅ 图片 ${fileName} 同步成功`);
733
- await deleteOldVersions(targetBot, fileName);
734
- return { success: true, reason: "synced" };
735
- } else if (responseData.error) {
736
- throw new Error(`${responseData.error.code}: ${responseData.error.info}`);
737
- } else {
738
- throw new Error(`未知响应: ${JSON.stringify(responseData)}`);
739
- }
740
- } catch (error) {
741
- if (error instanceof Error && error.message.includes("fileexists-no-change")) {
742
- logger.info(`[SyncImg] 🟡 图片 ${fileName} 已存在且内容相同,跳过`);
743
- return { success: true, reason: "no_change" };
720
+ } catch (error) {
721
+ const errorMsg = getErrorMessage(error);
722
+ logger.error(`[SyncImg] ❌ 获取版本信息失败:`, errorMsg);
744
723
  }
745
- const errMsg = error.message || String(error);
746
- logger.error(`[SyncImg] ❌ 图片 ${fileName} 同步失败:`, errMsg);
747
- return { success: false, reason: errMsg };
748
724
  }
749
- }
750
- __name(syncSingleImage, "syncSingleImage");
751
- async function getAllImages(site) {
752
- logger.info(`[SyncAllImg] 📥 开始获取WikiGG所有图片`);
753
- const allImages = [];
754
- const queryGen = site.continuedQueryGen({
755
- action: "query",
756
- list: "allimages",
757
- ailimit: "max",
758
- aidir: "ascending",
759
- ainamespace: 6
760
- });
761
- for await (const res of queryGen) {
762
- const imageItems = res.query?.allimages || [];
763
- const imageTitles = imageItems.map((img) => img.title);
764
- allImages.push(...imageTitles);
765
- logger.info(`[SyncAllImg] 📄 已获取 ${allImages.length} 个图片`);
766
- }
767
- logger.info(`[SyncAllImg] 📊 总计获取到 ${allImages.length} 个图片`);
768
- return allImages;
769
- }
770
- __name(getAllImages, "getAllImages");
771
- async function syncAllImages(sourceBot, targetBot, config) {
772
- try {
773
- const imageList = await getAllImages(sourceBot);
774
- if (imageList.length === 0) {
775
- logger.info(`[SyncAllImg] 📭 源站无图片可同步,结束`);
776
- return;
725
+ async syncOne(fileName) {
726
+ if (this.options.ignoredImages.includes(fileName)) {
727
+ logger.info(`[SyncImg] 🚫 图片 ${fileName} 在忽略列表,跳过`);
728
+ return { success: true, reason: "ignored" };
777
729
  }
778
- let successCount = 0;
779
- let failCount = 0;
780
- let skipCount = 0;
781
- const failedImages = [];
782
- logger.info(
783
- `[SyncAllImg] 🚦 开始批量同步,总计 ${imageList.length} 个图片`
784
- );
785
- for (let i = 0; i < imageList.length; i++) {
786
- const fileName = imageList[i];
787
- const progress = (i + 1) / imageList.length * 100;
730
+ const bareFileName = stripImagePrefix(fileName);
731
+ try {
732
+ logger.info(`[SyncImg] 🚀 开始处理: ${bareFileName}`);
733
+ const sourceImageInfo = await this.getImageInfo(this.source, bareFileName);
734
+ if (!sourceImageInfo) {
735
+ logger.info(`[SyncImg] ❌ 源站未找到图片: ${fileName}`);
736
+ return { success: false, reason: "source_missing" };
737
+ }
738
+ const targetImageInfo = await this.getImageInfo(this.target, bareFileName);
739
+ logger.info(`原图片sha1: ${sourceImageInfo.sha1}`);
740
+ logger.info(`目标图片sha1: ${targetImageInfo?.sha1}`);
741
+ if (targetImageInfo && targetImageInfo.sha1 === sourceImageInfo.sha1) {
742
+ logger.info(`[SyncImg] 🟡 图片 ${fileName} 已存在且内容一致,跳过`);
743
+ return { success: true, reason: "no_change" };
744
+ }
745
+ logger.info(`[SyncImg] 📥 下载图片: ${sourceImageInfo.url}`);
746
+ const imageResponse = await (0, import_node_fetch.default)(sourceImageInfo.url, {
747
+ headers: {
748
+ "User-Agent": "OniSyncBot/1.0 (https://klei.vip; Charles@klei.vip)"
749
+ }
750
+ });
751
+ if (!imageResponse.ok) {
752
+ throw new Error(`图片下载失败,HTTP状态码: ${imageResponse.status}`);
753
+ }
754
+ const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
788
755
  logger.info(
789
- `
790
- [SyncAllImg] 📈 进度 ${i + 1}/${imageList.length} (${progress.toFixed(1)}%)`
791
- );
792
- const result = await syncSingleImage(
793
- sourceBot,
794
- targetBot,
795
- fileName,
796
- config
756
+ `[SyncImg] 📤 上传图片: ${bareFileName} (大小: ${(imageBuffer.length / 1024).toFixed(1)} KB)`
797
757
  );
798
- if (!result.success) {
799
- failCount++;
800
- failedImages.push(fileName);
801
- await (0, import_koishi5.sleep)(CONFIG.SYNC_INTERVAL_FAILED);
802
- } else {
803
- successCount++;
804
- if (result.reason === "ignored" || result.reason === "no_change") {
805
- skipCount++;
758
+ const token = await this.target.getCsrfToken();
759
+ const form = new import_form_data.default();
760
+ form.append("action", "upload");
761
+ form.append("filename", bareFileName);
762
+ form.append("text", this.options.uploadText);
763
+ form.append("comment", this.options.uploadComment);
764
+ form.append("token", token);
765
+ form.append("ignorewarnings", "0");
766
+ form.append("format", "json");
767
+ form.append("file", imageBuffer, {
768
+ filename: bareFileName,
769
+ contentType: imageResponse.headers.get("content-type") || "application/octet-stream"
770
+ });
771
+ const rawResponse = await this.target.rawRequest({
772
+ method: "POST",
773
+ url: this.target.options.apiUrl,
774
+ data: form,
775
+ headers: {
776
+ ...form.getHeaders()
806
777
  }
807
- await (0, import_koishi5.sleep)(CONFIG.SYNC_INTERVAL_SUCCESS);
778
+ });
779
+ const responseData = rawResponse.data;
780
+ if (responseData.upload && responseData.upload.result === "Success") {
781
+ logger.info(`[SyncImg] ✅ 图片 ${fileName} 同步成功`);
782
+ await this.deleteOldVersions(this.target, fileName);
783
+ return { success: true, reason: "synced" };
784
+ } else if (responseData.error) {
785
+ throw new Error(`${responseData.error.code}: ${responseData.error.info}`);
786
+ } else {
787
+ throw new Error(`未知响应: ${JSON.stringify(responseData)}`);
788
+ }
789
+ } catch (error) {
790
+ if (error instanceof Error && error.message.includes("fileexists-no-change")) {
791
+ logger.info(`[SyncImg] 🟡 图片 ${fileName} 已存在且内容相同,跳过`);
792
+ return { success: true, reason: "no_change" };
808
793
  }
794
+ const errMsg = getErrorMessage(error);
795
+ logger.error(`[SyncImg] ❌ 图片 ${fileName} 同步失败:`, errMsg);
796
+ return { success: false, reason: errMsg };
797
+ }
798
+ }
799
+ async listAll() {
800
+ logger.info(`[SyncAllImg] 📥 开始获取WikiGG所有图片`);
801
+ const allImages = [];
802
+ const queryGen = this.source.continuedQueryGen({
803
+ action: "query",
804
+ list: "allimages",
805
+ ailimit: "max",
806
+ aidir: "ascending",
807
+ ainamespace: 6
808
+ });
809
+ for await (const res of queryGen) {
810
+ const imageItems = res.query?.allimages || [];
811
+ allImages.push(...imageItems.map((img) => img.title));
812
+ logger.info(`[SyncAllImg] 📄 已获取 ${allImages.length} 个图片`);
809
813
  }
810
- if (failedImages.length > 0) {
814
+ logger.info(`[SyncAllImg] 📊 总计获取到 ${allImages.length} 个图片`);
815
+ return allImages;
816
+ }
817
+ /** 批量同步所有图片:先串行同步一轮,再重试失败的 */
818
+ async syncAll() {
819
+ try {
820
+ const imageList = await this.listAll();
821
+ if (imageList.length === 0) {
822
+ logger.info(`[SyncAllImg] 📭 源站无图片可同步,结束`);
823
+ return;
824
+ }
825
+ let successCount = 0;
826
+ let failCount = 0;
827
+ let skipCount = 0;
828
+ const failedImages = [];
811
829
  logger.info(
812
- `
813
- [SyncAllImg] 🔄 开始重试 ${failedImages.length} 个失败图片`
830
+ `[SyncAllImg] 🚦 开始批量同步,总计 ${imageList.length} 个图片`
814
831
  );
815
- const stillFailed = [];
816
- for (const fileName of failedImages) {
817
- logger.info(`
818
- [SyncAllImg] 🔁 重试: ${fileName}`);
819
- const result = await syncSingleImage(
820
- sourceBot,
821
- targetBot,
822
- fileName,
823
- config
832
+ for (let i = 0; i < imageList.length; i++) {
833
+ const fileName = imageList[i];
834
+ const progress = (i + 1) / imageList.length * 100;
835
+ logger.info(
836
+ `
837
+ [SyncAllImg] 📈 进度 ${i + 1}/${imageList.length} (${progress.toFixed(1)}%)`
824
838
  );
825
- if (result.success) {
826
- successCount++;
827
- failCount--;
828
- logger.info(`[SyncAllImg] ✅ 重试成功: ${fileName}`);
839
+ const result = await this.syncOne(fileName);
840
+ if (!result.success) {
841
+ failCount++;
842
+ failedImages.push(fileName);
843
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
829
844
  } else {
830
- stillFailed.push(fileName);
831
- logger.info(`[SyncAllImg] ❌ 重试失败: ${fileName}`);
845
+ successCount++;
846
+ if (result.reason === "ignored" || result.reason === "no_change") {
847
+ skipCount++;
848
+ }
849
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
832
850
  }
833
- await (0, import_koishi5.sleep)(CONFIG.SYNC_INTERVAL_SUCCESS);
834
851
  }
835
- if (stillFailed.length > 0) {
836
- logger.info(`
837
- [SyncAllImg] ❌ 最终失败列表(需手动处理):`);
838
- stillFailed.forEach(
839
- (title, idx) => logger.info(` ${idx + 1}. ${title}`)
852
+ if (failedImages.length > 0) {
853
+ logger.info(
854
+ `
855
+ [SyncAllImg] 🔄 开始重试 ${failedImages.length} 个失败图片`
840
856
  );
841
- } else {
842
- logger.info(`
857
+ const stillFailed = [];
858
+ for (const fileName of failedImages) {
859
+ logger.info(`
860
+ [SyncAllImg] 🔁 重试: ${fileName}`);
861
+ const result = await this.syncOne(fileName);
862
+ if (result.success) {
863
+ successCount++;
864
+ failCount--;
865
+ logger.info(`[SyncAllImg] ✅ 重试成功: ${fileName}`);
866
+ } else {
867
+ stillFailed.push(fileName);
868
+ logger.info(`[SyncAllImg] ❌ 重试失败: ${fileName}`);
869
+ }
870
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
871
+ }
872
+ if (stillFailed.length > 0) {
873
+ logger.info(`
874
+ [SyncAllImg] ❌ 最终失败列表(需手动处理):`);
875
+ stillFailed.forEach(
876
+ (title, idx) => logger.info(` ${idx + 1}. ${title}`)
877
+ );
878
+ } else {
879
+ logger.info(`
843
880
  [SyncAllImg] 🎉 所有失败图片重试成功!`);
881
+ }
844
882
  }
845
- }
846
- logger.info(`
883
+ logger.info(`
847
884
  [SyncAllImg] 📊 同步完成!`);
848
- logger.info(`├─ 总计:${imageList.length} 个图片`);
849
- logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
850
- logger.info(`└─ 失败:${failCount} 个`);
851
- } catch (globalError) {
852
- logger.error(`[SyncAllImg] 💥 同步流程异常终止:`, globalError);
853
- throw globalError;
885
+ logger.info(`├─ 总计:${imageList.length} 个图片`);
886
+ logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
887
+ logger.info(`└─ 失败:${failCount} 个`);
888
+ } catch (globalError) {
889
+ logger.error(`[SyncAllImg] 💥 同步流程异常终止:`, globalError);
890
+ throw globalError;
891
+ }
854
892
  }
855
- }
856
- __name(syncAllImages, "syncAllImages");
893
+ };
857
894
 
858
895
  // src/sync/pageSync.ts
859
- var CONFIG2 = {
860
- IGNORED_PAGES: /* @__PURE__ */ new Set(["教程", "MediaWiki:Common.css", "首页", "Main Page"]),
861
- SYNC_INTERVAL_SUCCESS: 500,
862
- SYNC_INTERVAL_FAILED: 1e3,
863
- NAMESPACE: 0,
864
- BATCH_LIMIT: "max",
865
- FILE_NAMESPACE_PREFIX: "File:",
866
- DEFAULT_USER: "同步坤器人",
867
- INCREMENTAL_USER: "定时同步",
868
- DB_RETRY_MAX: 3,
869
- DB_RETRY_DELAY: 500
896
+ var DEFAULT_OPTIONS2 = {
897
+ ignoredPages: /* @__PURE__ */ new Set(["教程", "MediaWiki:Common.css", "首页", "Main Page"]),
898
+ intervalSuccess: 500,
899
+ intervalFailed: 1e3,
900
+ namespace: 0,
901
+ batchLimit: "max",
902
+ fileNamespacePrefix: "File:",
903
+ defaultUser: "同步坤器人",
904
+ dbRetryMax: 3,
905
+ dbRetryDelay: 500
870
906
  };
871
- async function withRetry(fn, maxRetries = CONFIG2.DB_RETRY_MAX, delay = CONFIG2.DB_RETRY_DELAY) {
872
- let lastError;
873
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
874
- try {
875
- return await fn();
876
- } catch (err) {
877
- lastError = err instanceof Error ? err : new Error(String(err));
878
- if (attempt < maxRetries) {
879
- logger.debug(
880
- `数据库操作失败,正在重试 (${attempt}/${maxRetries}): ${lastError.message}`
881
- );
882
- await (0, import_koishi6.sleep)(delay);
883
- }
884
- }
907
+ var PageSyncer = class {
908
+ constructor(source, target, deps = {}) {
909
+ this.source = source;
910
+ this.target = target;
911
+ this.options = { ...DEFAULT_OPTIONS2, ...deps.options };
912
+ this.database = deps.database;
913
+ this.notify = deps.notify;
914
+ this.images = new ImageSyncer(source, target);
885
915
  }
886
- throw lastError || new Error("数据库操作失败");
887
- }
888
- __name(withRetry, "withRetry");
889
- async function ensurePageInDatabase(database, pageId, title) {
890
- if (!database) return;
891
- try {
892
- await withRetry(async () => {
893
- const existing = await database.get("wikipages", { title });
894
- if (existing.length === 0) {
895
- const { pinyin_full, pinyin_first } = generatePinyinInfo(title);
896
- await database.create("wikipages", {
897
- id: pageId,
898
- title,
899
- pinyin_full,
900
- pinyin_first
901
- });
902
- logger.info(`[数据库初始化] ✅ 页面 ${title} 已添加到数据库`);
903
- }
916
+ static {
917
+ __name(this, "PageSyncer");
918
+ }
919
+ options;
920
+ database;
921
+ notify;
922
+ images;
923
+ // ---------------------------------------------------------------- 数据库
924
+ /** 带重试的数据库操作 */
925
+ retryDb(fn) {
926
+ return withRetry(fn, {
927
+ attempts: this.options.dbRetryMax,
928
+ delayMs: this.options.dbRetryDelay,
929
+ onRetry: /* @__PURE__ */ __name((error, attempt, attempts) => logger.debug(
930
+ `数据库操作失败,正在重试 (${attempt}/${attempts}): ${getErrorMessage(error)}`
931
+ ), "onRetry")
904
932
  });
905
- } catch (err) {
906
- const errMsg = err instanceof Error ? err.message : String(err);
907
- logger.warn(`[数据库初始化] ❌ 初始化页面 ${title} 失败: ${errMsg}`);
908
933
  }
909
- }
910
- __name(ensurePageInDatabase, "ensurePageInDatabase");
911
- async function updateContributorToDatabase(database, title, user, timestamp) {
912
- if (!database) return;
913
- try {
914
- await withRetry(async () => {
915
- await database.set(
916
- "wikipages",
917
- { title },
918
- {
919
- contributor: user,
920
- change_time: formatWikiTime(timestamp)
934
+ /** 若数据库中不存在该页面,先写入基本数据(含拼音索引) */
935
+ async ensurePageInDatabase(pageId, title) {
936
+ const database = this.database;
937
+ if (!database) return;
938
+ try {
939
+ await this.retryDb(async () => {
940
+ const existing = await database.get("wikipages", { title });
941
+ if (existing.length === 0) {
942
+ const { pinyin_full, pinyin_first } = generatePinyinInfo(title);
943
+ await database.create("wikipages", {
944
+ id: pageId,
945
+ title,
946
+ pinyin_full,
947
+ pinyin_first
948
+ });
949
+ logger.info(`[数据库初始化] ✅ 页面 ${title} 已添加到数据库`);
921
950
  }
951
+ });
952
+ } catch (err) {
953
+ logger.warn(
954
+ `[数据库初始化] ❌ 初始化页面 ${title} 失败: ${getErrorMessage(err)}`
922
955
  );
923
- logger.debug(`[数据库更新] ✅ 页面 ${title} 的贡献者信息已更新: ${user}`);
924
- });
925
- } catch (err) {
926
- const errMsg = err instanceof Error ? err.message : String(err);
927
- logger.warn(
928
- `[数据库更新] ❌ 更新页面 ${title} 的贡献者信息失败: ${errMsg}`
929
- );
956
+ }
930
957
  }
931
- }
932
- __name(updateContributorToDatabase, "updateContributorToDatabase");
933
- async function syncSinglePage(oldSite, newSite, pageTitle, user) {
934
- if (CONFIG2.IGNORED_PAGES.has(pageTitle)) {
935
- logger.info(`[syncSinglePage] 🚫 页面 ${pageTitle} 在忽略列表中,跳过`);
936
- return { success: true, reason: "ignored" };
937
- }
938
- try {
939
- logger.info(`[syncSinglePage] 🚀 开始同步页面: ${pageTitle}`);
940
- const [oldContent, newContent] = await Promise.all([
941
- getAndProcessPageContent(oldSite, pageTitle),
942
- getAndProcessPageContent(newSite, pageTitle)
943
- ]);
944
- if (oldContent === newContent) {
945
- logger.info(`[syncSinglePage] 🟡 页面 ${pageTitle} 内容未改变,跳过`);
946
- return { success: true, reason: "no_change" };
958
+ /** 更新页面贡献者信息到数据库 */
959
+ async updateContributorToDatabase(title, user, timestamp) {
960
+ const database = this.database;
961
+ if (!database) return;
962
+ try {
963
+ await this.retryDb(async () => {
964
+ await database.set(
965
+ "wikipages",
966
+ { title },
967
+ {
968
+ contributor: user,
969
+ change_time: formatWikiTime(timestamp)
970
+ }
971
+ );
972
+ logger.debug(
973
+ `[数据库更新] ✅ 页面 ${title} 的贡献者信息已更新: ${user}`
974
+ );
975
+ });
976
+ } catch (err) {
977
+ logger.warn(
978
+ `[数据库更新] ❌ 更新页面 ${title} 的贡献者信息失败: ${getErrorMessage(err)}`
979
+ );
947
980
  }
948
- await newSite.save(pageTitle, oldContent, `由:${user} 触发更改,此时同步`);
949
- logger.info(`[syncSinglePage] ✅ 页面 ${pageTitle} 同步成功`);
950
- return { success: true, reason: "synced" };
951
- } catch (error) {
952
- const errMsg = error instanceof Error ? error.message : String(error);
953
- logger.error(`[syncSinglePage] ❌ 页面 ${pageTitle} 同步失败:`, errMsg);
954
- return { success: false, reason: errMsg };
955
981
  }
956
- }
957
- __name(syncSinglePage, "syncSinglePage");
958
- async function getAllPages(site) {
959
- logger.info(
960
- `[SyncAllPages] 📥 开始获取原站点所有页面(命名空间${CONFIG2.NAMESPACE})`
961
- );
962
- const allPages = [];
963
- const queryGen = site.continuedQueryGen({
964
- action: "query",
965
- list: "allpages",
966
- apnamespace: CONFIG2.NAMESPACE,
967
- aplimit: CONFIG2.BATCH_LIMIT,
968
- apdir: "ascending"
969
- });
970
- for await (const res of queryGen) {
971
- const pageTitles = res.query?.allpages?.map((page) => page.title) || [];
972
- allPages.push(...pageTitles);
973
- logger.info(`[SyncAllPages] 📄 已获取 ${allPages.length} 个页面`);
982
+ // ------------------------------------------------------------ 单页 / 全量
983
+ async syncOne(pageTitle, user) {
984
+ if (this.options.ignoredPages.has(pageTitle)) {
985
+ logger.info(`[syncSinglePage] 🚫 页面 ${pageTitle} 在忽略列表中,跳过`);
986
+ return { success: true, reason: "ignored" };
987
+ }
988
+ try {
989
+ logger.info(`[syncSinglePage] 🚀 开始同步页面: ${pageTitle}`);
990
+ const [oldContent, newContent] = await Promise.all([
991
+ getAndProcessPageContent(this.source, pageTitle),
992
+ getAndProcessPageContent(this.target, pageTitle)
993
+ ]);
994
+ if (oldContent === newContent) {
995
+ logger.info(`[syncSinglePage] 🟡 页面 ${pageTitle} 内容未改变,跳过`);
996
+ return { success: true, reason: "no_change" };
997
+ }
998
+ await this.target.save(
999
+ pageTitle,
1000
+ oldContent,
1001
+ `由:${user} 触发更改,此时同步`
1002
+ );
1003
+ logger.info(`[syncSinglePage] ✅ 页面 ${pageTitle} 同步成功`);
1004
+ return { success: true, reason: "synced" };
1005
+ } catch (error) {
1006
+ const errMsg = getErrorMessage(error);
1007
+ logger.error(`[syncSinglePage] ❌ 页面 ${pageTitle} 同步失败:`, errMsg);
1008
+ return { success: false, reason: errMsg };
1009
+ }
974
1010
  }
975
- logger.info(`[SyncAllPages] 📊 原站点总计获取到 ${allPages.length} 个页面`);
976
- return allPages;
977
- }
978
- __name(getAllPages, "getAllPages");
979
- async function processPageWithStats(oldSite, newSite, pageTitle, user, stats, failedPages) {
980
- const syncResult = await syncSinglePage(oldSite, newSite, pageTitle, user);
981
- if (!syncResult.success) {
982
- stats.failCount++;
983
- failedPages.push(pageTitle);
984
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_FAILED);
985
- } else {
986
- stats.successCount++;
987
- if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
988
- stats.skipCount++;
1011
+ async listAll() {
1012
+ logger.info(
1013
+ `[SyncAllPages] 📥 开始获取原站点所有页面(命名空间${this.options.namespace})`
1014
+ );
1015
+ const allPages = [];
1016
+ const queryGen = this.source.continuedQueryGen({
1017
+ action: "query",
1018
+ list: "allpages",
1019
+ apnamespace: this.options.namespace,
1020
+ aplimit: this.options.batchLimit,
1021
+ apdir: "ascending"
1022
+ });
1023
+ for await (const res of queryGen) {
1024
+ const pageTitles = res.query?.allpages?.map((page) => page.title) || [];
1025
+ allPages.push(...pageTitles);
1026
+ logger.info(`[SyncAllPages] 📄 已获取 ${allPages.length} 个页面`);
1027
+ }
1028
+ logger.info(`[SyncAllPages] 📊 原站点总计获取到 ${allPages.length} 个页面`);
1029
+ return allPages;
1030
+ }
1031
+ async processPageWithStats(pageTitle, user, stats, failedPages) {
1032
+ const syncResult = await this.syncOne(pageTitle, user);
1033
+ if (!syncResult.success) {
1034
+ stats.failCount++;
1035
+ failedPages.push(pageTitle);
1036
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
1037
+ } else {
1038
+ stats.successCount++;
1039
+ if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
1040
+ stats.skipCount++;
1041
+ }
1042
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
989
1043
  }
990
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_SUCCESS);
991
1044
  }
992
- }
993
- __name(processPageWithStats, "processPageWithStats");
994
- function printProgress(current, total, pageTitle) {
995
- const progress = (current / total * 100).toFixed(1);
996
- const remaining = total - current;
997
- logger.info(
998
- `
1045
+ printProgress(current, total, pageTitle) {
1046
+ const progress = (current / total * 100).toFixed(1);
1047
+ const remaining = total - current;
1048
+ logger.info(
1049
+ `
999
1050
  [SyncAllPages] 📈 进度 [${current}/${total}] (${progress}%) - 处理 ${pageTitle} | 剩余 ${remaining} 个`
1000
- );
1001
- }
1002
- __name(printProgress, "printProgress");
1003
- function printFinalReport(total, successCount, failCount, skipCount, stillFailed) {
1004
- logger.info(`
1005
- [SyncAllPages] 📋 ===== 最终同步报告 =====`);
1006
- if (stillFailed.length > 0) {
1007
- logger.info(`❌ 以下页面经过重试仍然失败,请手动检查:`);
1008
- stillFailed.forEach((title, idx) => {
1009
- logger.info(` ${idx + 1}. ${title}`);
1010
- });
1011
- } else {
1012
- logger.info(`🎉 所有页面同步成功(含重试)!`);
1051
+ );
1013
1052
  }
1014
- logger.info(`
1015
- [SyncAllPages] 🎯 同步流程结束!`);
1016
- logger.info(`├─ 总计:${total} 个页面`);
1017
- logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
1018
- logger.info(`└─ 失败:${failCount} 个`);
1019
- }
1020
- __name(printFinalReport, "printFinalReport");
1021
- async function syncPages(oldSite, newSite) {
1022
- try {
1023
- const oldPageList = await getAllPages(oldSite);
1024
- const total = oldPageList.length;
1025
- if (total === 0) {
1026
- logger.info(`[SyncAllPages] 📭 原站点无页面可同步,结束`);
1027
- return;
1028
- }
1029
- const stats = { successCount: 0, failCount: 0, skipCount: 0 };
1030
- const failedPages = [];
1031
- logger.info(`[SyncAllPages] 🚦 开始批量同步,总计 ${total} 个页面`);
1032
- for (let index = 0; index < total; index++) {
1033
- const pageTitle = oldPageList[index];
1034
- printProgress(index + 1, total, pageTitle);
1035
- await processPageWithStats(
1036
- oldSite,
1037
- newSite,
1038
- pageTitle,
1039
- CONFIG2.DEFAULT_USER,
1040
- stats,
1041
- failedPages
1042
- );
1053
+ printFinalReport(total, successCount, failCount, skipCount, stillFailed) {
1054
+ logger.info(`
1055
+ [SyncAllPages] 📋 ===== 最终同步报告 =====`);
1056
+ if (stillFailed.length > 0) {
1057
+ logger.info(`❌ 以下页面经过重试仍然失败,请手动检查:`);
1058
+ stillFailed.forEach((title, idx) => {
1059
+ logger.info(` ${idx + 1}. ${title}`);
1060
+ });
1061
+ } else {
1062
+ logger.info(`🎉 所有页面同步成功(含重试)!`);
1043
1063
  }
1044
- let stillFailed = [];
1045
- if (failedPages.length > 0) {
1046
- logger.info(
1047
- `
1048
- [SyncAllPages] 🔄 ===== 开始重试 ${failedPages.length} 个失败页面 =====`
1049
- );
1050
- for (const pageTitle of failedPages) {
1051
- logger.info(`
1052
- [SyncAllPages] 🔁 重试中: ${pageTitle}`);
1053
- const syncResult = await syncSinglePage(
1054
- oldSite,
1055
- newSite,
1064
+ logger.info(`
1065
+ [SyncAllPages] 🎯 同步流程结束!`);
1066
+ logger.info(`├─ 总计:${total} 个页面`);
1067
+ logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
1068
+ logger.info(`└─ 失败:${failCount} 个`);
1069
+ }
1070
+ /** 全量同步所有页面:先串行同步一轮,再重试失败的 */
1071
+ async syncAll() {
1072
+ try {
1073
+ const oldPageList = await this.listAll();
1074
+ const total = oldPageList.length;
1075
+ if (total === 0) {
1076
+ logger.info(`[SyncAllPages] 📭 原站点无页面可同步,结束`);
1077
+ return;
1078
+ }
1079
+ const stats = {
1080
+ successCount: 0,
1081
+ failCount: 0,
1082
+ skipCount: 0
1083
+ };
1084
+ const failedPages = [];
1085
+ logger.info(`[SyncAllPages] 🚦 开始批量同步,总计 ${total} 个页面`);
1086
+ for (let index = 0; index < total; index++) {
1087
+ const pageTitle = oldPageList[index];
1088
+ this.printProgress(index + 1, total, pageTitle);
1089
+ await this.processPageWithStats(
1056
1090
  pageTitle,
1057
- CONFIG2.DEFAULT_USER
1091
+ this.options.defaultUser,
1092
+ stats,
1093
+ failedPages
1094
+ );
1095
+ }
1096
+ const stillFailed = [];
1097
+ if (failedPages.length > 0) {
1098
+ logger.info(
1099
+ `
1100
+ [SyncAllPages] 🔄 ===== 开始重试 ${failedPages.length} 个失败页面 =====`
1058
1101
  );
1059
- if (syncResult.success) {
1060
- stats.successCount++;
1061
- stats.failCount--;
1062
- if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
1063
- stats.skipCount++;
1102
+ for (const pageTitle of failedPages) {
1103
+ logger.info(`
1104
+ [SyncAllPages] 🔁 重试中: ${pageTitle}`);
1105
+ const syncResult = await this.syncOne(
1106
+ pageTitle,
1107
+ this.options.defaultUser
1108
+ );
1109
+ if (syncResult.success) {
1110
+ stats.successCount++;
1111
+ stats.failCount--;
1112
+ if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
1113
+ stats.skipCount++;
1114
+ }
1115
+ logger.info(`[SyncAllPages] ✅ 页面 ${pageTitle} 重试成功`);
1116
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
1117
+ } else {
1118
+ stillFailed.push(pageTitle);
1119
+ logger.info(`[SyncAllPages] ❌ 页面 ${pageTitle} 再次失败`);
1120
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
1064
1121
  }
1065
- logger.info(`[SyncAllPages] ✅ 页面 ${pageTitle} 重试成功`);
1066
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_SUCCESS);
1067
- } else {
1068
- stillFailed.push(pageTitle);
1069
- logger.info(`[SyncAllPages] ❌ 页面 ${pageTitle} 再次失败`);
1070
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_FAILED);
1071
1122
  }
1072
1123
  }
1124
+ this.printFinalReport(
1125
+ total,
1126
+ stats.successCount,
1127
+ stats.failCount,
1128
+ stats.skipCount,
1129
+ stillFailed
1130
+ );
1131
+ } catch (globalError) {
1132
+ logger.error(`[SyncAllPages] 💥 批量同步流程异常终止:`, globalError);
1133
+ throw globalError;
1073
1134
  }
1074
- printFinalReport(
1075
- total,
1076
- stats.successCount,
1077
- stats.failCount,
1078
- stats.skipCount,
1079
- stillFailed
1080
- );
1081
- } catch (globalError) {
1082
- logger.error(`[SyncAllPages] 💥 批量同步流程异常终止:`, globalError);
1083
- throw globalError;
1084
1135
  }
1085
- }
1086
- __name(syncPages, "syncPages");
1087
- async function incrementalUpdate(oldSite, newSite, config, onSynced, database) {
1088
- const startTime = Date.now();
1089
- const processedTitles = /* @__PURE__ */ new Set();
1090
- const syncedItems = [];
1091
- let totalProcessed = 0;
1092
- let totalSkipped = 0;
1093
- let totalSynced = 0;
1094
- try {
1095
- const now = /* @__PURE__ */ new Date();
1096
- const threeHoursAgo = new Date(now.getTime() - 3 * 60 * 60 * 1e3);
1097
- logger.info(
1098
- `[增量更新流程] ⏰ 开始处理 ${threeHoursAgo.toISOString()} 到 ${now.toISOString()} 的更新...`
1099
- );
1100
- const queryGen = oldSite.continuedQueryGen({
1101
- action: "query",
1102
- list: "recentchanges",
1103
- rcstart: now.toISOString(),
1104
- rcend: threeHoursAgo.toISOString(),
1105
- rcdir: "older",
1106
- rcprop: "user|comment|title|timestamp|ids"
1107
- });
1108
- for await (const res of queryGen) {
1109
- const pages = res.query?.recentchanges || [];
1110
- for (const page of pages) {
1111
- const {
1112
- title,
1113
- user: rcUser,
1114
- timestamp: rcTimestamp,
1115
- comment: rcComment,
1116
- pageid
1117
- } = page;
1118
- if (processedTitles.has(title)) {
1119
- logger.debug(`[增量更新流程] ⏭️ 已处理过 ${title}, 跳过`);
1120
- totalSkipped++;
1121
- continue;
1122
- }
1123
- if (CONFIG2.IGNORED_PAGES.has(title)) {
1124
- logger.info(
1125
- `[增量更新流程] 🚫 ${title} 在无需处理的页面列表中, 跳过`
1126
- );
1127
- processedTitles.add(title);
1128
- totalSkipped++;
1129
- continue;
1130
- }
1131
- processedTitles.add(title);
1132
- totalProcessed++;
1133
- try {
1134
- const user = rcUser || "未知";
1135
- const timestamp = rcTimestamp || "";
1136
- const comment = rcComment || "";
1137
- if (title.startsWith(CONFIG2.FILE_NAMESPACE_PREFIX)) {
1138
- await handleImageSync(
1139
- oldSite,
1140
- newSite,
1141
- title,
1142
- user,
1143
- timestamp,
1144
- comment,
1145
- config,
1146
- syncedItems
1147
- );
1148
- } else {
1149
- await handlePageSync(
1150
- oldSite,
1151
- newSite,
1152
- title,
1153
- pageid || 0,
1154
- user,
1155
- timestamp,
1156
- comment,
1157
- database,
1158
- syncedItems
1136
+ // ---------------------------------------------------------------- 增量更新
1137
+ /**
1138
+ * 增量更新:取最近 3 小时的 recentchanges 并逐条同步。
1139
+ *
1140
+ * 结束时通过构造时注入的 `notify` 一次性回调成功条目
1141
+ * (仅 reason==="synced" 的页面与图片)。
1142
+ */
1143
+ async incrementalUpdate() {
1144
+ const startTime = Date.now();
1145
+ const processedTitles = /* @__PURE__ */ new Set();
1146
+ const syncedItems = [];
1147
+ let totalProcessed = 0;
1148
+ let totalSkipped = 0;
1149
+ let totalSynced = 0;
1150
+ try {
1151
+ const now = /* @__PURE__ */ new Date();
1152
+ const threeHoursAgo = new Date(now.getTime() - 3 * 60 * 60 * 1e3);
1153
+ logger.info(
1154
+ `[增量更新流程] ⏰ 开始处理 ${threeHoursAgo.toISOString()} 到 ${now.toISOString()} 的更新...`
1155
+ );
1156
+ const queryGen = this.source.continuedQueryGen({
1157
+ action: "query",
1158
+ list: "recentchanges",
1159
+ rcstart: now.toISOString(),
1160
+ rcend: threeHoursAgo.toISOString(),
1161
+ rcdir: "older",
1162
+ rcprop: "user|comment|title|timestamp|ids"
1163
+ });
1164
+ for await (const res of queryGen) {
1165
+ const pages = res.query?.recentchanges || [];
1166
+ for (const page of pages) {
1167
+ const {
1168
+ title,
1169
+ user: rcUser,
1170
+ timestamp: rcTimestamp,
1171
+ comment: rcComment,
1172
+ pageid
1173
+ } = page;
1174
+ if (processedTitles.has(title)) {
1175
+ logger.debug(`[增量更新流程] ⏭️ 已处理过 ${title}, 跳过`);
1176
+ totalSkipped++;
1177
+ continue;
1178
+ }
1179
+ if (this.options.ignoredPages.has(title)) {
1180
+ logger.info(
1181
+ `[增量更新流程] 🚫 ${title} 在无需处理的页面列表中, 跳过`
1159
1182
  );
1160
- totalSynced++;
1183
+ processedTitles.add(title);
1184
+ totalSkipped++;
1185
+ continue;
1186
+ }
1187
+ processedTitles.add(title);
1188
+ totalProcessed++;
1189
+ try {
1190
+ const user = rcUser || "未知";
1191
+ const timestamp = rcTimestamp || "";
1192
+ const comment = rcComment || "";
1193
+ if (title.startsWith(this.options.fileNamespacePrefix)) {
1194
+ await this.handleImageSync(
1195
+ title,
1196
+ user,
1197
+ timestamp,
1198
+ comment,
1199
+ syncedItems
1200
+ );
1201
+ } else {
1202
+ await this.handlePageSync(
1203
+ title,
1204
+ pageid || 0,
1205
+ user,
1206
+ timestamp,
1207
+ comment,
1208
+ syncedItems
1209
+ );
1210
+ totalSynced++;
1211
+ }
1212
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
1213
+ } catch (error) {
1214
+ const errMsg = getErrorMessage(error);
1215
+ logger.error(`[增量更新流程] ❌ 处理 ${title} 时出错:`, errMsg);
1216
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
1161
1217
  }
1162
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_SUCCESS);
1163
- } catch (error) {
1164
- const errMsg = error instanceof Error ? error.message : String(error);
1165
- logger.error(`[增量更新流程] ❌ 处理 ${title} 时出错:`, errMsg);
1166
- await (0, import_koishi6.sleep)(CONFIG2.SYNC_INTERVAL_FAILED);
1167
1218
  }
1168
1219
  }
1169
- }
1170
- } catch (globalError) {
1171
- logger.error(`[增量更新流程] 💥 增量更新流程异常终止:`, globalError);
1172
- throw globalError;
1173
- } finally {
1174
- const duration = (Date.now() - startTime) / 1e3;
1175
- logger.info(
1176
- `[增量更新流程] ✅ 增量更新完成!处理: ${totalProcessed}, 跳过: ${totalSkipped}, 同步: ${totalSynced}, 通知: ${syncedItems.length}, 耗时: ${duration.toFixed(2)}s`
1177
- );
1178
- if (syncedItems.length > 0) {
1179
- onSynced?.(syncedItems);
1220
+ } catch (globalError) {
1221
+ logger.error(`[增量更新流程] 💥 增量更新流程异常终止:`, globalError);
1222
+ throw globalError;
1223
+ } finally {
1224
+ const duration = (Date.now() - startTime) / 1e3;
1225
+ logger.info(
1226
+ `[增量更新流程] ✅ 增量更新完成!处理: ${totalProcessed}, 跳过: ${totalSkipped}, 同步: ${totalSynced}, 通知: ${syncedItems.length}, 耗时: ${duration.toFixed(2)}s`
1227
+ );
1228
+ if (syncedItems.length > 0) {
1229
+ this.notify?.(syncedItems);
1230
+ }
1180
1231
  }
1181
1232
  }
1182
- }
1183
- __name(incrementalUpdate, "incrementalUpdate");
1184
- async function handleImageSync(oldSite, newSite, title, user, timestamp, comment, config, syncedItems) {
1185
- const fileName = title.replace(CONFIG2.FILE_NAMESPACE_PREFIX, "");
1186
- logger.info(`[增量更新流程] 🖼️ 检查到图片: ${title},正在尝试转存`);
1187
- const result = await syncSingleImage(oldSite, newSite, fileName, config);
1188
- if (result.success && result.reason === "synced") {
1189
- syncedItems.push({
1190
- title,
1191
- type: "image",
1192
- user,
1193
- timestamp,
1194
- comment
1195
- });
1196
- }
1197
- }
1198
- __name(handleImageSync, "handleImageSync");
1199
- async function handlePageSync(oldSite, newSite, title, pageId, user, timestamp, comment, database, syncedItems) {
1200
- await ensurePageInDatabase(database, pageId, title);
1201
- const result = await syncSinglePage(oldSite, newSite, title, user);
1202
- if (result.success) {
1203
- if (result.reason === "synced") {
1233
+ /** 增量更新中遇到图片页面时的处理 */
1234
+ async handleImageSync(title, user, timestamp, comment, syncedItems) {
1235
+ const fileName = title.replace(this.options.fileNamespacePrefix, "");
1236
+ logger.info(`[增量更新流程] 🖼️ 检查到图片: ${title},正在尝试转存`);
1237
+ const result = await this.images.syncOne(fileName);
1238
+ if (result.success && result.reason === "synced") {
1204
1239
  syncedItems.push({
1205
1240
  title,
1206
- type: "page",
1241
+ type: "image",
1207
1242
  user,
1208
1243
  timestamp,
1209
1244
  comment
1210
1245
  });
1211
1246
  }
1212
- await updateContributorToDatabase(database, title, user, timestamp);
1213
1247
  }
1214
- }
1215
- __name(handlePageSync, "handlePageSync");
1248
+ /** 增量更新中遇到普通页面时的处理 */
1249
+ async handlePageSync(title, pageId, user, timestamp, comment, syncedItems) {
1250
+ await this.ensurePageInDatabase(pageId, title);
1251
+ const result = await this.syncOne(title, user);
1252
+ if (result.success) {
1253
+ if (result.reason === "synced") {
1254
+ syncedItems.push({
1255
+ title,
1256
+ type: "page",
1257
+ user,
1258
+ timestamp,
1259
+ comment
1260
+ });
1261
+ }
1262
+ await this.updateContributorToDatabase(title, user, timestamp);
1263
+ }
1264
+ }
1265
+ };
1216
1266
 
1217
1267
  // src/sync/moduleSync.ts
1218
- var import_koishi7 = require("koishi");
1219
- var CONFIG3 = {
1220
- MODULE_NAMESPACE: 828,
1221
- // 模块命名空间
1222
- IGNORED_MODULES: [],
1223
- // 忽略的模块列表
1224
- SYNC_INTERVAL_SUCCESS: 500,
1225
- // 同步成功后等待时间(毫秒)
1226
- SYNC_INTERVAL_FAILED: 1e3
1227
- // 同步失败后等待时间(毫秒)
1268
+ var DEFAULT_OPTIONS3 = {
1269
+ moduleNamespace: 828,
1270
+ ignoredModules: [],
1271
+ intervalSuccess: 500,
1272
+ intervalFailed: 1e3
1228
1273
  };
1229
- async function syncSingleModule(oldSite, newSite, moduleTitle, user) {
1230
- if (CONFIG3.IGNORED_MODULES.includes(moduleTitle)) {
1231
- logger.info(`[SyncModule] 🚫 模块 ${moduleTitle} 在忽略列表中,跳过`);
1232
- return { success: true, reason: "ignored" };
1274
+ var DEFAULT_USER = "同步坤器人";
1275
+ var ModuleSyncer = class {
1276
+ constructor(source, target, deps = {}) {
1277
+ this.source = source;
1278
+ this.target = target;
1279
+ this.options = { ...DEFAULT_OPTIONS3, ...deps.options };
1233
1280
  }
1234
- try {
1235
- logger.info(`[SyncModule] 🔍 开始获取模块 ${moduleTitle} 的内容`);
1236
- let targetTitle = moduleTitle;
1237
- if (/^Dev:/i.test(moduleTitle)) {
1238
- const subPageName = moduleTitle.replace(/^Dev:/i, "");
1239
- targetTitle = `Module:Dev/${subPageName}`;
1240
- logger.info(
1241
- `[SyncModule] 🔀 检测到 Dev 命名空间,路径映射: ${moduleTitle} -> ${targetTitle}`
1281
+ static {
1282
+ __name(this, "ModuleSyncer");
1283
+ }
1284
+ options;
1285
+ async syncOne(moduleTitle, user) {
1286
+ if (this.options.ignoredModules.includes(moduleTitle)) {
1287
+ logger.info(`[SyncModule] 🚫 模块 ${moduleTitle} 在忽略列表中,跳过`);
1288
+ return { success: true, reason: "ignored" };
1289
+ }
1290
+ try {
1291
+ logger.info(`[SyncModule] 🔍 开始获取模块 ${moduleTitle} 的内容`);
1292
+ let targetTitle = moduleTitle;
1293
+ if (/^Dev:/i.test(moduleTitle)) {
1294
+ const subPageName = moduleTitle.replace(/^Dev:/i, "");
1295
+ targetTitle = `Module:Dev/${subPageName}`;
1296
+ logger.info(
1297
+ `[SyncModule] 🔀 检测到 Dev 命名空间,路径映射: ${moduleTitle} -> ${targetTitle}`
1298
+ );
1299
+ }
1300
+ const [oldContent, newContent] = await Promise.all([
1301
+ getAndProcessPageContent(this.source, moduleTitle),
1302
+ getAndProcessPageContent(this.target, targetTitle)
1303
+ ]);
1304
+ if (oldContent === newContent) {
1305
+ logger.info(`[SyncModule] 🟡 模块 ${moduleTitle} 内容未改变,跳过`);
1306
+ return { success: true, reason: "no_change" };
1307
+ }
1308
+ await this.target.save(
1309
+ targetTitle,
1310
+ oldContent,
1311
+ `由:${user || "同步坤器人手动"} 触发更改,此时同步`
1242
1312
  );
1313
+ logger.info(`[SyncModule] ✅ 模块 ${moduleTitle} 同步成功`);
1314
+ return { success: true, reason: "synced" };
1315
+ } catch (error) {
1316
+ const errMsg = getErrorMessage(error);
1317
+ logger.error(`[SyncModule] ❌ 模块 ${moduleTitle} 同步失败:`, errMsg);
1318
+ return { success: false, reason: errMsg };
1243
1319
  }
1244
- const [oldContent, newContent] = await Promise.all([
1245
- getAndProcessPageContent(oldSite, moduleTitle),
1246
- getAndProcessPageContent(newSite, targetTitle)
1247
- ]);
1248
- if (oldContent === newContent) {
1249
- logger.info(`[SyncModule] 🟡 模块 ${moduleTitle} 内容未改变,跳过`);
1250
- return { success: true, reason: "no_change" };
1320
+ }
1321
+ async listAll() {
1322
+ logger.info(
1323
+ `[SyncAllModules] 📥 开始获取原站点所有模块(命名空间${this.options.moduleNamespace})`
1324
+ );
1325
+ const allModules = [];
1326
+ const queryGen = this.source.continuedQueryGen({
1327
+ action: "query",
1328
+ list: "allpages",
1329
+ apnamespace: this.options.moduleNamespace,
1330
+ aplimit: "max",
1331
+ apdir: "ascending"
1332
+ });
1333
+ for await (const res of queryGen) {
1334
+ const titles = res.query?.allpages?.map((page) => page.title) || [];
1335
+ allModules.push(...titles);
1336
+ logger.info(`[SyncAllModules] 📄 已获取 ${allModules.length} 个模块`);
1251
1337
  }
1252
- await newSite.save(
1253
- targetTitle,
1254
- oldContent,
1255
- `由:${user || "同步坤器人手动"} 触发更改,此时同步`
1338
+ logger.info(
1339
+ `[SyncAllModules] 📊 原站点总计获取到 ${allModules.length} 个模块`
1256
1340
  );
1257
- logger.info(`[SyncModule] ✅ 模块 ${moduleTitle} 同步成功`);
1258
- return { success: true, reason: "synced" };
1259
- } catch (error) {
1260
- const errMsg = error.message || String(error);
1261
- logger.error(`[SyncModule] ❌ 模块 ${moduleTitle} 同步失败:`, errMsg);
1262
- return { success: false, reason: errMsg };
1263
- }
1264
- }
1265
- __name(syncSingleModule, "syncSingleModule");
1266
- async function getAllModules(site) {
1267
- logger.info(
1268
- `[SyncAllModules] 📥 开始获取原站点所有模块(命名空间${CONFIG3.MODULE_NAMESPACE})`
1269
- );
1270
- const allModules = [];
1271
- const queryGen = site.continuedQueryGen({
1272
- action: "query",
1273
- list: "allpages",
1274
- apnamespace: CONFIG3.MODULE_NAMESPACE,
1275
- // 模块命名空间
1276
- aplimit: "max",
1277
- apdir: "ascending"
1278
- });
1279
- for await (const res of queryGen) {
1280
- const moduleTitles = res.query?.allpages?.map((page) => page.title) || [];
1281
- allModules.push(...moduleTitles);
1282
- logger.info(`[SyncAllModules] 📄 已获取 ${allModules.length} 个模块`);
1341
+ return allModules;
1283
1342
  }
1284
- logger.info(
1285
- `[SyncAllModules] 📊 原站点总计获取到 ${allModules.length} 个模块`
1286
- );
1287
- return allModules;
1288
- }
1289
- __name(getAllModules, "getAllModules");
1290
- async function syncModules(oldSite, newSite) {
1291
- try {
1292
- const oldModuleList = await getAllModules(oldSite);
1293
- const total = oldModuleList.length;
1294
- if (total === 0) {
1295
- logger.info(`[SyncAllModules] 📭 原站点无模块可同步,结束`);
1296
- return;
1297
- }
1298
- let successCount = 0;
1299
- let failCount = 0;
1300
- let skipCount = 0;
1301
- const failedModules = [];
1302
- logger.info(`[SyncAllModules] 🚦 开始批量同步,总计 ${total} 个模块`);
1303
- for (let index = 0; index < total; index++) {
1304
- const moduleTitle = oldModuleList[index];
1305
- const current = index + 1;
1306
- const remaining = total - current;
1307
- const progress = (current / total * 100).toFixed(1);
1308
- logger.info(
1309
- `
1343
+ /** 批量同步所有模块:先串行同步一轮,再重试失败的 */
1344
+ async syncAll() {
1345
+ try {
1346
+ const oldModuleList = await this.listAll();
1347
+ const total = oldModuleList.length;
1348
+ if (total === 0) {
1349
+ logger.info(`[SyncAllModules] 📭 原站点无模块可同步,结束`);
1350
+ return;
1351
+ }
1352
+ let successCount = 0;
1353
+ let failCount = 0;
1354
+ let skipCount = 0;
1355
+ const failedModules = [];
1356
+ logger.info(`[SyncAllModules] 🚦 开始批量同步,总计 ${total} 个模块`);
1357
+ for (let index = 0; index < total; index++) {
1358
+ const moduleTitle = oldModuleList[index];
1359
+ const current = index + 1;
1360
+ const remaining = total - current;
1361
+ const progress = (current / total * 100).toFixed(1);
1362
+ logger.info(
1363
+ `
1310
1364
  [SyncAllModules] 📈 进度 [${current}/${total}] (${progress}%) - 处理 ${moduleTitle} | 剩余 ${remaining} 个`
1311
- );
1312
- const syncResult = await syncSingleModule(
1313
- oldSite,
1314
- newSite,
1315
- moduleTitle,
1316
- "同步坤器人"
1317
- );
1318
- if (!syncResult.success) {
1319
- failCount++;
1320
- failedModules.push(moduleTitle);
1321
- await (0, import_koishi7.sleep)(CONFIG3.SYNC_INTERVAL_FAILED);
1322
- } else {
1323
- successCount++;
1324
- if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
1325
- skipCount++;
1365
+ );
1366
+ const result = await this.syncOne(moduleTitle, DEFAULT_USER);
1367
+ if (!result.success) {
1368
+ failCount++;
1369
+ failedModules.push(moduleTitle);
1370
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
1371
+ } else {
1372
+ successCount++;
1373
+ if (result.reason === "ignored" || result.reason === "no_change") {
1374
+ skipCount++;
1375
+ }
1376
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
1326
1377
  }
1327
- await (0, import_koishi7.sleep)(CONFIG3.SYNC_INTERVAL_SUCCESS);
1328
1378
  }
1329
- }
1330
- if (failedModules.length > 0) {
1331
- logger.info(
1332
- `
1379
+ if (failedModules.length > 0) {
1380
+ logger.info(
1381
+ `
1333
1382
  [SyncAllModules] 🔄 ===== 开始重试 ${failedModules.length} 个失败模块 =====`
1334
- );
1335
- const stillFailed = [];
1336
- for (const moduleTitle of failedModules) {
1337
- logger.info(`
1338
- [SyncAllModules] 🔁 重试中: ${moduleTitle}`);
1339
- const syncResult = await syncSingleModule(
1340
- oldSite,
1341
- newSite,
1342
- moduleTitle,
1343
- "同步坤器人"
1344
1383
  );
1345
- if (syncResult.success) {
1346
- successCount++;
1347
- failCount--;
1348
- if (syncResult.reason === "ignored" || syncResult.reason === "no_change") {
1349
- skipCount++;
1384
+ const stillFailed = [];
1385
+ for (const moduleTitle of failedModules) {
1386
+ logger.info(`
1387
+ [SyncAllModules] 🔁 重试中: ${moduleTitle}`);
1388
+ const result = await this.syncOne(moduleTitle, DEFAULT_USER);
1389
+ if (result.success) {
1390
+ successCount++;
1391
+ failCount--;
1392
+ if (result.reason === "ignored" || result.reason === "no_change") {
1393
+ skipCount++;
1394
+ }
1395
+ logger.info(`[SyncAllModules] ✅ 模块 ${moduleTitle} 重试成功`);
1396
+ await (0, import_koishi3.sleep)(this.options.intervalSuccess);
1397
+ } else {
1398
+ stillFailed.push(moduleTitle);
1399
+ logger.info(`[SyncAllModules] ❌ 模块 ${moduleTitle} 再次失败`);
1400
+ await (0, import_koishi3.sleep)(this.options.intervalFailed);
1350
1401
  }
1351
- logger.info(`[SyncAllModules] ✅ 模块 ${moduleTitle} 重试成功`);
1352
- await (0, import_koishi7.sleep)(CONFIG3.SYNC_INTERVAL_SUCCESS);
1402
+ }
1403
+ logger.info(`
1404
+ [SyncAllModules] 📋 ===== 最终同步报告 =====`);
1405
+ if (stillFailed.length > 0) {
1406
+ logger.info(`❌ 以下模块经过重试仍然失败,请手动检查:`);
1407
+ stillFailed.forEach((title, idx) => {
1408
+ logger.info(` ${idx + 1}. ${title}`);
1409
+ });
1353
1410
  } else {
1354
- stillFailed.push(moduleTitle);
1355
- logger.info(`[SyncAllModules] ❌ 模块 ${moduleTitle} 再次失败`);
1356
- await (0, import_koishi7.sleep)(CONFIG3.SYNC_INTERVAL_FAILED);
1411
+ logger.info(`🎉 所有模块同步成功(含重试)!`);
1357
1412
  }
1358
1413
  }
1359
1414
  logger.info(`
1360
- [SyncAllModules] 📋 ===== 最终同步报告 =====`);
1361
- if (stillFailed.length > 0) {
1362
- logger.info(`❌ 以下模块经过重试仍然失败,请手动检查:`);
1363
- stillFailed.forEach((title, idx) => {
1364
- logger.info(` ${idx + 1}. ${title}`);
1365
- });
1366
- } else {
1367
- logger.info(`🎉 所有模块同步成功(含重试)!`);
1415
+ [SyncAllModules] 🎯 同步完成!`);
1416
+ logger.info(`├─ 总计:${total} 个模块`);
1417
+ logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
1418
+ logger.info(`└─ 失败:${failCount} 个`);
1419
+ } catch (error) {
1420
+ logger.error(
1421
+ `[SyncAllModules] 💥 批量同步流程异常终止:`,
1422
+ getErrorMessage(error)
1423
+ );
1424
+ throw error;
1425
+ }
1426
+ }
1427
+ };
1428
+
1429
+ // src/services/syncNotifier.ts
1430
+ var SyncNotifier = class {
1431
+ constructor(ctx, groupIds = [], platform = "qq") {
1432
+ this.ctx = ctx;
1433
+ this.groupIds = groupIds;
1434
+ this.platform = platform || "qq";
1435
+ }
1436
+ static {
1437
+ __name(this, "SyncNotifier");
1438
+ }
1439
+ groupIds;
1440
+ platform;
1441
+ get enabled() {
1442
+ return this.groupIds.length > 0;
1443
+ }
1444
+ async notify(items) {
1445
+ if (items.length === 0) return;
1446
+ try {
1447
+ const bots = this.activeBots();
1448
+ if (bots.length === 0) {
1449
+ logger.warn(
1450
+ `[通知] 未找到可用的 ${this.platform} 平台 bot,跳过群通知`
1451
+ );
1452
+ return;
1368
1453
  }
1454
+ const message = this.formatMessage(items);
1455
+ for (const bot of bots) {
1456
+ for (const rawChannelId of this.groupIds) {
1457
+ const channelId = normalizeChannelId(rawChannelId);
1458
+ if (!channelId) continue;
1459
+ try {
1460
+ await bot.sendMessage(channelId, message);
1461
+ logger.info(
1462
+ `[通知] 向 ${bot.platform}/${channelId} 推送成功 (${items.length} 条)`
1463
+ );
1464
+ } catch (error) {
1465
+ logger.error(
1466
+ `[通知] 向 ${bot.platform}/${channelId} 发送消息失败:`,
1467
+ getErrorMessage(error)
1468
+ );
1469
+ }
1470
+ }
1471
+ }
1472
+ } catch (error) {
1473
+ logger.error(`[通知] 处理通知过程出错:`, getErrorMessage(error));
1369
1474
  }
1370
- logger.info(`
1371
- [SyncAllModules] 🎯 同步完成!`);
1372
- logger.info(`├─ 总计:${total} 个模块`);
1373
- logger.info(`├─ 成功:${successCount} 个(含跳过 ${skipCount} 个)`);
1374
- logger.info(`└─ 失败:${failCount} 个`);
1375
- } catch (error) {
1376
- const errorMsg = getErrorMessage(error);
1377
- logger.error(`[SyncAllModules] 💥 批量同步流程异常终止:`, errorMsg);
1378
- throw error;
1379
1475
  }
1380
- }
1381
- __name(syncModules, "syncModules");
1476
+ activeBots() {
1477
+ const bots = [];
1478
+ for (const bot of this.ctx.bots) {
1479
+ if (bot.platform === this.platform && bot.isActive) {
1480
+ bots.push(bot);
1481
+ }
1482
+ }
1483
+ return bots;
1484
+ }
1485
+ formatMessage(items) {
1486
+ const lines = [`Wiki 同步更新(${items.length} 条)`, ""];
1487
+ items.forEach((item, index) => {
1488
+ const label = item.type === "image" ? "🖼️" : "📖";
1489
+ const time = item.timestamp ? formatWikiTime(item.timestamp) : "";
1490
+ const user = item.user || "未知";
1491
+ const summary = truncateComment(item.comment || "", 10);
1492
+ const commentPart = summary ? `|${summary}` : "";
1493
+ lines.push(
1494
+ `${label} ${index + 1}. ${item.title}|${user}|${time}${commentPart}`
1495
+ );
1496
+ });
1497
+ return lines.join("\n");
1498
+ }
1499
+ };
1382
1500
 
1383
1501
  // src/plugins/syncCommands.ts
1384
1502
  var SyncCommands = class {
@@ -1391,20 +1509,27 @@ var SyncCommands = class {
1391
1509
  constructor(ctx, config) {
1392
1510
  this.config = config;
1393
1511
  logger.info("WikiBot 服务已就绪,初始化定时任务和指令");
1394
- this.notifyFn = this.buildNotifyFn(ctx);
1512
+ const notifier = new SyncNotifier(
1513
+ ctx,
1514
+ config.notifyGroupIds,
1515
+ config.notifyBotPlatform
1516
+ );
1517
+ this.notifyFn = notifier.enabled ? (items) => void notifier.notify(items) : void 0;
1518
+ this.registerScheduledTasks(ctx);
1519
+ this.registerCommands(ctx);
1520
+ }
1521
+ /** 同步相关的定时任务;cron 表达式即调度策略,集中在一处便于对照 */
1522
+ registerScheduledTasks(ctx) {
1395
1523
  ctx.cron("15 * * * *", async () => {
1396
1524
  if (!await this.ensureBotsReady(ctx, "增量更新")) return;
1397
- await incrementalUpdate(
1398
- ctx.wikiBot.getGGBot(),
1399
- ctx.wikiBot.getBWikiBot(),
1400
- config,
1401
- this.notifyFn,
1402
- ctx.database
1403
- );
1525
+ await new PageSyncer(ctx.wikiBot.getGGBot(), ctx.wikiBot.getBWikiBot(), {
1526
+ database: ctx.database,
1527
+ notify: this.notifyFn
1528
+ }).incrementalUpdate();
1404
1529
  });
1405
1530
  ctx.cron("30 8 * * 4", async () => {
1406
1531
  if (!await this.ensureBotsReady(ctx, "同步所有页面")) return;
1407
- await syncPages(ctx.wikiBot.getGGBot(), ctx.wikiBot.getBWikiBot()).then(() => {
1532
+ await new PageSyncer(ctx.wikiBot.getGGBot(), ctx.wikiBot.getBWikiBot()).syncAll().then(() => {
1408
1533
  logger.info("自动任务:尝试同步所有页面,从 WIKIGG 到 bwiki");
1409
1534
  }).catch((err) => {
1410
1535
  logger.error(`同步所有页面失败,错误信息:${err}`);
@@ -1412,11 +1537,10 @@ var SyncCommands = class {
1412
1537
  });
1413
1538
  ctx.cron("30 8 * * 3", async () => {
1414
1539
  if (!await this.ensureBotsReady(ctx, "同步所有图片")) return;
1415
- await syncAllImages(
1540
+ await new ImageSyncer(
1416
1541
  ctx.wikiBot.getGGBot(),
1417
- ctx.wikiBot.getBWikiBot(),
1418
- config
1419
- ).then(() => {
1542
+ ctx.wikiBot.getBWikiBot()
1543
+ ).syncAll().then(() => {
1420
1544
  logger.info("自动任务:尝试同步所有图片,从 WIKIGG 到 bwiki");
1421
1545
  }).catch((err) => {
1422
1546
  logger.error(`同步所有图片失败,错误信息:${err}`);
@@ -1427,87 +1551,12 @@ var SyncCommands = class {
1427
1551
  await this.syncAllContributors(ctx, "定时任务");
1428
1552
  });
1429
1553
  logger.info("✅ 每周日贡献者定时同步任务已注册(每周日凌晨2点执行)");
1430
- this.registerCommands(ctx);
1431
1554
  }
1432
- /**
1433
- * 构建增量更新同步成功的通知回调
1434
- * 当配置了 notifyGroupIds 时,将同步成功的页面/图片合并成一条消息推送到指定 QQ 群
1435
- */
1436
- buildNotifyFn(ctx) {
1437
- const groupIds = this.config.notifyGroupIds;
1438
- if (!groupIds || groupIds.length === 0) return void 0;
1439
- const platform = this.config.notifyBotPlatform || "qq";
1440
- return async (items) => {
1441
- try {
1442
- if (!items || items.length === 0) return;
1443
- const bots = [];
1444
- for (const bot of ctx.bots) {
1445
- if (bot.platform === platform && bot.isActive) {
1446
- bots.push(bot);
1447
- }
1448
- }
1449
- if (bots.length === 0) {
1450
- logger.warn(`[通知] 未找到可用的 ${platform} 平台 bot,跳过群通知`);
1451
- return;
1452
- }
1453
- const lines = [];
1454
- lines.push(`Wiki 同步更新(${items.length} 条)`);
1455
- lines.push("");
1456
- for (let i = 0; i < items.length; i++) {
1457
- const item = items[i];
1458
- const label = item.type === "image" ? "🖼️" : "📖";
1459
- const zhTime = item.timestamp ? formatWikiTime(item.timestamp) : "";
1460
- const user = item.user || "未知";
1461
- const shortComment = truncateComment(item.comment || "", 10);
1462
- const commentLine = shortComment ? `|${shortComment}` : "";
1463
- lines.push(
1464
- `${label} ${i + 1}. ${item.title}|${user}|${zhTime}${commentLine}`
1465
- );
1466
- }
1467
- const message = lines.join("\n");
1468
- for (const bot of bots) {
1469
- for (const rawChannelId of groupIds) {
1470
- const channelId = normalizeChannelId(rawChannelId);
1471
- if (!channelId) continue;
1472
- try {
1473
- await bot.sendMessage(channelId, message);
1474
- logger.info(
1475
- `[通知] 向 ${bot.platform}/${channelId} 推送成功 (${items.length} 条)`
1476
- );
1477
- } catch (error) {
1478
- logger.error(
1479
- `[通知] 向 ${bot.platform}/${channelId} 发送消息失败:`,
1480
- getErrorMessage(error)
1481
- );
1482
- }
1483
- }
1484
- }
1485
- } catch (error) {
1486
- logger.error(`[通知] 处理通知过程出错:`, getErrorMessage(error));
1487
- }
1488
- };
1489
- }
1490
- /**
1491
- * 确保机器人就绪,如果未就绪则尝试重新登录
1492
- * @param ctx Koishi 上下文
1493
- * @param taskName 任务名称(用于日志)
1494
- * @returns 机器人是否已就绪
1495
- */
1496
1555
  async ensureBotsReady(ctx, taskName) {
1497
- if (!ctx.wikiBot.isGGBotReady() || !ctx.wikiBot.isBWikiBotReady()) {
1498
- logger.warn(`检测到部分机器人未就绪,尝试重新登录...`);
1499
- try {
1500
- await ctx.wikiBot.relogin();
1501
- } catch (error) {
1502
- logger.error(`重新登录失败: ${error}`);
1503
- return false;
1504
- }
1505
- }
1506
- const ggReady = ctx.wikiBot.isGGBotReady();
1507
- const bwikiReady = ctx.wikiBot.isBWikiBotReady();
1508
- if (!ggReady || !bwikiReady) {
1556
+ const { gg, bwiki } = await ctx.wikiBot.ensureReady();
1557
+ if (!gg || !bwiki) {
1509
1558
  logger.warn(
1510
- `${taskName} 跳过:Wiki 机器人仍未就绪 - WIKIGG: ${ggReady ? "✅" : "❌"}, bwiki: ${bwikiReady ? "✅" : "❌"}`
1559
+ `${taskName} 跳过:Wiki 机器人仍未就绪 - WIKIGG: ${gg ? "✅" : "❌"}, bwiki: ${bwiki ? "✅" : "❌"}`
1511
1560
  );
1512
1561
  return false;
1513
1562
  }
@@ -1519,12 +1568,10 @@ var SyncCommands = class {
1519
1568
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1520
1569
  }
1521
1570
  try {
1522
- await syncSinglePage(
1571
+ await new PageSyncer(
1523
1572
  ctx.wikiBot.getGGBot(),
1524
- ctx.wikiBot.getBWikiBot(),
1525
- pageTitle,
1526
- "sync-bot"
1527
- );
1573
+ ctx.wikiBot.getBWikiBot()
1574
+ ).syncOne(pageTitle, "sync-bot");
1528
1575
  return `✅ 已尝试同步页面:${pageTitle},请前往控制台查看:${this.config.logsUrl}`;
1529
1576
  } catch (err) {
1530
1577
  logger.error(`同步页面 ${pageTitle} 失败,错误信息:${err}`);
@@ -1538,12 +1585,11 @@ var SyncCommands = class {
1538
1585
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1539
1586
  }
1540
1587
  try {
1541
- await incrementalUpdate(
1588
+ await new PageSyncer(
1542
1589
  ctx.wikiBot.getGGBot(),
1543
1590
  ctx.wikiBot.getBWikiBot(),
1544
- this.config,
1545
- this.notifyFn
1546
- );
1591
+ { notify: this.notifyFn }
1592
+ ).incrementalUpdate();
1547
1593
  return `✅ 已尝试获取三小时前的编辑并同步,请前往控制台查看:${this.config.logsUrl}`;
1548
1594
  } catch (err) {
1549
1595
  logger.error(`增量更新失败,错误信息:${err}`);
@@ -1555,7 +1601,10 @@ var SyncCommands = class {
1555
1601
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1556
1602
  }
1557
1603
  try {
1558
- await syncPages(ctx.wikiBot.getGGBot(), ctx.wikiBot.getBWikiBot());
1604
+ await new PageSyncer(
1605
+ ctx.wikiBot.getGGBot(),
1606
+ ctx.wikiBot.getBWikiBot()
1607
+ ).syncAll();
1559
1608
  return `✅ 已尝试同步所有页面,请前往控制台查看:${this.config.logsUrl}`;
1560
1609
  } catch (err) {
1561
1610
  logger.error(`同步所有页面失败,错误信息:${err}`);
@@ -1569,12 +1618,10 @@ var SyncCommands = class {
1569
1618
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1570
1619
  }
1571
1620
  try {
1572
- await syncSingleModule(
1621
+ await new ModuleSyncer(
1573
1622
  ctx.wikiBot.getGGBot(),
1574
- ctx.wikiBot.getBWikiBot(),
1575
- moduleTitle,
1576
- "sync-bot"
1577
- );
1623
+ ctx.wikiBot.getBWikiBot()
1624
+ ).syncOne(moduleTitle, "sync-bot");
1578
1625
  return `✅ 已尝试同步模块:${moduleTitle},请前往控制台查看:${this.config.logsUrl}`;
1579
1626
  } catch (err) {
1580
1627
  logger.error(`同步模块 ${moduleTitle} 失败,错误信息:${err}`);
@@ -1586,7 +1633,10 @@ var SyncCommands = class {
1586
1633
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1587
1634
  }
1588
1635
  try {
1589
- await syncModules(ctx.wikiBot.getGGBot(), ctx.wikiBot.getBWikiBot());
1636
+ await new ModuleSyncer(
1637
+ ctx.wikiBot.getGGBot(),
1638
+ ctx.wikiBot.getBWikiBot()
1639
+ ).syncAll();
1590
1640
  return `✅ 已尝试同步所有模块,请前往控制台查看:${this.config.logsUrl}`;
1591
1641
  } catch (err) {
1592
1642
  logger.error(`同步所有模块失败,错误信息:${err}`);
@@ -1598,11 +1648,11 @@ var SyncCommands = class {
1598
1648
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1599
1649
  }
1600
1650
  try {
1601
- await syncSingleImage(
1651
+ await new ImageSyncer(
1602
1652
  ctx.wikiBot.getGGBot(),
1603
- ctx.wikiBot.getBWikiBot(),
1604
- `${imgTitle.startsWith("File:") ? "" : "File:"}${imgTitle}`,
1605
- this.config
1653
+ ctx.wikiBot.getBWikiBot()
1654
+ ).syncOne(
1655
+ `${imgTitle.startsWith("File:") ? "" : "File:"}${imgTitle}`
1606
1656
  );
1607
1657
  return `✅ 已尝试同步图片:${imgTitle}`;
1608
1658
  } catch (err) {
@@ -1615,11 +1665,10 @@ var SyncCommands = class {
1615
1665
  return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
1616
1666
  }
1617
1667
  try {
1618
- await syncAllImages(
1668
+ await new ImageSyncer(
1619
1669
  ctx.wikiBot.getGGBot(),
1620
- ctx.wikiBot.getBWikiBot(),
1621
- this.config
1622
- );
1670
+ ctx.wikiBot.getBWikiBot()
1671
+ ).syncAll();
1623
1672
  return `✅ 已尝试同步所有图片,请前往控制台查看:${this.config.logsUrl}`;
1624
1673
  } catch (err) {
1625
1674
  logger.error(`同步所有图片失败,错误信息:${err}`);
@@ -1646,10 +1695,14 @@ var SyncCommands = class {
1646
1695
  formatversion: "2",
1647
1696
  rvprop: "timestamp|user"
1648
1697
  });
1649
- if (res.query.pages[0].missing === true) {
1698
+ const page = res.query?.pages?.[0];
1699
+ if (!page || page.missing === true) {
1700
+ return { contributor: "", change_time: "" };
1701
+ }
1702
+ const revisions = page.revisions?.[0];
1703
+ if (!revisions) {
1650
1704
  return { contributor: "", change_time: "" };
1651
1705
  }
1652
- const revisions = res.query.pages[0].revisions[0];
1653
1706
  return {
1654
1707
  contributor: revisions.user,
1655
1708
  change_time: formatWikiTime(revisions.timestamp)
@@ -1718,7 +1771,7 @@ var SyncCommands = class {
1718
1771
  let failCount = 0;
1719
1772
  const failedPages = [];
1720
1773
  for (const page of pages) {
1721
- await (0, import_koishi8.sleep)(800);
1774
+ await (0, import_koishi3.sleep)(800);
1722
1775
  try {
1723
1776
  const data = await this.getContributorsAndTimestamp(
1724
1777
  page.title,
@@ -1756,25 +1809,221 @@ var SyncCommands = class {
1756
1809
  }
1757
1810
  }
1758
1811
  };
1759
- ((SyncCommands2) => {
1760
- SyncCommands2.Config = import_koishi8.Schema.object({
1761
- ggUsername: import_koishi8.Schema.string().description("WIKIGG 用户名").default("1"),
1762
- ggPassword: import_koishi8.Schema.string().description("WIKIGG 密码").default("1"),
1763
- bwikiusername: import_koishi8.Schema.string().description("bwiki用户名").default("1"),
1764
- bwikipassword: import_koishi8.Schema.string().description("bwiki密码").default("1"),
1765
- domain: import_koishi8.Schema.string().description("你的短链域名(必填,如:klei.vip)").default("klei.vip"),
1766
- main_site: import_koishi8.Schema.string().description("主站域名(必填,如:oxygennotincluded.wiki.gg)").default("oxygennotincluded.wiki.gg/zh"),
1767
- bwiki_site: import_koishi8.Schema.string().description("镜像站域名(必填,如:wiki.biligame.com)").default("wiki.biligame.com/oni"),
1768
- logsUrl: import_koishi8.Schema.string().description("日志查看地址").default("https://klei.vip/onilogs"),
1769
- notifyGroupIds: import_koishi8.Schema.array(import_koishi8.Schema.string()).description(
1770
- '增量更新同步成功时通知的群频道ID列表,如 ["group:123456"],留空则不发送通知'
1771
- ).default([]),
1772
- notifyBotPlatform: import_koishi8.Schema.string().description("通知 bot 的平台标识,默认 qq").default("qq")
1773
- });
1774
- })(SyncCommands || (SyncCommands = {}));
1812
+
1813
+ // src/utils/matcher.ts
1814
+ function getCommonPrefixLength(a, b) {
1815
+ const minLen = Math.min(a.length, b.length);
1816
+ let i = 0;
1817
+ while (i < minLen && a[i] === b[i]) i++;
1818
+ return i;
1819
+ }
1820
+ __name(getCommonPrefixLength, "getCommonPrefixLength");
1821
+ function calculateScore(page, queryKey, queryPinyinFull, queryPinyinFirst) {
1822
+ let score = 0;
1823
+ const { title, pinyin_full, pinyin_first } = page;
1824
+ if (queryKey && title.includes(queryKey)) score += 10;
1825
+ if (queryPinyinFull) {
1826
+ if (pinyin_full.startsWith(queryPinyinFull)) score += 9;
1827
+ if (pinyin_full.includes(queryPinyinFull)) score += 8;
1828
+ }
1829
+ if (queryPinyinFirst && pinyin_first.includes(queryPinyinFirst)) score += 6;
1830
+ const titlePrefixLen = getCommonPrefixLength(title, queryKey);
1831
+ if (titlePrefixLen >= 2) {
1832
+ score += titlePrefixLen;
1833
+ }
1834
+ const pinyinPrefixLen = getCommonPrefixLength(pinyin_full, queryPinyinFull);
1835
+ if (pinyinPrefixLen >= 3) {
1836
+ score += Math.floor(pinyinPrefixLen / 2);
1837
+ }
1838
+ return score;
1839
+ }
1840
+ __name(calculateScore, "calculateScore");
1841
+ function findFuzzyMatches(allPages, queryKey, queryPinyinFull, queryPinyinFirst, limit = 5) {
1842
+ const matchResults = [];
1843
+ for (const page of allPages) {
1844
+ const score = calculateScore(
1845
+ page,
1846
+ queryKey,
1847
+ queryPinyinFull,
1848
+ queryPinyinFirst
1849
+ );
1850
+ if (score > 0) {
1851
+ matchResults.push({ id: page.id, title: page.title, score });
1852
+ }
1853
+ }
1854
+ return matchResults.sort((a, b) => b.score - a.score || a.title.length - b.title.length).filter(
1855
+ (item, index, array) => array.findIndex((t) => t.title === item.title) === index
1856
+ ).slice(0, limit);
1857
+ }
1858
+ __name(findFuzzyMatches, "findFuzzyMatches");
1859
+
1860
+ // src/services/messageRenderer.ts
1861
+ var QQ_STYLE_ROW_SEPARATOR = "---\n";
1862
+ var MessageRenderer = class {
1863
+ constructor(ctx, domain) {
1864
+ this.ctx = ctx;
1865
+ this.domain = domain;
1866
+ }
1867
+ static {
1868
+ __name(this, "MessageRenderer");
1869
+ }
1870
+ isQQ(session) {
1871
+ return session?.platform === "qq";
1872
+ }
1873
+ /**
1874
+ * 发送(或返回)回复内容。
1875
+ * @returns QQ 平台发送成功时返回 undefined;其它情况返回可直接发给用户的纯文本
1876
+ */
1877
+ async send(session, content, keyboard) {
1878
+ if (!this.isQQ(session)) return content;
1879
+ try {
1880
+ const qq = session;
1881
+ const payload = {
1882
+ msg_id: qq.messageId,
1883
+ msg_type: 2,
1884
+ markdown: { content }
1885
+ };
1886
+ if (keyboard) payload.keyboard = keyboard;
1887
+ await qq.bot.internal.sendMessage(qq.channelId, payload);
1888
+ return void 0;
1889
+ } catch (error) {
1890
+ this.ctx.logger("oni-sync-bot").warn("QQ Markdown 发送失败,降级为纯文本:", error);
1891
+ return content;
1892
+ }
1893
+ }
1894
+ async usageMessage(session) {
1895
+ if (this.isQQ(session)) {
1896
+ const markdown = `**以下是使用说明:**
1897
+ > GG原站点: [https://${this.domain}/gg/88888888](https://${this.domain}/gg/88888888)
1898
+
1899
+ > bwiki: [https://${this.domain}/bw/88888888](https://${this.domain}/bw/88888888)
1900
+ `;
1901
+ return this.send(session, markdown);
1902
+ }
1903
+ return `以下是使用说明:
1904
+ GG原站点: https://${this.domain}/gg/88888888
1905
+
1906
+ bwiki: https://${this.domain}/bw/88888888`;
1907
+ }
1908
+ async resultMessage(session, page, prefix) {
1909
+ const hasMeta = Boolean(page.contributor || page.change_time);
1910
+ if (this.isQQ(session)) {
1911
+ let markdown = "";
1912
+ if (prefix) markdown += `**${prefix}**
1913
+ `;
1914
+ markdown += `**📖 ${page.title}**
1915
+
1916
+ `;
1917
+ if (hasMeta) {
1918
+ markdown += QQ_STYLE_ROW_SEPARATOR;
1919
+ if (page.contributor) {
1920
+ markdown += `> **👤 最后贡献者:** ${page.contributor}
1921
+ `;
1922
+ }
1923
+ if (page.change_time) {
1924
+ markdown += `> **🕐 最后修改:** ${page.change_time}
1925
+ `;
1926
+ }
1927
+ markdown += `惟知是信 至诚若天
1928
+ ${QQ_STYLE_ROW_SEPARATOR}`;
1929
+ }
1930
+ return this.send(session, markdown, this.pageKeyboard(page));
1931
+ }
1932
+ let message = "";
1933
+ if (prefix) message += `${prefix}
1934
+ `;
1935
+ message += `📖 ${page.title}
1936
+ `;
1937
+ if (hasMeta) {
1938
+ message += "--------\n";
1939
+ if (page.contributor) {
1940
+ message += `👤 最后贡献者:${page.contributor}
1941
+ `;
1942
+ }
1943
+ if (page.change_time) {
1944
+ message += `🕐 最后修改:${page.change_time}
1945
+ `;
1946
+ }
1947
+ }
1948
+ message += "惟知是信 至诚若天\n";
1949
+ message += "--------\n";
1950
+ message += `🔗 GG原站点: \`https://${this.domain}/gg/${page.id}\`
1951
+ `;
1952
+ message += `📚 bwiki: \`https://${this.domain}/bw/${page.id}\``;
1953
+ return message;
1954
+ }
1955
+ /** 命中多个候选时的按钮键盘(每行 2 个,跳 bwiki 镜像) */
1956
+ matchListKeyboard(matches) {
1957
+ const rows = [];
1958
+ for (let i = 0; i < matches.length; i += 2) {
1959
+ const buttons = matches.slice(i, i + 2).map((item) => {
1960
+ const label = item.title.length > 10 ? item.title.slice(0, 10) : item.title;
1961
+ return this.linkButton(
1962
+ `${item.id}`,
1963
+ label,
1964
+ `https://${this.domain}/bw/${item.id}`
1965
+ );
1966
+ });
1967
+ rows.push({ buttons });
1968
+ }
1969
+ return { content: { rows } };
1970
+ }
1971
+ /** 单个页面结果的按钮键盘:原站 / 镜像 / 直链 */
1972
+ pageKeyboard(page) {
1973
+ return {
1974
+ content: {
1975
+ rows: [
1976
+ {
1977
+ buttons: [
1978
+ this.linkButton(
1979
+ `gg-${page.id}`,
1980
+ "GG 原站",
1981
+ `https://${this.domain}/gg/${page.id}`
1982
+ )
1983
+ ]
1984
+ },
1985
+ {
1986
+ buttons: [
1987
+ this.linkButton(
1988
+ `bw-${page.id}`,
1989
+ "Bwiki 镜像",
1990
+ `https://${this.domain}/bw/${page.id}`
1991
+ )
1992
+ ]
1993
+ },
1994
+ {
1995
+ buttons: [
1996
+ this.linkButton(
1997
+ `wiki-${page.id}`,
1998
+ "GG直链",
1999
+ `https://oxygennotincluded.wiki.gg/zh/${encodeURIComponent(page.title)}`
2000
+ )
2001
+ ]
2002
+ }
2003
+ ]
2004
+ }
2005
+ };
2006
+ }
2007
+ linkButton(idSuffix, label, url) {
2008
+ return {
2009
+ id: `btn-${idSuffix}`,
2010
+ render_data: {
2011
+ label,
2012
+ visited_label: "已打开",
2013
+ style: 1
2014
+ },
2015
+ action: {
2016
+ type: 0,
2017
+ permission: {
2018
+ type: 2
2019
+ },
2020
+ data: url
2021
+ }
2022
+ };
2023
+ }
2024
+ };
1775
2025
 
1776
2026
  // src/plugins/queryCommands.ts
1777
- var import_koishi9 = require("koishi");
1778
2027
  var SPECIAL_CASES = /* @__PURE__ */ new Map([
1779
2028
  [
1780
2029
  "火箭计算器",
@@ -1788,20 +2037,22 @@ var QueryCommands = class {
1788
2037
  static inject = ["database"];
1789
2038
  config;
1790
2039
  ctx;
2040
+ renderer;
1791
2041
  constructor(ctx, config) {
1792
2042
  this.ctx = ctx;
1793
2043
  this.config = config;
2044
+ this.renderer = new MessageRenderer(ctx, config.domain);
1794
2045
  this.registerCommands(ctx);
1795
2046
  }
1796
2047
  registerCommands(ctx) {
1797
2048
  ctx.command("x <itemName:text>", "查询缺氧中文wiki,精准匹配+拼音模糊匹配").alias("/查wiki").action(async ({ session }, itemName = "") => {
1798
2049
  const queryKey = itemName.trim().toLowerCase();
1799
2050
  if (!queryKey) {
1800
- return this.renderUsageMessage(session);
2051
+ return this.renderer.usageMessage(session);
1801
2052
  }
1802
- if (SPECIAL_CASES.has(queryKey)) {
1803
- const content = SPECIAL_CASES.get(queryKey);
1804
- return this.sendResponse(session, content);
2053
+ const specialCase = SPECIAL_CASES.get(queryKey);
2054
+ if (specialCase !== void 0) {
2055
+ return this.renderer.send(session, specialCase);
1805
2056
  }
1806
2057
  const { pinyin_full: queryPinyinFull, pinyin_first: queryPinyinFirst } = generatePinyinInfo(queryKey);
1807
2058
  const preciseMatch = await this.findPreciseMatch(
@@ -1811,7 +2062,7 @@ var QueryCommands = class {
1811
2062
  queryPinyinFirst
1812
2063
  );
1813
2064
  if (preciseMatch) {
1814
- return this.renderResultMessage(
2065
+ return this.renderer.resultMessage(
1815
2066
  session,
1816
2067
  preciseMatch,
1817
2068
  preciseMatch.prefix
@@ -1819,19 +2070,19 @@ var QueryCommands = class {
1819
2070
  }
1820
2071
  const allPages = await ctx.database.get("wikipages", {});
1821
2072
  if (allPages.length === 0) {
1822
- return this.sendResponse(
2073
+ return this.renderer.send(
1823
2074
  session,
1824
2075
  "❌ 本地缓存为空,请联系管理员执行【update】指令更新缓存!"
1825
2076
  );
1826
2077
  }
1827
- const fuzzyMatches = this.findFuzzyMatches(
2078
+ const fuzzyMatches = findFuzzyMatches(
1828
2079
  allPages,
1829
2080
  queryKey,
1830
2081
  queryPinyinFull,
1831
2082
  queryPinyinFirst
1832
2083
  );
1833
2084
  if (fuzzyMatches.length === 0) {
1834
- return this.sendResponse(
2085
+ return this.renderer.send(
1835
2086
  session,
1836
2087
  `❌ 未找到【${queryKey}】相关内容,请按游戏内标准名称重新查询!`
1837
2088
  );
@@ -1839,163 +2090,7 @@ var QueryCommands = class {
1839
2090
  return await this.handleSelection(session, fuzzyMatches);
1840
2091
  });
1841
2092
  }
1842
- isQQPlatform(session) {
1843
- return session?.platform === "qq";
1844
- }
1845
- buildLinkButton(idSuffix, label, url) {
1846
- return {
1847
- id: `btn-${idSuffix}`,
1848
- render_data: {
1849
- label,
1850
- visited_label: "已打开",
1851
- style: 1
1852
- },
1853
- action: {
1854
- type: 0,
1855
- permission: {
1856
- type: 2
1857
- },
1858
- data: url
1859
- }
1860
- };
1861
- }
1862
- buildQQKeyboard(matches) {
1863
- const rows = [];
1864
- for (let i = 0; i < matches.length; i += 2) {
1865
- const buttonsInRow = matches.slice(i, i + 2).map((item) => {
1866
- const label = item.title.length > 10 ? item.title.slice(0, 10) : item.title;
1867
- return this.buildLinkButton(
1868
- `${item.id}`,
1869
- label,
1870
- `https://${this.config.domain}/bw/${item.id}`
1871
- );
1872
- });
1873
- rows.push({ buttons: buttonsInRow });
1874
- }
1875
- return {
1876
- content: { rows }
1877
- };
1878
- }
1879
- async sendResponse(session, content, keyboard) {
1880
- if (this.isQQPlatform(session)) {
1881
- try {
1882
- const payload = {
1883
- msg_id: session.messageId,
1884
- msg_type: 2,
1885
- markdown: {
1886
- content
1887
- }
1888
- };
1889
- if (keyboard) {
1890
- payload.keyboard = keyboard;
1891
- }
1892
- await session.bot.internal.sendMessage(session.channelId, payload);
1893
- return;
1894
- } catch (e) {
1895
- this.ctx.logger("oni-sync-bot").warn("QQ Markdown 发送失败,降级为纯文本:", e);
1896
- return content;
1897
- }
1898
- }
1899
- return content;
1900
- }
1901
- renderUsageMessage(session) {
1902
- if (this.isQQPlatform(session)) {
1903
- const md = `**以下是使用说明:**
1904
- > GG原站点: [https://${this.config.domain}/gg/88888888](https://${this.config.domain}/gg/88888888)
1905
-
1906
- > bwiki: [https://${this.config.domain}/bw/88888888](https://${this.config.domain}/bw/88888888)
1907
- `;
1908
- return this.sendResponse(session, md);
1909
- }
1910
- return `以下是使用说明:
1911
- GG原站点: https://${this.config.domain}/gg/88888888
1912
-
1913
- bwiki: https://${this.config.domain}/bw/88888888`;
1914
- }
1915
- buildResultKeyboard(match) {
1916
- return {
1917
- content: {
1918
- rows: [
1919
- {
1920
- buttons: [
1921
- this.buildLinkButton(
1922
- `gg-${match.id}`,
1923
- "GG 原站",
1924
- `https://${this.config.domain}/gg/${match.id}`
1925
- )
1926
- ]
1927
- },
1928
- {
1929
- buttons: [
1930
- this.buildLinkButton(
1931
- `bw-${match.id}`,
1932
- "Bwiki 镜像",
1933
- `https://${this.config.domain}/bw/${match.id}`
1934
- )
1935
- ]
1936
- },
1937
- {
1938
- buttons: [
1939
- this.buildLinkButton(
1940
- `wiki-${match.id}`,
1941
- "GG直链",
1942
- `https://oxygennotincluded.wiki.gg/zh/${encodeURIComponent(match.title)}`
1943
- )
1944
- ]
1945
- }
1946
- ]
1947
- }
1948
- };
1949
- }
1950
- renderResultMessage(session, match, prefix) {
1951
- if (this.isQQPlatform(session)) {
1952
- let md = "";
1953
- if (prefix) {
1954
- md += `**${prefix}**
1955
- `;
1956
- }
1957
- md += `**📖 ${match.title}**
1958
-
1959
- `;
1960
- if (match.contributor || match.change_time) {
1961
- md += "---\n";
1962
- if (match.contributor) {
1963
- md += `> **👤 最后贡献者:** ${match.contributor}
1964
- `;
1965
- }
1966
- if (match.change_time) {
1967
- md += `> **🕐 最后修改:** ${match.change_time}
1968
- `;
1969
- }
1970
- md += "惟知是信 至诚若天\n---\n";
1971
- }
1972
- const keyboard = this.buildResultKeyboard(match);
1973
- return this.sendResponse(session, md, keyboard);
1974
- }
1975
- let message = "";
1976
- if (prefix) {
1977
- message += prefix + "\n";
1978
- }
1979
- message += `📖 ${match.title}
1980
- `;
1981
- if (match.contributor || match.change_time) {
1982
- message += "--------\n";
1983
- if (match.contributor) {
1984
- message += `👤 最后贡献者:${match.contributor}
1985
- `;
1986
- }
1987
- if (match.change_time) {
1988
- message += `🕐 最后修改:${match.change_time}
1989
- `;
1990
- }
1991
- }
1992
- message += "惟知是信 至诚若天\n";
1993
- message += "--------\n";
1994
- message += `🔗 GG原站点: \`https://${this.config.domain}/gg/${match.id}\`
1995
- `;
1996
- message += `📚 bwiki: \`https://${this.config.domain}/bw/${match.id}\``;
1997
- return message;
1998
- }
2093
+ /** 标题 / 全拼 / 首字母三种精准匹配,命中即返回(带用于展示的前缀文案) */
1999
2094
  async findPreciseMatch(ctx, queryKey, queryPinyinFull, queryPinyinFirst) {
2000
2095
  const checks = [
2001
2096
  { query: { title: queryKey }, prefix: "✅ 精准匹配成功" },
@@ -2022,65 +2117,28 @@ bwiki: https://${this.config.domain}/bw/88888888`;
2022
2117
  }
2023
2118
  return null;
2024
2119
  }
2025
- getCommonPrefixLength(a, b) {
2026
- const minLen = Math.min(a.length, b.length);
2027
- let i = 0;
2028
- while (i < minLen && a[i] === b[i]) i++;
2029
- return i;
2030
- }
2031
- calculateScore(page, queryKey, queryPinyinFull, queryPinyinFirst) {
2032
- let score = 0;
2033
- const { title, pinyin_full, pinyin_first } = page;
2034
- if (title.includes(queryKey)) score += 10;
2035
- if (pinyin_full.startsWith(queryPinyinFull)) score += 9;
2036
- if (pinyin_full.includes(queryPinyinFull)) score += 8;
2037
- if (pinyin_first.includes(queryPinyinFirst)) score += 6;
2038
- const titlePrefixLen = this.getCommonPrefixLength(title, queryKey);
2039
- if (titlePrefixLen >= 2) {
2040
- score += titlePrefixLen;
2041
- }
2042
- const pinyinPrefixLen = this.getCommonPrefixLength(
2043
- pinyin_full,
2044
- queryPinyinFull
2045
- );
2046
- if (pinyinPrefixLen >= 3) {
2047
- score += Math.floor(pinyinPrefixLen / 2);
2048
- }
2049
- return score;
2050
- }
2051
- findFuzzyMatches(allPages, queryKey, queryPinyinFull, queryPinyinFirst) {
2052
- const matchResults = [];
2053
- for (const page of allPages) {
2054
- const score = this.calculateScore(
2055
- page,
2056
- queryKey,
2057
- queryPinyinFull,
2058
- queryPinyinFirst
2059
- );
2060
- if (score > 0) {
2061
- matchResults.push({ id: page.id, title: page.title, score });
2062
- }
2063
- }
2064
- return matchResults.sort((a, b) => b.score - a.score || a.title.length - b.title.length).filter(
2065
- (item, index, array) => array.findIndex((t) => t.title === item.title) === index
2066
- ).slice(0, 5);
2067
- }
2120
+ /**
2121
+ * 处理多候选选择:
2122
+ * - QQ:直接回按钮列表,结束;
2123
+ * - 其它平台:提示输入序号并等待 15 秒。
2124
+ */
2068
2125
  async handleSelection(session, matches) {
2069
2126
  const resultCount = matches.length;
2070
- let replyMsg;
2071
- if (this.isQQPlatform(session)) {
2072
- let md = `**🔍 为你找到【 ${resultCount} 】个相似结果,请点击下方按钮查看详情:**
2127
+ if (this.renderer.isQQ(session)) {
2128
+ let markdown = `**🔍 为你找到【 ${resultCount} 】个相似结果,请点击下方按钮查看详情:**
2073
2129
  `;
2074
2130
  matches.forEach((item, index) => {
2075
- md += `
2131
+ markdown += `
2076
2132
  > \`${index + 1}\`. **${item.title}**
2077
2133
  `;
2078
2134
  });
2079
- const keyboard = this.buildQQKeyboard(matches);
2080
- await this.sendResponse(session, md, keyboard);
2081
- return;
2135
+ return this.renderer.send(
2136
+ session,
2137
+ markdown,
2138
+ this.renderer.matchListKeyboard(matches)
2139
+ );
2082
2140
  }
2083
- replyMsg = `🔍 未找到精准匹配,为你找到【 ${resultCount} 】个相似结果,请输入序号选择(10秒内有效):
2141
+ let replyMsg = `🔍 未找到精准匹配,为你找到【 ${resultCount} 】个相似结果,请输入序号选择(10秒内有效):
2084
2142
  `;
2085
2143
  matches.forEach((item, index) => {
2086
2144
  replyMsg += `${index + 1}. ${item.title}
@@ -2088,32 +2146,22 @@ bwiki: https://${this.config.domain}/bw/88888888`;
2088
2146
  });
2089
2147
  replyMsg += `
2090
2148
  ❗️ 提示:超时将静默结束,无任何回应`;
2091
- await this.sendResponse(session, replyMsg);
2092
- const userInput = await session.prompt(15e3);
2149
+ await this.renderer.send(session, replyMsg);
2150
+ const userInput = await session?.prompt(15e3);
2093
2151
  if (!userInput) return;
2094
2152
  const selectNum = parseInt(userInput.trim(), 10);
2095
2153
  if (isNaN(selectNum) || selectNum < 1 || selectNum > resultCount) {
2096
- return this.sendResponse(
2154
+ return this.renderer.send(
2097
2155
  session,
2098
2156
  `❌ 输入无效!请输入 1-${resultCount} 之间的数字序号`
2099
2157
  );
2100
2158
  }
2101
2159
  const selected = matches[selectNum - 1];
2102
- return this.renderResultMessage(
2103
- session,
2104
- selected,
2105
- "✅ 选择成功"
2106
- );
2160
+ return this.renderer.resultMessage(session, selected, "✅ 选择成功");
2107
2161
  }
2108
2162
  };
2109
- ((QueryCommands2) => {
2110
- QueryCommands2.Config = import_koishi9.Schema.object({
2111
- domain: import_koishi9.Schema.string().description("你的短链域名(必填,如:klei.vip)").default("klei.vip")
2112
- });
2113
- })(QueryCommands || (QueryCommands = {}));
2114
2163
 
2115
2164
  // src/plugins/updateCommands.ts
2116
- var import_koishi10 = require("koishi");
2117
2165
  var UpdateCommands = class {
2118
2166
  constructor(ctx, config) {
2119
2167
  this.ctx = ctx;
@@ -2152,7 +2200,7 @@ var UpdateCommands = class {
2152
2200
  aplimit: "max"
2153
2201
  });
2154
2202
  logger.info("主站页面查询成功");
2155
- const pages = res.query.allpages || [];
2203
+ const pages = res.query?.allpages || [];
2156
2204
  const pageData = pages.map((page) => {
2157
2205
  const { pinyin_full, pinyin_first } = generatePinyinInfo(page.title);
2158
2206
  return {
@@ -2170,33 +2218,33 @@ var UpdateCommands = class {
2170
2218
  }
2171
2219
  registerCommands(ctx) {
2172
2220
  ctx.command("update", "更新本地页面缓存(主站)", { authority: 2 }).action(async ({ session }) => {
2173
- await session.execute("update.status");
2221
+ await session?.execute("update.status");
2174
2222
  try {
2175
2223
  const result = await this.updatePageCache();
2176
- session.send(`✅ 检索到 ${result.count} 个页面,已更新至数据库`);
2224
+ session?.send(`✅ 检索到 ${result.count} 个页面,已更新至数据库`);
2177
2225
  } catch (err) {
2178
2226
  this.log.error("主站缓存更新失败", err);
2179
- session.send("❌ 主站缓存更新失败,请联系管理员查看日志");
2227
+ session?.send("❌ 主站缓存更新失败,请联系管理员查看日志");
2180
2228
  }
2181
2229
  });
2182
2230
  ctx.command("update.delete", "删除本地页面缓存", { authority: 4 }).action(async ({ session }) => {
2183
2231
  try {
2184
2232
  const count = await ctx.database.remove("wikipages", {});
2185
- session.send(`✅ 已删除 ${count.removed} 条本地缓存`);
2233
+ session?.send(`✅ 已删除 ${count.removed} 条本地缓存`);
2186
2234
  logger.info(`已删除 ${count.removed} 条本地缓存`);
2187
2235
  } catch (err) {
2188
2236
  this.log.error("删除缓存失败", err);
2189
- session.send("❌ 删除缓存失败,请联系管理员查看日志");
2237
+ session?.send("❌ 删除缓存失败,请联系管理员查看日志");
2190
2238
  }
2191
2239
  });
2192
2240
  ctx.command("update.status", "查询本地缓存数量", { authority: 1 }).action(async ({ session }) => {
2193
2241
  try {
2194
2242
  const pages = await ctx.database.get("wikipages", {});
2195
- session.send(`📊 数据库中缓存了 ${pages.length} 条页面`);
2243
+ session?.send(`📊 数据库中缓存了 ${pages.length} 条页面`);
2196
2244
  logger.info(`数据库中缓存了 ${pages.length} 条页面`);
2197
2245
  } catch (err) {
2198
2246
  this.log.error("查询缓存状态失败", err);
2199
- session.send("❌ 查询缓存状态失败,请联系管理员查看日志");
2247
+ session?.send("❌ 查询缓存状态失败,请联系管理员查看日志");
2200
2248
  }
2201
2249
  });
2202
2250
  ctx.command("redirect <pageName> <targetPageName>", "添加原站点重定向", {
@@ -2212,18 +2260,18 @@ var UpdateCommands = class {
2212
2260
  "来自qq机器人的添加重定向页面请求"
2213
2261
  );
2214
2262
  logger.info(`已为 ${pageName} 添加重定向至 ${targetPageName}`);
2215
- session.send(`✅ 已尝试添加重定向 ${pageName} -> ${targetPageName}`);
2216
- await session.execute(`update`);
2263
+ session?.send(`✅ 已尝试添加重定向 ${pageName} -> ${targetPageName}`);
2264
+ await session?.execute(`update`);
2217
2265
  } catch (err) {
2218
2266
  this.log.error(
2219
2267
  `添加重定向 ${pageName} -> ${targetPageName} 失败`,
2220
2268
  err
2221
2269
  );
2222
- session.send(`❌ 添加重定向失败,请联系管理员查看日志`);
2270
+ session?.send(`❌ 添加重定向失败,请联系管理员查看日志`);
2223
2271
  }
2224
2272
  });
2225
2273
  ctx.command("relogin", "手动重新登录 Wiki 机器人", { authority: 2 }).alias("重新登录").action(async ({ session }) => {
2226
- session.send("🚀 开始重新登录 Wiki 机器人...");
2274
+ session?.send("🚀 开始重新登录 Wiki 机器人...");
2227
2275
  try {
2228
2276
  const result = await ctx.wikiBot.relogin();
2229
2277
  let message = "📋 重新登录结果:\n";
@@ -2236,20 +2284,14 @@ var UpdateCommands = class {
2236
2284
  } else {
2237
2285
  message += "\n💥 所有 Wiki 机器人登录都失败了,请检查配置";
2238
2286
  }
2239
- session.send(message);
2287
+ session?.send(message);
2240
2288
  } catch (err) {
2241
2289
  this.log.error("重新登录失败", err);
2242
- session.send("❌ 重新登录过程中发生错误,请查看日志");
2290
+ session?.send("❌ 重新登录过程中发生错误,请查看日志");
2243
2291
  }
2244
2292
  });
2245
2293
  }
2246
2294
  };
2247
- ((UpdateCommands2) => {
2248
- UpdateCommands2.Config = import_koishi10.Schema.object({
2249
- logsUrl: import_koishi10.Schema.string().description("日志查看地址").default("https://klei.vip/onilogs"),
2250
- updateCron: import_koishi10.Schema.string().description("页面缓存自动更新 cron 表达式(默认每天凌晨 2 点)").default("0 2 * * *")
2251
- });
2252
- })(UpdateCommands || (UpdateCommands = {}));
2253
2295
 
2254
2296
  // src/plugins/todoList.ts
2255
2297
  var TodoList = class {
@@ -2329,7 +2371,7 @@ var TodoList = class {
2329
2371
  params.continue = "-||";
2330
2372
  }
2331
2373
  const res = await this.apiCallWithRetry(
2332
- () => this.ctx.wikiBot.ggbot.query(params)
2374
+ () => this.ctx.wikiBot.getGGBot().query(params)
2333
2375
  );
2334
2376
  if (res.query?.allpages) {
2335
2377
  modules.push(...res.query.allpages);
@@ -2343,28 +2385,24 @@ var TodoList = class {
2343
2385
  throw err;
2344
2386
  }
2345
2387
  }
2346
- sleep(ms) {
2347
- return new Promise((resolve2) => setTimeout(resolve2, ms));
2348
- }
2349
- async apiCallWithRetry(apiCall, maxRetries = 3) {
2350
- for (let i = 0; i < maxRetries; i++) {
2351
- try {
2352
- return await apiCall();
2353
- } catch (err) {
2354
- if (i === maxRetries - 1) {
2355
- throw err;
2356
- }
2357
- this.log.warn(`API 调用失败,正在重试 (${i + 1}/${maxRetries})...`);
2358
- await this.sleep(2e3);
2359
- }
2360
- }
2361
- throw new Error("Max retries exceeded");
2388
+ apiCallWithRetry(apiCall, maxRetries = 3) {
2389
+ return withRetry(apiCall, {
2390
+ attempts: maxRetries,
2391
+ delayMs: 2e3,
2392
+ onRetry: /* @__PURE__ */ __name((_error, attempt, attempts) => this.log.warn(`API 调用失败,正在重试 (${attempt}/${attempts})...`), "onRetry")
2393
+ });
2362
2394
  }
2363
- async getModuleRevisionFromGG(title) {
2395
+ /**
2396
+ * 读取指定站点上模块页面的最新修订信息。
2397
+ * 原先 gg / bwiki 各有一份逐行相同的实现,只有站点不同 —— 合并为按站点寻址。
2398
+ */
2399
+ async getModuleRevision(site, title) {
2400
+ const isGG = site === "gg";
2401
+ const bot = isGG ? this.ctx.wikiBot.getGGBot() : this.ctx.wikiBot.getBWikiBot();
2364
2402
  try {
2365
- await this.sleep(1e3);
2403
+ await (0, import_koishi3.sleep)(1e3);
2366
2404
  const res = await this.apiCallWithRetry(
2367
- () => this.ctx.wikiBot.ggbot.query({
2405
+ () => bot.query({
2368
2406
  action: "query",
2369
2407
  format: "json",
2370
2408
  prop: "revisions",
@@ -2374,47 +2412,15 @@ var TodoList = class {
2374
2412
  rvlimit: "1"
2375
2413
  })
2376
2414
  );
2377
- if (res.query?.pages && res.query.pages.length > 0) {
2378
- const page = res.query.pages[0];
2379
- if (page.revisions && page.revisions.length > 0) {
2380
- return {
2381
- ...page,
2382
- revision: page.revisions[0]
2383
- };
2384
- }
2385
- }
2386
- return null;
2415
+ const page = res.query?.pages?.[0];
2416
+ const revisions = page?.revisions;
2417
+ if (!revisions?.length) return null;
2418
+ return { title: page?.title, revisions, revision: revisions[0] };
2387
2419
  } catch (err) {
2388
- this.log.error(`从 wiki.gg 获取模块 ${title} 的修订信息失败`, err);
2389
- return null;
2390
- }
2391
- }
2392
- async getModuleRevisionFromBWiki(title) {
2393
- try {
2394
- await this.sleep(1e3);
2395
- const res = await this.apiCallWithRetry(
2396
- () => this.ctx.wikiBot.bwikibot.query({
2397
- action: "query",
2398
- format: "json",
2399
- prop: "revisions",
2400
- titles: title,
2401
- formatversion: "2",
2402
- rvprop: "timestamp|user|comment",
2403
- rvlimit: "1"
2404
- })
2420
+ this.log.error(
2421
+ `从 ${isGG ? "wiki.gg" : "bwiki"} 获取模块 ${title} 的修订信息失败`,
2422
+ err
2405
2423
  );
2406
- if (res.query?.pages && res.query.pages.length > 0) {
2407
- const page = res.query.pages[0];
2408
- if (page.revisions && page.revisions.length > 0) {
2409
- return {
2410
- ...page,
2411
- revision: page.revisions[0]
2412
- };
2413
- }
2414
- }
2415
- return null;
2416
- } catch (err) {
2417
- this.log.error(`从 bwikia 获取模块 ${title} 的修订信息失败`, err);
2418
2424
  return null;
2419
2425
  }
2420
2426
  }
@@ -2429,7 +2435,7 @@ var TodoList = class {
2429
2435
  let added = 0;
2430
2436
  let updated = 0;
2431
2437
  for (const module2 of modules) {
2432
- const moduleData = await this.getModuleRevisionFromGG(module2.title);
2438
+ const moduleData = await this.getModuleRevision("gg", module2.title);
2433
2439
  if (!moduleData || !moduleData.revision) {
2434
2440
  continue;
2435
2441
  }
@@ -2474,8 +2480,8 @@ var TodoList = class {
2474
2480
  let synced = 0;
2475
2481
  for (const todo of todos) {
2476
2482
  checked++;
2477
- const ggRevision = await this.getModuleRevisionFromGG(todo.title);
2478
- const bwikiRevision = await this.getModuleRevisionFromBWiki(todo.title);
2483
+ const ggRevision = await this.getModuleRevision("gg", todo.title);
2484
+ const bwikiRevision = await this.getModuleRevision("bwiki", todo.title);
2479
2485
  if (!ggRevision || !ggRevision.revision) {
2480
2486
  continue;
2481
2487
  }
@@ -2510,12 +2516,12 @@ var TodoList = class {
2510
2516
  }
2511
2517
  registerCommands(ctx) {
2512
2518
  ctx.command("todolist", "缺氧 TodoList").alias("todo").action(async ({ session }) => {
2513
- await session.execute("todo.list");
2519
+ await session?.execute("todo.list");
2514
2520
  });
2515
2521
  ctx.command("todo.list", "查看 TodoList").alias("todo.l").action(async ({ session }) => {
2516
2522
  return "📋 请访问 https://klei.vip/onitodos 进行 TodoList 管理";
2517
2523
  });
2518
- ctx.command("todo.add <title>", "添加待办事项").alias("todo.a").option("content", "-c <content>").option("createdBy", "-u <createdBy>").action(async ({ session, options }, title) => {
2524
+ ctx.command("todo.add <title>", "添加待办事项").alias("todo.a").option("content", "-c <content>").option("createdBy", "-u <createdBy>").action(async ({ session, options = {} }, title) => {
2519
2525
  if (!title) {
2520
2526
  return "❌ 请提供标题!用法:todo.add <标题> [-c <内容>] [-u <创建人>]";
2521
2527
  }
@@ -2535,7 +2541,7 @@ var TodoList = class {
2535
2541
  return "❌ 添加待办事项失败,请查看日志";
2536
2542
  }
2537
2543
  });
2538
- ctx.command("todo.edit <id>", "编辑待办事项").alias("todo.e").option("title", "-t <title>").option("content", "-c <content>").option("createdBy", "-u <createdBy>").action(async ({ session, options }, idStr) => {
2544
+ ctx.command("todo.edit <id>", "编辑待办事项").alias("todo.e").option("title", "-t <title>").option("content", "-c <content>").option("createdBy", "-u <createdBy>").action(async ({ session, options = {} }, idStr) => {
2539
2545
  const id = Number(idStr);
2540
2546
  if (!id || isNaN(id)) {
2541
2547
  return "❌ 请提供有效的 ID!";
@@ -2692,22 +2698,20 @@ var TodoList = class {
2692
2698
 
2693
2699
  // src/index.ts
2694
2700
  var name = "oni-sync-bot";
2695
- var Config = import_koishi11.Schema.intersect([
2696
- WikiBotService.Config,
2697
- RouteRedirect.Config,
2698
- SyncCommands.Config,
2699
- QueryCommands.Config,
2700
- UpdateCommands.Config
2701
- ]);
2701
+ var SUB_PLUGINS = [
2702
+ WikiBotService,
2703
+ ConsoleLogProvider,
2704
+ DatabaseExtension,
2705
+ RouteRedirect,
2706
+ SyncCommands,
2707
+ QueryCommands,
2708
+ UpdateCommands,
2709
+ TodoList
2710
+ ];
2702
2711
  function apply(ctx, config) {
2703
- ctx.plugin(WikiBotService, config);
2704
- ctx.plugin(ConsoleLogProvider);
2705
- ctx.plugin(DatabaseExtension);
2706
- ctx.plugin(RouteRedirect, config);
2707
- ctx.plugin(SyncCommands, config);
2708
- ctx.plugin(QueryCommands, config);
2709
- ctx.plugin(UpdateCommands, config);
2710
- ctx.plugin(TodoList);
2712
+ for (const plugin of SUB_PLUGINS) {
2713
+ ctx.plugin(plugin, config);
2714
+ }
2711
2715
  ctx.inject(["console"], (ctx2) => {
2712
2716
  ctx2.console.addEntry({
2713
2717
  dev: (0, import_path.resolve)(__dirname, "../client/index.ts"),