// A LIBRARY POST'S MEDIA, FROM X'S MEDIA CDN (lane x-trending-2) — the media // half of `capture-posts` for an X trending library (controller/ // capturePosts.ts hands it to the X fetcher as `downloadMedia`). // // An ordinary X capture runs one LOGGED-IN gallery-dl per post. A library // already holds the answer that listed the post — the saved capture of the // read that showed it — and that answer names where the CDN serves each // file (xTrendingParse.ts mediaSourcesOf). So the files are asked of the CDN // directly: no login, no page, no request to X's API. // // IT RIDES THE CAPTURE JOB, on X's queue (`platform:twitter`): one job at a // time with every read and capture, X's gap between jobs, the X alert and the // fresh-jar rule at the job's start. Inside the job: // - X's cooldown is asked before every post: a 429 anywhere on X (a read's, // a capture's) holds the media too; // - one file after another, 1 to 2 s apart (the gap an article's inline // images use), never two at once; // - a job fetches at most `maxFiles` files or `maxBytes` (40, 200 MB): the // rest is OWED — its posts' media is not settled, and the next capture of // them asks again; // - a file over `maxVideoBytes` is not kept and is owed (a watch: 100 MB by // default; a kept post has no cap); // - a 429 from the CDN STOPS THE JOB and records the 15-minute cooldown; a // 403, a 404 or any other answer marks that file and moves on. NOTHING IS // RETRIED; // - THREE REFUSALS IN A ROW (a 403, or no answer at all) and the job asks // the CDN for nothing more: a CDN that has turned this client away is not // asked forty times. The rest is owed to a later capture. // // A FILE THE LIBRARY ALREADY HOLDS IS NOT FETCHED: one whose address the media // index knows is linked from the store (lib/xTrending/mediaStore.ts), and one // already in the post's directory is kept. Every file fetched is taken into // the store, so the same bytes under two posts are one file. // // THE LOGGED-IN FALLBACK (`fallback: "login"`, a post marked keep) runs the // fetcher's own gallery-dl download for a post the CDN could not serve whole — // no address in the capture, or a file refused — and takes what it lands into // the store too. A watch never falls back. // // Only X's two media hosts are ever asked (xTrendingParse.ts xMediaCdnUrl), a // redirect is refused, and no cookie or header of the session is sent. // ARCHILYZER_NO_NETWORK=1 (lib/noNetwork.mjs): imported for its effect. import "../lib/noNetwork.mjs"; import { createWriteStream } from "node:fs"; import { mkdir, rename, rm, stat } from "node:fs/promises"; import path from "node:path"; import { once } from "node:events"; import { adoptXTrendingMedia, noteXTrendingOversize, linkXTrendingMedia, readXTrendingMediaIndex, xTrendingBlobByUrl, } from "../lib/xTrending/mediaStore"; import { xRateLimitHoldSentence } from "../lib/xTrending/config"; import type { PostMediaDownload, PostMediaDownloadArgs } from "./fetchers"; import { listCapturedMediaFiles } from "./postCapture"; import { xMediaCdnUrl, type TrendingMediaSource } from "./xTrendingParse"; export const LIBRARY_MEDIA_MAX_FILES = 40; export const LIBRARY_MEDIA_MAX_BYTES = 200 * 1024 * 1024; // No file is ever kept past this, cap or no cap. export const LIBRARY_MEDIA_HARD_MAX_BYTES = 2 * 1024 * 1024 * 1024; export const LIBRARY_MEDIA_HEADERS_TIMEOUT_MS = 60_000; export const LIBRARY_MEDIA_FILE_TIMEOUT_MS = 10 * 60_000; // The gap between two files: 1 to 2 s. export function libraryMediaPauseMs(rand: () => number = Math.random): number { return 1000 + Math.floor(rand() * 1000); } // The slice of `fetch` this needs (the global one in production; a stand-in // that opens no socket in tests and under the e2e test server). export type MediaFetch = ( url: string, init: { signal: AbortSignal; redirect: "error"; credentials: "omit" }, ) => Promise<{ status: number; headers: { get: (name: string) => string | null }; // `cancel`, when the body has one (a web stream does), ends a download // nobody is going to read. body: (AsyncIterable & { cancel?: () => Promise | void }) | null; }>; export type LibraryMediaDeps = { fetch: MediaFetch; pauseMs: () => number; pause: (ms: number, signal: AbortSignal) => Promise; // X's cooldown: how long is left of it (ms), and a rate limit recorded // (answers when it ends, ms since the epoch). cooldownMs: () => Promise; noteRateLimit: () => Promise; now?: () => number; // For tests: the wait for an answer's headers, and for a whole file. timeouts?: { headersMs?: number; fileMs?: number }; }; export type LibraryMediaOptions = { // The library's channel directory (channels/). channelRoot: string; // Post id → where the CDN serves its media, from the saved captures. sources: ReadonlyMap>; // Post id → how many media files the post carries (the read's count): a post // whose capture names fewer addresses than that is owed the rest. expected?: ReadonlyMap; // A file over this is owed, not kept. null: no cap (a kept post). maxVideoBytes: number | null; fallback: "login" | "none"; // IS THIS POST STILL MARKED KEEP? — ONE predicate, asked once per post, // before any of its media (review 1 M4, review 2 N3). A capture of kept // posts is queued when they are kept and may start minutes later; a post // dropped meanwhile gets NEITHER of the things keeping buys: its media is // fetched under `maxVideoBytes` like any post's (no uncapped download), and // no logged-in download is run for it. A post still kept has no per-file // cap and the fallback `fallback` says. Absent: every post is fetched as // `maxVideoBytes` and `fallback` say. isKept?: (id: string) => Promise; maxFiles?: number; maxBytes?: number; deps: LibraryMediaDeps; }; const mb = (bytes: number) => `${Math.max(1, Math.round(bytes / (1024 * 1024)))} MB`; const firstLine = (err: unknown) => ((err as Error)?.message ?? String(err)).split("\n")[0]; const overCapWhy = (bytes: number, cap: number) => `it is ${bytes > cap + 1 ? `${mb(bytes)}, ` : ""}over the ${mb(cap)} cap: owed until the post is kept`; // `refused`: the CDN said 403, or did not answer at all — what a CDN that has // turned this client away looks like. type Fetched = { ok: true; bytes: number } | { ok: false; why: string; oversize?: number; rateLimited?: boolean; refused?: boolean }; // A job stops asking the CDN after this many refusals in a row (review 1 S9). export const LIBRARY_MEDIA_MAX_REFUSALS = 3; // One file, streamed to `.part` and renamed when whole. async function fetchOne(o: { source: TrendingMediaSource; file: string; cap: number; capIsHard: boolean; fetch: MediaFetch; signal: AbortSignal; headersMs: number; fileMs: number; }): Promise { const part = `${o.file}.part`; const over = (bytes: number): Fetched => o.capIsHard ? { ok: false, why: `it is larger than ${mb(o.cap)}, more than is ever kept` } : { ok: false, oversize: bytes > 0 ? bytes : o.cap + 1, why: overCapWhy(bytes, o.cap) }; const deadline = AbortSignal.any([o.signal, AbortSignal.timeout(o.fileMs)]); // THE WAIT FOR THE HEADERS IS ITS OWN TIMER, CLEARED WHEN THEY ARRIVE // (review 1 S3): the signal handed to fetch also aborts the body, so a timer // left running there would cut every download at the headers' limit and the // file's own limit would never be reached. const headers = new AbortController(); const headersTimer = setTimeout(() => headers.abort(new Error("no answer in time")), o.headersMs); let res: Awaited>; try { res = await o.fetch(o.source.fetchUrl, { signal: AbortSignal.any([deadline, headers.signal]), redirect: "error", credentials: "omit", }); } catch (err) { return { ok: false, refused: !o.signal.aborted, why: `the CDN did not answer (${firstLine(err)})` }; } finally { clearTimeout(headersTimer); } // A body nobody will read is ended, not left to download. const drop = async () => { try { await res.body?.cancel?.(); } catch { /* already ended */ } }; if (res.status === 429) { await drop(); return { ok: false, rateLimited: true, why: "the CDN answered 429 (rate limit)" }; } if (res.status < 200 || res.status >= 300 || !res.body) { await drop(); return { ok: false, refused: res.status === 403, why: `the CDN answered ${res.status}` }; } const declared = Number(res.headers.get("content-length") ?? ""); if (Number.isFinite(declared) && declared > o.cap) { await drop(); return over(declared); } await rm(part, { force: true }); const out = createWriteStream(part); let bytes = 0; let tooBig = false; try { for await (const chunk of res.body) { if (deadline.aborted) throw new Error(o.signal.aborted ? "cancelled" : "the file took too long"); bytes += chunk.byteLength; if (bytes > o.cap) { tooBig = true; break; } if (!out.write(chunk)) await once(out, "drain"); } } catch (err) { out.destroy(); await rm(part, { force: true }); return { ok: false, refused: !o.signal.aborted, why: `the download broke off (${firstLine(err)})` }; } await new Promise((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve()))); if (tooBig) { await drop(); await rm(part, { force: true }); return over(0); } if (bytes === 0) { await rm(part, { force: true }); return { ok: false, why: "the CDN sent an empty file" }; } await rename(part, o.file); return { ok: true, bytes }; } // The media half of a library's capture: `(args, login) => result`, one call // per post, sharing one job's budget. export function createLibraryMediaDownloader( o: LibraryMediaOptions, ): (args: PostMediaDownloadArgs, login: (args: PostMediaDownloadArgs) => Promise) => Promise { const { deps } = o; const now = deps.now ?? Date.now; const maxFiles = o.maxFiles ?? LIBRARY_MEDIA_MAX_FILES; const maxBytes = o.maxBytes ?? LIBRARY_MEDIA_MAX_BYTES; const capFor = (maxVideoBytes: number | null) => ({ cap: Math.min(maxVideoBytes ?? LIBRARY_MEDIA_HARD_MAX_BYTES, LIBRARY_MEDIA_HARD_MAX_BYTES), capIsHard: maxVideoBytes === null || maxVideoBytes >= LIBRARY_MEDIA_HARD_MAX_BYTES, }); const budget = { files: 0, bytes: 0 }; let saidSpent = false; // Refusals in a row, across the job's posts; and whether the job has // stopped asking the CDN for it. let refusals = 0; let halted = false; const headersMs = deps.timeouts?.headersMs ?? LIBRARY_MEDIA_HEADERS_TIMEOUT_MS; const fileMs = deps.timeouts?.fileMs ?? LIBRARY_MEDIA_FILE_TIMEOUT_MS; return async (args, login) => { const { id, dir, signal } = args; const log = args.onLog ?? (() => {}); // X cooling down after a rate limit holds the media too. const cooling = await deps.cooldownMs().catch(() => 0); if (cooling > 0) { const why = xRateLimitHoldSentence("media fetch", cooling, now()); return { ok: false, owed: "next", error: why, stop: why }; } // Still kept? Asked now, once, before anything of this post is fetched. const kept = o.isKept ? await o.isKept(id).catch(() => false) : null; if (kept === false) log(`${id}: no longer marked keep: its media is fetched as any post's (the per-file cap applies, no logged-in download).`); const { cap, capIsHard } = capFor(kept === true ? null : o.maxVideoBytes); const mayLogin = o.fallback === "login" && kept !== false; const sources = o.sources.get(id) ?? []; const expected = o.expected?.get(id) ?? sources.length; const files: { name: string; url?: string }[] = []; const problems: string[] = []; // Owed to a later capture (the budget, the cooldown), or until the post // is kept (a file over the cap, a file the capture names no address for). let owedNext = false; let owedKept = false; let failed = false; let stop: string | undefined; await mkdir(dir, { recursive: true }); // Taken into the store; a file the store cannot share stays where it is. const adopt = async (name: string, url?: string) => { const got = await adoptXTrendingMedia(o.channelRoot, { postId: id, name, ...(url ? { url } : {}), now }); if (got.deduped) log(`${id}: ${name} is a file the library already holds (kept once).`); }; for (const [i, source] of sources.entries()) { if (signal.aborted) break; const name = `${id}_${i + 1}.${source.ext}`; const file = path.join(dir, name); if (!xMediaCdnUrl(source.fetchUrl)) { problems.push(`${name}: not an address on X's media CDN`); failed = true; continue; } if ((await stat(file).catch(() => null))?.isFile()) { await adopt(name, source.url); files.push({ name, url: source.url }); continue; } // An address the library has seen: linked from the store, nothing asked. const index = await readXTrendingMediaIndex(o.channelRoot); const known = xTrendingBlobByUrl(index, source.url); if (known && (await linkXTrendingMedia(o.channelRoot, { postId: id, name, sha256: known, url: source.url }))) { log(`${id}: ${name} is already in the library (same address): linked, not fetched.`); files.push({ name, url: source.url }); continue; } // Found over the cap before: not asked for again while the cap stands. const big = index.oversize[source.url]; if (!capIsHard && big && big.bytes > cap) { owedKept = true; problems.push(`${name}: ${overCapWhy(big.bytes, cap)}`); continue; } // The CDN has refused this job three times running: it is not asked again. if (halted) { owedNext = true; problems.push(`${name}: owed (the CDN refused ${LIBRARY_MEDIA_MAX_REFUSALS} files in a row; this job asks it no more)`); continue; } if (budget.files >= maxFiles || budget.bytes >= maxBytes) { owedNext = true; problems.push(`${name}: owed (this job's media budget of ${maxFiles} files / ${mb(maxBytes)} is used)`); if (!saidSpent) { saidSpent = true; log(`This job's media budget (${maxFiles} files / ${mb(maxBytes)}) is used: the rest is owed to a later capture.`); } continue; } if (budget.files > 0) await deps.pause(deps.pauseMs(), signal); if (signal.aborted) break; const got = await fetchOne({ source, file, cap, capIsHard, fetch: deps.fetch, signal, headersMs, fileMs }); budget.files++; refusals = !got.ok && got.refused ? refusals + 1 : 0; if (refusals >= LIBRARY_MEDIA_MAX_REFUSALS && !halted) { halted = true; log( `X's media CDN refused ${LIBRARY_MEDIA_MAX_REFUSALS} files in a row (a 403, or no answer): this job asks it for no more. ` + "What is left is owed to a later capture; nothing retries by itself.", ); } if (got.ok) { budget.bytes += got.bytes; await adopt(name, source.url); files.push({ name, url: source.url }); continue; } if (got.rateLimited) { const until = await deps.noteRateLimit().catch(() => now() + 15 * 60_000); stop = `X's media CDN answered 429 (rate limit) for ${name}: the capture stopped at once and asked nothing more. ` + `Nothing X starts before ${new Date(until).toISOString().slice(11, 16)} UTC; nothing retries by itself.`; problems.push(`${name}: ${got.why}`); owedNext = true; break; } problems.push(`${name}: ${got.why}`); if (got.oversize) { owedKept = true; await noteXTrendingOversize(o.channelRoot, { url: source.url, bytes: got.oversize, now }); } else failed = true; } if (signal.aborted && !stop) { return { ok: false, owed: "next", error: "cancelled", files }; } if (sources.length < expected && !stop) { problems.push( `${expected - sources.length} of its ${expected} media file(s) have no CDN address in the saved capture` + (mayLogin ? "" : ": owed until the post is kept"), ); if (mayLogin) failed = true; else owedKept = true; } // A kept post the CDN could not serve whole: the fetcher's own logged-in // download, once, and what it lands is taken into the store. if (failed && !stop && mayLogin) { log(`${id}: ${problems.join("; ")} — falling back to the logged-in download.`); const viaLogin = await login(args); for (const name of await listCapturedMediaFiles(dir)) { const url = viaLogin.ok ? viaLogin.files.find((f) => f.name === name)?.url : undefined; await adopt(name, url ?? files.find((f) => f.name === name)?.url); } return viaLogin; } if (problems.length === 0) return { ok: true, files }; return { ok: false, error: problems.join("; "), files, ...(failed ? {} : owedNext ? { owed: "next" as const } : owedKept ? { owed: "kept" as const } : {}), ...(stop ? { stop } : {}), }; }; }