// THE CAPTURES A WAYBACK PAGES CHANNEL HOLDS (release 37 S1), on disk beside // its posts: // // channels//pages/-/raw.html.gz the body as captured (gzip) // channels//pages/-/capture.json what it is (StoredCapture) // // The directory name is pageRecordId(captureTs, originalUrl) — a whole-page // record's id. TEXT, on the corpus disk: `pages/` is at the channel's root, // never under `data//`, so the media tier (lib/mediaTier.ts, which names // files inside a video dir) never moves it; a channel rename moves it with the // channel. The raw body is kept so a better extractor re-derives every record // offline (`archilyzer wayback pages reextract`), with no request. // // Writes are atomic (tmp + rename), the body first: a capture.json is only // ever beside a whole body, so a capture.json IS a stored capture. import path from "node:path"; import { mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises"; import { gunzipSync, gzipSync } from "node:zlib"; import { writeJsonAtomic } from "../jsonFile-server"; import { pageRecordId } from "./types"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const PAGES_DIRNAME = "pages"; export const PAGE_RAW_FILENAME = "raw.html.gz"; export const PAGE_CAPTURE_FILENAME = "capture.json"; export type StoredCapture = { originalUrl: string; captureTs: string; digest?: string; // The bare mimetype, and the Content-Type as served (its charset). mimetype: string; contentType?: string; bytes: number; sha256: string; fetchedAt: string; // What made the records, so a re-extract knows what is stale. extractor: string; extractorVersion: number; extractorFallback?: { from: string; fromVersion: number; error: string }; // The URL the import asked for, when the archive redirected it elsewhere // (another timestamp, or the page the capture recorded a redirect to). requestedTs?: string; requestedUrl?: string; // The record ids this capture made, at the last extraction. records?: string[]; // Release 37 lane F: the archive source the copy is from (absent = the // Wayback Machine), and the copy's URL there (archive.today's // `https://archive.ph/`). The body is the copy AS SERVED — for // archive.today its rewritten snapshot, unwrapped each time it is read. source?: string; mementoUrl?: string; }; export function channelPagesDir(channelRoot: string): string { return path.join(channelRoot, PAGES_DIRNAME); } export function pageCaptureDirName(captureTs: string, originalUrl: string): string { return pageRecordId(captureTs, originalUrl); } export function pageCaptureDir(channelRoot: string, captureTs: string, originalUrl: string): string { return path.join(channelPagesDir(channelRoot), pageCaptureDirName(captureTs, originalUrl)); } const NAME_RE = /^\d{4,14}-[0-9a-f]{12}$/; function parseStoredCapture(raw: unknown): StoredCapture | null { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; const r = raw as Record; const s = (k: string) => (typeof r[k] === "string" && r[k] ? (r[k] as string) : undefined); const originalUrl = s("originalUrl"); const captureTs = s("captureTs"); const mimetype = s("mimetype"); const sha256 = s("sha256"); const fetchedAt = s("fetchedAt"); const extractor = s("extractor"); if (!originalUrl || !captureTs || !/^\d{4,14}$/.test(captureTs) || !mimetype || !sha256 || !fetchedAt || !extractor) return null; if (typeof r.bytes !== "number" || typeof r.extractorVersion !== "number") return null; const out: StoredCapture = { originalUrl, captureTs, mimetype, bytes: r.bytes, sha256, fetchedAt, extractor, extractorVersion: r.extractorVersion, }; const digest = s("digest"); if (digest) out.digest = digest; const contentType = s("contentType"); if (contentType) out.contentType = contentType; const requestedTs = s("requestedTs"); if (requestedTs) out.requestedTs = requestedTs; const requestedUrl = s("requestedUrl"); if (requestedUrl) out.requestedUrl = requestedUrl; const fb = r.extractorFallback as Record | undefined; if (fb && typeof fb.from === "string" && typeof fb.fromVersion === "number") { out.extractorFallback = { from: fb.from, fromVersion: fb.fromVersion, error: typeof fb.error === "string" ? fb.error : "" }; } if (Array.isArray(r.records)) out.records = r.records.filter((x): x is string => typeof x === "string"); const source = s("source"); if (source && source !== "wayback") out.source = source; const mementoUrl = s("mementoUrl"); if (mementoUrl) out.mementoUrl = mementoUrl; return out; } // Whether the capture is already stored (its capture.json is there). export async function hasStoredCapture(channelRoot: string, captureTs: string, originalUrl: string): Promise { return (await readStoredCapture(pageCaptureDir(channelRoot, captureTs, originalUrl))) !== null; } export async function readStoredCapture(dir: string): Promise { try { return parseStoredCapture(JSON.parse(await readFile(path.join(dir, PAGE_CAPTURE_FILENAME), "utf8"))); } catch { return null; } } // Store one capture: the body (gzip), then its capture.json. Answers the // directory. export async function writeStoredCapture( channelRoot: string, capture: StoredCapture, body: Buffer, ): Promise { const dir = pageCaptureDir(channelRoot, capture.captureTs, capture.originalUrl); await mkdir(dir, { recursive: true }); const raw = path.join(dir, PAGE_RAW_FILENAME); const tmp = tmpPathFor(raw); await writeFile(tmp, gzipSync(body)); await rename(tmp, raw); await writeJsonAtomic(path.join(dir, PAGE_CAPTURE_FILENAME), capture); return dir; } // Rewrite a stored capture's capture.json (after a re-extract). export async function updateStoredCapture(dir: string, capture: StoredCapture): Promise { await writeJsonAtomic(path.join(dir, PAGE_CAPTURE_FILENAME), capture); } export async function readStoredCaptureBody(dir: string): Promise { return gunzipSync(await readFile(path.join(dir, PAGE_RAW_FILENAME))); } export type StoredCaptureEntry = { dir: string; name: string; capture: StoredCapture }; // Every stored capture of a channel, oldest capture first (then by name). A // directory with no readable capture.json (an interrupted write) is skipped. export async function listStoredCaptures(channelRoot: string): Promise { const root = channelPagesDir(channelRoot); let names: string[]; try { names = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name); } catch { return []; } const out: StoredCaptureEntry[] = []; for (const name of names.filter((n) => NAME_RE.test(n)).sort()) { const dir = path.join(root, name); const capture = await readStoredCapture(dir); if (capture) out.push({ dir, name, capture }); } return out.sort( (a, b) => a.capture.captureTs.padEnd(14, "0").localeCompare(b.capture.captureTs.padEnd(14, "0")) || a.name.localeCompare(b.name), ); } // How many captures a channel holds (a readdir; no capture.json is read). export async function countStoredCaptures(channelRoot: string): Promise { try { return (await readdir(channelPagesDir(channelRoot))).filter((n) => NAME_RE.test(n)).length; } catch { return 0; } } // The stored capture of a copy by its URL at its source (release 37 lane F: // an archive.today short-id URL names neither page nor time, so "already // stored" is asked by the copy's URL before anything is fetched), or null. export async function findStoredCaptureByMemento(channelRoot: string, mementoUrl: string): Promise { const want = mementoKey(mementoUrl); for (const e of await listStoredCaptures(channelRoot)) { if (e.capture.mementoUrl && mementoKey(e.capture.mementoUrl) === want) return e; } return null; } // A copy's URL compared host-blind (archive.today's names are one service). function mementoKey(url: string): string { try { const u = new URL(url); return `${u.pathname}${u.search}`.replace(/\/+$/, ""); } catch { return url; } }