commit 519cd561663e329fd729ed37988b6b726ae5afc8
parent 327b25624e8e328dafef12a77ac7df07df41ac79
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 17:26:11 -0500
Merge lane/instagram: an Instagram account is a posts channel, slice 1 -- its posts, reels and carousels are read through gallery-dl with the channel's own cookie source and archived by their numeric id, with their media fetched in the same job from Instagram's own media hosts; one job at a time on Instagram's queue, ten minutes apart, never a retry: a rate limit holds everything Instagram for an hour, and a login wall, a challenge or a second refusal raises an alert that stops every Instagram job until the operator rechecks; a sync that was cut short continues down to where it began; a channel with no cookie source is refused before any request; Instagram posts are private by default on every build path; yt-dlp is not started for an instagram.com address; X is unchanged
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
95 files changed, 6289 insertions(+), 92 deletions(-)
diff --git a/CHANNEL.md b/CHANNEL.md
@@ -16,11 +16,11 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
|---|---|---|
| `handling` | required | REQUIRED. `"youtube"` (fetch the platform's captions) or `"transcribe"` (download audio and transcribe it locally). A file without a valid `handling` is not a channel: it reads as null. |
| `sourceKind` | config | What KIND of source this is: `"video"` (default — yt-dlp + transcription) or `"social"` (an account fetched into the posts corpus, skipped by the video scan). A separate axis from `handling`, so every binary handling branch stays binary. |
-| `postFetcher` | config | Social channels only: which social fetcher drives ingest (e.g. `"bluesky-atproto"`, `"x-gallery-dl"`). Absent = resolve by URL detection. Trimmed. |
+| `postFetcher` | config | Social channels only: which social fetcher drives ingest (e.g. `"bluesky-atproto"`, `"x-gallery-dl"`, `"instagram-gallery-dl"`). Absent = resolve by URL detection. Trimmed. |
| `socialHandle` | config | Social channels only: the bare account handle (a leading "@" is stripped). Derived from `url` at creation but stored, so a later URL-format change upstream cannot silently re-point ingest at a different account. |
| `postPagePauseSeconds` | config | Social channels that are read page by page (a forum thread) only: the pause between two page loads, in seconds; each pause is jittered to 0.85–1.65× of it. Absent = the fetcher's own (12 s, so 10–20 s); floored at 5, capped at 600. |
| `postCaptureThread` | config | X channels only: `capture-posts` also shoots each reply's THREAD SHOT — the post it answers over the reply, `posts-media/<id>/shot-thread.png` beside `shot.png`, the parent's author blurred unless verified or the reply's own — unless the run says `"thread": false`. Absent = false (a run asks with `"thread": true`). |
-| `platform` | config | The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, "archive.org items"), bitchute (BitChute videos and channels; see README.md, "BitChute"), twitter, bluesky, xenforo (a forum thread) or webpage (Wayback Machine captures of pages; see `wayback`). An unknown value is dropped. |
+| `platform` | config | The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, "archive.org items"), bitchute (BitChute videos and channels; see README.md, "BitChute"), twitter, bluesky, xenforo (a forum thread), webpage (Wayback Machine captures of pages; see `wayback`) or instagram (an Instagram account's posts and reels; OPERATING.md, "Instagram accounts"). An unknown value is dropped. |
| `name` | config | Display name. |
| `url` | config | The channel / playlist / account URL syncs enumerate. Absent = the channel is never auto-synced. |
| `audioFormat` | config | `"m4a"`, `"mp3"` or `"opus"`: the audio a transcribe-handling download keeps. |
@@ -45,13 +45,13 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `excludeFromCleanup` | config | Leave this channel's reclaimable bytes out of the aggregate "cleanable data" total on /cleanup and its badge. The per-channel cleanup sweeps stay available; only the running total changes. |
| `excludeFromCompaction` | config | Keep this channel's saved videos out of compaction (`compact-saved-videos`, a re-encode to AV1 that becomes the active copy): neither the selector nor an explicit list touches them. For a channel whose stored bytes are kept as evidence. Absent = false. |
| `cleanAfterCaptureUnverified` | config | Let clean-after-capture (settings `diarization.cleanAfterCapture`) delete this channel's audio with NO availability check. Only for a channel with no `url`: with no source there is nothing to list, so the automatic per-video clean holds every such channel ("no source to check: clean by hand") unless this is true. The manual Clean audio sweep is unaffected. Absent/false = held. |
-| `syncIntervalMinutes` | config | Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. |
+| `syncIntervalMinutes` | config | Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. AN INSTAGRAM CHANNEL is synced seldom, because every sync is a logged-in read: absent = every 12 hours at the most often (the global default when that is longer), and a value of its own is never under 240 (4 hours); 0 still turns it off (`common/jobs/syncScheduler.ts`). |
| `fullSweepIntervalMinutes` | config | Full-sweep cadence: a sync upgrades itself to a full sweep when `now - lastFullSweepAt >= fullSweepIntervalMinutes`. Absent = inherit `syncScheduler.fullSweepIntervalMinutes`; 0 = never sweep (every sync is a paged walk); positives clamp to [1, 44640]. |
| `skipLiveDownloads` | config | Per-channel override for the global `skipLiveDownloads`. Absent = inherit; false = allow downloading currently-live / upcoming videos. |
| `downloadMode` | config | `"auto"` (default) or `"manual"`. Manual: nothing is downloaded unasked — the download lane skips the channel, a sync or full sweep reads the listing (roster, `playlist`, maybe-missing) but downloads none of the new uploads it finds, and the batch downloads (Download from playlist, Download videos / `download-missing`, a bucket retry) refuse. What someone asks for still downloads: `import-video`, the video page's download and persist buttons, `persist-videos`, clip windows (`fetch-windows`), a whole-recording fetch; videos on disk are still transcribed by the lanes. The listed videos it never downloaded are reported as not requested (`manualNotRequestedIds` in its report), never as undownloaded work or as never-fetched losses. A Configure field (`downloadMode`). |
| `downloadFilter` | config | Per-channel title/description download filter, matched against the per-video metadata prefetch. A declined video is SETTLED by a terminal download-outcome keyed on the filter's signature, not by an archive line, so changing either pattern re-evaluates every settled video on the next run. An object with no real rule is dropped (the filter is inert). See [`downloadFilter`](#downloadfilter). |
| `skipShorts` | config | `true`: the channel's YouTube Shorts — the listing entries whose URL is `youtube.com/shorts/<id>` — are not wanted. Decided from the listing URL alone (no metadata): a sync or full sweep does not download them, Download from playlist, Download videos and the bucket retries skip them, the metadata scan does not read them, and the report lists the ones with nothing on disk as `skippedShortsIds` instead of as undownloaded work (or, once delisted, as never-fetched losses). Importing a Shorts URL still downloads it, and a Short already on disk stays an ordinary video. Absent = Shorts are downloaded like any upload. A Configure field (`skipShorts`). |
-| `cookiesFromBrowser` | config | Per-channel override of the global cookies-from-browser spec (a browser spec, or `file:<path>` for a cookies.txt). Trimmed; blank = inherit. A `firefox[:profile]` spec also sends that Firefox's own User-Agent (derived, so a Cloudflare clearance it earned is honoured after a browser update); a `--user-agent` in `ytdlpExtraArgs` overrides it. |
+| `cookiesFromBrowser` | config | Per-channel override of the global cookies-from-browser spec (a browser spec, or `file:<path>` for a cookies.txt). Trimmed; blank = inherit. A `firefox[:profile]` spec also sends that Firefox's own User-Agent (derived, so a Cloudflare clearance it earned is honoured after a browser update); a `--user-agent` in `ytdlpExtraArgs` overrides it. AN INSTAGRAM CHANNEL reads ONLY this, never the global spec: Instagram shows an account's posts only to a login, whose account is at risk of a checkpoint or a ban, so the source is chosen per channel — blank means nothing is fetched (`fetch-posts` refuses and says so). Name a browser profile or cookies file logged in to Instagram with an account kept for the archive. |
| `cookieMode` | config | Per-channel override of the global cookie mode. Absent = inherit. |
| `sleepBetweenDownloadsSeconds` | config | Per-channel override for the global pause between downloads. Absent = inherit; 0 = no sleep; floored and capped at 600. |
| `audioCheck` | config | Audio-integrity checking for sources that intermittently serve corrupt audio mid-download: the managed downloader periodically validates the in-progress `.part` file and rolls back to the last known-good snapshot on corruption (transcribe handling), and a clip window gets the same final probe, fetched once more when malformed and never kept when malformed twice. ON BY DEFAULT for an Odysee video (`audioCheck: {"enabled": false}` turns it off); the channel's opt-in for any other platform. See [`audioCheck`](#audiocheck). |
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -167,9 +167,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. "storedUrl": "fallback" \| "only" reads each video from the media URL its record stores when the page is rate-limited (or always), one file per 20 min; with one, a held platform's run goes ahead as "only". | |
| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` |
| `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | |
-| `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"} is SYNC NEW — from the top of the timeline down to the newest archived post (a sync that stopped part-way continues down to the watermark it began with). It never reads or clears an unfinished backfill's resume point. "backfill": true is RESUME BACKFILL instead (the same as resume-backfill). "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full", "older" and "backfill" are one at a time. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run of the same walk resumes there. | `pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait` |
+| `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"} is SYNC NEW — from the top of the timeline down to the newest archived post (a sync that stopped part-way continues down to the watermark it began with). It never reads or clears an unfinished backfill's resume point. "backfill": true is RESUME BACKFILL instead (the same as resume-backfill). "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full", "older" and "backfill" are one at a time. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. AN INSTAGRAM CHANNEL: a sync reads ONE page (up to 30 posts), a first fetch, "full" or "backfill" walks up to 120 posts and the next run resumes; the new posts' pictures and videos are fetched in the same job (a sync 40 files / 200 MB, a walk 120 / 600 MB, 100 MB a file; a walk leaves the posts whose media would not fit for its next run; what is still not fetched is recorded as owed, and none after a refusal). Refused before a job exists when the channel has no cookiesFromBrowser of its own, with "retryOnBlock" or "older", and with a "queueKey" other than platform:instagram. A login, challenge or checkpoint page raises Instagram's alert and refuses every Instagram job until recheck-service; the first 429 holds Instagram for an hour (clear-platform-hold {"platform": "instagram"} ends that by hand). A drained fetch stops at its next resume point and the next run of the same walk resumes there. | `pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait` |
| `resume-backfill` | resume-backfill continues a social channel's unfinished full-history timeline walk (X, Bluesky) from its saved resume point, with no watermark: {"slug"} ("limit"? caps the posts this run reads). The walk is left part-way by a first fetch, a full re-walk or a backfill that stopped; the channel page then says "backfill unfinished — N archived" and shows Resume backfill. Nothing resumes it but this (or fetch-posts "backfill": true): a plain fetch-posts, Sync and the scheduler sync new posts and keep its place. Refused when none is part-way, on a forum thread (every fetch catches up, then continues its history) and on an X search channel. | `pnpm ops resume-backfill --json '{"slug":"example-x"}' --wait` |
-| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/<id>/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"<id>": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/<handle>.<ext> + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["<one of their post ids>"\], "avatarsOnly": true}. X also reads each post's CONTEXT off the same page -- the post it quotes and the post it answers (its author, check, date, words, media links) -- into its capture.json's "context"; "context": false turns that off. "contextOnly": true (X) loads ONE page per post for that alone (and the avatars it shows): the context written into capture.json, nothing shot, no media, article, thread shot or availability; a post whose context is already read is skipped unless "force". Not with "avatarsOnly". Paced like a post fetch, on its queue. An X trending library is captured by this same job, under channels/<slug>/trending/posts-media/<id>/. Its media comes from X's media CDN by the addresses in the library's saved captures: no login, one file after another 1-2 s apart, under X's cooldown, each file kept once (trending/media-store/, a hardlink per post). A file over the library's maxVideoMb (100 MB) and whatever is past the job's budget (40 files / 200 MB) is owed: asked for again by the next capture of that post. A 429 from the CDN stops the job and leaves X alone for 15 minutes; a 403 or 404 marks the file; three refusals in a row (a 403, or no answer) and the job asks the CDN no more; nothing retries. "keptMedia": true is for posts marked keep (refused for any other id): no per-file cap, and a post the CDN cannot serve whole is downloaded the logged-in way, if it is still kept when that download would start. A library's capture runs on X's queue only: "queueKey" is refused for it. | |
+| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/<id>/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. An Instagram channel is refused: no screenshot is taken of an Instagram post, and its media come with the post, in the fetch-posts job. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"<id>": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/<handle>.<ext> + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["<one of their post ids>"\], "avatarsOnly": true}. X also reads each post's CONTEXT off the same page -- the post it quotes and the post it answers (its author, check, date, words, media links) -- into its capture.json's "context"; "context": false turns that off. "contextOnly": true (X) loads ONE page per post for that alone (and the avatars it shows): the context written into capture.json, nothing shot, no media, article, thread shot or availability; a post whose context is already read is skipped unless "force". Not with "avatarsOnly". Paced like a post fetch, on its queue. An X trending library is captured by this same job, under channels/<slug>/trending/posts-media/<id>/. Its media comes from X's media CDN by the addresses in the library's saved captures: no login, one file after another 1-2 s apart, under X's cooldown, each file kept once (trending/media-store/, a hardlink per post). A file over the library's maxVideoMb (100 MB) and whatever is past the job's budget (40 files / 200 MB) is owed: asked for again by the next capture of that post. A 429 from the CDN stops the job and leaves X alone for 15 minutes; a 403 or 404 marks the file; three refusals in a row (a 403, or no answer) and the job asks the CDN no more; nothing retries. "keptMedia": true is for posts marked keep (refused for any other id): no per-file cap, and a post the CDN cannot serve whole is downloaded the logged-in way, if it is still kept when that download would start. A library's capture runs on X's queue only: "queueKey" is refused for it. | |
| `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "<branch>", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of <id> in <dir> — archilyzer publish build <id>". `get publish` is the status. | |
| `build-index`, `build-site`, `build-deploy`, `deploy-site`, `build-hub`, `deploy-hub`, `build-homepage`, `deploy-homepage` | build-index, build-site, build-deploy, deploy-site, build-hub, deploy-hub, build-homepage and deploy-homepage are publish's aliases, with their old bodies and answers ("skipData" is accepted and ignored). | `pnpm ops build-deploy --json '{"siteIds":["anilyzer","jeralyzer"]}' --wait`<br>`pnpm ops build-site --json '{"siteId":"anilyzer"}' --wait`<br>`pnpm ops deploy-site --json '{"siteId":"anilyzer","preview":"tags-exclude"}' --wait`<br>`pnpm ops build-hub --wait`<br>`pnpm ops build-hub --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-hub --wait`<br>`pnpm ops build-homepage --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait` |
| `build-site`, `build-deploy`, `deploy-site` | build-site, build-deploy and deploy-site all take "siteId" (one) or "siteIds" (a list). | |
@@ -196,7 +196,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "<tts engine>:<stock voice>" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | |
| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
| `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | |
-| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` |
+| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The For "instagram" it sends Instagram NO request either and is the operator's word that its check is passed: it clears the alert, and the next Instagram job raises it again if it was not. The timer never asks Instagram. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` |
| `dismiss-service` | — | |
| `rerun-service-jobs` | — | |
| `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` |
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -231,7 +231,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| Variable | Default | What it does | Read by |
|---|---|---|---|
-| `E2E_TEST_ROUTES` | off | `1` opens the editor's `/api/test/*` routes and marks a test server at boot. Set by `editor/playwright.config.ts` on its test server, and by nothing else. | editor/app/api/test/_guard.ts, editor/instrumentation.ts |
+| `E2E_TEST_ROUTES` | off | `1` opens the editor's `/api/test/*` routes and marks a test server at boot. Under it Instagram's media CDN is played back, never asked (`fakeInstagramMediaDeps`). Set by `editor/playwright.config.ts` on its test server, and by nothing else. | editor/app/api/test/_guard.ts, editor/instrumentation.ts, common/social/instagramMedia.ts, common/social/fakeXProfileBrowser.ts |
| `E2E_MODE` | `start` | `start`: the editor and umtool suites run against `next start` from a build `scripts/e2e-stamp.mjs` vouches for, rebuilt through the heavy slot when the tree moved. `dev`: against `next dev`, for iterating on one spec. The export and homepage suites always run `next dev` (static exports) and say so when asked for `start`. | editor/playwright.config.ts, umtool/playwright.config.ts, scripts/e2e-stamp.mjs |
| `E2E_NEXT_DIST_DIR` | `.next` | The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server — and for the editor suite's export dev server (`.next/e2e-editor`), which then runs beside the export suite's own (Next allows one `next dev` per dist dir). | editor/next.config.ts, export/next.config.ts |
| `E2E_MODEL_LOG_SHOTS` | unset (no screenshots) | A directory: the model log's e2e (demo epic D3) saves its 1366×768 screenshots of the panel there — the run page live and done, a call opened, the Iterations tab, a media draft, the settings table, the editor's job page — for a lane's report. Unset, none is taken. | umtool/e2e/model-log.spec.ts, editor/e2e/report-draft.spec.ts |
diff --git a/OPERATING.md b/OPERATING.md
@@ -496,7 +496,7 @@ pnpm ops fetch-posts --json '{"slug":"example-forum-thread","pages":20,"retry
pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait
```
-- An X, Bluesky or XenForo URL makes a social channel (its handle derived from the URL). `"older": true` walks back below the oldest
+- An X, Bluesky, Instagram or XenForo URL makes a social channel (its handle derived from the URL; Instagram: "Instagram accounts" below). `"older": true` walks back below the oldest
archived post and resumes from its saved place; `"full": true` re-walks the timeline.
- **Sync new and resume backfill are two actions** for an X or Bluesky timeline (`common/lib/timelineWalk.ts`). A
plain `fetch-posts` — and Sync, the scheduler, the channel page's **Sync new** — is SYNC NEW: from the top down to
@@ -510,8 +510,8 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait
the next fetch. The job log's first line names the mode (`— sync new, since …` / `— resume backfill, from its
saved resume point`).
- **Pacing is enforced, not advised** (plans/pacing-guard.md). Every job that asks a platform waits its
- platform queue's gap after the previous one there ended — `pacing.jobGapSeconds`: X 300 s, forums and
- Bluesky 60 s, everything else 20 s (set on /settings) — and its /jobs row and log say so (`waiting 4m12s: X
+ platform queue's gap after the previous one there ended — `pacing.jobGapSeconds`: Instagram 600 s, X 300 s,
+ forums and Bluesky 60 s, everything else 20 s (set on /settings) — and its /jobs row and log say so (`waiting 4m12s: X
jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)`). Thirteen fetches queued in one loop run five
minutes apart and stop at the first challenge. A queue override of `""` (immediate) is refused for any
such job.
@@ -593,6 +593,74 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait
- Forum pages saved from a browser: `pnpm archilyzer posts import-html <slug> <file-or-dir> --dry-run`.
- Which archived posts were deleted at the source: `pnpm archilyzer posts check --slug <slug>`.
+### Instagram accounts
+
+```sh
+pnpm ops create-channel --json '{"fields":{"name":"Example (Instagram)","handling":"transcribe","url":"https://www.instagram.com/example.account/","cookiesFromBrowser":"firefox:instagram-archive"}}'
+pnpm ops channel-config --json '{"slug":"example-instagram","patch":{"cookiesFromBrowser":"file:/data/instagram-archive-cookies.txt"}}'
+pnpm ops fetch-posts --json '{"slug":"example-instagram"}' --wait # the first: a walk; after it: sync new, one page
+pnpm ops resume-backfill --json '{"slug":"example-instagram"}' --wait # the walk's next 120 posts
+pnpm ops recheck-service --json '{"service":"instagram"}' # the operator's word, no request
+pnpm ops clear-platform-hold --json '{"platform":"instagram"}' # end the hour's hold by hand
+pnpm ops settings --json '{"patch":{"social":{"instagram":{"visibility":"public"}}}}'
+```
+
+- An `instagram.com/<account>/` URL makes a posts channel (`platform: "instagram"`, fetcher `instagram-gallery-dl`):
+ the account's posts and reels, each with its text, date, link, likes and media. A carousel is ONE post with
+ several media; a reel is one video. Stories, highlights, screenshots and transcription are not built yet.
+- **A login is required, and it is the channel's own.** Logged out, Instagram answers an account's feed with
+ "Page Not Found", so nothing is read without one. An Instagram channel reads only its own **Cookies from
+ browser** (`cookiesFromBrowser`: a browser profile, or `file:<cookies.txt>`), never the global browser. With none
+ set, `fetch-posts` is refused before a job exists and says where to set it.
+- **Use an account made for the archive.** Instagram may checkpoint or ban an account that reads this way, and
+ the login the channel names is the one at risk. An archive account reads public accounts, and private ones only
+ if it follows them. Nothing logs in or refreshes a session by itself.
+- **What a run costs, and it says so.** gallery-dl sleeps 6–12 s before every request. A sync is ONE feed page
+ (up to 30 posts), plus up to two requests for the account's id the first time. A walk (the first fetch,
+ `"full"`, `resume-backfill`, a sync that continues) reads up to 120 posts and stops; the next run resumes from
+ its cursor, re-reading that one page. A run is stopped at 4 requests (a sync) or 7 (a walk). Its log ends
+ `This run cost Instagram N request(s) and its CDN F file(s).` The log never prints the cookie source.
+- **A sync that finds a whole page of new posts continues**: the next Sync new walks on from the top, skips what
+ it archived, and stops only at the newest post the archive held when the sync began. Nothing between is dropped.
+- **Media come with the post, in the same job.** Their addresses are signed and expire, so the new posts'
+ pictures and videos are fetched at once: one GET per file with no cookies and no referer, a plain `Mozilla/5.0`
+ User-Agent, 2–5 s apart, only from hosts under `.cdninstagram.com` or `.fbcdn.net`, into
+ `channels/<slug>/posts-media/<post id>/` beside a `capture.json`. A sync may fetch 40 files or 200 MB, a walk
+ 120 files or 600 MB, a file at most 100 MB; the media half has 20 minutes and a file 5.
+ **A walk is sized to its media**: it lists as many posts as its budget has files, and the posts whose media
+ would not fit are left for the next run, which starts where this one did and lists them again. So a post a run archives has its media asked
+ for in that run. What was still not fetched (a file over the cap, a CDN refusal, a drain) is recorded as owed
+ (`mediaOwed`) and the log says how many posts; nothing collects owed media yet. Three CDN refusals in a row
+ end the media half. `posts-media/` is not in the media tier: it stays on the corpus disk.
+- **A post's id is its numeric media pk**, not the shortcode in its URL. The two convert both ways with no
+ request (`common/lib/instagram/ids.ts`); the post keeps its shortcode in `instagram.shortcode`.
+- **Pacing.** Instagram jobs run one at a time, ten minutes apart (`pacing.jobGapSeconds.instagram`, 600). A
+ channel is synced every 12 hours at the most often, 4 hours with a `syncIntervalMinutes` of its own. The
+ scheduler does not queue a channel with no cookie source, nor any Instagram channel while Instagram is held;
+ /operations/sync says why. A restart never re-queues an interrupted Instagram fetch: its place is saved and
+ the next scheduled or pressed sync continues.
+- **Only the editor's jobs ask Instagram, on Instagram's queue.** `pnpm archilyzer posts fetch <slug>` refuses an
+ Instagram channel and names `pnpm ops fetch-posts`. A `queueKey` other than `platform:instagram` is refused
+ for one (by `fetch-posts`, `resume-backfill`, a Sync, a Retry), and the fetch refuses again if its job is on
+ any other queue. A channel whose `postFetcher` is not of its platform — or of its URL's host — is refused.
+ yt-dlp is never started on an instagram.com URL, from the editor or from umtool's scripts (`import-video`
+ says so; a metadata scan leaves such a URL out of its batch and says so; a single reel's import comes later).
+- **Nothing is retried.** The first 429 ends the run, keeps what it read, and holds every Instagram job for 60
+ minutes. So does one 401 or 403; a second in a row with no clean read between raises the alert instead. A
+ login, challenge or checkpoint page — and the "Page Not Found" a dead session gets — raises Instagram's alert
+ on the dashboard at once: every Instagram job is refused until a person passes the check in that browser and
+ presses **Recheck** (`recheck-service`), which sends Instagram no request and is taken on the operator's
+ word. The recheck timer never asks Instagram. A refusal during the account lookup ends the run too (gallery-dl
+ would carry on to the feed). **After a refusal no media is asked for either**: the posts the run read are
+ archived with their media owed. `retryOnBlock` is refused.
+- **An account is "gone" only when its own page answers 404.** A private account the login does not follow, and
+ a gone account, end the job with a sentence and raise no alert.
+- **Private by default.** An Instagram channel's posts are built only into private sites unless
+ `social.instagram.visibility` is `"public"` (`common/lib/postsVisibility.ts`). A Wayback pages channel scoped to
+ instagram.com follows the same setting, and a capture of an instagram.com page is refused by any other pages
+ channel while Instagram is private. A flip from public back to private is tombstoned on the hub and refuses a
+ stale homepage build, as X's is.
+
### X search
```sh
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -186,6 +186,7 @@ Per-platform settings of the social posts: X's three, all chosen in the X accoun
|---|---|---|
| `x` | `{}` | X / Twitter. See `social.x` below. |
| `xenforo` | absent | Forum threads (XenForo). See `social.xenforo` below. Absent: nothing set. |
+| `instagram` | absent | Instagram. See `social.instagram` below. Absent: nothing set (posts private). |
#### `social.x`
@@ -203,6 +204,14 @@ Per entry — each entry spells its own values.
|---|---|
| `retryOnBlock` | `{ "minutes": N, "max": M }` — what a forum thread's Fetch posts button does when the forum serves a browser check that will not clear, or refuses a page (403/429): the job waits N minutes and runs again, M tries in all (the first included; minutes 5–1440, tries 1–48). A captcha or a login wall is never retried — it needs a person. ABSENT (the default): off, the job stops at the block. Set on the forum channel page (Retry after a block); `fetch-posts` takes its own `retryOnBlock`. common/lib/forumWalk.ts. |
+#### `social.instagram`
+
+Per entry — each entry spells its own values.
+
+| Key | Description |
+|---|---|
+| `visibility` | Where Instagram posts may appear. `"private"` (the default; absent): every Instagram channel's posts (a channel with `sourceKind: "social"` and `platform: "instagram"`) are left out of every PUBLIC site build, the channel with them, and built only into PRIVATE sites (`site.json` `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. |
+
Default:
```json
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,
@@ -170,9 +171,10 @@ export type CapturePostsResult = {
// Why this fetcher cannot capture posts, or null when it can. Shared with the
// server action, so the refusal is one sentence everywhere.
export function capturePostsProblem(
- fetcher: Pick<SocialFetcher, "label" | "captureByIds"> | undefined,
+ fetcher: (Pick<SocialFetcher, "label" | "captureByIds"> & Partial<Pick<SocialFetcher, "platform">>) | undefined,
): string | null {
if (!fetcher) return "This channel has no post fetcher.";
+ if (fetcher.platform === "instagram") return INSTAGRAM_NO_CAPTURE;
return typeof fetcher.captureByIds === "function"
? null
: `${fetcher.label} cannot capture posts.`;
@@ -242,6 +244,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 =
+ "This 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";
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";
@@ -103,6 +104,13 @@ export function selectPostsToCheck(
return candidates.slice(0, Math.max(0, limit));
}
+// Instagram (lane instagram): there is one way to read it and it has no
+// per-post liveness probe yet — "switch the scraping method" would be advice
+// with nowhere to go.
+export const INSTAGRAM_NO_AVAILABILITY_CHECK =
+ "Instagram posts are not checked for deletion yet: a check is a logged-in request per post, and comes with a later slice. " +
+ "Nothing was asked of Instagram, and nothing is marked deleted.";
+
export async function checkPostAvailability(
opts: CheckPostAvailabilityOptions,
): Promise<CheckPostAvailabilityResult> {
@@ -149,6 +157,9 @@ export async function checkPostAvailability(
if (!fetcher) {
return { ok: false, ...empty, error: `No post fetcher configured for ${slug}.` };
}
+ if (fetcher.platform === "instagram") {
+ return { ok: false, ...empty, error: INSTAGRAM_NO_AVAILABILITY_CHECK };
+ }
if (!fetcher.checkAvailability) {
// Better to say so than to guess. gallery-dl, for instance, has no cheap
// per-post liveness probe, so its channels should switch fetcher to sweep.
diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts
@@ -83,6 +83,20 @@ 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 {
+ fakeInstagramMediaDeps,
+ fetchInstagramMedia,
+ instagramMediaLine,
+ recordInstagramMediaOwed,
+ type InstagramMediaDeps,
+} from "../social/instagramMedia";
+import { instagramJobGuard } from "../jobs/instagramGuard";
+import { currentJobContext } from "../lib/jobContext";
+import { INSTAGRAM_QUEUE_KEY, INSTAGRAM_QUEUE_REFUSAL, isInstagramPostsChannelConfig } from "../lib/instagram/channel";
+import { detectPlatform } from "../lib/platform";
+import { postsMediaDir } from "../social/postCapture";
import type { XCookieSource } from "../social/xCookieSource";
import { noteForumServiceOutcome } from "../lib/serviceCookies-server";
import {
@@ -147,8 +161,75 @@ 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;
+}
+
+// AN INSTAGRAM FETCH RUNS ONLY AS THE EDITOR'S JOB (review 1, M3). The job
+// funnel is what gives it its queue (one Instagram job at a time), its gap
+// (ten minutes) and its place in the jobs list; a direct call — `pnpm
+// archilyzer posts fetch`, a script — has none of them, and two of those at
+// once would be two logged-in reads side by side.
+export const INSTAGRAM_ONLY_AS_A_JOB = (slug: string) =>
+ `${slug} is an Instagram channel, and Instagram is asked only by the editor's own jobs (one at a time, ten minutes ` +
+ `apart, held after a refusal): nothing was asked. Queue it instead: pnpm ops fetch-posts --json '{"slug":"${slug}"}' --wait`;
+
+// A channel's fetcher is of the channel's platform (review 1, M3): a config
+// naming X's fetcher on an Instagram channel (or the other way round) would
+// run one platform's requests on another's queue, past its guard.
+//
+// BOTH SIGNS ARE ASKED (review 2, N5): the platform the config names, AND the
+// platform of its URL when the host is one the app knows. Trusting the config
+// alone let {platform: "twitter", url: an instagram.com account, postFetcher:
+// X's} hand X's fetcher an Instagram URL on X's queue. A URL whose host the
+// app does not know (a Nitter instance, a bare Bluesky handle, a forum that
+// is told by its platform) says nothing and is not judged.
+export function fetcherPlatformMismatch(
+ slug: string,
+ config: { platform?: string; url?: string },
+ fetcher: { platform: string; label: string; id: string },
+): string | null {
+ const named = config.platform ?? null;
+ const ofUrl = detectPlatform(config.url) ?? null;
+ const channel = named && named !== fetcher.platform ? named : ofUrl && ofUrl !== fetcher.platform ? ofUrl : null;
+ if (!channel) return null;
+ return (
+ `${slug} is on ${channel}${channel === ofUrl && channel !== named ? " (its URL's host)" : ""}, and its fetcher ` +
+ `(${fetcher.label}, "${fetcher.id}") is ${fetcher.platform}'s: nothing was asked. ` +
+ "Set the channel's postFetcher to one of its own platform's, or clear it."
+ );
+}
+
+// Why an Instagram channel's fetch is refused before anything is asked, or
+// null. ONE rule, asked where a fetch is queued (the button, `pnpm ops
+// fetch-posts`) and again where it runs.
+export function instagramFetchRefusal(
+ slug: string,
+ config: { cookiesFromBrowser?: string } | null | undefined,
+ asked: { retryOnBlock?: boolean } = {},
+): { error: string; needsCookies?: true } | null {
+ if (asked.retryOnBlock) return { error: INSTAGRAM_RETRY_REFUSAL };
+ if (!instagramCookieSource(config)) return { error: INSTAGRAM_NO_COOKIES(slug), needsCookies: true };
+ return null;
+}
+
// 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 =
@@ -303,6 +384,8 @@ export async function fetchPosts(
error: `No post fetcher for ${accountUrl || slug} (configured: ${config.postFetcher ?? "auto-detect"})`,
};
}
+ const mismatch = fetcherPlatformMismatch(slug, config, fetcher);
+ if (mismatch) return { ok: false, written: 0, skipped: 0, complete: false, error: mismatch };
// AN X SEARCH CHANNEL (release 38): its query across accounts, walked in
// search windows — no handle, no timeline, no older walk (fetchXSearch.ts).
@@ -357,6 +440,30 @@ export async function fetchPosts(
return { ok: false, written: 0, skipped: 0, complete: false, error: FORUM_BACKFILL_REFUSAL };
}
+ if (fetcher.platform === "instagram" || isInstagramPostsChannelConfig(config)) {
+ const refusal = instagramFetchRefusal(slug, config, { retryOnBlock: Boolean(opts.retryOnBlock) });
+ if (refusal) return { ok: false, written: 0, skipped: 0, complete: false, ...refusal };
+ // Only as the editor's job, and its guard asked HERE too: the alert and
+ // the cooldown hold whoever calls.
+ const job = currentJobContext();
+ if (!job) {
+ return { ok: false, written: 0, skipped: 0, complete: false, error: INSTAGRAM_ONLY_AS_A_JOB(slug) };
+ }
+ // …and only on Instagram's own queue (review 2, N1): a job on any other
+ // runs beside the one there, with no gap between them.
+ if (job.queueKey !== INSTAGRAM_QUEUE_KEY) {
+ return {
+ ok: false,
+ written: 0,
+ skipped: 0,
+ complete: false,
+ error: INSTAGRAM_QUEUE_REFUSAL(slug, job.queueKey ?? "(none)"),
+ };
+ }
+ const guard = await instagramJobGuard({ paths });
+ if (!guard.ok) return { ok: false, written: 0, skipped: 0, complete: false, error: guard.message };
+ }
+
const seenIds = await readSeenPostIds(channelRoot);
const priorState = await readPostFetchState(channelRoot);
if (opts.backfill) {
@@ -516,7 +623,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 +762,45 @@ 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.
+ const refusedListing = result.block === "blocked" || result.block === "challenge" || result.block === "login";
+ if (result.media?.length && refusedListing) {
+ // AFTER A REFUSAL NOTHING MORE IS ASKED OF INSTAGRAM, ITS CDN INCLUDED:
+ // the posts the run read are archived, their media recorded as owed.
+ const marked = await recordInstagramMediaOwed({
+ outDir: postsMediaDir(channelRoot),
+ plans: result.media,
+ why: "Instagram refused the listing, so nothing more was asked of it, its CDN included",
+ }).catch(() => 0);
+ log(
+ `Media: none asked for. Instagram refused the listing, so its CDN is not asked either; ${marked} post(s) are archived with their media owed ` +
+ "(nothing collects owed media yet).",
+ );
+ log(`This run cost Instagram ${result.requests ?? 0} request(s) and its CDN 0 file(s).`);
+ } else if (result.media?.length) {
+ const fake = fakeInstagramMediaDeps();
+ const media = await fetchInstagramMedia({
+ outDir: postsMediaDir(channelRoot),
+ plans: result.media,
+ signal: effectiveSignal,
+ ...(opts.drain ? { drain: opts.drain } : {}),
+ onLog: log,
+ deps: { ...(fake ?? {}), ...(opts.instagramMedia ?? {}) },
+ ...(result.mediaBudget ? { limits: result.mediaBudget } : {}),
+ }).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/controller/importPage.instagram.test.ts b/common/controller/importPage.instagram.test.ts
@@ -0,0 +1,26 @@
+// A capture of an instagram.com page goes into no PUBLIC pages channel while
+// Instagram posts are private (review 1, S12): import-page's one refusal,
+// asked for Instagram as it is for X. X's answers are pinned.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { xCaptureRefusal } from "./importPage";
+
+const IG_PUBLIC = { social: { instagram: { visibility: "public" } } };
+const PAGES = (url: string) => ({ sourceKind: "social" as const, platform: "webpage" as const, wayback: { targets: [{ url }] } });
+
+test("a capture of an instagram.com page goes into no public pages channel while Instagram is private; X's refusal is what it was", () => {
+ const url = "https://www.instagram.com/example.account/";
+ const other = PAGES("example.com/blog") as never;
+ const igPages = PAGES("instagram.com/example.account") as never;
+ assert.match(
+ xCaptureRefusal(other, "some-pages", url, {}) ?? "",
+ /is on Instagram, whose posts are private here \(social\.instagram\.visibility is not "public"\); import an Instagram capture into a Wayback pages channel whose target is on instagram\.com, which a public site leaves out — not into some-pages/,
+ );
+ assert.equal(xCaptureRefusal(igPages, "ig-pages", url, {}), null);
+ assert.equal(xCaptureRefusal(other, "some-pages", url, IG_PUBLIC), null);
+ assert.equal(xCaptureRefusal(other, "some-pages", "https://example.com/a", {}), null);
+ // X: refused only while X is private, with X's own sentence.
+ const xUrl = "https://x.com/example/status/1";
+ assert.equal(xCaptureRefusal(other, "some-pages", xUrl, {}), null);
+ assert.match(xCaptureRefusal(other, "some-pages", xUrl, { social: { x: { visibility: "private" } } }) ?? "", /is on X, whose posts are private here \(social\.x\.visibility "private"\)/);
+});
diff --git a/common/controller/importPage.ts b/common/controller/importPage.ts
@@ -51,7 +51,7 @@ import { ArchiveOrgRequestError } from "../lib/archiveOrgClient";
import { waybackClient as defaultWaybackClient, type WaybackClient } from "../lib/waybackClient";
import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
-import { isXHostUrl, videoPageOf } from "../lib/waybackPages/urls";
+import { isInstagramHostUrl, isXHostUrl, videoPageOf } from "../lib/waybackPages/urls";
import { parseArchiveCaptureAsk, type ArchiveCaptureAsk } from "../lib/archives/ask";
import { unwrapArchiveTodayHtml, mapArchiveTodayMedia } from "../lib/archives/archiveToday";
import { ARCHIVE_TODAY_QUEUE, ArchiveTodayRequestError, type ArchiveTodayClient } from "../lib/archives/archiveTodayClient";
@@ -66,7 +66,12 @@ import {
writeStoredCapture,
type StoredCapture,
} from "../lib/waybackPages/store-server";
-import { isXPostsChannel, xPostsVisibility } from "../lib/postsVisibility";
+import {
+ instagramPostsVisibility,
+ isInstagramPostsChannel,
+ isXPostsChannel,
+ xPostsVisibility,
+} from "../lib/postsVisibility";
import type { Post } from "../lib/posts";
export const IMPORT_PAGE_JOB_KIND = "import-page";
@@ -76,7 +81,7 @@ export const IMPORT_PAGE_RESULT_MARKER = "@@import-page ";
// on the queue a web.archive.org URL routes to.
export const WAYBACK_PAGES_QUEUE = queueKeyForUrl("https://web.archive.org/");
-type VisibilitySettings = { social?: { x?: { visibility?: unknown } } };
+type VisibilitySettings = { social?: { x?: { visibility?: unknown }; instagram?: { visibility?: unknown } } };
export type ImportPagePlan = {
config: ChannelConfig;
@@ -90,13 +95,23 @@ export function importPageQueueOf(ask: Pick<ArchiveCaptureAsk, "source">): strin
return ask.source === "archive.today" ? ARCHIVE_TODAY_QUEUE : WAYBACK_PAGES_QUEUE;
}
-// The refusal an X capture meets in this channel, or null.
+// The refusal an X capture — or an Instagram one (lane instagram) — meets in
+// this channel, or null. One question for both platforms: every call site
+// asks it of a capture's original URL before the capture is written.
export function xCaptureRefusal(
config: ChannelConfig,
slug: string,
originalUrl: string,
settings: VisibilitySettings,
): string | null {
+ if (isInstagramHostUrl(originalUrl)) {
+ if (instagramPostsVisibility(settings) !== "private") return null;
+ if (isInstagramPostsChannel(config)) return null;
+ return (
+ `${originalUrl} is on Instagram, whose posts are private here (social.instagram.visibility is not "public"); ` +
+ `import an Instagram capture into a Wayback pages channel whose target is on instagram.com, which a public site leaves out — not into ${slug}`
+ );
+ }
if (!isXHostUrl(originalUrl)) return null;
if (xPostsVisibility(settings) !== "private") return null;
if (isXPostsChannel(config)) return null;
diff --git a/common/controller/publishXTrending.ts b/common/controller/publishXTrending.ts
@@ -131,6 +131,7 @@ const POST_FIELDS = {
// Not an X post's.
forum: false,
page: false,
+ instagram: false,
// Derived at index time from the availability sidecar, never stored.
isDeleted: false,
availability: false,
diff --git a/common/controller/recheckServiceCookies.ts b/common/controller/recheckServiceCookies.ts
@@ -274,6 +274,17 @@ export async function recheckServiceCookies(opts: {
`${login.browser ?? "the browser cookiesFromBrowser names"}, pass its check, then Recheck. Recheck sends X no request.`,
);
}
+ case "instagram": {
+ // THE OPERATOR'S WORD, and no request: nothing on disk says whether
+ // Instagram's check is passed (slice 1 keeps no Instagram jar), so a
+ // Recheck is a person saying it is. The timer never comes here
+ // (serviceCookieTimer.ts holdBack).
+ if (!entry?.raisedAt || entry.clearedAt) {
+ return out("clean", `${label} has no cookie alert up. Recheck sends Instagram no request.`);
+ }
+ log(`Rechecking ${label}: your word that its check is passed, no request to Instagram.`);
+ return clean("on your word; no request sent. If the check was not passed, the next Instagram job raises it again");
+ }
case "archive": {
const url = target?.url;
if (!url) {
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -102,6 +102,7 @@ import {
import { refreshVideoMetadata, type RefreshRunner } from "./refreshVideoMetadata";
import { findVideoSourceUrl } from "./undownloadedVideos";
import { jitterYtdlpSleeps } from "../lib/jitter";
+import { refuseInstagramYtdlp } from "../lib/instagram/ytdlp";
import { parsePreclipKnob, type PreclipOptions } from "../lib/livePreclip";
import { jitterMs } from "../lib/jitter";
import "../lib/childKillGuard";
@@ -894,6 +895,8 @@ export async function recordLiveRun(
`ffmpeg_i:${mode !== "now" ? "-live_start_index 0 " : ""}-m3u8_hold_counters 180 -seg_max_retry 10`,
],
});
+ // The recorder's argv does not pass jitterYtdlpSleeps: asked here.
+ refuseInstagramYtdlp(args);
const o = await runRecorder({ bin: paths.ytdlpBin, args, cwd: channelDir, onLog, signal, label: tag });
finish(part, `${extraNote}yt-dlp exit ${o.exitCode ?? "null"}${o.signalled ? " (stopped)" : ""}`);
await save();
diff --git a/common/controller/serviceCookieTimer.test.ts b/common/controller/serviceCookieTimer.test.ts
@@ -310,3 +310,14 @@ test("the timer: a tick still in flight when the next is due skips it; the next
assert.ok(serviceCookieTimerView().lastTickAt);
assert.equal(logs.filter((l) => /still running/.test(l)).length, 0);
});
+
+test("Instagram's alert is a person's to clear: the timer never rechecks it, raised or listed as a probe", async () => {
+ const h = harness((s) => {
+ applyServiceCookieSignal(s, { service: "instagram", kind: "challenge", line: "HTTP redirect to challenge page" }, { channel: "example-ig" }, NOW - 3600_000);
+ });
+ h.deps.settings = () => ({ recheckIntervalMinutes: 180, probeServices: ["instagram"] });
+ const actions = await runServiceCookieTick(h.deps);
+ assert.deepEqual(h.calls, []);
+ assert.equal(actions.find((a) => a.service === "instagram")?.action, "skipped");
+ assert.match(actions.find((a) => a.service === "instagram")?.message ?? "", /person's Recheck only/);
+});
diff --git a/common/controller/serviceCookieTimer.ts b/common/controller/serviceCookieTimer.ts
@@ -107,6 +107,9 @@ export async function runServiceCookieTick(deps: ServiceCookieTickDeps): Promise
// Why a service is not asked now, or null.
const holdBack = async (svc: string): Promise<string | null> => {
+ // Instagram's alert is a person's to clear (Recheck or Dismiss on the
+ // dashboard): the timer never asks it, alert up or not.
+ if (serviceFamily(svc) === "instagram") return "Instagram's alert is cleared by a person's Recheck only";
if (rechecking(svc)) return "a recheck of it is already queued or running";
if (serviceFamily(svc) === "ytdlp") {
if (busy(svc)) return `a job is queued or running on its queue (its answer is the probe)`;
diff --git a/common/jobs/instagramGuard.test.ts b/common/jobs/instagramGuard.test.ts
@@ -0,0 +1,174 @@
+// INSTAGRAM'S GUARD (jobs/instagramGuard.ts) and its place in the network
+// guard's per-platform table (jobs/networkGuard.ts PLATFORM_GUARDS): the alert
+// refuses every Instagram job until a person's Recheck, the cooldown refuses
+// until it ends, and X's guard is the function it was.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/instagramGuard.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, 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-guard-"));
+process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts");
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ social: { x: { cookieSource: "profile" } } }));
+
+const { getPaths } = await import("../lib/paths");
+const { guardNetworkJob, PLATFORM_GUARDS } = await import("./networkGuard");
+const { instagramJobGuard, instagramCooldownSentence, INSTAGRAM_RATE_LIMIT_HOLD_MS } = await import("./instagramGuard");
+const { noteInstagramServiceOutcome, readServiceCookieState, raisedServiceAlert } = await import("../lib/serviceCookies-server");
+const { buildServiceCookieAlerts, isServiceKey, serviceFamily, serviceLabel, INSTAGRAM_SERVICE } = await import("../lib/serviceCookies");
+const { recheckServiceCookies } = await import("../controller/recheckServiceCookies");
+const { recordPlatformCooldown, platformCooldownRemainingMs } = await import("./downloadBackoff");
+
+const paths = getPaths();
+const channels = path.join(paths.transcriptsDir, "channels");
+async function channel(slug: string, platform: string, url: string): Promise<void> {
+ await mkdir(path.join(channels, slug), { recursive: true });
+ await writeFile(
+ path.join(channels, slug, "config.json"),
+ JSON.stringify({ handling: "transcribe", sourceKind: "social", platform, name: slug, url }),
+ );
+}
+await channel("example-ig", "instagram", "https://www.instagram.com/example.account/");
+await channel("example-sky", "bluesky", "https://bsky.app/profile/example.bsky.social");
+await channel("example-x", "twitter", "https://x.com/example");
+
+test.after(async () => {
+ await rm(ROOT, { recursive: true, force: true });
+});
+
+const ig = (job?: { id: string }) =>
+ guardNetworkJob({ kind: "fetch-posts", queueKey: "platform:instagram", paths, channelSlug: "example-ig", ...(job ? { job } : {}) });
+
+test("the table names X and Instagram, and nothing else", () => {
+ assert.deepEqual(Object.keys(PLATFORM_GUARDS).sort(), ["instagram", "twitter"]);
+ assert.ok(isServiceKey(INSTAGRAM_SERVICE));
+ assert.equal(serviceFamily(INSTAGRAM_SERVICE), "instagram");
+ assert.equal(serviceLabel(INSTAGRAM_SERVICE), "Instagram");
+ // X's and the others' families are what they were.
+ assert.equal(serviceFamily("x"), "x");
+ assert.equal(serviceFamily("rumble"), "ytdlp");
+ assert.equal(serviceFamily("forum.example"), "forum");
+});
+
+test("with no alert and no cooldown an Instagram job starts; a platform with no guard is not asked", async () => {
+ assert.deepEqual(await ig(), { ok: true, notes: [] });
+ assert.deepEqual(
+ await guardNetworkJob({ kind: "fetch-posts", queueKey: "platform:bluesky", paths, channelSlug: "example-sky" }),
+ { ok: true, notes: [] },
+ );
+ // A name on Object.prototype is not a platform with a guard.
+ assert.deepEqual(await guardNetworkJob({ kind: "fetch-posts", queueKey: "platform:constructor", paths }), { ok: true, notes: [] });
+});
+
+test("an Instagram job is never run unqueued either", async () => {
+ const r = await guardNetworkJob({ kind: "fetch-posts", queueKey: "", paths, channelSlug: "example-ig" });
+ assert.equal(r.ok, false);
+});
+
+test("a challenge raises Instagram's alert: every Instagram job is refused, at enqueue and at start, until a person's Recheck", async () => {
+ await noteInstagramServiceOutcome(paths, {
+ challengeLine: "[instagram][error] HTTP redirect to challenge page (https://www.instagram.com/challenge/)",
+ kind: "challenge",
+ channel: "example-ig",
+ });
+ assert.ok(await raisedServiceAlert(paths, INSTAGRAM_SERVICE));
+ const atEnqueue = await ig();
+ assert.equal(atEnqueue.ok, false);
+ assert.match((atEnqueue as { error: string }).error, /Instagram answered with a challenge or checkpoint page/);
+ assert.match((atEnqueue as { error: string }).error, /no Instagram job starts/);
+ assert.match((atEnqueue as { error: string }).error, /Recheck sends Instagram no request/);
+ // Whatever queue it was moved to: the channel's platform decides.
+ const moved = await guardNetworkJob({ kind: "capture-posts", queueKey: "somewhere", paths, channelSlug: "example-ig" });
+ assert.equal(moved.ok, false);
+ // Refused at its start: recorded against the alert for "Re-run stopped jobs".
+ assert.equal((await ig({ id: "job-7" })).ok, false);
+ const entry = (await readServiceCookieState(paths)).services[INSTAGRAM_SERVICE]!;
+ assert.deepEqual(entry.jobs.map((j) => j.id), ["job-7"]);
+ // A clean answer cannot be what clears it (no job runs), and the banner offers Recheck.
+ const view = buildServiceCookieAlerts(await readServiceCookieState(paths), { now: Date.now() });
+ const alert = view.alerts.find((a) => a.service === INSTAGRAM_SERVICE)!;
+ assert.equal(alert.state, "stale");
+ assert.equal(alert.canRecheck, true);
+ // Bluesky is not Instagram's business.
+ assert.equal((await guardNetworkJob({ kind: "fetch-posts", queueKey: "platform:bluesky", paths, channelSlug: "example-sky" })).ok, true);
+
+ // The operator's Recheck: no request, the alert cleared, jobs start again.
+ const out = await recheckServiceCookies({ paths, service: INSTAGRAM_SERVICE });
+ assert.equal(out.result, "clean");
+ assert.match(out.message, /no request sent/);
+ assert.equal(await raisedServiceAlert(paths, INSTAGRAM_SERVICE), null);
+ assert.deepEqual(await ig(), { ok: true, notes: [] });
+ // A Recheck with no alert up says so and changes nothing.
+ assert.match((await recheckServiceCookies({ paths, service: INSTAGRAM_SERVICE })).message, /no cookie alert up/);
+});
+
+test("a login redirect raises it as a login failure", async () => {
+ await noteInstagramServiceOutcome(paths, { challengeLine: "HTTP redirect to login page", kind: "auth-failure" });
+ const r = await ig();
+ assert.equal(r.ok, false);
+ assert.match((r as { error: string }).error, /its login page/);
+ await recheckServiceCookies({ paths, service: INSTAGRAM_SERVICE });
+});
+
+test("the 60-minute cooldown refuses every Instagram job until it ends, and says when", async () => {
+ assert.equal(INSTAGRAM_RATE_LIMIT_HOLD_MS, 60 * 60_000);
+ await recordPlatformCooldown("instagram", INSTAGRAM_RATE_LIMIT_HOLD_MS, paths);
+ const left = await platformCooldownRemainingMs("instagram", paths);
+ assert.ok(left > 59 * 60_000 && left <= 60 * 60_000);
+ const r = await ig();
+ assert.equal(r.ok, false);
+ assert.match((r as { error: string }).error, /Instagram answered a rate limit/);
+ assert.match((r as { error: string }).error, /nothing retries by itself/);
+ // Not an alert: nothing is recorded for "Re-run stopped jobs".
+ await ig({ id: "job-9" });
+ assert.equal((await readServiceCookieState(paths)).services[INSTAGRAM_SERVICE]?.jobs.some((j) => j.id === "job-9") ?? false, false);
+ // The cooldown is Instagram's alone.
+ assert.equal(await platformCooldownRemainingMs("twitter", paths), 0);
+});
+
+test("a cooldown that cannot be read refuses: the guard fails closed", async () => {
+ const r = await instagramJobGuard({
+ paths,
+ deps: {
+ raisedAlert: async () => null,
+ cooldownMs: async () => {
+ throw new Error("EACCES: the state file (invented)");
+ },
+ },
+ });
+ assert.equal(r.ok, false);
+ assert.match((r as { message: string }).message, /could not be read \(EACCES: the state file \(invented\)\): no Instagram job starts/);
+});
+
+test("ONE 401/403 is pending and refuses nothing; a SECOND with no clean read between raises the alert; a clean read between forgets the first", async () => {
+ const refuse = () => noteInstagramServiceOutcome(paths, { challengeLine: "HttpError: '401 Unauthorized' for '…'", kind: "refusal", channel: "example-ig" });
+ await refuse();
+ assert.equal(await raisedServiceAlert(paths, INSTAGRAM_SERVICE), null, "one refusal is the hour's hold, not the alert");
+ assert.equal((await readServiceCookieState(paths)).services[INSTAGRAM_SERVICE]?.kind, "refusal");
+ // A clean read between: forgotten.
+ await noteInstagramServiceOutcome(paths, { url: "https://www.instagram.com/example.account/" });
+ assert.equal((await readServiceCookieState(paths)).services[INSTAGRAM_SERVICE], undefined);
+ await refuse();
+ assert.equal(await raisedServiceAlert(paths, INSTAGRAM_SERVICE), null);
+ // The second in a row, hours later (the hold between them is an hour): the alert.
+ await refuse();
+ const raised = await raisedServiceAlert(paths, INSTAGRAM_SERVICE);
+ assert.equal(raised?.kind, "refusal");
+ const r = await instagramJobGuard({ paths, deps: { cooldownMs: async () => 0 } });
+ assert.equal(r.ok, false);
+ assert.match((r as { message: string }).message, /a second refusal \(401\/403\) in a row/);
+ await recheckServiceCookies({ paths, service: INSTAGRAM_SERVICE });
+});
+
+test("the guard's two answers, with injected state", async () => {
+ const now = Date.parse("2026-01-02T03:00:00Z");
+ assert.deepEqual(await instagramJobGuard({ paths, now, deps: { raisedAlert: async () => null, cooldownMs: async () => 0 } }), { ok: true });
+ const cooling = await instagramJobGuard({ paths, now, deps: { raisedAlert: async () => null, cooldownMs: async () => 30 * 60_000 } });
+ assert.deepEqual(cooling, { ok: false, message: instagramCooldownSentence(30 * 60_000, now), alert: false });
+ assert.match(instagramCooldownSentence(30 * 60_000, now), /before 03:30 UTC \(30 min from now\)/);
+});
diff --git a/common/jobs/instagramGuard.ts b/common/jobs/instagramGuard.ts
@@ -0,0 +1,90 @@
+// INSTAGRAM'S HALF OF THE NETWORK GUARD (lane instagram; jobs/networkGuard.ts
+// PLATFORM_GUARDS). Asked of every job aimed at Instagram, at enqueue and
+// again at its start:
+//
+// 1. NOT WHILE ITS ALERT IS UP. A redirect to Instagram's login, challenge
+// or checkpoint page raises the Instagram alert (lib/serviceCookies.ts):
+// the next request after one is the one that gets an account locked, so
+// every Instagram job is refused until a person's Recheck (or Dismiss).
+// 2. NOT WHILE IT COOLS DOWN. The first 429 (or "wait a few minutes") ends
+// the run that met it and records a 60-minute `instagram` platform
+// cooldown (jobs/downloadBackoff.ts recordPlatformCooldown); nothing
+// Instagram starts before it ends, and nothing retries by itself.
+//
+// There is no jar rule here: slice 1 keeps no Instagram jar.
+
+import type { Paths } from "../lib/paths";
+import { INSTAGRAM_SERVICE, serviceFixText, type ServiceCookieEntry } from "../lib/serviceCookies";
+import { raisedServiceAlert } from "../lib/serviceCookies-server";
+import { platformCooldownRemainingMs } from "./downloadBackoff";
+
+export const INSTAGRAM_PLATFORM = "instagram";
+
+// How long Instagram is left alone after it answered a rate limit.
+export const INSTAGRAM_RATE_LIMIT_HOLD_MS = 60 * 60_000;
+
+export function instagramCooldownSentence(remainingMs: number, now: number): string {
+ const until = new Date(now + remainingMs).toISOString().slice(11, 16);
+ return (
+ `Instagram answered a rate limit a short while ago: no Instagram job starts before ${until} UTC ` +
+ `(${Math.ceil(remainingMs / 60_000)} min from now). Ask again then; nothing retries by itself.`
+ );
+}
+
+export function instagramAlertSentence(raised: Pick<ServiceCookieEntry, "kind" | "raisedAt" | "since" | "evidence">): string {
+ const at = (raised.raisedAt ?? raised.since).slice(11, 16);
+ const what =
+ raised.kind === "auth-failure"
+ ? "its login page"
+ : raised.kind === "refusal"
+ ? "a second refusal (401/403) in a row"
+ : "a challenge or checkpoint page";
+ return (
+ `Instagram answered with ${what} at ${at} UTC (${raised.evidence.line}) and its alert is up, ` +
+ `so no Instagram job starts: ${serviceFixText(INSTAGRAM_SERVICE)}.`
+ );
+}
+
+export type InstagramGuardResult = { ok: true } | { ok: false; message: string; alert: boolean };
+
+export type InstagramGuardDeps = {
+ raisedAlert: (paths: Paths) => Promise<ServiceCookieEntry | null>;
+ cooldownMs: (paths: Paths) => Promise<number>;
+};
+
+const DEFAULT_DEPS: InstagramGuardDeps = {
+ raisedAlert: (paths) => raisedServiceAlert(paths, INSTAGRAM_SERVICE),
+ cooldownMs: (paths) => platformCooldownRemainingMs(INSTAGRAM_PLATFORM, paths),
+};
+
+// The cooldown could not be read: the guard FAILS CLOSED. Not knowing whether
+// Instagram is cooling down is not a reason to ask it.
+export const INSTAGRAM_COOLDOWN_UNREADABLE = (why: string) =>
+ `Whether Instagram is cooling down after a rate limit could not be read (${why}): no Instagram job starts until it can.`;
+
+export async function instagramJobGuard(opts: {
+ paths: Paths;
+ now?: number;
+ deps?: Partial<InstagramGuardDeps>;
+}): Promise<InstagramGuardResult> {
+ const deps = { ...DEFAULT_DEPS, ...opts.deps };
+ const now = opts.now ?? Date.now();
+ const raised = await deps.raisedAlert(opts.paths);
+ if (raised) return { ok: false, message: instagramAlertSentence(raised), alert: true };
+ let ms: number;
+ try {
+ ms = await deps.cooldownMs(opts.paths);
+ } catch (err) {
+ return { ok: false, message: INSTAGRAM_COOLDOWN_UNREADABLE((err as Error).message.split("\n")[0]!.slice(0, 200)), alert: false };
+ }
+ if (ms > 0) return { ok: false, message: instagramCooldownSentence(ms, now), alert: false };
+ return { ok: true };
+}
+
+// Why no Instagram job starts now, as a sentence, or null — for the scheduler,
+// which skips every Instagram channel with it rather than queue a fetch the
+// guard would refuse.
+export async function instagramHeldReason(paths: Paths, now: number = Date.now()): Promise<string | null> {
+ const g = await instagramJobGuard({ paths, now });
+ return g.ok ? null : g.message;
+}
diff --git a/common/jobs/instagramPacing.test.ts b/common/jobs/instagramPacing.test.ts
@@ -0,0 +1,483 @@
+// 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://scontent-invented.cdninstagram.com/" + 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, fetcherPlatformMismatch, INSTAGRAM_ONLY_AS_A_JOB, INSTAGRAM_RETRY_REFUSAL } = await import("../controller/fetchPosts");
+const { runInJobContext } = await import("../lib/jobContext");
+const { instagramQueueProblem } = await import("../lib/instagram/channel");
+const { capturePosts } = await import("../controller/capturePosts");
+const { checkPostAvailability, INSTAGRAM_NO_AVAILABILITY_CHECK } = await import("../controller/checkPostAvailability");
+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> = {}, queueKey = "platform:instagram") {
+ return runManagedFunction({
+ kind: "fetch-posts",
+ queueKey,
+ 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);
+ // NOT AS A JOB: a direct call (the CLI's) is refused with where to ask instead, and nothing runs.
+ const direct = await fetchPosts({ paths, slug: SLUGS[0], settings: {} });
+ assert.deepEqual([direct.ok, direct.error], [false, INSTAGRAM_ONLY_AS_A_JOB(SLUGS[0])]);
+ assert.match(direct.error!, /pnpm ops fetch-posts --json '\{"slug":"ig-acct-1"\}' --wait/);
+ assert.equal(await runCount(), 0);
+ // A fetcher of another platform on an Instagram channel (and the other way round) is refused: it would run past the guard.
+ const dir = path.join(transcripts, "channels", SLUGS[0], "config.json");
+ const config = JSON.parse(await readFile(dir, "utf8"));
+ await writeFile(dir, JSON.stringify({ ...config, postFetcher: "x-gallery-dl" }));
+ const crossed = await fetchPosts({ paths, slug: SLUGS[0], settings: {} });
+ assert.equal(crossed.ok, false);
+ assert.match(crossed.error!, /ig-acct-1 is on instagram, and its fetcher \(X \/ Twitter \(gallery-dl\), "x-gallery-dl"\) is twitter's: nothing was asked/);
+ await writeFile(dir, JSON.stringify({ ...config, platform: "twitter", url: "https://x.com/example", postFetcher: "instagram-gallery-dl" }));
+ assert.match((await fetchPosts({ paths, slug: SLUGS[0], settings: {} })).error!, /is on twitter, and its fetcher \(Instagram \(gallery-dl\)/);
+ assert.equal(await runCount(), 0);
+ await writeFile(dir, JSON.stringify(config));
+ assert.equal(fetcherPlatformMismatch("x", { platform: "twitter" }, { platform: "twitter", label: "X", id: "x-gallery-dl" }), null);
+ assert.equal(fetcherPlatformMismatch("x", { url: "https://x.com/example" }, { platform: "twitter", label: "X", id: "x-nitter" }), null);
+ assert.equal(fetcherPlatformMismatch("x", {}, { platform: "bluesky", label: "B", id: "b" }), null, "a channel that names no platform is not judged");
+ // BOTH SIGNS (review 2, N5): the config says X, the URL is Instagram's — X's fetcher is not handed it.
+ await writeFile(dir, JSON.stringify({ ...config, platform: "twitter", postFetcher: "x-gallery-dl" }));
+ const lied = await fetchPosts({ paths, slug: SLUGS[0], settings: {} });
+ assert.equal(lied.ok, false);
+ assert.match(lied.error!, /ig-acct-1 is on instagram \(its URL's host\), and its fetcher \(X \/ Twitter \(gallery-dl\), "x-gallery-dl"\) is twitter's: nothing was asked/);
+ assert.equal(await runCount(), 0);
+ await writeFile(dir, JSON.stringify(config));
+ const X = { platform: "twitter", label: "X", id: "x-gallery-dl" };
+ assert.match(fetcherPlatformMismatch("c", { platform: "twitter", url: "https://www.instagram.com/example.account/" }, X) ?? "", /is on instagram \(its URL's host\)/);
+ assert.match(fetcherPlatformMismatch("c", { url: "https://x.com/example" }, { platform: "instagram", label: "I", id: "instagram-gallery-dl" }) ?? "", /is on twitter/);
+ // The legitimate shapes are what they were: a Nitter instance's URL, an X search, a bare Bluesky handle,
+ // a forum told by its platform alone, no platform at all.
+ assert.equal(fetcherPlatformMismatch("c", { platform: "twitter", url: "https://nitter.example.invalid/example" }, { ...X, id: "x-nitter" }), null);
+ assert.equal(fetcherPlatformMismatch("c", { platform: "twitter", url: "https://x.com/search?q=%22demo%22" }, X), null);
+ assert.equal(fetcherPlatformMismatch("c", { platform: "twitter", url: "https://twitter.com/example" }, X), null);
+ assert.equal(fetcherPlatformMismatch("c", { platform: "bluesky", url: "example.bsky.social" }, { platform: "bluesky", label: "B", id: "bluesky-atproto" }), null);
+ assert.equal(fetcherPlatformMismatch("c", { platform: "bluesky", url: "https://bsky.app/profile/example.bsky.social" }, { platform: "bluesky", label: "B", id: "bluesky-atproto" }), null);
+ assert.equal(fetcherPlatformMismatch("c", { platform: "xenforo", url: "https://forum.example.invalid/community/topic-1/" }, { platform: "xenforo", label: "F", id: "xenforo-thread" }), null);
+ assert.equal(fetcherPlatformMismatch("c", { url: "https://unknown.example.invalid/someone" }, X), null);
+ assert.equal(fetcherPlatformMismatch("c", { platform: "instagram", url: "https://www.instagram.com/example.account/" }, { platform: "instagram", label: "I", id: "instagram-gallery-dl" }), null);
+ // The deleted-posts sweep says it is not built for Instagram, and asks nothing.
+ const sweep = await checkPostAvailability({ paths, slug: SLUGS[0] });
+ assert.deepEqual([sweep.ok, sweep.error], [false, INSTAGRAM_NO_AVAILABILITY_CHECK]);
+ 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);
+ // fetchPosts asks the guard itself, whoever calls it inside a job: the funnel's start check is not the only one.
+ const inside = await runInJobContext(
+ { jobId: "by-hand", kind: "fetch-posts", queueKey: "platform:instagram", onLog: () => {}, staleServices: new Set() },
+ () => fetchPosts({ paths, slug: SLUGS[2], settings: {}, instagramMedia }),
+ );
+ assert.equal(inside.ok, false);
+ assert.match(inside.error!, /its alert is up, so no Instagram job starts/);
+ 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 \(GET \/api\/v1\/feed\/user\/\d+\/ answered 429\): 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 with the resume point — and NO media is asked for:
+ // after a refusal everything Instagram stops, its CDN too. Its record says the media are owed.
+ 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, 0);
+ const owed = JSON.parse(await readFile(path.join(root, "posts-media", "3500000000000000009", "capture.json"), "utf8"));
+ assert.deepEqual([owed.mediaState, owed.mediaOwed, owed.media.length], ["error", "next", 0]);
+ assert.match(first, /Media: none asked for\. Instagram refused the listing, so its CDN is not asked either; 1 post\(s\) are archived with their media owed/);
+ assert.match(first, /This run cost Instagram 3 request\(s\) and its CDN 0 file\(s\)\./);
+ // 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: the channel's own cookie source, read by gallery-dl\./);
+ assert.ok(!log.includes("firefox:ig-profile"), "the cookie source is never printed");
+ 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 res = await fetchJob(slug, new Map());
+ assert.equal(res.ok, true);
+ if (res.ok) assert.equal((await res.done).status, "done");
+ // A first fetch is a walk: 7 requests at most (the lookup and 6 pages of one post).
+ const posts = await readAllPosts(path.join(paths.channelsDir, slug));
+ assert.ok(posts.length >= 6 && posts.length <= 8, `${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;
+ }
+});
+
+// Review 2, N1: a queue override ran an Instagram fetch beside the job on
+// Instagram's queue, with no gap between them.
+test("an Instagram fetch runs on platform:instagram and nowhere else: a job on any other queue is refused when it runs, and gallery-dl is not started", async () => {
+ await reset();
+ // By the rule the action asks before a job exists…
+ const config = (await readChannelConfig(paths, SLUGS[0]))!;
+ assert.equal(instagramQueueProblem(SLUGS[0], config, undefined), null);
+ assert.equal(instagramQueueProblem(SLUGS[0], config, "platform:instagram"), null);
+ assert.equal(instagramQueueProblem(SLUGS[0], config, " platform:instagram "), null);
+ for (const side of ["side", "", "platform:twitter", "platform:instagram.com"]) {
+ assert.match(
+ instagramQueueProblem(SLUGS[0], config, side) ?? "",
+ /is an Instagram channel: its jobs run on platform:instagram and nowhere else \(one at a time, ten minutes apart\)/,
+ side,
+ );
+ }
+ // An X channel's override is not Instagram's business.
+ assert.equal(instagramQueueProblem("x", { sourceKind: "social", platform: "twitter", url: "https://x.com/example" }, "side"), null);
+ // A channel that is Instagram's by its URL alone is held to it too.
+ assert.match(instagramQueueProblem("c", { sourceKind: "social", url: "https://www.instagram.com/example.account/" }, "side") ?? "", /nowhere else/);
+
+ // …and by the fetch itself, whatever queued the job: a named side queue is not the network guard's
+ // "unqueued" case, so the job starts — and is refused before anything is asked.
+ const starts = new Map<string, number>();
+ const res = await fetchJob(SLUGS[0], starts, {}, "side");
+ assert.equal(res.ok, true, res.ok ? "" : res.error);
+ if (res.ok) {
+ const end = await res.done;
+ assert.equal(end.status, "failed");
+ assert.match(await readLog(end.jobId), /its jobs run on platform:instagram and nowhere else .*the queue override "side" is refused/);
+ }
+ assert.equal(await runCount(), 0);
+ assert.equal(cdn.length, 0);
+});
diff --git a/common/jobs/instagramSchedule.test.ts b/common/jobs/instagramSchedule.test.ts
@@ -0,0 +1,74 @@
+// The scheduler does not queue an Instagram channel its fetch would refuse
+// (review 1, S10): no cookie source of its own, or Instagram held by its
+// alert or its cooldown. Such a channel takes no sync slot, and the schedule
+// view says why.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { defaultSyncScheduler } from "../lib/settings";
+import { defaultChannelPriority } from "../lib/channelPriority";
+import { emptySchedulerState } from "./syncSchedulerState";
+import { buildScheduleView, INSTAGRAM_SYNC_NO_COOKIES, instagramSyncHold, selectDueChannels } from "./syncScheduler";
+
+const NOW = Date.parse("2026-03-10T12:00:00Z");
+const scheduler = { ...defaultSyncScheduler(), enabled: true, defaultIntervalMinutes: 60, quietHoursStart: null, quietHoursEnd: null };
+const ig = (cookies?: string): ChannelConfig =>
+ ({ handling: "transcribe", sourceKind: "social", platform: "instagram", url: "https://www.instagram.com/example.account/", ...(cookies ? { cookiesFromBrowser: cookies } : {}) }) as ChannelConfig;
+const x: ChannelConfig = { handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/example" } as ChannelConfig;
+const channels = [
+ { slug: "ig-bare", config: ig() },
+ { slug: "ig-ready", config: ig("firefox:ig-profile") },
+ { slug: "x-chan", config: x },
+];
+const base = { channels, scheduler, state: emptySchedulerState(), activeSlugs: new Set<string>(), now: NOW, priority: defaultChannelPriority() };
+const HELD = "Instagram answered a rate limit a short while ago: no Instagram job starts before 13:00 UTC (60 min from now). Ask again then; nothing retries by itself.";
+
+test("an Instagram channel with no cookie source is never due; one with a source is, like any never-synced channel", () => {
+ const r = selectDueChannels(base);
+ assert.deepEqual([...r.due].sort(), ["ig-ready", "x-chan"]);
+ // Configuration, not a hold: no line in the run log each tick.
+ assert.deepEqual(r.skipped, []);
+});
+
+test("while Instagram is held every Instagram channel is skipped with the sentence, and takes no slot; X is not Instagram's business", () => {
+ const r = selectDueChannels({ ...base, instagramHeld: HELD });
+ assert.deepEqual(r.due, ["x-chan"]);
+ assert.deepEqual(r.skipped, [{ slug: "ig-ready", reason: HELD }]);
+});
+
+test("the schedule view agrees: not eligible, with the reason", () => {
+ const view = buildScheduleView({ ...base, instagramHeld: HELD });
+ const of = (slug: string) => view.find((v) => v.slug === slug)!;
+ assert.deepEqual([of("ig-bare").autoSyncEligible, of("ig-bare").heldReason], [false, INSTAGRAM_SYNC_NO_COOKIES]);
+ assert.deepEqual([of("ig-ready").autoSyncEligible, of("ig-ready").heldReason], [false, HELD]);
+ assert.deepEqual([of("x-chan").autoSyncEligible, of("x-chan").heldReason], [true, undefined]);
+ const free = buildScheduleView(base);
+ assert.equal(free.find((v) => v.slug === "ig-ready")!.autoSyncEligible, true);
+ assert.equal(free.find((v) => v.slug === "ig-ready")!.heldReason, undefined);
+});
+
+test("the one predicate", () => {
+ assert.equal(instagramSyncHold(x, HELD), null);
+ assert.equal(instagramSyncHold(ig(), null), INSTAGRAM_SYNC_NO_COOKIES);
+ assert.equal(instagramSyncHold(ig(" "), null), INSTAGRAM_SYNC_NO_COOKIES);
+ assert.equal(instagramSyncHold(ig("file:/x"), null), null);
+ assert.equal(instagramSyncHold(ig("file:/x"), HELD), HELD);
+ // A video channel that names the platform is not an Instagram posts channel.
+ assert.equal(instagramSyncHold({ platform: "instagram" } as ChannelConfig, HELD), null);
+});
+
+// Review 2, N7: the scheduler and the fetch agree about which channel is
+// Instagram's — by the platform, the fetcher or the URL's host.
+test("an Instagram channel told only by its URL (no platform in its config) is held back like any other", () => {
+ const byUrl = { handling: "transcribe", sourceKind: "social", url: "https://www.instagram.com/example.account/" } as ChannelConfig;
+ const byFetcher = { handling: "transcribe", sourceKind: "social", postFetcher: "instagram-gallery-dl", url: "https://example.invalid/x" } as ChannelConfig;
+ assert.equal(instagramSyncHold(byUrl, null), INSTAGRAM_SYNC_NO_COOKIES);
+ assert.equal(instagramSyncHold(byFetcher, null), INSTAGRAM_SYNC_NO_COOKIES);
+ assert.equal(instagramSyncHold({ ...byUrl, cookiesFromBrowser: "firefox:ig" } as ChannelConfig, HELD), HELD);
+ const r = selectDueChannels({ ...base, channels: [{ slug: "ig-by-url", config: byUrl }, { slug: "x-chan", config: x }] });
+ assert.deepEqual(r.due, ["x-chan"]);
+ const view = buildScheduleView({ ...base, channels: [{ slug: "ig-by-url", config: byUrl }] });
+ assert.deepEqual([view[0]!.autoSyncEligible, view[0]!.heldReason], [false, INSTAGRAM_SYNC_NO_COOKIES]);
+ // Its cadence is Instagram's too.
+ assert.equal(view[0]!.intervalMinutes, 720);
+});
diff --git a/common/jobs/instagramSyncInterval.test.ts b/common/jobs/instagramSyncInterval.test.ts
@@ -0,0 +1,35 @@
+// An Instagram channel is synced seldom, whatever the global default
+// (syncScheduler.ts resolveIntervalMinutes). Every other channel's interval is
+// what it was.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { defaultSyncScheduler } from "../lib/settings";
+import { INSTAGRAM_DEFAULT_SYNC_MINUTES, INSTAGRAM_MIN_SYNC_MINUTES, resolveIntervalMinutes } from "./syncScheduler";
+
+const sched = (defaultIntervalMinutes: number) => ({ ...defaultSyncScheduler(), defaultIntervalMinutes });
+const ig = (syncIntervalMinutes?: number) =>
+ ({ sourceKind: "social", platform: "instagram", ...(syncIntervalMinutes !== undefined ? { syncIntervalMinutes } : {}) }) as ChannelConfig;
+const x = (syncIntervalMinutes?: number) =>
+ ({ sourceKind: "social", platform: "twitter", ...(syncIntervalMinutes !== undefined ? { syncIntervalMinutes } : {}) }) as ChannelConfig;
+
+test("an Instagram channel with no interval of its own: every 12 hours at the most often", () => {
+ assert.equal(INSTAGRAM_DEFAULT_SYNC_MINUTES, 720);
+ assert.equal(resolveIntervalMinutes(ig(), sched(60)), 720);
+ assert.equal(resolveIntervalMinutes(ig(), sched(1440)), 1440);
+ // A global default of 0 (no default cadence) is still none.
+ assert.equal(resolveIntervalMinutes(ig(), sched(0)), 0);
+});
+
+test("its own interval is never under 4 hours, and 0 turns its auto-sync off", () => {
+ assert.equal(INSTAGRAM_MIN_SYNC_MINUTES, 240);
+ assert.equal(resolveIntervalMinutes(ig(30), sched(60)), 240);
+ assert.equal(resolveIntervalMinutes(ig(480), sched(60)), 480);
+ assert.equal(resolveIntervalMinutes(ig(0), sched(60)), 0);
+});
+
+test("every other channel's interval is what it was", () => {
+ assert.equal(resolveIntervalMinutes(x(), sched(60)), 60);
+ assert.equal(resolveIntervalMinutes(x(30), sched(60)), 30);
+ assert.equal(resolveIntervalMinutes({ platform: "instagram" } as ChannelConfig, sched(60)), 60, "a video channel is not an Instagram posts channel");
+});
diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts
@@ -7,6 +7,10 @@
// 2. X ONLY WHILE NO X ALERT IS UP. A challenge or login wall from X raises
// the X cookie alert (lib/serviceCookies.ts); until Recheck or Dismiss
// clears it, every job aimed at X is refused before it asks anything.
+// INSTAGRAM THE SAME (lane instagram): its alert refuses every Instagram
+// job until a person's Recheck, and so does its cooldown after a rate
+// limit (jobs/instagramGuard.ts). Which platforms have a guard is ONE
+// table, PLATFORM_GUARDS below.
// 3. X ONLY ON A FRESH JAR. With the "profile" login source, a job aimed at X
// starts only when the exported cookie jar was written within
// `social.x.maxCookieAgeMinutes` (default 60; 0 = off) and carries a login.
@@ -26,7 +30,8 @@ import { channelConfigSchema } from "../lib/channelConfigSchema";
import { downloadQueueKey } from "../lib/queueKeys";
import { getSettings, type SiteSettings } from "../lib/settings";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
-import { serviceFixText, X_SERVICE } from "../lib/serviceCookies";
+import { INSTAGRAM_SERVICE, serviceFixText, X_SERVICE } from "../lib/serviceCookies";
+import { instagramJobGuard } from "./instagramGuard";
import {
configuredCookieBrowser,
noteServiceStoppedJob,
@@ -279,16 +284,11 @@ export type NetworkGuardResult =
| { ok: true; notes: string[] }
| { ok: false; error: string };
-// Asked at ENQUEUE (no job yet) and at START (`job` set: a refusal by the X
-// alert is recorded against the alert, so "Re-run stopped jobs" offers it).
-export async function guardNetworkJob(
- opts: NetworkJobOpts & { job?: { id: string } },
-): Promise<NetworkGuardResult> {
- if (!kindIsNetwork(opts.kind)) return { ok: true, notes: [] };
- const empty = emptyQueueRefusal(opts.kind, opts.queueKey);
- if (empty) return { ok: false, error: empty };
- const platform = await networkJobPlatform(opts);
- if (platform !== "twitter") return { ok: true, notes: [] };
+// One platform's guard: asked with the job's options, at enqueue and at start.
+type PlatformGuard = (opts: NetworkJobOpts & { job?: { id: string } }) => Promise<NetworkGuardResult>;
+
+// X's (rules 2 and 3 above).
+async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promise<NetworkGuardResult> {
const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug });
if (x.ok) {
// The jar passed at a job's START: a jar-age banner from an earlier
@@ -311,3 +311,34 @@ export async function guardNetworkJob(
}
return { ok: false, error: x.message };
}
+
+// Instagram's: its alert, then its cooldown (jobs/instagramGuard.ts).
+async function guardInstagramJob(opts: NetworkJobOpts & { job?: { id: string } }): Promise<NetworkGuardResult> {
+ const g = await instagramJobGuard({ paths: opts.paths });
+ if (g.ok) return { ok: true, notes: [] };
+ if (g.alert && opts.job) {
+ await noteServiceStoppedJob(opts.paths, INSTAGRAM_SERVICE, { id: opts.job.id, kind: opts.kind });
+ }
+ return { ok: false, error: g.message };
+}
+
+// THE PLATFORMS THAT HAVE A GUARD, by the platform a job asks
+// (networkJobPlatform). A platform absent here runs on its queue and gap alone.
+export const PLATFORM_GUARDS: Readonly<Record<string, PlatformGuard>> = Object.freeze({
+ twitter: guardXJob,
+ instagram: guardInstagramJob,
+});
+
+// Asked at ENQUEUE (no job yet) and at START (`job` set: a refusal by the
+// platform's alert is recorded against the alert, so "Re-run stopped jobs"
+// offers it).
+export async function guardNetworkJob(
+ opts: NetworkJobOpts & { job?: { id: string } },
+): Promise<NetworkGuardResult> {
+ if (!kindIsNetwork(opts.kind)) return { ok: true, notes: [] };
+ const empty = emptyQueueRefusal(opts.kind, opts.queueKey);
+ if (empty) return { ok: false, error: empty };
+ const platform = await networkJobPlatform(opts);
+ const guard = platform && Object.hasOwn(PLATFORM_GUARDS, platform) ? PLATFORM_GUARDS[platform] : undefined;
+ return guard ? guard(opts) : { ok: true, notes: [] };
+}
diff --git a/common/jobs/queueGap.ts b/common/jobs/queueGap.ts
@@ -71,6 +71,7 @@ export function queueGapFor(
const PLATFORM_NAMES: Record<string, string> = {
twitter: "X",
bluesky: "Bluesky",
+ instagram: "Instagram",
xenforo: "Forum",
youtube: "YouTube",
rumble: "Rumble",
diff --git a/common/jobs/resumeInterrupted.test.ts b/common/jobs/resumeInterrupted.test.ts
@@ -232,3 +232,50 @@ test("the boot's running pass then the resume: what it closed is what it resumes
await rm(fx.root, { recursive: true, force: true });
}
});
+
+// Lane instagram: a restart never asks Instagram.
+test("an interrupted Instagram fetch is not re-queued by a boot: it waits for the next scheduled or pressed sync", async () => {
+ const spec: JobSpec = { kind: "fetch-posts", slug: "example-ig", params: {} };
+ const fx = await fixture([
+ { id: "IG1", kind: "fetch-posts", queueKey: "platform:instagram", channelSlug: "example-ig", spec },
+ { id: "X1", kind: "fetch-posts", queueKey: "platform:twitter", channelSlug: "example-x", spec: { kind: "fetch-posts", slug: "example-x", params: {} } },
+ ]);
+ try {
+ const { calls, requeue } = recorder();
+ const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["IG1", "X1"], now: NOW });
+ const ig = out.find((o) => o.id === "IG1")!;
+ assert.equal(ig.action, "not-resumed");
+ assert.match((ig as { reason: string }).reason, /an Instagram job is not started by a restart/);
+ // X's fetch resumes as it did.
+ assert.equal(out.find((o) => o.id === "X1")!.action, "resumed");
+ assert.deepEqual(calls.map((c) => c.slug), ["example-x"]);
+ assert.match((await fx.read("IG1")).cancelReason ?? "", /not resumed: an Instagram job is not started by a restart/);
+ } finally {
+ await rm(fx.root, { recursive: true, force: true });
+ }
+});
+
+// Review 2, N1: a queue key is only where a job ran. An Instagram channel's
+// job that ran on another queue is left too.
+test("an interrupted fetch of an Instagram channel is not re-queued whatever queue it ran on", async () => {
+ const spec: JobSpec = { kind: "fetch-posts", slug: "example-ig", params: { queueKey: "side" } };
+ const fx = await fixture([
+ { id: "IG2", kind: "fetch-posts", queueKey: "side", channelSlug: "example-ig", spec },
+ { id: "X2", kind: "fetch-posts", queueKey: "side", channelSlug: "example-x", spec: { kind: "fetch-posts", slug: "example-x", params: { queueKey: "side" } } },
+ ]);
+ try {
+ const channelsDir = path.join(fx.root, "channels");
+ await mkdir(path.join(channelsDir, "example-ig"), { recursive: true });
+ await mkdir(path.join(channelsDir, "example-x"), { recursive: true });
+ // Told by its URL alone: no platform in the config.
+ await writeFile(path.join(channelsDir, "example-ig", "config.json"), JSON.stringify({ sourceKind: "social", url: "https://www.instagram.com/example.account/" }));
+ await writeFile(path.join(channelsDir, "example-x", "config.json"), JSON.stringify({ sourceKind: "social", platform: "twitter", url: "https://x.com/example" }));
+ const { calls, requeue } = recorder();
+ const out = await resumeInterruptedJobs({ paths: { ...fx.paths, channelsDir } as Paths, requeue, ids: ["IG2", "X2"], now: NOW });
+ assert.equal(out.find((o) => o.id === "IG2")!.action, "not-resumed");
+ assert.equal(out.find((o) => o.id === "X2")!.action, "resumed");
+ assert.deepEqual(calls.map((c) => c.slug), ["example-x"]);
+ } finally {
+ await rm(fx.root, { recursive: true, force: true });
+ }
+});
diff --git a/common/jobs/resumeInterrupted.ts b/common/jobs/resumeInterrupted.ts
@@ -34,7 +34,8 @@
// `resumedAs`.
import path from "node:path";
-import { appendFile, readdir } from "node:fs/promises";
+import { appendFile, readFile, readdir } from "node:fs/promises";
+import { INSTAGRAM_QUEUE_KEY, isInstagramPostsChannelConfig, type InstagramChannelSigns } from "../lib/instagram/channel";
import { writeFileAtomic } from "../lib/jsonFile-server";
import type { Paths } from "../lib/paths";
import { INTERRUPTED_REASON, specKey, type RequeueFn } from "./bootQueuedJobs";
@@ -47,6 +48,23 @@ import { runWithResumeTag } from "./resumeTag";
// is "interrupted twice in a row" and is left for the operator.
export const MAX_RESUMES_IN_A_ROW = 1;
+// Why an interrupted Instagram job is left: one on Instagram's queue, or — a
+// queue key is only where the job ran — one whose channel is an Instagram
+// posts channel by the one predicate (lib/instagram/channel.ts).
+export { INSTAGRAM_QUEUE_KEY };
+
+async function isInstagramChannel(paths: Paths, slug: string | undefined): Promise<boolean> {
+ if (!slug || !paths.channelsDir) return false;
+ try {
+ const raw = JSON.parse(await readFile(path.join(paths.channelsDir, slug, "config.json"), "utf8")) as InstagramChannelSigns;
+ return isInstagramPostsChannelConfig(raw);
+ } catch {
+ return false;
+ }
+}
+export const INSTAGRAM_NOT_RESUMED =
+ "an Instagram job is not started by a restart — its place is saved, and the next scheduled sync (or a press) continues from it";
+
// How far back the by-hand command looks (the boot looks only at what it just
// closed).
export const RESUME_WINDOW_MS = 24 * 60 * 60 * 1000;
@@ -177,6 +195,14 @@ export async function resumeInterruptedJobs(opts: ResumeInterruptedOpts): Promis
await decline(meta, "kind", `${jobKindLabel(meta.kind)} does not resume on a re-run`);
continue;
}
+ // AN INSTAGRAM JOB IS NEVER STARTED BY A RESTART (lane instagram): every
+ // one is a logged-in read, and a boot that re-queued it would ask
+ // Instagram at a moment nobody chose. Its resume point is on disk; the
+ // next scheduled sync, or a press, continues from it.
+ if (meta.queueKey === INSTAGRAM_QUEUE_KEY || (await isInstagramChannel(opts.paths, meta.channelSlug ?? meta.spec?.slug))) {
+ await decline(meta, "not-resumable", INSTAGRAM_NOT_RESUMED);
+ continue;
+ }
if (!meta.spec) {
await decline(meta, "no-spec", "it has no replay descriptor");
continue;
diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts
@@ -519,6 +519,7 @@ export async function runManagedFunction(
jobId: id,
kind: opts.kind,
...(opts.channelSlug ? { channelSlug: opts.channelSlug } : {}),
+ queueKey: opts.queueKey,
onLog,
staleServices: new Set<string>(),
};
diff --git a/common/jobs/syncScheduler.ts b/common/jobs/syncScheduler.ts
@@ -1,3 +1,4 @@
+import { isInstagramPostsChannelConfig } from "../lib/instagram/channel";
import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig";
import type { SyncSchedulerSettings } from "../lib/settings";
import {
@@ -47,8 +48,38 @@ export type SelectDueInput = {
// sync, so it is the same on every tick until the next sync. Absent = 0, the
// exact interval (this module reads no settings; the tick passes it).
jitter?: number;
+ // WHY NO INSTAGRAM JOB STARTS NOW, when none does: Instagram's alert is up,
+ // or it is cooling down after a rate limit (jobs/instagramGuard.ts — I/O,
+ // so the tick asks and hands the sentence in). Every Instagram channel is
+ // then skipped with it, and takes no sync slot.
+ instagramHeld?: string | null;
};
+// WHY AN INSTAGRAM CHANNEL IS NOT SYNCED NOW, or null (review 1, S10). A
+// channel with no cookie source of its own would be refused by its fetch
+// before anything is asked; one while Instagram is held, by the guard. Either
+// way the scheduler does not queue it — a refusal each tick is a failed job
+// and a sync slot spent on nothing.
+export const INSTAGRAM_SYNC_NO_COOKIES =
+ "Instagram: no cookie source of its own (set Cookies from browser on the channel's Edit form)";
+
+// The ONE predicate (lib/instagram/channel.ts): the platform, the fetcher or
+// the URL's host — whatever the fetch itself would treat as Instagram's.
+export function isInstagramPostsConfig(
+ config: Pick<ChannelConfig, "sourceKind" | "platform"> & Partial<Pick<ChannelConfig, "postFetcher" | "url">>,
+): boolean {
+ return isInstagramPostsChannelConfig(config);
+}
+
+export function instagramSyncHold(
+ config: Pick<ChannelConfig, "sourceKind" | "platform" | "cookiesFromBrowser"> & Partial<Pick<ChannelConfig, "postFetcher" | "url">>,
+ held: string | null | undefined,
+): string | null {
+ if (!isInstagramPostsConfig(config)) return null;
+ if (!config.cookiesFromBrowser?.trim()) return INSTAGRAM_SYNC_NO_COOKIES;
+ return held ? held : null;
+}
+
// The most a channel's sync is pushed back by the jitter, whatever its
// interval: a share of a 24 h interval would otherwise be hours.
export const SYNC_JITTER_CAP_MS = 30 * 60_000;
@@ -65,12 +96,26 @@ export type SelectDueResult = {
// Resolve a channel's effective interval in minutes. undefined inherits the
// global default; 0 means auto-sync is disabled for the channel.
+//
+// AN INSTAGRAM CHANNEL IS SYNCED SELDOM (lane instagram): every sync is a
+// logged-in read, and Instagram checkpoints an account that reads too often.
+// With no interval of its own it is synced every 12 hours at the most often
+// (the global default when that is longer), and an interval of its own is
+// never under 4 hours. 0 still turns its auto-sync off.
+export const INSTAGRAM_DEFAULT_SYNC_MINUTES = 12 * 60;
+export const INSTAGRAM_MIN_SYNC_MINUTES = 4 * 60;
+
export function resolveIntervalMinutes(
config: ChannelConfig,
scheduler: SyncSchedulerSettings,
): number {
+ const instagram = isInstagramPostsConfig(config);
if (config.syncIntervalMinutes === undefined) {
- return scheduler.defaultIntervalMinutes;
+ const inherited = scheduler.defaultIntervalMinutes;
+ return instagram && inherited > 0 ? Math.max(inherited, INSTAGRAM_DEFAULT_SYNC_MINUTES) : inherited;
+ }
+ if (instagram && config.syncIntervalMinutes > 0) {
+ return Math.max(config.syncIntervalMinutes, INSTAGRAM_MIN_SYNC_MINUTES);
}
return config.syncIntervalMinutes;
}
@@ -153,6 +198,16 @@ export function selectDueChannels(input: SelectDueInput): SelectDueResult {
const interval = resolveIntervalMinutes(config, scheduler);
if (interval <= 0) continue; // per-channel disabled
+ // An Instagram channel that would be refused anyway is not queued: with
+ // no cookie source it is configuration (silent, like a paused channel —
+ // the schedule view says why); while Instagram is held it is a hold worth
+ // a line.
+ const igHold = instagramSyncHold(config, input.instagramHeld);
+ if (igHold) {
+ if (igHold !== INSTAGRAM_SYNC_NO_COOKIES) skipped.push({ slug, reason: igHold });
+ continue;
+ }
+
if (activeSlugs.has(slug)) {
skipped.push({ slug, reason: "already running" });
continue;
@@ -215,6 +270,10 @@ export type ChannelScheduleView = {
// on, so the sync console can never show a channel as eligible that the
// scheduler will not schedule.
autoSyncEligible: boolean;
+ // Why the scheduler does not sync this channel now though its settings
+ // would have it synced (an Instagram channel with no cookie source, or while
+ // Instagram is held). `autoSyncEligible` is false with it.
+ heldReason?: string;
intervalMinutes: number; // resolved; 0 = disabled
inheritsInterval: boolean; // using the global default vs a per-channel value
// The raw per-channel value as stored in config (undefined = inherit global,
@@ -252,9 +311,12 @@ export function buildScheduleView(input: {
// The scheduler's jitter (SelectDueInput.jitter), so the next-due time shown
// is the one selectDueChannels will act on.
jitter?: number;
+ // SelectDueInput.instagramHeld: the same sentence, for the same skip.
+ instagramHeld?: string | null;
}): ChannelScheduleView[] {
const { channels, scheduler, state, now, priority } = input;
return channels.map(({ slug, config }) => {
+ const igHold = instagramSyncHold(config, input.instagramHeld);
const interval = resolveIntervalMinutes(config, scheduler);
const sweepInterval = resolveFullSweepIntervalMinutes(config, scheduler);
const cs = state.channels[slug];
@@ -284,7 +346,9 @@ export function buildScheduleView(input: {
!!config.url &&
!isRemoteOnlyChannel(config) &&
!isChannelPaused(priority, slug, "sync") &&
- interval > 0,
+ interval > 0 &&
+ !igHold,
+ ...(igHold ? { heldReason: igHold } : {}),
intervalMinutes: interval,
inheritsInterval: config.syncIntervalMinutes === undefined,
configuredIntervalMinutes: config.syncIntervalMinutes,
diff --git a/common/lib/builtHomepage.test.ts b/common/lib/builtHomepage.test.ts
@@ -90,3 +90,21 @@ test("while X posts are private: no X post's moment and no X captures; public X
assert.equal(builtHomepageProblem(xMoment, { paths, settings: {} }), null);
assert.equal(builtHomepageProblem(xMedia, { paths, settings: {} }), null);
});
+
+// INSTAGRAM (lane instagram): private unless social.instagram.visibility is
+// "public" — a homepage built while it was public is caught after the flip.
+test("while Instagram posts are private (the default): no Instagram post's moment and no Instagram captures; public ones pass", () => {
+ put(path.join(paths.channelsDir, "igchan", "config.json"), { sourceKind: "social", platform: "instagram" });
+ const IG_PUBLIC = { social: { instagram: { visibility: "public" } } };
+ const igMoment = out({ "m/igchan/3500000000000000001/moment.json": moment("/articles/open/") });
+ assert.match(builtHomepageProblem(igMoment, { paths, settings: {} }) ?? "", /moment igchan\/3500000000000000001 is an Instagram post, and Instagram posts are private \(social\.instagram\.visibility\)/);
+ const igMedia = out({ "media/posts/igchan/3500000000000000001/01-1.jpg": "jpg" });
+ assert.match(builtHomepageProblem(igMedia, { paths, settings: {} }) ?? "", /media\/posts\/igchan\/, an Instagram channel's captures/);
+ assert.equal(builtHomepageProblem(igMoment, { paths, settings: IG_PUBLIC }), null);
+ assert.equal(builtHomepageProblem(igMedia, { paths, settings: IG_PUBLIC }), null);
+ // X's answers are what they were, whatever Instagram's setting.
+ const xMoment = out({ "m/xchan/123/moment.json": moment("/articles/open/") });
+ assert.equal(builtHomepageProblem(xMoment, { paths, settings: {} }), null);
+ assert.equal(builtHomepageProblem(xMoment, { paths, settings: IG_PUBLIC }), null);
+ assert.match(builtHomepageProblem(xMoment, { paths, settings: { ...X_PRIVATE.social ? { social: { ...X_PRIVATE.social, instagram: { visibility: "public" } } } : {} } }) ?? "", /is an X post/);
+});
diff --git a/common/lib/builtHomepage.ts b/common/lib/builtHomepage.ts
@@ -26,7 +26,7 @@
import { existsSync, readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import type { Paths } from "./paths";
-import { isXPostsChannel, xPostsVisibility } from "./postsVisibility";
+import { anyPostsPlatformPrivate, withheldPostsPlatform } from "./postsVisibility";
import { ARTICLES_REPORTS_BASE, reportBaseDir } from "./report/routes";
export const HOMEPAGE_BUILD_STAMP = "homepage-build.json";
@@ -34,7 +34,7 @@ export const HOMEPAGE_BUILD_STAMP = "homepage-build.json";
export type HomepageAuditOptions = {
paths?: Pick<Paths, "articlesDir" | "channelsDir">;
// `social.x.visibility`; asked only with `paths`.
- settings?: { social?: { x?: { visibility?: unknown } } };
+ settings?: { social?: { x?: { visibility?: unknown }; instagram?: { visibility?: unknown } } };
};
const readJson = (file: string): unknown => {
@@ -98,14 +98,19 @@ export function homepageAudienceProblem(outDir: string, opts: HomepageAuditOptio
}
}
- const xPrivate = xPostsVisibility(opts.settings ?? {}) === "private";
- const configs = new Map<string, boolean>();
- const isX = (slug: string) => {
+ // A posts platform that is private now (X by its setting; Instagram unless
+ // set public): which one withholds a channel, or null.
+ const settings = opts.settings ?? {};
+ const xPrivate = anyPostsPlatformPrivate(settings);
+ const configs = new Map<string, "x" | "instagram" | null>();
+ const withheld = (slug: string) => {
if (!configs.has(slug)) {
- configs.set(slug, isXPostsChannel(readJson(path.join(paths.channelsDir, slug, "config.json")) as never));
+ configs.set(slug, withheldPostsPlatform(readJson(path.join(paths.channelsDir, slug, "config.json")) as never, settings));
}
return configs.get(slug)!;
};
+ const isX = (slug: string) => withheld(slug) === "x";
+ const isInstagram = (slug: string) => withheld(slug) === "instagram";
const articlePrefix = ARTICLES_REPORTS_BASE;
for (const m of momentFiles(outDir)) {
const view = readJson(m.file) as { citedIn?: { href?: unknown }[] } | null;
@@ -119,12 +124,18 @@ export function homepageAudienceProblem(outDir: string, opts: HomepageAuditOptio
if (xPrivate && isX(m.key.split("/")[0])) {
return `the homepage build's moment ${m.key} is an X post, and X posts are private (social.x.visibility) — rebuild the homepage`;
}
+ if (xPrivate && isInstagram(m.key.split("/")[0])) {
+ return `the homepage build's moment ${m.key} is an Instagram post, and Instagram posts are private (social.instagram.visibility) — rebuild the homepage`;
+ }
}
if (xPrivate) {
for (const slug of dirs(path.join(outDir, "media", "posts"))) {
if (isX(slug)) {
return `the homepage build carries media/posts/${slug}/, an X channel's captures, and X posts are private (social.x.visibility) — rebuild the homepage`;
}
+ if (isInstagram(slug)) {
+ return `the homepage build carries media/posts/${slug}/, an Instagram channel's captures, and Instagram posts are private (social.instagram.visibility) — rebuild the homepage`;
+ }
}
}
return null;
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -316,14 +316,14 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
sourceKind:
'What KIND of source this is: `"video"` (default — yt-dlp + transcription) or `"social"` (an account fetched into the posts corpus, skipped by the video scan). A separate axis from `handling`, so every binary handling branch stays binary.',
postFetcher:
- 'Social channels only: which social fetcher drives ingest (e.g. `"bluesky-atproto"`, `"x-gallery-dl"`). Absent = resolve by URL detection. Trimmed.',
+ 'Social channels only: which social fetcher drives ingest (e.g. `"bluesky-atproto"`, `"x-gallery-dl"`, `"instagram-gallery-dl"`). Absent = resolve by URL detection. Trimmed.',
socialHandle:
'Social channels only: the bare account handle (a leading "@" is stripped). Derived from `url` at creation but stored, so a later URL-format change upstream cannot silently re-point ingest at a different account.',
postPagePauseSeconds:
"Social channels that are read page by page (a forum thread) only: the pause between two page loads, in seconds; each pause is jittered to 0.85–1.65× of it. Absent = the fetcher's own (12 s, so 10–20 s); floored at 5, capped at 600.",
postCaptureThread:
'X channels only: `capture-posts` also shoots each reply\'s THREAD SHOT — the post it answers over the reply, `posts-media/<id>/shot-thread.png` beside `shot.png`, the parent\'s author blurred unless verified or the reply\'s own — unless the run says `"thread": false`. Absent = false (a run asks with `"thread": true`).',
- platform: "The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, \"archive.org items\"), bitchute (BitChute videos and channels; see README.md, \"BitChute\"), twitter, bluesky, xenforo (a forum thread) or webpage (Wayback Machine captures of pages; see `wayback`). An unknown value is dropped.",
+ platform: "The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, \"archive.org items\"), bitchute (BitChute videos and channels; see README.md, \"BitChute\"), twitter, bluesky, xenforo (a forum thread), webpage (Wayback Machine captures of pages; see `wayback`) or instagram (an Instagram account's posts and reels; OPERATING.md, \"Instagram accounts\"). An unknown value is dropped.",
name: "Display name.",
url: "The channel / playlist / account URL syncs enumerate. Absent = the channel is never auto-synced.",
audioFormat: '`"m4a"`, `"mp3"` or `"opus"`: the audio a transcribe-handling download keeps.',
@@ -371,7 +371,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
cleanAfterCaptureUnverified:
"Let clean-after-capture (settings `diarization.cleanAfterCapture`) delete this channel's audio with NO availability check. Only for a channel with no `url`: with no source there is nothing to list, so the automatic per-video clean holds every such channel (\"no source to check: clean by hand\") unless this is true. The manual Clean audio sweep is unaffected. Absent/false = held.",
syncIntervalMinutes:
- "Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync.",
+ "Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. AN INSTAGRAM CHANNEL is synced seldom, because every sync is a logged-in read: absent = every 12 hours at the most often (the global default when that is longer), and a value of its own is never under 240 (4 hours); 0 still turns it off (`common/jobs/syncScheduler.ts`).",
fullSweepIntervalMinutes:
"Full-sweep cadence: a sync upgrades itself to a full sweep when `now - lastFullSweepAt >= fullSweepIntervalMinutes`. Absent = inherit `syncScheduler.fullSweepIntervalMinutes`; 0 = never sweep (every sync is a paged walk); positives clamp to [1, 44640].",
skipLiveDownloads:
@@ -383,7 +383,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
skipShorts:
"`true`: the channel's YouTube Shorts — the listing entries whose URL is `youtube.com/shorts/<id>` — are not wanted. Decided from the listing URL alone (no metadata): a sync or full sweep does not download them, Download from playlist, Download videos and the bucket retries skip them, the metadata scan does not read them, and the report lists the ones with nothing on disk as `skippedShortsIds` instead of as undownloaded work (or, once delisted, as never-fetched losses). Importing a Shorts URL still downloads it, and a Short already on disk stays an ordinary video. Absent = Shorts are downloaded like any upload. A Configure field (`skipShorts`).",
cookiesFromBrowser:
- "Per-channel override of the global cookies-from-browser spec (a browser spec, or `file:<path>` for a cookies.txt). Trimmed; blank = inherit. A `firefox[:profile]` spec also sends that Firefox's own User-Agent (derived, so a Cloudflare clearance it earned is honoured after a browser update); a `--user-agent` in `ytdlpExtraArgs` overrides it.",
+ "Per-channel override of the global cookies-from-browser spec (a browser spec, or `file:<path>` for a cookies.txt). Trimmed; blank = inherit. A `firefox[:profile]` spec also sends that Firefox's own User-Agent (derived, so a Cloudflare clearance it earned is honoured after a browser update); a `--user-agent` in `ytdlpExtraArgs` overrides it. AN INSTAGRAM CHANNEL reads ONLY this, never the global spec: Instagram shows an account's posts only to a login, whose account is at risk of a checkpoint or a ban, so the source is chosen per channel — blank means nothing is fetched (`fetch-posts` refuses and says so). Name a browser profile or cookies file logged in to Instagram with an account kept for the archive.",
cookieMode: "Per-channel override of the global cookie mode. Absent = inherit.",
sleepBetweenDownloadsSeconds:
"Per-channel override for the global pause between downloads. Absent = inherit; 0 = no sleep; floored and capped at 600.",
diff --git a/common/lib/detectPlatform.mjs b/common/lib/detectPlatform.mjs
@@ -51,6 +51,7 @@ export function detectPlatform(url) {
if (host === "x.com" || host.endsWith(".x.com")) return "twitter";
if (host.endsWith("twitter.com")) return "twitter";
if (host === "bsky.app" || host.endsWith(".bsky.app")) return "bluesky";
+ if (host === "instagram.com" || host === "www.instagram.com") return "instagram";
// archive.org ITEMS only. Not web.archive.org (the Wayback Machine's page
// captures are a different kind of record) — see lib/archiveOrgId.ts.
if (host === "archive.org" || host === "www.archive.org") return "archiveorg";
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -228,7 +228,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "ARCHILYZER_NO_NETWORK_LOG", audience: "internal", default: "unset (no log)", readBy: "common/lib/noNetwork.mjs", doc: "A file. Under `ARCHILYZER_NO_NETWORK`, each refused door adds one JSON line to it: the door, the target and the process's argv. It finds the tests that reach for the network even when their code swallows the failure." },
{ name: "DO_NOT_TRACK", audience: "internal", default: "unset", readBy: "common/lib/noNetwork.mjs", doc: "The common opt-out of CLI telemetry. Set to `1` for the run's children when `ARCHILYZER_NO_NETWORK` is on, unless already set." },
{ name: "HYPERFRAMES_NO_TELEMETRY", audience: "internal", default: "unset (HyperFrames sends usage telemetry)", readBy: "common/lib/noNetwork.mjs (for the HyperFrames CLI umtool renders through)", doc: "`1`: the HyperFrames CLI sends no telemetry. Set to `1` for the run's children when `ARCHILYZER_NO_NETWORK` is on, unless already set. Outside test runs, nothing sets it." },
- { name: "E2E_TEST_ROUTES", audience: "test", default: "off", readBy: "editor/app/api/test/_guard.ts, editor/instrumentation.ts", doc: "`1` opens the editor's `/api/test/*` routes and marks a test server at boot. Set by `editor/playwright.config.ts` on its test server, and by nothing else." },
+ { name: "E2E_TEST_ROUTES", audience: "test", default: "off", readBy: "editor/app/api/test/_guard.ts, editor/instrumentation.ts, common/social/instagramMedia.ts, common/social/fakeXProfileBrowser.ts", doc: "`1` opens the editor's `/api/test/*` routes and marks a test server at boot. Under it Instagram's media CDN is played back, never asked (`fakeInstagramMediaDeps`). Set by `editor/playwright.config.ts` on its test server, and by nothing else." },
{ name: "E2E_MODE", audience: "test", default: "`start`", readBy: "editor/playwright.config.ts, umtool/playwright.config.ts, scripts/e2e-stamp.mjs", doc: "`start`: the editor and umtool suites run against `next start` from a build `scripts/e2e-stamp.mjs` vouches for, rebuilt through the heavy slot when the tree moved. `dev`: against `next dev`, for iterating on one spec. The export and homepage suites always run `next dev` (static exports) and say so when asked for `start`." },
{ name: "E2E_NEXT_DIST_DIR", audience: "test", default: "`.next`", readBy: "editor/next.config.ts, export/next.config.ts", doc: "The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server — and for the editor suite's export dev server (`.next/e2e-editor`), which then runs beside the export suite's own (Next allows one `next dev` per dist dir)." },
{ name: "E2E_MODEL_LOG_SHOTS", audience: "test", default: "unset (no screenshots)", readBy: "umtool/e2e/model-log.spec.ts, editor/e2e/report-draft.spec.ts", doc: "A directory: the model log's e2e (demo epic D3) saves its 1366×768 screenshots of the panel there — the run page live and done, a call opened, the Iterations tab, a media draft, the settings table, the editor's job page — for a lane's report. Unset, none is taken." },
diff --git a/common/lib/instagram/channel.ts b/common/lib/instagram/channel.ts
@@ -0,0 +1,48 @@
+// IS THIS AN INSTAGRAM POSTS CHANNEL? One predicate, pure and client-safe, for
+// everything that must agree about it: the fetch (controller/fetchPosts.ts),
+// the action that queues it, the scheduler that would queue it
+// (jobs/syncScheduler.ts) and the boot's resume (jobs/resumeInterrupted.ts).
+//
+// ANY SIGN OF INSTAGRAM COUNTS — the platform the config names, the fetcher it
+// names, or its URL's host — because the fetch refuses a channel whose signs
+// disagree (fetcherPlatformMismatch) and everything else must hold back the
+// same channels the fetch would treat as Instagram's. Testing the config's
+// `platform` alone queued a channel with an instagram.com URL and no platform
+// every tick, to be refused every tick.
+
+import { detectPlatform } from "../detectPlatform.mjs";
+
+export const INSTAGRAM_FETCHER_ID = "instagram-gallery-dl";
+export const INSTAGRAM_QUEUE_KEY = "platform:instagram";
+
+export type InstagramChannelSigns = {
+ sourceKind?: string;
+ platform?: string;
+ postFetcher?: string;
+ url?: string;
+};
+
+export function isInstagramPostsChannelConfig(config: InstagramChannelSigns | null | undefined): boolean {
+ if (!config || config.sourceKind !== "social") return false;
+ return (
+ config.platform === "instagram" ||
+ config.postFetcher === INSTAGRAM_FETCHER_ID ||
+ detectPlatform(config.url) === "instagram"
+ );
+}
+
+// An Instagram fetch runs on Instagram's queue and no other: a queue override
+// would run it beside the job already there, with no gap between them.
+export const INSTAGRAM_QUEUE_REFUSAL = (slug: string, asked: string) =>
+ `${slug} is an Instagram channel: its jobs run on ${INSTAGRAM_QUEUE_KEY} and nowhere else (one at a time, ten minutes apart), ` +
+ `so the queue override "${asked}" is refused. Leave the queue at its default.`;
+
+// Why a queue override is refused for this channel, or null.
+export function instagramQueueProblem(
+ slug: string,
+ config: InstagramChannelSigns | null | undefined,
+ override: string | undefined,
+): string | null {
+ if (override === undefined || !isInstagramPostsChannelConfig(config)) return null;
+ return override.trim() === INSTAGRAM_QUEUE_KEY ? null : INSTAGRAM_QUEUE_REFUSAL(slug, override);
+}
diff --git a/common/lib/instagram/ids.test.ts b/common/lib/instagram/ids.test.ts
@@ -0,0 +1,101 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ instagramPkFromShortcode,
+ instagramShortcodeFromPk,
+ isInstagramPk,
+ isInstagramShortcode,
+ parseInstagramPostUrl,
+ instagramPostUrl,
+ instagramAccountUrl,
+ instagramHandleFromUrl,
+} from "./ids";
+
+test("a pk and its shortcode convert both ways", () => {
+ // 0 -> "A", 63 -> "_", 64 -> "BA": the base-64 alphabet A-Z a-z 0-9 - _
+ assert.equal(instagramShortcodeFromPk("0"), "A");
+ assert.equal(instagramShortcodeFromPk("63"), "_");
+ assert.equal(instagramShortcodeFromPk("64"), "BA");
+ assert.equal(instagramPkFromShortcode("BA"), "64");
+ assert.equal(instagramPkFromShortcode("_"), "63");
+});
+
+test("a pk beyond 2^53 survives the round trip as a string", () => {
+ for (const pk of ["9007199254740993", "3141592653589793238", "18446744073709551615"]) {
+ const code = instagramShortcodeFromPk(pk);
+ assert.ok(code && isInstagramShortcode(code), pk);
+ assert.equal(instagramPkFromShortcode(code!), pk);
+ }
+ // 2^53 + 1 is not a Number: the conversion must not have gone through one.
+ assert.notEqual(String(Number("9007199254740993")), "9007199254740993");
+});
+
+test("a shortcode that starts with - or _ converts", () => {
+ for (const code of ["-AbCdEfGhIj", "_zzzzzzzzzz", "-", "--_-"]) {
+ const pk = instagramPkFromShortcode(code);
+ assert.ok(pk && isInstagramPk(pk), code);
+ }
+ assert.equal(instagramShortcodeFromPk(instagramPkFromShortcode("-AbCdEfGhIj")!), "-AbCdEfGhIj");
+ // A leading "A" is a leading zero: it does not round-trip, and never names a post.
+ assert.equal(instagramShortcodeFromPk(instagramPkFromShortcode("AB")!), "B");
+});
+
+test("a private post's long shortcode is cut to its public part", () => {
+ const code = "CabcDEF1234";
+ const long = code + "x".repeat(28);
+ assert.equal(instagramPkFromShortcode(long), instagramPkFromShortcode(code));
+});
+
+test("what is not a pk or a shortcode is refused", () => {
+ assert.equal(instagramShortcodeFromPk("12a"), null);
+ assert.equal(instagramShortcodeFromPk(""), null);
+ assert.equal(instagramShortcodeFromPk("-5"), null);
+ assert.equal(instagramPkFromShortcode("ab/cd"), null);
+ assert.equal(instagramPkFromShortcode(""), null);
+ assert.equal(isInstagramPk("123_456"), false);
+ assert.equal(isInstagramPk("0123"), true);
+});
+
+test("a post's URL names its pk", () => {
+ const code = "CabcDEF1234";
+ const pk = instagramPkFromShortcode(code)!;
+ for (const u of [
+ `https://www.instagram.com/p/${code}/`,
+ `https://instagram.com/reel/${code}`,
+ `https://www.instagram.com/reels/${code}/?igsh=abc`,
+ `https://www.instagram.com/example.account/p/${code}/`,
+ `https://www.instagram.com/tv/${code}/`,
+ ]) {
+ const ref = parseInstagramPostUrl(u);
+ assert.deepEqual(ref && { id: ref.id, shortcode: ref.shortcode }, { id: pk, shortcode: code }, u);
+ }
+ assert.equal(parseInstagramPostUrl(`https://www.instagram.com/example.account/p/${code}/`)?.handle, "example.account");
+ assert.equal(parseInstagramPostUrl("https://www.instagram.com/example.account/"), null);
+ assert.equal(parseInstagramPostUrl("https://example.com/p/abc/"), null);
+ assert.equal(parseInstagramPostUrl("https://www.instagram.com/stories/example.account/123/"), null);
+ // A sound's page and other paths that are not a post.
+ assert.equal(parseInstagramPostUrl("https://www.instagram.com/reels/audio/1234567890/"), null);
+ assert.equal(parseInstagramPostUrl("https://www.instagram.com/reels/Audio/"), null);
+ assert.equal(parseInstagramPostUrl(`https://www.instagram.com/p/${code}/liked_by/`), null);
+ assert.equal(parseInstagramPostUrl("https://www.instagram.com/explore/p/x/y/"), null);
+ // A shortcode that names no pk (longer than any pk is) is refused, not turned into an id.
+ const tooLong = "z".repeat(20);
+ assert.equal(instagramPkFromShortcode(tooLong), null);
+ assert.equal(parseInstagramPostUrl(`https://www.instagram.com/p/${tooLong}/`), null);
+});
+
+test("the URLs the archive writes", () => {
+ assert.equal(instagramPostUrl("post", "Cabc"), "https://www.instagram.com/p/Cabc/");
+ assert.equal(instagramPostUrl("reel", "Cabc"), "https://www.instagram.com/reel/Cabc/");
+ assert.equal(instagramAccountUrl("example.account"), "https://www.instagram.com/example.account/");
+});
+
+test("an account URL's handle, and the paths that are not accounts", () => {
+ assert.equal(instagramHandleFromUrl("https://www.instagram.com/example.account/"), "example.account");
+ assert.equal(instagramHandleFromUrl("https://instagram.com/Example_Account?hl=en"), "Example_Account");
+ for (const p of ["p/abc", "reel/abc", "reels/abc", "stories/x", "explore/tags/x", "accounts/login", "tv/abc", "direct/inbox", "share/abc"]) {
+ assert.equal(instagramHandleFromUrl(`https://www.instagram.com/${p}/`), null, p);
+ }
+ assert.equal(instagramHandleFromUrl("https://example.com/someone/"), null);
+ assert.equal(instagramHandleFromUrl("https://www.instagram.com/"), null);
+});
diff --git a/common/lib/instagram/ids.ts b/common/lib/instagram/ids.ts
@@ -0,0 +1,157 @@
+// INSTAGRAM IDS AND URLS (lane instagram). Pure and client-safe.
+//
+// THE ARCHIVE KEY IS THE NUMERIC MEDIA PK, never the shortcode: a story item
+// has no shortcode at all, a shortcode is case-sensitive and may begin with
+// "-" (a hazard as a directory name under `posts-media/`), and the two convert
+// to each other with no request — a shortcode is the pk written in base 64
+// with the alphabet below. So a post's URL (which carries the shortcode) still
+// resolves to its archive key offline.
+//
+// A pk is beyond 2^53 for every post made since about 2012: it is a STRING of
+// digits here, converted with BigInt, never a Number.
+
+const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
+const INDEX = new Map([...ALPHABET].map((c, i) => [c, BigInt(i)]));
+
+const PK_RE = /^\d{1,25}$/;
+const SHORTCODE_RE = /^[A-Za-z0-9_-]{1,64}$/;
+// A private account's post has 28 more characters after the public shortcode.
+const PRIVATE_TAIL = 28;
+
+export function isInstagramPk(v: unknown): v is string {
+ return typeof v === "string" && PK_RE.test(v);
+}
+
+export function isInstagramShortcode(v: unknown): v is string {
+ return typeof v === "string" && SHORTCODE_RE.test(v);
+}
+
+// "64" -> "BA". Null for anything that is not a run of digits.
+export function instagramShortcodeFromPk(pk: string): string | null {
+ if (!isInstagramPk(pk)) return null;
+ let n = BigInt(pk);
+ if (n === 0n) return ALPHABET[0]!;
+ let out = "";
+ while (n > 0n) {
+ out = ALPHABET[Number(n % 64n)]! + out;
+ n /= 64n;
+ }
+ return out;
+}
+
+// "BA" -> "64". A private post's long shortcode is cut to its public part.
+// Null when what it names is not a pk (longer than any pk is).
+export function instagramPkFromShortcode(shortcode: string): string | null {
+ if (!isInstagramShortcode(shortcode)) return null;
+ const code = shortcode.length > PRIVATE_TAIL ? shortcode.slice(0, -PRIVATE_TAIL) : shortcode;
+ let n = 0n;
+ for (const c of code) {
+ const d = INDEX.get(c);
+ if (d === undefined) return null;
+ n = n * 64n + d;
+ }
+ const pk = n.toString();
+ return isInstagramPk(pk) ? pk : null;
+}
+
+export const INSTAGRAM_ORIGIN = "https://www.instagram.com";
+
+export type InstagramPostKind = "post" | "reel" | "story" | "highlight";
+
+export const INSTAGRAM_POST_KINDS: ReadonlyArray<InstagramPostKind> = ["post", "reel", "story", "highlight"];
+
+// The permalink of a post or a reel, from its shortcode.
+export function instagramPostUrl(kind: "post" | "reel", shortcode: string): string {
+ return `${INSTAGRAM_ORIGIN}/${kind === "reel" ? "reel" : "p"}/${shortcode}/`;
+}
+
+export function instagramAccountUrl(handle: string): string {
+ return `${INSTAGRAM_ORIGIN}/${handle}/`;
+}
+
+function instagramPath(input: string): string[] | null {
+ let u: URL;
+ try {
+ u = new URL(input.trim());
+ } catch {
+ return null;
+ }
+ if (u.protocol !== "https:" && u.protocol !== "http:") return null;
+ const host = u.hostname.toLowerCase().replace(/^www\./, "");
+ if (host !== "instagram.com") return null;
+ try {
+ return u.pathname.split("/").filter(Boolean).map((s) => decodeURIComponent(s));
+ } catch {
+ return null;
+ }
+}
+
+export function isInstagramUrl(input: string | undefined | null): boolean {
+ return Boolean(input && instagramPath(input));
+}
+
+const HANDLE_RE = /^[A-Za-z0-9._]{1,30}$/;
+// First path segments that are not accounts.
+const RESERVED = new Set([
+ "p",
+ "tv",
+ "reel",
+ "reels",
+ "stories",
+ "s",
+ "explore",
+ "accounts",
+ "direct",
+ "share",
+ "about",
+ "api",
+ "graphql",
+ "web",
+ "developer",
+ "legal",
+ "challenge",
+]);
+
+// The account an account URL names (instagram.com/<handle>/…), or null: a
+// post, a story, a tag page and the login pages are not accounts.
+export function instagramHandleFromUrl(input: string): string | null {
+ const seg = instagramPath(input);
+ if (!seg || seg.length === 0) return null;
+ const first = seg[0]!.replace(/^@/, "");
+ if (RESERVED.has(first.toLowerCase())) return null;
+ return HANDLE_RE.test(first) ? first : null;
+}
+
+// Words in a shortcode's place that are not one.
+const NOT_SHORTCODES = new Set(["audio", "explore", "videos", "create", "trending"]);
+
+export type InstagramPostUrlRef = {
+ // The archive key (the numeric pk), from the shortcode.
+ id: string;
+ shortcode: string;
+ kind: "post" | "reel";
+ handle?: string;
+ url: string;
+};
+
+// A post or reel URL: /p/<code>/, /reel/<code>/, /reels/<code>/, /tv/<code>/,
+// each also under /<handle>/. A story URL is not one (its item has no
+// shortcode, and reading it needs a login).
+export function parseInstagramPostUrl(input: string): InstagramPostUrlRef | null {
+ const seg = instagramPath(input);
+ if (!seg) return null;
+ const k = seg.findIndex((s) => s === "p" || s === "tv" || s === "reel" || s === "reels");
+ if (k < 0 || k > 1) return null;
+ const shortcode = seg[k + 1];
+ if (!shortcode || !isInstagramShortcode(shortcode)) return null;
+ // /reels/audio/<id>/ is a sound's page, /p/<code>/<more> nothing we know: a
+ // post's path ends at its shortcode (or one "embed" / "c/<comment>" below it
+ // is still that post, but is not offered here).
+ if (NOT_SHORTCODES.has(shortcode.toLowerCase()) || seg.length > k + 2) return null;
+ const id = instagramPkFromShortcode(shortcode);
+ if (!id) return null;
+ const handle = k === 1 && HANDLE_RE.test(seg[0]!) && !RESERVED.has(seg[0]!.toLowerCase()) ? seg[0]! : undefined;
+ if (k === 1 && !handle) return null;
+ const kind = seg[k] === "p" ? "post" : "reel";
+ return { id, shortcode, kind, ...(handle ? { handle } : {}), url: instagramPostUrl(kind, shortcode) };
+}
diff --git a/common/lib/instagram/platform.test.ts b/common/lib/instagram/platform.test.ts
@@ -0,0 +1,96 @@
+// The places a posts platform is told apart, asked about Instagram: none of
+// them may answer with X's.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { isPostPlatform, parsePost, postPermalink, postPlatformLabel, POST_PLATFORM_VALUES } from "../posts";
+import { defaultWebpageUrl, detectPlatform, isSocialPlatform, platformQueueKey, queueKeyForUrl, PLATFORM_VALUES, SOCIAL_PLATFORM_VALUES } from "../platform";
+import { jobGapSecondsFor } from "../jobGap";
+import { handleFromAccountUrl, parsePostUrl } from "../../social/fetchers";
+import { instagramPkFromShortcode } from "./ids";
+
+const CODE = "CabcDEF1234";
+const PK = instagramPkFromShortcode(CODE)!;
+
+test("instagram is a posts platform, a social platform and a detected host", () => {
+ assert.ok(isPostPlatform("instagram"));
+ assert.ok(POST_PLATFORM_VALUES.includes("instagram"));
+ assert.ok(PLATFORM_VALUES.includes("instagram"));
+ assert.ok(SOCIAL_PLATFORM_VALUES.includes("instagram"));
+ assert.ok(isSocialPlatform("instagram"));
+ assert.equal(postPlatformLabel("instagram"), "Instagram");
+ assert.equal(detectPlatform("https://www.instagram.com/example.account/"), "instagram");
+ assert.equal(detectPlatform("https://instagram.com/p/abc/"), "instagram");
+ assert.equal(detectPlatform("https://notinstagram.com/x/"), null);
+ assert.equal(queueKeyForUrl("https://www.instagram.com/example.account/"), "platform:instagram");
+ assert.equal(platformQueueKey("instagram"), "platform:instagram");
+});
+
+test("instagram jobs are spaced ten minutes apart; X's five are unchanged", () => {
+ assert.deepEqual(jobGapSecondsFor(undefined, "instagram"), { seconds: 600, key: "instagram" });
+ assert.deepEqual(jobGapSecondsFor(undefined, "twitter"), { seconds: 300, key: "twitter" });
+ assert.deepEqual(jobGapSecondsFor({ jobGapSeconds: { instagram: 900 } }, "instagram"), { seconds: 900, key: "instagram" });
+});
+
+test("an instagram permalink is never an x.com one", () => {
+ assert.equal(postPermalink("instagram", "example.account", PK), `https://www.instagram.com/p/${CODE}/`);
+ assert.equal(postPermalink("instagram", "example.account", PK, "reel"), `https://www.instagram.com/reel/${CODE}/`);
+ assert.equal(postPermalink("instagram", "example.account", "not-a-pk"), "https://www.instagram.com/example.account/");
+ assert.equal(postPermalink("instagram", "", "not-a-pk"), "");
+ assert.equal(defaultWebpageUrl("instagram", PK), "");
+ // X's is what it was.
+ assert.equal(postPermalink("twitter", "someone", "123"), "https://x.com/someone/status/123");
+ assert.equal(postPermalink("twitter", "", "123"), "https://x.com/i/status/123");
+});
+
+test("a stored instagram post reads back with its facts, and a url rebuilt from its pk", () => {
+ const post = parsePost({
+ id: PK,
+ channelSlug: "example-ig",
+ author: "example.account",
+ createdAt: "2026-01-02T03:04:05.000Z",
+ text: "hello",
+ platform: "instagram",
+ mediaCount: 3,
+ instagram: {
+ kind: "reel",
+ shortcode: CODE,
+ pinned: true,
+ coauthors: [{ handle: "second.account", name: "Second", id: "42" }, { nope: 1 }],
+ junk: "dropped",
+ },
+ });
+ assert.ok(post);
+ assert.equal(post!.url, `https://www.instagram.com/reel/${CODE}/`);
+ assert.deepEqual(post!.instagram, {
+ kind: "reel",
+ shortcode: CODE,
+ pinned: true,
+ coauthors: [{ handle: "second.account", name: "Second", id: "42" }],
+ });
+ // A malformed block is dropped, never the post.
+ const bare = parsePost({ id: PK, channelSlug: "c", createdAt: "2026-01-02T03:04:05.000Z", text: "", platform: "instagram", instagram: { kind: "tweet" } });
+ assert.ok(bare && bare.instagram === undefined);
+ assert.equal(bare!.url, `https://www.instagram.com/p/${CODE}/`);
+});
+
+test("an instagram account URL gives its handle; a post URL gives none", () => {
+ assert.equal(handleFromAccountUrl("https://www.instagram.com/example.account/"), "example.account");
+ assert.equal(handleFromAccountUrl(`https://www.instagram.com/p/${CODE}/`), null);
+ assert.equal(handleFromAccountUrl("https://www.instagram.com/stories/example.account/"), null);
+ assert.equal(handleFromAccountUrl("https://www.instagram.com/explore/tags/x/"), null);
+ // X's reserved paths are what they were.
+ assert.equal(handleFromAccountUrl("https://x.com/home"), null);
+ assert.equal(handleFromAccountUrl("https://x.com/someone"), "someone");
+});
+
+test("a post URL names its platform: instagram's is not X's", () => {
+ assert.deepEqual(parsePostUrl(`https://www.instagram.com/example.account/reel/${CODE}/?x=1`), {
+ platform: "instagram",
+ id: PK,
+ shortcode: CODE,
+ handle: "example.account",
+ url: `https://www.instagram.com/reel/${CODE}/`,
+ });
+ assert.equal(parsePostUrl("https://www.instagram.com/example.account/"), null);
+ assert.equal(parsePostUrl("https://x.com/someone/status/123")?.platform, "twitter");
+});
diff --git a/common/lib/instagram/visibility.test.ts b/common/lib/instagram/visibility.test.ts
@@ -0,0 +1,103 @@
+// Instagram posts are PRIVATE unless social.instagram.visibility says public —
+// the same rule as X's, with the other default. X's rule is pinned unchanged.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ instagramPostsVisibility,
+ isInstagramPostsChannel,
+ isXPostsChannel,
+ postsVisibleTo,
+ publishedMemberSlugs,
+} from "../postsVisibility";
+import { sanitizeSocial } from "../../social/xCookieSource";
+import { isSourcelessPostsChannel } from "../sourcelessPosts";
+import { anyPostsPlatformPrivate, withheldPostsPlatform } from "../postsVisibility";
+import { isInstagramHostUrl, isInstagramTargetUrl } from "../waybackPages/urls";
+
+const IG = { sourceKind: "social" as const, platform: "instagram" as const };
+const X = { sourceKind: "social" as const, platform: "twitter" as const };
+const BLUESKY = { sourceKind: "social" as const, platform: "bluesky" as const };
+const publicSite = { audience: undefined };
+const privateSite = { audience: "private" as const };
+const IG_PUBLIC = { social: { instagram: { visibility: "public" } } };
+
+test("an instagram channel is a social channel on platform instagram, and is not an X channel", () => {
+ assert.equal(isInstagramPostsChannel(IG), true);
+ assert.equal(isInstagramPostsChannel(X), false);
+ assert.equal(isInstagramPostsChannel({ platform: "instagram" }), false);
+ assert.equal(isInstagramPostsChannel(null), false);
+ assert.equal(isXPostsChannel(IG), false);
+ // A source-less published channel is X's only: an Instagram channel with no URL is not one.
+ assert.equal(isSourcelessPostsChannel(IG as never), false);
+});
+
+test("social.instagram.visibility: absent and unknown read as private", () => {
+ assert.equal(instagramPostsVisibility({}), "private");
+ assert.equal(instagramPostsVisibility({ social: {} }), "private");
+ assert.equal(instagramPostsVisibility({ social: { instagram: { visibility: "hidden" } } }), "private");
+ assert.equal(instagramPostsVisibility({ social: { instagram: { visibility: "private" } } }), "private");
+ assert.equal(instagramPostsVisibility(IG_PUBLIC), "public");
+});
+
+test("by default a public site leaves an instagram channel out and a private site carries it", () => {
+ assert.equal(postsVisibleTo(publicSite, IG, {}), false);
+ assert.equal(postsVisibleTo(privateSite, IG, {}), true);
+ assert.equal(postsVisibleTo(publicSite, IG, IG_PUBLIC), true);
+ // X's setting says nothing about Instagram, and Instagram's nothing about X.
+ assert.equal(postsVisibleTo(publicSite, IG, { social: { x: { visibility: "public" } } }), false);
+ assert.equal(postsVisibleTo(publicSite, X, {}), true);
+ assert.equal(postsVisibleTo(publicSite, X, IG_PUBLIC), true);
+ assert.equal(postsVisibleTo(publicSite, X, { social: { x: { visibility: "private" } } }), false);
+ assert.equal(postsVisibleTo(privateSite, X, { social: { x: { visibility: "private" } } }), true);
+ assert.equal(postsVisibleTo(publicSite, BLUESKY, {}), true);
+});
+
+test("a site's published members leave its instagram channels out unless it is private", () => {
+ const configs: Record<string, typeof IG | typeof X | typeof BLUESKY> = { ig: IG, x: X, sky: BLUESKY };
+ const site = { audience: undefined, channels: [{ slug: "ig" }, { slug: "x" }, { slug: "sky" }] };
+ assert.deepEqual(publishedMemberSlugs(site as never, (s) => configs[s], {}), ["x", "sky"]);
+ assert.deepEqual(publishedMemberSlugs(site as never, (s) => configs[s], IG_PUBLIC), ["ig", "x", "sky"]);
+ assert.deepEqual(publishedMemberSlugs({ ...site, audience: "private" } as never, (s) => configs[s], {}), ["ig", "x", "sky"]);
+});
+
+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" },
+ });
+ 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" },
+ instagram: { visibility: "private" },
+ });
+});
+
+// A Wayback pages channel scoped to instagram.com is an Instagram posts
+// channel, as one scoped to x.com is an X one (review 1, S12).
+const PAGES = (url: string) => ({ sourceKind: "social" as const, platform: "webpage" as const, wayback: { targets: [{ url }] } });
+
+test("a Wayback pages channel whose target is on instagram.com follows Instagram's setting", () => {
+ assert.equal(isInstagramTargetUrl("instagram.com/example.account"), true);
+ assert.equal(isInstagramTargetUrl("https://www.instagram.com/example.account/"), true);
+ assert.equal(isInstagramTargetUrl("example.com/instagram.com"), false);
+ assert.equal(isInstagramHostUrl("https://notinstagram.com/x"), false);
+ const igPages = PAGES("instagram.com/example.account") as never;
+ const otherPages = PAGES("example.com/blog") as never;
+ assert.equal(isInstagramPostsChannel(igPages), true);
+ assert.equal(isInstagramPostsChannel(otherPages), false);
+ assert.equal(isXPostsChannel(igPages), false);
+ assert.equal(postsVisibleTo(publicSite, igPages, {}), false);
+ assert.equal(postsVisibleTo(publicSite, igPages, IG_PUBLIC), true);
+ assert.equal(postsVisibleTo(publicSite, otherPages, {}), true);
+ // Which setting withholds a channel now.
+ assert.equal(withheldPostsPlatform(IG, {}), "instagram");
+ assert.equal(withheldPostsPlatform(IG, IG_PUBLIC), null);
+ assert.equal(withheldPostsPlatform(X, {}), null);
+ assert.equal(withheldPostsPlatform(X, { social: { x: { visibility: "private" } } }), "x");
+ assert.equal(withheldPostsPlatform(BLUESKY, { social: { x: { visibility: "private" } } }), null);
+ assert.equal(anyPostsPlatformPrivate({}), true, "Instagram is private by default");
+ assert.equal(anyPostsPlatformPrivate(IG_PUBLIC), false);
+});
diff --git a/common/lib/instagram/ytdlp.test.ts b/common/lib/instagram/ytdlp.test.ts
@@ -0,0 +1,71 @@
+// yt-dlp is never started on an instagram.com URL (review 1, S11): the pass
+// every yt-dlp argv takes before a spawn throws, so no process starts.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFile, readdir } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { jitterYtdlpSleeps } from "../jitter";
+import { jitterSleepArgs } from "../jitter.mjs";
+import { scanBatchIds } from "../../ytdlp/metadataScan";
+import { INSTAGRAM_YTDLP_REFUSAL, instagramUrlInArgs, refuseInstagramYtdlp } from "./ytdlp";
+
+test("an argv naming an instagram.com URL is refused, wherever the URL sits; any other is passed on", () => {
+ const reel = "https://www.instagram.com/reel/CabcDEF1234/";
+ assert.equal(instagramUrlInArgs(["--skip-download", "--", reel]), reel);
+ assert.equal(instagramUrlInArgs(["-J", "https://instagram.com/example.account/"]), "https://instagram.com/example.account/");
+ assert.equal(instagramUrlInArgs(["--referer", "x", "https://www.youtube.com/watch?v=aaaaaaaaaaa"]), null);
+ // A word that merely mentions it is not a URL on it.
+ assert.equal(instagramUrlInArgs(["--match-filter", "title~=instagram.com", "https://example.com/instagram.com"]), null);
+ assert.throws(() => refuseInstagramYtdlp(["--", reel]), new Error(INSTAGRAM_YTDLP_REFUSAL));
+ assert.throws(() => jitterYtdlpSleeps(["--sleep-requests", "2", "--", reel]), new Error(INSTAGRAM_YTDLP_REFUSAL));
+ assert.deepEqual(jitterYtdlpSleeps(["-J", "--", "https://www.youtube.com/watch?v=aaaaaaaaaaa"]), ["-J", "--", "https://www.youtube.com/watch?v=aaaaaaaaaaa"]);
+ assert.match(INSTAGRAM_YTDLP_REFUSAL, /Instagram is read as a posts channel; a single reel import comes with a later slice/);
+});
+
+test("every module of common/ that spawns yt-dlp passes its argv through that refusal", async () => {
+ const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
+ const offenders: string[] = [];
+ for (const dir of ["controller", "ytdlp", "jobs", "lib", "social", "publish", "bin"]) {
+ for (const name of await readdir(path.join(root, dir))) {
+ if (!name.endsWith(".ts") || name.endsWith(".test.ts") || name.endsWith(".fixture.ts")) continue;
+ // The doctor asks yt-dlp for its --version: no URL is ever in that argv.
+ if (dir === "bin" && name === "doctor.ts") continue;
+ const src = await readFile(path.join(root, dir, name), "utf8");
+ // A module that spawns the yt-dlp binary itself…
+ if (!/(execa|spawn|runRecorder)\(\s*(?:[\w.]*\.)?ytdlpBin\b|bin:\s*paths\.ytdlpBin/.test(src)) continue;
+ // …passes the argv through one of the two.
+ if (!/jitterYtdlpSleeps\(|refuseInstagramYtdlp\(/.test(src)) offenders.push(`${dir}/${name}`);
+ }
+ }
+ assert.deepEqual(offenders, []);
+});
+
+test("the refusal is in the shared plain-JS pass, so umtool's scripts are held to it too", async () => {
+ const reel = "https://www.instagram.com/reel/CabcDEF1234/";
+ assert.throws(() => jitterSleepArgs(["--simulate", "--", reel]), new Error(INSTAGRAM_YTDLP_REFUSAL));
+ assert.throws(() => jitterSleepArgs(["--simulate", "--", reel], 0), new Error(INSTAGRAM_YTDLP_REFUSAL), "with jitter off too");
+ assert.deepEqual(jitterSleepArgs(["--simulate", "--", "https://www.youtube.com/watch?v=aaaaaaaaaaa"], 0), ["--simulate", "--", "https://www.youtube.com/watch?v=aaaaaaaaaaa"]);
+ // The two umtool scripts that start yt-dlp hand it only an argv that went through that pass.
+ const umtool = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "umtool", "report-to-video");
+ for (const [file, bin] of [["check-availability.mjs", "ytdlp"], ["build-video.mjs", "YTDLP"]] as const) {
+ const src = await readFile(path.join(umtool, file), "utf8");
+ const calls = [...src.matchAll(new RegExp(`execFileP\\(${bin},\\s*([^)]{0,40})`, "g"))].map((m) => m[1]!);
+ assert.ok(calls.length > 0, `${file} starts yt-dlp`);
+ for (const c of calls) assert.ok(c.startsWith("jitterSleepArgs("), `${file}: ${c}`);
+ }
+});
+
+test("a metadata scan's batch file never holds an instagram.com URL: left out, in order, and said", () => {
+ const urls: Record<string, string> = {
+ a: "https://www.youtube.com/watch?v=aaaaaaaaaaa",
+ b: "https://www.instagram.com/reel/CabcDEF1234/",
+ c: "https://www.youtube.com/watch?v=ccccccccccc",
+ d: "https://instagram.com/p/CabcDEF1235/",
+ };
+ const r = scanBatchIds(["a", "b", "c", "d"], (id) => urls[id]!);
+ assert.deepEqual(r.ids, ["a", "c"]);
+ assert.equal(r.leftOut, `2 instagram.com URL(s) left out of this scan: ${INSTAGRAM_YTDLP_REFUSAL}\n`);
+ assert.deepEqual(scanBatchIds(["a", "c"], (id) => urls[id]!), { ids: ["a", "c"], leftOut: null });
+ assert.deepEqual(scanBatchIds(["b"], (id) => urls[id]!).ids, []);
+});
diff --git a/common/lib/instagram/ytdlp.ts b/common/lib/instagram/ytdlp.ts
@@ -0,0 +1,3 @@
+// yt-dlp is never started on an instagram.com URL: the rule and its sentence
+// are in ./ytdlpRefusal.mjs (plain JS, so umtool's .mjs scripts share it).
+export { INSTAGRAM_YTDLP_REFUSAL, instagramUrlInArgs, isInstagramComUrl, refuseInstagramYtdlp } from "./ytdlpRefusal.mjs";
diff --git a/common/lib/instagram/ytdlpRefusal.mjs b/common/lib/instagram/ytdlpRefusal.mjs
@@ -0,0 +1,45 @@
+// yt-dlp IS NEVER STARTED ON AN instagram.com URL (lane instagram, review 1
+// S11, review 2 N8). Instagram is read as a posts channel, by its own
+// fetcher, on its own queue, behind its own guard; a yt-dlp run on a reel or
+// an account would be a second, unguarded path to the same site. A single
+// reel's import comes with a later slice.
+//
+// Plain JS (with JSDoc types) so the ONE pass every yt-dlp argv takes before a
+// spawn — `jitterSleepArgs` in ../jitter.mjs — can ask it for common's TS and
+// for umtool's .mjs scripts alike. `./ytdlp.ts` re-exports this for TS callers.
+
+export const INSTAGRAM_YTDLP_REFUSAL =
+ "Instagram is read as a posts channel; a single reel import comes with a later slice. " +
+ "No yt-dlp process was started for this instagram.com URL.";
+
+/**
+ * Whether `value` is an http(s) URL on instagram.com.
+ * @param {unknown} value
+ * @returns {boolean}
+ */
+export function isInstagramComUrl(value) {
+ if (typeof value !== "string" || !/^https?:\/\//i.test(value.trim())) return false;
+ try {
+ return new URL(value.trim()).hostname.toLowerCase().replace(/^www\./, "") === "instagram.com";
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The first argument that is an instagram.com URL, or null.
+ * @param {readonly string[]} args
+ * @returns {string | null}
+ */
+export function instagramUrlInArgs(args) {
+ for (const a of args) if (isInstagramComUrl(a)) return a;
+ return null;
+}
+
+/**
+ * Throws the refusal when the argv names an instagram.com URL.
+ * @param {readonly string[]} args
+ */
+export function refuseInstagramYtdlp(args) {
+ if (instagramUrlInArgs(args)) throw new Error(INSTAGRAM_YTDLP_REFUSAL);
+}
diff --git a/common/lib/jitter.mjs b/common/lib/jitter.mjs
@@ -14,6 +14,8 @@
//
// Plain JS so umtool's .mjs scripts and common's TS share one implementation.
+import { refuseInstagramYtdlp } from "./instagram/ytdlpRefusal.mjs";
+
export const DEFAULT_JITTER_SPREAD = 0.25;
export const MAX_JITTER_SPREAD = 1;
@@ -84,12 +86,19 @@ export function secondsArg(seconds) {
* `args` with the value after each `--sleep-requests` / `--sleep-subtitles`
* (and the other fixed yt-dlp waits) stretched by `jitterUp`. Every occurrence
* is stretched because yt-dlp takes the last one. Returns a copy.
+ *
+ * EVERY yt-dlp ARGV PASSES HERE ON ITS WAY TO A SPAWN — common's (through
+ * jitter.ts jitterYtdlpSleeps) and umtool's .mjs scripts' — which is why the
+ * one refusal that holds for all of them is asked here: an instagram.com URL
+ * is never handed to yt-dlp (./instagram/ytdlpRefusal.mjs). It THROWS, and no
+ * process starts.
* @param {readonly string[]} args
* @param {number} [spread]
* @param {() => number} [rand]
* @returns {string[]}
*/
export function jitterSleepArgs(args, spread = DEFAULT_JITTER_SPREAD, rand = Math.random) {
+ refuseInstagramYtdlp(args);
const out = [...args];
if (clampSpread(spread) === 0) return out;
for (let i = 0; i < out.length - 1; i++) {
diff --git a/common/lib/jitter.ts b/common/lib/jitter.ts
@@ -45,6 +45,11 @@ export function jitterMsStable(ms: number, seed: string): number {
// yt-dlp args with their fixed waits (`--sleep-requests`, `--sleep-subtitles`)
// stretched — once per spawn, since yt-dlp itself waits exactly what it is told.
+//
+// EVERY yt-dlp ARGV PASSES HERE ON ITS WAY TO A SPAWN. The one refusal that
+// holds for all of them is asked inside jitterSleepArgs (jitter.mjs, shared
+// with umtool's scripts): an instagram.com URL is never handed to yt-dlp
+// (lib/instagram/ytdlpRefusal.mjs) — it throws, and no process starts.
export function jitterYtdlpSleeps(
args: readonly string[],
rand: () => number = Math.random,
diff --git a/common/lib/jobContext.ts b/common/lib/jobContext.ts
@@ -18,6 +18,9 @@ export type JobContext = {
jobId: string;
kind: string;
channelSlug?: string;
+ // The queue the job runs on (its key in the registry). Code that must run
+ // on ONE queue — an Instagram fetch, on platform:instagram — asks it here.
+ queueKey?: string;
// The job's log (the same sink its `fn` writes to).
onLog: (line: string) => void;
// Services whose cookie alert this job met while it ran (serviceCookies).
diff --git a/common/lib/jobGap.ts b/common/lib/jobGap.ts
@@ -4,12 +4,14 @@
// /settings form shows the gaps in force.
// The built-in gaps: every platform queue waits `default` seconds after the
-// previous network job on it ended; X five minutes, a forum and Bluesky one.
+// previous network job on it ended; X five minutes, a forum and Bluesky one,
+// Instagram ten (it checkpoints the logged-in account that reads too often).
export const JOB_GAP_DEFAULT_SECONDS: Readonly<Record<string, number>> = Object.freeze({
default: 20,
twitter: 300,
xenforo: 60,
bluesky: 60,
+ instagram: 600,
});
export const JOB_GAP_MAX_SECONDS = 24 * 60 * 60;
diff --git a/common/lib/platform.ts b/common/lib/platform.ts
@@ -21,7 +21,9 @@ export type Platform =
// lib/waybackPages/): a posts channel whose records are page records.
// Never detected from a URL — a web.archive.org URL is a capture of
// something else, which import-video or import-page decides.
- | "webpage";
+ | "webpage"
+ // An Instagram account's posts and reels (lane instagram).
+ | "instagram";
export const PLATFORM_VALUES: ReadonlyArray<Platform> = [
"local",
@@ -36,6 +38,7 @@ export const PLATFORM_VALUES: ReadonlyArray<Platform> = [
"bluesky",
"xenforo",
"webpage",
+ "instagram",
];
// The subset that carries social posts rather than videos. A channel on one of
@@ -46,6 +49,7 @@ export const SOCIAL_PLATFORM_VALUES: ReadonlyArray<Platform> = [
"bluesky",
"xenforo",
"webpage",
+ "instagram",
];
export function isSocialPlatform(platform: Platform | null | undefined): boolean {
@@ -53,7 +57,8 @@ export function isSocialPlatform(platform: Platform | null | undefined): boolean
platform === "twitter" ||
platform === "bluesky" ||
platform === "xenforo" ||
- platform === "webpage"
+ platform === "webpage" ||
+ platform === "instagram"
);
}
@@ -95,6 +100,9 @@ export function defaultWebpageUrl(platform: Platform, id: string): string {
// A page record's URL is its capture's original, which every record
// carries; an id (a timestamp and a hash) names none.
if (platform === "webpage") return /^https?:\/\//.test(id) ? id : "";
+ // An Instagram post's URL carries its shortcode; every archived post has its
+ // own `url` (postPermalink builds one from the id).
+ if (platform === "instagram") return /^https?:\/\//.test(id) ? id : "";
return `https://www.youtube.com/watch?v=${id}`;
}
diff --git a/common/lib/posts.ts b/common/lib/posts.ts
@@ -11,6 +11,14 @@
import { pageFileName } from "./manifest";
import type { PagePostInfo } from "./waybackPages/types";
import { parsePagePostInfo } from "./waybackPages/parse";
+import {
+ INSTAGRAM_POST_KINDS,
+ instagramAccountUrl,
+ instagramPostUrl,
+ instagramShortcodeFromPk,
+ isInstagramShortcode,
+ type InstagramPostKind,
+} from "./instagram/ids";
// "xenforo" is a forum THREAD read as a posts source: the channel is one
// thread, each forum post a Post. It is named for the forum software, not a
@@ -18,17 +26,20 @@ import { parsePagePostInfo } from "./waybackPages/parse";
// "webpage" (release 37) is a Wayback Machine capture of a page that is not a
// video: one captured state of one page, or one item a capture holds
// (`Post.page`; lib/waybackPages/).
-export type PostPlatform = "twitter" | "bluesky" | "xenforo" | "webpage";
+// "instagram" (lane instagram) is an Instagram account's posts and reels
+// (`Post.instagram`; lib/instagram/).
+export type PostPlatform = "twitter" | "bluesky" | "xenforo" | "webpage" | "instagram";
export const POST_PLATFORM_VALUES: ReadonlyArray<PostPlatform> = [
"twitter",
"bluesky",
"xenforo",
"webpage",
+ "instagram",
];
export function isPostPlatform(v: unknown): v is PostPlatform {
- return v === "twitter" || v === "bluesky" || v === "xenforo" || v === "webpage";
+ return typeof v === "string" && (POST_PLATFORM_VALUES as ReadonlyArray<string>).includes(v);
}
// The platform's name as a reader sees it.
@@ -37,6 +48,7 @@ export function postPlatformLabel(platform: PostPlatform | string | undefined):
if (platform === "bluesky") return "Bluesky";
if (platform === "xenforo") return "Forum";
if (platform === "webpage") return "Web page";
+ if (platform === "instagram") return "Instagram";
return "Post";
}
@@ -82,6 +94,26 @@ export type ForumPostInfo = {
quotes?: { postId?: string; author?: string; authorId?: string }[];
};
+// What an Instagram post carries beyond the common shape (platform
+// "instagram"). The post's `id` is its numeric media pk (lib/instagram/ids.ts
+// says why); the shortcode its URL carries is kept here.
+export type InstagramPostInfo = {
+ // "post" (a picture, or a carousel of several media), "reel" (one video),
+ // and, from slice 2, "story" and "highlight".
+ kind: InstagramPostKind;
+ shortcode?: string;
+ // The post is pinned to the top of the account's grid.
+ pinned?: boolean;
+ // A collaboration: the accounts it is shared with, the owner aside. `author`
+ // is the OWNER, who may not be the channel's account; the channel's account
+ // is then among these.
+ coauthors?: { handle: string; name?: string; id?: string }[];
+ // A story's end (ISO-8601) and when the archive read it; a highlight's title.
+ expiresAt?: string;
+ capturedAt?: string;
+ highlightTitle?: string;
+};
+
// A pointer to another post, which may or may not itself be archived. Used for
// reply/quote/repost edges so thread structure survives even when the
// referenced post is outside the archived account.
@@ -136,6 +168,8 @@ export type Post = {
// The capture a page record came from (platform "webpage"): its original
// URL, capture time, replay and raw URLs, kind and extractor.
page?: PagePostInfo;
+ // Instagram-specific facts (platform "instagram").
+ instagram?: InstagramPostInfo;
engagement?: PostEngagement;
// Merged in at index time from the channel's availability sidecar (the same
// shape videos use: the stored record is the source of truth, the flag on
@@ -299,6 +333,16 @@ export function postPermalink(
// A page record's permalink is the page it is a capture of (`base`, its
// `page.originalUrl`); an id alone names none.
if (platform === "webpage") return base ?? "";
+ // An Instagram post's permalink carries its shortcode, which is its id (the
+ // numeric pk) in base 64. `base` "reel" names a reel. An id that is not a pk
+ // (never written by the fetcher) names the account instead of a wrong post.
+ if (platform === "instagram") {
+ const code = instagramShortcodeFromPk(id);
+ if (code) return instagramPostUrl(base === "reel" ? "reel" : "post", code);
+ return author ? instagramAccountUrl(author) : "";
+ }
+ // Only X is left. Anything else has no permalink this function can build.
+ if (platform !== "twitter") return "";
return `https://x.com/${author || "i"}/status/${id}`;
}
@@ -340,7 +384,9 @@ export function parsePost(raw: unknown): Post | null {
? forumBaseOf(r.forum)
: r.platform === "webpage"
? pageOriginalOf(r.page)
- : undefined,
+ : r.platform === "instagram"
+ ? instagramKindOf(r.instagram)
+ : undefined,
),
platform: r.platform,
isReply: r.isReply === true,
@@ -376,9 +422,45 @@ export function parsePost(raw: unknown): Post | null {
// A malformed `page` is dropped, never the post.
const page = parsePagePostInfo(r.page);
if (page) post.page = page;
+ const instagram = parseInstagramInfo(r.instagram);
+ if (instagram) post.instagram = instagram;
return post;
}
+function instagramKindOf(raw: unknown): string | undefined {
+ const kind = (raw as { kind?: unknown } | null)?.kind;
+ return kind === "reel" ? "reel" : undefined;
+}
+
+// A malformed `instagram` is dropped, never the post.
+function parseInstagramInfo(raw: unknown): InstagramPostInfo | null {
+ if (!raw || typeof raw !== "object") return null;
+ const r = raw as Record<string, unknown>;
+ if (!(INSTAGRAM_POST_KINDS as ReadonlyArray<unknown>).includes(r.kind)) return null;
+ const out: InstagramPostInfo = { kind: r.kind as InstagramPostKind };
+ if (isInstagramShortcode(r.shortcode)) out.shortcode = r.shortcode;
+ if (r.pinned === true) out.pinned = true;
+ if (Array.isArray(r.coauthors)) {
+ const list: NonNullable<InstagramPostInfo["coauthors"]> = [];
+ for (const item of r.coauthors) {
+ if (!item || typeof item !== "object") continue;
+ const c = item as Record<string, unknown>;
+ if (typeof c.handle !== "string" || !c.handle) continue;
+ list.push({
+ handle: c.handle,
+ ...(typeof c.name === "string" && c.name ? { name: c.name } : {}),
+ ...(typeof c.id === "string" && c.id ? { id: c.id } : {}),
+ });
+ }
+ if (list.length > 0) out.coauthors = list;
+ }
+ for (const key of ["expiresAt", "capturedAt", "highlightTitle"] as const) {
+ const v = r[key];
+ if (typeof v === "string" && v) out[key] = v;
+ }
+ return out;
+}
+
function pageOriginalOf(raw: unknown): string | undefined {
const url = (raw as { originalUrl?: unknown } | null)?.originalUrl;
return typeof url === "string" && url ? url : undefined;
diff --git a/common/lib/postsVisibility.ts b/common/lib/postsVisibility.ts
@@ -26,13 +26,18 @@
// hasPostsCorpus), so a public site whose only posts were X posts ships an
// empty posts manifest and no Posts toggle.
//
+// INSTAGRAM (lane instagram) has the same rule with the other default: an
+// Instagram channel (a social channel on platform "instagram") is built only
+// into a PRIVATE site unless `social.instagram.visibility` is "public". Absent
+// is PRIVATE.
+//
// Pure: no fs, no settings read. The callers pass the settings and the configs.
import { isSocialChannel, type ChannelConfig } from "./channelConfig";
import { isPrivateSite, type Site } from "./siteSchema";
-import type { XPostsVisibility } from "../social/xCookieSource";
+import type { InstagramPostsVisibility, XPostsVisibility } from "../social/xCookieSource";
import { isWaybackPagesChannel } from "./waybackPages/config";
-import { isXTargetUrl } from "./waybackPages/urls";
+import { isInstagramTargetUrl, isXTargetUrl } from "./waybackPages/urls";
import { isXTrendingChannel } from "./xTrending/config";
// What the rule reads of a config: its kind and platform, and for a Wayback
@@ -66,17 +71,68 @@ export function xPostsVisibility(settings: {
return settings.social?.x?.visibility === "private" ? "private" : "public";
}
+// An Instagram channel: the posts of a social channel whose platform is
+// Instagram — and, as for X, a Wayback pages channel whose scope is on
+// instagram.com (a target there, or such a URL as its own): Instagram's
+// captures are Instagram posts, private by the same setting. import-page keeps
+// them out of every other Wayback pages channel while Instagram is private
+// (controller/importPage.ts, xCaptureRefusal).
+export function isInstagramPostsChannel(config: VisibilityConfig | null | undefined): boolean {
+ if (!isSocialChannel(config)) return false;
+ if (config?.platform === "instagram") return true;
+ if (!isWaybackPagesChannel(config)) return false;
+ if (config?.wayback?.targets.some((t) => isInstagramTargetUrl(t.url))) return true;
+ const url = config?.url ?? "";
+ if (!url) return false;
+ const inner = /^https?:\/\/(?:web|wayback)\.archive\.org\/web\/[^/]*\/(.+)$/i.exec(url)?.[1];
+ return isInstagramTargetUrl(inner ?? url);
+}
+
+// WHICH PRIVATE SETTING WITHHOLDS A CHANNEL'S POSTS FROM PUBLIC SITES NOW, or
+// null: "x" (an X channel while social.x.visibility is private), "instagram"
+// (an Instagram channel while social.instagram.visibility is not public). The
+// one question the tombstones (publish/tombstones.ts) and the homepage's
+// deploy check (lib/builtHomepage.ts) ask, so a flip to private is withdrawn
+// and caught for either platform.
+export function withheldPostsPlatform(
+ config: VisibilityConfig | null | undefined,
+ settings: VisibilitySettings,
+): "x" | "instagram" | null {
+ if (isXPostsChannel(config)) return xPostsVisibility(settings) === "private" ? "x" : null;
+ if (isInstagramPostsChannel(config)) return instagramPostsVisibility(settings) === "private" ? "instagram" : null;
+ return null;
+}
+
+// Whether any posts platform is private now (nothing to withhold when none is).
+export function anyPostsPlatformPrivate(settings: VisibilitySettings): boolean {
+ return xPostsVisibility(settings) === "private" || instagramPostsVisibility(settings) === "private";
+}
+
+// `social.instagram.visibility`, resolved: absent (or anything unknown) is
+// "private".
+export function instagramPostsVisibility(settings: VisibilitySettings): InstagramPostsVisibility {
+ return settings.social?.instagram?.visibility === "public" ? "public" : "private";
+}
+
+// What the rule reads of the settings.
+export type VisibilitySettings = {
+ social?: { x?: { visibility?: unknown }; instagram?: { visibility?: unknown } };
+};
+
// Whether `site` may carry the posts of the channel `config` describes. A
// channel with no readable config is not an X channel as far as this rule
// knows, and is left to whatever already decides its fate.
export function postsVisibleTo(
site: Pick<Site, "audience">,
config: VisibilityConfig | null | undefined,
- settings: { social?: { x?: { visibility?: unknown } } },
+ settings: VisibilitySettings,
): boolean {
// An X trending library (lane x-trending) is private: NO site carries it,
// a private one included, whatever the X visibility setting says.
if (isXTrendingChannel(config)) return false;
+ if (isInstagramPostsChannel(config)) {
+ return instagramPostsVisibility(settings) === "public" || isPrivateSite(site);
+ }
if (!isXPostsChannel(config)) return true;
if (xPostsVisibility(settings) === "public") return true;
return isPrivateSite(site);
@@ -90,7 +146,7 @@ export function publishedMemberSlugs(
configOf: (
slug: string,
) => VisibilityConfig | null | undefined,
- settings: { social?: { x?: { visibility?: unknown } } },
+ settings: VisibilitySettings,
): string[] {
return site.channels
.map((c) => c.slug)
diff --git a/common/lib/report/convert-server.ts b/common/lib/report/convert-server.ts
@@ -128,7 +128,9 @@ export function diskPostOf(channelsDir: string): PostOf {
? "forum"
: post.platform === "webpage"
? "webpage"
- : "x",
+ : post.platform === "instagram"
+ ? "instagram"
+ : "x",
url: post.url,
createdAt: post.createdAt,
author: post.author,
diff --git a/common/lib/report/convertManifest.ts b/common/lib/report/convertManifest.ts
@@ -365,7 +365,8 @@ export type PostRecord = {
// "forum": a forum-thread post (platform "xenforo"), and "webpage" a page
// record (a Wayback capture, release 37), which a video manifest does not
// carry yet — each is left out with a warning, never relabelled.
- platform: "x" | "bluesky" | "forum" | "webpage";
+ // "instagram": an Instagram post, left out the same way.
+ platform: "x" | "bluesky" | "forum" | "webpage" | "instagram";
url: string;
createdAt?: string;
author?: string;
@@ -510,6 +511,10 @@ export async function reportToManifest(raw: unknown, opts: ManifestOptions = {})
warnings.push(`${cid}: post ${c.channel}/${c.id} is a web page capture, which a video manifest does not carry — left out of posts`);
return;
}
+ if (rec?.platform === "instagram") {
+ warnings.push(`${cid}: post ${c.channel}/${c.id} is an Instagram post, which a video manifest does not carry yet — left out of posts`);
+ return;
+ }
const platform = rec?.platform ?? (/^\d+$/.test(c.id) ? "x" : null);
const url = rec?.url ?? (platform === "x" ? `https://x.com/i/status/${c.id}` : null);
const date = c.date ?? rec?.createdAt;
diff --git a/common/lib/serviceCookies-server.ts b/common/lib/serviceCookies-server.ts
@@ -19,6 +19,7 @@ import { getSettings } from "./settings";
import { detectPlatform } from "./platform";
import {
ARCHIVE_TODAY_SERVICE,
+ INSTAGRAM_SERVICE,
X_SERVICE,
applyServiceCookieClean,
applyServiceCookieSignal,
@@ -360,11 +361,29 @@ export async function noteXServiceOutcome(
paths: Pick<Paths, "transcriptsDir">,
outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure"; url?: string; channel?: string },
): Promise<string | null> {
+ return noteBlockingServiceOutcome(paths, X_SERVICE, outcome);
+}
+
+// One gallery-dl run against Instagram, the same way: a redirect to its
+// login, challenge or checkpoint page raises Instagram's alert (one is
+// enough), which refuses every Instagram job until a person's Recheck.
+export async function noteInstagramServiceOutcome(
+ paths: Pick<Paths, "transcriptsDir">,
+ outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure" | "refusal"; url?: string; channel?: string },
+): Promise<string | null> {
+ return noteBlockingServiceOutcome(paths, INSTAGRAM_SERVICE, outcome);
+}
+
+async function noteBlockingServiceOutcome(
+ paths: Pick<Paths, "transcriptsDir">,
+ service: string,
+ outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure" | "refusal"; url?: string; channel?: string },
+): Promise<string | null> {
try {
if (outcome.challengeLine) {
await noteServiceCookieSignal(
paths,
- { service: X_SERVICE, kind: outcome.kind ?? "challenge", line: outcome.challengeLine.trim().slice(0, 300) },
+ { service, kind: outcome.kind ?? "challenge", line: outcome.challengeLine.trim().slice(0, 300) },
{
...(outcome.url ? { url: outcome.url } : {}),
...(outcome.channel ? { channel: outcome.channel } : {}),
@@ -373,10 +392,10 @@ export async function noteXServiceOutcome(
return null;
}
const now = Date.now();
- if (!(await cleanWouldChange(paths, X_SERVICE, now))) return null;
+ if (!(await cleanWouldChange(paths, service, now))) return null;
return await noteServiceCookieClean(
paths,
- X_SERVICE,
+ service,
outcome.url ? { url: outcome.url, ...(outcome.channel ? { channel: outcome.channel } : {}) } : undefined,
{ now },
);
diff --git a/common/lib/serviceCookies.ts b/common/lib/serviceCookies.ts
@@ -30,7 +30,11 @@ import { RUMBLE_NEEDS_TEXT, rumbleMissingKeys } from "./rumbleDefaults";
// run (an X job refused for it, or X jobs queued) — the one kind that is NOT a
// request's answer, raised from a clock and a file's age, and the one X kind
// that does not itself refuse X jobs (the fresh-jar rule already does).
-export type ServiceCookieKind = "embed-403" | "bot-check" | "challenge" | "check-page" | "auth-failure" | "jar-age";
+// "refusal": Instagram answered a read with a 401 or a 403 (its "please wait a
+// few minutes"). ONE is a rate limit and holds Instagram for an hour; a
+// SECOND with no clean read between raises the alert — an account being
+// refused hour after hour needs a person, not another hourly try.
+export type ServiceCookieKind = "embed-403" | "bot-check" | "challenge" | "check-page" | "auth-failure" | "jar-age" | "refusal";
export const SERVICE_COOKIE_KINDS: readonly ServiceCookieKind[] = [
"embed-403",
@@ -39,6 +43,7 @@ export const SERVICE_COOKIE_KINDS: readonly ServiceCookieKind[] = [
"check-page",
"auth-failure",
"jar-age",
+ "refusal",
];
// The yt-dlp services: their requests go through yt-dlp with the browser
@@ -55,7 +60,14 @@ export const ARCHIVE_TODAY_SERVICE = "archive.today";
// challenge is the one that gets an account locked.
export const X_SERVICE = "x";
-export type ServiceFamily = "ytdlp" | "forum" | "archive" | "x";
+// Instagram (lane instagram): a redirect to its login, challenge or checkpoint
+// page in gallery-dl's output. Like X's, WHILE ITS ALERT IS UP NO INSTAGRAM
+// JOB STARTS (common/jobs/networkGuard.ts) — and unlike every other service
+// nothing clears it but a person: Recheck (or Dismiss) on the dashboard, which
+// sends Instagram no request. The recheck timer never asks it.
+export const INSTAGRAM_SERVICE = "instagram";
+
+export type ServiceFamily = "ytdlp" | "forum" | "archive" | "x" | "instagram";
export function isYtdlpCookieService(s: string): s is YtdlpCookieService {
return (YTDLP_COOKIE_SERVICES as readonly string[]).includes(s);
@@ -65,7 +77,7 @@ export function isYtdlpCookieService(s: string): s is YtdlpCookieService {
// (lowercased, no www.). Anything else is not a service.
export function isServiceKey(s: unknown): s is string {
if (typeof s !== "string" || s.length === 0 || s.length > 100) return false;
- if (isYtdlpCookieService(s) || s === ARCHIVE_TODAY_SERVICE || s === X_SERVICE) return true;
+ if (isYtdlpCookieService(s) || s === ARCHIVE_TODAY_SERVICE || s === X_SERVICE || s === INSTAGRAM_SERVICE) return true;
return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(s);
}
@@ -73,6 +85,7 @@ export function serviceFamily(service: string): ServiceFamily {
if (isYtdlpCookieService(service)) return "ytdlp";
if (service === ARCHIVE_TODAY_SERVICE) return "archive";
if (service === X_SERVICE) return "x";
+ if (service === INSTAGRAM_SERVICE) return "instagram";
return "forum";
}
@@ -93,6 +106,8 @@ export function serviceLabel(service: string): string {
return "archive.today";
case X_SERVICE:
return "X";
+ case INSTAGRAM_SERVICE:
+ return "Instagram";
default:
return /(^|\.)kiwifarms\./.test(service) ? `Kiwi Farms (${service})` : service;
}
@@ -123,6 +138,12 @@ export function serviceFixText(service: string, browser?: string, kind?: Service
"pass X's check by hand — Connect X account on /cookies and clear it in the window (with the " +
"browser login: open x.com in that browser) — then press Refresh cookies there; no X job starts until then"
);
+ case INSTAGRAM_SERVICE:
+ return (
+ "pass Instagram's check by hand, in the browser (or with the cookies file's account) the channel's " +
+ "cookie source names, then press Recheck on the dashboard; no Instagram job starts until then, and " +
+ "Recheck sends Instagram no request"
+ );
default:
return `use “Connect forum session” on the thread's channel page and clear the check in the window`;
}
@@ -284,6 +305,13 @@ export type ServiceCookieState = {
};
export const PENDING_SIGNAL_TTL_MS = 60 * 60_000;
+// A pending refusal outlives the hour's hold it came with, or its second
+// could never be "in a row".
+export const PENDING_REFUSAL_TTL_MS = 24 * 60 * 60_000;
+
+export function pendingSignalTtlMs(kind: ServiceCookieKind): number {
+ return kind === "refusal" ? PENDING_REFUSAL_TTL_MS : PENDING_SIGNAL_TTL_MS;
+}
export const CLEARED_KEEP_MS = 24 * 60 * 60_000;
// An "OK again" with no job to re-run is shown this long after the clearing.
export const OK_AGAIN_SHOW_MS = 15 * 60_000;
@@ -299,7 +327,7 @@ export function emptyServiceCookieState(): ServiceCookieState {
// How many distinct videos (or signals) raise the alert.
export function signalsToRaise(kind: ServiceCookieKind): number {
- return kind === "embed-403" ? 2 : 1;
+ return kind === "embed-403" || kind === "refusal" ? 2 : 1;
}
function str(v: unknown, max = 2000): string | undefined {
@@ -413,7 +441,7 @@ export function isAlertRaised(e: ServiceCookieEntry | undefined): boolean {
}
// A raised alert that REFUSES the service's jobs (jobs/networkGuard.ts — X
-// only): every raised kind but jar-age, whose refusal is the fresh-jar rule's
+// and Instagram): every raised kind but jar-age, whose refusal is the fresh-jar rule's
// own and which clears the moment the jar is fresh.
export function isBlockingAlert(e: ServiceCookieEntry | undefined): boolean {
return isAlertRaised(e) && e!.kind !== "jar-age";
@@ -437,7 +465,7 @@ export function applyServiceCookieSignal(
const at = new Date(now).toISOString();
let entry = state.services[signal.service];
const stalePending =
- entry && !entry.raisedAt && now - Date.parse(entry.lastSeen) > PENDING_SIGNAL_TTL_MS;
+ entry && !entry.raisedAt && now - Date.parse(entry.lastSeen) > pendingSignalTtlMs(entry.kind);
// A raised jar-age alert that meets a real answer from X (a challenge, a
// login wall) is ESCALATED to it — that kind refuses every X job, jar-age
// does not — keeping the jobs it already holds for "Re-run stopped jobs".
@@ -538,7 +566,7 @@ export function pruneServiceCookieState(state: ServiceCookieState, now: number):
for (const [k, e] of Object.entries(state.services)) {
const gone =
(e.clearedAt && now - Date.parse(e.clearedAt) > CLEARED_KEEP_MS) ||
- (!e.raisedAt && now - Date.parse(e.lastSeen) > PENDING_SIGNAL_TTL_MS);
+ (!e.raisedAt && now - Date.parse(e.lastSeen) > pendingSignalTtlMs(e.kind));
if (gone) {
delete state.services[k];
changed = true;
@@ -652,6 +680,8 @@ function kindPhrase(kind: ServiceCookieKind, count: number, videos: number): str
return `${count} login failure${count === 1 ? "" : "s"}`;
case "jar-age":
return "cookie jar past its age limit";
+ case "refusal":
+ return `${count} refusal${count === 1 ? "" : "s"} (401/403) in a row`;
}
}
@@ -673,7 +703,7 @@ export function buildServiceCookieAlerts(
for (const e of Object.values(state.services)) {
const label = serviceLabel(e.service);
if (!e.raisedAt) {
- if (opts.now - Date.parse(e.lastSeen) <= PENDING_SIGNAL_TTL_MS) {
+ if (opts.now - Date.parse(e.lastSeen) <= pendingSignalTtlMs(e.kind)) {
pending.push({ service: e.service, label, kind: e.kind, videos: e.videos, lastSeen: e.lastSeen });
}
continue;
@@ -757,6 +787,7 @@ export function buildServiceCookieAlerts(
canRecheck:
serviceFamily(e.service) === "archive" ||
serviceFamily(e.service) === "x" ||
+ serviceFamily(e.service) === "instagram" ||
!!state.lastGood[e.service] ||
!!e.evidence.url,
stoppedJobs,
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -55,6 +55,7 @@ import {
SOCIAL_SETTINGS_FIELD_DOCS,
X_SOCIAL_SETTINGS_FIELD_DOCS,
XENFORO_SOCIAL_SETTINGS_FIELD_DOCS,
+ INSTAGRAM_SOCIAL_SETTINGS_FIELD_DOCS,
SYNC_SCHEDULER_SETTINGS_FIELD_DOCS,
defaultSiteSettings,
siteSettingsSchema,
@@ -220,6 +221,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
defaults: fromObject(d.social.x),
},
{ path: "social.xenforo", docs: XENFORO_SOCIAL_SETTINGS_FIELD_DOCS },
+ { path: "social.instagram", docs: INSTAGRAM_SOCIAL_SETTINGS_FIELD_DOCS },
],
socialLinks: [{ path: "socialLinks[]", docs: SOCIAL_LINK_FIELD_DOCS }],
remoteArchives: [{ path: "remoteArchives[]", docs: REMOTE_ARCHIVE_FIELD_DOCS }],
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -145,12 +145,13 @@ import { previewBranchProblem } from "./pagesDeploy";
import {
sanitizeSocial,
type SocialSettings,
+ type InstagramSocialSettings,
type XenforoSocialSettings,
type XSocialSettings,
} from "../social/xCookieSource";
export type { Worker } from "./workers";
-export type { SocialSettings, XSocialSettings, XenforoSocialSettings } from "../social/xCookieSource";
+export type { SocialSettings, XSocialSettings, XenforoSocialSettings, InstagramSocialSettings } from "../social/xCookieSource";
import { sanitizeJobGapSeconds } from "./jobGap";
export { JOB_GAP_DEFAULT_SECONDS, JOB_GAP_MAX_SECONDS, jobGapSecondsFor } from "./jobGap";
@@ -160,6 +161,17 @@ 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).",
+};
+
+export const INSTAGRAM_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<InstagramSocialSettings> = {
+ visibility:
+ "Where Instagram posts may appear. `\"private\"` (the default; absent): every Instagram channel's " +
+ "posts (a channel with `sourceKind: \"social\"` and `platform: \"instagram\"`) are left out of " +
+ "every PUBLIC site build, the channel with them, and built only into PRIVATE sites (`site.json` " +
+ "`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.",
};
export const XENFORO_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XenforoSocialSettings> = {
diff --git a/common/lib/waybackPages/urls.ts b/common/lib/waybackPages/urls.ts
@@ -140,6 +140,21 @@ export function isXHostUrl(url: string): boolean {
}
}
+// Whether `url` is on Instagram: a capture of it follows
+// `social.instagram.visibility` exactly as Instagram posts do.
+export function isInstagramHostUrl(url: string): boolean {
+ try {
+ return new URL(url).hostname.toLowerCase().replace(/^www\./, "") === "instagram.com";
+ } catch {
+ return false;
+ }
+}
+
+// Whether a target URL (scheme optional) is on Instagram.
+export function isInstagramTargetUrl(url: string): boolean {
+ return isInstagramHostUrl(/^https?:\/\//i.test(url) ? url : `https://${url.replace(/^\*\./, "")}`);
+}
+
// Whether a target URL (scheme optional) is on X.
export function isXTargetUrl(url: string): boolean {
return isXHostUrl(/^https?:\/\//i.test(url) ? url : `https://${url.replace(/^\*\./, "")}`);
diff --git a/common/package.json b/common/package.json
@@ -41,6 +41,7 @@
"./lib/clips/suggest.mjs": "./lib/clips/suggest.mjs",
"./lib/atomicFile.mjs": "./lib/atomicFile.mjs",
"./lib/xTrending/marker.mjs": "./lib/xTrending/marker.mjs",
+ "./lib/instagram/ytdlpRefusal.mjs": "./lib/instagram/ytdlpRefusal.mjs",
"./lib/cueWiden.mjs": "./lib/cueWiden.mjs",
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
"./lib/platformSeek.mjs": "./lib/platformSeek.mjs",
diff --git a/common/publish/inputSig.ts b/common/publish/inputSig.ts
@@ -160,6 +160,8 @@ export async function siteInputSig(i: SiteSigInputs): Promise<string> {
`settings\t${JSON.stringify({
archiveStorage: settings.archiveStorage ?? null,
xVisibility: settings.social?.x?.visibility ?? null,
+ // Only when set: a corpus that never chose it keeps the signature it had.
+ ...(settings.social?.instagram?.visibility ? { instagramVisibility: settings.social.instagram.visibility } : {}),
buildArchives: settings.buildArchives ?? null,
})}`,
);
@@ -205,6 +207,8 @@ export function indexSettingsSig(settings: Partial<IndexSettingsInputs>): string
buildArchives: settings.buildArchives ?? null,
archiveStorage: settings.archiveStorage ?? null,
xVisibility: settings.social?.x?.visibility ?? null,
+ // Only when set: a corpus that never chose it keeps the signature it had.
+ ...(settings.social?.instagram?.visibility ? { instagramVisibility: settings.social.instagram.visibility } : {}),
maxTranscriptPageBytes: settings.maxTranscriptPageBytes ?? null,
locations: (settings.storage?.locations ?? []).map((l) => [l.id, l.root]),
}),
diff --git a/common/publish/tombstones.test.ts b/common/publish/tombstones.test.ts
@@ -314,3 +314,38 @@ test("hubNameableChannels: the pools of the sites that are not private, never a
["a", "b", "c"],
);
});
+
+// INSTAGRAM (lane instagram): the same withdrawal, with the other default — an
+// Instagram channel a non-private site carries is tombstoned unless
+// social.instagram.visibility is "public". X's list is what it was.
+test("withdrawnXChannels names Instagram channels too while Instagram posts are private; X's output is unchanged by it", async () => {
+ const root = mkdtempSync(path.join(tmpdir(), "tombstones-ig-"));
+ try {
+ const paths = {
+ channelsDir: path.join(root, "channels"),
+ exportSharedPostsDir: path.join(root, "shared", "posts"),
+ } as Paths;
+ const config = (slug: string, platform: string) =>
+ writeJson(path.join(paths.channelsDir, slug, "config.json"), { handling: "transcribe", url: `https://example.test/${slug}`, sourceKind: "social", platform });
+ config("a-x", "twitter");
+ config("ig-public-site", "instagram");
+ config("ig-private-only", "instagram");
+ config("sky", "bluesky");
+ for (const slug of ["a-x", "ig-public-site", "ig-private-only", "sky"]) sharedTree(paths.exportSharedPostsDir, slug, 1);
+ const members = (...slugs: string[]) => slugs.map((slug) => ({ slug, groupId: "default" }));
+ const sites = [
+ { channels: members("a-x", "ig-public-site", "sky") },
+ { audience: "private" as const, channels: members("ig-private-only") },
+ ];
+ const xPrivate = { social: { x: { visibility: "private" } } };
+ const igPublic = { social: { instagram: { visibility: "public" } } };
+ // Instagram private by default: its channel on the public site is withdrawn; the private-only one is never named.
+ assert.deepEqual(await withdrawnXChannels(paths, {}, sites), ["ig-public-site"]);
+ assert.deepEqual(await withdrawnXChannels(paths, igPublic, sites), []);
+ // X's own list, with Instagram public: exactly what X's rule gave before.
+ assert.deepEqual(await withdrawnXChannels(paths, { social: { ...xPrivate.social, ...igPublic.social } }, sites), ["a-x"]);
+ assert.deepEqual(await withdrawnXChannels(paths, xPrivate, sites), ["a-x", "ig-public-site"]);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/common/publish/tombstones.ts b/common/publish/tombstones.ts
@@ -49,7 +49,7 @@ import {
type ChannelPostsManifest,
type PostsManifest,
} from "../lib/posts";
-import { isXPostsChannel, xPostsVisibility } from "../lib/postsVisibility";
+import { anyPostsPlatformPrivate, withheldPostsPlatform } from "../lib/postsVisibility";
import { isPrivateSite, type Site } from "../lib/siteSchema";
import { readChannelConfig } from "../controller/channels";
import { ownDir, writePublicFile } from "../bin/_publicFile";
@@ -180,14 +180,17 @@ export function tombstoneNoStoreForHub(tombstones: readonly PostsTombstone[]): s
* only paths the edge can still hold. PRIVATE DATA IS NEVER NAMED ON THE HUB:
* an X channel carried only by private sites, or by no site, gets no
* tombstone, because its slug in a public bundle would itself publish it.
- * Empty while X posts are public.
+ * Empty while X posts are public. INSTAGRAM THE SAME (lane instagram): an
+ * Instagram channel on a non-private site is tombstoned while Instagram posts
+ * are private — which they are unless `social.instagram.visibility` is
+ * "public" — so a flip from public back to private withdraws what was served.
*/
export async function withdrawnXChannels(
paths: Paths,
- settings: { social?: { x?: { visibility?: unknown } } },
+ settings: { social?: { x?: { visibility?: unknown }; instagram?: { visibility?: unknown } } },
sites: readonly Pick<Site, "audience" | "channels">[],
): Promise<string[]> {
- if (xPostsVisibility(settings) !== "private") return [];
+ if (!anyPostsPlatformPrivate(settings)) return [];
const onPublicSite = hubNameableChannels(sites);
let entries: string[];
try {
@@ -201,7 +204,9 @@ export async function withdrawnXChannels(
const out: string[] = [];
for (const slug of entries) {
if (!onPublicSite.has(slug)) continue;
- if (isXPostsChannel(await readChannelConfig(paths, slug))) out.push(slug);
+ // An X channel while X is private; an Instagram channel while Instagram is
+ // (it is unless set public): the same withdrawal for both.
+ if (withheldPostsPlatform(await readChannelConfig(paths, slug), settings)) out.push(slug);
}
return out;
}
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
@@ -21,6 +21,7 @@ import type { PostCaptureState } from "./postCapture";
import type { XAvatarRunSummary } from "./xAvatarCapture";
import type { XContextRunSummary } from "./xPostContext";
import type { ChromiumLike } from "./playwrightRuntime";
+import { instagramHandleFromUrl, isInstagramUrl, parseInstagramPostUrl } from "../lib/instagram/ids";
export type PostFetchInput = {
// The account's canonical URL as configured on the channel.
@@ -110,6 +111,23 @@ 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;
+ // INSTAGRAM: the media this job may fetch (a sync's budget, or a walk's).
+ mediaBudget?: { maxFiles: number; maxBytes: 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
@@ -507,6 +525,9 @@ export function handleFromAccountUrl(input: string): string | null {
} catch {
return null;
}
+ // instagram.com/<handle>: its own reserved paths (p, reel, stories, …) and
+ // its own handle alphabet (lib/instagram/ids.ts).
+ if (isInstagramUrl(trimmed)) return instagramHandleFromUrl(trimmed);
const segments = url.pathname.split("/").filter(Boolean);
if (segments.length === 0) return null;
// A forum thread: its "<slug>.<id>" key is the channel's handle.
@@ -543,7 +564,10 @@ export function handleFromAccountUrl(input: string): string | null {
// (`bsky.app/profile/<handle|did>/post/<rkey>`, or its `at://` URI).
export type PostUrlRef =
| { platform: "twitter"; id: string; handle?: string; url: string }
- | { platform: "bluesky"; id: string; actor: string; url: string };
+ | { platform: "bluesky"; id: string; actor: string; url: string }
+ // An Instagram post or reel (`instagram.com/p/<shortcode>/`, `/reel/…`): its
+ // id is the numeric pk the shortcode is (lib/instagram/ids.ts).
+ | { platform: "instagram"; id: string; shortcode: string; handle?: string; url: string };
export function parsePostUrl(input: string): PostUrlRef | null {
const raw = input.trim();
@@ -558,6 +582,10 @@ export function parsePostUrl(input: string): PostUrlRef | null {
return null;
}
if (u.protocol !== "https:" && u.protocol !== "http:") return null;
+ const ig = parseInstagramPostUrl(raw);
+ if (ig) {
+ return { platform: "instagram", id: ig.id, shortcode: ig.shortcode, ...(ig.handle ? { handle: ig.handle } : {}), url: ig.url };
+ }
const host = u.hostname.toLowerCase().replace(/^(www|mobile)\./, "");
const seg = u.pathname.split("/").filter(Boolean).map((x) => decodeURIComponent(x));
if (host === "x.com" || host === "twitter.com") {
diff --git a/common/social/importPost.ts b/common/social/importPost.ts
@@ -48,7 +48,7 @@ export const NOT_A_POST_URL =
"not a post URL: give an X status (https://x.com/<handle>/status/<id>) or a Bluesky post " +
"(https://bsky.app/profile/<handle>/post/<id>, or its at:// URI)";
-const PLATFORM_LABEL: Record<string, string> = { twitter: "X", bluesky: "Bluesky", xenforo: "forum" };
+const PLATFORM_LABEL: Record<string, string> = { twitter: "X", bluesky: "Bluesky", xenforo: "forum", instagram: "Instagram" };
export type ImportPostPlan = {
config: ChannelConfig;
@@ -90,7 +90,12 @@ export async function planImportPost(
if (!fetcher.fetchOne) return { ok: false, error: `${slug}'s fetcher (${fetcher.label}) cannot import one post` };
const handle = config.socialHandle ?? handleFromAccountUrl(config.url ?? "") ?? "";
if (!handle) return { ok: false, error: `Could not determine an account handle for ${slug}` };
- const named = ref.platform === "twitter" ? ref.handle : ref.actor.startsWith("did:") ? undefined : ref.actor;
+ const named =
+ ref.platform === "twitter" || ref.platform === "instagram"
+ ? ref.handle
+ : ref.actor.startsWith("did:")
+ ? undefined
+ : ref.actor;
if (named && !sameAccount(named, handle)) {
return { ok: false, error: `the post is @${named}'s; ${slug} archives @${handle}'s posts` };
}
diff --git a/common/social/instagramGalleryDlFetcher.test.ts b/common/social/instagramGalleryDlFetcher.test.ts
@@ -0,0 +1,635 @@
+// 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;
+ // Whether Instagram's alert is up (the second refusal in a row raises it).
+ alert: boolean;
+ log: string[];
+};
+
+function harness(answer: { rows?: unknown[]; stdout?: string; stderr?: string[]; out?: Partial<InstagramRunOutput> }): Harness {
+ const h: Harness = { runs: [], outcomes: [], rateLimits: 0, alert: false, log: [], deps: undefined as never };
+ h.deps = {
+ bin: () => "gallery-dl-not-run",
+ run: async (_bin, args, opts) => {
+ const run = { args, stops: 0 };
+ h.runs.push(run);
+ for (const line of answer.stderr ?? []) if (opts.onStderrLine(line) === "stop") run.stops++;
+ return { stdout: answer.stdout ?? igStdout(answer.rows ?? []), timedOut: false, canceled: false, ...answer.out };
+ },
+ noteOutcome: async (o) => {
+ h.outcomes.push(o);
+ return null;
+ },
+ alertRaised: async () => h.alert,
+ noteRateLimit: async () => {
+ h.rateLimits++;
+ return NOW + 60 * 60_000;
+ },
+ now: () => NOW,
+ };
+ return h;
+}
+
+function input(h: Harness, over: Partial<PostFetchInput> = {}): 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 is sized to its media budget, a refusal is never retried", () => {
+ const SYNC = { maxFiles: 40, maxBytes: 200 * 1024 * 1024 };
+ const WALK = { maxFiles: 120, maxBytes: 600 * 1024 * 1024 };
+ assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z" }), { mode: "sync", maxPosts: 30, maxRequests: 4, stop: "known", media: SYNC });
+ assert.equal(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", limit: 5 }).maxPosts, 5);
+ assert.equal(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", limit: 500 }).maxPosts, 30);
+ // A first fetch, a full re-walk: from the top, no stop at what is known; as many posts as its budget has files.
+ assert.deepEqual(planInstagramRun({}), { mode: "walk", maxPosts: 120, maxRequests: 7, stop: "none", media: WALK });
+ assert.equal(planInstagramRun({ stopAtKnown: true }).stop, "none");
+ // A resumed backfill: from its cursor.
+ assert.deepEqual(planInstagramRun({ cursor: "abc_1" }), { mode: "walk", maxPosts: 120, maxRequests: 7, cursor: "abc_1", stop: "none", media: WALK });
+ // A walk is never under two pages (a one-page walk logs no resume point), never over its budget.
+ assert.equal(planInstagramRun({ limit: 10 }).maxPosts, 60);
+ assert.equal(planInstagramRun({ limit: 5000 }).maxPosts, 120);
+ // A SYNC THAT CONTINUES: a walk that ends at the WATERMARK, never at the posts it archived itself.
+ assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", cursor: INSTAGRAM_FROM_TOP_CURSOR }), {
+ mode: "walk",
+ maxPosts: 120,
+ maxRequests: 7,
+ stop: "watermark",
+ media: WALK,
+ });
+ assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", cursor: "page-3" }), {
+ mode: "walk",
+ maxPosts: 120,
+ maxRequests: 7,
+ cursor: "page-3",
+ stop: "watermark",
+ media: WALK,
+ });
+
+ const args = buildInstagramGalleryDlArgs({ handle: IG_HANDLE, cookies: "firefox:ig-profile", plan: planInstagramRun({ cursor: "abc_1" }) });
+ assert.deepEqual(args, [
+ "--config-ignore",
+ "--no-input",
+ "--no-colors",
+ "--dump-json",
+ "--verbose",
+ "-o",
+ "output.num-to-str=true",
+ "-o",
+ "extractor.instagram.retries=0",
+ "-o",
+ "extractor.instagram.videos=merged",
+ "-o",
+ "extractor.instagram.max-posts=120",
+ "-o",
+ "extractor.instagram.cursor=abc_1",
+ "--cookies-from-browser",
+ "firefox:ig-profile",
+ `https://www.instagram.com/${IG_HANDLE}/posts/`,
+ ]);
+ const file = buildInstagramGalleryDlArgs({ handle: IG_HANDLE, cookies: "file:/data/ig.txt", plan: planInstagramRun({ since: "x" }) });
+ assert.deepEqual(file.slice(-3), ["--cookies", "/data/ig.txt", `https://www.instagram.com/${IG_HANDLE}/posts/`]);
+ // Streaming output would hide the exception: never asked for.
+ assert.ok(!args.join(" ").includes("jsonl"));
+ assert.ok(!args.includes("--no-download"));
+});
+
+test("SYNC NEW: stops at the first archived post, skipping the pinned ones on top; one page, two requests", async () => {
+ const rows = igRows([
+ { n: 2, date: "2025-06-01 00:00:00", pinned: true }, // pinned and archived: no stop
+ { n: 50, date: "2026-03-09 00:00:00", pinned: true, media: ["image", "image"] }, // pinned and new: archived
+ { n: 49, date: "2026-03-08 00:00:00", media: ["video"] },
+ { n: 48, date: "2026-03-07 00:00:00" }, // archived: the stop
+ { n: 47, date: "2026-03-06 00:00:00" }, // below the stop: never read as new
+ ]);
+ const h = harness({ rows, stderr: [...lookup, page] });
+ const r = await fetchInstagramPosts(
+ input(h, { since: "2026-03-07T00:00:00.000Z", seenIds: new Set([igPk(2), igPk(48)]) }),
+ h.deps,
+ );
+ assert.equal(r.complete, true);
+ assert.equal(r.error, undefined);
+ assert.deepEqual(r.posts.map((p) => p.id), [igPk(50), igPk(49)]);
+ assert.deepEqual(r.media?.map((m) => [m.id, m.files.length]), [[igPk(50), 2], [igPk(49), 1]]);
+ assert.equal(r.requests, 2);
+ assert.equal(r.cursor, undefined);
+ assert.ok(h.runs[0]!.args.includes("extractor.instagram.max-posts=30"));
+ // A clean read is noted (it settles a pending signal); no cooldown.
+ assert.deepEqual(h.outcomes, [{ url: URL_, channel: "example-ig" }]);
+ assert.equal(h.rateLimits, 0);
+ assert.ok(h.log.some((l) => l === "Cost: 2 request(s) to Instagram (1 for the account's id, 1 feed page(s))."));
+ assert.ok(h.log.some((l) => /gallery-dl listed 5 post\(s\): 2 new, 2 already archived/.test(l)));
+});
+
+test("SYNC NEW: a post older than the watermark stops it even when it is not archived", async () => {
+ const rows = igRows([{ n: 9, date: "2026-03-09 00:00:00" }, { n: 3, date: "2026-03-03 00:00:00" }]);
+ const h = harness({ rows, stderr: [page] });
+ const r = await fetchInstagramPosts(input(h, { since: "2026-03-05T00:00:00.000Z", seenIds: new Set([igPk(4)]) }), h.deps);
+ assert.deepEqual(r.posts.map((p) => p.id), [igPk(9)]);
+ assert.equal(r.complete, true);
+});
+
+// THE GAP (review 1, M1). Post n is dated n days after 2020-01-01; the archive
+// holds posts up to n = 100 (the watermark W), and the account then posts
+// 101..180 before the next sync.
+const W = "2020-04-10T00:00:00.000Z"; // post 100's date
+const archived = (...extra: number[]) => new Set([...days(100, 100).map((p) => igPk(p.n)), ...extra.map(igPk)]);
+const range = (from: number, to: number) => Array.from({ length: from - to + 1 }, (_, i) => from - i);
+
+test("SYNC NEW: a whole page of new posts and none archived is not caught up — the next sync walks on from the top", async () => {
+ const h = harness({ rows: igRows(days(180, 30)), stderr: [...lookup, page] });
+ const r = await fetchInstagramPosts(input(h, { since: W, seenIds: archived() }), h.deps);
+ assert.deepEqual(r.posts.map((p) => p.id), range(180, 151).map(igPk));
+ assert.equal(r.complete, false);
+ assert.equal(r.cursor, INSTAGRAM_FROM_TOP_CURSOR);
+ assert.equal(r.error, undefined);
+ assert.ok(h.log.some((l) => /older new posts may lie below it/.test(l)));
+});
+
+test("A SYNC THAT CONTINUES skips the posts it archived and stops only at the watermark: more than 30 new posts between two syncs are all fetched", async () => {
+ // Run 2: from the top again (no gallery-dl cursor). Page 1 is the 30 posts run 1 archived; the gap is below them.
+ const stderr = [page, igCursorLine("page-2"), page, igCursorLine("page-3"), page, igCursorLine("page-4"), page];
+ const h = harness({ rows: igRows(days(180, 100)), stderr });
+ const r = await fetchInstagramPosts(
+ input(h, { since: W, cursor: INSTAGRAM_FROM_TOP_CURSOR, stopAtKnown: true, seenIds: archived(...range(180, 151)) }),
+ h.deps,
+ );
+ assert.ok(!h.runs[0]!.args.some((a) => a.includes("extractor.instagram.cursor")));
+ // Everything between the first page and the watermark, none of it dropped, none of it twice.
+ assert.deepEqual(r.posts.map((p) => p.id), range(150, 101).map(igPk));
+ assert.equal(r.complete, true, "it reached the watermark");
+ assert.equal(r.cursor, undefined);
+ assert.equal(r.error, undefined);
+ assert.ok(h.log.some((l) => /gallery-dl listed 100 post\(s\): 50 new, 31 already archived/.test(l)));
+ // The same from a REAL cursor: the walk starts below what run 1 read and still ends at the watermark only.
+ const h2 = harness({ rows: igRows(days(150, 70)), stderr: [page, igCursorLine("page-3"), page, igCursorLine("page-4"), page] });
+ const r2 = await fetchInstagramPosts(
+ input(h2, { since: W, cursor: "page-2", seenIds: archived(...range(180, 151), ...range(150, 141)) }),
+ h2.deps,
+ );
+ assert.ok(h2.runs[0]!.args.includes("extractor.instagram.cursor=page-2"));
+ assert.deepEqual(r2.posts.map((p) => p.id), range(140, 101).map(igPk));
+ assert.equal(r2.complete, true);
+});
+
+test("A SYNC THAT CONTINUES and is capped mid-gap keeps its place: the next run goes on from there, to the watermark", async () => {
+ // 300 new posts (101..400) since the watermark; run 1 archived 400..371. Run 2 lists 120 and is not at the watermark yet.
+ const stderr = [page, igCursorLine("page-2"), page, igCursorLine("page-3"), page, igCursorLine("page-4"), page];
+ const h = harness({ rows: igRows(days(400, 120)), stderr });
+ const seen = archived(...range(400, 371));
+ const r = await fetchInstagramPosts(input(h, { since: W, cursor: INSTAGRAM_FROM_TOP_CURSOR, seenIds: seen }), h.deps);
+ assert.deepEqual(r.posts.map((p) => p.id), range(370, 281).map(igPk));
+ assert.equal(r.complete, false);
+ assert.equal(r.cursor, "page-4", "the page it ended inside");
+ assert.equal(r.error, undefined);
+ // Run 3 from that cursor: re-reads the page (skipped as archived) and goes on.
+ const h3 = harness({ rows: igRows(days(310, 120)), stderr: [page, igCursorLine("page-5"), page, igCursorLine("page-6"), page, igCursorLine("page-7"), page] });
+ const r3 = await fetchInstagramPosts(input(h3, { since: W, cursor: "page-4", seenIds: new Set([...seen, ...range(370, 281).map(igPk)]) }), h3.deps);
+ assert.deepEqual(r3.posts.map((p) => p.id), range(280, 191).map(igPk));
+ assert.equal(r3.cursor, "page-7");
+ assert.equal(r3.complete, false);
+});
+
+test("A SYNC THAT CONTINUES and meets a 429 mid-gap keeps what it read and its place; the run after the hold finishes the gap", async () => {
+ const h = harness({
+ rows: [...igRows(days(180, 60)), igError("HttpError", `'429 Too Many Requests' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30&max_id=page-3'`)],
+ stderr: [page, igCursorLine("page-2"), page, igCursorLine("page-3"), igRequestLine(`${igFeedPath()}&max_id=page-3`, 429)],
+ });
+ const seen = archived(...range(180, 151));
+ const r = await fetchInstagramPosts(input(h, { since: W, cursor: INSTAGRAM_FROM_TOP_CURSOR, seenIds: seen }), h.deps);
+ assert.equal(r.block, "blocked");
+ assert.deepEqual(r.posts.map((p) => p.id), range(150, 121).map(igPk));
+ assert.equal(r.cursor, "page-3");
+ assert.equal(h.rateLimits, 1);
+ assert.equal(h.runs[0]!.stops, 1, "the 429's own request line ended the run");
+ // After the hold: from page-3 down to the watermark.
+ const h2 = harness({ rows: igRows(days(120, 60)), stderr: [page, igCursorLine("page-4"), page] });
+ const r2 = await fetchInstagramPosts(input(h2, { since: W, cursor: "page-3", seenIds: new Set([...seen, ...range(150, 121).map(igPk)]) }), h2.deps);
+ assert.deepEqual(r2.posts.map((p) => p.id), range(120, 101).map(igPk));
+ assert.equal(r2.complete, true);
+});
+
+test("A WALK: 120 posts and more behind them — it stops, and resumes from the last cursor gallery-dl logged", async () => {
+ const stderr = [...lookup];
+ for (let i = 1; i <= 4; i++) {
+ stderr.push(page);
+ if (i < 4) stderr.push(igCursorLine(`page-${i + 1}`));
+ }
+ const h = harness({ rows: igRows(days(400, 120)), stderr });
+ const r = await fetchInstagramPosts(input(h), h.deps);
+ assert.equal(r.posts.length, 120);
+ assert.equal(r.complete, false);
+ assert.equal(r.cursor, "page-4");
+ assert.equal(r.requests, 5);
+ assert.deepEqual(r.mediaBudget, { maxFiles: 120, maxBytes: 600 * 1024 * 1024 });
+ assert.equal(h.runs[0]!.stops, 0, "five requests are under the cap of 7");
+ // The resumed walk re-reads that page: archived posts do not stop it.
+ const h2 = harness({ rows: igRows(days(130, 40)), stderr: [page, igCursorLine("page-5"), page] });
+ const r2 = await fetchInstagramPosts(input(h2, { cursor: "page-4", stopAtKnown: true, seenIds: new Set(days(130, 30).map((p) => igPk(p.n))) }), h2.deps);
+ assert.ok(h2.runs[0]!.args.includes("extractor.instagram.cursor=page-4"));
+ assert.equal(r2.posts.length, 10);
+ // Fewer than it asked for: the account's first post is reached.
+ assert.equal(r2.complete, true);
+});
+
+test("A WALK IS SIZED TO ITS MEDIA: posts whose media would not fit the job's 120 files are left for the next run, which lists them again", async () => {
+ // 120 posts of 3 media each: 360 files. Only the first 40 posts' media fit.
+ const posts = days(400, 120, { media: ["image", "image", "video"] });
+ const stderr = [page, igCursorLine("page-2"), page, igCursorLine("page-3"), page, igCursorLine("page-4"), page];
+ const h = harness({ rows: igRows(posts), stderr });
+ const r = await fetchInstagramPosts(input(h), h.deps);
+ assert.deepEqual(r.posts.map((p) => p.id), range(400, 361).map(igPk));
+ assert.equal(r.media!.reduce((n, m) => n + m.files.length, 0), 120);
+ assert.equal(r.complete, false);
+ // The next run starts where this one did (the top): no page size is assumed.
+ assert.equal(r.cursor, INSTAGRAM_FROM_TOP_CURSOR);
+ assert.equal(r.error, undefined);
+ assert.ok(h.log.some((l) => /80 of the 120 new post\(s\) listed are left for the next run: their media would not fit this job's budget of 120 files/.test(l)));
+ // A cut on the first page resumes where the run began (the top), and still moves on: the posts before the cut are archived.
+ const h2 = harness({ rows: igRows(days(400, 60, { media: Array(10).fill("image") })), stderr: [page, igCursorLine("page-2"), page] });
+ const r2 = await fetchInstagramPosts(input(h2), h2.deps);
+ assert.equal(r2.posts.length, 12);
+ assert.equal(r2.cursor, INSTAGRAM_FROM_TOP_CURSOR);
+ // A sync is one page and is never trimmed: what does not fit its 40 files is owed by the media half.
+ const h3 = harness({ rows: igRows(days(130, 30, { media: ["image", "image"] })), stderr: [page] });
+ const r3 = await fetchInstagramPosts(input(h3, { since: W, seenIds: archived() }), h3.deps);
+ assert.equal(r3.posts.length, 30);
+ assert.deepEqual(r3.mediaBudget, { maxFiles: 40, maxBytes: 200 * 1024 * 1024 });
+});
+
+// Review 2, N2: a page is not always 30 posts. A trimmed walk resumes from its
+// OWN start, so the posts it left behind are listed again whatever a page held.
+test("A TRIMMED WALK over 33-post pages loses nothing: run after run from the same start, every post is archived once", async () => {
+ // 132 posts in pages of 33, each a carousel of 3: 40 posts' media fit a run.
+ const all = days(132, 132, { media: ["image", "image", "video"] });
+ const pagesOf33 = [page, igCursorLine("p2"), page, igCursorLine("p3"), page, igCursorLine("p4"), page];
+ const seen = new Set<string>();
+ const got: string[] = [];
+ let cursor: string | undefined;
+ let complete = false;
+ for (let run = 0; run < 8 && !complete; run++) {
+ // gallery-dl lists up to 120 posts from where the run starts: the top, or page k (33 posts a page).
+ const startRow = cursor && cursor !== INSTAGRAM_FROM_TOP_CURSOR ? (Number(cursor.slice(1)) - 1) * 33 : 0;
+ const listed = all.slice(startRow, startRow + 120);
+ const h = harness({ rows: igRows(listed), stderr: pagesOf33.slice(0, Math.max(1, Math.ceil(listed.length / 33) * 2 - 1)) });
+ const r = await fetchInstagramPosts(input(h, { seenIds: new Set(seen), ...(cursor ? { cursor } : {}) }), h.deps);
+ assert.equal(r.error, undefined);
+ assert.ok(r.posts.length > 0 || r.complete || r.cursor !== cursor, `run ${run} made no progress`);
+ for (const p of r.posts) {
+ assert.ok(!seen.has(p.id), `post ${p.id} archived twice`);
+ seen.add(p.id);
+ got.push(p.id);
+ }
+ assert.ok((r.media ?? []).reduce((n, m) => n + m.files.length, 0) <= 120);
+ cursor = r.cursor;
+ complete = r.complete;
+ }
+ assert.equal(complete, true);
+ // Every post, in order, none skipped: with the old page arithmetic posts 121..132 of a page past row 99 were lost.
+ assert.deepEqual(got, all.map((p) => igPk(p.n)));
+});
+
+test("A REFUSAL DURING THE ACCOUNT LOOKUP ends the run: gallery-dl swallows it and would go on to the feed", async () => {
+ // A 429 on the search: gallery-dl would try the profile page next, and then the feed.
+ const h = harness({ rows: igRows(days(10, 3)), stderr: [igRequestLine(igSearchPath(), 429), igRequestLine(`/${IG_HANDLE}`, 200), page] });
+ const r = await fetchInstagramPosts(input(h), h.deps);
+ assert.equal(h.runs[0]!.stops, 1, "stopped at the first refusal line");
+ assert.equal(r.block, "blocked");
+ assert.match(r.error!, /Instagram refused the read \(GET \/web\/search\/topsearch\/ answered 429\): a rate limit/);
+ assert.equal(h.rateLimits, 1);
+ assert.deepEqual(h.outcomes, [], "a 429 is a hold, never the alert");
+ // The profile page redirected to the login page: no error row says so (the lookup's exception is swallowed).
+ const login = harness({
+ rows: [igError("NotFoundError", "Requested user could not be found")],
+ stderr: [igRequestLine(igSearchPath(), 404), igRequestLine(`/${IG_HANDLE}`, 302), igRequestLine("/accounts/login/?next=%2Fexample.account%2F", 200)],
+ });
+ const l = await fetchInstagramPosts(input(login), login.deps);
+ assert.equal(login.runs[0]!.stops, 1);
+ assert.equal(l.block, "login");
+ assert.equal(login.outcomes[0]!.kind, "auth-failure");
+ assert.match(login.outcomes[0]!.challengeLine!, /the login page/);
+ // A challenge page during the lookup, with an error row that says something else entirely.
+ const ch = harness({ rows: igRows(days(10, 3)), stderr: [igRequestLine(igSearchPath(), 302), igRequestLine("/challenge/?next=/", 200), page] });
+ const c = await fetchInstagramPosts(input(ch), ch.deps);
+ assert.equal(c.block, "challenge");
+ assert.equal(ch.outcomes[0]!.kind, "challenge");
+ // LOGGED OUT the search's 404 is not a refusal by itself: the run goes on (and the feed's 404 is then the login).
+ const out = harness({ rows: igRows(days(10, 3)), stderr: [igRequestLine(igSearchPath(), 404), igRequestLine(`/${IG_HANDLE}`, 200), page] });
+ const o = await fetchInstagramPosts(input(out), out.deps);
+ assert.equal(out.runs[0]!.stops, 0);
+ assert.equal(o.block, undefined);
+ assert.equal(o.posts.length, 3);
+});
+
+test("ONE 401/403 holds Instagram for the hour; a SECOND with no clean read between raises the alert instead", async () => {
+ const row = igError("HttpError", `'401 Unauthorized' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30'`);
+ const first = harness({ rows: [row], stderr: [igRequestLine(igFeedPath(), 401)] });
+ const r1 = await fetchInstagramPosts(input(first), first.deps);
+ assert.equal(r1.block, "blocked");
+ assert.match(r1.error!, /a rate limit\. .*no Instagram job starts before 13:00 UTC/);
+ assert.equal(first.rateLimits, 1);
+ assert.equal(first.outcomes[0]!.kind, "refusal", "noted, pending");
+ assert.equal(r1.needsCookies, undefined);
+ // The second: the alert is up after it is noted.
+ const second = harness({ rows: [row], stderr: [igRequestLine(igFeedPath(), 403)] });
+ second.alert = true;
+ const r2 = await fetchInstagramPosts(input(second), second.deps);
+ assert.equal(r2.block, "blocked");
+ assert.match(r2.error!, /refused the read a second time in a row/);
+ assert.match(r2.error!, /Instagram's alert is up/);
+ assert.equal(second.rateLimits, 0, "not another hourly hold");
+ assert.equal(r2.needsCookies, true);
+ // A 429 is never noted for the alert, however many.
+ const many = harness({ rows: [], stderr: [igRequestLine(igFeedPath(), 429)] });
+ many.alert = true;
+ await fetchInstagramPosts(input(many), many.deps);
+ assert.deepEqual(many.outcomes, []);
+ assert.equal(many.rateLimits, 1);
+});
+
+test("NO request line read is a failure whatever was printed: never a clean read, never complete", async () => {
+ const h = harness({ rows: igRows(days(10, 3)), stderr: ["[instagram][debug] Sleeping 8.83 seconds (request)"] });
+ const r = await fetchInstagramPosts(input(h), h.deps);
+ assert.match(r.error!, /None of gallery-dl's requests could be read from its log/);
+ assert.equal(r.complete, false);
+ assert.equal(r.posts.length, 3, "what it printed is kept");
+ assert.deepEqual(h.outcomes, [], "no clean read is noted");
+ // …and with NOTHING printed too: an empty listing with no request seen is not "the account has no posts".
+ const empty = harness({ rows: [], stderr: [] });
+ const e = await fetchInstagramPosts(input(empty), empty.deps);
+ assert.match(e.error!, /None of gallery-dl's requests could be read/);
+ assert.equal(e.complete, false);
+ assert.deepEqual(empty.outcomes, []);
+ // A sync that printed only archived posts and showed no request is not "caught up" either.
+ const known = harness({ rows: igRows(days(10, 3)), stderr: [] });
+ const k = await fetchInstagramPosts(input(known, { since: "2020-01-02T00:00:00.000Z", seenIds: new Set(days(10, 3).map((p) => igPk(p.n))) }), known.deps);
+ assert.equal(k.complete, false);
+ assert.match(k.error!, /None of gallery-dl's requests/);
+});
+
+// Review 2, N6: only a run that ended by itself counts as the clean read that
+// forgets a pending 401/403.
+test("a cancelled, drained, timed-out or over-cap run that printed rows is not a clean read", async () => {
+ const rows = igRows(days(20, 10));
+ const ac = new AbortController();
+ ac.abort();
+ const cancelled = harness({ rows, stderr: [page], out: { canceled: true } });
+ const c = await fetchInstagramPosts(input(cancelled, { signal: ac.signal }), cancelled.deps);
+ assert.deepEqual([c.complete, c.posts.length, c.error], [false, 10, undefined]);
+ assert.deepEqual(cancelled.outcomes, [], "cancelled: no clean read noted");
+ const timed = harness({ rows, stderr: [page], out: { timedOut: true } });
+ assert.equal((await fetchInstagramPosts(input(timed), timed.deps)).complete, false);
+ assert.deepEqual(timed.outcomes, []);
+ const drain = new AbortController();
+ drain.abort();
+ const drained = harness({ rows, stderr: [page] });
+ const d = await fetchInstagramPosts(input(drained, { drain: drain.signal }), drained.deps);
+ assert.deepEqual([d.complete, d.drained], [false, true]);
+ assert.deepEqual(drained.outcomes, []);
+ const capped = harness({ rows, stderr: [page, page, page, page] });
+ const o = await fetchInstagramPosts(input(capped, { since: "2020-01-01T00:00:00.000Z", seenIds: new Set(["1"]) }), capped.deps);
+ assert.equal(capped.runs[0]!.stops, 1);
+ assert.equal(o.complete, false);
+ assert.deepEqual(capped.outcomes, [], "over its request cap: no clean read noted");
+ // A run that ended by itself is one: at the account's end…
+ const ended = harness({ rows, stderr: [page] });
+ assert.equal((await fetchInstagramPosts(input(ended), ended.deps)).complete, true);
+ assert.equal(ended.outcomes.length, 1);
+ assert.equal(ended.outcomes[0]!.challengeLine, undefined);
+ // …and at its own cap of posts.
+ const atCap = harness({ rows: igRows(days(400, 120)), stderr: [page, igCursorLine("page-2"), page, igCursorLine("page-3"), page, igCursorLine("page-4"), page] });
+ const a = await fetchInstagramPosts(input(atCap), atCap.deps);
+ assert.equal(a.complete, false);
+ assert.equal(atCap.outcomes.length, 1);
+});
+
+test("a run is stopped at its request cap, whatever Instagram's page size", async () => {
+ // A sync that somehow sends a fourth request.
+ const h = harness({ rows: igRows(days(20, 10)), stderr: [igRequestLine(igSearchPath(), 404), igRequestLine(`/${IG_HANDLE}`, 200), page, page] });
+ const r = await fetchInstagramPosts(input(h, { since: "2020-01-01T00:00:00.000Z", seenIds: new Set(["1"]) }), h.deps);
+ assert.equal(h.runs[0]!.stops, 1);
+ assert.equal(r.complete, false);
+ assert.equal(r.posts.length, 10);
+ assert.ok(h.log.some((l) => /Stopped at 4 requests, this run's cap/.test(l)));
+ // A request to another host (the CDN, were one made) is not Instagram's API.
+ const other = harness({
+ rows: igRows(days(20, 2)),
+ stderr: ['[urllib3.connectionpool][debug] https://cdn.example.invalid:443 "GET /a.jpg HTTP/1.1" 200 None', page],
+ });
+ assert.equal((await fetchInstagramPosts(input(other), other.deps)).requests, 1);
+});
+
+test("A DEAD OR MISSING SESSION: the search's 404 and the feed's 404 are the login — the alert, never 'account gone'", async () => {
+ const h = harness({
+ rows: [igError("HttpError", `'404 Not Found' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30'`)],
+ stderr: [igRequestLine(igSearchPath(), 404), igRequestLine(`/${IG_HANDLE}`, 200), igRequestLine(igFeedPath(), 404)],
+ });
+ const r = await fetchInstagramPosts(input(h), h.deps);
+ assert.equal(r.block, "login");
+ assert.equal(r.needsCookies, true);
+ assert.equal(r.complete, false);
+ assert.deepEqual(r.posts, []);
+ assert.equal(r.requests, 3);
+ assert.match(r.error!, /did not accept the login/);
+ assert.match(r.error!, /no Instagram job starts until/);
+ assert.match(r.error!, /Nothing retries by itself/);
+ assert.equal(h.outcomes.length, 1);
+ assert.equal(h.outcomes[0]!.kind, "auth-failure");
+ assert.match(h.outcomes[0]!.challengeLine!, /^HttpError: '404 Not Found'/);
+ assert.equal(h.rateLimits, 0);
+ assert.equal(h.runs.length, 1, "one run, never a second try");
+});
+
+test("a challenge or checkpoint redirect raises the alert as a challenge; a login redirect as a login failure", async () => {
+ const challenge = harness({ rows: [igError("AbortExtraction", "HTTP redirect to challenge page (https://www.instagram.com/challenge/)")], stderr: [page] });
+ const r = await fetchInstagramPosts(input(challenge), challenge.deps);
+ assert.equal(r.block, "challenge");
+ assert.match(r.error!, /challenge or checkpoint page/);
+ assert.equal(challenge.outcomes[0]!.kind, "challenge");
+ const login = harness({ rows: [igError("AbortExtraction", "HTTP redirect to login page (https://www.instagram.com/accounts/login/)")], stderr: [page] });
+ const r2 = await fetchInstagramPosts(input(login), login.deps);
+ assert.equal(r2.block, "login");
+ assert.equal(login.outcomes[0]!.kind, "auth-failure");
+});
+
+test("THE FIRST 429 ENDS THE RUN: what was read is kept with its resume point, Instagram cools down for an hour, nothing is retried", async () => {
+ const h = harness({
+ rows: [...igRows(days(100, 30)), igError("HttpError", `'429 Too Many Requests' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30&max_id=page-2'`)],
+ stderr: [...lookup, page, igCursorLine("page-2"), igRequestLine(`${igFeedPath()}&max_id=page-2`, 429)],
+ });
+ const r = await fetchInstagramPosts(input(h), h.deps);
+ assert.equal(r.block, "blocked");
+ assert.equal(r.posts.length, 30);
+ assert.equal(r.cursor, "page-2");
+ assert.equal(r.complete, false);
+ assert.equal(r.needsCookies, undefined);
+ assert.match(r.error!, /a rate limit/);
+ assert.match(r.error!, /no Instagram job starts before 13:00 UTC \(60 min\)/);
+ assert.equal(h.rateLimits, 1);
+ assert.equal(h.runs.length, 1);
+ // Not an alert: the cookies are not the fix.
+ assert.deepEqual(h.outcomes, []);
+ // A 401 ("please wait a few minutes") is the same.
+ const h401 = harness({ rows: [igError("HttpError", `'401 Unauthorized' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30'`)], stderr: [page] });
+ assert.equal((await fetchInstagramPosts(input(h401), h401.deps)).block, "blocked");
+ assert.equal(h401.rateLimits, 1);
+});
+
+test("the job log never prints the cookie source", async () => {
+ const h = harness({ rows: igRows(days(10, 3)), stderr: [page] });
+ await fetchInstagramPosts(input(h, { cookies: "file:/home/someone/secret-ig-cookies.txt" }), h.deps);
+ assert.ok(h.log.some((l) => l.startsWith("Instagram login: the channel's own cookie source, read by gallery-dl.")));
+ assert.ok(!h.log.join("\n").includes("secret-ig-cookies"));
+ assert.ok(!h.log.join("\n").includes("/home/someone"));
+});
+
+test("a private account, and an account that is gone: a sentence each, no alert, no cooldown", async () => {
+ const priv = harness({ rows: [], stderr: [...lookup, `[instagram][warning] ${IG_HANDLE}'s posts are private`, page] });
+ const r = await fetchInstagramPosts(input(priv), priv.deps);
+ assert.match(r.error!, /is a private account and this channel's login does not follow it/);
+ assert.equal(r.block, undefined);
+ assert.deepEqual(priv.outcomes, []);
+ // A private feed answered with a 404 (or any error row) is still the private sentence for that channel: no alert, no hold.
+ const priv404 = harness({
+ rows: [igError("HttpError", `'404 Not Found' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/?count=30'`)],
+ stderr: [...lookup, `[instagram][warning] ${IG_HANDLE}'s posts are private`, igRequestLine(igFeedPath(), 404)],
+ });
+ const p4 = await fetchInstagramPosts(input(priv404), priv404.deps);
+ assert.match(p4.error!, /is a private account/);
+ assert.equal(p4.block, undefined);
+ assert.deepEqual(priv404.outcomes, []);
+ assert.equal(priv404.rateLimits, 0);
+ // …unless it came with a 429: that is the platform's hold.
+ const priv429 = harness({ rows: [], stderr: [...lookup, `[instagram][warning] ${IG_HANDLE}'s posts are private`, igRequestLine(igFeedPath(), 429)] });
+ assert.equal((await fetchInstagramPosts(input(priv429), priv429.deps)).block, "blocked");
+ assert.equal(priv429.rateLimits, 1);
+
+ const gone = harness({
+ rows: [igError("NotFoundError", "Requested user could not be found")],
+ stderr: [igRequestLine(igSearchPath(), 200), igRequestLine(`/${IG_HANDLE}`, 404)],
+ });
+ const g = await fetchInstagramPosts(input(gone), gone.deps);
+ assert.equal(g.block, "not-found");
+ assert.match(g.error!, /its own page answered 404/);
+ assert.deepEqual(gone.outcomes, []);
+ assert.equal(gone.rateLimits, 0);
+
+ // The lookup failed and the page did not say 404: not proven gone — the login.
+ const unsure = harness({ rows: [igError("NotFoundError", "Requested user could not be found")], stderr: [igRequestLine(igSearchPath(), 404), igRequestLine(`/${IG_HANDLE}`, 302)] });
+ assert.equal((await fetchInstagramPosts(input(unsure), unsure.deps)).block, "login");
+});
+
+test("a 5xx or a crash is a plain failure that keeps what it read", async () => {
+ const h = harness({ rows: [...igRows(days(10, 3)), igError("HttpError", `'500 Internal Server Error' for 'https://www.instagram.com/api/v1/feed/user/${IG_UID}/'`)], stderr: [page] });
+ const r = await fetchInstagramPosts(input(h), h.deps);
+ assert.match(r.error!, /^gallery-dl failed: HttpError: '500/);
+ assert.equal(r.posts.length, 3);
+ assert.equal(r.block, undefined);
+ assert.equal(h.rateLimits, 0);
+ assert.deepEqual(h.outcomes, []);
+});
+
+test("a run cancelled before gallery-dl printed anything reads nothing and keeps the resume point it had", async () => {
+ const ac = new AbortController();
+ ac.abort();
+ const h = harness({ stdout: "\nKeyboardInterrupt", out: { canceled: true } });
+ const r = await fetchInstagramPosts(input(h, { cursor: "page-4", signal: ac.signal }), h.deps);
+ assert.deepEqual(r, { posts: [], complete: false, cursor: "page-4" });
+ const garbled = harness({ stdout: "Traceback (most recent call last)" });
+ assert.match((await fetchInstagramPosts(input(garbled), garbled.deps)).error!, /printed nothing this reads/);
+ // The binary is missing: thrown, as X's fetcher does.
+ const missing = harness({ out: { spawnError: 'gallery-dl not found (looked for "x"; set GALLERY_DL_BIN)' } });
+ await assert.rejects(fetchInstagramPosts(input(missing), missing.deps), /gallery-dl not found/);
+});
diff --git a/common/social/instagramGalleryDlFetcher.ts b/common/social/instagramGalleryDlFetcher.ts
@@ -0,0 +1,629 @@
+// 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 120 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 WALK IS SIZED TO ITS MEDIA: 120 posts is its job's media budget in files,
+// and the posts whose media would not fit that budget are not archived by this
+// run, so every post a run archives has its media asked for in the same run.
+// The next run starts where THIS one did and lists them again (the posts this
+// run archived are skipped as known): no page size is assumed, so nothing is
+// lost whatever a page holds, and each run archives at least one post. A run that sent as many requests as
+// MAX_REQUESTS is stopped, whatever Instagram's page size turns out to be.
+//
+// A SYNC THAT CONTINUES (its page was all new, or it stopped part-way) walks on
+// down to the WATERMARK it began with: the posts it archived on the way are
+// skipped, never a reason to stop — stopping at them dropped everything
+// between them and the watermark.
+//
+// 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).
+// - miss a refusal gallery-dl swallowed. Its account lookup catches every
+// exception and goes on, so each request line is read AS IT ARRIVES
+// (instagramSignals.ts instagramStopSignal): the first 429/401/403, login
+// page or challenge page ends the run and decides what happens next.
+//
+// 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";
+// A kill on a child that never started signals the caller's own group: the
+// guard is installed by this import (lib/childKillGuard.ts).
+import "../lib/childKillGuard";
+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 { raisedServiceAlert } from "../lib/serviceCookies-server";
+import { INSTAGRAM_SERVICE } from "../lib/serviceCookies";
+import {
+ classifyInstagramError,
+ instagramErrorStatus,
+ instagramStopSignal,
+ isInstagramApiHost,
+ isInstagramPrivateLine,
+ parseInstagramCursorLine,
+ parseInstagramRequestLine,
+ type InstagramRequestLine,
+} from "./instagramSignals";
+
+export const INSTAGRAM_FETCHER_ID = "instagram-gallery-dl";
+
+// Instagram's feed page, at the most.
+export const INSTAGRAM_PAGE_POSTS = 30;
+// SYNC NEW: one page.
+export const INSTAGRAM_SYNC_MAX_POSTS = INSTAGRAM_PAGE_POSTS;
+// THE MEDIA A JOB MAY FETCH (instagramMedia.ts enforces it): a sync's, and a
+// walk's. A walk lists no more posts than its budget has files.
+export const INSTAGRAM_SYNC_MEDIA = { maxFiles: 40, maxBytes: 200 * 1024 * 1024 } as const;
+export const INSTAGRAM_WALK_MEDIA = { maxFiles: 120, maxBytes: 600 * 1024 * 1024 } as const;
+// A walk: four 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 = INSTAGRAM_WALK_MEDIA.maxFiles;
+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 = 2 + INSTAGRAM_WALK_MAX_POSTS / INSTAGRAM_PAGE_POSTS + 1;
+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;
+ // WHERE THE WALK ENDS (pinned posts aside: they sit on top of the grid
+ // whatever their age, and are archived when new, never a stop):
+ // "known" at the first post already archived, or older than `since` —
+ // a sync from the top.
+ // "watermark" at the first post older than `since`; a post already
+ // archived is SKIPPED — a sync that continues, which meets
+ // its own earlier posts on the way down.
+ // "none" nowhere: a history walk reads on to the account's first post.
+ stop: "known" | "watermark" | "none";
+ // The media this job may fetch.
+ media: { maxFiles: number; maxBytes: number };
+};
+
+// 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,
+ stop: input.stopAtKnown === false ? "none" : "known",
+ media: INSTAGRAM_SYNC_MEDIA,
+ };
+ }
+ 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 } : {}),
+ // A walk with a watermark is a sync that continues; one without is the
+ // history walk, which re-reads a page of archived posts on purpose.
+ stop: input.since && input.stopAtKnown !== false ? "watermark" : "none",
+ media: INSTAGRAM_WALK_MEDIA,
+ };
+}
+
+// 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",
+ // A post's own numbers as strings: its pk is beyond 2^53.
+ "-o",
+ "output.num-to-str=true",
+ // 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 InstagramAlertKind = "challenge" | "auth-failure" | "refusal";
+
+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>;
+ // A signal for Instagram's alert (`challengeLine` set), or a clean read.
+ // Answers the line for the job log when a clean read settled something.
+ noteOutcome: (outcome: { challengeLine?: string; kind?: InstagramAlertKind; url?: string; channel?: string }) => Promise<string | null>;
+ // Whether Instagram's alert is up now.
+ alertRaised: () => Promise<boolean>;
+ // 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),
+ alertRaised: async () => (await raisedServiceAlert(paths, INSTAGRAM_SERVICE)) !== null,
+ 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 });
+ // The cookie source itself is never printed: it may be a path or a profile's name.
+ log(
+ "Instagram login: the channel's own cookie source, 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"}` +
+ (plan.stop === "watermark" ? ", down to the posts already archived." : ".")) +
+ ` At most ${plan.maxRequests} requests, 6-12 s apart; a refusal is not retried.`,
+ );
+
+ const requests: InstagramRequestLine[] = [];
+ const cursors: string[] = [];
+ let privateLine: string | undefined;
+ let overCap = false;
+ // The first request line that is a refusal: it ended the run.
+ let live: ReturnType<typeof instagramStopSignal> = null;
+ 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) {
+ cursors.push(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 (!live) {
+ live = instagramStopSignal(r);
+ if (live) return "stop";
+ }
+ if (requests.length >= plan.maxRequests && !overCap) {
+ overCap = true;
+ return "stop";
+ }
+ },
+ });
+ if (out.spawnError) throw new Error(out.spawnError);
+ const stopSignal = live as ReturnType<typeof instagramStopSignal>;
+ log(instagramCostLine(requests));
+
+ const rows = parseInstagramRun(out.stdout, { channelSlug, handle });
+ const listed = rows?.posts ?? [];
+ const cursor = cursors.at(-1);
+
+ // Which of what was listed is new, and where the walk met its end.
+ let fresh: InstagramListedPost[] = [];
+ let known = 0;
+ let reachedEnd = false;
+ for (const p of listed) {
+ const isKnown = seenIds.has(p.post.id);
+ 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;
+ }
+ const isOld = Boolean(since) && p.post.createdAt <= since!;
+ if (plan.stop === "known" && (isKnown || isOld)) {
+ known++;
+ reachedEnd = true;
+ break;
+ }
+ if (plan.stop === "watermark" && isOld) {
+ if (isKnown) known++;
+ reachedEnd = true;
+ break;
+ }
+ if (isKnown) {
+ // A post this walk (or the run before it) archived: skipped, and the walk goes on.
+ known++;
+ continue;
+ }
+ fresh.push(p);
+ }
+
+ // A WALK IS SIZED TO ITS MEDIA: the posts whose media would not fit this
+ // job's file budget are left for the next run, which lists them again from
+ // the page the first of them was on.
+ let trimmedAt: InstagramListedPost | undefined;
+ if (plan.mode === "walk") {
+ let files = 0;
+ const keep: InstagramListedPost[] = [];
+ for (const p of fresh) {
+ if (keep.length > 0 && files + p.files.length > plan.media.maxFiles) {
+ trimmedAt = p;
+ break;
+ }
+ files += p.files.length;
+ keep.push(p);
+ }
+ if (trimmedAt) {
+ log(
+ `${fresh.length - keep.length} of the ${fresh.length} new post(s) listed are left for the next run: their media would not fit ` +
+ `this job's budget of ${plan.media.maxFiles} files. Each run's posts get their media in the same run.`,
+ );
+ fresh = keep;
+ }
+ }
+
+ 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. A run that
+ // left posts behind for its media budget starts again WHERE THIS ONE DID
+ // (its own cursor, or the top): which page a post was on is not known —
+ // gallery-dl prints no page marks, and a page is not always 30 posts — so
+ // any later cursor could skip the posts left behind. Otherwise: the last
+ // page gallery-dl left; else the point it was given; else — when it saved
+ // posts before leaving any page — the top.
+ const start = plan.cursor ?? (input.cursor === INSTAGRAM_FROM_TOP_CURSOR ? INSTAGRAM_FROM_TOP_CURSOR : undefined);
+ const resumeAt = trimmedAt
+ ? (start ?? INSTAGRAM_FROM_TOP_CURSOR)
+ : (cursor ?? start ?? (posts.length > 0 ? INSTAGRAM_FROM_TOP_CURSOR : undefined));
+ const base = {
+ posts,
+ requests: requests.filter((r) => isInstagramApiHost(r.host)).length,
+ ...(media.length ? { media } : {}),
+ mediaBudget: { ...plan.media },
+ };
+ const accountUrl = instagramAccountUrl(handle);
+ const unfinished = resumeAt && !reachedEnd ? { cursor: resumeAt } : {};
+
+ // ── what the run met ──────────────────────────────────────────────────
+ // A refusal seen on a request line decides, whatever the error row says;
+ // then a private account; then the error row.
+ const fromRow = rows?.error ? classifyInstagramError(rows.error, { requests, handle }) : null;
+ const rateLimited = stopSignal?.class === "rate-limit" || (!stopSignal && fromRow?.class === "rate-limit");
+ const isPrivate = Boolean(privateLine) || fromRow?.class === "private";
+ const sig: { class: NonNullable<typeof fromRow>["class"]; line: string; status?: number } | null = stopSignal
+ ? { class: stopSignal.class, line: stopSignal.line, status: stopSignal.status }
+ : isPrivate && !rateLimited
+ ? { class: "private", line: privateLine ?? fromRow!.line }
+ : fromRow
+ ? { ...fromRow, ...(rows?.error && instagramErrorStatus(rows.error) !== null ? { status: instagramErrorStatus(rows.error)! } : {}) }
+ : null;
+
+ const alerted = async (kind: InstagramAlertKind, what: string, fix: string, line: string): Promise<PostFetchResult> => {
+ await deps.noteOutcome({ challengeLine: line, kind, url: accountUrl, channel: channelSlug });
+ return {
+ ...base,
+ complete: false,
+ ...unfinished,
+ needsCookies: true,
+ block: kind === "challenge" ? "challenge" : kind === "refusal" ? "blocked" : "login",
+ error:
+ `${what}: ${line}. The run stopped and Instagram's alert is up: no Instagram job starts until ${fix}, ` +
+ "and Recheck is pressed on the dashboard. Nothing retries by itself.",
+ };
+ };
+
+ if (sig?.class === "challenge") {
+ return alerted(
+ "challenge",
+ "Instagram answered with a challenge or checkpoint page",
+ "the check is passed by hand in the browser this channel's cookie source names",
+ sig.line,
+ );
+ }
+ if (sig?.class === "login") {
+ return alerted(
+ "auth-failure",
+ "Instagram did not accept the login (its login page, or the \"Page Not Found\" it answers a logged-out read with)",
+ "that browser (or cookies file) is logged in to Instagram again",
+ sig.line,
+ );
+ }
+ if (sig?.class === "rate-limit") {
+ // A 401 or a 403 is Instagram's "please wait a few minutes": ONE holds
+ // Instagram for the hour; a SECOND with no clean read between needs a
+ // person, not another hour.
+ if (sig.status === 401 || sig.status === 403) {
+ await deps.noteOutcome({ challengeLine: sig.line, kind: "refusal", url: accountUrl, channel: channelSlug });
+ if (await deps.alertRaised().catch(() => false)) {
+ return {
+ ...base,
+ complete: false,
+ ...unfinished,
+ needsCookies: true,
+ block: "blocked",
+ error:
+ `Instagram refused the read a second time in a row (${sig.line}), with no clean read between. ` +
+ "The run stopped and Instagram's alert is up: no Instagram job starts until the account is looked at by hand " +
+ "in the browser this channel's cookie source names, and Recheck is pressed on the dashboard. Nothing retries by itself.",
+ };
+ }
+ }
+ const until = await deps.noteRateLimit().catch(() => deps.now() + INSTAGRAM_RATE_LIMIT_HOLD_MS);
+ return {
+ ...base,
+ complete: false,
+ ...unfinished,
+ 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 === "private") {
+ return {
+ ...base,
+ complete: false,
+ error: `@${handle} is a private account and this channel's login does not follow it: nothing was read.`,
+ };
+ }
+ 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.`,
+ };
+ }
+ // Any other failure: a post already archived ends a sync before the row that failed mattered.
+ if (sig?.class === "error" && !reachedEnd) {
+ 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,
+ ...(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." };
+ }
+
+ // A RUN THAT WAS STOPPED — cancelled, drained, out of time, at its request
+ // cap — keeps what it printed and its place, and is NOT a clean read: it
+ // settles no pending refusal (review 2, N6) and is never complete.
+ const stoppedWhy =
+ out.canceled || signal.aborted
+ ? "Cancelled; the next run resumes where this one left off."
+ : 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.`
+ : input.drain?.aborted
+ ? "Drained; the next run resumes where this one left off."
+ : overCap
+ ? `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."
+ : null;
+ if (stoppedWhy) {
+ log(stoppedWhy);
+ const drained = Boolean(input.drain?.aborted) && !out.canceled && !signal.aborted && !out.timedOut;
+ return { ...base, complete: false, ...(resumeAt && !reachedEnd ? { cursor: resumeAt } : {}), ...(drained ? { drained: true } : {}) };
+ }
+
+ // NO REQUEST LINE READ (review 2, N4): the request cap and the refusal watch
+ // were blind — gallery-dl's log format changed, or --verbose was lost. A
+ // failure whatever it printed: never a clean read, never complete.
+ if (requests.length === 0) {
+ return {
+ ...base,
+ complete: false,
+ ...(resumeAt ? { cursor: resumeAt } : {}),
+ error:
+ "None of gallery-dl's requests could be read from its log, so this run's request cap and its watch for a refusal " +
+ "saw nothing. What it listed is kept; fix the log reading (instagramSignals.ts) before the next fetch.",
+ };
+ }
+
+ // A clean read — it ended by itself, with no signal, at its end or at its
+ // own cap: 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 (trimmedAt) return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}) };
+ if (reachedEnd) return { ...base, complete: true };
+ // 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,381 @@
+// The media half of an Instagram fetch (instagramMedia.ts): one GET per file,
+// paced, capped, and stopped by three refusals in a row. The CDN is a function
+// here; nothing opens a socket.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/instagramMedia.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, readdir, rm, writeFile, mkdir } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { PostMediaPlan } from "./fetchers";
+import {
+ fakeInstagramMediaDeps,
+ fakeInstagramMediaFetch,
+ fetchInstagramMedia,
+ instagramMediaLine,
+ instagramMediaPauseMs,
+ INSTAGRAM_MEDIA_MAX_BYTES,
+ INSTAGRAM_MEDIA_MAX_FILE_BYTES,
+ INSTAGRAM_MEDIA_MAX_FILES,
+ INSTAGRAM_MEDIA_BUDGET_MS,
+ INSTAGRAM_MEDIA_FILE_MS,
+ INSTAGRAM_MEDIA_USER_AGENT,
+ instagramMediaUrlProblem,
+ recordInstagramMediaOwed,
+ type InstagramMediaFetch,
+} from "./instagramMedia";
+
+// An invented host under Instagram's CDN suffix: never asked (the CDN is a function here).
+const CDN = "https://scontent-invented.cdninstagram.com";
+const pk = (n: number) => (3500000000000000000n + BigInt(n)).toString();
+
+function plan(n: number, files: number, tag = ""): PostMediaPlan {
+ return {
+ id: pk(n),
+ url: `https://www.instagram.com/p/Code${n}/`,
+ files: Array.from({ length: files }, (_, i) => ({
+ num: i + 1,
+ kind: "image" as const,
+ url: `${CDN}/${n}-${i + 1}${tag}.jpg?sig=invented`,
+ name: `${String(i + 1).padStart(2, "0")}-${n}${i + 1}.jpg`,
+ })),
+ };
+}
+
+type Cdn = { calls: { url: string; init: Record<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");
+ // No referer, and one plain browser User-Agent (never Node's own).
+ assert.equal(call.init.referrer, "");
+ assert.equal(call.init.referrerPolicy, "no-referrer");
+ assert.deepEqual(call.init.headers, { "User-Agent": INSTAGRAM_MEDIA_USER_AGENT });
+ }
+ assert.deepEqual(c.pauses, [3000, 3000]);
+ assert.deepEqual({ ...sum }, { fetched: 3, bytes: 30, kept: 0, owed: 0, oversize: 0, skipped: 0, failed: 0, postsWhole: 2, postsOwed: 0, posts: 2 });
+ assert.deepEqual((await readdir(path.join(out, pk(1)))).sort(), ["01-11.jpg", "02-12.jpg", "capture.json"]);
+ const r = await record(out, pk(1));
+ assert.deepEqual([r.version, r.id, r.url, r.state, r.mediaState, r.capturedAt], [1, pk(1), "https://www.instagram.com/p/Code1/", "captured", "ok", "2026-03-10T12:00:00.000Z"]);
+ assert.equal(r.shot, undefined);
+ assert.deepEqual(r.media.map((m: { name: string; bytes: number }) => [m.name, m.bytes]), [["01-11.jpg", 10], ["02-12.jpg", 10]]);
+ assert.match(instagramMediaLine(sum), /^Media: 3 file\(s\) fetched from its CDN \(0 MB\); 2 of 2 post\(s\) whole\.$/);
+
+ // A second job over the same posts asks the CDN nothing.
+ const again = cdn();
+ const sum2 = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 2)], signal: signal(), deps: deps(again) });
+ assert.equal(again.calls.length, 0);
+ assert.equal(sum2.kept, 2);
+ assert.equal((await record(out, pk(1))).mediaState, "ok");
+ } finally {
+ await rm(out, { recursive: true, force: true });
+ }
+});
+
+test("the job's budget: the 41st file is not asked for, and is recorded as owed", async () => {
+ const out = await tmp();
+ try {
+ const c = cdn();
+ const sum = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 10), plan(2, 10), plan(3, 10), plan(4, 10), plan(5, 3)], signal: signal(), deps: deps(c) });
+ assert.equal(c.calls.length, 40);
+ assert.equal(sum.fetched, 40);
+ assert.equal(sum.owed, 3);
+ assert.equal(sum.postsWhole, 4);
+ assert.match(sum.stopped!, /media budget of 40 files \/ 200 MB is used/);
+ const r = await record(out, pk(5));
+ assert.equal(r.mediaState, "error");
+ assert.equal(r.mediaOwed, "next");
+ assert.deepEqual(r.media, []);
+ // The byte budget, with small limits.
+ assert.equal(sum.postsOwed, 1);
+ assert.match(instagramMediaLine(sum), /1 with media owed \(nothing collects owed media yet\)/);
+ // The BYTE budget holds while a file streams: the file that would cross it is abandoned, nothing of it left.
+ const c2 = cdn(() => ({ bytes: 600 }));
+ const out2 = await tmp();
+ const sum2 = await fetchInstagramMedia({ outDir: out2, plans: [plan(7, 5)], signal: signal(), deps: deps(c2), limits: { maxBytes: 1000 } });
+ assert.equal(c2.calls.length, 2, "the second file is asked for, and abandoned when it crosses the budget");
+ assert.deepEqual([sum2.fetched, sum2.bytes, sum2.owed, sum2.oversize], [1, 600, 4, 0]);
+ assert.deepEqual((await readdir(path.join(out2, pk(7)))).sort(), ["01-71.jpg", "capture.json"]);
+ assert.equal((await record(out2, pk(7))).mediaOwed, "next");
+ // A walk's budget is the caller's to give.
+ const c3 = cdn();
+ const sum3 = await fetchInstagramMedia({ outDir: await tmp(), plans: [plan(8, 45)], signal: signal(), deps: deps(c3), limits: { maxFiles: 120, maxBytes: 600 * 1024 * 1024 } });
+ assert.equal(sum3.fetched, 45);
+ } finally {
+ await rm(out, { recursive: true, force: true });
+ }
+});
+
+test("a file over 100 MB is not fetched: by its declared length, or cut when the body runs past it", async () => {
+ const out = await tmp();
+ try {
+ const c = cdn((url) => (url.includes("/1-1") ? { declared: 150 * 1024 * 1024 } : {}));
+ const sum = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 2)], signal: signal(), deps: deps(c) });
+ assert.equal(sum.oversize, 1);
+ assert.equal(sum.fetched, 1);
+ assert.deepEqual((await readdir(path.join(out, pk(1)))).sort(), ["02-12.jpg", "capture.json"]);
+ const r = await record(out, pk(1));
+ assert.equal(r.mediaState, "error");
+ assert.match(r.error, /01-11\.jpg: it is 150 MB, over the 100 MB a file may be/);
+ assert.equal(r.mediaOwed, undefined, "over the cap is not owed: asking again gets the same file");
+ // Undeclared, and longer than the cap: cut, nothing left behind.
+ const lying = cdn(() => ({ bytes: 50, declared: 5 }));
+ const out2 = await tmp();
+ const sum2 = await fetchInstagramMedia({ outDir: out2, plans: [plan(2, 1)], signal: signal(), deps: deps(lying), limits: { maxFileBytes: 20 } });
+ assert.equal(sum2.oversize, 1);
+ assert.deepEqual(await readdir(path.join(out2, pk(2))), ["capture.json"]);
+ } finally {
+ await rm(out, { recursive: true, force: true });
+ }
+});
+
+test("three refusals in a row (a 403, a 429, no answer) end the media half; a success between them resets the count", async () => {
+ const out = await tmp();
+ try {
+ // refused, refused, ok, refused (429), refused (throws), refused -> stop; the rest unasked.
+ const seq = [403, 403, 200, 429, -1, 403, 200, 200];
+ const c = cdn((_u, i) => (seq[i] === -1 ? { throws: true } : { status: seq[i] }));
+ const sum = await fetchInstagramMedia({ outDir: out, plans: [plan(1, 4), plan(2, 4)], signal: signal(), deps: deps(c) });
+ assert.equal(c.calls.length, 6);
+ assert.equal(sum.fetched, 1);
+ assert.equal(sum.owed, 7);
+ assert.match(sum.stopped!, /the CDN refused 3 files in a row/);
+ const r2 = await record(out, pk(2));
+ assert.equal(r2.mediaOwed, "next");
+ assert.match(r2.error, /owed \(the CDN refused 3 files in a row\)/);
+ // A 404 or a 500 is a failure of that file, not a refusal: the job goes on.
+ const c2 = cdn((_u, i) => ({ status: i < 4 ? 404 : 200 }));
+ const out2 = await tmp();
+ const sum2 = await fetchInstagramMedia({ outDir: out2, plans: [plan(3, 5)], signal: signal(), deps: deps(c2) });
+ assert.equal(c2.calls.length, 5);
+ assert.deepEqual([sum2.failed, sum2.fetched, sum2.stopped], [4, 1, undefined]);
+ } finally {
+ await rm(out, { recursive: true, force: true });
+ }
+});
+
+test("a cancelled job asks for nothing more and says the rest is owed; an id that is not a post id touches no path", async () => {
+ const out = await tmp();
+ try {
+ const ac = new AbortController();
+ const c = cdn();
+ const d = deps(c);
+ const sum = await fetchInstagramMedia({
+ outDir: out,
+ plans: [plan(1, 3)],
+ signal: ac.signal,
+ deps: { ...d, pause: async () => ac.abort() },
+ });
+ assert.equal(c.calls.length, 1);
+ assert.deepEqual([sum.fetched, sum.owed], [1, 2]);
+ assert.equal((await record(out, pk(1))).mediaOwed, "next");
+ const bad = await fetchInstagramMedia({ outDir: out, plans: [{ ...plan(2, 1), id: "../escape" }], signal: signal(), deps: d });
+ assert.equal(bad.failed, 1);
+ assert.deepEqual((await readdir(out)).sort(), [pk(1)]);
+ // A file name is never a path.
+ await mkdir(path.join(out, "x"), { recursive: true });
+ const sneaky = { ...plan(4, 1), files: [{ num: 1, kind: "image" as const, url: `${CDN}/a.jpg`, name: "../../evil.jpg" }] };
+ assert.equal(sum.postsOwed, 1);
+ await fetchInstagramMedia({ outDir: out, plans: [sneaky], signal: signal(), deps: d });
+ assert.deepEqual((await readdir(path.join(out, pk(4)))).sort(), ["capture.json", "evil.jpg"]);
+ await writeFile(path.join(out, "x", "keep"), "");
+ } finally {
+ await rm(out, { recursive: true, force: true });
+ }
+});
+
+test("only Instagram's CDN is asked: https, a host under .cdninstagram.com or .fbcdn.net — anything else is skipped and said", async () => {
+ assert.equal(instagramMediaUrlProblem("https://scontent-xyz.cdninstagram.com/v/a.jpg?x=1"), null);
+ assert.equal(instagramMediaUrlProblem("https://video.fabc1-1.fna.fbcdn.net/v/a.mp4"), null);
+ assert.match(instagramMediaUrlProblem("http://scontent-xyz.cdninstagram.com/a.jpg")!, /not https/);
+ assert.match(instagramMediaUrlProblem("https://cdninstagram.com.example.org/a.jpg")!, /is not Instagram's CDN/);
+ assert.match(instagramMediaUrlProblem("https://evilcdninstagram.com/a.jpg")!, /is not Instagram's CDN/);
+ assert.match(instagramMediaUrlProblem("https://cdninstagram.com/a.jpg")!, /is not Instagram's CDN/);
+ assert.match(instagramMediaUrlProblem("https://www.instagram.com/api/v1/x")!, /is not Instagram's CDN/);
+ assert.match(instagramMediaUrlProblem("https://user:pw@scontent.cdninstagram.com/a.jpg")!, /credentials/);
+ assert.match(instagramMediaUrlProblem("file:///etc/passwd")!, /not https/);
+ assert.match(instagramMediaUrlProblem("not a url")!, /not a URL/);
+ const out = await tmp();
+ try {
+ const c = cdn();
+ const mixed = plan(1, 3);
+ mixed.files[1]!.url = "https://cdn.example.invalid/elsewhere.jpg";
+ const d = deps(c);
+ const sum = await fetchInstagramMedia({ outDir: out, plans: [mixed], signal: signal(), deps: { fetch: d.fetch, pause: d.pause, pauseMs: d.pauseMs, now: d.now } });
+ assert.equal(c.calls.length, 2, "the other host is never asked");
+ assert.ok(c.calls.every((x) => x.url.startsWith(CDN)));
+ assert.deepEqual([sum.fetched, sum.skipped, sum.owed], [2, 1, 0]);
+ const r = await record(out, pk(1));
+ assert.match(r.error, /02-12\.jpg: not fetched \(its host \(cdn\.example\.invalid\) is not Instagram's CDN\)/);
+ assert.equal(r.mediaOwed, undefined);
+ assert.match(instagramMediaLine(sum), /1 on a host that is not Instagram's CDN, not fetched/);
+ } finally {
+ await rm(out, { recursive: true, force: true });
+ }
+});
+
+test("a drain stops between two files; the media half has its own deadline; a file has five minutes", async () => {
+ assert.equal(INSTAGRAM_MEDIA_BUDGET_MS, 20 * 60_000);
+ assert.equal(INSTAGRAM_MEDIA_FILE_MS, 5 * 60_000);
+ const out = await tmp();
+ try {
+ // Drained during the pause before the second file: the first is whole, nothing after it starts.
+ const drain = new AbortController();
+ const c = cdn();
+ const d = deps(c);
+ const log: string[] = [];
+ const sum = await fetchInstagramMedia({
+ outDir: out,
+ plans: [plan(1, 3), plan(2, 1)],
+ signal: signal(),
+ drain: drain.signal,
+ onLog: (l) => log.push(l),
+ deps: { ...d, pause: async () => drain.abort() },
+ });
+ assert.equal(c.calls.length, 1);
+ assert.deepEqual([sum.fetched, sum.owed, sum.postsOwed], [1, 3, 2]);
+ assert.equal(sum.stopped, "the job was drained");
+ assert.ok(log.some((l) => l.startsWith("Drained: no more media is asked for")));
+ assert.equal((await record(out, pk(2))).mediaOwed, "next");
+ // The deadline: a clock that passes it after two files.
+ let now = 0;
+ const c2 = cdn();
+ const d2 = deps(c2);
+ const sum2 = await fetchInstagramMedia({
+ outDir: await tmp(),
+ plans: [plan(3, 5)],
+ signal: signal(),
+ deps: { ...d2, now: () => now, pause: async () => { now += 400_000; } },
+ limits: { budgetMs: 1_000_000 },
+ });
+ assert.equal(c2.calls.length, 3, "0 s, 400 s and 800 s are inside 1000 s; 1200 s is not");
+ assert.equal(sum2.stopped, "the media half's time is used");
+ assert.equal(sum2.owed, 2);
+ } finally {
+ await rm(out, { recursive: true, force: true });
+ }
+});
+
+test("a file that cannot be written fails that file with a sentence, and the job goes on", async () => {
+ const out = await tmp();
+ try {
+ const c = cdn();
+ const d = deps(c);
+ const { createWriteStream } = await import("node:fs");
+ let n = 0;
+ const sum = await fetchInstagramMedia({
+ outDir: out,
+ plans: [plan(1, 3)],
+ signal: signal(),
+ deps: {
+ ...d,
+ // The first file's directory does not exist (an open failure, as a full or read-only disk gives).
+ openFile: (file) => createWriteStream(n++ === 0 ? path.join(out, "no-such-dir", "x", path.basename(file)) : file),
+ },
+ });
+ assert.deepEqual([sum.fetched, sum.failed, sum.owed], [2, 1, 0]);
+ const r = await record(out, pk(1));
+ assert.match(r.error, /^01-11\.jpg: the file could not be written \(ENOENT/);
+ assert.deepEqual((await readdir(path.join(out, pk(1)))).sort(), ["02-12.jpg", "03-13.jpg", "capture.json"]);
+ // An opener that throws outright is the same sentence.
+ const sum2 = await fetchInstagramMedia({
+ outDir: await tmp(),
+ plans: [plan(2, 1)],
+ signal: signal(),
+ deps: { ...d, openFile: () => { throw new Error("ENOSPC: no space left on device (invented)"); } },
+ });
+ assert.equal(sum2.failed, 1);
+ } finally {
+ await rm(out, { recursive: true, force: true });
+ }
+});
+
+test("after a refusal in the listing no media is asked for at all: each post's record says its media are owed", async () => {
+ const out = await tmp();
+ try {
+ const marked = await recordInstagramMediaOwed({ outDir: out, plans: [plan(1, 2), plan(2, 1)], why: "Instagram refused the listing", now: Date.parse("2026-03-10T12:00:00Z") });
+ assert.equal(marked, 2);
+ const r = await record(out, pk(1));
+ assert.deepEqual([r.state, r.mediaState, r.mediaOwed, r.media.length], ["captured", "error", "next", 0]);
+ assert.match(r.error, /not fetched \(Instagram refused the listing\)/);
+ assert.deepEqual(await readdir(path.join(out, pk(1))), ["capture.json"]);
+ // A post whose media are already whole on disk is not marked.
+ const c = cdn();
+ await fetchInstagramMedia({ outDir: out, plans: [plan(3, 1)], signal: signal(), deps: deps(c) });
+ assert.equal(await recordInstagramMediaOwed({ outDir: out, plans: [plan(3, 1)], why: "x" }), 0);
+ assert.equal((await record(out, pk(3))).mediaState, "ok");
+ } finally {
+ await rm(out, { recursive: true, force: true });
+ }
+});
+
+test("the test server's CDN is played back, and there is none outside it", async () => {
+ assert.equal(fakeInstagramMediaFetch({}), null);
+ assert.equal(fakeInstagramMediaDeps({}), null);
+ // Played back, no CDN is asked: no pause between two files either.
+ assert.equal(fakeInstagramMediaDeps({ E2E_TEST_ROUTES: "1" })!.pauseMs(), 0);
+ const f = fakeInstagramMediaFetch({ E2E_TEST_ROUTES: "1" })!;
+ const init = { signal: signal(), redirect: "error" as const, credentials: "omit" as const, referrer: "" as const, referrerPolicy: "no-referrer" as const, headers: {} };
+ // The fixtures' invented host is allowed only beside the played-back fetch.
+ assert.match(instagramMediaUrlProblem("https://cdn.example.invalid/a.jpg")!, /is not Instagram's CDN/);
+ assert.equal(fakeInstagramMediaDeps({ E2E_TEST_ROUTES: "1" })!.urlProblem("https://cdn.example.invalid/a.jpg"), null);
+ assert.match(fakeInstagramMediaDeps({ E2E_TEST_ROUTES: "1" })!.urlProblem("https://example.org/a.jpg")!, /is not Instagram's CDN/);
+ assert.equal((await f(`${CDN}/a.jpg`, init)).status, 200);
+ assert.equal((await f(`${CDN}/refused.jpg`, init)).status, 403);
+ assert.equal((await f(`${CDN}/limited.jpg`, init)).status, 429);
+ assert.equal((await f(`${CDN}/huge.mp4`, init)).headers.get("content-length"), String(150 * 1024 * 1024));
+});
diff --git a/common/social/instagramMedia.ts b/common/social/instagramMedia.ts
@@ -0,0 +1,557 @@
+// THE MEDIA OF AN INSTAGRAM FETCH (lane instagram): the pictures and videos of
+// the posts a run just listed, fetched from the CDN addresses the run printed,
+// in the same job — they are signed and expire, so "later" is not an option.
+//
+// - ONLY INSTAGRAM'S CDN: an https address on a host ending in
+// .cdninstagram.com or .fbcdn.net. Anything else is skipped and said.
+// - ONE GET per file, with no cookies and no referer, a plain browser
+// User-Agent, never following a redirect, 2-5 s after the one before it.
+// - A job fetches at most its budget (a sync 40 files / 200 MB, a walk
+// 120 / 600 MB — the fetcher's plan says which); a file over 100 MB is not
+// fetched at all. The byte budget holds WHILE a file streams: one that
+// would cross it is abandoned. What a job did not fetch is OWED and said so
+// in the post's capture record (`mediaOwed: "next"`), never retried here.
+// - Three refusals in a row (a 403, a 429, no answer) end the media half.
+// - It ends with the job: a cancel stops it at once, a drain or its own
+// deadline (20 minutes) between two files; a file may take 5 minutes.
+// - NOT AT ALL after a refusal in the listing (recordInstagramMediaOwed):
+// when Instagram refused, challenged or asked for a login, everything
+// Instagram stops, its CDN included.
+//
+// Files land in `channels/<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";
+
+// A sync's budget; a walk's is larger (instagramGalleryDlFetcher.ts).
+export const INSTAGRAM_MEDIA_MAX_FILES = 40;
+export const INSTAGRAM_MEDIA_MAX_BYTES = 200 * 1024 * 1024;
+export const INSTAGRAM_MEDIA_MAX_FILE_BYTES = 100 * 1024 * 1024;
+export const INSTAGRAM_MEDIA_MAX_REFUSALS = 3;
+export const INSTAGRAM_MEDIA_PAUSE_MIN_MS = 2_000;
+export const INSTAGRAM_MEDIA_PAUSE_MAX_MS = 5_000;
+// The media half's own deadline, and one file's.
+export const INSTAGRAM_MEDIA_BUDGET_MS = 20 * 60_000;
+export const INSTAGRAM_MEDIA_FILE_MS = 5 * 60_000;
+const HEADERS_MS = 30_000;
+
+// THE ONE User-Agent a media GET sends. gallery-dl 1.32.9 sends exactly this
+// for an Instagram video or audio file (extractor/instagram.py
+// `videos_headers`), and its Chrome string for a picture; one plain string for
+// both here. Node's own ("node") would name the client.
+export const INSTAGRAM_MEDIA_USER_AGENT = "Mozilla/5.0";
+
+// The hosts Instagram serves media from.
+export const INSTAGRAM_MEDIA_HOST_SUFFIXES: readonly string[] = [".cdninstagram.com", ".fbcdn.net"];
+
+// Why an address is not fetched, or null when it may be.
+export function instagramMediaUrlProblem(url: string, suffixes: readonly string[] = INSTAGRAM_MEDIA_HOST_SUFFIXES): string | null {
+ let u: URL;
+ try {
+ u = new URL(url);
+ } catch {
+ return "its address is not a URL";
+ }
+ if (u.protocol !== "https:") return "its address is not https";
+ if (u.username || u.password) return "its address carries credentials";
+ const host = u.hostname.toLowerCase();
+ if (!suffixes.some((s) => host.endsWith(s) && host.length > s.length)) {
+ return `its host (${host}) is not Instagram's CDN`;
+ }
+ return null;
+}
+
+export type InstagramMediaFetch = (
+ url: string,
+ init: {
+ signal: AbortSignal;
+ redirect: "error";
+ credentials: "omit";
+ referrer: "";
+ referrerPolicy: "no-referrer";
+ headers: Record<string, string>;
+ },
+) => 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;
+ // Why an address is not fetched, or null.
+ urlProblem: (url: string) => string | null;
+ // A file's writer (tests break it).
+ openFile: (file: string) => NodeJS.WritableStream & { destroy: () => void };
+};
+
+export function instagramMediaPauseMs(rand: () => number = Math.random): number {
+ return Math.round(INSTAGRAM_MEDIA_PAUSE_MIN_MS + rand() * (INSTAGRAM_MEDIA_PAUSE_MAX_MS - INSTAGRAM_MEDIA_PAUSE_MIN_MS));
+}
+
+function sleep(ms: number, signal: AbortSignal): Promise<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(),
+ urlProblem: (url) => instagramMediaUrlProblem(url),
+ openFile: (file) => createWriteStream(file),
+});
+
+// UNDER THE E2E TEST SERVER the CDN is played back, always: no test server
+// opens a socket to it. An address containing "refused" answers 403, one
+// containing "limited" 429, one containing "huge" declares 150 MB; every
+// other answers a few bytes naming it. Null outside the test server.
+export function fakeInstagramMediaFetch(
+ env: Readonly<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,
+ };
+ };
+}
+
+// The fixtures' invented CDN host, allowed ONLY beside the played-back fetch:
+// outside the test server an address on it is skipped like any other host
+// that is not Instagram's, so the fake gallery-dl can never cause a request.
+export const E2E_INSTAGRAM_MEDIA_HOST_SUFFIX = ".example.invalid";
+
+// What the controller takes under the test server: the played-back fetch, no
+// pause between two files (no CDN is being asked), and the fixtures' host.
+export function fakeInstagramMediaDeps(
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): Pick<InstagramMediaDeps, "fetch" | "pauseMs" | "urlProblem"> | null {
+ const fake = fakeInstagramMediaFetch(env);
+ if (!fake) return null;
+ return {
+ fetch: fake,
+ pauseMs: () => 0,
+ urlProblem: (url) => instagramMediaUrlProblem(url, [...INSTAGRAM_MEDIA_HOST_SUFFIXES, E2E_INSTAGRAM_MEDIA_HOST_SUFFIX]),
+ };
+}
+
+const mb = (bytes: number) => `${Math.round(bytes / (1024 * 1024))} MB`;
+const firstLine = (err: unknown) => String((err as Error)?.message ?? err).split("\n")[0]!.slice(0, 200);
+
+type Fetched =
+ | { ok: true; bytes: number }
+ | {
+ ok: false;
+ why: string;
+ // The CDN refused (a 403, a 429, no answer): counted toward the three.
+ refused?: boolean;
+ // Larger than a file may ever be: not owed, asking again gets the same file.
+ oversize?: boolean;
+ // It would have crossed the job's byte budget: owed.
+ overBudget?: boolean;
+ };
+
+// One file, streamed to `<name>.part` and renamed when whole. `cap` is what a
+// file may be; `room` what is left of the job's byte budget.
+async function fetchOne(o: {
+ url: string;
+ file: string;
+ cap: number;
+ room: number;
+ deps: Pick<InstagramMediaDeps, "fetch" | "openFile">;
+ signal: AbortSignal;
+}): Promise<Fetched> {
+ const part = `${o.file}.part`;
+ const limit = Math.min(o.cap, o.room);
+ const over = (bytes: number): Fetched =>
+ bytes > o.cap || o.cap <= o.room
+ ? { ok: false, oversize: true, why: `it is ${bytes > 0 ? mb(bytes) : "more than " + mb(o.cap)}, over the ${mb(o.cap)} a file may be` }
+ : { ok: false, overBudget: true, why: "it would cross this job's byte budget" };
+ const deadline = AbortSignal.any([o.signal, AbortSignal.timeout(INSTAGRAM_MEDIA_FILE_MS)]);
+ // The wait for the headers is its own timer, cleared when they arrive: the
+ // signal handed to fetch also ends the body.
+ const headers = new AbortController();
+ const timer = setTimeout(() => headers.abort(new Error("no answer in time")), HEADERS_MS);
+ let res: Awaited<ReturnType<InstagramMediaFetch>>;
+ try {
+ res = await o.deps.fetch(o.url, {
+ signal: AbortSignal.any([deadline, headers.signal]),
+ redirect: "error",
+ credentials: "omit",
+ referrer: "",
+ referrerPolicy: "no-referrer",
+ headers: { "User-Agent": INSTAGRAM_MEDIA_USER_AGENT },
+ });
+ } catch (err) {
+ return { ok: false, refused: !o.signal.aborted, why: `the CDN did not answer (${firstLine(err)})` };
+ } finally {
+ clearTimeout(timer);
+ }
+ const drop = async () => {
+ try {
+ await res.body?.cancel?.();
+ } catch {
+ /* already ended */
+ }
+ };
+ if (res.status < 200 || res.status >= 300 || !res.body) {
+ await drop();
+ return { ok: false, refused: res.status === 403 || res.status === 429, why: `the CDN answered ${res.status}` };
+ }
+ const declared = Number(res.headers.get("content-length") ?? "");
+ if (Number.isFinite(declared) && declared > limit) {
+ await drop();
+ return over(declared);
+ }
+ await rm(part, { force: true });
+ // A writer that cannot open or runs out of disk says so through "error":
+ // listened for from the start, so it fails this file with a sentence and is
+ // never an unhandled event.
+ let writeError: Error | null = null;
+ let out: ReturnType<InstagramMediaDeps["openFile"]>;
+ try {
+ out = o.deps.openFile(part);
+ } catch (err) {
+ await drop();
+ return { ok: false, why: `the file could not be written (${firstLine(err)})` };
+ }
+ out.on("error", (err: Error) => {
+ writeError = err;
+ });
+ const failedWrite = async (): Promise<Fetched> => {
+ out.destroy();
+ await drop();
+ await rm(part, { force: true });
+ return { ok: false, why: `the file could not be written (${firstLine(writeError)})` };
+ };
+ let bytes = 0;
+ let tooBig = false;
+ try {
+ for await (const chunk of res.body) {
+ if (writeError) return await failedWrite();
+ if (deadline.aborted) throw new Error(o.signal.aborted ? "cancelled" : "the file took too long");
+ bytes += chunk.byteLength;
+ if (bytes > limit) {
+ tooBig = true;
+ break;
+ }
+ if (!out.write(chunk)) await Promise.race([once(out, "drain"), once(out, "error").catch(() => {})]);
+ }
+ } catch (err) {
+ if (writeError) return failedWrite();
+ out.destroy();
+ await rm(part, { force: true });
+ return { ok: false, refused: !o.signal.aborted, why: `the download broke off (${firstLine(err)})` };
+ }
+ if (writeError) return failedWrite();
+ await new Promise<void>((resolve) => {
+ out.once("error", () => resolve());
+ out.end(() => resolve());
+ });
+ if (writeError) return failedWrite();
+ if (tooBig) {
+ await drop();
+ await rm(part, { force: true });
+ return over(0);
+ }
+ if (bytes === 0) {
+ await rm(part, { force: true });
+ return { ok: false, why: "the CDN answered an empty file" };
+ }
+ try {
+ await rename(part, o.file);
+ } catch (err) {
+ await rm(part, { force: true });
+ return { ok: false, why: `the file could not be written (${firstLine(err)})` };
+ }
+ return { ok: true, bytes };
+}
+
+export type InstagramMediaSummary = {
+ // Files fetched by this job, and their bytes.
+ fetched: number;
+ bytes: number;
+ // Files already on disk from an earlier job.
+ kept: number;
+ // Files not fetched and owed to a later capture (the job's budget, a
+ // refusal, a cancel, a drain, the deadline), files over the per-file cap,
+ // files on a host that is not Instagram's CDN, and files that failed.
+ owed: number;
+ oversize: number;
+ skipped: number;
+ failed: number;
+ // Posts whose media are whole on disk after the job, of how many; and how
+ // many are left owed something.
+ postsWhole: number;
+ postsOwed: number;
+ posts: number;
+ // Why the media half stopped before its last file, when it did.
+ stopped?: string;
+};
+
+async function exists(file: string): Promise<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[];
+ // Cancel: ends the file in hand and everything after it.
+ signal: AbortSignal;
+ // Drain: the file in hand finishes, nothing after it starts.
+ drain?: AbortSignal;
+ onLog?: (line: string) => void;
+ deps?: Partial<InstagramMediaDeps>;
+ limits?: { maxFiles?: number; maxBytes?: number; maxFileBytes?: number; budgetMs?: 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 deadlineAt = deps.now() + (opts.limits?.budgetMs ?? INSTAGRAM_MEDIA_BUDGET_MS);
+ const sum: InstagramMediaSummary = {
+ fetched: 0,
+ bytes: 0,
+ kept: 0,
+ owed: 0,
+ oversize: 0,
+ skipped: 0,
+ failed: 0,
+ postsWhole: 0,
+ postsOwed: 0,
+ posts: opts.plans.length,
+ };
+ let asked = 0;
+ let refusals = 0;
+ const stop = (why: string, line: string) => {
+ if (sum.stopped) return;
+ sum.stopped = why;
+ log(line);
+ };
+ // Why nothing more is asked for now, or null.
+ const halted = (): string | null => {
+ if (opts.signal.aborted) return "cancelled";
+ if (sum.stopped) return sum.stopped;
+ if (opts.drain?.aborted) {
+ stop("the job was drained", "Drained: no more media is asked for; the rest is owed to a later capture.");
+ return sum.stopped!;
+ }
+ if (deps.now() >= deadlineAt) {
+ stop(
+ "the media half's time is used",
+ "The media half's time is used: no more media is asked for; the rest is owed to a later capture.",
+ );
+ return sum.stopped!;
+ }
+ if (asked >= maxFiles || sum.bytes >= maxBytes) {
+ stop(
+ `this job's media budget of ${maxFiles} files / ${mb(maxBytes)} is used`,
+ `This job's media budget (${maxFiles} files / ${mb(maxBytes)}) is used: the rest is owed to a later capture.`,
+ );
+ return sum.stopped!;
+ }
+ return null;
+ };
+ for (const plan of opts.plans) {
+ let dir: string;
+ try {
+ dir = postCaptureDir(opts.outDir, plan.id);
+ } catch (err) {
+ sum.failed += plan.files.length;
+ log(`[warn] ${firstLine(err)}: its media are left.`);
+ continue;
+ }
+ await mkdir(dir, { recursive: true });
+ const landed: CapturedFile[] = [];
+ const problems: string[] = [];
+ let owed = false;
+ for (const f of [...plan.files].sort((a, b) => a.num - b.num)) {
+ const name = path.basename(f.name);
+ const file = path.join(dir, name);
+ if (await exists(file)) {
+ sum.kept++;
+ landed.push(await describeCapturedFile(dir, name, f.url));
+ continue;
+ }
+ const notCdn = deps.urlProblem(f.url);
+ if (notCdn) {
+ sum.skipped++;
+ problems.push(`${name}: not fetched (${notCdn})`);
+ continue;
+ }
+ let why = halted();
+ if (!why && asked > 0) {
+ await deps.pause(deps.pauseMs(), opts.signal);
+ why = halted();
+ }
+ if (why) {
+ owed = true;
+ sum.owed++;
+ problems.push(`${name}: owed (${why})`);
+ continue;
+ }
+ asked++;
+ const got = await fetchOne({ url: f.url, file, cap: maxFileBytes, room: maxBytes - sum.bytes, deps, signal: opts.signal });
+ if (got.ok) {
+ refusals = 0;
+ sum.fetched++;
+ sum.bytes += got.bytes;
+ landed.push(await describeCapturedFile(dir, name, f.url));
+ continue;
+ }
+ problems.push(`${name}: ${got.why}`);
+ if (got.oversize) {
+ refusals = 0;
+ sum.oversize++;
+ continue;
+ }
+ if (got.overBudget) {
+ refusals = 0;
+ owed = true;
+ sum.owed++;
+ stop(
+ `this job's media budget of ${maxFiles} files / ${mb(maxBytes)} is used`,
+ `This job's media budget (${maxFiles} files / ${mb(maxBytes)}) is used: the rest is owed to a later capture.`,
+ );
+ continue;
+ }
+ refusals = got.refused ? refusals + 1 : 0;
+ if (got.refused) {
+ owed = true;
+ sum.owed++;
+ } else sum.failed++;
+ if (refusals >= INSTAGRAM_MEDIA_MAX_REFUSALS) {
+ stop(
+ `the CDN refused ${INSTAGRAM_MEDIA_MAX_REFUSALS} files in a row`,
+ `Instagram's media CDN refused ${INSTAGRAM_MEDIA_MAX_REFUSALS} files in a row (a 403, a 429 or no answer): ` +
+ "this job asks it for no more. What is left is owed to a later capture; nothing retries by itself.",
+ );
+ }
+ }
+ const whole = problems.length === 0;
+ if (whole) sum.postsWhole++;
+ if (owed) sum.postsOwed++;
+ await writeRecord(dir, plan, landed, whole ? null : { owed, error: problems.join("; ") }, deps.now());
+ }
+ return sum;
+}
+
+async function writeRecord(
+ dir: string,
+ plan: PostMediaPlan,
+ landed: CapturedFile[],
+ problem: { owed: boolean; error: string } | null,
+ now: number,
+): Promise<void> {
+ const prior = await readPostCapture(dir);
+ const record: PostCaptureRecord = {
+ ...(prior ?? {}),
+ version: 1,
+ id: plan.id,
+ url: plan.url,
+ capturedAt: new Date(now).toISOString(),
+ state: "captured",
+ mediaState: problem ? "error" : landed.length > 0 ? "ok" : "none",
+ media: landed,
+ };
+ delete record.mediaOwed;
+ delete record.error;
+ if (problem) {
+ if (problem.owed) record.mediaOwed = "next";
+ record.error = problem.error;
+ }
+ await writePostCapture(dir, record);
+}
+
+// THE LISTING WAS REFUSED (a rate limit, a challenge, a login page): the posts
+// it read are archived, and their media are NOT asked for — everything
+// Instagram stops, its CDN too. Each post's record says its media are owed.
+// Answers how many posts were marked.
+export async function recordInstagramMediaOwed(opts: {
+ outDir: string;
+ plans: readonly PostMediaPlan[];
+ why: string;
+ now?: number;
+}): Promise<number> {
+ let marked = 0;
+ for (const plan of opts.plans) {
+ let dir: string;
+ try {
+ dir = postCaptureDir(opts.outDir, plan.id);
+ } catch {
+ continue;
+ }
+ await mkdir(dir, { recursive: true });
+ const landed: CapturedFile[] = [];
+ for (const f of plan.files) {
+ const name = path.basename(f.name);
+ if (await exists(path.join(dir, name))) landed.push(await describeCapturedFile(dir, name, f.url));
+ }
+ if (landed.length === plan.files.length) continue;
+ await writeRecord(dir, plan, landed, { owed: true, error: `not fetched (${opts.why})` }, opts.now ?? Date.now());
+ marked++;
+ }
+ return marked;
+}
+
+// What the media half did, as one line for the job's log.
+export function instagramMediaLine(sum: InstagramMediaSummary): string {
+ const parts = [`${sum.fetched} file(s) fetched from its CDN (${mb(sum.bytes)})`];
+ if (sum.kept) parts.push(`${sum.kept} already on disk`);
+ if (sum.owed) parts.push(`${sum.owed} owed to a later capture`);
+ if (sum.oversize) parts.push(`${sum.oversize} over the per-file cap, not fetched`);
+ if (sum.skipped) parts.push(`${sum.skipped} on a host that is not Instagram's CDN, not fetched`);
+ if (sum.failed) parts.push(`${sum.failed} failed`);
+ return (
+ `Media: ${parts.join(", ")}; ${sum.postsWhole} of ${sum.posts} post(s) whole` +
+ (sum.postsOwed ? `, ${sum.postsOwed} with media owed (nothing collects owed media yet)` : "") +
+ "."
+ );
+}
diff --git a/common/social/instagramNormalize.test.ts b/common/social/instagramNormalize.test.ts
@@ -0,0 +1,154 @@
+// 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("digits inside a caption are never rewritten: long runs, escaped quotes, unicode", () => {
+ const captions = [
+ "call 12345678901234567890 now, or [12345678901234567, 99999999999999999]",
+ 'she said "id: 1234567890123456789", then {"n":12345678901234567}',
+ "a backslash at the end \\",
+ "émoji 🌊 1234567890123456789
fin, 12345678901234567",
+ ": 1234567890123456789,",
+ ];
+ const rows = igRows(captions.map((text, i) => ({ n: 40 + i, date: "2026-03-01 08:00:00", text })));
+ const text = igStdout(rows, captions.map((_c, i) => igPk(40 + i)));
+ for (let i = 0; i < captions.length; i++) assert.ok(text.includes(`"post_id": ${igPk(40 + i)}`), "the pks are bare numbers");
+ const run = parseInstagramRun(text, ctx);
+ assert.ok(run, "the run parses");
+ assert.deepEqual(run!.posts.map((p) => p.post.text), captions);
+ assert.deepEqual(run!.posts.map((p) => p.post.id), captions.map((_c, i) => igPk(40 + i)));
+ // The scan itself: a bare long integer is quoted; a float, a short one and a string are not.
+ assert.equal(
+ quoteBigIntegers('[1234567890123456789, 1.5e300, 12, "1234567890123456789", -1234567890123456789, 12345678901234567.5]'),
+ '["1234567890123456789", 1.5e300, 12, "1234567890123456789", "-1234567890123456789", 12345678901234567.5]',
+ );
+ assert.equal(quoteBigIntegers('{"a":"x\\\\","b":1234567890123456789}'), '{"a":"x\\\\","b":"1234567890123456789"}');
+ assert.equal(quoteBigIntegers('{"a":"say \\"1234567890123456789\\"","b":1}'), '{"a":"say \\"1234567890123456789\\"","b":1}');
+});
+
+test("numbers printed as strings (output.num-to-str) read the same", () => {
+ const rows = igRows([{ n: 6, date: "2026-03-06 00:00:00", media: ["image", "video"], likes: 12 }]) as [number, ...unknown[]][];
+ for (const row of rows) {
+ const dict = row[row.length - 1] as Record<string, unknown>;
+ for (const k of ["likes", "count", "num", "width", "height"]) if (typeof dict[k] === "number") dict[k] = String(dict[k]);
+ }
+ const [p] = parseInstagramRun(igStdout(rows), ctx)!.posts;
+ assert.deepEqual(p!.post.engagement, { likes: 12 });
+ assert.equal(p!.post.mediaCount, 2);
+ assert.deepEqual(p!.files.map((f) => f.num), [1, 2]);
+ assert.equal(p!.row, 0);
+});
+
+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,290 @@
+// 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;
+ // Its place among the post rows the run printed (0-based, repeats counted):
+ // what tells which page of the walk it was on, at the latest.
+ row: number;
+ 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 BARE integer of 16 digits or more, so JSON.parse keeps it whole.
+// A scan that knows where it is: digits INSIDE a string (a caption quoting a
+// 17-digit number, an escaped quote before it) are never touched — a regex
+// over the whole text rewrote them and broke the parse. The run is asked for
+// `output.num-to-str`, which prints a post's own numbers as strings already;
+// that option does not reach numbers inside lists, which is what this is for.
+export function quoteBigIntegers(json: string): string {
+ let out = "";
+ let i = 0;
+ const n = json.length;
+ while (i < n) {
+ const c = json[i]!;
+ if (c === '"') {
+ // A string: copied whole, escapes and all.
+ let j = i + 1;
+ while (j < n && json[j] !== '"') j += json[j] === "\\" ? 2 : 1;
+ out += json.slice(i, Math.min(j + 1, n));
+ i = j + 1;
+ continue;
+ }
+ if (c === "-" || (c >= "0" && c <= "9")) {
+ let j = i + (c === "-" ? 1 : 0);
+ while (j < n && json[j]! >= "0" && json[j]! <= "9") j++;
+ const digits = j - i - (c === "-" ? 1 : 0);
+ // An integer only: a fraction or an exponent follows a float, left alone.
+ const next = json[j];
+ const integer = next !== "." && next !== "e" && next !== "E";
+ if (!integer) {
+ while (j < n && /[0-9.eE+-]/.test(json[j]!)) j++;
+ out += json.slice(i, j);
+ } else out += digits >= 16 ? `"${json.slice(i, j)}"` : json.slice(i, j);
+ i = Math.max(j, i + 1);
+ continue;
+ }
+ out += c;
+ i++;
+ }
+ return out;
+}
+
+const str = (v: unknown): string | undefined => (typeof v === "string" && v ? v : undefined);
+// A count, printed as a number or (with `output.num-to-str`) as its digits.
+const countOf = (v: unknown): number | undefined => {
+ const n = typeof v === "number" ? v : typeof v === "string" && /^\d{1,15}$/.test(v) ? Number(v) : NaN;
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 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 given = countOf(raw.num);
+ const num = given !== undefined && given >= 1 ? given : 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 = countOf(raw.count);
+ const likes = countOf(raw.likes);
+ 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") {
+ const rowIndex = out.emitted;
+ 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, row: rowIndex, 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,145 @@
+// 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 {
+ instagramWallPage,
+ instagramErrorStatus,
+ instagramStopSignal,
+ 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");
+});
+
+test("a request line that ends the run: a 429/401/403, the login page, the challenge page — and never a 404", () => {
+ const sig = (l: string) => instagramStopSignal(parseInstagramRequestLine(l)!);
+ assert.deepEqual(sig(req(`/web/search/topsearch/?query=${H}`, 429)), { class: "rate-limit", status: 429, line: "GET /web/search/topsearch/ answered 429" });
+ assert.equal(sig(req(`/${H}`, 401))?.class, "rate-limit");
+ assert.equal(sig(req(`/api/v1/feed/user/${UID}/?count=30`, 403))?.status, 403);
+ assert.equal(sig(req("/accounts/login/?next=%2Fexample.account%2F", 200))?.class, "login");
+ assert.equal(sig(req("/challenge/?next=/x", 200))?.class, "challenge");
+ assert.equal(sig(req("/challenge/", 302))?.class, "challenge");
+ assert.equal(sig(req("/api/v1/checkpoint/required/", 400))?.class, "challenge");
+ // LOGGED OUT the search answers 404 and the run goes on: not a signal by itself.
+ assert.equal(sig(req(`/web/search/topsearch/?query=${H}`, 404)), null);
+ assert.equal(sig(req(`/api/v1/feed/user/${UID}/?count=30`, 404)), null);
+ assert.equal(sig(req(`/api/v1/feed/user/${UID}/?count=30`, 200)), null);
+ assert.equal(sig(req(`/${H}`, 302)), null);
+ // The query string never reaches a log line (it may name an account).
+ assert.ok(!sig(req(`/web/search/topsearch/?query=${H}`, 429))!.line.includes(H));
+ // Another host's 403 (a CDN) is not Instagram's refusal.
+ assert.equal(instagramStopSignal({ host: "cdn.example.invalid", method: "GET", path: "/a.jpg", status: 403 }), null);
+ assert.equal(instagramErrorStatus({ message: "'401 Unauthorized' for 'https://www.instagram.com/x'" }), 401);
+ assert.equal(instagramErrorStatus({ message: "Requested user could not be found" }), null);
+});
+
+// Review 2, N3: the walls are path SEGMENTS. gallery-dl asks for the account's
+// own page as /<handle>, and a handle may begin with "challenge" or contain
+// "checkpoint" (both handles invented).
+test("a handle that begins with 'challenge' or contains 'checkpoint' is an account's page, never a wall", () => {
+ const sig = (l: string) => instagramStopSignal(parseInstagramRequestLine(l)!);
+ for (const handle of ["challengeaccepted", "checkpoint.charlie", "challenge", "checkpoint"]) {
+ assert.equal(sig(req(`/${handle}`, 200)), null, handle);
+ assert.equal(instagramWallPage(`/${handle}`), null, handle);
+ // Its 404 is the account being gone, as for any handle.
+ const gone = classifyInstagramError(
+ { error: "NotFoundError", message: "Requested user could not be found" },
+ { requests: lines(req(`/web/search/topsearch/?query=${handle}`, 404), req(`/${handle}`, 404)), handle },
+ );
+ assert.equal(gone.class, "not-found", handle);
+ // An error row that quotes the account's own URL is not a challenge either.
+ const row = classifyInstagramError(
+ { error: "HttpError", message: `'500 Internal Server Error' for 'https://www.instagram.com/${handle}'` },
+ { requests: [], handle },
+ );
+ assert.equal(row.class, "error", handle);
+ // The search for it is not a wall.
+ assert.equal(sig(req(`/web/search/topsearch/?query=${handle}`, 200)), null);
+ }
+ // The walls themselves, by segment.
+ assert.equal(instagramWallPage("/challenge/"), "challenge");
+ assert.equal(instagramWallPage("/challenge/action/abc/"), "challenge");
+ assert.equal(instagramWallPage("/api/v1/challenge/"), null, "only the first segment is the challenge page");
+ assert.equal(instagramWallPage("/accounts/checkpoint/"), "challenge");
+ assert.equal(instagramWallPage("/checkpoint/"), "challenge");
+ assert.equal(instagramWallPage("/accounts/login/"), "login");
+ assert.equal(instagramWallPage("/accounts/login"), "login");
+ assert.equal(instagramWallPage("/accounts/loginhelp/"), null);
+ assert.equal(instagramWallPage("/challengeaccepted/"), null, "a handle with a trailing slash is still a handle");
+ assert.equal(instagramWallPage("/"), null);
+ // A row whose URL IS a wall still classifies by it.
+ const ctx = { requests: [], handle: "challengeaccepted" };
+ assert.equal(classifyInstagramError({ error: "HttpError", message: "'400 Bad Request' for 'https://www.instagram.com/challenge/?next=/'" }, ctx).class, "challenge");
+ assert.equal(classifyInstagramError({ error: "HttpError", message: "'200 OK' for 'https://www.instagram.com/accounts/login/?next=/'" }, ctx).class, "login");
+});
diff --git a/common/social/instagramSignals.ts b/common/social/instagramSignals.ts
@@ -0,0 +1,172 @@
+// 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;
+}
+
+// WHICH WALL A PATH IS, by its SEGMENTS — never by a substring: gallery-dl
+// asks for the account's own page as `/<handle>`, and a handle may begin with
+// "challenge" or contain "checkpoint". A wall is
+// /challenge/… the first segment, with something under it (or a
+// trailing slash): never the bare `/<handle>` form
+// /…/checkpoint/… a segment that is exactly "checkpoint", in a path
+// of more than one segment (or with a trailing slash)
+// /accounts/login… the first two segments
+export function instagramWallPage(pathname: string): "challenge" | "login" | null {
+ const path = pathname.split("?")[0]!.toLowerCase();
+ const segs = path.split("/").filter(Boolean);
+ if (segs.length === 0) return null;
+ // The bare one-segment form with no trailing slash is an account's page.
+ const bareHandle = segs.length === 1 && !path.endsWith("/");
+ if (segs[0] === "accounts" && segs[1] === "login") return "login";
+ if (bareHandle) return null;
+ if (segs[0] === "challenge" || segs.includes("checkpoint")) return "challenge";
+ return null;
+}
+
+// The wall an error row's text names: gallery-dl's own words for a redirect,
+// or the path of the URL it quotes — never a word inside a handle.
+function wallInText(text: string): "challenge" | "login" | null {
+ if (/redirect to challenge page|ChallengeError|challenge_required|checkpoint_required/i.test(text)) return "challenge";
+ if (/redirect to (?:login|home) page/i.test(text)) return "login";
+ for (const m of text.matchAll(/https?:\/\/[^\s'")]+/g)) {
+ try {
+ const u = new URL(m[0]);
+ if (!isInstagramApiHost(u.hostname.toLowerCase())) continue;
+ const page = instagramWallPage(u.pathname);
+ if (page) return page;
+ } catch {
+ /* not a URL */
+ }
+ }
+ return null;
+}
+
+// WHAT ONE REQUEST LINE SAYS, AS IT ARRIVES. gallery-dl swallows every
+// exception of its account lookup (the search, then the profile page) and
+// goes on to the next request, so a refusal there never reaches the error
+// row: the run would carry on into the feed with no hold and no alert. The
+// request lines are therefore read live, and the FIRST one that is a
+// refusal ends the run and decides its class, whatever the error row says:
+// "rate-limit" status 429, 401 or 403 from Instagram
+// "login" a request under /accounts/login
+// "challenge" a request under /challenge/, or a path naming a checkpoint
+// A 404 is NOT one: logged out, the search answers 404 and the run goes on to
+// the profile page, which is how the account's id is then found.
+export function instagramStopSignal(r: InstagramRequestLine): { class: "rate-limit" | "login" | "challenge"; status: number; line: string } | null {
+ if (!isInstagramApiHost(r.host)) return null;
+ const path = r.path.split("?")[0]!.toLowerCase();
+ const line = `${r.method} ${r.path.split("?")[0]} answered ${r.status}`.slice(0, 300);
+ const page = instagramWallPage(path);
+ if (page === "challenge") return { class: "challenge", status: r.status, line: `${r.method} ${path} (a challenge or checkpoint page)` };
+ if (page === "login") return { class: "login", status: r.status, line: `${r.method} ${path} (the login page)` };
+ if (r.status === 429 || r.status === 401 || r.status === 403) return { class: "rate-limit", status: r.status, line };
+ return null;
+}
+
+// The status a refusal named in an error row, or null.
+export function instagramErrorStatus(row: { message: string }): number | null {
+ const m = STATUS_IN_MESSAGE.exec(row.message);
+ return m ? Number(m[1]) : 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}`;
+ const wall = wallInText(text);
+ if (wall === "challenge") return { class: "challenge", line };
+ if (wall === "login") 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
@@ -82,10 +82,28 @@ export type XenforoSocialSettings = {
retryOnBlock?: RetryOnBlock;
};
+// Instagram's settings (lane instagram).
+export type InstagramPostsVisibility = "public" | "private";
+
+export const INSTAGRAM_POSTS_VISIBILITIES: readonly InstagramPostsVisibility[] = ["private", "public"];
+
+export function isInstagramPostsVisibility(v: unknown): v is InstagramPostsVisibility {
+ return v === "public" || v === "private";
+}
+
+export type InstagramSocialSettings = {
+ // WHERE INSTAGRAM POSTS MAY APPEAR. Absent = "private": an Instagram
+ // 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;
+};
+
export type SocialSettings = {
x: XSocialSettings;
// Absent: nothing set.
xenforo?: XenforoSocialSettings;
+ // Absent: nothing set (private).
+ instagram?: InstagramSocialSettings;
};
// Total over `unknown`, as every settings coercion is: anything that is not a
@@ -101,6 +119,12 @@ export function sanitizeSocial(value: unknown): SocialSettings {
const xf = (r.xenforo && typeof r.xenforo === "object" && !Array.isArray(r.xenforo)
? r.xenforo
: {}) as Record<string, unknown>;
+ const ig = (r.instagram && typeof r.instagram === "object" && !Array.isArray(r.instagram)
+ ? r.instagram
+ : {}) as Record<string, unknown>;
+ const instagram: InstagramSocialSettings = {
+ ...(isInstagramPostsVisibility(ig.visibility) ? { visibility: ig.visibility } : {}),
+ };
const retryOnBlock = parseRetryOnBlock(xf.retryOnBlock);
const maxCookieAgeMinutes = parseXMaxCookieAgeMinutes(x.maxCookieAgeMinutes);
return {
@@ -110,6 +134,7 @@ export function sanitizeSocial(value: unknown): SocialSettings {
...(maxCookieAgeMinutes !== undefined ? { maxCookieAgeMinutes } : {}),
},
...(retryOnBlock ? { xenforo: { retryOnBlock } } : {}),
+ ...(Object.keys(instagram).length > 0 ? { instagram } : {}),
};
}
diff --git a/common/views/schedulerStatus.ts b/common/views/schedulerStatus.ts
@@ -43,6 +43,9 @@ export type SchedulerStatusInputs = {
// Resolved by the shell: it reads the env override and imports the heartbeat
// module, which owns a RUNNER. A view never names a runner.
heartbeatSeconds: number;
+ // Why no Instagram job starts now, when none does (the shell asks the
+ // guard: jobs/instagramGuard.ts).
+ instagramHeld?: string | null;
};
export function buildSchedulerStatusPayload(
@@ -56,6 +59,7 @@ export function buildSchedulerStatusPayload(
now,
priority: settings.channelPriority,
jitter: settings.pacing?.jitter ?? 0,
+ ...(inputs.instagramHeld ? { instagramHeld: inputs.instagramHeld } : {}),
});
return {
now,
diff --git a/common/ytdlp/metadataScan.ts b/common/ytdlp/metadataScan.ts
@@ -14,6 +14,7 @@
// on a filtered channel, every one of those videos would otherwise be prefetched
// by the downloader on every run, forever.
+import { INSTAGRAM_YTDLP_REFUSAL, isInstagramComUrl } from "../lib/instagram/ytdlp";
import path from "node:path";
import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -93,6 +94,23 @@ const UNAVAILABLE_LINE = /video unavailable/i;
// video's own URL, falling back to yt-dlp's native id when there is no usable
// URL. Pure and exported so the divergence is testable without spawning
// anything.
+// THE IDS A BATCH FILE MAY HOLD: every one whose URL is not on instagram.com,
+// in the order asked (the pass's verdict reads that order), and the sentence
+// for the log when any was left out. yt-dlp is never started on an
+// instagram.com URL (lib/instagram/ytdlpRefusal.mjs), and a URL inside a
+// batch file is not in the argv that refusal reads.
+export function scanBatchIds(
+ asked: ReadonlyArray<string>,
+ urlOf: (id: string) => string,
+): { ids: string[]; leftOut: string | null } {
+ const ids = asked.filter((id) => !isInstagramComUrl(urlOf(id)));
+ const n = asked.length - ids.length;
+ return {
+ ids,
+ leftOut: n > 0 ? `${n} instagram.com URL(s) left out of this scan: ${INSTAGRAM_YTDLP_REFUSAL}\n` : null,
+ };
+}
+
export function canonicalScanId(record: {
id?: unknown;
webpage_url?: unknown;
@@ -418,16 +436,19 @@ export async function runMetadataScan(
// One pass over a batch file. Returns the ids it could not read as needs_auth,
// so the caller can decide whether a cookie retry is worth a second pass.
const runPass = async (
- ids: ReadonlyArray<string>,
+ asked: ReadonlyArray<string>,
cookies: string | undefined,
label: string,
): Promise<void> => {
+ // The batch file's URLs are not in the argv, so the argv's refusal
+ // (jitterSleepArgs) cannot see them: an instagram.com URL is left out of
+ // the batch here, and said (lib/instagram/ytdlpRefusal.mjs).
+ const urlOf = (id: string) => urlsById.get(id) ?? urlForId(id, channelConfig);
+ const { ids, leftOut } = scanBatchIds(asked, urlOf);
+ if (leftOut) opts.onLog(leftOut);
+ if (ids.length === 0) return;
const batchFile = path.join(tmpRoot, `${label}.batch`);
- await writeFile(
- batchFile,
- ids.map((id) => urlsById.get(id) ?? urlForId(id, channelConfig)).join("\n") +
- "\n",
- );
+ await writeFile(batchFile, ids.map(urlOf).join("\n") + "\n");
const args = [
"--ignore-config",
"--skip-download",
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,27 @@
# Changelog
## [Unreleased]
+- **An Instagram account can be archived as a posts channel.**
+ - An `instagram.com/<account>/` URL on the New channel form (or `pnpm ops create-channel`) makes one: posts and
+ reels with their text, date, link and media. A carousel is one post with several media.
+ - **A login is required, and it is the channel's own.** Logged out, Instagram shows no feed. The form asks for
+ **Cookies from browser** in the Source section and the channel never borrows the global browser; with none
+ set, a fetch is refused before a job exists. Use an account made for the archive: Instagram may checkpoint or
+ ban an account that reads this way.
+ - **Gentle by rule.** One Instagram job at a time, ten minutes apart, only as the editor's job and only on
+ Instagram's queue (the CLI's `posts fetch` refuses and names `pnpm ops fetch-posts`; a queue override is
+ refused). A sync reads one page; a walk reads up to 120 posts
+ and resumes. Nothing is retried: the first 429 (or one 401/403) holds Instagram for an hour; a login,
+ challenge or checkpoint page, or a second 401/403 in a row, raises Instagram's alert, which refuses every
+ Instagram job until **Recheck**. A run says what it cost in requests and files. A channel is synced every 12
+ hours at the most often; the scheduler skips one it could not fetch and says why. yt-dlp is never started
+ on an instagram.com URL.
+ - **Media come with the post**, in the same job, because their addresses expire: only from Instagram's CDN
+ hosts, a sync up to 40 files or 200 MB, a walk 120 files or 600 MB, 100 MB a file, into
+ `posts-media/<post id>/`. A walk leaves the posts whose media would not fit for its next run; what is still
+ not fetched is recorded as owed, and nothing is asked of the CDN after a refusal.
+ - **Private by default**: built only into private sites unless `social.instagram.visibility` is `"public"`.
+ - Stories, highlights, screenshots and transcription are not built yet. OPERATING.md, "Instagram accounts".
- **A trending library's topics can be organised, and a topic published.**
- **Rename** a topic, **move** posts between topics, **merge** topics into one: `pnpm ops organise-trending`, and
on umtool's Posts library page. A merge cannot be undone, so it is the operator's and asks twice; it waits
diff --git a/editor/app/api/ops/fetch-posts/route.ts b/editor/app/api/ops/fetch-posts/route.ts
@@ -44,6 +44,13 @@ export const dynamic = "force-dynamic";
// starts afresh at, replacing its saved position). The job runs on the platform's
// queue, as the buttons' does.
//
+// An Instagram channel (lane instagram): a sync reads one page, a walk up to
+// 120 posts, and the new posts' media are fetched in the same job. Refused
+// here, before a job exists, when the channel has no cookie source of its own
+// (`cookiesFromBrowser`), with `retryOnBlock`, and with a `queueKey` other
+// than platform:instagram (its jobs run one at a time, ten minutes apart, on
+// that queue and no other).
+//
// Every refusal is the action's own sentence: a channel that is not a social
// one, `full` and `older` together, a fetcher with no older walk, a floor
// without `older` or that is not a date, `force` without `older`, and an older
diff --git a/editor/app/api/ops/recheck-service/route.ts b/editor/app/api/ops/recheck-service/route.ts
@@ -4,12 +4,13 @@ import { ops, opsFail, reqString } from "../_lib";
export const dynamic = "force-dynamic";
-// POST { service: "rumble" | "youtube" | "odysee" | "archive.today" | "x" | <forum host> }
+// POST { service: "rumble" | "youtube" | "odysee" | "archive.today" | "x" | "instagram" | <forum host> }
//
// The cookie refresh banner's Recheck: ONE request through the service's own
// path (a yt-dlp metadata request for its last clean video; a forum page
// through the host's profile; archive.today's request again; for X no request
-// at all — the login on disk, renewed since the alert), as a one-step
+// at all — the login on disk, renewed since the alert; for Instagram no
+// request either — the operator's word that its check is passed), as a one-step
// job (kind `recheck-service-cookies`) the answer waits for:
// { ok, jobId, result: "clean" | "stale" | "failed", message }. "clean"
// clears the alert. A second ask while one runs for the service (a press, the
diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx
@@ -54,6 +54,9 @@ export type SocialChannelState = {
forumSession?: ForumSessionStatus;
// An X search channel (release 38): its query and where its walk stands.
search?: { query: string; walk: string };
+ // An Instagram channel (lane instagram): whether it has a cookie source of
+ // its own, without which nothing is fetched.
+ instagram?: { cookieSource: boolean };
// A TIMELINE's two walks (X, Bluesky; lib/timelineWalk.ts): Sync new, and
// Resume backfill when the full-history walk is part-way (`backfill`, its
// status line); `sync`, the line for a sync that stopped part-way. Absent on
@@ -241,6 +244,16 @@ export function SocialChannelPanel({
<Stat label="Older posts" value={state.olderStatus} />
)}
{state.search && <Stat label="Search walk" value={state.search.walk} />}
+ {state.instagram && (
+ <Stat
+ label="Cookie source"
+ value={
+ state.instagram.cookieSource
+ ? "set on this channel"
+ : "not set: nothing is fetched until Cookies from browser is set on the Edit form"
+ }
+ />
+ )}
</dl>
{state.availableFetchers.length > 1 && (
@@ -447,7 +460,9 @@ export function SocialChannelPanel({
role="status"
className="mt-3 rounded border border-warning/40 bg-warning-soft px-3 py-2 text-xs"
>
- {forum
+ {state.instagram
+ ? "Needs a login: Instagram shows an account's posts only to one. Set Cookies from browser on this channel's Edit form to a browser profile (or file:<cookies.txt>) logged in to Instagram, or log that one in again; if Instagram's alert is up, press Recheck on the dashboard after."
+ : forum
? "Needs the forum session: the forum showed a check (or a login) the headless browser could not get past. Use Connect forum session below, clear it in the window, close it, and fetch again."
: "Needs credentials: the fetcher could not authenticate. Configure cookies-from-browser for this channel (or globally) and re-run."}
{forum && (
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -25,6 +25,7 @@ import "yt-dlp-transcript-common/social/xGalleryDlFetcher";
import "yt-dlp-transcript-common/social/xPlaywrightFetcher";
import "yt-dlp-transcript-common/social/xNitterFetcher";
import "yt-dlp-transcript-common/social/xenforoFetcher";
+import "yt-dlp-transcript-common/social/instagramGalleryDlFetcher";
import { readForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession";
import { parseXenforoThreadUrl } from "yt-dlp-transcript-common/social/xenforoParse";
import {
@@ -329,6 +330,9 @@ export default async function ChannelDetailPage({
// X only: the capture's thread-shot option, at the channel's default.
...(config.platform === "twitter" ? { captureThread: config.postCaptureThread ?? false } : {}),
...(forumSession ? { forumSession } : {}),
+ ...(config.platform === "instagram"
+ ? { instagram: { cookieSource: Boolean(config.cookiesFromBrowser?.trim()) } }
+ : {}),
...(xSearch
? {
search: { query: xSearch.query, walk: describeXSearchWalk(fetchState?.search) },
diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts
@@ -1,5 +1,6 @@
"use server";
+import { INSTAGRAM_YTDLP_REFUSAL } from "yt-dlp-transcript-common/lib/instagram/ytdlp";
import { localMediaMetadataRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import { manualDownloadsRefusal } from "yt-dlp-transcript-common/lib/manualDownloads";
import { isSocialChannel, remoteOnlyRefusal } from "yt-dlp-transcript-common/lib/channelConfig";
@@ -606,6 +607,8 @@ export async function importVideoAction(
// (controller/archiveOrgDownload.ts) — and a file already on disk is not
// fetched again.
const urlPlatform = detectPlatform(videoUrl);
+ // An instagram.com URL is never handed to yt-dlp (lane instagram).
+ if (urlPlatform === "instagram") return { ok: false, error: INSTAGRAM_YTDLP_REFUSAL };
const archiveOrg = urlPlatform === "archiveorg";
// A BitChute URL likewise (controller/bitchuteImport.ts): canonicalized, run
// on BitChute's own queue with BitChute's args whatever the channel's
diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts
@@ -31,6 +31,7 @@ import { fakeXMediaFetch, fakeXProfileChromium } from "yt-dlp-transcript-common/
import { X_SEARCH_OLDER_REFUSAL } from "yt-dlp-transcript-common/controller/fetchXSearch";
import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts";
import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage";
+import { instagramQueueProblem, isInstagramPostsChannelConfig } from "yt-dlp-transcript-common/lib/instagram/channel";
import {
BACKFILL_AND_FULL_REFUSAL,
BACKFILL_AND_OLDER_REFUSAL,
@@ -38,6 +39,7 @@ import {
fetchPosts,
FORUM_BACKFILL_REFUSAL,
FULL_AND_OLDER_REFUSAL, OLDER_FROM_REFUSAL,
+ instagramFetchRefusal,
olderPostsProblem,
resumeBackfillProblem,
RETRY_AND_OLDER_REFUSAL,
@@ -141,6 +143,7 @@ async function registerBuiltinSocialFetchers(): Promise<void> {
await import("yt-dlp-transcript-common/social/xPlaywrightFetcher");
await import("yt-dlp-transcript-common/social/xNitterFetcher");
await import("yt-dlp-transcript-common/social/xenforoFetcher");
+ await import("yt-dlp-transcript-common/social/instagramGalleryDlFetcher");
}
// The posts analogue of the video availability check.
@@ -254,6 +257,18 @@ export async function fetchPostsAction(
if (isXTrendingChannel(config)) return { ok: false, info: true, error: X_TRENDING_NOT_FETCHED(slug) };
// Posts published from a private library: no account to fetch from.
if (isSourcelessPostsChannel(config)) return { ok: false, info: true, error: SOURCELESS_POSTS_CHANNEL(slug) };
+ // An Instagram channel (lane instagram): nothing is queued without a cookie
+ // source of its own, and its fetch is never retried on a block.
+ if (isInstagramPostsChannelConfig(config)) {
+ const refusal = instagramFetchRefusal(slug, config, { retryOnBlock: Boolean(retry) });
+ if (refusal) return { ok: false, error: refusal.error };
+ // On Instagram's queue and no other (review 2, N1). Every way a fetch of
+ // this channel is queued comes through here — the button, `pnpm ops
+ // fetch-posts` and resume-backfill, a Sync, the form's "Fetch posts now",
+ // a Retry or a replay — and the fetch itself asks again when it runs.
+ const queueProblem = instagramQueueProblem(slug, config, queueKey);
+ if (queueProblem) return { ok: false, error: queueProblem };
+ }
// An X search channel's one walk is its search windows (release 38).
if (older && isXSearchChannel(config)) return { ok: false, error: X_SEARCH_OLDER_REFUSAL };
if (backfill) {
diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts
@@ -105,6 +105,7 @@ async function registerBuiltinSocialFetchers(): Promise<void> {
await import("yt-dlp-transcript-common/social/xPlaywrightFetcher");
await import("yt-dlp-transcript-common/social/xNitterFetcher");
await import("yt-dlp-transcript-common/social/xenforoFetcher");
+ await import("yt-dlp-transcript-common/social/instagramGalleryDlFetcher");
}
export type ProbeChannelResult =
diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx
@@ -230,6 +230,10 @@ export function ChannelForm({
isWaybackPagesUrl(url) ||
platform === "x-search" ||
platform === "x-trending";
+ // An Instagram account (lane instagram): its cookie source is asked for in
+ // the Source section, because nothing is fetched without one.
+ const isInstagram =
+ isSocial && (platform === "instagram" || (!platform && detectPlatform(url) === "instagram"));
// An X search channel (release 38): a query across accounts, never on a site.
const isXSearch = isEdit ? Boolean(c?.xSearch) : !creatingLocal && platform === "x-search";
// An X trending library (lane x-trending): private, no URL, never on a site.
@@ -278,6 +282,7 @@ export function ChannelForm({
}
if (detected === "twitter" || detected === "x-search") setPostFetcher("x-gallery-dl");
else if (detected === "bluesky") setPostFetcher("bluesky-atproto");
+ else if (detected === "instagram") setPostFetcher("instagram-gallery-dl");
// A forum thread URL (…/threads/<title>.<id>/): the thread walker.
else if (detected === "xenforo") setPostFetcher("xenforo-thread");
else setPostFetcher("");
@@ -479,6 +484,7 @@ export function ChannelForm({
<option value="x-search">X search (posts from any account)</option>
<option value="x-trending">X trending library (private)</option>
<option value="bluesky">Bluesky (posts)</option>
+ <option value="instagram">Instagram (posts)</option>
<option value="xenforo">Forum thread — XenForo (posts)</option>
<option value="webpage">Archived pages (Wayback Machine, archive.today)</option>
</SeededSelect>
@@ -604,6 +610,7 @@ export function ChannelForm({
<option value="x-search">X search (posts from any account)</option>
<option value="x-trending">X trending library (private)</option>
<option value="bluesky">Bluesky (posts)</option>
+ <option value="instagram">Instagram (posts)</option>
<option value="xenforo">Forum thread — XenForo (posts)</option>
<option value="webpage">Archived pages (Wayback Machine, archive.today)</option>
</ControlledSelect>
@@ -733,6 +740,16 @@ export function ChannelForm({
{postFetcher ? ` Fetcher: ${postFetcher}.` : ""}
</span>
</label>
+ {isInstagram && (
+ <Field
+ label="Cookies from browser"
+ name="cookiesFromBrowser"
+ state={state}
+ defaultValue={c?.cookiesFromBrowser ?? ""}
+ placeholder="firefox:<profile> or file:/path/to/cookies.txt"
+ hint="Required. Instagram shows an account's posts only to a login, and this channel never borrows the global browser: blank means nothing is fetched. Name a browser profile, or file:<cookies.txt>, that is logged in to Instagram. Use an account made for the archive: Instagram may checkpoint or ban an account that reads this way, and the login named here is the one at risk. An archive account reads public accounts, and private ones only if it follows them. Posts are synced every 12 hours at the most often (4 hours with an interval set here), ten minutes apart from any other Instagram job."
+ />
+ )}
</>
)}
<SyncIntervalField
@@ -1147,6 +1164,8 @@ export function ChannelForm({
hint="For a channel that copies another creator's streams: the creator's channels here, by slug, separated by commas. The channel page then has a Mirror stage, where a scan pairs each video with the creator's and says which are the only copy left."
/>
<Fragment key={`cookies-${rumbleKey}`}>
+ {/* An Instagram channel's cookie source is in its Source section. */}
+ {!isInstagram && (
<Field
label="Cookies from browser"
name="cookiesFromBrowser"
@@ -1155,6 +1174,7 @@ export function ChannelForm({
placeholder="(inherit global)"
hint="Per-channel override of the global yt-dlp --cookies-from-browser browser spec (e.g. firefox, chrome:Default). Blank inherits the global value from /settings."
/>
+ )}
<label className="flex flex-col gap-1 text-sm">
<span className="font-medium">Cookie mode</span>
<SeededSelect
diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts
@@ -480,3 +480,26 @@ test("a stored library round-trips through the Configure form, and a patch sets
applyChannelFormPatch(fd, { xTrendingMaxScrolls: 5, xTrendingMaxPosts: "" });
assert.deepEqual(parseChannelForm(fd).config.xTrending, { maxScrolls: 5 });
});
+
+// An Instagram account (lane instagram): the platform, the kind and the handle
+// come from the URL alone, and the cookie source is the channel's own field.
+test("an instagram.com account URL makes a posts channel with its own cookie source", () => {
+ const { config } = parseChannelForm(
+ form({
+ handling: "transcribe",
+ url: "https://www.instagram.com/example.account/",
+ postFetcher: "instagram-gallery-dl",
+ cookiesFromBrowser: " firefox:instagram-archive ",
+ }),
+ );
+ assert.equal(config.platform, "instagram");
+ assert.equal(config.sourceKind, "social");
+ assert.equal(config.postFetcher, "instagram-gallery-dl");
+ assert.equal(config.socialHandle, "example.account");
+ assert.equal(config.cookiesFromBrowser, "firefox:instagram-archive");
+ // With no fetcher named the channel is still Instagram's, by its URL.
+ const bare = parseChannelForm(form({ handling: "transcribe", url: "https://www.instagram.com/example.account/" })).config;
+ assert.deepEqual([bare.platform, bare.sourceKind, bare.socialHandle], ["instagram", "social", "example.account"]);
+ // A post's URL names no account: refused, never a channel on someone's post.
+ assert.throws(() => parseChannelForm(form({ handling: "transcribe", url: "https://www.instagram.com/p/CabcDEF1234/" })));
+});
diff --git a/editor/app/operations/components/sync/SyncConsole.tsx b/editor/app/operations/components/sync/SyncConsole.tsx
@@ -282,6 +282,14 @@ export function SyncConsole({
type ChannelRow = SchedulerStatusPayload["channels"][number];
function statusBadge(c: ChannelRow) {
+ // Not scheduled though its settings would have it synced: say why.
+ if (c.heldReason) {
+ return (
+ <span className="text-warning" title={c.heldReason}>
+ held: {c.heldReason}
+ </span>
+ );
+ }
if (c.intervalMinutes === 0 || !c.autoSyncEligible) {
return <span className="text-muted-foreground">—</span>;
}
diff --git a/editor/app/scheduler/runTick.ts b/editor/app/scheduler/runTick.ts
@@ -4,6 +4,7 @@
// instrumentation.ts, both /api/scheduler/* routes, the operations rail's sync
// row and two forms import from it.
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { instagramHeldReason } from "yt-dlp-transcript-common/jobs/instagramGuard";
import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
@@ -13,6 +14,7 @@ import {
isInQuietHours,
nextEligibleAfterFailure,
selectDueChannels,
+ isInstagramPostsConfig,
type ChannelEntry,
} from "yt-dlp-transcript-common/jobs/syncScheduler";
import {
@@ -137,6 +139,8 @@ export async function runSchedulerTick(): Promise<SchedulerTickResult> {
priority,
// Each channel due up to pacing.jitter of its interval later (≤ 30 min).
jitter: pacingJitter(),
+ // Instagram's alert or cooldown: its channels take no slot while it is up.
+ instagramHeld: channels.some((c) => isInstagramPostsConfig(c.config)) ? await instagramHeldReason(paths) : null,
focusSlugs: resolveFocusSlugs(
priority,
siteChannels,
diff --git a/editor/app/scheduler/status.ts b/editor/app/scheduler/status.ts
@@ -6,6 +6,8 @@ import {
type SchedulerStatusPayload,
} from "yt-dlp-transcript-common/views/schedulerStatus";
import { readSchedulerState } from "yt-dlp-transcript-common/jobs/syncSchedulerState";
+import { instagramHeldReason } from "yt-dlp-transcript-common/jobs/instagramGuard";
+import { isInstagramPostsConfig } from "yt-dlp-transcript-common/jobs/syncScheduler";
import { resolveHeartbeatSeconds } from "./heartbeat";
// THE SHELL. The payload is `common/views/schedulerStatus.ts`; this reads the
@@ -26,5 +28,7 @@ export async function buildSchedulerStatusPayload(): Promise<SchedulerStatusPayl
state,
channels,
heartbeatSeconds: resolveHeartbeatSeconds(),
+ // Asked only when there is an Instagram channel to say it about.
+ instagramHeld: channels.some((c) => isInstagramPostsConfig(c.config)) ? await instagramHeldReason(paths) : null,
});
}
diff --git a/editor/app/settings/actions.ts b/editor/app/settings/actions.ts
@@ -35,7 +35,7 @@ import {
// The job-gap fields (SettingsForm's JOB_GAP_FIELDS): a value equal to the
// built-in is NOT stored, so a later change to a built-in reaches this
// install; every other key already set is kept.
-const JOB_GAP_FORM_KEYS = ["default", "twitter", "xenforo", "bluesky"] as const;
+const JOB_GAP_FORM_KEYS = ["default", "twitter", "xenforo", "bluesky", "instagram"] as const;
function parseJobGaps(
formData: FormData,
diff --git a/editor/app/settings/components/SettingsForm.tsx b/editor/app/settings/components/SettingsForm.tsx
@@ -24,13 +24,14 @@ import { YtdlpCookieFields } from "./YtdlpCookieFields";
import { jobGapSecondsFor } from "yt-dlp-transcript-common/lib/jobGap";
// The gaps this form edits (pacing.jobGapSeconds, plans/pacing-guard.md): the
-// default and the three platforms with a built-in of their own. Any other
+// default and the four platforms with a built-in of their own. Any other
// platform's key is set by hand in settings.json.
const JOB_GAP_FIELDS = [
{ key: "default", label: "Every platform" },
{ key: "twitter", label: "X" },
{ key: "xenforo", label: "Forums" },
{ key: "bluesky", label: "Bluesky" },
+ { key: "instagram", label: "Instagram" },
] as const;
import {
SocialLinksField,
diff --git a/editor/e2e/fixtures/bin/fake-gallery-dl-instagram.mjs b/editor/e2e/fixtures/bin/fake-gallery-dl-instagram.mjs
@@ -0,0 +1,178 @@
+// E2E fake gallery-dl, INSTAGRAM mode (lane instagram). Loaded by
+// fake-gallery-dl.mjs when the URL is on instagram.com.
+//
+// What the real binary (1.32.9) does with `--dump-json --verbose` and what the
+// fetcher reads (common/social/instagramGalleryDlFetcher.ts): request lines
+// and "Cursor:" lines on stderr; ONE JSON array on stdout when it exits, the
+// exception that ended the run as its last row; exit 0 whatever happened; on
+// SIGINT, what it has so far. Instagram is NEVER contacted, and every
+// account, id and address here is invented.
+//
+// The account in the URL picks the answer:
+// ig_loggedout a dead or missing session: the search answers 404, the
+// profile page 200, the feed 404 "Page Not Found"
+// ig_loginwall a redirect to the login page
+// ig_challenge a redirect to the challenge page
+// ig_ratelimited one page, then 429 on the next
+// ig_lookup429 the account search answers 429 — and, as the real binary
+// does (it swallows the lookup's exceptions), the run GOES ON
+// to the profile page and the feed unless it is stopped
+// ig_private a private account the login does not follow
+// ig_gone the search and the profile page both answer 404
+// anything else an account of 75 posts: two pinned on top (one of them
+// old), a carousel, a reel, pictures — in pages of 30, with
+// `extractor.instagram.max-posts` and `.cursor` honoured.
+// With no --cookies / --cookies-from-browser argument EVERY account answers
+// as ig_loggedout does: logged out, Instagram shows no feed.
+
+const PAGE = 30;
+const TOTAL = 75;
+const UID = "4000000001";
+const CDN = "https://cdn.example.invalid";
+
+const pk = (n) => (3500000000000000000n + BigInt(n)).toString();
+const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
+const shortcode = (id) => {
+ let n = BigInt(id);
+ let out = "";
+ while (n > 0n) {
+ out = ALPHABET[Number(n % 64n)] + out;
+ n /= 64n;
+ }
+ return out || "A";
+};
+const day = (n) => new Date(Date.UTC(2026, 0, 1) + n * 86_400_000).toISOString().slice(0, 19).replace("T", " ");
+
+// Post n of the account (n counts up with time), with its media kinds.
+function postOf(handle, n, opts = {}) {
+ const media = n % 10 === 0 ? ["image", "video", "image"] : n % 7 === 0 ? ["video"] : ["image"];
+ const id = pk(n);
+ const code = shortcode(id);
+ const type = media.length === 1 && media[0] === "video" ? "reel" : "post";
+ const post = {
+ category: "instagram",
+ subcategory: "posts",
+ post_id: id,
+ post_shortcode: code,
+ post_url: `https://www.instagram.com/${type === "reel" ? "reel" : "p"}/${code}/`,
+ type,
+ username: handle,
+ fullname: "Fake Instagram Account",
+ owner_id: UID,
+ description: `fake instagram post ${n} about zephyr archives`,
+ post_date: day(n),
+ date: day(n),
+ likes: n,
+ liked: false,
+ pinned: opts.pinned ? [Number(UID)] : [],
+ count: media.length,
+ };
+ const rows = [[2, post]];
+ media.forEach((kind, i) => {
+ const mediaId = pk(n * 100 + i + 1);
+ const ext = kind === "video" ? "mp4" : "jpg";
+ const url = `${CDN}/v/${mediaId}.${ext}?sig=invented`;
+ rows.push([
+ 3,
+ url,
+ { ...post, num: i + 1, media_id: mediaId, display_url: `${CDN}/v/${mediaId}.jpg?sig=invented`, video_url: kind === "video" ? url : null, extension: ext },
+ ]);
+ });
+ return rows;
+}
+
+// The grid, newest first: the two pinned posts on top, then every post by date.
+function grid(handle) {
+ const out = [postOf(handle, 3, { pinned: true }), postOf(handle, TOTAL - 5, { pinned: true })];
+ for (let n = TOTAL; n >= 1; n--) out.push(postOf(handle, n, { pinned: n === 3 || n === TOTAL - 5 }));
+ return out;
+}
+
+export async function runInstagram(args) {
+ const url = args[args.length - 1] ?? "";
+ const handle = /instagram\.com\/([^/?#]+)/i.exec(url)?.[1] ?? "nobody";
+ const opt = (key) => {
+ const hit = args.find((a) => a.startsWith(`extractor.instagram.${key}=`));
+ return hit ? hit.slice(`extractor.instagram.${key}=`.length) : undefined;
+ };
+ const loggedIn = args.includes("--cookies") || args.includes("--cookies-from-browser");
+ const maxPosts = Number(opt("max-posts") ?? Infinity);
+ const cursor = opt("cursor");
+ const rows = [];
+ const err = (line) => process.stderr.write(line + "\n");
+ const req = (path, status = 200) =>
+ err(`[urllib3.connectionpool][debug] https://www.instagram.com:443 "GET ${path} HTTP/1.1" ${status} ${status === 200 ? "None" : "20445"}`);
+ const dump = () => {
+ process.stdout.write(JSON.stringify(rows, null, 2) + "\n");
+ process.exit(0);
+ };
+ const fail = (error, message) => {
+ rows.push([-1, { error, message }]);
+ dump();
+ };
+ process.on("SIGINT", dump);
+ const feed = `/api/v1/feed/user/${UID}/?count=30`;
+ const feedUrl = `https://www.instagram.com${feed}`;
+
+ err("[gallery-dl][debug] Version 1.32.9");
+ if (!/extractor\.instagram\.retries=0/.test(args.join(" "))) {
+ // The fetcher must never let gallery-dl wait and ask again.
+ err("[fake][error] extractor.instagram.retries=0 was not passed");
+ process.exit(2);
+ }
+
+ if (!loggedIn || handle === "ig_loggedout") {
+ req(`/web/search/topsearch/?query=${handle}`, 404);
+ req(`/${handle}`, 200);
+ req(feed, 404);
+ fail("HttpError", `'404 Not Found' for '${feedUrl}'`);
+ }
+ if (handle === "ig_gone") {
+ req(`/web/search/topsearch/?query=${handle}`, 404);
+ req(`/${handle}`, 404);
+ fail("NotFoundError", "Requested user could not be found");
+ }
+ if (handle === "ig_lookup429") {
+ req(`/web/search/topsearch/?query=${handle}`, 429);
+ // What gallery-dl does next, a moment later: the profile page, then the feed.
+ await new Promise((r) => setTimeout(r, 1500));
+ req(`/${handle}`, 200);
+ } else req(`/web/search/topsearch/?query=${handle}`);
+ if (handle === "ig_loginwall") {
+ req(feed, 302);
+ fail("AbortExtraction", "HTTP redirect to login page (https://www.instagram.com/accounts/login/)");
+ }
+ if (handle === "ig_challenge") {
+ req(feed, 302);
+ fail("AbortExtraction", "HTTP redirect to challenge page (https://www.instagram.com/challenge/)");
+ }
+ if (handle === "ig_private") {
+ err(`[instagram][warning] ${handle}'s posts are private`);
+ req(feed);
+ dump();
+ }
+
+ const all = grid(handle);
+ const pages = [];
+ for (let i = 0; i < all.length; i += PAGE) pages.push(all.slice(i, i + PAGE));
+ let p = cursor ? Number(/^page-(\d+)$/.exec(cursor)?.[1] ?? 1) - 1 : 0;
+ let emitted = 0;
+ for (; p < pages.length; p++) {
+ if (handle === "ig_ratelimited" && p === 1) {
+ req(`${feed}&max_id=page-2`, 429);
+ fail("HttpError", `'429 Too Many Requests' for '${feedUrl}&max_id=page-2'`);
+ }
+ req(p === 0 ? feed : `${feed}&max_id=page-${p + 1}`);
+ for (const post of pages[p]) {
+ rows.push(...post);
+ emitted++;
+ // max-posts ends the run INSIDE the page that reached it, as the real
+ // extractor's islice does: no cursor is logged for a page it never
+ // left, and the next page is never asked for.
+ if (emitted >= maxPosts) dump();
+ }
+ // Logged when a page is LEFT, as the real extractor does.
+ if (p + 1 < pages.length) err(`[instagram][debug] Cursor: page-${p + 2}`);
+ }
+ dump();
+}
diff --git a/editor/e2e/fixtures/bin/fake-gallery-dl.mjs b/editor/e2e/fixtures/bin/fake-gallery-dl.mjs
@@ -18,6 +18,13 @@ const args = process.argv.slice(2);
// The account URL is the final positional argument.
const url = args[args.length - 1] ?? "";
+
+// INSTAGRAM (lane instagram): another extractor, another output shape — its
+// own module answers and exits.
+if (/instagram\.com/i.test(url)) {
+ const { runInstagram } = await import("./fake-gallery-dl-instagram.mjs");
+ await runInstagram(args);
+}
const handleMatch = /(?:x|twitter)\.com\/([^/?#]+)/i.exec(url);
const handle = handleMatch ? handleMatch[1] : "faketester";
diff --git a/editor/e2e/instagram.spec.ts b/editor/e2e/instagram.spec.ts
@@ -0,0 +1,315 @@
+// INSTAGRAM ACCOUNTS AS POSTS CHANNELS (lane instagram), end to end.
+//
+// Instagram is NEVER contacted. Every fetch runs against
+// e2e/fixtures/bin/fake-gallery-dl.mjs (its Instagram mode,
+// fake-gallery-dl-instagram.mjs), which prints what gallery-dl 1.32.9 prints
+// with `--dump-json --verbose`; the media CDN is played back by the test
+// server (common/social/instagramMedia.ts fakeInstagramMediaFetch). Every
+// account, id and address is invented.
+//
+// Same token as /api/ops/* (WORKER_TOKEN=test-worker-token on the test server).
+
+import { readFile, readdir } from "node:fs/promises";
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { generateReport, pathExists, readJson, resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { baseUrl } from "./baseUrl";
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const COOKIES = "file:/nonexistent/instagram-archive-cookies.txt";
+const pk = (n: number) => (3500000000000000000n + BigInt(n)).toString();
+const channelRel = (slug: string, p: string) => `${testPaths().transcriptsDir}/channels/${slug}/${p}`;
+
+type Answer = { status: number; body: { ok?: boolean; jobId?: string; error?: string; result?: string; message?: string; slug?: string } };
+
+async function ops(request: APIRequestContext, action: string, data: Record<string, unknown>): Promise<Answer> {
+ const res = await request.post(`${baseUrl}/api/ops/${action}`, { headers: AUTH, data });
+ return { status: res.status(), body: (await res.json()) as Answer["body"] };
+}
+
+async function waitJob(request: APIRequestContext, jobId: string, timeout = 90_000): Promise<string> {
+ let status = "";
+ await expect
+ .poll(
+ async () => {
+ const r = await request.get(`${baseUrl}/api/ops/job/${jobId}`, { headers: AUTH });
+ status = ((await r.json()) as { job?: { status?: string } }).job?.status ?? "";
+ return ["done", "failed", "cancelled"].includes(status);
+ },
+ { timeout },
+ )
+ .toBe(true);
+ return status;
+}
+
+const jobLog = (jobId: string) => readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${jobId}.log`), "utf8");
+
+async function archivedIds(slug: string): Promise<string[]> {
+ if (!(await pathExists(channelRel(slug, "posts-archive")))) return [];
+ // One line per post: "<platform> <id>".
+ return (await readFile(resolvePath(channelRel(slug, "posts-archive")), "utf8"))
+ .split("\n")
+ .filter(Boolean)
+ .map((l) => {
+ expect(l.startsWith("instagram ")).toBe(true);
+ return l.slice("instagram ".length);
+ });
+}
+
+async function makeChannel(request: APIRequestContext, slug: string, handle: string, cookies = true): Promise<void> {
+ const made = await ops(request, "create-channel", {
+ slug,
+ fields: {
+ name: `${handle} (Instagram)`,
+ handling: "transcribe",
+ url: `https://www.instagram.com/${handle}/`,
+ sourceKind: "social",
+ postFetcher: "instagram-gallery-dl",
+ },
+ });
+ expect(made.body).toMatchObject({ ok: true, slug });
+ if (cookies) {
+ const set = await ops(request, "channel-config", { slug, patch: { cookiesFromBrowser: COOKIES } });
+ expect(set.body.ok).toBe(true);
+ }
+}
+
+test("an Instagram URL derives a posts channel offline and asks for its cookie source in the Source section", async ({ page }) => {
+ await resetData("empty");
+ await generateReport(page, "new");
+ await page.goto("/channels/new");
+ await page.locator('input[name="url"]').fill("https://www.instagram.com/ig_fake/");
+ await expect(page.locator('select[name="platform"]')).toHaveValue("instagram");
+ await expect(page.locator('input[name="socialHandle"]')).toHaveValue("ig_fake");
+ await expect(page.locator('input[name="postFetcher"]')).toHaveValue("instagram-gallery-dl");
+ // No video controls, and ONE cookie field — required, and its help says the trade.
+ await expect(page.locator('select[name="audioFormat"]')).toHaveCount(0);
+ const cookies = page.locator('input[name="cookiesFromBrowser"]');
+ await expect(cookies).toHaveCount(1);
+ await expect(cookies).toBeVisible();
+ await expect(page.getByText(/Use an account made for the archive: Instagram may checkpoint or ban an account that reads this way/)).toBeVisible();
+ // A post's URL is not an account.
+ await page.locator('input[name="url"]').fill("https://www.instagram.com/p/CabcDEF1234/");
+ await expect(page.locator('input[name="socialHandle"]')).toHaveValue("");
+});
+
+test("no cookie source, nothing is asked; with one, a walk archives posts and their media, a capped walk resumes from its cursor, and a sync reads one page", async ({
+ page,
+ request,
+}) => {
+ test.setTimeout(240_000);
+ await resetData("empty");
+ await writeSettings({ minFreeDiskGB: 0, cookiesFromBrowser: "firefox", cookieMode: "always" });
+ const slug = "ig-fake";
+ await makeChannel(request, slug, "ig_fake", false);
+ const config = await readJson<Record<string, unknown>>(channelRel(slug, "config.json"));
+ expect(config).toMatchObject({ sourceKind: "social", platform: "instagram", postFetcher: "instagram-gallery-dl", socialHandle: "ig_fake" });
+
+ // The global browser is not borrowed: refused before a job exists.
+ const none = await ops(request, "fetch-posts", { slug });
+ expect(none.status).toBe(400);
+ expect(none.body.error).toMatch(/ig-fake has no cookie source of its own, and Instagram shows an account's posts only to a login/);
+ expect(none.body.error).toMatch(/Set "Cookies from browser" on the channel's Edit form/);
+ expect((await ops(request, "fetch-posts", { slug, retryOnBlock: { minutes: 30, max: 3 } })).body.error).toMatch(
+ /Retry on a block is not for Instagram/,
+ );
+ await generateReport(page, slug);
+ await page.goto(`/channels/${slug}`);
+ await expect(page.getByText("not set: nothing is fetched until Cookies from browser is set on the Edit form")).toBeVisible();
+
+ // Its own cookie source: the first fetch is a walk, capped here at 60 posts (two pages).
+ expect((await ops(request, "channel-config", { slug, patch: { cookiesFromBrowser: COOKIES } })).body.ok).toBe(true);
+ // On Instagram's queue and no other: a queue override would run it beside the job there, with no gap.
+ for (const action of ["fetch-posts", "resume-backfill"]) {
+ const side = await ops(request, action, { slug, queueKey: "side" });
+ expect(side.status).toBe(400);
+ expect(side.body.error).toMatch(/ig-fake is an Instagram channel: its jobs run on platform:instagram and nowhere else .*the queue override "side" is refused/);
+ }
+ const walk = await ops(request, "fetch-posts", { slug, limit: 60 });
+ expect(walk.body.ok).toBe(true);
+ expect(await waitJob(request, walk.body.jobId!)).toBe("done");
+ // 60 rows: the two pinned posts, then 58 by date — one of which is a pinned one again.
+ const first = await archivedIds(slug);
+ expect(first).toHaveLength(59);
+ expect(first).toContain(pk(3)); // the old pinned post, far below the walk's reach
+ const log = await jobLog(walk.body.jobId!);
+ // The cookie source is never printed.
+ expect(log).toContain("Instagram login: the channel's own cookie source, read by gallery-dl.");
+ expect(log).not.toContain("instagram-archive-cookies");
+ expect(log).toContain("Walking up to 60 posts from the top.");
+ expect(log).toContain("Cost: 3 request(s) to Instagram (1 for the account's id, 2 feed page(s)).");
+ // A walk's posts get their media in the same run: 71 files, inside its budget of 120.
+ expect(log).toMatch(/Media: 71 file\(s\) fetched from its CDN \(0 MB\); 59 of 59 post\(s\) whole\./);
+ expect(log).toContain("This run cost Instagram 3 request(s) and its CDN 71 file(s).");
+ expect(log).toContain("more history remains");
+ const state = await readJson<{ backfill?: { cursor?: string } }>(channelRel(slug, "posts-state.json"));
+ expect(state.backfill?.cursor).toBe("page-2");
+
+ // A carousel: one post, three media in order, a capture record, no screenshot.
+ const posts = (await readFile(resolvePath(channelRel(slug, "posts/2026-03.jsonl")), "utf8"))
+ .split("\n")
+ .filter(Boolean)
+ .map((l) => JSON.parse(l) as { id: string; platform: string; url: string; mediaCount?: number; instagram?: { kind: string; shortcode: string; pinned?: boolean }; media?: unknown });
+ const carousel = posts.find((p) => p.id === pk(70))!;
+ expect(carousel).toMatchObject({ platform: "instagram", mediaCount: 3, instagram: { kind: "post", pinned: true } });
+ expect(carousel.url).toBe(`https://www.instagram.com/p/${carousel.instagram!.shortcode}/`);
+ expect(carousel.media).toBeUndefined();
+ expect(JSON.stringify(posts)).not.toContain("cdn.example.invalid");
+ const files = (await readdir(resolvePath(channelRel(slug, `posts-media/${pk(70)}`)))).sort();
+ expect(files).toEqual([`01-${pk(7001)}.jpg`, `02-${pk(7002)}.mp4`, `03-${pk(7003)}.jpg`, "capture.json"]);
+ const record = await readJson<{ state: string; mediaState: string; shot?: unknown; media: unknown[] }>(
+ channelRel(slug, `posts-media/${pk(70)}/capture.json`),
+ );
+ expect(record).toMatchObject({ state: "captured", mediaState: "ok" });
+ expect(record.shot).toBeUndefined();
+ expect(record.media).toHaveLength(3);
+ // A reel is one video.
+ expect(posts.find((p) => p.id === pk(63))?.instagram?.kind).toBe("reel");
+
+ // capture-posts takes no screenshot of an Instagram post, and says so.
+ const shot = await ops(request, "capture-posts", { slug, ids: [pk(70)] });
+ expect(shot.body.error).toMatch(/takes no screenshot of an Instagram post/);
+
+ // RESUME BACKFILL: from the cursor, re-reading that one page; fewer posts than asked for ends the walk.
+ const resume = await ops(request, "fetch-posts", { slug, backfill: true, limit: 60 });
+ expect(resume.body.ok).toBe(true);
+ expect(await waitJob(request, resume.body.jobId!)).toBe("done");
+ expect(await archivedIds(slug)).toHaveLength(75);
+ const resumeLog = await jobLog(resume.body.jobId!);
+ expect(resumeLog).toContain("Walking up to 60 posts from the saved resume point.");
+ expect(resumeLog).toContain("Cost: 3 request(s) to Instagram (1 for the account's id, 2 feed page(s)).");
+ expect((await readJson<{ backfill?: unknown }>(channelRel(slug, "posts-state.json"))).backfill).toBeUndefined();
+
+ // SYNC NEW: one page, the pinned posts skipped, stopped at the first archived post.
+ await page.goto(`/channels/${slug}`);
+ await expect(page.getByText("set on this channel")).toBeVisible();
+ const sync = await ops(request, "fetch-posts", { slug });
+ expect(sync.body.ok).toBe(true);
+ expect(await waitJob(request, sync.body.jobId!)).toBe("done");
+ const syncLog = await jobLog(sync.body.jobId!);
+ expect(syncLog).toContain("Reading one page (up to 30 posts) from the top.");
+ expect(syncLog).toContain("Wrote 0 new post(s)");
+ expect(syncLog).toContain("This run cost Instagram 2 request(s) and its CDN 0 file(s).");
+ expect(await archivedIds(slug)).toHaveLength(75);
+});
+
+test("a dead session, a challenge and a login page raise Instagram's alert, which refuses every Instagram job until a person's Recheck", async ({
+ page,
+ request,
+}) => {
+ test.setTimeout(240_000);
+ await resetData("empty");
+ await writeSettings({ minFreeDiskGB: 0 });
+ await makeChannel(request, "ig-dead", "ig_loggedout");
+ await makeChannel(request, "ig-check", "ig_challenge");
+ await makeChannel(request, "ig-wall", "ig_loginwall");
+ await makeChannel(request, "ig-ok", "ig_fake");
+
+ // The session is not accepted: the search's and the feed's "Page Not Found" are the login, not a gone account.
+ const dead = await ops(request, "fetch-posts", { slug: "ig-dead" });
+ expect(await waitJob(request, dead.body.jobId!)).toBe("failed");
+ const deadLog = await jobLog(dead.body.jobId!);
+ expect(deadLog).toContain("Cost: 3 request(s) to Instagram (2 for the account's id, 1 feed page(s)).");
+ expect(deadLog).toMatch(/Instagram did not accept the login .*HttpError: '404 Not Found'/);
+ expect(deadLog).not.toMatch(/has no account/);
+
+ // Every Instagram job is refused now, before it exists.
+ const refused = await ops(request, "fetch-posts", { slug: "ig-ok" });
+ expect(refused.status).toBe(400);
+ expect(refused.body.error).toMatch(/^Instagram answered with its login page at \d\d:\d\d UTC .*its alert is up, so no Instagram job starts/);
+
+ // The banner, and the operator's Recheck (no request to Instagram).
+ await page.goto(`${baseUrl}/`);
+ const banner = page.getByRole("alert", { name: "Instagram cookies" });
+ await expect(banner).toContainText("Instagram needs fresh cookies: pass Instagram's check by hand");
+ await expect(banner).toHaveAttribute("data-state", "stale");
+ await banner.getByRole("button", { name: "Recheck" }).click();
+ await expect(banner).toHaveAttribute("data-state", "ok-again", { timeout: 30_000 });
+
+ // A challenge page: the same alert, as a challenge.
+ const check = await ops(request, "fetch-posts", { slug: "ig-check" });
+ expect(check.body.ok).toBe(true);
+ expect(await waitJob(request, check.body.jobId!)).toBe("failed");
+ expect(await jobLog(check.body.jobId!)).toMatch(/Instagram answered with a challenge or checkpoint page/);
+ expect((await ops(request, "fetch-posts", { slug: "ig-ok" })).body.error).toMatch(/a challenge or checkpoint page at \d\d:\d\d UTC/);
+ const recheck = await ops(request, "recheck-service", { service: "instagram" });
+ expect(recheck.body).toMatchObject({ ok: true, result: "clean" });
+ expect(recheck.body.message).toMatch(/no request sent/);
+
+ // A redirect to the login page.
+ const wall = await ops(request, "fetch-posts", { slug: "ig-wall" });
+ expect(await waitJob(request, wall.body.jobId!)).toBe("failed");
+ expect((await ops(request, "fetch-posts", { slug: "ig-ok" })).status).toBe(400);
+ expect((await ops(request, "recheck-service", { service: "instagram" })).body.result).toBe("clean");
+
+ // Cleared: the good account is read.
+ const ok = await ops(request, "fetch-posts", { slug: "ig-ok", limit: 60 });
+ expect(ok.body.ok).toBe(true);
+ expect(await waitJob(request, ok.body.jobId!)).toBe("done");
+});
+
+test("the first 429 ends the run and holds Instagram for an hour; a private account and a gone account are a sentence each", async ({ request }) => {
+ test.setTimeout(240_000);
+ await resetData("empty");
+ await writeSettings({ minFreeDiskGB: 0 });
+ await makeChannel(request, "ig-private", "ig_private");
+ await makeChannel(request, "ig-gone", "ig_gone");
+ await makeChannel(request, "ig-limited", "ig_ratelimited");
+ await makeChannel(request, "ig-lookup", "ig_lookup429");
+ await makeChannel(request, "ig-ok", "ig_fake");
+
+ const priv = await ops(request, "fetch-posts", { slug: "ig-private" });
+ expect(await waitJob(request, priv.body.jobId!)).toBe("failed");
+ expect(await jobLog(priv.body.jobId!)).toMatch(/@ig_private is a private account and this channel's login does not follow it/);
+
+ const gone = await ops(request, "fetch-posts", { slug: "ig-gone" });
+ expect(await waitJob(request, gone.body.jobId!)).toBe("failed");
+ expect(await jobLog(gone.body.jobId!)).toMatch(/Instagram has no account @ig_gone: its own page answered 404/);
+ // Neither is the login's fault: no alert, the next job is not refused.
+
+ const limited = await ops(request, "fetch-posts", { slug: "ig-limited" });
+ expect(limited.body.ok).toBe(true);
+ expect(await waitJob(request, limited.body.jobId!)).toBe("failed");
+ const log = await jobLog(limited.body.jobId!);
+ expect(log).toMatch(/Instagram refused the read \(GET \/api\/v1\/feed\/user\/\d+\/ answered 429\): a rate limit/);
+ // After a refusal nothing more is asked of Instagram, its CDN included: the posts are archived, their media owed.
+ expect(log).toMatch(/Media: none asked for\. Instagram refused the listing, so its CDN is not asked either; \d+ post\(s\) are archived with their media owed/);
+ expect(log).toMatch(/This run cost Instagram 3 request\(s\) and its CDN 0 file\(s\)\./);
+ const limitedIds = await archivedIds("ig-limited");
+ const owed = await readJson<{ mediaState: string; mediaOwed?: string; media: unknown[] }>(
+ channelRel("ig-limited", `posts-media/${limitedIds[0]}/capture.json`),
+ );
+ expect(owed).toMatchObject({ mediaState: "error", mediaOwed: "next", media: [] });
+ expect(log).toMatch(/no Instagram job starts before \d\d:\d\d UTC \(60 min\)\. Nothing retries by itself\./);
+ // What the first page held is archived, with the resume point for the page that was refused.
+ expect((await archivedIds("ig-limited")).length).toBeGreaterThan(20);
+ expect((await readJson<{ backfill?: { cursor?: string } }>(channelRel("ig-limited", "posts-state.json"))).backfill?.cursor).toBe("page-2");
+
+ // Held: refused before a job exists, whichever Instagram channel asks.
+ const held = await ops(request, "fetch-posts", { slug: "ig-ok" });
+ expect(held.status).toBe(400);
+ expect(held.body.error).toMatch(/^Instagram answered a rate limit a short while ago: no Instagram job starts before \d\d:\d\d UTC/);
+
+ // The operator's way out, by hand (the test server's state is shared by the specs after this one).
+ const cleared = await ops(request, "clear-platform-hold", { platform: "instagram" });
+ expect(cleared.body.ok).toBe(true);
+ const after = await ops(request, "fetch-posts", { slug: "ig-ok", limit: 60 });
+ expect(after.body.ok).toBe(true);
+ expect(await waitJob(request, after.body.jobId!)).toBe("done");
+
+ // A 429 DURING THE ACCOUNT LOOKUP: gallery-dl swallows it and would go on to the feed. The run is stopped at that
+ // line — one request — and Instagram is held, as for any 429.
+ const lookup = await ops(request, "fetch-posts", { slug: "ig-lookup" });
+ expect(lookup.body.ok).toBe(true);
+ expect(await waitJob(request, lookup.body.jobId!)).toBe("failed");
+ const lookupLog = await jobLog(lookup.body.jobId!);
+ expect(lookupLog).toContain("Cost: 1 request(s) to Instagram (1 for the account's id, 0 feed page(s)).");
+ expect(lookupLog).toMatch(/Instagram refused the read \(GET \/web\/search\/topsearch\/ answered 429\): a rate limit/);
+ expect(await archivedIds("ig-lookup")).toHaveLength(0);
+ expect((await ops(request, "fetch-posts", { slug: "ig-ok" })).body.error).toMatch(/^Instagram answered a rate limit a short while ago/);
+ expect((await ops(request, "clear-platform-hold", { platform: "instagram" })).body.ok).toBe(true);
+
+ // yt-dlp is never started on an instagram.com URL: import-video says so before a job exists.
+ const reel = await ops(request, "import-video", { slug: "ig-ok", url: "https://www.instagram.com/reel/CabcDEF1234/" });
+ expect(reel.status).toBe(400);
+ expect(reel.body.error).toMatch(/Instagram is read as a posts channel; a single reel import comes with a later slice/);
+});
diff --git a/mcp/src/server.ts b/mcp/src/server.ts
@@ -517,11 +517,11 @@ export const TOOLS: Tool[] = [
},
platforms: {
type: "array",
- items: { type: "string", enum: ["twitter", "bluesky", "xenforo", "webpage"] },
+ items: { type: "string", enum: ["twitter", "bluesky", "xenforo", "webpage", "instagram"] },
description:
"Keep only POST hits on these platforms: 'twitter', 'bluesky', " +
"'xenforo' (forum threads), 'webpage' (Wayback Machine page " +
- "captures). Absent = every platform. Video hits are not narrowed — " +
+ "captures), 'instagram'. Absent = every platform. Video hits are not narrowed — " +
"add content_types:['post'] for posts only.",
},
link_style: {
@@ -2249,7 +2249,7 @@ async function handleGetTranscripts(
}
// search_transcripts' `platforms`: the post platforms named, or undefined.
-const POST_PLATFORM_ARGS = new Set(["twitter", "bluesky", "xenforo", "webpage"]);
+const POST_PLATFORM_ARGS = new Set(["twitter", "bluesky", "xenforo", "webpage", "instagram"]);
function postPlatformsArg(raw: unknown): string[] | undefined {
if (!Array.isArray(raw)) return undefined;
const out = raw.filter((p): p is string => typeof p === "string" && POST_PLATFORM_ARGS.has(p));
diff --git a/plans/instagram.md b/plans/instagram.md
@@ -0,0 +1,101 @@
+# Instagram accounts as posts channels
+
+Lane `lane/instagram`, begun 18 Nov 2026. Guide: OPERATING.md, "Instagram accounts".
+
+## The ask
+
+An Instagram account becomes a posts channel, as an X account is: posts with their text, images, videos and
+reels, carousels, dates and links; and stories, which vanish in 24 h. Research reads and cites them like any
+post; video with speech should be transcribable.
+
+## Rulings
+
+These are rulings, not reasons. A later ruling overturns an earlier one only when it says so.
+
+**Safety**
+
+- All Instagram traffic goes through the editor's Instagram queue (`platform:instagram`): one job at a time,
+ ten minutes apart, only as the editor's own job. Never a burst, never a retry.
+- A login is required: logged out, the feed answers "Page Not Found" (one read, 18 Nov 2026). The cookie source
+ is the channel's own `cookiesFromBrowser`, never the global browser. The operator will use an account made
+ for the archive. Nothing logs in or refreshes a session unattended.
+- The first 429 ends the run and holds Instagram for 60 minutes. One 401/403 does the same; a second in a row
+ with no clean read between raises the alert. A login, challenge or checkpoint page raises Instagram's alert,
+ which refuses every Instagram job until a person's Recheck (no request). The recheck timer never asks.
+- After a refusal in the listing no media is asked for: everything Instagram stops, its CDN too.
+- A request line is read as it arrives: a refusal during the account lookup ends the run (gallery-dl swallows
+ it). Posts with no request line read are a failure.
+- A logged-out 404 on the search or the feed is the login, never "account gone". An account is gone only when
+ its own page answered 404.
+- yt-dlp is never started on an instagram.com URL (slice 1). A single reel's import is a later slice's.
+- Development and tests use invented fixtures and the fake gallery-dl. No test opens a socket.
+
+**The store**
+
+- A post's id is its numeric media pk; the shortcode is kept in `Post.instagram` and converts both ways.
+- A carousel is one post with several media; a reel is one video. A collaboration's author is the owner; the
+ channel's account is among `coauthors`.
+- Media are fetched in the fetch job (their addresses expire): only from `.cdninstagram.com` / `.fbcdn.net`, no
+ cookies, no referer, `Mozilla/5.0`. A sync: 40 files / 200 MB. A walk: 120 files / 600 MB, and it lists no
+ more posts than that, leaving the posts whose media would not fit for the next run. A file: 100 MB.
+- `posts-media/` is not in the media tier.
+- Instagram posts are private unless `social.instagram.visibility` is `"public"`, by X's rule shape. A Wayback
+ pages channel scoped to instagram.com follows it. Stories are never public.
+
+## Slice 1, as built (fetcher, store, channel, ops)
+
+- Platform `instagram`: `common/lib/instagram/` (ids, the yt-dlp refusal), `Post.instagram`, the job gap,
+ the visibility rule, the per-platform guard table (`common/jobs/networkGuard.ts PLATFORM_GUARDS`,
+ `instagramGuard.ts`), the service alert.
+- Fetcher `instagram-gallery-dl` (`common/social/instagramGalleryDlFetcher.ts`, `instagramSignals.ts`,
+ `instagramNormalize.ts`), media (`instagramMedia.ts`), the controller's part (`controller/fetchPosts.ts`).
+- gallery-dl runs with `--dump-json` and NOT `output.jsonl`: with it on, the exception that ended a run is
+ printed nowhere and the run exits 0. A stopped run is stopped with SIGINT, which prints what it has.
+- Sync new: one page. A walk: 120 posts, then the cursor. A sync whose page is all new continues from the
+ top down to its watermark, skipping what it archived.
+- The scheduler: every 12 h at the most often (4 h with an interval of its own); no slot for a channel with no
+ cookie source or while Instagram is held; a restart never re-queues an Instagram job.
+- The channel form asks for the cookie source in the Source section. `capture-posts`, `retryOnBlock`, the
+ older walk and the deleted-posts sweep refuse an Instagram channel by name.
+- Tests: `common/lib/instagram/*.test.ts`, `common/social/instagram*.test.ts`,
+ `common/jobs/instagram*.test.ts`, `editor/e2e/instagram.spec.ts` with
+ `editor/e2e/fixtures/bin/fake-gallery-dl-instagram.mjs`.
+
+**Review 2 (18 Nov), as fixed.** N1 a queue override ran an Instagram fetch beside the one on its queue: the
+action refuses any queue but `platform:instagram`, and the fetch refuses when its job is on another (the job
+context carries the queue). N2 a trimmed walk resumes from its own start (no page size assumed). N3 the walls
+are path segments, never a word in a handle. N4 no request line read is a failure whatever was printed. N5 the
+fetcher must match the URL's platform too. N6 a stopped run is not a clean read. N7 one predicate for "an
+Instagram channel" (`common/lib/instagram/channel.ts`). N8 the yt-dlp refusal is in the shared `jitter.mjs`
+(umtool's scripts too) and a metadata scan's batch file.
+
+**Review 1 (18 Nov), as fixed.** M1 a continuing sync dropped the gap (it stopped at its own posts); M2 a
+refusal during the lookup did not end the run; M3 the CLI's `posts fetch` ran past the guard, and a fetcher
+of another platform could. S1–S13: digits inside captions, no media after a refusal, the media half's
+deadline, host allowlist, User-Agent, write errors, a walk sized to its media, the second 401/403, private
+before the error row, the scheduler's skips, yt-dlp refused, Wayback captures and tombstones, the cookie
+source out of the log.
+
+## Slice 2 (not built): stories, the cookie row, owed media
+
+- `fetch-stories` on the same queue, a per-channel switch with its own interval (off by default), and a timer
+ armed below the idle gate. Stories need the login; a story deleted before the next read is missed.
+- A row on /cookies and a jar of its own with an age rule; nothing refreshes it unattended.
+- **The owed-media collector**: `capture-posts` for Instagram (media only, one request per post for fresh
+ addresses). Slice 1 records `mediaOwed` and collects nothing.
+- An ops read of what an Instagram job would be told now (the alert, the hold), as `get x-session` is for X.
+
+## Slice 3 (not built): viewer, export, transcription
+
+- PostBody: a kind badge, a carousel, a story's expiry. Published captures for a public Instagram channel.
+- `import-post` for one Instagram URL; a single reel's import (through the fetcher, never yt-dlp).
+- Highlights, by hand.
+- Transcription of a post's video: nothing transcribes `posts-media/` today, for any platform.
+- The deleted-posts sweep.
+
+## Open
+
+- A logged-in probe (the fetcher's own argv, 3 posts) has not been run: the row shape, the page size, the
+ cursor line and the CDN hosts are from gallery-dl 1.32.9's source.
+- A `--cookies-from-browser` spec that yields no session is not detected before the run: it costs three
+ requests logged out, then raises the alert.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1520,12 +1520,17 @@ export function usage() {
"",
'recheck-service asks a service whose cookie refresh alert is up ONE request',
' through its own path, as the dashboard banner\'s Recheck: {"service"}',
- ' ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host).',
+ ' ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a',
+ ' forum host).',
' Waits for it: {jobId, result: "clean" | "stale" | "failed", message};',
" \"clean\" clears the alert (and a yt-dlp service's backoff, as any clean",
' request). For "x" it sends X NO request: clean when the login on disk',
' was renewed after the alert (Refresh cookies on /cookies) — for a',
' jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The',
+ ' For "instagram" it sends Instagram NO request either and is the',
+ " operator's word that its check is passed: it clears the alert, and the",
+ " next Instagram job raises it again if it was not. The timer never asks",
+ ' Instagram. The',
' editor also rechecks by itself on a timer',
' (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off;',
' `pnpm ops settings',
@@ -1942,7 +1947,19 @@ export function usage() {
' in settings) waits out a challenge or refusal page and runs again, max',
' tries in all. "full", "older" and "backfill" are one at a time. An',
' older walk over an account that shows no posts (nothing archived, and',
- ' the last timeline fetch read none) is refused unless "force": true. A',
+ ' the last timeline fetch read none) is refused unless "force": true.',
+ " AN INSTAGRAM CHANNEL: a sync reads ONE page (up to 30 posts), a first",
+ ' fetch, "full" or "backfill" walks up to 120 posts and the next run',
+ " resumes; the new posts' pictures and videos are fetched in the same job",
+ " (a sync 40 files / 200 MB, a walk 120 / 600 MB, 100 MB a file; a walk",
+ " leaves the posts whose media would not fit for its next run; what is",
+ " still not fetched is recorded as owed, and none after a refusal).",
+ " Refused before a job exists when the channel has no cookiesFromBrowser",
+ ' of its own, with "retryOnBlock" or "older", and with a "queueKey" other',
+ " than platform:instagram. A login, challenge or",
+ " checkpoint page raises Instagram's alert and refuses every Instagram job",
+ " until recheck-service; the first 429 holds Instagram for an hour",
+ ' (clear-platform-hold {"platform": "instagram"} ends that by hand). A',
" drained fetch stops at its next resume point and the next run of the",
" same walk resumes there.",
"",
@@ -2142,6 +2159,8 @@ export function usage() {
' through gallery-dl (a forum thread: the same profile; Bluesky: its images',
' from the CDN), into the channel\'s posts-media/<id>/:',
' {"slug", "ids": [...]}. Every id must be in the channel\'s posts archive.',
+ " An Instagram channel is refused: no screenshot is taken of an Instagram",
+ " post, and its media come with the post, in the fetch-posts job.",
' "shots": false or "media": false skips that half; posts already captured',
' are skipped unless "force": true. A post that links to an X Article also',
' gets the article (article.json, .md, .png and its images) unless',
diff --git a/umtool/lib/research/case-leads.ts b/umtool/lib/research/case-leads.ts
@@ -108,7 +108,7 @@ const nameHash = (c: Pick<LeadCandidate, "name">) => privateNameHash(c.name.repl
export type PostsChannel = { slug: string; name: string; platform: string; inScope: boolean };
-const SOCIAL_PLATFORMS = new Set(["xenforo", "twitter", "bluesky", "webpage", "x-search"]);
+const SOCIAL_PLATFORMS = new Set(["xenforo", "twitter", "bluesky", "webpage", "instagram", "x-search"]);
async function configOf(slug: string): Promise<Record<string, unknown> | null> {
if (!/^[A-Za-z0-9_.@-]+$/.test(slug)) return null;
diff --git a/umtool/lib/research/case-verify.ts b/umtool/lib/research/case-verify.ts
@@ -187,7 +187,7 @@ async function sourceOf(caseId: string): Promise<string> {
async function postTrack(f: FindingRow, hashes: string[]): Promise<CaptionTrack | null> {
const platform = await channelPlatform(f.slug);
- if (!platform || !["xenforo", "twitter", "bluesky", "webpage"].includes(platform)) return null;
+ if (!platform || !["xenforo", "twitter", "bluesky", "webpage", "instagram"].includes(platform)) return null;
const posts = await readAllPosts(path.join(/* turbopackIgnore: true */ CHANNELS_DIR, f.slug)).catch(() => []);
const p = posts.find((x) => x.id === f.id);
if (!p) return null;
diff --git a/umtool/report-to-video/instagram-ytdlp.test.mjs b/umtool/report-to-video/instagram-ytdlp.test.mjs
@@ -0,0 +1,12 @@
+// yt-dlp is never started on an instagram.com URL (lane instagram): the pass
+// umtool's scripts hand every yt-dlp argv through throws, so no process starts.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { jitterSleepArgs } from "yt-dlp-transcript-common/lib/jitter.mjs";
+import { INSTAGRAM_YTDLP_REFUSAL } from "yt-dlp-transcript-common/lib/instagram/ytdlpRefusal.mjs";
+
+test("the argv pass check-availability and build-video use refuses an instagram.com URL", () => {
+ assert.throws(() => jitterSleepArgs(["--simulate", "--no-warnings", "https://www.instagram.com/reel/CabcDEF1234/"]), new Error(INSTAGRAM_YTDLP_REFUSAL));
+ assert.throws(() => jitterSleepArgs(["-f", "b", "--download-sections", "*10-20", "--", "https://instagram.com/p/CabcDEF1234/"]), /Instagram is read as a posts channel/);
+ assert.deepEqual(jitterSleepArgs(["--simulate", "https://www.youtube.com/watch?v=aaaaaaaaaaa"], 0), ["--simulate", "https://www.youtube.com/watch?v=aaaaaaaaaaa"]);
+});