commit 8a6742adc2d2ff8aeaeda178bca13b3e01302aca
parent d09fa0d6d86595cb28ac91e94dccab699def3be8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 15:36:13 -0500
review 1 M1-M3, S1-S9, S13: a continuing sync ends at its watermark, a refusal in the lookup ends the run, and Instagram is asked only by the editor's jobs
M1: a sync that continues skips the posts it archived on the way down and
stops only at the watermark it began with, so the posts between its first page
and the archive are fetched. M2: every request line is read as it arrives, and
the first 429/401/403, login page or challenge page ends the run and decides
the hold or the alert, whatever the error row says (gallery-dl swallows the
lookup's exceptions); posts with no request line read are a failure. M3:
fetchPosts asks Instagram's guard itself and refuses an Instagram fetch that is
not the editor's job; a fetcher of another platform than the channel's is
refused. S1: digits inside a caption are never rewritten. S2: after a refusal
in the listing no media is asked for. S3-S6: the media half has a deadline,
honours drain, asks only Instagram's CDN hosts, sends one User-Agent and no
referer, holds its byte budget while streaming and survives a write error. S7:
a walk lists as many posts as its media budget has files (120 / 600 MB) and
leaves the posts whose media would not fit for the next run. S8: a second
401/403 in a row raises the alert. S9: a private account is told before the
error row. S13: the log never prints the cookie source.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
17 files changed, 1247 insertions(+), 241 deletions(-)
diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts
@@ -89,8 +89,12 @@ import {
fakeInstagramMediaDeps,
fetchInstagramMedia,
instagramMediaLine,
+ recordInstagramMediaOwed,
type InstagramMediaDeps,
} from "../social/instagramMedia";
+import { instagramJobGuard } from "../jobs/instagramGuard";
+import { currentJobContext } from "../lib/jobContext";
+import { detectPlatform } from "../lib/platform";
import { postsMediaDir } from "../social/postCapture";
import type { XCookieSource } from "../social/xCookieSource";
import { noteForumServiceOutcome } from "../lib/serviceCookies-server";
@@ -177,6 +181,31 @@ export function instagramCookieSource(config: { cookiesFromBrowser?: string } |
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.
+export function fetcherPlatformMismatch(
+ slug: string,
+ config: { platform?: string; url?: string },
+ fetcher: { platform: string; label: string; id: string },
+): string | null {
+ const channel = config.platform ?? detectPlatform(config.url) ?? null;
+ if (!channel || channel === fetcher.platform) return null;
+ return (
+ `${slug} is on ${channel}, 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.
@@ -344,6 +373,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).
@@ -401,6 +432,13 @@ export async function fetchPosts(
if (fetcher.platform === "instagram") {
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.
+ if (!currentJobContext()) {
+ return { ok: false, written: 0, skipped: 0, complete: false, error: INSTAGRAM_ONLY_AS_A_JOB(slug) };
+ }
+ 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);
@@ -705,14 +743,30 @@ async function fetchTimeline(ctx: {
// expire, so the new posts' pictures and videos are fetched now, after the
// posts are on disk (social/instagramMedia.ts). A failure here never fails
// the fetch: what is missing is owed, and said.
- if (result.media?.length) {
+ const 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;
diff --git a/common/jobs/instagramGuard.test.ts b/common/jobs/instagramGuard.test.ts
@@ -131,6 +131,40 @@ test("the 60-minute cooldown refuses every Instagram job until it ends, and says
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 });
diff --git a/common/jobs/instagramGuard.ts b/common/jobs/instagramGuard.ts
@@ -33,7 +33,12 @@ export function instagramCooldownSentence(remainingMs: number, now: number): str
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" : "a challenge or checkpoint page";
+ 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)}.`
@@ -49,9 +54,14 @@ export type InstagramGuardDeps = {
const DEFAULT_DEPS: InstagramGuardDeps = {
raisedAlert: (paths) => raisedServiceAlert(paths, INSTAGRAM_SERVICE),
- cooldownMs: (paths) => platformCooldownRemainingMs(INSTAGRAM_PLATFORM, paths).catch(() => 0),
+ 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;
@@ -61,7 +71,12 @@ export async function instagramJobGuard(opts: {
const now = opts.now ?? Date.now();
const raised = await deps.raisedAlert(opts.paths);
if (raised) return { ok: false, message: instagramAlertSentence(raised), alert: true };
- const ms = await deps.cooldownMs(opts.paths);
+ 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 };
}
diff --git a/common/jobs/instagramPacing.test.ts b/common/jobs/instagramPacing.test.ts
@@ -53,7 +53,7 @@ const post = (n, media) => {
rows.push([2, p]);
media.forEach((kind, i) => {
const ext = kind === "video" ? "mp4" : "jpg";
- const url = "https://cdn.example.invalid/" + handle + "/" + n + "-" + (i + 1) + "." + ext + "?sig=invented";
+ 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 }]);
});
};
@@ -116,7 +116,8 @@ async function makeChannel(slug: string, cookies: string | null): Promise<void>
const { getPaths } = await import("../lib/paths");
const { runManagedFunction } = await import("./streamCommand");
-const { fetchPosts, INSTAGRAM_RETRY_REFUSAL } = await import("../controller/fetchPosts");
+const { fetchPosts, fetcherPlatformMismatch, INSTAGRAM_ONLY_AS_A_JOB, INSTAGRAM_RETRY_REFUSAL } = await import("../controller/fetchPosts");
+const { runInJobContext } = await import("../lib/jobContext");
const { capturePosts } = await import("../controller/capturePosts");
const { getSettings } = await import("../lib/settings");
const { setQueueGapClock, clearQueueGaps } = await import("./queueGap");
@@ -209,6 +210,25 @@ test("a channel with no cookie source of its own is refused, and gallery-dl neve
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");
// 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);
@@ -251,6 +271,14 @@ test("5 Instagram fetches, job 1 meets a challenge: job 1 fails, the alert is up
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", 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());
@@ -277,16 +305,21 @@ test("the first 429 ends the run and holds Instagram for an hour: what was read
assert.deepEqual(ends.map((e) => e.status), ["failed", "failed", "failed"]);
assert.equal(await runCount(), 1);
const first = await readLog(ends[0]!.jobId);
- assert.match(first, /Instagram refused the read .*429 Too Many Requests.*a rate limit/);
+ assert.match(first, /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, its media fetched, the resume point kept.
+ // 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, 1);
+ 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.
@@ -340,7 +373,8 @@ test("clean fetches start at least 600 s apart, archive the posts and fetch thei
// One GET per file, with no cookies asked of anything: 4 files a channel.
assert.equal(cdn.length, 12);
const log = await readLog(ends[0]!.jobId);
- assert.match(log, /Instagram login: this channel's cookie source \(firefox:ig-profile\)/);
+ assert.match(log, /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\)\./);
@@ -374,12 +408,12 @@ test("a run past its request cap is stopped with an interrupt and keeps what gal
process.env.FAKE_MODE = "endless";
try {
const slug = SLUGS[4];
- const r = await fetchPosts({ paths, slug, settings: {}, instagramMedia });
- // A first fetch is a walk: 13 requests at most (the lookup and 12 pages of one post).
- assert.equal(r.ok, true);
- assert.equal(r.complete, false);
+ const 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 >= 12 && posts.length <= 14, `${posts.length} posts`);
+ 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 {
diff --git a/common/lib/instagram/ids.test.ts b/common/lib/instagram/ids.test.ts
@@ -73,6 +73,15 @@ test("a post's URL names its pk", () => {
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", () => {
diff --git a/common/lib/instagram/ids.ts b/common/lib/instagram/ids.ts
@@ -40,6 +40,7 @@ export function instagramShortcodeFromPk(pk: string): string | null {
}
// "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;
@@ -49,7 +50,8 @@ export function instagramPkFromShortcode(shortcode: string): string | null {
if (d === undefined) return null;
n = n * 64n + d;
}
- return n.toString();
+ const pk = n.toString();
+ return isInstagramPk(pk) ? pk : null;
}
export const INSTAGRAM_ORIGIN = "https://www.instagram.com";
@@ -120,6 +122,9 @@ export function instagramHandleFromUrl(input: string): string | 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;
@@ -139,6 +144,10 @@ export function parseInstagramPostUrl(input: string): InstagramPostUrlRef | null
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;
diff --git a/common/lib/serviceCookies-server.ts b/common/lib/serviceCookies-server.ts
@@ -369,7 +369,7 @@ export async function noteXServiceOutcome(
// 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"; url?: string; channel?: string },
+ outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure" | "refusal"; url?: string; channel?: string },
): Promise<string | null> {
return noteBlockingServiceOutcome(paths, INSTAGRAM_SERVICE, outcome);
}
@@ -377,7 +377,7 @@ export async function noteInstagramServiceOutcome(
async function noteBlockingServiceOutcome(
paths: Pick<Paths, "transcriptsDir">,
service: string,
- outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure"; url?: string; channel?: string },
+ outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure" | "refusal"; url?: string; channel?: string },
): Promise<string | null> {
try {
if (outcome.challengeLine) {
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
@@ -300,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;
@@ -315,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 {
@@ -453,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".
@@ -554,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;
@@ -668,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`;
}
}
@@ -689,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;
diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts
@@ -118,6 +118,8 @@ export type PostFetchResult = {
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>/`.
diff --git a/common/social/instagramGalleryDlFetcher.test.ts b/common/social/instagramGalleryDlFetcher.test.ts
@@ -9,6 +9,7 @@ import assert from "node:assert/strict";
import {
buildInstagramGalleryDlArgs,
fetchInstagramPosts,
+ instagramResumeFor,
instagramGalleryDlFetcher,
INSTAGRAM_FROM_TOP_CURSOR,
INSTAGRAM_NO_COOKIES,
@@ -40,11 +41,13 @@ type Harness = {
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, log: [], deps: undefined as never };
+ 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) => {
@@ -57,6 +60,7 @@ function harness(answer: { rows?: unknown[]; stdout?: string; stderr?: string[];
h.outcomes.push(o);
return null;
},
+ alertRaised: async () => h.alert,
noteRateLimit: async () => {
h.rateLimits++;
return NOW + 60 * 60_000;
@@ -124,24 +128,35 @@ test("with no cookie source nothing is spawned: Instagram shows the feed only to
assert.match(INSTAGRAM_NO_COOKIES("example-ig"), /an account kept for this/);
});
-test("the plan: a sync is one page, a walk ten, a refusal is never retried", () => {
- assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z" }), { mode: "sync", maxPosts: 30, maxRequests: 4, stopAtKnown: true });
- assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", limit: 5 }), { mode: "sync", maxPosts: 5, maxRequests: 4, stopAtKnown: true });
- assert.deepEqual(planInstagramRun({ since: "2026-01-01T00:00:00.000Z", limit: 500 }).maxPosts, 30);
- // A first fetch, a full re-walk: from the top, no stop at what is known.
- assert.deepEqual(planInstagramRun({}), { mode: "walk", maxPosts: 300, maxRequests: 13, stopAtKnown: false });
- assert.deepEqual(planInstagramRun({ stopAtKnown: true }), { mode: "walk", maxPosts: 300, maxRequests: 13, stopAtKnown: false });
+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: 300, maxRequests: 13, cursor: "abc_1", stopAtKnown: false });
- // A walk is never under two pages (a one-page walk logs no resume point), never over ten.
+ assert.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, 300);
- // A sync continuing down to its watermark: a walk from the top that stops at what is known.
+ 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: 300,
- maxRequests: 13,
- stopAtKnown: true,
+ 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" }) });
@@ -152,11 +167,13 @@ test("the plan: a sync is one page, a walk ten, a refusal is never retried", ()
"--dump-json",
"--verbose",
"-o",
+ "output.num-to-str=true",
+ "-o",
"extractor.instagram.retries=0",
"-o",
"extractor.instagram.videos=merged",
"-o",
- "extractor.instagram.max-posts=300",
+ "extractor.instagram.max-posts=120",
"-o",
"extractor.instagram.cursor=abc_1",
"--cookies-from-browser",
@@ -168,6 +185,12 @@ test("the plan: a sync is one page, a walk ten, a refusal is never retried", ()
// Streaming output would hide the exception: never asked for.
assert.ok(!args.join(" ").includes("jsonl"));
assert.ok(!args.includes("--no-download"));
+ // Which resume point covers a post: the page it was on at the latest.
+ assert.equal(instagramResumeFor(0, ["p2", "p3"], undefined), undefined);
+ assert.equal(instagramResumeFor(29, ["p2", "p3"], "start"), "start");
+ assert.equal(instagramResumeFor(30, ["p2", "p3"], "start"), "p2");
+ assert.equal(instagramResumeFor(75, ["p2", "p3"], "start"), "p3");
+ assert.equal(instagramResumeFor(200, ["p2", "p3"], "start"), "p3");
});
test("SYNC NEW: stops at the first archived post, skipping the pinned ones on top; one page, two requests", async () => {
@@ -205,49 +228,201 @@ test("SYNC NEW: a post older than the watermark stops it even when it is not arc
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(130, 30)), stderr: [...lookup, page] });
- const r = await fetchInstagramPosts(input(h, { since: "2020-01-02T00:00:00.000Z", seenIds: new Set([igPk(1)]) }), h.deps);
- assert.equal(r.posts.length, 30);
+ 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)));
- // …and that next sync is a walk from the top (no gallery-dl cursor) that stops at what it knows.
- const h2 = harness({ rows: igRows([...days(130, 45), { n: 1, date: "2020-01-02 00:00:00" }]), stderr: [page, igCursorLine("c2"), page] });
+});
+
+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: "2020-01-02T00:00:00.000Z", cursor: INSTAGRAM_FROM_TOP_CURSOR, seenIds: new Set([igPk(1), ...days(130, 30).map((p) => igPk(p.n))]) }),
+ input(h2, { since: W, cursor: "page-2", seenIds: archived(...range(180, 151), ...range(150, 141)) }),
h2.deps,
);
- assert.ok(!h2.runs[0]!.args.some((a) => a.includes("extractor.instagram.cursor")));
- assert.ok(h2.runs[0]!.args.includes("extractor.instagram.max-posts=300"));
- // The 30 it already has are archived again nowhere: it stops at the first of them.
+ assert.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);
- assert.equal(r2.posts.length, 0);
});
-test("A WALK: 300 posts and more behind them — it stops, and resumes from the last cursor gallery-dl logged", async () => {
+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 <= 10; i++) {
+ for (let i = 1; i <= 4; i++) {
stderr.push(page);
- if (i < 10) stderr.push(igCursorLine(`page-${i + 1}`));
+ if (i < 4) stderr.push(igCursorLine(`page-${i + 1}`));
}
- const h = harness({ rows: igRows(days(400, 300)), stderr });
+ const h = harness({ rows: igRows(days(400, 120)), stderr });
const r = await fetchInstagramPosts(input(h), h.deps);
- assert.equal(r.posts.length, 300);
+ assert.equal(r.posts.length, 120);
assert.equal(r.complete, false);
- assert.equal(r.cursor, "page-10");
- assert.equal(r.requests, 11);
- assert.equal(h.runs[0]!.stops, 0, "eleven requests are under the cap of 13");
+ 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-11"), page] });
- const r2 = await fetchInstagramPosts(input(h2, { cursor: "page-10", stopAtKnown: true, seenIds: new Set(days(130, 30).map((p) => igPk(p.n))) }), h2.deps);
- assert.ok(h2.runs[0]!.args.includes("extractor.instagram.cursor=page-10"));
+ 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);
+ // Post 360 is row 40: on page 2 at the latest, so the next run starts at page-2.
+ assert.equal(r.cursor, "page-2");
+ 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 });
+});
+
+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("posts with no request line read are a failure, never a clean read: the cap and the refusal watch were blind", 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 its 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");
+});
+
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] });
@@ -320,12 +495,34 @@ test("THE FIRST 429 ENDS THE RUN: what was read is kept with its resume point, I
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")],
diff --git a/common/social/instagramGalleryDlFetcher.ts b/common/social/instagramGalleryDlFetcher.ts
@@ -8,11 +8,19 @@
// - gallery-dl sleeps 6-12 s before every request, by itself.
// SYNC NEW reads ONE page (max-posts 30). A WALK (a first fetch, a full
// re-walk, a resumed backfill, a sync continuing down to its watermark) reads
-// up to 300 posts and stops; the next run resumes from the cursor gallery-dl
+// 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 run that sent more requests than MAX_REQUESTS is stopped, whatever
-// Instagram's page size turns out to be.
+// 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 — the next one lists them again — so every post a run archives has its
+// media asked for in the same run. 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
@@ -24,6 +32,10 @@
// - 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
@@ -56,8 +68,12 @@ import {
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,
@@ -67,18 +83,22 @@ import {
export const INSTAGRAM_FETCHER_ID = "instagram-gallery-dl";
-// Instagram's feed page.
+// 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;
-// A walk: ten pages, then the next run resumes. Never under two pages: a
+// 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 = 10 * INSTAGRAM_PAGE_POSTS;
+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 = 13;
+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
@@ -100,9 +120,17 @@ export type InstagramRunPlan = {
maxRequests: number;
// gallery-dl's resume point, when the run continues from one.
cursor?: string;
- // Stop at the first post already archived, or older than `since` (pinned
- // posts aside: they sit on top of the grid whatever their age).
- stopAtKnown: boolean;
+ // 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.
@@ -115,7 +143,8 @@ export function planInstagramRun(input: Pick<PostFetchInput, "since" | "cursor"
mode: "sync",
maxPosts: Math.min(limit ?? INSTAGRAM_SYNC_MAX_POSTS, INSTAGRAM_SYNC_MAX_POSTS),
maxRequests: INSTAGRAM_SYNC_MAX_REQUESTS,
- stopAtKnown: input.stopAtKnown !== false,
+ stop: input.stopAtKnown === false ? "none" : "known",
+ media: INSTAGRAM_SYNC_MEDIA,
};
}
return {
@@ -123,9 +152,10 @@ export function planInstagramRun(input: Pick<PostFetchInput, "since" | "cursor"
maxPosts: Math.max(INSTAGRAM_WALK_MIN_POSTS, Math.min(limit ?? INSTAGRAM_WALK_MAX_POSTS, INSTAGRAM_WALK_MAX_POSTS)),
maxRequests: INSTAGRAM_WALK_MAX_REQUESTS,
...(real ? { cursor: real } : {}),
- // Only a walk with a watermark stops at what it knows: a history walk
- // resumed from its cursor re-reads one page of archived posts on purpose.
- stopAtKnown: Boolean(input.since) && input.stopAtKnown !== false,
+ // 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,
};
}
@@ -145,6 +175,9 @@ export function buildInstagramGalleryDlArgs(opts: { handle: string; cookies?: st
"--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",
@@ -167,6 +200,8 @@ export type InstagramRunOutput = {
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:
@@ -176,7 +211,11 @@ export type InstagramFetcherDeps = {
args: string[],
opts: { signal: AbortSignal; drain?: AbortSignal; timeoutMs: number; onStderrLine: (line: string) => "stop" | void },
) => Promise<InstagramRunOutput>;
- noteOutcome: (outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure"; url?: string; channel?: string }) => Promise<string | null>;
+ // 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;
@@ -235,6 +274,7 @@ 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(),
});
@@ -252,6 +292,16 @@ export function instagramCostLine(requests: readonly InstagramRequestLine[]): st
);
}
+// WHICH RESUME POINT COVERS A POST: the page the post at `row` was on is, at
+// the latest, page floor(row / 30) + 1 of this run (a page holds at most 30
+// posts), and the cursor that page was reached by is the (page − 1)th logged.
+// Page 1 is where the run began.
+export function instagramResumeFor(row: number, cursors: readonly string[], start: string | undefined): string | undefined {
+ const page = Math.floor(row / INSTAGRAM_PAGE_POSTS) + 1;
+ if (page <= 1) return start;
+ return cursors[Math.min(page - 2, cursors.length - 1)] ?? start;
+}
+
export async function fetchInstagramPosts(
input: PostFetchInput,
given: Partial<InstagramFetcherDeps> = {},
@@ -269,18 +319,22 @@ export async function fetchInstagramPosts(
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: this channel's cookie source (${cookies}), read by gallery-dl. ` +
+ "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"}.`) +
+ : `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[] = [];
- let cursor: string | undefined;
+ 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 } : {}),
@@ -288,13 +342,17 @@ export async function fetchInstagramPosts(
onStderrLine: (line) => {
const c = parseInstagramCursorLine(line);
if (c) {
- cursor = 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";
@@ -302,34 +360,68 @@ export async function fetchInstagramPosts(
},
});
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 what it knows.
- const fresh: InstagramListedPost[] = [];
+ // Which of what was listed is new, and where the walk met its end.
+ let fresh: InstagramListedPost[] = [];
let known = 0;
- let stoppedAtKnown = false;
+ let reachedEnd = false;
for (const p of listed) {
const isKnown = seenIds.has(p.post.id);
- const isOld = Boolean(since) && p.post.createdAt <= since!;
if (p.pinned) {
// On top of the grid whatever its age: archived when new, never a stop.
if (isKnown) known++;
else fresh.push(p);
continue;
}
- if (isKnown || (isOld && plan.stopAtKnown)) {
+ 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++;
- if (plan.stopAtKnown) {
- stoppedAtKnown = true;
- break;
- }
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(
@@ -340,71 +432,116 @@ export async function fetchInstagramPosts(
".",
);
- // Where the next run picks up when this one did not finish.
- // the last page gallery-dl left, else the point it was given, else — when
- // it saved posts before leaving any page — the top.
- const resumeAt = cursor ?? plan.cursor ?? (posts.length > 0 ? INSTAGRAM_FROM_TOP_CURSOR : undefined);
- const base = { posts, requests: requests.filter((r) => isInstagramApiHost(r.host)).length, ...(media.length ? { media } : {}) };
+ // Where the next run picks up when this one did not finish: the page the
+ // first post it left behind was on; else 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
+ ? (instagramResumeFor(trimmedAt.row, cursors, 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 (rows?.error) {
- const sig = classifyInstagramError(rows.error, { requests, handle });
- if (sig.class === "challenge" || sig.class === "login") {
- await deps.noteOutcome({
- challengeLine: sig.line,
- kind: sig.class === "challenge" ? "challenge" : "auth-failure",
- url: accountUrl,
- channel: channelSlug,
- });
- const what =
- sig.class === "challenge"
- ? "Instagram answered with a challenge or checkpoint page"
- : "Instagram did not accept the login (its login page, or the \"Page Not Found\" it answers a logged-out read with)";
- return {
- ...base,
- complete: false,
- ...(resumeAt && !stoppedAtKnown ? { cursor: resumeAt } : {}),
- needsCookies: true,
- block: sig.class,
- error:
- `${what}: ${sig.line}. The run stopped and Instagram's alert is up: no Instagram job starts until ` +
- (sig.class === "challenge"
- ? "the check is passed by hand in the browser this channel's cookie source names"
- : "that browser (or cookies file) is logged in to Instagram again") +
- ", and Recheck is pressed on the dashboard. Nothing retries by itself.",
- };
- }
- if (sig.class === "rate-limit") {
- const until = await deps.noteRateLimit().catch(() => deps.now() + INSTAGRAM_RATE_LIMIT_HOLD_MS);
- return {
- ...base,
- complete: false,
- ...(resumeAt && !stoppedAtKnown ? { cursor: resumeAt } : {}),
- block: "blocked",
- error:
- `Instagram refused the read (${sig.line}): a rate limit. The run stopped at once and asked nothing more; ` +
- `no Instagram job starts before ${hhmm(until)} UTC (${Math.round(INSTAGRAM_RATE_LIMIT_HOLD_MS / 60_000)} min). Nothing retries by itself.`,
- };
- }
- if (sig.class === "not-found") {
- return {
- ...base,
- complete: false,
- block: "not-found",
- error: `Instagram has no account @${handle}: its own page answered 404 (renamed, deleted or suspended). What is archived is kept.`,
- };
- }
- if (sig.class === "private") {
- return {
- ...base,
- complete: false,
- error: `@${handle} is a private account and this channel's login does not follow it: nothing was read.`,
- };
- }
- // A post already archived stops a sync before the row that failed mattered.
- if (!stoppedAtKnown) {
- return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}), error: `gallery-dl failed: ${sig.line}` };
+ if (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) {
@@ -413,18 +550,24 @@ export async function fetchInstagramPosts(
return {
posts: [],
complete: false,
- ...(plan.cursor ? { cursor: plan.cursor } : input.cursor ? { cursor: input.cursor } : {}),
+ ...(input.cursor ? { cursor: input.cursor } : {}),
...(input.drain?.aborted && !signal.aborted ? { drained: true } : {}),
};
}
return { posts: [], complete: false, error: "gallery-dl printed nothing this reads as its JSON output." };
}
- if (privateLine && listed.length === 0) {
+ // POSTS WITH NO REQUEST LINE READ: the request cap and the refusal watch
+ // were blind (gallery-dl's log format changed, or --verbose was lost). What
+ // it printed is kept; the run is a failure, never a clean read.
+ if (requests.length === 0 && rows.emitted > 0) {
return {
...base,
complete: false,
- error: `@${handle} is a private account and this channel's login does not follow it: nothing was read.`,
+ ...(resumeAt ? { cursor: resumeAt } : {}),
+ error:
+ "gallery-dl listed posts but none of its requests could be read from its log, so this run's request cap and its " +
+ "watch for a refusal saw nothing. The posts are kept; fix the log reading (instagramSignals.ts) before the next fetch.",
};
}
@@ -432,7 +575,8 @@ export async function fetchInstagramPosts(
const cleared = await deps.noteOutcome({ url: accountUrl, channel: channelSlug });
if (cleared) log(cleared.trimEnd());
- if (stoppedAtKnown) return { ...base, complete: true };
+ if (trimmedAt) return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}) };
+ if (reachedEnd) return { ...base, complete: true };
if (out.canceled || signal.aborted || out.timedOut) {
log(
diff --git a/common/social/instagramMedia.test.ts b/common/social/instagramMedia.test.ts
@@ -19,10 +19,16 @@ import {
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";
-const CDN = "https://cdn.example.invalid";
+// 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 {
@@ -95,9 +101,13 @@ test("one GET per file, with no cookies, a pause before every file but the first
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, failed: 0, postsWhole: 2, posts: 2 });
+ 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"]);
@@ -131,10 +141,20 @@ test("the job's budget: the 41st file is not asked for, and is recorded as owed"
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 sum2 = await fetchInstagramMedia({ outDir: await tmp(), plans: [plan(7, 5)], signal: signal(), deps: deps(c2), limits: { maxBytes: 1000 } });
- assert.equal(c2.calls.length, 2);
- assert.equal(sum2.owed, 3);
+ 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 });
}
@@ -209,6 +229,7 @@ test("a cancelled job asks for nothing more and says the rest is owed; an id tha
// 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"), "");
@@ -217,13 +238,142 @@ test("a cancelled job asks for nothing more and says the rest is owed; an id tha
}
});
+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 };
+ 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);
diff --git a/common/social/instagramMedia.ts b/common/social/instagramMedia.ts
@@ -2,12 +2,21 @@
// the posts a run just listed, fetched from the CDN addresses the run printed,
// in the same job — they are signed and expire, so "later" is not an option.
//
-// - ONE GET per file, with no cookies, 2-5 s after the one before it.
-// - A job fetches at most 40 files or 200 MB; a file over 100 MB is not
-// fetched at all. What a job did not fetch is OWED and said so in the
-// post's capture record (`mediaOwed: "next"`), never retried here.
-// - Three refusals in a row (a 403, a 429, no answer) end the media half:
-// the CDN is asked for no more by this job.
+// - 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.
@@ -29,18 +38,54 @@ import {
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;
-const FILE_MS = 10 * 60_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" },
+ init: {
+ signal: AbortSignal;
+ redirect: "error";
+ credentials: "omit";
+ referrer: "";
+ referrerPolicy: "no-referrer";
+ headers: Record<string, string>;
+ },
) => Promise<{
status: number;
headers: { get: (name: string) => string | null };
@@ -53,6 +98,10 @@ export type InstagramMediaDeps = {
// 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 {
@@ -77,14 +126,14 @@ const defaultDeps = (): InstagramMediaDeps => ({
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.
-// (fakeInstagramMediaDeps is what the controller takes: this fetch, and no
-// pause between two files, since no CDN is being asked.)
export function fakeInstagramMediaFetch(
env: Readonly<Record<string, string | undefined>> = process.env,
): InstagramMediaFetch | null {
@@ -106,11 +155,23 @@ export function fakeInstagramMediaFetch(
};
}
+// 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"> | null {
+): Pick<InstagramMediaDeps, "fetch" | "pauseMs" | "urlProblem"> | null {
const fake = fakeInstagramMediaFetch(env);
- return fake ? { fetch: fake, pauseMs: () => 0 } : null;
+ 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`;
@@ -118,25 +179,48 @@ const firstLine = (err: unknown) => String((err as Error)?.message ?? err).split
type Fetched =
| { ok: true; bytes: number }
- | { ok: false; why: string; refused?: boolean; oversize?: boolean };
+ | {
+ 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.
+// 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;
- fetch: InstagramMediaFetch;
+ room: number;
+ deps: Pick<InstagramMediaDeps, "fetch" | "openFile">;
signal: AbortSignal;
}): Promise<Fetched> {
const part = `${o.file}.part`;
- const deadline = AbortSignal.any([o.signal, AbortSignal.timeout(FILE_MS)]);
+ 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.fetch(o.url, { signal: AbortSignal.any([deadline, headers.signal]), redirect: "error", credentials: "omit" });
+ 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 {
@@ -154,40 +238,71 @@ async function fetchOne(o: {
return { ok: false, refused: res.status === 403 || res.status === 429, why: `the CDN answered ${res.status}` };
}
const declared = Number(res.headers.get("content-length") ?? "");
- if (Number.isFinite(declared) && declared > o.cap) {
+ if (Number.isFinite(declared) && declared > limit) {
await drop();
- return { ok: false, oversize: true, why: `it is ${mb(declared)}, over the ${mb(o.cap)} a file may be` };
+ return over(declared);
}
await rm(part, { force: true });
- const out = createWriteStream(part);
+ // 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 > o.cap) {
+ if (bytes > limit) {
tooBig = true;
break;
}
- if (!out.write(chunk)) await once(out, "drain");
+ 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)})` };
}
- await new Promise<void>((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve())));
+ 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 { ok: false, oversize: true, why: `it is over the ${mb(o.cap)} a file may be` };
+ return over(0);
}
if (bytes === 0) {
await rm(part, { force: true });
return { ok: false, why: "the CDN answered an empty file" };
}
- await rename(part, o.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 };
}
@@ -198,12 +313,16 @@ export type InstagramMediaSummary = {
// Files already on disk from an earlier job.
kept: number;
// Files not fetched and owed to a later capture (the job's budget, a
- // refusal, a cancel), and files over the per-file cap.
+ // 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.
+ // 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;
@@ -223,19 +342,63 @@ async function exists(file: string): Promise<boolean> {
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 };
+ 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 sum: InstagramMediaSummary = { fetched: 0, bytes: 0, kept: 0, owed: 0, oversize: 0, failed: 0, postsWhole: 0, posts: opts.plans.length };
+ 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 {
@@ -250,62 +413,63 @@ export async function fetchInstagramMedia(opts: {
const problems: string[] = [];
let owed = false;
for (const f of [...plan.files].sort((a, b) => a.num - b.num)) {
- const file = path.join(dir, path.basename(f.name));
+ const name = path.basename(f.name);
+ const file = path.join(dir, name);
if (await exists(file)) {
sum.kept++;
- landed.push(await describeCapturedFile(dir, path.basename(f.name), f.url));
- continue;
- }
- if (opts.signal.aborted) {
- owed = true;
- sum.owed++;
- problems.push(`${f.name}: owed (cancelled)`);
+ landed.push(await describeCapturedFile(dir, name, f.url));
continue;
}
- if (sum.stopped) {
- owed = true;
- sum.owed++;
- problems.push(`${f.name}: owed (${sum.stopped})`);
+ const notCdn = deps.urlProblem(f.url);
+ if (notCdn) {
+ sum.skipped++;
+ problems.push(`${name}: not fetched (${notCdn})`);
continue;
}
- if (asked >= maxFiles || sum.bytes >= maxBytes) {
- sum.stopped = `this job's media budget of ${maxFiles} files / ${mb(maxBytes)} is used`;
- log(`This job's media budget (${maxFiles} files / ${mb(maxBytes)}) is used: the rest is owed to a later capture.`);
- owed = true;
- sum.owed++;
- problems.push(`${f.name}: owed (${sum.stopped})`);
- continue;
+ let why = halted();
+ if (!why && asked > 0) {
+ await deps.pause(deps.pauseMs(), opts.signal);
+ why = halted();
}
- if (asked > 0) await deps.pause(deps.pauseMs(), opts.signal);
- if (opts.signal.aborted) {
+ if (why) {
owed = true;
sum.owed++;
- problems.push(`${f.name}: owed (cancelled)`);
+ problems.push(`${name}: owed (${why})`);
continue;
}
asked++;
- const got = await fetchOne({ url: f.url, file, cap: maxFileBytes, fetch: deps.fetch, signal: opts.signal });
+ 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, path.basename(f.name), f.url));
+ landed.push(await describeCapturedFile(dir, name, f.url));
continue;
}
- problems.push(`${f.name}: ${got.why}`);
+ 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) {
- sum.stopped = `the CDN refused ${INSTAGRAM_MEDIA_MAX_REFUSALS} files in a row`;
- log(
+ 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.",
);
@@ -313,34 +477,81 @@ export async function fetchInstagramMedia(opts: {
}
const whole = problems.length === 0;
if (whole) sum.postsWhole++;
- const prior = await readPostCapture(dir);
- const record: PostCaptureRecord = {
- ...(prior ?? {}),
- version: 1,
- id: plan.id,
- url: plan.url,
- capturedAt: new Date(deps.now()).toISOString(),
- state: "captured",
- mediaState: whole ? (landed.length > 0 ? "ok" : "none") : "error",
- media: landed,
- };
- delete record.mediaOwed;
- delete record.error;
- if (!whole) {
- if (owed) record.mediaOwed = "next";
- record.error = problems.join("; ");
- }
- await writePostCapture(dir, record);
+ 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.`;
+ 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
@@ -57,6 +57,43 @@ test("a pk printed as a bare number beyond 2^53 is kept whole", () => {
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 },
diff --git a/common/social/instagramNormalize.ts b/common/social/instagramNormalize.ts
@@ -37,6 +37,9 @@ export type InstagramMediaFile = {
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[];
};
@@ -55,12 +58,52 @@ export type InstagramRunRows = {
otherKinds: number;
};
-// Quote every integer of 16 digits or more, so JSON.parse keeps it whole.
+// 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 {
- return json.replace(/([:[,]\s*)(-?\d{16,})(?=\s*[,}\]])/g, '$1"$2"');
+ 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;
@@ -109,7 +152,8 @@ function fileOf(url: string, raw: Record<string, unknown>, fallbackNum: number):
if (str(raw.audio_url)) return null;
// A video item yields its video (and no picture); a picture has no video_url.
const kind: "image" | "video" = str(raw.video_url) ? "video" : "image";
- const num = typeof raw.num === "number" && raw.num >= 1 ? Math.floor(raw.num) : fallbackNum;
+ const 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) };
}
@@ -156,8 +200,8 @@ export function normalizeInstagramPost(
const text = typeof raw.description === "string" ? raw.description : "";
const pinned = Array.isArray(raw.pinned) ? raw.pinned.length > 0 : raw.pinned === true;
const coauthors = coauthorsOf(raw.coauthors, author, ctx.handle);
- const count = typeof raw.count === "number" && raw.count >= 0 ? Math.floor(raw.count) : undefined;
- const likes = typeof raw.likes === "number" && raw.likes >= 0 ? Math.floor(raw.likes) : undefined;
+ const count = countOf(raw.count);
+ const likes = countOf(raw.likes);
const post: Post = {
id,
slug: postSlug(ctx.channelSlug, id),
@@ -208,6 +252,7 @@ export function parseInstagramRun(stdout: string, ctx: { channelSlug: string; ha
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") {
@@ -226,7 +271,7 @@ export function parseInstagramRun(stdout: string, ctx: { channelSlug: string; ha
current = null;
continue;
}
- current = { post: n.post, pinned: n.pinned, files: [] };
+ current = { post: n.post, row: rowIndex, pinned: n.pinned, files: [] };
byId.set(n.post.id, current);
out.posts.push(current);
continue;
diff --git a/common/social/instagramSignals.test.ts b/common/social/instagramSignals.test.ts
@@ -3,6 +3,8 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import {
+ instagramErrorStatus,
+ instagramStopSignal,
classifyInstagramError,
isInstagramPrivateLine,
parseInstagramCursorLine,
@@ -78,3 +80,25 @@ test("a 429, a 401 and a 403 are the rate limit; a 5xx and a crash are plain err
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);
+});
diff --git a/common/social/instagramSignals.ts b/common/social/instagramSignals.ts
@@ -71,6 +71,33 @@ export function profilePageStatus(requests: readonly InstagramRequestLine[], han
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);
+ if (path.startsWith("/challenge") || path.includes("checkpoint")) return { class: "challenge", status: r.status, line: `${r.method} ${path} (a challenge or checkpoint page)` };
+ if (path.startsWith("/accounts/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 };