// INSTAGRAM ACCOUNTS AS POSTS CHANNELS (lane instagram), end to end. // // Instagram is NEVER contacted. Every fetch runs against // e2e/fixtures/bin/fake-gallery-dl.mjs (its Instagram mode, // fake-gallery-dl-instagram.mjs), which prints what gallery-dl 1.32.9 prints // with `--dump-json --verbose`; the media CDN is played back by the test // server (common/social/instagramMedia.ts fakeInstagramMediaFetch). Every // account, id and address is invented. // // Same token as /api/ops/* (WORKER_TOKEN=test-worker-token on the test server). import { readFile, readdir } from "node:fs/promises"; import { test, expect, type APIRequestContext } from "@playwright/test"; import { generateReport, pathExists, readJson, resetData, resolvePath, testPaths, writeSettings } from "./helpers"; import { baseUrl } from "./baseUrl"; const AUTH = { authorization: "Bearer test-worker-token" }; const COOKIES = "file:/nonexistent/instagram-archive-cookies.txt"; const pk = (n: number) => (3500000000000000000n + BigInt(n)).toString(); const channelRel = (slug: string, p: string) => `${testPaths().transcriptsDir}/channels/${slug}/${p}`; type Answer = { status: number; body: { ok?: boolean; jobId?: string; error?: string; result?: string; message?: string; slug?: string } }; async function ops(request: APIRequestContext, action: string, data: Record): Promise { const res = await request.post(`${baseUrl}/api/ops/${action}`, { headers: AUTH, data }); return { status: res.status(), body: (await res.json()) as Answer["body"] }; } async function waitJob(request: APIRequestContext, jobId: string, timeout = 90_000): Promise { let status = ""; await expect .poll( async () => { const r = await request.get(`${baseUrl}/api/ops/job/${jobId}`, { headers: AUTH }); status = ((await r.json()) as { job?: { status?: string } }).job?.status ?? ""; return ["done", "failed", "cancelled"].includes(status); }, { timeout }, ) .toBe(true); return status; } const jobLog = (jobId: string) => readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${jobId}.log`), "utf8"); async function archivedIds(slug: string): Promise { if (!(await pathExists(channelRel(slug, "posts-archive")))) return []; // One line per post: " ". return (await readFile(resolvePath(channelRel(slug, "posts-archive")), "utf8")) .split("\n") .filter(Boolean) .map((l) => { expect(l.startsWith("instagram ")).toBe(true); return l.slice("instagram ".length); }); } async function makeChannel(request: APIRequestContext, slug: string, handle: string, cookies = true): Promise { const made = await ops(request, "create-channel", { slug, fields: { name: `${handle} (Instagram)`, handling: "transcribe", url: `https://www.instagram.com/${handle}/`, sourceKind: "social", postFetcher: "instagram-gallery-dl", }, }); expect(made.body).toMatchObject({ ok: true, slug }); if (cookies) { const set = await ops(request, "channel-config", { slug, patch: { cookiesFromBrowser: COOKIES } }); expect(set.body.ok).toBe(true); } } test("an Instagram URL derives a posts channel offline and asks for its cookie source in the Source section", async ({ page }) => { await resetData("empty"); await generateReport(page, "new"); await page.goto("/channels/new"); await page.locator('input[name="url"]').fill("https://www.instagram.com/ig_fake/"); await expect(page.locator('select[name="platform"]')).toHaveValue("instagram"); await expect(page.locator('input[name="socialHandle"]')).toHaveValue("ig_fake"); await expect(page.locator('input[name="postFetcher"]')).toHaveValue("instagram-gallery-dl"); // No video controls, and ONE cookie field — required, and its help says the trade. await expect(page.locator('select[name="audioFormat"]')).toHaveCount(0); const cookies = page.locator('input[name="cookiesFromBrowser"]'); await expect(cookies).toHaveCount(1); await expect(cookies).toBeVisible(); await expect(page.getByText(/Use an account made for the archive: Instagram may checkpoint or ban an account that reads this way/)).toBeVisible(); // A post's URL is not an account. await page.locator('input[name="url"]').fill("https://www.instagram.com/p/CabcDEF1234/"); await expect(page.locator('input[name="socialHandle"]')).toHaveValue(""); }); test("no cookie source, nothing is asked; with one, a walk archives posts and their media, a capped walk resumes from its cursor, and a sync reads one page", async ({ page, request, }) => { test.setTimeout(240_000); await resetData("empty"); await writeSettings({ minFreeDiskGB: 0, cookiesFromBrowser: "firefox", cookieMode: "always" }); const slug = "ig-fake"; await makeChannel(request, slug, "ig_fake", false); const config = await readJson>(channelRel(slug, "config.json")); expect(config).toMatchObject({ sourceKind: "social", platform: "instagram", postFetcher: "instagram-gallery-dl", socialHandle: "ig_fake" }); // The global browser is not borrowed: refused before a job exists. const none = await ops(request, "fetch-posts", { slug }); expect(none.status).toBe(400); expect(none.body.error).toMatch(/ig-fake has no cookie source of its own, and Instagram shows an account's posts only to a login/); expect(none.body.error).toMatch(/Set "Cookies from browser" on the channel's Edit form/); expect((await ops(request, "fetch-posts", { slug, retryOnBlock: { minutes: 30, max: 3 } })).body.error).toMatch( /Retry on a block is not for Instagram/, ); await generateReport(page, slug); await page.goto(`/channels/${slug}`); await expect(page.getByText("not set: nothing is fetched until Cookies from browser is set on the Edit form")).toBeVisible(); // Its own cookie source: the first fetch is a walk, capped here at 60 posts (two pages). expect((await ops(request, "channel-config", { slug, patch: { cookiesFromBrowser: COOKIES } })).body.ok).toBe(true); // On Instagram's queue and no other: a queue override would run it beside the job there, with no gap. for (const action of ["fetch-posts", "resume-backfill"]) { const side = await ops(request, action, { slug, queueKey: "side" }); expect(side.status).toBe(400); expect(side.body.error).toMatch(/ig-fake is an Instagram channel: its jobs run on platform:instagram and nowhere else .*the queue override "side" is refused/); } const walk = await ops(request, "fetch-posts", { slug, limit: 60 }); expect(walk.body.ok).toBe(true); expect(await waitJob(request, walk.body.jobId!)).toBe("done"); // 60 rows: the two pinned posts, then 58 by date — one of which is a pinned one again. const first = await archivedIds(slug); expect(first).toHaveLength(59); expect(first).toContain(pk(3)); // the old pinned post, far below the walk's reach const log = await jobLog(walk.body.jobId!); // The cookie source is never printed. expect(log).toContain("Instagram login: the channel's own cookie source, read by gallery-dl."); expect(log).not.toContain("instagram-archive-cookies"); expect(log).toContain("Walking up to 60 posts from the top."); expect(log).toContain("Cost: 3 request(s) to Instagram (1 for the account's id, 2 feed page(s))."); // A walk's posts get their media in the same run: 71 files, inside its budget of 120. expect(log).toMatch(/Media: 71 file\(s\) fetched from its CDN \(0 MB\); 59 of 59 post\(s\) whole\./); expect(log).toContain("This run cost Instagram 3 request(s) and its CDN 71 file(s)."); expect(log).toContain("more history remains"); const state = await readJson<{ backfill?: { cursor?: string } }>(channelRel(slug, "posts-state.json")); expect(state.backfill?.cursor).toBe("page-2"); // A carousel: one post, three media in order, a capture record, no screenshot. const posts = (await readFile(resolvePath(channelRel(slug, "posts/2026-03.jsonl")), "utf8")) .split("\n") .filter(Boolean) .map((l) => JSON.parse(l) as { id: string; platform: string; url: string; mediaCount?: number; instagram?: { kind: string; shortcode: string; pinned?: boolean }; media?: unknown }); const carousel = posts.find((p) => p.id === pk(70))!; expect(carousel).toMatchObject({ platform: "instagram", mediaCount: 3, instagram: { kind: "post", pinned: true } }); expect(carousel.url).toBe(`https://www.instagram.com/p/${carousel.instagram!.shortcode}/`); expect(carousel.media).toBeUndefined(); expect(JSON.stringify(posts)).not.toContain("cdn.example.invalid"); const files = (await readdir(resolvePath(channelRel(slug, `posts-media/${pk(70)}`)))).sort(); expect(files).toEqual([`01-${pk(7001)}.jpg`, `02-${pk(7002)}.mp4`, `03-${pk(7003)}.jpg`, "capture.json"]); const record = await readJson<{ state: string; mediaState: string; shot?: unknown; media: unknown[] }>( channelRel(slug, `posts-media/${pk(70)}/capture.json`), ); expect(record).toMatchObject({ state: "captured", mediaState: "ok" }); expect(record.shot).toBeUndefined(); expect(record.media).toHaveLength(3); // A reel is one video. expect(posts.find((p) => p.id === pk(63))?.instagram?.kind).toBe("reel"); // capture-posts takes no screenshot of an Instagram post, and says so. const shot = await ops(request, "capture-posts", { slug, ids: [pk(70)] }); expect(shot.body.error).toMatch(/takes no screenshot of an Instagram post/); // RESUME BACKFILL: from the cursor, re-reading that one page; fewer posts than asked for ends the walk. const resume = await ops(request, "fetch-posts", { slug, backfill: true, limit: 60 }); expect(resume.body.ok).toBe(true); expect(await waitJob(request, resume.body.jobId!)).toBe("done"); expect(await archivedIds(slug)).toHaveLength(75); const resumeLog = await jobLog(resume.body.jobId!); expect(resumeLog).toContain("Walking up to 60 posts from the saved resume point."); expect(resumeLog).toContain("Cost: 3 request(s) to Instagram (1 for the account's id, 2 feed page(s))."); expect((await readJson<{ backfill?: unknown }>(channelRel(slug, "posts-state.json"))).backfill).toBeUndefined(); // SYNC NEW: one page, the pinned posts skipped, stopped at the first archived post. await page.goto(`/channels/${slug}`); await expect(page.getByText("set on this channel")).toBeVisible(); const sync = await ops(request, "fetch-posts", { slug }); expect(sync.body.ok).toBe(true); expect(await waitJob(request, sync.body.jobId!)).toBe("done"); const syncLog = await jobLog(sync.body.jobId!); expect(syncLog).toContain("Reading one page (up to 30 posts) from the top."); expect(syncLog).toContain("Wrote 0 new post(s)"); expect(syncLog).toContain("This run cost Instagram 2 request(s) and its CDN 0 file(s)."); expect(await archivedIds(slug)).toHaveLength(75); }); test("a dead session, a challenge and a login page raise Instagram's alert, which refuses every Instagram job until a person's Recheck", async ({ page, request, }) => { test.setTimeout(240_000); await resetData("empty"); await writeSettings({ minFreeDiskGB: 0 }); await makeChannel(request, "ig-dead", "ig_loggedout"); await makeChannel(request, "ig-check", "ig_challenge"); await makeChannel(request, "ig-wall", "ig_loginwall"); await makeChannel(request, "ig-ok", "ig_fake"); // The session is not accepted: the search's and the feed's "Page Not Found" are the login, not a gone account. const dead = await ops(request, "fetch-posts", { slug: "ig-dead" }); expect(await waitJob(request, dead.body.jobId!)).toBe("failed"); const deadLog = await jobLog(dead.body.jobId!); expect(deadLog).toContain("Cost: 3 request(s) to Instagram (2 for the account's id, 1 feed page(s))."); expect(deadLog).toMatch(/Instagram did not accept the login .*HttpError: '404 Not Found'/); expect(deadLog).not.toMatch(/has no account/); // Every Instagram job is refused now, before it exists. const refused = await ops(request, "fetch-posts", { slug: "ig-ok" }); expect(refused.status).toBe(400); expect(refused.body.error).toMatch(/^Instagram answered with its login page at \d\d:\d\d UTC .*its alert is up, so no Instagram job starts/); // The banner, and the operator's Recheck (no request to Instagram). await page.goto(`${baseUrl}/`); const banner = page.getByRole("alert", { name: "Instagram cookies" }); await expect(banner).toContainText("Instagram needs fresh cookies: pass Instagram's check by hand"); await expect(banner).toHaveAttribute("data-state", "stale"); await banner.getByRole("button", { name: "Recheck" }).click(); await expect(banner).toHaveAttribute("data-state", "ok-again", { timeout: 30_000 }); // A challenge page: the same alert, as a challenge. const check = await ops(request, "fetch-posts", { slug: "ig-check" }); expect(check.body.ok).toBe(true); expect(await waitJob(request, check.body.jobId!)).toBe("failed"); expect(await jobLog(check.body.jobId!)).toMatch(/Instagram answered with a challenge or checkpoint page/); expect((await ops(request, "fetch-posts", { slug: "ig-ok" })).body.error).toMatch(/a challenge or checkpoint page at \d\d:\d\d UTC/); const recheck = await ops(request, "recheck-service", { service: "instagram" }); expect(recheck.body).toMatchObject({ ok: true, result: "clean" }); expect(recheck.body.message).toMatch(/no request sent/); // A redirect to the login page. const wall = await ops(request, "fetch-posts", { slug: "ig-wall" }); expect(await waitJob(request, wall.body.jobId!)).toBe("failed"); expect((await ops(request, "fetch-posts", { slug: "ig-ok" })).status).toBe(400); expect((await ops(request, "recheck-service", { service: "instagram" })).body.result).toBe("clean"); // Cleared: the good account is read. const ok = await ops(request, "fetch-posts", { slug: "ig-ok", limit: 60 }); expect(ok.body.ok).toBe(true); expect(await waitJob(request, ok.body.jobId!)).toBe("done"); }); test("the first 429 ends the run and holds Instagram for an hour; a private account and a gone account are a sentence each", async ({ request }) => { test.setTimeout(240_000); await resetData("empty"); await writeSettings({ minFreeDiskGB: 0 }); await makeChannel(request, "ig-private", "ig_private"); await makeChannel(request, "ig-gone", "ig_gone"); await makeChannel(request, "ig-limited", "ig_ratelimited"); await makeChannel(request, "ig-lookup", "ig_lookup429"); await makeChannel(request, "ig-ok", "ig_fake"); const priv = await ops(request, "fetch-posts", { slug: "ig-private" }); expect(await waitJob(request, priv.body.jobId!)).toBe("failed"); expect(await jobLog(priv.body.jobId!)).toMatch(/@ig_private is a private account and this channel's login does not follow it/); const gone = await ops(request, "fetch-posts", { slug: "ig-gone" }); expect(await waitJob(request, gone.body.jobId!)).toBe("failed"); expect(await jobLog(gone.body.jobId!)).toMatch(/Instagram has no account @ig_gone: its own page answered 404/); // Neither is the login's fault: no alert, the next job is not refused. const limited = await ops(request, "fetch-posts", { slug: "ig-limited" }); expect(limited.body.ok).toBe(true); expect(await waitJob(request, limited.body.jobId!)).toBe("failed"); const log = await jobLog(limited.body.jobId!); expect(log).toMatch(/Instagram refused the read \(GET \/api\/v1\/feed\/user\/\d+\/ answered 429\): a rate limit/); // After a refusal nothing more is asked of Instagram, its CDN included: the posts are archived, their media owed. expect(log).toMatch(/Media: none asked for\. Instagram refused the listing, so its CDN is not asked either; \d+ post\(s\) are archived with their media owed/); expect(log).toMatch(/This run cost Instagram 3 request\(s\) and its CDN 0 file\(s\)\./); const limitedIds = await archivedIds("ig-limited"); const owed = await readJson<{ mediaState: string; mediaOwed?: string; media: unknown[] }>( channelRel("ig-limited", `posts-media/${limitedIds[0]}/capture.json`), ); expect(owed).toMatchObject({ mediaState: "error", mediaOwed: "next", media: [] }); expect(log).toMatch(/no Instagram job starts before \d\d:\d\d UTC \(60 min\)\. Nothing retries by itself\./); // What the first page held is archived, with the resume point for the page that was refused. expect((await archivedIds("ig-limited")).length).toBeGreaterThan(20); expect((await readJson<{ backfill?: { cursor?: string } }>(channelRel("ig-limited", "posts-state.json"))).backfill?.cursor).toBe("page-2"); // Held: refused before a job exists, whichever Instagram channel asks. const held = await ops(request, "fetch-posts", { slug: "ig-ok" }); expect(held.status).toBe(400); expect(held.body.error).toMatch(/^Instagram answered a rate limit a short while ago: no Instagram job starts before \d\d:\d\d UTC/); // The operator's way out, by hand (the test server's state is shared by the specs after this one). const cleared = await ops(request, "clear-platform-hold", { platform: "instagram" }); expect(cleared.body.ok).toBe(true); const after = await ops(request, "fetch-posts", { slug: "ig-ok", limit: 60 }); expect(after.body.ok).toBe(true); expect(await waitJob(request, after.body.jobId!)).toBe("done"); // A 429 DURING THE ACCOUNT LOOKUP: gallery-dl swallows it and would go on to the feed. The run is stopped at that // line — one request — and Instagram is held, as for any 429. const lookup = await ops(request, "fetch-posts", { slug: "ig-lookup" }); expect(lookup.body.ok).toBe(true); expect(await waitJob(request, lookup.body.jobId!)).toBe("failed"); const lookupLog = await jobLog(lookup.body.jobId!); expect(lookupLog).toContain("Cost: 1 request(s) to Instagram (1 for the account's id, 0 feed page(s))."); expect(lookupLog).toMatch(/Instagram refused the read \(GET \/web\/search\/topsearch\/ answered 429\): a rate limit/); expect(await archivedIds("ig-lookup")).toHaveLength(0); expect((await ops(request, "fetch-posts", { slug: "ig-ok" })).body.error).toMatch(/^Instagram answered a rate limit a short while ago/); expect((await ops(request, "clear-platform-hold", { platform: "instagram" })).body.ok).toBe(true); // yt-dlp is never started on an instagram.com URL: import-video says so before a job exists. const reel = await ops(request, "import-video", { slug: "ig-ok", url: "https://www.instagram.com/reel/CabcDEF1234/" }); expect(reel.status).toBe(400); expect(reel.body.error).toMatch(/Instagram is read as a posts channel; a single reel import comes with a later slice/); });