Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit f66c2d4fc4557a20bea1290c01b98e4304f05dc1
parent 9f1457fbe5f815b199234e458a143aedbe452025
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue,  3 Nov 2026 00:53:33 -0500

Merge main into lane/post-narration: the X avatar store, posts context (capture-context), the post-videos plan

Conflicts kept both sides: manifest.mjs (the avatar, narration and fit writers
beside setPostItemsContext), postsCli.mjs (posts narrate / fit / avatar / avatars
beside posts context; set-item's fit=), cli.md (the reel row with the capture's
context, set-item's fit=, narrate / fit / avatar rows, the context row), and
plans/post-videos.md (the dedicated UI and the narration sources sections).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 2+-
MOPERATING.md | 41+++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/capturePosts.test.ts | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/controller/capturePosts.ts | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/report/draft/research/tools.ts | 6+++---
Acommon/social/__fixtures__/gallery-dl-timeline-quotes.jsonl | 10++++++++++
Acommon/social/__fixtures__/x-avatar-quoted_400x400.jpg | 0
Acommon/social/__fixtures__/x-avatar_400x400.jpg | 0
Acommon/social/__fixtures__/x-avatar_normal.jpg | 0
Acommon/social/__fixtures__/x-post-avatars.html | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/fetchers.ts | 27+++++++++++++++++++++++++++
Mcommon/social/postCapture.ts | 42++++++++++++++++++++++++++++++++++++++++--
Acommon/social/xAvatarCapture.browser.test.ts | 284+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/xAvatarCapture.test.ts | 269+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/xAvatarCapture.ts | 238+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/xAvatars.test.ts | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/xAvatars.ts | 228+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xGalleryDlFetcher.test.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xGalleryDlFetcher.ts | 75++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/social/xNormalize.ts | 33++++++++++++++++++++++++++++++++-
Mcommon/social/xPostCapture.ts | 315++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Acommon/social/xPostContext.test.ts | 282+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/xPostContext.ts | 254+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xThreadShot.ts | 24++++++++++++++----------
Meditor/CHANGELOG.md | 4++++
Meditor/app/api/ops/capture-posts/route.test.ts | 48++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/capture-posts/route.ts | 34++++++++++++++++++++++++++++++----
Meditor/app/channels/[slug]/socialActions.ts | 41++++++++++++++++++++++++++++++++++-------
Meditor/app/jobs/jobReplayRegistry.ts | 4++++
Meditor/e2e/capture-posts.spec.ts | 21+++++++++++++++++++++
Mplans/post-videos.md | 9+++++++++
Mscripts/archilyzer-ops.mjs | 19+++++++++++++++++--
Mumtool/docs/cli.md | 3++-
Mumtool/docs/knobs.md | 1+
Mumtool/docs/report-video.md | 6+++++-
Mumtool/lib/report/manifest.mjs | 40++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postContext.mjs | 190+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postContext.test.mjs | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postReel.mjs | 13++++++++++---
Mumtool/lib/report/postsCli.mjs | 29+++++++++++++++++++++++++++++
40 files changed, 3342 insertions(+), 57 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -146,7 +146,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | | `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | | -| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"&lt;id&gt;": false} sets it per post. Paced like a post fetch, on its queue. | | +| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"&lt;id&gt;": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/&lt;handle&gt;.&lt;ext&gt; + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["&lt;one of their post ids&gt;"\], "avatarsOnly": true}. X also reads each post's CONTEXT off the same page -- the post it quotes and the post it answers (its author, check, date, words, media links) -- into its capture.json's "context"; "context": false turns that off. "contextOnly": true (X) loads ONE page per post for that alone (and the avatars it shows): the context written into capture.json, nothing shot, no media, article, thread shot or availability; a post whose context is already read is skipped unless "force". Not with "avatarsOnly". Paced like a post fetch, on its queue. | | | `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "&lt;branch&gt;", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of &lt;id&gt; in &lt;dir&gt; — archilyzer publish build &lt;id&gt;". `get publish` is the status. | | | `build-index`, `build-site`, `build-deploy`, `deploy-site`, `build-hub`, `deploy-hub`, `build-homepage`, `deploy-homepage` | build-index, build-site, build-deploy, deploy-site, build-hub, deploy-hub, build-homepage and deploy-homepage are publish's aliases, with their old bodies and answers ("skipData" is accepted and ignored). | `pnpm ops build-deploy --json '{"siteIds":["anilyzer","jeralyzer"]}' --wait`<br>`pnpm ops build-site --json '{"siteId":"anilyzer"}' --wait`<br>`pnpm ops deploy-site --json '{"siteId":"anilyzer","preview":"tags-exclude"}' --wait`<br>`pnpm ops build-hub --wait`<br>`pnpm ops build-hub --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-hub --wait`<br>`pnpm ops build-homepage --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait` | | `build-site`, `build-deploy`, `deploy-site` | build-site, build-deploy and deploy-site all take "siteId" (one) or "siteIds" (a list). | | diff --git a/OPERATING.md b/OPERATING.md @@ -408,6 +408,47 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait pnpm ops capture-posts --json '{"slug":"example-x-replies","ids":["<postId>"],"thread":true}' --wait umtool posts set <project> <postId> thread=on ``` +- **Authors' avatars (X).** A post card draws its author's face from the channel's avatar store, not an initial + letter. Every X capture that loads a post page reads the author's avatar off it (with `"thread": true`, the + replied-to and quoted authors' too) and fetches it at 400×400 through the same browser context — no extra page + load; once per author per run, and an author already stored is not fetched again unless `"force": true`. + `"avatars": false` turns that off. For the avatars alone, `"avatarsOnly": true` loads ONE post page per distinct + archived author (the first id of each; one already stored costs no load unless `"force"`), paced like any X + contact, and writes nothing else — no shot, media, article, thread shot, `capture.json` or availability. One + author's avatar is one page load: + + ```sh + pnpm ops capture-posts --json '{"slug":"ObviousRises-x","ids":["<one of his post ids>"],"avatarsOnly":true}' --wait + ``` + + The store, beside the post ids (never one of them): + + ``` + channels/<slug>/posts-media/_avatars/<handle>.<ext> # jpg | png | webp | gif + channels/<slug>/posts-media/_avatars/avatars.json # { "<handle>": { "file", "url" (the _400x400), "capturedAt", "postId" } } + ``` +- **A post's context (X): what it quotes and what it answers.** The archive often names neither — a timeline + read kept no quote until the fetcher asked gallery-dl for them (it does now: a quote becomes the post's + `quoted`, never one of the account's posts), and a reply's parent is another account's post, never archived + with the account's. Every X capture that loads a post page reads both off it — the parent (the archive's + in-reply-to id, else the post directly above it; read even when the archive calls the post no reply) and the + quote card: author, display name, check, date, words, the media links the page drew, the status id when the + page names it — into `capture.json`'s `context: {quoted?, parent?, readAt}`, with no extra page load; + `"context": false` turns that off. For a list of posts already captured (or not), `"contextOnly": true` loads + ONE page per post for its context (and the avatars it shows) and writes nothing else — no shot, media, article, + thread shot or availability; a post whose context is already read is skipped unless `"force": true`: + + ```sh + pnpm ops capture-posts --json '{"slug":"ObviousRises-x","ids":["<postId>","<postId>"],"contextOnly":true}' --wait + umtool posts context <project> # every post item of the cut takes the quoted post / parent it lacks + ``` + + A post video draws them on the card (`quoted`, `parents`), blurring every author but the subject unless + gold- or grey-checked. `umtool posts reel` and `timeline insert post:` fill them when the entry is made; + `umtool posts context` refreshes a cut made before the capture, in one write (one undo point), and names the + posts with no context yet with the call above. + + Keys keep the handle's case as X prints it; lookups ignore case. X's default "egg" picture is not stored. - A **forum thread** keeps two positions (`posts-state.json` `forum`): **Fetch posts** catches up from the last page to the newest held post, then continues the history from where it stopped, down to page 1 — `"pages": N` caps the pages that hold anything new (an all-held page is stepped past uncounted), and a capped catch-up never moves diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts @@ -202,7 +202,7 @@ test("the articles: on by default, refused alone only when not asked for by name assert.deepEqual(archived.get("222"), { text: "a plain post", links: ["https://example.com/page"] }); calls = []; - assert.equal((await run("demo-x", ["111"], { articles: false })).ok, true); + assert.equal((await run("demo-x", ["111"], { articles: false, context: false })).ok, true); assert.equal(calls[0].articles, false); assert.equal(calls[0].archived, undefined); @@ -245,9 +245,9 @@ test("the thread shots (X): off by default, the run's word or the channel's, eac answer = { outcomes: [] }; calls = []; - assert.equal((await run("demo-x-replies", ["501"], { articles: false })).ok, true); + assert.equal((await run("demo-x-replies", ["501"], { articles: false, context: false })).ok, true); assert.equal(calls[0].thread, false); - assert.equal(calls[0].archived, undefined, "nothing read for a run with no articles and no thread"); + assert.equal(calls[0].archived, undefined, "nothing read for a run with no articles, no thread and no context"); calls = []; assert.equal((await run("demo-x-replies", ["501", "502"], { thread: true, threadRedact: { "501": false } })).ok, true); @@ -352,3 +352,135 @@ 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: [] }; +}); + +test("context (X): read by default with each post's archived parent and quoted ids; contextOnly is its own run, X's only, nothing recorded", async () => { + const root = path.join(channelsDir, "demo-x-context"); + 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: "ObviousRises", + name: "Example (X context)", + url: "https://x.com/ObviousRises", + }), + ); + const base = { + channelSlug: "demo-x-context", author: "ObviousRises", createdAt: "2026-10-29T04:34:32.000Z", uploadDate: "20261029", + platform: "twitter" as const, isRepost: false, links: [], + }; + await writePosts(root, [ + { + ...base, id: "701", slug: "demo-x-context/701", text: "a reply quoting", url: "https://x.com/ObviousRises/status/701", isReply: true, + replyTo: { platform: "twitter" as const, id: "700", author: "Kirsche" }, + quoted: { platform: "twitter" as const, id: "699", author: "someone" }, + }, + // The archive names neither (the operator's case): the page is the word. + { ...base, id: "702", slug: "demo-x-context/702", text: "you called me a Leftist", url: "https://x.com/ObviousRises/status/702", isReply: false }, + ]); + + // A normal run: on by default (the fetcher's), the archive's ids passed. + calls = []; + answer = { outcomes: [] }; + await run("demo-x-context", ["701", "702"], { articles: false }); + assert.equal(calls[0].context, undefined); + assert.equal(calls[0].contextOnly, undefined); + assert.deepEqual(calls[0].archived?.get("701")?.replyTo, { id: "700", author: "Kirsche" }); + assert.deepEqual(calls[0].archived?.get("701")?.quoted, { id: "699", author: "someone" }); + assert.equal(calls[0].archived?.get("702")?.replyTo, undefined); + calls = []; + await run("demo-x-context", ["701"], { articles: false, context: false }); + assert.equal(calls[0].context, false); + + // contextOnly: a run even with both halves off; the summary is the result's, + // and an outcome the fetcher (wrongly) returns is not recorded. + calls = []; + answer = { + outcomes: [{ id: "701", state: "deleted", availability: "deleted", files: 0 }], + context: { read: 2, quoted: 1, parents: 2, skipped: 0, pages: 2, failed: [] }, + }; + const res = await run("demo-x-context", ["701", "702"], { contextOnly: true, shots: false, media: false, articles: false }); + assert.equal(res.ok, true); + assert.deepEqual(res.outcomes, []); + assert.equal(res.context?.parents, 2); + assert.equal(calls[0].contextOnly, true); + assert.deepEqual(await readPostAvailability(root), {}); + + // With avatarsOnly: two runs, refused; another platform reads none. + calls = []; + assert.match( + (await run("demo-x-context", ["701"], { contextOnly: true, avatarsOnly: true })).error ?? "", + /^"contextOnly" and "avatarsOnly" are two runs/, + ); + await makeChannel("demo-social-context"); + assert.equal( + (await run("demo-social-context", ["aaa"], { contextOnly: true })).error, + "Post context is X's only; Test capture reads none.", + ); + assert.equal(calls.length, 0); + answer = { outcomes: [] }; +}); diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -13,6 +13,17 @@ // 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. +// +// And X reads each post's CONTEXT off the same page -- the post it quotes and +// the post it answers, which the archive often lacks -- into its capture.json +// (social/xPostContext.ts): on by default (`context: false` turns it off), and +// `contextOnly` loads one page per post for that alone (and the avatars it +// shows), writing the context into the record and nothing about availability. import path from "node:path"; import { isXSearchChannel } from "../lib/xSearch/config"; @@ -39,6 +50,8 @@ import { type SocialFetcher, } from "../social/fetchers"; import { postsMediaDir } from "../social/postCapture"; +import type { XAvatarRunSummary } from "../social/xAvatarCapture"; +import type { XContextRunSummary } from "../social/xPostContext"; import { isWaybackPagesChannel } from "../lib/waybackPages/config"; import { captureWaybackPageRecords, @@ -74,6 +87,17 @@ 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; + // X: read each post's context (the quoted post, the parent) off the pages + // the shots load (default true), or ONLY it -- one page per post, the + // context written into its capture.json, the avatars it shows saved; no + // shot, media, article, thread shot or availability. + context?: boolean; + contextOnly?: boolean; onLog?: (line: string) => void; signal?: AbortSignal; // The job's drain: stop between posts. @@ -88,6 +112,10 @@ export type CapturePostsResult = { outcomes: PostCaptureOutcome[]; needsCookies?: boolean; error?: string; + // X: what the run did about avatars, when it did anything. + avatars?: XAvatarRunSummary; + // X: what the run read of the posts' context, when it read any. + context?: XContextRunSummary; }; // Why this fetcher cannot capture posts, or null when it can. Shared with the @@ -105,16 +133,36 @@ 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 or context-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; + contextOnly?: boolean; }): boolean { + if (o.avatarsOnly === true || o.contextOnly === 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 refusal for a context-only run asked of a platform that reads none, or +// asked together with an avatars-only one (it keeps the avatars itself). +export function contextOnlyProblem( + platform: string | undefined, + label: string, + o: { avatarsOnly?: boolean } = {}, +): string | null { + if (o.avatarsOnly) return '"contextOnly" and "avatarsOnly" are two runs; a context-only run keeps the avatars it shows too.'; + return platform === "twitter" ? null : `Post context is X's only; ${label} reads 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 +211,28 @@ 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")!); + if (opts.contextOnly) return fail(contextOnlyProblem(undefined, "a Wayback pages channel", opts)!); + 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); + } + const contextOnly = opts.contextOnly === true; + if (contextOnly) { + const nope = contextOnlyProblem(fetcher.platform, fetcher.label, opts); + if (nope) return fail(nope); + } + // The context read (X): what the archive says each post answers and quotes. + const contextWanted = fetcher.platform === "twitter" && (contextOnly || opts.context !== false); // 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. @@ -192,11 +256,12 @@ export async function capturePosts( author?: string; isReply?: boolean; replyTo?: { id: string; author?: string }; + quoted?: { id: string; author?: string }; }; 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 || contextWanted) { const wanted = new Set(ids); archived = new Map(); for (const p of await readAllPosts(channelRoot)) { @@ -207,6 +272,16 @@ 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 context read tells the parent by the id the reply answers, and + // fills a quote card's missing id from the quoted one. + ...(contextWanted + ? { + ...(p.replyTo ? { replyTo: { id: p.replyTo.id, ...(p.replyTo.author ? { author: p.replyTo.author } : {}) } } : {}), + ...(p.quoted ? { quoted: { id: p.quoted.id, ...(p.quoted.author ? { author: p.quoted.author } : {}) } } : {}), + } + : {}), // The thread shot tells the parent by the id the reply answers. ...(thread ? { @@ -225,13 +300,29 @@ export async function capturePosts( ? await resolveXCookieSourceFor(paths, settings, policy.cookies) : undefined; - log( + if (contextOnly) { + log( + `Reading the context (the quoted post, the post answered) of ${ids.length} post(s) of ${slug} via ${fetcher.label}` + + (opts.avatars === false ? "" : ", and the avatars it shows") + + (opts.force ? ", again where already read" : "") + + ".", + ); + } else 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" : "", + contextWanted ? " context" : "", ].join("") + (opts.force ? ", again where already captured" : "") + ".", @@ -254,6 +345,10 @@ export async function capturePosts( articles: opts.articles, thread, ...(opts.threadRedact !== undefined ? { threadRedact: opts.threadRedact } : {}), + ...(opts.avatars !== undefined ? { avatars: opts.avatars } : {}), + ...(avatarsOnly ? { avatarsOnly: true } : {}), + ...(opts.context !== undefined ? { context: opts.context } : {}), + ...(contextOnly ? { contextOnly: true } : {}), archived, cookies: alwaysCookies(policy), cookieSource: xLogin?.source, @@ -268,6 +363,20 @@ export async function capturePosts( return fail(message); } + const avatars = { + ...(result.avatars ? { avatars: result.avatars } : {}), + ...(result.context ? { context: result.context } : {}), + }; + if (avatarsOnly || contextOnly) { + // 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 +411,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 +420,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/lib/report/draft/research/tools.ts b/common/lib/report/draft/research/tools.ts @@ -128,10 +128,10 @@ export const ACTION_SPECS: Record<AcquisitionAction, ActionSpec> = { action: "capture-posts", editorAction: "capture-posts", description: - "Capture archived posts of a social channel: a screenshot and the attached media of each id; thread: an X reply also shot with the post it answers above it (shot-thread.png, the replied-to author blurred unless verified).", - properties: { slug: str, ids: strList, shots: bool, media: bool, articles: bool, thread: bool }, + "Capture archived posts of a social channel: a screenshot and the attached media of each id; thread: an X reply also shot with the post it answers above it (shot-thread.png, the replied-to author blurred unless verified); X keeps each author's avatar (posts-media/_avatars/) and each post's context (the post it quotes, the post it answers) in its capture.json; avatarsOnly: only the avatars, one page per author; contextOnly: only the context, one page per post.", + properties: { slug: str, ids: strList, shots: bool, media: bool, articles: bool, thread: bool, avatarsOnly: bool, contextOnly: bool }, required: ["slug", "ids"], - body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles", "thread"]), + body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles", "thread", "avatarsOnly", "contextOnly"]), }, "import-post": { action: "import-post", diff --git a/common/social/__fixtures__/gallery-dl-timeline-quotes.jsonl b/common/social/__fixtures__/gallery-dl-timeline-quotes.jsonl @@ -0,0 +1,10 @@ +[2, {"tweet_id": 1983300000000000001, "retweet_id": 0, "quote_id": 0, "reply_id": 0, "conversation_id": 1983300000000000001, "source_id": 0, "date": "2026-10-29 14:05:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "you called me a Leftist, so here is what you said", "count": 0, "category": "twitter", "subcategory": "timeline"}] +[2, {"tweet_id": 1983200000000000007, "retweet_id": 0, "quote_id": 1983300000000000001, "reply_id": 0, "conversation_id": 1983200000000000007, "source_id": 0, "date": "2026-10-29 12:00:00", "author": {"id": 2222222222, "name": "Kirsche", "nick": "Kirsche", "location": "", "date": "2019-03-01 10:00:00", "verified": true, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/2222222222/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "Mr. Obvious is a leftist in disguise.", "count": 0, "category": "twitter", "subcategory": "timeline", "quote_by": "ObviousRises"}] +[2, {"tweet_id": 1983300000000000002, "retweet_id": 0, "quote_id": 0, "reply_id": 0, "conversation_id": 1983300000000000002, "source_id": 0, "date": "2026-10-28 09:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "the receipt", "count": 1, "category": "twitter", "subcategory": "timeline"}] +[3, "https://pbs.twimg.com/media/T2pic.jpg?name=orig", {"tweet_id": 1983300000000000002, "retweet_id": 0, "quote_id": 0, "reply_id": 0, "conversation_id": 1983300000000000002, "source_id": 0, "date": "2026-10-28 09:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "the receipt", "count": 1, "category": "twitter", "subcategory": "timeline", "num": 1, "filename": "T2pic", "extension": "jpg"}] +[2, {"tweet_id": 1983100000000000003, "retweet_id": 0, "quote_id": 1983300000000000002, "reply_id": 0, "conversation_id": 1983100000000000003, "source_id": 0, "date": "2026-10-27 18:30:00", "author": {"id": 3333333333, "name": "quoted_person", "nick": "Quoted Person", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/3333333333/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "The receipt itself.", "count": 1, "category": "twitter", "subcategory": "timeline", "quote_by": "ObviousRises"}] +[3, "https://pbs.twimg.com/media/Q2pic.jpg?name=orig", {"tweet_id": 1983100000000000003, "retweet_id": 0, "quote_id": 1983300000000000002, "reply_id": 0, "conversation_id": 1983100000000000003, "source_id": 0, "date": "2026-10-27 18:30:00", "author": {"id": 3333333333, "name": "quoted_person", "nick": "Quoted Person", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/3333333333/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "The receipt itself.", "count": 1, "category": "twitter", "subcategory": "timeline", "quote_by": "ObviousRises", "num": 1, "filename": "Q2pic", "extension": "jpg"}] +[2, {"tweet_id": 1983300000000000003, "retweet_id": 0, "quote_id": 0, "reply_id": 0, "conversation_id": 1983300000000000003, "source_id": 0, "date": "2026-10-27 08:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "as I said last week", "count": 0, "category": "twitter", "subcategory": "timeline"}] +[2, {"tweet_id": 1981000000000000005, "retweet_id": 0, "quote_id": 1983300000000000003, "reply_id": 0, "conversation_id": 1981000000000000005, "source_id": 0, "date": "2026-10-20 08:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "an older post of my own", "count": 0, "category": "twitter", "subcategory": "timeline", "quote_by": "ObviousRises"}] +[2, {"tweet_id": 1983300000000000004, "retweet_id": 0, "quote_id": 0, "reply_id": 1983200000000000001, "conversation_id": 1983200000000000001, "source_id": 0, "date": "2026-10-26 08:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "@Kirsche no", "count": 0, "category": "twitter", "subcategory": "timeline", "reply_to": "Kirsche"}] +[2, {"tweet_id": 1981000000000000005, "retweet_id": 0, "quote_id": 0, "reply_id": 0, "conversation_id": 1981000000000000005, "source_id": 0, "date": "2026-10-20 08:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "an older post of my own", "count": 0, "category": "twitter", "subcategory": "timeline"}] 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,113 @@ +<!doctype html> +<!-- An X status page as X draws it (2026-11), cut to what the capture reads: + the reply's parent above it (a blue check by its name), the post itself + (its author's avatar, a quoted post's card with its own avatar, its + words, date and a picture whose link names the quoted status), and a + reply under it. Every picture is on {{ORIGIN}}, the test's loopback + server, at X's profile_images (and media) paths. 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(&quot;{{ORIGIN}}/profile_images/777/pp_normal.jpg&quot;);"></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> + <svg data-testid="icon-verified" viewBox="0 0 22 22" width="16" height="16" fill="#1d9bf0" aria-label="Verified account"><path d="M0 0h22v22H0z"></path></svg> + <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(&quot;{{ORIGIN}}/profile_images/1712345678901234567/Mr_O_normal.jpg&quot;);"></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> + <div data-testid="UserAvatar-Container-quoted_person"> + <div class="bg" style="background-image: url(&quot;{{ORIGIN}}/profile_images/888/qq_mini.jpg&quot;);"></div> + <img alt="" draggable="true" src="{{ORIGIN}}/profile_images/888/qq_mini.jpg"> + </div> + <span>Quoted Person</span> + </div> + <div><span class="handle">@quoted_person</span> <span class="handle">·</span> <time datetime="2026-10-29T08:00:00.000Z">Oct 29</time></div> + </div> + <div data-testid="tweetText" lang="en"><span>The receipt itself.</span></div> + <a href="/quoted_person/status/1849000000000000005/photo/1" role="link"> + <div data-testid="tweetPhoto"><img alt="Image" src="{{ORIGIN}}/media/QQ_receipt.jpg?format=jpg&amp;name=small"></div> + </a> + </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,8 @@ 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"; +import type { XContextRunSummary } from "./xPostContext"; export type PostFetchInput = { // The account's canonical URL as configured on the channel. @@ -255,6 +257,24 @@ 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; + // X: read the post's CONTEXT off the page the shot loads -- the post it + // quotes and the post it answers -- into its capture.json's `context` + // (xPostContext.ts). Defaults to true. + context?: boolean; + // X: ONLY the context — one post page per post (one already read, or + // deleted, not loaded unless `force`), the context written into its + // capture.json and the avatars the page shows saved; no shot, no media, no + // article, no thread shot, no availability observation. Defaults to false. + contextOnly?: 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. @@ -274,6 +294,9 @@ export type PostCaptureInput = Pick< // parent is told by this id). isReply?: boolean; replyTo?: { id: string; author?: string }; + // What it quotes, as archived (X: the context read fills a quote + // card's missing id from it). + quoted?: { id: string; author?: string }; } >; // A soft stop: no new post is started once it fires, and the one in hand @@ -300,6 +323,10 @@ 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; + // X: what the run read of the posts' context, when it read any. + context?: XContextRunSummary; }; // Input for importing ONE post by its URL (`SocialFetcher.fetchOne`, release diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts @@ -30,6 +30,7 @@ import { readdir, stat } from "node:fs/promises"; import path from "node:path"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import type { PostAvailability } from "../lib/posts"; +import { AVATARS_DIRNAME } from "./xAvatars"; export const POSTS_MEDIA_DIRNAME = "posts-media"; export const CAPTURE_FILENAME = "capture.json"; @@ -56,9 +57,10 @@ export function postsMediaDir(channelRoot: string): string { // One post's capture directory. The id is checked here, at the one place a // post id becomes a path: a platform-native id is digits (X) or a short -// alphanumeric key (Bluesky), never a separator. +// alphanumeric key (Bluesky), never a separator. `_avatars` is the authors' +// pictures beside them (xAvatars.ts), never a post. export function postCaptureDir(outDir: string, id: string): string { - if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) { + if (!/^[A-Za-z0-9_-]{1,64}$/.test(id) || id === AVATARS_DIRNAME) { throw new Error(`"${id}" is not a post id`); } return path.join(outDir, id); @@ -173,6 +175,40 @@ export type ThreadCaptureRecord = CapturedFile & { }; }; +// THE POST'S CONTEXT as its page showed it (X, xPostContext.ts): the post it +// quotes and the post it answers, read off the page the capture loaded -- the +// archive often names neither (a timeline read keeps no quote, and a reply's +// parent is another account's post). What a card needs to draw them: who, +// their check, when, the words, the status link and the media URLs the page +// drew. `readAt` is when the page was read; a read that found neither is +// still a read (`{ readAt }` alone), so a context-only run does not load it +// again. Editor-only, like the rest of the record: never published. +export type PostContextPost = { + // The status id and link, when the page names them (a quote card often + // does not: the archive's quoted id fills it, when it agrees). + id?: string; + url?: string; + handle?: string; + // The display name. + author?: string; + verified?: boolean; + badge?: "blue" | "gold" | "grey" | "other"; + // ISO, from the post's <time>. + date?: string; + text: string; + // The pictures and videos it carries, as the page drew them (a video by its + // poster): links, never downloaded. + media: { kind: "image" | "video"; url: string }[]; +}; + +export type PostContextRecord = { + readAt: string; + quoted?: PostContextPost; + // How the parent was told: its status link matched the archive's + // in-reply-to id, or (the archive not saying) the post directly above. + parent?: PostContextPost & { from: "reply-to" | "above" }; +}; + export type PostCaptureRecord = { version: 1; id: string; @@ -202,6 +238,8 @@ export type PostCaptureRecord = { // is `threadError` instead, and owed again. threadNone?: string; threadError?: string; + // X: the quoted post and the parent, read off the page (xPostContext.ts). + context?: PostContextRecord; error?: string; }; diff --git a/common/social/xAvatarCapture.browser.test.ts b/common/social/xAvatarCapture.browser.test.ts @@ -0,0 +1,284 @@ +// 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. And the post's CONTEXT +// (xPostContext.ts) off the same page: the parent's and the quoted post's +// author, check, date, words and media, into capture.json -- on a normal run, +// and on a context-only one (one page load, nothing shot). +// +// 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 { CAPTURE_FILENAME, readPostCapture, 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); + // The context, read off the same load: the archive not saying, the + // parent is the article above. + const ctx = (await readPostCapture(path.join(out, POST_ID)))?.context; + assert.ok(ctx, log.join("\n")); + assert.deepEqual(ctx.parent, { + id: PARENT_ID, + url: `https://x.com/parent_person/status/${PARENT_ID}`, + handle: "parent_person", + author: "A Private Person", + verified: true, + badge: "blue", + date: "2026-10-30T12:00:00.000Z", + text: "So what happened next?", + media: [], + from: "above", + }); + assert.deepEqual(ctx.quoted, { + id: "1849000000000000005", + url: "https://x.com/quoted_person/status/1849000000000000005", + handle: "quoted_person", + author: "Quoted Person", + date: "2026-10-29T08:00:00.000Z", + text: "The receipt itself.", + media: [{ kind: "image", url: `${fx.origin}/media/QQ_receipt.jpg?format=jpg&name=small` }], + }); + + // 3. contextOnly, into a channel with no capture yet: one page load, + // nothing shot, the context and the avatars only; the archive's parent id. + const out3 = path.join(path.dirname(out), "posts-media-context"); + const res3 = await captureXPosts( + { ids: [POST_ID], handle: "ObviousRises", outDir: out3, signal: new AbortController().signal, contextOnly: true, archived, onLog }, + deps, + ); + assert.deepEqual(res3.outcomes, []); + assert.equal(res3.context?.read, 1, log.join("\n")); + assert.deepEqual(docLoads, [`/i/status/${POST_ID}`, `/i/status/${POST_ID}`, `/i/status/${POST_ID}`]); + assert.deepEqual(await readdir(path.join(out3, POST_ID)), [CAPTURE_FILENAME]); + const rec3 = await readPostCapture(path.join(out3, POST_ID)); + assert.equal(rec3?.shot, undefined); + assert.equal(rec3?.context?.parent?.from, "reply-to"); + assert.equal(rec3?.context?.parent?.id, PARENT_ID); + assert.equal(rec3?.context?.quoted?.handle, "quoted_person"); + assert.deepEqual(Object.keys(await readXAvatarIndex(path.join(out3, AVATARS_DIRNAME))), ["ObviousRises", "parent_person", "quoted_person"]); + assert.deepEqual(blocked, []); + + 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/xAvatars.test.ts b/common/social/xAvatars.test.ts @@ -0,0 +1,160 @@ +// The avatar store and the URL rule (xAvatars.ts). Temp dirs only. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xAvatars.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + AVATARS_DIRNAME, + AVATARS_INDEX_FILENAME, + isXAvatarHandle, + lookupXAvatar, + readXAvatarIndex, + upgradeXAvatarUrl, + writeXAvatar, + xAvatarExtension, + xAvatarFile, + xAvatarsDir, +} from "./xAvatars"; +import { postCaptureDir, postsMediaDir } from "./postCapture"; + +const JPG = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]); +const PB = "https://pbs.twimg.com/profile_images/1712345678901234567/AbC-dEf_"; + +test("url: every size X serves maps to _400x400, the extension and query kept", () => { + for (const suffix of ["normal", "bigger", "mini", "reasonably_small", "x96", "200x200", "400x400"]) { + assert.equal(upgradeXAvatarUrl(`${PB}${suffix}.jpg`), `${PB}400x400.jpg`, suffix); + } + // No suffix: the original upload, any size — asked for at 400 too. + assert.equal( + upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/abc.png"), + "https://pbs.twimg.com/profile_images/123/abc_400x400.png", + ); + // A name with an underscore of its own, and no extension at all. + assert.equal( + upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/my_pic_normal.jpeg"), + "https://pbs.twimg.com/profile_images/123/my_pic_400x400.jpeg", + ); + assert.equal( + upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/abc_normal"), + "https://pbs.twimg.com/profile_images/123/abc_400x400", + ); + assert.equal( + upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/abc_normal.webp?v=2"), + "https://pbs.twimg.com/profile_images/123/abc_400x400.webp?v=2", + ); +}); + +test("url: X's default egg, another host, another path or no URL is no avatar", () => { + assert.equal(upgradeXAvatarUrl("https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png"), null); + assert.equal(upgradeXAvatarUrl("https://pbs.twimg.com/sticky/default_profile_images/default_profile_400x400.png"), null); + assert.equal(upgradeXAvatarUrl("https://evil.example/profile_images/123/abc_normal.jpg"), null); + assert.equal(upgradeXAvatarUrl("https://pbs.twimg.com/media/Gabc123?format=jpg&name=small"), null); + assert.equal(upgradeXAvatarUrl("data:image/png;base64,AAAA"), null); + assert.equal(upgradeXAvatarUrl("not a url"), null); + // Loopback is allowed: a test's fixture server. + assert.equal( + upgradeXAvatarUrl("http://127.0.0.1:4321/profile_images/123/abc_normal.jpg"), + "http://127.0.0.1:4321/profile_images/123/abc_400x400.jpg", + ); +}); + +test("extension: the response's type, else the URL's, else jpg", () => { + assert.equal(xAvatarExtension(`${PB}400x400.jpg`, "image/png"), "png"); + assert.equal(xAvatarExtension(`${PB}400x400.jpg`, "image/jpeg; charset=binary"), "jpg"); + assert.equal(xAvatarExtension(`${PB}400x400.jpeg`), "jpg"); + assert.equal(xAvatarExtension(`${PB}400x400.webp`, "application/octet-stream"), "webp"); + assert.equal(xAvatarExtension(`${PB}400x400.gif`), "gif"); + assert.equal(xAvatarExtension(`${PB}400x400`), "jpg"); + assert.equal(xAvatarExtension(`${PB}400x400.bmp`), "jpg"); +}); + +test("handles: X's own shape only", () => { + for (const h of ["ObviousRises", "a", "under_score_1", "x".repeat(30)]) assert.equal(isXAvatarHandle(h), true, h); + for (const h of ["", "x".repeat(31), "../etc", "a.b", "a-b", "a b", "avatars.json"]) assert.equal(isXAvatarHandle(h), false, h); +}); + +test("layout: posts-media/_avatars, and _avatars is never taken for a post id", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "xavatars-layout-")); + assert.equal(xAvatarsDir(postsMediaDir(root)), path.join(root, "posts-media", AVATARS_DIRNAME)); + assert.throws(() => postCaptureDir(postsMediaDir(root), AVATARS_DIRNAME), /not a post id/); + assert.doesNotThrow(() => postCaptureDir(postsMediaDir(root), "_avatars2")); +}); + +test("store: the picture and its entry, in the exact shape umtool reads", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME); + const got = await writeXAvatar(dir, { + handle: "ObviousRises", + bytes: JPG, + url: `${PB}400x400.jpg`, + contentType: "image/jpeg", + postId: "1850000000000000001", + capturedAt: "2026-11-02T20:00:00.000Z", + }); + assert.equal(got.handle, "ObviousRises"); + assert.deepEqual(await readdir(dir).then((n) => n.sort()), ["ObviousRises.jpg", AVATARS_INDEX_FILENAME]); + assert.deepEqual(new Uint8Array(await readFile(path.join(dir, "ObviousRises.jpg"))), JPG); + assert.deepEqual(JSON.parse(await readFile(path.join(dir, AVATARS_INDEX_FILENAME), "utf8")), { + ObviousRises: { + file: "ObviousRises.jpg", + url: `${PB}400x400.jpg`, + capturedAt: "2026-11-02T20:00:00.000Z", + postId: "1850000000000000001", + }, + }); + assert.equal(await xAvatarFile(dir, "obviousrises"), path.join(dir, "ObviousRises.jpg")); + assert.equal(await xAvatarFile(dir, "nobody"), null); +}); + +test("store: merged with what is there; another case replaces the entry and its file", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME); + const w = (handle: string, ext = "jpg", postId = "1") => + writeXAvatar(dir, { handle, bytes: JPG, url: `${PB}400x400.${ext}`, postId, capturedAt: "2026-11-02T20:00:00.000Z" }); + await w("alice"); + await w("Bob", "png"); + // Two at once: the read-modify-writes do not drop each other. + await Promise.all([w("carol"), w("dave"), w("erin")]); + let index = await readXAvatarIndex(dir); + assert.deepEqual(Object.keys(index), ["alice", "Bob", "carol", "dave", "erin"]); + + // A re-capture as X prints it now: one entry, the old file gone. + await w("BOB", "jpg", "2"); + index = await readXAvatarIndex(dir); + assert.deepEqual(Object.keys(index), ["alice", "BOB", "carol", "dave", "erin"]); + assert.equal(index.BOB.postId, "2"); + assert.equal(lookupXAvatar(index, "@bob")?.handle, "BOB"); + assert.equal(lookupXAvatar(index, "nobody"), null); + const files = (await readdir(dir)).sort(); + assert.ok(!files.includes("Bob.png"), files.join(",")); + assert.ok(files.includes("BOB.jpg")); + assert.ok(!files.some((f) => f.includes(".tmp-")), "no temp file left"); +}); + +test("store: a bad handle, a bad post id or no bytes is refused; an unreadable index is never overwritten", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME); + const ok = { handle: "alice", bytes: JPG, url: `${PB}400x400.jpg`, postId: "1" }; + await assert.rejects(writeXAvatar(dir, { ...ok, handle: "../x" }), /not an X handle/); + await assert.rejects(writeXAvatar(dir, { ...ok, handle: "avatars.json" }), /not an X handle/); + await assert.rejects(writeXAvatar(dir, { ...ok, postId: "../1" }), /not a post id/); + await assert.rejects(writeXAvatar(dir, { ...ok, bytes: new Uint8Array() }), /empty/); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, AVATARS_INDEX_FILENAME), "{ truncated"); + await assert.rejects(writeXAvatar(dir, ok), /unparseable; not overwriting/); + assert.equal(await readFile(path.join(dir, AVATARS_INDEX_FILENAME), "utf8"), "{ truncated"); + // A reader just finds nothing. + assert.deepEqual(await readXAvatarIndex(dir), {}); +}); + +test("store: entries not of the shape, or under a key that is no handle, are left out on read", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME); + await mkdir(dir, { recursive: true }); + const good = { file: "a.jpg", url: "u", capturedAt: "t", postId: "1" }; + await writeFile( + path.join(dir, AVATARS_INDEX_FILENAME), + JSON.stringify({ a: good, "b/c": good, d: { file: 3 }, e: null }), + ); + assert.deepEqual(await readXAvatarIndex(dir), { a: good }); +}); diff --git a/common/social/xAvatars.ts b/common/social/xAvatars.ts @@ -0,0 +1,228 @@ +// X authors' profile pictures, kept beside a channel's post captures so a post +// card can show the author's face instead of an initial letter. +// +// THE STORE (umtool reads it as plain JSON; keep the shape): +// +// channels/<slug>/posts-media/_avatars/<handle>.<ext> ext: jpg | png | webp | gif +// channels/<slug>/posts-media/_avatars/avatars.json +// { "<handle>": { "file": "<handle>.<ext>", +// "url": "<the _400x400 url it was fetched from>", +// "capturedAt": "<ISO>", +// "postId": "<the post page it was read from>" } } +// +// Keys keep the handle's case as X prints it; a lookup ignores case, and a +// re-capture under another case REPLACES the entry (and its file), never adds a +// second one. Handles are X's: `^[A-Za-z0-9_]{1,30}$`. Every write is atomic +// (tmp + rename) and a read-modify-write of the index under the process's +// per-file lock, so a write never drops another handle. +// +// `_avatars` sits among the post-id directories of posts-media/ and is never +// one: postCaptureDir refuses the name (postCapture.ts), and nothing that walks +// posts-media/ takes its children for post ids (the readers go by archived or +// cited id). +// +// Capturing them is xAvatarCapture.ts (in the post page capture-posts already +// loads); this module is the store and the URL rule only — no browser. +// +// SERVER-ONLY (node:fs). + +import { rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { + readJsonFile, + withJsonFileLock, + writeFileAtomic, + writeJsonAtomic, +} from "../lib/jsonFile-server"; + +export const AVATARS_DIRNAME = "_avatars"; +export const AVATARS_INDEX_FILENAME = "avatars.json"; + +export type XAvatarEntry = { + file: string; + url: string; + capturedAt: string; + postId: string; +}; + +export type XAvatarIndex = Record<string, XAvatarEntry>; + +const HANDLE_RE = /^[A-Za-z0-9_]{1,30}$/; +const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; + +export function isXAvatarHandle(handle: string): boolean { + return HANDLE_RE.test(handle); +} + +// `<posts-media>/_avatars`. +export function xAvatarsDir(postsMediaDir: string): string { + return path.join(postsMediaDir, AVATARS_DIRNAME); +} + +// The sizes X serves a profile picture at, as the suffix before the extension. +const SIZE_SUFFIXES = ["normal", "bigger", "mini", "reasonably_small", "x96", "200x200", "400x400"]; +const PROFILE_IMAGE_PATH = new RegExp( + `^(.*/profile_images/\\d+/)([^/]+?)(?:_(?:${SIZE_SUFFIXES.join("|")}))?(\\.[A-Za-z0-9]+)?$`, +); + +// Hosts an avatar is fetched from: X's image CDN, and loopback (a test's +// fixture server — never a third-party host a page could name). +function avatarHostAllowed(host: string): boolean { + return host === "pbs.twimg.com" || host === "127.0.0.1" || host === "localhost" || host === "[::1]"; +} + +// A profile picture's URL at 400×400, the largest fixed size X serves (the +// no-suffix original can be any size). `_normal` (48), `_bigger` (73), `_mini` +// (24), `_reasonably_small` (128), `_x96`, `_200x200`, `_400x400` and the +// no-suffix original all map to it; the extension and any query stay. X's +// default "egg" (abs.twimg.com/sticky/default_profile_images/…) is no +// picture of anyone and is not stored: null — as is anything that is not a +// profile_images URL on X's CDN. +export function upgradeXAvatarUrl(src: string): string | null { + let u: URL; + try { + u = new URL(src); + } catch { + return null; + } + if (u.protocol !== "https:" && u.protocol !== "http:") return null; + if (/\/default_profile_images\//.test(u.pathname)) return null; + if (!avatarHostAllowed(u.hostname === "::1" ? "[::1]" : u.hostname)) return null; + const m = PROFILE_IMAGE_PATH.exec(u.pathname); + if (!m) return null; + u.pathname = `${m[1]}${m[2]}_400x400${m[3] ?? ""}`; + return u.toString(); +} + +const TYPE_EXT: Record<string, string> = { + "image/jpeg": "jpg", + "image/jpg": "jpg", + "image/pjpeg": "jpg", + "image/png": "png", + "image/webp": "webp", + "image/gif": "gif", +}; + +// The stored file's extension: the response's type when it names one of the +// four, else the URL's, else jpg (what X serves profile pictures as). +export function xAvatarExtension(url: string, contentType?: string | null): string { + const t = (contentType ?? "").split(";")[0].trim().toLowerCase(); + if (TYPE_EXT[t]) return TYPE_EXT[t]; + let pathname = url; + try { + pathname = new URL(url).pathname; + } catch { + /* a bare path */ + } + const ext = /\.([A-Za-z0-9]+)$/.exec(pathname)?.[1]?.toLowerCase(); + if (ext === "jpeg" || ext === "jpg") return "jpg"; + if (ext === "png" || ext === "webp" || ext === "gif") return ext; + return "jpg"; +} + +function validEntry(handle: string, v: unknown): v is XAvatarEntry { + if (!isXAvatarHandle(handle) || !v || typeof v !== "object") return false; + const e = v as Partial<XAvatarEntry>; + return typeof e.file === "string" && typeof e.url === "string" && typeof e.capturedAt === "string" && typeof e.postId === "string"; +} + +type IndexRead = { ok: true; index: XAvatarIndex } | { ok: false; reason: "unreadable" | "unparseable" }; + +async function readIndexStrict(dir: string): Promise<IndexRead> { + const got = await readJsonFile(path.join(dir, AVATARS_INDEX_FILENAME)); + if (!got.ok) return got.reason === "absent" ? { ok: true, index: {} } : { ok: false, reason: got.reason }; + const v = got.value; + if (!v || typeof v !== "object" || Array.isArray(v)) return { ok: false, reason: "unparseable" }; + const index: XAvatarIndex = {}; + for (const [k, e] of Object.entries(v as Record<string, unknown>)) { + if (validEntry(k, e)) index[k] = { file: e.file, url: e.url, capturedAt: e.capturedAt, postId: e.postId }; + } + return { ok: true, index }; +} + +// The store's index; {} when there is none (or it cannot be read — a lookup +// then simply finds nothing). Entries that are not the shape are left out. +export async function readXAvatarIndex(dir: string): Promise<XAvatarIndex> { + const got = await readIndexStrict(dir); + return got.ok ? got.index : {}; +} + +// The entry for `handle`, whatever case it was stored under. +export function lookupXAvatar( + index: XAvatarIndex, + handle: string, +): { handle: string; entry: XAvatarEntry } | null { + const want = handle.replace(/^@/, "").toLowerCase(); + for (const [k, entry] of Object.entries(index)) { + if (k.toLowerCase() === want) return { handle: k, entry }; + } + return null; +} + +// The picture's absolute path, when the store has one for `handle` and the +// file is there. +export async function xAvatarFile(dir: string, handle: string): Promise<string | null> { + const hit = lookupXAvatar(await readXAvatarIndex(dir), handle); + if (!hit) return null; + const file = path.join(dir, path.basename(hit.entry.file)); + return (await stat(file).catch(() => null))?.isFile() ? file : null; +} + +export type WriteXAvatarInput = { + handle: string; + bytes: Uint8Array; + // The URL the bytes came from (the _400x400 one). + url: string; + contentType?: string | null; + // The post page the avatar was read from. + postId: string; + capturedAt?: string; +}; + +// Store one avatar: the picture as `<handle>.<ext>`, then its entry merged +// into avatars.json (an entry for the same handle in another case, and its +// file, replaced). Refuses a handle that is not X's, and an index it cannot +// read (it is never overwritten from ignorance). +export async function writeXAvatar(dir: string, a: WriteXAvatarInput): Promise<{ handle: string; entry: XAvatarEntry }> { + const handle = a.handle.replace(/^@/, ""); + if (!isXAvatarHandle(handle)) throw new Error(`"${a.handle}" is not an X handle`); + if (!POST_ID_RE.test(a.postId)) throw new Error(`"${a.postId}" is not a post id`); + if (!a.bytes || a.bytes.length === 0) throw new Error(`The avatar for @${handle} is empty`); + const file = `${handle}.${xAvatarExtension(a.url, a.contentType)}`; + const entry: XAvatarEntry = { + file, + url: a.url, + capturedAt: a.capturedAt ?? new Date().toISOString(), + postId: a.postId, + }; + const indexPath = path.join(dir, AVATARS_INDEX_FILENAME); + await withJsonFileLock(indexPath, async () => { + const got = await readIndexStrict(dir); + if (!got.ok) throw new Error(`${indexPath} is ${got.reason}; not overwriting it`); + await writeFileAtomic(path.join(dir, file), Buffer.from(a.bytes), { mkdir: true }); + const index = got.index; + for (const [k, old] of Object.entries(index)) { + if (k.toLowerCase() !== handle.toLowerCase()) continue; + delete index[k]; + if (old.file !== file) await removeOldFile(dir, path.basename(old.file), file); + } + index[handle] = entry; + const sorted: XAvatarIndex = {}; + for (const k of Object.keys(index).sort((x, y) => x.toLowerCase().localeCompare(y.toLowerCase()) || x.localeCompare(y))) { + sorted[k] = index[k]; + } + await writeJsonAtomic(indexPath, sorted); + }); + return { handle, entry }; +} + +// The replaced entry's picture, unless it IS the new one (a case-insensitive +// filesystem names `Foo.jpg` and `foo.jpg` the same file). +async function removeOldFile(dir: string, oldName: string, newName: string): Promise<void> { + if (!oldName || oldName === AVATARS_INDEX_FILENAME) return; + const oldPath = path.join(dir, oldName); + const [o, n] = await Promise.all([stat(oldPath).catch(() => null), stat(path.join(dir, newName)).catch(() => null)]); + if (!o) return; + if (n && o.ino === n.ino && o.dev === n.dev) return; + await rm(oldPath, { force: true }); +} diff --git a/common/social/xGalleryDlFetcher.test.ts b/common/social/xGalleryDlFetcher.test.ts @@ -416,3 +416,101 @@ test("the capture's gap before each contact is the reads' 4–10 s, drawn fresh" assert.equal(xRequestPauseMs(() => 1), 10_000); assert.equal(xRequestPauseMs(() => 0.5), 7_000); }); + +// --------------------------------------------------------------------------- +// Quoted posts (gallery-dl's twitter `quoted` option) +// --------------------------------------------------------------------------- +// +// __fixtures__/gallery-dl-timeline-quotes.jsonl is a timeline read in +// gallery-dl 1.32.9's --dump-json/output.jsonl shape, as its twitter +// extractor writes it (extractor/twitter.py _transform_tweet: bare 64-bit +// ids, `quote_id` set on the QUOTED tweet's record naming the one quoting it, +// `quote_by`, a [3, url, kwdict] record per file): built to that shape by +// hand -- the suite never contacts X. Lines: a post quoting Kirsche and the +// quote; a post with a picture quoting one with a picture (each with its file +// record); a post quoting the account's OWN older post, that post met first +// as the quote; a reply; and the older post again as a post of the timeline +// (gallery-dl's dedupe is off, so the walk still archives it). + +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { normalizeXTweets } from "./xNormalize"; +import { parseGalleryDlOutput } from "./xGalleryDlFetcher"; + +const QUOTES_JSONL = readFileSync( + fileURLToPath(new URL("./__fixtures__/gallery-dl-timeline-quotes.jsonl", import.meta.url)), + "utf8", +); +const T1 = "1983300000000000001"; // quotes Kirsche's Q1 +const Q1 = "1983200000000000007"; +const T2 = "1983300000000000002"; // quotes quoted_person's Q2 +const Q2 = "1983100000000000003"; +const T3 = "1983300000000000003"; // quotes his own T5 +const T5 = "1981000000000000005"; +const T4 = "1983300000000000004"; // a reply + +test("every read keeps quoted posts and turns gallery-dl's own dedupe off; the media capture does neither", () => { + const timeline = buildGalleryDlArgs({ accountUrl: ACCOUNT, stream: true }); + const search = buildGalleryDlSearchArgs({ handle: "example_user", position: { since: "2020-12-11", until: "2021-03-11" } }); + for (const argv of [timeline, search]) { + assert.ok(argv.includes("extractor.twitter.quoted=true")); + assert.ok(argv.includes("extractor.twitter.unique=false")); + } + const capture = buildGalleryDlCaptureArgs({ id: "123", dir: "/corpus/x/posts-media/123" }); + assert.equal(capture.some((a) => a.startsWith("extractor.twitter.quoted=")), false, "a capture downloads the post's own media only"); +}); + +test("stream: a quoted tweet's record becomes the quoting post's `quoted`, never a post of the account's", () => { + const s = newStream({ channelSlug: "ObviousRises-x" }); + for (const line of QUOTES_JSONL.split("\n")) s.pushStdout(line); + const posts = s.finish(); + assert.deepEqual(posts.map((p) => p.id), [T1, T2, T3, T4, T5]); + const by = new Map(posts.map((p) => [p.id, p])); + assert.deepEqual(by.get(T1)?.quoted, { platform: "twitter", id: Q1, author: "Kirsche", url: `https://x.com/Kirsche/status/${Q1}` }); + assert.deepEqual(by.get(T2)?.quoted, { platform: "twitter", id: Q2, author: "quoted_person", url: `https://x.com/quoted_person/status/${Q2}` }); + // His own older post: the quote of the newer one, and archived as his post when the walk reaches it. + assert.equal(by.get(T3)?.quoted?.id, T5); + assert.equal(by.get(T3)?.quoted?.author, "ObviousRises"); + assert.equal(by.get(T5)?.text, "an older post of my own"); + assert.equal(by.get(T5)?.quoted, undefined); + assert.equal(by.get(T4)?.quoted, undefined); + assert.equal(by.get(T4)?.replyTo?.author, "Kirsche"); + assert.equal(by.get(T2)?.mediaCount, 1); + // Counted: 5 posts, 3 given their quote; gallery-dl yielded 8 tweets + // toward --post-range (each quote, and T5 twice — as a quote and as itself). + assert.equal(s.distinct, 5); + assert.equal(s.newPosts, 5); + assert.equal(s.quotesLinked, 3); + assert.equal(s.yielded, 8); +}); + +test("stream: a quote is no resume point and no stop — and is linked whichever of the two arrives first", () => { + const lines = QUOTES_JSONL.split("\n").filter(Boolean); + // T1 then Q1: Q1's id is OLDER than T1's, and must not become the walk's + // oldest post (a search window resumes below it). + const a = newStream(); + a.pushStdout(lines[0]); + a.pushStdout(lines[1]); + assert.equal(a.oldestId, T1); + // The quote first. + const b = newStream(); + b.pushStdout(lines[1]); + b.pushStdout(lines[0]); + const [post] = b.finish(); + assert.equal(post.quoted?.id, Q1); + // A quoting post already archived: not re-written, the quote not a post. + const c = newStream({ seenIds: new Set([T1]) }); + c.pushStdout(lines[0]); + c.pushStdout(lines[1]); + assert.deepEqual(c.finish(), []); + assert.equal(c.known, 1); + assert.equal(c.quotesLinked, 0); +}); + +test("normalizeXTweets (the Playwright fallback's batch) links quotes the same way", () => { + const posts = normalizeXTweets(parseGalleryDlOutput(QUOTES_JSONL), "ObviousRises-x"); + assert.deepEqual(posts.map((p) => p.id).sort(), [T5, T4, T3, T2, T1].sort()); + assert.equal(posts.find((p) => p.id === T1)?.quoted?.id, Q1); + assert.equal(posts.find((p) => p.id === T3)?.quoted?.id, T5); + assert.ok(!posts.some((p) => p.id === Q1 || p.id === Q2)); +}); diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -33,9 +33,9 @@ import { getPaths } from "../lib/paths"; import { noteXServiceOutcome } from "../lib/serviceCookies-server"; import { looksLikeXAuthFailure, xBlockKind, xBlockLine } from "./xGalleryDlSignals"; import { cookieArgs } from "../lib/cookiePolicy"; -import type { Post } from "../lib/posts"; +import type { Post, PostRef } from "../lib/posts"; import type { OlderBackfillPosition } from "../lib/posts-server"; -import { normalizeXTweet, xCreatedAt, type XTweetRaw } from "./xNormalize"; +import { normalizeXTweet, xCreatedAt, xIdOf, xQuoteOf, type XTweetRaw } from "./xNormalize"; import { OLDER_MAX_EMPTY_WINDOWS, OLDER_WINDOW_MONTHS, @@ -191,6 +191,21 @@ function galleryDlCommonArgs(opts: GalleryDlLoginAndCap): string[] { "extractor.twitter.retweets=true", "-o", "extractor.twitter.replies=true", + // QUOTED POSTS: gallery-dl yields the post a tweet quotes as a record of + // its own, right after the tweet (its `quote_id` naming the quoting one) -- + // the only way a read learns what a post quotes, since its flat record of + // the quoting tweet names none. The stream (GalleryDlStream) turns it into + // the quoting post's `quoted` and never archives it as the account's own. + // On the timeline it costs no request: the quote is already inside the + // page X returned. + "-o", + "extractor.twitter.quoted=true", + // …and gallery-dl's own "previously seen" dedupe off: with quotes on, the + // account's OWN older post, met first as the quote of a newer one, would + // otherwise be skipped when the walk reaches it as a post of the timeline, + // and never archived. The stream dedupes by id itself. + "-o", + "extractor.twitter.unique=false", // Media is counted, not archived. "-o", "extractor.twitter.videos=false", @@ -201,7 +216,9 @@ function galleryDlCommonArgs(opts: GalleryDlLoginAndCap): string[] { ]; // A cap on POSTS. `--range` counts files, and with downloads off most tweets // yield none, so it never stopped the walk: a 400-post fetch of a new - // channel read 3,803. `--post-range` counts the tweets themselves. + // channel read 3,803. `--post-range` counts the tweets themselves -- the + // quoted ones and any repeat among them (GalleryDlStream.yielded is what + // a capped run is told by). if (opts.limit && opts.limit > 0) { args.push("--post-range", `1-${Math.floor(opts.limit)}`); } @@ -372,11 +389,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 = @@ -582,6 +600,12 @@ export type GalleryDlCheckpoint = { posts: Post[]; cursor: string }; export class GalleryDlStream { // Every distinct post seen this run, new or not. distinct = 0; + // Every record gallery-dl counted toward --post-range: each tweet it + // yielded, quoted ones and repeats included (a tweet's directory record and + // its per-URL records are one). What tells a capped run from a finished one. + yielded = 0; + // Posts read this run that a quoted record gave their `quoted`. + quotesLinked = 0; newPosts = 0; known = 0; older = 0; @@ -599,6 +623,11 @@ export class GalleryDlStream { private savedCursor?: string; private pending: Post[] = []; private ids = new Set<string>(); + private yieldedKeys = new Set<string>(); + // The new posts of this run by id, for a quote met after its quoting post. + private newById = new Map<string, Post>(); + // Quoting id → the quoted ref, for a quoting post met after its quote. + private quotedBy = new Map<string, PostRef>(); private knownRun = 0; private tail: string[] = []; private unparsed: string[] = []; @@ -696,6 +725,26 @@ export class GalleryDlStream { } private addRecord(rec: XTweetRaw): void { + const link = xQuoteOf(rec); + const rawId = xIdOf(rec); + // One tweet's directory record and its per-URL records are one post to + // --post-range; the same tweet quoted by two posts is two. + const tweetKey = rawId ? `${rawId}:${link?.quoterId ?? ""}` : ""; + if (tweetKey && !this.yieldedKeys.has(tweetKey)) { + this.yieldedKeys.add(tweetKey); + this.yielded++; + } + // A QUOTED tweet's own record: the quote of the post quoting it, never a + // post of this account's. Not counted, not a resume point, not a stop. + if (link) { + if (!this.quotedBy.has(link.quoterId)) this.quotedBy.set(link.quoterId, link.quoted); + const quoter = this.newById.get(link.quoterId); + if (quoter && !quoter.quoted) { + quoter.quoted = link.quoted; + this.quotesLinked++; + } + return; + } const post = normalizeXTweet(rec, this.opts.channelSlug); // gallery-dl can emit a tweet more than once (a directory record, then one // per media URL); count it once. @@ -728,6 +777,12 @@ export class GalleryDlStream { } this.knownRun = 0; this.newPosts++; + const quoted = this.quotedBy.get(post.id); + if (quoted && !post.quoted) { + post.quoted = quoted; + this.quotesLinked++; + } + this.newById.set(post.id, post); this.pending.push(post); } } @@ -1121,7 +1176,8 @@ async function walkSearchWindows( } onLog?.( `${windowStart.since} – ${windowStart.until}: read ${stream.distinct} post(s), ${stream.newPosts} new` + - (stream.known ? `, ${stream.known} already archived` : ""), + (stream.known ? `, ${stream.known} already archived` : "") + + (stream.quotesLinked ? `, ${stream.quotesLinked} with the post it quotes` : ""), ); if (stream.challengeLine) { @@ -1147,7 +1203,7 @@ async function walkSearchWindows( error: `gallery-dl exited ${res.exitCode ?? res.signal ?? "abnormally"}: ${tail || "(no output)"}`, }); } - if (remainingLimit !== undefined && stream.distinct >= remainingLimit) { + if (remainingLimit !== undefined && stream.yielded >= remainingLimit) { return stopped(here); } @@ -1392,7 +1448,8 @@ export const xGalleryDlFetcher: SocialFetcher = { onLog?.( `gallery-dl read ${stream.distinct} post(s): ${stream.newPosts} new` + (stream.known ? `, ${stream.known} already archived` : "") + - (stream.older ? `, ${stream.older} older than the watermark` : ""), + (stream.older ? `, ${stream.older} older than the watermark` : "") + + (stream.quotesLinked ? `, ${stream.quotesLinked} new with the post it quotes` : ""), ); // Where the next run should pick up when this one did not finish: the last @@ -1459,7 +1516,7 @@ export const xGalleryDlFetcher: SocialFetcher = { // A clean exit walked everything it was given: gallery-dl waits out rate // limits rather than skipping pages. Only a --post-range cap leaves history // behind — resume from the last page it finished. - const capped = Boolean(limit && stream.distinct >= limit); + const capped = Boolean(limit && stream.yielded >= limit); return capped ? { posts, complete: false, cursor: resumeAt } : { posts, complete: true }; diff --git a/common/social/xNormalize.ts b/common/social/xNormalize.ts @@ -144,6 +144,25 @@ function refFrom( return ref; } +// THE QUOTED TWEET AS gallery-dl YIELDS IT. With its twitter `quoted` option +// on (every read here turns it on, xGalleryDlFetcher.ts), gallery-dl yields a +// quoted tweet as a record of its own, right after the tweet quoting it, its +// `quote_id` naming the QUOTING tweet (and `quote_by` that tweet's author) -- +// the reverse link: X's timeline carries the quote inside the quoting tweet, +// and gallery-dl's flat record of the quoting tweet names no quote at all. +// Such a record is not one of the account's posts: it says what ANOTHER post +// quotes. This is the link it carries -- the quoting tweet's id, and the ref +// the quoting post's `quoted` should hold -- or null for any other record. +export function xQuoteOf(rec: XTweetRaw): { quoterId: string; quoted: PostRef } | null { + const quoterId = refId(rec.quote_id); + if (!quoterId) return null; + const id = xIdOf(rec); + if (!id || id === quoterId) return null; + const handle = xAuthor(rec).handle; + const quoted = refFrom(id, handle || undefined); + return quoted ? { quoterId, quoted } : null; +} + // Normalize one tweet record into a Post. Returns null when the record has no // resolvable id or timestamp — a shape we don't understand is skipped rather // than stored as a corrupt entry. @@ -244,15 +263,27 @@ export function normalizeXTweet( } // Normalize a batch, dropping unparseable records and deduping by id (a -// timeline page can repeat a tweet across a cursor boundary). +// timeline page can repeat a tweet across a cursor boundary). A quoted tweet's +// own record (xQuoteOf) is not a post of the batch: it becomes the `quoted` of +// the post quoting it, where that post names none. export function normalizeXTweets( records: ReadonlyArray<XTweetRaw>, channelSlug: string, ): Post[] { const byId = new Map<string, Post>(); + const quotes = new Map<string, PostRef>(); for (const rec of records) { + const link = xQuoteOf(rec); + if (link) { + if (!quotes.has(link.quoterId)) quotes.set(link.quoterId, link.quoted); + continue; + } const post = normalizeXTweet(rec, channelSlug); if (post && !byId.has(post.id)) byId.set(post.id, post); } + for (const [quoterId, quoted] of quotes) { + const post = byId.get(quoterId); + if (post && !post.quoted) post.quoted = quoted; + } return [...byId.values()]; } diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts @@ -30,6 +30,19 @@ // 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. +// +// The post's CONTEXT -- the post it quotes and the post it answers, as the +// page shows them -- is read off the same page too (xPostContext.ts) and kept +// in capture.json's `context`, unless `context` is off. `contextOnly` loads +// one page per post for that alone (and the avatars it shows), and writes the +// context into the post's record, nothing else. +// // 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. @@ -55,11 +68,30 @@ import { type CaptureMediaState, type PostCaptureRecord, type PostCaptureState, + type PostContextRecord, } from "./postCapture"; 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"; +import { + describeContext, + describeContextSummary, + emptyContextSummary, + noteContext, + readXPostContext, + type XContextReadOptions, +} from "./xPostContext"; // The post's own article, marked by the snapshot. const CAPTURE_SELECTOR = "[data-archilyzer-capture]"; @@ -209,6 +241,11 @@ 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[]; + // The quoted post and the parent, read off the page, when asked for and + // the post rendered (null: the page could not be read for them). + context?: PostContextRecord | null; }; export type XShotOptions = { @@ -217,6 +254,11 @@ 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; + // Read the post's context (xPostContext.ts): the quoted post, the parent. + context?: XContextReadOptions | null; }; // One post's screenshot: load, read the page, open a sensitive cover, shoot @@ -262,9 +304,14 @@ 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 context = opts.context ? await readXPostContext(page, opts.context) : undefined; + const found = { ...(avatars ? { avatars } : {}), ...(context !== undefined ? { context } : {}) }; 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 +345,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 +389,16 @@ export async function captureXPosts( force: input.force ?? false, articles: input.articles ?? true, thread: input.thread ?? false, + avatars: input.avatars ?? true, + context: input.context ?? true, }; + if (input.contextOnly) return captureXContextOnly(input, deps); + 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 contextSummary = emptyContextSummary(); const outcomes: PostCaptureOutcome[] = []; let contacts = 0; let errorsInARow = 0; @@ -352,9 +407,20 @@ 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 withContext = (): Partial<PostCaptureResult> => { + if (!contextSummary.read && !contextSummary.failed.length) return {}; + onLog?.(describeContextSummary(contextSummary)); + return { context: contextSummary }; + }; const stopped = (why: string, extra: Partial<PostCaptureResult> = {}) => { onLog?.(why); - return { outcomes, stoppedEarly: why, ...extra }; + return { outcomes, stoppedEarly: why, ...extra, ...withAvatars(), ...withContext() }; }; try { @@ -392,6 +458,8 @@ export async function captureXPosts( let state: PostCaptureState | undefined = work.shot ? undefined : existing?.state; let sensitive = work.shot ? undefined : existing?.sensitive; let shot = work.shot ? undefined : existing?.shot; + // The context is read from any page this run loads; else the last one's stands. + let context = existing?.context; let error: string | undefined; let stop: string | undefined; @@ -404,7 +472,24 @@ 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, + context: wanted.context ? contextReadOptions(arch, now) : null, }); + if (res.context) { + context = res.context; + noteContext(contextSummary, res.context); + } + 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; @@ -493,6 +578,7 @@ export async function captureXPosts( ...(thread ? { thread } : {}), ...(threadNone && !thread ? { threadNone } : {}), ...(threadError && !thread ? { threadError } : {}), + ...(context ? { context } : {}), ...(error ? { error } : {}), }; await writePostCapture(dir, record); @@ -516,6 +602,7 @@ export async function captureXPosts( (work.thread && !thread && (threadNone || threadError) ? `, no thread shot: ${threadNone ?? threadError}` : "") + (mediaState === "ok" ? `, ${media.length} media file(s)` : mediaState === "none" ? ", no media" : "") + (article && article !== existing?.article ? `, ${describeArticle(article)}` : "") + + (context && context !== existing?.context ? `, ${describeContext(context)}` : "") + (error ? ` — ${error}` : ""), ); @@ -531,7 +618,227 @@ export async function captureXPosts( ); } } - return { outcomes }; + return { outcomes, ...withAvatars(), ...withContext() }; + } finally { + await browser?.close().catch(() => {}); + } +} + +type ArchivedForAvatars = { author?: string; isReply?: boolean; replyTo?: { id: string } } | undefined; +type ArchivedForContext = + | { replyTo?: { id: string; author?: string }; quoted?: { id: string; author?: string } } + | undefined; + +// What the context read is told by the archive: the id the post answers (its +// parent is that article), and the id it quotes (for a card that names none). +function contextReadOptions(arch: ArchivedForContext, now: () => Date): XContextReadOptions { + return { replyTo: arch?.replyTo ?? null, quoted: arch?.quoted ?? null, now }; +} + +// 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(() => {}); + } +} + +// `contextOnly`: one post page per post, its CONTEXT read off it (the post it +// quotes, the post it answers) and written into the post's capture.json -- +// merged into the record there, or a record of its own (state "captured", +// nothing shot, media owed) when there is none -- and the avatars the page +// shows saved (unless `avatars` is off). No shot, no media, no article, no +// thread shot, no availability: `outcomes` stays empty. A post whose context +// is already recorded, or that a capture found deleted, is not loaded unless +// `force`. Paced like every other X contact, and stopped like one. +async function captureXContextOnly(input: PostCaptureInput, deps: XCaptureDeps): Promise<PostCaptureResult> { + const { signal, onLog } = input; + const force = input.force ?? false; + const avatarsOn = input.avatars ?? true; + const now = deps.now ?? (() => new Date()); + const avatarDir = xAvatarsDir(input.outDir); + const summary = emptyContextSummary(); + const avatarSummary = emptyAvatarSummary(); + const avatarSeen = new Set<string>(); + + const picks: { id: string; existing: PostCaptureRecord | null }[] = []; + for (const id of input.ids) { + const existing = await readPostCapture(postCaptureDir(input.outDir, id)); + if (!force && existing?.context) { + summary.skipped++; + onLog?.(`${id}: context already read (${existing.context.readAt}) — skipped (no page load).`); + continue; + } + if (!force && existing?.state === "deleted") { + summary.skipped++; + onLog?.(`${id}: captured as deleted — skipped.`); + continue; + } + picks.push({ id, existing }); + } + onLog?.(`Context only: ${picks.length} post page(s) to load.`); + + let contacts = 0; + let errorsInARow = 0; + let browser: { page: PageLike; close: () => Promise<void> } | undefined; + const done = (extra: Partial<PostCaptureResult> = {}): PostCaptureResult => { + onLog?.(describeContextSummary(summary)); + const avatars = avatarSummary.stored.length || avatarSummary.skipped.length || avatarSummary.failed.length; + if (avatars) onLog?.(describeAvatarSummary(avatarSummary)); + return { outcomes: [], context: summary, ...(avatars ? { avatars: avatarSummary } : {}), ...extra }; + }; + const stopped = (why: string, extra: Partial<PostCaptureResult> = {}) => { + onLog?.(why); + return done({ stoppedEarly: why, ...extra }); + }; + try { + for (const [i, { id, existing }] 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 context)`); + browser ??= await deps.openPage(); + summary.pages++; + const arch = input.archived?.get(id); + const dir = postCaptureDir(input.outDir, id); + const res = await shootXPost(browser.page, id, dir, onLog, { + own: false, + thread: null, + avatars: avatarsOn ? { parent: true, quotes: true, parentId: arch?.replyTo?.id ?? null } : null, + context: contextReadOptions(arch, now), + }); + if (res.state !== "captured") { + const why = res.error ?? `the page showed the post as ${res.state}`; + onLog?.(`${id}: no context read — ${why}.`); + summary.failed.push({ id, error: 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?.length) { + await saveXAvatars(browser.page, res.avatars, { + dir: avatarDir, postId: id, force, seen: avatarSeen, summary: avatarSummary, now, onLog, + }); + } + if (!res.context) { + summary.failed.push({ id, error: "the page could not be read for its context" }); + onLog?.(`${id}: the page could not be read for its context.`); + continue; + } + // Re-read: a capture that ran meanwhile wrote the rest of the record. + const base = (await readPostCapture(dir)) ?? existing; + const record: PostCaptureRecord = base + ? { ...base, context: res.context } + : { + version: 1, + id, + url: xStatusUrl(id), + capturedAt: now().toISOString(), + state: "captured", + ...(res.sensitive ? { sensitive: true } : {}), + mediaState: "skipped", + media: [], + context: res.context, + }; + await writePostCapture(dir, record); + noteContext(summary, res.context); + onLog?.(`${id}: ${describeContext(res.context)}.`); + } + return done(); } finally { await browser?.close().catch(() => {}); } diff --git a/common/social/xPostContext.test.ts b/common/social/xPostContext.test.ts @@ -0,0 +1,282 @@ +// The context half of the X capture (the quoted post, the parent), against +// fakes only: the parse of the in-page read's answer, the record built from +// it, and the run (a normal capture and contextOnly) over a page that answers +// the capture's evaluates. The in-page read itself is proved in a real +// Chromium by xAvatarCapture.browser.test.ts, against the recorded-style page. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xPostContext.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readdir } 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 { + CONTEXT_SCRIPT_MARKER, + CONTEXT_TEXT_MAX, + contextRecordFrom, + contextScript, + parseContextPost, + readXPostContext, +} from "./xPostContext"; +import { THREAD_SNAPSHOT_MARKER, type ThreadSnapshot } from "./xThreadShot"; +import { AVATARS_SCRIPT_MARKER } from "./xAvatarCapture"; +import { VIEW_SCRIPT_MARKER } from "./viewportShot"; +import { readPostCapture, writePostCapture } from "./postCapture"; +import type { PostCaptureInput } from "./fetchers"; + +const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 9, 9]); +const RECT = { x: 10, y: 120, width: 598, height: 300 }; +const snap = (id: string): XPostSnapshot => ({ path: `/ObviousRises/status/${id}`, text: "the post", article: { rect: RECT, sensitive: false } }); + +// What the read returns for the operator's case: a reply to Kirsche, quoting +// a third post. +const KIRSCHE = { + id: "1983000000000000001", + handle: "Kirsche", + author: "Kirsche", + verified: true, + badge: "blue", + date: "2026-10-29T13:00:00.000Z", + text: "Your whole channel is grift.", + media: [], +}; +const QUOTED = { + id: null, + handle: "quoted_person", + author: "Quoted Person", + verified: false, + badge: null, + date: "2026-10-28T09:00:00.000Z", + text: "The receipt itself.", + media: [{ kind: "image", url: "https://pbs.twimg.com/media/QQ1.jpg?format=jpg&name=small" }], +}; +const THREAD: ThreadSnapshot = { + own: 1, + articles: [ + { id: KIRSCHE.id, handle: "Kirsche", verified: true, badge: "blue", top: 0, bottom: 200 }, + { id: "1983000000000000002", handle: "ObviousRises", verified: false, top: 200, bottom: 500 }, + ], +}; + +test("parse: the read's post kept to the shape — ids are digits, the date ISO, the media http(s) and at most four, the text capped", () => { + const p = parseContextPost({ + ...KIRSCHE, + handle: "@Kirsche", + date: "2026-10-29T13:00:00Z", + badge: "platinum", + media: [ + { kind: "image", url: "https://pbs.twimg.com/media/a.jpg" }, + { kind: "image", url: "https://pbs.twimg.com/media/a.jpg" }, + { kind: "gif", url: "https://pbs.twimg.com/media/b.jpg" }, + { kind: "video", url: "javascript:alert(1)" }, + { kind: "video", url: "https://pbs.twimg.com/ext_tw_video_thumb/1/pu/img/c.jpg" }, + ], + }); + assert.deepEqual(p, { + id: KIRSCHE.id, + url: `https://x.com/Kirsche/status/${KIRSCHE.id}`, + handle: "Kirsche", + author: "Kirsche", + verified: true, + date: "2026-10-29T13:00:00.000Z", + text: "Your whole channel is grift.", + media: [ + { kind: "image", url: "https://pbs.twimg.com/media/a.jpg" }, + { kind: "video", url: "https://pbs.twimg.com/ext_tw_video_thumb/1/pu/img/c.jpg" }, + ], + }); + assert.equal(parseContextPost({ ...KIRSCHE, id: "../etc", handle: "not a handle!" })?.id, undefined); + assert.equal(parseContextPost({ ...KIRSCHE, text: "x".repeat(CONTEXT_TEXT_MAX + 50) })?.text.length, CONTEXT_TEXT_MAX); + // Nobody and nothing said is no post. + assert.equal(parseContextPost({ handle: null, text: " " }), null); + assert.equal(parseContextPost("a string"), null); + assert.equal(parseContextPost(null), null); +}); + +test("record: the quote and the parent with how the parent was told; the archive's quoted id fills a card that names none, only when the authors agree", () => { + const rec = contextRecordFrom({ quoted: QUOTED, parent: KIRSCHE }, { from: "above" }, { + quoted: { id: "1982000000000000009", author: "quoted_person" }, + readAt: "2026-11-02T20:00:00.000Z", + }); + assert.equal(rec?.readAt, "2026-11-02T20:00:00.000Z"); + assert.equal(rec?.parent?.from, "above"); + assert.equal(rec?.parent?.handle, "Kirsche"); + assert.equal(rec?.parent?.badge, "blue"); + assert.equal(rec?.quoted?.id, "1982000000000000009"); + assert.equal(rec?.quoted?.url, "https://x.com/quoted_person/status/1982000000000000009"); + assert.equal(rec?.quoted?.media.length, 1); + + const other = contextRecordFrom({ quoted: QUOTED, parent: null }, null, { quoted: { id: "1982000000000000009", author: "someone_else" }, readAt: "t" }); + assert.equal(other?.quoted?.id, undefined, "another author's id is not this card's"); + // No pick: no parent, whatever the page answered. + assert.equal(contextRecordFrom({ quoted: null, parent: KIRSCHE }, null, { readAt: "t" })?.parent, undefined); + // Neither: still a read. + assert.deepEqual(contextRecordFrom({ quoted: null, parent: null }, null, { readAt: "t" }), { readAt: "t" }); + // Not the read's shape: not read. + assert.equal(contextRecordFrom(snap("1"), null, { readAt: "t" }), null); + assert.equal(contextRecordFrom(null, null, { readAt: "t" }), null); +}); + +test("script: carries its marker; reads the parent at the picked index, or none", () => { + assert.ok(contextScript(0).includes(CONTEXT_SCRIPT_MARKER)); + assert.match(contextScript(3), /all\[3\] \|\| null/); + assert.match(contextScript(null), /const parent = null;/); + assert.ok(contextScript(null).includes("badgeOf"), "the badge is told as the thread snapshot tells it"); +}); + +function contextPage(answer: { quoted: unknown; parent: unknown }, thread: ThreadSnapshot = THREAD) { + const reads: string[] = []; + const gotos: string[] = []; + let current = ""; + const page: PageLike & { reads: string[]; gotos: string[]; shots: number } = { + reads, + gotos, + 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(THREAD_SNAPSHOT_MARKER)) { + reads.push("thread"); + return thread; + } + if (script.includes(CONTEXT_SCRIPT_MARKER)) { + reads.push(`context ${/all\[(\d+)\]/.exec(script)?.[1] ?? "none"}`); + return answer; + } + if (script.includes(AVATARS_SCRIPT_MARKER)) return []; + if (script.includes(VIEW_SCRIPT_MARKER)) return null; + if (script.includes("imgs.length")) return 0; + return snap(current); + }, + screenshot: async () => { + page.shots++; + return PNG; + }, + }; + return page; +} + +test("read: the parent is the archive's in-reply-to id when it says, else the article above; an id not on the page is no parent", async () => { + const page = contextPage({ quoted: null, parent: KIRSCHE }); + const told = await readXPostContext(page, { replyTo: { id: KIRSCHE.id }, now: () => new Date("2026-11-02T00:00:00Z") }); + assert.equal(told?.parent?.from, "reply-to"); + assert.deepEqual(page.reads, ["thread", "context 0"]); + // The archive says nothing (the operator's case): the article above. + assert.equal((await readXPostContext(page, { replyTo: null }))?.parent?.from, "above"); + // An id not on the page: the article above is not taken for it. + page.reads.length = 0; + const wrong = await readXPostContext(page, { replyTo: { id: "1" } }); + assert.equal(wrong?.parent, undefined); + assert.deepEqual(page.reads, ["thread", "context none"]); +}); + +const deps = (page: PageLike, pauses: number[] = []): XCaptureDeps => ({ + openPage: async () => ({ page, close: async () => {} }), + downloadMedia: async () => ({ ok: true, files: [] }), + pauseMs: () => 5000, + pause: async (ms) => void pauses.push(ms), + now: () => new Date("2026-11-02T20:00:00.000Z"), +}); + +const input = async (over: Partial<PostCaptureInput> = {}): Promise<PostCaptureInput> => ({ + ids: ["1983000000000000002"], + handle: "ObviousRises", + outDir: path.join(await mkdtemp(path.join(os.tmpdir(), "xcontext-")), "posts-media"), + signal: new AbortController().signal, + media: false, + articles: false, + avatars: false, + ...over, +}); + +test("run: a normal capture writes the context it read into capture.json, from the page it shot — one load", async () => { + const page = contextPage({ quoted: QUOTED, parent: KIRSCHE }); + const inp = await input(); + const res = await captureXPosts(inp, deps(page)); + assert.equal(res.outcomes[0]?.state, "captured"); + assert.equal(page.gotos.length, 1); + assert.equal(page.shots, 1); + const rec = await readPostCapture(path.join(inp.outDir, "1983000000000000002")); + assert.equal(rec?.context?.readAt, "2026-11-02T20:00:00.000Z"); + assert.equal(rec?.context?.parent?.handle, "Kirsche"); + assert.equal(rec?.context?.quoted?.text, "The receipt itself."); + assert.deepEqual(res.context, { read: 1, quoted: 1, parents: 1, skipped: 0, pages: 0, failed: [] }); + + // context: false reads none, and keeps the one on disk. + const again = contextPage({ quoted: null, parent: null }); + const res2 = await captureXPosts({ ...inp, force: true, context: false }, deps(again)); + assert.equal(res2.context, undefined); + assert.ok(!again.reads.includes("thread")); + assert.equal((await readPostCapture(path.join(inp.outDir, "1983000000000000002")))?.context?.parent?.handle, "Kirsche"); +}); + +test("contextOnly: one page per post, paced, no shot, the context merged into the record — or a record of its own; read ones and deleted ones not loaded", async () => { + const page = contextPage({ quoted: QUOTED, parent: KIRSCHE }); + const inp = await input({ ids: ["11", "22", "33", "44"], contextOnly: true, shots: false }); + // 22 was shot before; 33's context is already read; 44 was found deleted. + const shot = { name: "shot.png", bytes: 6, sha256: "ab" }; + await writePostCapture(path.join(inp.outDir, "22"), { + version: 1, id: "22", url: "https://x.com/i/status/22", capturedAt: "2026-10-01T00:00:00.000Z", state: "captured", + shot, mediaState: "ok", media: [shot], + }); + await writePostCapture(path.join(inp.outDir, "33"), { + version: 1, id: "33", url: "https://x.com/i/status/33", capturedAt: "x", state: "captured", mediaState: "none", media: [], + context: { readAt: "2026-10-30T00:00:00.000Z" }, + }); + await writePostCapture(path.join(inp.outDir, "44"), { + version: 1, id: "44", url: "https://x.com/i/status/44", capturedAt: "x", state: "deleted", mediaState: "skipped", media: [], + }); + const pauses: number[] = []; + const res = await captureXPosts(inp, deps(page, pauses)); + assert.deepEqual(res.outcomes, []); + assert.deepEqual(page.gotos, ["https://x.com/i/status/11", "https://x.com/i/status/22"]); + assert.deepEqual(pauses, [5000], "paced before every page after the first"); + assert.equal(page.shots, 0); + assert.deepEqual(res.context, { read: 2, quoted: 2, parents: 2, skipped: 2, pages: 2, failed: [] }); + + const fresh = (await readPostCapture(path.join(inp.outDir, "11")))!; + assert.equal(fresh.state, "captured"); + assert.equal(fresh.shot, undefined); + assert.equal(fresh.mediaState, "skipped", "the media is still owed"); + assert.equal(fresh.context?.parent?.id, KIRSCHE.id); + assert.deepEqual(await readdir(path.join(inp.outDir, "11")), ["capture.json"]); + const merged = (await readPostCapture(path.join(inp.outDir, "22")))!; + assert.deepEqual(merged.shot, shot); + assert.equal(merged.capturedAt, "2026-10-01T00:00:00.000Z"); + assert.equal(merged.context?.quoted?.handle, "quoted_person"); + assert.equal((await readPostCapture(path.join(inp.outDir, "33")))?.context?.readAt, "2026-10-30T00:00:00.000Z"); + + // force reads again. + const page2 = contextPage({ quoted: null, parent: null }); + await captureXPosts({ ...inp, ids: ["33"], force: true }, deps(page2)); + assert.deepEqual((await readPostCapture(path.join(inp.outDir, "33")))?.context, { readAt: "2026-11-02T20:00:00.000Z" }); +}); + +test("contextOnly: a login wall stops the run with needsCookies, the rest left; a page that is not the post writes nothing", async () => { + let n = 0; + const page = contextPage({ quoted: null, parent: null }); + const inner = page.evaluate; + page.evaluate = async (s: string) => { + if (!s.includes(CONTEXT_SCRIPT_MARKER) && !s.includes(THREAD_SNAPSHOT_MARKER) && !s.includes("imgs.length")) { + n++; + if (n === 1) return { path: "/i/status/11", text: "This post was deleted", article: null }; + return { path: "/i/flow/login", text: "", article: null }; + } + return inner(s); + }; + const inp = await input({ ids: ["11", "22", "33"], contextOnly: true }); + const res = await captureXPosts(inp, deps(page)); + assert.equal(res.needsCookies, true); + assert.match(res.stoppedEarly ?? "", /Stopped at 22/); + assert.deepEqual(page.gotos, ["https://x.com/i/status/11", "https://x.com/i/status/22"]); + assert.deepEqual(await readdir(inp.outDir).catch(() => []), []); + assert.equal(res.context?.failed.length, 2); +}); diff --git a/common/social/xPostContext.ts b/common/social/xPostContext.ts @@ -0,0 +1,254 @@ +// Reading an X post's CONTEXT off the post page capture-posts has ALREADY +// loaded: the post it QUOTES (the card inside its own article) and the post it +// ANSWERS (the article above it), into capture.json's `context` +// (postCapture.ts has the record's shape). +// +// Why: the archive often names neither. A timeline read keeps no quoted post +// unless gallery-dl is asked to (xGalleryDlFetcher.ts now asks), and a reply's +// parent is another account's post, never archived with the account's own -- +// so a post video drew "you called me a Leftist…" with nothing it answered. +// The page shows both, so the capture that loads it reads them. +// +// NO EXTRA PAGE LOAD. Two evaluates over the page as it stands, before any +// shot (the thread shot's blur is a CSS filter; the read sees X's drawing): +// 1. the thread snapshot (xThreadShot.ts) and its pick of the IMMEDIATE +// parent -- the article whose status link is the archive's in-reply-to +// id, else (the archive not saying) the article directly above the post; +// an archive id not on the page is no parent at all. Read whether or not +// the archive calls the post a reply: X draws only a status's ancestors +// above it, and the archive is often what is wrong; +// 2. the context read: that parent article's author, check, date, words and +// media, and the post's own quote card (a `div[role="link"]` inside its +// article holding a User-Name) -- the same fields, and its status id when +// a link inside the card names one (a quote card often has none: the +// archive's quoted id fills it, when its author agrees). +// +// The words are kept whole; the people are not judged here. Whose name a card +// may show is the card's rule (umtool post-item.mjs authorRedaction), which +// blurs every author but the subject unless gold- or grey-checked -- the +// badge recorded here is what it decides by. capture.json is editor-only. +// +// 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.ts); the first real run is the check. + +import type { PageLike } from "./playwrightRuntime"; +import type { PostContextPost, PostContextRecord } from "./postCapture"; +import { BADGE_OF_JS, pickThreadParent, threadSnapshotScript, type ThreadSnapshot } from "./xThreadShot"; + +export const CONTEXT_SCRIPT_MARKER = "__archilyzerContext"; + +// The longest text kept of one context post (a long post's whole body is a +// note-tweet's 25,000; a card never draws more than a few lines of context). +export const CONTEXT_TEXT_MAX = 10_000; +const MEDIA_MAX = 4; + +// The in-page read: the parent article at `parentIndex` (among +// `article[data-testid="tweet"]`, the thread snapshot's order) and the quote +// card inside the marked own article. Each as { id, handle, author, verified, +// badge, date, text, media }; null where there is none. Null altogether when +// the own article is not marked. +export const contextScript = (parentIndex: number | null) => `(() => { + const ${CONTEXT_SCRIPT_MARKER} = true; + const badgeOf = ${BADGE_OF_JS}; + const all = Array.from(document.querySelectorAll('article[data-testid="tweet"]')); + const own = document.querySelector("[data-archilyzer-capture]"); + if (!own) return null; + const HANDLE = /^[A-Za-z0-9_]{1,30}$/; + // A quote card: a div link inside an article, holding a User-Name. + const inCard = (el, root) => { const q = el.closest('div[role="link"]'); return !!q && root.contains(q) && q !== root; }; + const cardOf = (a) => Array.from(a.querySelectorAll('div[role="link"]')).find((q) => q.querySelector('[data-testid="User-Name"]')) || null; + const read = (root, isCard) => { + // An article's own parts, never its quote card's; a card's, all of them. + const pick = (sel) => Array.from(root.querySelectorAll(sel)).filter((el) => isCard || !inCard(el, root)); + const un = pick('[data-testid="User-Name"]')[0] || null; + let handle = null, id = null; + const links = pick('a[href*="/status/"]'); + const timed = links.filter((l) => l.querySelector("time")); + for (const l of [...timed, ...(isCard ? links : [])]) { + const m = /^(?:https:\\/\\/(?:x|twitter)\\.com)?\\/([A-Za-z0-9_]{1,30})\\/status\\/(\\d+)/.exec(l.getAttribute("href") || ""); + if (m) { handle = m[1]; id = m[2]; break; } + } + if (!handle) { + const c = pick('[data-testid^="UserAvatar-Container-"]')[0]; + const t = c ? (c.getAttribute("data-testid") || "").replace(/^UserAvatar-Container-/, "") : ""; + if (HANDLE.test(t)) handle = t; + } + const lines = un ? (un.innerText || "").split("\\n").map((s) => s.trim()).filter((s) => s && s !== "·") : []; + if (!handle) { + const at = lines.map((s) => /(?:^|\\s)@([A-Za-z0-9_]{1,30})\\b/.exec(s)).find(Boolean); + if (at) handle = at[1]; + } + let author = null; + if (un && handle) { + for (const l of un.querySelectorAll("a[href]")) { + const h = (l.getAttribute("href") || "").split(/[?#]/)[0].toLowerCase(); + const t = (l.innerText || "").trim(); + if (h === "/" + handle.toLowerCase() && t && !t.startsWith("@")) { author = t; break; } + } + } + if (!author && lines[0] && !lines[0].startsWith("@")) author = lines[0].split(/\\s+@[A-Za-z0-9_]/)[0].trim() || null; + const icon = un && un.querySelector('[data-testid="icon-verified"]'); + const time = (timed[0] && timed[0].querySelector("time[datetime]")) || pick("time[datetime]")[0] || null; + const words = pick('[data-testid="tweetText"]')[0]; + const media = []; + for (const img of pick('[data-testid="tweetPhoto"] img[src]')) media.push({ kind: "image", url: img.src }); + for (const v of pick("video")) { const u = v.poster || v.currentSrc || v.src; if (u) media.push({ kind: "video", url: new URL(u, location.href).href }); } + return { + id, handle, author, + verified: !!icon, badge: icon ? badgeOf(icon) : null, + date: time ? time.getAttribute("datetime") : null, + text: words ? (words.innerText || "").trim() : "", + media, + }; + }; + const card = cardOf(own); + const parent = ${parentIndex === null ? "null" : `all[${Math.floor(parentIndex)}] || null`}; + return { quoted: card ? read(card, true) : null, parent: parent && parent !== own ? read(parent, false) : null }; +})()`; + +const HANDLE_RE = /^[A-Za-z0-9_]{1,30}$/; +const ID_RE = /^\d{1,25}$/; +const BADGES = new Set(["blue", "gold", "grey", "other"]); + +function statusUrl(id: string | undefined, handle: string | undefined): string | undefined { + if (!id) return undefined; + return handle ? `https://x.com/${handle}/status/${id}` : `https://x.com/i/status/${id}`; +} + +// One post of what the read returned, kept to the shape (null: not a post — +// no author and no words is nothing to draw). +export function parseContextPost(raw: unknown): PostContextPost | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const r = raw as Record<string, unknown>; + const s = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim() : undefined); + const id = s(r.id) && ID_RE.test(s(r.id)!) ? s(r.id) : undefined; + const handle = s(r.handle)?.replace(/^@/, ""); + const okHandle = handle && HANDLE_RE.test(handle) ? handle : undefined; + const text = typeof r.text === "string" ? r.text.trim().slice(0, CONTEXT_TEXT_MAX) : ""; + if (!okHandle && !text) return null; + const author = s(r.author)?.slice(0, 200); + const dateRaw = s(r.date); + const date = dateRaw && Number.isFinite(Date.parse(dateRaw)) ? new Date(Date.parse(dateRaw)).toISOString() : undefined; + const badge = typeof r.badge === "string" && BADGES.has(r.badge) ? (r.badge as PostContextPost["badge"]) : undefined; + const media: PostContextPost["media"] = []; + const seen = new Set<string>(); + for (const m of Array.isArray(r.media) ? r.media : []) { + if (!m || typeof m !== "object") continue; + const { kind, url } = m as Record<string, unknown>; + if ((kind !== "image" && kind !== "video") || typeof url !== "string" || !/^https?:\/\//.test(url) || seen.has(url)) continue; + seen.add(url); + media.push({ kind, url }); + if (media.length >= MEDIA_MAX) break; + } + const url = statusUrl(id, okHandle); + return { + ...(id ? { id } : {}), + ...(url ? { url } : {}), + ...(okHandle ? { handle: okHandle } : {}), + ...(author ? { author } : {}), + ...(r.verified === true ? { verified: true } : {}), + ...(badge ? { badge } : {}), + ...(date ? { date } : {}), + text, + media, + }; +} + +export type XContextReadOptions = { + // What the archive says the post answers, when it says (the parent is the + // article with this status id; not on the page means no parent). + replyTo?: { id?: string; author?: string } | null; + // What the archive says it quotes: its id fills a quote card that names + // none, when the authors agree. + quoted?: { id?: string; author?: string } | null; + now?: () => Date; +}; + +const sameHandle = (a?: string, b?: string) => + !!a && !!b && a.replace(/^@/, "").toLowerCase() === b.replace(/^@/, "").toLowerCase(); + +// The whole record from the read's answer and the parent pick. Pure. Null +// when the answer is not the read's shape (the page could not be read: a +// later run reads it again). +export function contextRecordFrom( + raw: unknown, + pick: { from: "reply-to" | "above" } | null, + o: Pick<XContextReadOptions, "quoted"> & { readAt: string }, +): PostContextRecord | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw) || !("quoted" in raw) || !("parent" in raw)) return null; + const r = raw as { quoted: unknown; parent: unknown }; + const record: PostContextRecord = { readAt: o.readAt }; + const quoted = parseContextPost(r.quoted); + if (quoted) { + const arch = o.quoted; + if (!quoted.id && arch?.id && ID_RE.test(arch.id) && (!arch.author || !quoted.handle || sameHandle(arch.author, quoted.handle))) { + quoted.id = arch.id; + quoted.url = statusUrl(arch.id, quoted.handle ?? arch.author?.replace(/^@/, "")); + } + record.quoted = quoted; + } + const parent = pick ? parseContextPost(r.parent) : null; + if (parent && pick) record.parent = { ...parent, from: pick.from }; + return record; +} + +// The read, in the page shot — never throws: an unreadable page is null. +export async function readXPostContext(page: PageLike, o: XContextReadOptions = {}): Promise<PostContextRecord | null> { + try { + const snap = (await page.evaluate(threadSnapshotScript()).catch(() => null)) as ThreadSnapshot | null; + let parentIndex: number | null = null; + let pick: { from: "reply-to" | "above" } | null = null; + if (snap && Array.isArray(snap.articles) && typeof snap.own === "number") { + const got = pickThreadParent(snap, o.replyTo ?? null); + if ("index" in got) { + parentIndex = got.index; + pick = { from: got.from }; + } + } + const raw = await page.evaluate(contextScript(parentIndex)); + return contextRecordFrom(raw, pick, { quoted: o.quoted, readAt: (o.now ?? (() => new Date()))().toISOString() }); + } catch { + return null; + } +} + +export type XContextRunSummary = { + // Posts whose context was read and recorded this run. + read: number; + // Of them, how many showed a quoted post / a parent. + quoted: number; + parents: number; + // Posts not loaded for it: a context already recorded, or a deleted post. + skipped: number; + // Post pages loaded for the context alone (contextOnly). + pages: number; + failed: { id: string; error: string }[]; +}; + +export function emptyContextSummary(): XContextRunSummary { + return { read: 0, quoted: 0, parents: 0, skipped: 0, pages: 0, failed: [] }; +} + +export function noteContext(s: XContextRunSummary, c: PostContextRecord): void { + s.read++; + if (c.quoted) s.quoted++; + if (c.parent) s.parents++; +} + +export function describeContextSummary(s: XContextRunSummary): string { + return ( + `Context: ${s.read} read (${s.quoted} quoting a post, ${s.parents} answering one)` + + (s.skipped ? `, ${s.skipped} already read or deleted` : "") + + (s.failed.length ? `, ${s.failed.length} failed (${s.failed.map((f) => f.id).join(", ")})` : "") + + (s.pages ? `; ${s.pages} page(s) loaded for it` : "") + + "." + ); +} + +// A one-line account of one post's context, for the run's log. +export function describeContext(c: PostContextRecord): string { + const who = (p: PostContextPost) => (p.handle ? `@${p.handle}` : p.author ?? "?") + (p.id ? ` ${p.id}` : ""); + const parts = [c.parent ? `answers ${who(c.parent)}` : "", c.quoted ? `quotes ${who(c.quoted)}` : ""].filter(Boolean); + return parts.length ? `context: ${parts.join(", ")}` : "context: no quote, no parent"; +} diff --git a/common/social/xThreadShot.ts b/common/social/xThreadShot.ts @@ -81,8 +81,21 @@ export type ThreadSnapshot = { articles: ThreadArticle[]; }; +// Which check an `icon-verified` element is, in the page: gold is drawn with a +// gradient; blue and grey are one fill, X's own colours. Shared by the in-page +// reads that name a badge (the thread snapshot, the post context). +export const BADGE_OF_JS = `(icon) => { + const paint = [getComputedStyle(icon).color, icon.getAttribute("fill") || "", + ...Array.from(icon.querySelectorAll("[fill]")).map((e) => e.getAttribute("fill") || "")].join(" "); + return /linearGradient/i.test(icon.outerHTML) ? "gold" + : /29,\\s*155,\\s*240|#1d9bf0/i.test(paint) ? "blue" + : /130,\\s*154,\\s*171|#829aab/i.test(paint) ? "grey" + : "other"; +}`; + export const threadSnapshotScript = () => `(() => { const ${THREAD_SNAPSHOT_MARKER} = true; + const badgeOf = ${BADGE_OF_JS}; const all = Array.from(document.querySelectorAll('article[data-testid="tweet"]')); const own = all.findIndex((a) => a.hasAttribute("data-archilyzer-capture")); const articles = all.map((a) => { @@ -95,16 +108,7 @@ export const threadSnapshotScript = () => `(() => { const name = un ? ((un.innerText || "").split("\\n")[0] || "").trim() : ""; const icon = un && un.querySelector('[data-testid="icon-verified"]'); const verified = !!icon; - let badge; - if (icon) { - // Gold is drawn with a gradient; blue and grey are one fill, X's own colours. - const paint = [getComputedStyle(icon).color, icon.getAttribute("fill") || "", - ...Array.from(icon.querySelectorAll("[fill]")).map((e) => e.getAttribute("fill") || "")].join(" "); - badge = /linearGradient/i.test(icon.outerHTML) ? "gold" - : /29,\\s*155,\\s*240|#1d9bf0/i.test(paint) ? "blue" - : /130,\\s*154,\\s*171|#829aab/i.test(paint) ? "grey" - : "other"; - } + const badge = icon ? badgeOf(icon) : undefined; const r = a.getBoundingClientRect(); return { id, handle, name: name || undefined, verified, badge, top: r.top + window.scrollY, bottom: r.bottom + window.scrollY }; }); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,10 @@ # Changelog ## [Unreleased] +- **X post captures keep the post's context: what it quotes and what it answers.** A post video drew a reply ("you called me a Leftist…") with nothing it answered, because the archive row named no parent, no quote and no links. `capture-posts` on an X channel now reads, off the page it already loads, the post it answers (the archive's in-reply-to id, else the post directly above it) and the post it quotes — author, display name, check, date, words and media links — into the post's `capture.json` as `context`, with no extra page load (`"context": false` turns it off). `"contextOnly": true` loads one page per post for that alone (and the avatars it shows) and writes nothing else: `pnpm ops capture-posts --json '{"slug":"<x-channel>","ids":["<post id>", …],"contextOnly":true}' --wait`. Not verified against live X yet; the first run is the check. Needs a restart of the editor. +- **The X fetcher keeps quoted posts.** A timeline read never recorded what a post quotes (gallery-dl drops the quoted tweet unless asked). Every read now asks for it, and a quote becomes the quoting post's `quoted` — never archived as one of the account's own posts; an account quoting its own older post still archives that post when the walk reaches it. Posts already archived keep what they have (a re-fetch does not rewrite them; their context comes from `contextOnly`). Needs a restart of the editor. +- **`umtool posts context <project>`** fills every post item's quoted post and parent from its capture's `context` where the archive row lacks them, in one write (one undo point), and names the posts with no context yet with the capture call that reads it; `umtool posts reel` and `timeline insert post:` fill them when the entry is made. Needs a restart of umtool. +- **X post captures keep the authors' avatars.** A post card showed an initial letter because the posts archive keeps no profile pictures. `capture-posts` on an X channel now reads the post author's avatar off the page it already loads for the shot (with `"thread": true`, the replied-to and quoted authors' too) and saves it at 400×400, fetched through the same browser context with no extra page load, into `posts-media/_avatars/<handle>.<ext>` and `avatars.json` — once per author, an author already stored skipped unless `"force": true`; `"avatars": false` turns it off. `"avatarsOnly": true` loads one post page per distinct archived author for the avatars alone and writes nothing else (no shot, media, record or availability): `pnpm ops capture-posts --json '{"slug":"<x-channel>","ids":["<one post id>"],"avatarsOnly":true}' --wait`. X's default picture is not stored. Needs a restart of the editor. - **A research case can be verified, its leads decided and its evidence captured, all in umtool.** The case pipeline page gains **7 Verify**, **8 Leads** and **10 Evidence**. **Verify** shows each finding's moment in every caption track side by side — the original audio's captions beside the uploaded `en` ones, the quote's words lit where they land and "holds the quote" or "4 of 5 words" on each — and an **Audio check** that has the editor transcribe the window on a local worker (its held media, or a clip fetched through it; **Run even while transcription is paused** for a pause-all) and diffs what was heard with the quote ("Heard 9 of 9 words"). A finding is marked Verified, Corrected, Disputed, Unverified or Quarantined (one first seen on a forum says so); **Correct by hand** keeps the reader's words ("The reader wrote: …"). **Leads** lists the accounts and pages a forum or posts channel links most, counted by post, with the posts around each on demand; **Never archive** makes the lead's name one of the case's private names — stored as its hash, never as text, and withheld from then on — and **Archive** creates its channel through the editor on no site and starts its first fetch (**Older walk** after). **Evidence** takes Wayback captures of a list of pages at chosen dates (a page the Wayback Machine will not show is the row "excluded from the Wayback Machine (cause unknown)") and a forum post's attachments and screenshot, shown everywhere as "forum attachment, post #N, unverified", attached to the findings they back and listed in the exported report's Evidence section. Any quote, note or role typed by hand that holds one of the case's private names is refused by the privacy gate, with the row and a count, never the name. Needs a restart of umtool. - **Newgrounds pages are read whole.** A Wayback capture of a 2014 Newgrounds user page used to come out as one small block of it: the page keeps its profile, stats, links and news in many small boxes the generic extractor dropped. A user page (`<user>.newgrounds.com/`) is now read box by box — "Profile", "Location: …", "Joined on: …", its links — and an art page or a movie page is one record per work (its title, author, comments, image or file, tags, credits and date) that later captures update. A channel imported before this is put right by **Re-extract** (`reextract-pages`), from the captures it already keeps; nothing is fetched. Needs a restart of the editor. - **A Wayback scan goes on past a page the archive excludes.** A target the Wayback Machine answers 403 for stopped the whole `wayback-scan` as an error. Now that target is marked "excluded from the Wayback Machine (cause unknown)" on the Captures tab (and `refusal: "excluded"` in the scan's result), it is done for this pass, and the next target is scanned. A new pass asks again. Needs a restart of the editor. diff --git a/editor/app/api/ops/capture-posts/route.test.ts b/editor/app/api/ops/capture-posts/route.test.ts @@ -167,3 +167,51 @@ test("capture-posts refuses what it cannot capture, and an id not in the archive assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); }); + +test("avatars and avatarsOnly: booleans; avatarsOnly is a run of its own, X's only — refused before any job", async () => { + for (const key of ["avatars", "avatarsOnly"]) { + const bad = await post({ slug: SLUG, ids: ["111"], [key]: "yes" }); + assert.equal(bad.status, 400, key); + assert.match(bad.error, new RegExp(`"${key}" must be a boolean`)); + } + // Both halves off is no refusal for an avatars-only run: past it, to the + // next one (an id not archived). + const stray = await post({ slug: SLUG, ids: ["999"], shots: false, media: false, avatarsOnly: true }); + assert.equal(stray.status, 400); + assert.equal(stray.error, "1 id(s) not in demo-x's posts archive: 999"); + // Another platform keeps none. + await channel("example-bsky-avatars", { + handling: "transcribe", + sourceKind: "social", + platform: "bluesky", + postFetcher: "bluesky-atproto", + socialHandle: "example.bsky.social", + name: "Example (Bluesky)", + url: "https://bsky.app/profile/example.bsky.social", + }); + const bsky = await post({ slug: "example-bsky-avatars", ids: ["1"], avatarsOnly: true }); + assert.equal(bsky.status, 400); + assert.match(bsky.error, /^Avatars are X's only; .* keeps none\.$/); + assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); +}); + +test("context and contextOnly: booleans; contextOnly is a run of its own, X's only, not with avatarsOnly — refused before any job", async () => { + for (const key of ["context", "contextOnly"]) { + const bad = await post({ slug: SLUG, ids: ["111"], [key]: "yes" }); + assert.equal(bad.status, 400, key); + assert.match(bad.error, new RegExp(`"${key}" must be a boolean`)); + } + // Both halves off is no refusal for a context-only run: past it, to the + // next one (an id not archived). + const stray = await post({ slug: SLUG, ids: ["999"], shots: false, media: false, contextOnly: true }); + assert.equal(stray.status, 400); + assert.equal(stray.error, "1 id(s) not in demo-x's posts archive: 999"); + const both = await post({ slug: SLUG, ids: ["111"], contextOnly: true, avatarsOnly: true }); + assert.equal(both.status, 400); + assert.match(both.error, /^"contextOnly" and "avatarsOnly" are two runs/); + // Another platform reads none (the channel the avatars test made). + const bsky = await post({ slug: "example-bsky-avatars", ids: ["1"], contextOnly: true }); + assert.equal(bsky.status, 400); + assert.match(bsky.error, /^Post context is X's only; .* reads none\.$/); + assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); +}); diff --git a/editor/app/api/ops/capture-posts/route.ts b/editor/app/api/ops/capture-posts/route.ts @@ -10,7 +10,7 @@ import { export const dynamic = "force-dynamic"; -// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, queueKey? } -> { ok: true, jobId } +// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, avatars?, avatarsOnly?, context?, contextOnly?, queueKey? } -> { ok: true, jobId } // // Capture specific archived posts of a social channel: a screenshot of each // (`shots`, default true) and its attached media (`media`, default true), into @@ -25,14 +25,33 @@ export const dynamic = "force-dynamic"; // skipped unless `force`. The job runs on the platform's queue, as a post // fetch does. // +// X keeps each post author's AVATAR, read off the page the shot loads (with +// `thread`, the replied-to and quoted authors' too), in +// `posts-media/_avatars/<handle>.<ext>` + `avatars.json` -- `avatars: false` +// turns that off. `avatarsOnly: true` loads ONE post page per distinct +// archived author for the avatars alone: no shot, media, article or thread +// shot, no capture record, no availability; an author already stored is +// skipped unless `force`. One author's avatar is one page load: +// {"slug":"ObviousRises-x","ids":["<one of his post ids>"],"avatarsOnly":true} +// +// X also reads each post's CONTEXT off the page the shot loads -- the post it +// quotes and the post it answers (the archive often names neither) -- into +// its capture.json's `context`; `context: false` turns that off. +// `contextOnly: true` loads ONE page per post for that alone (and the avatars +// it shows): the context written into the post's capture.json, nothing shot, +// no media, article or thread shot, no availability; a post whose context is +// already read is skipped unless `force`: +// {"slug":"ObviousRises-x","ids":["<post id>", …],"contextOnly":true} +// // Every refusal is the action's own sentence: both halves off (an // articles-only run names `articles: true`), a channel that // is not a social one, a fetcher that cannot capture, an id not in the -// channel's posts archive. +// channel's posts archive, `avatarsOnly` or `contextOnly` on a channel that +// is not X, both of them at once. export async function POST(request: Request) { return ops( request, - ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "queueKey"], + ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "avatars", "avatarsOnly", "context", "contextOnly", "queueKey"], async (body) => { const slug = reqSlug(body, "slug"); return jobResponse( @@ -44,7 +63,14 @@ export async function POST(request: Request) { optBool(body, "media"), optBool(body, "force"), optBool(body, "articles"), - { thread: optBool(body, "thread"), threadRedact: body.threadRedact as boolean | Record<string, boolean> | undefined }, + { + thread: optBool(body, "thread"), + threadRedact: body.threadRedact as boolean | Record<string, boolean> | undefined, + avatars: optBool(body, "avatars"), + avatarsOnly: optBool(body, "avatarsOnly"), + context: optBool(body, "context"), + contextOnly: optBool(body, "contextOnly"), + }, ), ); }, diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -43,7 +43,9 @@ import { type CheckPostAvailabilityMode, } from "yt-dlp-transcript-common/controller/checkPostAvailability"; import { + avatarsOnlyProblem, capturePosts, + contextOnlyProblem, capturePostsProblem, NOTHING_TO_CAPTURE, nothingToCapture, @@ -302,7 +304,12 @@ export async function fetchPostsAction( // links to an X Article gets the article too unless `articles` is false. An X // reply gets its thread shot (the post it answers over it) with `thread` // (default: the channel's `postCaptureThread`), its parent's author blurred -// by the rule unless `threadRedact` says otherwise. +// by the rule unless `threadRedact` says otherwise. X keeps the authors' +// avatars from the pages it loads (`avatars: false` turns that off); +// `avatarsOnly` loads one page per archived author for them alone (X only, +// refused here elsewhere). X reads each post's context (the quoted post, the +// parent) off the same pages (`context: false` turns that off); `contextOnly` +// loads one page per post for it alone (X only; not with avatarsOnly). export async function capturePostsAction( slug: string, ids: string[], @@ -311,13 +318,20 @@ export async function capturePostsAction( media?: boolean, force?: boolean, articles?: boolean, - more: { thread?: boolean; threadRedact?: ThreadRedactKnob } = {}, + more: { + thread?: boolean; + threadRedact?: ThreadRedactKnob; + avatars?: boolean; + avatarsOnly?: boolean; + context?: boolean; + contextOnly?: boolean; + } = {}, ): Promise<StreamActionResult> { - const { thread } = more; + const { thread, avatars, avatarsOnly, context, contextOnly } = more; const redact = parseThreadRedact(more.threadRedact); if (!redact.ok) return { ok: false, error: redact.error }; const threadRedact = redact.value; - if (nothingToCapture({ shots, media, articles, thread })) return { ok: false, error: NOTHING_TO_CAPTURE }; + if (nothingToCapture({ shots, media, articles, thread, avatarsOnly, contextOnly })) return { ok: false, error: NOTHING_TO_CAPTURE }; const wanted = [...new Set(ids)]; if (wanted.length === 0) return { ok: false, error: "No post ids to capture." }; const paths = getPaths(); @@ -329,12 +343,17 @@ export async function capturePostsAction( // A Wayback pages channel has no fetcher: its records are rendered from // their captures, on archive.org's queue (release 37 S4). const pages = isWaybackPagesChannel(config); + if (pages && avatarsOnly) return { ok: false, error: avatarsOnlyProblem(undefined, "a Wayback pages channel")! }; + if (pages && contextOnly) return { ok: false, error: contextOnlyProblem(undefined, "a Wayback pages channel", { avatarsOnly })! }; if (!pages) { await registerBuiltinSocialFetchers(); - const problem = capturePostsProblem( - resolveSocialFetcher(config.postFetcher, config.url), - ); + const fetcher = resolveSocialFetcher(config.postFetcher, config.url); + const problem = capturePostsProblem(fetcher); if (problem) return { ok: false, error: problem }; + const nope = avatarsOnly ? avatarsOnlyProblem(fetcher?.platform, fetcher?.label ?? "") : null; + if (nope) return { ok: false, error: nope }; + const noContext = contextOnly ? contextOnlyProblem(fetcher?.platform, fetcher?.label ?? "", { avatarsOnly }) : null; + if (noContext) return { ok: false, error: noContext }; } const stray = strayCaptureIds( wanted, @@ -355,6 +374,10 @@ export async function capturePostsAction( queueKey, ids: wanted, shots, media, force, articles, ...(thread !== undefined ? { thread } : {}), ...(threadRedact !== undefined ? { threadRedact } : {}), + ...(avatars !== undefined ? { avatars } : {}), + ...(avatarsOnly ? { avatarsOnly } : {}), + ...(context !== undefined ? { context } : {}), + ...(contextOnly ? { contextOnly } : {}), }, }, fn: async (onLog, signal, _progress, ctx) => { @@ -369,6 +392,10 @@ export async function capturePostsAction( articles, thread, threadRedact, + avatars, + avatarsOnly, + context, + contextOnly, onLog, signal, drain: ctx.drainSignal, diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -443,6 +443,10 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { thread: bool(p.thread), // A boolean or { id: boolean }; the action refuses any other shape. threadRedact: p.threadRedact as boolean | Record<string, boolean> | undefined, + avatars: bool(p.avatars), + avatarsOnly: bool(p.avatarsOnly), + context: bool(p.context), + contextOnly: bool(p.contextOnly), }, ); }, diff --git a/editor/e2e/capture-posts.spec.ts b/editor/e2e/capture-posts.spec.ts @@ -123,6 +123,27 @@ test("capture-posts on a Bluesky channel: shots cropped to the post, its images, `/profile/${HANDLE}/post/${withImages}`, `/profile/${HANDLE}/post/${textOnly}`, ]); + + // Avatars are X's: a Bluesky capture keeps none, and an avatars-only + // run here is refused by name before any job. + expect(await readdir(media)).not.toContain("_avatars"); + const av = await request.post(`${baseUrl}/api/ops/capture-posts`, { + headers: AUTH, + data: { slug: SLUG, ids, avatarsOnly: true }, + }); + expect(av.status()).toBe(400); + expect(((await av.json()) as { error?: string }).error).toMatch(/^Avatars are X's only; .* keeps none\.$/); + + // So is a post's context (the quoted post, the parent): a Bluesky + // record carries none, and a context-only run is refused by name. + const textRecord = JSON.parse(await readFile(path.join(media, textOnly, "capture.json"), "utf8")) as { context?: unknown }; + expect(textRecord.context).toBeUndefined(); + const ctx = await request.post(`${baseUrl}/api/ops/capture-posts`, { + headers: AUTH, + data: { slug: SLUG, ids, contextOnly: true }, + }); + expect(ctx.status()).toBe(400); + expect(((await ctx.json()) as { error?: string }).error).toMatch(/^Post context is X's only; .* reads none\.$/); } finally { await rm(originFile, { force: true }); await bsky.close(); diff --git a/plans/post-videos.md b/plans/post-videos.md @@ -55,3 +55,12 @@ progress + the archive's channel snapshot), each next action a link to the surfa classification task and its Y/N review (step 2), then the storyline draft (step 3); (c) attachment blur boxes (step 6); (d) "record the whole cut" (step 5's walk opening on the first unrecorded post); (e) the card following the read. Each is a lane of its own, merged in that order. + +## Narration sources (operator, 2 Nov: "pure AI voice, record voice, and run AI on recorded voice (and re-run or re-record)") +A take = a source (TTS, a recording, or another take) + a chain of steps; derived takes never overwrite their source. +The model and UI are in lane/post-narration. Still to build (a follow-up lane): editor ops with local engines, through +`archilyzer tts setup`-style installs and the heavy slot — +- `voice-enhance`: denoise / level / de-reverb of a recording (CPU-light candidates: DeepFilterNet, RNNoise; a bake-off). +- `voice-convert`: keep the operator's performance, swap the timbre for a STOCK synthetic voice (e.g. an Orpheus voice + as the target reference) — never a real person's voice (Drama 3's licence and ours). Candidates to bake off on the + RX 6600 XT (8 GB, Vulkan/ROCm-limited): Seed-VC, OpenVoice v2's tone-colour converter, RVC (needs a target model). diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1535,8 +1535,23 @@ export function usage() { ' shot-thread.png beside shot.png (a post shot before gets only that);', ' the replied-to author\'s avatar, name and handle are blurred unless', ' verified or the reply\'s own. "threadRedact": false turns the blur off,', - ' true blurs any author; {"<id>": false} sets it per post. Paced like a', - ' post fetch, on its queue.', + ' true blurs any author; {"<id>": false} sets it per post. X also keeps', + ' each author\'s avatar, read off the page the shot loads (with "thread",', + ' the replied-to and quoted authors\' too), in', + ' posts-media/_avatars/<handle>.<ext> + avatars.json; an author already', + ' stored is not fetched again unless "force". "avatars": false turns that', + ' off. "avatarsOnly": true (X) loads ONE post page per distinct archived', + ' author for the avatars alone -- no shot, media, article or thread shot,', + ' no capture record, no availability: one author\'s avatar is', + ' {"slug", "ids": ["<one of their post ids>"], "avatarsOnly": true}.', + ' X also reads each post\'s CONTEXT off the same page -- the post it quotes', + ' and the post it answers (its author, check, date, words, media links) --', + ' into its capture.json\'s "context"; "context": false turns that off.', + ' "contextOnly": true (X) loads ONE page per post for that alone (and the', + ' avatars it shows): the context written into capture.json, nothing shot,', + ' no media, article, thread shot or availability; a post whose context is', + ' already read is skipped unless "force". Not with "avatarsOnly".', + ' Paced like a post fetch, on its queue.', "", 'persist-videos saves specific videos, across channels, to the saved-video', ' store: {"items": [{"slug", "id"}, ...]}. "format": "original" |', diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -81,11 +81,12 @@ Inbox cannot disagree about what is wrong with one. | `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) | | `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** | | `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) | -| `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` | +| `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` | | `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words | | `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration`. Refused in the build's words (**exit 1**) | | `posts fit <project> [--all \| <item> …] [--linger <s>] [--dry-run] [--json]` · `posts set-item <project> <item> fit=read[:<linger>]` | narrated posts' video attachments cut to their **best part** for the read (lead + take + tail + linger): a scored scan of the sound (loudness, its peaks), the speech (a transcript) and the scene cuts, the start snapped to a pause or a cut, recorded with why (`narration.window`) -- ONE write; each post's old and new length printed. A video no longer than the read is left as it is | | `posts avatar <project> [<handle> <image-file> \| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]` | the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one | +| `posts context <project> [--dry-run] [--json]` | every **post item's context from its capture** (`postContext.mjs`): the post it quotes and the post it answers, as its page showed them (`capture.json`'s `context`, read by the editor's `capture-posts` -- `"contextOnly": true` reads it alone), filled where the archive row lacks them -- `quoted` where the entry has none (or a named one with no words, the same post), `parents` where it has none (a thread shot stays on the entry; the card draws the parents). What the archive gave is never replaced. ONE write for every entry (`setPostItemsContext`: one undo point, refused whole in the build's words); a re-run with nothing new writes nothing. A post whose capture read no context is listed with the call that reads it (`pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait`). The card's blur of other authors is unchanged ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)) | | `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters | | `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one | | `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -657,6 +657,7 @@ its knobs are one writer, `updatePostItem` (`lib/report/manifest.mjs`), refused |---|---|---|---| | a posts reel: the archive's posts as post items, re-run to add only what is new (one write, one undo point) | — | `umtool posts reel <p> --channel <slug> [--channel …] [--since D] [--until D] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run]` | — | | one post item among clips | — | `umtool timeline <p> insert --after <id\|-> post:<channel>/<postId> [--id ID]` (or `--to-section N`, `--group G`) | `POST /api/report/timeline {op: "insert", …}` with an entry | +| its `quoted` and `parents` the archive row lacks, from the capture's `context` (the post's page, read by `capture-posts`): filled when the entry is made, and into a cut made before (one write, one undo point; the archive's own never replaced) | — | `umtool posts context <p> [--dry-run]` (no context yet: `pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait` first) | — | | move, remove, a section, a group | the Cut tab's row (⠿, ⋯, the section bars), Play's reel strip | `umtool timeline <p> move\|remove\|section-move\|section-add …` | as a clip's | | the card's page, an attachment, the faces | Play the cut, the post bench | — | `GET /api/report/post-item?project&id&w&h[&phase][&take]` · `?project&file=posts-media/…` · `?project&font=regular\|bold` | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -495,7 +495,11 @@ plays skipped — by its id, as a repost's original, or reposted by one — so a adds only what is new, and the rest put in through ONE write (`insertEntries`: one undo point, refused whole in the build's words). A reply's parents come from the archive (the replies channel carries the posts he answered), else from the capture's -`shot-thread.png`, else a "Replying to" line. The attachments are COPIED into the +`shot-thread.png`, else a "Replying to" line. The quoted post and the parent the +archive lacks come from the capture's `context` (the post's page, read by +`capture-posts`; `"contextOnly": true` reads it alone) -- snapshotted when the entry is +made, and filled into a cut made before by `umtool posts context <p>` (one write, one +undo point; what the archive gave is never replaced). The attachments are COPIED into the project's `posts-media/` and measured (ffprobe: pixels, length, sound; X serves a GIF as a silent mp4 from `tweet_video/`). `umtool new <p> --from-posts <slug>` scaffolds a posts reel (the deck on; with no `siteOrigin` each QR opens the post), and `umtool diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -2589,6 +2589,46 @@ export async function fitPostItems(dir, fits, { token = null } = {}) { }); } +/** What a context write may set on a post item (postContext.mjs). */ +export const POST_ITEM_CONTEXT_KEYS = Object.freeze(["quoted", "parents"]); + +/** + * FILL POST ITEMS' CONTEXT (`umtool posts context`, postContext.mjs): `patches` + * is `{ <entry id>: { quoted?, parents? } }` -- the post it quotes and the posts + * it answers, snapshotted from each post's capture; a null clears one. ONE + * structural write for them all (one undo point), refused whole in the + * build's words (validatePostItem). Returns `{ ids }`. + * + * @param {string} dir + * @param {Record<string, Record<string, any>>} patches + * @param {{ token?: string | null }} [opts] + */ +export async function setPostItemsContext(dir, patches, { token = null } = {}) { + if (!isObj(patches) || !Object.keys(patches).length) throw new Error("nothing to set"); + for (const [id, p] of Object.entries(patches)) { + if (!isObj(p)) throw new Error(`${id}: a post item's context is an object`); + for (const k of Object.keys(p)) { + if (!POST_ITEM_CONTEXT_KEYS.includes(k)) throw new Error(`${k} is not a post item's context (${POST_ITEM_CONTEXT_KEYS.join(", ")})`); + } + } + return structural(dir, "post-context", token, (m) => { + const ids = []; + for (const [id, p] of Object.entries(patches)) { + const e = m.timeline[entryIndex(m.timeline, id)]; + if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`); + for (const k of POST_ITEM_CONTEXT_KEYS) { + if (!(k in p)) continue; + if (p[k] === null || p[k] === undefined) delete e[k]; + else e[k] = structuredClone(p[k]); + } + const errors = validatePostItem(e); + if (errors.length) throw new StructureRefused(errors); + ids.push(id); + } + return { ids }; + }); +} + /** The cut's mix knobs a write may set (`render.postNarration`). */ export const POST_NARRATION_RENDER_KNOBS = Object.freeze(Object.keys(POST_NARRATION_DEFAULTS).filter((k) => k !== "attach")); diff --git a/umtool/lib/report/postContext.mjs b/umtool/lib/report/postContext.mjs @@ -0,0 +1,190 @@ +// A POST ITEM's CONTEXT FROM ITS CAPTURE (umtool/docs/report-video.md, "Post +// items"): the post it quotes and the post it answers, as the post's page +// showed them -- `capture.json`'s `context`, read by the editor's +// capture-posts (common/social/xPostContext.ts) -- filled into the entry when +// the archive row lacks them. +// +// The archive often does: an X timeline read kept no quote until the fetcher +// asked for it, and a reply's parent is another account's post, never +// archived with the account's own. So a post item that the archive gives no +// `quoted` (or one with no words) and no `parents` takes the capture's: +// +// quoted <- context.quoted { id?, author?, handle?, badge?, date?, text, url? } +// parents <- [context.parent] (the post it answers; the capture reads one) +// +// SNAPSHOTTED like the rest of the entry: written into it when it is made +// (postReel.mjs postEntryFrom -- `posts reel`, `timeline insert post:`) or +// refreshed (`umtool posts context <project>`, every post item at once, one +// write). What the archive gives is never replaced: the capture only fills +// what is missing, and a ref the archive names is only completed by a context +// post that is the same post (its id, else its author). The card's own rule +// (post-item.mjs authorRedaction) decides whose name and face it shows -- a +// parent or a quoted author who is not the subject is blurred unless gold- or +// grey-checked; the badge the capture read is what it decides by. +// +// Plain ESM: the CLI runs it under bare node. +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { channelsDirFor, readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, setPostItemsContext } from "./manifest.mjs"; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); +const HANDLE_RE = /^[A-Za-z0-9_]{1,30}$/; +const ID_RE = /^[A-Za-z0-9_-]{1,64}$/; +const BADGES = new Set(["blue", "gold", "grey", "other"]); +/** The longest context text a ref takes (post-item.mjs refuses past 25,000). */ +const TEXT_MAX = 10000; +const POST_KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; + +/** + * A post item ref from a capture's context post, kept to the shape the + * validator takes; null for nothing usable (no author and no words). + */ +export function contextRefOf(p) { + if (!isObj(p)) return null; + const handle = str(p.handle).replace(/^@/, ""); + const text = str(p.text).slice(0, TEXT_MAX); + const okHandle = HANDLE_RE.test(handle) ? handle : ""; + if (!okHandle && !text.trim()) return null; + const id = ID_RE.test(str(p.id)) ? str(p.id) : ""; + const url = /^https?:\/\//.test(str(p.url)) ? p.url : ""; + const date = str(p.date) && Number.isFinite(Date.parse(p.date)) ? p.date : ""; + return { + ...(id ? { id } : {}), + ...(str(p.author) ? { author: str(p.author).slice(0, 200) } : {}), + ...(okHandle ? { handle: okHandle } : {}), + ...(BADGES.has(p.badge) ? { badge: p.badge } : {}), + ...(date ? { date } : {}), + text, + ...(url ? { url } : {}), + }; +} + +const sameHandle = (a, b) => !!a && !!b && String(a).replace(/^@/, "").toLowerCase() === String(b).replace(/^@/, "").toLowerCase(); + +/** Whether `ref` (the archive's) and `ctx` (the capture's) are the same post: their ids, else their authors. */ +export function sameRef(ref, ctx) { + if (str(ref?.id) && str(ctx?.id)) return String(ref.id) === String(ctx.id); + if (str(ref?.handle) && str(ctx?.handle)) return sameHandle(ref.handle, ctx.handle); + return !str(ref?.id) && !str(ref?.handle); +} + +/** `ref` completed from `ctx`: every field the archive gave kept, the rest the capture's. */ +function completed(ref, ctx) { + const out = { ...ctx }; + for (const [k, v] of Object.entries(ref)) if (v !== undefined && v !== null && v !== "") out[k] = v; + return out; +} + +/** + * FILL `entry` (a post item, mutated) from its capture's `context`: the + * quoted post where the entry has none (or one with no words, the same post), + * the post it answers where it has no parents. Returns what it filled: + * a subset of ["quoted", "parents"]. + */ +export function applyCaptureContext(entry, context) { + const filled = []; + if (!isObj(entry) || !isObj(context)) return filled; + const q = contextRefOf(context.quoted); + if (q) { + if (!isObj(entry.quoted)) { + entry.quoted = q; + filled.push("quoted"); + } else if (!str(entry.quoted.text).trim() && sameRef(entry.quoted, q)) { + entry.quoted = completed(entry.quoted, q); + filled.push("quoted"); + } + } + const p = contextRefOf(context.parent); + if (p) { + const parents = Array.isArray(entry.parents) ? entry.parents.filter(isObj) : []; + if (!parents.length) { + entry.parents = [p]; + filled.push("parents"); + } else if (!str(parents[0].text).trim() && sameRef(parents[0], p)) { + entry.parents = [completed(parents[0], p), ...parents.slice(1)]; + filled.push("parents"); + } + } + return filled; +} + +/** + * The `context` of a post's capture (`channels/<slug>/posts-media/<postId>/capture.json`), + * or null when there is no capture or it read none. + */ +export async function readCaptureContext(channelsDir, slug, postId) { + if (!POST_KEY_RE.test(slug) || !ID_RE.test(String(postId)) || postId === "_avatars") return null; + try { + const cap = JSON.parse(await readFile(path.join(channelsDir, slug, "posts-media", String(postId), "capture.json"), "utf8")); + return isObj(cap?.context) ? cap.context : null; + } catch { + return null; + } +} + +/** The ops call that reads the context of `ids` (one channel's), ready to paste. */ +export function contextCaptureCall(slug, ids) { + return `pnpm ops capture-posts --json '${JSON.stringify({ slug, ids, contextOnly: true })}' --wait`; +} + +/** + * REFRESH EVERY POST ITEM's CONTEXT from its capture (`umtool posts context + * <project>`): each post item whose capture read a context it lacks gets it, + * in ONE write (one undo point), refused whole in the build's words. + * `dryRun`: nothing written. A post whose capture read none is listed with + * the capture-posts call that reads it (`missing`, by channel). + * + * @param {{ id: string, dir: string }} project + * @param {{ channelsDir?: string | null, dryRun?: boolean }} [o] + */ +export async function postsContext(project, { channelsDir = null, dryRun = false } = {}) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new Error(`${project.id} has no manifest`); + const dir = channelsDir ?? channelsDirFor(project.dir, manifest); + const items = (Array.isArray(manifest.timeline) ? manifest.timeline : []).filter((e) => e?.type === "post" && typeof e.post === "string"); + /** @type {Record<string, { quoted?: any, parents?: any }>} */ + const patches = {}; + const report = []; + /** @type {Map<string, string[]>} */ + const missing = new Map(); + for (const e of items) { + const [slug, rowId] = e.post.split("/"); + // A repost is drawn as its original: the original's capture first. + const shownId = str(e.originalId) || rowId; + const context = (await readCaptureContext(dir, slug, shownId)) ?? (shownId !== rowId ? await readCaptureContext(dir, slug, rowId) : null); + if (!context) { + report.push({ id: e.id, post: e.post, state: "no-context" }); + if (!missing.has(slug)) missing.set(slug, []); + missing.get(slug).push(shownId); + continue; + } + const copy = structuredClone(e); + const filled = applyCaptureContext(copy, context); + if (!filled.length) { + report.push({ id: e.id, post: e.post, state: "complete" }); + continue; + } + patches[e.id] = { + ...(filled.includes("quoted") ? { quoted: copy.quoted } : {}), + ...(filled.includes("parents") ? { parents: copy.parents } : {}), + }; + report.push({ id: e.id, post: e.post, state: "filled", filled, ...patches[e.id] }); + } + const summary = { + items: items.length, + filled: Object.keys(patches).length, + complete: report.filter((r) => r.state === "complete").length, + noContext: report.filter((r) => r.state === "no-context").length, + channelsDir: dir, + report, + missing: [...missing].map(([slug, ids]) => ({ slug, ids, call: contextCaptureCall(slug, ids) })), + }; + if (dryRun || !summary.filled) return { ...summary, dryRun: dryRun === true, result: null, editNotes: null }; + const { result, editNotes } = await withEditNotes(project, async () => + setPostItemsContext(project.dir, patches, { token: await manifestToken(project.dir) }), + ); + return { ...summary, dryRun: false, result, editNotes }; +} diff --git a/umtool/lib/report/postContext.test.mjs b/umtool/lib/report/postContext.test.mjs @@ -0,0 +1,176 @@ +// postContext.mjs: a post item's quoted post and parent from its capture's +// `context` when the archive row lacks them -- the fill rule (pure), the +// snapshot when an entry is made (`posts reel`, `timeline insert post:`), and +// the refresh of every entry (`umtool posts context`): one write, an undo +// point, a re-run that does nothing, the posts with no context named with the +// capture call that reads it. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { cardAuthors, validatePostItem } from "umtool-report-to-video/post-item"; +import { applyCaptureContext, contextCaptureCall, contextRefOf, postsContext, readCaptureContext, sameRef } from "./postContext.mjs"; +import { postItemFromArchive, postsReel } from "./postReel.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { setPostItemsContext, undoStructural } from "./manifest.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-context-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const CH = path.join(ROOT, "channels"); +const REPORTS = path.join(ROOT, "reports"); + +// The operator's case: his reply to Kirsche, archived with no replyTo, no +// quoted and no links -- the capture's page showed both. +const KIRSCHE = { + id: "1983200000000000001", url: "https://x.com/Kirsche/status/1983200000000000001", handle: "Kirsche", author: "Kirsche", + verified: true, badge: "blue", date: "2026-10-29T12:00:00.000Z", text: "Mr. Obvious is a leftist in disguise.", media: [], from: "above", +}; +const QUOTED = { + id: "1983100000000000003", url: "https://x.com/quoted_person/status/1983100000000000003", handle: "quoted_person", author: "Quoted Person", + date: "2026-10-28T09:00:00.000Z", text: "The receipt itself.", media: [{ kind: "image", url: "https://pbs.twimg.com/media/Q2.jpg" }], +}; +const CONTEXT = { readAt: "2026-11-02T20:00:00.000Z", quoted: QUOTED, parent: KIRSCHE }; + +const row = (id, o = {}) => ({ + id, slug: `obv-x/${id}`, channelSlug: "obv-x", author: "ObviousRises", authorName: "Mr. Obvious", createdAt: "2026-10-29T14:05:00.000Z", + text: `post ${id}`, url: `https://x.com/ObviousRises/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], ...o, +}); +async function archive(slug, rows) { + await mkdir(path.join(CH, slug, "posts"), { recursive: true }); + await writeFile(path.join(CH, slug, "config.json"), JSON.stringify({ socialHandle: "ObviousRises", platform: "twitter" })); + await writeFile(path.join(CH, slug, "posts", "2026-10.jsonl"), rows.map((r) => JSON.stringify({ ...r, channelSlug: slug })).join("\n") + "\n"); +} +async function capture(slug, id, context) { + const dir = path.join(CH, slug, "posts-media", id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "capture.json"), JSON.stringify({ version: 1, id, state: "captured", mediaState: "skipped", media: [], ...(context ? { context } : {}) })); +} +async function project(name) { + const dir = path.join(REPORTS, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "obv-x", channelsDir: CH }, + render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" }, chrome: { engine: "hyperframes", layout: "deck", deck: { qr: { links: "original" } } } }, + timeline: [{ type: "clip", id: "c01", video: "v1", start: 1, end: 3 }], + }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + +await archive("obv-x", [ + row("300", { text: "you called me a Leftist, so here is what you said" }), + // The archive names the quote but has no words for it (not archived). + row("301", { createdAt: "2026-10-29T15:00:00.000Z", text: "the receipt", quoted: { platform: "twitter", id: QUOTED.id, author: "quoted_person", url: QUOTED.url } }), + row("302", { createdAt: "2026-10-29T16:00:00.000Z", text: "no context captured yet" }), + // The archive has this reply's parent: its own wins. + row("303", { createdAt: "2026-10-29T17:00:00.000Z", author: "someone_private", authorName: "Private", text: "really?" }), + row("304", { createdAt: "2026-10-29T18:00:00.000Z", text: "@someone_private yes", isReply: true, replyTo: { platform: "twitter", id: "303", author: "someone_private" } }), +]); + +test("the fill rule: only what is missing, a named ref only completed by the same post; the card's blur rule still decides", () => { + assert.deepEqual(contextRefOf(KIRSCHE), { + id: KIRSCHE.id, author: "Kirsche", handle: "Kirsche", badge: "blue", date: KIRSCHE.date, text: KIRSCHE.text, url: KIRSCHE.url, + }); + assert.equal(contextRefOf({ handle: "no spaces allowed", text: " " }), null); + assert.equal(contextRefOf({ handle: "a", text: "x".repeat(30000) }).text.length, 10000); + + const bare = { type: "post", id: "p-1", handle: "ObviousRises", subjects: ["ObviousRises"] }; + assert.deepEqual(applyCaptureContext(bare, CONTEXT), ["quoted", "parents"]); + assert.equal(bare.parents[0].handle, "Kirsche"); + assert.equal(bare.quoted.text, "The receipt itself."); + // Blurred by the card's rule: neither author is the subject, and a blue check is bought. + assert.deepEqual(cardAuthors(bare).map((a) => [a.where, a.redact, a.reason]), [ + ["author", false, "subject"], + ["parents[0]", true, "blue-check"], + ["quoted", true, "private"], + ]); + + // The archive's own: kept; completed only by the same post. + const named = { quoted: { id: QUOTED.id, handle: "quoted_person", url: QUOTED.url }, parents: [{ id: "303", handle: "someone_private", text: "really?" }] }; + assert.deepEqual(applyCaptureContext(named, CONTEXT), ["quoted"]); + assert.equal(named.quoted.text, "The receipt itself."); + assert.equal(named.quoted.author, "Quoted Person"); + assert.equal(named.parents[0].id, "303", "the archive's parent stands"); + const other = { quoted: { id: "1", handle: "elsewhere" } }; + assert.deepEqual(applyCaptureContext(other, CONTEXT), ["parents"]); + assert.deepEqual(other.quoted, { id: "1", handle: "elsewhere" }); + assert.equal(sameRef({ handle: "Quoted_Person" }, { handle: "quoted_person" }), true); + assert.equal(sameRef({ id: "1", handle: "a" }, { id: "2", handle: "a" }), false); + // A context that read neither fills nothing. + assert.deepEqual(applyCaptureContext({}, { readAt: "t" }), []); + assert.deepEqual(applyCaptureContext({}, null), []); + assert.equal(contextCaptureCall("obv-x", ["302"]), `pnpm ops capture-posts --json '{"slug":"obv-x","ids":["302"],"contextOnly":true}' --wait`); +}); + +test("made with it: posts reel and timeline insert snapshot the capture's context where the archive lacks it", async () => { + await capture("obv-x", "300", CONTEXT); + await capture("obv-x", "301", { readAt: "t", quoted: { ...QUOTED, id: undefined } }); + const p = await project("ctx-reel"); + const r = await postsReel(p, { channels: ["obv-x"], until: "2026-10-29" }); + assert.equal(r.added, 5); + const by = new Map((await manifest(p)).timeline.filter((e) => e.type === "post").map((e) => [e.id, e])); + const e300 = by.get("p-300"); + assert.equal(e300.parents?.[0]?.handle, "Kirsche"); + assert.equal(e300.parents?.[0]?.text, KIRSCHE.text); + assert.equal(e300.quoted?.handle, "quoted_person"); + assert.deepEqual(validatePostItem(e300), []); + // The archive named 301's quote: completed with the words, its id kept. + assert.equal(by.get("p-301").quoted.id, QUOTED.id); + assert.equal(by.get("p-301").quoted.text, "The receipt itself."); + assert.equal(by.get("p-301").parents, undefined); + assert.equal(by.get("p-302").quoted, undefined); + assert.equal(by.get("p-304").parents[0].id, "303"); + + const one = await postItemFromArchive(p, await manifest(p), "obv-x", "300", { id: "again-300" }); + assert.equal(one.parents[0].handle, "Kirsche"); +}); + +test("refreshed: posts context fills every entry in one write, an undo point; a re-run does nothing; no context named with its call", async () => { + // A reel made before any capture read a context. + await archive("obv-y", [row("400", { channelSlug: "obv-y", slug: "obv-y/400" }), row("401", { channelSlug: "obv-y", slug: "obv-y/401", createdAt: "2026-10-29T15:00:00.000Z" })]); + const p = await project("ctx-refresh"); + await postsReel(p, { channels: ["obv-y"] }); + assert.equal((await manifest(p)).timeline.find((e) => e.id === "p-400").parents, undefined); + + await capture("obv-y", "400", CONTEXT); + const dry = await postsContext(p, { dryRun: true }); + assert.equal(dry.filled, 1); + assert.equal((await manifest(p)).timeline.find((e) => e.id === "p-400").parents, undefined, "a dry run writes nothing"); + + const r = await postsContext(p); + assert.deepEqual([r.items, r.filled, r.complete, r.noContext], [2, 1, 0, 1]); + assert.deepEqual(r.report.find((x) => x.id === "p-400").filled, ["quoted", "parents"]); + assert.deepEqual(r.missing, [{ slug: "obv-y", ids: ["401"], call: contextCaptureCall("obv-y", ["401"]) }]); + assert.ok(r.result.snapshot?.rel, "an undo point"); + const e = (await manifest(p)).timeline.find((x) => x.id === "p-400"); + assert.equal(e.parents[0].handle, "Kirsche"); + assert.equal(e.quoted.handle, "quoted_person"); + + const again = await postsContext(p); + assert.deepEqual([again.filled, again.complete], [0, 1]); + assert.equal(again.result, null); + + await undoStructural(p.dir); + assert.equal((await manifest(p)).timeline.find((x) => x.id === "p-400").parents, undefined, "undone"); + + // The CLI. + const lines = []; + const code = await postsCommand(["context", p.dir], { root: REPORTS, out: (s) => lines.push(s), err: (s) => lines.push(s) }); + assert.equal(code, 0, lines.join("\n")); + assert.match(lines[0], /^filled the context of 1 of 2 post item\(s\)/); + assert.ok(lines.some((l) => /p-400 {2}quotes @quoted_person, answers @Kirsche/.test(l)), lines.join("\n")); + assert.ok(lines.some((l) => l.includes('"contextOnly":true')), lines.join("\n")); +}); + +test("the writer: only quoted and parents, refused whole in the build's words; the reader refuses what is no post", async () => { + const p = await project("ctx-writer"); + await postsReel(p, { channels: ["obv-x"], until: "2026-10-29" }); + await assert.rejects(setPostItemsContext(p.dir, { "p-300": { text: "rewritten" } }), /text is not a post item's context/); + await assert.rejects(setPostItemsContext(p.dir, { c01: { quoted: QUOTED } }), /not a post item/); + await assert.rejects(setPostItemsContext(p.dir, { "p-302": { parents: [{ handle: "bad handle!" }] } }), (e) => /handle must be a handle/.test(String(e.errors ?? e.message))); + assert.equal((await manifest(p)).timeline.find((x) => x.id === "p-302").parents, undefined, "refused whole"); + assert.equal(await readCaptureContext(CH, "obv-x", "../../etc"), null); + assert.equal(await readCaptureContext(CH, "obv-x", "302"), null); + assert.equal((await readCaptureContext(CH, "obv-x", "300")).parent.handle, "Kirsche"); +}); diff --git a/umtool/lib/report/postReel.mjs b/umtool/lib/report/postReel.mjs @@ -43,6 +43,7 @@ import { channelsDirFor, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { addArchiveAvatars, insertEntries, manifestToken } from "./manifest.mjs"; import { deckPlatformOf } from "./postsCli.mjs"; +import { applyCaptureContext } from "./postContext.mjs"; const execFileP = promisify(execFile); const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe"; @@ -100,16 +101,20 @@ export async function channelHandle(channelsDir, slug) { /** * The files a post's capture holds (`posts-media/<postId>/`): capture.json's * `media` in its order (with each one's source url), else the folder's - * pictures and videos by name. Never `shot.png` or the thread shot. + * pictures and videos by name. Never `shot.png` or the thread shot. And the + * record's `context` (the quoted post and the parent its page showed; + * postContext.mjs), or null. * - * @returns {Promise<{ dir: string, media: Array<{ name: string, url: string | null }>, threadShot: string | null }>} + * @returns {Promise<{ dir: string, media: Array<{ name: string, url: string | null }>, threadShot: string | null, context: Record<string, any> | null }>} */ export async function captureOf(channelsDir, slug, postId) { const dir = path.join(channelsDir, slug, "posts-media", postId); const names = await readdir(dir).catch(() => []); let media = []; + let context = null; try { const cap = JSON.parse(await readFile(path.join(dir, "capture.json"), "utf8")); + if (cap?.context && typeof cap.context === "object" && !Array.isArray(cap.context)) context = cap.context; if (Array.isArray(cap?.media)) { media = cap.media.filter((m) => typeof m?.name === "string" && names.includes(m.name)).map((m) => ({ name: m.name, url: typeof m.url === "string" ? m.url : null })); } @@ -122,7 +127,7 @@ export async function captureOf(channelsDir, slug, postId) { .sort() .map((name) => ({ name, url: null })); } - return { dir, media: media.slice(0, POST_MEDIA_MAX), threadShot: names.includes("shot-thread.png") ? path.join(dir, "shot-thread.png") : null }; + return { dir, media: media.slice(0, POST_MEDIA_MAX), threadShot: names.includes("shot-thread.png") ? path.join(dir, "shot-thread.png") : null, context }; } /** @@ -277,6 +282,8 @@ export async function postEntryFrom(row, { index, io, subjects = [] }) { const q = index.get(String(shown.quoted.id ?? "")) ?? null; entry.quoted = refOf(q ?? { ...shown.quoted, author: shown.quoted.author ?? shown.quoted.handle, authorName: shown.quoted.authorName ?? shown.quoted.name }, shown.quoted); } + // What the archive lacks of its context, from the capture's (postContext.mjs): the shown post's, else the row's. + applyCaptureContext(entry, (await io.capture(shownSlug, String(shown.id))).context ?? (shown !== row ? (await io.capture(slug, row.id)).context : null)); // Its attachments: the shown post's capture (a repost's original), else the row's own. let cap = await io.capture(shownSlug, String(shown.id)); let capSlug = shownSlug; diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -71,6 +71,10 @@ export const POSTS_USAGE = [ " umtool posts avatars <project> [--dry-run] [--json]", " every author the cut's cards draw unblurred, their picture from the archive's store (the channels' posts-media/", " _avatars/, capture-posts') copied in where the cut has none; a manual one is never replaced.", + " umtool posts context <project> [--dry-run] [--json]", + " every post item's CONTEXT from its capture (capture.json's `context`: the post it quotes, the post it answers, as", + " its page showed them) where the archive row lacks it -- one write (one undo point). A post whose capture read", + " none is listed with the call that reads it: pnpm ops capture-posts --json '{\"slug\":…,\"ids\":[…],\"contextOnly\":true}'.", ].join("\n"); const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete"]); @@ -367,6 +371,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con } if (verb === "avatar" && projectArg && !flags.has("--help")) return await avatarCommand(projectArg, words.slice(2), { root, json, out }); if (verb === "avatars" && projectArg && !flags.has("--help")) return await avatarsCommand(projectArg, { root, json, dryRun, out }); + if (verb === "context" && projectArg && !flags.has("--help")) return await contextCommand(projectArg, { root, json, dryRun, out }); if ((verb !== "add" && verb !== "set") || !projectArg || !ref || flags.has("--help")) { err(POSTS_USAGE); return 2; @@ -560,6 +565,30 @@ export function postItemPatchOf(pairs) { return out; } +/** `posts context`: every post item's context from its capture (postContext.mjs postsContext). */ +async function contextCommand(projectArg, { root, json, dryRun, out }) { + const project = await projectOf(projectArg, root); + const { postsContext } = await import("./postContext.mjs"); + const r = await postsContext(project, { dryRun }); + if (json) { + out(JSON.stringify({ ok: true, ...r, result: r.result ? { ids: r.result.ids, snapshot: r.result.snapshot, token: r.result.token } : null }, null, 2)); + return 0; + } + out(`${r.dryRun ? "would fill" : "filled"} the context of ${r.filled} of ${r.items} post item(s) in ${project.id} (${r.complete} complete, ${r.noContext} with no context captured)`); + for (const x of r.report) { + if (x.state !== "filled") continue; + const what = [ + x.quoted ? `quotes ${x.quoted.handle ? `@${x.quoted.handle}` : x.quoted.author ?? "?"}` : "", + x.parents ? `answers ${x.parents[0]?.handle ? `@${x.parents[0].handle}` : x.parents[0]?.author ?? "?"}` : "", + ].filter(Boolean).join(", "); + out(` ${x.id} ${what}`); + } + for (const m of r.missing) out(` no context captured for ${m.ids.length} post(s) of ${m.slug}:\n ${m.call}\n then umtool posts context ${project.id} again`); + if (r.result?.snapshot?.rel && !r.result.snapshot.skipped) out(` undo point: ${r.result.snapshot.rel} (umtool timeline ${project.id} undo)`); + if (r.editNotes) out(` edit noted for ${r.editNotes.generatedBy}`); + return 0; +} + /** `posts set-item`: a post item's knobs, through updatePostItem (`fit=read[:linger]`: posts fit, on this item). */ async function setItemCommand(projectArg, ref, pairs, { root, json, out }) { const fitPair = pairs.find((p) => /^fit=/.test(p));