// FIND A COPY OF A GONE PAGE A REPORT CITES (release 37 S5) — find-copy's // page mode, beside its video modes (./findCopy.ts). A report cites a web page // either as a `page` citation (`{url, archiveUrl?}`: the page is not in the // corpus) or as a `post` citation of a page record (a Wayback Machine capture // already imported into a Wayback pages channel). When the page's ORIGINAL is // gone, the Wayback Machine's copy is the only copy, and the report should // cite it as a record: // // a `page` citation its original URL asked at its own site // (lib/waybackPages/liveness-server.ts, the web pacer); // gone (deleted, or the account/document unavailable) → // the capture NEAREST the citation's date (its `date`, // else its archiveUrl's timestamp, else today: the latest) // through ONE CDX request (WaybackClient.closestCapture), // imported into the Wayback pages channel named // (`channel`) or the one whose targets cover the URL // (import-page, controller/importPage.ts) — unless that // channel already holds a record of the page. Live: left // (Save Page Now is the act for a live page). The answer // names the record the citation should cite (`pointTo`) // and the citation as a `post` citation of it (`as`). // a `post` citation of a page record whose original the availability // check found deleted: its capture is held (nothing to // do) or, when its raw body is not stored, imported again. // // THE CITATION IS NOT REWRITTEN HERE: `pointTo`/`as` are what the report's // citation becomes (the report editor's "Import this capture" rewrites a page // citation to a post citation and keeps the page citation as its fallback; // release 37 lane D). A dry run asks the same paced questions and imports // nothing. // // PACED: one page at a time, at most `max` lookups per run; every Wayback // request goes through the process's Wayback client (one stream, 2 s apart, // 429s waited out — a refusal stops the run there), every original-site // request through the web pacer. The job runs on the archive.org queue. import { nearestAcrossSources } from "../lib/archives/index"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { Citation, PageCitation, PostCitation } from "../lib/citations/schema"; import { pageCitationAsPost } from "../lib/citations/pageAsPost"; import type { Post } from "../lib/posts"; import { readAllPosts, readPostAvailability } from "../lib/posts-server"; import { listChannelConfigs } from "../controller/channels"; import { isWaybackPagesChannel, type WaybackTarget } from "../lib/waybackPages/config"; import { bareHost, type OriginalCheck } from "../lib/waybackPages/liveness"; import { checkOriginalUrl, type CheckOriginalOptions } from "../lib/waybackPages/liveness-server"; import { hasStoredCapture } from "../lib/waybackPages/store-server"; import { parseWaybackUrl, waybackPageUrl } from "../lib/wayback"; import { ArchiveOrgRequestError } from "../lib/archiveOrgClient"; import { waybackClient, type WaybackCapture, type WaybackClient } from "../lib/waybackClient"; import { importPage, type ImportPageResult } from "../controller/importPage"; import { loadHostReports } from "./reportMedia"; import type { ReportHost } from "./reportHost"; export const FIND_PAGE_COPY_DEFAULT_MAX = 10; export const FIND_PAGE_COPY_MAX_LIMIT = 100; // ─── Which channel a page belongs in ─── const bare = (u: string) => u .trim() .replace(/^https?:\/\//i, "") .replace(/^www\./i, "") .replace(/#.*$/, "") .replace(/\/+$/, "") .toLowerCase(); // Whether a Wayback pages channel's target covers a page. export function targetCoversUrl(target: Pick, url: string): boolean { const host = bareHost(/^https?:\/\//i.test(url) ? url : `https://${url}`); const targetHost = bareHost(/^https?:\/\//i.test(target.url) ? target.url : `https://${target.url}`); if (!host || !targetHost) return false; switch (target.match) { case "exact": return bare(url) === bare(target.url); case "prefix": return bare(url).startsWith(bare(target.url)); case "host": return host === targetHost; case "domain": return host === targetHost || host.endsWith(`.${targetHost}`); default: return false; } } // The Wayback pages channels whose targets cover `url`, by slug. export function channelsCovering( channels: ReadonlyArray<{ slug: string; config: { sourceKind?: string; platform?: string; wayback?: { targets?: WaybackTarget[] } } }>, url: string, ): string[] { return channels .filter((c) => isWaybackPagesChannel(c.config) && (c.config.wayback?.targets ?? []).some((t) => targetCoversUrl(t, url))) .map((c) => c.slug); } // ─── What the reports cite ─── export type CitedPage = { // `#` of each citation of it. citedBy: string[]; url: string; // The citation's own date or archive copy, for the nearest capture. at?: string; // The first citation's words (to pick the record of a split capture). quote: string; citation: PageCitation; }; export type CitedPageRecord = { citedBy: string[]; channel: string; id: string; }; // "2014-03-05…" / "2014-03" / "2014" → a capture time prefix. export function captureAtOf(c: Pick, today: Date): string { const d = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?/.exec(c.date ?? ""); if (d) return `${d[1]}${d[2] ?? ""}${d[3] ?? ""}`; const ref = parseWaybackUrl(c.archiveUrl ?? ""); if (ref && /^\d{4,14}$/.test(ref.captureTs)) return ref.captureTs; return today.toISOString().slice(0, 10).replaceAll("-", ""); } export function citedPages( reports: ReadonlyArray<{ id: string; citations?: Record }>, today: Date, ): { pages: CitedPage[]; posts: CitedPageRecord[] } { const pages = new Map(); const posts = new Map(); for (const r of reports) { for (const [cid, c] of Object.entries(r.citations ?? {})) { const by = `${r.id}#${cid}`; if (c.kind === "page") { if (!/^https?:\/\//i.test(c.url)) continue; const key = bare(c.url); const seen = pages.get(key); if (seen) seen.citedBy.push(by); else pages.set(key, { citedBy: [by], url: c.url.trim(), at: captureAtOf(c, today), quote: c.quote, citation: c }); } else if (c.kind === "post") { const key = `${c.channel}/${c.id}`; const seen = posts.get(key); if (seen) seen.citedBy.push(by); else posts.set(key, { citedBy: [by], channel: c.channel, id: c.id }); } } } return { pages: [...pages.values()], posts: [...posts.values()] }; } // The record a quote is from, among a capture's records: the one whose text // holds the quote's words, else the first (a whole page's one record). export function recordForQuote(records: ReadonlyArray>, quote: string): string | null { if (records.length === 0) return null; const fold = (s: string) => s.replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, " ").trim().toLowerCase(); const q = fold(quote); if (q) { const hit = records.find((r) => fold(r.text).includes(q)); if (hit) return hit.id; } return records[0]!.id; } // A page citation as a post citation of the record: the one builder, shared // with umtool's Import this capture (lib/citations/pageAsPost.ts) — its words // and editorial fields kept, the page kept as its `fallback`. export { pageCitationAsPost }; // ─── find-copy, page mode ─── export type FindPageCopyOutcome = // imported the nearest capture imported; `pointTo` is its record // would-import (dry run) what an import would fetch // held the channel already holds a record of the page (or the // cited record's capture is stored): nothing fetched // live the original still answers: left (Save Page Now it) // none-found the Wayback Machine holds no capture that recorded a page // no-channel no Wayback pages channel covers the URL and none was named // refused the import was refused (its sentence: X, a video, …) // error a check or a lookup failed: a later run asks again | "imported" | "would-import" | "held" | "live" | "none-found" | "no-channel" | "refused" | "error"; export type FindPageCopyItem = { citedBy: string[]; // The page cited, or the record cited. url: string; record?: { channel: string; id: string }; original?: Pick; channel?: string; capture?: { timestamp: string; original: string; waybackUrl: string }; outcome: FindPageCopyOutcome; detail: string; pointTo?: { channel: string; id: string }; // The citation as a post citation of `pointTo` (a page citation only). as?: PostCitation; records?: string[]; }; export type FindPageCopiesResult = { host: string; dryRun: boolean; max: number; pages: number; posts: number; items: FindPageCopyItem[]; // Cited pages left for a later run by `max`. left: number; stopped?: string; }; export type FindPageCopiesDeps = { reports: (host: ReportHost) => Promise }>>; channels: (paths: Paths) => Promise>; check: (url: string, signal?: AbortSignal) => Promise; // THE ONE CAPTURE LOOKUP: the capture of `url` nearest `at` (default: the // Wayback Machine's CDX `closest`). An archive-source registry can stand in // here without the rest of the mode changing. nearest: (url: string, at: string, signal?: AbortSignal) => Promise; importCapture: (o: { slug: string; url: string; signal?: AbortSignal; onLog?: (line: string) => void }) => Promise; now: () => Date; }; export function defaultFindPageCopiesDeps(paths: Paths, o: { check?: CheckOriginalOptions; client?: WaybackClient } = {}): FindPageCopiesDeps { const client = o.client ?? waybackClient; return { reports: async (host) => (await loadHostReports(host)).reports, channels: (p) => listChannelConfigs(p), check: (url, signal) => checkOriginalUrl(url, { ...o.check, ...(signal ? { signal } : {}) }), // Release 37 lane F: across archive sources (the Wayback Machine, then // archive.today); a row's copy URL is its replayUrl, so the import reads // whichever source holds it. A Wayback client given here keeps the // Wayback-only lookup (tests). nearest: o.client ? (url, at, signal) => client.closestCapture(url, at, signal ? { signal } : {}) : async (url, at, signal) => { const row = await nearestAcrossSources(url, at, signal ? { signal } : {}); return row ? { timestamp: row.captureTs, original: row.originalUrl, status: row.status ?? "200", replayUrl: row.mementoUrl, ...(row.mimetype ? { mimetype: row.mimetype } : {}) } : null; }, importCapture: (io) => importPage({ paths, slug: io.slug, url: io.url, client, ...(io.signal ? { signal: io.signal } : {}), ...(io.onLog ? { onLog: io.onLog } : {}) }), now: () => new Date(), }; } const GONE = new Set(["deleted", "account_unavailable"]); export async function findPageCopies(opts: { paths: Paths; host: ReportHost; // The Wayback pages channel every capture goes to (else: the one whose // targets cover the page). channel?: string; dryRun?: boolean; max?: number; signal?: AbortSignal; onLog?: (line: string) => void; deps?: Partial; }): Promise { const deps: FindPageCopiesDeps = { ...defaultFindPageCopiesDeps(opts.paths), ...opts.deps }; const log = (line: string) => opts.onLog?.(line); const signal = opts.signal; const dryRun = opts.dryRun === true; const max = Math.min(FIND_PAGE_COPY_MAX_LIMIT, Math.max(1, Math.floor(opts.max ?? FIND_PAGE_COPY_DEFAULT_MAX))); const today = deps.now(); const cited = citedPages(await deps.reports(opts.host), today); const channels = await deps.channels(opts.paths); const pagesChannels = new Set(channels.filter((c) => isWaybackPagesChannel(c.config)).map((c) => c.slug)); if (opts.channel && !pagesChannels.has(opts.channel)) { throw new Error(`${opts.channel} is not a Wayback pages channel; name one on platform "webpage", or none (the channel whose targets cover each page)`); } // The post citations of page records only. const postCitations = cited.posts.filter((p) => pagesChannels.has(p.channel)); const result: FindPageCopiesResult = { host: opts.host.id, dryRun, max, pages: cited.pages.length, posts: postCitations.length, items: [], left: 0 }; log( `find-copy ${opts.host.id} (pages${dryRun ? ", dry run" : ""}): ${cited.pages.length} cited page(s), ` + `${postCitations.length} cited page record(s); at most ${max} looked up.`, ); const recordsOf = new Map(); const channelRecords = async (slug: string): Promise => { let list = recordsOf.get(slug); if (!list) { list = (await readAllPosts(path.join(opts.paths.channelsDir, slug)).catch(() => [] as Post[])).filter((p) => p.page); recordsOf.set(slug, list); } return list; }; let lookups = 0; const stopOn = (e: unknown): string | null => e instanceof ArchiveOrgRequestError && e.rateLimited ? `archive.org kept refusing (${e.message}); the rest are left for a later run` : null; // 1. Cited pages. for (const page of cited.pages) { if (signal?.aborted || result.stopped) break; if (lookups >= max) { result.left++; continue; } lookups++; const item: FindPageCopyItem = { citedBy: page.citedBy, url: page.url, outcome: "error", detail: "" }; result.items.push(item); const checked = await deps.check(page.url, signal); item.original = { availability: checked.availability, status: checked.status, reason: checked.reason }; if (checked.availability === "available") { item.outcome = "live"; item.detail = `the original still answers (${checked.reason}): left — Save Page Now captures a live page`; } else if (!GONE.has(checked.availability)) { item.outcome = "error"; item.detail = `the original could not be checked (${checked.reason}): try again later`; } else { const covering = opts.channel ? [opts.channel] : channelsCovering(channels, page.url); const slug = covering[0]; if (!slug) { item.outcome = "no-channel"; item.detail = `the original is gone (${checked.reason}), and no Wayback pages channel covers ${bareHost(page.url) || page.url}: name one ("channel") or create one targeting it`; } else { item.channel = slug; const held = (await channelRecords(slug)).filter((r) => bare(r.page!.originalUrl) === bare(page.url)); if (held.length > 0) { const id = recordForQuote(held, page.quote)!; item.outcome = "held"; item.pointTo = { channel: slug, id }; item.as = pageCitationAsPost(page.citation, item.pointTo); item.detail = `the original is gone (${checked.reason}); ${slug} already holds ${held.length} record(s) of the page`; } else { try { const near: WaybackCapture | null = await deps.nearest(page.url, page.at ?? "", signal); if (!near) { item.outcome = "none-found"; item.detail = `the original is gone (${checked.reason}), and no archive source holds a copy of it that recorded a page`; } else { // The copy's own URL (a Wayback replay URL, or an archive.today // copy's from the source registry — release 37 lane F). const waybackUrl = near.replayUrl || waybackPageUrl({ captureTs: near.timestamp, originalUrl: near.original }); item.capture = { timestamp: near.timestamp, original: near.original, waybackUrl }; if (dryRun) { item.outcome = "would-import"; item.detail = `the original is gone (${checked.reason}); would import the capture ${near.timestamp} (nearest ${page.at}) into ${slug}`; } else { const imp = await deps.importCapture({ slug, url: waybackUrl, ...(signal ? { signal } : {}), onLog: (l) => log(` ${l}`) }); if (!imp.ok) { // archive.org kept refusing (the client's sentence): stop the run there. const busy = /did not answer .* attempts/.test(imp.error ?? ""); item.outcome = busy ? "error" : "refused"; item.detail = busy ? (imp.error ?? "") : `the import was refused: ${imp.error}`; if (busy) result.stopped = `archive.org kept refusing (${imp.error}); the rest are left for a later run`; } else { recordsOf.delete(slug); const records = (await channelRecords(slug)).filter((r) => (imp.records ?? []).includes(r.id)); const id = recordForQuote(records.length ? records : (imp.records ?? []).map((rid) => ({ id: rid, text: "" })), page.quote); item.outcome = "imported"; item.records = imp.records ?? []; if (id) { item.pointTo = { channel: slug, id }; item.as = pageCitationAsPost(page.citation, item.pointTo); } item.detail = `the original is gone (${checked.reason}); ${imp.already ? "the capture was already stored" : "imported"} the capture ${imp.captureTs} into ${slug}`; } } } } catch (e) { if (signal?.aborted) break; item.outcome = "error"; item.detail = (e as Error).message; const stop = stopOn(e); if (stop) result.stopped = stop; } } } } log(` ${page.url} (${page.citedBy.join(", ")}): ${item.outcome} — ${item.detail}${item.pointTo ? ` → cite ${item.pointTo.channel}/${item.pointTo.id}` : ""}`); } // 2. Cited page records whose original the availability check found gone. for (const cite of postCitations) { if (signal?.aborted || result.stopped) break; const channelRoot = path.join(opts.paths.channelsDir, cite.channel); const av = (await readPostAvailability(channelRoot))[cite.id]; if (!av || !GONE.has(av.availability)) continue; const record = (await channelRecords(cite.channel)).find((r) => r.id === cite.id); if (!record?.page) continue; const item: FindPageCopyItem = { citedBy: cite.citedBy, url: record.page.originalUrl, record: { channel: cite.channel, id: cite.id }, original: { availability: av.availability, status: av.status ?? null, reason: av.reason ?? "the availability check" }, channel: cite.channel, capture: { timestamp: record.page.captureTs, original: record.page.originalUrl, waybackUrl: record.page.waybackUrl }, outcome: "held", detail: "", pointTo: { channel: cite.channel, id: cite.id }, }; result.items.push(item); if (await hasStoredCapture(channelRoot, record.page.captureTs, record.page.originalUrl)) { item.detail = `the original is gone (${item.original!.reason}); the record's capture is held — the Wayback copy is the only copy`; } else if (dryRun) { item.outcome = "would-import"; item.detail = `the original is gone; the record's capture is not stored: would import ${record.page.waybackUrl} into ${cite.channel}`; } else { try { const imp = await deps.importCapture({ slug: cite.channel, url: record.page.waybackUrl, ...(signal ? { signal } : {}), onLog: (l) => log(` ${l}`) }); item.outcome = imp.ok ? "imported" : "refused"; item.records = imp.records ?? []; item.detail = imp.ok ? `the original is gone; the record's capture imported again into ${cite.channel}` : `the import was refused: ${imp.error}`; } catch (e) { if (signal?.aborted) break; item.outcome = "error"; item.detail = (e as Error).message; const stop = stopOn(e); if (stop) result.stopped = stop; } } log(` ${cite.channel}/${cite.id} (${cite.citedBy.join(", ")}): ${item.outcome} — ${item.detail}`); } if (signal?.aborted && !result.stopped) result.stopped = "cancelled; the rest are left for a later run"; if (result.stopped) log(`find-copy: ${result.stopped}.`); if (result.left > 0) log(`find-copy: ${result.left} more cited page(s) are left for a later run (max ${max}).`); const imported = result.items.filter((i) => i.outcome === "imported").length; const would = result.items.filter((i) => i.outcome === "would-import").length; log(`find-copy: ${dryRun ? `${would} capture(s) would be imported (dry run: nothing imported)` : `${imported} capture(s) imported`}.`); return result; }