// The media half of an Instagram fetch (instagramMedia.ts): one GET per file, // paced, capped, and stopped by three refusals in a row. The CDN is a function // here; nothing opens a socket. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/instagramMedia.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile, readdir, rm, writeFile, mkdir } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import type { PostMediaPlan } from "./fetchers"; import { fakeInstagramMediaDeps, fakeInstagramMediaFetch, fetchInstagramMedia, instagramMediaLine, instagramMediaPauseMs, INSTAGRAM_MEDIA_MAX_BYTES, INSTAGRAM_MEDIA_MAX_FILE_BYTES, INSTAGRAM_MEDIA_MAX_FILES, INSTAGRAM_MEDIA_BUDGET_MS, INSTAGRAM_MEDIA_FILE_MS, INSTAGRAM_MEDIA_USER_AGENT, instagramMediaUrlProblem, recordInstagramMediaOwed, type InstagramMediaFetch, } from "./instagramMedia"; // An invented host under Instagram's CDN suffix: never asked (the CDN is a function here). const CDN = "https://scontent-invented.cdninstagram.com"; const pk = (n: number) => (3500000000000000000n + BigInt(n)).toString(); function plan(n: number, files: number, tag = ""): PostMediaPlan { return { id: pk(n), url: `https://www.instagram.com/p/Code${n}/`, files: Array.from({ length: files }, (_, i) => ({ num: i + 1, kind: "image" as const, url: `${CDN}/${n}-${i + 1}${tag}.jpg?sig=invented`, name: `${String(i + 1).padStart(2, "0")}-${n}${i + 1}.jpg`, })), }; } type Cdn = { calls: { url: string; init: Record }[]; pauses: number[]; fetch: InstagramMediaFetch }; function cdn(answer: (url: string, i: number) => { status?: number; bytes?: number; declared?: number; throws?: boolean } = () => ({})): Cdn { const c: Cdn = { calls: [], pauses: [], fetch: undefined as never }; c.fetch = async (url, init) => { const i = c.calls.length; c.calls.push({ url, init: init as never }); const a = answer(url, i); if (a.throws) throw new Error("connect ECONNREFUSED (invented)"); const status = a.status ?? 200; const body = new Uint8Array(a.bytes ?? 10).fill(7); return { status, headers: { get: (name: string) => (name.toLowerCase() === "content-length" ? String(a.declared ?? body.length) : null) }, body: status === 200 ? (async function* () { yield body; })() : null, }; }; return c; } const deps = (c: Cdn) => ({ fetch: c.fetch, pause: async (ms: number) => { c.pauses.push(ms); }, pauseMs: () => 3000, now: () => Date.parse("2026-03-10T12:00:00Z"), }); async function tmp(): Promise { return mkdtemp(path.join(os.tmpdir(), "instagram-media-")); } const record = async (out: string, id: string) => JSON.parse(await readFile(path.join(out, id, "capture.json"), "utf8")); const signal = () => new AbortController().signal; test("the caps and the pause are what the lane ruled", () => { assert.equal(INSTAGRAM_MEDIA_MAX_FILES, 40); assert.equal(INSTAGRAM_MEDIA_MAX_BYTES, 200 * 1024 * 1024); assert.equal(INSTAGRAM_MEDIA_MAX_FILE_BYTES, 100 * 1024 * 1024); assert.equal(instagramMediaPauseMs(() => 0), 2000); assert.equal(instagramMediaPauseMs(() => 0.999999), 5000); }); test("one GET per file, with no cookies, a pause before every file but the first; a capture record and no screenshot", async () => { const out = await tmp(); try { const c = cdn(); const sum = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 2), plan(2, 1)], signal: signal(), deps: deps(c) }); assert.deepEqual(c.calls.map((x) => x.url), [`${CDN}/1-1.jpg?sig=invented`, `${CDN}/1-2.jpg?sig=invented`, `${CDN}/2-1.jpg?sig=invented`]); for (const call of c.calls) { assert.equal(call.init.credentials, "omit"); assert.equal(call.init.redirect, "error"); // No referer, and one plain browser User-Agent (never Node's own). assert.equal(call.init.referrer, ""); assert.equal(call.init.referrerPolicy, "no-referrer"); assert.deepEqual(call.init.headers, { "User-Agent": INSTAGRAM_MEDIA_USER_AGENT }); } assert.deepEqual(c.pauses, [3000, 3000]); assert.deepEqual({ ...sum }, { fetched: 3, bytes: 30, kept: 0, owed: 0, oversize: 0, skipped: 0, failed: 0, postsWhole: 2, postsOwed: 0, posts: 2 }); assert.deepEqual((await readdir(path.join(out, pk(1)))).sort(), ["01-11.jpg", "02-12.jpg", "capture.json"]); const r = await record(out, pk(1)); assert.deepEqual([r.version, r.id, r.url, r.state, r.mediaState, r.capturedAt], [1, pk(1), "https://www.instagram.com/p/Code1/", "captured", "ok", "2026-03-10T12:00:00.000Z"]); assert.equal(r.shot, undefined); assert.deepEqual(r.media.map((m: { name: string; bytes: number }) => [m.name, m.bytes]), [["01-11.jpg", 10], ["02-12.jpg", 10]]); assert.match(instagramMediaLine(sum), /^Media: 3 file\(s\) fetched from its CDN \(0 MB\); 2 of 2 post\(s\) whole\.$/); // A second job over the same posts asks the CDN nothing. const again = cdn(); const sum2 = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 2)], signal: signal(), deps: deps(again) }); assert.equal(again.calls.length, 0); assert.equal(sum2.kept, 2); assert.equal((await record(out, pk(1))).mediaState, "ok"); } finally { await rm(out, { recursive: true, force: true }); } }); test("the job's budget: the 41st file is not asked for, and is recorded as owed", async () => { const out = await tmp(); try { const c = cdn(); const sum = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 10), plan(2, 10), plan(3, 10), plan(4, 10), plan(5, 3)], signal: signal(), deps: deps(c) }); assert.equal(c.calls.length, 40); assert.equal(sum.fetched, 40); assert.equal(sum.owed, 3); assert.equal(sum.postsWhole, 4); assert.match(sum.stopped!, /media budget of 40 files \/ 200 MB is used/); const r = await record(out, pk(5)); assert.equal(r.mediaState, "error"); assert.equal(r.mediaOwed, "next"); assert.deepEqual(r.media, []); // The byte budget, with small limits. assert.equal(sum.postsOwed, 1); assert.match(instagramMediaLine(sum), /1 with media owed \(nothing collects owed media yet\)/); // The BYTE budget holds while a file streams: the file that would cross it is abandoned, nothing of it left. const c2 = cdn(() => ({ bytes: 600 })); const out2 = await tmp(); const sum2 = await fetchInstagramMedia({ outDir: out2, plans: [plan(7, 5)], signal: signal(), deps: deps(c2), limits: { maxBytes: 1000 } }); assert.equal(c2.calls.length, 2, "the second file is asked for, and abandoned when it crosses the budget"); assert.deepEqual([sum2.fetched, sum2.bytes, sum2.owed, sum2.oversize], [1, 600, 4, 0]); assert.deepEqual((await readdir(path.join(out2, pk(7)))).sort(), ["01-71.jpg", "capture.json"]); assert.equal((await record(out2, pk(7))).mediaOwed, "next"); // A walk's budget is the caller's to give. const c3 = cdn(); const sum3 = await fetchInstagramMedia({ outDir: await tmp(), plans: [plan(8, 45)], signal: signal(), deps: deps(c3), limits: { maxFiles: 120, maxBytes: 600 * 1024 * 1024 } }); assert.equal(sum3.fetched, 45); } finally { await rm(out, { recursive: true, force: true }); } }); test("a file over 100 MB is not fetched: by its declared length, or cut when the body runs past it", async () => { const out = await tmp(); try { const c = cdn((url) => (url.includes("/1-1") ? { declared: 150 * 1024 * 1024 } : {})); const sum = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 2)], signal: signal(), deps: deps(c) }); assert.equal(sum.oversize, 1); assert.equal(sum.fetched, 1); assert.deepEqual((await readdir(path.join(out, pk(1)))).sort(), ["02-12.jpg", "capture.json"]); const r = await record(out, pk(1)); assert.equal(r.mediaState, "error"); assert.match(r.error, /01-11\.jpg: it is 150 MB, over the 100 MB a file may be/); assert.equal(r.mediaOwed, undefined, "over the cap is not owed: asking again gets the same file"); // Undeclared, and longer than the cap: cut, nothing left behind. const lying = cdn(() => ({ bytes: 50, declared: 5 })); const out2 = await tmp(); const sum2 = await fetchInstagramMedia({ outDir: out2, plans: [plan(2, 1)], signal: signal(), deps: deps(lying), limits: { maxFileBytes: 20 } }); assert.equal(sum2.oversize, 1); assert.deepEqual(await readdir(path.join(out2, pk(2))), ["capture.json"]); } finally { await rm(out, { recursive: true, force: true }); } }); test("three refusals in a row (a 403, a 429, no answer) end the media half; a success between them resets the count", async () => { const out = await tmp(); try { // refused, refused, ok, refused (429), refused (throws), refused -> stop; the rest unasked. const seq = [403, 403, 200, 429, -1, 403, 200, 200]; const c = cdn((_u, i) => (seq[i] === -1 ? { throws: true } : { status: seq[i] })); const sum = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 4), plan(2, 4)], signal: signal(), deps: deps(c) }); assert.equal(c.calls.length, 6); assert.equal(sum.fetched, 1); assert.equal(sum.owed, 7); assert.match(sum.stopped!, /the CDN refused 3 files in a row/); const r2 = await record(out, pk(2)); assert.equal(r2.mediaOwed, "next"); assert.match(r2.error, /owed \(the CDN refused 3 files in a row\)/); // A 404 or a 500 is a failure of that file, not a refusal: the job goes on. const c2 = cdn((_u, i) => ({ status: i < 4 ? 404 : 200 })); const out2 = await tmp(); const sum2 = await fetchInstagramMedia({ outDir: out2, plans: [plan(3, 5)], signal: signal(), deps: deps(c2) }); assert.equal(c2.calls.length, 5); assert.deepEqual([sum2.failed, sum2.fetched, sum2.stopped], [4, 1, undefined]); } finally { await rm(out, { recursive: true, force: true }); } }); test("a cancelled job asks for nothing more and says the rest is owed; an id that is not a post id touches no path", async () => { const out = await tmp(); try { const ac = new AbortController(); const c = cdn(); const d = deps(c); const sum = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 3)], signal: ac.signal, deps: { ...d, pause: async () => ac.abort() }, }); assert.equal(c.calls.length, 1); assert.deepEqual([sum.fetched, sum.owed], [1, 2]); assert.equal((await record(out, pk(1))).mediaOwed, "next"); const bad = await fetchInstagramMedia({ outDir: out, plans: [{ ...plan(2, 1), id: "../escape" }], signal: signal(), deps: d }); assert.equal(bad.failed, 1); assert.deepEqual((await readdir(out)).sort(), [pk(1)]); // A file name is never a path. await mkdir(path.join(out, "x"), { recursive: true }); const sneaky = { ...plan(4, 1), files: [{ num: 1, kind: "image" as const, url: `${CDN}/a.jpg`, name: "../../evil.jpg" }] }; assert.equal(sum.postsOwed, 1); await fetchInstagramMedia({ outDir: out, plans: [sneaky], signal: signal(), deps: d }); assert.deepEqual((await readdir(path.join(out, pk(4)))).sort(), ["capture.json", "evil.jpg"]); await writeFile(path.join(out, "x", "keep"), ""); } finally { await rm(out, { recursive: true, force: true }); } }); test("only Instagram's CDN is asked: https, a host under .cdninstagram.com or .fbcdn.net — anything else is skipped and said", async () => { assert.equal(instagramMediaUrlProblem("https://scontent-xyz.cdninstagram.com/v/a.jpg?x=1"), null); assert.equal(instagramMediaUrlProblem("https://video.fabc1-1.fna.fbcdn.net/v/a.mp4"), null); assert.match(instagramMediaUrlProblem("http://scontent-xyz.cdninstagram.com/a.jpg")!, /not https/); assert.match(instagramMediaUrlProblem("https://cdninstagram.com.example.org/a.jpg")!, /is not Instagram's CDN/); assert.match(instagramMediaUrlProblem("https://evilcdninstagram.com/a.jpg")!, /is not Instagram's CDN/); assert.match(instagramMediaUrlProblem("https://cdninstagram.com/a.jpg")!, /is not Instagram's CDN/); assert.match(instagramMediaUrlProblem("https://www.instagram.com/api/v1/x")!, /is not Instagram's CDN/); assert.match(instagramMediaUrlProblem("https://user:pw@scontent.cdninstagram.com/a.jpg")!, /credentials/); assert.match(instagramMediaUrlProblem("file:///etc/passwd")!, /not https/); assert.match(instagramMediaUrlProblem("not a url")!, /not a URL/); const out = await tmp(); try { const c = cdn(); const mixed = plan(1, 3); mixed.files[1]!.url = "https://cdn.example.invalid/elsewhere.jpg"; const d = deps(c); const sum = await fetchInstagramMedia({ outDir: out, plans: [mixed], signal: signal(), deps: { fetch: d.fetch, pause: d.pause, pauseMs: d.pauseMs, now: d.now } }); assert.equal(c.calls.length, 2, "the other host is never asked"); assert.ok(c.calls.every((x) => x.url.startsWith(CDN))); assert.deepEqual([sum.fetched, sum.skipped, sum.owed], [2, 1, 0]); const r = await record(out, pk(1)); assert.match(r.error, /02-12\.jpg: not fetched \(its host \(cdn\.example\.invalid\) is not Instagram's CDN\)/); assert.equal(r.mediaOwed, undefined); assert.match(instagramMediaLine(sum), /1 on a host that is not Instagram's CDN, not fetched/); } finally { await rm(out, { recursive: true, force: true }); } }); test("a drain stops between two files; the media half has its own deadline; a file has five minutes", async () => { assert.equal(INSTAGRAM_MEDIA_BUDGET_MS, 20 * 60_000); assert.equal(INSTAGRAM_MEDIA_FILE_MS, 5 * 60_000); const out = await tmp(); try { // Drained during the pause before the second file: the first is whole, nothing after it starts. const drain = new AbortController(); const c = cdn(); const d = deps(c); const log: string[] = []; const sum = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 3), plan(2, 1)], signal: signal(), drain: drain.signal, onLog: (l) => log.push(l), deps: { ...d, pause: async () => drain.abort() }, }); assert.equal(c.calls.length, 1); assert.deepEqual([sum.fetched, sum.owed, sum.postsOwed], [1, 3, 2]); assert.equal(sum.stopped, "the job was drained"); assert.ok(log.some((l) => l.startsWith("Drained: no more media is asked for"))); assert.equal((await record(out, pk(2))).mediaOwed, "next"); // The deadline: a clock that passes it after two files. let now = 0; const c2 = cdn(); const d2 = deps(c2); const sum2 = await fetchInstagramMedia({ outDir: await tmp(), plans: [plan(3, 5)], signal: signal(), deps: { ...d2, now: () => now, pause: async () => { now += 400_000; } }, limits: { budgetMs: 1_000_000 }, }); assert.equal(c2.calls.length, 3, "0 s, 400 s and 800 s are inside 1000 s; 1200 s is not"); assert.equal(sum2.stopped, "the media half's time is used"); assert.equal(sum2.owed, 2); } finally { await rm(out, { recursive: true, force: true }); } }); test("a file that cannot be written fails that file with a sentence, and the job goes on", async () => { const out = await tmp(); try { const c = cdn(); const d = deps(c); const { createWriteStream } = await import("node:fs"); let n = 0; const sum = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 3)], signal: signal(), deps: { ...d, // The first file's directory does not exist (an open failure, as a full or read-only disk gives). openFile: (file) => createWriteStream(n++ === 0 ? path.join(out, "no-such-dir", "x", path.basename(file)) : file), }, }); assert.deepEqual([sum.fetched, sum.failed, sum.owed], [2, 1, 0]); const r = await record(out, pk(1)); assert.match(r.error, /^01-11\.jpg: the file could not be written \(ENOENT/); assert.deepEqual((await readdir(path.join(out, pk(1)))).sort(), ["02-12.jpg", "03-13.jpg", "capture.json"]); // An opener that throws outright is the same sentence. const sum2 = await fetchInstagramMedia({ outDir: await tmp(), plans: [plan(2, 1)], signal: signal(), deps: { ...d, openFile: () => { throw new Error("ENOSPC: no space left on device (invented)"); } }, }); assert.equal(sum2.failed, 1); } finally { await rm(out, { recursive: true, force: true }); } }); test("after a refusal in the listing no media is asked for at all: each post's record says its media are owed", async () => { const out = await tmp(); try { const marked = await recordInstagramMediaOwed({ outDir: out, plans: [plan(1, 2), plan(2, 1)], why: "Instagram refused the listing", now: Date.parse("2026-03-10T12:00:00Z") }); assert.equal(marked, 2); const r = await record(out, pk(1)); assert.deepEqual([r.state, r.mediaState, r.mediaOwed, r.media.length], ["captured", "error", "next", 0]); assert.match(r.error, /not fetched \(Instagram refused the listing\)/); assert.deepEqual(await readdir(path.join(out, pk(1))), ["capture.json"]); // A post whose media are already whole on disk is not marked. const c = cdn(); await fetchInstagramMedia({ outDir: out, plans: [plan(3, 1)], signal: signal(), deps: deps(c) }); assert.equal(await recordInstagramMediaOwed({ outDir: out, plans: [plan(3, 1)], why: "x" }), 0); assert.equal((await record(out, pk(3))).mediaState, "ok"); } finally { await rm(out, { recursive: true, force: true }); } }); test("the test server's CDN is played back, and there is none outside it", async () => { assert.equal(fakeInstagramMediaFetch({}), null); assert.equal(fakeInstagramMediaDeps({}), null); // Played back, no CDN is asked: no pause between two files either. assert.equal(fakeInstagramMediaDeps({ E2E_TEST_ROUTES: "1" })!.pauseMs(), 0); const f = fakeInstagramMediaFetch({ E2E_TEST_ROUTES: "1" })!; const init = { signal: signal(), redirect: "error" as const, credentials: "omit" as const, referrer: "" as const, referrerPolicy: "no-referrer" as const, headers: {} }; // The fixtures' invented host is allowed only beside the played-back fetch. assert.match(instagramMediaUrlProblem("https://cdn.example.invalid/a.jpg")!, /is not Instagram's CDN/); assert.equal(fakeInstagramMediaDeps({ E2E_TEST_ROUTES: "1" })!.urlProblem("https://cdn.example.invalid/a.jpg"), null); assert.match(fakeInstagramMediaDeps({ E2E_TEST_ROUTES: "1" })!.urlProblem("https://example.org/a.jpg")!, /is not Instagram's CDN/); assert.equal((await f(`${CDN}/a.jpg`, init)).status, 200); assert.equal((await f(`${CDN}/refused.jpg`, init)).status, 403); assert.equal((await f(`${CDN}/limited.jpg`, init)).status, 429); assert.equal((await f(`${CDN}/huge.mp4`, init)).headers.get("content-length"), String(150 * 1024 * 1024)); });