Archilyzer · Source

archilyzer

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

commit f36ae5a1e64cc7d0bf3e2169fbba5bde45ce5f8a
parent 6ca8b210cfee5cbe20de6ac4104fb1946b1a008c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 09:37:48 -0400

wayback pages: the Captures tab, import selected / all in range, wayback.auto in the download lane

The channel page's Captures tab (Overview | Captures on a Wayback pages
channel): the scan as a table, one row per distinct content of a page — path,
first/last seen, version i of n, imported (the record), new since the last
scan — filtered on the server by year, path prefix, text and show, 100 rows a
page; Scan now / Continue scan as a wayback-scan job; Import selected and
Import all in range (a confirm above 50) queue one import-page job per row
through controller/waybackImport.ts (a seam until S1's job is on main; the
e2e server's E2E_IMPORT_PAGE_SEAM_FILE records what would be queued). `pnpm
ops wayback-scan` / `wayback-import`, `archilyzer wayback scan`. The download
lane's wayback.auto unit (controller/laneWaybackAuto.ts): an opted-in
channel's rows listed after its first pass, one import-page job per unit on
the archive.org slot, waited on like the metadata scan's child job.

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

Diffstat:
Mcommon/bin/archilyzer.ts | 20++++++++++++++++++++
Acommon/bin/wayback-scan.ts | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/autoRunner.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/laneWaybackAuto.test.ts | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/laneWaybackAuto.ts | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/waybackImport.test.ts | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/waybackImport.ts | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/scanView.ts | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/wayback-import/route.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/wayback-scan/route.ts | 39+++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/captures/actions.ts | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/captures/components/CapturesPanel.tsx | 340+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/captures/page.tsx | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/ChannelTabs.tsx | 21+++++++++++++++++++--
Meditor/app/channels/[slug]/layout.tsx | 11++++++++++-
Mscripts/archilyzer-ops.mjs | 39+++++++++++++++++++++++++++++++++++++++
16 files changed, 1391 insertions(+), 3 deletions(-)

diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -677,6 +677,26 @@ export const COMMANDS: Command[] = [ }, }, { + path: ["wayback", "scan"], + usage: + "<slug> [--dry-run] [--max-rows N] [--full] list the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json: the CDX API per target, paged with a resume key, collapse=digest, status 200, at most N rows (50000) a run, no bodies; a cut run continues next time, a complete one starts a new pass (--full: from each target's start); paced as archive.org asks, in this process — with the editor running use `pnpm ops wayback-scan`; --dry-run asks nothing and prints the next request per target", + flags: { "dry-run": "boolean", "max-rows": "string", full: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => { + const [slug] = positionals; + if (!slug) { + console.error("wayback scan: which channel? Pass its slug."); + return 2; + } + return (await import("./wayback-scan")).main({ + slug, + dryRun: flags["dry-run"] === true, + full: flags.full === true, + ...(typeof flags["max-rows"] === "string" ? { maxRows: Number(flags["max-rows"]) } : {}), + }); + }, + }, + { path: ["feeds", "backfill-metadata"], usage: "<slug> [--feed <url>] [--dry-run] complete a podcast channel's records (title, date, description, duration) from its RSS feed: one fetch of the feed (default: the channel's url), no media; --dry-run counts matched / unmatched / already complete and writes nothing", diff --git a/common/bin/wayback-scan.ts b/common/bin/wayback-scan.ts @@ -0,0 +1,54 @@ +// `archilyzer wayback scan <slug> [--dry-run] [--max-rows N] [--full]` — a +// Wayback pages channel's CDX scan into its wayback-scan.json +// (controller/waybackScan.ts), in this process: no editor needed. The same +// paced client the editor uses (one request at a time, 2 s apart, 429/503 +// waited out) — its own instance, so with the editor running, scan through +// `pnpm ops wayback-scan` instead and keep archive.org on one queue. No bodies +// are fetched. Prints the run's summary; exit 1 when archive.org refused. + +import { isValidChannelSlug } from "../controller/channels"; +import { readWaybackChannelConfig, runWaybackScan } from "../controller/waybackScan"; +import { SCAN_MAX_ROWS_LIMIT } from "../lib/waybackPages/scanCdx"; +import { getPaths, type Paths } from "../lib/paths"; + +export async function main(opts: { + slug: string; + dryRun: boolean; + full: boolean; + maxRows?: number; + paths?: Paths; +}): Promise<number> { + if (!isValidChannelSlug(opts.slug)) { + console.error(`wayback scan: "${opts.slug}" is not a channel slug`); + return 2; + } + if (opts.maxRows !== undefined && (!Number.isInteger(opts.maxRows) || opts.maxRows < 1 || opts.maxRows > SCAN_MAX_ROWS_LIMIT)) { + console.error(`wayback scan: --max-rows must be a whole number from 1 to ${SCAN_MAX_ROWS_LIMIT}`); + return 2; + } + const paths = opts.paths ?? getPaths(); + const wayback = await readWaybackChannelConfig(paths, opts.slug); + if (!wayback) { + console.error(`wayback scan: ${opts.slug} is not a Wayback pages channel (its config names no wayback.targets)`); + return 2; + } + const r = await runWaybackScan({ + paths, + slug: opts.slug, + wayback, + dryRun: opts.dryRun, + full: opts.full, + ...(opts.maxRows !== undefined ? { maxRows: opts.maxRows } : {}), + onLog: (line) => console.log(line), + }); + console.log( + `${r.dryRun ? "dry run: " : ""}pass ${r.pass}${r.newPass ? " (new)" : ""}: ${r.requests} requests, ${r.rowsRead} rows read, ` + + `${r.added} new, ${r.totalRows} in the scan` + + (r.complete ? " — every target complete" : r.stopped ? ` — stopped: ${r.stopped}` : ""), + ); + if (!r.ok) { + console.error(`wayback scan: ${r.error}`); + return 1; + } + return 0; +} diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts @@ -95,6 +95,13 @@ import { type StoredUrlAttempt, } from "../lib/downloadOutcome"; import { downloadQueueKey } from "../lib/queueKeys"; +import { + launchWaybackAutoImport, + WAYBACK_AUTO_LEAF_ID, + WAYBACK_AUTO_PLATFORM, + WaybackAutoPicker, + type WaybackAutoPick, +} from "./laneWaybackAuto"; import { isGateHeld } from "../lib/pauseGates"; import { inspectChannelMedia, @@ -1176,6 +1183,10 @@ type Picked = { // past a cooling or held platform because its record stores a media URL; it // downloads as `only`, `held` on a held platform. storedOnly?: { held: boolean }; + // THE WAYBACK IMPORT UNIT (release 37 S2, controller/laneWaybackAuto.ts): a + // `wayback.auto` channel's next new scan row, imported by one import-page + // job. Channel-scoped like `scan`: no node's active count moves for it. + waybackImport?: WaybackAutoPick; }; async function runLoop( @@ -1290,6 +1301,9 @@ async function runLoop( // Channels this runner has already scanned (or tried to). See the pre-pick in // next() for why a scan is never retried inside one runner's lifetime. const scannedThisRun = new Set<string>(); + // `wayback.auto` channels' new scan rows (release 37 S2): read once a minute + // per channel, each row offered once in this runner's life. + const waybackAuto = WaybackAutoPicker.forPaths(paths); // Platforms this tick may not touch — busy or cooling down. Hoisted out of the // download branch because the metadata-scan pre-pick honours it too: a // platform in a 429 cooldown must not be asked for 1,800 titles either. @@ -1847,6 +1861,42 @@ async function runLoop( } } + // ── A WAYBACK PAGES CHANNEL'S NEW CAPTURES (release 37 S2) ───────────── + // + // Only a channel whose `wayback.auto` is on: the lane never crawls a host + // nobody opted in. One import-page job per unit, on the `archive.org` + // platform slot (one at a time, the lane's gap and back-off for it), after + // the scans and before the downloads; honours the focus hold. + if (kind === "download") { + const wb = await waybackAuto.pick(metaCache, { + platformSkip, + ...(focus ? { focus: { slugs: new Set(ctx.focusSlugs), holding: focus.holding } } : {}), + }); + if (wb) { + const unitPlatform = WAYBACK_AUTO_PLATFORM; + const videoId = wb.unitId; + const note = `importing a Wayback capture for ${wb.slug}: ${wb.row.replayUrl}`; + live.idleReason = null; + live.inFlight.set(videoId, { + videoId, + leafId: WAYBACK_AUTO_LEAF_ID, + channelSlug: wb.slug, + startedAt: Date.now(), + note, + }); + platformInFlight.set(unitPlatform, (platformInFlight.get(unitPlatform) ?? 0) + 1); + recordPick(kindState, { at: Date.now(), leafId: WAYBACK_AUTO_LEAF_ID, videoId, channelSlug: wb.slug }); + persist(); + onLog(`Auto-download: ${note}.`); + return { + pick: { leafId: WAYBACK_AUTO_LEAF_ID, videoId, path: [] }, + channelSlug: wb.slug, + unitPlatform, + waybackImport: wb, + }; + } + } + const pick = selectNextWork(root, pending, runtime, live.active); if (!pick) { // Attribute the idleness. Nothing pending at all is a different situation @@ -2024,6 +2074,14 @@ async function runLoop( result = { outcome: "skipped" }; return; } + if (picked.waybackImport) { + result = await launchWaybackAutoImport({ + pick: picked.waybackImport, + onLog, + onChildJob: (jid) => { childJobIds.set(pick.videoId, jid); const u = live.inFlight.get(pick.videoId); if (u) u.jobId = jid; }, + }); + return; + } if (picked.scan) { result = await launchMetadataScan({ paths, diff --git a/common/controller/laneWaybackAuto.test.ts b/common/controller/laneWaybackAuto.test.ts @@ -0,0 +1,101 @@ +// `wayback.auto` in the download lane (release 37 S2): which channel's row a +// unit takes (opted in only, the lane's order, the focus hold, the platform +// slot), each row once per runner, the minute-long cache; and a unit's +// import-page job waited on to its end. Synthetic rows; the starter is the +// seam. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/laneWaybackAuto.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "lane-wayback-")); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); + +const { WaybackAutoPicker, waybackAutoOn, awaitJobEnd, launchWaybackAutoImport, WAYBACK_AUTO_PLATFORM } = await import("./laneWaybackAuto"); +const { setImportPageStarterForTest } = await import("./waybackImport"); +const { runManagedFunction } = await import("../jobs/streamCommand"); +const { getPaths } = await import("../lib/paths"); + +const row = (key: string) => + ({ key, originalUrl: key, path: key, digest: "D", firstTs: "20160101000000", lastTs: "20160101000000", count: 1, version: 1, versions: 1, isNew: true, imported: null, replayUrl: `https://web.archive.org/web/20160101000000/${key}` }) as const; + +const on = (targets = [{ url: "a.example", match: "host" }]) => ({ handling: "transcribe", wayback: { targets, auto: true } }); + +test("only opted-in channels, in the lane's order; each row once; none while the platform is skipped or outside a holding focus", async () => { + let reads = 0; + let clock = 0; + const picker = new WaybackAutoPicker({ + pending: async (slug) => { + reads++; + return slug === "b" ? [row("https://b.example/1"), row("https://b.example/2")] : slug === "c" ? [row("https://c.example/1")] : []; + }, + now: () => clock, + ttlMs: 1000, + }); + assert.equal(waybackAutoOn(on()), true); + assert.equal(waybackAutoOn({ wayback: { targets: [{ url: "x" }] } }), false); + assert.equal(waybackAutoOn({}), false); + const channels = [ + { slug: "a", config: { handling: "transcribe", wayback: { targets: [{ url: "a.example" }] } } }, + { slug: "b", config: on() }, + { slug: "c", config: on() }, + ]; + const none = new Set<string>(); + assert.equal(await picker.pick(channels, { platformSkip: new Set([WAYBACK_AUTO_PLATFORM]) }), null); + const p1 = await picker.pick(channels, { platformSkip: none }); + assert.equal(p1?.slug, "b"); + assert.equal(p1?.row.key, "https://b.example/1"); + assert.equal(p1?.unitId, "wayback-import b https://b.example/1"); + assert.equal((await picker.pick(channels, { platformSkip: none }))?.row.key, "https://b.example/2"); + assert.equal((await picker.pick(channels, { platformSkip: none }))?.slug, "c"); + assert.equal(await picker.pick(channels, { platformSkip: none }), null, "each row once in a runner's life"); + const readsBefore = reads; + await picker.pick(channels, { platformSkip: none }); + assert.equal(reads, readsBefore, "cached inside the TTL"); + clock = 5000; + await picker.pick(channels, { platformSkip: none }); + assert.ok(reads > readsBefore, "re-read after the TTL"); + const focused = new WaybackAutoPicker({ pending: async (slug) => [row(`https://${slug}.example/1`)] }); + assert.equal((await focused.pick(channels, { platformSkip: none, focus: { slugs: new Set(["c"]), holding: true } }))?.slug, "c"); + assert.equal((await focused.pick(channels, { platformSkip: none, focus: { slugs: new Set(["c"]), holding: false } }))?.slug, "b"); +}); + +test("a unit: the row's import-page job, waited on to its end; a refusal is a skip", async () => { + const paths = getPaths(); + const pick = { slug: "b", row: row("https://b.example/1"), unitId: "u" }; + for (const [fail, outcome] of [[false, "transcribed"], [true, "failed"]] as const) { + setImportPageStarterForTest(async () => { + const r = await runManagedFunction({ + kind: "import-page-test", + queueKey: "", + paths, + fn: async () => { + await new Promise((res) => setTimeout(res, 20)); + if (fail) throw new Error("no"); + }, + }); + if (!r.ok) throw new Error(r.error); + void r.stream.cancel(); + return { jobId: r.jobId }; + }); + let child = ""; + const lines: string[] = []; + const out = await launchWaybackAutoImport({ pick, onLog: (l) => lines.push(l), onChildJob: (j) => (child = j) }); + assert.equal(out.outcome, outcome); + assert.ok(child); + assert.ok(["done", "failed"].includes(await awaitJobEnd(child)), "an ended job answers at once"); + } + setImportPageStarterForTest(async () => { + throw new Error("held"); + }); + const lines: string[] = []; + assert.deepEqual(await launchWaybackAutoImport({ pick, onLog: (l) => lines.push(l) }), { outcome: "skipped" }); + assert.match(lines[0], /could not queue the Wayback import .*: held/); + setImportPageStarterForTest(async () => ({ jobId: "seam-1" })); + assert.deepEqual(await launchWaybackAutoImport({ pick, onLog: () => {} }), { outcome: "skipped" }, "an id the registry does not hold"); + setImportPageStarterForTest(null); +}); diff --git a/common/controller/laneWaybackAuto.ts b/common/controller/laneWaybackAuto.ts @@ -0,0 +1,123 @@ +// `wayback.auto` IN THE DOWNLOAD LANE (release 37 S2): a Wayback pages channel +// that opts in has its new scan rows imported by the lane — one row per unit, +// one `import-page` job per row (controller/waybackImport.ts), on archive.org's +// queue, waited on like the metadata scan's child job, at the lane's pace for +// the `archive.org` platform (one unit at a time; the gap and back-off its +// outcomes earn). Default off: no unattended crawling of a host unless the +// channel opts in. +// +// What a unit takes is `pendingAutoImports`: rows first listed after the +// channel's first pass that no record holds yet, oldest first. A channel's list +// is read at most once a minute (the scan file and the channel's posts), and a +// row the runner has tried is not offered again in its lifetime — a failed +// import waits for the operator or a restart, never a re-hammer. + +import type { Paths } from "../lib/paths"; +import { onJobEnd, getRegistry, type JobStatus } from "../jobs/registry"; +import { waybackConfigOf } from "../lib/waybackPages/targets"; +import type { CaptureRowView } from "../lib/waybackPages/scanView"; +import { pendingAutoImports, startCaptureImport } from "./waybackImport"; + +export const WAYBACK_AUTO_LEAF_ID = "wayback-auto"; +export const WAYBACK_AUTO_UNIT_PREFIX = "wayback-import "; +// The platform key a unit holds: one Wayback import at a time in the lane. +export const WAYBACK_AUTO_PLATFORM = "archive.org"; +export const WAYBACK_AUTO_TTL_MS = 60_000; + +export function waybackAutoOn(config: unknown): boolean { + return waybackConfigOf(config)?.auto === true; +} + +export type WaybackAutoPick = { slug: string; row: CaptureRowView; unitId: string }; + +export class WaybackAutoPicker { + private readonly cache = new Map<string, { at: number; rows: CaptureRowView[] }>(); + private readonly tried = new Set<string>(); + constructor( + private readonly deps: { + pending: (slug: string) => Promise<CaptureRowView[]>; + now?: () => number; + ttlMs?: number; + }, + ) {} + + static forPaths(paths: Paths): WaybackAutoPicker { + return new WaybackAutoPicker({ pending: (slug) => pendingAutoImports(paths, slug) }); + } + + private async rowsOf(slug: string): Promise<CaptureRowView[]> { + const now = (this.deps.now ?? Date.now)(); + const hit = this.cache.get(slug); + if (hit && now - hit.at < (this.deps.ttlMs ?? WAYBACK_AUTO_TTL_MS)) return hit.rows; + const rows = await this.deps.pending(slug).catch(() => [] as CaptureRowView[]); + this.cache.set(slug, { at: now, rows }); + return rows; + } + + // The next row to import: the first opted-in channel (in the lane's order) + // with a row not tried yet. None while the platform is skipped (busy, + // cooling, held, paced) or, under a holding focus, outside it. + async pick( + channels: ReadonlyArray<{ slug: string; config: unknown }>, + opts: { platformSkip: ReadonlySet<string>; focus?: { slugs: ReadonlySet<string>; holding: boolean } }, + ): Promise<WaybackAutoPick | null> { + if (opts.platformSkip.has(WAYBACK_AUTO_PLATFORM)) return null; + for (const c of channels) { + if (!waybackAutoOn(c.config)) continue; + if (opts.focus?.holding && !opts.focus.slugs.has(c.slug)) continue; + for (const row of await this.rowsOf(c.slug)) { + const unitId = `${WAYBACK_AUTO_UNIT_PREFIX}${c.slug} ${row.key}`; + if (this.tried.has(unitId)) continue; + this.tried.add(unitId); + return { slug: c.slug, row, unitId }; + } + } + return null; + } +} + +// A job's end: its terminal status, or "unknown" for an id the registry does +// not hold (the e2e seam's). +export function awaitJobEnd(jobId: string): Promise<JobStatus | "unknown"> { + const terminal = (s: JobStatus | undefined) => s === "done" || s === "failed" || s === "cancelled"; + const now = getRegistry().get(jobId); + if (!now) return Promise.resolve("unknown"); + if (terminal(now.status)) return Promise.resolve(now.status); + return new Promise((resolve) => { + const stop = onJobEnd((j) => { + if (j.id !== jobId) return; + stop(); + resolve(j.status); + }); + // The end may have landed between the read above and the listener. + const again = getRegistry().get(jobId); + if (again && terminal(again.status)) { + stop(); + resolve(again.status); + } + }); +} + +// ONE UNIT: the row's import-page job, waited on. "transcribed" (the lane's +// word for done), "failed", or "skipped" (refused before a job, or cancelled). +export async function launchWaybackAutoImport(args: { + pick: WaybackAutoPick; + onLog: (line: string) => void; + onChildJob?: (jobId: string) => void; +}): Promise<{ outcome: "transcribed" | "failed" | "skipped" }> { + let jobId: string; + try { + ({ jobId } = await startCaptureImport(args.pick.slug, args.pick.row, "auto-download")); + } catch (e) { + args.onLog(`Auto-download: could not queue the Wayback import of ${args.pick.row.replayUrl}: ${(e as Error).message}`); + return { outcome: "skipped" }; + } + args.onChildJob?.(jobId); + const end = await awaitJobEnd(jobId); + if (end === "done") return { outcome: "transcribed" }; + if (end === "failed") { + args.onLog(`Auto-download: the Wayback import of ${args.pick.row.replayUrl} failed.`); + return { outcome: "failed" }; + } + return { outcome: "skipped" }; +} diff --git a/common/controller/waybackImport.test.ts b/common/controller/waybackImport.test.ts @@ -0,0 +1,138 @@ +// Queueing imports of chosen scan rows (release 37 S2): by key, by the +// table's filter, a dry run, the batch cap, a refusal, and what wayback.auto +// would take — one import-page request per row, through the seam (S1's job is +// not in this build yet). Synthetic scan files only. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/waybackImport.test.ts + +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "wayback-import-")); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +after(() => rm(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { emptyScanFile, mergeCdxRows, summarizeScan } = await import("../lib/waybackPages/scanFile"); +const { writeWaybackScan } = await import("../lib/waybackPages/scanFile-server"); +const { + IMPORT_BATCH_MAX, + pendingAutoImports, + queueCaptureImports, + setImportPageStarterForTest, +} = await import("./waybackImport"); + +const row = (originalUrl: string, timestamp: string, digest: string) => ({ originalUrl, timestamp, digest, mimetype: "text/html", status: 200 }); + +async function scan(slug: string, pass1: ReturnType<typeof row>[], pass2: ReturnType<typeof row>[] = []) { + await mkdir(path.join(getPaths().channelsDir, slug), { recursive: true }); + const file = emptyScanFile(slug, "2026-01-01T00:00:00.000Z"); + mergeCdxRows(file, pass1); + if (pass2.length) { + file.pass = 2; + mergeCdxRows(file, pass2); + } + file.summary = summarizeScan(file.rows); + await writeWaybackScan(getPaths().channelsDir, file); +} + +const asked: unknown[] = []; +setImportPageStarterForTest(async (req) => { + asked.push(req); + return { jobId: `job-${asked.length}` }; +}); + +await scan( + "blog", + [ + row("https://blog.example/", "20140102030405", "HOMEA"), + row("https://blog.example/post/1", "20140203000000", "P1A"), + row("https://blog.example/post/1", "20150203000000", "P1B"), + row("https://blog.example/post/2", "20150506000000", "P2A"), + ], + [row("https://blog.example/post/3", "20160101000000", "P3A")], +); + +test("by key: one import-page request per row, the capture it was first listed at; an unknown key is skipped", async () => { + asked.length = 0; + const r = await queueCaptureImports({ + paths: getPaths(), + slug: "blog", + keys: ["P1B https://blog.example/post/1", "NOPE https://blog.example/x", "P1B https://blog.example/post/1"], + requestedBy: "captures", + }); + assert.equal(r.ok, true); + assert.equal(r.chosen, 1); + assert.deepEqual(asked, [{ slug: "blog", url: "https://web.archive.org/web/20150203000000/https://blog.example/post/1", requestedBy: "captures" }]); + assert.deepEqual(r.queued, [{ key: "P1B https://blog.example/post/1", url: "https://web.archive.org/web/20150203000000/https://blog.example/post/1", jobId: "job-1" }]); + assert.deepEqual(r.skipped, [{ key: "NOPE https://blog.example/x", why: "not in the scan" }]); +}); + +test("by filter (Import all in range): year, prefix, text, new; a dry run queues nothing", async () => { + asked.length = 0; + const y = await queueCaptureImports({ paths: getPaths(), slug: "blog", filter: { year: "2015" } }); + assert.deepEqual(y.queued.map((q) => q.key), ["P1B https://blog.example/post/1", "P2A https://blog.example/post/2"]); + const p = await queueCaptureImports({ paths: getPaths(), slug: "blog", filter: { prefix: "blog.example/post/" }, dryRun: true }); + assert.equal(p.queued.length, 4); + assert.equal(p.queued.every((q) => q.jobId === undefined), true); + const n = await queueCaptureImports({ paths: getPaths(), slug: "blog", filter: { show: "new" }, dryRun: true }); + assert.deepEqual(n.queued.map((q) => q.key), ["P3A https://blog.example/post/3"]); + const q = await queueCaptureImports({ paths: getPaths(), slug: "blog", filter: { q: "POST/2" }, dryRun: true }); + assert.deepEqual(q.queued.map((x) => x.key), ["P2A https://blog.example/post/2"]); + assert.equal(asked.length, 2, "only the real run asked"); +}); + +test("no scan is a refusal; a starter's refusal stops the batch with its sentence", async () => { + const none = await queueCaptureImports({ paths: getPaths(), slug: "nothing", filter: {} }); + assert.equal(none.ok, false); + assert.match(none.error ?? "", /no Wayback scan yet/); + setImportPageStarterForTest(async () => { + throw new Error("the platform is held"); + }); + try { + const r = await queueCaptureImports({ paths: getPaths(), slug: "blog", filter: {} }); + assert.equal(r.ok, false); + assert.equal(r.error, "the platform is held"); + assert.equal(r.queued.length, 0); + } finally { + setImportPageStarterForTest(async (req) => { + asked.push(req); + return { jobId: `job-${asked.length}` }; + }); + } +}); + +test("at most IMPORT_BATCH_MAX a call; the rest are left for the next", async () => { + const many = Array.from({ length: IMPORT_BATCH_MAX + 7 }, (_, i) => row(`https://many.example/p/${i}`, `2014010100${String(i).padStart(4, "0")}`, `D${i}`)); + await scan("many", many); + const r = await queueCaptureImports({ paths: getPaths(), slug: "many", filter: {}, dryRun: true }); + assert.equal(r.chosen, IMPORT_BATCH_MAX + 7); + assert.equal(r.queued.length, IMPORT_BATCH_MAX); + assert.equal(r.left, 7); +}); + +test("wayback.auto takes the rows listed after the first pass, oldest first", async () => { + const pending = await pendingAutoImports(getPaths(), "blog"); + assert.deepEqual(pending.map((r) => r.key), ["P3A https://blog.example/post/3"]); + assert.deepEqual(await pendingAutoImports(getPaths(), "nothing"), []); +}); + +test("the e2e seam: E2E_IMPORT_PAGE_SEAM_FILE records each request", async () => { + setImportPageStarterForTest(null); + const seam = path.join(ROOT, "seam.jsonl"); + process.env.E2E_IMPORT_PAGE_SEAM_FILE = seam; + try { + const r = await queueCaptureImports({ paths: getPaths(), slug: "blog", keys: ["HOMEA https://blog.example/"] }); + assert.equal(r.ok, true); + assert.match(r.queued[0].jobId ?? "", /^seam-\d+$/); + assert.deepEqual(JSON.parse((await readFile(seam, "utf8")).trim()), { slug: "blog", url: "https://web.archive.org/web/20140102030405/https://blog.example/" }); + } finally { + delete process.env.E2E_IMPORT_PAGE_SEAM_FILE; + } + const refused = await queueCaptureImports({ paths: getPaths(), slug: "blog", keys: ["HOMEA https://blog.example/"] }); + assert.equal(refused.ok, false); + assert.match(refused.error ?? "", /import-page job/); +}); diff --git a/common/controller/waybackImport.ts b/common/controller/waybackImport.ts @@ -0,0 +1,130 @@ +// IMPORTING CHOSEN SCAN ROWS (release 37 S2): the Captures tab's Import selected +// and Import all in range, `pnpm ops wayback-import`, and the download lane's +// `wayback.auto` pick all end here — one `import-page` job per row (S1's job, +// controller/importPage.ts), queued on archive.org's queue, so they run one at +// a time at its pace. A row already imported (a webpage record holds its +// content, imported.ts) is skipped; at most IMPORT_BATCH_MAX are queued per +// call. Each job takes the capture the row was first listed at — exactly that +// content. + +import type { Paths } from "../lib/paths"; +import { appendFile } from "node:fs/promises"; +import { readImportedIndex, readWaybackScan } from "../lib/waybackPages/scanFile-server"; +import { + captureRows, + filterCaptureRows, + type CaptureFilter, + type CaptureRowView, +} from "../lib/waybackPages/scanView"; + +export type ImportPageRequest = { slug: string; url: string; at?: string; requestedBy?: string }; +export type ImportPageStarter = (req: ImportPageRequest) => Promise<{ jobId: string }>; + +// At most this many jobs per call: a 50,000-row range is queued a batch at a +// time, never as 50,000 records at once. +export const IMPORT_BATCH_MAX = 500; + +export const WAYBACK_IMPORT_BODY_KEYS = ["slug", "keys", "year", "prefix", "q", "show", "dryRun"] as const; + +// THE SEAM to `import-page`. Until S1's job is in the build, the default refuses +// — except on the editor's e2e server, where E2E_IMPORT_PAGE_SEAM_FILE names a +// file each request is appended to (one JSON line) so a spec can read what +// would have been queued. +let seamCount = 0; +async function defaultStarter(req: ImportPageRequest): Promise<{ jobId: string }> { + const file = process.env.E2E_IMPORT_PAGE_SEAM_FILE; + if (file) { + await appendFile(file, `${JSON.stringify(req)}\n`); + return { jobId: `seam-${++seamCount}` }; + } + throw new Error("Importing a capture needs the import-page job (release 37 S1), which is not in this build."); +} + +let starter: ImportPageStarter = defaultStarter; + +// Tests (and nothing else) swap the starter. +export function setImportPageStarterForTest(fn: ImportPageStarter | null): void { + starter = fn ?? defaultStarter; +} + +export type CaptureImportResult = { + ok: boolean; + error?: string; + slug: string; + dryRun: boolean; + // Rows the selection or the range named. + chosen: number; + queued: { key: string; url: string; jobId?: string }[]; + skipped: { key: string; why: string }[]; + // Rows left for another call (over IMPORT_BATCH_MAX). + left: number; +}; + +export type QueueCaptureImportsOpts = { + paths: Paths; + slug: string; + // The rows by key (`<digest> <originalUrl>`), or every row the filter keeps. + keys?: ReadonlyArray<string>; + filter?: CaptureFilter; + dryRun?: boolean; + requestedBy?: string; +}; + +export async function queueCaptureImports(opts: QueueCaptureImportsOpts): Promise<CaptureImportResult> { + const base = { slug: opts.slug, dryRun: opts.dryRun === true, chosen: 0, queued: [], skipped: [], left: 0 }; + const file = await readWaybackScan(opts.paths.channelsDir, opts.slug); + if (!file) return { ...base, ok: false, error: `${opts.slug} has no Wayback scan yet: scan it first.` }; + const rows = captureRows(file, await readImportedIndex(opts.paths.channelsDir, opts.slug)); + const out: CaptureImportResult = { ...base, ok: true, queued: [], skipped: [] }; + let chosen: CaptureRowView[]; + if (opts.keys) { + const byKey = new Map(rows.map((r) => [r.key, r])); + chosen = []; + for (const key of new Set(opts.keys)) { + const r = byKey.get(key); + if (r) chosen.push(r); + else out.skipped.push({ key, why: "not in the scan" }); + } + } else { + chosen = filterCaptureRows(rows, opts.filter ?? {}); + } + out.chosen = chosen.length; + const todo: CaptureRowView[] = []; + for (const r of chosen) { + if (r.imported) out.skipped.push({ key: r.key, why: `imported as ${r.imported.id}` }); + else todo.push(r); + } + out.left = Math.max(0, todo.length - IMPORT_BATCH_MAX); + for (const r of todo.slice(0, IMPORT_BATCH_MAX)) { + if (opts.dryRun) { + out.queued.push({ key: r.key, url: r.replayUrl }); + continue; + } + try { + const { jobId } = await starter({ slug: opts.slug, url: r.replayUrl, ...(opts.requestedBy ? { requestedBy: opts.requestedBy } : {}) }); + out.queued.push({ key: r.key, url: r.replayUrl, jobId }); + } catch (e) { + // A refusal of the first is a refusal of all (the same channel, the same job). + return { ...out, ok: false, error: (e as Error).message }; + } + } + return out; +} + +// ONE ROW, for the download lane's `wayback.auto` unit. +export async function startCaptureImport(slug: string, row: Pick<CaptureRowView, "replayUrl">, requestedBy: string): Promise<{ jobId: string }> { + return starter({ slug, url: row.replayUrl, requestedBy }); +} + +// What `wayback.auto` imports: rows first listed after the channel's first +// pass (a capture the Wayback Machine took, or indexed, since the channel's +// scope was first listed) that no record holds yet, oldest first. The first +// pass's rows are the operator's to choose. +export async function pendingAutoImports(paths: Paths, slug: string): Promise<CaptureRowView[]> { + const file = await readWaybackScan(paths.channelsDir, slug); + if (!file) return []; + const pass1 = new Set(file.rows.filter((r) => r.pass <= 1).map((r) => `${r.digest} ${r.originalUrl}`)); + return captureRows(file, await readImportedIndex(paths.channelsDir, slug)) + .filter((r) => !r.imported && !pass1.has(r.key)) + .sort((a, b) => a.firstTs.localeCompare(b.firstTs) || a.key.localeCompare(b.key)); +} diff --git a/common/lib/waybackPages/scanView.ts b/common/lib/waybackPages/scanView.ts @@ -0,0 +1,119 @@ +// THE CAPTURES TABLE (release 37 S2): a Wayback pages channel's scan rows as +// the channel page's Captures tab shows them, and the filter the tab, Import +// all in range and the download lane's `wayback.auto` pick share. Pure, +// client-safe. + +import { waybackReplayUrl } from "../waybackClient"; +import { importedRecordOf, type ImportedIndex, type ImportedRecordRef } from "./imported"; +import { displayPathOf, hostsOf, isNewRow, type WaybackScanFile, type WaybackScanRow } from "./scanFile"; + +export type CaptureRowView = { + // `<digest> <originalUrl>`: what a selection names. + key: string; + originalUrl: string; + path: string; + digest: string; + firstTs: string; + lastTs: string; + count: number; + // This content's place among the URL's versions (1 = the earliest), of + // `versions`. + version: number; + versions: number; + isNew: boolean; + imported: ImportedRecordRef | null; + // The capture an import of this row takes: the content's first listing. + replayUrl: string; +}; + +export type CaptureShow = "all" | "new" | "not-imported" | "imported"; +export const CAPTURE_SHOW_VALUES: readonly CaptureShow[] = ["all", "new", "not-imported", "imported"]; + +export type CaptureFilter = { + // YYYY of first seen. + year?: string; + // A path prefix as the summary names it ("blog.example/post/"): host first, + // no scheme, no www. + prefix?: string; + // Free text, over the original URL (case-insensitive). + q?: string; + show?: CaptureShow; +}; + +export function captureRowKey(r: Pick<WaybackScanRow, "digest" | "originalUrl">): string { + return `${r.digest} ${r.originalUrl}`; +} + +// Every row, in table order (by URL, then first seen), with its version +// ordinal, new mark and imported record. +export function captureRows(file: WaybackScanFile, index: ImportedIndex): CaptureRowView[] { + const withHost = hostsOf(file.rows).size > 1; + const byUrl = new Map<string, WaybackScanRow[]>(); + for (const r of file.rows) { + const list = byUrl.get(r.originalUrl) ?? []; + list.push(r); + byUrl.set(r.originalUrl, list); + } + const out: CaptureRowView[] = []; + for (const url of [...byUrl.keys()].sort()) { + const list = byUrl.get(url)!.sort((a, b) => a.firstTs.localeCompare(b.firstTs)); + list.forEach((r, i) => { + out.push({ + key: captureRowKey(r), + originalUrl: r.originalUrl, + path: displayPathOf(r.originalUrl, withHost), + digest: r.digest, + firstTs: r.firstTs, + lastTs: r.lastTs, + count: r.count, + version: i + 1, + versions: list.length, + isNew: isNewRow(file, r), + imported: importedRecordOf(r, index), + replayUrl: waybackReplayUrl(r.firstTs, r.originalUrl), + }); + }); + } + return out; +} + +export function filterCaptureRows(rows: ReadonlyArray<CaptureRowView>, f: CaptureFilter): CaptureRowView[] { + const q = f.q?.trim().toLowerCase(); + return rows.filter((r) => { + if (f.year && r.firstTs.slice(0, 4) !== f.year) return false; + if (f.prefix && !displayPathOf(r.originalUrl, true).startsWith(f.prefix)) return false; + if (q && !r.originalUrl.toLowerCase().includes(q)) return false; + switch (f.show ?? "all") { + case "new": + return r.isNew; + case "not-imported": + return !r.imported; + case "imported": + return !!r.imported; + default: + return true; + } + }); +} + +// A filter from a URL's search params (the tab's own links). +export function captureFilterFrom(sp: Record<string, string | string[] | undefined>): CaptureFilter { + const one = (k: string) => { + const v = sp[k]; + const s = Array.isArray(v) ? v[0] : v; + return typeof s === "string" && s.trim() ? s.trim() : undefined; + }; + const year = one("year"); + const show = one("show"); + return { + ...(year && /^\d{4}$/.test(year) ? { year } : {}), + ...(one("prefix") ? { prefix: one("prefix") } : {}), + ...(one("q") ? { q: one("q") } : {}), + ...(show && (CAPTURE_SHOW_VALUES as readonly string[]).includes(show) ? { show: show as CaptureShow } : {}), + }; +} + +// Rows per page of the table. +export const CAPTURES_PAGE_SIZE = 100; +// Import all in range asks for a confirmation above this many. +export const IMPORT_CONFIRM_ABOVE = 50; diff --git a/editor/app/api/ops/wayback-import/route.ts b/editor/app/api/ops/wayback-import/route.ts @@ -0,0 +1,50 @@ +import { NextResponse } from "next/server"; +import { WAYBACK_IMPORT_BODY_KEYS } from "yt-dlp-transcript-common/controller/waybackImport"; +import { CAPTURE_SHOW_VALUES, type CaptureShow } from "yt-dlp-transcript-common/lib/waybackPages/scanView"; +import { importCapturesAction } from "../../../channels/[slug]/captures/actions"; +import { OpsInputError, ops, opsFail, optBool, optString, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, keys? | year?, prefix?, q?, show?, dryRun? } -> { ok, slug, +// dryRun, chosen, queued: [{key, url, jobId?}], skipped: [{key, why}], left } +// +// Imports chosen rows of a Wayback pages channel's scan (release 37 S2): one +// `import-page` job per row, each the capture the row's content was first +// listed at, queued on archive.org's queue (they run one at a time at its +// pace). `keys` names rows as the Captures tab does (`<digest> <originalUrl>`); +// without it, every row the tab's filter keeps — `year` (first seen), `prefix` +// ("blog.example/post/": host first, no scheme), `q` (text in the URL), `show` +// (all | new | not-imported | imported) — is Import all in range. A row already +// imported is skipped; at most 500 are queued a call (`left` says how many +// remain). `dryRun` says what would be queued and queues nothing. +// +// AN ADAPTER: the refusals are the controller's (controller/waybackImport.ts). +export async function POST(request: Request) { + return ops(request, WAYBACK_IMPORT_BODY_KEYS, async (body) => { + const slug = reqSlug(body, "slug"); + const keys = body.keys; + if (keys !== undefined && (!Array.isArray(keys) || keys.some((k) => typeof k !== "string" || !k.trim()))) { + throw new OpsInputError('"keys" must be a list of row keys ("<digest> <originalUrl>")'); + } + const show = optString(body, "show"); + if (show !== undefined && !(CAPTURE_SHOW_VALUES as readonly string[]).includes(show)) { + throw new OpsInputError(`"show" must be one of ${CAPTURE_SHOW_VALUES.join(", ")}`); + } + const year = optString(body, "year"); + if (year !== undefined && !/^\d{4}$/.test(year)) throw new OpsInputError('"year" must be YYYY'); + const filterKeys = ["year", "prefix", "q", "show"].filter((k) => body[k] !== undefined); + if (keys !== undefined && filterKeys.length) throw new OpsInputError(`send "keys" or a range (${filterKeys.join(", ")}), not both`); + const prefix = optString(body, "prefix"); + const q = optString(body, "q"); + const r = await importCapturesAction( + slug, + keys !== undefined + ? { keys: keys as string[] } + : { filter: { ...(year ? { year } : {}), ...(prefix ? { prefix } : {}), ...(q ? { q } : {}), ...(show ? { show: show as CaptureShow } : {}) } }, + { dryRun: optBool(body, "dryRun") === true, requestedBy: "ops" }, + ); + if (!r.ok) return opsFail(r.error ?? "the import was refused", 409, { queued: r.queued, skipped: r.skipped }); + return NextResponse.json(r); + }); +} diff --git a/editor/app/api/ops/wayback-scan/route.ts b/editor/app/api/ops/wayback-scan/route.ts @@ -0,0 +1,39 @@ +import { WAYBACK_SCAN_BODY_KEYS } from "yt-dlp-transcript-common/controller/waybackScan"; +import { waybackScanAction } from "../../../channels/[slug]/captures/actions"; +import { jobResponse, ops, optBool, optPositiveInt, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, dryRun?, maxRows?, full? } -> { ok: true, jobId } +// +// A Wayback pages channel's scan (release 37 S2), as a `wayback-scan` job on +// archive.org's queue: the CDX listing of every target in its +// `config.wayback.targets` (matchType per target, status 200, its mimes, +// collapse=digest, its date bounds), in pages of 5,000, at most `maxRows` +// (50,000, at most 200,000) a run, into `channels/<slug>/wayback-scan.json` — +// one row per distinct (URL, digest) with first/last seen. No bodies. A run cut +// short keeps each target's resume key and the next continues; once every +// target is complete the next run is a new pass (from 30 days before the last +// began); `full` starts a new pass from each target's start. Paced as +// archive.org asks (one at a time, 2 s apart, 429/503 waited out; a refusal +// stops the job and keeps the resume key). `dryRun` asks nothing and writes +// nothing: it logs what the next run would ask. Refused before any job for a +// channel with no `wayback.targets`. The log ends `@@wayback-scan {slug, +// dryRun, pass, newPass, targets: [{url, match, requests, rows, added, +// complete, resumeKey?, next?}], requests, rowsRead, added, totalRows, +// complete, stopped?, error?}`. +// +// AN ADAPTER: the refusals are the controller's (controller/waybackScan.ts). +export async function POST(request: Request) { + return ops(request, WAYBACK_SCAN_BODY_KEYS, async (body) => { + const slug = reqSlug(body, "slug"); + const maxRows = optPositiveInt(body, "maxRows"); + return jobResponse( + await waybackScanAction(slug, { + dryRun: optBool(body, "dryRun") === true, + full: optBool(body, "full") === true, + ...(maxRows !== undefined ? { maxRows } : {}), + }), + ); + }); +} diff --git a/editor/app/channels/[slug]/captures/actions.ts b/editor/app/channels/[slug]/captures/actions.ts @@ -0,0 +1,62 @@ +"use server"; + +// THE CAPTURES TAB'S ACTIONS (release 37 S2), and `pnpm ops wayback-scan` / +// `wayback-import` over HTTP: one code path for the button and the agent. +// +// waybackScanAction a `wayback-scan` job on archive.org's queue +// (controller/waybackScan.ts) — Scan now / Continue scan. +// importCapturesAction one `import-page` job per chosen row +// (controller/waybackImport.ts) — Import selected (keys) +// and Import all in range (the table's filter). +// +// Refusals are the controllers' sentences. A scan or an import that wrote +// anything revalidates the tab. + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { startWaybackScanJob } from "yt-dlp-transcript-common/controller/waybackScan"; +import { queueCaptureImports, type CaptureImportResult } from "yt-dlp-transcript-common/controller/waybackImport"; +import type { CaptureFilter } from "yt-dlp-transcript-common/lib/waybackPages/scanView"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { safeRevalidate } from "../../../lib/safeRevalidate"; + +const revalidate = (slug: string) => safeRevalidate([`/channels/${slug}`, `/channels/${slug}/captures`]); + +export async function waybackScanAction( + slug: string, + opts: { dryRun?: boolean; maxRows?: number; full?: boolean } = {}, +): Promise<StreamActionResult> { + return startWaybackScanJob( + { + slug, + ...(opts.dryRun ? { dryRun: true } : {}), + ...(opts.maxRows !== undefined ? { maxRows: opts.maxRows } : {}), + ...(opts.full ? { full: true } : {}), + }, + { paths: getPaths(), onDone: revalidate }, + ); +} + +// The button's form: a job id, or the refusal. +export async function startWaybackScanFromTab(slug: string, full: boolean): Promise<{ ok: true; jobId: string } | { ok: false; error: string }> { + const r = await waybackScanAction(slug, full ? { full: true } : {}); + if (!r.ok) return { ok: false, error: r.error }; + // Nobody reads the stream: the log is on disk, the tab polls nothing. + void r.stream.cancel().catch(() => {}); + return { ok: true, jobId: r.jobId }; +} + +export async function importCapturesAction( + slug: string, + choice: { keys: string[] } | { filter: CaptureFilter }, + opts: { dryRun?: boolean; requestedBy?: string } = {}, +): Promise<CaptureImportResult> { + const r = await queueCaptureImports({ + paths: getPaths(), + slug, + ...("keys" in choice ? { keys: choice.keys } : { filter: choice.filter }), + ...(opts.dryRun ? { dryRun: true } : {}), + requestedBy: opts.requestedBy ?? "captures", + }); + if (r.queued.length > 0 && !r.dryRun) revalidate(slug); + return r; +} diff --git a/editor/app/channels/[slug]/captures/components/CapturesPanel.tsx b/editor/app/channels/[slug]/captures/components/CapturesPanel.tsx @@ -0,0 +1,340 @@ +"use client"; + +import Link from "next/link"; +import Form from "next/form"; +import { useRouter } from "next/navigation"; +import { useState, useTransition } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cdxTsDate } from "yt-dlp-transcript-common/lib/waybackPages/scanFile"; +import { + IMPORT_CONFIRM_ABOVE, + type CaptureFilter, + type CaptureRowView, +} from "yt-dlp-transcript-common/lib/waybackPages/scanView"; +import type { CaptureImportResult } from "yt-dlp-transcript-common/controller/waybackImport"; +import { importCapturesAction, waybackScanAction } from "../actions"; +import { cancelJobAction } from "../../../../jobs/actions"; + +// THE CAPTURES TAB'S PANEL (release 37 S2). The server hands it one page of +// already-filtered rows; the filter is the URL's (a GET form), so a 50,000-row +// scan never reaches the browser. Selection is per page; Import all in range +// is the filter, sent back and re-applied on the server. + +export type CapturesStatus = { + scanned: boolean; + versions: number; + pages: number; + imported: number; + newRows: number; + lastScanAt?: string; + lastScanJobId?: string; + pass: number; + complete: boolean; + targets: { url: string; match: string; complete: boolean; rows: number; resumable: boolean }[]; + auto: boolean; + liveScanJobId?: string; +}; + +type Props = { + slug: string; + status: CapturesStatus; + rows: CaptureRowView[]; + matching: number; + matchingToImport: number; + page: number; + pages: number; + filter: CaptureFilter; + years: string[]; + prefixes: string[]; +}; + +const n = (x: number) => x.toLocaleString("en-US"); +const plural = (x: number, one: string, many = `${one}s`) => `${n(x)} ${x === 1 ? one : many}`; +const when = (iso: string) => `${iso.slice(0, 16).replace("T", " ")} UTC`; + +function hrefWith(slug: string, filter: CaptureFilter, page?: number): string { + const q = new URLSearchParams(); + if (filter.year) q.set("year", filter.year); + if (filter.prefix) q.set("prefix", filter.prefix); + if (filter.q) q.set("q", filter.q); + if (filter.show && filter.show !== "all") q.set("show", filter.show); + if (page && page > 1) q.set("page", String(page)); + const s = q.toString(); + return `/channels/${slug}/captures${s ? `?${s}` : ""}`; +} + +function importLine(r: CaptureImportResult): string { + if (!r.ok) return r.error ?? "The import was refused."; + const parts = [`Queued ${plural(r.queued.length, "import job")}`]; + const imported = r.skipped.filter((s) => s.why.startsWith("imported")).length; + if (imported) parts.push(`${n(imported)} already imported`); + const gone = r.skipped.length - imported; + if (gone) parts.push(`${n(gone)} no longer in the scan`); + if (r.left) parts.push(`${n(r.left)} left: import the range again for the rest`); + return `${parts.join("; ")}.`; +} + +export function CapturesPanel({ slug, status, rows, matching, matchingToImport, page, pages, filter, years, prefixes }: Props) { + const router = useRouter(); + const [selected, setSelected] = useState<Set<string>>(new Set()); + const [confirming, setConfirming] = useState(false); + const [result, setResult] = useState<CaptureImportResult | null>(null); + const [pending, startTransition] = useTransition(); + const selectable = rows.filter((r) => !r.imported); + const allOnPage = selectable.length > 0 && selectable.every((r) => selected.has(r.key)); + + const toggle = (key: string) => + setSelected((s) => { + const next = new Set(s); + if (next.has(key)) next.delete(key); + else next.add(key); + return next; + }); + + const run = (choice: { keys: string[] } | { filter: CaptureFilter }) => + startTransition(async () => { + const r = await importCapturesAction(slug, choice); + setResult(r); + setConfirming(false); + if (r.ok) setSelected(new Set()); + router.refresh(); + }); + + const scanLabel = !status.scanned || status.complete ? "Scan now" : "Continue scan"; + const statusLine = !status.scanned + ? "Not scanned yet" + : [ + `${plural(status.versions, "version")} of ${plural(status.pages, "page")}`, + `${n(status.imported)} imported`, + ...(status.newRows ? [`${n(status.newRows)} new since the last scan`] : []), + ...(status.lastScanAt ? [`last scan ${when(status.lastScanAt)}`] : []), + status.complete ? "complete" : `continues where it stopped (${status.targets.filter((t) => !t.complete).length} of ${status.targets.length} targets left)`, + ].join(" · "); + + return ( + <div className="flex flex-col gap-5" aria-label="captures"> + <section className="rounded-lg border border-border bg-card p-4 flex flex-col gap-3" aria-label="wayback scan"> + <p className="text-sm text-muted-foreground" aria-label="captures status line"> + {statusLine} + </p> + <ul className="text-xs text-muted-foreground flex flex-col gap-0.5" aria-label="scan targets"> + {status.targets.map((t) => ( + <li key={`${t.match} ${t.url}`}> + <span className="font-mono">{t.url}</span> ({t.match}) — {t.complete ? "complete" : t.resumable ? `${n(t.rows)} rows read, continues` : "not scanned this pass"} + </li> + ))} + </ul> + {status.liveScanJobId ? ( + <p className="text-sm" aria-label="scan running"> + A scan is queued or running:{" "} + <Link href={`/jobs/${status.liveScanJobId}`} className="underline font-mono"> + {status.liveScanJobId} + </Link> + </p> + ) : ( + <StreamActionLog + trigger={() => waybackScanAction(slug)} + cancelAction={cancelJobAction} + buttonLabel={scanLabel} + runningLabel="Scanning…" + label="Wayback scan" + onSettled={() => router.refresh()} + /> + )} + {status.lastScanJobId ? ( + <p className="text-xs text-muted-foreground"> + Last scan:{" "} + <Link href={`/jobs/${status.lastScanJobId}`} className="underline font-mono" aria-label="last scan job"> + {status.lastScanJobId} + </Link> + </p> + ) : null} + <p className="text-xs text-muted-foreground" aria-label="automatic import"> + Automatic import: {status.auto ? "on — the download lane imports new captures at archive.org's pace" : "off"} + </p> + </section> + + {status.scanned ? ( + <section className="flex flex-col gap-3" aria-label="capture table"> + <Form action={`/channels/${slug}/captures`} className="flex flex-wrap items-end gap-2 text-sm" aria-label="capture filters"> + <label className="flex flex-col gap-1"> + <span className="text-xs text-muted-foreground">Year</span> + <select name="year" defaultValue={filter.year ?? ""} className="rounded-md border border-border bg-card px-2 py-1" aria-label="Year"> + <option value="">All years</option> + {years.map((y) => ( + <option key={y} value={y}> + {y} + </option> + ))} + </select> + </label> + <label className="flex flex-col gap-1"> + <span className="text-xs text-muted-foreground">Path</span> + <select name="prefix" defaultValue={filter.prefix ?? ""} className="rounded-md border border-border bg-card px-2 py-1 max-w-72" aria-label="Path prefix"> + <option value="">All paths</option> + {prefixes.map((p) => ( + <option key={p} value={p}> + {p} + </option> + ))} + </select> + </label> + <label className="flex flex-col gap-1"> + <span className="text-xs text-muted-foreground">Contains</span> + <input name="q" defaultValue={filter.q ?? ""} className="rounded-md border border-border bg-card px-2 py-1" aria-label="Filter text" /> + </label> + <label className="flex flex-col gap-1"> + <span className="text-xs text-muted-foreground">Show</span> + <select name="show" defaultValue={filter.show ?? "all"} className="rounded-md border border-border bg-card px-2 py-1" aria-label="Show"> + <option value="all">All</option> + <option value="not-imported">Not imported</option> + <option value="new">New since the last scan</option> + <option value="imported">Imported</option> + </select> + </label> + <button type="submit" className="rounded-md border border-border bg-card px-3 py-1 hover:bg-muted"> + Filter + </button> + <Link href={`/channels/${slug}/captures`} className="text-xs underline text-muted-foreground"> + Clear + </Link> + </Form> + + <div className="flex flex-wrap items-center gap-2 text-sm"> + <span aria-label="capture count" className="text-muted-foreground"> + {plural(matching, "row")} match{matching === 1 ? "es" : ""} + {matching !== matchingToImport ? ` (${n(matchingToImport)} not imported)` : ""} + </span> + <button + type="button" + disabled={pending || selected.size === 0} + onClick={() => run({ keys: [...selected] })} + className="rounded-md border border-border bg-card px-3 py-1 hover:bg-muted disabled:opacity-50" + > + Import selected ({n(selected.size)}) + </button> + {confirming ? ( + <span className="flex items-center gap-2" aria-label="confirm import range"> + <span>Import {plural(matchingToImport, "capture")}, one job each, at archive.org&apos;s pace?</span> + <button type="button" disabled={pending} onClick={() => run({ filter })} className="rounded-md border border-border bg-card px-3 py-1 hover:bg-muted"> + Confirm + </button> + <button type="button" onClick={() => setConfirming(false)} className="text-xs underline"> + Cancel + </button> + </span> + ) : ( + <button + type="button" + disabled={pending || matchingToImport === 0} + onClick={() => (matchingToImport > IMPORT_CONFIRM_ABOVE ? setConfirming(true) : run({ filter }))} + className="rounded-md border border-border bg-card px-3 py-1 hover:bg-muted disabled:opacity-50" + > + Import all in range ({n(matchingToImport)}) + </button> + )} + </div> + {result ? ( + <p className={`text-sm ${result.ok ? "" : "text-destructive"}`} aria-label="import result"> + {importLine(result)}{" "} + {result.ok && result.queued.length > 0 ? ( + <Link href="/jobs" className="underline"> + Jobs + </Link> + ) : null} + </p> + ) : null} + + <div className="overflow-x-auto"> + <table className="text-sm border-collapse w-full" aria-label="captures table"> + <thead> + <tr className="text-left text-muted-foreground"> + <th className="py-1 pr-2 font-medium"> + <input + type="checkbox" + aria-label="Select every row on this page" + checked={allOnPage} + disabled={selectable.length === 0} + onChange={() => + setSelected((s) => { + const next = new Set(s); + for (const r of selectable) { + if (allOnPage) next.delete(r.key); + else next.add(r.key); + } + return next; + }) + } + /> + </th> + <th className="py-1 pr-4 font-medium">Path</th> + <th className="py-1 pr-4 font-medium">First seen</th> + <th className="py-1 pr-4 font-medium">Last seen</th> + <th className="py-1 pr-4 font-medium">Version</th> + <th className="py-1 pr-4 font-medium">Imported</th> + <th className="py-1 font-medium">New</th> + </tr> + </thead> + <tbody> + {rows.map((r) => ( + <tr key={r.key} className="border-t border-border align-top" aria-label={`capture ${r.path} ${r.digest}`} data-key={r.key}> + <td className="py-1 pr-2"> + <input + type="checkbox" + aria-label={`Select ${r.path} (${cdxTsDate(r.firstTs)})`} + checked={selected.has(r.key)} + disabled={!!r.imported} + onChange={() => toggle(r.key)} + /> + </td> + <td className="py-1 pr-4 break-all"> + <a href={r.replayUrl} target="_blank" rel="noreferrer" className="underline hover:no-underline font-mono" title={r.originalUrl}> + {r.path || "/"} + </a> + </td> + <td className="py-1 pr-4 whitespace-nowrap tabular-nums">{cdxTsDate(r.firstTs)}</td> + <td className="py-1 pr-4 whitespace-nowrap tabular-nums">{cdxTsDate(r.lastTs)}</td> + <td className="py-1 pr-4 whitespace-nowrap tabular-nums" title={`${plural(r.count, "listed capture")} of this content`}> + {r.version} of {r.versions} + </td> + <td className="py-1 pr-4 whitespace-nowrap"> + {r.imported ? ( + r.imported.waybackUrl ? ( + <a href={r.imported.waybackUrl} target="_blank" rel="noreferrer" className="underline" title={`record ${r.imported.id}`} aria-label={`imported as ${r.imported.id}`}> + ✓ {r.imported.id} + </a> + ) : ( + <span aria-label={`imported as ${r.imported.id}`}>✓ {r.imported.id}</span> + ) + ) : ( + <span className="text-muted-foreground">—</span> + )} + </td> + <td className="py-1 whitespace-nowrap">{r.isNew ? <span className="text-xs rounded-full border border-info/30 bg-info-soft text-info px-2 py-0.5">new</span> : null}</td> + </tr> + ))} + </tbody> + </table> + </div> + {pages > 1 ? ( + <nav className="flex items-center gap-3 text-sm" aria-label="capture pages"> + {page > 1 ? ( + <Link href={hrefWith(slug, filter, page - 1)} className="underline"> + Previous + </Link> + ) : null} + <span className="text-muted-foreground"> + Page {page} of {pages} + </span> + {page < pages ? ( + <Link href={hrefWith(slug, filter, page + 1)} className="underline"> + Next + </Link> + ) : null} + </nav> + ) : null} + </section> + ) : null} + </div> + ); +} diff --git a/editor/app/channels/[slug]/captures/page.tsx b/editor/app/channels/[slug]/captures/page.tsx @@ -0,0 +1,89 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; +import { readWaybackChannelConfig, WAYBACK_SCAN_JOB_KIND } from "yt-dlp-transcript-common/controller/waybackScan"; +import { readImportedIndex, readWaybackScan } from "yt-dlp-transcript-common/lib/waybackPages/scanFile-server"; +import { + captureFilterFrom, + captureRows, + CAPTURES_PAGE_SIZE, + filterCaptureRows, +} from "yt-dlp-transcript-common/lib/waybackPages/scanView"; +import { waybackTargetKey } from "yt-dlp-transcript-common/lib/waybackPages/targets"; +import { readChannelConfigCached } from "../lib/channelConfigCache"; +import { CapturesPanel, type CapturesStatus } from "./components/CapturesPanel"; + +export const dynamic = "force-dynamic"; + +export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> { + const { slug } = await params; + const config = await readChannelConfigCached(slug); + return { title: `${config?.name ?? slug} — Captures` }; +} + +// THE CAPTURES TAB (release 37 S2): a Wayback pages channel's scan +// (wayback-scan.json, controller/waybackScan.ts) as a table — one row per +// distinct content of a page — filtered on the server by year, path prefix, +// text and what to show, a page of rows at a time (a 50,000-row scan never +// reaches the browser whole). Import selected / Import all in range queue one +// import-page job per row (controller/waybackImport.ts). +export default async function CapturesPage({ + params, + searchParams, +}: { + params: Promise<{ slug: string }>; + searchParams?: Promise<Record<string, string | string[] | undefined>>; +}) { + const { slug } = await params; + const sp = (await searchParams) ?? {}; + const config = await readChannelConfigCached(slug); + if (!config) notFound(); + const paths = getPaths(); + const wayback = await readWaybackChannelConfig(paths, slug); + if (!wayback) notFound(); + const scan = await readWaybackScan(paths.channelsDir, slug); + const all = scan ? captureRows(scan, await readImportedIndex(paths.channelsDir, slug)) : []; + const filter = captureFilterFrom(sp); + const matching = filterCaptureRows(all, filter); + const pages = Math.max(1, Math.ceil(matching.length / CAPTURES_PAGE_SIZE)); + const pageRaw = Number(Array.isArray(sp.page) ? sp.page[0] : sp.page); + const page = Number.isInteger(pageRaw) && pageRaw >= 1 ? Math.min(pageRaw, pages) : 1; + const shown = matching.slice((page - 1) * CAPTURES_PAGE_SIZE, page * CAPTURES_PAGE_SIZE); + const liveScan = getRegistry() + .list() + .find((j) => j.kind === WAYBACK_SCAN_JOB_KIND && j.channelSlug === slug && (j.status === "queued" || j.status === "running")); + const status: CapturesStatus = { + scanned: scan !== null, + versions: all.length, + pages: scan?.summary.pages ?? 0, + imported: all.filter((r) => r.imported).length, + newRows: all.filter((r) => r.isNew).length, + ...(scan?.lastScanAt ? { lastScanAt: scan.lastScanAt } : {}), + ...(scan?.jobId ? { lastScanJobId: scan.jobId } : {}), + pass: scan?.pass ?? 0, + complete: scan ? wayback.targets.every((t) => scan.targets.some((s) => s.key === waybackTargetKey(t) && s.complete)) : false, + targets: wayback.targets.map((t) => { + const st = scan?.targets.find((s) => s.key === waybackTargetKey(t)); + return { url: t.url, match: t.match, complete: st?.complete ?? false, rows: st?.rows ?? 0, resumable: !!st?.resumeKey }; + }), + auto: wayback.auto, + ...(liveScan ? { liveScanJobId: liveScan.id } : {}), + }; + const years = scan ? Object.keys(scan.summary.byYear).sort() : []; + const prefixes = scan ? Object.keys(scan.summary.byPrefix).sort() : []; + return ( + <CapturesPanel + slug={slug} + status={status} + rows={shown} + matching={matching.length} + matchingToImport={matching.filter((r) => !r.imported).length} + page={page} + pages={pages} + filter={filter} + years={years} + prefixes={prefixes} + /> + ); +} diff --git a/editor/app/channels/[slug]/components/ChannelTabs.tsx b/editor/app/channels/[slug]/components/ChannelTabs.tsx @@ -3,7 +3,7 @@ import Link from "next/link"; import { useSelectedLayoutSegment } from "next/navigation"; -// Overview | Videos. +// Overview | Videos (a Wayback pages channel: Overview | Captures). // // A CLIENT component on purpose. Next 16 layouts are cached during navigation // and DO NOT RERENDER — they cannot read searchParams and would not re-evaluate @@ -11,8 +11,25 @@ import { useSelectedLayoutSegment } from "next/navigation"; // useSelectedLayoutSegment is the supported way to ask "which child segment is // rendered", and it re-renders because this component does. -export function ChannelTabs({ slug }: { slug: string }) { +export function ChannelTabs({ + slug, + captures = false, +}: { + slug: string; + // A Wayback pages channel (release 37 S2): Overview | Captures — its + // records are captures, not videos. + captures?: boolean; +}) { const segment = useSelectedLayoutSegment(); + if (captures) { + const onCaptures = segment === "captures"; + return ( + <nav aria-label="channel sections" className="flex items-center gap-1"> + <Tab href={`/channels/${slug}`} active={!onCaptures} label="Overview" /> + <Tab href={`/channels/${slug}/captures`} active={onCaptures} label="Captures" /> + </nav> + ); + } const onVideos = segment === "videos"; return ( <nav aria-label="channel sections" className="flex items-center gap-1"> diff --git a/editor/app/channels/[slug]/layout.tsx b/editor/app/channels/[slug]/layout.tsx @@ -5,6 +5,8 @@ import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { ChannelTabs } from "./components/ChannelTabs"; import { RefreshSnapshotButton } from "./components/RefreshSnapshotButton"; import { readChannelConfigCached } from "./lib/channelConfigCache"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { readWaybackChannelConfig } from "yt-dlp-transcript-common/controller/waybackScan"; // Shared chrome for every channel route: the breadcrumb, the name, the refresh // control and the Overview | Videos switch. This is what StatusHeader used to @@ -35,6 +37,9 @@ export default async function ChannelLayout({ // Deduped with page.tsx's read of the same file via React cache(). const config = await readChannelConfigCached(slug); if (!config) notFound(); + // A Wayback pages channel (release 37 S2) is a posts channel whose records + // are captures: its tabs are Overview | Captures. + const wayback = await readWaybackChannelConfig(getPaths(), slug); return ( <div className="flex flex-col gap-6"> @@ -59,7 +64,11 @@ export default async function ChannelLayout({ the video workspace would be an empty room, and there is no video report to refresh. Both controls stay off it — which is also what the header did before this layout existed. */} - {!isSocialChannel(config) && ( + {wayback ? ( + <div className="flex items-center gap-3"> + <ChannelTabs slug={slug} captures /> + </div> + ) : !isSocialChannel(config) && ( <div className="flex items-center gap-3"> <ChannelTabs slug={slug} /> <RefreshSnapshotButton slug={slug} /> diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -117,6 +117,9 @@ // pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait // pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait // pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait +// pnpm ops wayback-scan --json '{"slug":"demo-pages","dryRun":true}' --wait +// pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait +// pnpm ops wayback-import --json '{"slug":"demo-pages","year":"2014","show":"not-imported","dryRun":true}' // pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait // pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait // pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}' @@ -447,6 +450,12 @@ const ACTIONS = [ // brings every gone video's WHOLE audio home (a fetch-copies job). "wayback-lookup", "find-copy", + // WAYBACK PAGES, SCAN AND CHOOSE (release 37 S2): a Wayback pages channel's + // CDX scan into wayback-scan.json ({slug, dryRun?, maxRows?, full?}), as a + // job on archive.org's queue; and the chosen rows imported, one import-page + // job each ({slug, keys? | year?, prefix?, q?, show?, dryRun?}). + "wayback-scan", + "wayback-import", // GENERATION (release 27 S6): a sweep, a report or video revision, or a // narration step over an article's iteration ({task, article, iteration?, // model?, extractorModel?, feedback?, question?, channels?, copyOf?, maxUsd?, @@ -1439,6 +1448,36 @@ export function usage() { " looked: [{slug, id, gone, noTranscript, watchUrl, youtubeId, tried,", " copy?, via?, outcome}], left, items, stopped?, fetchJobId?, refused?}.", "", + 'wayback-scan lists the Wayback Machine\'s captures of a Wayback pages', + ' channel\'s targets (config wayback.targets) into its wayback-scan.json,', + ' as a wayback-scan job on archive.org\'s queue: {"slug", "dryRun"?,', + ' "maxRows"? (50000, at most 200000), "full"?} -> {jobId}. The CDX API per', + ' target (its matchType exact | prefix | host | domain, status 200, its', + ' mimes — text/html unless it names text/plain or application/json —', + ' collapse=digest, its from/to), in pages of 5,000 with a resume key; obvious', + ' assets (css, js, images, fonts) dropped unless the target\'s include names', + ' them. One row per distinct (URL, digest) with first/last seen. No bodies:', + " import-page fetches a capture. A run cut short (the row cap, a refusal, a", + " drain) keeps each target's resume key and the next continues; once every", + " target is complete the next run is a new pass, from 30 days before the", + ' last began, and what it adds is marked new; "full" starts a new pass from', + " each target's start. Paced as archive.org asks (one at a time, 2 s apart,", + " 429/503 waited out; a refusal stops the job). dryRun asks nothing and", + " writes nothing: it logs the next request per target. The log ends with", + " @@wayback-scan {slug, dryRun, pass, newPass, targets: [{url, match,", + " requests, rows, added, complete, resumeKey?, next?}], requests, rowsRead,", + " added, totalRows, complete, stopped?, error?}.", + "", + 'wayback-import imports chosen rows of a Wayback pages channel\'s scan, one', + ' import-page job per row (the capture the content was first listed at),', + ' queued on archive.org\'s queue: {"slug", "keys"?: ["<digest> <url>", ...]}', + ' or a range — "year"? (first seen), "prefix"? ("host/path/"), "q"? (text', + ' in the URL), "show"? (all | new | not-imported | imported) — and', + ' "dryRun"? -> {ok, slug, dryRun, chosen, queued: [{key, url, jobId?}],', + " skipped: [{key, why}], left}. Rows already imported are skipped; at most", + " 500 are queued a call (left: how many remain). The Captures tab's Import", + " selected and Import all in range.", + "", 'import-post imports ONE post by its URL into a posts channel of its', ' platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a', ' Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read',