// The verdict bench's disk half (release 29 V1): what a channels tree tells // the items beside the cues (`diskCuesOf`, ../../convert-server.ts) — a // recording's speaker segments (its attribution sidecar, for the `turn` window // mode) and its own date (metadata.info.json's upload_date, for a quote whose // citation names none). Behind the text guard (lib/channelMedia.ts), as the // cues are: a channel whose text is not readable answers null. Reads only. // // SERVER-ONLY (node:fs). import { open } from "node:fs/promises"; import path from "node:path"; import { assertChannelTextReadable } from "../../../channelMedia"; import { resolveVideoDir } from "../../../videoDir-server.mjs"; import { isSafeChannelSegment, isSafeIdSegment } from "../../../citations/moments"; import { loadAttribution } from "../../../attribution-server"; import type { DateOf, SpeakerTurn, TurnsOf } from "./items"; function guard(channelsDir: string) { const readable = new Map>(); return (slug: string) => { let p = readable.get(slug); if (!p) { p = assertChannelTextReadable({ channelsDir }, slug).then( () => true, () => false, ); readable.set(slug, p); } return p; }; } async function videoDirOf(channelsDir: string, ok: (slug: string) => Promise, channel: string, id: string): Promise { if (!isSafeChannelSegment(channel) || !isSafeIdSegment(id)) return null; if (!(await ok(channel))) return null; return resolveVideoDir(channelsDir, channel, id).catch(() => null); } /** A recording's speaker segments from its attribution sidecar, or null. */ export function diskTurnsOf(channelsDir: string): TurnsOf { const ok = guard(channelsDir); return async (channel, id) => { const dir = await videoDirOf(channelsDir, ok, channel, id); if (!dir) return null; const rec = await loadAttribution(dir).catch(() => null); if (!rec?.segments.length) return null; return rec.segments.map((s): SpeakerTurn => ({ start: s.start, end: s.end, speaker: s.speaker })); }; } const UPLOAD_DATE_RE = /"upload_date":\s*"(\d{4})(\d{2})(\d{2})"/; const TAIL_BYTES = 8192; /** * A recording's own date, `YYYY-MM-DD`, off its metadata.info.json — yt-dlp * writes upload_date near the end, so the file's last 8 KB, then (a file * whose date is not there) the whole file. */ export function diskDateOf(channelsDir: string): DateOf { const ok = guard(channelsDir); return async (channel, id) => { const dir = await videoDirOf(channelsDir, ok, channel, id); if (!dir) return null; let fh; try { fh = await open(path.join(dir, "metadata.info.json"), "r"); const { size } = await fh.stat(); const tail = Buffer.alloc(Math.min(size, TAIL_BYTES)); await fh.read(tail, 0, tail.length, Math.max(0, size - tail.length)); let m = UPLOAD_DATE_RE.exec(tail.toString("utf8")); if (!m && size > TAIL_BYTES) { const all = Buffer.alloc(size); await fh.read(all, 0, size, 0); m = UPLOAD_DATE_RE.exec(all.toString("utf8")); } return m ? `${m[1]}-${m[2]}-${m[3]}` : null; } catch { return null; } finally { await fh?.close().catch(() => {}); } }; }