@boy-offi9-inc/tidepull 0.0.0-stage → 0.1.0-rc.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/LICENSE +21 -0
- package/README.md +107 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +3 -0
- package/dist/core/downloader.d.ts +44 -0
- package/dist/core/downloader.js +160 -0
- package/dist/core/errors.d.ts +11 -0
- package/dist/core/errors.js +22 -0
- package/dist/core/events.d.ts +51 -0
- package/dist/core/events.js +5 -0
- package/dist/core/ffmpeg.d.ts +3 -0
- package/dist/core/ffmpeg.js +38 -0
- package/dist/core/hls.d.ts +41 -0
- package/dist/core/hls.js +102 -0
- package/dist/core/http.d.ts +46 -0
- package/dist/core/http.js +120 -0
- package/dist/core/meter.d.ts +6 -0
- package/dist/core/meter.js +17 -0
- package/dist/core/pipeline.d.ts +25 -0
- package/dist/core/pipeline.js +126 -0
- package/dist/core/selector.d.ts +32 -0
- package/dist/core/selector.js +166 -0
- package/dist/core/template.d.ts +3 -0
- package/dist/core/template.js +20 -0
- package/dist/core/types.d.ts +56 -0
- package/dist/core/types.js +1 -0
- package/dist/dash/index.d.ts +7 -0
- package/dist/dash/index.js +70 -0
- package/dist/dash/parse.d.ts +31 -0
- package/dist/dash/parse.js +140 -0
- package/dist/dash/xml.d.ts +9 -0
- package/dist/dash/xml.js +56 -0
- package/dist/extractors/direct.d.ts +3 -0
- package/dist/extractors/direct.js +34 -0
- package/dist/extractors/generic.d.ts +3 -0
- package/dist/extractors/generic.js +103 -0
- package/dist/extractors/hls.d.ts +3 -0
- package/dist/extractors/hls.js +72 -0
- package/dist/extractors/index.d.ts +5 -0
- package/dist/extractors/index.js +9 -0
- package/dist/extractors/util.d.ts +7 -0
- package/dist/extractors/util.js +13 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +8 -0
- package/dist/loader.d.ts +7 -0
- package/dist/loader.js +76 -0
- package/dist/main.d.ts +3 -0
- package/dist/main.js +243 -0
- package/dist/plugins.d.ts +10 -0
- package/dist/plugins.js +4 -0
- package/dist/tidepull.d.ts +48 -0
- package/dist/tidepull.js +107 -0
- package/dist/ui/format.d.ts +4 -0
- package/dist/ui/format.js +26 -0
- package/dist/ui/log.d.ts +19 -0
- package/dist/ui/log.js +37 -0
- package/dist/ui/render.d.ts +9 -0
- package/dist/ui/render.js +60 -0
- package/package.json +66 -4
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export interface HttpOptions {
|
|
2
|
+
headers?: Record<string, string>;
|
|
3
|
+
userAgent?: string;
|
|
4
|
+
retries?: number;
|
|
5
|
+
timeoutMs?: number;
|
|
6
|
+
maxRedirects?: number;
|
|
7
|
+
/**
|
|
8
|
+
* Scope for non-trivial custom headers (Authorization, Cookie, API tokens...).
|
|
9
|
+
* undefined = legacy/low-level mode: headers go to the origin each request starts at.
|
|
10
|
+
* string[] = scoped mode: they go ONLY to origins passed to `trust()` plus these host patterns
|
|
11
|
+
* ("cdn.example.com" or "*.example.com"). Tidepull uses scoped mode.
|
|
12
|
+
* Referer, Origin, User-Agent, Accept-* and Range are never considered secret and are always sent.
|
|
13
|
+
*/
|
|
14
|
+
headerHosts?: string[];
|
|
15
|
+
}
|
|
16
|
+
export interface RequestInitLite {
|
|
17
|
+
method?: string;
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
}
|
|
21
|
+
export declare class Http {
|
|
22
|
+
/** non-secret defaults (UA, Accept-Language, Referer...), always sent */
|
|
23
|
+
headers: Record<string, string>;
|
|
24
|
+
/** custom headers that may be secret; sent only to trusted origins (scoped mode) */
|
|
25
|
+
private secret;
|
|
26
|
+
private scopedMode;
|
|
27
|
+
private hostPatterns;
|
|
28
|
+
private trusted;
|
|
29
|
+
retries: number;
|
|
30
|
+
timeoutMs: number;
|
|
31
|
+
maxRedirects: number;
|
|
32
|
+
private defaultSignal?;
|
|
33
|
+
constructor(o?: HttpOptions);
|
|
34
|
+
/** Allow scoped headers to be sent to this URL's origin (scoped mode only). Tidepull calls this for every URL you give it. */
|
|
35
|
+
trust(url: string | URL): void;
|
|
36
|
+
private headersFor;
|
|
37
|
+
/** A view of this client whose requests are cancelled by `signal` (so extractors don't need to pass it around). */
|
|
38
|
+
scoped(signal?: AbortSignal): Http;
|
|
39
|
+
/** fetch with manual, origin-aware redirects + retry (network errors, 5xx, 429) with backoff. The timeout covers headers only. */
|
|
40
|
+
request(url: string, init?: RequestInitLite): Promise<Response>;
|
|
41
|
+
private follow;
|
|
42
|
+
text(url: string, init?: RequestInitLite): Promise<{
|
|
43
|
+
text: string;
|
|
44
|
+
finalUrl: string;
|
|
45
|
+
}>;
|
|
46
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { TidepullError, RedirectError, errMsg } from "./errors.js";
|
|
2
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3
|
+
const REDIRECT = new Set([301, 302, 303, 307, 308]);
|
|
4
|
+
/** Never secret: always sent wherever we connect. Everything else is "scoped" (see HttpOptions.headerHosts). */
|
|
5
|
+
const OPEN_HEADERS = new Set(["user-agent", "accept", "accept-language", "accept-encoding", "range", "referer", "origin"]);
|
|
6
|
+
const hostMatches = (pattern, host) => pattern.startsWith("*.") ? host === pattern.slice(2) || host.endsWith(pattern.slice(1)) : host === pattern;
|
|
7
|
+
export class Http {
|
|
8
|
+
/** non-secret defaults (UA, Accept-Language, Referer...), always sent */
|
|
9
|
+
headers;
|
|
10
|
+
/** custom headers that may be secret; sent only to trusted origins (scoped mode) */
|
|
11
|
+
secret;
|
|
12
|
+
scopedMode;
|
|
13
|
+
hostPatterns;
|
|
14
|
+
trusted = new Set();
|
|
15
|
+
retries;
|
|
16
|
+
timeoutMs;
|
|
17
|
+
maxRedirects;
|
|
18
|
+
defaultSignal;
|
|
19
|
+
constructor(o = {}) {
|
|
20
|
+
this.headers = {
|
|
21
|
+
"User-Agent": o.userAgent ?? "Mozilla/5.0 (compatible; tidepull/0.1)",
|
|
22
|
+
"Accept-Language": "en-US,en;q=0.9",
|
|
23
|
+
};
|
|
24
|
+
this.secret = {};
|
|
25
|
+
for (const [k, v] of Object.entries(o.headers ?? {})) {
|
|
26
|
+
if (OPEN_HEADERS.has(k.toLowerCase()))
|
|
27
|
+
this.headers[k] = v;
|
|
28
|
+
else
|
|
29
|
+
this.secret[k] = v;
|
|
30
|
+
}
|
|
31
|
+
this.scopedMode = o.headerHosts !== undefined;
|
|
32
|
+
this.hostPatterns = (o.headerHosts ?? []).map((h) => h.toLowerCase());
|
|
33
|
+
this.retries = o.retries ?? 3;
|
|
34
|
+
this.timeoutMs = o.timeoutMs ?? 30_000;
|
|
35
|
+
this.maxRedirects = o.maxRedirects ?? 10;
|
|
36
|
+
}
|
|
37
|
+
/** Allow scoped headers to be sent to this URL's origin (scoped mode only). Tidepull calls this for every URL you give it. */
|
|
38
|
+
trust(url) {
|
|
39
|
+
this.trusted.add(new URL(url).origin);
|
|
40
|
+
}
|
|
41
|
+
headersFor(u, start) {
|
|
42
|
+
const send = this.scopedMode ? this.trusted.has(u.origin) || this.hostPatterns.some((p) => hostMatches(p, u.hostname)) : u.origin === start.origin;
|
|
43
|
+
return send ? { ...this.headers, ...this.secret } : { ...this.headers };
|
|
44
|
+
}
|
|
45
|
+
/** A view of this client whose requests are cancelled by `signal` (so extractors don't need to pass it around). */
|
|
46
|
+
scoped(signal) {
|
|
47
|
+
if (!signal)
|
|
48
|
+
return this;
|
|
49
|
+
const h = Object.create(this);
|
|
50
|
+
h.defaultSignal = signal;
|
|
51
|
+
return h;
|
|
52
|
+
}
|
|
53
|
+
/** fetch with manual, origin-aware redirects + retry (network errors, 5xx, 429) with backoff. The timeout covers headers only. */
|
|
54
|
+
async request(url, init = {}) {
|
|
55
|
+
init = { ...init, signal: init.signal ?? this.defaultSignal };
|
|
56
|
+
let lastErr;
|
|
57
|
+
for (let attempt = 0; attempt <= this.retries; attempt++) {
|
|
58
|
+
if (attempt > 0)
|
|
59
|
+
await sleep(Math.min(250 * 2 ** (attempt - 1), 8000));
|
|
60
|
+
init.signal?.throwIfAborted();
|
|
61
|
+
try {
|
|
62
|
+
const res = await this.follow(url, init);
|
|
63
|
+
if ((res.status >= 500 || res.status === 429) && attempt < this.retries) {
|
|
64
|
+
await res.body?.cancel();
|
|
65
|
+
lastErr = new TidepullError(`HTTP ${res.status}`);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
return res;
|
|
69
|
+
}
|
|
70
|
+
catch (e) {
|
|
71
|
+
if (init.signal?.aborted || e instanceof RedirectError)
|
|
72
|
+
throw e;
|
|
73
|
+
lastErr = e;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
throw new TidepullError(`Unable to reach ${url}: ${errMsg(lastErr)}`);
|
|
77
|
+
}
|
|
78
|
+
async follow(url, init) {
|
|
79
|
+
const start = new URL(url);
|
|
80
|
+
let cur = start;
|
|
81
|
+
for (let hop = 0;; hop++) {
|
|
82
|
+
// per-request headers (Range, extractor-supplied Referer/Cookie...) only travel with the start origin; Range goes everywhere
|
|
83
|
+
const own = Object.fromEntries(Object.entries(init.headers ?? {}).filter(([k]) => cur.origin === start.origin || k.toLowerCase() === "range"));
|
|
84
|
+
const headers = { ...this.headersFor(cur, start), ...own };
|
|
85
|
+
const ctl = new AbortController();
|
|
86
|
+
const timer = setTimeout(() => ctl.abort(), this.timeoutMs);
|
|
87
|
+
const signal = init.signal ? AbortSignal.any([ctl.signal, init.signal]) : ctl.signal;
|
|
88
|
+
let res;
|
|
89
|
+
try {
|
|
90
|
+
res = await fetch(cur, { method: init.method, headers, redirect: "manual", signal });
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
}
|
|
95
|
+
if (!REDIRECT.has(res.status))
|
|
96
|
+
return res;
|
|
97
|
+
await res.body?.cancel();
|
|
98
|
+
const loc = res.headers.get("location");
|
|
99
|
+
if (!loc)
|
|
100
|
+
throw new RedirectError(`HTTP ${res.status} without Location from ${cur.href}`);
|
|
101
|
+
if (hop >= this.maxRedirects)
|
|
102
|
+
throw new RedirectError(`Too many redirects (>${this.maxRedirects}) starting at ${url}`);
|
|
103
|
+
const next = new URL(loc, cur);
|
|
104
|
+
if (next.protocol !== "http:" && next.protocol !== "https:")
|
|
105
|
+
throw new RedirectError(`Refusing redirect to ${next.protocol} URL`);
|
|
106
|
+
cur = next;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
async text(url, init = {}) {
|
|
110
|
+
const res = await this.request(url, init);
|
|
111
|
+
if (!res.ok) {
|
|
112
|
+
await res.body?.cancel();
|
|
113
|
+
throw new TidepullError(`HTTP ${res.status} ${res.statusText} for ${url}`);
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
text: await res.text(),
|
|
117
|
+
finalUrl: res.url || url,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Speed over a sliding ~3s window. */
|
|
2
|
+
export class Meter {
|
|
3
|
+
samples = [];
|
|
4
|
+
startBytes;
|
|
5
|
+
push(bytes, now = Date.now()) {
|
|
6
|
+
this.startBytes ??= bytes;
|
|
7
|
+
this.samples.push([now, bytes]);
|
|
8
|
+
while (this.samples.length > 2 && now - this.samples[0][0] > 3000)
|
|
9
|
+
this.samples.shift();
|
|
10
|
+
if (this.samples.length < 2)
|
|
11
|
+
return undefined;
|
|
12
|
+
const a = this.samples[0];
|
|
13
|
+
const b = this.samples[this.samples.length - 1];
|
|
14
|
+
const dt = (b[0] - a[0]) / 1000;
|
|
15
|
+
return dt > 0 ? (b[1] - a[1]) / dt : undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Ctx, Info } from "./types.js";
|
|
2
|
+
export declare const DEFAULT_OUTPUT = "%(title)s [%(id)s].%(ext)s";
|
|
3
|
+
export interface DownloadOptions {
|
|
4
|
+
/** format selector, default "bv*+ba/b" */
|
|
5
|
+
format: string;
|
|
6
|
+
/** output template, default "%(title)s [%(id)s].%(ext)s" */
|
|
7
|
+
output: string;
|
|
8
|
+
/** base directory */
|
|
9
|
+
paths: string;
|
|
10
|
+
/** resume from .part files */
|
|
11
|
+
resume: boolean;
|
|
12
|
+
overwrite: boolean;
|
|
13
|
+
/** HLS segments fetched in parallel */
|
|
14
|
+
concurrency: number;
|
|
15
|
+
/** container used when merging video+audio */
|
|
16
|
+
mergeFormat: string;
|
|
17
|
+
remuxVideo?: string;
|
|
18
|
+
/** ffmpeg binary or its directory (default: search PATH) */
|
|
19
|
+
ffmpeg?: string;
|
|
20
|
+
/** extra request headers for the media downloads */
|
|
21
|
+
headers: Record<string, string>;
|
|
22
|
+
}
|
|
23
|
+
export declare function extractInfo(rawUrl: string, ctx: Ctx): Promise<Info>;
|
|
24
|
+
/** Selects formats per opts.format, downloads them, merges/remuxes with ffmpeg if needed. Returns the final file path. */
|
|
25
|
+
export declare function downloadInfo(info: Info, opts: DownloadOptions, ctx: Ctx): Promise<string>;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { mkdir, rename, rm, stat } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { downloadDash, downloadHls, downloadHttp } from "./downloader.js";
|
|
4
|
+
import { TidepullError } from "./errors.js";
|
|
5
|
+
import { findFfmpeg, mergeStreams, remux } from "./ffmpeg.js";
|
|
6
|
+
import { Meter } from "./meter.js";
|
|
7
|
+
import { selectFormats } from "./selector.js";
|
|
8
|
+
import { renderTemplate } from "./template.js";
|
|
9
|
+
export const DEFAULT_OUTPUT = "%(title)s [%(id)s].%(ext)s";
|
|
10
|
+
export async function extractInfo(rawUrl, ctx) {
|
|
11
|
+
let url;
|
|
12
|
+
try {
|
|
13
|
+
url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(rawUrl) ? rawUrl : `https://${rawUrl}`);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
throw new TidepullError(`Invalid URL: ${rawUrl}`, 2);
|
|
17
|
+
}
|
|
18
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
19
|
+
throw new TidepullError(`Unsupported URL scheme: ${url.protocol}`, 2);
|
|
20
|
+
const ex = ctx.extractors.find((e) => e.suitable(url));
|
|
21
|
+
if (!ex)
|
|
22
|
+
throw new TidepullError(`No extractor can handle ${url.href}`);
|
|
23
|
+
ctx.emit({ type: "extract", extractor: ex.name, url: url.href });
|
|
24
|
+
const info = await ex.extract(url, ctx);
|
|
25
|
+
if (!info.formats?.length)
|
|
26
|
+
throw new TidepullError(`Extractor "${ex.name}" returned no formats`);
|
|
27
|
+
return info;
|
|
28
|
+
}
|
|
29
|
+
/** Drop undefined keys so events stay clean JSON (NDJSON consumers shouldn't see "speed": undefined / missing-vs-null ambiguity). */
|
|
30
|
+
const compact = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
31
|
+
const scalars = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => ["string", "number", "boolean"].includes(typeof v)));
|
|
32
|
+
/** Selects formats per opts.format, downloads them, merges/remuxes with ffmpeg if needed. Returns the final file path. */
|
|
33
|
+
export async function downloadInfo(info, opts, ctx) {
|
|
34
|
+
const chosen = selectFormats(opts.format, info.formats);
|
|
35
|
+
if (!chosen)
|
|
36
|
+
throw new TidepullError(`Requested format is not available: ${opts.format} (try --list-formats)`);
|
|
37
|
+
const ffmpeg = findFfmpeg(opts.ffmpeg);
|
|
38
|
+
const merging = chosen.length > 1;
|
|
39
|
+
if (merging && !ffmpeg) {
|
|
40
|
+
throw new TidepullError(`ffmpeg is required to merge ${chosen.map((f) => f.format_id).join("+")}. Install it, or pick one format (-f b).`);
|
|
41
|
+
}
|
|
42
|
+
const predictedExt = merging ? opts.mergeFormat : chosen[0].ext;
|
|
43
|
+
const fields = {
|
|
44
|
+
...scalars(info),
|
|
45
|
+
...scalars(chosen[0]),
|
|
46
|
+
format_id: chosen.map((f) => f.format_id).join("+"),
|
|
47
|
+
resolution: chosen[0].height ? `${chosen[0].width ?? "?"}x${chosen[0].height}` : "audio only",
|
|
48
|
+
ext: predictedExt,
|
|
49
|
+
};
|
|
50
|
+
let target = path.resolve(opts.paths, renderTemplate(opts.output, fields));
|
|
51
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
52
|
+
const exists = await stat(target).then(() => true, () => false);
|
|
53
|
+
if (exists && !opts.overwrite) {
|
|
54
|
+
ctx.log.info("download", `${target} has already been downloaded`);
|
|
55
|
+
return target;
|
|
56
|
+
}
|
|
57
|
+
const base = target.slice(0, target.length - path.extname(target).length);
|
|
58
|
+
const fetchOne = async (f, dest) => {
|
|
59
|
+
ctx.emit({ type: "start", format_id: f.format_id, dest });
|
|
60
|
+
const meter = new Meter();
|
|
61
|
+
const t0 = Date.now();
|
|
62
|
+
let last = 0;
|
|
63
|
+
let bytes = 0;
|
|
64
|
+
const onProgress = (p) => {
|
|
65
|
+
bytes = p.downloaded;
|
|
66
|
+
const speed = meter.push(p.downloaded);
|
|
67
|
+
const now = Date.now();
|
|
68
|
+
if (now - last < 100)
|
|
69
|
+
return;
|
|
70
|
+
last = now;
|
|
71
|
+
const eta = speed && p.total ? (p.total - p.downloaded) / speed : undefined;
|
|
72
|
+
ctx.emit(compact({ type: "progress", format_id: f.format_id, ...p, speed, eta }));
|
|
73
|
+
};
|
|
74
|
+
const common = { http: ctx.http, headers: { ...f.http_headers, ...opts.headers }, signal: ctx.signal, onProgress };
|
|
75
|
+
let ext = f.ext;
|
|
76
|
+
if (f.protocol === "hls")
|
|
77
|
+
({ ext } = await downloadHls(f.url, dest, { ...common, concurrency: opts.concurrency }));
|
|
78
|
+
else if (f.protocol === "dash")
|
|
79
|
+
({ ext } = await downloadDash(f, dest, { ...common, concurrency: opts.concurrency }));
|
|
80
|
+
else
|
|
81
|
+
await downloadHttp(f.url, dest, { ...common, resume: opts.resume });
|
|
82
|
+
const seconds = (Date.now() - t0) / 1000;
|
|
83
|
+
const avg = seconds > 0 ? (bytes - (meter.startBytes ?? 0)) / seconds : undefined;
|
|
84
|
+
ctx.emit(compact({ type: "finish", format_id: f.format_id, bytes, seconds, speed: avg }));
|
|
85
|
+
return ext;
|
|
86
|
+
};
|
|
87
|
+
if (!merging) {
|
|
88
|
+
const ext = await fetchOne(chosen[0], target);
|
|
89
|
+
if (ext !== path.extname(target).slice(1)) {
|
|
90
|
+
const fixed = `${base}.${ext}`; // e.g. HLS turned out to be fMP4
|
|
91
|
+
await rename(target, fixed);
|
|
92
|
+
target = fixed;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
const tmp = [];
|
|
97
|
+
try {
|
|
98
|
+
for (const f of chosen.slice(0, 2)) {
|
|
99
|
+
const dest = `${base}.f${f.format_id.replace(/\W+/g, "_")}.${f.ext}`;
|
|
100
|
+
tmp.push(dest);
|
|
101
|
+
await fetchOne(f, dest);
|
|
102
|
+
}
|
|
103
|
+
// video stream first, audio second
|
|
104
|
+
const [v, a] = chosen[0].vcodec !== "none" ? [tmp[0], tmp[1]] : [tmp[1], tmp[0]];
|
|
105
|
+
ctx.emit({ type: "merge", output: target });
|
|
106
|
+
await mergeStreams(ffmpeg, v, a, target);
|
|
107
|
+
}
|
|
108
|
+
catch (e) {
|
|
109
|
+
await rm(target, { force: true });
|
|
110
|
+
throw e;
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
await Promise.all(tmp.map((t) => rm(t, { force: true })));
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (opts.remuxVideo && path.extname(target).slice(1) !== opts.remuxVideo) {
|
|
117
|
+
if (!ffmpeg)
|
|
118
|
+
throw new TidepullError("ffmpeg is required for --remux-video");
|
|
119
|
+
const out = `${base}.${opts.remuxVideo}`;
|
|
120
|
+
ctx.emit({ type: "remux", output: out });
|
|
121
|
+
await remux(ffmpeg, target, out);
|
|
122
|
+
await rm(target, { force: true });
|
|
123
|
+
target = out;
|
|
124
|
+
}
|
|
125
|
+
return target;
|
|
126
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* yt-dlp-style format selector.
|
|
3
|
+
* b / best best pre-merged format bv / bestvideo best video-only
|
|
4
|
+
* w / worst worst pre-merged format ba / bestaudio best audio-only
|
|
5
|
+
* bv* / ba* best with video / with audio <format_id> exact id
|
|
6
|
+
* a+b merge two formats a/b fallback if a unavailable
|
|
7
|
+
* x[height<=720] filters: <= >= < > = != (add ? after the op to also accept missing fields)
|
|
8
|
+
* (a/b)+c grouping
|
|
9
|
+
*/
|
|
10
|
+
import type { Format } from "./types.js";
|
|
11
|
+
export declare const DEFAULT_FORMAT = "bv*+ba/b";
|
|
12
|
+
interface Filter {
|
|
13
|
+
field: string;
|
|
14
|
+
op: string;
|
|
15
|
+
value: string;
|
|
16
|
+
optional: boolean;
|
|
17
|
+
}
|
|
18
|
+
type Node = {
|
|
19
|
+
kind: "fmt";
|
|
20
|
+
name: string;
|
|
21
|
+
filters: Filter[];
|
|
22
|
+
} | {
|
|
23
|
+
kind: "merge";
|
|
24
|
+
parts: Node[];
|
|
25
|
+
} | {
|
|
26
|
+
kind: "alt";
|
|
27
|
+
options: Node[];
|
|
28
|
+
};
|
|
29
|
+
export declare function parseSelector(sel: string): Node;
|
|
30
|
+
/** Returns the chosen formats (2+ means "merge these"), or undefined if nothing matches. */
|
|
31
|
+
export declare function selectFormats(selector: string, formats: Format[]): Format[] | undefined;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { TidepullError } from "./errors.js";
|
|
2
|
+
export const DEFAULT_FORMAT = "bv*+ba/b";
|
|
3
|
+
function bad(sel, why) {
|
|
4
|
+
throw new TidepullError(`Invalid format selector "${sel}": ${why}`, 2);
|
|
5
|
+
}
|
|
6
|
+
export function parseSelector(sel) {
|
|
7
|
+
let i = 0;
|
|
8
|
+
const peek = () => sel[i];
|
|
9
|
+
function alt() {
|
|
10
|
+
const options = [merge()];
|
|
11
|
+
while (peek() === "/") {
|
|
12
|
+
i++;
|
|
13
|
+
options.push(merge());
|
|
14
|
+
}
|
|
15
|
+
return options.length === 1 ? options[0] : { kind: "alt", options };
|
|
16
|
+
}
|
|
17
|
+
function merge() {
|
|
18
|
+
const parts = [atom()];
|
|
19
|
+
while (peek() === "+") {
|
|
20
|
+
i++;
|
|
21
|
+
parts.push(atom());
|
|
22
|
+
}
|
|
23
|
+
return parts.length === 1 ? parts[0] : { kind: "merge", parts };
|
|
24
|
+
}
|
|
25
|
+
function atom() {
|
|
26
|
+
if (peek() === "(") {
|
|
27
|
+
i++;
|
|
28
|
+
const n = alt();
|
|
29
|
+
if (peek() !== ")")
|
|
30
|
+
bad(sel, "missing )");
|
|
31
|
+
i++;
|
|
32
|
+
return n;
|
|
33
|
+
}
|
|
34
|
+
const start = i;
|
|
35
|
+
while (i < sel.length && !"+/[()".includes(sel[i]))
|
|
36
|
+
i++;
|
|
37
|
+
const name = sel.slice(start, i).trim();
|
|
38
|
+
if (!name)
|
|
39
|
+
bad(sel, `expected a format name at position ${start}`);
|
|
40
|
+
const filters = [];
|
|
41
|
+
while (peek() === "[") {
|
|
42
|
+
const end = sel.indexOf("]", i);
|
|
43
|
+
if (end < 0)
|
|
44
|
+
bad(sel, "missing ]");
|
|
45
|
+
const m = /^\s*([a-z_]+)\s*(<=|>=|!=|<|>|=)\s*(\?)?\s*([^<>=!\s].*?)\s*$/.exec(sel.slice(i + 1, end));
|
|
46
|
+
if (!m)
|
|
47
|
+
bad(sel, `bad filter "${sel.slice(i, end + 1)}"`);
|
|
48
|
+
filters.push({ field: m[1], op: m[2], value: m[4], optional: m[3] === "?" });
|
|
49
|
+
i = end + 1;
|
|
50
|
+
}
|
|
51
|
+
return { kind: "fmt", name, filters };
|
|
52
|
+
}
|
|
53
|
+
const tree = alt();
|
|
54
|
+
if (i < sel.length)
|
|
55
|
+
bad(sel, `unexpected "${sel[i]}" at position ${i}`);
|
|
56
|
+
return tree;
|
|
57
|
+
}
|
|
58
|
+
function parseNum(s) {
|
|
59
|
+
const m = /^(\d+(?:\.\d+)?)\s*([kmg])?i?b?$/i.exec(s);
|
|
60
|
+
if (!m)
|
|
61
|
+
return undefined;
|
|
62
|
+
const unit = (m[2] ?? "").toLowerCase();
|
|
63
|
+
const mult = unit === "k" ? 1024 : unit === "m" ? 1024 ** 2 : unit === "g" ? 1024 ** 3 : 1;
|
|
64
|
+
return Number(m[1]) * mult;
|
|
65
|
+
}
|
|
66
|
+
function passes(f, flt) {
|
|
67
|
+
const raw = f[flt.field];
|
|
68
|
+
if (raw === undefined || raw === null)
|
|
69
|
+
return flt.optional;
|
|
70
|
+
const want = parseNum(flt.value);
|
|
71
|
+
if (typeof raw === "number" && want !== undefined) {
|
|
72
|
+
switch (flt.op) {
|
|
73
|
+
case "<=": return raw <= want;
|
|
74
|
+
case ">=": return raw >= want;
|
|
75
|
+
case "<": return raw < want;
|
|
76
|
+
case ">": return raw > want;
|
|
77
|
+
case "=": return raw === want;
|
|
78
|
+
case "!=": return raw !== want;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const s = String(raw);
|
|
82
|
+
if (flt.op === "=")
|
|
83
|
+
return s === flt.value;
|
|
84
|
+
if (flt.op === "!=")
|
|
85
|
+
return s !== flt.value;
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
const hasV = (f) => f.vcodec !== "none";
|
|
89
|
+
const hasA = (f) => f.acodec !== "none";
|
|
90
|
+
const ALIASES = {
|
|
91
|
+
best: { kind: "mux", worst: false }, b: { kind: "mux", worst: false },
|
|
92
|
+
worst: { kind: "mux", worst: true }, w: { kind: "mux", worst: true },
|
|
93
|
+
"b*": { kind: "any", worst: false }, "w*": { kind: "any", worst: true },
|
|
94
|
+
bestvideo: { kind: "v", worst: false }, bv: { kind: "v", worst: false }, "bv*": { kind: "v*", worst: false },
|
|
95
|
+
worstvideo: { kind: "v", worst: true }, wv: { kind: "v", worst: true }, "wv*": { kind: "v*", worst: true },
|
|
96
|
+
bestaudio: { kind: "a", worst: false }, ba: { kind: "a", worst: false }, "ba*": { kind: "a*", worst: false },
|
|
97
|
+
worstaudio: { kind: "a", worst: true }, wa: { kind: "a", worst: true }, "wa*": { kind: "a*", worst: true },
|
|
98
|
+
};
|
|
99
|
+
function poolFor(kind, fs) {
|
|
100
|
+
switch (kind) {
|
|
101
|
+
case "mux": {
|
|
102
|
+
const m = fs.filter((f) => hasV(f) && hasA(f));
|
|
103
|
+
return m.length ? m : fs.filter(hasV).length ? fs.filter(hasV) : fs;
|
|
104
|
+
}
|
|
105
|
+
case "v": return fs.filter((f) => hasV(f) && !hasA(f));
|
|
106
|
+
case "v*": return fs.filter(hasV);
|
|
107
|
+
case "a": return fs.filter((f) => hasA(f) && !hasV(f));
|
|
108
|
+
case "a*": return fs.filter(hasA);
|
|
109
|
+
default: return fs;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function rank(f, audio) {
|
|
113
|
+
return audio ? [f.abr ?? f.tbr ?? 0, f.tbr ?? 0] : [f.height ?? 0, f.fps ?? 0, f.tbr ?? 0];
|
|
114
|
+
}
|
|
115
|
+
function cmp(a, b) {
|
|
116
|
+
for (let i = 0; i < a.length; i++)
|
|
117
|
+
if (a[i] !== b[i])
|
|
118
|
+
return a[i] - b[i];
|
|
119
|
+
return 0;
|
|
120
|
+
}
|
|
121
|
+
function pick(name, filters, all) {
|
|
122
|
+
const fs = all.filter((f) => filters.every((x) => passes(f, x)));
|
|
123
|
+
const alias = ALIASES[name];
|
|
124
|
+
if (!alias)
|
|
125
|
+
return fs.find((f) => f.format_id === name);
|
|
126
|
+
const pool = poolFor(alias.kind, fs);
|
|
127
|
+
if (!pool.length)
|
|
128
|
+
return undefined;
|
|
129
|
+
const audio = alias.kind === "a" || alias.kind === "a*";
|
|
130
|
+
let best = pool[0];
|
|
131
|
+
for (const f of pool.slice(1)) {
|
|
132
|
+
const c = cmp(rank(f, audio), rank(best, audio));
|
|
133
|
+
if (alias.worst ? c < 0 : c >= 0)
|
|
134
|
+
best = f;
|
|
135
|
+
}
|
|
136
|
+
return best;
|
|
137
|
+
}
|
|
138
|
+
function evaluate(n, fs) {
|
|
139
|
+
switch (n.kind) {
|
|
140
|
+
case "fmt": {
|
|
141
|
+
const f = pick(n.name, n.filters, fs);
|
|
142
|
+
return f ? [f] : undefined;
|
|
143
|
+
}
|
|
144
|
+
case "merge": {
|
|
145
|
+
const out = [];
|
|
146
|
+
for (const p of n.parts) {
|
|
147
|
+
const r = evaluate(p, fs);
|
|
148
|
+
if (!r)
|
|
149
|
+
return undefined;
|
|
150
|
+
out.push(...r);
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
case "alt":
|
|
155
|
+
for (const o of n.options) {
|
|
156
|
+
const r = evaluate(o, fs);
|
|
157
|
+
if (r)
|
|
158
|
+
return r;
|
|
159
|
+
}
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/** Returns the chosen formats (2+ means "merge these"), or undefined if nothing matches. */
|
|
164
|
+
export function selectFormats(selector, formats) {
|
|
165
|
+
return evaluate(parseSelector(selector), formats);
|
|
166
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** yt-dlp-style output templates: "%(title)s [%(id)s].%(ext)s", "%(uploader|unknown)s", "%(title).50s" */
|
|
2
|
+
export function sanitize(s) {
|
|
3
|
+
const cleaned = s
|
|
4
|
+
.replace(/[\\/:*?"<>|\x00-\x1f]/g, "_")
|
|
5
|
+
.replace(/\s+/g, " ")
|
|
6
|
+
.trim()
|
|
7
|
+
.replace(/^[. ]+|[. ]+$/g, "");
|
|
8
|
+
return (cleaned || "_").slice(0, 200);
|
|
9
|
+
}
|
|
10
|
+
export function renderTemplate(tpl, fields) {
|
|
11
|
+
return tpl.replace(/%%|%\(([A-Za-z_]\w*)(?:\|([^)]*))?\)(?:\.(\d+))?s/g, (m, key, dflt, max) => {
|
|
12
|
+
if (m === "%%")
|
|
13
|
+
return "%";
|
|
14
|
+
const v = fields[key];
|
|
15
|
+
let s = v === undefined || v === null || typeof v === "object" ? (dflt ?? "NA") : String(v);
|
|
16
|
+
if (max)
|
|
17
|
+
s = s.slice(0, Number(max));
|
|
18
|
+
return sanitize(s);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Emit, Log } from "./events.js";
|
|
2
|
+
import type { Http } from "./http.js";
|
|
3
|
+
export type Protocol = "https" | "hls" | "dash";
|
|
4
|
+
/** One downloadable stream. Mirrors the yt-dlp format dict, minus the baggage. */
|
|
5
|
+
export interface Format {
|
|
6
|
+
format_id: string;
|
|
7
|
+
url: string;
|
|
8
|
+
ext: string;
|
|
9
|
+
protocol: Protocol;
|
|
10
|
+
width?: number;
|
|
11
|
+
height?: number;
|
|
12
|
+
fps?: number;
|
|
13
|
+
/** "none" = no video track. "unknown" = present but codec not known. */
|
|
14
|
+
vcodec: string;
|
|
15
|
+
/** "none" = no audio track. */
|
|
16
|
+
acodec: string;
|
|
17
|
+
/** total bitrate, kbit/s */
|
|
18
|
+
tbr?: number;
|
|
19
|
+
/** audio bitrate, kbit/s */
|
|
20
|
+
abr?: number;
|
|
21
|
+
filesize?: number;
|
|
22
|
+
format_note?: string;
|
|
23
|
+
http_headers?: Record<string, string>;
|
|
24
|
+
/** dash: init segment URL (written first) */
|
|
25
|
+
init?: string;
|
|
26
|
+
/** dash: media segment URLs in order */
|
|
27
|
+
fragments?: string[];
|
|
28
|
+
}
|
|
29
|
+
/** What every extractor returns (the "info dict"). */
|
|
30
|
+
export interface Info {
|
|
31
|
+
id: string;
|
|
32
|
+
title: string;
|
|
33
|
+
extractor: string;
|
|
34
|
+
webpage_url: string;
|
|
35
|
+
formats: Format[];
|
|
36
|
+
thumbnail?: string;
|
|
37
|
+
duration?: number;
|
|
38
|
+
uploader?: string;
|
|
39
|
+
upload_date?: string;
|
|
40
|
+
[key: string]: unknown;
|
|
41
|
+
}
|
|
42
|
+
/** Passed to every extractor call. */
|
|
43
|
+
export interface Ctx {
|
|
44
|
+
http: Http;
|
|
45
|
+
log: Log;
|
|
46
|
+
emit: Emit;
|
|
47
|
+
/** Ordered extractor list (plugins, built-ins, generic last). */
|
|
48
|
+
extractors: readonly Extractor[];
|
|
49
|
+
signal?: AbortSignal;
|
|
50
|
+
}
|
|
51
|
+
/** The extractor contract. One file per site. */
|
|
52
|
+
export interface Extractor {
|
|
53
|
+
readonly name: string;
|
|
54
|
+
suitable(url: URL): boolean;
|
|
55
|
+
extract(url: URL, ctx: Ctx): Promise<Info>;
|
|
56
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Ctx, Extractor, Info } from "../core/types.js";
|
|
2
|
+
import { parseMpd } from "./parse.js";
|
|
3
|
+
export declare const dashExtractor: Extractor;
|
|
4
|
+
export declare function extractDash(url: URL, ctx: Ctx): Promise<Info>;
|
|
5
|
+
export { parseMpd };
|
|
6
|
+
declare const _default: import("../plugins.js").TidepullPlugin;
|
|
7
|
+
export default _default;
|