dsh-mikan 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/constants.js CHANGED
@@ -25,6 +25,8 @@ export const DOW_LABELS = {
25
25
 
26
26
  /** Default plugin configuration. */
27
27
  export const DEFAULT_CONFIG = {
28
+ /** Downloader backend: 'bitcomet' or 'qbittorrent'. */
29
+ downloader: 'bitcomet',
28
30
  /** Empty string = direct connection. */
29
31
  proxy: '',
30
32
  /** BitComet WebUI base URL. */
@@ -32,7 +34,15 @@ export const DEFAULT_CONFIG = {
32
34
  /** BitComet WebUI credentials; read from BitComet.xml when empty. */
33
35
  bitcometUser: '',
34
36
  bitcometPassword: '',
35
- /** Download directory inside BitComet; must be set before downloading. */
37
+ /** qBittorrent WebUI. */
38
+ qbittorrentBase: 'http://127.0.0.1:8080',
39
+ qbittorrentUser: '',
40
+ qbittorrentPassword: '',
41
+ /** Optional custom Mikan mirror; empty means auto-detect between built-ins. */
42
+ mikanBase: '',
43
+ /** Optional custom bgm.tv API base; empty means the official api.bgm.tv. */
44
+ bgmBase: '',
45
+ /** Download directory inside the downloader; must be set before downloading. */
36
46
  savePath: '',
37
47
  /** Minutes between automatic update checks. */
38
48
  checkIntervalMinutes: 30,
package/lib/mikan.js CHANGED
@@ -43,13 +43,18 @@ export function createMikanClient({ base = MIKAN_INSIDE, proxy = '' } = {}) {
43
43
  }
44
44
 
45
45
  /**
46
- * Pick the reachable mirror. Tries the outside domain through the proxy, then
47
- * the inside domain directly, then the outside domain directly.
46
+ * Pick the reachable mirror. A custom mirror wins when configured; otherwise it
47
+ * tries the outside domain through the proxy, then the inside domain directly,
48
+ * then the outside domain directly.
48
49
  * @returns {Promise<{base:string, viaProxy:boolean, reason:string}>}
49
50
  */
50
- export async function detectMikanSource({ proxy = '' } = {}) {
51
+ export async function detectMikanSource({ proxy = '', customBase = '' } = {}) {
51
52
  const probe = { proxy, timeout: 8000 };
52
53
  const attempts = [];
54
+ if (customBase) {
55
+ attempts.push({ base: customBase.replace(/\/+$/, ''), proxy: '', label: 'custom-direct' });
56
+ if (proxy) attempts.push({ base: customBase.replace(/\/+$/, ''), proxy, label: 'custom+proxy' });
57
+ }
53
58
  if (proxy) attempts.push({ base: MIKAN_OUTSIDE, proxy, label: 'outside+proxy' });
54
59
  attempts.push({ base: MIKAN_INSIDE, proxy: '', label: 'inside-direct' });
55
60
  if (proxy) attempts.push({ base: MIKAN_OUTSIDE, proxy: '', label: 'outside-direct' });
@@ -63,7 +68,7 @@ export async function detectMikanSource({ proxy = '' } = {}) {
63
68
  /* try next */
64
69
  }
65
70
  }
66
- return { base: MIKAN_INSIDE, viaProxy: false, reason: 'all-probes-failed' };
71
+ return { base: customBase || MIKAN_INSIDE, viaProxy: false, reason: 'all-probes-failed' };
67
72
  }
68
73
 
69
74
  /** Extract the 40-char info hash from an Episode link. */
@@ -120,7 +125,61 @@ export function parseRss(xml) {
120
125
  return items;
121
126
  }
122
127
 
123
- /** Pull subgroup, series and episode number out of a release title. */
128
+ /**
129
+ * Classify a release's subtitle language into three buckets.
130
+ *
131
+ * - `trad`: traditional Chinese only (繁 / CHT / BIG5 / 繁日)
132
+ * - `simp`: simplified Chinese only (简 / CHS / GB / 简日)
133
+ * - `multi`: both scripts in one release, or multi-language / raw (简繁, 多语, 生肉, unmarked)
134
+ *
135
+ * `繁日` counts as trad and `简日` as simp; only a release carrying both
136
+ * scripts is promoted to `multi`.
137
+ */
138
+ export function detectSubtitleTag(title) {
139
+ const t = String(title || '');
140
+ const hasSimp = /简|簡|CHS|GBK?/i.test(t);
141
+ const hasTrad = /繁|CHT|BIG5/i.test(t);
142
+ if (hasSimp && hasTrad) return 'multi';
143
+ if (hasSimp) return 'simp';
144
+ if (hasTrad) return 'trad';
145
+ return 'multi';
146
+ }
147
+
148
+ /**
149
+ * Parse the full release table on a bangumi page (`/Home/Bangumi/<id>`).
150
+ *
151
+ * The RSS endpoint caps at 100 entries per subgroup, so long-running shows
152
+ * lose their older episodes there. The bangumi page carries the complete
153
+ * list; each row's first bracket segment is the publishing subgroup.
154
+ */
155
+ export function parseBangumiWorks(html) {
156
+ const items = [];
157
+ const seen = new Set();
158
+ for (const m of html.matchAll(/<tr>([\s\S]*?)<\/tr>/g)) {
159
+ const row = m[1];
160
+ const ep = row.match(/<a[^>]*class="magnet-link-wrap"[^>]*href="\/Home\/Episode\/([0-9a-fA-F]{40})"[^>]*>([\s\S]*?)<\/a>/);
161
+ if (!ep) continue;
162
+ const hash = ep[1].toLowerCase();
163
+ if (seen.has(hash)) continue;
164
+ seen.add(hash);
165
+ const title = textOf(ep[2]);
166
+ if (!title) continue;
167
+ const sg = title.match(/^\s*[\[【]([^\]】]{1,40})[\]】]/);
168
+ const parsed = parseReleaseTitle(title);
169
+ const sizeMatch = row.match(/<td>\s*(\d+(?:\.\d+)?\s*[MG]B)\s*<\/td>/);
170
+ items.push({
171
+ hash,
172
+ title,
173
+ subgroup: sg ? sg[1].trim() : parsed.subgroup,
174
+ episode: parsed.episode,
175
+ subtitle: parsed.subtitle,
176
+ size: sizeMatch ? sizeMatch[1] : '',
177
+ });
178
+ }
179
+ return items;
180
+ }
181
+
182
+ /** Pull subgroup, series, episode number and subtitle bucket out of a release title. */
124
183
  export function parseReleaseTitle(rawTitle) {
125
184
  const title = String(rawTitle || '').trim();
126
185
  let subgroup = '';
@@ -147,7 +206,7 @@ export function parseReleaseTitle(rawTitle) {
147
206
  const cut = series.search(/\s*[-–—]\s*\d|\[[^\]]*\d{1,3}[^\]]*\]|第\s*\d+\s*[话話集]|S\d{1,2}E\d/i);
148
207
  if (cut > 0) series = series.slice(0, cut);
149
208
  series = series.replace(/[\[\]【】]/g, ' ').replace(/\s+/g, ' ').trim();
150
- return { subgroup, series, episode };
209
+ return { subgroup, series, episode, subtitle: detectSubtitleTag(title) };
151
210
  }
152
211
 
153
212
  /**
package/lib/mirrors.js ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Community Bangumi mirror directory.
3
+ *
4
+ * https://bangumi.wiki/api/v1/mirrors lists mirrors of the main site along with
5
+ * the services each one exposes (`main`, `next`, `api`, `lain`, `doujin`). Only
6
+ * entries that carry an `api` service are useful here, because the plugin talks
7
+ * to the v0 / search API rather than the website.
8
+ *
9
+ * The directory itself is a third party; a failure to fetch it never becomes an
10
+ * error, it just means no extra candidates are offered.
11
+ */
12
+ import { fetchText } from './net.js';
13
+
14
+ const DIRECTORY_URL = 'https://bangumi.wiki/api/v1/mirrors';
15
+ const CACHE_TTL = 60 * 60 * 1000;
16
+
17
+ let cache = { at: 0, list: [] };
18
+
19
+ /**
20
+ * Return mirrors that expose an `api` service, highest weight first.
21
+ * Cached for an hour; failures fall back to the previous cached list.
22
+ * @param {string} [proxy]
23
+ * @returns {Promise<Array<{name:string, base:string, weight:number, recommended:boolean}>>}
24
+ */
25
+ export async function fetchBgmMirrors(proxy = '') {
26
+ if (Date.now() - cache.at < CACHE_TTL && cache.list.length > 0) return cache.list;
27
+ try {
28
+ // The directory itself is directly reachable; only fall back to the proxy
29
+ // when a direct attempt fails (a configured-but-dead proxy must not block it).
30
+ let res;
31
+ try {
32
+ res = await fetchText(DIRECTORY_URL, { timeout: 8000 });
33
+ } catch {
34
+ res = await fetchText(DIRECTORY_URL, { proxy, timeout: 8000 });
35
+ }
36
+ if (res.status !== 200) return cache.list;
37
+ const data = JSON.parse(res.body);
38
+ const list = [];
39
+ for (const mirror of Array.isArray(data?.mirrors) ? data.mirrors : []) {
40
+ for (const service of Array.isArray(mirror?.services) ? mirror.services : []) {
41
+ if (service?.id !== 'api') continue;
42
+ const host = Array.isArray(service.hosts) && service.hosts[0];
43
+ if (!host) continue;
44
+ list.push({
45
+ name: mirror.name || host,
46
+ base: `https://${host}`,
47
+ weight: Number(mirror.weight) || 0,
48
+ recommended: Boolean(mirror.recommended),
49
+ });
50
+ }
51
+ }
52
+ list.sort((a, b) => b.weight - a.weight);
53
+ cache = { at: Date.now(), list };
54
+ return list;
55
+ } catch {
56
+ return cache.list;
57
+ }
58
+ }
package/lib/net.js CHANGED
@@ -176,12 +176,20 @@ function requestDirect(url, opts) {
176
176
  return new Promise((resolve, reject) => {
177
177
  const u = new URL(url);
178
178
  const mod = u.protocol === 'https:' ? https : http;
179
+ const bodyBuf = opts.body === undefined ? null : Buffer.from(String(opts.body), 'utf8');
180
+ const headers = {
181
+ 'User-Agent': 'dsh-mikan/0.1',
182
+ 'Accept-Encoding': 'identity',
183
+ ...(opts.headers || {}),
184
+ };
185
+ // qBittorrent rejects chunked multipart bodies, so always declare the length.
186
+ if (bodyBuf && headers['content-length'] === undefined) headers['content-length'] = bodyBuf.length;
179
187
  const req = mod.request({
180
188
  host: u.hostname,
181
189
  port: u.port || (u.protocol === 'https:' ? 443 : 80),
182
190
  path: u.pathname + u.search,
183
191
  method: opts.method || 'GET',
184
- headers: { 'User-Agent': 'dsh-mikan/0.1', 'Accept-Encoding': 'identity', ...(opts.headers || {}) },
192
+ headers,
185
193
  timeout: opts.timeout || 20000,
186
194
  }, (res) => {
187
195
  const chunks = [];
@@ -199,7 +207,7 @@ function requestDirect(url, opts) {
199
207
  });
200
208
  req.on('timeout', () => { req.destroy(); reject(new Error(`request timeout ${url}`)); });
201
209
  req.on('error', reject);
202
- if (opts.body) req.write(opts.body);
210
+ if (bodyBuf) req.write(bodyBuf);
203
211
  req.end();
204
212
  });
205
213
  }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * qBittorrent WebAPI v2 client.
3
+ *
4
+ * qB uses a cookie session (`SID`) obtained from `/api/v2/auth/login`, and
5
+ * expects a matching `Referer` on state-changing calls. Magnet uploads go
6
+ * through `multipart/form-data`. Every method mirrors the BitComet client so
7
+ * the plugin can switch downloaders without touching call sites.
8
+ */
9
+ import { fetchText } from './net.js';
10
+
11
+ const AUTH_REQUIRED = '未配置 qBittorrent 账号密码';
12
+
13
+ function cookieFrom(headers) {
14
+ const raw = headers['set-cookie'];
15
+ if (!raw) return '';
16
+ const list = Array.isArray(raw) ? raw : [raw];
17
+ const parts = list
18
+ .map((c) => String(c).split(';')[0])
19
+ .filter((c) => c && c.includes('='));
20
+ return parts.join('; ');
21
+ }
22
+
23
+ function multipartBody(fields) {
24
+ // qB's parser is happier with the long dashed boundary curl emits.
25
+ const boundary = '------------------------' + Math.random().toString(16).slice(2) + Date.now().toString(16);
26
+ const chunks = [];
27
+ for (const [key, value] of Object.entries(fields)) {
28
+ chunks.push(
29
+ `--${boundary}\r\n`,
30
+ `Content-Disposition: form-data; name="${key}"\r\n\r\n`,
31
+ String(value),
32
+ '\r\n',
33
+ );
34
+ }
35
+ chunks.push(`--${boundary}--\r\n`);
36
+ return { boundary, body: chunks.join('') };
37
+ }
38
+
39
+ /**
40
+ * Create a client bound to one qBittorrent WebUI.
41
+ * @param {{base?:string, user?:string, password?:string, proxy?:string}} [options]
42
+ */
43
+ export function createQbittorrentClient(options = {}) {
44
+ const base = String(options.base || 'http://127.0.0.1:8080').replace(/\/+$/, '');
45
+ const user = String(options.user || '');
46
+ const password = String(options.password || '');
47
+ const proxy = options.proxy || '';
48
+ let sid = '';
49
+
50
+ async function login() {
51
+ // qB's Web UI can allow localhost without authentication; an empty
52
+ // credential pair means the caller relies on that bypass.
53
+ if (!user || !password) return '';
54
+ const res = await fetchText(`${base}/api/v2/auth/login`, {
55
+ proxy,
56
+ method: 'POST',
57
+ headers: {
58
+ 'content-type': 'application/x-www-form-urlencoded',
59
+ referer: base,
60
+ },
61
+ body: `username=${encodeURIComponent(user)}&password=${encodeURIComponent(password)}`,
62
+ timeout: 15000,
63
+ });
64
+ if (res.status !== 200 || !/Ok\./.test(res.body)) {
65
+ throw new Error(`qBittorrent 登录失败(HTTP ${res.status}):账号或密码错误`);
66
+ }
67
+ sid = cookieFrom(res.headers);
68
+ if (!sid) throw new Error('qBittorrent 登录失败:没有返回会话 Cookie');
69
+ return sid;
70
+ }
71
+
72
+ async function call(path, { method = 'GET', body, headers = {}, type, retry = true } = {}) {
73
+ const send = async () => fetchText(base + path, {
74
+ proxy,
75
+ method,
76
+ headers: {
77
+ referer: base,
78
+ ...(sid ? { cookie: sid } : {}),
79
+ ...(type ? { 'content-type': type } : {}),
80
+ ...headers,
81
+ },
82
+ body,
83
+ timeout: 20000,
84
+ });
85
+ let res = await send();
86
+ if (res.status === 403 && retry) {
87
+ // session expired or not yet established
88
+ await login();
89
+ res = await send();
90
+ }
91
+ return res;
92
+ }
93
+
94
+ /** Confirm the WebUI answers and the credentials work. */
95
+ async function checkAuth() {
96
+ try {
97
+ await login();
98
+ const res = await call('/api/v2/app/version');
99
+ if (res.status !== 200) return { ok: false, reason: `HTTP ${res.status}` };
100
+ return { ok: true, version: res.body.trim() };
101
+ } catch (err) {
102
+ return { ok: false, reason: err.message };
103
+ }
104
+ }
105
+
106
+ /** All torrents as `{ id, name, state, size, progress, downSpeed, upSpeed }`. */
107
+ async function listTasks() {
108
+ if (!sid) await login();
109
+ const res = await call('/api/v2/torrents/info');
110
+ if (res.status !== 200) throw new Error(`qBittorrent 任务列表失败(HTTP ${res.status})`);
111
+ const list = JSON.parse(res.body || '[]');
112
+ return (Array.isArray(list) ? list : []).map((t) => ({
113
+ id: String(t.hash || ''),
114
+ name: t.name || '',
115
+ state: t.state || '',
116
+ size: Number(t.size) || 0,
117
+ progress: Number(t.progress) || 0,
118
+ downSpeed: Number(t.dlspeed) || 0,
119
+ upSpeed: Number(t.upspeed) || 0,
120
+ }));
121
+ }
122
+
123
+ /** Add one magnet; returns `{ ok, message }`. */
124
+ async function addMagnet(magnet, savePath) {
125
+ if (!sid) await login();
126
+ const fields = { urls: magnet, paused: 'false' };
127
+ if (savePath) fields.savepath = savePath;
128
+ const { boundary, body } = multipartBody(fields);
129
+ const res = await call('/api/v2/torrents/add', {
130
+ method: 'POST',
131
+ type: `multipart/form-data; boundary=${boundary}`,
132
+ body,
133
+ });
134
+ const text = String(res.body || '').trim();
135
+ const ok = res.status === 200 && (/Ok/i.test(text) || text === '');
136
+ return { ok, message: text || `HTTP ${res.status}` };
137
+ }
138
+
139
+ /** Delete one torrent by hash; qB answers 200 and the list confirms. */
140
+ async function deleteTask(hash) {
141
+ if (!sid) await login();
142
+ const res = await call('/api/v2/torrents/delete', {
143
+ method: 'POST',
144
+ type: 'application/x-www-form-urlencoded',
145
+ body: `hashes=${encodeURIComponent(hash)}&deleteFiles=false`,
146
+ });
147
+ let verified = false;
148
+ try {
149
+ const tasks = await listTasks();
150
+ verified = !tasks.some((t) => t.id.toLowerCase() === String(hash).toLowerCase());
151
+ } catch { /* leave unverified */ }
152
+ return { ok: res.status === 200, verified };
153
+ }
154
+
155
+ /** Find a task whose name contains the fragment. */
156
+ async function hasTaskByName(fragment) {
157
+ const needle = String(fragment || '').toLowerCase();
158
+ if (!needle) return null;
159
+ const tasks = await listTasks();
160
+ return tasks.find((t) => t.name.toLowerCase().includes(needle)) || null;
161
+ }
162
+
163
+ return { listTasks, addMagnet, deleteTask, checkAuth, hasTaskByName };
164
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-mikan",
3
- "version": "0.1.0",
4
- "description": "Mikan Project tracker with BitComet integration: browse seasons, follow subgroups, and send confirmed releases to BitComet.",
3
+ "version": "0.2.1",
4
+ "description": "Mikan Project tracker for DeepSeek Harness: browse current and past seasons, follow subgroups, and send confirmed releases to BitComet or qBittorrent.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "琉璃羽Ryuribana",
@@ -12,6 +12,7 @@
12
12
  "mikan",
13
13
  "anime",
14
14
  "bitcomet",
15
+ "qbittorrent",
15
16
  "rss"
16
17
  ],
17
18
  "exports": {
@@ -27,7 +28,10 @@
27
28
  "cordis.patch.yml",
28
29
  "locale/*.json",
29
30
  "docs",
30
- "icon.svg"
31
+ "icon.svg",
32
+ "README.md",
33
+ "LICENSE",
34
+ "CHANGELOG.md"
31
35
  ],
32
36
  "dsh": {
33
37
  "bundle": {