// E2E fake gallery-dl, INSTAGRAM mode (lane instagram). Loaded by // fake-gallery-dl.mjs when the URL is on instagram.com. // // What the real binary (1.32.9) does with `--dump-json --verbose` and what the // fetcher reads (common/social/instagramGalleryDlFetcher.ts): request lines // and "Cursor:" lines on stderr; ONE JSON array on stdout when it exits, the // exception that ended the run as its last row; exit 0 whatever happened; on // SIGINT, what it has so far. Instagram is NEVER contacted, and every // account, id and address here is invented. // // The account in the URL picks the answer: // ig_loggedout a dead or missing session: the search answers 404, the // profile page 200, the feed 404 "Page Not Found" // ig_loginwall a redirect to the login page // ig_challenge a redirect to the challenge page // ig_ratelimited one page, then 429 on the next // ig_lookup429 the account search answers 429 — and, as the real binary // does (it swallows the lookup's exceptions), the run GOES ON // to the profile page and the feed unless it is stopped // ig_private a private account the login does not follow // ig_gone the search and the profile page both answer 404 // anything else an account of 75 posts: two pinned on top (one of them // old), a carousel, a reel, pictures — in pages of 30, with // `extractor.instagram.max-posts` and `.cursor` honoured. // With no --cookies / --cookies-from-browser argument EVERY account answers // as ig_loggedout does: logged out, Instagram shows no feed. const PAGE = 30; const TOTAL = 75; const UID = "4000000001"; const CDN = "https://cdn.example.invalid"; const pk = (n) => (3500000000000000000n + BigInt(n)).toString(); const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; const shortcode = (id) => { let n = BigInt(id); let out = ""; while (n > 0n) { out = ALPHABET[Number(n % 64n)] + out; n /= 64n; } return out || "A"; }; const day = (n) => new Date(Date.UTC(2026, 0, 1) + n * 86_400_000).toISOString().slice(0, 19).replace("T", " "); // Post n of the account (n counts up with time), with its media kinds. function postOf(handle, n, opts = {}) { const media = n % 10 === 0 ? ["image", "video", "image"] : n % 7 === 0 ? ["video"] : ["image"]; const id = pk(n); const code = shortcode(id); const type = media.length === 1 && media[0] === "video" ? "reel" : "post"; const post = { category: "instagram", subcategory: "posts", post_id: id, post_shortcode: code, post_url: `https://www.instagram.com/${type === "reel" ? "reel" : "p"}/${code}/`, type, username: handle, fullname: "Fake Instagram Account", owner_id: UID, description: `fake instagram post ${n} about zephyr archives`, post_date: day(n), date: day(n), likes: n, liked: false, pinned: opts.pinned ? [Number(UID)] : [], count: media.length, }; const rows = [[2, post]]; media.forEach((kind, i) => { const mediaId = pk(n * 100 + i + 1); const ext = kind === "video" ? "mp4" : "jpg"; const url = `${CDN}/v/${mediaId}.${ext}?sig=invented`; rows.push([ 3, url, { ...post, num: i + 1, media_id: mediaId, display_url: `${CDN}/v/${mediaId}.jpg?sig=invented`, video_url: kind === "video" ? url : null, extension: ext }, ]); }); return rows; } // The grid, newest first: the two pinned posts on top, then every post by date. function grid(handle) { const out = [postOf(handle, 3, { pinned: true }), postOf(handle, TOTAL - 5, { pinned: true })]; for (let n = TOTAL; n >= 1; n--) out.push(postOf(handle, n, { pinned: n === 3 || n === TOTAL - 5 })); return out; } export async function runInstagram(args) { const url = args[args.length - 1] ?? ""; const handle = /instagram\.com\/([^/?#]+)/i.exec(url)?.[1] ?? "nobody"; const opt = (key) => { const hit = args.find((a) => a.startsWith(`extractor.instagram.${key}=`)); return hit ? hit.slice(`extractor.instagram.${key}=`.length) : undefined; }; const loggedIn = args.includes("--cookies") || args.includes("--cookies-from-browser"); const maxPosts = Number(opt("max-posts") ?? Infinity); const cursor = opt("cursor"); const rows = []; const err = (line) => process.stderr.write(line + "\n"); const req = (path, status = 200) => err(`[urllib3.connectionpool][debug] https://www.instagram.com:443 "GET ${path} HTTP/1.1" ${status} ${status === 200 ? "None" : "20445"}`); const dump = () => { process.stdout.write(JSON.stringify(rows, null, 2) + "\n"); process.exit(0); }; const fail = (error, message) => { rows.push([-1, { error, message }]); dump(); }; process.on("SIGINT", dump); const feed = `/api/v1/feed/user/${UID}/?count=30`; const feedUrl = `https://www.instagram.com${feed}`; err("[gallery-dl][debug] Version 1.32.9"); if (!/extractor\.instagram\.retries=0/.test(args.join(" "))) { // The fetcher must never let gallery-dl wait and ask again. err("[fake][error] extractor.instagram.retries=0 was not passed"); process.exit(2); } if (!loggedIn || handle === "ig_loggedout") { req(`/web/search/topsearch/?query=${handle}`, 404); req(`/${handle}`, 200); req(feed, 404); fail("HttpError", `'404 Not Found' for '${feedUrl}'`); } if (handle === "ig_gone") { req(`/web/search/topsearch/?query=${handle}`, 404); req(`/${handle}`, 404); fail("NotFoundError", "Requested user could not be found"); } if (handle === "ig_lookup429") { req(`/web/search/topsearch/?query=${handle}`, 429); // What gallery-dl does next, a moment later: the profile page, then the feed. await new Promise((r) => setTimeout(r, 1500)); req(`/${handle}`, 200); } else req(`/web/search/topsearch/?query=${handle}`); if (handle === "ig_loginwall") { req(feed, 302); fail("AbortExtraction", "HTTP redirect to login page (https://www.instagram.com/accounts/login/)"); } if (handle === "ig_challenge") { req(feed, 302); fail("AbortExtraction", "HTTP redirect to challenge page (https://www.instagram.com/challenge/)"); } if (handle === "ig_private") { err(`[instagram][warning] ${handle}'s posts are private`); req(feed); dump(); } const all = grid(handle); const pages = []; for (let i = 0; i < all.length; i += PAGE) pages.push(all.slice(i, i + PAGE)); let p = cursor ? Number(/^page-(\d+)$/.exec(cursor)?.[1] ?? 1) - 1 : 0; let emitted = 0; for (; p < pages.length; p++) { if (handle === "ig_ratelimited" && p === 1) { req(`${feed}&max_id=page-2`, 429); fail("HttpError", `'429 Too Many Requests' for '${feedUrl}&max_id=page-2'`); } req(p === 0 ? feed : `${feed}&max_id=page-${p + 1}`); for (const post of pages[p]) { rows.push(...post); emitted++; // max-posts ends the run INSIDE the page that reached it, as the real // extractor's islice does: no cursor is logged for a page it never // left, and the next page is never asked for. if (emitted >= maxPosts) dump(); } // Logged when a page is LEFT, as the real extractor does. if (p + 1 < pages.length) err(`[instagram][debug] Cursor: page-${p + 2}`); } dump(); }