dsh-chat-comprehension 0.4.0 → 0.5.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/NOTICE.md +4 -3
- package/README.md +62 -15
- package/client.js +400 -52
- package/lib/engines.mjs +36 -5
- package/lib/index.js +210 -20
- package/lib/qqbot-0.5.3-patches.json +31 -1
- package/lib/qqbot-patch.mjs +1 -1
- package/lib/video.mjs +45 -2
- package/package.json +6 -6
- package/vendor/dsh-agent-md/lib/chat-persona.js +9 -3
- package/vendor/dsh-agent-md/lib/index.js +72 -18
- package/vendor/dsh-agent-md/lib/qq.js +64 -0
- package/vendor/dsh-agent-md/package.json +1 -1
- package/vendor/dsh-bili-scroll/index.js +39 -10
- package/vendor/dsh-meme/index.js +3 -1
- package/vendor/dsh-video-storyboard/LICENSE-workbuddy.txt +21 -0
- package/vendor/dsh-video-storyboard/NOTICE +7 -0
- package/vendor/dsh-video-storyboard/NOTICE-workbuddy.md +18 -0
- package/vendor/dsh-video-storyboard/dsh.plugin.json +1 -1
- package/vendor/dsh-video-storyboard/package.json +1 -1
- package/vendor/dsh-video-storyboard/src/sniff.mjs +545 -0
- package/vendor/dsh-video-storyboard/src/storyboard/direct-url.js +2 -2
- package/vendor/dsh-video-storyboard/src/storyboard/fetch.js +3 -3
- package/vendor/dsh-video-storyboard/src/storyboard/pipeline.js +1 -1
- package/vendor/dsh-video-storyboard/src/storyboard/source.js +409 -0
- package/vendor/dsh-video-storyboard/src/storyboard/tool-spec.js +5 -3
- package/vendor/dsh-video-storyboard/src/storyboard/url.js +105 -17
- package/vendor/dsh-video-storyboard/src/tools/locate.js +1 -1
- package/vendor/dsh-video-storyboard/src/tools/probe.js +4 -6
- package/vendor/dsh-video-storyboard/src/tools/zoom.js +1 -1
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* source.js — 「输入 → 本地文件」的统一入口(管线和工具都只调这一个)。
|
|
3
|
+
*
|
|
4
|
+
* 在 fetch.js(移植自 dsh-video-storyboard 的 yt-dlp 取流层)外面加一层"页面嗅探"兜底:
|
|
5
|
+
* 1. 这条链接之前已经靠嗅探下过 → 直接命中缓存(meta.json 里记着实际文件名);
|
|
6
|
+
* 2. yt-dlp 认得 → 走 fetch.js 原路(格式选择、站点字幕、高清直链都在那边);
|
|
7
|
+
* 3. yt-dlp 认不出(Unsupported URL 等)→ 页面嗅探:静态(脚本 / HTML 里的媒体直链)
|
|
8
|
+
* → 无头浏览器(真实播放器的网络请求),拿到媒体地址后直接下载。
|
|
9
|
+
*
|
|
10
|
+
* 1 和 2 是**并行**的:静态嗅探只要一两秒,等 yt-dlp 明确失败时它多半已经有结果了。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { createWriteStream } from 'node:fs';
|
|
14
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
15
|
+
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
16
|
+
import { Readable, Transform } from 'node:stream';
|
|
17
|
+
import { pipeline } from 'node:stream/promises';
|
|
18
|
+
|
|
19
|
+
import { fetchMedia, probeUrl } from './fetch.js';
|
|
20
|
+
import { assertFetchableUrlResolved, isHttpUrl, normalizeUrl } from './url.js';
|
|
21
|
+
import { fileExists, mediaDir, mediaKey, mediaMaxBytes, pruneMedia } from './media-store.js';
|
|
22
|
+
import { DEFAULT_UA, discoverYtdlp, explainYtdlpError, runProcess } from './ytdlp.js';
|
|
23
|
+
import { DEFAULT_FFMPEG, DEFAULT_FFPROBE } from './binaries.js';
|
|
24
|
+
import { probeVideo } from './probe.js';
|
|
25
|
+
import { browserSniff, pickVariants, probeCandidates, staticSniff } from '../sniff.mjs';
|
|
26
|
+
|
|
27
|
+
/** normalizeUrl(页面链接) → { at, found, variants }。只活在进程内存里:嗅到的媒体地址可能带签名。 */
|
|
28
|
+
const sniffed = new Map();
|
|
29
|
+
/** normalizeUrl(页面链接) → { mediaDir }:哪条链接的缓存目录在哪,用于重开进程后重建上面的记录 */
|
|
30
|
+
const flow = new Map();
|
|
31
|
+
|
|
32
|
+
const AUDIO_EXTS = new Set(['.m4a', '.m4b', '.mp3', '.aac', '.opus', '.ogg', '.oga', '.wav', '.flac', '.weba']);
|
|
33
|
+
const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
34
|
+
|
|
35
|
+
const sniffEnabled = (opts = {}) => opts.sniff !== false && process.env.DSH_VIDEO_SNIFF !== '0' && process.env.DSH_VIDEO_SNIFF !== 'false';
|
|
36
|
+
const browserOpts = (opts = {}) => ({
|
|
37
|
+
browserPath: process.env.DSH_VIDEO_BROWSER_PATH || process.env.VIDEO_BROWSER_PATH || undefined,
|
|
38
|
+
timeoutMs: 25000, onProgress: opts.onProgress,
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
function sniffError(message) {
|
|
42
|
+
const error = new Error(message);
|
|
43
|
+
error.code = 'SNIFF_FAILED';
|
|
44
|
+
return error;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** yt-dlp 的失败是不是"这个站点它不认识"。只有这种情况才值得开浏览器去嗅探。 */
|
|
48
|
+
const looksUnsupported = (reason) => /Unsupported URL|no video formats|not supported by the installed yt-dlp/i.test(reason);
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* yt-dlp 失败后还要不要继续嗅探。
|
|
52
|
+
* 站点本身是 yt-dlp 认识的(只是限流 412 / 要登录 / 网络抖动):嗅探帮不上忙,把原因原样报出去,
|
|
53
|
+
* 否则会白开一次浏览器,还把真正的原因("稍后重试")盖掉。
|
|
54
|
+
* 例外:静态嗅探已经找到了媒体地址(比如页面里另有一条内嵌视频),那就用它。
|
|
55
|
+
*/
|
|
56
|
+
function shouldContinueSniffing(reason, staticOk) {
|
|
57
|
+
if (staticOk) return true;
|
|
58
|
+
return looksUnsupported(reason);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 已经靠嗅探下过这条链接 → 直接给缓存 */
|
|
62
|
+
async function sniffedHit(input, opts = {}) {
|
|
63
|
+
const key = normalizeUrl(input);
|
|
64
|
+
const dir = join(mediaDir(), mediaKey(key, opts.scanHeight ?? 360));
|
|
65
|
+
const v = await readSniffMeta(dir);
|
|
66
|
+
if (!v) return null;
|
|
67
|
+
flow.set(key, { mediaDir: dir, at: Date.now() }); // 高清地址走 frameSourceOf 现取现寻
|
|
68
|
+
return {
|
|
69
|
+
path: join(dir, v.meta.file),
|
|
70
|
+
source: { ...v.meta, cached: true },
|
|
71
|
+
frameSource: await frameSourceFromMeta(v.meta, v.meta.url || input).catch(() => null),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 读某条链接下载缓存里的 meta(嗅探来的才有 sniffed 标记) */
|
|
76
|
+
async function readSniffMeta(dir) {
|
|
77
|
+
try {
|
|
78
|
+
const meta = JSON.parse(await readFile(join(dir, 'meta.json'), 'utf8'));
|
|
79
|
+
if (!meta?.sniffed || typeof meta.file !== 'string') return null;
|
|
80
|
+
if (!(await fileExists(join(dir, meta.file)))) return null;
|
|
81
|
+
return { meta };
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 从 meta 里存的候选(或页面地址重新嗅探一遍)拿高清地址;静态嗅探很便宜 */
|
|
88
|
+
async function frameSourceFromMeta(meta, pageUrl) {
|
|
89
|
+
const cands = Array.isArray(meta.sniffCandidates) ? meta.sniffCandidates : [];
|
|
90
|
+
if (cands.length > 0) return frameSourceOf(pageUrl, { variants: pickVariants(cands) });
|
|
91
|
+
const st = await staticSniff(pageUrl);
|
|
92
|
+
if (!st.ok) return null;
|
|
93
|
+
const probed = await probeCandidates(st.candidates, { ffprobe: DEFAULT_FFPROBE });
|
|
94
|
+
return frameSourceOf(pageUrl, { variants: pickVariants(probed) });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function rememberSniffed(key, found) {
|
|
98
|
+
const probed = await probeCandidates(found.candidates, { ffprobe: DEFAULT_FFPROBE });
|
|
99
|
+
const variants = pickVariants(probed);
|
|
100
|
+
if (!variants) throw sniffError('页面嗅探找到了媒体地址,但都读不出来(可能已过期、需要登录,或是 DRM 加密流)');
|
|
101
|
+
const rec = { at: Date.now(), found: { ...found, candidates: probed }, variants };
|
|
102
|
+
sniffed.set(key, rec);
|
|
103
|
+
return rec;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** zoom 远程取高清帧用的高清地址(嗅探来的):从内存或缓存目录的 meta 里取,都取不到就返回 null。 */
|
|
107
|
+
async function frameSourceOf(input, rec) {
|
|
108
|
+
let r = rec ?? sniffed.get(normalizeUrl(input));
|
|
109
|
+
if (!r) {
|
|
110
|
+
const entry = flow.get(normalizeUrl(input));
|
|
111
|
+
const meta = entry ? (await readSniffMeta(entry.mediaDir))?.meta : null;
|
|
112
|
+
if (meta) {
|
|
113
|
+
const url = meta.url || input;
|
|
114
|
+
const st = Array.isArray(meta.sniffCandidates) ? { candidates: meta.sniffCandidates } : await staticSniff(url);
|
|
115
|
+
if (!st?.ok) return null;
|
|
116
|
+
const probed = await probeCandidates(st.candidates, { ffprobe: DEFAULT_FFPROBE });
|
|
117
|
+
r = { variants: pickVariants(probed) };
|
|
118
|
+
sniffed.set(normalizeUrl(input), { at: Date.now(), variants: r.variants });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (!r?.variants) return null;
|
|
122
|
+
const z = r.variants.zoom;
|
|
123
|
+
if (!z?.url || z.url === r.variants?.scan?.url) return null; // 和扫描副本同一个文件:直接用本地副本
|
|
124
|
+
const h = z.headers ?? {};
|
|
125
|
+
return {
|
|
126
|
+
uri: z.url, userAgent: h['User-Agent'] || DEFAULT_UA, referer: h.Referer ?? null,
|
|
127
|
+
cookie: h.Cookie ?? null, origin: h.Origin ?? null,
|
|
128
|
+
height: z.height ?? null, expiresAt: Date.now() + 60 * 60_000,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 给"没保存高清地址"的情况补一次嗅探(静态嗅探很便宜);拿不到就返回 null,调用方退回本地副本。 */
|
|
133
|
+
export async function frameSourceFor(input, opts = {}) {
|
|
134
|
+
if (!isHttpUrl(input)) return null;
|
|
135
|
+
const key = normalizeUrl(input);
|
|
136
|
+
try {
|
|
137
|
+
const hit = sniffed.get(key);
|
|
138
|
+
if (hit && Date.now() - hit.at < 60 * 60_000) return frameSourceOf(input, hit);
|
|
139
|
+
if (!flow.has(key)) {
|
|
140
|
+
const st = await staticSniff(input);
|
|
141
|
+
if (!st.ok) return null;
|
|
142
|
+
const rec = await rememberSniffed(key, st);
|
|
143
|
+
flow.set(key, { mediaDir: null, at: Date.now() });
|
|
144
|
+
return frameSourceOf(input, rec);
|
|
145
|
+
}
|
|
146
|
+
return frameSourceOf(input);
|
|
147
|
+
} catch {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/* ------------------------------------------------------------------ 嗅探结果的下载 */
|
|
153
|
+
|
|
154
|
+
function mediaHeaders(cand) {
|
|
155
|
+
const h = cand.headers ?? {};
|
|
156
|
+
return {
|
|
157
|
+
'User-Agent': h['User-Agent'] || DEFAULT_UA,
|
|
158
|
+
...(h.Referer ? { Referer: h.Referer } : {}),
|
|
159
|
+
...(h.Cookie ? { Cookie: h.Cookie } : {}),
|
|
160
|
+
...(h.Origin ? { Origin: h.Origin } : {}),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** yt-dlp 的进度行 → onProgress */
|
|
165
|
+
function progressTap(onProgress) {
|
|
166
|
+
let tail = '';
|
|
167
|
+
return (chunk) => {
|
|
168
|
+
if (!onProgress) return;
|
|
169
|
+
tail = (tail + chunk.toString()).slice(-600);
|
|
170
|
+
const all = [...tail.matchAll(/\[download\]\s+([\d.]+)% of\s+~?\s*([\d.]+\w+)(?:.*?ETA\s+([0-9:]+))?/g)];
|
|
171
|
+
const m = all[all.length - 1];
|
|
172
|
+
if (m) onProgress({ phase: 'download', percent: Number(m[1]), size: m[2], eta: m[3] ?? null });
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** 渐进式文件(mp4 等):自己下。支持断点续传(Range),最多重试 4 次。 */
|
|
177
|
+
async function downloadHttp(cand, destDir, { onProgress, timeoutMs = 30 * 60_000 } = {}) {
|
|
178
|
+
const ext = (/\.(mp4|m4v|webm|mov|flv|mkv)(\?|$)/i.exec(cand.url.split('#')[0])?.[1] || 'mp4').toLowerCase();
|
|
179
|
+
const dest = join(destDir, `video.${ext}`);
|
|
180
|
+
const part = `${dest}.part`;
|
|
181
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
182
|
+
let have = 0;
|
|
183
|
+
try { have = (await stat(part)).size; } catch { have = 0; }
|
|
184
|
+
const headers = mediaHeaders(cand);
|
|
185
|
+
if (have > 0) headers.Range = `bytes=${have}-`;
|
|
186
|
+
try {
|
|
187
|
+
const res = await fetch(cand.url, { headers, redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) });
|
|
188
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
189
|
+
const append = have > 0 && res.status === 206;
|
|
190
|
+
const total = (append ? have : 0) + (Number(res.headers.get('content-length')) || 0);
|
|
191
|
+
let got = append ? have : 0;
|
|
192
|
+
let last = 0;
|
|
193
|
+
const counter = new Transform({
|
|
194
|
+
transform(chunk, _enc, cb) {
|
|
195
|
+
got += chunk.length;
|
|
196
|
+
if (onProgress && Date.now() - last > 600) {
|
|
197
|
+
last = Date.now();
|
|
198
|
+
onProgress({ phase: 'download', percent: total ? (got / total) * 100 : null, bytes: got, total });
|
|
199
|
+
}
|
|
200
|
+
cb(null, chunk);
|
|
201
|
+
},
|
|
202
|
+
});
|
|
203
|
+
await pipeline(Readable.fromWeb(res.body), counter, createWriteStream(part, { flags: append ? 'a' : 'w' }));
|
|
204
|
+
if (total && got < total) throw new Error(`连接中断(${(got / 1048576).toFixed(0)}/${(total / 1048576).toFixed(0)} MB)`);
|
|
205
|
+
await rename(part, dest);
|
|
206
|
+
return { path: dest, bytes: got };
|
|
207
|
+
} catch (error) {
|
|
208
|
+
if (attempt >= 4) throw new Error(`下载失败:${error.message}`);
|
|
209
|
+
await sleep(1000 * attempt);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function biggestVideo(dir) {
|
|
215
|
+
let best = null;
|
|
216
|
+
for (const name of await readdir(dir).catch(() => [])) {
|
|
217
|
+
if (/\.(part|ytdl|temp)$/i.test(name)) continue;
|
|
218
|
+
if (AUDIO_EXTS.has(name.slice(name.lastIndexOf('.')).toLowerCase())) continue;
|
|
219
|
+
try {
|
|
220
|
+
const st = await stat(join(dir, name));
|
|
221
|
+
if (st.isFile() && st.size > 0 && (!best || st.size > best.bytes)) best = { path: join(dir, name), bytes: st.size };
|
|
222
|
+
} catch { /* 半成品 */ }
|
|
223
|
+
}
|
|
224
|
+
return best;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** 流清单(HLS / DASH):交给 yt-dlp;它兜不住(清单变体怪、分片过期…)再让 ffmpeg 直接读流。 */
|
|
228
|
+
async function downloadStream(cand, destDir, { onProgress } = {}) {
|
|
229
|
+
const tool = await discoverYtdlp({});
|
|
230
|
+
const h = cand.headers ?? {};
|
|
231
|
+
const cap = cand.height ? `bv*[height<=${cand.height}]+ba/b[height<=${cand.height}]/` : '';
|
|
232
|
+
const args = ['--no-warnings', '--no-playlist', '--newline', '--retries', '3', '--fragment-retries', '5', '--continue',
|
|
233
|
+
...(isAbsolute(DEFAULT_FFMPEG) ? ['--ffmpeg-location', DEFAULT_FFMPEG] : []),
|
|
234
|
+
'--user-agent', h['User-Agent'] || DEFAULT_UA,
|
|
235
|
+
...(h.Referer ? ['--referer', h.Referer] : []),
|
|
236
|
+
...(h.Cookie ? ['--add-header', `Cookie:${h.Cookie}`] : []),
|
|
237
|
+
...(h.Origin ? ['--add-header', `Origin:${h.Origin}`] : []),
|
|
238
|
+
...(cap ? ['-f', `${cap}b`] : []),
|
|
239
|
+
'-o', join(destDir, 'video.%(ext)s'), cand.url];
|
|
240
|
+
const out = await runProcess(tool, args, { timeoutMs: 30 * 60_000, onOutput: progressTap(onProgress) });
|
|
241
|
+
if (out.code === 0) {
|
|
242
|
+
const best = await biggestVideo(destDir);
|
|
243
|
+
if (best) return best;
|
|
244
|
+
}
|
|
245
|
+
const dest = join(destDir, 'video.mp4');
|
|
246
|
+
const ff = await runProcess({ bin: DEFAULT_FFMPEG, prefix: [] }, [
|
|
247
|
+
'-nostdin', '-y', '-loglevel', 'error', '-user_agent', h['User-Agent'] || DEFAULT_UA,
|
|
248
|
+
...(h.Referer ? ['-referer', h.Referer] : []), '-i', cand.url, '-c', 'copy', '-movflags', '+faststart', dest,
|
|
249
|
+
], { timeoutMs: 30 * 60_000 });
|
|
250
|
+
if (ff.code === 0 && await fileExists(dest)) return { path: dest, bytes: (await stat(dest)).size };
|
|
251
|
+
throw new Error(`流媒体下载失败:${explainYtdlpError(out.stderr, out.code)}`);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async function fetchSniffed(input, rec, opts = {}) {
|
|
255
|
+
const scanHeight = opts.scanHeight ?? 360;
|
|
256
|
+
const key = normalizeUrl(input);
|
|
257
|
+
const scan = rec.variants.scan;
|
|
258
|
+
// 嗅探结果也是从网页里来的:真正下载前再做一次解析后地址检查,防止页面把内网地址塞进来。
|
|
259
|
+
if (isHttpUrl(scan?.url)) await assertFetchableUrlResolved(scan.url);
|
|
260
|
+
const dir = join(mediaDir(), mediaKey(key, scanHeight));
|
|
261
|
+
const tmp = `${dir}.part`;
|
|
262
|
+
await mkdir(tmp, { recursive: true });
|
|
263
|
+
opts.onProgress?.({
|
|
264
|
+
phase: 'sniff',
|
|
265
|
+
message: `已找到视频地址(${rec.found.via === 'browser' ? '浏览器嗅探' : '页面脚本'}),开始下载…`,
|
|
266
|
+
});
|
|
267
|
+
try {
|
|
268
|
+
const out = scan.kind === 'file'
|
|
269
|
+
? await downloadHttp(scan, tmp, { onProgress: opts.onProgress })
|
|
270
|
+
: await downloadStream(scan, tmp, { onProgress: opts.onProgress });
|
|
271
|
+
await rm(dir, { recursive: true, force: true });
|
|
272
|
+
await rename(tmp, dir); // 整个目录一起落位,不留"下了一半"的半成品被当成命中
|
|
273
|
+
// 目录已改名:返回的必须是落位后的新路径(后面的探测、缓存保护都用它)
|
|
274
|
+
const file = join(dir, basename(out.path));
|
|
275
|
+
const info = await probeVideo(file).catch(() => null);
|
|
276
|
+
const maxH = rec.variants.maxHeight ?? scan.height ?? null;
|
|
277
|
+
const source = {
|
|
278
|
+
kind: 'url', sniffed: true, sniffVia: rec.found.via, url: input, cached: false, bytes: out.bytes,
|
|
279
|
+
scanHeight, scanActual: scan.height ?? scanHeight, maxAvailable: maxH,
|
|
280
|
+
availableHeights: rec.variants.heights ?? [], zoomTarget: Math.max(maxH ?? 0, scan.height ?? 0) || scanHeight,
|
|
281
|
+
title: rec.found.pageTitle ?? null,
|
|
282
|
+
duration: info?.duration ?? rec.variants.duration ?? null,
|
|
283
|
+
auth: 'sniffed', file: basename(out.path),
|
|
284
|
+
// 候选地址只进缓存文件,供下次(或重启后)重新定位高清流;带签名的链接会自然过期,过期就现嗅一次
|
|
285
|
+
sniffCandidates: (rec.found.candidates ?? []).map((c) => ({ url: c.url, kind: c.kind, heights: c.heights, height: c.height, shortSide: c.shortSide, duration: c.duration, size: c.size, headers: c.headers })),
|
|
286
|
+
...(rec.found.drm ? { drm: true } : {}),
|
|
287
|
+
};
|
|
288
|
+
await writeFile(join(dir, 'meta.json'), JSON.stringify(source, null, 0), 'utf8').catch(() => {});
|
|
289
|
+
rec.at = Date.now();
|
|
290
|
+
flow.set(key, { mediaDir: dir, at: Date.now() });
|
|
291
|
+
await pruneMedia({ dir: mediaDir(), maxBytes: mediaMaxBytes() }).catch(() => {});
|
|
292
|
+
return { path: out.path, source, frameSource: await frameSourceOf(input, rec) };
|
|
293
|
+
} catch (error) {
|
|
294
|
+
// 失败时保留 .part 目录供断点续传;由媒体缓存按时间淘汰
|
|
295
|
+
throw new Error(`${error.message}${rec.found.drm ? '(这个页面有 DRM 许可证请求,视频很可能是加密流)' : ''}`);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/* ------------------------------------------------------------------ 对外:解析与探测 */
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* 管线唯一要调的函数:本地路径原样返回,链接则换成本地文件。
|
|
303
|
+
* @returns {Promise<{path:string, source:object|null, frameSource:object|null}>}
|
|
304
|
+
*/
|
|
305
|
+
export async function resolveInput(input, opts = {}) {
|
|
306
|
+
if (!isHttpUrl(input)) return { path: input, source: null, frameSource: null };
|
|
307
|
+
await assertFetchableUrlResolved(input);
|
|
308
|
+
const hit = await sniffedHit(input, opts);
|
|
309
|
+
if (hit) return hit;
|
|
310
|
+
|
|
311
|
+
const useSniff = sniffEnabled(opts);
|
|
312
|
+
const [ref, st] = await Promise.allSettled([
|
|
313
|
+
fetchMedia(input, opts),
|
|
314
|
+
useSniff ? staticSniff(input) : Promise.resolve({ ok: false, reason: 'off' }),
|
|
315
|
+
]);
|
|
316
|
+
if (ref.status === 'fulfilled') return ref.value;
|
|
317
|
+
|
|
318
|
+
const reason = String(ref.reason?.message ?? ref.reason);
|
|
319
|
+
// yt-dlp 没装 / 站点明确要登录:嗅探也帮不上忙(不带登录态),把原因原样报出去
|
|
320
|
+
if (ref.reason?.code === 'YTDLP_MISSING' || /signed-in session|Sign in to confirm/i.test(reason)) throw ref.reason;
|
|
321
|
+
if (!useSniff) throw ref.reason;
|
|
322
|
+
// 站点是 yt-dlp 认识的、只是这次限流 / 抖动:不开浏览器,直接把真正的原因报出去
|
|
323
|
+
if (!shouldContinueSniffing(reason, st.status === 'fulfilled' && st.value?.ok)) throw ref.reason;
|
|
324
|
+
|
|
325
|
+
const key = normalizeUrl(input);
|
|
326
|
+
try {
|
|
327
|
+
if (!(st.status === 'fulfilled' && st.value?.ok)) {
|
|
328
|
+
opts.onProgress?.({ phase: 'sniff', message: '正在用无头浏览器打开页面、嗅探视频地址…' });
|
|
329
|
+
}
|
|
330
|
+
const found = st.status === 'fulfilled' && st.value?.ok
|
|
331
|
+
? st.value
|
|
332
|
+
: await browserSniff(input, browserOpts(opts));
|
|
333
|
+
if (!found.ok) {
|
|
334
|
+
throw sniffError(`这个页面里没有找到可播放的视频(${found.reason}${found.detail ? `:${found.detail}` : ''})。`
|
|
335
|
+
+ '常见原因:需要登录、DRM 加密流、或页面本身没有视频。');
|
|
336
|
+
}
|
|
337
|
+
const rec = await rememberSniffed(key, { ...found, via: found.via ?? 'browser' });
|
|
338
|
+
return await fetchSniffed(input, rec, opts);
|
|
339
|
+
} catch (error) {
|
|
340
|
+
if (error?.code === 'SNIFF_FAILED') throw sniffError(`${reason}\n[页面嗅探] ${error.message}`);
|
|
341
|
+
throw error;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* 只探测、不下载(video_probe 用)。
|
|
347
|
+
* @returns {Promise<{remote:object}|{local:object}>}
|
|
348
|
+
*/
|
|
349
|
+
export async function probeInput(input, opts = {}) {
|
|
350
|
+
if (!isHttpUrl(input)) return { local: { ...(await probeVideo(input)), path: input } };
|
|
351
|
+
await assertFetchableUrlResolved(input);
|
|
352
|
+
const hit = await sniffedHit(input, opts);
|
|
353
|
+
if (hit) {
|
|
354
|
+
// 进程刚起来时内存里没有记录:用 meta 里存的候选(没有就现做一次静态嗅探)
|
|
355
|
+
const rec = sniffed.get(normalizeUrl(input))
|
|
356
|
+
?? await frameSourceFromMeta(hit.source, hit.source.url || input).then((fs) => (fs ? sniffed.get(normalizeUrl(input)) : null))
|
|
357
|
+
?? null;
|
|
358
|
+
return { remote: toRemoteProbe(input, rec, hit.source) };
|
|
359
|
+
}
|
|
360
|
+
const useSniff = sniffEnabled(opts);
|
|
361
|
+
const [ref, st] = await Promise.allSettled([
|
|
362
|
+
probeUrl(input, opts),
|
|
363
|
+
useSniff ? staticSniff(input) : Promise.resolve({ ok: false, reason: 'off' }),
|
|
364
|
+
]);
|
|
365
|
+
if (ref.status === 'fulfilled') return { remote: ref.value };
|
|
366
|
+
const reason = String(ref.reason?.message ?? ref.reason);
|
|
367
|
+
if (ref.reason?.code === 'YTDLP_MISSING' || /signed-in session|Sign in to confirm/i.test(reason)) throw ref.reason;
|
|
368
|
+
if (!useSniff) throw ref.reason;
|
|
369
|
+
// 同 resolveInput:认识的站点只是这次限流 / 抖动,就别开浏览器了
|
|
370
|
+
if (!shouldContinueSniffing(reason, st.status === 'fulfilled' && st.value?.ok)) throw ref.reason;
|
|
371
|
+
|
|
372
|
+
try {
|
|
373
|
+
const found = st.status === 'fulfilled' && st.value?.ok
|
|
374
|
+
? st.value
|
|
375
|
+
: await browserSniff(input, browserOpts(opts));
|
|
376
|
+
if (!found.ok) {
|
|
377
|
+
throw sniffError(`这个页面里没有找到可播放的视频(${found.reason}${found.detail ? `:${found.detail}` : ''})。`);
|
|
378
|
+
}
|
|
379
|
+
const key = normalizeUrl(input);
|
|
380
|
+
const rec = await rememberSniffed(key, { ...found, via: found.via ?? 'browser' });
|
|
381
|
+
return { remote: toRemoteProbe(input, rec, null) };
|
|
382
|
+
} catch (error) {
|
|
383
|
+
if (error?.code === 'SNIFF_FAILED') throw sniffError(`${reason}\n[页面嗅探] ${error.message}`);
|
|
384
|
+
throw error;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function toRemoteProbe(input, rec, cached) {
|
|
389
|
+
const v = rec?.variants ?? null;
|
|
390
|
+
const cands = rec?.found?.candidates ?? cached?.sniffCandidates ?? [];
|
|
391
|
+
const sizes = cands.map((c) => [
|
|
392
|
+
c.shortSide ? `${c.shortSide}p` : null,
|
|
393
|
+
c.kind && c.kind !== 'file' ? '自适应流' : null,
|
|
394
|
+
c.size ? `≈ ${(c.size / 1048576).toFixed(0)} MB` : null,
|
|
395
|
+
].filter(Boolean).join(' ')).filter((s) => s !== '');
|
|
396
|
+
return {
|
|
397
|
+
url: input,
|
|
398
|
+
sniffed: true,
|
|
399
|
+
sniffVia: rec?.found?.via ?? cached?.sniffVia ?? null,
|
|
400
|
+
title: rec?.found?.pageTitle ?? cached?.title ?? null,
|
|
401
|
+
duration: v?.duration ?? cached?.duration ?? null,
|
|
402
|
+
heights: v?.heights ?? cached?.availableHeights ?? [],
|
|
403
|
+
maxHeight: v?.maxHeight ?? cached?.maxAvailable ?? null,
|
|
404
|
+
auth: 'sniffed',
|
|
405
|
+
...(cached ? { cached: true } : {}),
|
|
406
|
+
...(sizes.length ? { sizes } : {}),
|
|
407
|
+
...(rec?.found?.drm || cached?.drm ? { drm: true } : {}),
|
|
408
|
+
};
|
|
409
|
+
}
|
|
@@ -56,9 +56,11 @@ export function storyboardToolSpec() {
|
|
|
56
56
|
input: {
|
|
57
57
|
type: 'string',
|
|
58
58
|
required: true,
|
|
59
|
-
description: 'Local absolute path (mp4/mov/mkv/webm...), or an http(s)
|
|
60
|
-
'
|
|
61
|
-
'the
|
|
59
|
+
description: 'Local absolute path (mp4/mov/mkv/webm...), or an http(s) video page / direct link. ' +
|
|
60
|
+
'yt-dlp-supported sites (Bilibili, YouTube, Douyin, ... ) are resolved directly; when yt-dlp does ' +
|
|
61
|
+
'not recognize a page, the plugin sniffs the page scripts or a headless Edge/Chrome for the real ' +
|
|
62
|
+
'media URL. Links are downloaded once at low resolution for scanning; video_zoom re-reads the ' +
|
|
63
|
+
'original stream at high resolution.',
|
|
62
64
|
},
|
|
63
65
|
from: {
|
|
64
66
|
type: 'number',
|
|
@@ -18,32 +18,120 @@ export function isHttpUrl(value) {
|
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
21
|
+
/** IPv4 保留/内网网段:[基址, 前缀长度]。 */
|
|
22
|
+
const V4_BLOCKS = [
|
|
23
|
+
[0x00000000, 8], [0x0a000000, 8], [0x64400000, 10], [0x7f000000, 8],
|
|
24
|
+
[0xa9fe0000, 16], [0xac100000, 12], [0xc0000000, 24], [0xc0000200, 24],
|
|
25
|
+
[0xc0586300, 24], [0xc0a80000, 16], [0xc6120000, 15], [0xc6336400, 24],
|
|
26
|
+
[0xcb007100, 24], [0xe0000000, 4], [0xf0000000, 4],
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
/** 单标签/本机域名:公网不会用这些名字。 */
|
|
30
|
+
const PRIVATE_NAME = [
|
|
31
|
+
/^localhost$/i, /\.localhost$/i, /\.local$/i, /\.internal$/i, /\.home\.arpa$/i,
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
/** 去掉方括号与尾随点,再转小写;`localhost.` 与 `[::1]` 都要能识别。 */
|
|
35
|
+
export function normalizeHost(hostname) {
|
|
36
|
+
return String(hostname).trim().toLowerCase().replace(/^\[|\]$/g, '').replace(/\.+$/, '')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function v4IsPrivate(ip) {
|
|
40
|
+
const parts = ip.split('.').map(Number)
|
|
41
|
+
if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false
|
|
42
|
+
const n = ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0
|
|
43
|
+
return V4_BLOCKS.some(([base, bits]) => (n >>> (32 - bits)) === (base >>> (32 - bits)))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 把 v6 地址展开成 8 个 16 位组;支持 `::` 与带点分尾的映射地址。 */
|
|
47
|
+
function expandV6(raw) {
|
|
48
|
+
let ip = normalizeHost(raw)
|
|
49
|
+
const tail = ip.match(/(\d+\.\d+\.\d+\.\d+)$/)
|
|
50
|
+
let tailGroups = []
|
|
51
|
+
if (tail) {
|
|
52
|
+
const oct = tail[1].split('.').map(Number)
|
|
53
|
+
tailGroups = [(oct[0] << 8) | oct[1], (oct[2] << 8) | oct[3]]
|
|
54
|
+
ip = ip.slice(0, -tail[1].length).replace(/:$/, '::')
|
|
55
|
+
}
|
|
56
|
+
const [head, rest] = ip.split('::')
|
|
57
|
+
const left = head ? head.split(':').filter(Boolean).map((g) => parseInt(g, 16)) : []
|
|
58
|
+
const right = rest === undefined ? [] : rest.split(':').filter(Boolean).map((g) => parseInt(g, 16))
|
|
59
|
+
const groups = [...left, ...tailGroups, ...right]
|
|
60
|
+
if (rest !== undefined) {
|
|
61
|
+
const fill = 8 - groups.length
|
|
62
|
+
return fill < 0 ? null : [...left, ...Array(fill).fill(0), ...tailGroups, ...right]
|
|
63
|
+
}
|
|
64
|
+
return groups.length === 8 ? groups : null
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function v6IsPrivate(raw) {
|
|
68
|
+
const g = expandV6(raw)
|
|
69
|
+
if (!g || g.some((x) => !Number.isInteger(x))) return false
|
|
70
|
+
if (g.every((x) => x === 0)) return true
|
|
71
|
+
if (g.slice(0, 7).every((x) => x === 0) && g[7] === 1) return true
|
|
72
|
+
if ((g[0] & 0xffc0) === 0xfe80) return true
|
|
73
|
+
if ((g[0] & 0xfe00) === 0xfc00) return true
|
|
74
|
+
if (g.slice(0, 5).every((x) => x === 0) && (g[5] === 0xffff || g[5] === 0)) {
|
|
75
|
+
return v4IsPrivate(`${g[6] >> 8}.${g[6] & 0xff}.${g[7] >> 8}.${g[7] & 0xff}`)
|
|
76
|
+
}
|
|
77
|
+
return false
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 一个字面地址是否属于内网/保留网段。 */
|
|
81
|
+
export function isPrivateAddress(raw) {
|
|
82
|
+
const host = normalizeHost(raw)
|
|
83
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) return v4IsPrivate(host)
|
|
84
|
+
if (host.includes(':')) return v6IsPrivate(host)
|
|
85
|
+
return false
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function hostIsPrivateLiteral(hostname) {
|
|
89
|
+
const host = normalizeHost(hostname)
|
|
90
|
+
if (!host) return true
|
|
91
|
+
if (isPrivateAddress(host)) return true
|
|
92
|
+
if (PRIVATE_NAME.some((re) => re.test(host))) return true
|
|
93
|
+
if (!host.includes('.') && !host.includes(':')) return true
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
32
96
|
|
|
33
97
|
/**
|
|
34
98
|
* 允许的链接:只放 http(s),且**拒绝内网地址**。
|
|
35
99
|
* 理由不是洁癖 —— yt-dlp 会把链接交给 ffmpeg,一个 169.254.169.254 就能把云元数据读出来。
|
|
36
100
|
*/
|
|
37
101
|
export function assertFetchableUrl(raw) {
|
|
38
|
-
const value = String(raw).trim()
|
|
102
|
+
const value = String(raw).trim()
|
|
39
103
|
if (!isHttpUrl(value)) {
|
|
40
|
-
throw new Error('only http(s) links are fetched; for a local file pass the path directly')
|
|
104
|
+
throw new Error('only http(s) links are fetched; for a local file pass the path directly')
|
|
105
|
+
}
|
|
106
|
+
const { hostname } = new URL(value)
|
|
107
|
+
if (hostIsPrivateLiteral(hostname)) {
|
|
108
|
+
throw new Error(`refusing to fetch a private/loopback host: ${hostname}`)
|
|
109
|
+
}
|
|
110
|
+
return value
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 在 `assertFetchableUrl` 之外,把域名解析出的每个地址再判一遍。
|
|
115
|
+
* 这样 `http://evil.example/`(A 记录指向 127.0.0.1)也不会被送去 yt-dlp。
|
|
116
|
+
* DNS rebinding 与 yt-dlp 自己跟随的 30x 仍在本层视野之外,属于已知残留风险。
|
|
117
|
+
*/
|
|
118
|
+
export async function assertFetchableUrlResolved(raw, { lookup } = {}) {
|
|
119
|
+
const value = assertFetchableUrl(raw)
|
|
120
|
+
const host = normalizeHost(new URL(value).hostname)
|
|
121
|
+
if (isPrivateAddress(host)) return value
|
|
122
|
+
const resolve = lookup ?? (await import('node:dns')).promises.lookup
|
|
123
|
+
let addrs
|
|
124
|
+
try {
|
|
125
|
+
addrs = await resolve(host, { all: true, verbatim: true })
|
|
126
|
+
} catch {
|
|
127
|
+
return value
|
|
41
128
|
}
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
129
|
+
for (const entry of Array.isArray(addrs) ? addrs : [addrs]) {
|
|
130
|
+
if (entry?.address && isPrivateAddress(entry.address)) {
|
|
131
|
+
throw new Error(`refusing to fetch ${host}: it resolves to a private host (${entry.address})`)
|
|
132
|
+
}
|
|
45
133
|
}
|
|
46
|
-
return value
|
|
134
|
+
return value
|
|
47
135
|
}
|
|
48
136
|
|
|
49
137
|
/**
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { formatMatches, matchSegments, recallSegments } from '../storyboard/locate.js';
|
|
9
|
-
import { resolveInput } from '../storyboard/
|
|
9
|
+
import { resolveInput } from '../storyboard/source.js';
|
|
10
10
|
import { runStoryboard } from '../storyboard/pipeline.js';
|
|
11
11
|
|
|
12
12
|
export async function execute(ctx, args) {
|
|
@@ -7,17 +7,15 @@
|
|
|
7
7
|
|
|
8
8
|
import { probeVideo } from '../storyboard/probe.js';
|
|
9
9
|
import { formatProbe, formatRemoteProbe } from '../storyboard/format.js';
|
|
10
|
-
import {
|
|
10
|
+
import { probeInput } from '../storyboard/source.js';
|
|
11
11
|
import { isHttpUrl } from '../storyboard/url.js';
|
|
12
12
|
|
|
13
13
|
export async function execute(ctx, args) {
|
|
14
14
|
if (!args?.input) throw new Error('input is required');
|
|
15
15
|
const fetchOptions = { cookies: args.cookies, allowAnonymous: args.allowAnonymous === true };
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
}
|
|
20
|
-
const info = { ...(await probeVideo(args.input)), path: args.input };
|
|
16
|
+
const got = await probeInput(args.input, fetchOptions);
|
|
17
|
+
if (got.remote) return { text: formatRemoteProbe(got.remote) };
|
|
18
|
+
const info = got.local ?? { ...(await probeVideo(args.input)), path: args.input };
|
|
21
19
|
return { text: await formatProbe(info) };
|
|
22
20
|
}
|
|
23
21
|
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
import { boardOptions } from '../storyboard/board.js';
|
|
11
11
|
import { lookupCell } from '../storyboard/cells.js';
|
|
12
|
-
import { resolveInput } from '../storyboard/
|
|
12
|
+
import { resolveInput } from '../storyboard/source.js';
|
|
13
13
|
import { isHttpUrl } from '../storyboard/url.js';
|
|
14
14
|
import { resolveDirectUrl } from '../storyboard/direct-url.js';
|
|
15
15
|
import { runStoryboard } from '../storyboard/pipeline.js';
|