Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit dbb9bddb21f3b88f562fabd3005292ab766d7df3
parent 5730b052e1ea9113d3848297fd27bf98198f51a9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 14:01:16 -0500

posts: an Instagram account is fetched through gallery-dl, with its media, on one paced queue

instagram-gallery-dl reads an account's posts and reels: one page for a sync,
at most 300 posts for a walk, never without the channel's own cookie source
(logged out, the feed answers "Page Not Found"), never a retry. gallery-dl's
exception row and its request lines say what happened: a login, challenge or
checkpoint page raises Instagram's alert; the feed's or the search's 404 is the
login, and an account is gone only when its own page answered 404; the first
429 ends the run and holds Instagram for an hour. The new posts' pictures and
videos are fetched in the same job, one paced GET each with no cookies, under
40 files / 200 MB a job and 100 MB a file, into posts-media/<pk>/; three CDN
refusals in a row end that half and the rest is recorded as owed. A run says
what it cost in requests and files. capture-posts and retry-on-block refuse an
Instagram channel by name.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/controller/capturePosts.ts | 10++++++++++
Mcommon/controller/checkPostAvailability.ts | 1+
Mcommon/controller/fetchPosts.ts | 63++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Acommon/jobs/instagramPacing.test.ts | 388+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/instagram/visibility.test.ts | 7+++----
Mcommon/lib/settingsSchema.ts | 7+------
Acommon/social/__fixtures__/instagramRun.ts | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/fetchers.ts | 15+++++++++++++++
Acommon/social/instagramGalleryDlFetcher.test.ts | 366+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/instagramGalleryDlFetcher.ts | 486+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/instagramMedia.test.ts | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/instagramMedia.ts | 337+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/instagramNormalize.test.ts | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/instagramNormalize.ts | 245+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/instagramSignals.test.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/instagramSignals.ts | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xCookieSource.ts | 7+------
17 files changed, 2545 insertions(+), 17 deletions(-)

diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -90,6 +90,7 @@ import "../social/xGalleryDlFetcher"; import "../social/xPlaywrightFetcher"; import "../social/xNitterFetcher"; import "../social/xenforoFetcher"; +import "../social/instagramGalleryDlFetcher"; import { resolveXCookieSourceFor, type XLoginSettings, @@ -242,6 +243,14 @@ export function strayIdsRefusal(slug: string, stray: string[]): string { return `${stray.length} id(s) not in ${slug}'s posts archive: ${stray.join(", ")}`; } +// Instagram (lane instagram): no screenshot is ever taken — a post's page +// needs a login, and a logged-in page load is the request most likely to get +// the account checked — and a post's media are fetched by the job that +// fetches the post, because their addresses expire. +export const INSTAGRAM_NO_CAPTURE = (slug: string) => + `${slug} is an Instagram channel: capture-posts takes no screenshot of an Instagram post (its page needs a login), ` + + "and its pictures and videos are fetched with the post, by fetch-posts. Nothing was asked of Instagram."; + // The fetcher that captures an X trending library's posts. export const X_LIBRARY_FETCHER = "x-gallery-dl"; @@ -282,6 +291,7 @@ export async function capturePosts( const fetcher = library ? (getSocialFetcher(config.postFetcher) ?? getSocialFetcher(X_LIBRARY_FETCHER)) : resolveSocialFetcher(config.postFetcher, accountUrl); + if (fetcher?.platform === "instagram") return fail(INSTAGRAM_NO_CAPTURE(slug)); const problem = capturePostsProblem(fetcher); if (problem || !fetcher?.captureByIds) return fail(problem ?? "This channel has no post fetcher."); const avatarsOnly = opts.avatarsOnly === true; diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts @@ -34,6 +34,7 @@ import { } from "../social/fetchers"; import "../social/blueskyFetcher"; import "../social/xenforoFetcher"; +import "../social/instagramGalleryDlFetcher"; import "../social/xGalleryDlFetcher"; import "../social/xPlaywrightFetcher"; import "../social/xNitterFetcher"; diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -83,6 +83,15 @@ import "../social/xPlaywrightFetcher"; import "../social/xNitterFetcher"; // A forum thread (platform "xenforo"): claims only thread URLs. import "../social/xenforoFetcher"; +// An Instagram account (lane instagram): claims instagram.com account URLs. +import { INSTAGRAM_NO_COOKIES } from "../social/instagramGalleryDlFetcher"; +import { + fakeInstagramMediaFetch, + fetchInstagramMedia, + instagramMediaLine, + type InstagramMediaDeps, +} from "../social/instagramMedia"; +import { postsMediaDir } from "../social/postCapture"; import type { XCookieSource } from "../social/xCookieSource"; import { noteForumServiceOutcome } from "../lib/serviceCookies-server"; import { @@ -147,8 +156,27 @@ export type FetchPostsOptions = { // The retry's wait (tests pass a fake clock). Default: a real timer that a // cancel or a drain ends. sleep?: (ms: number, signal?: AbortSignal, drain?: AbortSignal) => Promise<"slept" | "aborted" | "drained">; + // Instagram: the media half's fetch, pause and clock (tests pass fakes). + // Default: the real ones — under the e2e test server, the played-back CDN. + instagramMedia?: Partial<InstagramMediaDeps>; }; +// Instagram is never waited out and asked again (lane instagram): a refusal +// ends the run and leaves Instagram alone for an hour, a challenge needs a +// person. +export const INSTAGRAM_RETRY_REFUSAL = + "Retry on a block is not for Instagram: a refusal stops every Instagram job for an hour, and a challenge " + + "or login page until a person's Recheck. Nothing retries by itself."; + +// THE COOKIE SOURCE OF AN INSTAGRAM CHANNEL IS ITS OWN (`cookiesFromBrowser` in +// its config), never the global one: the global spec is the browser yt-dlp +// reads, which is the operator's everyday one, and whose account Instagram +// sees is a decision made per channel, not inherited. None set: refused +// before anything is asked. +export function instagramCookieSource(config: { cookiesFromBrowser?: string } | null | undefined): string | undefined { + return config?.cookiesFromBrowser?.trim() || undefined; +} + // A Wayback pages channel (release 37) has no account to fetch: its captures // are imported one by one (import-page), as chosen. export const WAYBACK_PAGES_NOT_FETCHED = @@ -357,6 +385,15 @@ export async function fetchPosts( return { ok: false, written: 0, skipped: 0, complete: false, error: FORUM_BACKFILL_REFUSAL }; } + if (fetcher.platform === "instagram") { + if (opts.retryOnBlock) { + return { ok: false, written: 0, skipped: 0, complete: false, error: INSTAGRAM_RETRY_REFUSAL }; + } + if (!instagramCookieSource(config)) { + return { ok: false, written: 0, skipped: 0, complete: false, needsCookies: true, error: INSTAGRAM_NO_COOKIES(slug) }; + } + } + const seenIds = await readSeenPostIds(channelRoot); const priorState = await readPostFetchState(channelRoot); if (opts.backfill) { @@ -516,7 +553,8 @@ async function fetchTimeline(ctx: { const resumeCursor = plan?.cursor; const since = plan?.since; const policy = resolveCookiePolicy(settings, config); - const cookies = alwaysCookies(policy); + // Instagram reads the channel's OWN cookie source, whatever the cookie mode. + const cookies = fetcher.platform === "instagram" ? instagramCookieSource(config) : alwaysCookies(policy); // An X fetcher's login source (social.x.cookieSource, xCookieSource.ts), // resolved against THIS channel's browser spec — its own cookiesFromBrowser // over the global one, whatever the cookieMode. @@ -654,6 +692,29 @@ async function fetchTimeline(ctx: { ? " — the sync stopped part-way; the next Sync new continues it." : " — more history remains."), ); + // INSTAGRAM'S MEDIA, in the same job: the CDN addresses the run printed + // expire, so the new posts' pictures and videos are fetched now, after the + // posts are on disk (social/instagramMedia.ts). A failure here never fails + // the fetch: what is missing is owed, and said. + if (result.media?.length) { + const fake = fakeInstagramMediaFetch(); + const media = await fetchInstagramMedia({ + outDir: postsMediaDir(channelRoot), + plans: result.media, + signal: effectiveSignal, + onLog: log, + deps: { ...(fake ? { fetch: fake } : {}), ...(opts.instagramMedia ?? {}) }, + }).catch((err: unknown) => { + log(`[warn] The media could not be fetched: ${(err as Error).message}. The posts are archived.`); + return null; + }); + if (media) log(instagramMediaLine(media)); + log( + `This run cost Instagram ${result.requests ?? 0} request(s) and its CDN ${media?.fetched ?? 0} file(s).`, + ); + } else if (fetcher.platform === "instagram" && result.requests !== undefined) { + log(`This run cost Instagram ${result.requests} request(s) and its CDN 0 file(s).`); + } if (result.notSeen?.length) { log( `${result.notSeen.length} archived post(s) were on no page of the thread (deleted or moved since): ` + diff --git a/common/jobs/instagramPacing.test.ts b/common/jobs/instagramPacing.test.ts @@ -0,0 +1,388 @@ +// INSTAGRAM THROUGH THE REAL JOB FUNNEL (runManagedFunction), the real fetch +// controller and the real fetcher, against a fake gallery-dl written here (no +// request leaves the machine; the media CDN is an injected function): +// - a channel with no cookie source of its own is refused and gallery-dl +// never runs; +// - a challenge in job 1 fails job 1, raises Instagram's alert, and refuses +// every later Instagram job unrun, until a person's Recheck; +// - the first 429 ends the run, keeps what it read, and holds Instagram for +// an hour: the jobs behind it are refused unrun; +// - clean jobs start at least pacing.jobGapSeconds.instagram (600 s) apart, +// write their posts and fetch their media in the same job, and say what +// the run cost; +// - a run past its request cap is stopped with SIGINT and keeps what +// gallery-dl then prints. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/instagramPacing.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "instagram-pacing-")); +const BIN = path.join(ROOT, "fake-gallery-dl.mjs"); +const RUNS = path.join(ROOT, "runs.log"); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.GALLERY_DL_BIN = BIN; +process.env.FAKE_RUNS = RUNS; +delete process.env.E2E_JOB_GAP_SECONDS; +delete process.env.E2E_TEST_ROUTES; + +// What gallery-dl prints for Instagram with --dump-json --verbose: request +// lines and cursors on stderr, ONE array on stdout at exit — the exception as +// its last row — and exit 0 whatever happened. SIGINT: it prints what it has. +await writeFile( + BIN, + `#!/usr/bin/env node +import { appendFileSync } from "node:fs"; +const args = process.argv.slice(2); +appendFileSync(process.env.FAKE_RUNS, args.join(" ") + "\\n"); +const mode = process.env.FAKE_MODE ?? "clean"; +const handle = /instagram\\.com\\/([^/]+)\\/posts/.exec(args.at(-1))?.[1] ?? "nobody"; +const rows = []; +const req = (p, s = 200) => process.stderr.write('[urllib3.connectionpool][debug] https://www.instagram.com:443 "GET ' + p + ' HTTP/1.1" ' + s + ' None\\n'); +const feed = "/api/v1/feed/user/4000000001/?count=30"; +const post = (n, media) => { + const pk = (3500000000000000000n + BigInt(n)).toString(); + const p = { post_id: pk, post_shortcode: "Code" + n, type: media[0] === "video" && media.length === 1 ? "reel" : "post", + username: handle, fullname: "Example Account", description: "post " + n + " of " + handle, + post_date: "2026-03-" + String(n).padStart(2, "0") + " 10:00:00", pinned: [], count: media.length, likes: n }; + rows.push([2, p]); + media.forEach((kind, i) => { + const ext = kind === "video" ? "mp4" : "jpg"; + const url = "https://cdn.example.invalid/" + handle + "/" + n + "-" + (i + 1) + "." + ext + "?sig=invented"; + rows.push([3, url, { ...p, num: i + 1, media_id: String(BigInt(pk) * 10n + BigInt(i + 1)), video_url: kind === "video" ? url : null, display_url: url, extension: ext }]); + }); +}; +const dump = () => { process.stdout.write(JSON.stringify(rows, null, 2) + "\\n"); process.exit(0); }; +process.on("SIGINT", dump); +req("/web/search/topsearch/?query=" + handle); +if (mode === "challenge") { + // Instagram answers after a moment: the loop has queued every job by then. + await new Promise((r) => setTimeout(r, 1500)); + req(feed, 302); + rows.push([-1, { error: "AbortExtraction", message: "HTTP redirect to challenge page (https://www.instagram.com/challenge/)" }]); + dump(); +} +if (mode === "ratelimit") { + await new Promise((r) => setTimeout(r, 1500)); + req(feed); + post(9, ["image"]); + process.stderr.write("[instagram][debug] Cursor: page-2\\n"); + req(feed + "&max_id=page-2", 429); + rows.push([-1, { error: "HttpError", message: "'429 Too Many Requests' for 'https://www.instagram.com" + feed + "&max_id=page-2'" }]); + dump(); +} +if (mode === "endless") { + // Pages of one post, for ever: only the request cap ends this. + let n = 1; + const t = setInterval(() => { req(feed); post(n++, ["image"]); process.stderr.write("[instagram][debug] Cursor: page-" + n + "\\n"); }, 40); + setTimeout(() => { clearInterval(t); process.exit(3); }, 30_000); + await new Promise(() => {}); +} +req(feed); +post(3, ["image", "video"]); +post(2, ["video"]); +post(1, ["image"]); +dump(); +`, +); +await chmod(BIN, 0o755); +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({})); + +const transcripts = path.join(ROOT, "transcripts"); +const SLUGS = Array.from({ length: 5 }, (_, i) => `ig-acct-${i + 1}`); +async function makeChannel(slug: string, cookies: string | null): Promise<void> { + const dir = path.join(transcripts, "channels", slug); + await rm(dir, { recursive: true, force: true }); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "config.json"), + JSON.stringify({ + handling: "transcribe", + sourceKind: "social", + postFetcher: "instagram-gallery-dl", + socialHandle: `example.${slug}`, + platform: "instagram", + name: slug, + url: `https://www.instagram.com/example.${slug}/`, + ...(cookies ? { cookiesFromBrowser: cookies } : {}), + }), + ); +} + +const { getPaths } = await import("../lib/paths"); +const { runManagedFunction } = await import("./streamCommand"); +const { fetchPosts, INSTAGRAM_RETRY_REFUSAL } = await import("../controller/fetchPosts"); +const { capturePosts } = await import("../controller/capturePosts"); +const { getSettings } = await import("../lib/settings"); +const { setQueueGapClock, clearQueueGaps } = await import("./queueGap"); +const { readServiceCookieState, serviceCookiesFile } = await import("../lib/serviceCookies-server"); +const { recheckServiceCookies } = await import("../controller/recheckServiceCookies"); +const { readAllPosts, readPostFetchState } = await import("../lib/posts-server"); +const { platformCooldownRemainingMs, clearPlatformHold } = await import("./downloadBackoff"); +const { readChannelConfig } = await import("../controller/channels"); + +const paths = getPaths(); + +let fakeNow = Date.parse("2026-03-10T03:00:00Z"); +setQueueGapClock({ + now: () => fakeNow, + sleep: async (ms) => { + fakeNow += ms; + }, +}); + +// The media CDN, invented: every address answers a few bytes naming it. +const cdn: string[] = []; +const instagramMedia = { + fetch: async (url: string) => { + cdn.push(url); + const bytes = new TextEncoder().encode(`media ${url}`); + return { + status: 200, + headers: { get: () => String(bytes.length) }, + body: (async function* () { + yield bytes; + })(), + }; + }, + pause: async () => {}, + pauseMs: () => 3000, +}; + +async function fetchJob(slug: string, starts: Map<string, number>, extra: Record<string, unknown> = {}) { + return runManagedFunction({ + kind: "fetch-posts", + queueKey: "platform:instagram", + paths, + channelSlug: slug, + fn: async (onLog, signal) => { + starts.set(slug, fakeNow); + const result = await fetchPosts({ paths, slug, settings: getSettings(), onLog, signal, instagramMedia, ...extra }); + if (!result.ok) throw new Error(result.error ?? "Post fetch failed"); + fakeNow += 3_000; + }, + }); +} + +async function runCount(): Promise<number> { + try { + return (await readFile(RUNS, "utf8")).split("\n").filter(Boolean).length; + } catch { + return 0; + } +} + +async function reset(cookies: string | null = "firefox:ig-profile"): Promise<void> { + clearQueueGaps(); + cdn.length = 0; + await rm(RUNS, { force: true }); + await rm(serviceCookiesFile(paths), { force: true }); + await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true }); + for (const slug of SLUGS) await makeChannel(slug, cookies); +} + +async function readLog(jobId: string): Promise<string> { + return readFile(path.join(paths.jobsDir, `${jobId}.log`), "utf8"); +} + +test.after(async () => { + await rm(ROOT, { recursive: true, force: true }); +}); + +test("a channel with no cookie source of its own is refused, and gallery-dl never runs — the global browser is not borrowed", async () => { + await reset(null); + await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ cookiesFromBrowser: "firefox", cookieMode: "always" })); + try { + const r = await fetchPosts({ paths, slug: SLUGS[0], settings: { cookiesFromBrowser: "firefox", cookieMode: "always" } }); + assert.equal(r.ok, false); + assert.equal(r.needsCookies, true); + assert.match(r.error!, /has no cookie source of its own/); + assert.match(r.error!, /Set "Cookies from browser" on the channel's Edit form/); + assert.equal(await runCount(), 0); + // Retry on a block is refused by name, before anything else is asked. + await makeChannel(SLUGS[0], "firefox:ig-profile"); + const retry = await fetchPosts({ paths, slug: SLUGS[0], settings: {}, retryOnBlock: { minutes: 30, max: 3 } }); + assert.deepEqual([retry.ok, retry.error], [false, INSTAGRAM_RETRY_REFUSAL]); + assert.equal(await runCount(), 0); + // capture-posts takes no screenshot of an Instagram post and asks nothing. + const cap = await capturePosts({ paths, slug: SLUGS[0], settings: {}, ids: ["3500000000000000001"] } as never); + assert.equal(cap.ok, false); + assert.match(cap.error!, /takes no screenshot of an Instagram post/); + assert.equal(await runCount(), 0); + } finally { + await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({})); + } +}); + +test("5 Instagram fetches, job 1 meets a challenge: job 1 fails, the alert is up, jobs 2-5 are refused unrun until a person's Recheck", async () => { + await reset(); + process.env.FAKE_MODE = "challenge"; + try { + const starts = new Map<string, number>(); + const started = []; + for (const slug of SLUGS) { + const res = await fetchJob(slug, starts); + assert.equal(res.ok, true, res.ok ? "" : res.error); + if (res.ok) started.push(res); + } + const ends = await Promise.all(started.map((r) => r.done)); + assert.deepEqual(ends.map((e) => e.status), Array(5).fill("failed")); + assert.equal(await runCount(), 1, "gallery-dl ran once: only job 1 asked Instagram"); + assert.deepEqual([...starts.keys()], [SLUGS[0]]); + const first = await readLog(ends[0]!.jobId); + assert.match(first, /Instagram answered with a challenge or checkpoint page/); + assert.match(first, /Cost: 2 request\(s\) to Instagram/); + const second = await readLog(ends[1]!.jobId); + assert.match(second, /its alert is up, so no Instagram job starts/); + const ig = (await readServiceCookieState(paths)).services.instagram; + assert.ok(ig?.raisedAt && !ig.clearedAt); + assert.equal(ig.kind, "challenge"); + assert.equal(ig.jobs.length, 5); + // A sixth is refused at enqueue: no job at all. + const again = await fetchJob(SLUGS[0], new Map()); + assert.equal(again.ok, false); + assert.match(again.ok ? "" : again.error, /its alert is up/); + // The run with the gallery-dl that would now answer cleanly is still refused: nothing probes by itself. + process.env.FAKE_MODE = "clean"; + assert.equal((await fetchJob(SLUGS[1], new Map())).ok, false); + assert.equal(await runCount(), 1); + // The operator's Recheck (no request) clears it, and a fetch runs. + await recheckServiceCookies({ paths, service: "instagram" }); + const after = await fetchJob(SLUGS[1], new Map()); + assert.equal(after.ok, true); + if (after.ok) assert.equal((await after.done).status, "done"); + assert.equal(await runCount(), 2); + } finally { + delete process.env.FAKE_MODE; + } +}); + +test("the first 429 ends the run and holds Instagram for an hour: what was read is kept, the jobs behind it are refused unrun", async () => { + await reset(); + process.env.FAKE_MODE = "ratelimit"; + try { + const starts = new Map<string, number>(); + const started = []; + for (const slug of SLUGS.slice(0, 3)) { + const res = await fetchJob(slug, starts); + assert.equal(res.ok, true, res.ok ? "" : res.error); + if (res.ok) started.push(res); + } + const ends = await Promise.all(started.map((r) => r.done)); + assert.deepEqual(ends.map((e) => e.status), ["failed", "failed", "failed"]); + assert.equal(await runCount(), 1); + const first = await readLog(ends[0]!.jobId); + assert.match(first, /Instagram refused the read .*429 Too Many Requests.*a rate limit/); + assert.match(first, /Nothing retries by itself/); + assert.match(await readLog(ends[1]!.jobId), /Instagram answered a rate limit a short while ago: no Instagram job starts before/); + const left = await platformCooldownRemainingMs("instagram", paths); + assert.ok(left > 58 * 60_000 && left <= 60 * 60_000, `cooldown ${left}`); + // The post it read before the 429 is archived, its media fetched, the resume point kept. + const root = path.join(paths.channelsDir, SLUGS[0]); + assert.deepEqual((await readAllPosts(root)).map((p) => p.id), ["3500000000000000009"]); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "page-2"); + assert.equal(cdn.length, 1); + // No alert: the cookies are not the fix. + assert.equal((await readServiceCookieState(paths)).services.instagram, undefined); + // Refused at enqueue while it cools down. + assert.equal((await fetchJob(SLUGS[3], new Map())).ok, false); + } finally { + delete process.env.FAKE_MODE; + // The cooldown is cleared by hand for the tests below (the operator's clear-platform-hold). + await clearPlatformHold("instagram", paths); + assert.equal(await platformCooldownRemainingMs("instagram", paths), 0); + } +}); + +test("clean fetches start at least 600 s apart, archive the posts and fetch their media in the same job, and say what the run cost", async () => { + await reset(); + const starts = new Map<string, number>(); + const started = []; + for (const slug of SLUGS.slice(0, 3)) { + const res = await fetchJob(slug, starts); + assert.equal(res.ok, true, res.ok ? "" : res.error); + if (res.ok) started.push(res); + } + const ends = await Promise.all(started.map((r) => r.done)); + assert.deepEqual(ends.map((e) => e.status), ["done", "done", "done"]); + assert.equal(await runCount(), 3); + const at = SLUGS.slice(0, 3).map((s) => starts.get(s)!); + for (let i = 1; i < at.length; i++) { + assert.ok(at[i] - at[i - 1] >= 600_000, `job ${i + 1} started ${(at[i] - at[i - 1]) / 1000}s after job ${i}`); + } + assert.match(await readLog(ends[1]!.jobId), /Instagram jobs are spaced 10 min apart \(pacing\.jobGapSeconds\.instagram\)/); + + const slug = SLUGS[0]; + const root = path.join(paths.channelsDir, slug); + const posts = await readAllPosts(root); + assert.deepEqual(posts.map((p) => p.id).sort(), ["3500000000000000001", "3500000000000000002", "3500000000000000003"]); + const carousel = posts.find((p) => p.id === "3500000000000000003")!; + assert.equal(carousel.platform, "instagram"); + assert.equal(carousel.mediaCount, 2); + assert.equal(carousel.instagram?.kind, "post"); + assert.equal(posts.find((p) => p.id === "3500000000000000002")!.instagram?.kind, "reel"); + // No signed address is stored with a post. + assert.ok(!JSON.stringify(posts).includes("cdn.example.invalid")); + // Its media are in posts-media/<pk>/, in order, with a capture record and no screenshot. + const dir = path.join(root, "posts-media", "3500000000000000003"); + assert.deepEqual((await readdir(dir)).sort(), ["01-35000000000000000031.jpg", "02-35000000000000000032.mp4", "capture.json"]); + const record = JSON.parse(await readFile(path.join(dir, "capture.json"), "utf8")); + assert.equal(record.state, "captured"); + assert.equal(record.mediaState, "ok"); + assert.equal(record.shot, undefined); + assert.equal(record.media.length, 2); + assert.equal(record.url, carousel.url); + // One GET per file, with no cookies asked of anything: 4 files a channel. + assert.equal(cdn.length, 12); + const log = await readLog(ends[0]!.jobId); + assert.match(log, /Instagram login: this channel's cookie source \(firefox:ig-profile\)/); + assert.match(log, /Cost: 2 request\(s\) to Instagram \(1 for the account's id, 1 feed page\(s\)\)\./); + assert.match(log, /Media: 4 file\(s\) fetched from its CDN/); + assert.match(log, /This run cost Instagram 2 request\(s\) and its CDN 4 file\(s\)\./); + // The argv: never a retry, never the operator's own gallery-dl config, the channel's cookies. + const argv = (await readFile(RUNS, "utf8")).split("\n")[0]!; + assert.match(argv, /--config-ignore/); + assert.match(argv, /extractor\.instagram\.retries=0/); + assert.match(argv, /--cookies-from-browser firefox:ig-profile/); + // The first fetch walked everything there was: complete, no resume point; the channel is stamped. + assert.equal((await readPostFetchState(root))?.backfill, undefined); + assert.ok((await readChannelConfig(paths, slug))?.lastSyncedAt); + + // SYNC NEW after it: one page, everything known, nothing written, nothing fetched. + cdn.length = 0; + fakeNow += 3_600_000; + const again = await fetchJob(slug, new Map()); + assert.equal(again.ok, true); + if (again.ok) { + const end = await again.done; + assert.equal(end.status, "done"); + const l = await readLog(end.jobId); + assert.match(l, /Reading one page \(up to 30 posts\) from the top/); + assert.match(l, /Wrote 0 new post\(s\)/); + assert.match(l, /This run cost Instagram 2 request\(s\) and its CDN 0 file\(s\)\./); + } + assert.equal(cdn.length, 0); +}); + +test("a run past its request cap is stopped with an interrupt and keeps what gallery-dl then prints", async () => { + await reset(); + process.env.FAKE_MODE = "endless"; + try { + const slug = SLUGS[4]; + const r = await fetchPosts({ paths, slug, settings: {}, instagramMedia }); + // A first fetch is a walk: 13 requests at most (the lookup and 12 pages of one post). + assert.equal(r.ok, true); + assert.equal(r.complete, false); + const posts = await readAllPosts(path.join(paths.channelsDir, slug)); + assert.ok(posts.length >= 12 && posts.length <= 14, `${posts.length} posts`); + const state = await readPostFetchState(path.join(paths.channelsDir, slug)); + assert.match(state?.backfill?.cursor ?? "", /^page-\d+$/); + } finally { + delete process.env.FAKE_MODE; + } +}); diff --git a/common/lib/instagram/visibility.test.ts b/common/lib/instagram/visibility.test.ts @@ -58,15 +58,14 @@ test("a site's published members leave its instagram channels out unless it is p assert.deepEqual(publishedMemberSlugs({ ...site, audience: "private" } as never, (s) => configs[s], {}), ["ig", "x", "sky"]); }); -test("the social block keeps instagram's two keys and drops the rest", () => { +test("the social block keeps instagram's visibility and drops the rest", () => { assert.deepEqual(sanitizeSocial({}), { x: {} }); assert.deepEqual(sanitizeSocial({ instagram: {} }), { x: {} }); assert.deepEqual(sanitizeSocial({ instagram: { visibility: "public", allowLoggedOut: true, other: 1 } }), { x: {}, - instagram: { visibility: "public", allowLoggedOut: true }, + instagram: { visibility: "public" }, }); - assert.deepEqual(sanitizeSocial({ instagram: { visibility: "nope", allowLoggedOut: "yes" } }), { x: {} }); - assert.deepEqual(sanitizeSocial({ instagram: { allowLoggedOut: false } }), { x: {} }); + assert.deepEqual(sanitizeSocial({ instagram: { visibility: "nope" } }), { x: {} }); // X's keys are untouched by Instagram's. assert.deepEqual(sanitizeSocial({ x: { visibility: "private" }, instagram: { visibility: "private" } }), { x: { visibility: "private" }, diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -161,7 +161,7 @@ export { JOB_GAP_DEFAULT_SECONDS, JOB_GAP_MAX_SECONDS, jobGapSecondsFor } from " export const SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<SocialSettings> = { x: "X / Twitter. See `social.x` below.", xenforo: "Forum threads (XenForo). See `social.xenforo` below. Absent: nothing set.", - instagram: "Instagram. See `social.instagram` below. Absent: nothing set (posts private, no logged-out reads).", + instagram: "Instagram. See `social.instagram` below. Absent: nothing set (posts private).", }; export const INSTAGRAM_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<InstagramSocialSettings> = { @@ -172,11 +172,6 @@ export const INSTAGRAM_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<InstagramSocialSett "`audience`). `\"public\"`: built into every site that has the channel. Nothing on disk changes " + "and fetching does not; a site already published changes on its next build and deploy. The rule " + "is common/lib/postsVisibility.ts. `pnpm ops settings` sets it.", - allowLoggedOut: - "`true` lets an Instagram channel that has no cookie source of its own (`cookiesFromBrowser` in " + - "its config) be read LOGGED OUT. ABSENT (the default): such a channel refuses to fetch and says " + - "where to set the source. Whether Instagram answers a logged-out read at all is unproven: leave " + - "this off until one probe has shown it does. Stored only when true.", }; export const XENFORO_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XenforoSocialSettings> = { diff --git a/common/social/__fixtures__/instagramRun.ts b/common/social/__fixtures__/instagramRun.ts @@ -0,0 +1,101 @@ +// INVENTED Instagram runs, in the shape gallery-dl 1.32.9 prints with +// `--dump-json` (extractor/instagram.py `_parse_post_rest`, job.py DataJob): +// one array, `[2, post]` per post, `[3, url, file]` per media file, and +// `[-1, {error, message}]` for the exception that ended the run. No account, +// id, shortcode or address here is a real one. + +import { instagramShortcodeFromPk } from "../../lib/instagram/ids"; + +export const IG_HANDLE = "example.account"; +export const IG_UID = "4000000001"; +export const IG_CDN = "https://cdn.example.invalid"; + +// Beyond 2^53, like every real pk. +export const igPk = (n: number): string => (3500000000000000000n + BigInt(n)).toString(); + +export type FakeIgPost = { + n: number; + date: string; // "YYYY-MM-DD HH:MM:SS" + text?: string; + type?: "post" | "reel" | "story"; + // Media of the post: "image" | "video" each. + media?: ("image" | "video")[]; + pinned?: boolean; + owner?: string; + ownerName?: string; + coauthors?: { username: string; full_name?: string; id?: string }[]; + likes?: number; + // Print the pk as a bare JSON number, as gallery-dl may. + bareNumber?: boolean; +}; + +export function igRows(posts: FakeIgPost[], opts: { handle?: string } = {}): unknown[] { + const rows: unknown[] = []; + for (const p of posts) { + const pk = igPk(p.n); + const code = instagramShortcodeFromPk(pk)!; + const type = p.type ?? (p.media?.length === 1 && p.media[0] === "video" ? "reel" : "post"); + const media = p.media ?? ["image"]; + const post = { + category: "instagram", + subcategory: "posts", + post_id: pk, + post_shortcode: code, + post_url: `https://www.instagram.com/${type === "reel" ? "reel" : "p"}/${code}/`, + type, + username: p.owner ?? opts.handle ?? IG_HANDLE, + fullname: p.ownerName ?? "Example Account", + owner_id: IG_UID, + description: p.text ?? "", + post_date: p.date, + date: p.date, + likes: p.likes ?? 0, + liked: false, + pinned: p.pinned ? [Number(IG_UID)] : [], + count: media.length, + ...(p.coauthors ? { coauthors: p.coauthors } : {}), + ...(media.length > 1 ? { sidecar_media_id: pk, sidecar_shortcode: code } : {}), + }; + rows.push([2, post]); + media.forEach((kind, i) => { + const mediaId = igPk(p.n * 100 + i + 1); + const ext = kind === "video" ? "mp4" : "jpg"; + const url = `${IG_CDN}/v/t51/${mediaId}.${ext}?sig=invented&oe=0`; + rows.push([ + 3, + url, + { + ...post, + num: i + 1, + media_id: mediaId, + shortcode: instagramShortcodeFromPk(mediaId), + display_url: `${IG_CDN}/v/t51/${mediaId}.jpg?sig=invented&oe=0`, + video_url: kind === "video" ? url : null, + extension: ext, + filename: mediaId, + width: 1080, + height: 1350, + }, + ]); + }); + } + return rows; +} + +// What gallery-dl prints: the array, with the named pks as bare numbers. +export function igStdout(rows: unknown[], bare: string[] = []): string { + let text = JSON.stringify(rows, null, 2); + for (const pk of bare) text = text.replaceAll(`"post_id": "${pk}"`, `"post_id": ${pk}`); + return text; +} + +export const igError = (error: string, message: string): unknown => [-1, { error, message }]; + +// A request line as `--verbose` prints it. +export const igRequestLine = (path: string, status = 200, method = "GET"): string => + `[urllib3.connectionpool][debug] https://www.instagram.com:443 "${method} ${path} HTTP/1.1" ${status} ${status === 200 ? "None" : "20445"}`; + +export const igCursorLine = (cursor: string): string => `[instagram][debug] Cursor: ${cursor}`; + +export const igFeedPath = (uid = IG_UID): string => `/api/v1/feed/user/${uid}/?count=30`; +export const igSearchPath = (handle = IG_HANDLE): string => `/web/search/topsearch/?query=${handle}`; diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -111,6 +111,21 @@ export type PostFetchResult = { block?: "challenge" | "captcha" | "blocked" | "login" | "not-found" | "unknown"; // A complete full re-walk: archived posts of the thread it met on no page. notSeen?: string[]; + // INSTAGRAM (lane instagram): the media of the NEW posts, as the CDN + // addresses the run printed. They are signed and expire, so the fetch + // controller fetches them in the same job, after the posts are written + // (social/instagramMedia.ts) — never the fetcher, and never later from these. + media?: PostMediaPlan[]; + // How many requests the run sent the platform, when the fetcher counts them. + requests?: number; +}; + +// One post's media to fetch into `posts-media/<id>/`. +export type PostMediaPlan = { + id: string; + // The post's own URL, for its capture record. + url: string; + files: { num: number; kind: "image" | "video"; url: string; name: string }[]; }; // Input for the older-posts backfill (`SocialFetcher.fetchOlder`): walk the diff --git a/common/social/instagramGalleryDlFetcher.test.ts b/common/social/instagramGalleryDlFetcher.test.ts @@ -0,0 +1,366 @@ +// 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<InstagramFetcherDeps["noteOutcome"]>[0][]; + rateLimits: number; + log: string[]; +}; + +function harness(answer: { rows?: unknown[]; stdout?: string; stderr?: string[]; out?: Partial<InstagramRunOutput> }): Harness { + const h: Harness = { runs: [], outcomes: [], rateLimits: 0, 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; + }, + noteRateLimit: async () => { + h.rateLimits++; + return NOW + 60 * 60_000; + }, + now: () => NOW, + }; + return h; +} + +function input(h: Harness, over: Partial<PostFetchInput> = {}): 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> = {}): 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 ten, a refusal is never retried", () => { + assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z" }), { mode: "sync", maxPosts: 30, maxRequests: 4, stopAtKnown: true }); + assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", limit: 5 }), { mode: "sync", maxPosts: 5, maxRequests: 4, stopAtKnown: true }); + assert.deepEqual(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. + assert.deepEqual(planInstagramRun({}), { mode: "walk", maxPosts: 300, maxRequests: 13, stopAtKnown: false }); + assert.deepEqual(planInstagramRun({ stopAtKnown: true }), { mode: "walk", maxPosts: 300, maxRequests: 13, stopAtKnown: false }); + // A resumed backfill: from its cursor. + assert.deepEqual(planInstagramRun({ cursor: "abc_1" }), { mode: "walk", maxPosts: 300, maxRequests: 13, cursor: "abc_1", stopAtKnown: false }); + // A walk is never under two pages (a one-page walk logs no resume point), never over ten. + assert.equal(planInstagramRun({ limit: 10 }).maxPosts, 60); + assert.equal(planInstagramRun({ limit: 5000 }).maxPosts, 300); + // A sync continuing down to its watermark: a walk from the top that stops at what is known. + assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", cursor: INSTAGRAM_FROM_TOP_CURSOR }), { + mode: "walk", + maxPosts: 300, + maxRequests: 13, + stopAtKnown: true, + }); + + 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", + "extractor.instagram.retries=0", + "-o", + "extractor.instagram.videos=merged", + "-o", + "extractor.instagram.max-posts=300", + "-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); +}); + +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(130, 30)), stderr: [...lookup, page] }); + const r = await fetchInstagramPosts(input(h, { since: "2020-01-02T00:00:00.000Z", seenIds: new Set([igPk(1)]) }), h.deps); + assert.equal(r.posts.length, 30); + 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))); + // …and that next sync is a walk from the top (no gallery-dl cursor) that stops at what it knows. + const h2 = harness({ rows: igRows([...days(130, 45), { n: 1, date: "2020-01-02 00:00:00" }]), stderr: [page, igCursorLine("c2"), page] }); + const r2 = await fetchInstagramPosts( + input(h2, { since: "2020-01-02T00:00:00.000Z", cursor: INSTAGRAM_FROM_TOP_CURSOR, seenIds: new Set([igPk(1), ...days(130, 30).map((p) => igPk(p.n))]) }), + h2.deps, + ); + assert.ok(!h2.runs[0]!.args.some((a) => a.includes("extractor.instagram.cursor"))); + assert.ok(h2.runs[0]!.args.includes("extractor.instagram.max-posts=300")); + // The 30 it already has are archived again nowhere: it stops at the first of them. + assert.equal(r2.complete, true); + assert.equal(r2.posts.length, 0); +}); + +test("A WALK: 300 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 <= 10; i++) { + stderr.push(page); + if (i < 10) stderr.push(igCursorLine(`page-${i + 1}`)); + } + const h = harness({ rows: igRows(days(400, 300)), stderr }); + const r = await fetchInstagramPosts(input(h), h.deps); + assert.equal(r.posts.length, 300); + assert.equal(r.complete, false); + assert.equal(r.cursor, "page-10"); + assert.equal(r.requests, 11); + assert.equal(h.runs[0]!.stops, 0, "eleven requests are under the cap of 13"); + // 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-11"), page] }); + const r2 = await fetchInstagramPosts(input(h2, { cursor: "page-10", 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-10")); + 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 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("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, []); + + 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/); +}); diff --git a/common/social/instagramGalleryDlFetcher.ts b/common/social/instagramGalleryDlFetcher.ts @@ -0,0 +1,486 @@ +// Instagram via gallery-dl (lane instagram): an account's posts and reels as a +// posts channel. +// +// WHAT ONE RUN ASKS OF INSTAGRAM (gallery-dl 1.32.9's extractor/instagram.py): +// - the account's id: one search request, and the profile page when that +// fails — up to 2, and none once gallery-dl has cached the id; +// - the feed: one request per page of up to 30 posts; +// - gallery-dl sleeps 6-12 s before every request, by itself. +// SYNC NEW reads ONE page (max-posts 30). A WALK (a first fetch, a full +// re-walk, a resumed backfill, a sync continuing down to its watermark) reads +// up to 300 posts and stops; the next run resumes from the cursor gallery-dl +// logged, which re-reads that one page (the resume point is logged when a +// page is LEFT, so the page a capped run ended inside is the resume point). +// A run that sent more requests than MAX_REQUESTS is stopped, whatever +// Instagram's page size turns out to be. +// +// WHAT IT NEVER DOES: +// - run without a login. Logged out, Instagram answers the feed with a +// "Page Not Found" (one read, 18 Nov 2026), so a run with no cookie source +// costs requests and reads nothing: refused before gallery-dl is spawned. +// - retry. `extractor.instagram.retries=0`: gallery-dl's own default is to +// wait 60 s on a 429 and ask again, four times. The first 429 (or 401/403) +// ends the run and Instagram is left alone for an hour. +// - carry on past a login, challenge or checkpoint page: Instagram's alert +// goes up and every Instagram job is refused until a person's Recheck +// (jobs/instagramGuard.ts). +// +// gallery-dl prints everything it read as ONE JSON array when it exits, the +// exception that ended it as the last row (`output.jsonl` is left OFF: with +// it on, the exception is printed nowhere and the run exits 0 — a login wall +// would read as "no new posts"). A run stopped early is stopped with SIGINT, +// which gallery-dl answers by printing what it has. +// +// THE MEDIA are not fetched here: the run's CDN addresses are handed back as +// `media` and the fetch controller fetches them in the same job +// (instagramMedia.ts), because they expire. + +import { execa } from "execa"; +import { createInterface } from "node:readline"; +import type { Readable } from "node:stream"; +import { cookieArgs } from "../lib/cookiePolicy"; +import { instagramAccountUrl, instagramHandleFromUrl, isInstagramUrl } from "../lib/instagram/ids"; +import { getPaths, type Paths } from "../lib/paths"; +import type { Post } from "../lib/posts"; +import { noteInstagramServiceOutcome } from "../lib/serviceCookies-server"; +import { recordPlatformCooldown } from "../jobs/downloadBackoff"; +import { INSTAGRAM_PLATFORM, INSTAGRAM_RATE_LIMIT_HOLD_MS } from "../jobs/instagramGuard"; +import { + registerSocialFetcher, + type PostFetchInput, + type PostFetchResult, + type SocialFetcher, + type SocialFetcherProbe, +} from "./fetchers"; +import { parseInstagramRun, type InstagramListedPost } from "./instagramNormalize"; +import { + classifyInstagramError, + isInstagramApiHost, + isInstagramPrivateLine, + parseInstagramCursorLine, + parseInstagramRequestLine, + type InstagramRequestLine, +} from "./instagramSignals"; + +export const INSTAGRAM_FETCHER_ID = "instagram-gallery-dl"; + +// Instagram's feed page. +export const INSTAGRAM_PAGE_POSTS = 30; +// SYNC NEW: one page. +export const INSTAGRAM_SYNC_MAX_POSTS = INSTAGRAM_PAGE_POSTS; +// A walk: ten pages, then the next run resumes. Never under two pages: a +// one-page walk ends inside its first page, before any resume point is logged. +export const INSTAGRAM_WALK_MAX_POSTS = 10 * INSTAGRAM_PAGE_POSTS; +export const INSTAGRAM_WALK_MIN_POSTS = 2 * INSTAGRAM_PAGE_POSTS; +// The requests one run may send before it is stopped: the lookup's two, the +// pages, and one to spare. +export const INSTAGRAM_SYNC_MAX_REQUESTS = 4; +export const INSTAGRAM_WALK_MAX_REQUESTS = 13; +export const INSTAGRAM_BUDGET_MS = 20 * 60_000; + +// "Continue from the top": the resume point of a sync that filled its one page +// with new posts and met none it knew — more may lie below, and the page it +// ended in logged no cursor. The next sync walks from the top down to the +// watermark this one began with. +export const INSTAGRAM_FROM_TOP_CURSOR = "top"; + +export const INSTAGRAM_NO_COOKIES = (slug: string) => + `${slug} has no cookie source of its own, and Instagram shows an account's posts only to a login ` + + "(logged out, its feed answers \"Page Not Found\"): nothing was asked. Set \"Cookies from browser\" on the " + + "channel's Edit form (pnpm ops channel-config, cookiesFromBrowser) to a browser profile, or file:<cookies.txt>, " + + "that is logged in to Instagram with an account kept for this — then fetch again."; + +export type InstagramRunPlan = { + // "sync": one page from the top. "walk": up to maxPosts, from `cursor` or the top. + mode: "sync" | "walk"; + maxPosts: number; + maxRequests: number; + // gallery-dl's resume point, when the run continues from one. + cursor?: string; + // Stop at the first post already archived, or older than `since` (pinned + // posts aside: they sit on top of the grid whatever their age). + stopAtKnown: boolean; +}; + +// What one run reads, from what the controller asks. +export function planInstagramRun(input: Pick<PostFetchInput, "since" | "cursor" | "limit" | "stopAtKnown">): InstagramRunPlan { + const real = input.cursor && input.cursor !== INSTAGRAM_FROM_TOP_CURSOR ? input.cursor : undefined; + const walk = !input.since || Boolean(input.cursor); + const limit = input.limit && input.limit > 0 ? Math.floor(input.limit) : undefined; + if (!walk) { + return { + mode: "sync", + maxPosts: Math.min(limit ?? INSTAGRAM_SYNC_MAX_POSTS, INSTAGRAM_SYNC_MAX_POSTS), + maxRequests: INSTAGRAM_SYNC_MAX_REQUESTS, + stopAtKnown: input.stopAtKnown !== false, + }; + } + return { + mode: "walk", + maxPosts: Math.max(INSTAGRAM_WALK_MIN_POSTS, Math.min(limit ?? INSTAGRAM_WALK_MAX_POSTS, INSTAGRAM_WALK_MAX_POSTS)), + maxRequests: INSTAGRAM_WALK_MAX_REQUESTS, + ...(real ? { cursor: real } : {}), + // Only a walk with a watermark stops at what it knows: a history walk + // resumed from its cursor re-reads one page of archived posts on purpose. + stopAtKnown: Boolean(input.since) && input.stopAtKnown !== false, + }; +} + +// The account's posts URL gallery-dl's posts extractor claims. +export function instagramPostsUrl(handle: string): string { + return `${instagramAccountUrl(handle)}posts/`; +} + +export function buildInstagramGalleryDlArgs(opts: { handle: string; cookies?: string; plan: InstagramRunPlan }): string[] { + return [ + // The operator's own gallery-dl config is not read: it could carry a + // login, a pace or a retry count this run must not inherit. + "--config-ignore", + "--no-input", + "--no-colors", + // Metadata only; ONE array at exit, the exception as its last row. + "--dump-json", + // The request lines and the "Cursor:" lines. + "--verbose", + // NEVER wait and ask again: the first refusal ends the run. + "-o", + "extractor.instagram.retries=0", + // A video's one file with its sound, not the DASH pair. + "-o", + "extractor.instagram.videos=merged", + "-o", + `extractor.instagram.max-posts=${opts.plan.maxPosts}`, + ...(opts.plan.cursor ? ["-o", `extractor.instagram.cursor=${opts.plan.cursor}`] : []), + ...cookieArgs(opts.cookies), + instagramPostsUrl(opts.handle), + ]; +} + +export type InstagramRunOutput = { + stdout: string; + // The run could not be started at all (the binary is missing). + spawnError?: string; + timedOut: boolean; + canceled: boolean; +}; + +export type InstagramFetcherDeps = { + bin: () => string; + // Run gallery-dl. `onStderrLine` answers "stop" to end the run now (SIGINT: + // gallery-dl prints what it has). + run: ( + bin: string, + args: string[], + opts: { signal: AbortSignal; drain?: AbortSignal; timeoutMs: number; onStderrLine: (line: string) => "stop" | void }, + ) => Promise<InstagramRunOutput>; + noteOutcome: (outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure"; url?: string; channel?: string }) => Promise<string | null>; + // Records the cooldown; answers when it ends (ms since the epoch). + noteRateLimit: () => Promise<number>; + now: () => number; +}; + +function readLines(input: Readable | null | undefined, onLine: (line: string) => void): Promise<void> { + if (!input) return Promise.resolve(); + return new Promise((resolve) => { + const rl = createInterface({ input, crlfDelay: Infinity }); + rl.on("line", onLine); + rl.on("close", resolve); + }); +} + +async function runGalleryDl( + bin: string, + args: string[], + opts: { signal: AbortSignal; drain?: AbortSignal; timeoutMs: number; onStderrLine: (line: string) => "stop" | void }, +): Promise<InstagramRunOutput> { + const subprocess = execa(bin, args, { + reject: false, + stdin: "ignore", + stderr: "pipe", + timeout: opts.timeoutMs, + cancelSignal: opts.signal, + // SIGINT, never SIGTERM: gallery-dl answers an interrupt by printing what + // it has read, and that is what a stopped run is told by. + killSignal: "SIGINT", + env: { PYTHONUNBUFFERED: "1" }, + }); + let stopped = false; + const stop = () => { + if (stopped) return; + stopped = true; + subprocess.kill("SIGINT"); + }; + opts.drain?.addEventListener("abort", stop, { once: true }); + if (opts.drain?.aborted) stop(); + const stderrDone = readLines(subprocess.stderr, (line) => { + if (opts.onStderrLine(line) === "stop") stop(); + }); + const res = await subprocess; + opts.drain?.removeEventListener("abort", stop); + await stderrDone; + const spawnError = `${res.code ?? ""} ${res.message ?? ""}`; + const stdout = typeof res.stdout === "string" ? res.stdout : ""; + return { + stdout, + ...(res.failed && /ENOENT/.test(spawnError) && !stdout ? { spawnError: `gallery-dl not found (looked for "${bin}"; set GALLERY_DL_BIN)` } : {}), + timedOut: res.timedOut === true, + canceled: res.isCanceled === true, + }; +} + +const defaultDeps = (paths: Paths = getPaths()): InstagramFetcherDeps => ({ + bin: () => paths.galleryDlBin, + run: runGalleryDl, + noteOutcome: (o) => noteInstagramServiceOutcome(paths, o), + noteRateLimit: () => recordPlatformCooldown(INSTAGRAM_PLATFORM, INSTAGRAM_RATE_LIMIT_HOLD_MS, paths), + now: () => Date.now(), +}); + +const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); + +// What a run cost Instagram, as a sentence for the job's log. +export function instagramCostLine(requests: readonly InstagramRequestLine[]): string { + const api = requests.filter((r) => isInstagramApiHost(r.host)); + const pages = api.filter((r) => /\/feed\/user\//.test(r.path)).length; + const lookups = api.length - pages; + return ( + `Cost: ${api.length} request(s) to Instagram ` + + `(${lookups} for the account's id, ${pages} feed page(s)).` + ); +} + +export async function fetchInstagramPosts( + input: PostFetchInput, + given: Partial<InstagramFetcherDeps> = {}, +): Promise<PostFetchResult> { + const deps = { ...defaultDeps(), ...given }; + const { channelSlug, seenIds, since, signal } = input; + const log = (line: string) => input.onLog?.(line); + const handle = instagramHandleFromUrl(input.accountUrl) ?? input.handle; + const cookies = input.cookies?.trim(); + if (!cookies) { + return { posts: [], complete: false, needsCookies: true, error: INSTAGRAM_NO_COOKIES(channelSlug) }; + } + if (!handle) return { posts: [], complete: false, error: `${input.accountUrl} names no Instagram account` }; + + const plan = planInstagramRun(input); + const bin = deps.bin(); + const args = buildInstagramGalleryDlArgs({ handle, cookies, plan }); + log( + `Instagram login: this channel's cookie source (${cookies}), read by gallery-dl. ` + + (plan.mode === "sync" + ? `Reading one page (up to ${plan.maxPosts} posts) from the top.` + : `Walking up to ${plan.maxPosts} posts ${plan.cursor ? "from the saved resume point" : "from the top"}.`) + + ` At most ${plan.maxRequests} requests, 6-12 s apart; a refusal is not retried.`, + ); + + const requests: InstagramRequestLine[] = []; + let cursor: string | undefined; + let privateLine: string | undefined; + let overCap = false; + const out = await deps.run(bin, args, { + signal, + ...(input.drain ? { drain: input.drain } : {}), + timeoutMs: INSTAGRAM_BUDGET_MS, + onStderrLine: (line) => { + const c = parseInstagramCursorLine(line); + if (c) { + cursor = c; + return; + } + if (isInstagramPrivateLine(line)) privateLine = line.trim().slice(0, 300); + const r = parseInstagramRequestLine(line); + if (!r || !isInstagramApiHost(r.host)) return; + requests.push(r); + if (requests.length >= plan.maxRequests && !overCap) { + overCap = true; + return "stop"; + } + }, + }); + if (out.spawnError) throw new Error(out.spawnError); + log(instagramCostLine(requests)); + + const rows = parseInstagramRun(out.stdout, { channelSlug, handle }); + const listed = rows?.posts ?? []; + + // Which of what was listed is new, and where the walk met what it knows. + const fresh: InstagramListedPost[] = []; + let known = 0; + let stoppedAtKnown = false; + for (const p of listed) { + const isKnown = seenIds.has(p.post.id); + const isOld = Boolean(since) && p.post.createdAt <= since!; + if (p.pinned) { + // On top of the grid whatever its age: archived when new, never a stop. + if (isKnown) known++; + else fresh.push(p); + continue; + } + if (isKnown || (isOld && plan.stopAtKnown)) { + known++; + if (plan.stopAtKnown) { + stoppedAtKnown = true; + break; + } + continue; + } + fresh.push(p); + } + const posts: Post[] = fresh.map((p) => p.post); + const media = fresh.filter((p) => p.files.length > 0).map((p) => ({ id: p.post.id, url: p.post.url, files: p.files })); + log( + `gallery-dl listed ${listed.length} post(s): ${posts.length} new` + + (known ? `, ${known} already archived` : "") + + (rows?.unreadable ? `, ${rows.unreadable} unreadable (no id or date) left out` : "") + + (rows?.otherKinds ? `, ${rows.otherKinds} not a post or reel left out` : "") + + ".", + ); + + // Where the next run picks up when this one did not finish. + // the last page gallery-dl left, else the point it was given, else — when + // it saved posts before leaving any page — the top. + const resumeAt = cursor ?? plan.cursor ?? (posts.length > 0 ? INSTAGRAM_FROM_TOP_CURSOR : undefined); + const base = { posts, requests: requests.filter((r) => isInstagramApiHost(r.host)).length, ...(media.length ? { media } : {}) }; + const accountUrl = instagramAccountUrl(handle); + + if (rows?.error) { + const sig = classifyInstagramError(rows.error, { requests, handle }); + if (sig.class === "challenge" || sig.class === "login") { + await deps.noteOutcome({ + challengeLine: sig.line, + kind: sig.class === "challenge" ? "challenge" : "auth-failure", + url: accountUrl, + channel: channelSlug, + }); + const what = + sig.class === "challenge" + ? "Instagram answered with a challenge or checkpoint page" + : "Instagram did not accept the login (its login page, or the \"Page Not Found\" it answers a logged-out read with)"; + return { + ...base, + complete: false, + ...(resumeAt && !stoppedAtKnown ? { cursor: resumeAt } : {}), + needsCookies: true, + block: sig.class, + error: + `${what}: ${sig.line}. The run stopped and Instagram's alert is up: no Instagram job starts until ` + + (sig.class === "challenge" + ? "the check is passed by hand in the browser this channel's cookie source names" + : "that browser (or cookies file) is logged in to Instagram again") + + ", and Recheck is pressed on the dashboard. Nothing retries by itself.", + }; + } + if (sig.class === "rate-limit") { + const until = await deps.noteRateLimit().catch(() => deps.now() + INSTAGRAM_RATE_LIMIT_HOLD_MS); + return { + ...base, + complete: false, + ...(resumeAt && !stoppedAtKnown ? { cursor: resumeAt } : {}), + block: "blocked", + error: + `Instagram refused the read (${sig.line}): a rate limit. The run stopped at once and asked nothing more; ` + + `no Instagram job starts before ${hhmm(until)} UTC (${Math.round(INSTAGRAM_RATE_LIMIT_HOLD_MS / 60_000)} min). Nothing retries by itself.`, + }; + } + if (sig.class === "not-found") { + return { + ...base, + complete: false, + block: "not-found", + error: `Instagram has no account @${handle}: its own page answered 404 (renamed, deleted or suspended). What is archived is kept.`, + }; + } + if (sig.class === "private") { + return { + ...base, + complete: false, + error: `@${handle} is a private account and this channel's login does not follow it: nothing was read.`, + }; + } + // A post already archived stops a sync before the row that failed mattered. + if (!stoppedAtKnown) { + return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}), error: `gallery-dl failed: ${sig.line}` }; + } + } + + if (!rows) { + if (out.canceled || signal.aborted || out.timedOut || input.drain?.aborted || overCap) { + log("The run was stopped before gallery-dl printed what it read; the next run starts where this one did."); + return { + posts: [], + complete: false, + ...(plan.cursor ? { cursor: plan.cursor } : input.cursor ? { cursor: input.cursor } : {}), + ...(input.drain?.aborted && !signal.aborted ? { drained: true } : {}), + }; + } + return { posts: [], complete: false, error: "gallery-dl printed nothing this reads as its JSON output." }; + } + + if (privateLine && listed.length === 0) { + return { + ...base, + complete: false, + error: `@${handle} is a private account and this channel's login does not follow it: nothing was read.`, + }; + } + + // A clean read: a pending signal is settled, and this is a request a person can name. + const cleared = await deps.noteOutcome({ url: accountUrl, channel: channelSlug }); + if (cleared) log(cleared.trimEnd()); + + if (stoppedAtKnown) return { ...base, complete: true }; + + if (out.canceled || signal.aborted || out.timedOut) { + log( + out.timedOut + ? `Stopped at this run's ${Math.round(INSTAGRAM_BUDGET_MS / 60_000)}-minute budget; the next run resumes where this one left off.` + : "Cancelled; the next run resumes where this one left off.", + ); + return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}) }; + } + if (input.drain?.aborted) { + log("Drained; the next run resumes where this one left off."); + return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}), drained: true }; + } + if (overCap) { + log( + `Stopped at ${plan.maxRequests} requests, this run's cap: Instagram's pages were smaller than ${INSTAGRAM_PAGE_POSTS} posts. ` + + "The next run resumes where this one left off.", + ); + return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}) }; + } + // Fewer posts than were asked for: the walk reached the account's first post. + if (rows.emitted < plan.maxPosts) return { ...base, complete: true }; + if (plan.mode === "sync") { + log( + `All ${listed.length} posts of the page are new and none is archived: older new posts may lie below it. ` + + "The next Sync new walks on from the top down to what is archived.", + ); + } + return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}) }; +} + +export const instagramGalleryDlFetcher: SocialFetcher = { + id: INSTAGRAM_FETCHER_ID, + label: "Instagram (gallery-dl)", + platform: "instagram", + fields: { cookies: true, binPath: true, limit: true }, + + detect(url: string): boolean { + return isInstagramUrl(url) && instagramHandleFromUrl(url) !== null; + }, + + // NO REQUEST: an account's details cannot be read without a login, and a + // form's "Fetch details" press is not worth one. The handle and the + // canonical URL are read off the URL. + async probe(url: string): Promise<SocialFetcherProbe> { + const handle = instagramHandleFromUrl(url); + if (!handle) return { ok: false, error: "Not an Instagram account URL (https://www.instagram.com/<account>/)." }; + return { ok: true, name: handle, handle, url: instagramAccountUrl(handle) }; + }, + + fetch: (input) => fetchInstagramPosts(input), +}; + +registerSocialFetcher(instagramGalleryDlFetcher); diff --git a/common/social/instagramMedia.test.ts b/common/social/instagramMedia.test.ts @@ -0,0 +1,227 @@ +// 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 { + fakeInstagramMediaFetch, + fetchInstagramMedia, + instagramMediaLine, + instagramMediaPauseMs, + INSTAGRAM_MEDIA_MAX_BYTES, + INSTAGRAM_MEDIA_MAX_FILE_BYTES, + INSTAGRAM_MEDIA_MAX_FILES, + type InstagramMediaFetch, +} from "./instagramMedia"; + +const CDN = "https://cdn.example.invalid"; +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<string, unknown> }[]; 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<string> { + 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"); + } + assert.deepEqual(c.pauses, [3000, 3000]); + assert.deepEqual({ ...sum }, { fetched: 3, bytes: 30, kept: 0, owed: 0, oversize: 0, failed: 0, postsWhole: 2, 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. + const c2 = cdn(() => ({ bytes: 600 })); + const sum2 = await fetchInstagramMedia({ outDir: await tmp(), plans: [plan(7, 5)], signal: signal(), deps: deps(c2), limits: { maxBytes: 1000 } }); + assert.equal(c2.calls.length, 2); + assert.equal(sum2.owed, 3); + } 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" }] }; + 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("the test server's CDN is played back, and there is none outside it", async () => { + assert.equal(fakeInstagramMediaFetch({}), null); + const f = fakeInstagramMediaFetch({ E2E_TEST_ROUTES: "1" })!; + const init = { signal: signal(), redirect: "error" as const, credentials: "omit" as const }; + 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)); +}); diff --git a/common/social/instagramMedia.ts b/common/social/instagramMedia.ts @@ -0,0 +1,337 @@ +// 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. +// +// - ONE GET per file, with no cookies, 2-5 s after the one before it. +// - A job fetches at most 40 files or 200 MB; a file over 100 MB is not +// fetched at all. 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: +// the CDN is asked for no more by this job. +// +// Files land in `channels/<slug>/posts-media/<pk>/` 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"; + +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; +const HEADERS_MS = 30_000; +const FILE_MS = 10 * 60_000; + +export type InstagramMediaFetch = ( + url: string, + init: { signal: AbortSignal; redirect: "error"; credentials: "omit" }, +) => Promise<{ + status: number; + headers: { get: (name: string) => string | null }; + body: (AsyncIterable<Uint8Array> & { cancel?: () => Promise<void> | void }) | null; +}>; + +export type InstagramMediaDeps = { + fetch: InstagramMediaFetch; + pause: (ms: number, signal: AbortSignal) => Promise<void>; + // The pause before a file that is not the job's first, in ms. + pauseMs: () => number; + now: () => number; +}; + +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<void> { + 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<InstagramMediaFetch>, + pause: sleep, + pauseMs: () => instagramMediaPauseMs(), + now: () => Date.now(), +}); + +// 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<Record<string, string | undefined>> = 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, + }; + }; +} + +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; refused?: boolean; oversize?: boolean }; + +// One file, streamed to `<name>.part` and renamed when whole. +async function fetchOne(o: { + url: string; + file: string; + cap: number; + fetch: InstagramMediaFetch; + signal: AbortSignal; +}): Promise<Fetched> { + const part = `${o.file}.part`; + const deadline = AbortSignal.any([o.signal, AbortSignal.timeout(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<ReturnType<InstagramMediaFetch>>; + try { + res = await o.fetch(o.url, { 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(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 > o.cap) { + await drop(); + return { ok: false, oversize: true, why: `it is ${mb(declared)}, over the ${mb(o.cap)} a file may be` }; + } + 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<void>((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve()))); + if (tooBig) { + await drop(); + await rm(part, { force: true }); + return { ok: false, oversize: true, why: `it is over the ${mb(o.cap)} a file may be` }; + } + if (bytes === 0) { + await rm(part, { force: true }); + return { ok: false, why: "the CDN answered an empty file" }; + } + await rename(part, o.file); + 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), and files over the per-file cap. + owed: number; + oversize: number; + failed: number; + // Posts whose media are whole on disk after the job. + postsWhole: number; + posts: number; + // Why the media half stopped before its last file, when it did. + stopped?: string; +}; + +async function exists(file: string): Promise<boolean> { + 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[]; + signal: AbortSignal; + onLog?: (line: string) => void; + deps?: Partial<InstagramMediaDeps>; + limits?: { maxFiles?: number; maxBytes?: number; maxFileBytes?: number }; +}): Promise<InstagramMediaSummary> { + 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 sum: InstagramMediaSummary = { fetched: 0, bytes: 0, kept: 0, owed: 0, oversize: 0, failed: 0, postsWhole: 0, posts: opts.plans.length }; + let asked = 0; + let refusals = 0; + 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 file = path.join(dir, path.basename(f.name)); + if (await exists(file)) { + sum.kept++; + landed.push(await describeCapturedFile(dir, path.basename(f.name), f.url)); + continue; + } + if (opts.signal.aborted) { + owed = true; + sum.owed++; + problems.push(`${f.name}: owed (cancelled)`); + continue; + } + if (sum.stopped) { + owed = true; + sum.owed++; + problems.push(`${f.name}: owed (${sum.stopped})`); + continue; + } + if (asked >= maxFiles || sum.bytes >= maxBytes) { + sum.stopped = `this job's media budget of ${maxFiles} files / ${mb(maxBytes)} is used`; + log(`This job's media budget (${maxFiles} files / ${mb(maxBytes)}) is used: the rest is owed to a later capture.`); + owed = true; + sum.owed++; + problems.push(`${f.name}: owed (${sum.stopped})`); + continue; + } + if (asked > 0) await deps.pause(deps.pauseMs(), opts.signal); + if (opts.signal.aborted) { + owed = true; + sum.owed++; + problems.push(`${f.name}: owed (cancelled)`); + continue; + } + asked++; + const got = await fetchOne({ url: f.url, file, cap: maxFileBytes, fetch: deps.fetch, signal: opts.signal }); + if (got.ok) { + refusals = 0; + sum.fetched++; + sum.bytes += got.bytes; + landed.push(await describeCapturedFile(dir, path.basename(f.name), f.url)); + continue; + } + problems.push(`${f.name}: ${got.why}`); + if (got.oversize) { + refusals = 0; + sum.oversize++; + continue; + } + refusals = got.refused ? refusals + 1 : 0; + if (got.refused) { + owed = true; + sum.owed++; + } else sum.failed++; + if (refusals >= INSTAGRAM_MEDIA_MAX_REFUSALS) { + sum.stopped = `the CDN refused ${INSTAGRAM_MEDIA_MAX_REFUSALS} files in a row`; + log( + `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++; + const prior = await readPostCapture(dir); + const record: PostCaptureRecord = { + ...(prior ?? {}), + version: 1, + id: plan.id, + url: plan.url, + capturedAt: new Date(deps.now()).toISOString(), + state: "captured", + mediaState: whole ? (landed.length > 0 ? "ok" : "none") : "error", + media: landed, + }; + delete record.mediaOwed; + delete record.error; + if (!whole) { + if (owed) record.mediaOwed = "next"; + record.error = problems.join("; "); + } + await writePostCapture(dir, record); + } + return sum; +} + +// 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.failed) parts.push(`${sum.failed} failed`); + return `Media: ${parts.join(", ")}; ${sum.postsWhole} of ${sum.posts} post(s) whole.`; +} diff --git a/common/social/instagramNormalize.test.ts b/common/social/instagramNormalize.test.ts @@ -0,0 +1,117 @@ +// gallery-dl's Instagram rows as Posts (instagramNormalize.ts), on invented runs. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { parsePost } from "../lib/posts"; +import { instagramPkFromShortcode, instagramShortcodeFromPk } from "../lib/instagram/ids"; +import { instagramDateToIso, parseInstagramRun, quoteBigIntegers } from "./instagramNormalize"; +import { IG_CDN, IG_HANDLE, igError, igPk, igRows, igStdout } from "./__fixtures__/instagramRun"; + +const ctx = { channelSlug: "example-ig", handle: IG_HANDLE }; + +test("a picture, a carousel and a reel: one Post each, keyed by the pk, with its files in order", () => { + const rows = igRows([ + { n: 3, date: "2026-03-03 10:00:00", text: "a reel https://example.com/a.", media: ["video"], likes: 7 }, + { n: 2, date: "2026-03-02 09:30:00", text: "three of them", media: ["image", "video", "image"] }, + { n: 1, date: "2026-03-01 08:00:00", text: "" }, + ]); + const run = parseInstagramRun(igStdout(rows), ctx)!; + assert.equal(run.emitted, 3); + assert.equal(run.error, undefined); + const [reel, carousel, picture] = run.posts; + assert.equal(reel!.post.id, igPk(3)); + assert.equal(reel!.post.slug, `example-ig/${igPk(3)}`); + assert.equal(reel!.post.platform, "instagram"); + assert.equal(reel!.post.createdAt, "2026-03-03T10:00:00.000Z"); + assert.equal(reel!.post.uploadDate, "20260303"); + assert.equal(reel!.post.url, `https://www.instagram.com/reel/${instagramShortcodeFromPk(igPk(3))}/`); + assert.deepEqual(reel!.post.instagram, { kind: "reel", shortcode: instagramShortcodeFromPk(igPk(3)) }); + assert.deepEqual(reel!.post.links, ["https://example.com/a"]); + assert.deepEqual(reel!.post.engagement, { likes: 7 }); + assert.equal(reel!.post.mediaCount, 1); + assert.deepEqual(reel!.files.map((f) => [f.num, f.kind, f.name]), [[1, "video", `01-${igPk(301)}.mp4`]]); + assert.ok(reel!.files[0]!.url.startsWith(IG_CDN)); + + assert.equal(carousel!.post.instagram?.kind, "post"); + assert.equal(carousel!.post.url, `https://www.instagram.com/p/${instagramShortcodeFromPk(igPk(2))}/`); + assert.equal(carousel!.post.mediaCount, 3); + assert.deepEqual(carousel!.files.map((f) => f.kind), ["image", "video", "image"]); + assert.deepEqual(carousel!.files.map((f) => f.num), [1, 2, 3]); + // The signed addresses are never part of the stored post. + assert.equal(carousel!.post.media, undefined); + assert.ok(!JSON.stringify(carousel!.post).includes(IG_CDN)); + + assert.equal(picture!.post.text, ""); + assert.equal(picture!.post.isReply, false); + // What is written reads back the same. + for (const p of run.posts) assert.deepEqual(parsePost(JSON.parse(JSON.stringify(p.post))), p.post); + // The shortcode in the URL is the pk. + assert.equal(instagramPkFromShortcode(reel!.post.instagram!.shortcode!), reel!.post.id); +}); + +test("a pk printed as a bare number beyond 2^53 is kept whole", () => { + const pk = igPk(987654321); + const text = igStdout(igRows([{ n: 987654321, date: "2026-03-01 08:00:00" }]), [pk]); + assert.ok(text.includes(`"post_id": ${pk}`)); + assert.notEqual(String(JSON.parse(text)[0][1].post_id), pk, "a plain parse rounds it"); + assert.equal(parseInstagramRun(text, ctx)!.posts[0]!.post.id, pk); + assert.equal(quoteBigIntegers('{"a": 123, "b": 1234567890123456789}'), '{"a": 123, "b": "1234567890123456789"}'); +}); + +test("a pinned post is flagged, and one met twice is kept once", () => { + const rows = igRows([ + { n: 1, date: "2025-01-01 00:00:00", pinned: true }, + { n: 9, date: "2026-03-09 00:00:00" }, + { n: 1, date: "2025-01-01 00:00:00", pinned: true }, + ]); + const run = parseInstagramRun(igStdout(rows), ctx)!; + assert.equal(run.emitted, 3); + assert.deepEqual(run.posts.map((p) => [p.post.id, p.pinned]), [[igPk(1), true], [igPk(9), false]]); + assert.equal(run.posts[0]!.post.instagram?.pinned, true); + assert.equal(run.posts[0]!.files.length, 1); +}); + +test("a collaboration: the author is the owner, and the channel's account is among the coauthors", () => { + const rows = igRows([ + { n: 5, date: "2026-03-05 00:00:00", owner: "other.owner", ownerName: "Other Owner", coauthors: [{ username: IG_HANDLE, full_name: "Example Account", id: "4000000001" }] }, + // The row names no coauthor, yet the post is on this account's grid. + { n: 4, date: "2026-03-04 00:00:00", owner: "other.owner" }, + // The channel's own post with an invited collaborator. + { n: 3, date: "2026-03-03 00:00:00", coauthors: [{ username: "invited.one" }, { username: IG_HANDLE }] }, + ]); + const [a, b, c] = parseInstagramRun(igStdout(rows), ctx)!.posts; + assert.equal(a!.post.author, "other.owner"); + assert.equal(a!.post.authorName, "Other Owner"); + assert.equal(a!.post.channelSlug, "example-ig"); + assert.deepEqual(a!.post.instagram?.coauthors, [{ handle: IG_HANDLE, name: "Example Account", id: "4000000001" }]); + assert.deepEqual(b!.post.instagram?.coauthors, [{ handle: IG_HANDLE }]); + assert.equal(c!.post.author, IG_HANDLE); + assert.deepEqual(c!.post.instagram?.coauthors, [{ handle: "invited.one" }]); +}); + +test("the exception row is read; unreadable rows and stories are counted, never guessed", () => { + const rows = [ + ...igRows([{ n: 2, date: "2026-03-02 00:00:00" }, { n: 1, date: "not a date" }, { n: 7, date: "2026-03-07 00:00:00", type: "story" }]), + igError("HttpError", "'429 Too Many Requests' for 'https://www.instagram.com/api/v1/feed/user/4000000001/?count=30'"), + ]; + const run = parseInstagramRun(igStdout(rows), ctx)!; + assert.equal(run.posts.length, 1); + assert.equal(run.unreadable, 1); + assert.equal(run.otherKinds, 1); + assert.deepEqual(run.error, { error: "HttpError", message: "'429 Too Many Requests' for 'https://www.instagram.com/api/v1/feed/user/4000000001/?count=30'" }); + // A file row after an unread post is not given to the post before it. + assert.equal(run.posts[0]!.files.length, 1); +}); + +test("what is not gallery-dl's array reads as nothing", () => { + assert.equal(parseInstagramRun("", ctx), null); + assert.equal(parseInstagramRun("\nKeyboardInterrupt", ctx), null); + assert.equal(parseInstagramRun('{"a":1}', ctx), null); + assert.deepEqual(parseInstagramRun("[]", ctx), { posts: [], emitted: 0, unreadable: 0, otherKinds: 0 }); +}); + +test("gallery-dl's dates are UTC", () => { + assert.equal(instagramDateToIso("2026-03-01 08:00:00"), "2026-03-01T08:00:00.000Z"); + assert.equal(instagramDateToIso("2026-03-01T08:00:00+02:00"), "2026-03-01T06:00:00.000Z"); + assert.equal(instagramDateToIso("yesterday"), null); + assert.equal(instagramDateToIso(undefined), null); +}); diff --git a/common/social/instagramNormalize.ts b/common/social/instagramNormalize.ts @@ -0,0 +1,245 @@ +// gallery-dl's Instagram rows -> `Post`s and the media they carry (lane +// instagram). Pure: no I/O. +// +// `gallery-dl --dump-json` prints ONE JSON array when it exits (never line by +// line here: instagramGalleryDlFetcher.ts says why). Its rows: +// [2, {…post…}] a post ("directory" row): post_id, post_shortcode, +// username, fullname, description, post_date, type +// ("post" | "reel"), post_url, count, pinned, +// coauthors, likes +// [3, "<url>", {…file…}] one media file of the post before it: num, +// media_id, video_url | display_url, extension +// [-1, {error, message}] the exception that ended the run, when one did +// +// A post's pk is beyond 2^53 and gallery-dl may print it as a bare number: +// every long integer is quoted before the parse (quoteBigIntegers), and an id +// is a string of digits from then on. + +import type { Post } from "../lib/posts"; +import { postSlug, uploadDateFromCreatedAt } from "../lib/posts"; +import { + instagramPostUrl, + instagramShortcodeFromPk, + isInstagramPk, + isInstagramShortcode, +} from "../lib/instagram/ids"; + +export type InstagramMediaFile = { + // 1-based position in the post (a carousel's order). + num: number; + kind: "image" | "video"; + // The CDN address as the run printed it. Signed, and it EXPIRES: fetched in + // the same job, never stored in the post. + url: string; + // The file's name in `posts-media/<pk>/`. + name: string; +}; + +export type InstagramListedPost = { + post: Post; + pinned: boolean; + files: InstagramMediaFile[]; +}; + +export type InstagramRunRows = { + posts: InstagramListedPost[]; + // The exception that ended the run, when one did. + error?: { error: string; message: string }; + // How many post rows the run printed, repeats and unread ones included: + // what a `max-posts` cap is told by. + emitted: number; + // Post rows that could not be read (no pk, no date): counted, never guessed. + unreadable: number; + // Rows that are not a post or reel of the grid (a story, a highlight): left + // for the slice that reads them. + otherKinds: number; +}; + +// Quote every integer of 16 digits or more, so JSON.parse keeps it whole. +export function quoteBigIntegers(json: string): string { + return json.replace(/([:[,]\s*)(-?\d{16,})(?=\s*[,}\]])/g, '$1"$2"'); +} + +const str = (v: unknown): string | undefined => (typeof v === "string" && v ? v : undefined); +const idOf = (v: unknown): string | undefined => + typeof v === "string" && /^\d+$/.test(v) ? v : typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? String(v) : undefined; + +// gallery-dl prints a date as "YYYY-MM-DD HH:MM:SS", in UTC. +export function instagramDateToIso(v: unknown): string | null { + const s = str(v); + if (!s) return null; + const m = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(\.\d+)?(Z|[+-]\d{2}:?\d{2})?$/.exec(s); + if (!m) return null; + const ms = Date.parse(`${m[1]}T${m[2]}${m[3] ?? ""}${m[4] ?? "Z"}`); + return Number.isFinite(ms) ? new Date(ms).toISOString() : null; +} + +const LINK_RE = /https?:\/\/[^\s<>"'))\]]+/g; + +function linksIn(text: string): string[] { + const out: string[] = []; + for (const m of text.match(LINK_RE) ?? []) { + const url = m.replace(/[.,;:!?]+$/, ""); + if (!out.includes(url)) out.push(url); + } + return out; +} + +function extensionOf(file: Record<string, unknown>, url: string, kind: "image" | "video"): string { + const given = str(file.extension)?.toLowerCase(); + if (given && /^[a-z0-9]{1,5}$/.test(given)) return given; + try { + const m = /\.([A-Za-z0-9]{1,5})$/.exec(new URL(url).pathname); + if (m) return m[1]!.toLowerCase(); + } catch { + /* not a URL */ + } + return kind === "video" ? "mp4" : "jpg"; +} + +// "01-<media pk>.jpg": the carousel's order first, so a listing reads in it. +export function instagramMediaFileName(num: number, mediaId: string | undefined, ext: string): string { + const n = String(Math.max(1, Math.floor(num))).padStart(2, "0"); + return mediaId ? `${n}-${mediaId}.${ext}` : `${n}.${ext}`; +} + +function fileOf(url: string, raw: Record<string, unknown>, fallbackNum: number): InstagramMediaFile | null { + if (!/^https:\/\//i.test(url)) return null; + // A music track of a post is not its picture or video. + if (str(raw.audio_url)) return null; + // A video item yields its video (and no picture); a picture has no video_url. + const kind: "image" | "video" = str(raw.video_url) ? "video" : "image"; + const num = typeof raw.num === "number" && raw.num >= 1 ? Math.floor(raw.num) : fallbackNum; + const ext = extensionOf(raw, url, kind); + return { num, kind, url, name: instagramMediaFileName(num, idOf(raw.media_id), ext) }; +} + +function coauthorsOf(raw: unknown, owner: string, channelHandle: string): NonNullable<NonNullable<Post["instagram"]>["coauthors"]> { + const out: NonNullable<NonNullable<Post["instagram"]>["coauthors"]> = []; + const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase(); + if (Array.isArray(raw)) { + for (const item of raw) { + if (!item || typeof item !== "object") continue; + const c = item as Record<string, unknown>; + const handle = str(c.username); + if (!handle || same(handle, owner) || out.some((o) => same(o.handle, handle))) continue; + const id = idOf(c.id); + const name = str(c.full_name); + out.push({ handle, ...(name ? { name } : {}), ...(id ? { id } : {}) }); + } + } + // A post the channel's account did not make is on its grid as a + // collaboration: the account is among the coauthors even when the row + // names none. + if (channelHandle && !same(channelHandle, owner) && !out.some((o) => same(o.handle, channelHandle))) { + out.push({ handle: channelHandle }); + } + return out; +} + +// One post row as a Post, or null when it is not one this slice archives +// ("other") or cannot be read ("unreadable"). +export function normalizeInstagramPost( + raw: Record<string, unknown>, + ctx: { channelSlug: string; handle: string }, +): { post: Post; pinned: boolean } | "other" | "unreadable" { + const type = str(raw.type) ?? "post"; + if (type !== "post" && type !== "reel") return "other"; + const id = idOf(raw.post_id); + const createdAt = instagramDateToIso(raw.post_date ?? raw.date); + if (!id || !isInstagramPk(id) || !createdAt) return "unreadable"; + const kind = type === "reel" ? "reel" : "post"; + const given = str(raw.post_shortcode); + const shortcode = given && isInstagramShortcode(given) ? given : (instagramShortcodeFromPk(id) ?? undefined); + const author = str(raw.username) ?? ctx.handle; + const authorName = str(raw.fullname); + const text = typeof raw.description === "string" ? raw.description : ""; + const pinned = Array.isArray(raw.pinned) ? raw.pinned.length > 0 : raw.pinned === true; + const coauthors = coauthorsOf(raw.coauthors, author, ctx.handle); + const count = typeof raw.count === "number" && raw.count >= 0 ? Math.floor(raw.count) : undefined; + const likes = typeof raw.likes === "number" && raw.likes >= 0 ? Math.floor(raw.likes) : undefined; + const post: Post = { + id, + slug: postSlug(ctx.channelSlug, id), + channelSlug: ctx.channelSlug, + author, + ...(authorName ? { authorName } : {}), + createdAt, + uploadDate: uploadDateFromCreatedAt(createdAt), + text, + url: shortcode ? instagramPostUrl(kind, shortcode) : (str(raw.post_url) ?? ""), + platform: "instagram", + isReply: false, + isRepost: false, + links: linksIn(text), + ...(count !== undefined ? { mediaCount: count } : {}), + ...(likes !== undefined ? { engagement: { likes } } : {}), + instagram: { + kind, + ...(shortcode ? { shortcode } : {}), + ...(pinned ? { pinned: true } : {}), + ...(coauthors.length > 0 ? { coauthors } : {}), + }, + }; + return { post, pinned }; +} + +// Everything a run printed, in the order it printed it. A post met twice (a +// pinned post is on the grid again further down) is kept once, the first time. +export function parseInstagramRun(stdout: string, ctx: { channelSlug: string; handle: string }): InstagramRunRows | null { + const text = stdout.trim(); + if (!text) return null; + let rows: unknown; + try { + rows = JSON.parse(quoteBigIntegers(text)); + } catch { + return null; + } + if (!Array.isArray(rows)) return null; + const out: InstagramRunRows = { posts: [], emitted: 0, unreadable: 0, otherKinds: 0 }; + const byId = new Map<string, InstagramListedPost>(); + let current: InstagramListedPost | null = null; + for (const row of rows) { + if (!Array.isArray(row)) continue; + const [tag, a, b] = row as [unknown, unknown, unknown]; + if (tag === -1 && a && typeof a === "object") { + const e = a as Record<string, unknown>; + out.error = { error: str(e.error) ?? "Error", message: str(e.message) ?? "" }; + continue; + } + if (tag === 2 && a && typeof a === "object") { + out.emitted++; + const n = normalizeInstagramPost(a as Record<string, unknown>, ctx); + if (n === "other") { + out.otherKinds++; + current = null; + continue; + } + if (n === "unreadable") { + out.unreadable++; + current = null; + continue; + } + const seen = byId.get(n.post.id); + if (seen) { + // The files of a repeat are the same files: not listed twice. + current = null; + continue; + } + current = { post: n.post, pinned: n.pinned, files: [] }; + byId.set(n.post.id, current); + out.posts.push(current); + continue; + } + if (tag === 3 && typeof a === "string" && current) { + const file = fileOf(a, b && typeof b === "object" ? (b as Record<string, unknown>) : {}, current.files.length + 1); + if (file && !current.files.some((f) => f.name === file.name)) current.files.push(file); + } + } + for (const p of out.posts) { + // The row's own count is of every file (a track included): what the + // archive counts is the pictures and videos it listed. + if (p.files.length > 0) p.post.mediaCount = p.files.length; + } + return out; +} diff --git a/common/social/instagramSignals.test.ts b/common/social/instagramSignals.test.ts @@ -0,0 +1,80 @@ +// What one gallery-dl run says about Instagram (instagramSignals.ts). Every +// line here is invented, in the shape gallery-dl 1.32.9 prints. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + classifyInstagramError, + isInstagramPrivateLine, + parseInstagramCursorLine, + parseInstagramRequestLine, + profilePageStatus, +} from "./instagramSignals"; + +const req = (path: string, status: number, method = "GET") => + `[urllib3.connectionpool][debug] https://www.instagram.com:443 "${method} ${path} HTTP/1.1" ${status} ${status === 200 ? "None" : "20445"}`; +const H = "example.account"; +const UID = "4000000001"; +const lines = (...l: string[]) => l.map((x) => parseInstagramRequestLine(x)!).filter(Boolean); + +test("a request line is read; other lines are not requests", () => { + assert.deepEqual(parseInstagramRequestLine(req(`/api/v1/feed/user/${UID}/?count=30`, 404)), { + host: "www.instagram.com", + method: "GET", + path: `/api/v1/feed/user/${UID}/?count=30`, + status: 404, + }); + assert.equal(parseInstagramRequestLine("[urllib3.connectionpool][debug] Starting new HTTPS connection (1): www.instagram.com:443"), null); + assert.equal(parseInstagramRequestLine("[instagram][debug] Sleeping 8.83 seconds (request)"), null); + assert.equal(parseInstagramRequestLine(req("/api/v1/clips/user/", 200, "POST"))?.method, "POST"); +}); + +test("the cursor line and the private warning", () => { + assert.equal(parseInstagramCursorLine("[instagram][debug] Cursor: 3500000000000000001_4000000001"), "3500000000000000001_4000000001"); + assert.equal(parseInstagramCursorLine("[instagram][debug] Sleeping 8.83 seconds (request)"), null); + assert.ok(isInstagramPrivateLine("[instagram][warning] example.account's posts are private")); +}); + +test("LOGGED OUT: the search's 404 then the feed's 404 is the login, never a gone account", () => { + const requests = lines(req(`/web/search/topsearch/?query=${H}`, 404), req(`/${H}`, 200), req(`/api/v1/feed/user/${UID}/?count=30`, 404)); + const s = classifyInstagramError( + { error: "HttpError", message: `'404 Not Found' for 'https://www.instagram.com/api/v1/feed/user/${UID}/?count=30'` }, + { requests, handle: H }, + ); + assert.equal(s.class, "login"); + assert.match(s.line, /^HttpError: '404 Not Found'/); +}); + +test("the account is gone only when its own page answered 404", () => { + const row = { error: "NotFoundError", message: "Requested user could not be found" }; + const gone = lines(req(`/web/search/topsearch/?query=${H}`, 404), req(`/${H}`, 404)); + assert.equal(classifyInstagramError(row, { requests: gone, handle: H }).class, "not-found"); + // The handle's case and a trailing slash do not matter. + assert.equal(profilePageStatus(lines(req("/Example.Account/", 404)), H), 404); + // The lookup failed some other way (a login redirect swallowed by gallery-dl): not proven gone. + const walled = lines(req(`/web/search/topsearch/?query=${H}`, 404), req(`/${H}`, 302), req("/accounts/login/?next=%2F", 200)); + assert.equal(classifyInstagramError(row, { requests: walled, handle: H }).class, "login"); + assert.equal(classifyInstagramError(row, { requests: [], handle: H }).class, "login"); + // Another account's page is not this one's. + assert.equal(profilePageStatus(lines(req("/someone.else", 404)), H), null); +}); + +test("redirects: the challenge and checkpoint pages, the login and home pages", () => { + const ctx = { requests: [], handle: H }; + const abort = (page: string, url: string) => ({ error: "AbortExtraction", message: `HTTP redirect to ${page} page (${url})` }); + assert.equal(classifyInstagramError(abort("challenge", "https://www.instagram.com/challenge/"), ctx).class, "challenge"); + assert.equal(classifyInstagramError(abort("login", "https://www.instagram.com/accounts/login/"), ctx).class, "login"); + assert.equal(classifyInstagramError(abort("home", "https://www.instagram.com/"), ctx).class, "login"); + assert.equal(classifyInstagramError({ error: "AuthRequired", message: "authenticated cookies needed to access this resource" }, ctx).class, "login"); + assert.equal(classifyInstagramError({ error: "ChallengeError", message: "Cloudflare challenge (403 Forbidden) for 'https://www.instagram.com/x'" }, ctx).class, "challenge"); +}); + +test("a 429, a 401 and a 403 are the rate limit; a 5xx and a crash are plain errors", () => { + const ctx = { requests: [], handle: H }; + const http = (s: string) => ({ error: "HttpError", message: `'${s}' for 'https://www.instagram.com/api/v1/feed/user/${UID}/?count=30'` }); + assert.equal(classifyInstagramError(http("429 Too Many Requests"), ctx).class, "rate-limit"); + assert.equal(classifyInstagramError(http("401 Unauthorized"), ctx).class, "rate-limit"); + assert.equal(classifyInstagramError(http("403 Forbidden"), ctx).class, "rate-limit"); + assert.equal(classifyInstagramError(http("500 Internal Server Error"), ctx).class, "error"); + assert.equal(classifyInstagramError({ error: "KeyError", message: "'items'" }, ctx).class, "error"); + assert.equal(classifyInstagramError({ error: "AbortExtraction", message: "example.account's posts are private" }, ctx).class, "private"); +}); diff --git a/common/social/instagramSignals.ts b/common/social/instagramSignals.ts @@ -0,0 +1,105 @@ +// WHAT ONE gallery-dl RUN SAYS ABOUT INSTAGRAM (lane instagram). Pure and +// client-safe. +// +// gallery-dl's `--dump-json` run ends 0 whatever happened: an exception is +// the LAST ROW of what it prints, `[-1, {"error": <class>, "message": <text>}]`, +// and with `--verbose` each request is a line on stderr, +// `[urllib3.connectionpool][debug] https://www.instagram.com:443 "GET /path HTTP/1.1" 404 20445`. +// Both are read here, because the error row alone lies about two things +// (one logged-out read, 18 Nov 2026): +// +// - LOGGED OUT, Instagram answers the feed endpoint — and the account +// search — with a 404 "Page Not Found". That is "needs a login", never +// "the account is gone". +// - gallery-dl turns EVERY failure of its account lookup into +// `NotFoundError: Requested user could not be found`, a login redirect +// included. The account is gone only when the PROFILE PAGE's own request +// (`GET /<handle>`) answered 404. +// +// The classes, and what each does (instagramGalleryDlFetcher.ts): +// "challenge" a redirect to Instagram's challenge or checkpoint page: the +// alert goes up and every Instagram job is refused until a +// person's Recheck. +// "login" a redirect to its login (or home) page, an auth error, the +// feed's or the search's 404: the same alert, as a login failure. +// "rate-limit" a 429, or a 401/403 (Instagram's "please wait a few minutes" +// is a 401): the run ends and Instagram cools down for an hour. +// "private" the account is private and the login does not follow it. +// "not-found" the profile page itself answered 404. +// "error" anything else that failed (a 5xx, a crash): no alert, no cooldown. + +export type InstagramSignalClass = "challenge" | "login" | "rate-limit" | "private" | "not-found" | "error"; + +export type InstagramRequestLine = { method: string; host: string; path: string; status: number }; + +const REQUEST_LINE = + /^\[urllib3\.connectionpool\]\[debug\]\s+https?:\/\/([^\s:/]+)(?::\d+)?\s+"([A-Z]+)\s+(\S+)\s+HTTP\/[\d.]+"\s+(\d{3})\b/; + +// One stderr line as a request gallery-dl made, or null. +export function parseInstagramRequestLine(line: string): InstagramRequestLine | null { + const m = REQUEST_LINE.exec(line.trim()); + if (!m) return null; + return { host: m[1]!.toLowerCase(), method: m[2]!, path: m[3]!, status: Number(m[4]) }; +} + +export function isInstagramApiHost(host: string): boolean { + return host === "instagram.com" || host.endsWith(".instagram.com"); +} + +const CURSOR_LINE = /\]\[debug\]\s+Cursor:\s+(\S+)\s*$/; + +// The resume point gallery-dl logs after each page it finished, or null. +export function parseInstagramCursorLine(line: string): string | null { + return CURSOR_LINE.exec(line)?.[1] ?? null; +} + +const PRIVATE_LINE = /posts are private/i; + +export function isInstagramPrivateLine(line: string): boolean { + return PRIVATE_LINE.test(line); +} + +// What a request for the account's own page (`GET /<handle>`) answered, or +// null when the run made none. +export function profilePageStatus(requests: readonly InstagramRequestLine[], handle: string): number | null { + const want = `/${handle}`.toLowerCase(); + for (const r of requests) { + if (!isInstagramApiHost(r.host) || r.method !== "GET") continue; + const p = r.path.split("?")[0]!.replace(/\/+$/, "").toLowerCase(); + if (p === want) return r.status; + } + return null; +} + +const STATUS_IN_MESSAGE = /'(\d{3}) [^']*' for '([^']*)'/; + +export type InstagramSignal = { class: InstagramSignalClass; line: string }; + +// The error row of a run (`error` its class, `message` its text), read with +// the requests the run made and the account it asked for. +export function classifyInstagramError( + row: { error: string; message: string }, + ctx: { requests: readonly InstagramRequestLine[]; handle: string }, +): InstagramSignal { + const line = `${row.error}: ${row.message}`.trim().slice(0, 300); + const text = `${row.error} ${row.message}`; + if (/redirect to challenge page|\/challenge\/|checkpoint|ChallengeError/i.test(text)) return { class: "challenge", line }; + if (/redirect to (?:login|home) page|\/accounts\/login/i.test(text)) return { class: "login", line }; + if (/AuthRequired|AuthenticationError|AuthorizationError|authenticated cookies|login required|credentials/i.test(text)) { + return { class: "login", line }; + } + if (PRIVATE_LINE.test(text)) return { class: "private", line }; + if (/NotFoundError/.test(row.error) || /could not be found/i.test(row.message)) { + return { class: profilePageStatus(ctx.requests, ctx.handle) === 404 ? "not-found" : "login", line }; + } + const http = STATUS_IN_MESSAGE.exec(row.message); + if (http) { + const status = Number(http[1]); + if (status === 429 || status === 401 || status === 403) return { class: "rate-limit", line }; + // The feed's, the search's or any API path's "Page Not Found": the login. + if (status === 404) return { class: "login", line }; + return { class: "error", line }; + } + if (/\b429\b|too many requests|wait a few minutes/i.test(text)) return { class: "rate-limit", line }; + return { class: "error", line }; +} diff --git a/common/social/xCookieSource.ts b/common/social/xCookieSource.ts @@ -96,17 +96,13 @@ export type InstagramSocialSettings = { // channel's posts are built only into PRIVATE sites. The rule is // lib/postsVisibility.ts, the same shape as X's with the other default. visibility?: InstagramPostsVisibility; - // Let an Instagram channel with no cookie source of its own be read LOGGED - // OUT. Stored only when true; absent = such a channel refuses to fetch. - // Whether Instagram answers a logged-out read at all is unproven. - allowLoggedOut?: boolean; }; export type SocialSettings = { x: XSocialSettings; // Absent: nothing set. xenforo?: XenforoSocialSettings; - // Absent: nothing set (private, and no logged-out reads). + // Absent: nothing set (private). instagram?: InstagramSocialSettings; }; @@ -128,7 +124,6 @@ export function sanitizeSocial(value: unknown): SocialSettings { : {}) as Record<string, unknown>; const instagram: InstagramSocialSettings = { ...(isInstagramPostsVisibility(ig.visibility) ? { visibility: ig.visibility } : {}), - ...(ig.allowLoggedOut === true ? { allowLoggedOut: true } : {}), }; const retryOnBlock = parseRetryOnBlock(xf.retryOnBlock); const maxCookieAgeMinutes = parseXMaxCookieAgeMinutes(x.maxCookieAgeMinutes);