// gallery-dl's Instagram rows -> `Post`s and the media they carry (lane // instagram). Pure: no I/O. // // `gallery-dl --dump-json` prints ONE JSON array when it exits (never line by // line here: instagramGalleryDlFetcher.ts says why). Its rows: // [2, {…post…}] a post ("directory" row): post_id, post_shortcode, // username, fullname, description, post_date, type // ("post" | "reel"), post_url, count, pinned, // coauthors, likes // [3, "", {…file…}] one media file of the post before it: num, // media_id, video_url | display_url, extension // [-1, {error, message}] the exception that ended the run, when one did // // A post's pk is beyond 2^53 and gallery-dl may print it as a bare number: // every long integer is quoted before the parse (quoteBigIntegers), and an id // is a string of digits from then on. import type { Post } from "../lib/posts"; import { postSlug, uploadDateFromCreatedAt } from "../lib/posts"; import { instagramPostUrl, instagramShortcodeFromPk, isInstagramPk, isInstagramShortcode, } from "../lib/instagram/ids"; export type InstagramMediaFile = { // 1-based position in the post (a carousel's order). num: number; kind: "image" | "video"; // The CDN address as the run printed it. Signed, and it EXPIRES: fetched in // the same job, never stored in the post. url: string; // The file's name in `posts-media//`. name: string; }; export type InstagramListedPost = { post: Post; // Its place among the post rows the run printed (0-based, repeats counted): // what tells which page of the walk it was on, at the latest. row: number; pinned: boolean; files: InstagramMediaFile[]; }; export type InstagramRunRows = { posts: InstagramListedPost[]; // The exception that ended the run, when one did. error?: { error: string; message: string }; // How many post rows the run printed, repeats and unread ones included: // what a `max-posts` cap is told by. emitted: number; // Post rows that could not be read (no pk, no date): counted, never guessed. unreadable: number; // Rows that are not a post or reel of the grid (a story, a highlight): left // for the slice that reads them. otherKinds: number; }; // Quote every BARE integer of 16 digits or more, so JSON.parse keeps it whole. // A scan that knows where it is: digits INSIDE a string (a caption quoting a // 17-digit number, an escaped quote before it) are never touched — a regex // over the whole text rewrote them and broke the parse. The run is asked for // `output.num-to-str`, which prints a post's own numbers as strings already; // that option does not reach numbers inside lists, which is what this is for. export function quoteBigIntegers(json: string): string { let out = ""; let i = 0; const n = json.length; while (i < n) { const c = json[i]!; if (c === '"') { // A string: copied whole, escapes and all. let j = i + 1; while (j < n && json[j] !== '"') j += json[j] === "\\" ? 2 : 1; out += json.slice(i, Math.min(j + 1, n)); i = j + 1; continue; } if (c === "-" || (c >= "0" && c <= "9")) { let j = i + (c === "-" ? 1 : 0); while (j < n && json[j]! >= "0" && json[j]! <= "9") j++; const digits = j - i - (c === "-" ? 1 : 0); // An integer only: a fraction or an exponent follows a float, left alone. const next = json[j]; const integer = next !== "." && next !== "e" && next !== "E"; if (!integer) { while (j < n && /[0-9.eE+-]/.test(json[j]!)) j++; out += json.slice(i, j); } else out += digits >= 16 ? `"${json.slice(i, j)}"` : json.slice(i, j); i = Math.max(j, i + 1); continue; } out += c; i++; } return out; } const str = (v: unknown): string | undefined => (typeof v === "string" && v ? v : undefined); // A count, printed as a number or (with `output.num-to-str`) as its digits. const countOf = (v: unknown): number | undefined => { const n = typeof v === "number" ? v : typeof v === "string" && /^\d{1,15}$/.test(v) ? Number(v) : NaN; return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined; }; const idOf = (v: unknown): string | undefined => typeof v === "string" && /^\d+$/.test(v) ? v : typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? String(v) : undefined; // gallery-dl prints a date as "YYYY-MM-DD HH:MM:SS", in UTC. export function instagramDateToIso(v: unknown): string | null { const s = str(v); if (!s) return null; const m = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(\.\d+)?(Z|[+-]\d{2}:?\d{2})?$/.exec(s); if (!m) return null; const ms = Date.parse(`${m[1]}T${m[2]}${m[3] ?? ""}${m[4] ?? "Z"}`); return Number.isFinite(ms) ? new Date(ms).toISOString() : null; } const LINK_RE = /https?:\/\/[^\s<>"'))\]]+/g; function linksIn(text: string): string[] { const out: string[] = []; for (const m of text.match(LINK_RE) ?? []) { const url = m.replace(/[.,;:!?]+$/, ""); if (!out.includes(url)) out.push(url); } return out; } function extensionOf(file: Record, url: string, kind: "image" | "video"): string { const given = str(file.extension)?.toLowerCase(); if (given && /^[a-z0-9]{1,5}$/.test(given)) return given; try { const m = /\.([A-Za-z0-9]{1,5})$/.exec(new URL(url).pathname); if (m) return m[1]!.toLowerCase(); } catch { /* not a URL */ } return kind === "video" ? "mp4" : "jpg"; } // "01-.jpg": the carousel's order first, so a listing reads in it. export function instagramMediaFileName(num: number, mediaId: string | undefined, ext: string): string { const n = String(Math.max(1, Math.floor(num))).padStart(2, "0"); return mediaId ? `${n}-${mediaId}.${ext}` : `${n}.${ext}`; } function fileOf(url: string, raw: Record, fallbackNum: number): InstagramMediaFile | null { if (!/^https:\/\//i.test(url)) return null; // A music track of a post is not its picture or video. if (str(raw.audio_url)) return null; // A video item yields its video (and no picture); a picture has no video_url. const kind: "image" | "video" = str(raw.video_url) ? "video" : "image"; const given = countOf(raw.num); const num = given !== undefined && given >= 1 ? given : fallbackNum; const ext = extensionOf(raw, url, kind); return { num, kind, url, name: instagramMediaFileName(num, idOf(raw.media_id), ext) }; } function coauthorsOf(raw: unknown, owner: string, channelHandle: string): NonNullable["coauthors"]> { const out: NonNullable["coauthors"]> = []; const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase(); if (Array.isArray(raw)) { for (const item of raw) { if (!item || typeof item !== "object") continue; const c = item as Record; const handle = str(c.username); if (!handle || same(handle, owner) || out.some((o) => same(o.handle, handle))) continue; const id = idOf(c.id); const name = str(c.full_name); out.push({ handle, ...(name ? { name } : {}), ...(id ? { id } : {}) }); } } // A post the channel's account did not make is on its grid as a // collaboration: the account is among the coauthors even when the row // names none. if (channelHandle && !same(channelHandle, owner) && !out.some((o) => same(o.handle, channelHandle))) { out.push({ handle: channelHandle }); } return out; } // One post row as a Post, or null when it is not one this slice archives // ("other") or cannot be read ("unreadable"). export function normalizeInstagramPost( raw: Record, ctx: { channelSlug: string; handle: string }, ): { post: Post; pinned: boolean } | "other" | "unreadable" { const type = str(raw.type) ?? "post"; if (type !== "post" && type !== "reel") return "other"; const id = idOf(raw.post_id); const createdAt = instagramDateToIso(raw.post_date ?? raw.date); if (!id || !isInstagramPk(id) || !createdAt) return "unreadable"; const kind = type === "reel" ? "reel" : "post"; const given = str(raw.post_shortcode); const shortcode = given && isInstagramShortcode(given) ? given : (instagramShortcodeFromPk(id) ?? undefined); const author = str(raw.username) ?? ctx.handle; const authorName = str(raw.fullname); const text = typeof raw.description === "string" ? raw.description : ""; const pinned = Array.isArray(raw.pinned) ? raw.pinned.length > 0 : raw.pinned === true; const coauthors = coauthorsOf(raw.coauthors, author, ctx.handle); const count = countOf(raw.count); const likes = countOf(raw.likes); const post: Post = { id, slug: postSlug(ctx.channelSlug, id), channelSlug: ctx.channelSlug, author, ...(authorName ? { authorName } : {}), createdAt, uploadDate: uploadDateFromCreatedAt(createdAt), text, url: shortcode ? instagramPostUrl(kind, shortcode) : (str(raw.post_url) ?? ""), platform: "instagram", isReply: false, isRepost: false, links: linksIn(text), ...(count !== undefined ? { mediaCount: count } : {}), ...(likes !== undefined ? { engagement: { likes } } : {}), instagram: { kind, ...(shortcode ? { shortcode } : {}), ...(pinned ? { pinned: true } : {}), ...(coauthors.length > 0 ? { coauthors } : {}), }, }; return { post, pinned }; } // Everything a run printed, in the order it printed it. A post met twice (a // pinned post is on the grid again further down) is kept once, the first time. export function parseInstagramRun(stdout: string, ctx: { channelSlug: string; handle: string }): InstagramRunRows | null { const text = stdout.trim(); if (!text) return null; let rows: unknown; try { rows = JSON.parse(quoteBigIntegers(text)); } catch { return null; } if (!Array.isArray(rows)) return null; const out: InstagramRunRows = { posts: [], emitted: 0, unreadable: 0, otherKinds: 0 }; const byId = new Map(); let current: InstagramListedPost | null = null; for (const row of rows) { if (!Array.isArray(row)) continue; const [tag, a, b] = row as [unknown, unknown, unknown]; if (tag === -1 && a && typeof a === "object") { const e = a as Record; out.error = { error: str(e.error) ?? "Error", message: str(e.message) ?? "" }; continue; } if (tag === 2 && a && typeof a === "object") { const rowIndex = out.emitted; out.emitted++; const n = normalizeInstagramPost(a as Record, ctx); if (n === "other") { out.otherKinds++; current = null; continue; } if (n === "unreadable") { out.unreadable++; current = null; continue; } const seen = byId.get(n.post.id); if (seen) { // The files of a repeat are the same files: not listed twice. current = null; continue; } current = { post: n.post, row: rowIndex, pinned: n.pinned, files: [] }; byId.set(n.post.id, current); out.posts.push(current); continue; } if (tag === 3 && typeof a === "string" && current) { const file = fileOf(a, b && typeof b === "object" ? (b as Record) : {}, current.files.length + 1); if (file && !current.files.some((f) => f.name === file.name)) current.files.push(file); } } for (const p of out.posts) { // The row's own count is of every file (a track included): what the // archive counts is the pictures and videos it listed. if (p.files.length > 0) p.post.mediaCount = p.files.length; } return out; }