Archilyzer · Source

archilyzer

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

commit 9ede6e8fc8ac6381089e7478e328d288af1770e0
parent 7d7a2c3a35b01d10493fc2ef9800d1821780e4c3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 13:10:33 -0400

wayback pages: page records' shots and images, and how a capture is shown

capture-posts on a Wayback pages channel renders each record's capture
(`if_`, no toolbar) in a headless Chromium with JavaScript off and nothing
but the archive reachable, inside the Wayback client's chain and gap: a
whole-page record shot full page to 8000 px, a split record clipped to its
own element (located by the id the extractor used), its images saved through
their own `im_` URLs. Runs on platform:archive.org; nothing written to the
availability sidecar.

lib/waybackPages/view.ts + PageCaptureFacts: the kind, the capture date,
"Original (may be gone)" + "Wayback Machine copy, <date>", the version list,
no content and the extractor-fallback note — on a report site's moment page
and citation card (compose fills originalLabel/downloads for a page record)
and in the post modal.

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

Diffstat:
Acommon/components/PageCaptureFacts.tsx | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/components/PostModal.tsx | 34++++++++++++++++++++++++++--------
Mcommon/components/citations/CitationCard.tsx | 7++++++-
Mcommon/components/report/MomentArticle.tsx | 10++++++++--
Mcommon/controller/capturePosts.test.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/capturePosts.ts | 69++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/archiveOrgClient.ts | 18++++++++++++++++++
Mcommon/lib/report/views.ts | 4++++
Mcommon/lib/wayback.ts | 16++++++++++++++++
Mcommon/lib/waybackClient.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/view.test.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/view.ts | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/publish/composeReports.ts | 10+++++++++-
Mcommon/social/postCapture.ts | 6++++++
Acommon/social/waybackPageCapture.test.ts | 287+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/waybackPageCapture.ts | 578++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/README.md | 2+-
Mcommon/testing/web/fakeWayback.d.mts | 8+++++++-
Mcommon/testing/web/fakeWayback.mjs | 52+++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/app/channels/[slug]/socialActions.ts | 18++++++++++++------
20 files changed, 1526 insertions(+), 22 deletions(-)

diff --git a/common/components/PageCaptureFacts.tsx b/common/components/PageCaptureFacts.tsx @@ -0,0 +1,68 @@ +// WHAT A PAGE RECORD'S CAPTURE IS (release 37 S4), from its view +// (lib/waybackPages/view.ts): the kind and capture date, a capture that holds +// no content, the extractor-fallback note, the version list, and — unless the +// surface prints them itself — "Original (may be gone)" and "Wayback Machine +// copy, <date>". The same words on a report site's moment page, the corpus +// viewer's post modal and the editor's Wayback pages panel. + +import { pageCaptureLine, pageVersionsLine, PAGE_NO_CONTENT_LINE, type PageCaptureView } from "../lib/waybackPages/view"; + +const link = "underline underline-offset-2"; + +export function PageCaptureFacts({ + view, + links = true, + className = "", +}: { + view: PageCaptureView; + // Print the original and the Wayback copy (off where the surface's own + // links line carries them). + links?: boolean; + className?: string; +}) { + return ( + <div data-page-capture={view.kind} className={`flex flex-col gap-1 text-sm ${className}`}> + <p className="font-mono text-xs text-muted-foreground">{pageCaptureLine(view)}</p> + {view.noContent && ( + <p data-page-no-content="" className="text-muted-foreground"> + {PAGE_NO_CONTENT_LINE} + </p> + )} + {view.fallbackNote && ( + <p data-page-fallback="" className="text-xs text-muted-foreground"> + {view.fallbackNote} + </p> + )} + {links && ( + <p className="flex flex-wrap gap-x-4 gap-y-1"> + <a href={view.links.original.url} target="_blank" rel="noreferrer" className={link}> + {view.links.original.label} + </a> + <a href={view.links.copy.url} target="_blank" rel="noreferrer" className={link}> + {view.links.copy.label} + </a> + </p> + )} + {view.versions && ( + <div data-page-versions={view.versions.count} className="flex flex-col gap-1"> + <p className="text-muted-foreground">{pageVersionsLine(view.versions)}</p> + <ol className="flex flex-wrap gap-x-3 gap-y-1 font-mono text-xs"> + {view.versions.captures.map((c) => ( + <li key={c.id}> + {c.current ? ( + <span aria-current="true" className="font-semibold"> + {c.date} + </span> + ) : ( + <a href={c.waybackUrl} target="_blank" rel="noreferrer" className={link}> + {c.date} + </a> + )} + </li> + ))} + </ol> + </div> + )} + </div> + ); +} diff --git a/common/components/PostModal.tsx b/common/components/PostModal.tsx @@ -15,6 +15,8 @@ import { Button } from "./ui/button"; import { useUrlParams, writeUrlParams } from "./urlState"; import { fetchPost, fetchThread } from "./postsCache"; import { postPlatformLabel, type Post } from "../lib/posts"; +import { pageCaptureView } from "../lib/waybackPages/view"; +import { PageCaptureFacts } from "./PageCaptureFacts"; function formatWhen(iso: string): string { const ms = Date.parse(iso); @@ -168,6 +170,9 @@ function PostBody({ }) { const links = useMemo(() => post.links ?? [], [post.links]); const capturedMedia = capture?.media.length ?? 0; + // A page record (a Wayback capture, release 37 S4): what the capture is, + // and the original named as possibly gone beside the Wayback copy. + const page = useMemo(() => pageCaptureView(post), [post]); return ( <article data-post-id={post.id} @@ -215,6 +220,8 @@ function PostBody({ {capture && <PostCapturePanel capture={capture} />} + {page && !compact && <PageCaptureFacts view={page} links={false} className="mt-2" />} + {post.forum?.threadTitle && !compact && ( <p className="mt-1 text-xs text-muted-foreground"> In thread: {post.forum.threadTitle} @@ -263,14 +270,25 @@ function PostBody({ )} <footer className="mt-2 flex flex-wrap items-center gap-x-3 text-xs text-muted-foreground"> - <a - href={post.url} - target="_blank" - rel="noopener noreferrer" - className="underline" - > - {post.isDeleted ? "Original (deleted)" : "Open original"} - </a> + {page ? ( + <> + <a href={page.links.original.url} target="_blank" rel="noopener noreferrer" className="underline"> + {post.isDeleted ? "Original (deleted)" : page.links.original.label} + </a> + <a href={page.links.copy.url} target="_blank" rel="noopener noreferrer" className="underline"> + {page.links.copy.label} + </a> + </> + ) : ( + <a + href={post.url} + target="_blank" + rel="noopener noreferrer" + className="underline" + > + {post.isDeleted ? "Original (deleted)" : "Open original"} + </a> + )} {post.engagement?.likes != null && ( <span>{post.engagement.likes} likes</span> )} diff --git a/common/components/citations/CitationCard.tsx b/common/components/citations/CitationCard.tsx @@ -178,7 +178,12 @@ function PostLinks({ c }: { c: PostCitationView }) { <a href={c.href} className={linkClass}> Open post </a> - {c.record.originalUrl && <ExternalA href={c.record.originalUrl}>Original</ExternalA>} + {c.record.originalUrl && <ExternalA href={c.record.originalUrl}>{c.record.originalLabel ?? "Original"}</ExternalA>} + {c.record.downloads?.map((d) => ( + <ExternalA key={d.url} href={d.url}> + {d.label} + </ExternalA> + ))} </> ); } diff --git a/common/components/report/MomentArticle.tsx b/common/components/report/MomentArticle.tsx @@ -4,6 +4,7 @@ import { formatTimestamp } from "../../lib/vtt"; import { CITATION_KIND_LABELS, spanLabel, type MomentPageView, type RecordView } from "../../lib/report/views"; import { ExternalLinkText, Eyebrow, dateLabel, textLink } from "./parts"; import { SOURCE_GONE_LABELS } from "../../lib/sourceGone"; +import { PageCaptureFacts } from "../PageCaptureFacts"; // ONE CITED MOMENT, from its view (common/lib/report/views.ts): a span's // self-hosted evidence clip (video, or audio with its poster) or a post's @@ -87,10 +88,15 @@ export default function MomentArticle({ // eslint-disable-next-line @next/next/no-img-element -- a published file of unknown size; the export serves images unoptimized <img src={view.post.shot} - alt={`Screenshot of the post${view.post.author ? ` by ${view.post.author}` : ""}`} + alt={ + view.post.page + ? `Screenshot of the Wayback Machine copy, ${view.post.page.captureDate}` + : `Screenshot of the post${view.post.author ? ` by ${view.post.author}` : ""}` + } className="w-full max-w-xl rounded-lg border border-border" /> )} + {view.post?.page && <PageCaptureFacts view={view.post.page} links={false} />} <div className="flex flex-col gap-2"> <blockquote className="border-l-4 border-brand pl-4 text-lg leading-relaxed text-foreground"> @@ -153,7 +159,7 @@ export default function MomentArticle({ <ExternalLinkText href={r.originalUrl}> {isSpan && view.start !== undefined ? `${r.originalLabel ?? "Original"} at ${formatTimestamp(view.start)}` - : "Original post"} + : (r.originalLabel ?? "Original post")} </ExternalLinkText> )} {r.downloads?.map((d) => ( diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts @@ -217,3 +217,75 @@ test("the articles: on by default, refused alone only when not asked for by name assert.equal((await run("demo-x", ["111"], { shots: false, media: false, articles: true })).ok, true); assert.equal(calls[0].articles, true); }); + +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 }); + await writeFile( + path.join(root, "config.json"), + JSON.stringify({ + handling: "transcribe", + sourceKind: "social", + platform: "webpage", + name: "Pages", + url: "https://web.archive.org/web/*/blog.example/*", + wayback: { targets: [{ url: "https://blog.example/", match: "prefix" }] }, + }), + ); + const page = { + originalUrl: "https://blog.example/a.html", + captureTs: "20140305120000", + waybackUrl: "https://web.archive.org/web/20140305120000/https://blog.example/a.html", + rawUrl: "https://web.archive.org/web/20140305120000id_/https://blog.example/a.html", + kind: "generic" as const, + extractor: "generic", + extractorVersion: 1, + }; + await writePosts(root, [ + { + id: "20140305120000-0123456789ab", + slug: "demo-pages/20140305120000-0123456789ab", + channelSlug: "demo-pages", + author: "blog.example", + createdAt: "2014-03-05T12:00:00.000Z", + uploadDate: "20140305", + text: "A page.", + url: page.originalUrl, + platform: "webpage", + isReply: false, + isRepost: false, + links: [], + page, + }, + ]); + const loads: string[] = []; + const res = await run("demo-pages", ["20140305120000-0123456789ab"], { + media: false, + pageDeps: { + openPage: async () => ({ + page: { + goto: async (url: string) => { + loads.push(url); + return { status: () => 200 }; + }, + waitForSelector: async () => ({}), + waitForTimeout: async () => {}, + evaluate: async (fn: string) => (fn.includes("scrollHeight") ? { width: 1280, height: 900 } : 0), + on: () => {}, + screenshot: async () => new Uint8Array([137, 80, 78, 71]), + }, + close: async () => {}, + }), + paced: (fn: () => Promise<unknown>) => fn(), + fetchFile: async () => null, + }, + }); + assert.equal(res.ok, true, res.error); + assert.deepEqual(res.outcomes.map((o) => o.state), ["captured"]); + assert.deepEqual(loads, ["https://web.archive.org/web/20140305120000if_/https://blog.example/a.html"]); + assert.deepEqual(await readPostAvailability(root), {}); + assert.equal( + (await run("demo-pages", ["nope"])).error, + "1 id(s) not in demo-pages's posts archive: nope", + ); +}); diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -17,7 +17,7 @@ import path from "node:path"; import { readChannelConfig } from "./channels"; import type { Paths } from "../lib/paths"; -import type { PostAvailability } from "../lib/posts"; +import type { Post, PostAvailability } from "../lib/posts"; import { isSocialChannel } from "../lib/channelConfig"; import { alwaysCookies, @@ -38,6 +38,12 @@ import { type SocialFetcher, } from "../social/fetchers"; import { postsMediaDir } from "../social/postCapture"; +import { isWaybackPagesChannel } from "../lib/waybackPages/config"; +import { + captureWaybackPageRecords, + liveWaybackPageCaptureDeps, + type WaybackPageCaptureDeps, +} from "../social/waybackPageCapture"; import "../social/blueskyFetcher"; import "../social/xGalleryDlFetcher"; import "../social/xPlaywrightFetcher"; @@ -64,6 +70,9 @@ export type CapturePostsOptions = { signal?: AbortSignal; // The job's drain: stop between posts. drain?: AbortSignal; + // A Wayback pages channel's render and archive (tests; default the + // process's Wayback client and a headless Chromium). + pageDeps?: WaybackPageCaptureDeps; }; export type CapturePostsResult = { @@ -126,6 +135,10 @@ export async function capturePosts( if (!config) return fail(`No such channel: ${slug}`); if (!isSocialChannel(config)) return fail(`${slug} is not a social channel.`); + // 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); + const accountUrl = config.url ?? ""; const fetcher = resolveSocialFetcher(config.postFetcher, accountUrl); const problem = capturePostsProblem(fetcher); @@ -257,3 +270,57 @@ export async function capturePosts( } return { ok: true, outcomes: result.outcomes }; } + +// capture-posts on a Wayback pages channel: the records' shots from their +// captures' replays (social/waybackPageCapture.ts). Only ids in the channel's +// posts archive; nothing is recorded in the availability sidecar (a capture +// says nothing about the original — release 37 S5 owns that). +async function captureChannelPageRecords( + opts: CapturePostsOptions, + channelRoot: string, + ids: string[], +): Promise<CapturePostsResult> { + const log = (line: string) => opts.onLog?.(line); + const wanted = new Set(ids); + const records = new Map<string, Post>(); + for (const p of await readAllPosts(channelRoot)) if (wanted.has(p.id)) records.set(p.id, p); + const stray = ids.filter((id) => !records.has(id)); + if (stray.length) return { ok: false, outcomes: [], error: strayIdsRefusal(opts.slug, stray) }; + log( + `Capturing ${ids.length} page record(s) of ${opts.slug} from the Wayback Machine:` + + [opts.shots === false ? "" : " screenshot", opts.media === false ? "" : " images"].join("") + + (opts.force ? ", again where already captured" : "") + + ".", + ); + const controller = new AbortController(); + const signal = opts.signal ?? controller.signal; + let result; + try { + result = await captureWaybackPageRecords( + { + ids, + records, + outDir: postsMediaDir(channelRoot), + shots: opts.shots, + media: opts.media, + force: opts.force, + signal, + drain: opts.drain, + onLog: log, + }, + opts.pageDeps ?? liveWaybackPageCaptureDeps(), + ); + } catch (err) { + const message = (err as Error).message; + log(`[error] ${message}`); + return { ok: false, outcomes: [], error: message }; + } + const count = (state: string) => result.outcomes.filter((o) => o.state === state).length; + log( + `Done: ${count("captured")} captured, ${count("error")} failed; ` + + `${ids.length - result.outcomes.length} not attempted or already captured.`, + ); + const stoppedByOperator = signal.aborted || Boolean(opts.drain?.aborted); + if (result.stoppedEarly && !stoppedByOperator) return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly }; + return { ok: true, outcomes: result.outcomes }; +} diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts @@ -304,6 +304,24 @@ export class ArchiveOrgClient { }); } + // A request SOMETHING ELSE makes (release 37 S4: a headless browser's load of + // a Wayback replay page for a page record's shot), run in this client's + // chain and gap: it waits for every earlier request and the gap, and the + // next one waits for it to end and the gap after. No retry here — the caller + // reads the answer and stops on a 429/503 rather than asking again. + paced<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T> { + return this.serial(async () => { + const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now(); + if (wait > 0) await this.deps.sleep(wait, signal); + this.requests++; + try { + return await fn(); + } finally { + this.lastDoneAt = this.deps.now(); + } + }); + } + getJson(url: string, signal?: AbortSignal): Promise<unknown> { return this.serial(async () => { const res = await this.getOnce(url, "application/json", signal); diff --git a/common/lib/report/views.ts b/common/lib/report/views.ts @@ -39,6 +39,7 @@ // Pure, no imports but types and pure helpers: the export site's pages and the // browser can use it. +import type { PageCaptureView } from "../waybackPages/view"; import { citationAnchor, extractCiteRefs } from "../citations/inline"; import { formatMomentSeconds, @@ -447,6 +448,9 @@ export type MomentPostView = { text: string; shot?: string; media?: { src: string; kind: "image" | "video" }[]; + // A page record's capture (platform "webpage", release 37 S4): its kind and + // date, the version list, no content, the extractor-fallback note. + page?: PageCaptureView; }; export type MomentPageView = { diff --git a/common/lib/wayback.ts b/common/lib/wayback.ts @@ -85,6 +85,22 @@ export function waybackRawUrl(ref: Pick<WaybackRef, "captureTs" | "originalUrl"> return `https://web.archive.org/web/${ref.captureTs}id_/${ref.originalUrl}`; } +// The capture as a page with no toolbar (`if_`, the replay's frame mode): what +// a page record's shot renders (release 37 S4). +export function waybackFrameUrl(ref: Pick<WaybackRef, "captureTs" | "originalUrl">): string { + return `https://web.archive.org/web/${ref.captureTs}if_/${ref.originalUrl}`; +} + +// A file a capture names (an image), through its own Wayback URL (`im_`): a +// web.archive.org URL keeps its timestamp and original, anything else is +// asked for at `captureTs` — the archive answers the nearest capture of it. +export function waybackFileUrl(captureTs: string, url: string): string { + const ref = parseWaybackUrl(url); + return ref + ? `https://web.archive.org/web/${ref.captureTs}im_/${ref.originalUrl}` + : `https://web.archive.org/web/${captureTs}im_/${url}`; +} + // `YYYY-MM-DD` of a capture timestamp, or the year (/month) when that is all // it names. export function waybackCaptureDate(captureTs: string): string { diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts @@ -161,6 +161,9 @@ export const WAYBACK_PAGE_MAX_BYTES = 2 * 1024 * 1024; // How many redirects inside the archive a capture fetch follows. export const WAYBACK_MAX_REDIRECTS = 5; +// The cap on one archived file a page record's capture downloads (release 37 S4). +export const WAYBACK_FILE_MAX_BYTES = 10 * 1024 * 1024; + const PAGE_ACCEPT = "text/html,application/xhtml+xml;q=0.9,text/plain;q=0.8,application/json;q=0.8,*/*;q=0.1"; // One capture's bytes (getCapture). @@ -353,6 +356,56 @@ export class WaybackClient { throw new WaybackCaptureRefusal("redirect-loop", `the capture of ${url} redirected more than ${WAYBACK_MAX_REDIRECTS} times`); } + // Run a request something else makes (a headless browser's load of a + // replay page, release 37 S4) in this client's chain and gap. + paced<T>(fn: () => Promise<T>, o: { signal?: AbortSignal } = {}): Promise<T> { + return this.http.paced(fn, o.signal); + } + + // A FILE a capture names (release 37 S4: a page record's image), by its own + // Wayback URL (`im_`, lib/wayback.ts waybackFileUrl), through the same chain, + // gap and back-off: its body read up to `maxBytes` (default 10 MB), redirects + // followed by hand inside web.archive.org only (≤ WAYBACK_MAX_REDIRECTS, the + // modifier kept). Answers null for a file the archive does not hold (404/410) + // or one over the cap; throws WaybackCaptureRefusal for a redirect off the + // archive or a loop, ArchiveOrgRequestError as getCapture does. + async getArchivedFile( + url: string, + o: { maxBytes?: number; accept?: string; signal?: AbortSignal } = {}, + ): Promise<{ body: Buffer; contentType: string | null; url: string } | null> { + const maxBytes = o.maxBytes ?? WAYBACK_FILE_MAX_BYTES; + let at = url; + const seen = new Set<string>(); + for (let hop = 0; hop <= WAYBACK_MAX_REDIRECTS; hop++) { + seen.add(at); + let res; + try { + res = await this.http.getBounded(at, o.accept ?? "image/*,*/*;q=0.5", { maxBytes, signal: o.signal, manualRedirect: true }); + } catch (e) { + if (e instanceof ArchiveOrgRequestError && (e.status === 404 || e.status === 410)) return null; + throw e; + } + if (res.location !== null || (res.status >= 300 && res.status < 400)) { + const next = res.location; + let host = ""; + try { + host = next ? new URL(next).hostname : ""; + } catch { + host = ""; + } + if (!next || !isWaybackHost(host)) { + throw new WaybackCaptureRefusal("offsite-redirect", `the archived file ${url} redirects off the Wayback Machine (${next ?? "no URL"})`); + } + if (seen.has(next)) throw new WaybackCaptureRefusal("redirect-loop", `the archived file ${url} redirects in a loop (${next})`); + at = next; + continue; + } + if (res.tooLarge || !res.body) return null; + return { body: res.body, contentType: res.headers.get("content-type"), url: at }; + } + throw new WaybackCaptureRefusal("redirect-loop", `the archived file ${url} redirected more than ${WAYBACK_MAX_REDIRECTS} times`); + } + // The captures of `url`, oldest first: every capture, or (`okOnly`) only the // ones that recorded a 200. Throws ArchiveOrgRequestError when the API kept // refusing (`rateLimited`) or answered an error. diff --git a/common/lib/waybackPages/view.test.ts b/common/lib/waybackPages/view.test.ts @@ -0,0 +1,87 @@ +// How a page record is shown (release 37 S4): the kind, the links, the +// version list, no content and the fallback note. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/view.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { renderToStaticMarkup } from "react-dom/server"; +import * as React from "react"; +// The components compile to `React.createElement` on a free `React`. +(globalThis as { React?: typeof React }).React = React; +import type { Post } from "../posts"; +import { pageRecordId } from "./types"; +import { isWholePageId, pageCaptureLine, pageCaptureView, pageKindLabel, pageVersionsLine, PAGE_NO_CONTENT_LINE } from "./view"; +import { PageCaptureFacts } from "../../components/PageCaptureFacts"; + +const URL_A = "https://blog.example/a.html"; + +function rec(ts: string, text: string, over: Partial<Post["page"]> = {}): Post { + const id = pageRecordId(ts, URL_A); + return { + id, + slug: `pages/${id}`, + channelSlug: "pages", + author: "blog.example", + createdAt: "2014-03-05T12:00:00.000Z", + uploadDate: "20140305", + text, + url: URL_A, + platform: "webpage", + isReply: false, + isRepost: false, + links: [], + page: { + originalUrl: URL_A, + captureTs: ts, + waybackUrl: `https://web.archive.org/web/${ts}/${URL_A}`, + rawUrl: `https://web.archive.org/web/${ts}id_/${URL_A}`, + kind: "generic", + extractor: "generic", + extractorVersion: 1, + ...over, + }, + }; +} + +test("a whole-page record: links, kind, and the versions of the same page", () => { + const a = rec("20140305120000", "First."); + const b = rec("20150611090000", "First."); + const c = rec("20160102000000", "Second."); + const other = { ...rec("20150101000000", "x"), page: { ...rec("20150101000000", "x").page!, originalUrl: "https://blog.example/b.html" } }; + assert.ok(isWholePageId(a.id)); + assert.ok(!isWholePageId("tumblr-123")); + const v = pageCaptureView(b, [a, c, other])!; + assert.equal(v.kindLabel, "Web page"); + assert.equal(v.captureDate, "2015-06-11"); + assert.deepEqual(v.links.original, { label: "Original (may be gone)", url: URL_A }); + assert.deepEqual(v.links.copy, { label: "Wayback Machine copy, 2015-06-11", url: b.page!.waybackUrl }); + assert.equal(v.versions?.count, 3); + assert.deepEqual(v.versions?.changedOn, ["2016-01-02"]); + assert.deepEqual(v.versions?.captures.map((x) => x.current), [false, true, false]); + assert.equal(pageVersionsLine(v.versions!), "3 captures of this page; text changed on 2016-01-02."); + assert.equal(pageVersionsLine({ count: 2, changedOn: [] }), "2 captures of this page; the text is the same in both."); + assert.equal(pageVersionsLine({ count: 4, changedOn: ["a", "b", "c"] }), "4 captures of this page; text changed on a, b and c."); + assert.equal(pageCaptureView(a)?.versions, undefined, "one capture: no list"); + assert.equal(pageCaptureView({ id: "p", text: "" }), undefined); +}); + +test("no content, the fallback note, an item seen first in an earlier capture", () => { + const shell = rec("20220101000000", "", { noContent: true, kind: "x-profile", extractorFallback: { from: "x", fromVersion: 1, error: "boom" } }); + const v = pageCaptureView(shell)!; + assert.equal(v.noContent, true); + assert.equal(v.kindLabel, "X/Twitter profile"); + assert.equal(v.fallbackNote, "The x reader could not read this capture (boom); the text is the generic reader's."); + const item = { ...rec("20140305120000", "t", { kind: "tumblr-post", firstSeenTs: "20120601000000" }), id: "tumblr-1" }; + const iv = pageCaptureView(item)!; + assert.equal(iv.firstSeenDate, "2012-06-01"); + assert.equal(pageCaptureLine(iv), "Tumblr post · captured 2014-03-05 (first seen 2012-06-01)"); + assert.equal(pageKindLabel("newkind"), "Web page (newkind)"); + + const html = renderToStaticMarkup(React.createElement(PageCaptureFacts, { view: v })); + assert.match(html, /data-page-capture="x-profile"/); + assert.ok(html.includes(PAGE_NO_CONTENT_LINE)); + assert.match(html, /data-page-fallback/); + assert.match(html, /Original \(may be gone\)/); + assert.match(html, /Wayback Machine copy, 2022-01-01/); +}); diff --git a/common/lib/waybackPages/view.ts b/common/lib/waybackPages/view.ts @@ -0,0 +1,149 @@ +// HOW A PAGE RECORD IS SHOWN (release 37 S4): the facts every surface that +// renders a page record — a report site's moment page and citation card, the +// editor's Wayback pages panel, umtool's evidence rail, the corpus viewer's +// post modal — prints about its capture, in the same words everywhere: +// +// the kind ("Tumblr post", "Web page", …), the capture's date, +// "Original (may be gone)" + "Wayback Machine copy, <date>" +// (lib/wayback.ts waybackCitationLinks), +// the version list — "4 captures of this page; text changed on …" — from +// the records of the same original URL, +// "This capture holds no content." for a shell, and the extractor-fallback +// note when a site extractor failed and the generic one read the page. +// +// Client-safe and pure: types only from ./types (whose urlHash is +// node:crypto), so the whole-page test is the id's shape, not a hash. + +import type { Post } from "../posts"; +import type { PagePostInfo } from "./types"; +import { waybackCaptureDate, waybackCitationLinks, type WaybackLink } from "../wayback"; + +export const PAGE_KIND_LABELS: Record<string, string> = { + generic: "Web page", + "tumblr-post": "Tumblr post", + "tumblr-index": "Tumblr page", + tweet: "Tweet", + "x-profile": "X/Twitter profile", + "forum-post": "Forum post", + gdoc: "Google Doc", + "yt-about": "YouTube channel page", +}; + +export function pageKindLabel(kind: string): string { + return PAGE_KIND_LABELS[kind] ?? `Web page (${kind})`; +} + +export const PAGE_NO_CONTENT_LINE = "This capture holds no content."; + +// A whole-page record's id is pageRecordId(captureTs, originalUrl): +// `<ts>-<12 hex>`. An item's id is the source's own (`tumblr-…`, `tweet-…`). +const WHOLE_PAGE_ID = /^\d{4,14}-[0-9a-f]{12}$/; +export function isWholePageId(id: string): boolean { + return WHOLE_PAGE_ID.test(id); +} + +export type PageVersionsView = { + // Captures of the page held (this one included). + count: number; + // The capture dates on which the text differs from the capture before. + changedOn: string[]; + // Each capture, oldest first. + captures: { id: string; date: string; waybackUrl: string; current: boolean }[]; +}; + +export type PageCaptureView = { + kind: string; + kindLabel: string; + captureTs: string; + captureDate: string; + originalUrl: string; + waybackUrl: string; + links: { original: WaybackLink; copy: WaybackLink }; + title?: string; + noContent?: boolean; + // The extractor-fallback sentence. + fallbackNote?: string; + // An item seen in more than one capture: the first one's date. + firstSeenDate?: string; + versions?: PageVersionsView; +}; + +export function pageFallbackNote(page: Pick<PagePostInfo, "extractorFallback">): string | undefined { + const f = page.extractorFallback; + if (!f) return undefined; + return `The ${f.from} reader could not read this capture (${f.error}); the text is the generic reader's.`; +} + +const tsKey = (ts: string) => ts.padEnd(14, "0"); + +// The versions of a whole-page record: the other whole-page records of the +// same original URL (`siblings` may hold anything — the channel's records; +// the ones that are not versions of this page are ignored). Undefined for an +// item record, or a page held in one capture only. +export function pageVersions(post: Pick<Post, "id" | "page" | "text">, siblings: ReadonlyArray<Pick<Post, "id" | "page" | "text">>): PageVersionsView | undefined { + if (!post.page || !isWholePageId(post.id)) return undefined; + const original = post.page.originalUrl; + const all = new Map<string, Pick<Post, "id" | "page" | "text">>(); + for (const s of [post, ...siblings]) { + if (s.page && s.page.originalUrl === original && isWholePageId(s.id)) all.set(s.id, s); + } + if (all.size < 2) return undefined; + const list = [...all.values()].sort((a, b) => tsKey(a.page!.captureTs).localeCompare(tsKey(b.page!.captureTs))); + const changedOn: string[] = []; + for (let i = 1; i < list.length; i++) { + if (list[i]!.text.trim() !== list[i - 1]!.text.trim()) changedOn.push(waybackCaptureDate(list[i]!.page!.captureTs)); + } + return { + count: list.length, + changedOn, + captures: list.map((s) => ({ + id: s.id, + date: waybackCaptureDate(s.page!.captureTs), + waybackUrl: s.page!.waybackUrl, + current: s.id === post.id, + })), + }; +} + +// "4 captures of this page; text changed on 2015-06-11 and 2016-01-02." / +// "2 captures of this page; the text is the same in both." +export function pageVersionsLine(v: Pick<PageVersionsView, "count" | "changedOn">): string { + const head = `${v.count} captures of this page`; + if (v.changedOn.length === 0) return `${head}; the text is the same in ${v.count === 2 ? "both" : "all"}.`; + const dates = + v.changedOn.length === 1 + ? v.changedOn[0] + : `${v.changedOn.slice(0, -1).join(", ")} and ${v.changedOn[v.changedOn.length - 1]}`; + return `${head}; text changed on ${dates}.`; +} + +export function pageCaptureView( + post: Pick<Post, "id" | "page" | "text">, + siblings: ReadonlyArray<Pick<Post, "id" | "page" | "text">> = [], +): PageCaptureView | undefined { + const page = post.page; + if (!page) return undefined; + const versions = pageVersions(post, siblings); + const fallbackNote = pageFallbackNote(page); + const firstSeen = + page.firstSeenTs && tsKey(page.firstSeenTs) !== tsKey(page.captureTs) ? waybackCaptureDate(page.firstSeenTs) : undefined; + return { + kind: page.kind, + kindLabel: pageKindLabel(page.kind), + captureTs: page.captureTs, + captureDate: waybackCaptureDate(page.captureTs), + originalUrl: page.originalUrl, + waybackUrl: page.waybackUrl, + links: waybackCitationLinks(page), + ...(page.title ? { title: page.title } : {}), + ...(page.noContent ? { noContent: true } : {}), + ...(fallbackNote ? { fallbackNote } : {}), + ...(firstSeen ? { firstSeenDate: firstSeen } : {}), + ...(versions ? { versions } : {}), + }; +} + +// One line of what the capture is: "Tumblr post · captured 2012-06-01". +export function pageCaptureLine(v: Pick<PageCaptureView, "kindLabel" | "captureDate" | "firstSeenDate">): string { + return `${v.kindLabel} · captured ${v.captureDate}${v.firstSeenDate ? ` (first seen ${v.firstSeenDate})` : ""}`; +} diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts @@ -69,6 +69,7 @@ // thrown together (ComposeReportsError), so a failed compose leaves no half // set of reports behind. +import { pageCaptureView } from "../lib/waybackPages/view"; import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { publishFileSizeProblem } from "../lib/builtExport"; @@ -761,13 +762,18 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol const config = await configOf(c.channel); if (c.kind === "post") { const post = (await postOf(c.channel, c.id))!; + // A page record (a Wayback capture, release 37 S4): the original, named + // as possibly gone, then the Wayback copy — as an archived video's. + const page = post.page ? waybackCitationLinks(post.page) : null; return defined({ channel: c.channel, channelTitle: config?.name ?? post.authorName, id: c.id, + ...(post.page?.title ? { title: post.page.title } : {}), date: post.createdAt.slice(0, 10), platform: post.platform, - originalUrl: post.url, + originalUrl: page ? page.original.url : post.url, + ...(page ? { originalLabel: page.original.label, downloads: [page.copy] } : {}), corpusUrl: corpusLink(c.channel, `${c.channel}/${c.id}`, { vm: "post" }), }); } @@ -888,9 +894,11 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol } as const; if (c.kind === "post") { const post = postsByChannel.get(c.channel)!.get(c.id)!; + const pageView = post.page ? pageCaptureView(post, [...postsByChannel.get(c.channel)!.values()]) : undefined; const postView: MomentPostView = { author: postAuthor(post), text: post.text, + ...(pageView ? { page: pageView } : {}), ...(entry?.kind === "post" ? { shot: `/media/${entry.file}`, diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts @@ -140,6 +140,12 @@ export type PostCaptureRecord = { sensitive?: boolean; // The screenshot, when one was taken. shot?: CapturedFile; + // A page record's shot (release 37 S4, platform "webpage"): of the item's + // own element ("item") or of the whole page ("page" — a whole-page record, + // or an item the render could not locate); `trimmed` when the page ran + // past the height cap. + shotScope?: "item" | "page"; + trimmed?: boolean; mediaState: CaptureMediaState; media: CapturedFile[]; // The X Article the post links to, when one was captured or tried. diff --git a/common/social/waybackPageCapture.test.ts b/common/social/waybackPageCapture.test.ts @@ -0,0 +1,287 @@ +// Page records' shots and images (release 37 S4), over the fake Wayback on +// loopback (common/testing/web/fakeWayback.mjs): the records come from the +// fake's own captures through the real extractors; the run's logic is driven +// with a stub page, and the crop with a real headless Chromium (skipped, +// saying why, on a host with no browser). No network. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/waybackPageCapture.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readdir, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + IMAGE_PNG, + PAGE_ARTICLE_TS, + PAGE_ARTICLE_URL, + PAGE_SPLIT_POSTS, + PAGE_SPLIT_TS, + PAGE_SPLIT_URL, + startFakeWayback, +} from "../testing/web/fakeWayback.mjs"; +import type { Post } from "../lib/posts"; +import { recordsOfCapture } from "../controller/importPage"; +import type { StoredCapture } from "../lib/waybackPages/store-server"; +import { WaybackClient } from "../lib/waybackClient"; +import { waybackFileUrl, waybackFrameUrl } from "../lib/wayback"; +import { + captureWaybackPageRecords, + openWaybackRenderPage, + PAGE_MEDIA_MAX, + pageItemTarget, + pageRecordImages, + shootPageRecord, + type WaybackPageCaptureDeps, +} from "./waybackPageCapture"; +import { readPostCapture, SHOT_FILENAME } from "./postCapture"; +import type { PageLike } from "./playwrightRuntime"; +import { pngSize } from "../publish/citedPostCaptures"; + +async function recordsOf(fetchUrl: string, ts: string, original: string): Promise<Post[]> { + const res = await fetch(fetchUrl); + const body = Buffer.from(await res.arrayBuffer()); + const capture = { originalUrl: original, captureTs: ts, mimetype: "text/html", contentType: "text/html; charset=utf-8" } as StoredCapture; + return recordsOfCapture("pages", capture, body).posts; +} + +async function fixtureRecords(base: string) { + const article = await recordsOf(`${base}/web/${PAGE_ARTICLE_TS}id_/${PAGE_ARTICLE_URL}`, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL); + const split = await recordsOf(`${base}/web/${PAGE_SPLIT_TS}id_/${PAGE_SPLIT_URL}`, PAGE_SPLIT_TS, PAGE_SPLIT_URL); + return { article: article[0]!, split }; +} + +test("what a record is shot as: the whole page, or its item's element", async () => { + const wb = await startFakeWayback(); + try { + const { article, split } = await fixtureRecords(wb.base); + assert.deepEqual(pageItemTarget(article), { scope: "page" }); + assert.deepEqual(split.map((p) => p.id).sort(), PAGE_SPLIT_POSTS.map((id) => `tumblr-${id}`).sort()); + const t = pageItemTarget(split[0]!); + assert.equal(t.scope, "item"); + if (t.scope === "item") { + assert.equal(t.kind, "tumblr-post"); + assert.ok(t.selectors.includes(`#post-${t.nativeId}`)); + assert.ok(new RegExp(t.permalink!).test(`/post/${t.nativeId}/on-crusts`)); + assert.ok(!new RegExp(t.permalink!).test(`/post/${t.nativeId}9`)); + } + const tweet = { id: "tweet-123456789012345678", page: { ...article.page!, kind: "tweet" as const } }; + const tt = pageItemTarget(tweet); + assert.equal(tt.scope, "item"); + if (tt.scope === "item") assert.ok(tt.selectors[0]!.includes("123456789012345678")); + assert.deepEqual(pageItemTarget({ id: "yt-about-UCx-2014", page: { ...article.page!, kind: "yt-about" } }), { scope: "page" }); + assert.deepEqual(pageItemTarget({ id: "x" }), { scope: "page" }); + } finally { + await wb.close(); + } +}); + +test("a record's images go by their own Wayback URLs (im_), deduplicated and capped", () => { + const page = { originalUrl: "https://a.example/", captureTs: "20140101000000", waybackUrl: "w", rawUrl: "r", kind: "generic" as const, extractor: "generic", extractorVersion: 1 }; + const many = Array.from({ length: PAGE_MEDIA_MAX + 5 }, (_, n) => ({ kind: "image" as const, url: `https://a.example/${n}.jpg` })); + const imgs = pageRecordImages({ + page, + media: [ + { kind: "image", url: "https://web.archive.org/web/20130101000000im_/https://a.example/x.png" }, + { kind: "image", url: "https://web.archive.org/web/20130101000000im_/https://a.example/x.png" }, + { kind: "link-card", url: "https://a.example/card" }, + ...many, + ], + }); + assert.equal(imgs[0]!.url, "https://web.archive.org/web/20130101000000im_/https://a.example/x.png"); + assert.equal(imgs[1]!.url, "https://web.archive.org/web/20140101000000im_/https://a.example/0.jpg"); + assert.equal(imgs.length, PAGE_MEDIA_MAX); + assert.equal(waybackFileUrl("2014", "https://web.archive.org/web/2012/https://b.example/i.gif"), "https://web.archive.org/web/2012im_/https://b.example/i.gif"); + assert.equal(waybackFrameUrl({ captureTs: "2014", originalUrl: "https://b.example/" }), "https://web.archive.org/web/2014if_/https://b.example/"); +}); + +// A page that answers without a browser: the item is found at a fixed box. +function stubPage(o: { itemFound?: boolean; status?: number } = {}) { + const visited: string[] = []; + const clips: unknown[] = []; + const page: PageLike = { + goto: async (url: string) => { + visited.push(url); + return { status: () => o.status ?? 200 }; + }, + waitForSelector: async () => ({}), + waitForTimeout: async () => {}, + evaluate: async (fn: string) => { + if (fn.includes("data-archilyzer-capture")) return o.itemFound === false ? null : { x: 190, y: 160, width: 534, height: 140 }; + if (fn.includes("scrollHeight")) return { width: 1280, height: 9500 }; + return 0; + }, + on: () => {}, + screenshot: async (opts) => { + clips.push(opts?.clip); + return new Uint8Array(IMAGE_PNG); + }, + }; + return { page, visited, clips }; +} + +async function setup(stub = stubPage()) { + const wb = await startFakeWayback(); + const client = new WaybackClient({ fetch: (u, i) => wb.fetch(u, i), sleep: async () => {} }, { minGapMs: 0 }); + const outDir = await mkdtemp(path.join(os.tmpdir(), "page-capture-")); + let paced = 0; + let opened = 0; + const deps: WaybackPageCaptureDeps = { + openPage: async () => { + opened++; + return { page: stub.page, close: async () => {} }; + }, + paced: (fn, signal) => { + paced++; + return client.paced(fn, { signal }); + }, + fetchFile: (url, signal) => client.getArchivedFile(url, { signal }), + now: () => new Date("2026-10-20T12:00:00.000Z"), + }; + const { article, split } = await fixtureRecords(wb.base); + const records = new Map([article, ...split].map((p) => [p.id, p])); + return { + wb, + deps, + outDir, + records, + article, + split, + stub, + counts: () => ({ paced, opened }), + close: async () => { + await wb.close(); + await rm(outDir, { recursive: true, force: true }); + }, + }; +} + +test("a run: the whole page shot to the cap, the item clipped to its box, images saved; nothing said about the original", async () => { + const s = await setup(); + try { + const crumb = s.split.find((p) => p.id === `tumblr-${PAGE_SPLIT_POSTS[1]}`)!; + assert.ok(crumb.media?.length, "the second post carries its image"); + const logs: string[] = []; + const res = await captureWaybackPageRecords( + { ids: [s.article.id, crumb.id], records: s.records, outDir: s.outDir, signal: new AbortController().signal, onLog: (l) => logs.push(l) }, + s.deps, + ); + assert.equal(res.stoppedEarly, undefined); + assert.deepEqual(res.outcomes.map((o) => o.state), ["captured", "captured"]); + assert.ok(res.outcomes.every((o) => o.availability === undefined), "a capture says nothing about the original"); + // Each page load inside the client's chain, the frame (`if_`) URL. + assert.equal(s.counts().paced, 2); + assert.equal(s.counts().opened, 1); + assert.deepEqual(s.stub.visited, [waybackFrameUrl(s.article.page!), waybackFrameUrl(crumb.page!)]); + // The whole page: cut at 8000 px; the item: its own box. + assert.deepEqual(s.stub.clips[0], { x: 0, y: 0, width: 1280, height: 8000 }); + assert.deepEqual(s.stub.clips[1], { x: 190, y: 160, width: 534, height: 140 }); + const a = await readPostCapture(path.join(s.outDir, s.article.id)); + assert.equal(a?.shotScope, "page"); + assert.equal(a?.trimmed, true); + assert.equal(a?.url, waybackFrameUrl(s.article.page!)); + const c = await readPostCapture(path.join(s.outDir, crumb.id)); + assert.equal(c?.shotScope, "item"); + assert.equal(c?.mediaState, "ok"); + assert.equal(c?.media.length, 1); + assert.match(c!.media[0]!.url!, /\/web\/20120601000000im_\/http:\/\/24\.media\.tumblr\.com\//); + assert.deepEqual((await readdir(path.join(s.outDir, crumb.id))).sort(), ["capture.json", "media-1.png", SHOT_FILENAME]); + // The image went through the archive's own URL. + assert.ok(s.wb.requests.some((r) => r.path.includes("im_/http://24.media.tumblr.com/"))); + + // A second run skips both; force shoots again. + const again = await captureWaybackPageRecords( + { ids: [s.article.id, crumb.id], records: s.records, outDir: s.outDir, signal: new AbortController().signal }, + s.deps, + ); + assert.equal(again.outcomes.length, 0); + assert.equal(s.counts().paced, 2); + } finally { + await s.close(); + } +}); + +test("an item the render cannot find is shot as the page; a 429 stops the run", async () => { + const s = await setup(stubPage({ itemFound: false })); + try { + const ids = s.split.map((p) => p.id); + const logs: string[] = []; + const res = await captureWaybackPageRecords( + { ids: [ids[0]!], records: s.records, outDir: s.outDir, media: false, signal: new AbortController().signal, onLog: (l) => logs.push(l) }, + s.deps, + ); + assert.equal(res.outcomes[0]?.state, "captured"); + assert.equal((await readPostCapture(path.join(s.outDir, ids[0]!)))?.shotScope, "page"); + assert.ok(logs.some((l) => /was not found on the rendered page; shot the whole page/.test(l))); + } finally { + await s.close(); + } + const busy = await setup(stubPage({ status: 429 })); + try { + const ids = busy.split.map((p) => p.id); + const res = await captureWaybackPageRecords( + { ids, records: busy.records, outDir: busy.outDir, signal: new AbortController().signal }, + busy.deps, + ); + assert.equal(res.outcomes.length, 1); + assert.equal(res.outcomes[0]?.state, "error"); + assert.match(res.stoppedEarly ?? "", /answered 429; stopping/); + } finally { + await busy.close(); + } +}); + +// ─── A real browser over the fake's captures ─── + +test("a real headless Chromium: the whole page, and one post clipped to its box", async (t) => { + const wb = await startFakeWayback(); + let opened; + try { + opened = await openWaybackRenderPage(wb.base); + } catch (e) { + await wb.close(); + t.skip(`no headless Chromium on this host: ${(e as Error).message.split("\n")[0].slice(0, 120)}`); + return; + } + const dir = await mkdtemp(path.join(os.tmpdir(), "page-shot-")); + const client = new WaybackClient({ fetch: (u, i) => wb.fetch(u, i), sleep: async () => {} }, { minGapMs: 0 }); + const paced: WaybackPageCaptureDeps["paced"] = (fn, signal) => client.paced(fn, { signal }); + const load = (u: string) => u.replace("https://web.archive.org", wb.base); + try { + const { article, split } = await fixtureRecords(wb.base); + const whole = await shootPageRecord(opened.page, { + url: load(waybackFrameUrl(article.page!)), + canonicalUrl: waybackFrameUrl(article.page!), + target: pageItemTarget(article), + dir: path.join(dir, "whole"), + signal: new AbortController().signal, + paced, + }); + assert.equal(whole.state, "captured", whole.error); + assert.equal(whole.shotScope, "page"); + const wsize = await pngSize(path.join(dir, "whole", SHOT_FILENAME)); + assert.equal(wsize?.width, 1280); + + const post = split.find((p) => p.id === `tumblr-${PAGE_SPLIT_POSTS[0]}`)!; + const item = await shootPageRecord(opened.page, { + url: load(waybackFrameUrl(post.page!)), + canonicalUrl: waybackFrameUrl(post.page!), + target: pageItemTarget(post), + dir: path.join(dir, "item"), + signal: new AbortController().signal, + paced, + }); + assert.equal(item.state, "captured", item.error); + assert.equal(item.shotScope, "item"); + const isize = await pngSize(path.join(dir, "item", SHOT_FILENAME)); + // The post box is 500 px + padding + border wide: clipped to it, not the page. + assert.ok(isize && isize.width > 500 && isize.width < 560, `width ${isize?.width}`); + assert.ok(isize!.height < 400, `height ${isize?.height}`); + // Nothing but the archive's origin was asked (the tumblr assets were refused). + assert.ok(!wb.requests.some((r) => r.path.includes("tumblr.com/iframe"))); + } finally { + await opened.close(); + await wb.close(); + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/social/waybackPageCapture.ts b/common/social/waybackPageCapture.ts @@ -0,0 +1,578 @@ +// Capturing PAGE RECORDS (release 37 S4, platform "webpage"): a screenshot of +// each record as the Wayback Machine replays its capture, and the images it +// names, into `posts-media/<id>/` (postCapture.ts owns the layout and the +// record) — what `capture-posts` does for a Wayback pages channel. +// +// THE RENDER is the capture's replay with the `if_` modifier (no toolbar: +// lib/wayback.ts waybackFrameUrl) in a headless Chromium, one fresh context +// with no profile and no cookies, JavaScript OFF (the archive rewrites a +// capture's links and styles server-side; the capture's own scripts would only +// ask the archive for more), and every request that is not to the archive +// refused — a render never reaches the live web. Fonts, stylesheets and images +// load from the archive; audio/video are refused. +// - a WHOLE-PAGE record (lib/waybackPages/toPost.ts isWholePageRecord) is +// shot full page, cut at PAGE_SHOT_MAX_HEIGHT CSS px (`trimmed`); +// - a SPLIT record (a tweet, a Tumblr post, a forum post — one item of a +// capture that holds several) is shot clipped to its own element, found by +// the id the extractor used (`pageItemTarget`); an item the render cannot +// find is shot as the whole page, `shotScope: "page"`, and the log says so. +// +// THE IMAGES in a record's `media` are saved through their own Wayback URLs +// (`im_`, waybackFileUrl) — at most PAGE_MEDIA_MAX per record, each capped. +// +// POLITE: every contact is the process's Wayback client's — the page load runs +// inside its chain and gap (`paced`), the images through `getArchivedFile` — +// and the job runs on the `platform:archive.org` queue. A page load answered +// 429/503 stops the run there, the rest left for a later run. +// +// A capture says nothing about whether the ORIGINAL is still up, so no outcome +// carries an availability: the posts-availability sidecar of a page record is +// the original's state (release 37 S5), never this render's. + +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import type { Post } from "../lib/posts"; +import { waybackFileUrl, waybackFrameUrl } from "../lib/wayback"; +import { WAYBACK_ORIGIN, waybackClient, waybackTestOrigin } from "../lib/waybackClient"; +import { isWholePageRecord } from "../lib/waybackPages/toPost"; +import type { PostCaptureInput, PostCaptureOutcome, PostCaptureResult } from "./fetchers"; +import { importPlaywright, type PageLike } from "./playwrightRuntime"; +import { + captureWork, + describeCapturedFile, + postCaptureDir, + readPostCapture, + SHOT_FILENAME, + writePostCapture, + type CapturedFile, + type CaptureMediaState, + type PostCaptureRecord, + type PostCaptureState, +} from "./postCapture"; + +// A whole page is shot to this height (CSS px) and no further. +export const PAGE_SHOT_MAX_HEIGHT = 8000; +// The window the page renders in. +export const PAGE_VIEWPORT = { width: 1280, height: 1600 }; +// The images one record's capture saves. +export const PAGE_MEDIA_MAX = 20; +// How long a replay may take to load. +export const PAGE_LOAD_TIMEOUT_MS = 60_000; + +// ─── Which element is the record ─── + +export type PageShotTarget = + | { scope: "page" } + | { + scope: "item"; + kind: string; + // The item's own id as the page carries it (a status id, a Tumblr post + // id, a forum post id). + nativeId: string; + // CSS selectors that name the item directly, most specific first. + selectors: string[]; + // A link whose href matches this (a regexp source, tested on the + // href's path) is the item's permalink; a link matching `anyPermalink` + // with another id is another item's. + permalink?: string; + anyPermalink?: string; + }; + +const reEscape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +const cssString = (s: string) => JSON.stringify(s); + +// What to shoot for a record: the whole page, or the item's element. Derived +// from the record's kind and id (the ids lane C's extractors make — +// plans/FACTS.md "Release 37 lane C"), so no locator is stored. +export function pageItemTarget(post: Pick<Post, "id" | "page">): PageShotTarget { + if (!post.page || isWholePageRecord(post)) return { scope: "page" }; + const kind = post.page.kind; + if (kind === "tweet") { + const id = post.id.replace(/^tweet-/, ""); + if (!/^\d+$/.test(id)) return { scope: "page" }; + return { + scope: "item", + kind, + nativeId: id, + selectors: [ + `div.tweet[data-tweet-id=${cssString(id)}]`, + `[data-tweet-id=${cssString(id)}]`, + `li[data-item-id=${cssString(id)}]`, + `[data-item-id=${cssString(id)}]`, + ], + permalink: `/status(?:es)?/${reEscape(id)}(?:[/?#]|$)`, + anyPermalink: `/status(?:es)?/\\d+(?:[/?#]|$)`, + }; + } + if (kind === "tumblr-post") { + const id = post.id.replace(/^tumblr-/, ""); + if (!/^\d+$/.test(id)) return { scope: "page" }; + return { + scope: "item", + kind, + nativeId: id, + selectors: [`#post-${id}`, `#post_${id}`, `[data-post-id=${cssString(id)}]`], + permalink: `/post/${reEscape(id)}(?:[/?#]|$)`, + anyPermalink: `/post/\\d+(?:[/?#]|$)`, + }; + } + if (kind === "forum-post") { + const id = post.id; + if (!/^\d+$/.test(id)) return { scope: "page" }; + return { + scope: "item", + kind, + nativeId: id, + selectors: [`#js-post-${id}`, `article[data-content=${cssString(`post-${id}`)}]`, `#post-${id}`], + permalink: `/posts/${reEscape(id)}(?:[/?#]|$)`, + anyPermalink: `/posts/\\d+(?:[/?#]|$)`, + }; + } + if (kind === "x-profile") { + return { + scope: "item", + kind, + nativeId: post.id, + selectors: [".ProfileHeaderCard", ".profile-card", ".profile-details", ".ProfileCanopy"], + }; + } + // A yt-about record, or a kind this module does not know: the page. + return { scope: "page" }; +} + +// Marks the item's element (`data-archilyzer-capture`) and answers its box in +// document coordinates, or null when the page holds no such item: +// 1. the first selector that matches exactly one element; +// 2. else the LARGEST element around a link to the item's permalink that +// holds no link to another item's permalink (lane C's Tumblr rule). +export const LOCATE_ITEM_SCRIPT = (t: Extract<PageShotTarget, { scope: "item" }>) => `(() => { + const selectors = ${JSON.stringify(t.selectors)}; + const own = ${t.permalink ? `new RegExp(${JSON.stringify(t.permalink)})` : "null"}; + const any = ${t.anyPermalink ? `new RegExp(${JSON.stringify(t.anyPermalink)})` : "null"}; + for (const el of document.querySelectorAll("[data-archilyzer-capture]")) el.removeAttribute("data-archilyzer-capture"); + const pathOf = (a) => { try { return new URL(a.getAttribute("href"), location.href).pathname; } catch { return ""; } }; + let found = null; + for (const sel of selectors) { + let hits = []; + try { hits = Array.from(document.querySelectorAll(sel)); } catch { hits = []; } + if (hits.length === 1) { found = hits[0]; break; } + if (hits.length > 1) { found = hits[0].closest(".tweet") || hits[0]; break; } + } + if (!found && own) { + const links = Array.from(document.querySelectorAll("a[href]")); + const mine = links.filter((a) => own.test(pathOf(a))); + const others = any ? links.filter((a) => any.test(pathOf(a)) && !own.test(pathOf(a))) : []; + let best = null; + for (const a of mine) { + let el = a.parentElement; + let top = null; + while (el && el !== document.body && el !== document.documentElement) { + if (others.some((o) => el.contains(o))) break; + top = el; + el = el.parentElement; + } + if (top && (!best || (top.contains(best)))) best = top; + } + found = best; + } + if (!found) return null; + found.setAttribute("data-archilyzer-capture", ""); + const r = found.getBoundingClientRect(); + return { x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height }; +})()`; + +// The page's own size, for a whole-page shot. +export const PAGE_SIZE_SCRIPT = `(() => { + const d = document.documentElement, b = document.body; + return { + width: Math.max(d ? d.scrollWidth : 0, b ? b.scrollWidth : 0, window.innerWidth), + height: Math.max(d ? d.scrollHeight : 0, b ? b.scrollHeight : 0, 1), + }; +})()`; + +// Let the images finish loading (each capped at 5 s), so a shot is not of +// grey boxes. +const IMAGES_LOADED_SCRIPT = `(() => { + const imgs = Array.from(document.images).filter((i) => !i.complete); + return Promise.all(imgs.map((i) => new Promise((r) => { + i.addEventListener("load", r, { once: true }); + i.addEventListener("error", r, { once: true }); + setTimeout(r, 5000); + }))).then(() => imgs.length); +})()`; + +type Rect = { x: number; y: number; width: number; height: number }; + +// ─── Deps ─── + +export type WaybackPageCaptureDeps = { + // A page in a fresh browser context: opened on the first shot, closed at + // the end of the run. + openPage: () => Promise<{ page: PageLike; close: () => Promise<void> }>; + // Run a page load inside the Wayback client's chain and gap. + paced: <T>(fn: () => Promise<T>, signal: AbortSignal) => Promise<T>; + // One archived file (an image) through the Wayback client; null when the + // archive does not hold it. + fetchFile: (url: string, signal: AbortSignal) => Promise<{ body: Buffer; contentType: string | null } | null>; + // The URL to load for a web.archive.org URL (the e2e suite's fake origin). + loadUrl?: (url: string) => string; + now?: () => Date; + pageTimeoutMs?: number; +}; + +// A headless Chromium with a fresh context: no profile, no cookies, no +// JavaScript, and nothing but `allowOrigin` reachable. +export async function openWaybackRenderPage( + allowOrigin: string, +): Promise<{ page: PageLike; close: () => Promise<void> }> { + const { chromium } = await importPlaywright(); + const browser = await chromium.launch({ headless: true }); + try { + const context = (await browser.newContext({ + viewport: PAGE_VIEWPORT, + deviceScaleFactor: 1, + locale: "en-US", + colorScheme: "light", + javaScriptEnabled: false, + })) as unknown as { + newPage: () => Promise<PageLike>; + close: () => Promise<void>; + route: ( + match: (url: URL) => boolean, + handler: (route: { + request: () => { url: () => string; resourceType: () => string }; + abort: () => Promise<void>; + continue: () => Promise<void>; + }) => unknown, + ) => Promise<void>; + }; + const origin = new URL(allowOrigin).origin; + await context.route( + () => true, + (route) => { + const req = route.request(); + let ok = false; + try { + const u = new URL(req.url()); + ok = u.origin === origin || u.protocol === "data:"; + } catch { + ok = false; + } + const type = req.resourceType(); + if (!ok || type === "media" || type === "websocket" || type === "eventsource") return route.abort(); + return route.continue(); + }, + ); + const page = await context.newPage(); + return { + page, + close: async () => { + await context.close().catch(() => {}); + await browser.close().catch(() => {}); + }, + }; + } catch (err) { + await browser.close().catch(() => {}); + throw err; + } +} + +// The process's deps: the process's Wayback client (its chain, gap and +// back-off), and the e2e suite's fake origin when E2E_WAYBACK_ORIGIN_FILE +// names one (lib/waybackClient.ts waybackTestOrigin). +export function liveWaybackPageCaptureDeps(): WaybackPageCaptureDeps { + const testOrigin = waybackTestOrigin(); + const loadUrl = (u: string) => (testOrigin ? u.replace(/^https?:\/\/(?:web|wayback)\.archive\.org/, testOrigin) : u); + return { + openPage: () => openWaybackRenderPage(testOrigin ?? WAYBACK_ORIGIN), + paced: (fn, signal) => waybackClient.paced(fn, { signal }), + fetchFile: (url, signal) => waybackClient.getArchivedFile(url, { signal }), + loadUrl, + }; +} + +// ─── One record's shot ─── + +export type PageShotResult = { + state: PostCaptureState; + shot?: CapturedFile; + shotScope?: "item" | "page"; + trimmed?: boolean; + error?: string; + // The page load answered 429/503: the run stops. + rateLimited?: boolean; + note?: string; +}; + +function firstLine(err: unknown): string { + return ((err as Error)?.message ?? String(err)).split("\n")[0]; +} + +// Shoot one record: load `url` (inside `paced`), find the item (or take the +// page), write shot.png into `dir`. `canonicalUrl` is what the record names. +export async function shootPageRecord( + page: PageLike, + o: { + url: string; + canonicalUrl: string; + target: PageShotTarget; + dir: string; + signal: AbortSignal; + paced: WaybackPageCaptureDeps["paced"]; + pageTimeoutMs?: number; + }, +): Promise<PageShotResult> { + let status: number | undefined; + try { + status = await o.paced(async () => { + const response = await page.goto(o.url, { waitUntil: "load", timeout: o.pageTimeoutMs ?? PAGE_LOAD_TIMEOUT_MS }); + await page.evaluate(IMAGES_LOADED_SCRIPT).catch(() => 0); + return (response as { status?: () => number } | null)?.status?.(); + }, o.signal); + } catch (err) { + if (o.signal.aborted) return { state: "error", error: "cancelled" }; + return { state: "error", error: `Could not load ${o.canonicalUrl}: ${firstLine(err)}` }; + } + if (status === 429 || status === 503) { + return { state: "error", error: `the Wayback Machine answered ${status}`, rateLimited: true }; + } + if (status !== undefined && status >= 400) { + return { state: "error", error: `the Wayback Machine answered HTTP ${status} for ${o.canonicalUrl}` }; + } + + let rect: Rect | null = null; + let scope: "item" | "page" = "page"; + let note: string | undefined; + if (o.target.scope === "item") { + rect = (await page.evaluate(LOCATE_ITEM_SCRIPT(o.target)).catch(() => null)) as Rect | null; + if (rect && rect.width >= 1 && rect.height >= 1) scope = "item"; + else { + rect = null; + note = `the ${o.target.kind} ${o.target.nativeId} was not found on the rendered page; shot the whole page`; + } + } + let trimmed = false; + if (!rect) { + const size = (await page.evaluate(PAGE_SIZE_SCRIPT).catch(() => null)) as { width: number; height: number } | null; + const width = Math.max(1, Math.min(size?.width ?? PAGE_VIEWPORT.width, PAGE_VIEWPORT.width * 2)); + const height = Math.max(1, size?.height ?? PAGE_VIEWPORT.height); + trimmed = height > PAGE_SHOT_MAX_HEIGHT; + rect = { x: 0, y: 0, width, height: Math.min(height, PAGE_SHOT_MAX_HEIGHT) }; + } else if (rect.height > PAGE_SHOT_MAX_HEIGHT) { + trimmed = true; + rect = { ...rect, height: PAGE_SHOT_MAX_HEIGHT }; + } + let png: Uint8Array; + try { + png = await page.screenshot({ + type: "png", + fullPage: true, + clip: { + x: Math.max(0, Math.floor(rect.x)), + y: Math.max(0, Math.floor(rect.y)), + width: Math.ceil(rect.width), + height: Math.ceil(rect.height), + }, + }); + } catch (err) { + return { state: "error", error: `The screenshot failed: ${firstLine(err)}` }; + } + await mkdir(o.dir, { recursive: true }); + await writeFile(path.join(o.dir, SHOT_FILENAME), png); + return { + state: "captured", + shot: await describeCapturedFile(o.dir, SHOT_FILENAME, o.canonicalUrl), + shotScope: scope, + ...(trimmed ? { trimmed } : {}), + ...(note ? { note } : {}), + }; +} + +// ─── The images ─── + +const EXT_BY_TYPE: Record<string, string> = { + "image/jpeg": "jpg", + "image/png": "png", + "image/gif": "gif", + "image/webp": "webp", + "image/avif": "avif", + "image/svg+xml": "svg", +}; + +function imageExt(url: string, contentType: string | null): string { + const ct = (contentType ?? "").split(";")[0].trim().toLowerCase(); + if (EXT_BY_TYPE[ct]) return EXT_BY_TYPE[ct]; + let pathname = url; + try { + pathname = new URL(url).pathname; + } catch { + /* the raw string */ + } + const m = /\.([a-z0-9]{2,5})$/i.exec(pathname); + return m ? m[1].toLowerCase().replace("jpeg", "jpg") : "bin"; +} + +// The images a record's capture saves: its `media` of kind image, each by its +// own Wayback URL at the record's capture time, deduplicated, at most +// PAGE_MEDIA_MAX. +export function pageRecordImages(post: Pick<Post, "media" | "page">): { url: string; source: string }[] { + const ts = post.page?.captureTs; + if (!ts) return []; + const out: { url: string; source: string }[] = []; + for (const m of post.media ?? []) { + if (m.kind !== "image" || !/^https?:\/\//.test(m.url)) continue; + const url = waybackFileUrl(ts, m.url); + if (out.some((x) => x.url === url)) continue; + out.push({ url, source: m.url }); + if (out.length >= PAGE_MEDIA_MAX) break; + } + return out; +} + +// ─── The run ─── + +const STOP_AFTER_ERRORS = 3; + +export type PageCaptureInput = Pick< + PostCaptureInput, + "ids" | "outDir" | "shots" | "media" | "force" | "signal" | "drain" | "onLog" +> & { + // The archived records, by id (capturePosts reads them). + records: ReadonlyMap<string, Post>; +}; + +export async function captureWaybackPageRecords( + input: PageCaptureInput, + deps: WaybackPageCaptureDeps, +): Promise<PostCaptureResult> { + const { signal, onLog } = input; + const wanted = { shots: input.shots ?? true, media: input.media ?? true, force: input.force ?? false }; + const now = deps.now ?? (() => new Date()); + const load = deps.loadUrl ?? ((u: string) => u); + const outcomes: PostCaptureOutcome[] = []; + const stopped = (why: string): PostCaptureResult => { + onLog?.(why); + return { outcomes, stoppedEarly: why }; + }; + + let browser: { page: PageLike; close: () => Promise<void> } | undefined; + let errorsInARow = 0; + try { + for (const [i, id] of input.ids.entries()) { + if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); + if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); + const post = input.records.get(id); + if (!post?.page) { + onLog?.(`${id}: not a page record (no capture facts) — skipped.`); + outcomes.push({ id, state: "error", files: 0, error: "not a page record" }); + continue; + } + const dir = postCaptureDir(input.outDir, id); + const existing = await readPostCapture(dir); + const work = captureWork(existing, { ...wanted, articles: false }); + if (!work.shot && !work.media) { + onLog?.(`${id}: already captured (${existing?.state ?? "nothing asked for"}) — skipped.`); + continue; + } + onLog?.(`[${i + 1}/${input.ids.length}] ${id}`); + const frameUrl = waybackFrameUrl(post.page); + + let state: PostCaptureState | undefined = work.shot ? undefined : existing?.state; + let shot = work.shot ? undefined : existing?.shot; + let shotScope = work.shot ? undefined : existing?.shotScope; + let trimmed = work.shot ? undefined : existing?.trimmed; + let error: string | undefined; + let stop: string | undefined; + + if (work.shot) { + browser ??= await deps.openPage(); + const res = await shootPageRecord(browser.page, { + url: load(frameUrl), + canonicalUrl: frameUrl, + target: pageItemTarget(post), + dir, + signal, + paced: deps.paced, + ...(deps.pageTimeoutMs ? { pageTimeoutMs: deps.pageTimeoutMs } : {}), + }); + if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); + state = res.state; + shot = res.shot; + shotScope = res.shotScope; + trimmed = res.trimmed; + error = res.error; + if (res.note) onLog?.(`${id}: ${res.note}.`); + if (res.rateLimited) stop = `${res.error}; stopping.`; + } + + let mediaState: CaptureMediaState = work.media ? "skipped" : (existing?.mediaState ?? "skipped"); + let media: CapturedFile[] = work.media ? [] : (existing?.media ?? []); + if (work.media && !stop && (state === undefined || state === "captured")) { + const images = pageRecordImages(post); + if (images.length === 0) { + mediaState = "none"; + } else { + let failed = 0; + for (const [n, im] of images.entries()) { + if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); + let got; + try { + got = await deps.fetchFile(im.url, signal); + } catch (err) { + failed++; + onLog?.(`${id}: image ${n + 1} failed: ${firstLine(err)}`); + if ((err as { rateLimited?: boolean }).rateLimited) { + stop = `${firstLine(err)}; stopping.`; + break; + } + continue; + } + if (!got) { + failed++; + onLog?.(`${id}: image ${n + 1} is not in the archive (or over the cap): ${im.source}`); + continue; + } + const name = `media-${n + 1}.${imageExt(im.source, got.contentType)}`; + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, name), got.body); + media.push(await describeCapturedFile(dir, name, im.url)); + } + mediaState = failed > 0 ? "error" : "ok"; + if (failed > 0) error = error ? `${error}; ${failed} image(s) failed` : `${failed} image(s) failed`; + } + state ??= existing?.state ?? "captured"; + } + + const finalState: PostCaptureState = state ?? "error"; + const record: PostCaptureRecord = { + version: 1, + id, + url: frameUrl, + capturedAt: now().toISOString(), + state: finalState, + ...(shot ? { shot } : {}), + ...(shot && shotScope ? { shotScope } : {}), + ...(shot && trimmed ? { trimmed } : {}), + mediaState, + media, + ...(error ? { error } : {}), + }; + await writePostCapture(dir, record); + outcomes.push({ id, state: finalState, files: (shot ? 1 : 0) + media.length, ...(error ? { error } : {}) }); + onLog?.( + `${id}: ${finalState}` + + (work.shot && shot ? `, shot (${shotScope ?? "page"}${trimmed ? ", trimmed" : ""})` : "") + + (mediaState === "ok" ? `, ${media.length} image(s)` : mediaState === "none" ? ", no images" : "") + + (error ? ` — ${error}` : ""), + ); + if (stop) return stopped(`${stop} Stopped at ${id}; the rest are left for a later run.`); + errorsInARow = finalState === "error" ? errorsInARow + 1 : 0; + if (errorsInARow >= STOP_AFTER_ERRORS) { + return stopped(`${STOP_AFTER_ERRORS} records in a row failed; stopping rather than going through the rest.`); + } + } + return { outcomes }; + } finally { + await browser?.close().catch(() => {}); + } +} diff --git a/common/testing/README.md b/common/testing/README.md @@ -23,7 +23,7 @@ transcript, channel or person goes in these fixtures, ever. | `draft/manifests/full`, `flips` | Release 28: every media field a draft task writes, as the build accepts it today — per-entry `onscreen`, a narrated card, a teaser, `claim` verdicts, `render.chrome.threads` with a `thread` per clip (`full`), or `render.chrome.flips` (`flips`: one THEN/NOW pair over clips of different dates). Hand-written, not derived; `umtool/report-to-video/fixtures-r28.test.mjs` keeps them lint-clean. | | `draft/reports/ruled.report.json` | Release 28: a synthetic fact-check whose claims carry verdicts standing for operator rulings — every verdict at least once, each cited quote a cue of the corpus. The verdict bench's tests read it. | | `social/fakeBluesky.mjs` | Release 29: a fake Bluesky on loopback — the public AppView (`resolveHandle`, `getPosts` answering only live posts, images as `embed.images[].fullsize`), a bsky.app-shaped post page (`pageUrl(handle, rkey)`: the post in `[data-testid="postThreadItem-by-<handle>"]` inside page chrome, "Post not found" for a deleted one) for a headless screenshot, and PNG images. `bsky.fetch` sends `https://public.api.bsky.app`, `https://bsky.app` and `https://cdn.bsky.app` to it; `busyTimes` answers 429 first. | -| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. Release 37 (lane A): PAGE captures served raw (`PAGE_CAPTURES`, `opts.pageCaptures`) — an article with nav/header/footer around an `<article>` (two captures), a body still carrying the toolbar insert and rewritten hrefs, a 3 MB page, a `text/plain` and an `image/jpeg` capture, and one that redirects off the archive; a timestamp with no capture of a known page answers 302 to the nearest; CDX honours `closest=`. | +| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. Release 37 (lane A): PAGE captures served raw (`PAGE_CAPTURES`, `opts.pageCaptures`) — an article with nav/header/footer around an `<article>` (two captures), a body still carrying the toolbar insert and rewritten hrefs, a 3 MB page, a `text/plain` and an `image/jpeg` capture, and one that redirects off the archive; a timestamp with no capture of a known page answers 302 to the nearest; CDX honours `closest=`. Release 37 (lane D): a Tumblr-themed index holding two posts (`PAGE_SPLIT_URL`/`PAGE_SPLIT_TS`, `PAGE_CAPTURES_SPLIT`, served by default) for the split-record shot, and `/web/<ts>im_/<image url>` answering a small PNG (`IMAGE_PNG`). | | `web/fakeRangedCdn.mjs` | Release 32 R7: a fake media CDN shaped like Odysee's `player.odycdn.com` — ranged GETs with a Referer answer 206 (`Content-Range`), unranged 429, no Referer 403, past the end 416; `refuseAfterBytes` (429/403 once a budget is served), `corruptOnce`, `ignoreRange`, `requireUnlock` + `unlockBytes` (served only after `cdn.unlock()` — a player's page open — lapsing after a budget; `cdn.lock()` takes it back). Release 32 R10: `dropAfterBytes` / `drops` / `dropGapBytes` cut the connection mid-body (undici's body read throws) or before any response (the fetch throws `fetch failed`); a cut request is `dropped: true`. `cdn.fetch` sends `https://player.odycdn.com` to it. | | `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. | | `audio/corruptAudio.mjs` | Release 30 lane Q: damaged audio for the salvage and refetch tests — `makeToneFile` (an AAC-in-MP4 tone-burst recording: a 0.3 s burst every 4 s, the bursts being the clock), `corruptBytes` (the same with a seeded run of its bytes overwritten: the frames there fail to decode, their timestamps survive), `readWavMono16`, `toneOnsets` (burst onsets in decoded samples), `burstTimes`, `hasFfmpeg`. Needs ffmpeg; the tests that use it skip without. | diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts @@ -18,6 +18,12 @@ export const PAGE_IMAGE_URL: string; export const PAGE_IMAGE_TS: string; export const PAGE_JUMP_URL: string; export const PAGE_JUMP_TS: string; +// Release 37 (lane D): a capture of several items, and archived images (`im_`). +export const PAGE_SPLIT_URL: string; +export const PAGE_SPLIT_TS: string; +export const PAGE_SPLIT_POSTS: string[]; +export const PAGE_CAPTURES_SPLIT: FakePageCapture[]; +export const IMAGE_PNG: Buffer; export const VIDEOS: string[]; export type FakeWayback = { @@ -35,6 +41,6 @@ export function startFakeWayback(opts?: { busyTimes?: number; downTimes?: number; streamBusyTimes?: number; - // (release 37) the page captures served raw (default PAGE_CAPTURES). + // (release 37) the page captures served raw (default PAGE_CAPTURES + PAGE_CAPTURES_SPLIT). pageCaptures?: FakePageCapture[]; }): Promise<FakeWayback>; diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs @@ -142,6 +142,50 @@ export const PAGE_CAPTURES = [ { original: PAGE_JUMP_URL, timestamp: PAGE_JUMP_TS, statuscode: "302", mimetype: "text/html", offsite: "https://elsewhere.example/landing" }, ]; +// ─── Release 37 (lane D): a capture that holds several items, and images ─── +// +// SPLIT a Tumblr-themed blog index (two posts, each a fixed-width box, the +// second with an image) — split by the Tumblr extractor into +// `tumblr-<id>` records, each shot clipped to its own post +// Served as every page capture is (`id_` / `if_` / framed). `/web/<ts>im_/<url>` +// of an image URL (.jpg/.jpeg/.png/.gif/.webp) answers a small PNG — the page +// records' images through their own Wayback URLs; any other `im_` is a 404. +export const PAGE_SPLIT_URL = "https://crumb-notes.tumblr.com/"; +export const PAGE_SPLIT_TS = "20120601000000"; +export const PAGE_SPLIT_POSTS = ["30000000002", "30000000001"]; +// A 2×2 PNG (opaque grey). +export const IMAGE_PNG = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAADklEQVR4nGNoAAMGCAUAKg4GARWeQtcAAAAASUVORK5CYII=", + "base64", +); + +const splitHtml = `<!DOCTYPE html> +<html><head><title>Crumb Notes</title> +<style>body{margin:0;font:16px sans-serif;background:#eee}#content{width:900px;margin:0 auto;padding:20px} +.post{width:500px;background:#fff;border:1px solid #999;margin:0 0 40px 0;padding:16px}#header{height:120px;background:#ccd}</style> +</head><body> +<iframe id="tumblr_controls" src="http://assets.tumblr.com/iframe.html?lang=en_US&amp;name=crumb-notes" width="1" height="1"></iframe> +<div id="header"><h1><a href="/">Crumb Notes</a></h1></div> +<div id="content"> + <div class="post"> + <h3><a href="http://crumb-notes.tumblr.com/post/30000000002/on-crusts">On crusts</a></h3> + <p>A crust should crackle when it cools on the rack.</p> + <div class="date"><a href="http://crumb-notes.tumblr.com/post/30000000002/on-crusts">June 1st, 2012</a></div> + </div> + <div class="post"> + <h3><a href="http://crumb-notes.tumblr.com/post/30000000001/on-crumbs">On crumbs</a></h3> + <p>An open crumb comes from a wet dough and a long, slow rise.</p> + <img src="http://24.media.tumblr.com/tumblr_crumb_500.jpg" alt="a sliced loaf" width="300" height="200" /> + <div class="date"><a href="http://crumb-notes.tumblr.com/post/30000000001/on-crumbs">May 20th, 2012</a></div> + </div> + <div id="navigation"><a href="/page/2">Older &rarr;</a></div> +</div> +</body></html>`; + +export const PAGE_CAPTURES_SPLIT = [ + { original: PAGE_SPLIT_URL, timestamp: PAGE_SPLIT_TS, statuscode: "200", mimetype: "text/html", body: () => splitHtml }, +]; + // The answer to `/web/<ts>[mod]/<original>` for a page capture, or null when // the original is not one of PAGE_CAPTURES. function pageCaptureAnswer(pageCaptures, ts, mod, original, send, res) { @@ -172,7 +216,7 @@ export const VIDEOS = ["gone-video-05"]; export async function startFakeWayback(opts = {}) { // Release 37: the page captures are served beside whatever `captures` says, // and listed by CDX unless a test names its own `captures`. - const pageCaptures = opts.pageCaptures ?? PAGE_CAPTURES; + const pageCaptures = opts.pageCaptures ?? [...PAGE_CAPTURES, ...PAGE_CAPTURES_SPLIT]; const captures = opts.captures ?? [...CAPTURES, ...pageCaptures]; const videos = opts.videos ?? VIDEOS; const streams = opts.streams ?? videos; @@ -234,6 +278,12 @@ export async function startFakeWayback(opts = {}) { const to = Math.min(body.length - 1, range[2] ? Number(range[2]) : body.length - 1); return send(206, "video/mp4", body.subarray(from, to + 1), { "content-range": `bytes ${from}-${to}/${body.length}` }); } + // Release 37 (lane D): an archived image by its own Wayback URL. + const im = /^\/web\/(\d{1,14})im_\/(.+)$/.exec(u.pathname + u.search); + if (im) { + if (/\.(?:jpe?g|png|gif|webp)$/i.test(im[2])) return send(200, "image/png", IMAGE_PNG); + return send(404, "text/html", "<p>Wayback Machine has not archived that URL.</p>"); + } // Release 37: a page capture (PAGE_CAPTURES), raw. const pc = /^\/web\/(\d{1,14})(id_|if_)?\/(.+)$/.exec(u.pathname + u.search); if (pc && pageCaptureAnswer(pageCaptures, pc[1], pc[2] ?? "", pc[3], send, res)) return; diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -22,6 +22,7 @@ import { import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts"; +import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage"; import { emptyAccountOlderProblem, fetchPosts, @@ -280,18 +281,23 @@ export async function capturePostsAction( if (!isSocialChannel(config)) { return { ok: false, error: `${slug} is not a social channel.` }; } - await registerBuiltinSocialFetchers(); - const problem = capturePostsProblem( - resolveSocialFetcher(config.postFetcher, config.url), - ); - if (problem) return { ok: false, error: problem }; + // 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) { + await registerBuiltinSocialFetchers(); + const problem = capturePostsProblem( + resolveSocialFetcher(config.postFetcher, config.url), + ); + if (problem) return { ok: false, error: problem }; + } const stray = strayCaptureIds( wanted, await readSeenPostIds(path.join(paths.channelsDir, slug)), ); if (stray) return { ok: false, error: strayIdsRefusal(slug, stray) }; - const key = resolveQueueKey(downloadQueueKey(config), queueKey); + const key = resolveQueueKey(pages ? WAYBACK_PAGES_QUEUE : downloadQueueKey(config), queueKey); return runManagedFunction({ kind: "capture-posts", queueKey: key,