@boy-offi9-inc/tidepull 0.1.0-rc.1 → 0.2.0-rc.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/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
  |---|---|
@@ -42,6 +44,7 @@ await g.pull(url, { signal: ctl.signal }); // rejects with name === "Abor
42
44
  | `definePlugin`, `PLUGIN_API_VERSION` | write extractor plugins |
43
45
  | `@boy-offi9-inc/tidepull/dash` *(opt-in)* | DASH VOD: `createTidepull({ plugins: [dash] })` |
44
46
  | `@boy-offi9-inc/tidepull/loader` *(opt-in)* | `loadPlugins(paths)` / `loadPlugin(file)`: load plugins from disk |
47
+ | `@boy-offi9-inc/tidepull/cookies` *(opt-in)* | `parseCookies`, `loadCookieFile`, `cookieJar`: `createTidepull({ http: { cookies: cookieJar(cookies) } })` |
45
48
  | `selectFormats`, `renderTemplate`, `parseHlsMaster/Media` | the building blocks, usable standalone |
46
49
  | `Http`, `TidepullError` | redirect-safe, header-scoped HTTP client; error type |
47
50
  | types | `Info`, `Format`, `Extractor`, `TidepullEvent`, `DownloadOptions`, `TidepullPlugin`, ... |
@@ -72,11 +75,38 @@ tidepull -F URL # list formats
72
75
  tidepull -f "bv*[height<=720]+ba/b" URL # select + merge (needs ffmpeg)
73
76
  tidepull -o "%(title).60s [%(id)s].%(ext)s" -P ~/Videos URL
74
77
  tidepull -j URL | jq .formats # data on stdout, logs on stderr
78
+ tidepull -a urls.txt --download-archive done.txt # batch input; skip what you already downloaded
79
+ tidepull --limit-rate 1M URL # cap the speed (500K, 1.5M, ...)
80
+ tidepull --cookies cookies.txt URL # use your own logged-in session
75
81
  ```
82
+
83
+ **Cookies.** `--cookies FILE` reads a Netscape `cookies.txt` (the format browser extensions export). Each cookie is sent only to the host, path and scheme it was issued for. Keep the file private (`chmod 600`); you get a warning if other users can read it.
84
+
85
+ **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.
86
+
87
+ **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.
88
+
76
89
  From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node >= 22.18); `npm run build` emits JS + `.d.ts`.
77
90
 
78
- ## What works today
79
- | Area | Status |
91
+ ## Capabilities and limits
92
+
93
+ **What Tidepull does**
94
+ - Downloads direct media files, HLS (VOD, AES-128) and DASH (VOD) streams, and pages that embed them
95
+ - Resumes interrupted downloads, caps speed, retries with backoff and cancels cleanly
96
+ - Merges separate video and audio, or remuxes, with ffmpeg
97
+ - Selects formats (`bv*[height<=720]+ba/b`) and names files from templates
98
+ - Uses your own cookies (`--cookies`) and headers, sending them only to the hosts they belong to
99
+ - Works as a CLI or a typed library with JSON events; support for a specific site is added through plugins
100
+
101
+ **What it does not do**
102
+ - No site-specific extractors are built in. Platforms such as YouTube hide their media behind scripts and tokens and need a plugin
103
+ - No DRM: protected streams (Widevine, PlayReady, FairPlay, encrypted DASH) are not supported and will not be
104
+ - No circumvention: it cannot get past logins, paywalls or geo-blocks. With `--cookies` it only fetches what your own session can already see
105
+ - Not implemented yet: live streams, multi-period DASH (first period only), SAMPLE-AES, byte-range HLS/DASH, subtitles, playlists, a proxy option
106
+ - Cookies are read-only: `Set-Cookie` responses are not stored
107
+
108
+ ### Details
109
+ | Area | Behavior |
80
110
  |---|---|
81
111
  | Direct files | resumable (`.part` + `Range`), retries with backoff |
82
112
  | HLS VOD | master + media playlists, parallel segments written in order, AES-128 (explicit/default IV), fMP4 init maps, separate audio renditions |
@@ -84,9 +114,9 @@ From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node
84
114
  | Generic page extractor | `og:video`, `<video>/<source>`, bare media URLs in HTML/JSON |
85
115
  | Format selector | `b bv bv* ba ba* w wv wa`, `+` merge, `/` fallback, `()` groups, `[height<=720]` `[filesize<?50M]` `[ext=mp4]` |
86
116
  | Output templates | `%(title)s`, `%(x\|default)s`, `%(title).50s`, sanitized |
117
+ | Cookies | Netscape `cookies.txt`; matched by domain, path, `Secure` and expiry; re-evaluated on every redirect hop |
118
+ | CLI conveniences | `-a` batch input, `--download-archive`, `--limit-rate`, `--config-location` |
87
119
  | Merge / remux | ffmpeg |
88
- | Site-specific extractors | none built in. Platforms such as YouTube hide their media behind scripts and tokens and need a plugin (see Plugins) |
89
- | Not yet | live HLS/DASH, multi-period DASH, SAMPLE-AES, byte-range HLS/DASH, playlists, subtitles, cookies |
90
120
 
91
121
  ## Footprint (enforced in CI)
92
122
  The core does only what every user needs: extract → select → download, events, cancellation. Everything else is a plugin or an opt-in subpath.
@@ -101,8 +131,9 @@ The core does only what every user needs: extract → select → download, event
101
131
 
102
132
  ## Security model
103
133
  - **No shell, ever.** ffmpeg is spawned with argv arrays. There is deliberately no `--exec` and no `--netrc-cmd`-style hook; the command-injection CVEs in this space came from exactly those features.
104
- - **Redirect-safe HTTP.** Redirects are followed manually: on a cross-origin hop everything except `User-Agent/Accept*/Range` is dropped (Authorization, Cookie, custom tokens), non-http(s) targets are refused, loops are capped.
134
+ - **Redirect-safe HTTP.** Redirects are followed manually and headers are recomputed on every hop: secrets and per-request headers stay with their own host, non-http(s) targets are refused, loops are capped.
105
135
  - **Origin-scoped secrets.** Custom headers like `Authorization`, `Cookie` or API tokens (`--header` / `http.headers`) are sent only to the origins you pass to `extract()`/`pull()`, plus any `--header-host` / `http.headerHosts` patterns (`cdn.example.com`, `*.example.com`). `Referer`, `Origin`, `Accept*`, `User-Agent` and `Range` are never treated as secret. Using one `Tidepull` instance for several sites trusts all of them, so use one instance per credential. The low-level `Http` class (without `headerHosts`) sends headers to each request's start origin only.
136
+ - **Per-host cookies.** `--cookies` sends each cookie only to the host, path and scheme it was issued for (`Secure` cookies never go over http). A cookie with a single-label domain such as `.com` is treated as host-only. Cookie values are never logged and never appear in `-j` output.
106
137
  - Output filenames are built from sanitized fields only. Only `http(s)` URLs are accepted.
107
138
 
108
139
  ## Legal
@@ -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
+ }
@@ -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
+ }
@@ -0,0 +1,21 @@
1
+ export interface Cookie {
2
+ domain: string;
3
+ /** also valid for subdomains of `domain` */
4
+ subdomains: boolean;
5
+ path: string;
6
+ secure: boolean;
7
+ /** seconds since epoch, 0 for a session cookie */
8
+ expires: number;
9
+ name: string;
10
+ value: string;
11
+ }
12
+ export declare function parseCookies(text: string): Cookie[];
13
+ /** The Cookie header value for `url`, or undefined when no cookie applies. */
14
+ export declare function cookieHeader(cookies: readonly Cookie[], url: URL, now?: number): string | undefined;
15
+ /** Plug into the HTTP client: `createTidepull({ http: { cookies: cookieJar(cookies) } })`. */
16
+ export declare const cookieJar: (cookies: readonly Cookie[]) => (url: URL) => string | undefined;
17
+ /** Reads a cookies.txt file. The warning (if any) says the file is readable by other users. */
18
+ export declare function loadCookieFile(file: string): {
19
+ cookies: Cookie[];
20
+ warning?: string;
21
+ };
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Netscape cookies.txt support (opt-in: "@boy-offi9-inc/tidepull/cookies").
3
+ * Cookies are sent only to the hosts, paths and schemes they were issued for, and are re-evaluated on every redirect hop.
4
+ * Read-only: Set-Cookie responses are not stored. No public-suffix list: only a single-label domain guard.
5
+ */
6
+ import { readFileSync, statSync } from "node:fs";
7
+ import { TidepullError, errMsg } from "./core/errors.js";
8
+ export function parseCookies(text) {
9
+ const out = [];
10
+ for (const raw of text.split("\n")) {
11
+ let line = raw.replace(/\r$/, "");
12
+ if (!line.trim())
13
+ continue;
14
+ if (line.startsWith("#HttpOnly_"))
15
+ line = line.slice("#HttpOnly_".length);
16
+ else if (line.startsWith("#"))
17
+ continue;
18
+ const f = line.split("\t");
19
+ if (f.length < 6)
20
+ continue;
21
+ const [domain, flag, path, secure, expires, name, ...rest] = f;
22
+ const bare = domain.replace(/^\./, "").toLowerCase();
23
+ if (!bare || !name)
24
+ continue;
25
+ // A domain without a dot ("com") must not match every site under it.
26
+ const subdomains = (flag.toUpperCase() === "TRUE" || domain.startsWith(".")) && bare.includes(".");
27
+ out.push({ domain: bare, subdomains, path: path || "/", secure: secure.toUpperCase() === "TRUE", expires: Number(expires) || 0, name, value: rest.join("\t") });
28
+ }
29
+ return out;
30
+ }
31
+ const pathMatch = (reqPath, cookiePath) => reqPath === cookiePath || (reqPath.startsWith(cookiePath) && (cookiePath.endsWith("/") || reqPath[cookiePath.length] === "/"));
32
+ /** The Cookie header value for `url`, or undefined when no cookie applies. */
33
+ export function cookieHeader(cookies, url, now = Date.now() / 1000) {
34
+ const host = url.hostname.toLowerCase();
35
+ const isIp = /^[\d.]+$/.test(host) || host.includes(":");
36
+ const hits = cookies.filter((c) => (host === c.domain || (c.subdomains && !isIp && host.endsWith("." + c.domain))) &&
37
+ pathMatch(url.pathname || "/", c.path) &&
38
+ (!c.secure || url.protocol === "https:") &&
39
+ (c.expires === 0 || c.expires > now));
40
+ if (!hits.length)
41
+ return undefined;
42
+ return hits.sort((a, b) => b.path.length - a.path.length).map((c) => `${c.name}=${c.value}`).join("; ");
43
+ }
44
+ /** Plug into the HTTP client: `createTidepull({ http: { cookies: cookieJar(cookies) } })`. */
45
+ export const cookieJar = (cookies) => (url) => cookieHeader(cookies, url);
46
+ /** Reads a cookies.txt file. The warning (if any) says the file is readable by other users. */
47
+ export function loadCookieFile(file) {
48
+ let text;
49
+ try {
50
+ text = readFileSync(file, "utf8");
51
+ }
52
+ catch (e) {
53
+ throw new TidepullError(`Cannot read cookie file ${file}: ${errMsg(e)}`, 2);
54
+ }
55
+ const cookies = parseCookies(text);
56
+ if (!cookies.length)
57
+ throw new TidepullError(`No cookies found in ${file} (expected the Netscape cookies.txt format)`, 2);
58
+ let warning;
59
+ try {
60
+ if (process.platform !== "win32" && (statSync(file).mode & 0o077) !== 0)
61
+ warning = `${file} is readable by other users; run: chmod 600 ${file}`;
62
+ }
63
+ catch {
64
+ /* permissions are advisory */
65
+ }
66
+ return { cookies, warning };
67
+ }
@@ -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. */
@@ -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";
@@ -52,7 +68,19 @@ export async function downloadHttp(url, dest, o) {
52
68
  cb(null, chunk);
53
69
  },
54
70
  });
55
- await pipeline(Readable.fromWeb(res.body), counter, createWriteStream(part, { flags: append ? "a" : "w" }), { signal: o.signal });
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
  }
@@ -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)
@@ -12,6 +12,8 @@ export interface HttpOptions {
12
12
  * Referer, Origin, User-Agent, Accept-* and Range are never considered secret and are always sent.
13
13
  */
14
14
  headerHosts?: string[];
15
+ /** Returns the Cookie header value for a URL (see "@boy-offi9-inc/tidepull/cookies"). Called on every request and redirect hop. */
16
+ cookies?: (url: URL) => string | undefined;
15
17
  }
16
18
  export interface RequestInitLite {
17
19
  method?: string;
@@ -25,6 +27,7 @@ export declare class Http {
25
27
  private secret;
26
28
  private scopedMode;
27
29
  private hostPatterns;
30
+ private cookies?;
28
31
  private trusted;
29
32
  retries: number;
30
33
  timeoutMs: number;
package/dist/core/http.js CHANGED
@@ -11,6 +11,7 @@ export class Http {
11
11
  secret;
12
12
  scopedMode;
13
13
  hostPatterns;
14
+ cookies;
14
15
  trusted = new Set();
15
16
  retries;
16
17
  timeoutMs;
@@ -18,7 +19,7 @@ export class Http {
18
19
  defaultSignal;
19
20
  constructor(o = {}) {
20
21
  this.headers = {
21
- "User-Agent": o.userAgent ?? "Mozilla/5.0 (compatible; tidepull/0.1)",
22
+ "User-Agent": o.userAgent ?? "Mozilla/5.0 (compatible; tidepull)",
22
23
  "Accept-Language": "en-US,en;q=0.9",
23
24
  };
24
25
  this.secret = {};
@@ -30,6 +31,7 @@ export class Http {
30
31
  }
31
32
  this.scopedMode = o.headerHosts !== undefined;
32
33
  this.hostPatterns = (o.headerHosts ?? []).map((h) => h.toLowerCase());
34
+ this.cookies = o.cookies;
33
35
  this.retries = o.retries ?? 3;
34
36
  this.timeoutMs = o.timeoutMs ?? 30_000;
35
37
  this.maxRedirects = o.maxRedirects ?? 10;
@@ -82,6 +84,13 @@ export class Http {
82
84
  // per-request headers (Range, extractor-supplied Referer/Cookie...) only travel with the start origin; Range goes everywhere
83
85
  const own = Object.fromEntries(Object.entries(init.headers ?? {}).filter(([k]) => cur.origin === start.origin || k.toLowerCase() === "range"));
84
86
  const headers = { ...this.headersFor(cur, start), ...own };
87
+ const cookie = this.cookies?.(cur);
88
+ if (cookie) {
89
+ for (const k of Object.keys(headers))
90
+ if (k.toLowerCase() === "cookie")
91
+ delete headers[k];
92
+ headers.Cookie = cookie;
93
+ }
85
94
  const ctl = new AbortController();
86
95
  const timer = setTimeout(() => ctl.abort(), this.timeoutMs);
87
96
  const signal = init.signal ? AbortSignal.any([ctl.signal, init.signal]) : ctl.signal;
@@ -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. */
@@ -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";
@@ -73,7 +73,8 @@ export async function downloadInfo(info, opts, ctx) {
73
73
  const eta = speed && p.total ? (p.total - p.downloaded) / speed : undefined;
74
74
  ctx.emit(compact({ type: "progress", format_id: f.format_id, ...p, speed, eta }));
75
75
  };
76
- const common = { http: ctx.http, headers: { ...f.http_headers, ...opts.headers }, signal: ctx.signal, onProgress };
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 };
77
78
  let ext = f.ext;
78
79
  if (f.protocol === "hls")
79
80
  ({ ext } = await downloadHls(f.url, dest, { ...common, concurrency: opts.concurrency }));
package/dist/main.js CHANGED
@@ -2,6 +2,8 @@ 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";
6
+ import { cookieJar, loadCookieFile } from "./cookies.js";
5
7
  import { createTidepull } from "./tidepull.js";
6
8
  import dash from "./dash/index.js";
7
9
  import { defaultPluginDir, loadPlugins } from "./loader.js";
@@ -40,7 +42,17 @@ Plugins:
40
42
  --plugin PATH Load a plugin file or directory (repeatable). Plugins run with your privileges!
41
43
  --no-plugins Skip auto-loading ~/.config/tidepull/plugins (or $TIDEPULL_PLUGIN_DIR)
42
44
 
45
+ Input:
46
+ -a, --batch-file FILE Read URLs from FILE, one per line ("-" = stdin, # starts a comment)
47
+ --download-archive FILE Skip items listed in FILE; record new ones after downloading
48
+
49
+ Config:
50
+ --config-location FILE Read options from FILE (default: ~/.config/tidepull/config)
51
+ --no-config Do not read a config file
52
+
43
53
  Network:
54
+ --limit-rate RATE Maximum download speed per file, e.g. 500K or 1.5M
55
+ --cookies FILE Send cookies from a Netscape cookies.txt file, only to the hosts they belong to
44
56
  -N, --concurrent-fragments N HLS segments fetched in parallel (default: 4)
45
57
  -R, --retries N Retries per request (default: 3)
46
58
  --header "Name: value" Extra request header (repeatable). Secret-looking headers (Authorization,
@@ -85,7 +97,7 @@ export async function main(argv) {
85
97
  let positionals;
86
98
  function parse() {
87
99
  return parseArgs({
88
- args: argv,
100
+ args,
89
101
  allowPositionals: true,
90
102
  options: {
91
103
  format: { type: "string", short: "f" },
@@ -113,12 +125,26 @@ export async function main(argv) {
113
125
  "progress-json": { type: "boolean" },
114
126
  plugin: { type: "string", multiple: true },
115
127
  "no-plugins": { type: "boolean" },
128
+ "batch-file": { type: "string", short: "a" },
129
+ "download-archive": { type: "string" },
130
+ "limit-rate": { type: "string" },
131
+ cookies: { type: "string" },
132
+ "config-location": { type: "string" },
133
+ "no-config": { type: "boolean" },
116
134
  "no-color": { type: "boolean" },
117
135
  help: { type: "boolean", short: "h" },
118
136
  version: { type: "boolean" },
119
137
  },
120
138
  });
121
139
  }
140
+ let args = argv;
141
+ try {
142
+ args = [...configArgs(argv), ...argv];
143
+ }
144
+ catch (e) {
145
+ process.stderr.write(`ERROR: ${errMsg(e)}\n`);
146
+ return e instanceof TidepullError ? e.exitCode : 2;
147
+ }
122
148
  try {
123
149
  ({ values, positionals } = parse());
124
150
  }
@@ -135,7 +161,29 @@ export async function main(argv) {
135
161
  verbose: values.verbose,
136
162
  color: !values["no-color"] && shouldUseColor(),
137
163
  });
138
- if (!positionals.length && !values["list-extractors"]) {
164
+ const urls = [...positionals];
165
+ let limitRate;
166
+ let archive;
167
+ let cookies;
168
+ try {
169
+ if (values["batch-file"])
170
+ urls.push(...readUrlList(values["batch-file"]));
171
+ if (values["limit-rate"])
172
+ limitRate = parseRate(values["limit-rate"]);
173
+ if (values["download-archive"])
174
+ archive = new Archive(values["download-archive"]);
175
+ if (values.cookies) {
176
+ const loaded = loadCookieFile(values.cookies);
177
+ if (loaded.warning)
178
+ log.warn(loaded.warning);
179
+ cookies = cookieJar(loaded.cookies);
180
+ }
181
+ }
182
+ catch (e) {
183
+ log.error(errMsg(e));
184
+ return e instanceof TidepullError ? e.exitCode : 1;
185
+ }
186
+ if (!urls.length && !values["list-extractors"]) {
139
187
  log.error("You must provide at least one URL. Try 'tidepull --help'.");
140
188
  return 2;
141
189
  }
@@ -163,7 +211,7 @@ export async function main(argv) {
163
211
  return e instanceof TidepullError ? e.exitCode : 1;
164
212
  }
165
213
  const tp = createTidepull({
166
- http: { headers, headerHosts: values["header-host"] ?? [], userAgent: values["user-agent"], retries: num(values.retries, 3) },
214
+ http: { headers, headerHosts: values["header-host"] ?? [], userAgent: values["user-agent"], retries: num(values.retries, 3), cookies },
167
215
  plugins: [...plugins, dash],
168
216
  ffmpeg: values["ffmpeg-location"],
169
217
  });
@@ -184,6 +232,7 @@ export async function main(argv) {
184
232
  mergeFormat: values["merge-output-format"],
185
233
  remuxVideo: values["remux-video"],
186
234
  headers,
235
+ limitRate,
187
236
  };
188
237
  for (const k of Object.keys(opts))
189
238
  if (opts[k] === undefined)
@@ -194,7 +243,7 @@ export async function main(argv) {
194
243
  process.once("SIGINT", onSigint);
195
244
  let code = 0;
196
245
  try {
197
- for (const url of positionals) {
246
+ for (const url of urls) {
198
247
  try {
199
248
  const info = await tp.extract(url, { signal: ctl.signal });
200
249
  if (values["dump-json"])
@@ -213,8 +262,12 @@ export async function main(argv) {
213
262
  else if (values.simulate) {
214
263
  log.tag("info", `${info.title} (${info.formats.length} format(s))`);
215
264
  }
265
+ else if (archive?.has(info)) {
266
+ log.tag("download", `${info.title}: already in the archive, skipping`);
267
+ }
216
268
  else {
217
269
  const file = await tp.download(info, { ...opts, signal: ctl.signal });
270
+ archive?.add(info);
218
271
  if (values["print-path"])
219
272
  process.stdout.write(file + "\n");
220
273
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boy-offi9-inc/tidepull",
3
- "version": "0.1.0-rc.1",
3
+ "version": "0.2.0-rc.1",
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",
@@ -45,6 +45,10 @@
45
45
  "./loader": {
46
46
  "types": "./dist/loader.d.ts",
47
47
  "import": "./dist/loader.js"
48
+ },
49
+ "./cookies": {
50
+ "types": "./dist/cookies.d.ts",
51
+ "import": "./dist/cookies.js"
48
52
  }
49
53
  },
50
54
  "files": [