// THE MEDIA OF AN INSTAGRAM FETCH (lane instagram): the pictures and videos of // the posts a run just listed, fetched from the CDN addresses the run printed, // in the same job — they are signed and expire, so "later" is not an option. // // - ONLY INSTAGRAM'S CDN: an https address on a host ending in // .cdninstagram.com or .fbcdn.net. Anything else is skipped and said. // - ONE GET per file, with no cookies and no referer, a plain browser // User-Agent, never following a redirect, 2-5 s after the one before it. // - A job fetches at most its budget (a sync 40 files / 200 MB, a walk // 120 / 600 MB — the fetcher's plan says which); a file over 100 MB is not // fetched at all. The byte budget holds WHILE a file streams: one that // would cross it is abandoned. What a job did not fetch is OWED and said so // in the post's capture record (`mediaOwed: "next"`), never retried here. // - Three refusals in a row (a 403, a 429, no answer) end the media half. // - It ends with the job: a cancel stops it at once, a drain or its own // deadline (20 minutes) between two files; a file may take 5 minutes. // - NOT AT ALL after a refusal in the listing (recordInstagramMediaOwed): // when Instagram refused, challenged or asked for a login, everything // Instagram stops, its CDN included. // // Files land in `channels//posts-media//` beside a `capture.json` // (postCapture.ts): the layout X's captures have, with no screenshot. // `posts-media/` is NOT in the media tier and never moves to another drive. // // SERVER-ONLY. import { createWriteStream } from "node:fs"; import { mkdir, rename, rm, stat } from "node:fs/promises"; import { once } from "node:events"; import path from "node:path"; import type { PostMediaPlan } from "./fetchers"; import { describeCapturedFile, postCaptureDir, readPostCapture, writePostCapture, type CapturedFile, type PostCaptureRecord, } from "./postCapture"; // A sync's budget; a walk's is larger (instagramGalleryDlFetcher.ts). export const INSTAGRAM_MEDIA_MAX_FILES = 40; export const INSTAGRAM_MEDIA_MAX_BYTES = 200 * 1024 * 1024; export const INSTAGRAM_MEDIA_MAX_FILE_BYTES = 100 * 1024 * 1024; export const INSTAGRAM_MEDIA_MAX_REFUSALS = 3; export const INSTAGRAM_MEDIA_PAUSE_MIN_MS = 2_000; export const INSTAGRAM_MEDIA_PAUSE_MAX_MS = 5_000; // The media half's own deadline, and one file's. export const INSTAGRAM_MEDIA_BUDGET_MS = 20 * 60_000; export const INSTAGRAM_MEDIA_FILE_MS = 5 * 60_000; const HEADERS_MS = 30_000; // THE ONE User-Agent a media GET sends. gallery-dl 1.32.9 sends exactly this // for an Instagram video or audio file (extractor/instagram.py // `videos_headers`), and its Chrome string for a picture; one plain string for // both here. Node's own ("node") would name the client. export const INSTAGRAM_MEDIA_USER_AGENT = "Mozilla/5.0"; // The hosts Instagram serves media from. export const INSTAGRAM_MEDIA_HOST_SUFFIXES: readonly string[] = [".cdninstagram.com", ".fbcdn.net"]; // Why an address is not fetched, or null when it may be. export function instagramMediaUrlProblem(url: string, suffixes: readonly string[] = INSTAGRAM_MEDIA_HOST_SUFFIXES): string | null { let u: URL; try { u = new URL(url); } catch { return "its address is not a URL"; } if (u.protocol !== "https:") return "its address is not https"; if (u.username || u.password) return "its address carries credentials"; const host = u.hostname.toLowerCase(); if (!suffixes.some((s) => host.endsWith(s) && host.length > s.length)) { return `its host (${host}) is not Instagram's CDN`; } return null; } export type InstagramMediaFetch = ( url: string, init: { signal: AbortSignal; redirect: "error"; credentials: "omit"; referrer: ""; referrerPolicy: "no-referrer"; headers: Record; }, ) => Promise<{ status: number; headers: { get: (name: string) => string | null }; body: (AsyncIterable & { cancel?: () => Promise | void }) | null; }>; export type InstagramMediaDeps = { fetch: InstagramMediaFetch; pause: (ms: number, signal: AbortSignal) => Promise; // The pause before a file that is not the job's first, in ms. pauseMs: () => number; now: () => number; // Why an address is not fetched, or null. urlProblem: (url: string) => string | null; // A file's writer (tests break it). openFile: (file: string) => NodeJS.WritableStream & { destroy: () => void }; }; export function instagramMediaPauseMs(rand: () => number = Math.random): number { return Math.round(INSTAGRAM_MEDIA_PAUSE_MIN_MS + rand() * (INSTAGRAM_MEDIA_PAUSE_MAX_MS - INSTAGRAM_MEDIA_PAUSE_MIN_MS)); } function sleep(ms: number, signal: AbortSignal): Promise { return new Promise((resolve) => { if (signal.aborted) return resolve(); const t = setTimeout(done, ms); function done() { clearTimeout(t); signal.removeEventListener("abort", done); resolve(); } signal.addEventListener("abort", done, { once: true }); }); } const defaultDeps = (): InstagramMediaDeps => ({ fetch: (url, init) => fetch(url, init) as unknown as ReturnType, pause: sleep, pauseMs: () => instagramMediaPauseMs(), now: () => Date.now(), urlProblem: (url) => instagramMediaUrlProblem(url), openFile: (file) => createWriteStream(file), }); // UNDER THE E2E TEST SERVER the CDN is played back, always: no test server // opens a socket to it. An address containing "refused" answers 403, one // containing "limited" 429, one containing "huge" declares 150 MB; every // other answers a few bytes naming it. Null outside the test server. export function fakeInstagramMediaFetch( env: Readonly> = process.env, ): InstagramMediaFetch | null { if (env.E2E_TEST_ROUTES !== "1") return null; return async (url) => { const status = /refused/.test(url) ? 403 : /limited/.test(url) ? 429 : 200; const bytes = Buffer.from(`fake instagram media ${url}`); const length = /huge/.test(url) ? 150 * 1024 * 1024 : bytes.length; return { status, headers: { get: (name: string) => (name.toLowerCase() === "content-length" ? String(length) : null) }, body: status === 200 ? (async function* () { yield new Uint8Array(bytes); })() : null, }; }; } // The fixtures' invented CDN host, allowed ONLY beside the played-back fetch: // outside the test server an address on it is skipped like any other host // that is not Instagram's, so the fake gallery-dl can never cause a request. export const E2E_INSTAGRAM_MEDIA_HOST_SUFFIX = ".example.invalid"; // What the controller takes under the test server: the played-back fetch, no // pause between two files (no CDN is being asked), and the fixtures' host. export function fakeInstagramMediaDeps( env: Readonly> = process.env, ): Pick | null { const fake = fakeInstagramMediaFetch(env); if (!fake) return null; return { fetch: fake, pauseMs: () => 0, urlProblem: (url) => instagramMediaUrlProblem(url, [...INSTAGRAM_MEDIA_HOST_SUFFIXES, E2E_INSTAGRAM_MEDIA_HOST_SUFFIX]), }; } const mb = (bytes: number) => `${Math.round(bytes / (1024 * 1024))} MB`; const firstLine = (err: unknown) => String((err as Error)?.message ?? err).split("\n")[0]!.slice(0, 200); type Fetched = | { ok: true; bytes: number } | { ok: false; why: string; // The CDN refused (a 403, a 429, no answer): counted toward the three. refused?: boolean; // Larger than a file may ever be: not owed, asking again gets the same file. oversize?: boolean; // It would have crossed the job's byte budget: owed. overBudget?: boolean; }; // One file, streamed to `.part` and renamed when whole. `cap` is what a // file may be; `room` what is left of the job's byte budget. async function fetchOne(o: { url: string; file: string; cap: number; room: number; deps: Pick; signal: AbortSignal; }): Promise { const part = `${o.file}.part`; const limit = Math.min(o.cap, o.room); const over = (bytes: number): Fetched => bytes > o.cap || o.cap <= o.room ? { ok: false, oversize: true, why: `it is ${bytes > 0 ? mb(bytes) : "more than " + mb(o.cap)}, over the ${mb(o.cap)} a file may be` } : { ok: false, overBudget: true, why: "it would cross this job's byte budget" }; const deadline = AbortSignal.any([o.signal, AbortSignal.timeout(INSTAGRAM_MEDIA_FILE_MS)]); // The wait for the headers is its own timer, cleared when they arrive: the // signal handed to fetch also ends the body. const headers = new AbortController(); const timer = setTimeout(() => headers.abort(new Error("no answer in time")), HEADERS_MS); let res: Awaited>; try { res = await o.deps.fetch(o.url, { signal: AbortSignal.any([deadline, headers.signal]), redirect: "error", credentials: "omit", referrer: "", referrerPolicy: "no-referrer", headers: { "User-Agent": INSTAGRAM_MEDIA_USER_AGENT }, }); } catch (err) { return { ok: false, refused: !o.signal.aborted, why: `the CDN did not answer (${firstLine(err)})` }; } finally { clearTimeout(timer); } const drop = async () => { try { await res.body?.cancel?.(); } catch { /* already ended */ } }; if (res.status < 200 || res.status >= 300 || !res.body) { await drop(); return { ok: false, refused: res.status === 403 || res.status === 429, why: `the CDN answered ${res.status}` }; } const declared = Number(res.headers.get("content-length") ?? ""); if (Number.isFinite(declared) && declared > limit) { await drop(); return over(declared); } await rm(part, { force: true }); // A writer that cannot open or runs out of disk says so through "error": // listened for from the start, so it fails this file with a sentence and is // never an unhandled event. let writeError: Error | null = null; let out: ReturnType; try { out = o.deps.openFile(part); } catch (err) { await drop(); return { ok: false, why: `the file could not be written (${firstLine(err)})` }; } out.on("error", (err: Error) => { writeError = err; }); const failedWrite = async (): Promise => { out.destroy(); await drop(); await rm(part, { force: true }); return { ok: false, why: `the file could not be written (${firstLine(writeError)})` }; }; let bytes = 0; let tooBig = false; try { for await (const chunk of res.body) { if (writeError) return await failedWrite(); if (deadline.aborted) throw new Error(o.signal.aborted ? "cancelled" : "the file took too long"); bytes += chunk.byteLength; if (bytes > limit) { tooBig = true; break; } if (!out.write(chunk)) await Promise.race([once(out, "drain"), once(out, "error").catch(() => {})]); } } catch (err) { if (writeError) return failedWrite(); out.destroy(); await rm(part, { force: true }); return { ok: false, refused: !o.signal.aborted, why: `the download broke off (${firstLine(err)})` }; } if (writeError) return failedWrite(); await new Promise((resolve) => { out.once("error", () => resolve()); out.end(() => resolve()); }); if (writeError) return failedWrite(); 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 answered an empty file" }; } try { await rename(part, o.file); } catch (err) { await rm(part, { force: true }); return { ok: false, why: `the file could not be written (${firstLine(err)})` }; } return { ok: true, bytes }; } export type InstagramMediaSummary = { // Files fetched by this job, and their bytes. fetched: number; bytes: number; // Files already on disk from an earlier job. kept: number; // Files not fetched and owed to a later capture (the job's budget, a // refusal, a cancel, a drain, the deadline), files over the per-file cap, // files on a host that is not Instagram's CDN, and files that failed. owed: number; oversize: number; skipped: number; failed: number; // Posts whose media are whole on disk after the job, of how many; and how // many are left owed something. postsWhole: number; postsOwed: number; posts: number; // Why the media half stopped before its last file, when it did. stopped?: string; }; async function exists(file: string): Promise { try { return (await stat(file)).isFile(); } catch { return false; } } // Fetch the media of `plans` into `outDir` (the channel's `posts-media/`), in // order, under the job's caps. Never throws: what went wrong is in the // summary and in each post's capture record. export async function fetchInstagramMedia(opts: { outDir: string; plans: readonly PostMediaPlan[]; // Cancel: ends the file in hand and everything after it. signal: AbortSignal; // Drain: the file in hand finishes, nothing after it starts. drain?: AbortSignal; onLog?: (line: string) => void; deps?: Partial; limits?: { maxFiles?: number; maxBytes?: number; maxFileBytes?: number; budgetMs?: number }; }): Promise { const deps = { ...defaultDeps(), ...opts.deps }; const log = (line: string) => opts.onLog?.(line); const maxFiles = opts.limits?.maxFiles ?? INSTAGRAM_MEDIA_MAX_FILES; const maxBytes = opts.limits?.maxBytes ?? INSTAGRAM_MEDIA_MAX_BYTES; const maxFileBytes = opts.limits?.maxFileBytes ?? INSTAGRAM_MEDIA_MAX_FILE_BYTES; const deadlineAt = deps.now() + (opts.limits?.budgetMs ?? INSTAGRAM_MEDIA_BUDGET_MS); const sum: InstagramMediaSummary = { fetched: 0, bytes: 0, kept: 0, owed: 0, oversize: 0, skipped: 0, failed: 0, postsWhole: 0, postsOwed: 0, posts: opts.plans.length, }; let asked = 0; let refusals = 0; const stop = (why: string, line: string) => { if (sum.stopped) return; sum.stopped = why; log(line); }; // Why nothing more is asked for now, or null. const halted = (): string | null => { if (opts.signal.aborted) return "cancelled"; if (sum.stopped) return sum.stopped; if (opts.drain?.aborted) { stop("the job was drained", "Drained: no more media is asked for; the rest is owed to a later capture."); return sum.stopped!; } if (deps.now() >= deadlineAt) { stop( "the media half's time is used", "The media half's time is used: no more media is asked for; the rest is owed to a later capture.", ); return sum.stopped!; } if (asked >= maxFiles || sum.bytes >= maxBytes) { stop( `this job's media budget of ${maxFiles} files / ${mb(maxBytes)} is used`, `This job's media budget (${maxFiles} files / ${mb(maxBytes)}) is used: the rest is owed to a later capture.`, ); return sum.stopped!; } return null; }; for (const plan of opts.plans) { let dir: string; try { dir = postCaptureDir(opts.outDir, plan.id); } catch (err) { sum.failed += plan.files.length; log(`[warn] ${firstLine(err)}: its media are left.`); continue; } await mkdir(dir, { recursive: true }); const landed: CapturedFile[] = []; const problems: string[] = []; let owed = false; for (const f of [...plan.files].sort((a, b) => a.num - b.num)) { const name = path.basename(f.name); const file = path.join(dir, name); if (await exists(file)) { sum.kept++; landed.push(await describeCapturedFile(dir, name, f.url)); continue; } const notCdn = deps.urlProblem(f.url); if (notCdn) { sum.skipped++; problems.push(`${name}: not fetched (${notCdn})`); continue; } let why = halted(); if (!why && asked > 0) { await deps.pause(deps.pauseMs(), opts.signal); why = halted(); } if (why) { owed = true; sum.owed++; problems.push(`${name}: owed (${why})`); continue; } asked++; const got = await fetchOne({ url: f.url, file, cap: maxFileBytes, room: maxBytes - sum.bytes, deps, signal: opts.signal }); if (got.ok) { refusals = 0; sum.fetched++; sum.bytes += got.bytes; landed.push(await describeCapturedFile(dir, name, f.url)); continue; } problems.push(`${name}: ${got.why}`); if (got.oversize) { refusals = 0; sum.oversize++; continue; } if (got.overBudget) { refusals = 0; owed = true; sum.owed++; stop( `this job's media budget of ${maxFiles} files / ${mb(maxBytes)} is used`, `This job's media budget (${maxFiles} files / ${mb(maxBytes)}) is used: the rest is owed to a later capture.`, ); continue; } refusals = got.refused ? refusals + 1 : 0; if (got.refused) { owed = true; sum.owed++; } else sum.failed++; if (refusals >= INSTAGRAM_MEDIA_MAX_REFUSALS) { stop( `the CDN refused ${INSTAGRAM_MEDIA_MAX_REFUSALS} files in a row`, `Instagram's media CDN refused ${INSTAGRAM_MEDIA_MAX_REFUSALS} files in a row (a 403, a 429 or no answer): ` + "this job asks it for no more. What is left is owed to a later capture; nothing retries by itself.", ); } } const whole = problems.length === 0; if (whole) sum.postsWhole++; if (owed) sum.postsOwed++; await writeRecord(dir, plan, landed, whole ? null : { owed, error: problems.join("; ") }, deps.now()); } return sum; } async function writeRecord( dir: string, plan: PostMediaPlan, landed: CapturedFile[], problem: { owed: boolean; error: string } | null, now: number, ): Promise { const prior = await readPostCapture(dir); const record: PostCaptureRecord = { ...(prior ?? {}), version: 1, id: plan.id, url: plan.url, capturedAt: new Date(now).toISOString(), state: "captured", mediaState: problem ? "error" : landed.length > 0 ? "ok" : "none", media: landed, }; delete record.mediaOwed; delete record.error; if (problem) { if (problem.owed) record.mediaOwed = "next"; record.error = problem.error; } await writePostCapture(dir, record); } // THE LISTING WAS REFUSED (a rate limit, a challenge, a login page): the posts // it read are archived, and their media are NOT asked for — everything // Instagram stops, its CDN too. Each post's record says its media are owed. // Answers how many posts were marked. export async function recordInstagramMediaOwed(opts: { outDir: string; plans: readonly PostMediaPlan[]; why: string; now?: number; }): Promise { let marked = 0; for (const plan of opts.plans) { let dir: string; try { dir = postCaptureDir(opts.outDir, plan.id); } catch { continue; } await mkdir(dir, { recursive: true }); const landed: CapturedFile[] = []; for (const f of plan.files) { const name = path.basename(f.name); if (await exists(path.join(dir, name))) landed.push(await describeCapturedFile(dir, name, f.url)); } if (landed.length === plan.files.length) continue; await writeRecord(dir, plan, landed, { owed: true, error: `not fetched (${opts.why})` }, opts.now ?? Date.now()); marked++; } return marked; } // What the media half did, as one line for the job's log. export function instagramMediaLine(sum: InstagramMediaSummary): string { const parts = [`${sum.fetched} file(s) fetched from its CDN (${mb(sum.bytes)})`]; if (sum.kept) parts.push(`${sum.kept} already on disk`); if (sum.owed) parts.push(`${sum.owed} owed to a later capture`); if (sum.oversize) parts.push(`${sum.oversize} over the per-file cap, not fetched`); if (sum.skipped) parts.push(`${sum.skipped} on a host that is not Instagram's CDN, not fetched`); if (sum.failed) parts.push(`${sum.failed} failed`); return ( `Media: ${parts.join(", ")}; ${sum.postsWhole} of ${sum.posts} post(s) whole` + (sum.postsOwed ? `, ${sum.postsOwed} with media owed (nothing collects owed media yet)` : "") + "." ); }