commit 224003c8f6574c13459a77d56d38a80f0996604e
parent 6ba247b6417c5cafe546f6c4e9f66e29ccfe17a0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 19:46:44 -0500
common: capture-posts keeps the authors' avatars -- read off the page it loads, fetched through its context; avatarsOnly
An X capture reads the post author's avatar off the page shootXPost already
loaded (Tweet-User-Avatar / UserAvatar-Container-<handle>, the img or its
background-image) and, with the thread on, the parent's (the archive's replyTo
id, else the article above) and the quoted post's. The picture is fetched at
_400x400 through page.request -- the browser context's own request context,
the profile's cookies, no tab and no navigation, as an X Article's images
are -- once per author per run, and an author already stored is not fetched
again unless force (social/xAvatarCapture.ts).
"avatars": false turns it off. "avatarsOnly": true loads ONE post page per
distinct archived author (the first id of each; a stored author costs no
load unless force), paced like every X contact, reads and stores only the
avatars: no shot, media, article or thread shot, no capture.json, nothing in
the availability sidecar. It is a run of its own for nothingToCapture, X's
only (refused by name elsewhere), and needs the session profile.
Proved in a real headless Chromium against a recorded-style status page
(__fixtures__/x-post-avatars.html): x.com answered by the context's router,
every other host unresolvable, the pictures on a loopback server -- one page
load, the page left where it was, each 400x400 fetched once with the
context's cookie (xAvatarCapture.browser.test.ts; skips without Playwright).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
12 files changed, 1131 insertions(+), 12 deletions(-)
diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts
@@ -352,3 +352,64 @@ test("a Wayback pages channel: its records rendered from their captures, no fetc
"1 id(s) not in demo-pages's posts archive: nope",
);
});
+
+test("avatars (X): on by default, off by word; avatarsOnly is its own run, X's only, archived authors passed, nothing recorded", async () => {
+ const root = path.join(channelsDir, "demo-x-avatars");
+ await mkdir(root, { recursive: true });
+ await writeFile(
+ path.join(root, "config.json"),
+ JSON.stringify({
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "twitter",
+ postFetcher: "test-capture-x",
+ socialHandle: "example_user",
+ name: "Example (X avatars)",
+ url: "https://x.com/example_user",
+ }),
+ );
+ const base = {
+ channelSlug: "demo-x-avatars", createdAt: "2026-10-25T04:34:32.000Z", uploadDate: "20261025",
+ platform: "twitter" as const, isRepost: false, isReply: false, links: [],
+ };
+ await writePosts(root, [
+ { ...base, id: "601", slug: "demo-x-avatars/601", author: "ObviousRises", text: "a", url: "https://x.com/ObviousRises/status/601" },
+ { ...base, id: "602", slug: "demo-x-avatars/602", author: "someone_else", text: "b", url: "https://x.com/someone_else/status/602" },
+ ]);
+
+ // A normal run: the fetcher's default (on), or the run's word.
+ calls = [];
+ answer = { outcomes: [] };
+ await run("demo-x-avatars", ["601"], { articles: false });
+ assert.equal(calls[0].avatars, undefined);
+ assert.equal(calls[0].avatarsOnly, undefined);
+ calls = [];
+ await run("demo-x-avatars", ["601"], { articles: false, avatars: false });
+ assert.equal(calls[0].avatars, false);
+
+ // avatarsOnly: a run even with both halves off; each id's archived author
+ // goes with it; an outcome the fetcher (wrongly) returns is not recorded.
+ calls = [];
+ answer = {
+ outcomes: [{ id: "601", state: "deleted", availability: { state: "deleted", checkedAt: "x" } as never, files: 0 }],
+ avatars: { stored: ["ObviousRises"], skipped: [], failed: [], pages: 1 },
+ };
+ const res = await run("demo-x-avatars", ["601", "602"], { avatarsOnly: true, shots: false, media: false, articles: false });
+ assert.equal(res.ok, true);
+ assert.deepEqual(res.outcomes, []);
+ assert.deepEqual(res.avatars?.stored, ["ObviousRises"]);
+ assert.equal(calls[0].avatarsOnly, true);
+ assert.equal(calls[0].archived?.get("601")?.author, "ObviousRises");
+ assert.equal(calls[0].archived?.get("602")?.author, "someone_else");
+ assert.deepEqual(await readPostAvailability(root), {});
+
+ // Another platform keeps none: refused by name, before the fetcher.
+ await makeChannel("demo-social-avatars");
+ calls = [];
+ assert.equal(
+ (await run("demo-social-avatars", ["aaa"], { avatarsOnly: true })).error,
+ "Avatars are X's only; Test capture keeps none.",
+ );
+ assert.equal(calls.length, 0);
+ answer = { outcomes: [] };
+});
diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts
@@ -13,6 +13,11 @@
// of the archive, and an id from somewhere else is refused by name. Each id's
// archived text and links go to the fetcher with it, so a post that is an X
// Article's link is known as one before its page is opened.
+//
+// X also keeps the posts' AUTHORS' AVATARS, read off the page the shot loads,
+// in `posts-media/_avatars/` (social/xAvatars.ts has the store): on by
+// default (`avatars: false` turns it off), and `avatarsOnly` loads one page
+// per archived author for that alone, recording nothing about the posts.
import path from "node:path";
import { isXSearchChannel } from "../lib/xSearch/config";
@@ -39,6 +44,7 @@ import {
type SocialFetcher,
} from "../social/fetchers";
import { postsMediaDir } from "../social/postCapture";
+import type { XAvatarRunSummary } from "../social/xAvatarCapture";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
import {
captureWaybackPageRecords,
@@ -74,6 +80,11 @@ export type CapturePostsOptions = {
// The thread shot's blur of the parent's author (xThreadShot.ts): absent
// is the rule, false off, true always -- for the run or per post id.
threadRedact?: ThreadRedactKnob;
+ // X: save the authors' avatars from the pages the shots load (default
+ // true), or ONLY them -- one page per distinct archived author, no shot,
+ // media, article or thread shot, no capture record, no availability.
+ avatars?: boolean;
+ avatarsOnly?: boolean;
onLog?: (line: string) => void;
signal?: AbortSignal;
// The job's drain: stop between posts.
@@ -88,6 +99,8 @@ export type CapturePostsResult = {
outcomes: PostCaptureOutcome[];
needsCookies?: boolean;
error?: string;
+ // X: what the run did about avatars, when it did anything.
+ avatars?: XAvatarRunSummary;
};
// Why this fetcher cannot capture posts, or null when it can. Shared with the
@@ -105,16 +118,24 @@ export const NOTHING_TO_CAPTURE =
'Nothing to capture: both the screenshot and the media are turned off (to read only the articles, ask for "articles": true; only the thread shots, "thread": true).';
// Both halves off is nothing to do — unless the articles or the thread shots
-// were asked for by name: their defaults alone do not make a run.
+// were asked for by name: their defaults alone do not make a run. An
+// avatars-only run is a run of its own, whatever the halves say.
export function nothingToCapture(o: {
shots?: boolean;
media?: boolean;
articles?: boolean;
thread?: boolean;
+ avatarsOnly?: boolean;
}): boolean {
+ if (o.avatarsOnly === true) return false;
return o.shots === false && o.media === false && o.articles !== true && o.thread !== true;
}
+// The refusal for avatars asked of a platform that keeps none.
+export function avatarsOnlyProblem(platform: string | undefined, label: string): string | null {
+ return platform === "twitter" ? null : `Avatars are X's only; ${label} keeps none.`;
+}
+
// The thread shot's blur knob as a caller wrote it: a boolean for the run, or
// { "<post id>": boolean }. Returns the knob, or the sentence refusing it.
export type ThreadRedactKnob = boolean | Record<string, boolean>;
@@ -163,12 +184,20 @@ export async function capturePosts(
// A Wayback pages channel (release 37 S4): no fetcher — each record is
// rendered from its capture's replay, its images from the archive.
- if (isWaybackPagesChannel(config)) return captureChannelPageRecords(opts, channelRoot, ids);
+ if (isWaybackPagesChannel(config)) {
+ if (opts.avatarsOnly) return fail(avatarsOnlyProblem(undefined, "a Wayback pages channel")!);
+ return captureChannelPageRecords(opts, channelRoot, ids);
+ }
const accountUrl = config.url ?? "";
const fetcher = resolveSocialFetcher(config.postFetcher, accountUrl);
const problem = capturePostsProblem(fetcher);
if (problem || !fetcher?.captureByIds) return fail(problem ?? "This channel has no post fetcher.");
+ const avatarsOnly = opts.avatarsOnly === true;
+ if (avatarsOnly) {
+ const nope = avatarsOnlyProblem(fetcher.platform, fetcher.label);
+ if (nope) return fail(nope);
+ }
// An X search channel has no account (release 38): its posts are any
// author's, and the X capture opens each by its status id alone.
@@ -196,7 +225,7 @@ export async function capturePosts(
let archived: Map<string, Archived> | undefined;
const forum = fetcher.platform === "xenforo";
const bluesky = fetcher.platform === "bluesky";
- if ((opts.articles !== false && fetcher.platform === "twitter") || thread || forum || bluesky) {
+ if ((opts.articles !== false && fetcher.platform === "twitter") || thread || forum || bluesky || avatarsOnly) {
const wanted = new Set(ids);
archived = new Map();
for (const p of await readAllPosts(channelRoot)) {
@@ -207,6 +236,8 @@ export async function capturePosts(
...(forum ? { url: p.url, ...(p.media ? { media: p.media } : {}) } : {}),
// Bluesky looks each post up under its own author (a repost's is the original's).
...(bluesky ? { url: p.url, author: p.author } : {}),
+ // An avatars-only run loads one page per author.
+ ...(avatarsOnly ? { author: p.author } : {}),
// The thread shot tells the parent by the id the reply answers.
...(thread
? {
@@ -225,13 +256,21 @@ export async function capturePosts(
? await resolveXCookieSourceFor(paths, settings, policy.cookies)
: undefined;
- log(
+ if (avatarsOnly) {
+ log(
+ `Capturing the authors' avatars of ${ids.length} post(s) of ${slug} via ${fetcher.label}` +
+ (thread ? " (with the replied-to and quoted authors')" : "") +
+ (opts.force ? ", again where already stored" : "") +
+ ".",
+ );
+ } else log(
`Capturing ${ids.length} post(s) of ${slug} via ${fetcher.label} (@${handle}):` +
[
opts.shots === false ? "" : " screenshot",
opts.media === false ? "" : " media",
opts.articles === false || fetcher.platform !== "twitter" ? "" : " articles",
thread ? ` thread shots${opts.threadRedact === false ? " (no blur)" : ""}` : "",
+ fetcher.platform === "twitter" && opts.avatars !== false ? " avatars" : "",
].join("") +
(opts.force ? ", again where already captured" : "") +
".",
@@ -254,6 +293,8 @@ export async function capturePosts(
articles: opts.articles,
thread,
...(opts.threadRedact !== undefined ? { threadRedact: opts.threadRedact } : {}),
+ ...(opts.avatars !== undefined ? { avatars: opts.avatars } : {}),
+ ...(avatarsOnly ? { avatarsOnly: true } : {}),
archived,
cookies: alwaysCookies(policy),
cookieSource: xLogin?.source,
@@ -268,6 +309,17 @@ export async function capturePosts(
return fail(message);
}
+ const avatars = result.avatars ? { avatars: result.avatars } : {};
+ if (avatarsOnly) {
+ // Nothing about the posts was learned or written: no sidecar, no records.
+ if (result.needsCookies) {
+ return { ok: false, outcomes: [], needsCookies: true, error: result.stoppedEarly ?? "The capture needs an X login.", ...avatars };
+ }
+ const stoppedByOperator = (opts.signal ?? controller.signal).aborted || Boolean(opts.drain?.aborted);
+ if (result.stoppedEarly && !stoppedByOperator) return { ok: false, outcomes: [], error: result.stoppedEarly, ...avatars };
+ return { ok: true, outcomes: [], ...avatars };
+ }
+
// What the pages said about each post, folded into the sidecar.
const observations = new Map<string, PostAvailability>();
for (const o of result.outcomes) {
@@ -302,6 +354,7 @@ export async function capturePosts(
ok: false,
outcomes: result.outcomes,
needsCookies: true,
+ ...avatars,
error:
result.stoppedEarly ??
(forum ? "The capture needs the forum session (Connect)." : "The capture needs an X login."),
@@ -310,9 +363,9 @@ export async function capturePosts(
const stoppedByOperator =
(opts.signal ?? controller.signal).aborted || Boolean(opts.drain?.aborted);
if (result.stoppedEarly && !stoppedByOperator) {
- return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly };
+ return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly, ...avatars };
}
- return { ok: true, outcomes: result.outcomes };
+ return { ok: true, outcomes: result.outcomes, ...avatars };
}
// capture-posts on a Wayback pages channel: the records' shots from their
diff --git a/common/social/__fixtures__/x-avatar-quoted_400x400.jpg b/common/social/__fixtures__/x-avatar-quoted_400x400.jpg
Binary files differ.
diff --git a/common/social/__fixtures__/x-avatar_400x400.jpg b/common/social/__fixtures__/x-avatar_400x400.jpg
Binary files differ.
diff --git a/common/social/__fixtures__/x-avatar_normal.jpg b/common/social/__fixtures__/x-avatar_normal.jpg
Binary files differ.
diff --git a/common/social/__fixtures__/x-post-avatars.html b/common/social/__fixtures__/x-post-avatars.html
@@ -0,0 +1,104 @@
+<!doctype html>
+<!-- An X status page as X draws it (2026-11), cut to what the capture reads:
+ the reply's parent above it, the post itself (its author's avatar, a
+ quoted post's card with its own avatar), and a reply under it. Every
+ picture is on {{ORIGIN}}, the test's loopback server, at X's
+ profile_images path. Recorded-style, hand-trimmed; no live X. -->
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Mr. Obvious on X</title>
+<style>
+ body { margin: 0; background: #000; color: #e7e9ea; font: 15px/20px system-ui, sans-serif; }
+ [data-testid="primaryColumn"] { width: 600px; margin: 0 auto; border-left: 1px solid #2f3336; border-right: 1px solid #2f3336; }
+ article { display: flex; gap: 12px; padding: 12px 16px; border-bottom: 1px solid #2f3336; }
+ [data-testid="Tweet-User-Avatar"] { flex: none; width: 40px; }
+ [data-testid^="UserAvatar-Container-"] { width: 40px; height: 40px; border-radius: 9999px; overflow: hidden; position: relative; }
+ [data-testid^="UserAvatar-Container-"] img { width: 100%; height: 100%; display: block; }
+ .bg { position: absolute; inset: 0; background-size: cover; }
+ .body { flex: 1; min-width: 0; }
+ [data-testid="User-Name"] a { color: inherit; text-decoration: none; }
+ .handle, time { color: #71767b; }
+ .quote { margin-top: 12px; border: 1px solid #2f3336; border-radius: 16px; padding: 12px; }
+ .quote [data-testid^="UserAvatar-Container-"] { width: 20px; height: 20px; display: inline-block; vertical-align: middle; }
+</style>
+</head>
+<body>
+<main role="main">
+<div data-testid="primaryColumn">
+ <section aria-labelledby="accessible-list-1" role="region">
+ <div aria-label="Timeline: Conversation">
+
+ <article aria-labelledby="id-p" role="article" tabindex="0" data-testid="tweet">
+ <div data-testid="Tweet-User-Avatar">
+ <div data-testid="UserAvatar-Container-parent_person">
+ <a href="/parent_person" role="link" tabindex="-1">
+ <div class="bg" style="background-image: url("{{ORIGIN}}/profile_images/777/pp_normal.jpg");"></div>
+ <img alt="" draggable="true" src="{{ORIGIN}}/profile_images/777/pp_normal.jpg">
+ </a>
+ </div>
+ </div>
+ <div class="body">
+ <div data-testid="User-Name">
+ <a href="/parent_person" role="link"><span>A Private Person</span></a>
+ <a href="/parent_person" role="link" tabindex="-1"><span class="handle">@parent_person</span></a>
+ <a href="/parent_person/status/1849999999999999990" role="link"><time datetime="2026-10-30T12:00:00.000Z">Oct 30</time></a>
+ </div>
+ <div data-testid="tweetText" lang="en"><span>So what happened next?</span></div>
+ </div>
+ </article>
+
+ <article aria-labelledby="id-o" role="article" tabindex="-1" data-testid="tweet">
+ <div data-testid="Tweet-User-Avatar">
+ <div data-testid="UserAvatar-Container-ObviousRises">
+ <a href="/ObviousRises" role="link" tabindex="-1">
+ <div class="bg" style="background-image: url("{{ORIGIN}}/profile_images/1712345678901234567/Mr_O_normal.jpg");"></div>
+ <img alt="" draggable="true" src="{{ORIGIN}}/profile_images/1712345678901234567/Mr_O_normal.jpg">
+ </a>
+ </div>
+ </div>
+ <div class="body">
+ <div data-testid="User-Name">
+ <a href="/ObviousRises" role="link"><span>Mr. Obvious</span></a>
+ <a href="/ObviousRises" role="link" tabindex="-1"><span class="handle">@ObviousRises</span></a>
+ <a href="/ObviousRises/status/1850000000000000001" role="link"><time datetime="2026-10-31T09:00:00.000Z">9:00 AM · Oct 31, 2026</time></a>
+ </div>
+ <div><span class="handle">Replying to </span><a href="/parent_person" role="link">@parent_person</a></div>
+ <div data-testid="tweetText" lang="en"><span>It is obvious, and here is the receipt.</span></div>
+ <div class="quote" role="link" tabindex="0">
+ <div data-testid="User-Name">
+ <div data-testid="UserAvatar-Container-quoted_person">
+ <div class="bg" style="background-image: url("{{ORIGIN}}/profile_images/888/qq_mini.jpg");"></div>
+ <img alt="" draggable="true" src="{{ORIGIN}}/profile_images/888/qq_mini.jpg">
+ </div>
+ <span>Quoted Person</span> <span class="handle">@quoted_person · Oct 29</span>
+ </div>
+ <div data-testid="tweetText" lang="en"><span>The receipt itself.</span></div>
+ </div>
+ <div role="group" aria-label="3 replies, 5 reposts, 40 likes"><button data-testid="reply" type="button"><span>3</span></button></div>
+ </div>
+ </article>
+
+ <article aria-labelledby="id-r" role="article" tabindex="0" data-testid="tweet">
+ <div data-testid="Tweet-User-Avatar">
+ <div data-testid="UserAvatar-Container-a_replier">
+ <a href="/a_replier" role="link" tabindex="-1">
+ <img alt="" draggable="true" src="{{ORIGIN}}/profile_images/999/rr_normal.jpg">
+ </a>
+ </div>
+ </div>
+ <div class="body">
+ <div data-testid="User-Name">
+ <a href="/a_replier" role="link"><span>Someone Replying</span></a>
+ <a href="/a_replier/status/1850000000000000009" role="link"><time datetime="2026-10-31T10:00:00.000Z">Oct 31</time></a>
+ </div>
+ <div data-testid="tweetText" lang="en"><span>A reply under the post: never read.</span></div>
+ </div>
+ </article>
+
+ </div>
+ </section>
+</div>
+</main>
+</body>
+</html>
diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts
@@ -18,6 +18,7 @@ import type { OlderBackfillPosition } from "../lib/posts-server";
import type { ForumWalkState } from "../lib/forumWalk";
import type { XCookieSource } from "./xCookieSource";
import type { PostCaptureState } from "./postCapture";
+import type { XAvatarRunSummary } from "./xAvatarCapture";
export type PostFetchInput = {
// The account's canonical URL as configured on the channel.
@@ -255,6 +256,15 @@ export type PostCaptureInput = Pick<
// (blurred unless verified or the reply's own), false off, true always --
// for the whole run, or per post id (an id not named takes the rule).
threadRedact?: boolean | Readonly<Record<string, boolean>>;
+ // X: read the post author's avatar off the page the shot loads (and, with
+ // the thread on, the parent's and the quoted post's authors'), into
+ // `<outDir>/_avatars/` (xAvatars.ts). Defaults to true; an author already
+ // stored is not fetched again unless `force`.
+ avatars?: boolean;
+ // X: ONLY the avatars — one post page per distinct archived author, no
+ // shot, no media, no article, no thread shot, and no capture record or
+ // availability observation written. Defaults to false.
+ avatarsOnly?: boolean;
// What the posts archive holds for each id — its text and expanded links —
// for the links a capture follows (an X Article's). Ids absent are read
// from the page alone.
@@ -300,6 +310,8 @@ export type PostCaptureResult = {
// Why the run stopped before its last id, when it did. The ids after it are
// left for a later run — never retried in this one.
stoppedEarly?: string;
+ // X: what the run did about avatars, when it did anything.
+ avatars?: XAvatarRunSummary;
};
// Input for importing ONE post by its URL (`SocialFetcher.fetchOne`, release
diff --git a/common/social/xAvatarCapture.browser.test.ts b/common/social/xAvatarCapture.browser.test.ts
@@ -0,0 +1,237 @@
+// The avatar read and download in a REAL headless Chromium, against a
+// recorded-style X status page (__fixtures__/x-post-avatars.html) — never
+// x.com. The browser's every request to x.com is answered by the fixture
+// through the context's router, anything else not on the test's loopback
+// server is aborted, and the host resolver maps every other name to nowhere,
+// so nothing can leave the machine. The pictures are served by a loopback
+// server at X's profile_images path.
+//
+// What it proves: the read finds the author's, the quoted post's and the
+// parent's avatars in X's markup; the download is the _400x400 size, fetched
+// ONCE per author through the page's own request context (it carries the
+// context's cookie), with no second page load and the page left where it was;
+// an avatars-only run writes no capture record; a normal run shoots the post
+// and reads the avatars from the same load.
+//
+// Skips where Playwright or its Chromium is not installed. With
+// AVATAR_PROOF_DIR set, it leaves a screenshot, the store and a log there.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xAvatarCapture.browser.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { cp, mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { importPlaywright, type PageLike } from "./playwrightRuntime";
+import { captureXPosts, type XCaptureDeps } from "./xPostCapture";
+import { AVATARS_DIRNAME, readXAvatarIndex } from "./xAvatars";
+import { SHOT_FILENAME } from "./postCapture";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIX = path.join(HERE, "__fixtures__");
+const POST_ID = "1850000000000000001";
+const PARENT_ID = "1849999999999999990";
+
+type Served = { path: string; cookie?: string; drawnByPage?: boolean };
+
+async function fixtureServer() {
+ const normal = await readFile(path.join(FIX, "x-avatar_normal.jpg"));
+ const big = await readFile(path.join(FIX, "x-avatar_400x400.jpg"));
+ const quoted = await readFile(path.join(FIX, "x-avatar-quoted_400x400.jpg"));
+ const served: Served[] = [];
+ const server = http.createServer((req, res) => {
+ const p = (req.url ?? "").split("?")[0];
+ served.push({
+ path: p,
+ ...(req.headers.cookie ? { cookie: req.headers.cookie } : {}),
+ ...(req.headers["x-drawn-by"] ? { drawnByPage: true } : {}),
+ });
+ const m = /^\/profile_images\/\d+\/([A-Za-z0-9_-]+?)_(normal|mini|400x400)\.jpg$/.exec(p);
+ if (!m) {
+ res.writeHead(404).end();
+ return;
+ }
+ const body = m[2] !== "400x400" ? normal : m[1] === "Mr_O" ? big : quoted;
+ res.writeHead(200, { "content-type": "image/jpeg", "content-length": body.length }).end(body);
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ const html = (await readFile(path.join(FIX, "x-post-avatars.html"), "utf8")).replaceAll("{{ORIGIN}}", origin);
+ return { origin, html, served, close: () => new Promise<void>((r) => server.close(() => r())) };
+}
+
+type PwPage = PageLike & {
+ url: () => string;
+ mainFrame: () => unknown;
+ on: (event: "framenavigated", cb: (f: { url: () => string }) => void) => void;
+};
+
+test("in a real Chromium: the avatars read off a recorded-style X page and fetched through its own context", async (t) => {
+ let chromium;
+ try {
+ ({ chromium } = await importPlaywright());
+ } catch (err) {
+ t.skip(`Playwright is not installed here: ${(err as Error).message.slice(0, 80)}`);
+ return;
+ }
+ const fx = await fixtureServer();
+ let browser;
+ try {
+ browser = await chromium.launch({
+ headless: true,
+ // Nothing resolves but the loopback server: x.com is answered by the router.
+ args: ["--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"],
+ });
+ } catch (err) {
+ await fx.close();
+ t.skip(`Chromium would not launch: ${(err as Error).message.slice(0, 80)}`);
+ return;
+ }
+ const proofDir = process.env.AVATAR_PROOF_DIR;
+ const log: string[] = [];
+ const onLog = (line: string) => log.push(line);
+ try {
+ const context = (await browser.newContext({ viewport: { width: 1000, height: 900 } })) as unknown as {
+ newPage: () => Promise<PwPage>;
+ route: (url: string, handler: (route: Route) => Promise<void>) => Promise<void>;
+ addCookies: (c: Record<string, unknown>[]) => Promise<void>;
+ close: () => Promise<void>;
+ };
+ type Route = {
+ request: () => { url: () => string; resourceType: () => string };
+ fulfill: (o: Record<string, unknown>) => Promise<void>;
+ continue: () => Promise<void>;
+ abort: () => Promise<void>;
+ };
+ const docLoads: string[] = [];
+ const blocked: string[] = [];
+ await context.route("**/*", async (route) => {
+ const u = new URL(route.request().url());
+ if (u.hostname === "x.com") {
+ docLoads.push(u.pathname);
+ await route.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fx.html });
+ } else if (u.hostname === "127.0.0.1" && u.port === new URL(fx.origin).port) {
+ // The page's own pictures. An https page's http image is mixed
+ // content Chromium upgrades to https, which the loopback server does
+ // not speak: answered from it here, so the page draws them.
+ const r = await fetch(`${fx.origin}${u.pathname}${u.search}`, { headers: { "x-drawn-by": "page" } });
+ await route.fulfill({
+ status: r.status,
+ contentType: r.headers.get("content-type") ?? "application/octet-stream",
+ body: Buffer.from(await r.arrayBuffer()),
+ });
+ } else {
+ blocked.push(u.href);
+ await route.abort();
+ }
+ });
+ // The profile's cookie, as the live context carries X's: the download
+ // must arrive with it.
+ await context.addCookies([{ name: "auth_token", value: "fixture-session", domain: "127.0.0.1", path: "/" }]);
+ const page = await context.newPage();
+ const navs: string[] = [];
+ page.on("framenavigated", (f) => {
+ if (f === page.mainFrame()) navs.push(f.url());
+ });
+
+ const out = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatar-browser-")), "posts-media");
+ const deps: XCaptureDeps = {
+ openPage: async () => ({ page, close: async () => {} }),
+ downloadMedia: async () => ({ ok: true, files: [] }),
+ pauseMs: () => 0,
+ pause: async () => {},
+ };
+ const archived = new Map([
+ [POST_ID, { text: "", author: "ObviousRises", isReply: true, replyTo: { id: PARENT_ID, author: "parent_person" } }],
+ ]);
+
+ // 1. avatarsOnly, thread on: the author's, the quoted post's and the parent's.
+ const res = await captureXPosts(
+ { ids: [POST_ID], handle: "ObviousRises", outDir: out, signal: new AbortController().signal, avatarsOnly: true, thread: true, archived, onLog },
+ deps,
+ );
+ assert.deepEqual(res.outcomes, []);
+ assert.deepEqual(res.avatars?.stored, ["ObviousRises", "quoted_person", "parent_person"], log.join("\n"));
+ assert.deepEqual(res.avatars?.failed, []);
+ // One page load, and the page is where it was.
+ assert.deepEqual(docLoads, [`/i/status/${POST_ID}`]);
+ assert.deepEqual(navs, [`https://x.com/i/status/${POST_ID}`]);
+ assert.equal(page.url(), `https://x.com/i/status/${POST_ID}`);
+ assert.deepEqual(blocked, []);
+ // Each author's 400×400, once, through the context (its cookie on it).
+ const bigs = fx.served.filter((s) => s.path.endsWith("_400x400.jpg"));
+ assert.deepEqual(
+ bigs.map((s) => s.path).sort(),
+ [
+ "/profile_images/1712345678901234567/Mr_O_400x400.jpg",
+ "/profile_images/777/pp_400x400.jpg",
+ "/profile_images/888/qq_400x400.jpg",
+ ],
+ );
+ for (const s of bigs) assert.match(s.cookie ?? "", /auth_token=fixture-session/, s.path);
+ // Not one of them is a picture the page drew: those are the small sizes.
+ assert.ok(bigs.every((s) => !s.drawnByPage));
+ assert.ok(fx.served.some((s) => s.drawnByPage && s.path.endsWith("Mr_O_normal.jpg")), "the page drew the 48px one");
+ // The reply under the post is never read.
+ assert.ok(!fx.served.some((s) => s.path.includes("rr_400x400")));
+ const store = path.join(out, AVATARS_DIRNAME);
+ const index = await readXAvatarIndex(store);
+ assert.deepEqual(Object.keys(index), ["ObviousRises", "parent_person", "quoted_person"]);
+ assert.equal(index.ObviousRises.url, `${fx.origin}/profile_images/1712345678901234567/Mr_O_400x400.jpg`);
+ assert.equal(index.ObviousRises.postId, POST_ID);
+ assert.deepEqual(
+ await readFile(path.join(store, "ObviousRises.jpg")),
+ await readFile(path.join(FIX, "x-avatar_400x400.jpg")),
+ "the stored picture is the 400×400, not the 48px one the page drew",
+ );
+ // No capture record: posts-media holds the store and nothing else.
+ assert.deepEqual(await readdir(out), [AVATARS_DIRNAME]);
+
+ // 2. A normal run on the same page: the shot, and the avatar already
+ // stored is not fetched again.
+ const before = fx.served.filter((s) => s.path.endsWith("_400x400.jpg")).length;
+ const res2 = await captureXPosts(
+ { ids: [POST_ID], handle: "ObviousRises", outDir: out, signal: new AbortController().signal, media: false, articles: false, onLog },
+ deps,
+ );
+ assert.equal(res2.outcomes[0]?.state, "captured", log.join("\n"));
+ assert.deepEqual(res2.avatars?.skipped, ["ObviousRises"]);
+ assert.equal(fx.served.filter((s) => s.path.endsWith("_400x400.jpg")).length, before);
+ assert.deepEqual(docLoads, [`/i/status/${POST_ID}`, `/i/status/${POST_ID}`]);
+ const shot = await readFile(path.join(out, POST_ID, SHOT_FILENAME));
+ assert.equal(shot.readUInt32BE(0), 0x89504e47);
+
+ if (proofDir) {
+ await mkdir(proofDir, { recursive: true });
+ await writeFile(path.join(proofDir, "fixture-page.png"), await page.screenshot({ type: "png", fullPage: true }));
+ await cp(path.join(out, POST_ID, SHOT_FILENAME), path.join(proofDir, "fixture-post-shot.png"));
+ await cp(store, path.join(proofDir, "_avatars"), { recursive: true });
+ await writeFile(
+ path.join(proofDir, "fixture-proof.log"),
+ [
+ `fixture origin: ${fx.origin} (x.com answered by the context router; everything else unresolvable)`,
+ `document loads (x.com): ${JSON.stringify(docLoads)}`,
+ `main-frame navigations: ${JSON.stringify(navs)}`,
+ `page.url() after the runs: ${page.url()}`,
+ `blocked requests: ${JSON.stringify(blocked)}`,
+ "served by the loopback server (path, cookie):",
+ ...fx.served.map(
+ (s) => ` ${s.path}${s.drawnByPage ? " [drawn by the page]" : ""}${s.cookie ? ` [cookie: ${s.cookie}]` : ""}`,
+ ),
+ `avatars.json: ${JSON.stringify(index, null, 2)}`,
+ "run log:",
+ ...log.map((l) => ` ${l}`),
+ "",
+ ].join("\n"),
+ );
+ }
+ await context.close();
+ } finally {
+ await browser.close();
+ await fx.close();
+ }
+});
diff --git a/common/social/xAvatarCapture.test.ts b/common/social/xAvatarCapture.test.ts
@@ -0,0 +1,269 @@
+// The avatar half of the X capture, against fakes only: a page that answers
+// the capture's evaluates (the post's snapshot, the avatar read) and serves
+// the picture through a fake request context. No browser, no network — the
+// in-page read itself is proved in a real Chromium by
+// xAvatarCapture.browser.test.ts.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xAvatarCapture.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readdir, readFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { PageLike } from "./playwrightRuntime";
+import { captureXPosts, type XCaptureDeps, type XPostSnapshot } from "./xPostCapture";
+import { AVATARS_SCRIPT_MARKER, avatarsScript, parseAvatarCandidates, type XAvatarCandidate } from "./xAvatarCapture";
+import { AVATARS_DIRNAME, readXAvatarIndex, writeXAvatar } from "./xAvatars";
+import { VIEW_SCRIPT_MARKER } from "./viewportShot";
+import type { PostCaptureInput } from "./fetchers";
+
+const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 9, 9]);
+const JPG = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 7]);
+const RECT = { x: 10, y: 120, width: 598, height: 300 };
+const snap = (id: string): XPostSnapshot => ({ path: `/someone/status/${id}`, text: "the post", article: { rect: RECT, sensitive: false } });
+const pic = (n: string) => `https://pbs.twimg.com/profile_images/${n}/face_normal.jpg`;
+
+type Fake = PageLike & { gotos: string[]; gets: string[]; reads: string[]; shots: number };
+
+// Each status page answers with its snapshot and the avatars `byId` names.
+function fakePage(byId: Record<string, XAvatarCandidate[]>): Fake {
+ let current = "";
+ const gotos: string[] = [];
+ const gets: string[] = [];
+ const reads: string[] = [];
+ const page: Fake = {
+ gotos,
+ gets,
+ reads,
+ shots: 0,
+ goto: async (url: string) => {
+ gotos.push(url);
+ current = /status\/(\d+)/.exec(url)?.[1] ?? "";
+ },
+ waitForSelector: async () => undefined,
+ waitForTimeout: async () => undefined,
+ on: () => {},
+ evaluate: async (script: string) => {
+ if (script.includes(AVATARS_SCRIPT_MARKER)) {
+ reads.push(script);
+ return byId[current] ?? [];
+ }
+ if (script.includes(VIEW_SCRIPT_MARKER)) return null;
+ if (script.includes("imgs.length")) return 0;
+ return snap(current);
+ },
+ screenshot: async () => {
+ page.shots++;
+ return PNG;
+ },
+ request: {
+ get: async (url: string) => {
+ gets.push(url);
+ return {
+ ok: () => true,
+ status: () => 200,
+ headers: () => ({ "content-type": "image/jpeg" }),
+ body: async () => JPG,
+ };
+ },
+ },
+ };
+ return page;
+}
+
+function deps(page: Fake, over: Partial<XCaptureDeps> = {}): XCaptureDeps & { pauses: number[]; opened: number } {
+ const d = {
+ pauses: [] as number[],
+ opened: 0,
+ openPage: async () => {
+ d.opened++;
+ return { page, close: async () => {} };
+ },
+ downloadMedia: async () => ({ ok: true as const, files: [] }),
+ pauseMs: () => 4000,
+ pause: async (ms: number) => {
+ d.pauses.push(ms);
+ },
+ now: () => new Date("2026-11-02T20:00:00.000Z"),
+ ...over,
+ };
+ return d;
+}
+
+async function outDir(): Promise<string> {
+ return path.join(await mkdtemp(path.join(os.tmpdir(), "xavatar-run-")), "posts-media");
+}
+
+const input = (out: string, ids: string[], over: Partial<PostCaptureInput> = {}): PostCaptureInput => ({
+ ids,
+ handle: "ObviousRises",
+ outDir: out,
+ signal: new AbortController().signal,
+ media: false,
+ articles: false,
+ ...over,
+});
+
+test("read: the script carries its marker and the archive's parent id; its answer is kept to the shape", () => {
+ const s = avatarsScript({ parent: true, quotes: true, parentId: "500" });
+ assert.ok(s.includes(AVATARS_SCRIPT_MARKER));
+ assert.ok(s.includes('"500"'));
+ assert.deepEqual(parseAvatarCandidates({ path: "/x" }), []);
+ assert.deepEqual(
+ parseAvatarCandidates([
+ { role: "author", handle: "ObviousRises", src: pic("1") },
+ { role: "author", handle: "../x", src: pic("1") },
+ { role: "fan", handle: "a", src: pic("1") },
+ { role: "parent", handle: "b", src: "" },
+ null,
+ ]),
+ [{ role: "author", handle: "ObviousRises", src: pic("1") }],
+ );
+});
+
+test("run: a normal capture stores the author's avatar from the page it shot — one load, one fetch at 400×400", async () => {
+ const out = await outDir();
+ const page = fakePage({ "11": [{ role: "author", handle: "ObviousRises", src: pic("9") }] });
+ const d = deps(page);
+ const res = await captureXPosts(input(out, ["11"]), d);
+ assert.equal(res.outcomes[0].state, "captured");
+ assert.equal(page.gotos.length, 1);
+ assert.equal(page.shots, 1);
+ assert.deepEqual(page.gets, ["https://pbs.twimg.com/profile_images/9/face_400x400.jpg"]);
+ assert.deepEqual(res.avatars?.stored, ["ObviousRises"]);
+ const index = await readXAvatarIndex(path.join(out, AVATARS_DIRNAME));
+ assert.deepEqual(index, {
+ ObviousRises: {
+ file: "ObviousRises.jpg",
+ url: "https://pbs.twimg.com/profile_images/9/face_400x400.jpg",
+ capturedAt: "2026-11-02T20:00:00.000Z",
+ postId: "11",
+ },
+ });
+ assert.deepEqual(new Uint8Array(await readFile(path.join(out, AVATARS_DIRNAME, "ObviousRises.jpg"))), JPG);
+ // Without the thread, only the author is looked for.
+ assert.ok(page.reads[0].includes("const wantParent = false"));
+});
+
+test("run: two posts of one author fetch the picture once; an author already stored is not fetched again", async () => {
+ const out = await outDir();
+ const a = [{ role: "author" as const, handle: "ObviousRises", src: pic("9") }];
+ const page = fakePage({ "11": a, "12": a });
+ await captureXPosts(input(out, ["11", "12"]), deps(page));
+ assert.equal(page.gets.length, 1);
+ // A later run: stored (under another case, even) — read, not fetched.
+ const page2 = fakePage({ "13": [{ role: "author", handle: "obviousrises", src: pic("9") }] });
+ const res = await captureXPosts(input(out, ["13"]), deps(page2));
+ assert.equal(page2.gets.length, 0);
+ assert.deepEqual(res.avatars?.skipped, ["obviousrises"]);
+ // force fetches again, and the entry takes the case X prints now.
+ const page3 = fakePage({ "14": [{ role: "author", handle: "obviousrises", src: pic("10") }] });
+ await captureXPosts(input(out, ["14"], { force: true }), deps(page3));
+ assert.equal(page3.gets.length, 1);
+ const index = await readXAvatarIndex(path.join(out, AVATARS_DIRNAME));
+ assert.deepEqual(Object.keys(index), ["obviousrises"]);
+ assert.equal(index.obviousrises.postId, "14");
+});
+
+test("run: avatars: false reads none; X's default picture is not stored", async () => {
+ const out = await outDir();
+ const page = fakePage({ "11": [{ role: "author", handle: "ObviousRises", src: pic("9") }] });
+ const res = await captureXPosts(input(out, ["11"], { avatars: false }), deps(page));
+ assert.equal(page.reads.length, 0);
+ assert.equal(page.gets.length, 0);
+ assert.equal(res.avatars, undefined);
+
+ const egg = fakePage({
+ "12": [{ role: "author", handle: "eggy", src: "https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png" }],
+ });
+ const res2 = await captureXPosts(input(out, ["12"]), deps(egg));
+ assert.equal(egg.gets.length, 0);
+ assert.deepEqual(res2.avatars?.skipped, ["eggy"]);
+ assert.deepEqual(await readXAvatarIndex(path.join(out, AVATARS_DIRNAME)), {});
+});
+
+test("run: with the thread on, the parent's and the quoted post's authors' too, by the archive's parent id", async () => {
+ const out = await outDir();
+ const page = fakePage({
+ "21": [
+ { role: "author", handle: "ObviousRises", src: pic("1") },
+ { role: "quoted", handle: "quoted_one", src: pic("2") },
+ { role: "parent", handle: "parent_one", src: pic("3") },
+ ],
+ });
+ const archived = new Map([["21", { text: "", author: "ObviousRises", isReply: true, replyTo: { id: "20" } }]]);
+ const res = await captureXPosts(input(out, ["21"], { thread: true, shots: false, archived }), deps(page));
+ assert.ok(page.reads[0].includes("const wantParent = true"));
+ assert.ok(page.reads[0].includes('const parentId = "20"'));
+ assert.deepEqual(res.avatars?.stored, ["ObviousRises", "quoted_one", "parent_one"]);
+ assert.deepEqual(Object.keys(await readXAvatarIndex(path.join(out, AVATARS_DIRNAME))), ["ObviousRises", "parent_one", "quoted_one"]);
+});
+
+test("avatarsOnly: one page per distinct archived author, paced, no shot, no media, no capture record", async () => {
+ const out = await outDir();
+ const page = fakePage({
+ "31": [{ role: "author", handle: "ObviousRises", src: pic("1") }],
+ "33": [{ role: "author", handle: "someone_else", src: pic("2") }],
+ });
+ let downloads = 0;
+ const d = deps(page, {
+ downloadMedia: async () => {
+ downloads++;
+ return { ok: true, files: [] };
+ },
+ });
+ const archived = new Map([
+ ["31", { text: "", author: "ObviousRises" }],
+ ["32", { text: "", author: "obviousrises" }],
+ ["33", { text: "", author: "someone_else" }],
+ ]);
+ const res = await captureXPosts(input(out, ["31", "32", "33"], { avatarsOnly: true, media: true, archived }), d);
+ assert.deepEqual(page.gotos, ["https://x.com/i/status/31", "https://x.com/i/status/33"]);
+ assert.deepEqual(d.pauses, [4000], "the gap before every contact after the first");
+ assert.equal(page.shots, 0);
+ assert.equal(downloads, 0);
+ assert.deepEqual(res.outcomes, []);
+ assert.equal(res.avatars?.pages, 2);
+ assert.deepEqual(res.avatars?.stored, ["ObviousRises", "someone_else"]);
+ // Nothing but the store under posts-media/: no post directory, no capture.json.
+ assert.deepEqual(await readdir(out), [AVATARS_DIRNAME]);
+});
+
+test("avatarsOnly: an author already stored costs no page load unless force", async () => {
+ const out = await outDir();
+ await writeXAvatar(path.join(out, AVATARS_DIRNAME), {
+ handle: "ObviousRises",
+ bytes: JPG,
+ url: "https://pbs.twimg.com/profile_images/1/face_400x400.jpg",
+ postId: "1",
+ });
+ const page = fakePage({ "31": [{ role: "author", handle: "ObviousRises", src: pic("1") }] });
+ const archived = new Map([["31", { text: "", author: "obviousrises" }]]);
+ const d = deps(page);
+ const res = await captureXPosts(input(out, ["31"], { avatarsOnly: true, archived }), d);
+ assert.equal(d.opened, 0);
+ assert.deepEqual(page.gotos, []);
+ assert.deepEqual(res.avatars?.skipped, ["obviousrises"]);
+
+ const res2 = await captureXPosts(input(out, ["31"], { avatarsOnly: true, archived, force: true }), deps(page));
+ assert.deepEqual(page.gotos, ["https://x.com/i/status/31"]);
+ assert.deepEqual(page.gets, ["https://pbs.twimg.com/profile_images/1/face_400x400.jpg"]);
+ assert.deepEqual(res2.avatars?.stored, ["ObviousRises"]);
+});
+
+test("avatarsOnly: a login wall stops the run with needsCookies, the rest left", async () => {
+ const out = await outDir();
+ const page = fakePage({});
+ page.evaluate = async (script: string) =>
+ script.includes(AVATARS_SCRIPT_MARKER) ? [] : { path: "/i/flow/login", text: "", article: null };
+ const archived = new Map([
+ ["41", { text: "", author: "a" }],
+ ["42", { text: "", author: "b" }],
+ ]);
+ const res = await captureXPosts(input(out, ["41", "42"], { avatarsOnly: true, archived }), deps(page));
+ assert.equal(res.needsCookies, true);
+ assert.match(res.stoppedEarly ?? "", /Stopped at 41/);
+ assert.equal(page.gotos.length, 1);
+ assert.deepEqual(res.outcomes, []);
+});
diff --git a/common/social/xAvatarCapture.ts b/common/social/xAvatarCapture.ts
@@ -0,0 +1,238 @@
+// 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-<handle>"]`, a link to `/<handle>` and an
+// <img src="https://pbs.twimg.com/profile_images/<n>/<name>_normal.jpg">. 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 <img>, 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<XAvatarRole>(["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<string, unknown>;
+ 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<XAvatarCandidate[]> {
+ 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: `<posts-media>/_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<string>;
+ 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<XAvatarCandidate>,
+ ctx: SaveXAvatarsContext,
+): Promise<void> {
+ const { summary, onLog } = ctx;
+ let index: Awaited<ReturnType<typeof readXAvatarIndex>> | 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 });
+ 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` : "") +
+ "."
+ );
+}
diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts
@@ -372,11 +372,12 @@ export async function captureXPostsByIds(
const paths = getPaths();
// The profile shoots the posts and opens the articles. A post is known to
// link to an article before any page only by its archived text; one found
- // on a card is found by a shot, which already needs the profile.
+ // on a card is found by a shot, which already needs the profile. An
+ // avatars-only run reads the post pages through it too.
const articles =
(input.articles ?? true) &&
input.ids.some((id) => xArticleLinkFromArchive(input.archived?.get(id)) !== null);
- if ((input.shots ?? true) || articles) {
+ if (input.avatarsOnly || (input.shots ?? true) || articles) {
const status = await readXSessionStatus(paths);
if (!status.hasProfile) {
const why =
diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts
@@ -30,6 +30,13 @@
// author blurred unless verified or the reply's own (xThreadShot.ts). A post
// the archive says is no reply is not opened for it.
//
+// The AUTHOR'S AVATAR is read off the same page (xAvatarCapture.ts) and saved
+// into `posts-media/_avatars/` (xAvatars.ts) — with the thread on, the
+// parent's and the quoted post's authors' too — unless `avatars` is off; an
+// author already stored is not fetched again. `avatarsOnly` loads one post
+// page per distinct archived author for that alone, and writes no capture
+// record.
+//
// NOT VERIFIED AGAINST LIVE X. The page markers below are X's as of this
// writing and are tested against recorded snapshots, never x.com; the first
// real run is the check.
@@ -60,6 +67,16 @@ import { xArticleLinkFromArchive, type XArticleLink } from "./xArticle";
import { captureXArticle, xArticleLinkFromCard } from "./xArticleCapture";
import { shootFromViewport } from "./viewportShot";
import { shootXThread, type ThreadShotOptions, type ThreadShotResult } from "./xThreadShot";
+import {
+ describeAvatarSummary,
+ emptyAvatarSummary,
+ readXAvatarCandidates,
+ saveXAvatars,
+ type XAvatarCandidate,
+ type XAvatarReadOptions,
+ type XAvatarRunSummary,
+} from "./xAvatarCapture";
+import { lookupXAvatar, readXAvatarIndex, xAvatarsDir } from "./xAvatars";
// The post's own article, marked by the snapshot.
const CAPTURE_SELECTOR = "[data-archilyzer-capture]";
@@ -209,6 +226,8 @@ export type XShotResult = XPostVerdict & {
articleLink?: XArticleLink;
// The thread shot, when one was asked for and the post rendered.
thread?: ThreadShotResult;
+ // The avatars read off the page, when asked for and the post rendered.
+ avatars?: XAvatarCandidate[];
};
export type XShotOptions = {
@@ -217,6 +236,9 @@ export type XShotOptions = {
own?: boolean;
// The thread shot too (xThreadShot.ts), after the post's own.
thread?: Omit<ThreadShotOptions, "onLog" | "url"> | null;
+ // Read the authors' avatars off the page (xAvatarCapture.ts): nothing is
+ // fetched here, the caller saves them through the same page.
+ avatars?: XAvatarReadOptions | null;
};
// One post's screenshot: load, read the page, open a sensitive cover, shoot
@@ -262,9 +284,13 @@ export async function shootXPost(
return { state: "error", error: "The post rendered with no size to shoot." };
}
const articleLink = xArticleLinkFromCard(snap.article?.articleHrefs);
+ // Before any shot: the thread shot's blur is a CSS filter, but the read
+ // should see the page as X drew it.
+ const avatars = opts.avatars ? await readXAvatarCandidates(page, opts.avatars) : undefined;
+ const found = avatars ? { avatars } : {};
if (opts.own === false) {
const thread = opts.thread ? await shootXThread(page, id, dir, { ...opts.thread, url, onLog }) : undefined;
- return { ...verdict, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}) };
+ return { ...verdict, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}), ...found };
}
let png: Uint8Array;
try {
@@ -298,7 +324,7 @@ export async function shootXPost(
const shot = await describeCapturedFile(dir, SHOT_FILENAME, url);
// After the post's own shot, so nothing the thread shot blurs is in it.
const thread = opts.thread ? await shootXThread(page, id, dir, { ...opts.thread, url, onLog }) : undefined;
- return { ...verdict, shot, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}) };
+ return { ...verdict, shot, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}), ...found };
}
export type MediaDownloadResult =
@@ -342,8 +368,13 @@ export async function captureXPosts(
force: input.force ?? false,
articles: input.articles ?? true,
thread: input.thread ?? false,
+ avatars: input.avatars ?? true,
};
+ if (input.avatarsOnly) return captureXAvatarsOnly(input, deps);
const now = deps.now ?? (() => new Date());
+ const avatarDir = xAvatarsDir(input.outDir);
+ const avatarSeen = new Set<string>();
+ const avatarSummary = emptyAvatarSummary();
const outcomes: PostCaptureOutcome[] = [];
let contacts = 0;
let errorsInARow = 0;
@@ -352,9 +383,15 @@ export async function captureXPosts(
const contact = async () => {
if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal);
};
+ const withAvatars = (): Partial<PostCaptureResult> => {
+ const s = avatarSummary;
+ if (!s.stored.length && !s.skipped.length && !s.failed.length) return {};
+ onLog?.(describeAvatarSummary(s));
+ return { avatars: s };
+ };
const stopped = (why: string, extra: Partial<PostCaptureResult> = {}) => {
onLog?.(why);
- return { outcomes, stoppedEarly: why, ...extra };
+ return { outcomes, stoppedEarly: why, ...extra, ...withAvatars() };
};
try {
@@ -404,7 +441,19 @@ export async function captureXPosts(
thread: threadOwed
? { replyTo: arch?.replyTo ?? null, ownHandle: arch?.author, redact: threadRedactFor(input.threadRedact, id) }
: null,
+ avatars: wanted.avatars ? avatarReadOptions(wanted.thread, arch) : null,
});
+ if (res.avatars?.length) {
+ await saveXAvatars(browser.page, res.avatars, {
+ dir: avatarDir,
+ postId: id,
+ force: wanted.force,
+ seen: avatarSeen,
+ summary: avatarSummary,
+ now,
+ onLog,
+ });
+ }
if (work.shot) {
state = res.state;
sensitive = res.sensitive;
@@ -531,7 +580,102 @@ export async function captureXPosts(
);
}
}
- return { outcomes };
+ return { outcomes, ...withAvatars() };
+ } finally {
+ await browser?.close().catch(() => {});
+ }
+}
+
+type ArchivedForAvatars = { author?: string; isReply?: boolean; replyTo?: { id: string } } | undefined;
+
+// What the avatar read looks for on one post's page: its author's always;
+// with the thread on, the post it answers (unless the archive says it is no
+// reply) and the post it quotes.
+function avatarReadOptions(thread: boolean, arch: ArchivedForAvatars): XAvatarReadOptions {
+ if (!thread) return {};
+ const noReply = !!arch && arch.isReply === false && !arch.replyTo;
+ return { parent: !noReply, quotes: true, parentId: arch?.replyTo?.id ?? null };
+}
+
+// `avatarsOnly`: one post page per distinct archived author (the first id of
+// each; an author the store has is not loaded unless `force`), the avatars
+// read off it and saved — no shot, no media, no article, no thread shot, and
+// no capture record or availability: `outcomes` stays empty. Paced like every
+// other X contact, and stopped like one by a login wall or X refusing.
+async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): Promise<PostCaptureResult> {
+ const { signal, onLog } = input;
+ const force = input.force ?? false;
+ const thread = input.thread ?? false;
+ const now = deps.now ?? (() => new Date());
+ const dir = xAvatarsDir(input.outDir);
+ const summary = emptyAvatarSummary();
+ const seen = new Set<string>();
+ const store = await readXAvatarIndex(dir);
+
+ // The pages owed: the first id of each archived author not yet stored.
+ const authorKeys = new Set<string>();
+ const picks: string[] = [];
+ for (const id of input.ids) {
+ const author = input.archived?.get(id)?.author?.replace(/^@/, "");
+ const key = author ? author.toLowerCase() : `#${id}`;
+ if (authorKeys.has(key)) continue;
+ authorKeys.add(key);
+ if (author && !force && lookupXAvatar(store, author)) {
+ summary.skipped.push(author);
+ onLog?.(`@${author}: avatar already stored — skipped (no page load).`);
+ continue;
+ }
+ picks.push(id);
+ }
+ onLog?.(`Avatars only: ${picks.length} post page(s) to load, one per author.`);
+
+ let contacts = 0;
+ let errorsInARow = 0;
+ let browser: { page: PageLike; close: () => Promise<void> } | undefined;
+ const done = (extra: Partial<PostCaptureResult> = {}): PostCaptureResult => {
+ onLog?.(describeAvatarSummary(summary));
+ return { outcomes: [], avatars: summary, ...extra };
+ };
+ const stopped = (why: string, extra: Partial<PostCaptureResult> = {}) => {
+ onLog?.(why);
+ return done({ stoppedEarly: why, ...extra });
+ };
+ try {
+ for (const [i, id] of picks.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.");
+ if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ onLog?.(`[${i + 1}/${picks.length}] ${id} (for its author's avatar)`);
+ browser ??= await deps.openPage();
+ summary.pages++;
+ const arch = input.archived?.get(id);
+ const res = await shootXPost(browser.page, id, postCaptureDir(input.outDir, id), onLog, {
+ own: false,
+ thread: null,
+ avatars: avatarReadOptions(thread, arch),
+ });
+ if (res.state !== "captured") {
+ const why = res.error ?? `the page showed the post as ${res.state}`;
+ onLog?.(`${id}: no avatar read — ${why}.`);
+ if (res.stop) {
+ return stopped(`${res.stop} Stopped at ${id}; the rest are left for a later run.`, {
+ needsCookies: res.state === "login-wall",
+ });
+ }
+ errorsInARow = res.state === "error" ? errorsInARow + 1 : 0;
+ if (errorsInARow >= STOP_AFTER_ERRORS) {
+ return stopped(`${STOP_AFTER_ERRORS} pages in a row failed; stopping rather than paging through the rest.`);
+ }
+ continue;
+ }
+ errorsInARow = 0;
+ if (!res.avatars?.some((a) => a.role === "author")) onLog?.(`${id}: no author avatar found on the page.`);
+ if (res.avatars?.length) {
+ await saveXAvatars(browser.page, res.avatars, { dir, postId: id, force, seen, summary, now, onLog });
+ }
+ }
+ return done();
} finally {
await browser?.close().catch(() => {});
}