// Reading X authors' avatars off a post page capture-posts has ALREADY loaded, // and saving them into the channel's avatar store (xAvatars.ts). // // NO EXTRA PAGE LOAD. The read is one evaluate over the page as it stands: the // post's own article (xPostCapture.ts marks it) and its author's avatar // container — X draws `[data-testid="Tweet-User-Avatar"]` holding // `[data-testid="UserAvatar-Container-"]`, a link to `/` and an // . With // the thread on, also the post it answers (the archive's replyTo id, else the // article directly above — the thread shot's own pick, xThreadShot.ts) and the // post it quotes (an avatar container inside the article's quote card, // `[role="link"]`). // // THE DOWNLOAD goes through the page's own request context (`page.request`, a // Playwright APIRequestContext that IS the browser context's: the profile's // cookies, no tab, no navigation) — the same route an X Article's images take // (xArticleCapture.ts), chosen over an in-page fetch() because pbs.twimg.com's // CORS answer is not ours to rely on and the bytes would have to cross the // evaluate boundary as base64. One GET per author per run, of the _400x400 // size; nothing is retried. It is a request to X's image CDN for a picture the // page has just drawn, so it takes no post gap of its own (the page load that // preceded it took one). // // NOT VERIFIED AGAINST LIVE X: the markup is X's as of 2026-11, proved against // a recorded-style fixture page in a real Chromium (xAvatarCapture.browser // test); the first real run is the check. import type { PageLike } from "./playwrightRuntime"; import { isXAvatarHandle, lookupXAvatar, readXAvatarIndex, upgradeXAvatarUrl, writeXAvatar, } from "./xAvatars"; export const AVATARS_SCRIPT_MARKER = "__archilyzerAvatars"; export type XAvatarRole = "author" | "parent" | "quoted"; export type XAvatarCandidate = { role: XAvatarRole; handle: string; src: string }; export type XAvatarReadOptions = { // The post it answers, and the quoted post: read only with the thread on. parent?: boolean; quotes?: boolean; // The archive's word for the parent: its status id. Not on the page means // no parent (the article above would be another post of the thread). parentId?: string | null; }; // The in-page read. Each article's author avatar: the container inside // Tweet-User-Avatar, else the first container not inside a quote card. The // handle from the container's test id, else its profile link; the picture from // its , else a background-image. export const avatarsScript = (o: XAvatarReadOptions = {}) => `(() => { const ${AVATARS_SCRIPT_MARKER} = true; const wantParent = ${o.parent ? "true" : "false"}; const wantQuotes = ${o.quotes ? "true" : "false"}; const parentId = ${JSON.stringify(o.parentId ?? null)}; const all = Array.from(document.querySelectorAll('article[data-testid="tweet"]')); const own = document.querySelector("[data-archilyzer-capture]"); if (!own) return []; const HANDLE = /^[A-Za-z0-9_]{1,30}$/; const handleOf = (c) => { const t = (c.getAttribute("data-testid") || "").replace(/^UserAvatar-Container-/, ""); if (HANDLE.test(t)) return t; for (const l of c.querySelectorAll("a[href]")) { const m = /^\\/([A-Za-z0-9_]{1,30})\\/?$/.exec(l.getAttribute("href") || ""); if (m) return m[1]; } return null; }; const srcOf = (c) => { const img = c.querySelector("img[src]"); if (img && img.src) return img.src; for (const el of c.querySelectorAll("*")) { const m = /url\\(["']?([^"')]+)["']?\\)/.exec(el.style && el.style.backgroundImage || ""); if (m) return new URL(m[1], location.href).href; } return null; }; const read = (c, role) => { const handle = handleOf(c); const src = srcOf(c); return handle && src ? { role, handle, src } : null; }; const containers = (a) => Array.from(a.querySelectorAll('[data-testid^="UserAvatar-Container-"]')); const inQuote = (c, a) => { const q = c.closest('[role="link"]'); return !!q && a.contains(q) && q !== a; }; const authorContainer = (a) => { const box = a.querySelector('[data-testid="Tweet-User-Avatar"]'); const inBox = box && (box.matches('[data-testid^="UserAvatar-Container-"]') ? box : box.querySelector('[data-testid^="UserAvatar-Container-"]')); return inBox || containers(a).find((c) => !inQuote(c, a)) || null; }; const out = []; const mine = authorContainer(own); const author = mine && read(mine, "author"); if (author) out.push(author); if (wantQuotes) { for (const c of containers(own)) { if (c === mine || !inQuote(c, own)) continue; const q = read(c, "quoted"); if (q) out.push(q); } } if (wantParent) { const ownIdx = all.indexOf(own); const top = own.getBoundingClientRect().top; const idOf = (a) => { for (const l of a.querySelectorAll('a[href*="/status/"]')) { const m = /\\/status\\/(\\d+)/.exec(l.getAttribute("href") || ""); if (m && l.querySelector("time")) return m[1]; } return null; }; const above = all.filter((a, i) => i < ownIdx && a.getBoundingClientRect().bottom <= top + 2); const parent = parentId ? above.find((a) => idOf(a) === parentId) : above[above.length - 1]; const pc = parent && authorContainer(parent); const p = pc && read(pc, "parent"); if (p) out.push(p); } return out; })()`; const ROLES = new Set(["author", "parent", "quoted"]); // What the read returned, kept to the shape (anything else is no avatar). export function parseAvatarCandidates(raw: unknown): XAvatarCandidate[] { if (!Array.isArray(raw)) return []; const out: XAvatarCandidate[] = []; for (const r of raw) { if (!r || typeof r !== "object") continue; const { role, handle, src } = r as Record; if (typeof role !== "string" || !ROLES.has(role as XAvatarRole)) continue; if (typeof handle !== "string" || !isXAvatarHandle(handle) || typeof src !== "string" || !src) continue; out.push({ role: role as XAvatarRole, handle, src }); } return out; } export async function readXAvatarCandidates(page: PageLike, o: XAvatarReadOptions = {}): Promise { try { return parseAvatarCandidates(await page.evaluate(avatarsScript(o))); } catch { return []; } } export type XAvatarRunSummary = { // Handles stored this run, as X prints them. stored: string[]; // Handles not fetched: already in the store, or X's default picture. skipped: string[]; failed: { handle: string; error: string }[]; // Post pages loaded for the avatars alone (avatarsOnly). pages: number; }; export function emptyAvatarSummary(): XAvatarRunSummary { return { stored: [], skipped: [], failed: [], pages: 0 }; } export type SaveXAvatarsContext = { // The store: `/_avatars`. dir: string; // The post page they were read from. postId: string; // Fetch even an author the store already has. force?: boolean; // Lower-cased handles already handled this run: one fetch per author. seen: Set; summary: XAvatarRunSummary; now?: () => Date; onLog?: (line: string) => void; }; // Fetch and store each candidate's picture, through the page's own request // context. Never throws: a failure is the summary's and the log's. export async function saveXAvatars( page: PageLike, candidates: ReadonlyArray, ctx: SaveXAvatarsContext, ): Promise { const { summary, onLog } = ctx; let index: Awaited> | undefined; for (const c of candidates) { const key = c.handle.toLowerCase(); if (ctx.seen.has(key)) continue; ctx.seen.add(key); index ??= await readXAvatarIndex(ctx.dir); if (!ctx.force && lookupXAvatar(index, c.handle)) { summary.skipped.push(c.handle); continue; } const url = upgradeXAvatarUrl(c.src); if (!url) { summary.skipped.push(c.handle); onLog?.(`avatar @${c.handle}: X's default picture (or not X's CDN) — not stored.`); continue; } if (!page.request) { summary.failed.push({ handle: c.handle, error: "this browser page cannot fetch (no request context)" }); continue; } try { const res = await page.request.get(url, { timeout: 30_000, failOnStatusCode: false }); // X's media host rate-limited the avatar: the one X stop (review 1 F1), // and no further avatar is asked in this run. if (res.status() === 429) { const { recordXStop } = await import("../jobs/downloadBackoff"); const { getPaths } = await import("../lib/paths"); await recordXStop("a rate limit (429) to an avatar", getPaths()).catch(() => 0); summary.failed.push({ handle: c.handle, error: `HTTP 429 for ${url}` }); onLog?.(`avatar @${c.handle}: X answered 429 (rate limit); no further avatar is asked.`); break; } if (!res.ok()) throw new Error(`HTTP ${res.status()} for ${url}`); const type = res.headers()["content-type"] ?? ""; if (type && !/^image\//i.test(type)) throw new Error(`${url} answered ${type.split(";")[0]}, not an image`); const bytes = await res.body(); const { handle } = await writeXAvatar(ctx.dir, { handle: c.handle, bytes, url, contentType: type, postId: ctx.postId, capturedAt: (ctx.now ?? (() => new Date()))().toISOString(), }); summary.stored.push(handle); onLog?.(`avatar @${handle} saved (${c.role}${c.role === "author" ? "" : " of " + ctx.postId}).`); } catch (err) { const error = ((err as Error)?.message ?? String(err)).split("\n")[0]; summary.failed.push({ handle: c.handle, error }); onLog?.(`avatar @${c.handle}: ${error}`); } } } export function describeAvatarSummary(s: XAvatarRunSummary): string { return ( `Avatars: ${s.stored.length} saved` + (s.stored.length ? ` (${s.stored.map((h) => "@" + h).join(", ")})` : "") + `, ${s.skipped.length} already stored or default` + (s.failed.length ? `, ${s.failed.length} failed (${s.failed.map((f) => "@" + f.handle).join(", ")})` : "") + (s.pages ? `; ${s.pages} page(s) loaded for them` : "") + "." ); }