@boy-offi9-inc/tidepull 0.1.0-rc.0 → 0.2.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/README.md +10 -0
- package/dist/cliutil.d.ts +22 -0
- package/dist/cliutil.js +115 -0
- package/dist/core/downloader.d.ts +9 -0
- package/dist/core/downloader.js +33 -4
- package/dist/core/events.d.ts +1 -1
- package/dist/core/http.js +2 -2
- package/dist/core/pipeline.d.ts +4 -2
- package/dist/core/pipeline.js +8 -5
- package/dist/core/selector.d.ts +1 -1
- package/dist/core/template.d.ts +1 -1
- package/dist/core/template.js +1 -1
- package/dist/core/types.d.ts +1 -1
- package/dist/dash/index.js +2 -2
- package/dist/dash/xml.js +1 -1
- package/dist/extractors/generic.js +2 -1
- package/dist/main.d.ts +1 -1
- package/dist/main.js +49 -5
- package/dist/tidepull.d.ts +1 -1
- package/dist/tidepull.js +2 -3
- package/dist/ui/render.d.ts +2 -2
- package/dist/ui/render.js +14 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -35,6 +35,8 @@ setTimeout(() => ctl.abort(), 5000);
|
|
|
35
35
|
await g.pull(url, { signal: ctl.signal }); // rejects with name === "AbortError"
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
+
Cap the speed with `limitRate` (bytes per second, applied to each file): `g.download(info, { limitRate: 1_000_000 })`.
|
|
39
|
+
|
|
38
40
|
## API (everything else is internal)
|
|
39
41
|
| Export | Purpose |
|
|
40
42
|
|---|---|
|
|
@@ -72,7 +74,14 @@ tidepull -F URL # list formats
|
|
|
72
74
|
tidepull -f "bv*[height<=720]+ba/b" URL # select + merge (needs ffmpeg)
|
|
73
75
|
tidepull -o "%(title).60s [%(id)s].%(ext)s" -P ~/Videos URL
|
|
74
76
|
tidepull -j URL | jq .formats # data on stdout, logs on stderr
|
|
77
|
+
tidepull -a urls.txt --download-archive done.txt # batch input; skip what you already downloaded
|
|
78
|
+
tidepull --limit-rate 1M URL # cap the speed (500K, 1.5M, ...)
|
|
75
79
|
```
|
|
80
|
+
|
|
81
|
+
**Batch and archive.** `-a FILE` reads one URL per line (`#` starts a comment, `-` reads stdin). `--download-archive FILE` records each finished item and skips it on later runs.
|
|
82
|
+
|
|
83
|
+
**Config file.** Defaults go in `~/.config/tidepull/config` (or `--config-location FILE`): one or more options per line, `#` for comments, for example `-P ~/Videos` and `--limit-rate 2M`. Options on the command line win; `--no-config` ignores the file.
|
|
84
|
+
|
|
76
85
|
From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node >= 22.18); `npm run build` emits JS + `.d.ts`.
|
|
77
86
|
|
|
78
87
|
## What works today
|
|
@@ -85,6 +94,7 @@ From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node
|
|
|
85
94
|
| Format selector | `b bv bv* ba ba* w wv wa`, `+` merge, `/` fallback, `()` groups, `[height<=720]` `[filesize<?50M]` `[ext=mp4]` |
|
|
86
95
|
| Output templates | `%(title)s`, `%(x\|default)s`, `%(title).50s`, sanitized |
|
|
87
96
|
| Merge / remux | ffmpeg |
|
|
97
|
+
| Site-specific extractors | none built in. Platforms such as YouTube hide their media behind scripts and tokens and need a plugin (see Plugins) |
|
|
88
98
|
| Not yet | live HLS/DASH, multi-period DASH, SAMPLE-AES, byte-range HLS/DASH, playlists, subtitles, cookies |
|
|
89
99
|
|
|
90
100
|
## Footprint (enforced in CI)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Info } from "./core/types.js";
|
|
2
|
+
/** "500K", "1.5M", "2G" or plain bytes per second. */
|
|
3
|
+
export declare function parseRate(s: string): number;
|
|
4
|
+
/** Splits a config line into arguments. Supports 'single' and "double" quotes and \" inside double quotes. */
|
|
5
|
+
export declare function splitArgs(line: string): string[];
|
|
6
|
+
/** One URL per line; blank lines and lines starting with # are ignored. "-" reads stdin. */
|
|
7
|
+
export declare function readUrlList(file: string): string[];
|
|
8
|
+
export declare function defaultConfigPath(env?: NodeJS.ProcessEnv): string;
|
|
9
|
+
/**
|
|
10
|
+
* Arguments from the config file: one or more options per line, # starts a comment.
|
|
11
|
+
* Placed before the command line so the command line wins. Returns [] when disabled or absent.
|
|
12
|
+
*/
|
|
13
|
+
export declare function configArgs(argv: string[], env?: NodeJS.ProcessEnv): string[];
|
|
14
|
+
/** Remembers finished downloads so later runs skip them. One key per line. */
|
|
15
|
+
export declare class Archive {
|
|
16
|
+
private file;
|
|
17
|
+
private keys;
|
|
18
|
+
constructor(file: string);
|
|
19
|
+
static key(info: Info): string;
|
|
20
|
+
has(info: Info): boolean;
|
|
21
|
+
add(info: Info): void;
|
|
22
|
+
}
|
package/dist/cliutil.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/** CLI-only helpers: config file, batch input, download archive, rate parsing. Not part of the library entry point. */
|
|
2
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { TidepullError, errMsg } from "./core/errors.js";
|
|
6
|
+
/** "500K", "1.5M", "2G" or plain bytes per second. */
|
|
7
|
+
export function parseRate(s) {
|
|
8
|
+
const m = /^(\d+(?:\.\d+)?)([KMG])?$/i.exec(s.trim());
|
|
9
|
+
if (!m || !(Number(m[1]) > 0))
|
|
10
|
+
throw new TidepullError(`Invalid rate "${s}" (examples: 500K, 1.5M)`, 2);
|
|
11
|
+
const mult = { K: 1024, M: 1024 ** 2, G: 1024 ** 3 }[(m[2] ?? "").toUpperCase()] ?? 1;
|
|
12
|
+
return Math.round(Number(m[1]) * mult);
|
|
13
|
+
}
|
|
14
|
+
/** Splits a config line into arguments. Supports 'single' and "double" quotes and \" inside double quotes. */
|
|
15
|
+
export function splitArgs(line) {
|
|
16
|
+
const out = [];
|
|
17
|
+
let cur = "";
|
|
18
|
+
let quote = "";
|
|
19
|
+
let started = false;
|
|
20
|
+
for (let i = 0; i < line.length; i++) {
|
|
21
|
+
const c = line[i];
|
|
22
|
+
if (quote) {
|
|
23
|
+
if (c === quote)
|
|
24
|
+
quote = "";
|
|
25
|
+
else if (c === "\\" && quote === '"' && i + 1 < line.length)
|
|
26
|
+
cur += line[++i];
|
|
27
|
+
else
|
|
28
|
+
cur += c;
|
|
29
|
+
}
|
|
30
|
+
else if (c === '"' || c === "'") {
|
|
31
|
+
quote = c;
|
|
32
|
+
started = true;
|
|
33
|
+
}
|
|
34
|
+
else if (/\s/.test(c)) {
|
|
35
|
+
if (cur || started)
|
|
36
|
+
out.push(cur);
|
|
37
|
+
cur = "";
|
|
38
|
+
started = false;
|
|
39
|
+
}
|
|
40
|
+
else
|
|
41
|
+
cur += c;
|
|
42
|
+
}
|
|
43
|
+
if (quote)
|
|
44
|
+
throw new TidepullError(`Unterminated quote in: ${line}`, 2);
|
|
45
|
+
if (cur || started)
|
|
46
|
+
out.push(cur);
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
/** One URL per line; blank lines and lines starting with # are ignored. "-" reads stdin. */
|
|
50
|
+
export function readUrlList(file) {
|
|
51
|
+
let text;
|
|
52
|
+
try {
|
|
53
|
+
text = readFileSync(file === "-" ? 0 : file, "utf8");
|
|
54
|
+
}
|
|
55
|
+
catch (e) {
|
|
56
|
+
throw new TidepullError(`Cannot read batch file ${file}: ${errMsg(e)}`, 2);
|
|
57
|
+
}
|
|
58
|
+
return text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith("#"));
|
|
59
|
+
}
|
|
60
|
+
export function defaultConfigPath(env = process.env) {
|
|
61
|
+
return path.join(env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"), "tidepull", "config");
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Arguments from the config file: one or more options per line, # starts a comment.
|
|
65
|
+
* Placed before the command line so the command line wins. Returns [] when disabled or absent.
|
|
66
|
+
*/
|
|
67
|
+
export function configArgs(argv, env = process.env) {
|
|
68
|
+
if (argv.includes("--no-config"))
|
|
69
|
+
return [];
|
|
70
|
+
const at = argv.findIndex((a) => a === "--config-location" || a.startsWith("--config-location="));
|
|
71
|
+
let file;
|
|
72
|
+
if (at >= 0) {
|
|
73
|
+
const a = argv[at];
|
|
74
|
+
file = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[at + 1];
|
|
75
|
+
if (!file || !existsSync(file))
|
|
76
|
+
throw new TidepullError(`Config file not found: ${file ?? "(no path given)"}`, 2);
|
|
77
|
+
}
|
|
78
|
+
else if (existsSync(defaultConfigPath(env)))
|
|
79
|
+
file = defaultConfigPath(env);
|
|
80
|
+
if (!file)
|
|
81
|
+
return [];
|
|
82
|
+
const out = [];
|
|
83
|
+
for (const raw of readFileSync(file, "utf8").split(/\r?\n/)) {
|
|
84
|
+
const line = raw.trim();
|
|
85
|
+
if (line && !line.startsWith("#"))
|
|
86
|
+
out.push(...splitArgs(line));
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
/** Extractors whose ids are not globally unique (a file name, a playlist path): key them by URL instead. */
|
|
91
|
+
const BY_URL = new Set(["direct", "hls", "dash", "generic"]);
|
|
92
|
+
/** Remembers finished downloads so later runs skip them. One key per line. */
|
|
93
|
+
export class Archive {
|
|
94
|
+
file;
|
|
95
|
+
keys;
|
|
96
|
+
constructor(file) {
|
|
97
|
+
this.file = file;
|
|
98
|
+
const lines = existsSync(file) ? readFileSync(file, "utf8").split(/\r?\n/) : [];
|
|
99
|
+
this.keys = new Set(lines.map((l) => l.trim()).filter(Boolean));
|
|
100
|
+
}
|
|
101
|
+
static key(info) {
|
|
102
|
+
return `${info.extractor} ${BY_URL.has(info.extractor) ? info.webpage_url : info.id}`;
|
|
103
|
+
}
|
|
104
|
+
has(info) {
|
|
105
|
+
return this.keys.has(Archive.key(info));
|
|
106
|
+
}
|
|
107
|
+
add(info) {
|
|
108
|
+
const key = Archive.key(info);
|
|
109
|
+
if (this.keys.has(key))
|
|
110
|
+
return;
|
|
111
|
+
mkdirSync(path.dirname(path.resolve(this.file)), { recursive: true });
|
|
112
|
+
appendFileSync(this.file, key + "\n");
|
|
113
|
+
this.keys.add(key);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -6,10 +6,19 @@ export interface Progress {
|
|
|
6
6
|
/** total is a guess (HLS: extrapolated from finished segments) */
|
|
7
7
|
estimated?: boolean;
|
|
8
8
|
}
|
|
9
|
+
/** Caps average throughput at `rate` bytes per second by delaying callers. */
|
|
10
|
+
export declare class RateLimiter {
|
|
11
|
+
private rate;
|
|
12
|
+
private start;
|
|
13
|
+
private sent;
|
|
14
|
+
constructor(rate: number);
|
|
15
|
+
take(bytes: number, signal?: AbortSignal): Promise<void>;
|
|
16
|
+
}
|
|
9
17
|
export interface DownloadOpts {
|
|
10
18
|
http: Http;
|
|
11
19
|
headers?: Record<string, string>;
|
|
12
20
|
signal?: AbortSignal;
|
|
21
|
+
limiter?: RateLimiter;
|
|
13
22
|
onProgress: (p: Progress) => void;
|
|
14
23
|
}
|
|
15
24
|
/** Plain HTTP download. Resumes from `<dest>.part` with Range requests. */
|
package/dist/core/downloader.js
CHANGED
|
@@ -1,10 +1,26 @@
|
|
|
1
1
|
import { createDecipheriv } from "node:crypto";
|
|
2
2
|
import { createWriteStream } from "node:fs";
|
|
3
3
|
import { rename, rm, stat } from "node:fs/promises";
|
|
4
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
4
5
|
import { Readable, Transform } from "node:stream";
|
|
5
6
|
import { pipeline } from "node:stream/promises";
|
|
6
7
|
import { TidepullError } from "./errors.js";
|
|
7
8
|
import { isMasterPlaylist, parseMedia } from "./hls.js";
|
|
9
|
+
/** Caps average throughput at `rate` bytes per second by delaying callers. */
|
|
10
|
+
export class RateLimiter {
|
|
11
|
+
rate;
|
|
12
|
+
start = Date.now();
|
|
13
|
+
sent = 0;
|
|
14
|
+
constructor(rate) {
|
|
15
|
+
this.rate = rate;
|
|
16
|
+
}
|
|
17
|
+
async take(bytes, signal) {
|
|
18
|
+
this.sent += bytes;
|
|
19
|
+
const wait = this.start + (this.sent / this.rate) * 1000 - Date.now();
|
|
20
|
+
if (wait > 0)
|
|
21
|
+
await sleep(wait, undefined, { signal });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
8
24
|
/** Plain HTTP download. Resumes from `<dest>.part` with Range requests. */
|
|
9
25
|
export async function downloadHttp(url, dest, o) {
|
|
10
26
|
const part = dest + ".part";
|
|
@@ -16,7 +32,7 @@ export async function downloadHttp(url, dest, o) {
|
|
|
16
32
|
headers.Range = `bytes=${offset}-`;
|
|
17
33
|
const res = await o.http.request(url, { headers, signal: o.signal });
|
|
18
34
|
if (res.status === 416) {
|
|
19
|
-
// Range not satisfiable: the .part is either
|
|
35
|
+
// Range not satisfiable: the .part is either complete or stale.
|
|
20
36
|
await res.body?.cancel();
|
|
21
37
|
const total = /\*\/(\d+)/.exec(res.headers.get("content-range") ?? "")?.[1];
|
|
22
38
|
if (total && Number(total) === offset) {
|
|
@@ -40,7 +56,7 @@ export async function downloadHttp(url, dest, o) {
|
|
|
40
56
|
total = m ? Number(m[2]) : undefined;
|
|
41
57
|
}
|
|
42
58
|
else {
|
|
43
|
-
offset = 0; //
|
|
59
|
+
offset = 0; // no usable Range response: start over
|
|
44
60
|
const cl = res.headers.get("content-length");
|
|
45
61
|
total = cl ? Number(cl) : undefined;
|
|
46
62
|
}
|
|
@@ -52,7 +68,19 @@ export async function downloadHttp(url, dest, o) {
|
|
|
52
68
|
cb(null, chunk);
|
|
53
69
|
},
|
|
54
70
|
});
|
|
55
|
-
|
|
71
|
+
const limiter = o.limiter;
|
|
72
|
+
const throttle = new Transform({
|
|
73
|
+
async transform(chunk, _enc, cb) {
|
|
74
|
+
try {
|
|
75
|
+
await limiter?.take(chunk.length, o.signal);
|
|
76
|
+
cb(null, chunk);
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
cb(e);
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
await pipeline(Readable.fromWeb(res.body), throttle, counter, createWriteStream(part, { flags: append ? "a" : "w" }), { signal: o.signal });
|
|
56
84
|
if (total !== undefined && done !== total) {
|
|
57
85
|
throw new TidepullError(`Incomplete download (${done}/${total} bytes). Re-run to resume.`);
|
|
58
86
|
}
|
|
@@ -105,7 +133,7 @@ export async function downloadSegments(segments, dest, o) {
|
|
|
105
133
|
const inflight = new Array(n);
|
|
106
134
|
const start = (i) => {
|
|
107
135
|
inflight[i] = fetchSeg(i);
|
|
108
|
-
inflight[i].catch(() => { }); //
|
|
136
|
+
inflight[i].catch(() => { }); // handled when awaited in order
|
|
109
137
|
};
|
|
110
138
|
let ext = "ts";
|
|
111
139
|
let lastMap;
|
|
@@ -126,6 +154,7 @@ export async function downloadSegments(segments, dest, o) {
|
|
|
126
154
|
lastMap = map;
|
|
127
155
|
ext = "mp4";
|
|
128
156
|
}
|
|
157
|
+
await o.limiter?.take(buf.length, o.signal);
|
|
129
158
|
await write(buf);
|
|
130
159
|
bytes += buf.length;
|
|
131
160
|
if (next < n)
|
package/dist/core/events.d.ts
CHANGED
|
@@ -42,7 +42,7 @@ export type TidepullEvent = {
|
|
|
42
42
|
url?: string;
|
|
43
43
|
};
|
|
44
44
|
export type Emit = (e: TidepullEvent) => void;
|
|
45
|
-
/**
|
|
45
|
+
/** Logging interface exposed to extractors. */
|
|
46
46
|
export interface Log {
|
|
47
47
|
debug(msg: string): void;
|
|
48
48
|
info(tag: string, msg: string): void;
|
package/dist/core/http.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { TidepullError, RedirectError, errMsg } from "./errors.js";
|
|
2
2
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3
3
|
const REDIRECT = new Set([301, 302, 303, 307, 308]);
|
|
4
|
-
/**
|
|
4
|
+
/** Sent to every host. All other custom headers are scoped (see HttpOptions.headerHosts). */
|
|
5
5
|
const OPEN_HEADERS = new Set(["user-agent", "accept", "accept-language", "accept-encoding", "range", "referer", "origin"]);
|
|
6
6
|
const hostMatches = (pattern, host) => pattern.startsWith("*.") ? host === pattern.slice(2) || host.endsWith(pattern.slice(1)) : host === pattern;
|
|
7
7
|
export class Http {
|
|
@@ -18,7 +18,7 @@ export class Http {
|
|
|
18
18
|
defaultSignal;
|
|
19
19
|
constructor(o = {}) {
|
|
20
20
|
this.headers = {
|
|
21
|
-
"User-Agent": o.userAgent ?? "Mozilla/5.0 (compatible; tidepull
|
|
21
|
+
"User-Agent": o.userAgent ?? "Mozilla/5.0 (compatible; tidepull)",
|
|
22
22
|
"Accept-Language": "en-US,en;q=0.9",
|
|
23
23
|
};
|
|
24
24
|
this.secret = {};
|
package/dist/core/pipeline.d.ts
CHANGED
|
@@ -3,8 +3,8 @@ export declare const DEFAULT_OUTPUT = "%(title)s [%(id)s].%(ext)s";
|
|
|
3
3
|
export interface DownloadOptions {
|
|
4
4
|
/** format selector, default "bv*+ba/b" */
|
|
5
5
|
format: string;
|
|
6
|
-
/** output template
|
|
7
|
-
output
|
|
6
|
+
/** output template. Default: "%(title)s [%(id)s].%(ext)s", or just the title when the id is identical (typical for direct files) */
|
|
7
|
+
output?: string;
|
|
8
8
|
/** base directory */
|
|
9
9
|
paths: string;
|
|
10
10
|
/** resume from .part files */
|
|
@@ -19,6 +19,8 @@ export interface DownloadOptions {
|
|
|
19
19
|
ffmpeg?: string;
|
|
20
20
|
/** extra request headers for the media downloads */
|
|
21
21
|
headers: Record<string, string>;
|
|
22
|
+
/** maximum average download speed in bytes per second (applies to each file) */
|
|
23
|
+
limitRate?: number;
|
|
22
24
|
}
|
|
23
25
|
export declare function extractInfo(rawUrl: string, ctx: Ctx): Promise<Info>;
|
|
24
26
|
/** Selects formats per opts.format, downloads them, merges/remuxes with ffmpeg if needed. Returns the final file path. */
|
package/dist/core/pipeline.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { mkdir, rename, rm, stat } from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { downloadDash, downloadHls, downloadHttp } from "./downloader.js";
|
|
3
|
+
import { downloadDash, downloadHls, downloadHttp, RateLimiter } from "./downloader.js";
|
|
4
4
|
import { TidepullError } from "./errors.js";
|
|
5
5
|
import { findFfmpeg, mergeStreams, remux } from "./ffmpeg.js";
|
|
6
6
|
import { Meter } from "./meter.js";
|
|
@@ -26,7 +26,7 @@ export async function extractInfo(rawUrl, ctx) {
|
|
|
26
26
|
throw new TidepullError(`Extractor "${ex.name}" returned no formats`);
|
|
27
27
|
return info;
|
|
28
28
|
}
|
|
29
|
-
/**
|
|
29
|
+
/** Drops undefined keys so events serialize cleanly. */
|
|
30
30
|
const compact = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
31
31
|
const scalars = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => ["string", "number", "boolean"].includes(typeof v)));
|
|
32
32
|
/** Selects formats per opts.format, downloads them, merges/remuxes with ffmpeg if needed. Returns the final file path. */
|
|
@@ -47,7 +47,9 @@ export async function downloadInfo(info, opts, ctx) {
|
|
|
47
47
|
resolution: chosen[0].height ? `${chosen[0].width ?? "?"}x${chosen[0].height}` : "audio only",
|
|
48
48
|
ext: predictedExt,
|
|
49
49
|
};
|
|
50
|
-
|
|
50
|
+
// Default name: just the title when it equals the id (direct files).
|
|
51
|
+
const template = opts.output ?? (String(info.title) === String(info.id) ? "%(title)s.%(ext)s" : DEFAULT_OUTPUT);
|
|
52
|
+
let target = path.resolve(opts.paths, renderTemplate(template, fields));
|
|
51
53
|
await mkdir(path.dirname(target), { recursive: true });
|
|
52
54
|
const exists = await stat(target).then(() => true, () => false);
|
|
53
55
|
if (exists && !opts.overwrite) {
|
|
@@ -71,7 +73,8 @@ export async function downloadInfo(info, opts, ctx) {
|
|
|
71
73
|
const eta = speed && p.total ? (p.total - p.downloaded) / speed : undefined;
|
|
72
74
|
ctx.emit(compact({ type: "progress", format_id: f.format_id, ...p, speed, eta }));
|
|
73
75
|
};
|
|
74
|
-
const
|
|
76
|
+
const limiter = opts.limitRate ? new RateLimiter(opts.limitRate) : undefined;
|
|
77
|
+
const common = { http: ctx.http, headers: { ...f.http_headers, ...opts.headers }, signal: ctx.signal, limiter, onProgress };
|
|
75
78
|
let ext = f.ext;
|
|
76
79
|
if (f.protocol === "hls")
|
|
77
80
|
({ ext } = await downloadHls(f.url, dest, { ...common, concurrency: opts.concurrency }));
|
|
@@ -87,7 +90,7 @@ export async function downloadInfo(info, opts, ctx) {
|
|
|
87
90
|
if (!merging) {
|
|
88
91
|
const ext = await fetchOne(chosen[0], target);
|
|
89
92
|
if (ext !== path.extname(target).slice(1)) {
|
|
90
|
-
const fixed = `${base}.${ext}`; //
|
|
93
|
+
const fixed = `${base}.${ext}`; // the real container can differ from the predicted one (e.g. fMP4 HLS)
|
|
91
94
|
await rename(target, fixed);
|
|
92
95
|
target = fixed;
|
|
93
96
|
}
|
package/dist/core/selector.d.ts
CHANGED
package/dist/core/template.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Output templates: "%(title)s [%(id)s].%(ext)s", "%(uploader|unknown)s", "%(title).50s". */
|
|
2
2
|
export declare function sanitize(s: string): string;
|
|
3
3
|
export declare function renderTemplate(tpl: string, fields: Record<string, unknown>): string;
|
package/dist/core/template.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Output templates: "%(title)s [%(id)s].%(ext)s", "%(uploader|unknown)s", "%(title).50s". */
|
|
2
2
|
export function sanitize(s) {
|
|
3
3
|
const cleaned = s
|
|
4
4
|
.replace(/[\\/:*?"<>|\x00-\x1f]/g, "_")
|
package/dist/core/types.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Emit, Log } from "./events.js";
|
|
2
2
|
import type { Http } from "./http.js";
|
|
3
3
|
export type Protocol = "https" | "hls" | "dash";
|
|
4
|
-
/** One downloadable stream.
|
|
4
|
+
/** One downloadable stream. */
|
|
5
5
|
export interface Format {
|
|
6
6
|
format_id: string;
|
|
7
7
|
url: string;
|
package/dist/dash/index.js
CHANGED
|
@@ -17,7 +17,7 @@ export const dashExtractor = {
|
|
|
17
17
|
export async function extractDash(url, ctx) {
|
|
18
18
|
const { text, finalUrl } = await ctx.http.text(url.href);
|
|
19
19
|
if (text.length > MAX_MPD_BYTES)
|
|
20
|
-
throw new TidepullError("Manifest is
|
|
20
|
+
throw new TidepullError("Manifest is too large");
|
|
21
21
|
const mpd = parseMpd(text, finalUrl);
|
|
22
22
|
if (mpd.dynamic)
|
|
23
23
|
throw new TidepullError("Live DASH streams are not supported yet");
|
|
@@ -36,7 +36,7 @@ export async function extractDash(url, ctx) {
|
|
|
36
36
|
const formats = [];
|
|
37
37
|
for (const r of mpd.reps) {
|
|
38
38
|
if (r.kind === "other")
|
|
39
|
-
continue; // subtitles
|
|
39
|
+
continue; // subtitles and other tracks are not supported
|
|
40
40
|
const { v, a } = splitCodecs(r.codecs);
|
|
41
41
|
const video = r.kind === "video";
|
|
42
42
|
const f = {
|
package/dist/dash/xml.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Minimal
|
|
1
|
+
/** Minimal XML parser: elements, attributes and text. DTDs and custom entities are not expanded; namespace prefixes are dropped. */
|
|
2
2
|
import { TidepullError } from "../core/errors.js";
|
|
3
3
|
const ENT = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
4
4
|
const decode = (s) => s.replace(/&(?:#x([0-9a-f]+)|#(\d+)|(\w+));/gi, (m, hex, dec, name) => {
|
|
@@ -92,7 +92,8 @@ export const genericExtractor = {
|
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
94
|
if (!formats.length)
|
|
95
|
-
throw new TidepullError(`
|
|
95
|
+
throw new TidepullError(`No downloadable media found on ${url.hostname}. This looks like a site that needs its own extractor plugin (see README, Plugins). ` +
|
|
96
|
+
"Built in: direct media files, HLS, DASH and pages that embed them.");
|
|
96
97
|
const id = (await sha(pageUrl)).slice(0, 10);
|
|
97
98
|
return { id, title: title || id, extractor: "generic", webpage_url: pageUrl, thumbnail, formats };
|
|
98
99
|
},
|
package/dist/main.d.ts
CHANGED
package/dist/main.js
CHANGED
|
@@ -2,13 +2,14 @@ import { parseArgs } from "node:util";
|
|
|
2
2
|
import { DEFAULT_FORMAT, selectFormats } from "./core/selector.js";
|
|
3
3
|
import { TidepullError, errMsg } from "./core/errors.js";
|
|
4
4
|
import { existsSync, readFileSync } from "node:fs";
|
|
5
|
+
import { Archive, configArgs, parseRate, readUrlList } from "./cliutil.js";
|
|
5
6
|
import { createTidepull } from "./tidepull.js";
|
|
6
7
|
import dash from "./dash/index.js";
|
|
7
8
|
import { defaultPluginDir, loadPlugins } from "./loader.js";
|
|
8
9
|
import { table, fmtBytes } from "./ui/format.js";
|
|
9
10
|
import { Logger, shouldUseColor } from "./ui/log.js";
|
|
10
11
|
import { humanRenderer, jsonRenderer } from "./ui/render.js";
|
|
11
|
-
/**
|
|
12
|
+
/** Package version, read from package.json. */
|
|
12
13
|
export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
13
14
|
const HELP = `tidepull ${VERSION}: a minimal media downloader
|
|
14
15
|
|
|
@@ -20,7 +21,8 @@ Selection:
|
|
|
20
21
|
-F, --list-formats List available formats and exit
|
|
21
22
|
|
|
22
23
|
Output:
|
|
23
|
-
-o, --output TEMPLATE Output template (default: "%(title)s [%(id)s].%(ext)s"
|
|
24
|
+
-o, --output TEMPLATE Output template (default: "%(title)s [%(id)s].%(ext)s",
|
|
25
|
+
or just the title when the id is the same)
|
|
24
26
|
-P, --paths DIR Download directory (default: .)
|
|
25
27
|
-w, --overwrite Overwrite existing files
|
|
26
28
|
--no-continue Do not resume partial downloads
|
|
@@ -39,7 +41,16 @@ Plugins:
|
|
|
39
41
|
--plugin PATH Load a plugin file or directory (repeatable). Plugins run with your privileges!
|
|
40
42
|
--no-plugins Skip auto-loading ~/.config/tidepull/plugins (or $TIDEPULL_PLUGIN_DIR)
|
|
41
43
|
|
|
44
|
+
Input:
|
|
45
|
+
-a, --batch-file FILE Read URLs from FILE, one per line ("-" = stdin, # starts a comment)
|
|
46
|
+
--download-archive FILE Skip items listed in FILE; record new ones after downloading
|
|
47
|
+
|
|
48
|
+
Config:
|
|
49
|
+
--config-location FILE Read options from FILE (default: ~/.config/tidepull/config)
|
|
50
|
+
--no-config Do not read a config file
|
|
51
|
+
|
|
42
52
|
Network:
|
|
53
|
+
--limit-rate RATE Maximum download speed per file, e.g. 500K or 1.5M
|
|
43
54
|
-N, --concurrent-fragments N HLS segments fetched in parallel (default: 4)
|
|
44
55
|
-R, --retries N Retries per request (default: 3)
|
|
45
56
|
--header "Name: value" Extra request header (repeatable). Secret-looking headers (Authorization,
|
|
@@ -84,7 +95,7 @@ export async function main(argv) {
|
|
|
84
95
|
let positionals;
|
|
85
96
|
function parse() {
|
|
86
97
|
return parseArgs({
|
|
87
|
-
args
|
|
98
|
+
args,
|
|
88
99
|
allowPositionals: true,
|
|
89
100
|
options: {
|
|
90
101
|
format: { type: "string", short: "f" },
|
|
@@ -112,12 +123,25 @@ export async function main(argv) {
|
|
|
112
123
|
"progress-json": { type: "boolean" },
|
|
113
124
|
plugin: { type: "string", multiple: true },
|
|
114
125
|
"no-plugins": { type: "boolean" },
|
|
126
|
+
"batch-file": { type: "string", short: "a" },
|
|
127
|
+
"download-archive": { type: "string" },
|
|
128
|
+
"limit-rate": { type: "string" },
|
|
129
|
+
"config-location": { type: "string" },
|
|
130
|
+
"no-config": { type: "boolean" },
|
|
115
131
|
"no-color": { type: "boolean" },
|
|
116
132
|
help: { type: "boolean", short: "h" },
|
|
117
133
|
version: { type: "boolean" },
|
|
118
134
|
},
|
|
119
135
|
});
|
|
120
136
|
}
|
|
137
|
+
let args = argv;
|
|
138
|
+
try {
|
|
139
|
+
args = [...configArgs(argv), ...argv];
|
|
140
|
+
}
|
|
141
|
+
catch (e) {
|
|
142
|
+
process.stderr.write(`ERROR: ${errMsg(e)}\n`);
|
|
143
|
+
return e instanceof TidepullError ? e.exitCode : 2;
|
|
144
|
+
}
|
|
121
145
|
try {
|
|
122
146
|
({ values, positionals } = parse());
|
|
123
147
|
}
|
|
@@ -134,7 +158,22 @@ export async function main(argv) {
|
|
|
134
158
|
verbose: values.verbose,
|
|
135
159
|
color: !values["no-color"] && shouldUseColor(),
|
|
136
160
|
});
|
|
137
|
-
|
|
161
|
+
const urls = [...positionals];
|
|
162
|
+
let limitRate;
|
|
163
|
+
let archive;
|
|
164
|
+
try {
|
|
165
|
+
if (values["batch-file"])
|
|
166
|
+
urls.push(...readUrlList(values["batch-file"]));
|
|
167
|
+
if (values["limit-rate"])
|
|
168
|
+
limitRate = parseRate(values["limit-rate"]);
|
|
169
|
+
if (values["download-archive"])
|
|
170
|
+
archive = new Archive(values["download-archive"]);
|
|
171
|
+
}
|
|
172
|
+
catch (e) {
|
|
173
|
+
log.error(errMsg(e));
|
|
174
|
+
return e instanceof TidepullError ? e.exitCode : 1;
|
|
175
|
+
}
|
|
176
|
+
if (!urls.length && !values["list-extractors"]) {
|
|
138
177
|
log.error("You must provide at least one URL. Try 'tidepull --help'.");
|
|
139
178
|
return 2;
|
|
140
179
|
}
|
|
@@ -183,6 +222,7 @@ export async function main(argv) {
|
|
|
183
222
|
mergeFormat: values["merge-output-format"],
|
|
184
223
|
remuxVideo: values["remux-video"],
|
|
185
224
|
headers,
|
|
225
|
+
limitRate,
|
|
186
226
|
};
|
|
187
227
|
for (const k of Object.keys(opts))
|
|
188
228
|
if (opts[k] === undefined)
|
|
@@ -193,7 +233,7 @@ export async function main(argv) {
|
|
|
193
233
|
process.once("SIGINT", onSigint);
|
|
194
234
|
let code = 0;
|
|
195
235
|
try {
|
|
196
|
-
for (const url of
|
|
236
|
+
for (const url of urls) {
|
|
197
237
|
try {
|
|
198
238
|
const info = await tp.extract(url, { signal: ctl.signal });
|
|
199
239
|
if (values["dump-json"])
|
|
@@ -212,8 +252,12 @@ export async function main(argv) {
|
|
|
212
252
|
else if (values.simulate) {
|
|
213
253
|
log.tag("info", `${info.title} (${info.formats.length} format(s))`);
|
|
214
254
|
}
|
|
255
|
+
else if (archive?.has(info)) {
|
|
256
|
+
log.tag("download", `${info.title}: already in the archive, skipping`);
|
|
257
|
+
}
|
|
215
258
|
else {
|
|
216
259
|
const file = await tp.download(info, { ...opts, signal: ctl.signal });
|
|
260
|
+
archive?.add(info);
|
|
217
261
|
if (values["print-path"])
|
|
218
262
|
process.stdout.write(file + "\n");
|
|
219
263
|
}
|
package/dist/tidepull.d.ts
CHANGED
|
@@ -38,7 +38,7 @@ export declare class Tidepull {
|
|
|
38
38
|
private ctx;
|
|
39
39
|
private guard;
|
|
40
40
|
extract(url: string, o?: CallOptions): Promise<Info>;
|
|
41
|
-
/**
|
|
41
|
+
/** Which format(s) the selector picks (two or more means merge), or undefined if none match. */
|
|
42
42
|
select(info: Info, selector?: string): Format[] | undefined;
|
|
43
43
|
/** Downloads the selected format(s). Resolves to the final file path. */
|
|
44
44
|
download(info: Info, o?: Partial<DownloadOptions> & CallOptions): Promise<string>;
|
package/dist/tidepull.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { downloadInfo, extractInfo
|
|
1
|
+
import { downloadInfo, extractInfo } from "./core/pipeline.js";
|
|
2
2
|
import { abortError } from "./core/errors.js";
|
|
3
3
|
import { makeLog } from "./core/events.js";
|
|
4
4
|
import { Http } from "./core/http.js";
|
|
@@ -73,7 +73,7 @@ export class Tidepull {
|
|
|
73
73
|
}
|
|
74
74
|
return this.guard(o.signal, () => extractInfo(url, this.ctx(o.signal)));
|
|
75
75
|
}
|
|
76
|
-
/**
|
|
76
|
+
/** Which format(s) the selector picks (two or more means merge), or undefined if none match. */
|
|
77
77
|
select(info, selector = DEFAULT_FORMAT) {
|
|
78
78
|
return selectFormats(selector, info.formats);
|
|
79
79
|
}
|
|
@@ -82,7 +82,6 @@ export class Tidepull {
|
|
|
82
82
|
const { signal, ...rest } = o;
|
|
83
83
|
const opts = {
|
|
84
84
|
format: DEFAULT_FORMAT,
|
|
85
|
-
output: DEFAULT_OUTPUT,
|
|
86
85
|
paths: ".",
|
|
87
86
|
resume: true,
|
|
88
87
|
overwrite: false,
|
package/dist/ui/render.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { TidepullEvent } from "../core/events.js";
|
|
2
2
|
import type { Logger } from "./log.js";
|
|
3
|
-
/**
|
|
3
|
+
/** Renders engine events as terminal output on stderr, redrawing one progress line on a TTY. */
|
|
4
4
|
export declare function humanRenderer(log: Logger, o: {
|
|
5
5
|
progress: boolean;
|
|
6
6
|
stream?: NodeJS.WriteStream;
|
|
7
7
|
}): (e: TidepullEvent) => void;
|
|
8
|
-
/**
|
|
8
|
+
/** Writes one JSON event per line to stdout (NDJSON). */
|
|
9
9
|
export declare const jsonRenderer: () => ((e: TidepullEvent) => void);
|
package/dist/ui/render.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { fmtBytes, fmtTime } from "./format.js";
|
|
2
|
-
/**
|
|
2
|
+
/** Renders engine events as terminal output on stderr, redrawing one progress line on a TTY. */
|
|
3
3
|
export function humanRenderer(log, o) {
|
|
4
4
|
const stream = o.stream ?? process.stderr;
|
|
5
5
|
const live = o.progress && !!stream.isTTY;
|
|
@@ -29,11 +29,22 @@ export function humanRenderer(log, o) {
|
|
|
29
29
|
case "progress": {
|
|
30
30
|
if (!live)
|
|
31
31
|
break;
|
|
32
|
+
const cols = stream.columns || 80;
|
|
32
33
|
const pct = e.total ? `${((e.downloaded / e.total) * 100).toFixed(1).padStart(5)}%` : "";
|
|
33
34
|
const size = e.total ? ` of ${e.estimated ? "~" : ""}${fmtBytes(e.total)}` : ` ${fmtBytes(e.downloaded)}`;
|
|
34
35
|
const rate = e.speed ? ` at ${fmtBytes(e.speed)}/s` : "";
|
|
35
36
|
const eta = e.eta !== undefined ? ` ETA ${fmtTime(e.eta)}` : "";
|
|
36
|
-
|
|
37
|
+
// Keep the line narrower than the terminal: a wrapped line cannot be redrawn in place.
|
|
38
|
+
let line = `[download] ${pct}${size}${rate}${eta}`;
|
|
39
|
+
if (line.length >= cols)
|
|
40
|
+
line = `[download] ${pct}${size}${rate}`;
|
|
41
|
+
if (line.length >= cols)
|
|
42
|
+
line = `${pct}${size}${rate}`.trim();
|
|
43
|
+
if (line.length >= cols)
|
|
44
|
+
line = `${pct}${size}`.trim();
|
|
45
|
+
if (line.length >= cols)
|
|
46
|
+
line = (pct || fmtBytes(e.downloaded)).trim();
|
|
47
|
+
stream.write(`\r\x1b[K${line.slice(0, Math.max(1, cols - 1))}`);
|
|
37
48
|
drawn = true;
|
|
38
49
|
break;
|
|
39
50
|
}
|
|
@@ -56,5 +67,5 @@ export function humanRenderer(log, o) {
|
|
|
56
67
|
}
|
|
57
68
|
};
|
|
58
69
|
}
|
|
59
|
-
/**
|
|
70
|
+
/** Writes one JSON event per line to stdout (NDJSON). */
|
|
60
71
|
export const jsonRenderer = () => (e) => void process.stdout.write(JSON.stringify(e) + "\n");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@boy-offi9-inc/tidepull",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0-rc.0",
|
|
4
4
|
"description": "A minimal, from-scratch media downloader library: extractor plugins, yt-dlp-style format selection, resumable downloads.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|