// The Instagram fetcher (instagramGalleryDlFetcher.ts) with gallery-dl // injected: what it asks for, where it stops, what each refusal does. Nothing // here spawns a binary or opens a socket; every run is invented. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/instagramGalleryDlFetcher.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { buildInstagramGalleryDlArgs, fetchInstagramPosts, instagramGalleryDlFetcher, INSTAGRAM_FROM_TOP_CURSOR, INSTAGRAM_NO_COOKIES, planInstagramRun, type InstagramFetcherDeps, type InstagramRunOutput, } from "./instagramGalleryDlFetcher"; import { detectSocialFetcher, getSocialFetcher } from "./fetchers"; import type { PostFetchInput } from "./fetchers"; import { IG_HANDLE, IG_UID, igCursorLine, igError, igFeedPath, igPk, igRequestLine, igRows, igSearchPath, igStdout, type FakeIgPost, } from "./__fixtures__/instagramRun"; const NOW = Date.parse("2026-03-10T12:00:00Z"); const URL_ = `https://www.instagram.com/${IG_HANDLE}/`; type Harness = { deps: InstagramFetcherDeps; runs: { args: string[]; stops: number }[]; outcomes: Parameters[0][]; rateLimits: number; // Whether Instagram's alert is up (the second refusal in a row raises it). alert: boolean; log: string[]; }; function harness(answer: { rows?: unknown[]; stdout?: string; stderr?: string[]; out?: Partial }): Harness { const h: Harness = { runs: [], outcomes: [], rateLimits: 0, alert: false, log: [], deps: undefined as never }; h.deps = { bin: () => "gallery-dl-not-run", run: async (_bin, args, opts) => { const run = { args, stops: 0 }; h.runs.push(run); for (const line of answer.stderr ?? []) if (opts.onStderrLine(line) === "stop") run.stops++; return { stdout: answer.stdout ?? igStdout(answer.rows ?? []), timedOut: false, canceled: false, ...answer.out }; }, noteOutcome: async (o) => { h.outcomes.push(o); return null; }, alertRaised: async () => h.alert, noteRateLimit: async () => { h.rateLimits++; return NOW + 60 * 60_000; }, now: () => NOW, }; return h; } function input(h: Harness, over: Partial = {}): PostFetchInput { return { accountUrl: URL_, handle: IG_HANDLE, channelSlug: "example-ig", seenIds: new Set(), cookies: "firefox:ig-profile", signal: new AbortController().signal, onLog: (l) => h.log.push(l), ...over, }; } // `count` posts, newest first, numbered down from `from`: post n is dated n days after 2020-01-01. const days = (from: number, count: number, extra: Partial = {}): FakeIgPost[] => Array.from({ length: count }, (_, i) => { const n = from - i; const date = new Date(Date.UTC(2020, 0, 1) + n * 86_400_000).toISOString().slice(0, 19).replace("T", " "); return { n, date, ...extra }; }); const lookup = [igRequestLine(igSearchPath(), 200)]; const page = igRequestLine(igFeedPath(), 200); test("the fetcher claims instagram.com account URLs, and only those", () => { assert.equal(getSocialFetcher("instagram-gallery-dl"), instagramGalleryDlFetcher); assert.equal(detectSocialFetcher(URL_)?.id, "instagram-gallery-dl"); assert.equal(instagramGalleryDlFetcher.platform, "instagram"); assert.equal(instagramGalleryDlFetcher.detect("https://www.instagram.com/p/CabcDEF1234/"), false); assert.equal(instagramGalleryDlFetcher.detect("https://x.com/someone"), false); // No capture, no older walk, no one-post import, no availability sweep in this slice. assert.equal(instagramGalleryDlFetcher.captureByIds, undefined); assert.equal(instagramGalleryDlFetcher.fetchOlder, undefined); assert.equal(instagramGalleryDlFetcher.fetchOne, undefined); assert.equal(instagramGalleryDlFetcher.checkAvailability, undefined); }); test("the form's probe reads the URL and asks Instagram nothing", async () => { assert.deepEqual(await instagramGalleryDlFetcher.probe("https://instagram.com/Example.Account?hl=en"), { ok: true, name: "Example.Account", handle: "Example.Account", url: "https://www.instagram.com/Example.Account/", }); assert.equal((await instagramGalleryDlFetcher.probe("https://www.instagram.com/p/abc/")).ok, false); }); test("with no cookie source nothing is spawned: Instagram shows the feed only to a login", async () => { const h = harness({}); for (const cookies of [undefined, "", " "]) { const r = await fetchInstagramPosts(input(h, { cookies }), h.deps); assert.deepEqual(r, { posts: [], complete: false, needsCookies: true, error: INSTAGRAM_NO_COOKIES("example-ig") }); } assert.equal(h.runs.length, 0); assert.match(INSTAGRAM_NO_COOKIES("example-ig"), /Cookies from browser/); assert.match(INSTAGRAM_NO_COOKIES("example-ig"), /an account kept for this/); }); test("the plan: a sync is one page, a walk is sized to its media budget, a refusal is never retried", () => { const SYNC = { maxFiles: 40, maxBytes: 200 * 1024 * 1024 }; const WALK = { maxFiles: 120, maxBytes: 600 * 1024 * 1024 }; assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z" }), { mode: "sync", maxPosts: 30, maxRequests: 4, stop: "known", media: SYNC }); assert.equal(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", limit: 5 }).maxPosts, 5); assert.equal(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", limit: 500 }).maxPosts, 30); // A first fetch, a full re-walk: from the top, no stop at what is known; as many posts as its budget has files. assert.deepEqual(planInstagramRun({}), { mode: "walk", maxPosts: 120, maxRequests: 7, stop: "none", media: WALK }); assert.equal(planInstagramRun({ stopAtKnown: true }).stop, "none"); // A resumed backfill: from its cursor. assert.deepEqual(planInstagramRun({ cursor: "abc_1" }), { mode: "walk", maxPosts: 120, maxRequests: 7, cursor: "abc_1", stop: "none", media: WALK }); // A walk is never under two pages (a one-page walk logs no resume point), never over its budget. assert.equal(planInstagramRun({ limit: 10 }).maxPosts, 60); assert.equal(planInstagramRun({ limit: 5000 }).maxPosts, 120); // A SYNC THAT CONTINUES: a walk that ends at the WATERMARK, never at the posts it archived itself. assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", cursor: INSTAGRAM_FROM_TOP_CURSOR }), { mode: "walk", maxPosts: 120, maxRequests: 7, stop: "watermark", media: WALK, }); assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", cursor: "page-3" }), { mode: "walk", maxPosts: 120, maxRequests: 7, cursor: "page-3", stop: "watermark", media: WALK, }); const args = buildInstagramGalleryDlArgs({ handle: IG_HANDLE, cookies: "firefox:ig-profile", plan: planInstagramRun({ cursor: "abc_1" }) }); assert.deepEqual(args, [ "--config-ignore", "--no-input", "--no-colors", "--dump-json", "--verbose", "-o", "output.num-to-str=true", "-o", "extractor.instagram.retries=0", "-o", "extractor.instagram.videos=merged", "-o", "extractor.instagram.max-posts=120", "-o", "extractor.instagram.cursor=abc_1", "--cookies-from-browser", "firefox:ig-profile", `https://www.instagram.com/${IG_HANDLE}/posts/`, ]); const file = buildInstagramGalleryDlArgs({ handle: IG_HANDLE, cookies: "file:/data/ig.txt", plan: planInstagramRun({ since: "x" }) }); assert.deepEqual(file.slice(-3), ["--cookies", "/data/ig.txt", `https://www.instagram.com/${IG_HANDLE}/posts/`]); // Streaming output would hide the exception: never asked for. assert.ok(!args.join(" ").includes("jsonl")); assert.ok(!args.includes("--no-download")); }); test("SYNC NEW: stops at the first archived post, skipping the pinned ones on top; one page, two requests", async () => { const rows = igRows([ { n: 2, date: "2025-06-01 00:00:00", pinned: true }, // pinned and archived: no stop { n: 50, date: "2026-03-09 00:00:00", pinned: true, media: ["image", "image"] }, // pinned and new: archived { n: 49, date: "2026-03-08 00:00:00", media: ["video"] }, { n: 48, date: "2026-03-07 00:00:00" }, // archived: the stop { n: 47, date: "2026-03-06 00:00:00" }, // below the stop: never read as new ]); const h = harness({ rows, stderr: [...lookup, page] }); const r = await fetchInstagramPosts( input(h, { since: "2026-03-07T00:00:00.000Z", seenIds: new Set([igPk(2), igPk(48)]) }), h.deps, ); assert.equal(r.complete, true); assert.equal(r.error, undefined); assert.deepEqual(r.posts.map((p) => p.id), [igPk(50), igPk(49)]); assert.deepEqual(r.media?.map((m) => [m.id, m.files.length]), [[igPk(50), 2], [igPk(49), 1]]); assert.equal(r.requests, 2); assert.equal(r.cursor, undefined); assert.ok(h.runs[0]!.args.includes("extractor.instagram.max-posts=30")); // A clean read is noted (it settles a pending signal); no cooldown. assert.deepEqual(h.outcomes, [{ url: URL_, channel: "example-ig" }]); assert.equal(h.rateLimits, 0); assert.ok(h.log.some((l) => l === "Cost: 2 request(s) to Instagram (1 for the account's id, 1 feed page(s)).")); assert.ok(h.log.some((l) => /gallery-dl listed 5 post\(s\): 2 new, 2 already archived/.test(l))); }); test("SYNC NEW: a post older than the watermark stops it even when it is not archived", async () => { const rows = igRows([{ n: 9, date: "2026-03-09 00:00:00" }, { n: 3, date: "2026-03-03 00:00:00" }]); const h = harness({ rows, stderr: [page] }); const r = await fetchInstagramPosts(input(h, { since: "2026-03-05T00:00:00.000Z", seenIds: new Set([igPk(4)]) }), h.deps); assert.deepEqual(r.posts.map((p) => p.id), [igPk(9)]); assert.equal(r.complete, true); }); // THE GAP (review 1, M1). Post n is dated n days after 2020-01-01; the archive // holds posts up to n = 100 (the watermark W), and the account then posts // 101..180 before the next sync. const W = "2020-04-10T00:00:00.000Z"; // post 100's date const archived = (...extra: number[]) => new Set([...days(100, 100).map((p) => igPk(p.n)), ...extra.map(igPk)]); const range = (from: number, to: number) => Array.from({ length: from - to + 1 }, (_, i) => from - i); test("SYNC NEW: a whole page of new posts and none archived is not caught up — the next sync walks on from the top", async () => { const h = harness({ rows: igRows(days(180, 30)), stderr: [...lookup, page] }); const r = await fetchInstagramPosts(input(h, { since: W, seenIds: archived() }), h.deps); assert.deepEqual(r.posts.map((p) => p.id), range(180, 151).map(igPk)); assert.equal(r.complete, false); assert.equal(r.cursor, INSTAGRAM_FROM_TOP_CURSOR); assert.equal(r.error, undefined); assert.ok(h.log.some((l) => /older new posts may lie below it/.test(l))); }); test("A SYNC THAT CONTINUES skips the posts it archived and stops only at the watermark: more than 30 new posts between two syncs are all fetched", async () => { // Run 2: from the top again (no gallery-dl cursor). Page 1 is the 30 posts run 1 archived; the gap is below them. const stderr = [page, igCursorLine("page-2"), page, igCursorLine("page-3"), page, igCursorLine("page-4"), page]; const h = harness({ rows: igRows(days(180, 100)), stderr }); const r = await fetchInstagramPosts( input(h, { since: W, cursor: INSTAGRAM_FROM_TOP_CURSOR, stopAtKnown: true, seenIds: archived(...range(180, 151)) }), h.deps, ); assert.ok(!h.runs[0]!.args.some((a) => a.includes("extractor.instagram.cursor"))); // Everything between the first page and the watermark, none of it dropped, none of it twice. assert.deepEqual(r.posts.map((p) => p.id), range(150, 101).map(igPk)); assert.equal(r.complete, true, "it reached the watermark"); assert.equal(r.cursor, undefined); assert.equal(r.error, undefined); assert.ok(h.log.some((l) => /gallery-dl listed 100 post\(s\): 50 new, 31 already archived/.test(l))); // The same from a REAL cursor: the walk starts below what run 1 read and still ends at the watermark only. const h2 = harness({ rows: igRows(days(150, 70)), stderr: [page, igCursorLine("page-3"), page, igCursorLine("page-4"), page] }); const r2 = await fetchInstagramPosts( input(h2, { since: W, cursor: "page-2", seenIds: archived(...range(180, 151), ...range(150, 141)) }), h2.deps, ); assert.ok(h2.runs[0]!.args.includes("extractor.instagram.cursor=page-2")); assert.deepEqual(r2.posts.map((p) => p.id), range(140, 101).map(igPk)); assert.equal(r2.complete, true); }); test("A SYNC THAT CONTINUES and is capped mid-gap keeps its place: the next run goes on from there, to the watermark", async () => { // 300 new posts (101..400) since the watermark; run 1 archived 400..371. Run 2 lists 120 and is not at the watermark yet. const stderr = [page, igCursorLine("page-2"), page, igCursorLine("page-3"), page, igCursorLine("page-4"), page]; const h = harness({ rows: igRows(days(400, 120)), stderr }); const seen = archived(...range(400, 371)); const r = await fetchInstagramPosts(input(h, { since: W, cursor: INSTAGRAM_FROM_TOP_CURSOR, seenIds: seen }), h.deps); assert.deepEqual(r.posts.map((p) => p.id), range(370, 281).map(igPk)); assert.equal(r.complete, false); assert.equal(r.cursor, "page-4", "the page it ended inside"); assert.equal(r.error, undefined); // Run 3 from that cursor: re-reads the page (skipped as archived) and goes on. const h3 = harness({ rows: igRows(days(310, 120)), stderr: [page, igCursorLine("page-5"), page, igCursorLine("page-6"), page, igCursorLine("page-7"), page] }); const r3 = await fetchInstagramPosts(input(h3, { since: W, cursor: "page-4", seenIds: new Set([...seen, ...range(370, 281).map(igPk)]) }), h3.deps); assert.deepEqual(r3.posts.map((p) => p.id), range(280, 191).map(igPk)); assert.equal(r3.cursor, "page-7"); assert.equal(r3.complete, false); }); test("A SYNC THAT CONTINUES and meets a 429 mid-gap keeps what it read and its place; the run after the hold finishes the gap", async () => { const h = harness({ rows: [...igRows(days(180, 60)), igError("HttpError", `'429 Too Many Requests' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30&max_id=page-3'`)], stderr: [page, igCursorLine("page-2"), page, igCursorLine("page-3"), igRequestLine(`${igFeedPath()}&max_id=page-3`, 429)], }); const seen = archived(...range(180, 151)); const r = await fetchInstagramPosts(input(h, { since: W, cursor: INSTAGRAM_FROM_TOP_CURSOR, seenIds: seen }), h.deps); assert.equal(r.block, "blocked"); assert.deepEqual(r.posts.map((p) => p.id), range(150, 121).map(igPk)); assert.equal(r.cursor, "page-3"); assert.equal(h.rateLimits, 1); assert.equal(h.runs[0]!.stops, 1, "the 429's own request line ended the run"); // After the hold: from page-3 down to the watermark. const h2 = harness({ rows: igRows(days(120, 60)), stderr: [page, igCursorLine("page-4"), page] }); const r2 = await fetchInstagramPosts(input(h2, { since: W, cursor: "page-3", seenIds: new Set([...seen, ...range(150, 121).map(igPk)]) }), h2.deps); assert.deepEqual(r2.posts.map((p) => p.id), range(120, 101).map(igPk)); assert.equal(r2.complete, true); }); test("A WALK: 120 posts and more behind them — it stops, and resumes from the last cursor gallery-dl logged", async () => { const stderr = [...lookup]; for (let i = 1; i <= 4; i++) { stderr.push(page); if (i < 4) stderr.push(igCursorLine(`page-${i + 1}`)); } const h = harness({ rows: igRows(days(400, 120)), stderr }); const r = await fetchInstagramPosts(input(h), h.deps); assert.equal(r.posts.length, 120); assert.equal(r.complete, false); assert.equal(r.cursor, "page-4"); assert.equal(r.requests, 5); assert.deepEqual(r.mediaBudget, { maxFiles: 120, maxBytes: 600 * 1024 * 1024 }); assert.equal(h.runs[0]!.stops, 0, "five requests are under the cap of 7"); // The resumed walk re-reads that page: archived posts do not stop it. const h2 = harness({ rows: igRows(days(130, 40)), stderr: [page, igCursorLine("page-5"), page] }); const r2 = await fetchInstagramPosts(input(h2, { cursor: "page-4", stopAtKnown: true, seenIds: new Set(days(130, 30).map((p) => igPk(p.n))) }), h2.deps); assert.ok(h2.runs[0]!.args.includes("extractor.instagram.cursor=page-4")); assert.equal(r2.posts.length, 10); // Fewer than it asked for: the account's first post is reached. assert.equal(r2.complete, true); }); test("A WALK IS SIZED TO ITS MEDIA: posts whose media would not fit the job's 120 files are left for the next run, which lists them again", async () => { // 120 posts of 3 media each: 360 files. Only the first 40 posts' media fit. const posts = days(400, 120, { media: ["image", "image", "video"] }); const stderr = [page, igCursorLine("page-2"), page, igCursorLine("page-3"), page, igCursorLine("page-4"), page]; const h = harness({ rows: igRows(posts), stderr }); const r = await fetchInstagramPosts(input(h), h.deps); assert.deepEqual(r.posts.map((p) => p.id), range(400, 361).map(igPk)); assert.equal(r.media!.reduce((n, m) => n + m.files.length, 0), 120); assert.equal(r.complete, false); // The next run starts where this one did (the top): no page size is assumed. assert.equal(r.cursor, INSTAGRAM_FROM_TOP_CURSOR); assert.equal(r.error, undefined); assert.ok(h.log.some((l) => /80 of the 120 new post\(s\) listed are left for the next run: their media would not fit this job's budget of 120 files/.test(l))); // A cut on the first page resumes where the run began (the top), and still moves on: the posts before the cut are archived. const h2 = harness({ rows: igRows(days(400, 60, { media: Array(10).fill("image") })), stderr: [page, igCursorLine("page-2"), page] }); const r2 = await fetchInstagramPosts(input(h2), h2.deps); assert.equal(r2.posts.length, 12); assert.equal(r2.cursor, INSTAGRAM_FROM_TOP_CURSOR); // A sync is one page and is never trimmed: what does not fit its 40 files is owed by the media half. const h3 = harness({ rows: igRows(days(130, 30, { media: ["image", "image"] })), stderr: [page] }); const r3 = await fetchInstagramPosts(input(h3, { since: W, seenIds: archived() }), h3.deps); assert.equal(r3.posts.length, 30); assert.deepEqual(r3.mediaBudget, { maxFiles: 40, maxBytes: 200 * 1024 * 1024 }); }); // Review 2, N2: a page is not always 30 posts. A trimmed walk resumes from its // OWN start, so the posts it left behind are listed again whatever a page held. test("A TRIMMED WALK over 33-post pages loses nothing: run after run from the same start, every post is archived once", async () => { // 132 posts in pages of 33, each a carousel of 3: 40 posts' media fit a run. const all = days(132, 132, { media: ["image", "image", "video"] }); const pagesOf33 = [page, igCursorLine("p2"), page, igCursorLine("p3"), page, igCursorLine("p4"), page]; const seen = new Set(); const got: string[] = []; let cursor: string | undefined; let complete = false; for (let run = 0; run < 8 && !complete; run++) { // gallery-dl lists up to 120 posts from where the run starts: the top, or page k (33 posts a page). const startRow = cursor && cursor !== INSTAGRAM_FROM_TOP_CURSOR ? (Number(cursor.slice(1)) - 1) * 33 : 0; const listed = all.slice(startRow, startRow + 120); const h = harness({ rows: igRows(listed), stderr: pagesOf33.slice(0, Math.max(1, Math.ceil(listed.length / 33) * 2 - 1)) }); const r = await fetchInstagramPosts(input(h, { seenIds: new Set(seen), ...(cursor ? { cursor } : {}) }), h.deps); assert.equal(r.error, undefined); assert.ok(r.posts.length > 0 || r.complete || r.cursor !== cursor, `run ${run} made no progress`); for (const p of r.posts) { assert.ok(!seen.has(p.id), `post ${p.id} archived twice`); seen.add(p.id); got.push(p.id); } assert.ok((r.media ?? []).reduce((n, m) => n + m.files.length, 0) <= 120); cursor = r.cursor; complete = r.complete; } assert.equal(complete, true); // Every post, in order, none skipped: with the old page arithmetic posts 121..132 of a page past row 99 were lost. assert.deepEqual(got, all.map((p) => igPk(p.n))); }); test("A REFUSAL DURING THE ACCOUNT LOOKUP ends the run: gallery-dl swallows it and would go on to the feed", async () => { // A 429 on the search: gallery-dl would try the profile page next, and then the feed. const h = harness({ rows: igRows(days(10, 3)), stderr: [igRequestLine(igSearchPath(), 429), igRequestLine(`/${IG_HANDLE}`, 200), page] }); const r = await fetchInstagramPosts(input(h), h.deps); assert.equal(h.runs[0]!.stops, 1, "stopped at the first refusal line"); assert.equal(r.block, "blocked"); assert.match(r.error!, /Instagram refused the read \(GET \/web\/search\/topsearch\/ answered 429\): a rate limit/); assert.equal(h.rateLimits, 1); assert.deepEqual(h.outcomes, [], "a 429 is a hold, never the alert"); // The profile page redirected to the login page: no error row says so (the lookup's exception is swallowed). const login = harness({ rows: [igError("NotFoundError", "Requested user could not be found")], stderr: [igRequestLine(igSearchPath(), 404), igRequestLine(`/${IG_HANDLE}`, 302), igRequestLine("/accounts/login/?next=%2Fexample.account%2F", 200)], }); const l = await fetchInstagramPosts(input(login), login.deps); assert.equal(login.runs[0]!.stops, 1); assert.equal(l.block, "login"); assert.equal(login.outcomes[0]!.kind, "auth-failure"); assert.match(login.outcomes[0]!.challengeLine!, /the login page/); // A challenge page during the lookup, with an error row that says something else entirely. const ch = harness({ rows: igRows(days(10, 3)), stderr: [igRequestLine(igSearchPath(), 302), igRequestLine("/challenge/?next=/", 200), page] }); const c = await fetchInstagramPosts(input(ch), ch.deps); assert.equal(c.block, "challenge"); assert.equal(ch.outcomes[0]!.kind, "challenge"); // LOGGED OUT the search's 404 is not a refusal by itself: the run goes on (and the feed's 404 is then the login). const out = harness({ rows: igRows(days(10, 3)), stderr: [igRequestLine(igSearchPath(), 404), igRequestLine(`/${IG_HANDLE}`, 200), page] }); const o = await fetchInstagramPosts(input(out), out.deps); assert.equal(out.runs[0]!.stops, 0); assert.equal(o.block, undefined); assert.equal(o.posts.length, 3); }); test("ONE 401/403 holds Instagram for the hour; a SECOND with no clean read between raises the alert instead", async () => { const row = igError("HttpError", `'401 Unauthorized' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30'`); const first = harness({ rows: [row], stderr: [igRequestLine(igFeedPath(), 401)] }); const r1 = await fetchInstagramPosts(input(first), first.deps); assert.equal(r1.block, "blocked"); assert.match(r1.error!, /a rate limit\. .*no Instagram job starts before 13:00 UTC/); assert.equal(first.rateLimits, 1); assert.equal(first.outcomes[0]!.kind, "refusal", "noted, pending"); assert.equal(r1.needsCookies, undefined); // The second: the alert is up after it is noted. const second = harness({ rows: [row], stderr: [igRequestLine(igFeedPath(), 403)] }); second.alert = true; const r2 = await fetchInstagramPosts(input(second), second.deps); assert.equal(r2.block, "blocked"); assert.match(r2.error!, /refused the read a second time in a row/); assert.match(r2.error!, /Instagram's alert is up/); assert.equal(second.rateLimits, 0, "not another hourly hold"); assert.equal(r2.needsCookies, true); // A 429 is never noted for the alert, however many. const many = harness({ rows: [], stderr: [igRequestLine(igFeedPath(), 429)] }); many.alert = true; await fetchInstagramPosts(input(many), many.deps); assert.deepEqual(many.outcomes, []); assert.equal(many.rateLimits, 1); }); test("NO request line read is a failure whatever was printed: never a clean read, never complete", async () => { const h = harness({ rows: igRows(days(10, 3)), stderr: ["[instagram][debug] Sleeping 8.83 seconds (request)"] }); const r = await fetchInstagramPosts(input(h), h.deps); assert.match(r.error!, /None of gallery-dl's requests could be read from its log/); assert.equal(r.complete, false); assert.equal(r.posts.length, 3, "what it printed is kept"); assert.deepEqual(h.outcomes, [], "no clean read is noted"); // …and with NOTHING printed too: an empty listing with no request seen is not "the account has no posts". const empty = harness({ rows: [], stderr: [] }); const e = await fetchInstagramPosts(input(empty), empty.deps); assert.match(e.error!, /None of gallery-dl's requests could be read/); assert.equal(e.complete, false); assert.deepEqual(empty.outcomes, []); // A sync that printed only archived posts and showed no request is not "caught up" either. const known = harness({ rows: igRows(days(10, 3)), stderr: [] }); const k = await fetchInstagramPosts(input(known, { since: "2020-01-02T00:00:00.000Z", seenIds: new Set(days(10, 3).map((p) => igPk(p.n))) }), known.deps); assert.equal(k.complete, false); assert.match(k.error!, /None of gallery-dl's requests/); }); // Review 2, N6: only a run that ended by itself counts as the clean read that // forgets a pending 401/403. test("a cancelled, drained, timed-out or over-cap run that printed rows is not a clean read", async () => { const rows = igRows(days(20, 10)); const ac = new AbortController(); ac.abort(); const cancelled = harness({ rows, stderr: [page], out: { canceled: true } }); const c = await fetchInstagramPosts(input(cancelled, { signal: ac.signal }), cancelled.deps); assert.deepEqual([c.complete, c.posts.length, c.error], [false, 10, undefined]); assert.deepEqual(cancelled.outcomes, [], "cancelled: no clean read noted"); const timed = harness({ rows, stderr: [page], out: { timedOut: true } }); assert.equal((await fetchInstagramPosts(input(timed), timed.deps)).complete, false); assert.deepEqual(timed.outcomes, []); const drain = new AbortController(); drain.abort(); const drained = harness({ rows, stderr: [page] }); const d = await fetchInstagramPosts(input(drained, { drain: drain.signal }), drained.deps); assert.deepEqual([d.complete, d.drained], [false, true]); assert.deepEqual(drained.outcomes, []); const capped = harness({ rows, stderr: [page, page, page, page] }); const o = await fetchInstagramPosts(input(capped, { since: "2020-01-01T00:00:00.000Z", seenIds: new Set(["1"]) }), capped.deps); assert.equal(capped.runs[0]!.stops, 1); assert.equal(o.complete, false); assert.deepEqual(capped.outcomes, [], "over its request cap: no clean read noted"); // A run that ended by itself is one: at the account's end… const ended = harness({ rows, stderr: [page] }); assert.equal((await fetchInstagramPosts(input(ended), ended.deps)).complete, true); assert.equal(ended.outcomes.length, 1); assert.equal(ended.outcomes[0]!.challengeLine, undefined); // …and at its own cap of posts. const atCap = harness({ rows: igRows(days(400, 120)), stderr: [page, igCursorLine("page-2"), page, igCursorLine("page-3"), page, igCursorLine("page-4"), page] }); const a = await fetchInstagramPosts(input(atCap), atCap.deps); assert.equal(a.complete, false); assert.equal(atCap.outcomes.length, 1); }); test("a run is stopped at its request cap, whatever Instagram's page size", async () => { // A sync that somehow sends a fourth request. const h = harness({ rows: igRows(days(20, 10)), stderr: [igRequestLine(igSearchPath(), 404), igRequestLine(`/${IG_HANDLE}`, 200), page, page] }); const r = await fetchInstagramPosts(input(h, { since: "2020-01-01T00:00:00.000Z", seenIds: new Set(["1"]) }), h.deps); assert.equal(h.runs[0]!.stops, 1); assert.equal(r.complete, false); assert.equal(r.posts.length, 10); assert.ok(h.log.some((l) => /Stopped at 4 requests, this run's cap/.test(l))); // A request to another host (the CDN, were one made) is not Instagram's API. const other = harness({ rows: igRows(days(20, 2)), stderr: ['[urllib3.connectionpool][debug] https://cdn.example.invalid:443 "GET /a.jpg HTTP/1.1" 200 None', page], }); assert.equal((await fetchInstagramPosts(input(other), other.deps)).requests, 1); }); test("A DEAD OR MISSING SESSION: the search's 404 and the feed's 404 are the login — the alert, never 'account gone'", async () => { const h = harness({ rows: [igError("HttpError", `'404 Not Found' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30'`)], stderr: [igRequestLine(igSearchPath(), 404), igRequestLine(`/${IG_HANDLE}`, 200), igRequestLine(igFeedPath(), 404)], }); const r = await fetchInstagramPosts(input(h), h.deps); assert.equal(r.block, "login"); assert.equal(r.needsCookies, true); assert.equal(r.complete, false); assert.deepEqual(r.posts, []); assert.equal(r.requests, 3); assert.match(r.error!, /did not accept the login/); assert.match(r.error!, /no Instagram job starts until/); assert.match(r.error!, /Nothing retries by itself/); assert.equal(h.outcomes.length, 1); assert.equal(h.outcomes[0]!.kind, "auth-failure"); assert.match(h.outcomes[0]!.challengeLine!, /^HttpError: '404 Not Found'/); assert.equal(h.rateLimits, 0); assert.equal(h.runs.length, 1, "one run, never a second try"); }); test("a challenge or checkpoint redirect raises the alert as a challenge; a login redirect as a login failure", async () => { const challenge = harness({ rows: [igError("AbortExtraction", "HTTP redirect to challenge page (https://www.instagram.com/challenge/)")], stderr: [page] }); const r = await fetchInstagramPosts(input(challenge), challenge.deps); assert.equal(r.block, "challenge"); assert.match(r.error!, /challenge or checkpoint page/); assert.equal(challenge.outcomes[0]!.kind, "challenge"); const login = harness({ rows: [igError("AbortExtraction", "HTTP redirect to login page (https://www.instagram.com/accounts/login/)")], stderr: [page] }); const r2 = await fetchInstagramPosts(input(login), login.deps); assert.equal(r2.block, "login"); assert.equal(login.outcomes[0]!.kind, "auth-failure"); }); test("THE FIRST 429 ENDS THE RUN: what was read is kept with its resume point, Instagram cools down for an hour, nothing is retried", async () => { const h = harness({ rows: [...igRows(days(100, 30)), igError("HttpError", `'429 Too Many Requests' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30&max_id=page-2'`)], stderr: [...lookup, page, igCursorLine("page-2"), igRequestLine(`${igFeedPath()}&max_id=page-2`, 429)], }); const r = await fetchInstagramPosts(input(h), h.deps); assert.equal(r.block, "blocked"); assert.equal(r.posts.length, 30); assert.equal(r.cursor, "page-2"); assert.equal(r.complete, false); assert.equal(r.needsCookies, undefined); assert.match(r.error!, /a rate limit/); assert.match(r.error!, /no Instagram job starts before 13:00 UTC \(60 min\)/); assert.equal(h.rateLimits, 1); assert.equal(h.runs.length, 1); // Not an alert: the cookies are not the fix. assert.deepEqual(h.outcomes, []); // A 401 ("please wait a few minutes") is the same. const h401 = harness({ rows: [igError("HttpError", `'401 Unauthorized' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30'`)], stderr: [page] }); assert.equal((await fetchInstagramPosts(input(h401), h401.deps)).block, "blocked"); assert.equal(h401.rateLimits, 1); }); test("the job log never prints the cookie source", async () => { const h = harness({ rows: igRows(days(10, 3)), stderr: [page] }); await fetchInstagramPosts(input(h, { cookies: "file:/home/someone/secret-ig-cookies.txt" }), h.deps); assert.ok(h.log.some((l) => l.startsWith("Instagram login: the channel's own cookie source, read by gallery-dl."))); assert.ok(!h.log.join("\n").includes("secret-ig-cookies")); assert.ok(!h.log.join("\n").includes("/home/someone")); }); test("a private account, and an account that is gone: a sentence each, no alert, no cooldown", async () => { const priv = harness({ rows: [], stderr: [...lookup, `[instagram][warning] ${IG_HANDLE}'s posts are private`, page] }); const r = await fetchInstagramPosts(input(priv), priv.deps); assert.match(r.error!, /is a private account and this channel's login does not follow it/); assert.equal(r.block, undefined); assert.deepEqual(priv.outcomes, []); // A private feed answered with a 404 (or any error row) is still the private sentence for that channel: no alert, no hold. const priv404 = harness({ rows: [igError("HttpError", `'404 Not Found' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30'`)], stderr: [...lookup, `[instagram][warning] ${IG_HANDLE}'s posts are private`, igRequestLine(igFeedPath(), 404)], }); const p4 = await fetchInstagramPosts(input(priv404), priv404.deps); assert.match(p4.error!, /is a private account/); assert.equal(p4.block, undefined); assert.deepEqual(priv404.outcomes, []); assert.equal(priv404.rateLimits, 0); // …unless it came with a 429: that is the platform's hold. const priv429 = harness({ rows: [], stderr: [...lookup, `[instagram][warning] ${IG_HANDLE}'s posts are private`, igRequestLine(igFeedPath(), 429)] }); assert.equal((await fetchInstagramPosts(input(priv429), priv429.deps)).block, "blocked"); assert.equal(priv429.rateLimits, 1); const gone = harness({ rows: [igError("NotFoundError", "Requested user could not be found")], stderr: [igRequestLine(igSearchPath(), 200), igRequestLine(`/${IG_HANDLE}`, 404)], }); const g = await fetchInstagramPosts(input(gone), gone.deps); assert.equal(g.block, "not-found"); assert.match(g.error!, /its own page answered 404/); assert.deepEqual(gone.outcomes, []); assert.equal(gone.rateLimits, 0); // The lookup failed and the page did not say 404: not proven gone — the login. const unsure = harness({ rows: [igError("NotFoundError", "Requested user could not be found")], stderr: [igRequestLine(igSearchPath(), 404), igRequestLine(`/${IG_HANDLE}`, 302)] }); assert.equal((await fetchInstagramPosts(input(unsure), unsure.deps)).block, "login"); }); test("a 5xx or a crash is a plain failure that keeps what it read", async () => { const h = harness({ rows: [...igRows(days(10, 3)), igError("HttpError", `'500 Internal Server Error' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/'`)], stderr: [page] }); const r = await fetchInstagramPosts(input(h), h.deps); assert.match(r.error!, /^gallery-dl failed: HttpError: '500/); assert.equal(r.posts.length, 3); assert.equal(r.block, undefined); assert.equal(h.rateLimits, 0); assert.deepEqual(h.outcomes, []); }); test("a run cancelled before gallery-dl printed anything reads nothing and keeps the resume point it had", async () => { const ac = new AbortController(); ac.abort(); const h = harness({ stdout: "\nKeyboardInterrupt", out: { canceled: true } }); const r = await fetchInstagramPosts(input(h, { cursor: "page-4", signal: ac.signal }), h.deps); assert.deepEqual(r, { posts: [], complete: false, cursor: "page-4" }); const garbled = harness({ stdout: "Traceback (most recent call last)" }); assert.match((await fetchInstagramPosts(input(garbled), garbled.deps)).error!, /printed nothing this reads/); // The binary is missing: thrown, as X's fetcher does. const missing = harness({ out: { spawnError: 'gallery-dl not found (looked for "x"; set GALLERY_DL_BIN)' } }); await assert.rejects(fetchInstagramPosts(input(missing), missing.deps), /gallery-dl not found/); });