Archilyzer · Source

archilyzer

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

commit 284247fd065347b2d35e09511560ad105c12fea8
parent 8ca9345d5dbb2547e96928a5548c7bbb7c660ca3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 27 Oct 2026 13:20:26 -0400

capture-posts: a reply's thread shot -- the post it answers over it, its author blurred

An X reply's capture can now also write shot-thread.png beside shot.png
(never in its place): the union box from the IMMEDIATE parent article's
top to the reply's bottom, shot from the window like every X shot
(viewportShot.ts takes a selector list and shoots their union). The
parent is the article whose status link is the archive's replyTo.id;
with no archive word, the article directly above the reply; an archive
id not on the page is no parent (the article above would be a
grandparent). A post the archive says is no reply is not opened for it.

The parent's avatar, display name and @handle -- and every link to that
profile in the reply -- are blurred in the page (CSS filter) before the
thread shot, unless the parent's author is verified or the reply's own.
The blurred boxes are recorded in the shot's pixels in capture.json
(thread: {name, parentId, parentHandle, parentAuthor, parentVerified,
parentFrom, redaction}). A parent whose name cannot be found to blur
gets no thread shot.

Opt-in: capture-posts "thread": true (or the channel's new
postCaptureThread), "threadRedact": false | true | {"<id>": bool}; the
channel page's Capture posts gains Thread shot and Blur options on X
channels. A post shot before gets only its thread shot.

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

Diffstat:
MCHANNEL.md | 1+
Mcommon/controller/capturePosts.test.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/capturePosts.ts | 51++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/lib/channelConfig.ts | 4++++
Mcommon/lib/channelConfigSchema.test.ts | 2+-
Mcommon/lib/channelConfigSchema.ts | 1+
Mcommon/lib/report/draft/research/tools.ts | 7++++---
Mcommon/social/fetchers.ts | 11+++++++++++
Mcommon/social/postCapture.test.ts | 49++++++++++++++++++++++++++++++++++++++++---------
Mcommon/social/postCapture.ts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/social/viewportShot.test.ts | 34+++++++++++++++++++++++++++++++++-
Mcommon/social/viewportShot.ts | 37++++++++++++++++++++++++++++++-------
Mcommon/social/xPostCapture.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Acommon/social/xThreadShot.test.ts | 359+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/xThreadShot.ts | 333+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/capture-posts/route.test.ts | 16++++++++++++++++
Meditor/app/api/ops/capture-posts/route.ts | 14++++++++++----
Meditor/app/channels/[slug]/components/SocialChannelPanel.tsx | 5++++-
Meditor/app/channels/[slug]/components/SocialPostTools.tsx | 28+++++++++++++++++++++++++---
Meditor/app/channels/[slug]/page.tsx | 2++
Meditor/app/channels/[slug]/socialActions.ts | 22+++++++++++++++++++---
Meditor/app/jobs/jobReplayRegistry.ts | 5+++++
Mscripts/archilyzer-ops.mjs | 8+++++++-
23 files changed, 1148 insertions(+), 53 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -19,6 +19,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `postFetcher` | config | Social channels only: which social fetcher drives ingest (e.g. `"bluesky-atproto"`, `"x-gallery-dl"`). Absent = resolve by URL detection. Trimmed. | | `socialHandle` | config | Social channels only: the bare account handle (a leading "@" is stripped). Derived from `url` at creation but stored, so a later URL-format change upstream cannot silently re-point ingest at a different account. | | `postPagePauseSeconds` | config | Social channels that are read page by page (a forum thread) only: the pause between two page loads, in seconds; each pause is jittered to 0.85–1.65× of it. Absent = the fetcher's own (12 s, so 10–20 s); floored at 5, capped at 600. | +| `postCaptureThread` | config | X channels only: `capture-posts` also shoots each reply's THREAD SHOT — the post it answers over the reply, `posts-media/<id>/shot-thread.png` beside `shot.png`, the parent's author blurred unless verified or the reply's own — unless the run says `"thread": false`. Absent = false (a run asks with `"thread": true`). | | `platform` | config | The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, "archive.org items"), bitchute (BitChute videos and channels; see README.md, "BitChute"), twitter, bluesky, xenforo (a forum thread) or webpage (Wayback Machine captures of pages; see `wayback`). An unknown value is dropped. | | `name` | config | Display name. | | `url` | config | The channel / playlist / account URL syncs enumerate. Absent = the channel is never auto-synced. | diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts @@ -218,6 +218,69 @@ test("the articles: on by default, refused alone only when not asked for by name assert.equal(calls[0].articles, true); }); +test("the thread shots (X): off by default, the run's word or the channel's, each reply's parent id passed", async () => { + const root = path.join(channelsDir, "demo-x-replies"); + await mkdir(root, { recursive: true }); + const config = { + handling: "transcribe", + sourceKind: "social", + platform: "twitter", + postFetcher: "test-capture-x", + socialHandle: "example_user", + name: "Example (X replies)", + url: "https://x.com/example_user", + }; + await writeFile(path.join(root, "config.json"), JSON.stringify(config)); + const base = { + channelSlug: "demo-x-replies", author: "example_user", createdAt: "2026-10-25T04:34:32.000Z", uploadDate: "20261025", + platform: "twitter" as const, isRepost: false, links: [], + }; + await writePosts(root, [ + { + ...base, id: "501", slug: "demo-x-replies/501", text: "@someone Well..", url: "https://x.com/example_user/status/501", isReply: true, + replyTo: { platform: "twitter" as const, id: "500", author: "someone" }, + }, + { ...base, id: "502", slug: "demo-x-replies/502", text: "a post", url: "https://x.com/example_user/status/502", isReply: false }, + ]); + answer = { outcomes: [] }; + + calls = []; + assert.equal((await run("demo-x-replies", ["501"], { articles: 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"); + + calls = []; + assert.equal((await run("demo-x-replies", ["501", "502"], { thread: true, threadRedact: { "501": false } })).ok, true); + assert.equal(calls[0].thread, true); + assert.deepEqual(calls[0].threadRedact, { "501": false }); + const archived = calls[0].archived!; + assert.deepEqual(archived.get("501"), { + text: "@someone Well..", links: [], author: "example_user", isReply: true, replyTo: { id: "500", author: "someone" }, + }); + assert.equal(archived.get("502")?.isReply, false); + + // The channel's default, and the run's word over it. + await writeFile(path.join(root, "config.json"), JSON.stringify({ ...config, postCaptureThread: true })); + calls = []; + await run("demo-x-replies", ["501"]); + assert.equal(calls[0].thread, true); + calls = []; + await run("demo-x-replies", ["501"], { thread: false }); + assert.equal(calls[0].thread, false); + + // Asked for by name, the thread shots alone are a run. + calls = []; + assert.equal((await run("demo-x-replies", ["501"], { shots: false, media: false, thread: true })).ok, true); + assert.equal(calls.length, 1); +}); + +test("the thread shots are X's only: another platform's run takes none", async () => { + await makeChannel("demo-social-thread"); + calls = []; + await run("demo-social-thread", ["aaa"], { thread: true }); + assert.equal(calls[0].thread, false); +}); + test("a Wayback pages channel: its records rendered from their captures, no fetcher, nothing in the availability sidecar", async () => { const root = path.join(channelsDir, "demo-pages"); await mkdir(root, { recursive: true }); diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -67,6 +67,13 @@ export type CapturePostsOptions = { force?: boolean; // Also open and save the X Article a post links to. Defaults to true. articles?: boolean; + // X: also shoot a reply's thread shot (the post it answers over it, + // shot-thread.png). Defaults to the channel's `postCaptureThread`, else + // false. + thread?: boolean; + // 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; onLog?: (line: string) => void; signal?: AbortSignal; // The job's drain: stop between posts. @@ -95,16 +102,34 @@ export function capturePostsProblem( } 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).'; + '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 were asked for by -// name: their default alone does not make a run. +// 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. export function nothingToCapture(o: { shots?: boolean; media?: boolean; articles?: boolean; + thread?: boolean; }): boolean { - return o.shots === false && o.media === false && o.articles !== true; + return o.shots === false && o.media === false && o.articles !== true && o.thread !== true; +} + +// 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>; +export function parseThreadRedact(v: unknown): { ok: true; value: ThreadRedactKnob | undefined } | { ok: false; error: string } { + if (v === undefined || v === null) return { ok: true, value: undefined }; + if (typeof v === "boolean") return { ok: true, value: v }; + if (typeof v === "object" && !Array.isArray(v)) { + const out: Record<string, boolean> = {}; + for (const [k, b] of Object.entries(v as Record<string, unknown>)) { + if (typeof b !== "boolean") return { ok: false, error: `"threadRedact" for ${k} must be true or false` }; + out[k] = b; + } + return { ok: true, value: out }; + } + return { ok: false, error: '"threadRedact" must be true, false or { "<post id>": true | false }' }; } // The ids not in the channel's archive, or null when every one is. @@ -147,6 +172,9 @@ export async function capturePosts( // 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. + // The thread shot: X only, the run's word or the channel's default. + const thread = fetcher.platform === "twitter" ? (opts.thread ?? config.postCaptureThread ?? false) : false; + if (opts.thread && fetcher.platform !== "twitter") log(`Thread shots are X's only; ${fetcher.label} takes none.`); const handle = config.socialHandle ?? handleFromAccountUrl(accountUrl) ?? (isXSearchChannel(config) ? slug : ""); if (!handle) return fail(`Could not determine an account handle for ${slug}`); @@ -162,11 +190,13 @@ export async function capturePosts( url?: string; media?: { kind: string; url: string; name?: string }[]; author?: string; + isReply?: boolean; + replyTo?: { 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") || forum || bluesky) { + if ((opts.articles !== false && fetcher.platform === "twitter") || thread || forum || bluesky) { const wanted = new Set(ids); archived = new Map(); for (const p of await readAllPosts(channelRoot)) { @@ -177,6 +207,14 @@ 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 } : {}), + // The thread shot tells the parent by the id the reply answers. + ...(thread + ? { + author: p.author, + isReply: p.isReply, + ...(p.replyTo ? { replyTo: { id: p.replyTo.id, ...(p.replyTo.author ? { author: p.replyTo.author } : {}) } } : {}), + } + : {}), }); } } @@ -193,6 +231,7 @@ export async function capturePosts( opts.shots === false ? "" : " screenshot", opts.media === false ? "" : " media", opts.articles === false || fetcher.platform !== "twitter" ? "" : " articles", + thread ? ` thread shots${opts.threadRedact === false ? " (no blur)" : ""}` : "", ].join("") + (opts.force ? ", again where already captured" : "") + ".", @@ -213,6 +252,8 @@ export async function capturePosts( media: opts.media, force: opts.force, articles: opts.articles, + thread, + ...(opts.threadRedact !== undefined ? { threadRedact: opts.threadRedact } : {}), archived, cookies: alwaysCookies(policy), cookieSource: xLogin?.source, diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -171,6 +171,7 @@ export type ChannelConfig = { postFetcher?: string; socialHandle?: string; postPagePauseSeconds?: number; + postCaptureThread?: boolean; platform?: Platform; name?: string; url?: string; @@ -225,6 +226,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { 'Social channels only: the bare account handle (a leading "@" is stripped). Derived from `url` at creation but stored, so a later URL-format change upstream cannot silently re-point ingest at a different account.', postPagePauseSeconds: "Social channels that are read page by page (a forum thread) only: the pause between two page loads, in seconds; each pause is jittered to 0.85–1.65× of it. Absent = the fetcher's own (12 s, so 10–20 s); floored at 5, capped at 600.", + postCaptureThread: + 'X channels only: `capture-posts` also shoots each reply\'s THREAD SHOT — the post it answers over the reply, `posts-media/<id>/shot-thread.png` beside `shot.png`, the parent\'s author blurred unless verified or the reply\'s own — unless the run says `"thread": false`. Absent = false (a run asks with `"thread": true`).', platform: "The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, \"archive.org items\"), bitchute (BitChute videos and channels; see README.md, \"BitChute\"), twitter, bluesky, xenforo (a forum thread) or webpage (Wayback Machine captures of pages; see `wayback`). An unknown value is dropped.", name: "Display name.", url: "The channel / playlist / account URL syncs enumerate. Absent = the channel is never auto-synced.", @@ -448,6 +451,7 @@ export const CHANNEL_CONFIG_COERCIONS: { typeof v === "string" && v.trim() ? v.trim().replace(/^@/, "") : undefined, postPagePauseSeconds: (v) => isFiniteNumber(v) && v > 0 ? Math.min(Math.max(Math.floor(v), 5), 600) : undefined, + postCaptureThread: bool, platform: (v) => typeof v === "string" && PLATFORM_VALUES.includes(v as Platform) ? (v as Platform) diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts @@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it", assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]); - assert.equal(CHANNEL_CONFIG_KEYS.length, 39); // 2026-10-26: `chat` + assert.equal(CHANNEL_CONFIG_KEYS.length, 40); // 2026-10-27: `postCaptureThread` assert.equal(sameKeys, true); assert.equal(fits, true); for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k); diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -48,6 +48,7 @@ export const channelConfigObjectSchema = z.object({ postFetcher: field("postFetcher"), socialHandle: field("socialHandle"), postPagePauseSeconds: field("postPagePauseSeconds"), + postCaptureThread: field("postCaptureThread"), platform: field("platform"), name: field("name"), url: field("url"), diff --git a/common/lib/report/draft/research/tools.ts b/common/lib/report/draft/research/tools.ts @@ -127,10 +127,11 @@ export const ACTION_SPECS: Record<AcquisitionAction, ActionSpec> = { "capture-posts": { action: "capture-posts", editorAction: "capture-posts", - description: "Capture archived posts of a social channel: a screenshot and the attached media of each id.", - properties: { slug: str, ids: strList, shots: bool, media: bool, articles: bool }, + 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 }, required: ["slug", "ids"], - body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles"]), + body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles", "thread"]), }, "import-post": { action: "import-post", diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -248,6 +248,13 @@ export type PostCaptureInput = Pick< // Also capture the long-form article a post links to (X Articles), where it // links to one. Defaults to true. articles?: boolean; + // X: also shoot a reply's thread shot -- the post it answers over it, + // `shot-thread.png` (xThreadShot.ts). Defaults to false. + thread?: boolean; + // The thread shot's blur of the parent's author: undefined is the rule + // (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>>; // 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. @@ -263,6 +270,10 @@ export type PostCaptureInput = Pick< // The post's author as archived (Bluesky: a repost is archived under the // original's author, which its lookup must name). author?: string; + // Whether it is a reply, and what it answers (X: the thread shot's + // parent is told by this id). + isReply?: boolean; + replyTo?: { id: string; author?: string }; } >; // A soft stop: no new post is started once it fires, and the one in hand diff --git a/common/social/postCapture.test.ts b/common/social/postCapture.test.ts @@ -23,6 +23,7 @@ import { postsMediaDir, readPostCapture, SHOT_FILENAME, + THREAD_SHOT_FILENAME, writePostCapture, type ArticleCaptureRecord, type PostCaptureRecord, @@ -106,28 +107,30 @@ test("availability: only what the page said about the post — never a verdict f test("what a capture owes: nothing for a settled post, only the missing half otherwise, everything when forced", () => { const all = { shots: true, media: true, force: false }; - assert.deepEqual(captureWork(null, all), { shot: true, media: true, article: false }); - assert.deepEqual(captureWork(null, { ...all, media: false }), { shot: true, media: false, article: false }); + assert.deepEqual(captureWork(null, all), { shot: true, media: true, article: false, thread: false }); + assert.deepEqual(captureWork(null, { ...all, media: false }), { shot: true, media: false, article: false, thread: false }); const done = record({ shot: { name: SHOT_FILENAME, bytes: 1, sha256: "x" }, mediaState: "ok" }); - assert.deepEqual(captureWork(done, all), { shot: false, media: false, article: false }); - assert.deepEqual(captureWork(record({ ...done, mediaState: "none" }), all), { shot: false, media: false, article: false }); + assert.deepEqual(captureWork(done, all), { shot: false, media: false, article: false, thread: false }); + assert.deepEqual(captureWork(record({ ...done, mediaState: "none" }), all), { shot: false, media: false, article: false, thread: false }); // The media failed (or was never asked for): only the media is owed. - assert.deepEqual(captureWork(record({ ...done, mediaState: "error" }), all), { shot: false, media: true, article: false }); - assert.deepEqual(captureWork(record({ ...done, mediaState: "skipped" }), all), { shot: false, media: true, article: false }); + assert.deepEqual(captureWork(record({ ...done, mediaState: "error" }), all), { shot: false, media: true, article: false, thread: false }); + assert.deepEqual(captureWork(record({ ...done, mediaState: "skipped" }), all), { shot: false, media: true, article: false, thread: false }); // A shot that failed is owed again. - assert.deepEqual(captureWork(record({ state: "error", mediaState: "ok" }), all), { shot: true, media: false, article: false }); + assert.deepEqual(captureWork(record({ state: "error", mediaState: "ok" }), all), { shot: true, media: false, article: false, thread: false }); // Deleted is settled: asking again is a request for the same answer. assert.deepEqual(captureWork(record({ state: "deleted", mediaState: "skipped" }), all), { shot: false, media: false, article: false, + thread: false, }); // force re-takes whatever was asked for. - assert.deepEqual(captureWork(done, { ...all, force: true }), { shot: true, media: true, article: false }); + assert.deepEqual(captureWork(done, { ...all, force: true }), { shot: true, media: true, article: false, thread: false }); assert.deepEqual(captureWork(record({ state: "deleted" }), { shots: false, media: true, force: true }), { shot: false, media: true, article: false, + thread: false, }); }); @@ -147,7 +150,7 @@ test("what a capture owes the article half: only when asked, settled once captur // Not asked for by name: the older callers' shape owes no article. assert.equal(captureWork(null, { shots: true, media: true, force: false }).article, false); // A post shot before articles were captured owes only its article. - assert.deepEqual(captureWork(done, all), { shot: false, media: false, article: true }); + assert.deepEqual(captureWork(done, all), { shot: false, media: false, article: true, thread: false }); for (const state of ["captured", "deleted", "unavailable"] as const) { assert.equal(captureWork(record({ ...done, article: article(state) }), all).article, false, state); } @@ -159,6 +162,34 @@ test("what a capture owes the article half: only when asked, settled once captur assert.equal(captureWork(record({ state: "deleted" }), all).article, false); }); +test("what a capture owes the thread shot: only when asked, settled once taken or found to be none, owed again after an error", () => { + const all = { shots: true, media: true, force: false, thread: true }; + const done = record({ shot: { name: SHOT_FILENAME, bytes: 1, sha256: "x" }, mediaState: "ok" }); + assert.equal(captureWork(null, all).thread, true); + assert.equal(captureWork(null, { ...all, thread: false }).thread, false); + // Not asked for: the older callers' shape owes none. + assert.equal(captureWork(done, { shots: true, media: true, force: false }).thread, false); + // A post shot before: only its thread shot is owed. + assert.deepEqual(captureWork(done, all), { shot: false, media: false, article: false, thread: true }); + const thread = { + name: THREAD_SHOT_FILENAME, bytes: 2, sha256: "y", parentId: "5", parentVerified: false, parentFrom: "reply-to" as const, + redaction: { applied: true, reason: "private" as const, boxes: [] }, + }; + assert.equal(captureWork(record({ ...done, thread }), all).thread, false); + assert.equal(captureWork(record({ ...done, threadNone: "not a reply" }), all).thread, false); + assert.equal(captureWork(record({ ...done, threadError: "the page moved" }), all).thread, true); + assert.equal(captureWork(record({ ...done, thread }), { ...all, force: true }).thread, true); + assert.equal(captureWork(record({ state: "deleted" }), all).thread, false); +}); + +test("the thread shot is not a medium of the post", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "thread-files-")); + await writeFile(path.join(dir, SHOT_FILENAME), "a"); + await writeFile(path.join(dir, THREAD_SHOT_FILENAME), "b"); + await writeFile(path.join(dir, "1_1.jpg"), "c"); + assert.deepEqual(await listCapturedMediaFiles(dir), ["1_1.jpg"]); +}); + test("article files are named by the layout, images numbered from 1", () => { assert.equal(articleImageFilename(1, "jpg"), "article-img-1.jpg"); assert.ok(isArticleFile("article.md")); diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts @@ -2,6 +2,10 @@ // // Layout, per channel: // channels/<slug>/posts-media/<post id>/shot.png — the post, as rendered +// channels/<slug>/posts-media/<post id>/shot-thread.png — a reply with the +// post it answers above it (X, opt-in: `thread`), its author blurred +// unless verified or the reply's own (xPostCapture.ts); never in place +// of shot.png // channels/<slug>/posts-media/<post id>/<media…> — its attached media // channels/<slug>/posts-media/<post id>/capture.json — this module's record // channels/<slug>/posts-media/<post id>/article.* — the X Article the post @@ -30,6 +34,7 @@ import type { PostAvailability } from "../lib/posts"; export const POSTS_MEDIA_DIRNAME = "posts-media"; export const CAPTURE_FILENAME = "capture.json"; export const SHOT_FILENAME = "shot.png"; +export const THREAD_SHOT_FILENAME = "shot-thread.png"; export const ARTICLE_JSON_FILENAME = "article.json"; export const ARTICLE_MD_FILENAME = "article.md"; export const ARTICLE_SHOT_FILENAME = "article.png"; @@ -128,6 +133,41 @@ export type ArticleCaptureRecord = { error?: string; }; +// Why a thread shot's parent author was or was not blurred: +// private — the parent's author is neither verified nor the reply's own +// (the default's reason to blur) +// verified — the parent's author carries X's verified badge: not blurred +// self — a self-thread: the parent is the reply's own author's +// off — the capture (or its channel) turned the blur off +// forced — the capture asked for the blur whatever the author +export type ThreadRedactionReason = "private" | "verified" | "self" | "off" | "forced"; + +// One blurred box of a thread shot, in the shot's own pixels (its top-left +// is 0,0), and what it covered. +export type RedactedBox = { + what: "avatar" | "name" | "user-name" | "mention"; + box: { x: number; y: number; width: number; height: number }; +}; + +// The thread shot: shot-thread.png (CapturedFile's `name`), the reply with +// its IMMEDIATE parent above it -- one parent only, a longer chain cut to it. +export type ThreadCaptureRecord = CapturedFile & { + parentId: string; + parentHandle?: string; + // The parent's display name as the page showed it. + parentAuthor?: string; + parentVerified: boolean; + // How the parent was told on the page: its status link matched the + // archive's in-reply-to id, or (the archive not saying) the post directly + // above the reply. + parentFrom: "reply-to" | "above"; + redaction: { + applied: boolean; + reason: ThreadRedactionReason; + boxes: RedactedBox[]; + }; +}; + export type PostCaptureRecord = { version: 1; id: string; @@ -150,6 +190,13 @@ export type PostCaptureRecord = { media: CapturedFile[]; // The X Article the post links to, when one was captured or tried. article?: ArticleCaptureRecord; + // The thread shot (X replies, asked for with `thread`), when one was taken. + thread?: ThreadCaptureRecord; + // Why a thread shot was asked for and none taken, settled: the post is not + // a reply, or its parent did not render above it. A failure that may pass + // is `threadError` instead, and owed again. + threadNone?: string; + threadError?: string; error?: string; }; @@ -189,6 +236,7 @@ export async function listCapturedMediaFiles(dir: string): Promise<string[]> { .filter( (n) => n !== SHOT_FILENAME && + n !== THREAD_SHOT_FILENAME && n !== CAPTURE_FILENAME && !isArticleFile(n) && !n.endsWith(".part") && @@ -222,15 +270,18 @@ export async function writePostCapture( // media download that did not finish ("error", or never attempted) is owed. // The article half is owed only if the post links to one (the caller knows); // one captured, deleted or walled is settled, one that failed is owed. +// The thread shot is owed when asked for and neither taken nor settled as +// none (not a reply, no parent shown); one that failed is owed again. export function captureWork( existing: PostCaptureRecord | null, - wanted: { shots: boolean; media: boolean; force: boolean; articles?: boolean }, -): { shot: boolean; media: boolean; article: boolean } { + wanted: { shots: boolean; media: boolean; force: boolean; articles?: boolean; thread?: boolean }, +): { shot: boolean; media: boolean; article: boolean; thread: boolean } { const articles = wanted.articles ?? false; + const thread = wanted.thread ?? false; if (wanted.force || !existing) { - return { shot: wanted.shots, media: wanted.media, article: articles }; + return { shot: wanted.shots, media: wanted.media, article: articles, thread }; } - if (existing.state === "deleted") return { shot: false, media: false, article: false }; + if (existing.state === "deleted") return { shot: false, media: false, article: false, thread: false }; return { shot: wanted.shots && !existing.shot, media: @@ -238,6 +289,7 @@ export function captureWork( existing.mediaState !== "ok" && existing.mediaState !== "none", article: articles && !articleSettled(existing.article), + thread: thread && !existing.thread && !existing.threadNone, }; } diff --git a/common/social/viewportShot.test.ts b/common/social/viewportShot.test.ts @@ -7,7 +7,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import type { PageLike } from "./playwrightRuntime"; -import { shootFromViewport, TOP_ROOM, VIEW_SCRIPT_MARKER, type ElementView } from "./viewportShot"; +import { shootFromViewport, TOP_ROOM, unionBox, VIEW_SCRIPT_MARKER, viewScript, type ElementView } from "./viewportShot"; const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47]); @@ -153,3 +153,35 @@ test("the window is put back even when the shot throws", async () => { await assert.rejects(shootFromViewport(p, { selector: SEL, settleMs: 0 }), /Target closed/); assert.deepEqual(p.sizes.at(-1), { width: 1280, height: 720 }); }); + +test("a selector list is measured as ONE box, their union, by the page's own script", () => { + const rects: Record<string, { left: number; top: number; right: number; bottom: number }> = { + "[p]": { left: 283, top: -200, right: 881, bottom: 20 }, + "[o]": { left: 283, top: 20, right: 881, bottom: 300 }, + }; + const g = globalThis as Record<string, unknown>; + const saved = { document: g.document, window: g.window }; + g.document = { + querySelector: (s: string) => + rects[s] + ? { getBoundingClientRect: () => ({ ...rects[s], width: rects[s].right - rects[s].left, height: rects[s].bottom - rects[s].top }) } + : null, + }; + g.window = { innerWidth: 1280, innerHeight: 720 }; + try { + assert.deepEqual((0, eval)(viewScript(["[p]", "[o]"])), { x: 283, y: -200, width: 598, height: 500, vw: 1280, vh: 720 }); + assert.deepEqual((0, eval)(viewScript("[o]")), { x: 283, y: 20, width: 598, height: 280, vw: 1280, vh: 720 }); + // One of them missing: nothing to shoot as the union. + assert.equal((0, eval)(viewScript(["[p]", "[gone]"])), null); + } finally { + g.document = saved.document; + g.window = saved.window; + } + assert.deepEqual( + unionBox([ + { x: 283, y: -200, width: 598, height: 220 }, + { x: 283, y: 20, width: 598, height: 280 }, + ]), + { x: 283, y: -200, width: 598, height: 500 }, + ); +}); diff --git a/common/social/viewportShot.ts b/common/social/viewportShot.ts @@ -38,8 +38,9 @@ export type ElementView = { export type ViewportShotOptions = { // The element, as a selector the page can query (a marker attribute the - // caller set). - selector: string; + // caller set) -- or several, shot as ONE box: their union (a reply's thread + // shot, its parent's article over its own). Every one must be on the page. + selector: string | ReadonlyArray<string>; // Shoot at most this much of the element's height, from its top. maxHeight?: number; // The tallest window it will grow to (default 16 384 px). @@ -65,12 +66,34 @@ const MOVED_PX = 1; export const VIEW_SCRIPT_MARKER = "__archilyzerElementView"; -export const viewScript = (selector: string) => `(() => { +// The smallest box holding every one of `boxes` (null for none): what a +// selector list is shot as. The page runs the same arithmetic (viewScript). +export function unionBox( + boxes: ReadonlyArray<{ x: number; y: number; width: number; height: number }>, +): { x: number; y: number; width: number; height: number } | null { + if (boxes.length === 0) return null; + const left = Math.min(...boxes.map((b) => b.x)); + const top = Math.min(...boxes.map((b) => b.y)); + const right = Math.max(...boxes.map((b) => b.x + b.width)); + const bottom = Math.max(...boxes.map((b) => b.y + b.height)); + return { x: left, y: top, width: right - left, height: bottom - top }; +} + +export const viewScript = (selector: string | ReadonlyArray<string>) => `(() => { const ${VIEW_SCRIPT_MARKER} = true; - const el = document.querySelector(${JSON.stringify(selector)}); - if (!el) return null; - const r = el.getBoundingClientRect(); - return { x: r.left, y: r.top, width: r.width, height: r.height, vw: window.innerWidth, vh: window.innerHeight }; + const sels = ${JSON.stringify(typeof selector === "string" ? [selector] : [...selector])}; + const rs = []; + for (const s of sels) { + const el = document.querySelector(s); + if (!el) return null; + rs.push(el.getBoundingClientRect()); + } + if (!rs.length) return null; + const left = Math.min(...rs.map((r) => r.left)); + const top = Math.min(...rs.map((r) => r.top)); + const right = Math.max(...rs.map((r) => r.right)); + const bottom = Math.max(...rs.map((r) => r.bottom)); + return { x: left, y: top, width: right - left, height: bottom - top, vw: window.innerWidth, vh: window.innerHeight }; })()`; const scrollScript = (dy: number) => `window.scrollBy(0, ${Math.round(dy)})`; diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts @@ -25,6 +25,11 @@ // or on its rendered card — and the run then opens the article too, one more // paced contact (xArticleCapture.ts), unless `articles` is off. // +// With `thread` (opt-in), a reply also gets its THREAD SHOT in the same page +// load: the post it answers over the reply, `shot-thread.png`, the parent's +// author blurred unless verified or the reply's own (xThreadShot.ts). A post +// the archive says is no reply is not opened for it. +// // 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. @@ -54,6 +59,7 @@ import { import { xArticleLinkFromArchive, type XArticleLink } from "./xArticle"; import { captureXArticle, xArticleLinkFromCard } from "./xArticleCapture"; import { shootFromViewport } from "./viewportShot"; +import { shootXThread, type ThreadShotOptions, type ThreadShotResult } from "./xThreadShot"; // The post's own article, marked by the snapshot. const CAPTURE_SELECTOR = "[data-archilyzer-capture]"; @@ -201,16 +207,27 @@ export type XShotResult = XPostVerdict & { shot?: CapturedFile; // The X Article the post's card links to, when it does. articleLink?: XArticleLink; + // The thread shot, when one was asked for and the post rendered. + thread?: ThreadShotResult; +}; + +export type XShotOptions = { + // Shoot the post's own article (default true): false for a run that owes + // only the thread shot of a post shot before. + own?: boolean; + // The thread shot too (xThreadShot.ts), after the post's own. + thread?: Omit<ThreadShotOptions, "onLog" | "url"> | null; }; // One post's screenshot: load, read the page, open a sensitive cover, shoot // the post's own article. Writes `shot.png` into `dir` only for a post that -// rendered. +// rendered (and `shot-thread.png`, asked for, for a reply). export async function shootXPost( page: PageLike, id: string, dir: string, onLog?: (line: string) => void, + opts: XShotOptions = {}, ): Promise<XShotResult> { const url = xStatusUrl(id); try { @@ -244,6 +261,11 @@ export async function shootXPost( if (!rect || rect.width < 1 || rect.height < 1) { return { state: "error", error: "The post rendered with no size to shoot." }; } + const articleLink = xArticleLinkFromCard(snap.article?.articleHrefs); + if (opts.own === false) { + const thread = opts.thread ? await shootXThread(page, id, dir, { ...opts.thread, url, onLog }) : undefined; + return { ...verdict, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}) }; + } let png: Uint8Array; try { // From the window, the post made to fit it: a full-page capture resizes @@ -274,8 +296,9 @@ export async function shootXPost( await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, SHOT_FILENAME), png); const shot = await describeCapturedFile(dir, SHOT_FILENAME, url); - const articleLink = xArticleLinkFromCard(snap.article?.articleHrefs); - return { ...verdict, shot, ...(articleLink ? { articleLink } : {}) }; + // 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 } : {}) }; } export type MediaDownloadResult = @@ -318,6 +341,7 @@ export async function captureXPosts( media: input.media ?? true, force: input.force ?? false, articles: input.articles ?? true, + thread: input.thread ?? false, }; const now = deps.now ?? (() => new Date()); const outcomes: PostCaptureOutcome[] = []; @@ -348,7 +372,18 @@ export async function captureXPosts( : null; const articleOwedNow = work.article && !!articleLink && (!existing || work.shot || existing.state === "captured"); - if (!work.shot && !work.media && !articleOwedNow) { + // The thread shot: not for a post the archive says is no reply (no page + // load for it), nor for one a page already said is not there. + const arch = input.archived?.get(id); + let thread = work.thread ? undefined : existing?.thread; + let threadNone = work.thread ? undefined : existing?.threadNone; + let threadError = work.thread ? undefined : existing?.threadError; + let threadOwed = work.thread && (!existing || work.shot || existing.state === "captured"); + if (threadOwed && arch && arch.isReply === false && !arch.replyTo) { + threadNone = "Not a reply (the archive says so)."; + threadOwed = false; + } + if (!work.shot && !work.media && !articleOwedNow && !threadOwed && threadNone === existing?.threadNone) { onLog?.(`${id}: already captured (${existing?.state ?? "nothing asked for"}) — skipped.`); continue; } @@ -360,16 +395,31 @@ export async function captureXPosts( let error: string | undefined; let stop: string | undefined; - if (work.shot) { + if (work.shot || threadOwed) { await contact(); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); browser ??= await deps.openPage(); - const res = await shootXPost(browser.page, id, dir, onLog); - state = res.state; - sensitive = res.sensitive; - shot = res.shot; - error = res.error; + const res = await shootXPost(browser.page, id, dir, onLog, { + own: work.shot, + thread: threadOwed + ? { replyTo: arch?.replyTo ?? null, ownHandle: arch?.author, redact: threadRedactFor(input.threadRedact, id) } + : null, + }); + if (work.shot) { + state = res.state; + sensitive = res.sensitive; + shot = res.shot; + error = res.error; + } else if (res.state !== "captured") { + // A thread-only load the page refused: the post's record stands. + threadError = res.error ?? `The page showed the post as ${res.state}.`; + } stop = res.stop; + if (res.thread) { + if ("thread" in res.thread) thread = res.thread.thread; + else if ("none" in res.thread) threadNone = res.thread.none; + else threadError = res.thread.error; + } if (wanted.articles && !articleLink && res.articleLink) articleLink = res.articleLink; } @@ -440,6 +490,9 @@ export async function captureXPosts( mediaState, media, ...(article ? { article } : {}), + ...(thread ? { thread } : {}), + ...(threadNone && !thread ? { threadNone } : {}), + ...(threadError && !thread ? { threadError } : {}), ...(error ? { error } : {}), }; await writePostCapture(dir, record); @@ -451,12 +504,16 @@ export async function captureXPosts( ...(work.shot && captureAvailability(finalState) ? { availability: captureAvailability(finalState) } : {}), - files: (shot ? 1 : 0) + media.length + (article?.files.length ?? 0), + files: (shot ? 1 : 0) + (thread ? 1 : 0) + media.length + (article?.files.length ?? 0), ...(error ? { error } : {}), }); onLog?.( `${id}: ${finalState}${sensitive ? " (behind a sensitive-media cover)" : ""}` + (shot ? ", shot" : "") + + (thread && thread !== existing?.thread + ? `, thread shot (parent ${thread.parentId}${thread.redaction.applied ? ", its author blurred" : `, not blurred: ${thread.redaction.reason}`})` + : "") + + (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)}` : "") + (error ? ` — ${error}` : ""), @@ -480,6 +537,16 @@ export async function captureXPosts( } } +// The blur knob for one post: the run's, or the post's own entry of it. +export function threadRedactFor( + knob: PostCaptureInput["threadRedact"], + id: string, +): boolean | undefined { + if (knob === undefined || typeof knob === "boolean") return knob; + const v = knob[id]; + return typeof v === "boolean" ? v : undefined; +} + function describeArticle(a: ArticleCaptureRecord): string { if (a.state !== "captured") { return `article ${a.state}` + (a.error ? ` (${a.error})` : ""); diff --git a/common/social/xThreadShot.test.ts b/common/social/xThreadShot.test.ts @@ -0,0 +1,359 @@ +// A reply's thread shot, against fakes only: the parent picked from a +// recorded page snapshot, the blur's choice, the union box, and the run that +// shoots it beside the post's own shot. No browser, no network. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xThreadShot.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, stat } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { PageLike } from "./playwrightRuntime"; +import { readPostCapture, SHOT_FILENAME, THREAD_SHOT_FILENAME, writePostCapture } from "./postCapture"; +import { unionBox, VIEW_SCRIPT_MARKER, type ElementView } from "./viewportShot"; +import { + boxInShot, + MARK_PARENT_MARKER, + pickThreadParent, + REDACT_MARKER, + REDACTED_BOXES_MARKER, + redactScript, + shootXThread, + THREAD_SNAPSHOT_MARKER, + threadRedaction, + type ThreadArticle, + type ThreadSnapshot, +} from "./xThreadShot"; +import { captureXPosts, threadRedactFor, type XCaptureDeps, type XPostSnapshot } from "./xPostCapture"; + +const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 7]); +const THREAD_PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 8, 8]); + +const art = (id: string, handle: string, top: number, bottom: number, over: Partial<ThreadArticle> = {}): ThreadArticle => ({ + id, + handle, + name: handle, + verified: false, + top, + bottom, + ...over, +}); + +// The reply 2114214000653414579's page, as its archive says: a chain +// root -> 2114113495989907691 (Toothless2210) -> the reply, and a reply under it. +const CHAIN: ThreadSnapshot = { + own: 2, + articles: [ + art("2114053463176855722", "TheQuartering", 0, 400), + art("2114113495989907691", "Toothless2210", 400, 620), + art("2114214000653414579", "TheQuartering", 620, 900), + art("2114300000000000000", "someone", 900, 1100), + ], +}; + +// --- the parent ---------------------------------------------------------------- + +test("parent: the archive's in-reply-to id picks the IMMEDIATE parent out of a chain, not its root", () => { + const pick = pickThreadParent(CHAIN, { id: "2114113495989907691" }); + assert.ok("parent" in pick); + assert.equal(pick.index, 1); + assert.equal(pick.parent.handle, "Toothless2210"); + assert.equal(pick.from, "reply-to"); +}); + +test("parent: with no archive word, the post directly above the reply; never a reply listed under it", () => { + const pick = pickThreadParent(CHAIN, null); + assert.ok("parent" in pick); + assert.equal(pick.parent.id, "2114113495989907691"); + assert.equal(pick.from, "above"); + // The reply under the post is not a parent, even named by id. + const under = pickThreadParent(CHAIN, { id: "2114300000000000000" }); + assert.ok("none" in under); +}); + +test("parent: an archive id not on the page is no parent (the post above it would be a grandparent)", () => { + const gone = pickThreadParent(CHAIN, { id: "999" }); + assert.ok("none" in gone); + assert.match(gone.none, /999.*did not render/); +}); + +test("parent: a post with nothing above it is not a reply; an unmarked page has no own article", () => { + const alone: ThreadSnapshot = { own: 0, articles: [art("1", "a", 0, 300), art("2", "b", 300, 500)] }; + const none = pickThreadParent(alone, null); + assert.ok("none" in none); + assert.match(none.none, /Not a reply/); + assert.ok("none" in pickThreadParent({ own: -1, articles: CHAIN.articles }, null)); +}); + +// --- the blur ------------------------------------------------------------------ + +test("blur: a private author is blurred; a verified one or the reply's own author is not; the knob overrides", () => { + assert.deepEqual(threadRedaction({ parentHandle: "Toothless2210", parentVerified: false, ownHandle: "TheQuartering" }), { + redact: true, + reason: "private", + }); + assert.deepEqual(threadRedaction({ parentHandle: "elonmusk", parentVerified: true, ownHandle: "TheQuartering" }), { + redact: false, + reason: "verified", + }); + // A self-thread, whatever the case or the @. + assert.deepEqual(threadRedaction({ parentHandle: "thequartering", parentVerified: false, ownHandle: "@TheQuartering" }), { + redact: false, + reason: "self", + }); + assert.deepEqual(threadRedaction({ parentHandle: "x", parentVerified: false, ownHandle: "y" }, false), { redact: false, reason: "off" }); + assert.deepEqual(threadRedaction({ parentHandle: "x", parentVerified: true, ownHandle: "y" }, true), { redact: true, reason: "forced" }); + // No own handle known: not a self-thread. + assert.equal(threadRedaction({ parentHandle: "x", parentVerified: false }).redact, true); +}); + +test("blur: the knob per post — the run's boolean, or the post's own entry", () => { + assert.equal(threadRedactFor(undefined, "1"), undefined); + assert.equal(threadRedactFor(false, "1"), false); + assert.equal(threadRedactFor({ "1": false }, "1"), false); + assert.equal(threadRedactFor({ "1": false }, "2"), undefined); +}); + +test("blur: the page script blurs by profile link, case-insensitively, falling back to the User-Name block", () => { + const s = redactScript("@Toothless2210"); + assert.match(s, /"toothless2210"/); + assert.match(s, /Tweet-User-Avatar/); + assert.match(s, /User-Name/); + assert.match(s, /blur\(/); +}); + +test("boxes: the union of the parent's and the reply's boxes; a blurred box placed in the shot, its spread clipped", () => { + const parent = { x: 283, y: -200, width: 598, height: 220 }; + const own = { x: 283, y: 20, width: 598, height: 280 }; + assert.deepEqual(unionBox([parent, own]), { x: 283, y: -200, width: 598, height: 500 }); + assert.equal(unionBox([]), null); + const u = unionBox([parent, own])!; + // The avatar at the parent's top-left corner: its spread clipped at 0. + assert.deepEqual(boxInShot({ x: 299, y: -188, width: 40, height: 40 }, u, 36), { x: 0, y: 0, width: 92, height: 88 }); + assert.deepEqual(boxInShot({ x: 400, y: -150, width: 100, height: 20 }, u, 0), { x: 117, y: 50, width: 100, height: 20 }); +}); + +// --- the shot ------------------------------------------------------------------ + +type FakeThreadPage = PageLike & { calls: string[]; shots: unknown[] }; + +// A page holding CHAIN: the window measure answers the union of the parent's +// and the reply's boxes (viewport coordinates) when asked for both. +function threadPage(opts: { + snap?: ThreadSnapshot; + redacted?: { avatar: number; name: number; mention: number } | null; + post?: XPostSnapshot; + windowed?: boolean; +} = {}): FakeThreadPage { + const calls: string[] = []; + const shots: unknown[] = []; + const view: ElementView = { x: 283, y: 64, width: 598, height: 500, vw: 1280, vh: 900 }; + const ownView: ElementView = { x: 283, y: 284, width: 598, height: 280, vw: 1280, vh: 900 }; + return { + calls, + shots, + goto: async (url: string) => void calls.push(`goto ${url}`), + waitForSelector: async () => undefined, + waitForTimeout: async () => undefined, + on: () => {}, + ...(opts.windowed === false ? {} : { setViewportSize: async () => undefined }), + evaluate: async (script: string) => { + if (script.includes(VIEW_SCRIPT_MARKER)) { + if (opts.windowed === false) return null; + const both = script.includes("data-archilyzer-thread-parent"); + calls.push(both ? "measure-thread" : "measure-own"); + return both ? view : ownView; + } + if (script.includes(THREAD_SNAPSHOT_MARKER)) return opts.snap ?? CHAIN; + if (script.includes(MARK_PARENT_MARKER)) { + calls.push(`mark ${/\[(\d+)\]/.exec(script)?.[1]}`); + return true; + } + if (script.includes(REDACT_MARKER)) { + calls.push("redact"); + return opts.redacted === undefined ? { avatar: 1, name: 2, mention: 1 } : opts.redacted; + } + if (script.includes(REDACTED_BOXES_MARKER)) { + return { + parts: [ + { x: 283, y: 64, width: 598, height: 220 }, + { x: 283, y: 284, width: 598, height: 280 }, + ], + redacted: [ + { what: "avatar", box: { x: 299, y: 76, width: 40, height: 40 } }, + { what: "name", box: { x: 347, y: 76, width: 110, height: 20 } }, + ], + }; + } + if (script.includes("imgs.length")) return 0; + if (script.includes("b.click()")) return 0; + if (script.includes("article[data-testid")) { + calls.push("snapshot"); + return opts.post ?? { path: "/TheQuartering/status/2114214000653414579", text: "", article: { rect: { x: 283, y: 284, width: 598, height: 280 }, sensitive: false } }; + } + return undefined; + }, + screenshot: async (o?: unknown) => { + shots.push(o); + const clip = (o as { clip?: { height: number } })?.clip; + return clip && clip.height === 500 ? THREAD_PNG : PNG; + }, + }; +} + +test("shot: the union from the parent's top to the reply's bottom, the private author blurred first, the boxes recorded", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "2114214000653414579"); + const p = threadPage(); + const res = await shootXThread(p, "2114214000653414579", dir, { + replyTo: { id: "2114113495989907691", author: "Toothless2210" }, + url: "https://x.com/i/status/2114214000653414579", + }); + assert.ok("thread" in res, JSON.stringify(res)); + const t = res.thread; + assert.equal(t.name, THREAD_SHOT_FILENAME); + assert.equal(t.parentId, "2114113495989907691"); + assert.equal(t.parentHandle, "Toothless2210"); + assert.equal(t.parentVerified, false); + assert.equal(t.parentFrom, "reply-to"); + assert.equal(t.redaction.applied, true); + assert.equal(t.redaction.reason, "private"); + assert.deepEqual(t.redaction.boxes, [ + { what: "avatar", box: { x: 0, y: 0, width: 92, height: 88 } }, + { what: "name", box: { x: 28, y: 0, width: 182, height: 68 } }, + ]); + // Marked, blurred, THEN shot -- one viewport clip of the union. + assert.deepEqual(p.calls.filter((c) => c !== "measure-thread"), ["mark 1", "redact"]); + assert.deepEqual(p.shots, [{ type: "png", clip: { x: 283, y: 64, width: 598, height: 500 } }]); + assert.deepEqual(new Uint8Array(await readFile(path.join(dir, THREAD_SHOT_FILENAME))), THREAD_PNG); +}); + +test("shot: a verified parent is shot unblurred; a parent whose name cannot be found to blur gets no shot", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); + const verified = { ...CHAIN, articles: CHAIN.articles.map((a, i) => (i === 1 ? { ...a, verified: true } : a)) }; + const p = threadPage({ snap: verified }); + const res = await shootXThread(p, "1", dir, { replyTo: { id: "2114113495989907691" } }); + assert.ok("thread" in res); + assert.deepEqual(res.thread.redaction, { applied: false, reason: "verified", boxes: [] }); + assert.ok(!p.calls.includes("redact")); + + const dir2 = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); + const blind = threadPage({ redacted: { avatar: 1, name: 0, mention: 0 } }); + const refused = await shootXThread(blind, "1", dir2, { replyTo: { id: "2114113495989907691" } }); + assert.ok("error" in refused); + assert.match(refused.error, /could not be found to blur/); + assert.equal(blind.shots.length, 0); + await assert.rejects(stat(path.join(dir2, THREAD_SHOT_FILENAME))); +}); + +test("shot: with nothing above it there is no thread shot, and nothing is shot or blurred", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); + const p = threadPage({ snap: { own: 0, articles: [art("1", "TheQuartering", 0, 300)] } }); + const res = await shootXThread(p, "1", dir, {}); + assert.ok("none" in res); + assert.equal(p.shots.length, 0); + assert.ok(!p.calls.includes("redact")); +}); + +test("shot: a page that cannot be measured in its window shoots the union from a full-page clip", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); + const p = threadPage({ windowed: false }); + const inner = p.evaluate; + p.evaluate = async (s: string) => + s.includes("window.scrollX") && s.includes("data-archilyzer-thread-parent") && !s.includes(REDACTED_BOXES_MARKER) + ? [ + { x: 283, y: 1000, width: 598, height: 220 }, + { x: 283, y: 1220, width: 598, height: 280 }, + ] + : inner(s); + const res = await shootXThread(p, "1", dir, { replyTo: { id: "2114113495989907691" } }); + assert.ok("thread" in res, JSON.stringify(res)); + assert.deepEqual(p.shots, [{ type: "png", fullPage: true, clip: { x: 283, y: 1000, width: 598, height: 500 } }]); +}); + +// --- the run --------------------------------------------------------------------- + +function deps(p: PageLike, opened: { n: number }): XCaptureDeps { + return { + openPage: async () => { + opened.n++; + return { page: p, close: async () => {} }; + }, + downloadMedia: async () => ({ ok: true, files: [] }), + pauseMs: () => 5_000, + pause: async () => {}, + now: () => new Date("2026-10-27T12:00:00.000Z"), + }; +} + +test("run: thread on — the post's own shot, then the thread shot in the same load, both recorded", async () => { + const outDir = await mkdtemp(path.join(os.tmpdir(), "posts-media-")); + const p = threadPage(); + const opened = { n: 0 }; + const id = "2114214000653414579"; + const res = await captureXPosts( + { + ids: [id], + handle: "TheQuartering", + outDir, + media: false, + thread: true, + archived: new Map([[id, { text: "@Toothless2210 Well..", isReply: true, replyTo: { id: "2114113495989907691", author: "Toothless2210" }, author: "TheQuartering" }]]), + signal: new AbortController().signal, + }, + deps(p, opened), + ); + assert.deepEqual(res.outcomes, [{ id, state: "captured", availability: "available", files: 2 }]); + assert.equal(p.calls.filter((c) => c.startsWith("goto")).length, 1, "one page load for both shots"); + const rec = (await readPostCapture(path.join(outDir, id)))!; + assert.equal(rec.shot?.name, SHOT_FILENAME); + assert.equal(rec.thread?.name, THREAD_SHOT_FILENAME); + assert.equal(rec.thread?.parentId, "2114113495989907691"); + assert.equal(rec.thread?.redaction.applied, true); + // The own shot was taken before anything was blurred. + const firstShot = p.calls.indexOf("measure-own"); + assert.ok(firstShot >= 0 && firstShot < p.calls.indexOf("redact")); +}); + +test("run: a post shot before gets only its thread shot; a post the archive says is no reply gets no page load", async () => { + const outDir = await mkdtemp(path.join(os.tmpdir(), "posts-media-")); + const id = "2114214000653414579"; + const plain = "2091829122808832397"; + for (const pid of [id, plain]) { + await writePostCapture(path.join(outDir, pid), { + version: 1, id: pid, url: `https://x.com/i/status/${pid}`, capturedAt: "2026-10-20T00:00:00.000Z", state: "captured", + shot: { name: SHOT_FILENAME, bytes: 5, sha256: "old" }, mediaState: "none", media: [], + }); + } + const p = threadPage(); + const opened = { n: 0 }; + const res = await captureXPosts( + { + ids: [plain, id], + handle: "TheQuartering", + outDir, + thread: true, + archived: new Map([ + [plain, { text: "Up all night.", isReply: false }], + [id, { text: "@Toothless2210 Well..", isReply: true, replyTo: { id: "2114113495989907691" } }], + ]), + signal: new AbortController().signal, + }, + deps(p, opened), + ); + assert.deepEqual(res.outcomes.map((o) => [o.id, o.availability]), [ + [plain, undefined], + [id, undefined], + ]); + assert.equal(p.calls.filter((c) => c.startsWith("goto")).length, 1, "only the reply's page is opened"); + assert.ok(!p.calls.includes("measure-own"), "the post's own shot is not taken again"); + const r = (await readPostCapture(path.join(outDir, id)))!; + assert.equal(r.shot?.sha256, "old", "shot.png is kept"); + assert.equal(r.thread?.parentId, "2114113495989907691"); + const n = (await readPostCapture(path.join(outDir, plain)))!; + assert.match(n.threadNone ?? "", /Not a reply/); + // Settled: the next run owes neither. + const again = threadPage(); + await captureXPosts({ ids: [plain, id], handle: "TheQuartering", outDir, thread: true, signal: new AbortController().signal }, deps(again, { n: 0 })); + assert.equal(again.calls.length, 0); +}); diff --git a/common/social/xThreadShot.ts b/common/social/xThreadShot.ts @@ -0,0 +1,333 @@ +// A reply's THREAD SHOT: the post it answers, over the reply itself, as one +// picture -- `shot-thread.png` beside the post's own `shot.png`, never in its +// place (postCapture.ts has the layout; xPostCapture.ts calls this after the +// post's own shot, in the same page load). +// +// An X status page for a reply renders the conversation above the post: its +// parent, the parent's parent, up to the root, each an +// `article[data-testid="tweet"]`. The thread shot is cut to ONE of them, the +// IMMEDIATE parent -- the box from that article's top to the reply's bottom. +// Which article that is: the one whose status link is the id the archive +// says the reply answers (`replyTo.id`); with no archive word, the article +// directly above the reply. An archive id that is not on the page is no +// parent at all -- the article above it would be a grandparent (X draws a +// deleted or walled parent as a notice, not an article), and a shot that +// names the wrong post as the one replied to is worse than none. +// +// PRIVACY. The parent's author is often a private person replying to a +// public one. By default the shot blurs the parent's avatar, display name and +// @handle, and every link to their profile in the reply (the "Replying to" +// line and any @mention), unless the parent's author is verified or is the +// reply's own author (a self-thread). The blur is a CSS filter set on those +// elements in the page before the shot; their boxes are measured after it +// and recorded, in the shot's own pixels, in capture.json. A parent whose +// name cannot be found to blur gets NO thread shot: the blur is not skipped +// to get a picture. +// +// `redact: false` turns the blur off (an author the operator has judged +// public); `redact: true` blurs even a verified author. +// +// NOT VERIFIED AGAINST LIVE X beyond the one proof run the CHANGELOG names; +// the markers are X's as of 2026-10. + +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import type { PageLike } from "./playwrightRuntime"; +import { + describeCapturedFile, + THREAD_SHOT_FILENAME, + type RedactedBox, + type ThreadCaptureRecord, + type ThreadRedactionReason, +} from "./postCapture"; +import { shootFromViewport, unionBox } from "./viewportShot"; + +// The post's own article (xPostCapture.ts marks it) and its parent's. +export const OWN_SELECTOR = "[data-archilyzer-capture]"; +export const PARENT_SELECTOR = "[data-archilyzer-thread-parent]"; +const REDACTED_ATTR = "data-archilyzer-redacted"; + +export const THREAD_SNAPSHOT_MARKER = "__archilyzerThreadSnapshot"; +export const MARK_PARENT_MARKER = "__archilyzerMarkParent"; +export const REDACT_MARKER = "__archilyzerRedact"; +export const REDACTED_BOXES_MARKER = "__archilyzerBlurredBoxes"; + +// One article of the page as the thread snapshot reads it, in document order. +export type ThreadArticle = { + // Its status link (the one holding its <time>): /<handle>/status/<id>. + id?: string; + handle?: string; + // The display name: User-Name's first line. + name?: string; + verified: boolean; + // Its box's top and bottom, document coordinates. + top: number; + bottom: number; +}; + +export type ThreadSnapshot = { + // The post's own article among `articles`, or -1 when it is not marked. + own: number; + articles: ThreadArticle[]; +}; + +export const threadSnapshotScript = () => `(() => { + const ${THREAD_SNAPSHOT_MARKER} = true; + 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) => { + let id, handle; + for (const l of a.querySelectorAll('a[href*="/status/"]')) { + const m = /^\\/([^/?#]+)\\/status\\/(\\d+)/.exec(l.getAttribute("href") || ""); + if (m && l.querySelector("time")) { handle = m[1]; id = m[2]; break; } + } + const un = a.querySelector('[data-testid="User-Name"]'); + const name = un ? ((un.innerText || "").split("\\n")[0] || "").trim() : ""; + const verified = !!(un && un.querySelector('[data-testid="icon-verified"]')); + const r = a.getBoundingClientRect(); + return { id, handle, name: name || undefined, verified, top: r.top + window.scrollY, bottom: r.bottom + window.scrollY }; + }); + return { own, articles }; +})()`; + +export type ThreadParentPick = + | { index: number; parent: ThreadArticle; from: "reply-to" | "above" } + | { none: string }; + +// Which article is the reply's immediate parent. Pure: the snapshot and the +// archive's word in, the pick out. Only articles ABOVE the reply count (in +// document order before it, and ending above its top): X lists the replies to +// a post under it, as articles too. +export function pickThreadParent( + snap: ThreadSnapshot, + replyTo?: { id?: string } | null, +): ThreadParentPick { + if (snap.own < 0 || !snap.articles[snap.own]) return { none: "The post's own article is not on the page." }; + const own = snap.articles[snap.own]; + const above = snap.articles + .map((a, index) => ({ a, index })) + .filter(({ a, index }) => index < snap.own && a.bottom <= own.top + 2); + const want = replyTo?.id; + if (want) { + const hit = above.find(({ a }) => a.id === want); + if (hit) return { index: hit.index, parent: hit.a, from: "reply-to" }; + return { + none: + `The post it answers (${want}) did not render above it` + + (above.length ? " — the post above is another one of the thread" : "") + + " (deleted or walled?).", + }; + } + const last = above[above.length - 1]; + if (!last) return { none: "Not a reply: no post above it on the page." }; + if (!last.a.id) return { none: "The post above it has no status link to name it by." }; + return { index: last.index, parent: last.a, from: "above" }; +} + +// Whether the parent's author is blurred, and why. Pure. +export function threadRedaction( + p: { parentHandle?: string; parentVerified: boolean; ownHandle?: string }, + redact?: boolean, +): { redact: boolean; reason: ThreadRedactionReason } { + if (redact === false) return { redact: false, reason: "off" }; + if (redact === true) return { redact: true, reason: "forced" }; + const same = (a?: string, b?: string) => !!a && !!b && a.replace(/^@/, "").toLowerCase() === b.replace(/^@/, "").toLowerCase(); + if (same(p.parentHandle, p.ownHandle)) return { redact: false, reason: "self" }; + if (p.parentVerified) return { redact: false, reason: "verified" }; + return { redact: true, reason: "private" }; +} + +export const markParentScript = (index: number) => `(() => { + const ${MARK_PARENT_MARKER} = true; + for (const el of document.querySelectorAll("[data-archilyzer-thread-parent]")) el.removeAttribute("data-archilyzer-thread-parent"); + const a = document.querySelectorAll('article[data-testid="tweet"]')[${Math.floor(index)}]; + if (!a) return false; + a.setAttribute("data-archilyzer-thread-parent", ""); + return true; +})()`; + +// The blur: the parent's avatar, every link to its author's profile (X draws +// the display name and the @handle as two), or -- when it finds no such link +// -- the whole User-Name block; and every link to that profile in the reply. +// Returns how many of each it set. +export const redactScript = (handle: string, px = 14) => `(() => { + const ${REDACT_MARKER} = true; + const handle = ${JSON.stringify(handle.replace(/^@/, "").toLowerCase())}; + const parent = document.querySelector(${JSON.stringify(PARENT_SELECTOR)}); + const own = document.querySelector(${JSON.stringify(OWN_SELECTOR)}); + if (!parent) return null; + const blur = (el, what, amount) => { + el.setAttribute("${REDACTED_ATTR}", what); + el.style.setProperty("filter", "blur(" + amount + "px)", "important"); + }; + const toProfile = (root) => Array.from(root.querySelectorAll("a[href]")).filter((l) => { + const h = (l.getAttribute("href") || "").split(/[?#]/)[0].toLowerCase(); + return h === "/" + handle || h === "https://x.com/" + handle || h === "https://twitter.com/" + handle; + }); + const n = { avatar: 0, name: 0, mention: 0 }; + for (const el of parent.querySelectorAll('[data-testid="Tweet-User-Avatar"]')) { blur(el, "avatar", ${px + 4}); n.avatar++; } + // A profile link inside the avatar is the avatar's, already blurred. + for (const l of toProfile(parent)) { + if (l.closest('[data-testid="Tweet-User-Avatar"]')) continue; + blur(l, "name", ${px}); n.name++; + } + if (n.name === 0) { + const un = parent.querySelector('[data-testid="User-Name"]'); + if (un) { blur(un, "user-name", ${px}); n.name++; } + } + if (own) for (const l of toProfile(own)) { blur(l, "mention", ${px}); n.mention++; } + return n; +})()`; + +// The blurred boxes and the thread's union box, in viewport coordinates, read +// together so the one is placed in the other. +export const redactedBoxesScript = () => `(() => { + const ${REDACTED_BOXES_MARKER} = true; + const rect = (el) => { const r = el.getBoundingClientRect(); return { x: r.left, y: r.top, width: r.width, height: r.height }; }; + const parent = document.querySelector(${JSON.stringify(PARENT_SELECTOR)}); + const own = document.querySelector(${JSON.stringify(OWN_SELECTOR)}); + if (!parent || !own) return null; + return { + parts: [parent, own].map(rect), + redacted: Array.from(document.querySelectorAll("[${REDACTED_ATTR}]")).map((el) => ({ what: el.getAttribute("${REDACTED_ATTR}"), box: rect(el) })), + }; +})()`; + +type Box = { x: number; y: number; width: number; height: number }; + +// A blurred box in the shot's pixels: offset by the union's top-left, the +// CSS blur's spread added round it, and clipped to the shot. +export function boxInShot(box: Box, union: Box, spread = 0): Box { + const x0 = Math.max(0, Math.floor(box.x - union.x - spread)); + const y0 = Math.max(0, Math.floor(box.y - union.y - spread)); + const x1 = Math.min(Math.ceil(union.width), Math.ceil(box.x - union.x + box.width + spread)); + const y1 = Math.min(Math.ceil(union.height), Math.ceil(box.y - union.y + box.height + spread)); + return { x: x0, y: y0, width: Math.max(0, x1 - x0), height: Math.max(0, y1 - y0) }; +} + +// Let the parent's images load too, so the shot is not of grey boxes. +const PARENT_IMAGES_SCRIPT = `(() => { + const root = document.querySelector(${JSON.stringify(PARENT_SELECTOR)}) || document; + const imgs = Array.from(root.querySelectorAll("img")).filter((i) => !i.complete); + return Promise.all(imgs.map((i) => new Promise((r) => { + i.addEventListener("load", r, { once: true }); + i.addEventListener("error", r, { once: true }); + setTimeout(r, 5000); + }))).then(() => imgs.length); +})()`; + +const DOC_UNION_SCRIPT = `(() => { + const els = [${JSON.stringify(PARENT_SELECTOR)}, ${JSON.stringify(OWN_SELECTOR)}].map((s) => document.querySelector(s)); + if (els.some((e) => !e)) return null; + return els.map((e) => { const r = e.getBoundingClientRect(); return { x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height }; }); +})()`; + +export type ThreadShotOptions = { + // What the archive says the post answers, when it says. + replyTo?: { id?: string; author?: string } | null; + // The reply's own author (for a self-thread), when the caller knows it; + // else read off the page. + ownHandle?: string; + // undefined: the rule (blur a private author); false: off; true: always. + redact?: boolean; + url?: string; + onLog?: (line: string) => void; +}; + +export type ThreadShotResult = + | { thread: ThreadCaptureRecord } + | { none: string } + | { error: string }; + +// The CSS blur's spread beyond an element's box, as recorded (≈ 2σ of the +// strongest blur set). +const BLUR_SPREAD = 36; + +// The thread shot of the post whose own article is marked. The page is the +// one the post was just shot in; what is blurred here stays blurred until the +// page is left. +export async function shootXThread( + page: PageLike, + id: string, + dir: string, + opts: ThreadShotOptions = {}, +): Promise<ThreadShotResult> { + const { onLog } = opts; + const snap = (await page.evaluate(threadSnapshotScript()).catch(() => null)) as ThreadSnapshot | null; + if (!snap || !Array.isArray(snap.articles)) return { error: "The page could not be read for the thread." }; + const pick = pickThreadParent(snap, opts.replyTo); + if ("none" in pick) return { none: pick.none }; + const { parent } = pick; + const ownHandle = opts.ownHandle ?? snap.articles[snap.own]?.handle; + const choice = threadRedaction( + { parentHandle: parent.handle ?? opts.replyTo?.author, parentVerified: parent.verified, ownHandle }, + opts.redact, + ); + if (!(await page.evaluate(markParentScript(pick.index)).catch(() => false))) { + return { error: "The parent's article vanished before it could be marked." }; + } + if (choice.redact) { + const handle = parent.handle ?? opts.replyTo?.author; + if (!handle) return { error: "The parent's author has no handle to blur by; no thread shot." }; + const n = (await page.evaluate(redactScript(handle)).catch(() => null)) as + | { avatar: number; name: number; mention: number } + | null; + if (!n || n.name === 0) { + return { error: "The parent's name could not be found to blur; no thread shot." }; + } + onLog?.( + `${id}: blurring @${handle} (${choice.reason}): ${n.avatar} avatar, ${n.name} name, ${n.mention} mention(s).`, + ); + } else { + onLog?.(`${id}: the parent's author @${parent.handle ?? "?"} is not blurred (${choice.reason}).`); + } + await page.evaluate(PARENT_IMAGES_SCRIPT).catch(() => {}); + + let png: Uint8Array; + try { + const fromWindow = await shootFromViewport(page, { selector: [PARENT_SELECTOR, OWN_SELECTOR], onLog }); + if (fromWindow && "error" in fromWindow) return { error: `The thread could not be shot: ${fromWindow.error}` }; + if (fromWindow) png = fromWindow.png; + else { + const parts = (await page.evaluate(DOC_UNION_SCRIPT).catch(() => null)) as Box[] | null; + const u = parts ? unionBox(parts) : null; + if (!u || u.width < 1 || u.height < 1) return { error: "The thread rendered with no size to shoot." }; + onLog?.(`${id}: shooting the thread from a full-page capture.`); + png = await page.screenshot({ + type: "png", + fullPage: true, + clip: { x: Math.max(0, Math.floor(u.x)), y: Math.max(0, Math.floor(u.y)), width: Math.ceil(u.width), height: Math.ceil(u.height) }, + }); + } + } catch (err) { + return { error: `The thread's screenshot failed: ${((err as Error)?.message ?? String(err)).split("\n")[0]}` }; + } + + // Where the blur landed, in the shot's own pixels. The window shot's + // layout is the one measured now (shootFromViewport checks it held still). + let boxes: RedactedBox[] = []; + if (choice.redact) { + const read = (await page.evaluate(redactedBoxesScript()).catch(() => null)) as + | { parts: Box[]; redacted: { what: RedactedBox["what"]; box: Box }[] } + | null; + const u = read ? unionBox(read.parts) : null; + if (u) { + boxes = read!.redacted.map((r) => ({ what: r.what, box: boxInShot(r.box, u, BLUR_SPREAD) })); + } + } + + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, THREAD_SHOT_FILENAME), png); + const file = await describeCapturedFile(dir, THREAD_SHOT_FILENAME, opts.url); + return { + thread: { + ...file, + parentId: parent.id!, + ...(parent.handle ? { parentHandle: parent.handle } : {}), + ...(parent.name ? { parentAuthor: parent.name } : {}), + parentVerified: parent.verified, + parentFrom: pick.from, + redaction: { applied: choice.redact, reason: choice.reason, boxes }, + }, + }; +} diff --git a/editor/app/api/ops/capture-posts/route.test.ts b/editor/app/api/ops/capture-posts/route.test.ts @@ -72,6 +72,22 @@ test("both halves off is nothing to do unless the articles are asked for by name assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); }); +test("thread: a boolean; threadRedact a boolean or { id: boolean }; the thread shots alone are a run", async () => { + const bad = await post({ slug: SLUG, ids: ["111"], thread: "yes" }); + assert.equal(bad.status, 400); + assert.match(bad.error, /"thread" must be a boolean/); + for (const threadRedact of ["no", [false], { "111": "off" }]) { + const res = await post({ slug: SLUG, ids: ["111"], thread: true, threadRedact }); + assert.equal(res.status, 400, JSON.stringify(threadRedact)); + assert.match(res.error, /"threadRedact"/); + } + // Asked for by name, past the nothing-to-do check to the next refusal. + const stray = await post({ slug: SLUG, ids: ["999"], shots: false, media: false, thread: true, threadRedact: { "999": false } }); + assert.equal(stray.status, 400); + assert.equal(stray.error, "1 id(s) not in demo-x's posts archive: 999"); + assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); +}); + // Moved from e2e/ops-api.spec.ts (release 19, A2b): nothing below reaches X — // every case is refused before a job exists. async function channel(slug: string, config: Record<string, unknown>): Promise<void> { diff --git a/editor/app/api/ops/capture-posts/route.ts b/editor/app/api/ops/capture-posts/route.ts @@ -10,15 +10,20 @@ import { export const dynamic = "force-dynamic"; -// POST { slug, ids, shots?, media?, force?, articles?, queueKey? } -> { ok: true, jobId } +// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, 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 // the channel's posts-media/<id>/. A post that links to an X Article (its // archived text, or its card) also gets the article — read into article.json, // article.md and article.png, with its images — unless `articles` is false -// (default true). Posts already captured are skipped unless `force`. The job -// runs on the platform's queue, as a post fetch does. +// (default true). An X reply also gets its thread shot -- the post it answers +// over it, shot-thread.png -- with `thread` (default: the channel's +// `postCaptureThread`); its parent's author is blurred unless verified or the +// reply's own, and `threadRedact` (false: off, true: always, or +// { "<id>": bool } per post) overrides that. Posts already captured are +// skipped unless `force`. The job runs on the platform's queue, as a post +// fetch does. // // Every refusal is the action's own sentence: both halves off (an // articles-only run names `articles: true`), a channel that @@ -27,7 +32,7 @@ export const dynamic = "force-dynamic"; export async function POST(request: Request) { return ops( request, - ["slug", "ids", "shots", "media", "force", "articles", "queueKey"], + ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "queueKey"], async (body) => { const slug = reqSlug(body, "slug"); return jobResponse( @@ -39,6 +44,7 @@ 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 }, ), ); }, diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx @@ -47,6 +47,9 @@ export type SocialChannelState = { olderStatus: string; // The channel's platform; "xenforo" is a forum thread. platform?: string; + // X channels: the Capture posts thread-shot option's default (the + // channel's `postCaptureThread`); absent elsewhere, and the option with it. + captureThread?: boolean; // A forum thread's browser session (its host's profile), when it is one. forumSession?: ForumSessionStatus; // An X search channel (release 38): its query and where its walk stands. @@ -581,7 +584,7 @@ export function SocialChannelPanel({ </section> )} - <SocialPostTools slug={slug} /> + <SocialPostTools slug={slug} captureThread={state.captureThread} /> <p className="text-xs text-muted-foreground"> Posts are indexed into the search corpus by the normal build — there is diff --git a/editor/app/channels/[slug]/components/SocialPostTools.tsx b/editor/app/channels/[slug]/components/SocialPostTools.tsx @@ -8,13 +8,19 @@ import { importPostAction } from "../importPostAction"; // A posts channel's ops-only operations as buttons (release 32): one post // imported by its URL (`import-post`), and specific posts captured — a -// screenshot and their media (`capture-posts`). -export function SocialPostTools({ slug }: { slug: string }) { +// screenshot and their media (`capture-posts`). On an X channel +// (`captureThread` given: the channel's default), a reply's thread shot too -- +// the post it answers over it, its author blurred unless verified or the +// reply's own, or not blurred when the operator unticks the blur. +export function SocialPostTools({ slug, captureThread }: { slug: string; captureThread?: boolean }) { const [url, setUrl] = useState(""); const [ids, setIds] = useState(""); const [shots, setShots] = useState(true); const [media, setMedia] = useState(true); const [force, setForce] = useState(false); + const [thread, setThread] = useState(captureThread ?? false); + const [blur, setBlur] = useState(true); + const x = captureThread !== undefined; const idList = ids.split(/[\s,]+/).filter(Boolean); const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono"; return ( @@ -47,9 +53,25 @@ export function SocialPostTools({ slug }: { slug: string }) { <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} /> Again, if captured </label> + {x && ( + <label className="flex items-center gap-2" title="A reply: the post it answers over it, as shot-thread.png beside shot.png"> + <input type="checkbox" checked={thread} onChange={(e) => setThread(e.target.checked)} /> + Thread shot (replies) + </label> + )} + {x && thread && ( + <label className="flex items-center gap-2" title="Blur the replied-to author's avatar, name and handle unless they are verified or the reply's own author"> + <input type="checkbox" checked={blur} onChange={(e) => setBlur(e.target.checked)} /> + Blur the replied-to author + </label> + )} </div> <StreamActionLog - trigger={() => capturePostsAction(slug, idList, undefined, shots, media, force)} + trigger={() => + capturePostsAction(slug, idList, undefined, shots, media, force, undefined, x + ? { thread, ...(thread && !blur ? { threadRedact: false } : {}) } + : {}) + } cancelAction={cancelJobAction} buttonLabel={`Capture ${idList.length || ""} post${idList.length === 1 ? "" : "s"}`.replace(" ", " ")} runningLabel="Capturing…" diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -274,6 +274,8 @@ export default async function ChannelDetailPage({ handle: config.socialHandle ?? slug, accountUrl: config.url, platform: config.platform, + // X only: the capture's thread-shot option, at the channel's default. + ...(config.platform === "twitter" ? { captureThread: config.postCaptureThread ?? false } : {}), ...(forumSession ? { forumSession } : {}), ...(xSearch ? { diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -47,8 +47,10 @@ import { capturePostsProblem, NOTHING_TO_CAPTURE, nothingToCapture, + parseThreadRedact, strayCaptureIds, strayIdsRefusal, + type ThreadRedactKnob, } from "yt-dlp-transcript-common/controller/capturePosts"; import { readPostFetchState, @@ -297,7 +299,10 @@ export async function fetchPostsAction( // exists: nothing asked for, no ids, a channel that is not social, a fetcher // that cannot capture, or an id that is not in the channel's posts archive // (named). Posts already captured are skipped unless `force`. A post that -// links to an X Article gets the article too unless `articles` is false. +// 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. export async function capturePostsAction( slug: string, ids: string[], @@ -306,8 +311,13 @@ export async function capturePostsAction( media?: boolean, force?: boolean, articles?: boolean, + more: { thread?: boolean; threadRedact?: ThreadRedactKnob } = {}, ): Promise<StreamActionResult> { - if (nothingToCapture({ shots, media, articles })) return { ok: false, error: NOTHING_TO_CAPTURE }; + const { thread } = 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 }; const wanted = [...new Set(ids)]; if (wanted.length === 0) return { ok: false, error: "No post ids to capture." }; const paths = getPaths(); @@ -341,7 +351,11 @@ export async function capturePostsAction( spec: { kind: "capture-posts", slug, - params: { queueKey, ids: wanted, shots, media, force, articles }, + params: { + queueKey, ids: wanted, shots, media, force, articles, + ...(thread !== undefined ? { thread } : {}), + ...(threadRedact !== undefined ? { threadRedact } : {}), + }, }, fn: async (onLog, signal, _progress, ctx) => { const result = await capturePosts({ @@ -353,6 +367,8 @@ export async function capturePostsAction( media, force, articles, + thread, + threadRedact, onLog, signal, drain: ctx.drainSignal, diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -439,6 +439,11 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { bool(p.media), bool(p.force), bool(p.articles), + { + thread: bool(p.thread), + // A boolean or { id: boolean }; the action refuses any other shape. + threadRedact: p.threadRedact as boolean | Record<string, boolean> | undefined, + }, ); }, "download-missing-subs": (spec) => { diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1449,7 +1449,13 @@ export function usage() { ' 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. Paced like a post fetch, on its queue.', + ' 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; {"<id>": false} sets it per post. 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" |',