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/CHANGELOG.md +36 -2
- package/README.md +80 -45
- package/assets/mikan.png +0 -0
- package/assets/nyaa.png +0 -0
- package/client.js +458 -20
- package/docs/DETAIL.md +29 -4
- package/index.js +1171 -6
- package/lib/bgmdata.js +90 -0
- package/lib/catalog.js +131 -0
- package/lib/constants.js +5 -0
- package/lib/library.js +120 -0
- package/lib/mikan.js +14 -4
- package/lib/names.js +138 -0
- package/lib/nyaa.js +119 -0
- package/lib/store.js +76 -0
- package/lib/t2s.js +52 -0
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +6 -2
package/lib/bgmdata.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Offline title index built from bangumi-data.
|
|
3
|
+
*
|
|
4
|
+
* `dist/data.json` carries every series' original title, its Chinese
|
|
5
|
+
* translations (`titleTranslate['zh-Hans']`) and its English title, plus the
|
|
6
|
+
* first air date. Building a local index turns "which Chinese title and which
|
|
7
|
+
* year does this English folder name belong to?" into a file lookup, so
|
|
8
|
+
* organising a library no longer needs Bangumi or a proxy.
|
|
9
|
+
*
|
|
10
|
+
* The index maps every normalised name (Chinese, Japanese, English, aliases)
|
|
11
|
+
* to one record: `{ cn, jp, en, begin }`.
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs/promises';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { storeDir } from './store.js';
|
|
16
|
+
import { normName } from './catalog.js';
|
|
17
|
+
|
|
18
|
+
const FILE = 'bgm-names.json';
|
|
19
|
+
|
|
20
|
+
function indexPath() {
|
|
21
|
+
return path.join(storeDir(), FILE);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Build the index object from a parsed bangumi-data document. */
|
|
25
|
+
export function buildIndexFromData(data) {
|
|
26
|
+
const items = Array.isArray(data) ? data : (data?.items || []);
|
|
27
|
+
const index = {};
|
|
28
|
+
for (const item of items) {
|
|
29
|
+
if (!item || !item.title) continue;
|
|
30
|
+
const cn = (item.titleTranslate?.['zh-Hans'] || [])[0] || '';
|
|
31
|
+
const jp = item.title;
|
|
32
|
+
const en = (item.titleTranslate?.en || [])[0] || '';
|
|
33
|
+
const begin = String(item.begin || '').slice(0, 10);
|
|
34
|
+
if (!cn && !jp) continue;
|
|
35
|
+
const record = { cn: cn || jp, jp, en, begin };
|
|
36
|
+
const names = [
|
|
37
|
+
cn,
|
|
38
|
+
jp,
|
|
39
|
+
en,
|
|
40
|
+
...(item.titleTranslate?.['zh-Hans'] || []),
|
|
41
|
+
...(item.titleTranslate?.en || []),
|
|
42
|
+
];
|
|
43
|
+
for (const name of names) {
|
|
44
|
+
const key = normName(name);
|
|
45
|
+
if (!key || index[key]) continue;
|
|
46
|
+
index[key] = record;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return index;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function saveBgmIndex(index) {
|
|
53
|
+
await fs.mkdir(storeDir(), { recursive: true });
|
|
54
|
+
const target = indexPath();
|
|
55
|
+
const tmp = `${target}.tmp`;
|
|
56
|
+
await fs.writeFile(tmp, JSON.stringify(index), 'utf8');
|
|
57
|
+
await fs.rename(tmp, target);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function loadBgmIndex() {
|
|
61
|
+
try {
|
|
62
|
+
const raw = await fs.readFile(indexPath(), 'utf8');
|
|
63
|
+
const parsed = JSON.parse(raw);
|
|
64
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
65
|
+
} catch {
|
|
66
|
+
return {};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Look a title up; returns `{ cn, jp, en, begin }` or null. */
|
|
71
|
+
export function lookupTitle(index, title) {
|
|
72
|
+
const key = normName(title);
|
|
73
|
+
if (!key) return null;
|
|
74
|
+
if (index[key]) return index[key];
|
|
75
|
+
// Fall back to containment for names with extra season suffixes.
|
|
76
|
+
for (const [k, v] of Object.entries(index)) {
|
|
77
|
+
if (k.length >= 4 && (key.includes(k) || k.includes(key))) return v;
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function bgmIndexStatus() {
|
|
83
|
+
try {
|
|
84
|
+
const stat = await fs.stat(indexPath());
|
|
85
|
+
const index = await loadBgmIndex();
|
|
86
|
+
return { exists: true, entries: Object.keys(index).length, bytes: stat.size, updatedAt: stat.mtime.toISOString() };
|
|
87
|
+
} catch {
|
|
88
|
+
return { exists: false, entries: 0, bytes: 0, updatedAt: '' };
|
|
89
|
+
}
|
|
90
|
+
}
|
package/lib/catalog.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local season catalog.
|
|
3
|
+
*
|
|
4
|
+
* Resolving a series to its Mikan bangumiId used to cost one season request per
|
|
5
|
+
* lookup (plus a Bangumi request when the first guess missed). Season membership
|
|
6
|
+
* changes once per quarter, so it belongs in a local file rather than in the
|
|
7
|
+
* request path:
|
|
8
|
+
*
|
|
9
|
+
* catalog.json
|
|
10
|
+
* {
|
|
11
|
+
* "updatedAt": "...",
|
|
12
|
+
* "seasons": { "2026秋": [{ "id": "4077", "title": "青之芦苇 第二季", "norm": "青之芦苇第二季" }] },
|
|
13
|
+
* "names": { "莉可丽丝": { "bgmId": 364450, "jp": "...", "en": "...", "aliases": [...] } }
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* `names` is filled lazily: a miss falls back to Bangumi once, then the answer
|
|
17
|
+
* is stored here for every later lookup.
|
|
18
|
+
*/
|
|
19
|
+
import fs from 'node:fs/promises';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { storeDir } from './store.js';
|
|
22
|
+
import { toSimplified } from './t2s.js';
|
|
23
|
+
|
|
24
|
+
const FILE = 'catalog.json';
|
|
25
|
+
|
|
26
|
+
function catalogFile() {
|
|
27
|
+
return path.join(storeDir(), FILE);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const EMPTY = { updatedAt: '', seasons: {}, names: {} };
|
|
31
|
+
|
|
32
|
+
/** Normalize a title for matching: fold traditional, drop spacing/punctuation. */
|
|
33
|
+
export function normName(value) {
|
|
34
|
+
return toSimplified(String(value || ''))
|
|
35
|
+
.toLowerCase()
|
|
36
|
+
.replace(/[\s\-_/\\·・::,,.。!!??\[\]【】()()"'“”「」『』~~++&&★☆]/g, '');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function loadCatalog() {
|
|
40
|
+
try {
|
|
41
|
+
const raw = await fs.readFile(catalogFile(), 'utf8');
|
|
42
|
+
const parsed = JSON.parse(raw);
|
|
43
|
+
return {
|
|
44
|
+
updatedAt: typeof parsed.updatedAt === 'string' ? parsed.updatedAt : '',
|
|
45
|
+
seasons: parsed.seasons && typeof parsed.seasons === 'object' ? parsed.seasons : {},
|
|
46
|
+
names: parsed.names && typeof parsed.names === 'object' ? parsed.names : {},
|
|
47
|
+
};
|
|
48
|
+
} catch {
|
|
49
|
+
return { ...EMPTY, seasons: {}, names: {} };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function saveCatalog(catalog) {
|
|
54
|
+
await fs.mkdir(storeDir(), { recursive: true });
|
|
55
|
+
const target = catalogFile();
|
|
56
|
+
const tmp = `${target}.tmp`;
|
|
57
|
+
await fs.writeFile(tmp, JSON.stringify(catalog), 'utf8');
|
|
58
|
+
await fs.rename(tmp, target);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** List the season keys already indexed, e.g. ['2026秋', '2026夏']. */
|
|
62
|
+
export function indexedSeasons(catalog) {
|
|
63
|
+
return Object.keys(catalog.seasons || {});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Find every season containing a series whose title matches `name`.
|
|
68
|
+
* Returns `[{ season, bangumiId, title }]`, newest season first.
|
|
69
|
+
*/
|
|
70
|
+
export function findSeriesInCatalog(catalog, name) {
|
|
71
|
+
const key = normName(name);
|
|
72
|
+
if (!key) return [];
|
|
73
|
+
const out = [];
|
|
74
|
+
const seen = new Set();
|
|
75
|
+
for (const season of Object.keys(catalog.seasons || {}).sort().reverse()) {
|
|
76
|
+
for (const item of catalog.seasons[season] || []) {
|
|
77
|
+
const n = item.norm || normName(item.title);
|
|
78
|
+
if (!n) continue;
|
|
79
|
+
const exact = n === key;
|
|
80
|
+
const contains = n.includes(key) || key.includes(n);
|
|
81
|
+
// A short key such as "机动战士高达" would otherwise match every Gundam
|
|
82
|
+
// series; require the two titles to be of comparable length.
|
|
83
|
+
const ratio = Math.min(n.length, key.length) / Math.max(n.length, key.length);
|
|
84
|
+
if (exact || (contains && ratio >= 0.55)) {
|
|
85
|
+
if (seen.has(item.id)) continue;
|
|
86
|
+
seen.add(item.id);
|
|
87
|
+
out.push({ season, bangumiId: item.id, title: item.title });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Store a name resolution so later lookups skip Bangumi. */
|
|
95
|
+
export async function rememberNames(keyword, match) {
|
|
96
|
+
if (!keyword || !match) return;
|
|
97
|
+
const catalog = await loadCatalog();
|
|
98
|
+
catalog.names[normName(keyword)] = {
|
|
99
|
+
bgmId: match.bgmId,
|
|
100
|
+
cn: match.cn || '',
|
|
101
|
+
jp: match.jp || '',
|
|
102
|
+
en: match.en || '',
|
|
103
|
+
aliases: Array.isArray(match.aliases) ? match.aliases : [],
|
|
104
|
+
airDate: match.airDate || '',
|
|
105
|
+
at: new Date().toISOString(),
|
|
106
|
+
};
|
|
107
|
+
await saveCatalog(catalog);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Look up a cached name resolution. */
|
|
111
|
+
export function recallNames(catalog, keyword) {
|
|
112
|
+
const rec = catalog.names?.[normName(keyword)];
|
|
113
|
+
if (!rec) return null;
|
|
114
|
+
return {
|
|
115
|
+
bgmId: rec.bgmId,
|
|
116
|
+
cn: rec.cn,
|
|
117
|
+
jp: rec.jp,
|
|
118
|
+
en: rec.en,
|
|
119
|
+
aliases: rec.aliases || [],
|
|
120
|
+
airDate: rec.airDate || '',
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Replace one season's entries (used by the builder). */
|
|
125
|
+
export function setSeason(catalog, season, items) {
|
|
126
|
+
catalog.seasons[season] = items.map((it) => ({
|
|
127
|
+
id: String(it.id),
|
|
128
|
+
title: it.title,
|
|
129
|
+
norm: normName(it.title),
|
|
130
|
+
}));
|
|
131
|
+
}
|
package/lib/constants.js
CHANGED
|
@@ -50,6 +50,11 @@ export const DEFAULT_CONFIG = {
|
|
|
50
50
|
savePath: '',
|
|
51
51
|
/** Minutes between automatic update checks. */
|
|
52
52
|
checkIntervalMinutes: 30,
|
|
53
|
+
/**
|
|
54
|
+
* Language used for the folder name after 【YYYY.M】 when organising a
|
|
55
|
+
* library: 'cn' (Bangumi's Chinese title), 'jp', 'en', or 'romaji'.
|
|
56
|
+
*/
|
|
57
|
+
namePreference: 'cn',
|
|
53
58
|
/** Season used when a subscription omits one. */
|
|
54
59
|
defaultSeason: '',
|
|
55
60
|
};
|
package/lib/library.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local media library scanner.
|
|
3
|
+
*
|
|
4
|
+
* Handles the two filename shapes the library actually uses:
|
|
5
|
+
* [Group][Title][01][spec].mkv → bracket-delimited
|
|
6
|
+
* [Group] Title - 01 [spec].mp4 → dash-delimited
|
|
7
|
+
* Title [01].mp4 → trailing episode
|
|
8
|
+
*
|
|
9
|
+
* Read-only: the library directory is never modified.
|
|
10
|
+
*/
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
const VIDEO = /\.(mp4|mkv|avi|rmvb|flv|wmv|mov|ts|m2ts|webm)$/i;
|
|
15
|
+
const SKIP_DIR = /^(System Volume Information|\$RECYCLE\.BIN|node_modules|\.git|\.cache)$/i;
|
|
16
|
+
|
|
17
|
+
/** Build a regex-free text cleaner for series names. */
|
|
18
|
+
function cleanTitle(value) {
|
|
19
|
+
return String(value || '')
|
|
20
|
+
.replace(/[[【][^\]】]*[\]】]/g, ' ')
|
|
21
|
+
.replace(/\s+/g, ' ')
|
|
22
|
+
.trim();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Parse one file name into group / title / episode. */
|
|
26
|
+
export function parseMediaFile(file) {
|
|
27
|
+
const noExt = String(file || '').replace(VIDEO, '');
|
|
28
|
+
// Bracket-delimited: [Group][Title][01][spec]...
|
|
29
|
+
const parts = noExt.split(/[[\]【】]/).map((s) => s.trim()).filter(Boolean);
|
|
30
|
+
if (parts.length >= 3 && /^\d{1,4}(?:v\d)?$/.test(parts[2])) {
|
|
31
|
+
return {
|
|
32
|
+
group: parts[0],
|
|
33
|
+
title: parts[1],
|
|
34
|
+
episode: Number(parts[2].replace(/v\d+$/, '')),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
// [Group][Title][Movie]/[OVA]/[SP]: no episode number, title is parts[1].
|
|
38
|
+
if (parts.length >= 3 && /^(movie|ova|oad|sp|special|劇場版|剧场版)$/i.test(parts[2])) {
|
|
39
|
+
return { group: parts[0], title: parts[1], episode: 0 };
|
|
40
|
+
}
|
|
41
|
+
const group = (noExt.match(/^\s*[[【]([^\]】]{1,40})[\]】]/) || [])[1] || '';
|
|
42
|
+
const body = noExt.replace(/^\s*[[【][^\]】]*[\]】]\s*/, '');
|
|
43
|
+
const dash = body.match(/[-–—]\s*(\d{1,4})(?:v\d)?(?:\s|\[|\(|$)/) || body.match(/\s(\d{1,4})(?:v\d)?\s*[[【(]/);
|
|
44
|
+
if (dash) {
|
|
45
|
+
return {
|
|
46
|
+
group,
|
|
47
|
+
title: cleanTitle(body.split(/\s*[-–—]\s*\d{1,4}/)[0]),
|
|
48
|
+
episode: Number(dash[1]),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
const trailing = noExt.match(/^(.*?)\s*[[【](\d{1,4})(?:v\d)?[\]】]\s*$/);
|
|
52
|
+
if (trailing) {
|
|
53
|
+
return { group, title: cleanTitle(trailing[1]), episode: Number(trailing[2]) };
|
|
54
|
+
}
|
|
55
|
+
return { group, title: cleanTitle(body), episode: 0 };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Recursively collect video files under one root. */
|
|
59
|
+
export function listVideoFiles(root, { maxDepth = 6 } = {}) {
|
|
60
|
+
const out = [];
|
|
61
|
+
const walk = (dir, depth) => {
|
|
62
|
+
if (depth > maxDepth) return;
|
|
63
|
+
let entries;
|
|
64
|
+
try {
|
|
65
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
66
|
+
} catch {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
for (const e of entries) {
|
|
70
|
+
const full = path.join(dir, e.name);
|
|
71
|
+
if (e.isDirectory()) {
|
|
72
|
+
if (!SKIP_DIR.test(e.name)) walk(full, depth + 1);
|
|
73
|
+
} else if (VIDEO.test(e.name)) {
|
|
74
|
+
out.push(full);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
walk(root, 0);
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Scan roots and aggregate episodes per (series, group). */
|
|
83
|
+
export function scanLibrary(roots, { maxDepth = 6 } = {}) {
|
|
84
|
+
const files = [];
|
|
85
|
+
for (const root of roots) {
|
|
86
|
+
if (!root) continue;
|
|
87
|
+
try {
|
|
88
|
+
if (fs.statSync(root).isDirectory()) files.push(...listVideoFiles(root, { maxDepth }));
|
|
89
|
+
} catch { /* skip unreadable root */ }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const series = new Map();
|
|
93
|
+
const unparsed = [];
|
|
94
|
+
for (const full of files) {
|
|
95
|
+
const parsed = parseMediaFile(path.basename(full));
|
|
96
|
+
if (!parsed.title || !parsed.episode) {
|
|
97
|
+
unparsed.push(path.basename(full));
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const key = parsed.title;
|
|
101
|
+
if (!series.has(key)) series.set(key, new Map());
|
|
102
|
+
const groups = series.get(key);
|
|
103
|
+
const gkey = parsed.group || '(无组)';
|
|
104
|
+
if (!groups.has(gkey)) groups.set(gkey, new Set());
|
|
105
|
+
groups.get(gkey).add(parsed.episode);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const rows = [...series.entries()].map(([title, groups]) => {
|
|
109
|
+
const list = [...groups.entries()]
|
|
110
|
+
.map(([group, eps]) => {
|
|
111
|
+
const nums = [...eps].sort((a, b) => a - b);
|
|
112
|
+
return { group, episodes: nums, count: nums.length, range: `${nums[0]}-${nums[nums.length - 1]}` };
|
|
113
|
+
})
|
|
114
|
+
.sort((a, b) => b.count - a.count);
|
|
115
|
+
const total = list.reduce((sum, g) => sum + g.count, 0);
|
|
116
|
+
return { title, groups: list, totalEpisodes: total };
|
|
117
|
+
}).sort((a, b) => b.totalEpisodes - a.totalEpisodes);
|
|
118
|
+
|
|
119
|
+
return { files: files.length, unparsed: unparsed.length, series: rows };
|
|
120
|
+
}
|
package/lib/mikan.js
CHANGED
|
@@ -280,15 +280,25 @@ export function parseSearchPage(html) {
|
|
|
280
280
|
}
|
|
281
281
|
const resources = [];
|
|
282
282
|
const seenHash = new Set();
|
|
283
|
-
|
|
284
|
-
|
|
283
|
+
// Rows carry attributes, so match `<tr ...>` rather than a bare `<tr>`, and
|
|
284
|
+
// pull the upload date from the same row.
|
|
285
|
+
for (const m of html.matchAll(/<tr[^>]*>([\s\S]*?)<\/tr>/g)) {
|
|
286
|
+
const row = m[1];
|
|
287
|
+
const ep = row.match(/<a[^>]*href="\/Home\/Episode\/([0-9a-fA-F]{40})"[^>]*>([\s\S]*?)<\/a>/);
|
|
288
|
+
if (!ep) continue;
|
|
289
|
+
const hash = ep[1].toLowerCase();
|
|
285
290
|
if (seenHash.has(hash)) continue;
|
|
286
|
-
const title = textOf(m[2]);
|
|
287
|
-
if (!title) continue;
|
|
288
291
|
seenHash.add(hash);
|
|
292
|
+
const title = textOf(ep[2]);
|
|
293
|
+
if (!title) continue;
|
|
294
|
+
// Mikan renders dates as `2016/12/23 18:32`, not ISO form.
|
|
295
|
+
const dateMatch = row.match(/<td[^>]*>\s*(\d{4}[/-]\d{1,2}[/-]\d{1,2}(?:\s+\d{1,2}:\d{2}(?::\d{2})?)?)\s*<\/td>/);
|
|
296
|
+
const sizeMatch = row.match(/<td[^>]*>\s*(\d+(?:\.\d+)?\s*[KMGT]i?B)\s*<\/td>/i);
|
|
289
297
|
resources.push({
|
|
290
298
|
hash,
|
|
291
299
|
title,
|
|
300
|
+
date: dateMatch ? dateMatch[1].trim() : '',
|
|
301
|
+
size: sizeMatch ? sizeMatch[1].trim() : '',
|
|
292
302
|
link: `/Home/Episode/${hash}`,
|
|
293
303
|
torrentRel: '',
|
|
294
304
|
...parseReleaseTitle(title),
|
package/lib/names.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-language title resolver backed by Bangumi.
|
|
3
|
+
*
|
|
4
|
+
* Mikan indexes Chinese titles, nyaa indexes Japanese/romanised ones, and other
|
|
5
|
+
* sources differ again — so name translation is its own module that every
|
|
6
|
+
* source can call, rather than being baked into one search path.
|
|
7
|
+
*
|
|
8
|
+
* `searchBgm` already returns the Japanese (`name`) and Chinese (`name_cn`)
|
|
9
|
+
* titles. The English title and any extra aliases live in the subject detail's
|
|
10
|
+
* infobox, so those require one extra request per match (opt out with
|
|
11
|
+
* `detail: false`).
|
|
12
|
+
*/
|
|
13
|
+
import { fetchText } from './net.js';
|
|
14
|
+
import { searchBgm } from './airdate.js';
|
|
15
|
+
import { loadCatalog, recallNames, rememberNames } from './catalog.js';
|
|
16
|
+
|
|
17
|
+
const USER_AGENT = 'dsh-mikan/0.3 (https://github.com/)';
|
|
18
|
+
const DEFAULT_BASE = 'https://api.bgm.tv';
|
|
19
|
+
|
|
20
|
+
function errMessage(err) {
|
|
21
|
+
return err && err.message ? err.message : String(err);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function str(value) {
|
|
25
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Pull alias strings out of a bgm subject's infobox. */
|
|
29
|
+
function collectAliases(infobox) {
|
|
30
|
+
const out = [];
|
|
31
|
+
const seen = new Set();
|
|
32
|
+
const push = (v) => {
|
|
33
|
+
const s = str(v);
|
|
34
|
+
if (!s || seen.has(s)) return;
|
|
35
|
+
seen.add(s);
|
|
36
|
+
out.push(s);
|
|
37
|
+
};
|
|
38
|
+
for (const box of Array.isArray(infobox) ? infobox : []) {
|
|
39
|
+
if (!box || typeof box !== 'object') continue;
|
|
40
|
+
const key = str(box.key);
|
|
41
|
+
if (!/别名|別名|alias|中文名|英文名|日文名/i.test(key)) continue;
|
|
42
|
+
const value = box.value;
|
|
43
|
+
if (Array.isArray(value)) {
|
|
44
|
+
for (const v of value) {
|
|
45
|
+
if (v && typeof v === 'object') push(v.v ?? v.value);
|
|
46
|
+
else push(v);
|
|
47
|
+
}
|
|
48
|
+
} else if (typeof value === 'string') {
|
|
49
|
+
push(value);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** True when the string is mostly Latin letters (a usable English title). */
|
|
56
|
+
function looksLatin(s) {
|
|
57
|
+
const letters = s.replace(/[^A-Za-z]/g, '');
|
|
58
|
+
return letters.length >= 4 && letters.length / s.length >= 0.5;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Resolve every name a series is known by.
|
|
63
|
+
*
|
|
64
|
+
* @param {string} keyword
|
|
65
|
+
* @param {{proxy?:string, base?:string, timeout?:number, detail?:boolean, limit?:number}} [opts]
|
|
66
|
+
* @returns {Promise<{ok:boolean, keyword:string, matches:Array<object>, reason?:string}>}
|
|
67
|
+
*/
|
|
68
|
+
export async function resolveNames(keyword, opts = {}) {
|
|
69
|
+
const kw = str(keyword);
|
|
70
|
+
if (!kw) return { ok: false, keyword: '', matches: [], reason: '搜索关键词为空' };
|
|
71
|
+
|
|
72
|
+
const wantDetail = opts.detail !== false;
|
|
73
|
+
|
|
74
|
+
// Local cache first: a name resolved once never asks Bangumi again.
|
|
75
|
+
try {
|
|
76
|
+
const catalog = await loadCatalog();
|
|
77
|
+
const cached = recallNames(catalog, kw);
|
|
78
|
+
if (cached && (!wantDetail || cached.en)) {
|
|
79
|
+
return { ok: true, keyword: kw, matches: [cached], cached: true };
|
|
80
|
+
}
|
|
81
|
+
} catch { /* fall through to the network */ }
|
|
82
|
+
|
|
83
|
+
const base = String(opts.base || DEFAULT_BASE).replace(/\/+$/, '');
|
|
84
|
+
const search = await searchBgm(kw, { proxy: opts.proxy, base, timeout: opts.timeout });
|
|
85
|
+
if (!search.ok) return { ok: false, keyword: kw, matches: [], reason: search.reason };
|
|
86
|
+
|
|
87
|
+
const limit = Math.max(1, Math.min(Number(opts.limit) || 3, 10));
|
|
88
|
+
const detail = opts.detail !== false;
|
|
89
|
+
const matches = [];
|
|
90
|
+
|
|
91
|
+
for (const item of search.results.slice(0, limit)) {
|
|
92
|
+
const cn = str(item.nameCn);
|
|
93
|
+
const jp = str(item.name);
|
|
94
|
+
let aliases = [];
|
|
95
|
+
if (detail) {
|
|
96
|
+
try {
|
|
97
|
+
const res = await fetchText(`${base}/v0/subjects/${item.id}`, {
|
|
98
|
+
proxy: opts.proxy,
|
|
99
|
+
timeout: opts.timeout || 10000,
|
|
100
|
+
headers: { 'User-Agent': USER_AGENT, Accept: 'application/json' },
|
|
101
|
+
redirects: 2,
|
|
102
|
+
});
|
|
103
|
+
if (res.status >= 200 && res.status < 300) {
|
|
104
|
+
const parsed = JSON.parse(res.body || '{}');
|
|
105
|
+
aliases = collectAliases(parsed.infobox);
|
|
106
|
+
if (parsed.name_cn && !cn) aliases.unshift(str(parsed.name_cn));
|
|
107
|
+
if (parsed.name && !jp) aliases.unshift(str(parsed.name));
|
|
108
|
+
}
|
|
109
|
+
} catch { /* aliases are optional */ }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const names = [...new Set([cn, jp, ...aliases].map(str).filter(Boolean))];
|
|
113
|
+
const latinAliases = names.filter((a) => looksLatin(a) && a !== jp && a !== cn);
|
|
114
|
+
// Prefer a real English title ("The Promised Neverland") over a romaji
|
|
115
|
+
// rendering ("Yakusoku no Neverland") by looking for common English words.
|
|
116
|
+
const english = latinAliases.find((a) => /\b(the|of|and|season|movie|part)\b/i.test(a))
|
|
117
|
+
|| latinAliases[0]
|
|
118
|
+
|| '';
|
|
119
|
+
|
|
120
|
+
matches.push({
|
|
121
|
+
bgmId: item.id,
|
|
122
|
+
cn,
|
|
123
|
+
jp,
|
|
124
|
+
en: english,
|
|
125
|
+
aliases: names.filter((a) => a !== cn && a !== jp && a !== english),
|
|
126
|
+
airDate: item.airDate || '',
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Cache the best match for later lookups (best-effort; never blocks).
|
|
131
|
+
if (matches[0]) {
|
|
132
|
+
try {
|
|
133
|
+
await rememberNames(kw, matches[0]);
|
|
134
|
+
} catch { /* caching is optional */ }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return { ok: true, keyword: kw, matches };
|
|
138
|
+
}
|
package/lib/nyaa.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* nyaa.si client.
|
|
3
|
+
*
|
|
4
|
+
* Search is served by the site's RSS endpoint (`?page=rss&q=…`), which returns
|
|
5
|
+
* title, size, seeders/leechers, category and a `.torrent` link — but **not**
|
|
6
|
+
* the info hash. The hash lives on the torrent's detail page, so it is fetched
|
|
7
|
+
* on demand rather than for every result.
|
|
8
|
+
*
|
|
9
|
+
* Category codes used by the anime top-level (`c=1_0`):
|
|
10
|
+
* 1_1 AMV · 1_2 English-translated · 1_3 Non-English-translated · 1_4 Raw
|
|
11
|
+
*/
|
|
12
|
+
import { fetchText } from './net.js';
|
|
13
|
+
|
|
14
|
+
const DEFAULT_BASE = 'https://nyaa.si';
|
|
15
|
+
const UA = 'dsh-mikan/0.3';
|
|
16
|
+
|
|
17
|
+
const CATEGORY_LABELS = {
|
|
18
|
+
'1_0': '动画(全部)',
|
|
19
|
+
'1_1': '动画 AMV',
|
|
20
|
+
'1_2': '动画 英译',
|
|
21
|
+
'1_3': '动画 中字',
|
|
22
|
+
'1_4': '动画 生肉',
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
function textOf(xml) {
|
|
26
|
+
return String(xml || '')
|
|
27
|
+
.replace(/<!\[CDATA\[|\]\]>/g, '')
|
|
28
|
+
.replace(/&/g, '&')
|
|
29
|
+
.replace(/</g, '<')
|
|
30
|
+
.replace(/>/g, '>')
|
|
31
|
+
.replace(/"/g, '"')
|
|
32
|
+
.replace(/'/g, "'")
|
|
33
|
+
.trim();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function parseRss(xml) {
|
|
37
|
+
const items = [];
|
|
38
|
+
for (const m of String(xml || '').matchAll(/<item>([\s\S]*?)<\/item>/g)) {
|
|
39
|
+
const body = m[1];
|
|
40
|
+
const pick = (tag) => {
|
|
41
|
+
const r = body.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`));
|
|
42
|
+
return r ? textOf(r[1]) : '';
|
|
43
|
+
};
|
|
44
|
+
const num = (tag) => {
|
|
45
|
+
const r = body.match(new RegExp(`<nyaa:${tag}[^>]*>(\\d+)<`));
|
|
46
|
+
return r ? Number(r[1]) : 0;
|
|
47
|
+
};
|
|
48
|
+
const link = pick('link');
|
|
49
|
+
const id = (link.match(/\/download\/(\d+)\.torrent/i) || [])[1] || '';
|
|
50
|
+
const category = (body.match(/<nyaa:category[^>]*>([^<]*)</) || [])[1] || '';
|
|
51
|
+
const categoryId = (body.match(/<nyaa:categoryId>([^<]*)</) || [])[1] || '';
|
|
52
|
+
const title = pick('title');
|
|
53
|
+
if (!title) continue;
|
|
54
|
+
items.push({
|
|
55
|
+
id,
|
|
56
|
+
title,
|
|
57
|
+
category,
|
|
58
|
+
categoryId,
|
|
59
|
+
categoryLabel: CATEGORY_LABELS[categoryId] || category,
|
|
60
|
+
size: (body.match(/<nyaa:size[^>]*>([^<]*)</) || [])[1] || '',
|
|
61
|
+
seeders: num('seeders'),
|
|
62
|
+
leechers: num('leechers'),
|
|
63
|
+
downloads: num('downloads'),
|
|
64
|
+
pubDate: pick('pubDate'),
|
|
65
|
+
torrentUrl: link,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return items;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Create a client bound to one nyaa host.
|
|
73
|
+
* @param {{base?:string, proxy?:string}} [options]
|
|
74
|
+
*/
|
|
75
|
+
export function createNyaaClient(options = {}) {
|
|
76
|
+
const root = String(options.base || DEFAULT_BASE).replace(/\/+$/, '');
|
|
77
|
+
const proxy = options.proxy || '';
|
|
78
|
+
|
|
79
|
+
/** Keyword search over RSS. */
|
|
80
|
+
async function search(keyword, { category = '1_0', limit = 20, timeout = 20000 } = {}) {
|
|
81
|
+
const kw = String(keyword || '').trim();
|
|
82
|
+
if (!kw) return { ok: false, items: [], reason: '搜索关键词为空' };
|
|
83
|
+
const url = `${root}/?page=rss&q=${encodeURIComponent(kw)}&c=${category}&f=0`;
|
|
84
|
+
try {
|
|
85
|
+
const res = await fetchText(url, { proxy, timeout, headers: { 'User-Agent': UA, Accept: 'application/rss+xml, application/xml' } });
|
|
86
|
+
if (res.status === 404) return { ok: true, items: [], reason: '' };
|
|
87
|
+
if (res.status < 200 || res.status >= 300) {
|
|
88
|
+
return { ok: false, items: [], reason: `nyaa 返回 HTTP ${res.status}` };
|
|
89
|
+
}
|
|
90
|
+
const items = parseRss(res.body);
|
|
91
|
+
const cap = Math.max(1, Math.min(Number(limit) || 20, 100));
|
|
92
|
+
return { ok: true, total: items.length, items: items.slice(0, cap) };
|
|
93
|
+
} catch (err) {
|
|
94
|
+
return { ok: false, items: [], reason: `nyaa 请求失败:${err && err.message ? err.message : err}` };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Fetch the info hash and magnet for one torrent id. */
|
|
99
|
+
async function detail(id, { timeout = 20000 } = {}) {
|
|
100
|
+
const tid = String(id || '').replace(/[^\d]/g, '');
|
|
101
|
+
if (!tid) return { ok: false, reason: 'id 无效' };
|
|
102
|
+
try {
|
|
103
|
+
const res = await fetchText(`${root}/view/${tid}`, { proxy, timeout, headers: { 'User-Agent': UA } });
|
|
104
|
+
if (res.status < 200 || res.status >= 300) {
|
|
105
|
+
return { ok: false, reason: `nyaa 详情返回 HTTP ${res.status}` };
|
|
106
|
+
}
|
|
107
|
+
const html = res.body;
|
|
108
|
+
const hash = (html.match(/Info hash[\s\S]{0,200}?([0-9a-fA-F]{40})/i) || [])[1] || '';
|
|
109
|
+
const magnet = (html.match(/href="(magnet:\?[^"]+)"/i) || [])[1] || '';
|
|
110
|
+
return { ok: Boolean(hash || magnet), id: tid, hash: hash.toLowerCase(), magnet: textOf(magnet) };
|
|
111
|
+
} catch (err) {
|
|
112
|
+
return { ok: false, reason: `nyaa 详情请求失败:${err && err.message ? err.message : err}` };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return { search, detail };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export { CATEGORY_LABELS };
|