// Capturing specific Bluesky posts (release 29 E1): a screenshot of each post // as bsky.app renders it, and its images, into `posts-media//` // (postCapture.ts owns the layout and the record). No login, ever. // // TWO SOURCES, EACH ASKED AS LITTLE AS IT CAN BE: // - the public AppView (`app.bsky.feed.getPosts`, 25 posts a request, the // same batch the deleted-post sweep uses) says which posts are live — one // absent from the answer is deleted, recorded as X's capture records it — // and where each live post's images are (`embed.images[].fullsize`, or a // recordWithMedia's `media.images`); // - a headless Chromium, ONE fresh context with no profile and no cookies, // opens each live post's page (`bsky.app/profile//post/`), // waits for the post (`[data-testid="postThreadItem-by-"]`) and // shoots that element — cropped to the post, not the page — as shot.png. // // PACED: one page at a time, a real gap (3–6 s, jittered; a channel's // `postPagePauseSeconds` raises it) before every page after the first, a // timeout per page, cancellable between and during posts. A 429 from the // AppView or the CDN is waited out (its Retry-After, else 5 s, 10 s, … capped) // and asked again a few times; one that persists stops the run there, the // rest left for a later run. A page that answers 429 is waited out once; a // second stops the run. // // What a capture finds, per post: // captured live, shot (and its images downloaded) // deleted absent from getPosts — the platform says the post is gone; no // page is opened, and what an earlier capture took is kept // error the page did not show the post (a timeout, an author who // shows posts only to signed-in users, a post the page could // not tell from others), or an image failed; a later run tries // again // // Base URLs are injectable (deps.endpoints; blueskyEndpoints.ts for the e2e // suite's fake), and so is everything that waits or touches the network. import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { postPermalink, type PostAvailability } from "../lib/posts"; import { parseRetryAfterMs } from "../lib/archiveOrgClient"; import { blueskyEndpoints, onBlueskyEndpoints, type BlueskyEndpoints } from "./blueskyEndpoints"; import type { PostCaptureInput, PostCaptureOutcome, PostCaptureResult } from "./fetchers"; import { importPlaywright, type PageLike } from "./playwrightRuntime"; import { captureWork, describeCapturedFile, postCaptureDir, readPostCapture, SHOT_FILENAME, writePostCapture, type CapturedFile, type CaptureMediaState, type PostCaptureRecord, type PostCaptureState, } from "./postCapture"; // ─── The AppView's answer (only what the capture reads) ─── type ImageView = { fullsize?: string; thumb?: string; alt?: string }; export type BlueskyPostView = { uri?: string; author?: { did?: string; handle?: string }; record?: { text?: string }; embed?: { $type?: string; images?: ImageView[]; media?: { images?: ImageView[] } }; }; const rkeyOf = (uri: string | undefined): string | null => { const i = uri?.lastIndexOf("/") ?? -1; return uri && i >= 0 && i < uri.length - 1 ? uri.slice(i + 1) : null; }; // A live post's images, as the AppView names them: an images embed, or the // media half of a recordWithMedia. The full-size URL, else the thumbnail. export function blueskyPostImages(view: BlueskyPostView): { url: string; alt?: string }[] { const list = view.embed?.images ?? view.embed?.media?.images ?? []; const out: { url: string; alt?: string }[] = []; for (const im of list) { const url = im?.fullsize ?? im?.thumb; if (typeof url !== "string" || !/^https?:\/\//.test(url)) continue; out.push({ url, ...(im.alt ? { alt: im.alt } : {}) }); } return out; } // getPosts' documented ceiling. export const GET_POSTS_BATCH = 25; // The gap before each page after a run's first: 3–6 s, or the channel's own // pause (at least 3 s) jittered to [1, 2) of itself. export const MIN_PAGE_GAP_MS = 3_000; export function blueskyPageGapMs(random: () => number, baseMs?: number): number { const base = Math.max(MIN_PAGE_GAP_MS, baseMs ?? MIN_PAGE_GAP_MS); return Math.round(base * (1 + random())); } // ─── Deps ─── export type BlueskyCaptureDeps = { fetch: (url: string, init?: RequestInit) => Promise; endpoints: BlueskyEndpoints; // A page in a fresh browser context: opened on the first shot, closed at the // end of the run. openPage: () => Promise<{ page: PageLike; close: () => Promise }>; // The gap before each page after the first, before each AppView request // after the first (a handle's DID, a getPosts batch), and between two images. pageGapMs: () => number; apiGapMs: () => number; imageGapMs: () => number; pause: (ms: number, signal: AbortSignal) => Promise; now?: () => Date; // A 429/503 retry's wait when the answer names none (doubling per attempt), // its cap, and how many attempts a request gets. backoffBaseMs?: number; backoffMaxMs?: number; maxAttempts?: number; // How long a page may take to load, and the post to appear on it. pageTimeoutMs?: number; postTimeoutMs?: number; }; export function sleepUnlessAborted(ms: number, signal: AbortSignal): Promise { return new Promise((resolve) => { if (ms <= 0 || signal.aborted) return resolve(); const timer = setTimeout(done, ms); function done() { clearTimeout(timer); signal.removeEventListener("abort", done); resolve(); } signal.addEventListener("abort", done, { once: true }); }); } // A headless Chromium with a fresh context: no profile directory, no cookies, // no stored state — what a logged-out reader sees. export async function openFreshBlueskyPage(): Promise<{ page: PageLike; close: () => Promise }> { const { chromium } = await importPlaywright(); const browser = await chromium.launch({ headless: true }); try { const context = await browser.newContext({ viewport: { width: 1280, height: 1600 }, deviceScaleFactor: 2, locale: "en-US", colorScheme: "light", }); const page = await context.newPage(); return { page, close: async () => { await context.close().catch(() => {}); await browser.close().catch(() => {}); }, }; } catch (err) { await browser.close().catch(() => {}); throw err; } } export function liveBlueskyCaptureDeps(input: Pick): BlueskyCaptureDeps { return { fetch: (url, init) => fetch(url, init), endpoints: blueskyEndpoints(), openPage: openFreshBlueskyPage, pageGapMs: () => blueskyPageGapMs(Math.random, input.pagePauseMs), imageGapMs: () => 1_000 + Math.round(Math.random() * 1_000), apiGapMs: () => 1_000 + Math.round(Math.random() * 1_000), pause: sleepUnlessAborted, }; } // ─── Requests, with the 429 back-off ─── type Got = | { ok: true; res: Response } | { ok: false; error: string; rateLimited?: boolean; status?: number }; async function politeGet( deps: BlueskyCaptureDeps, url: string, accept: string, signal: AbortSignal, onLog?: (line: string) => void, ): Promise { const attempts = deps.maxAttempts ?? 4; const base = deps.backoffBaseMs ?? 5_000; const cap = deps.backoffMaxMs ?? 120_000; const now = () => (deps.now ?? (() => new Date()))().getTime(); let last = ""; for (let attempt = 1; attempt <= attempts; attempt++) { let res: Response; try { res = await deps.fetch(url, { signal, headers: { accept } }); } catch (err) { if (signal.aborted) return { ok: false, error: "cancelled" }; return { ok: false, error: firstLine(err) }; } if (res.ok) return { ok: true, res }; if (res.status !== 429 && res.status !== 503) { await res.arrayBuffer().catch(() => {}); return { ok: false, error: `HTTP ${res.status}`, status: res.status }; } last = `HTTP ${res.status}`; await res.arrayBuffer().catch(() => {}); if (attempt === attempts) break; const wait = Math.min(cap, parseRetryAfterMs(res.headers.get("retry-after"), now()) ?? base * 2 ** (attempt - 1)); onLog?.(`Bluesky answered ${res.status}; waiting ${Math.round(wait / 1000)} s before asking again.`); await deps.pause(wait, signal); if (signal.aborted) return { ok: false, error: "cancelled" }; } return { ok: false, error: `Bluesky kept answering ${last} after ${attempts} attempts`, rateLimited: true }; } // ─── One page's shot ─── // The post on its page. A self-thread's parents and replies by the same // author share the anchor's test id, and a short reply ("lol") is a substring // of many a parent, so the post is found by what is its own and nothing else's: // 1. the item holding a link to its own permalink (…/post/); // 2. else the item holding an element whose whole text IS the post's text; // 3. else the only item by the author on the page. // Two items matching the same rule are ambiguous: no shot (an error), never a // shot of the wrong post. Marked for the shot; its box in document coordinates. export const SNAPSHOT_SCRIPT = (handle: string, text: string, rkey: string) => `(() => { const sel = ${JSON.stringify(`[data-testid="postThreadItem-by-${handle}"]`)}; const rkey = ${JSON.stringify(rkey)}; const norm = (s) => (s || "").replace(/\\s+/g, " ").trim().toLowerCase(); const want = norm(${JSON.stringify(text)}); const all = Array.from(document.querySelectorAll(sel)); const ownLink = (el) => Array.from(el.querySelectorAll("a[href]")).some((a) => { try { return new URL(a.getAttribute("href"), location.href).pathname.replace(/\\/+$/, "").endsWith("/post/" + rkey); } catch { return false; } }); const exactText = (el) => want !== "" && Array.from(el.querySelectorAll("*")).some((d) => norm(d.innerText) === want); let own = null; let ambiguous = 0; for (const rule of [ownLink, exactText]) { const hits = all.filter(rule); if (hits.length === 1) { own = hits[0]; break; } if (hits.length > 1) { ambiguous = hits.length; break; } } if (!own && !ambiguous && all.length === 1) own = all[0]; for (const el of document.querySelectorAll("[data-archilyzer-capture]")) el.removeAttribute("data-archilyzer-capture"); if (!own) return { count: all.length, ambiguous, rect: null, text: norm(document.body && document.body.innerText).slice(0, 2000) }; own.setAttribute("data-archilyzer-capture", ""); const r = own.getBoundingClientRect(); return { count: all.length, ambiguous: 0, rect: { x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height }, text: "" }; })()`; // Let the post's images finish loading (each capped), so the shot is not of // grey boxes. const IMAGES_LOADED_SCRIPT = `(() => { const own = document.querySelector("[data-archilyzer-capture]") || document; const imgs = Array.from(own.querySelectorAll("img")).filter((i) => !i.complete); return Promise.all(imgs.map((i) => new Promise((r) => { i.addEventListener("load", r, { once: true }); i.addEventListener("error", r, { once: true }); setTimeout(r, 5000); }))).then(() => imgs.length); })()`; type Snapshot = { count: number; ambiguous?: number; rect: { x: number; y: number; width: number; height: number } | null; text: string }; export type BlueskyShotResult = { state: PostCaptureState; shot?: CapturedFile; error?: string; // The page answered 429. rateLimited?: boolean; }; function raceAbort(p: Promise, signal: AbortSignal): Promise { if (signal.aborted) return Promise.reject(new Error("cancelled")); return new Promise((resolve, reject) => { const onAbort = () => reject(new Error("cancelled")); signal.addEventListener("abort", onAbort, { once: true }); p.then( (v) => { signal.removeEventListener("abort", onAbort); resolve(v); }, (e) => { signal.removeEventListener("abort", onAbort); reject(e); }, ); }); } // One post's screenshot: load its page, wait for the post, shoot that element. // Writes `shot.png` into `dir` only for a post that rendered. `url` is the // page to open; `canonicalUrl` the bsky.app URL the record names. export async function shootBlueskyPost( page: PageLike, o: { url: string; canonicalUrl: string; handle: string; // The post's rkey: an item holding a link to it is the post. rkey: string; text: string; dir: string; signal: AbortSignal; pageTimeoutMs?: number; postTimeoutMs?: number; }, ): Promise { let response: unknown; try { response = await raceAbort( page.goto(o.url, { waitUntil: "domcontentloaded", timeout: o.pageTimeoutMs ?? 45_000 }), o.signal, ); } catch (err) { return { state: "error", error: `Could not load ${o.canonicalUrl}: ${firstLine(err)}` }; } const status = (response as { status?: () => number } | null)?.status?.(); if (status === 429) return { state: "error", error: "bsky.app answered 429", rateLimited: true }; const sel = `[data-testid="postThreadItem-by-${o.handle}"]`; const appeared = await raceAbort( page.waitForSelector(sel, { timeout: o.postTimeoutMs ?? 20_000 }).then( () => true, () => false, ), o.signal, ).catch(() => false); if (o.signal.aborted) return { state: "error", error: "cancelled" }; if (!appeared) { const snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text, o.rkey)).catch(() => null)) as Snapshot | null; const body = snap?.text ?? ""; if (/sign in|log in/.test(body) && /(required|to view|logged-in|signed-in)/.test(body)) { return { state: "error", error: "The author shows their posts only to signed-in users; the capture has no login." }; } return { state: "error", error: `The post did not render (no ${sel} on the page).` }; } await page.waitForTimeout(1_000); let snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text, o.rkey))) as Snapshot; if (!snap.rect) { return { state: "error", error: snap.ambiguous ? `${snap.ambiguous} posts by @${o.handle} on the page match this one; none shot rather than the wrong one.` : `${snap.count} posts by @${o.handle} on the page, none of them this one (by its link or its whole text).`, }; } await page.evaluate(IMAGES_LOADED_SCRIPT).catch(() => {}); // Re-read the box: images that loaded may have grown it. snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text, o.rkey))) as Snapshot; const rect = snap.rect; if (!rect || rect.width < 1 || rect.height < 1) { return { state: "error", error: "The post rendered with no size to shoot." }; } let png: Uint8Array; try { // fullPage, so a post taller than the window is shot whole; the clip is in // document coordinates, which is what the snapshot measured. png = await page.screenshot({ type: "png", fullPage: true, clip: { x: Math.max(0, Math.floor(rect.x)), y: Math.max(0, Math.floor(rect.y)), width: Math.ceil(rect.width), height: Math.ceil(rect.height), }, }); } catch (err) { return { state: "error", error: `The screenshot failed: ${firstLine(err)}` }; } await mkdir(o.dir, { recursive: true }); await writeFile(path.join(o.dir, SHOT_FILENAME), png); return { state: "captured", shot: await describeCapturedFile(o.dir, SHOT_FILENAME, o.canonicalUrl) }; } // ─── The images ─── const EXT_BY_TYPE: Record = { "image/jpeg": "jpg", "image/png": "png", "image/gif": "gif", "image/webp": "webp", "image/avif": "avif", }; function imageExt(url: string, contentType: string | null): string { const ct = (contentType ?? "").split(";")[0].trim().toLowerCase(); if (EXT_BY_TYPE[ct]) return EXT_BY_TYPE[ct]; // The CDN names the format after an "@": …/@jpeg. const at = /@(jpeg|jpg|png|webp|gif)$/i.exec(url); if (at) return at[1].toLowerCase() === "jpeg" ? "jpg" : at[1].toLowerCase(); const m = /\.([a-z0-9]{2,5})(?:[?#]|$)/i.exec(url); return m ? m[1].toLowerCase() : "jpg"; } // ─── The run ─── // A run's errors in a row that stop it: a host whose network or browser is // failing every post should not page through the rest of the list. const STOP_AFTER_ERRORS = 3; export async function captureBlueskyPosts( input: PostCaptureInput, deps: BlueskyCaptureDeps, ): Promise { const { signal, onLog } = input; const wanted = { shots: input.shots ?? true, media: input.media ?? true, force: input.force ?? false }; const now = deps.now ?? (() => new Date()); const outcomes: PostCaptureOutcome[] = []; const stopped = (why: string): PostCaptureResult => { onLog?.(why); return { outcomes, stoppedEarly: why }; }; // What each post is owed, from what is on disk. const owed: { id: string; dir: string; existing: PostCaptureRecord | null; shot: boolean; media: boolean }[] = []; for (const id of input.ids) { const dir = postCaptureDir(input.outDir, id); const existing = await readPostCapture(dir); const work = captureWork(existing, { ...wanted, articles: false }); if (!work.shot && !work.media) { onLog?.(`${id}: already captured (${existing?.state ?? "nothing asked for"}) — skipped.`); continue; } owed.push({ id, dir, existing, shot: work.shot, media: work.media }); } if (owed.length === 0) return { outcomes }; // EACH POST UNDER ITS OWN AUTHOR. A repost is archived under the original's // rkey and author (normalizeBlueskyItem), so the channel's own DID would not // find it, and its absence would read as a deletion. Each owed post is looked // up as at:///…/ (the author from the archive; a // handle resolved once). An absence is a deletion only from a batch asked // under the post's own author; a post whose author is not known, or whose // author did not resolve, learns nothing (never `deleted`). const appview = deps.endpoints.appview; let calls = 0; const apiCall = async (url: string): Promise => { if (calls++ > 0) await deps.pause(deps.apiGapMs(), signal); if (signal.aborted) return { ok: false, error: "cancelled" }; return politeGet(deps, url, "application/json", signal, onLog); }; const authorOf = (id: string): string | null => input.archived?.get(id)?.author?.trim().replace(/^@/, "") || null; const byAuthor = new Map(); const unanswered = new Map(); for (const o of owed) { const author = authorOf(o.id); if (!author) { unanswered.set(o.id, "the archive names no author for this post; nothing learned"); continue; } const list = byAuthor.get(author) ?? []; list.push(o); byAuthor.set(author, list); } const views = new Map(); for (const [author, posts] of byAuthor) { let did = author; if (!did.startsWith("did:")) { const got = await apiCall(`${appview}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(author)}`); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (!got.ok && got.rateLimited) return stopped(`${got.error}; stopping — the posts are left for a later run.`); const body = got.ok ? ((await got.res.json().catch(() => null)) as { did?: string } | null) : null; if (!body?.did) { // The account itself did not answer: no evidence about its posts. const why = `could not resolve @${author}: ${got.ok ? "no DID in the answer" : got.error}`; onLog?.(`${why} — ${posts.length} post(s) left as they were.`); for (const o of posts) unanswered.set(o.id, why); continue; } did = body.did; } // Liveness and images, 25 posts a request, a gap between requests. for (let i = 0; i < posts.length; i += GET_POSTS_BATCH) { const batch = posts.slice(i, i + GET_POSTS_BATCH); const params = new URLSearchParams(); for (const o of batch) params.append("uris", `at://${did}/app.bsky.feed.post/${o.id}`); const got = await apiCall(`${appview}/xrpc/app.bsky.feed.getPosts?${params.toString()}`); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (!got.ok) { if (got.rateLimited) return stopped(`${got.error}; stopping — the posts are left for a later run.`); for (const o of batch) unanswered.set(o.id, `getPosts failed: ${got.error}`); continue; } const body = (await got.res.json().catch(() => null)) as { posts?: BlueskyPostView[] } | null; if (!body || !Array.isArray(body.posts)) { for (const o of batch) unanswered.set(o.id, "getPosts answered no post list"); continue; } for (const v of body.posts) { const rkey = rkeyOf(v.uri); // Only the answer for the post asked: its own author's record. if (rkey && v.uri === `at://${did}/app.bsky.feed.post/${rkey}`) views.set(rkey, v); } } } let pages = 0; let errorsInARow = 0; let browser: { page: PageLike; close: () => Promise } | undefined; try { for (const [i, o] of owed.entries()) { if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); const { id, dir, existing } = o; onLog?.(`[${i + 1}/${owed.length}] ${id}`); const view = views.get(id); const failedLookup = unanswered.get(id); const author = view?.author?.handle || authorOf(id) || input.handle; const canonicalUrl = postPermalink("bluesky", author, id); let state: PostCaptureState; let availability: PostAvailability | undefined; let shot = existing?.shot; let mediaState: CaptureMediaState = existing?.mediaState ?? "skipped"; let media: CapturedFile[] = existing?.media ?? []; let error: string | undefined; let stop: string | undefined; if (failedLookup) { // Nothing learned about the post: what is on disk stands. state = "error"; error = failedLookup; } else if (!view) { // The platform says it is gone. What an earlier capture took is kept. state = "deleted"; availability = "deleted"; } else { availability = "available"; // A run that does not shoot keeps the shot's verdict on disk. state = o.shot ? "error" : (existing?.state ?? "captured"); if (o.shot) { if (pages++ > 0) await deps.pause(deps.pageGapMs(), signal); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); browser ??= await deps.openPage(); const shotArgs = { url: onBlueskyEndpoints(`https://bsky.app/profile/${author}/post/${id}`, deps.endpoints), canonicalUrl, handle: author, rkey: id, text: view.record?.text ?? "", dir, signal, ...(deps.pageTimeoutMs ? { pageTimeoutMs: deps.pageTimeoutMs } : {}), ...(deps.postTimeoutMs ? { postTimeoutMs: deps.postTimeoutMs } : {}), }; let res = await shootBlueskyPost(browser.page, shotArgs); if (res.rateLimited) { const wait = Math.max(deps.backoffBaseMs ?? 30_000, deps.pageGapMs()); onLog?.(`bsky.app answered 429; waiting ${Math.round(wait / 1000)} s before one more try.`); await deps.pause(wait, signal); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); res = await shootBlueskyPost(browser.page, shotArgs); if (res.rateLimited) stop = "bsky.app answered 429 twice; stopping."; } state = res.state; if (res.shot) shot = res.shot; if (res.error) error = res.error; } const postIsThere = state === "captured" || !o.shot; if (o.media && postIsThere && !stop) { const images = blueskyPostImages(view); if (images.length === 0) { mediaState = "none"; media = []; } else { media = []; let failed = 0; for (const [n, im] of images.entries()) { if (n > 0) await deps.pause(deps.imageGapMs(), signal); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); const got = await politeGet(deps, onBlueskyEndpoints(im.url, deps.endpoints), "image/*", signal, onLog); if (!got.ok) { failed++; onLog?.(`${id}: image ${n + 1} failed: ${got.error}`); if (got.rateLimited) { stop = `${got.error}; stopping.`; break; } continue; } const name = `media-${n + 1}.${imageExt(im.url, got.res.headers.get("content-type"))}`; await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, name), new Uint8Array(await got.res.arrayBuffer())); media.push(await describeCapturedFile(dir, name, im.url)); } mediaState = failed > 0 ? "error" : "ok"; if (failed > 0) error = error ? `${error}; ${failed} image(s) failed` : `${failed} image(s) failed`; } if (!o.shot && !existing && mediaState === "error") state = "error"; } } const record: PostCaptureRecord = { version: 1, id, url: canonicalUrl, capturedAt: now().toISOString(), state, ...(shot ? { shot } : {}), mediaState, media, ...(error ? { error } : {}), }; await writePostCapture(dir, record); outcomes.push({ id, state, ...(availability ? { availability } : {}), files: (shot ? 1 : 0) + media.length, ...(error ? { error } : {}), }); onLog?.( `${id}: ${state}` + (state === "captured" && o.shot ? ", shot" : "") + (mediaState === "ok" ? `, ${media.length} image(s)` : mediaState === "none" && view ? ", no images" : "") + (error ? ` — ${error}` : ""), ); if (stop) return stopped(`${stop} Stopped at ${id}; the rest are left for a later run.`); errorsInARow = state === "error" ? errorsInARow + 1 : 0; if (errorsInARow >= STOP_AFTER_ERRORS) { return stopped(`${STOP_AFTER_ERRORS} posts in a row failed; stopping rather than paging through the rest.`); } } return { outcomes }; } finally { await browser?.close().catch(() => {}); } } function firstLine(err: unknown): string { return ((err as Error)?.message ?? String(err)).split("\n")[0]; }