dsh-wechat-access 0.0.0-stage → 0.0.2

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +675 -0
  3. package/README.md +278 -2
  4. package/cordis.patch.yml +5 -0
  5. package/examples/config.example.json +98 -0
  6. package/index.mjs +123 -0
  7. package/lib/access.mjs +131 -0
  8. package/lib/anysearch.mjs +143 -0
  9. package/lib/capabilities.mjs +312 -0
  10. package/lib/client.js +2532 -0
  11. package/lib/config.mjs +509 -0
  12. package/lib/emotion-store.mjs +352 -0
  13. package/lib/emotion.mjs +428 -0
  14. package/lib/endocrine/LICENSE +21 -0
  15. package/lib/endocrine/README.md +39 -0
  16. package/lib/endocrine/diseases.js +791 -0
  17. package/lib/endocrine/engine.mjs +131 -0
  18. package/lib/endocrine/store.mjs +253 -0
  19. package/lib/endocrine/upstream.mjs +1230 -0
  20. package/lib/group-gate.mjs +305 -0
  21. package/lib/imagegen.mjs +360 -0
  22. package/lib/lock.mjs +204 -0
  23. package/lib/meme-classify.mjs +190 -0
  24. package/lib/memes.mjs +442 -0
  25. package/lib/memory.mjs +437 -0
  26. package/lib/normalize.mjs +230 -0
  27. package/lib/parser.mjs +602 -0
  28. package/lib/reply-settled.mjs +130 -0
  29. package/lib/runtime.mjs +3367 -0
  30. package/lib/startup.mjs +70 -0
  31. package/lib/steam-binding.mjs +144 -0
  32. package/lib/steam.mjs +334 -0
  33. package/lib/store.mjs +259 -0
  34. package/lib/thoughts.mjs +149 -0
  35. package/lib/time-context.mjs +182 -0
  36. package/lib/tools.mjs +583 -0
  37. package/lib/ui.mjs +997 -0
  38. package/lib/util.mjs +489 -0
  39. package/lib/virtual-life-generate.mjs +421 -0
  40. package/lib/virtual-life.mjs +971 -0
  41. package/lib/weather.mjs +172 -0
  42. package/lib/wechat-client.mjs +476 -0
  43. package/lib/wechat-events.mjs +269 -0
  44. package/locale/zh.json +6 -0
  45. package/package.json +77 -4
package/lib/parser.mjs ADDED
@@ -0,0 +1,602 @@
1
+ /**
2
+ * Link parser: turn a pasted social-media link into something worth sending.
3
+ *
4
+ * Ported in spirit from astrbot_plugin_parser, but this is not a translation:
5
+ * that project is Python and renders PIL cards, while this plugin speaks Node and
6
+ * sends plain text plus real media. What is kept is the useful half -- recognise
7
+ * a link, ask the platform for its metadata, and hand back images and a caption.
8
+ *
9
+ * VIDEO IS NEVER DOWNLOADED. A phone-shot clip is tens of megabytes and QQ caps
10
+ * what it will accept, so a video link is answered with its title, cover and the
11
+ * original URL. Galleries (which are small and are the actual reason to parse)
12
+ * are sent as images.
13
+ *
14
+ * Every platform degrades to "link only" instead of throwing: a parser that
15
+ * breaks the reply is worse than one that echoes the URL.
16
+ */
17
+ import { appendFileSync } from 'node:fs';
18
+ import { homedir } from 'node:os';
19
+ import { join } from 'node:path';
20
+
21
+ const DESKTOP_UA =
22
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
23
+ const MOBILE_UA =
24
+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1';
25
+
26
+ function trace(line) {
27
+ try {
28
+ appendFileSync(
29
+ join(homedir(), '.dsh-qq-access', 'debug.log'),
30
+ new Date().toISOString() + ' parse ' + line + '\n',
31
+ );
32
+ } catch { /* diagnostics must never break parsing */ }
33
+ }
34
+
35
+ /** Fetch a URL as text, following redirects, with a hard per-request budget. */
36
+ async function fetchText(url, { timeoutMs = 15_000, ua = DESKTOP_UA, headers = {} } = {}) {
37
+ // `ua: ''` means "send no User-Agent at all", which is not the same as sending an
38
+ // empty one: at least one API (B站) treats the presence of a browser UA as a
39
+ // risk-control signal and only answers 200 when the header is absent.
40
+ const base = {
41
+ 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
42
+ accept: 'text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8',
43
+ };
44
+ if (ua) base['user-agent'] = ua;
45
+ const response = await fetch(url, {
46
+ // 不跟随跳转。
47
+ // 短链(b23.tv / xhslink.com)若跳到内网或元数据地址,请求是插件进程发的,
48
+ // 正文会进模型和回复。平台匹配只保证「起始 URL 是已知平台的」,
49
+ // 管不住它跳到哪里。
50
+ redirect: 'error',
51
+ signal: AbortSignal.timeout(timeoutMs),
52
+ headers: { ...base, ...headers },
53
+ });
54
+ if (!response.ok) throw new Error('HTTP ' + response.status);
55
+ return { text: await response.text(), finalUrl: response.url };
56
+ }
57
+
58
+ /**
59
+ * 短链跳转:只在「平台自己的域名」和白名单短链中转域名之间跟,最多 3 跳,只走 https。
60
+ *
61
+ * 为什么需要它:b23.tv 和 xhslink.com 本身不含任何内容,只回一个 302。
62
+ * 而 fetchText 固定 redirect: 'error'(用来挡住跳到内网),于是这两个最常见
63
+ * 的分享形态永远解析失败 —— QQ 的分享卡片几乎都是短链。
64
+ *
65
+ * 所以单独走一条受控的跟随路径:
66
+ * - 只跟 3xx,手动处理 Location
67
+ * - 每一跳的域名必须在 allowHosts(平台)或 relayHosts(短链中转)里
68
+ * - 终点必须落在 allowHosts 里 —— 中转域名永远不能当作结果
69
+ * - 强制 https
70
+ * - 本机地址 / IP 字面量一律拒绝
71
+ * 最后两条是底线:短链是别人发来的,不能让它把插件进程导向内网。
72
+ */
73
+ const SHORT_LINK_MAX_HOPS = 3;
74
+
75
+ /**
76
+ * 允许作为「中转」的短链服务域名。
77
+ *
78
+ * 有些分享会先绕一跳第三方短链(t.cn、url.cn 之类)才回到平台,只按平台域名
79
+ * 校验会直接失败。所以开一个显式名单 —— 注意开放的是「已知短链服务」,
80
+ * 不是「任意域名」:
81
+ * - 名单之外的一律拒绝
82
+ * - 每一跳仍然过 blockedHost(挡内网)
83
+ * - 终点必须回到平台域名,停在中转域名上算失败
84
+ */
85
+ export const SHORT_LINK_RELAY_HOSTS = Object.freeze([
86
+ 't.cn', 'url.cn', 'dwz.cn', 'suo.im', 'm.tb.cn', 's.click.taobao.com', 'link.zhihu.com',
87
+ ]);
88
+
89
+ /** 本机、私网、IP 字面量一律视为不可访问。 */
90
+ export function blockedHost(hostname) {
91
+ const h = String(hostname ?? '').toLowerCase().replace(/^\[|\]$/g, '');
92
+ if (!h) return true;
93
+ if (h === 'localhost' || h.endsWith('.localhost')) return true;
94
+ // 纯 IP(v4 点分或任何含冒号的 v6)都不允许:平台域名不长这样。
95
+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(h)) return true;
96
+ if (h.includes(':')) return true;
97
+ return false;
98
+ }
99
+
100
+ export function hostAllowed(hostname, allowHosts) {
101
+ const h = String(hostname ?? '').toLowerCase();
102
+ return (allowHosts ?? []).some((suffix) => {
103
+ const sfx = String(suffix ?? '').toLowerCase();
104
+ return h === sfx || h.endsWith('.' + sfx);
105
+ });
106
+ }
107
+
108
+ /** 这一跳是否允许:平台域名,或白名单里的短链中转域名。 */
109
+ export function hopAllowed(hostname, { allowHosts = [], relayHosts = [] } = {}) {
110
+ return hostAllowed(hostname, allowHosts) || hostAllowed(hostname, relayHosts);
111
+ }
112
+
113
+ async function resolveShortLink(startUrl, {
114
+ allowHosts = [],
115
+ relayHosts = SHORT_LINK_RELAY_HOSTS,
116
+ timeoutMs = 15_000,
117
+ ua = MOBILE_UA,
118
+ } = {}) {
119
+ let current = String(startUrl);
120
+ for (let hop = 0; hop < SHORT_LINK_MAX_HOPS; hop++) {
121
+ const url = new URL(current);
122
+ if (url.protocol !== 'https:') throw new Error('短链只允许 https');
123
+ if (blockedHost(url.hostname)) throw new Error('短链指向本机地址');
124
+ const onPlatform = hostAllowed(url.hostname, allowHosts);
125
+ if (!onPlatform && !hostAllowed(url.hostname, relayHosts)) {
126
+ throw new Error('短链跳到了不允许的域名:' + url.hostname);
127
+ }
128
+ const headers = { 'accept-language': 'zh-CN,zh;q=0.9', accept: 'text/html,*/*;q=0.8' };
129
+ if (ua) headers['user-agent'] = ua;
130
+ const response = await fetch(url, {
131
+ redirect: 'manual',
132
+ signal: AbortSignal.timeout(timeoutMs),
133
+ headers,
134
+ });
135
+ const location = response.headers.get('location');
136
+ if (!location) {
137
+ // 没有 Location 就是终点了 —— 但必须落在平台域名上。
138
+ // 中转域名自己回一个 200 错误页(没解开)时不能当结果用。
139
+ if (!onPlatform) throw new Error('短链停在中转域名上,没有落到平台:' + url.hostname);
140
+ if (!response.ok) throw new Error('HTTP ' + response.status);
141
+ return { finalUrl: url.toString(), text: await response.text() };
142
+ }
143
+ current = new URL(location, url).toString();
144
+ }
145
+ throw new Error('短链跳转次数过多');
146
+ }
147
+
148
+ async function fetchJson(url, options) {
149
+ const { text, finalUrl } = await fetchText(url, options);
150
+ return { data: JSON.parse(text), finalUrl };
151
+ }
152
+
153
+ const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', '#39': "'" };
154
+
155
+ function decodeEntities(value) {
156
+ return String(value ?? '')
157
+ .replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (whole, code) => {
158
+ const key = code.toLowerCase();
159
+ if (ENTITIES[key] !== undefined) return ENTITIES[key];
160
+ if (key.startsWith('#x')) return String.fromCodePoint(parseInt(key.slice(2), 16));
161
+ if (key.startsWith('#')) return String.fromCodePoint(parseInt(key.slice(1), 10));
162
+ return whole;
163
+ })
164
+ .replace(/\\u([0-9a-f]{4})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
165
+ }
166
+
167
+ /** Pull `<meta property/name=... content=...>` pairs out of an HTML document. */
168
+ function metaTags(html) {
169
+ const out = {};
170
+ for (const tag of html.match(/<meta\s[^>]*>/gi) ?? []) {
171
+ const key = tag.match(/(?:property|name)\s*=\s*["']([^"']+)["']/i)?.[1];
172
+ const value = tag.match(/content\s*=\s*["']([^"']*)["']/i)?.[1];
173
+ if (!key || value === undefined) continue;
174
+ const name = key.toLowerCase();
175
+ if (out[name] === undefined) out[name] = decodeEntities(value);
176
+ }
177
+ return out;
178
+ }
179
+
180
+ /** Collect image URLs a page declares through the usual social-media tags. */
181
+ function imageTags(html, meta) {
182
+ const found = [];
183
+ for (const key of ['og:image', 'og:image:secure_url', 'twitter:image', 'twitter:image:src']) {
184
+ if (meta[key]) found.push(meta[key]);
185
+ }
186
+ // Some sites only expose the gallery as JSON-LD.
187
+ for (const block of html.match(/<script[^>]+application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi) ?? []) {
188
+ const body = block.replace(/^[\s\S]*?>/, '').replace(/<\/script>$/i, '');
189
+ try {
190
+ const walk = (node) => {
191
+ if (Array.isArray(node)) return node.forEach(walk);
192
+ if (!node || typeof node !== 'object') return;
193
+ for (const [k, v] of Object.entries(node)) {
194
+ if (/^(image|contentUrl|thumbnailUrl)$/i.test(k)) {
195
+ if (typeof v === 'string') found.push(v);
196
+ else if (Array.isArray(v)) v.forEach((x) => typeof x === 'string' && found.push(x));
197
+ else if (v && typeof v === 'object' && typeof v.url === 'string') found.push(v.url);
198
+ } else walk(v);
199
+ }
200
+ };
201
+ walk(JSON.parse(body));
202
+ } catch { /* a malformed JSON-LD block is not an error */ }
203
+ }
204
+ return found;
205
+ }
206
+
207
+ /** Make a possibly relative or protocol-relative URL absolute, and reject junk. */
208
+ function absolute(url, base) {
209
+ const raw = String(url ?? "").trim();
210
+ if (!raw || raw.startsWith("data:")) return "";
211
+ try {
212
+ const resolved = new URL(raw.startsWith("//") ? "https:" + raw : raw, base);
213
+ if (resolved.protocol === "http:") {
214
+ // QQ fetches media over https and silently drops an http cover, so upgrade
215
+ // it here instead of handing the client a URL it will not use.
216
+ resolved.protocol = "https:";
217
+ }
218
+ return resolved.protocol === "https:" ? resolved.href : "";
219
+ } catch { return ""; }
220
+ }
221
+
222
+ function unique(list) {
223
+ return [...new Set(list.filter(Boolean))];
224
+ }
225
+
226
+ function formatCount(value) {
227
+ const n = Number(value);
228
+ if (!Number.isFinite(n) || n <= 0) return '';
229
+ if (n >= 100_000_000) return (n / 100_000_000).toFixed(1) + '亿';
230
+ if (n >= 10_000) return (n / 10_000).toFixed(1) + '万';
231
+ return String(n);
232
+ }
233
+
234
+ function formatDuration(seconds) {
235
+ const total = Number(seconds);
236
+ if (!Number.isFinite(total) || total <= 0) return '';
237
+ const m = Math.floor(total / 60);
238
+ const s = Math.floor(total % 60);
239
+ return m + ':' + String(s).padStart(2, '0');
240
+ }
241
+
242
+ /**
243
+ * One parser per platform.
244
+ *
245
+ * `match` receives the URL and returns an id/context or null. `parse` receives
246
+ * that context plus the shared fetch helpers and returns a result object; it may
247
+ * throw, in which case the caller falls back to a link-only reply.
248
+ */
249
+ const PARSERS = [
250
+ {
251
+ id: 'bilibili',
252
+ name: 'B站',
253
+ match(url) {
254
+ if (/(^|\.)b23\.tv$/i.test(url.hostname)) return { short: true };
255
+ if (!/(^|\.)bilibili\.com$/i.test(url.hostname)) return null;
256
+ const bv = url.pathname.match(/\/(BV[0-9A-Za-z]+)/);
257
+ if (bv) return { bvid: bv[1] };
258
+ const av = url.pathname.match(/\/av(\d+)/i);
259
+ if (av) return { aid: av[1] };
260
+ return null;
261
+ },
262
+ async parse(ctx, helpers) {
263
+ let { bvid, aid } = ctx;
264
+ let base = 'https://www.bilibili.com/';
265
+ if (ctx.short) {
266
+ // b23.tv 只回 302,必须在受控范围内跟一跳才知道指向哪个视频。
267
+ // 只允许留在 B 站自己的域名里,最多 3 跳。
268
+ const { finalUrl } = await helpers.resolveShortLink('https://' + helpers.host + helpers.pathname, {
269
+ allowHosts: ['b23.tv', 'bilibili.com'],
270
+ });
271
+ const m = String(finalUrl).match(/\/(BV[0-9A-Za-z]+)/);
272
+ if (!m) throw new Error('短链未指向视频');
273
+ bvid = m[1];
274
+ base = finalUrl;
275
+ }
276
+ const query = bvid ? 'bvid=' + bvid : 'aid=' + aid;
277
+ // Deliberately NO User-Agent. Measured against the live API: a Chrome UA
278
+ // answers HTTP 412 (-412 risk control) while an empty header set answers 200.
279
+ // Sending the "polite" headers here is what breaks it.
280
+ const { data } = await helpers.fetchJson('https://api.bilibili.com/x/web-interface/view?' + query, {
281
+ ua: '',
282
+ headers: {},
283
+ });
284
+ if (data?.code !== 0 || !data.data) throw new Error('B站接口返回 ' + (data?.code ?? 'unknown'));
285
+ const v = data.data;
286
+ const stat = v.stat ?? {};
287
+ const parts = [
288
+ '▶ ' + formatCount(stat.view),
289
+ '👍 ' + formatCount(stat.like),
290
+ '🪙 ' + formatCount(stat.coin),
291
+ '⭐ ' + formatCount(stat.favorite),
292
+ ].filter((p) => !p.endsWith(' '));
293
+ return {
294
+ platform: 'bilibili',
295
+ platformName: 'B站',
296
+ kind: 'video',
297
+ url: 'https://www.bilibili.com/video/' + v.bvid,
298
+ title: v.title,
299
+ author: v.owner?.name,
300
+ description: v.desc,
301
+ cover: absolute(v.pic, 'https://www.bilibili.com/'),
302
+ images: [],
303
+ meta: [formatDuration(v.duration), parts.join(' ')].filter(Boolean).join(' · '),
304
+ };
305
+ },
306
+ },
307
+ {
308
+ id: 'youtube',
309
+ name: 'YouTube',
310
+ match(url) {
311
+ if (/(^|\.)youtu\.be$/i.test(url.hostname)) return { id: url.pathname.slice(1) };
312
+ if (!/(^|\.)youtube\.com$/i.test(url.hostname)) return null;
313
+ const v = url.searchParams.get('v');
314
+ if (v) return { id: v };
315
+ const shorts = url.pathname.match(/\/(?:shorts|embed)\/([\w-]+)/);
316
+ return shorts ? { id: shorts[1] } : null;
317
+ },
318
+ async parse(ctx, helpers) {
319
+ const canonical = 'https://www.youtube.com/watch?v=' + ctx.id;
320
+ // oEmbed needs no key and answers with exactly the fields worth showing.
321
+ const { data } = await helpers.fetchJson(
322
+ 'https://www.youtube.com/oembed?format=json&url=' + encodeURIComponent(canonical),
323
+ );
324
+ return {
325
+ platform: 'youtube',
326
+ platformName: 'YouTube',
327
+ kind: 'video',
328
+ url: canonical,
329
+ title: data.title,
330
+ author: data.author_name,
331
+ description: '',
332
+ cover: absolute(data.thumbnail_url, 'https://www.youtube.com/'),
333
+ images: [],
334
+ meta: '',
335
+ };
336
+ },
337
+ },
338
+ {
339
+ id: 'twitter',
340
+ name: 'X',
341
+ match(url) {
342
+ if (!/(^|\.)(x|twitter)\.com$/i.test(url.hostname)) return null;
343
+ const m = url.pathname.match(/\/status(?:es)?\/(\d+)/);
344
+ return m ? { id: m[1], handle: url.pathname.split('/')[1] || '' } : null;
345
+ },
346
+ async parse(ctx, helpers) {
347
+ // fxtwitter is a public mirror that returns the tweet as JSON, including
348
+ // media, without needing a token. It falls back to the OG tags below.
349
+ const canonical = 'https://x.com/' + (ctx.handle ? ctx.handle + '/' : 'i/') + 'status/' + ctx.id;
350
+ // fxtwitter mirrors a tweet as JSON without a token. The handle form is
351
+ // tried first because that is the shape its resolver expects; `i` is the
352
+ // documented fallback for links whose handle segment is not a username.
353
+ let tweet;
354
+ for (const prefix of [ctx.handle, 'i'].filter(Boolean)) {
355
+ try {
356
+ const { data } = await helpers.fetchJson('https://api.fxtwitter.com/' + prefix + '/status/' + ctx.id);
357
+ if (data?.tweet) { tweet = data.tweet; break; }
358
+ } catch { /* try the next shape */ }
359
+ }
360
+ if (!tweet) throw new Error('X 接口未返回内容');
361
+ const photos = (tweet.media?.photos ?? []).map((p) => absolute(p.url, 'https://x.com/'));
362
+ const videos = (tweet.media?.videos ?? []).map((v) => absolute(v.thumbnail_url, 'https://x.com/')).filter(Boolean);
363
+ return {
364
+ platform: 'twitter',
365
+ platformName: 'X',
366
+ kind: photos.length ? 'gallery' : 'video',
367
+ url: canonical,
368
+ title: String(tweet.text ?? '').split('\n')[0].slice(0, 120),
369
+ author: '@' + (tweet.author?.screen_name ?? ctx.handle),
370
+ description: String(tweet.text ?? '').slice(0, 400),
371
+ cover: videos[0] ?? photos[0] ?? '',
372
+ images: photos,
373
+ meta: [formatCount(tweet.likes), formatCount(tweet.replies)].filter(Boolean).join(' · '),
374
+ };
375
+ },
376
+ },
377
+ {
378
+ id: 'xiaohongshu',
379
+ name: '小红书',
380
+ match(url) {
381
+ if (/(^|\.)xhslink\.com$/i.test(url.hostname)) return { short: true };
382
+ if (!/(^|\.)xiaohongshu\.com$/i.test(url.hostname)) return null;
383
+ const m = url.pathname.match(/\/(?:explore|discovery\/item|note)\/([0-9a-f]+)/i);
384
+ return m ? { noteId: m[1] } : null;
385
+ },
386
+ async parse(ctx, helpers) {
387
+ let target = ctx.short ? null : "https://www.xiaohongshu.com/explore/" + ctx.noteId;
388
+ let page = null;
389
+ if (ctx.short) {
390
+ // 同上:xhslink.com 也只回 302。只允许留在小红书自己的域名里。
391
+ // resolveShortLink 在终点已经读过正文(它默认就用 MOBILE_UA),
392
+ // 直接复用 —— 再 fetchText 一次不只是白跑一趟:
393
+ // fetchText 是 redirect: "error",落地页若还有一次规范化跳转
394
+ //(http→https、m 站→主站)就会直接抛 fetch failed。
395
+ page = await helpers.resolveShortLink("https://" + helpers.host + helpers.pathname, {
396
+ allowHosts: ['xhslink.com', 'xiaohongshu.com'],
397
+ });
398
+ target = page.finalUrl;
399
+ }
400
+ if (!page) page = await helpers.fetchText(target, { ua: MOBILE_UA });
401
+ const finalUrl = page.finalUrl || target;
402
+ // 短链(xhslink.com)匹配时没有 noteId,真正的 id 在跳转后的地址里。
403
+ // 以前直接拿 ctx.noteId 拼 URL,404 分支和成功分支都会写出
404
+ // https://www.xiaohongshu.com/explore/undefined。从 finalUrl 里补一次。
405
+ const resolvedNoteId = String(ctx.noteId ?? '')
406
+ || (String(finalUrl).match(/\/(?:explore|discovery\/item|note)\/([0-9a-f]+)/i)?.[1] ?? '');
407
+ const noteUrl = resolvedNoteId
408
+ ? 'https://www.xiaohongshu.com/explore/' + resolvedNoteId
409
+ : finalUrl;
410
+ // A note that does not exist (or is region-blocked) redirects to an error
411
+ // page whose og:title is the error URL itself. Detect that shape instead of
412
+ // publishing a wall of percent-encoded query string as a "title".
413
+ if (/\/404\/|error_code=|当前笔记暂时无法浏览|sec_/i.test(finalUrl) || /\/404\/|error_code=/i.test(page.text.slice(0, 4000))) {
414
+ return {
415
+ platform: "xiaohongshu",
416
+ platformName: "小红书",
417
+ kind: "video",
418
+ url: noteUrl,
419
+ title: "",
420
+ author: "",
421
+ description: "",
422
+ cover: "",
423
+ images: [],
424
+ meta: "",
425
+ linkOnly: true,
426
+ };
427
+ }
428
+ const meta = metaTags(page.text);
429
+ const inline = [...page.text.matchAll(/https?:\/\/sns-img[^"'\\\s)]+/gi)].map((m) => m[0]);
430
+ const images = unique([...imageTags(page.text, meta), ...inline].map((u) => absolute(u, finalUrl)));
431
+ const title = (meta["og:title"] || meta.title || "").replace(/\s*-\s*小红书.*$/, "").trim();
432
+ const description = (meta["og:description"] || meta.description || "").slice(0, 300);
433
+ return {
434
+ platform: "xiaohongshu",
435
+ platformName: "小红书",
436
+ kind: images.length > 1 ? "gallery" : "video",
437
+ url: noteUrl,
438
+ title: title.slice(0, 140),
439
+ author: "",
440
+ description,
441
+ cover: images[0] ?? "",
442
+ images: images.slice(1),
443
+ meta: "",
444
+ linkOnly: !title && images.length === 0,
445
+ };
446
+ },
447
+ },
448
+ {
449
+ id: 'instagram',
450
+ name: 'Instagram',
451
+ match(url) {
452
+ if (!/(^|\.)instagram\.com$/i.test(url.hostname)) return null;
453
+ const m = url.pathname.match(/\/(?:p|reel|reels|tv)\/([\w-]+)/);
454
+ return m ? { code: m[1] } : null;
455
+ },
456
+ async parse(ctx, helpers) {
457
+ const canonical = 'https://www.instagram.com/p/' + ctx.code + '/';
458
+ // Instagram answers every anonymous request with a login wall: measured on
459
+ // /p/<code>/embed/captioned/ for empty, bogus and plausible codes alike --
460
+ // identical ~186 KB pages, all carrying a login prompt and no media tags.
461
+ // The upstream Python project reads it through gallery-dl plus cookies, which
462
+ // this plugin has no equivalent of, so this platform degrades to link-only
463
+ // rather than failing the whole reply.
464
+ let title = "";
465
+ let images = [];
466
+ try {
467
+ const page = await helpers.fetchText(canonical, { ua: DESKTOP_UA });
468
+ const meta = metaTags(page.text);
469
+ title = meta["og:title"] || "";
470
+ images = unique(imageTags(page.text, meta).map((u) => absolute(u, page.finalUrl)));
471
+ } catch { /* the link itself is still worth sending */ }
472
+ return {
473
+ platform: 'instagram',
474
+ platformName: 'Instagram',
475
+ kind: images.length > 1 ? 'gallery' : 'video',
476
+ url: canonical,
477
+ title: title.slice(0, 140),
478
+ author: '',
479
+ description: '',
480
+ cover: images[0] ?? '',
481
+ images: images.slice(1),
482
+ meta: '',
483
+ linkOnly: !title && images.length === 0,
484
+ };
485
+ },
486
+ },
487
+ {
488
+ id: 'xiaoheihe',
489
+ name: '小黑盒',
490
+ match(url) {
491
+ if (!/(^|\.)xiaoheihe\.cn$/i.test(url.hostname)) return null;
492
+ const m = url.pathname.match(/\/(?:bbs\/)?(?:link|app|share)?\/?(\d{6,})/);
493
+ return m ? { id: m[1] } : null;
494
+ },
495
+ async parse(ctx, helpers) {
496
+ // 小黑盒 renders its share pages client-side and exposes no public metadata
497
+ // endpoint, so whatever the static HTML carries is all there is. When that is
498
+ // nothing the link is still returned, instead of an error the reader cannot act on.
499
+ const target = 'https://www.xiaoheihe.cn' + helpers.pathname;
500
+ let title = "";
501
+ let description = "";
502
+ let images = [];
503
+ let finalUrl = target;
504
+ try {
505
+ const page = await helpers.fetchText(target, { ua: MOBILE_UA });
506
+ finalUrl = page.finalUrl;
507
+ const meta = metaTags(page.text);
508
+ title = meta["og:title"] || meta.title || "";
509
+ description = meta["og:description"] || meta.description || "";
510
+ images = unique(imageTags(page.text, meta).map((u) => absolute(u, finalUrl)));
511
+ } catch { /* link-only */ }
512
+ return {
513
+ platform: 'xiaoheihe',
514
+ platformName: '小黑盒',
515
+ kind: images.length > 1 ? 'gallery' : 'video',
516
+ url: finalUrl,
517
+ title: title.slice(0, 140),
518
+ author: '',
519
+ description: description.slice(0, 300),
520
+ cover: images[0] ?? '',
521
+ images: images.slice(1),
522
+ meta: '',
523
+ linkOnly: !title && images.length === 0,
524
+ };
525
+ },
526
+ },
527
+ ];
528
+
529
+ /** Every URL-looking token in a message, trimmed of trailing punctuation. */
530
+ export function extractLinks(text) {
531
+ const found = String(text ?? '').match(/https?:\/\/[^\s<>"'))】\]]+/gi) ?? [];
532
+ return unique(found.map((raw) => raw.replace(/[.,;:!?。,;:!?]+$/, '')));
533
+ }
534
+
535
+ /** Find the parser that claims this URL, if any. */
536
+ export function findParser(rawUrl) {
537
+ let url;
538
+ try { url = new URL(rawUrl); } catch { return null; }
539
+ for (const parser of PARSERS) {
540
+ try {
541
+ const ctx = parser.match(url);
542
+ if (ctx) return { parser, ctx, url };
543
+ } catch { /* a parser with a broken matcher must not stop the others */ }
544
+ }
545
+ return null;
546
+ }
547
+
548
+ /**
549
+ * Parse one link.
550
+ *
551
+ * @returns the result object, or null when the link belongs to no known platform.
552
+ * @throws when a platform was recognised but its metadata could not be read.
553
+ */
554
+ export async function parseLink(rawUrl, { timeoutMs = 20_000 } = {}) {
555
+ const hit = findParser(rawUrl);
556
+ if (!hit) return null;
557
+ const url = new URL(rawUrl);
558
+ const helpers = {
559
+ host: url.host,
560
+ pathname: url.pathname + url.search,
561
+ fetchText: (target, options = {}) => fetchText(target, { timeoutMs, ...options }),
562
+ fetchJson: (target, options = {}) => fetchJson(target, { timeoutMs, ...options }),
563
+ // 短链专用:受控跟随跳转。普通请求仍然用 fetchText(不跟随)。
564
+ resolveShortLink: (target, options = {}) => resolveShortLink(target, { timeoutMs, ...options }),
565
+ };
566
+ const result = await hit.parser.parse(hit.ctx, helpers);
567
+ result.sourceUrl = rawUrl;
568
+ return result;
569
+ }
570
+
571
+ /**
572
+ * Render a parsed result into the messages that should be sent.
573
+ *
574
+ * A video becomes a caption plus its cover (never the file); a gallery becomes a
575
+ * caption plus each image. The original URL is always last so the reader can
576
+ * open the thing this came from.
577
+ */
578
+ export function renderResult(result, { maxImages = 9 } = {}) {
579
+ const url = result.url || result.sourceUrl || "";
580
+ // A platform that could not be read still gets a useful message: the title if
581
+ // there is one, and always the URL. Sending an empty caption would look broken.
582
+ if (result.linkOnly) {
583
+ const lines = ["【" + result.platformName + "】" + (result.title || "链接")];
584
+ if (result.description) lines.push(result.description);
585
+ lines.push(url);
586
+ return { text: lines.join("\n"), images: [] };
587
+ }
588
+ const lines = [];
589
+ lines.push("【" + result.platformName + "】" + (result.kind === "gallery" ? "图集" : "视频"));
590
+ if (result.title) lines.push(result.title);
591
+ const sub = [result.author, result.meta].filter(Boolean).join(" · ");
592
+ if (sub) lines.push(sub);
593
+ if (result.description) {
594
+ const clipped = result.description.length > 120 ? result.description.slice(0, 120) + "…" : result.description;
595
+ if (clipped !== result.title) lines.push(clipped);
596
+ }
597
+ lines.push(url);
598
+ const images = unique([result.cover, ...(result.images ?? [])]).slice(0, Math.max(0, maxImages));
599
+ return { text: lines.join("\n"), images };
600
+ }
601
+
602
+ export const SUPPORTED_PLATFORMS = PARSERS.map((p) => ({ id: p.id, name: p.name }));