// The disk half of the source status (./sourceStatus.mjs): one video directory's // records read and handed to deriveSourceStatus. READ ONLY, and only these five // files: availability.json, download-outcome.json, metadata.info.json, // metadata.history.json, live-recording.json. A file that is missing or is not // JSON is null, never an error: no record is no state. // // SERVER-ONLY (node:fs). Plain JS: umtool's bins run under bare node. import { readFile, stat } from "node:fs/promises"; import path from "node:path"; import { deriveSourceStatus } from "./sourceStatus.mjs"; /** The record files a source status is read from, by deriveSourceStatus's names. */ export const SOURCE_RECORD_FILES = Object.freeze({ availability: "availability.json", outcome: "download-outcome.json", metadata: "metadata.info.json", metadataHistory: "metadata.history.json", liveRecording: "live-recording.json", }); async function readJson(file) { try { return JSON.parse(await readFile(file, "utf8")); } catch { return null; } } /** The records deriveSourceStatus reads, from one video directory. */ export async function readSourceRecords(videoDir) { const entries = await Promise.all( Object.entries(SOURCE_RECORD_FILES).map(async ([k, name]) => [k, await readJson(path.join(videoDir, name))]), ); const records = Object.fromEntries(entries); // metadata.info.json can be tens of MB (formats, captions): keep the few fields read. const m = records.metadata; if (m && typeof m === "object") { records.metadata = { ...(Object.hasOwn(m, "availability") ? { availability: m.availability } : {}), ...(Object.hasOwn(m, "live_status") ? { live_status: m.live_status } : {}), ...(Number.isFinite(m.epoch) ? { epoch: m.epoch } : {}), ...(Number.isFinite(m.release_timestamp) ? { release_timestamp: m.release_timestamp } : {}), ...(Number.isFinite(m.duration) ? { duration: m.duration } : {}), }; } return records; } /** One video directory's source status (deriveSourceStatus), or null. */ export async function readSourceStatus(videoDir) { return deriveSourceStatus(await readSourceRecords(videoDir)); } /** * The newest modification time (ms, whole) of the record files in one video * directory, or null when it holds none: what a stamp keeps per source * (`recordsAt`), so `umtool check` says it is out of date only when a record * was written after the reading it holds -- not after the stamp's own write, * which a refresh that found nothing new does not make. */ export async function newestSourceRecordMs(videoDir) { let newest = null; for (const name of Object.values(SOURCE_RECORD_FILES)) { const st = await stat(path.join(videoDir, name)).catch(() => null); if (st?.isFile()) newest = Math.max(newest ?? 0, Math.floor(st.mtimeMs)); } return newest; }