import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import type { Report } from "yt-dlp-transcript-common/lib/report/schema"; import { parseWaybackUrl } from "yt-dlp-transcript-common/lib/wayback"; import { HandEditError, replacePageCitationWithRecord } from "yt-dlp-transcript-common/controller/handEdits"; import type { Citation } from "yt-dlp-transcript-common/lib/citations/schema"; import { pageCitationAsPost } from "yt-dlp-transcript-common/lib/citations/pageAsPost"; import { ARTICLES_KEY, CHANNELS_DIR } from "@/lib/paths"; import { askEditor } from "./generation"; import { channelPosts } from "./article"; import { sitesPaths } from "./sites"; // IMPORT THIS CAPTURE (release 37 S4): a report's `page` citation whose // archived copy is a Wayback Machine capture becomes a page record — the // editor's `import-page` into a Wayback pages channel picked (or created) here // — and then a `post` citation of that record, the page kept as its // `fallback`. No model: three buttons over the editor's ops door. // // start create-channel (when asked) → import-page {slug, url: archiveUrl} // status the job's state, and when done the records it made (the // `@@import-page` line of its log) // use a store article: the citation rewritten as a hand edit (common // controller/handEdits.ts replacePageCitationWithRecord). A site // report is built from its draft, which umtool never writes: the // replacement citation comes back for the draft. export const IMPORT_PAGE_MARKER = "@@import-page "; export type PagesChannel = { slug: string; name: string }; /** The Wayback pages channels (platform "webpage") a capture can go into. */ export async function webpageChannels(): Promise { let names: string[] = []; try { names = await readdir(/* turbopackIgnore: true */ CHANNELS_DIR); } catch { return []; } const out: PagesChannel[] = []; for (const slug of names.sort()) { if (slug.startsWith(".")) continue; try { const c = JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(CHANNELS_DIR, slug, "config.json"), "utf8")); if (c?.sourceKind === "social" && c?.platform === "webpage") out.push({ slug, name: typeof c.name === "string" ? c.name : slug }); } catch { // not a channel } } return out; } export class ImportCaptureError extends Error { constructor( message: string, readonly status = 400, readonly problems: string[] = [], ) { super(message); } } /** The page citation `cite` and its capture, or the refusal. */ export function importablePage(report: Report, cite: string): { url: string; title?: string; archiveUrl: string; host: string } { const c = report.citations?.[cite]; if (!c) throw new ImportCaptureError(`no citation ${cite}`, 404); if (c.kind !== "page") throw new ImportCaptureError(`citation ${cite} is a ${c.kind}, not a page`); const ref = parseWaybackUrl(c.archiveUrl); if (!c.archiveUrl || !ref) throw new ImportCaptureError(`citation ${cite} has no Wayback Machine copy (archiveUrl) to import`); let host = ""; try { host = new URL(ref.originalUrl).hostname; } catch { host = ""; } return { url: c.url, ...(c.title ? { title: c.title } : {}), archiveUrl: c.archiveUrl, host }; } /** A capture page citation's import, started: into `slug`, or a channel created for its host. */ export async function startCaptureImport( report: Report, cite: string, into: { slug: string } | { create: { name: string } }, ): Promise<{ slug: string; jobId: string; created: boolean }> { const page = importablePage(report, cite); let slug: string; let created = false; if ("create" in into) { const name = into.create.name.trim(); if (!name) throw new ImportCaptureError("give the new channel a name"); if (!page.host) throw new ImportCaptureError("the capture names no host to scope a channel by"); const made = await askEditor<{ slug: string }>("/api/ops/create-channel", { method: "POST", body: { fields: { name, handling: "transcribe", url: `https://web.archive.org/web/*/${page.host}/*` } }, }); slug = made.slug; created = true; } else { slug = into.slug; if (!(await webpageChannels()).some((c) => c.slug === slug)) throw new ImportCaptureError(`${slug} is not a Wayback pages channel`); } const job = await askEditor<{ jobId: string }>("/api/ops/import-page", { method: "POST", body: { slug, url: page.archiveUrl } }); return { slug, jobId: job.jobId, created }; } export type ImportedRecord = { id: string; title?: string; text: string }; export type ImportStatus = { status: string; done: boolean; ok?: boolean; error?: string; records: ImportedRecord[]; }; /** Where an import job is, and the records it made once it is done. */ export async function captureImportStatus(jobId: string, slug: string): Promise { if (!/^[A-Za-z0-9_-]+$/.test(jobId)) throw new ImportCaptureError(`"${jobId}" is not a job id`); const got = await askEditor<{ job: { status: string }; tail?: string[] }>(`/api/ops/job/${jobId}?tail=80`, { fresh: true }); const status = got.job.status; const done = status === "done" || status === "failed" || status === "cancelled"; const line = [...(got.tail ?? [])].reverse().find((l) => l.includes(IMPORT_PAGE_MARKER)); let result: { ok?: boolean; error?: string; records?: string[] } | null = null; if (line) { try { result = JSON.parse(line.slice(line.indexOf(IMPORT_PAGE_MARKER) + IMPORT_PAGE_MARKER.length)); } catch { result = null; } } const ids = result?.records ?? []; const posts = ids.length ? await channelPosts(slug, { fresh: true }) : new Map(); return { status, done, ...(result ? { ok: result.ok === true } : {}), ...(result?.error ? { error: result.error } : done && status !== "done" ? { error: `the import job ${status}` } : {}), records: ids.map((id) => { const p = posts.get(id); return { id, ...(p?.page?.title ? { title: p.page.title } : {}), text: (p?.text ?? "").slice(0, 280) }; }), }; } /** The citation that replaces the page citation: a post of the record, the page as its fallback. */ export function replacementCitation(report: Report, cite: string, slug: string, id: string): Citation { const c = report.citations?.[cite]; if (!c || c.kind !== "page") throw new ImportCaptureError(`citation ${cite} is not a page citation`); return pageCitationAsPost(c, { channel: slug, id }); } /** * Use the imported record: a store article's citation rewritten (a hand * edit, its quote checked against the record); a site report's replacement * handed back for its draft. */ export async function useImportedRecord( site: string, report: Report, cite: string, slug: string, id: string, ): Promise<{ written: boolean; n?: number; citation: Citation }> { if (site !== ARTICLES_KEY) return { written: false, citation: replacementCitation(report, cite, slug, id) }; try { const r = await replacePageCitationWithRecord(report.id, { cite, channel: slug, id }, sitesPaths()); return { written: true, n: r.n, citation: r.citation }; } catch (e) { if (e instanceof HandEditError) throw new ImportCaptureError(e.message, 400, e.problems); throw e; } }