Archilyzer · Source

archilyzer

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

commit 4e6077b3b94ddfdf9f948c9d44604454bfcc71c2
parent dbb9bddb21f3b88f562fabd3005292ab766d7df3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 14:10:20 -0500

channels: an Instagram account is made from the channel form, and says where its cookie source goes

The form derives the platform, the handle and the fetcher from an
instagram.com account URL and asks for "Cookies from browser" in the Source
section: required, the channel's own, with the trade of an archive account in
its help. A fetch with none is refused before a job exists, as is a retry on a
block; the channel page says whether the source is set. An Instagram channel is
synced every 12 hours at the most often (4 with an interval of its own). The
fake gallery-dl answers instagram.com in its own module: a dead session, a
login page, a challenge, a 429, a private account, a gone account, and an
account of 75 posts with pinned posts, a carousel, reels and a cursor.

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

Diffstat:
Mcommon/controller/capturePosts.ts | 8++++----
Mcommon/controller/fetchPosts.ts | 21+++++++++++++++------
Acommon/jobs/instagramSyncInterval.test.ts | 35+++++++++++++++++++++++++++++++++++
Mcommon/jobs/syncScheduler.ts | 16+++++++++++++++-
Meditor/app/channels/[slug]/components/SocialChannelPanel.tsx | 17++++++++++++++++-
Meditor/app/channels/[slug]/page.tsx | 4++++
Meditor/app/channels/[slug]/socialActions.ts | 8++++++++
Meditor/app/channels/actions.ts | 1+
Meditor/app/channels/components/ChannelForm.tsx | 20++++++++++++++++++++
Meditor/app/settings/actions.ts | 2+-
Meditor/app/settings/components/SettingsForm.tsx | 3++-
Aeditor/e2e/fixtures/bin/fake-gallery-dl-instagram.mjs | 167+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/fixtures/bin/fake-gallery-dl.mjs | 7+++++++
Aeditor/e2e/instagram.spec.ts | 273+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
14 files changed, 568 insertions(+), 14 deletions(-)

diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -171,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.`; @@ -247,8 +248,8 @@ export function strayIdsRefusal(slug: string, stray: string[]): string { // needs a login, and a logged-in page load is the request most likely to get // the account checked — and a post's media are fetched by the job that // fetches the post, because their addresses expire. -export const INSTAGRAM_NO_CAPTURE = (slug: string) => - `${slug} is an Instagram channel: capture-posts takes no screenshot of an Instagram post (its page needs a login), ` + +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. @@ -291,7 +292,6 @@ export async function capturePosts( const fetcher = library ? (getSocialFetcher(config.postFetcher) ?? getSocialFetcher(X_LIBRARY_FETCHER)) : resolveSocialFetcher(config.postFetcher, accountUrl); - if (fetcher?.platform === "instagram") return fail(INSTAGRAM_NO_CAPTURE(slug)); const problem = capturePostsProblem(fetcher); if (problem || !fetcher?.captureByIds) return fail(problem ?? "This channel has no post fetcher."); const avatarsOnly = opts.avatarsOnly === true; diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -177,6 +177,19 @@ export function instagramCookieSource(config: { cookiesFromBrowser?: string } | return config?.cookiesFromBrowser?.trim() || undefined; } +// 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 = @@ -386,12 +399,8 @@ export async function fetchPosts( } if (fetcher.platform === "instagram") { - if (opts.retryOnBlock) { - return { ok: false, written: 0, skipped: 0, complete: false, error: INSTAGRAM_RETRY_REFUSAL }; - } - if (!instagramCookieSource(config)) { - return { ok: false, written: 0, skipped: 0, complete: false, needsCookies: true, error: INSTAGRAM_NO_COOKIES(slug) }; - } + const refusal = instagramFetchRefusal(slug, config, { retryOnBlock: Boolean(opts.retryOnBlock) }); + if (refusal) return { ok: false, written: 0, skipped: 0, complete: false, ...refusal }; } const seenIds = await readSeenPostIds(channelRoot); 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/syncScheduler.ts b/common/jobs/syncScheduler.ts @@ -65,12 +65,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 = config.sourceKind === "social" && config.platform === "instagram"; 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; } 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]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -38,6 +38,7 @@ import { fetchPosts, FORUM_BACKFILL_REFUSAL, FULL_AND_OLDER_REFUSAL, OLDER_FROM_REFUSAL, + instagramFetchRefusal, olderPostsProblem, resumeBackfillProblem, RETRY_AND_OLDER_REFUSAL, @@ -141,6 +142,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 +256,12 @@ 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 (config.platform === "instagram") { + const refusal = instagramFetchRefusal(slug, config, { retryOnBlock: Boolean(retry) }); + if (refusal) return { ok: false, error: refusal.error }; + } // 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/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,167 @@ +// 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_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"); + } + 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]) { + if (emitted >= maxPosts) dump(); + rows.push(...post); + emitted++; + } + // 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,273 @@ +// 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 []; + return (await readFile(resolvePath(channelRel(slug, "posts-archive")), "utf8")).split("\n").filter(Boolean); +} + +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); + 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!); + expect(log).toContain(`Instagram login: this channel's cookie source (${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))."); + expect(log).toContain("This job's media budget (40 files / 200 MB) is used: the rest is owed to a later capture."); + expect(log).toContain("This run cost Instagram 3 request(s) and its CDN 40 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-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 \(HttpError: '429 Too Many Requests'.*a rate limit/); + 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"); +});