dsh-mikan 0.2.3 → 0.3.0

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/index.js CHANGED
@@ -11,10 +11,26 @@
11
11
  * file instead of a schemastery `Config`.
12
12
  */
13
13
  import fs from 'node:fs/promises';
14
+ import os from 'node:os';
14
15
  import path from 'node:path';
16
+ import { fileURLToPath } from 'node:url';
17
+
18
+ const PLUGIN_DIR = path.dirname(fileURLToPath(import.meta.url));
15
19
 
16
20
  import { DEFAULT_CONFIG, MIKAN_INSIDE, MIKAN_OUTSIDE, BGM_API, NYAA_OFFICIAL, COMMON_PROXY_PORTS } from './lib/constants.js';
17
21
  import { fetchBgmMirrors } from './lib/mirrors.js';
22
+ import { resolveNames } from './lib/names.js';
23
+ import { scanLibrary, listVideoFiles, parseMediaFile } from './lib/library.js';
24
+ import { createNyaaClient } from './lib/nyaa.js';
25
+ import {
26
+ loadCatalog,
27
+ saveCatalog,
28
+ findSeriesInCatalog,
29
+ indexedSeasons,
30
+ setSeason,
31
+ recallNames,
32
+ rememberNames,
33
+ } from './lib/catalog.js';
18
34
  import {
19
35
  createMikanClient,
20
36
  detectMikanSource,
@@ -30,7 +46,8 @@ import { createBitCometClient } from './lib/bitcomet.js';
30
46
  import { createQbittorrentClient } from './lib/qbittorrent.js';
31
47
  import { resolveAirDate } from './lib/airdate.js';
32
48
  import * as store from './lib/store.js';
33
- import { probeProxy, parseProxy, probePort } from './lib/net.js';
49
+ import { probeProxy, parseProxy, probePort, fetchText } from './lib/net.js';
50
+ import { buildIndexFromData, saveBgmIndex, loadBgmIndex, lookupTitle, bgmIndexStatus } from './lib/bgmdata.js';
34
51
  import { defineTool } from './lib/tooldef.js';
35
52
 
36
53
  const OBJ = { type: 'object' };
@@ -141,7 +158,7 @@ export const inject = ['tools', 'webServer'];
141
158
  export async function apply(ctx) {
142
159
  const logger = ctx.logger;
143
160
  let env = null;
144
- const ENV_TTL = 5 * 60 * 1000;
161
+ const ENV_TTL = 60 * 1000;
145
162
 
146
163
  async function detectEnv(force = false) {
147
164
  const cfg = await loadConfig();
@@ -254,7 +271,8 @@ export async function apply(ctx) {
254
271
  }
255
272
  nyaaReason = r.reason || 'unreachable';
256
273
  }
257
- env = {
274
+ const prev = env;
275
+ const next = {
258
276
  at: Date.now(),
259
277
  proxy,
260
278
  bgmOk,
@@ -273,15 +291,52 @@ export async function apply(ctx) {
273
291
  // to be reachable through a direct mirror.
274
292
  mode: (bgmViaProxy || mikan.viaProxy) ? 'proxy' : 'direct',
275
293
  };
294
+ // Remember the last mirror/mode change so `mikan_status` can report that a
295
+ // switch happened instead of silently presenting the new state as always so.
296
+ const changed = Boolean(prev) && (prev.mikanBase !== next.mikanBase || prev.mode !== next.mode);
297
+ next.transition = changed
298
+ ? {
299
+ fromMode: prev.mode,
300
+ fromMikan: prev.mikanBase,
301
+ toMode: next.mode,
302
+ toMikan: next.mikanBase,
303
+ at: new Date().toISOString(),
304
+ }
305
+ : (prev?.transition || null);
306
+ env = next;
307
+ if (changed) {
308
+ logger?.info?.(`[dsh-mikan] switched ${prev.mikanBase}/${prev.mode} → ${next.mikanBase}/${next.mode}`);
309
+ }
276
310
  logger?.info?.(`[dsh-mikan] env=${env.mode} mikan=${env.mikanBase} bgm=${bgmOk}`);
277
311
  return env;
278
312
  }
279
313
 
280
314
  function mikanClient(cfg) {
281
- return createMikanClient({
315
+ const client = createMikanClient({
282
316
  base: env?.mikanBase || MIKAN_INSIDE,
283
317
  proxy: env?.mikanViaProxy ? cfg.proxy : '',
284
318
  });
319
+ const rawGet = client.get.bind(client);
320
+ // A failing request usually means the cached mirror went stale — typically
321
+ // because the proxy was just toggled and the inside/outside preference
322
+ // flipped. Drop the cache, re-probe, and retry once so a mode switch does
323
+ // not surface as an error to the caller.
324
+ client.get = async (path) => {
325
+ try {
326
+ return await rawGet(path);
327
+ } catch (err) {
328
+ env = null;
329
+ try {
330
+ await detectEnv(true);
331
+ } catch { /* keep the original error */ }
332
+ const fresh = createMikanClient({
333
+ base: env?.mikanBase || MIKAN_INSIDE,
334
+ proxy: env?.mikanViaProxy ? cfg.proxy : '',
335
+ });
336
+ return fresh.get(path);
337
+ }
338
+ };
339
+ return client;
285
340
  }
286
341
 
287
342
  async function bitcometClient() {
@@ -380,6 +435,391 @@ export async function apply(ctx) {
380
435
  }
381
436
 
382
437
  /** Level 1: a season's bangumi grouped by weekday (titles only). */
438
+ /**
439
+ * Keyword search.
440
+ *
441
+ * Mikan's search endpoint returns individual releases, never series. We
442
+ * therefore group releases by their parsed series name, classify each one as
443
+ * a collection or a single episode, and — when the series happens to be in
444
+ * the current season list — attach its bangumiId so callers can jump to the
445
+ * subgroup view.
446
+ */
447
+ /**
448
+ * Pull a stable series name out of a release title.
449
+ *
450
+ * `parseReleaseTitle` truncates at the episode marker, which leaves the whole
451
+ * title intact for collections (no marker). Here we instead take the first
452
+ * CJK-led run, which yields "机动战士高达00" from both a single-episode title
453
+ * and a BOX title.
454
+ */
455
+ function extractSeriesName(title) {
456
+ let s = String(title || '').trim();
457
+ // Strip the leading subgroup bracket.
458
+ s = s.replace(/^\s*[[【][^\]】]{1,60}[\]】]\s*/, '');
459
+ // Many groups wrap the title itself in brackets: take the first bracketed
460
+ // segment rather than the raw remainder.
461
+ const bracket = s.match(/^\s*[[【]([^\]】]{2,100})[\]】]/);
462
+ if (bracket) s = bracket[1];
463
+ else s = s.split(/[//]/)[0] || s;
464
+ const cleaned = s
465
+ .replace(/\s*(?:WebRip|WEB-DL|WEB|BDRip|BDRIP|Blu-?ray|TV|Movie|MOVIE|OVA|OAD|SP|Fin|END|\d{3,4}[pP]|HEVC|x26[45]|AVC|AAC|FLAC|MKV|MP4|简繁.*|繁简.*|简日.*|繁日.*|简中.*|繁中.*|内封.*|外挂.*|日语.*|中日.*)\b.*$/i, '')
466
+ .trim();
467
+ const candidate = cleaned || s.trim();
468
+ // Generic labels and bare numbers are not series names.
469
+ if (/^(剧场版|劇場版|电影|電影|TV|OVA|OAD|SP|合集|全集|新番|月新番|七月新番|番外篇?|总集篇|特别篇|特別篇|BDRIP|\d{4})$/i.test(candidate)) return '';
470
+ if (candidate.length >= 2) return candidate;
471
+ return '';
472
+ }
473
+
474
+ /** Season lists cached for an hour; resolving ids can touch several seasons. */
475
+ const seasonCache = new Map();
476
+
477
+ async function seasonItemsCached(year, season) {
478
+ const key = `${year}${season}`;
479
+ const hit = seasonCache.get(key);
480
+ if (hit && Date.now() - hit.at < 60 * 60 * 1000) return hit.items;
481
+ const groups = await seasonList(year, season);
482
+ const items = (Array.isArray(groups) ? groups : []).flatMap((g) => g.items || []);
483
+ seasonCache.set(key, { at: Date.now(), items });
484
+ return items;
485
+ }
486
+
487
+ function matchSeasonItem(items, name) {
488
+ const key = normTitle(name);
489
+ if (!key) return null;
490
+ const exact = items.find((it) => normTitle(it.title) === key);
491
+ if (exact) return exact;
492
+ return items.find((it) => {
493
+ const n = normTitle(it.title);
494
+ return n && (n.includes(key) || key.includes(n));
495
+ }) || null;
496
+ }
497
+
498
+ /**
499
+ * Collect every season where a series name matches.
500
+ *
501
+ * Mikan's search indexes releases, so one keyword can span several seasons of
502
+ * the same franchise (青之芦苇 exists in 2022春 and 2026秋). We therefore look
503
+ * in the current season *and* in the season implied by Bangumi's first air
504
+ * date, returning all hits instead of stopping at the first one.
505
+ */
506
+ /**
507
+ * Fetch every season's series list into the local catalog.
508
+ *
509
+ * Done once (or per new season); afterwards id lookups are pure file reads.
510
+ */
511
+ async function buildCatalog({ years = 10, force = false } = {}) {
512
+ const catalog = await loadCatalog();
513
+ const now = new Date();
514
+ const curYear = now.getFullYear();
515
+ const startYear = Math.max(2012, curYear - Math.max(1, Math.min(Number(years) || 10, 20)));
516
+ const plan = [];
517
+ for (let y = startYear; y <= curYear; y += 1) {
518
+ for (const s of ['冬', '春', '夏', '秋']) plan.push({ y, s, key: `${y}${s}` });
519
+ }
520
+ const built = [];
521
+ const failed = [];
522
+ await mapLimit(plan, 5, async ({ y, s, key }) => {
523
+ if (!force && Array.isArray(catalog.seasons[key]) && catalog.seasons[key].length > 0) return;
524
+ try {
525
+ const groups = await seasonList(y, s);
526
+ const items = (Array.isArray(groups) ? groups : []).flatMap((g) => g.items || []);
527
+ setSeason(catalog, key, items);
528
+ if (items.length > 0) built.push(key);
529
+ } catch {
530
+ failed.push(key);
531
+ }
532
+ });
533
+ catalog.updatedAt = new Date().toISOString();
534
+ await saveCatalog(catalog);
535
+ let series = 0;
536
+ for (const key of Object.keys(catalog.seasons)) series += (catalog.seasons[key] || []).length;
537
+ return {
538
+ ok: true,
539
+ built: built.length,
540
+ failed: failed.length,
541
+ seasons: Object.keys(catalog.seasons).length,
542
+ series,
543
+ };
544
+ }
545
+
546
+ async function resolveSeriesIds(name, deep = false) {
547
+ // Local catalog first: every indexed season, zero requests.
548
+ try {
549
+ const catalog = await loadCatalog();
550
+ const local = findSeriesInCatalog(catalog, name);
551
+ if (local.length > 0) return local;
552
+ } catch { /* fall through to the network path */ }
553
+
554
+ const out = [];
555
+ const seen = new Set();
556
+ const add = (seasonLabel, item) => {
557
+ if (!item || !item.id || seen.has(item.id)) return;
558
+ seen.add(item.id);
559
+ out.push({ season: seasonLabel, bangumiId: item.id, title: item.title });
560
+ };
561
+
562
+ const now = new Date();
563
+ const month = now.getMonth() + 1;
564
+ const curSeason = month <= 3 ? '冬' : month <= 6 ? '春' : month <= 9 ? '夏' : '秋';
565
+ try {
566
+ const items = await seasonItemsCached(now.getFullYear(), curSeason);
567
+ add(`${now.getFullYear()}${curSeason}`, matchSeasonItem(items, name));
568
+ } catch { /* best-effort */ }
569
+
570
+ let airDate = '';
571
+ try {
572
+ const air = await resolveAirDate({
573
+ names: [name],
574
+ proxy: env?.bgmViaProxy ? (env?.proxy || '') : '',
575
+ bgmBase: env?.bgmBase || '',
576
+ });
577
+ if (air.ok && air.airDate) {
578
+ airDate = air.airDate;
579
+ const d = new Date(air.airDate);
580
+ const y = d.getFullYear();
581
+ const m = d.getMonth() + 1;
582
+ const s = m <= 3 ? '冬' : m <= 6 ? '春' : m <= 9 ? '夏' : '秋';
583
+ const items = await seasonItemsCached(y, s);
584
+ add(`${y}${s}`, matchSeasonItem(items, name));
585
+ }
586
+ } catch { /* best-effort */ }
587
+
588
+ // Deep mode walks every season from the first air year (or ten years back
589
+ // when Bangumi has no date) so mid-franchise seasons are not skipped.
590
+ if (deep) {
591
+ const curYear = now.getFullYear();
592
+ let startYear = curYear - 10;
593
+ if (airDate) {
594
+ const y = new Date(airDate).getFullYear();
595
+ if (Number.isFinite(y) && y >= 2012 && y <= curYear) startYear = y;
596
+ }
597
+ const plan = [];
598
+ for (let y = startYear; y <= curYear; y += 1) {
599
+ for (const s of ['冬', '春', '夏', '秋']) plan.push({ y, s });
600
+ }
601
+ await mapLimit(plan, 6, async ({ y, s }) => {
602
+ try {
603
+ const items = await seasonItemsCached(y, s);
604
+ add(`${y}${s}`, matchSeasonItem(items, name));
605
+ } catch { /* try next season */ }
606
+ });
607
+ }
608
+
609
+ return out;
610
+ }
611
+
612
+ /** Parse a formatted size ("594.5MB", "13.8GB") back into bytes. */
613
+ function parseBytes(text) {
614
+ const m = String(text || '').match(/([\d.]+)\s*([KMGT])i?B/i);
615
+ if (!m) return 0;
616
+ const value = Number(m[1]);
617
+ const unit = m[2].toUpperCase();
618
+ const mult = { K: 1024, M: 1024 ** 2, G: 1024 ** 3, T: 1024 ** 4 }[unit] || 1;
619
+ return value * mult;
620
+ }
621
+
622
+ /**
623
+ * Build per-subgroup bundles from each subgroup's complete release list.
624
+ *
625
+ * Some groups never publish a collection, so a search only shows isolated
626
+ * episodes. For the groups that appear in the results we resolve the series
627
+ * id, find that subgroup on the bangumi page, then read its full list to
628
+ * report真 the episode range, gaps and total size — clearly distinct from a
629
+ * real collection, which is one hash.
630
+ */
631
+ async function buildFullBundles(items, maxSeries = 3, maxGroups = 3) {
632
+ const wanted = new Map();
633
+ for (const it of items) {
634
+ if (!it.series || !it.subgroup) continue;
635
+ const key = normTitle(it.series);
636
+ if (!wanted.has(key)) wanted.set(key, { series: it.series, groups: new Set() });
637
+ wanted.get(key).groups.add(it.subgroup);
638
+ }
639
+
640
+ const bundles = [];
641
+ const cfg = await loadConfig();
642
+ const dedupe = new Set();
643
+ for (const { series, groups } of [...wanted.values()].slice(0, maxSeries)) {
644
+ let bangumiId = '';
645
+ try {
646
+ const ids = await resolveSeriesIds(series);
647
+ bangumiId = ids[0]?.bangumiId || '';
648
+ } catch { /* no id, skip */ }
649
+ if (!bangumiId) continue;
650
+
651
+ let page;
652
+ try {
653
+ page = parseBangumiPage(await mikanClient(cfg).get(`/Home/Bangumi/${bangumiId}`), bangumiId);
654
+ } catch { continue; }
655
+
656
+ for (const gname of [...groups].slice(0, maxGroups)) {
657
+ const sg = (page.subgroups || []).find((s) => normTitle(s.name) === normTitle(gname));
658
+ if (!sg) continue;
659
+ // The same subgroup can appear under several series buckets; keep one.
660
+ const key = `${bangumiId}|${sg.subgroupId}`;
661
+ if (dedupe.has(key)) continue;
662
+ dedupe.add(key);
663
+ let rel;
664
+ try {
665
+ rel = await works(bangumiId, sg.subgroupId, 500);
666
+ } catch { continue; }
667
+ // A collection also parses to an episode number ("S05 | 01-13" → 13),
668
+ // so exclude collection-shaped titles before counting episodes.
669
+ const eps = (rel.items || []).filter((r) => {
670
+ if (!r.episode || !/^\d+$/.test(String(r.episode))) return false;
671
+ const t = r.title || '';
672
+ if (/全集|COMPLETE\s*BOX|\[Fin\]|完结|合集|TV\s*[&++]\s*|剧场版|Movie|MOIVE|S\d\b/i.test(t)) return false;
673
+ if (/\b\d{1,2}\s*-\s*\d{1,3}\b/.test(t)) return false;
674
+ return true;
675
+ });
676
+ if (eps.length < 2) continue;
677
+ const nums = [...new Set(eps.map((r) => Number(r.episode)))].sort((a, b) => a - b);
678
+ const present = new Set(nums);
679
+ const missing = [];
680
+ for (let i = nums[0]; i <= nums[nums.length - 1]; i += 1) if (!present.has(i)) missing.push(i);
681
+ const bytes = eps.reduce((sum, r) => sum + parseBytes(r.size), 0);
682
+ bundles.push({
683
+ series,
684
+ bangumiId,
685
+ subgroup: sg.name,
686
+ subgroupId: sg.subgroupId,
687
+ range: `${nums[0]}-${nums[nums.length - 1]}`,
688
+ count: nums.length,
689
+ episodes: nums,
690
+ missing,
691
+ totalSize: bytes > 0 ? fmtSize(bytes) : '',
692
+ note: '单集汇总(该组未发布合集)',
693
+ });
694
+ }
695
+ }
696
+ return bundles;
697
+ }
698
+
699
+ async function searchReleases(keyword, limit = 30, deep = false, full = false) {
700
+ const kw = String(keyword || '').trim();
701
+ if (!kw) return { keyword: kw, series: [], items: [], total: 0 };
702
+ await detectEnv();
703
+ const cfg = await loadConfig();
704
+
705
+ const searchOnce = async (term) => {
706
+ const html = await mikanClient(cfg).get('/Home/Search?searchstr=' + encodeURIComponent(term));
707
+ return parseSearchPage(html).resources;
708
+ };
709
+
710
+ let usedName = kw;
711
+ let autoCorrected = false;
712
+ let resources = await searchOnce(kw);
713
+
714
+ // Alternate translations (莉可莉丝 vs 莉可丽丝) return almost nothing on
715
+ // Mikan. When the first search is thin, retry with Bangumi's canonical
716
+ // Chinese title and keep whichever found more.
717
+ if (resources.length < 3) {
718
+ try {
719
+ const resolved = await resolveNames(kw, {
720
+ base: env?.bgmBase || cfg.bgmBase || '',
721
+ proxy: env?.bgmViaProxy ? (env.proxy || '') : '',
722
+ detail: false,
723
+ limit: 1,
724
+ });
725
+ const alt = resolved.ok && resolved.matches[0] ? String(resolved.matches[0].cn || '').trim() : '';
726
+ if (alt && alt !== kw) {
727
+ const retry = await searchOnce(alt);
728
+ if (retry.length > resources.length) {
729
+ resources = retry;
730
+ usedName = alt;
731
+ autoCorrected = true;
732
+ }
733
+ }
734
+ } catch { /* keep the original results */ }
735
+ }
736
+
737
+ // Reject substring false positives: "高达00" must not match "高达0083".
738
+ const esc = kw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
739
+ const exact = new RegExp(`(?:^|[^0-9])${esc}(?![0-9])`, 'i');
740
+ const suffixDigit = new RegExp(`${esc}[0-9]`, 'i');
741
+ const matches = (title) => {
742
+ if (!title) return false;
743
+ if (exact.test(title)) return true;
744
+ return !suffixDigit.test(title);
745
+ };
746
+
747
+ const isCollection = (title) => {
748
+ if (/全集|COMPLETE\s*BOX|\[Fin\]|完结|合集|TV\s*[&++]\s*|剧场版|Movie|MOIVE|S\d\b/i.test(title)) return true;
749
+ if (/\b\d{1,2}\s*-\s*\d{1,3}\b/.test(title)) return true;
750
+ return false;
751
+ };
752
+
753
+ const items = resources
754
+ .filter((r) => matches(r.title))
755
+ .map((r) => {
756
+ const title = r.title || '';
757
+ const seriesLike = /\bS\d\b|Season|BDRip|BDRIP|Blu-?ray/i.test(title) && !/\b\d{1,3}\s*\]/.test(title);
758
+ const SUB_LABEL = { simp: '简中', trad: '繁中', multi: '多字幕' };
759
+ const sub = r.subtitle || 'multi';
760
+ return {
761
+ source: 'mikan',
762
+ hash: r.hash,
763
+ title,
764
+ publisher: r.subgroup || '',
765
+ episode: r.episode || '',
766
+ size: r.size || '',
767
+ seeders: null,
768
+ category: SUB_LABEL[sub] || '多字幕',
769
+ date: r.date || '',
770
+ url: r.link || '',
771
+ // mikan-specific extras, kept for the language filters.
772
+ series: extractSeriesName(title),
773
+ subtitle: sub,
774
+ kind: isCollection(title) ? 'collection' : (r.episode ? 'episode' : (seriesLike ? 'season' : 'unknown')),
775
+ };
776
+ });
777
+
778
+ // Group by series name; ids come from the current season, then from the
779
+ // season implied by Bangumi's first air date.
780
+ const buckets = new Map();
781
+ for (const it of items) {
782
+ const key = normTitle(it.series) || '(未识别)';
783
+ if (!buckets.has(key)) buckets.set(key, { name: it.series || '(未识别)', items: [] });
784
+ buckets.get(key).items.push(it);
785
+ }
786
+ // Only the largest buckets can be real series; resolving every fragment
787
+ // would cost one or two requests each.
788
+ const ranked = [...buckets.entries()]
789
+ .sort((a, b) => b[1].items.length - a[1].items.length)
790
+ .slice(0, 5);
791
+ const ids = new Map();
792
+ await Promise.all(ranked.map(async ([key, bucket]) => {
793
+ if (key === '(未识别)') return;
794
+ ids.set(key, await resolveSeriesIds(bucket.name, deep));
795
+ }));
796
+ const series = [...buckets.entries()].map(([key, b]) => {
797
+ const seasons = ids.get(key) || [];
798
+ return {
799
+ name: b.name,
800
+ // First hit for convenience; `seasons` lists every match so franchise
801
+ // entries across different years are all reachable.
802
+ bangumiId: seasons[0]?.bangumiId || '',
803
+ seasons,
804
+ total: b.items.length,
805
+ collections: b.items.filter((i) => i.kind === 'collection').length,
806
+ episodes: b.items.filter((i) => i.kind === 'episode').length,
807
+ };
808
+ });
809
+
810
+ const cap = Math.max(1, Math.min(Number(limit) || 30, 100));
811
+ // Optional: per-subgroup episode bundles for groups that never publish a
812
+ // collection. Costs a couple of requests per series, so it is opt-in.
813
+ let bundles = [];
814
+ if (full) {
815
+ try {
816
+ bundles = await buildFullBundles(items);
817
+ } catch { /* aggregation is best-effort */ }
818
+ }
819
+
820
+ return { keyword: kw, usedName, autoCorrected, series, bundles, total: items.length, items: items.slice(0, cap) };
821
+ }
822
+
383
823
  async function seasonList(year, season) {
384
824
  await detectEnv();
385
825
  const cfg = await loadConfig();
@@ -522,6 +962,8 @@ export async function apply(ctx) {
522
962
  proxy: e.proxy || '(none)',
523
963
  bgm: { ok: e.bgmOk, reason: e.bgmReason },
524
964
  mikan: { base: e.mikanBase, viaProxy: e.mikanViaProxy, reason: e.mikanReason },
965
+ nyaa: { ok: e.nyaaOk, base: e.nyaaBase, viaProxy: e.nyaaViaProxy, reason: e.nyaaReason },
966
+ switch: e.transition || null,
525
967
  downloader: dl,
526
968
  savePath: cfg.savePath,
527
969
  checkIntervalMinutes: cfg.checkIntervalMinutes,
@@ -642,6 +1084,572 @@ export async function apply(ctx) {
642
1084
  },
643
1085
  }));
644
1086
 
1087
+ ctx.tools.register(defineTool({
1088
+ name: 'mikan_order',
1089
+ description: 'Queue releases in the current conversation\'s order list instead of downloading them. The user reviews the order in the "点单" tab; confirming there hands them to the downloader and clears them. Use this whenever the user has not yet confirmed a download.',
1090
+ parameters: {
1091
+ type: 'object',
1092
+ properties: {
1093
+ hashes: {
1094
+ type: 'array',
1095
+ description: '40-character info hashes to queue.',
1096
+ items: { type: 'string' },
1097
+ },
1098
+ items: {
1099
+ type: 'array',
1100
+ description: 'Optional display records; when omitted only hashes are queued.',
1101
+ items: {
1102
+ type: 'object',
1103
+ properties: {
1104
+ hash: { type: 'string' },
1105
+ title: { type: 'string' },
1106
+ episode: { type: 'string' },
1107
+ size: { type: 'string' },
1108
+ subtitle: { type: 'string' },
1109
+ },
1110
+ required: ['hash'],
1111
+ additionalProperties: false,
1112
+ },
1113
+ },
1114
+ },
1115
+ required: ['hashes'],
1116
+ additionalProperties: false,
1117
+ },
1118
+ output: { schema: OBJ, render: renderJson },
1119
+ async execute(args) {
1120
+ const given = Array.isArray(args.items) ? args.items : [];
1121
+ const byHash = new Map(given.map((i) => [String(i.hash || ''), i]));
1122
+ const items = (args.hashes || []).map((hash) => {
1123
+ const rec = byHash.get(String(hash)) || {};
1124
+ return {
1125
+ hash: String(hash),
1126
+ title: rec.title || '',
1127
+ episode: rec.episode || '',
1128
+ size: rec.size || '',
1129
+ subtitle: rec.subtitle || 'multi',
1130
+ source: 'mikan',
1131
+ };
1132
+ });
1133
+ const res = await store.addOrderItems('', items);
1134
+ return { ok: true, sessionId: res.sessionId, count: res.items.length, items: res.items };
1135
+ },
1136
+ }));
1137
+
1138
+ ctx.tools.register(defineTool({
1139
+ name: 'mikan_resolve_names',
1140
+ description: 'Resolve a series title into the names other sources index it under — Chinese, Japanese, English and aliases — via Bangumi. Call it before searching a source with a different naming convention: Mikan indexes Chinese titles, nyaa indexes Japanese ones.',
1141
+ parameters: {
1142
+ type: 'object',
1143
+ properties: {
1144
+ keyword: { type: 'string', description: 'Any known title, usually the Chinese name.' },
1145
+ detail: { type: 'boolean', description: 'Fetch subject details for English titles and aliases (one extra request per match). Defaults to true.' },
1146
+ },
1147
+ required: ['keyword'],
1148
+ additionalProperties: false,
1149
+ },
1150
+ output: { schema: OBJ, render: renderJson },
1151
+ async execute(args) {
1152
+ const e = await detectEnv();
1153
+ const cfg = await loadConfig();
1154
+ return await resolveNames(args.keyword, {
1155
+ base: e.bgmBase || cfg.bgmBase || '',
1156
+ proxy: e.bgmViaProxy ? (e.proxy || '') : '',
1157
+ detail: args.detail !== false,
1158
+ });
1159
+ },
1160
+ }));
1161
+
1162
+ ctx.tools.register(defineTool({
1163
+ name: 'mikan_catalog',
1164
+ description: 'Inspect or build the local season catalog. Building fetches each season\'s series list once; afterwards bangumi-id lookups are local file reads with no network requests.',
1165
+ parameters: {
1166
+ type: 'object',
1167
+ properties: {
1168
+ action: { type: 'string', enum: ['status', 'build'], description: 'status reports the index; build fetches missing seasons.' },
1169
+ years: { type: 'number', description: 'build: how many years back to index (default 10, max 20).' },
1170
+ force: { type: 'boolean', description: 'build: refetch seasons that are already indexed.' },
1171
+ },
1172
+ required: ['action'],
1173
+ additionalProperties: false,
1174
+ },
1175
+ output: { schema: OBJ, render: renderJson },
1176
+ async execute(args) {
1177
+ if (args.action === 'build') {
1178
+ return await buildCatalog({ years: args.years, force: args.force === true });
1179
+ }
1180
+ const catalog = await loadCatalog();
1181
+ const seasons = indexedSeasons(catalog).sort();
1182
+ let series = 0;
1183
+ for (const key of seasons) series += (catalog.seasons[key] || []).length;
1184
+ return {
1185
+ updatedAt: catalog.updatedAt || '',
1186
+ seasons: seasons.length,
1187
+ series,
1188
+ names: Object.keys(catalog.names || {}).length,
1189
+ latest: seasons.slice(-4),
1190
+ };
1191
+ },
1192
+ }));
1193
+
1194
+ /** First bracket segment of a nyaa title, unless it is a format marker. */
1195
+ function nyaaGroupOf(title) {
1196
+ const m = String(title || '').match(/^\s*[[【]([^\]】]{2,40})[\]】]/);
1197
+ if (!m) return '';
1198
+ const name = m[1].trim();
1199
+ if (/^(?:\d{3,4}p|[48]k|bd|web|dvd|hevc|avc|aac|flac|x26[45]|mkv|mp4|multi|dual)/i.test(name)) return '';
1200
+ return name;
1201
+ }
1202
+
1203
+ /** Episode number from the common nyaa title shapes (S01E08, "- 08", "[08]"). */
1204
+ function nyaaEpisodeOf(title) {
1205
+ const t = String(title || '');
1206
+ const patterns = [
1207
+ /\bS\d{1,2}E(\d{1,4})\b/i,
1208
+ /[-–—]\s*(\d{1,4})(?:\s|\[|\(|$)/,
1209
+ /[[【](\d{1,4})(?:v\d)?[\]】]/,
1210
+ ];
1211
+ for (const p of patterns) {
1212
+ const m = t.match(p);
1213
+ if (m) return String(Number(m[1]));
1214
+ }
1215
+ return '';
1216
+ }
1217
+
1218
+ /** Folder name used for the staging area inside a library workspace. */
1219
+ const STAGING_DIR = '下载中转站';
1220
+
1221
+ function seasonFolderFor(index) {
1222
+ return `Season ${index}`;
1223
+ }
1224
+
1225
+ /** Strip a trailing season marker so all seasons map to one base title. */
1226
+ function baseSeriesTitle(title) {
1227
+ return String(title || '')
1228
+ .replace(/\s*(?:第\s*[一二三四五六七八九十\d]{1,2}\s*[季期]|Season\s*\d{1,2}|\bS\d{1,2}\b)\s*$/i, '')
1229
+ .trim();
1230
+ }
1231
+
1232
+ /** Season number from a path or file name: folder "Season 2", "第二季", file "S2". */
1233
+ function seasonOf(pathOrName) {
1234
+ const t = String(pathOrName || '');
1235
+ const cn = { 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9, 十: 10 };
1236
+ // A "Season N" / "第N季" folder in the path is the most reliable signal.
1237
+ const folder = t.match(/[\\/](?:Season\s*(\d{1,2})|第\s*([一二三四五六七八九十\d]{1,2})\s*[季期])[\\/]/i);
1238
+ if (folder) return cn[folder[1] || folder[2]] || Number(folder[1] || folder[2]) || 1;
1239
+ const file = t.match(/\bS(\d{1,2})\b/i) || t.match(/第\s*([一二三四五六七八九十\d]{1,2})\s*[季期]/) || t.match(/Season\s*(\d{1,2})/i);
1240
+ if (!file) return 1;
1241
+ return cn[file[1]] || Number(file[1]) || 1;
1242
+ }
1243
+
1244
+ /** Special content type from a file name. */
1245
+ function specialTypeOf(fileName) {
1246
+ const t = String(fileName || '');
1247
+ if (/\b(movie|剧场版|劇場版|the movie)\b/i.test(t)) return 'movie';
1248
+ if (/\b(ova|oad)\b/i.test(t)) return 'ova';
1249
+ if (/\b(sp|special|特典)\b/i.test(t)) return 'special';
1250
+ return '';
1251
+ }
1252
+
1253
+ /** `【YYYY.M】` label from an ISO-ish date; month is 1-based without padding. */
1254
+ function yearMonthLabel(dateText) {
1255
+ const m = String(dateText || '').match(/^(\d{4})-(\d{1,2})/);
1256
+ if (!m) return '';
1257
+ return `【${m[1]}.${Number(m[2])}】`;
1258
+ }
1259
+
1260
+ /** `2026秋` → `【2026.10】` (冬=1, 春=4, 夏=7, 秋=10). */
1261
+ function seasonLabelOf(seasonKey) {
1262
+ const m = String(seasonKey || '').match(/^(\d{4})([冬春夏秋])/);
1263
+ if (!m) return '';
1264
+ const month = { 冬: 1, 春: 4, 夏: 7, 秋: 10 }[m[2]];
1265
+ return month ? `【${m[1]}.${month}】` : '';
1266
+ }
1267
+
1268
+ /**
1269
+ * Media library deployment and organisation.
1270
+ *
1271
+ * deploy : create the staging folder inside the chosen workspace and point
1272
+ * the downloader at it.
1273
+ * organize: move finished downloads from staging into
1274
+ * `<library>/【YYYY.M】Title/Season N/` folders, creating them as
1275
+ * needed. Dry-run unless `apply` is true.
1276
+ */
1277
+ async function deployLibrary(action, { library = '', apply = false } = {}) {
1278
+ const cfg = await loadConfig();
1279
+ // The library directory must be chosen explicitly. Deploying into whatever
1280
+ // directory happens to be current would turn a scratch workspace into a
1281
+ // media library and route every download into it.
1282
+ if (!library) {
1283
+ return {
1284
+ ok: false,
1285
+ action,
1286
+ reason: '请先指定媒体库目录(library),例如 D:\\Anime 或 E:\\番剧。不要用默认工作区当媒体库。',
1287
+ cwd: process.cwd(),
1288
+ };
1289
+ }
1290
+ const root = path.resolve(library);
1291
+ // Deploying into DSH's own directories must never happen: the default
1292
+ // workspace and the profile/config tree hold state the plugin must not mix
1293
+ // into downloads. Organisation may still run anywhere the user points it.
1294
+ if (action === 'deploy') {
1295
+ const forbidden = [
1296
+ path.join(os.homedir(), '.dsh'),
1297
+ path.join(os.homedir(), 'Documents', 'deepseek-harness', 'default-workspace'),
1298
+ path.resolve(process.cwd()),
1299
+ ];
1300
+ const isForbidden = forbidden.some((p) => root === p || root.startsWith(p + path.sep));
1301
+ if (isForbidden) {
1302
+ return {
1303
+ ok: false,
1304
+ action,
1305
+ reason: '不能用 DSH 的工作区或配置目录当媒体库,请另选一个专门的目录(如 D:\\Anime)。',
1306
+ library: root,
1307
+ };
1308
+ }
1309
+ }
1310
+ const staging = path.join(root, STAGING_DIR);
1311
+
1312
+ if (action === 'deploy') {
1313
+ await fs.mkdir(staging, { recursive: true });
1314
+ await saveConfig({ ...cfg, savePath: staging });
1315
+ return {
1316
+ ok: true,
1317
+ action: 'deploy',
1318
+ library: root,
1319
+ staging,
1320
+ savePath: staging,
1321
+ note: `请在下载器里确认默认下载目录已改为 ${staging};该文件夹不要删除或重命名。`,
1322
+ };
1323
+ }
1324
+
1325
+ const files = listVideoFiles(staging);
1326
+ const plan = [];
1327
+ const skipped = [];
1328
+ const seriesCache = new Map();
1329
+ const norm = (s) => normTitle(s);
1330
+ // Offline title index: resolves English/Japanese folder names to the
1331
+ // Chinese title and first air date without touching the network.
1332
+ const bgmIndex = await loadBgmIndex();
1333
+
1334
+ for (const full of files) {
1335
+ const name = path.basename(full);
1336
+ const parsed = parseMediaFile(name);
1337
+ const special = specialTypeOf(name);
1338
+ // Movies/OVAs have no episode number, so a special type alone is enough.
1339
+ if (!parsed.title || (!parsed.episode && !special)) {
1340
+ skipped.push({ file: name, reason: parsed.title ? '无法识别集数(非正片?)' : '无法识别番名' });
1341
+ continue;
1342
+ }
1343
+ if (!seriesCache.has(norm(parsed.title))) {
1344
+ let airDate = '';
1345
+ let cn = '';
1346
+ try {
1347
+ const resolved = await resolveNames(parsed.title, {
1348
+ base: env?.bgmBase || cfg.bgmBase || '',
1349
+ proxy: env?.bgmViaProxy ? (env.proxy || '') : '',
1350
+ detail: false,
1351
+ limit: 1,
1352
+ });
1353
+ const hit = resolved.matches?.[0];
1354
+ airDate = hit?.airDate || '';
1355
+ cn = hit?.cn || '';
1356
+ } catch { /* best-effort */ }
1357
+ seriesCache.set(norm(parsed.title), { airDate, cn });
1358
+ }
1359
+ const info = seriesCache.get(norm(parsed.title));
1360
+ // 1) Offline bangumi-data index — covers English and Japanese names too.
1361
+ // 2) Local season catalog.
1362
+ // 3) Bangumi air date.
1363
+ let label = '';
1364
+ let folderName = '';
1365
+ let displayTitle = '';
1366
+ const offline = lookupTitle(bgmIndex, baseSeriesTitle(parsed.title)) || lookupTitle(bgmIndex, parsed.title);
1367
+ if (offline) {
1368
+ label = yearMonthLabel(offline.begin);
1369
+ // Folder name follows the configured language preference.
1370
+ const pref = cfg.namePreference || 'cn';
1371
+ displayTitle = (pref === 'jp' ? offline.jp : pref === 'en' ? offline.en : pref === 'romaji' ? (offline.en || offline.jp) : offline.cn) || '';
1372
+ }
1373
+ if (!label) {
1374
+ try {
1375
+ const catalog = await loadCatalog();
1376
+ const local = findSeriesInCatalog(catalog, baseSeriesTitle(parsed.title));
1377
+ if (local.length > 0) {
1378
+ const earliest = [...local].sort((a, b) => String(a.season).localeCompare(String(b.season)))[0];
1379
+ label = seasonLabelOf(earliest.season);
1380
+ folderName = earliest.title;
1381
+ }
1382
+ } catch { /* best-effort */ }
1383
+ }
1384
+ if (!label && info.airDate) label = yearMonthLabel(info.airDate);
1385
+ if (!label) {
1386
+ skipped.push({ file: path.basename(full), reason: '查不到首播年月,无法确定【YYYY.M】' });
1387
+ continue;
1388
+ }
1389
+ const finalTitle = displayTitle || info.cn || folderName || baseSeriesTitle(parsed.title) || parsed.title;
1390
+ const seriesDir = path.join(root, `${label}${finalTitle}`);
1391
+ const season = seasonOf(full);
1392
+ let targetDir = seriesDir;
1393
+ if (special === 'movie') targetDir = path.join(seriesDir, 'Movie');
1394
+ else if (special === 'ova') targetDir = path.join(seriesDir, 'OVA');
1395
+ else if (special === 'special') targetDir = path.join(seriesDir, 'Special');
1396
+ else if (season > 1) targetDir = path.join(seriesDir, seasonFolderFor(season));
1397
+ plan.push({
1398
+ file: full,
1399
+ title: parsed.title,
1400
+ episode: parsed.episode,
1401
+ targetDir,
1402
+ targetFolder: path.relative(root, targetDir) || '.',
1403
+ });
1404
+ }
1405
+
1406
+ const dirs = [...new Set(plan.map((p) => p.targetDir))];
1407
+ const moved = [];
1408
+ const failed = [];
1409
+ if (apply) {
1410
+ for (const p of plan) {
1411
+ try {
1412
+ await fs.mkdir(p.targetDir, { recursive: true });
1413
+ const dest = path.join(p.targetDir, path.basename(p.file));
1414
+ await fs.rename(p.file, dest);
1415
+ moved.push(p.targetFolder);
1416
+ } catch (err) {
1417
+ failed.push({ file: path.basename(p.file), reason: err && err.message ? err.message : String(err) });
1418
+ }
1419
+ }
1420
+ }
1421
+
1422
+ return {
1423
+ ok: true,
1424
+ action: 'organize',
1425
+ applied: apply,
1426
+ library: root,
1427
+ staging,
1428
+ series: seriesCache.size,
1429
+ files: plan.length,
1430
+ dirs: dirs.map((d) => path.relative(root, d) || '.'),
1431
+ moved: moved.length,
1432
+ failed,
1433
+ skipped: skipped.slice(0, 40),
1434
+ note: apply
1435
+ ? `已整理 ${moved.length} 个文件`
1436
+ : '演练模式,未改动任何文件;确认后用 apply: true 执行',
1437
+ };
1438
+ }
1439
+
1440
+ ctx.tools.register(defineTool({
1441
+ name: 'mikan_names',
1442
+ description: 'Build or inspect the offline title index from bangumi-data: maps Chinese, Japanese and English titles to first air dates so library organisation works without Bangumi or a proxy.',
1443
+ parameters: {
1444
+ type: 'object',
1445
+ properties: {
1446
+ action: { type: 'string', enum: ['status', 'build'], description: 'status reports the index; build downloads bangumi-data (about 7 MB) and rebuilds it. Needs network once.' },
1447
+ },
1448
+ required: ['action'],
1449
+ additionalProperties: false,
1450
+ },
1451
+ output: { schema: OBJ, render: renderJson },
1452
+ async execute(args) {
1453
+ if (args.action !== 'build') return await bgmIndexStatus();
1454
+ const e = await detectEnv();
1455
+ const cfg = await loadConfig();
1456
+ const proxy = e.proxy || cfg.proxy || '';
1457
+ const urls = [
1458
+ 'https://raw.githubusercontent.com/bangumi-data/bangumi-data/master/dist/data.json',
1459
+ 'https://cdn.jsdelivr.net/gh/bangumi-data/bangumi-data@master/dist/data.json',
1460
+ ];
1461
+ let lastErr = '';
1462
+ for (const url of urls) {
1463
+ try {
1464
+ const res = await fetchText(url, { proxy, timeout: 180000, headers: { Accept: '*/*' } });
1465
+ if (res.status !== 200) {
1466
+ lastErr = `HTTP ${res.status}`;
1467
+ continue;
1468
+ }
1469
+ const index = buildIndexFromData(JSON.parse(res.body));
1470
+ await saveBgmIndex(index);
1471
+ return { ok: true, entries: Object.keys(index).length, source: url };
1472
+ } catch (err) {
1473
+ lastErr = err && err.message ? err.message : String(err);
1474
+ }
1475
+ }
1476
+ return { ok: false, reason: lastErr || '下载失败' };
1477
+ },
1478
+ }));
1479
+
1480
+ ctx.tools.register(defineTool({
1481
+ name: 'mikan_deploy',
1482
+ description: 'Media library deployment and organisation. action=deploy creates the 下载中转站 staging folder in the workspace and points the downloader at it; action=organize scans staging and plans 【YYYY.M】Title/Season N folders for finished downloads (dry-run unless apply is true).',
1483
+ parameters: {
1484
+ type: 'object',
1485
+ properties: {
1486
+ action: { type: 'string', enum: ['deploy', 'organize'], description: 'deploy sets up the staging folder; organize plans (and with apply, performs) the folder layout.' },
1487
+ library: { type: 'string', description: 'Library workspace directory. REQUIRED: pass the intended media library path (e.g. D:\\Anime). Never default to the current working directory.' },
1488
+ apply: { type: 'boolean', description: 'organize: actually create folders and move files. Defaults to false (dry run).' },
1489
+ },
1490
+ required: ['action'],
1491
+ additionalProperties: false,
1492
+ },
1493
+ output: { schema: OBJ, render: renderJson },
1494
+ async execute(args) {
1495
+ return await deployLibrary(args.action, { library: args.library || '', apply: args.apply === true });
1496
+ },
1497
+ }));
1498
+
1499
+ ctx.tools.register(defineTool({
1500
+ name: 'mikan_align',
1501
+ description: 'Scan a local media directory, aggregate episodes per series and subgroup, and compare the result against current subscriptions: which subscribed series exist locally, which are missing entirely, and which local series are not subscribed.',
1502
+ parameters: {
1503
+ type: 'object',
1504
+ properties: {
1505
+ root: { type: 'string', description: 'Directory to scan. Defaults to the current working directory.' },
1506
+ maxDepth: { type: 'number', description: 'Recursion depth (default 6).' },
1507
+ },
1508
+ additionalProperties: false,
1509
+ },
1510
+ output: { schema: OBJ, render: renderJson },
1511
+ async execute(args) {
1512
+ const e = await detectEnv();
1513
+ const cfg = await loadConfig();
1514
+ const root = args.root || process.cwd();
1515
+ const scan = scanLibrary([root], { maxDepth: Number(args.maxDepth) || 6 });
1516
+ const subs = await store.listSubscriptions();
1517
+
1518
+ const norm = (s) => normTitle(s);
1519
+ const localByNorm = new Map(scan.series.map((s) => [norm(s.title), s]));
1520
+
1521
+ const matched = [];
1522
+ const usedLocal = new Set();
1523
+ for (const sub of subs) {
1524
+ // Translate the subscription's Chinese title so it can match an English
1525
+ // folder name, reusing the same resolver the other sources use.
1526
+ let english = '';
1527
+ try {
1528
+ const resolved = await resolveNames(sub.title, {
1529
+ base: e.bgmBase || cfg.bgmBase || '',
1530
+ proxy: e.bgmViaProxy ? (e.proxy || '') : '',
1531
+ detail: true,
1532
+ limit: 1,
1533
+ });
1534
+ english = resolved.matches?.[0]?.en || '';
1535
+ } catch { /* matching is best-effort */ }
1536
+
1537
+ let local = localByNorm.get(norm(sub.title)) || null;
1538
+ if (!local && english) {
1539
+ const want = norm(english);
1540
+ local = scan.series.find((s) => norm(s.title) === want || norm(s.title).includes(want) || want.includes(norm(s.title))) || null;
1541
+ }
1542
+ if (local) usedLocal.add(norm(local.title));
1543
+
1544
+ matched.push({
1545
+ title: sub.title,
1546
+ bangumiId: sub.bangumiId,
1547
+ weekday: sub.weekday || '',
1548
+ localTitle: local?.title || '',
1549
+ found: Boolean(local),
1550
+ localEpisodes: local?.totalEpisodes || 0,
1551
+ // Summaries only: an episode array per group would dwarf the answer.
1552
+ groups: (local?.groups || []).map((g) => ({ group: g.group, count: g.count, range: g.range })),
1553
+ subscribedGroups: (sub.subgroups || []).map((g) => ({ name: g.name, lastSeen: g.lastSeen })),
1554
+ });
1555
+ }
1556
+
1557
+ const unsubscribed = scan.series
1558
+ .filter((s) => !usedLocal.has(norm(s.title)))
1559
+ .slice(0, 30)
1560
+ .map((s) => ({
1561
+ title: s.title,
1562
+ totalEpisodes: s.totalEpisodes,
1563
+ groups: s.groups.map((g) => ({ group: g.group, count: g.count, range: g.range })),
1564
+ }));
1565
+
1566
+ return {
1567
+ root,
1568
+ scanned: { files: scan.files, unparsed: scan.unparsed, series: scan.series.length },
1569
+ matched,
1570
+ unsubscribed,
1571
+ };
1572
+ },
1573
+ }));
1574
+
1575
+ ctx.tools.register(defineTool({
1576
+ name: 'nyaa_search',
1577
+ description: 'Search nyaa.si by keyword. nyaa indexes Japanese/romanised titles, so resolve the Japanese name first with mikan_resolve_names. Returns title, size, seeders, category and a torrent link; pass withHash to also fetch the info hash needed by the downloader.',
1578
+ parameters: {
1579
+ type: 'object',
1580
+ properties: {
1581
+ keyword: { type: 'string', description: 'Search term, usually the Japanese or English title.' },
1582
+ category: { type: 'string', enum: ['1_0', '1_1', '1_2', '1_3', '1_4'], description: 'Anime category: 1_0 all, 1_1 music video, 1_2 English-subbed, 1_3 Chinese-subbed, 1_4 raw.' },
1583
+ limit: { type: 'number', description: 'Max results (default 20).' },
1584
+ withHash: { type: 'boolean', description: 'Fetch the info hash for each result (one extra request per result).' },
1585
+ },
1586
+ required: ['keyword'],
1587
+ additionalProperties: false,
1588
+ },
1589
+ output: { schema: OBJ, render: renderJson },
1590
+ async execute(args) {
1591
+ const e = await detectEnv();
1592
+ const cfg = await loadConfig();
1593
+ if (!e.nyaaOk) {
1594
+ return { ok: false, reason: 'nyaa 不可达:需要代理,或在配置里填 nyaaBase 镜像' };
1595
+ }
1596
+ const client = createNyaaClient({
1597
+ base: e.nyaaBase || cfg.nyaaBase || '',
1598
+ proxy: e.nyaaViaProxy ? (e.proxy || '') : '',
1599
+ });
1600
+ const res = await client.search(args.keyword, {
1601
+ category: args.category || '1_0',
1602
+ limit: args.limit || 20,
1603
+ });
1604
+ if (!res.ok) return res;
1605
+ if (args.withHash) {
1606
+ // nyaa rate-limits detail pages; two at a time is reliable.
1607
+ await mapLimit(res.items, 2, async (it) => {
1608
+ if (!it.id) return;
1609
+ const d = await client.detail(it.id);
1610
+ if (d.ok) {
1611
+ it.hash = d.hash;
1612
+ it.magnet = d.magnet;
1613
+ }
1614
+ });
1615
+ }
1616
+ // Same resource shape as mikan_search so the two can be merged directly.
1617
+ const items = res.items.map((it) => ({
1618
+ source: 'nyaa',
1619
+ hash: it.hash || '',
1620
+ title: it.title,
1621
+ publisher: nyaaGroupOf(it.title),
1622
+ episode: nyaaEpisodeOf(it.title),
1623
+ size: it.size,
1624
+ seeders: it.seeders,
1625
+ category: it.categoryLabel,
1626
+ date: it.pubDate,
1627
+ url: `https://nyaa.si/view/${it.id}`,
1628
+ }));
1629
+ return { ok: true, source: 'nyaa', total: res.total, items };
1630
+ },
1631
+ }));
1632
+
1633
+ ctx.tools.register(defineTool({
1634
+ name: 'mikan_search',
1635
+ description: 'Keyword search Mikan. Mikan only indexes releases, so results are grouped by series and each release is marked collection / season / episode. Each series also carries a bangumiId, resolved from the current season list or from the season implied by Bangumi\'s first air date.',
1636
+ parameters: {
1637
+ type: 'object',
1638
+ properties: {
1639
+ keyword: { type: 'string', description: 'Search keyword, e.g. 高达00.' },
1640
+ limit: { type: 'number', description: 'Max releases to return (default 30).' },
1641
+ deep: { type: 'boolean', description: 'Scan every season from the first air year (or ten years back) instead of only the current and first-air seasons. Slower on first use, then cached.' },
1642
+ full: { type: 'boolean', description: 'Also build per-subgroup episode bundles: for groups that only publish single episodes, report the real range, gaps and total size. Costs one or two extra requests per series.' },
1643
+ },
1644
+ required: ['keyword'],
1645
+ additionalProperties: false,
1646
+ },
1647
+ output: { schema: OBJ, render: renderJson },
1648
+ async execute(args) {
1649
+ return await searchReleases(args.keyword, args.limit, args.deep === true, args.full === true);
1650
+ },
1651
+ }));
1652
+
645
1653
  ctx.tools.register(defineTool({
646
1654
  name: 'mikan_check_updates',
647
1655
  description: 'Fetch fresh releases and report episodes newer than each subscription watermark. Does not download anything.',
@@ -738,8 +1746,97 @@ export async function apply(ctx) {
738
1746
  path: '/dsh-mikan',
739
1747
  handler: async (req, res) => {
740
1748
  const u = new URL(req.url, 'http://dsh');
741
- const route = u.pathname.slice('/dsh-mikan'.length);
1749
+ const rawRoute = u.pathname.slice('/dsh-mikan'.length);
1750
+ // Per-source namespace: /source/mikan/<feature> maps onto the existing
1751
+ // handlers, so old paths keep working during the migration. Public
1752
+ // endpoints (state, schedule, download, …) stay at the root.
1753
+ const route = rawRoute.startsWith('/source/mikan/')
1754
+ ? rawRoute.slice('/source/mikan'.length)
1755
+ : rawRoute;
742
1756
  try {
1757
+ if (route.startsWith('/assets/') && req.method === 'GET') {
1758
+ const name = path.basename(decodeURIComponent(route.slice('/assets/'.length)));
1759
+ if (!/^[a-z0-9_.-]+\.png$/i.test(name)) return send(res, 404, { ok: false });
1760
+ try {
1761
+ const data = await fs.readFile(path.join(PLUGIN_DIR, 'assets', name));
1762
+ res.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'public, max-age=86400' });
1763
+ return res.end(data);
1764
+ } catch {
1765
+ return send(res, 404, { ok: false, reason: 'not found' });
1766
+ }
1767
+ }
1768
+ if (route === '/catalog-status' && req.method === 'GET') {
1769
+ const catalog = await loadCatalog();
1770
+ const seasons = indexedSeasons(catalog).length;
1771
+ let series = 0;
1772
+ for (const key of Object.keys(catalog.seasons || {})) series += (catalog.seasons[key] || []).length;
1773
+ return send(res, 200, { seasons, series, updatedAt: catalog.updatedAt || '' });
1774
+ }
1775
+ if (route === '/names-status' && req.method === 'GET') {
1776
+ return send(res, 200, await bgmIndexStatus());
1777
+ }
1778
+ if (route === '/names-build' && req.method === 'POST') {
1779
+ const e = await detectEnv();
1780
+ const cfg = await loadConfig();
1781
+ const proxy = e.proxy || cfg.proxy || '';
1782
+ const urls = [
1783
+ 'https://raw.githubusercontent.com/bangumi-data/bangumi-data/master/dist/data.json',
1784
+ 'https://cdn.jsdelivr.net/gh/bangumi-data/bangumi-data@master/dist/data.json',
1785
+ ];
1786
+ let lastErr = '';
1787
+ for (const url of urls) {
1788
+ try {
1789
+ const r = await fetchText(url, { proxy, timeout: 180000, headers: { Accept: '*/*' } });
1790
+ if (r.status !== 200) { lastErr = `HTTP ${r.status}`; continue; }
1791
+ const index = buildIndexFromData(JSON.parse(r.body));
1792
+ await saveBgmIndex(index);
1793
+ return send(res, 200, { ok: true, entries: Object.keys(index).length });
1794
+ } catch (err) {
1795
+ lastErr = err && err.message ? err.message : String(err);
1796
+ }
1797
+ }
1798
+ return send(res, 200, { ok: false, reason: lastErr || '下载失败' });
1799
+ }
1800
+ if (route === '/resolve-names' && req.method === 'GET') {
1801
+ const q = u.searchParams.get('q') || '';
1802
+ if (!q) return send(res, 400, { ok: false, reason: 'q is required' });
1803
+ const e = await detectEnv();
1804
+ const cfg = await loadConfig();
1805
+ const result = await resolveNames(q, {
1806
+ base: e.bgmBase || cfg.bgmBase || '',
1807
+ proxy: e.bgmViaProxy ? (e.proxy || '') : '',
1808
+ detail: false,
1809
+ limit: 1,
1810
+ });
1811
+ return send(res, 200, result);
1812
+ }
1813
+ if (route === '/nyaa-hash' && req.method === 'GET') {
1814
+ const id = u.searchParams.get('id') || '';
1815
+ if (!id) return send(res, 400, { ok: false, reason: 'id is required' });
1816
+ const e = await detectEnv();
1817
+ const cfg = await loadConfig();
1818
+ if (!e.nyaaOk) return send(res, 200, { ok: false, reason: 'Nyaa 不可达' });
1819
+ const client = createNyaaClient({
1820
+ base: e.nyaaBase || cfg.nyaaBase || '',
1821
+ proxy: e.nyaaViaProxy ? (e.proxy || '') : '',
1822
+ });
1823
+ const detail = await client.detail(id);
1824
+ return send(res, 200, detail);
1825
+ }
1826
+ if (route === '/nyaa-search' && req.method === 'GET') {
1827
+ const q = u.searchParams.get('q') || '';
1828
+ const category = u.searchParams.get('c') || '1_0';
1829
+ if (!q) return send(res, 400, { ok: false, reason: 'q is required' });
1830
+ const e = await detectEnv();
1831
+ const cfg = await loadConfig();
1832
+ if (!e.nyaaOk) return send(res, 200, { ok: false, reason: 'Nyaa 不可达:需要代理,或在设置里填镜像' });
1833
+ const client = createNyaaClient({
1834
+ base: e.nyaaBase || cfg.nyaaBase || '',
1835
+ proxy: e.nyaaViaProxy ? (e.proxy || '') : '',
1836
+ });
1837
+ const result = await client.search(q, { category, limit: 100 });
1838
+ return send(res, 200, result);
1839
+ }
743
1840
  if (route === '/state' && req.method === 'GET') {
744
1841
  const e = await detectEnv(u.searchParams.get('refresh') === '1');
745
1842
  const cfg = await loadConfig();
@@ -759,9 +1856,11 @@ export async function apply(ctx) {
759
1856
  mikanOk: e.mikanOk,
760
1857
  mikanReason: e.mikanReason,
761
1858
  mikanCustom: cfg.mikanBase || '',
1859
+ switch: e.transition || null,
762
1860
  downloader: dl,
763
1861
  savePath: cfg.savePath,
764
1862
  checkIntervalMinutes: cfg.checkIntervalMinutes,
1863
+ namePreference: cfg.namePreference || 'cn',
765
1864
  lastCheckAt: await store.getLastCheck(),
766
1865
  });
767
1866
  }
@@ -826,6 +1925,19 @@ export async function apply(ctx) {
826
1925
  });
827
1926
  }
828
1927
  if (route === '/ack' && req.method === 'POST') {
1928
+ // Acknowledging must also advance each subgroup's watermark.
1929
+ // Clearing the list alone leaves lastSeen untouched, so the next
1930
+ // background check rediscovers the same episodes and the banner
1931
+ // comes back.
1932
+ try {
1933
+ const { updates } = await store.getLastUpdates();
1934
+ for (const u of updates) {
1935
+ const newest = (u.episodes || []).reduce((max, e) => Math.max(max, Number(e.episode) || 0), 0);
1936
+ if (newest > (Number(u.lastSeen) || 0)) {
1937
+ await store.advanceGroup(u.title, u.subgroupName, newest);
1938
+ }
1939
+ }
1940
+ } catch { /* best-effort */ }
829
1941
  await store.setLastUpdates([]);
830
1942
  return send(res, 200, { ok: true });
831
1943
  }
@@ -976,6 +2088,11 @@ export async function apply(ctx) {
976
2088
  }
977
2089
  return send(res, 200, { ...info, airDate, airSource });
978
2090
  }
2091
+ if (route === '/search' && req.method === 'GET') {
2092
+ const q = u.searchParams.get('q') || '';
2093
+ if (!q) return send(res, 400, { ok: false, reason: 'q is required' });
2094
+ return send(res, 200, await searchReleases(q));
2095
+ }
979
2096
  if (route === '/works' && req.method === 'GET') {
980
2097
  const bangumiId = u.searchParams.get('bangumiId') || '';
981
2098
  const subgroupId = u.searchParams.get('subgroupId') || '';
@@ -1068,9 +2185,57 @@ export async function apply(ctx) {
1068
2185
  }
1069
2186
  return send(res, 200, { ok: false, reason: '未找到可用代理,已保持直连模式', tried });
1070
2187
  }
2188
+ if (route === '/order' && req.method === 'GET') {
2189
+ const sessionId = u.searchParams.get('sessionId') || '';
2190
+ if (sessionId) await store.setActiveSession(sessionId);
2191
+ return send(res, 200, await store.getOrder(sessionId));
2192
+ }
2193
+ if (route === '/order/add' && req.method === 'POST') {
2194
+ const body = await readBody(req);
2195
+ const items = Array.isArray(body.items) ? body.items : [];
2196
+ if (items.length === 0) return send(res, 400, { ok: false, reason: 'items is required' });
2197
+ if (body.sessionId) await store.setActiveSession(body.sessionId);
2198
+ return send(res, 200, { ok: true, ...(await store.addOrderItems(body.sessionId || '', items)) });
2199
+ }
2200
+ if (route === '/order/clear' && req.method === 'POST') {
2201
+ const body = await readBody(req);
2202
+ const res2 = await store.consumeOrderItems(body.sessionId || '', []);
2203
+ return send(res, 200, { ok: true, removed: res2.removed, items: res2.items });
2204
+ }
2205
+ if (route === '/order/remove' && req.method === 'POST') {
2206
+ const body = await readBody(req);
2207
+ if (!body.hash) return send(res, 400, { ok: false, reason: 'hash is required' });
2208
+ return send(res, 200, { ok: true, ...(await store.removeOrderItem(body.sessionId || '', body.hash)) });
2209
+ }
2210
+ if (route === '/order/confirm' && req.method === 'POST') {
2211
+ const body = await readBody(req);
2212
+ const sessionId = body.sessionId || '';
2213
+ const order = await store.getOrder(sessionId);
2214
+ const hashes = Array.isArray(body.hashes) && body.hashes.length > 0
2215
+ ? body.hashes
2216
+ : order.items.map((i) => i.hash);
2217
+ if (hashes.length === 0) return send(res, 400, { ok: false, reason: '点单是空的' });
2218
+ const cfg = await loadConfig();
2219
+ if (!cfg.savePath) {
2220
+ return send(res, 200, { ok: false, reason: '未配置下载目录(savePath)' });
2221
+ }
2222
+ const client = await downloaderClient();
2223
+ const auth = await client.checkAuth();
2224
+ if (!auth.ok) return send(res, 200, { ok: false, reason: `下载器未就绪:${auth.reason}` });
2225
+ const results = [];
2226
+ for (const hash of hashes) {
2227
+ const added = await client.addMagnet(magnetFromHash(hash, ''), cfg.savePath);
2228
+ results.push({ hash, added: added.ok, message: added.message });
2229
+ }
2230
+ const okCount = results.filter((r) => r.added).length;
2231
+ const removed = okCount > 0
2232
+ ? (await store.consumeOrderItems(sessionId, results.filter((r) => r.added).map((r) => r.hash))).removed
2233
+ : 0;
2234
+ return send(res, 200, { ok: okCount > 0, added: okCount, total: hashes.length, removed, results });
2235
+ }
1071
2236
  if (route === '/config' && req.method === 'POST') {
1072
2237
  const body = await readBody(req);
1073
- const allowed = ['downloader', 'proxy', 'bitcometBase', 'qbittorrentBase', 'qbittorrentUser', 'qbittorrentPassword', 'mikanBase', 'bgmBase', 'nyaaBase', 'savePath', 'checkIntervalMinutes'];
2238
+ const allowed = ['downloader', 'proxy', 'bitcometBase', 'qbittorrentBase', 'qbittorrentUser', 'qbittorrentPassword', 'mikanBase', 'bgmBase', 'nyaaBase', 'savePath', 'checkIntervalMinutes', 'namePreference'];
1074
2239
  const patch = {};
1075
2240
  for (const key of allowed) {
1076
2241
  if (body[key] !== undefined) patch[key] = body[key];