// A CHANNEL'S AVAILABILITY VERDICT, cached: which videos its source listed the // last time the quick availability check asked, and when. Written by that check // (controller/quickAvailabilityCheck.ts, one flat-playlist listing on the // channel's platform queue); READ by clean-after-capture, which must never ask // the network itself (lane/speakers-run review, B1: one full listing per // cleaned video, outside every queue, gap and hold). // // The per-video question (verdictFor) has four answers: // listed — the channel's fresh listing names the video: safe to clean; // absent — a fresh listing does NOT name it: maybe deleted, maybe unlisted // (unlisted videos legitimately drop out of a listing). Held; the // manual "check maybe missing" resolves which; // stale — the newest listing is older than diarization.cleanVerdictMaxAgeHours; // none — the channel has never been listed by the check. // Stale and none hold the video "awaiting an availability check", and // requestAvailabilityCheck asks for at most one check of that channel per // max age, on its platform's own queue. import path from "node:path"; import type { Paths } from "../lib/paths"; import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { heldPlatformRefusal } from "../jobs/downloadBackoff"; import { raisedServiceAlert } from "../lib/serviceCookies-server"; import { detectPlatform, platformQueueKey, queueKeyForUrl } from "../lib/platform"; import { resolveQueueKey } from "../lib/queueKeys"; import { readChannelConfig } from "./channels"; import { runQuickAvailabilityCheck } from "./quickAvailabilityCheck"; export const AVAILABILITY_VERDICT_FILENAME = "availability-verdict.json"; export type AvailabilityVerdictRecord = { version: 1; // ISO 8601 of the listing, or null before the first one. checkedAt: string | null; // Canonical ids (data-dir names) the listing named, sorted. ids: string[]; // ISO 8601 of the last check REQUESTED by clean-after-capture, so a lane that // holds a hundred videos of one channel asks once, and a restart does not // ask again inside the max age. requestedAt?: string; }; export function availabilityVerdictPath(paths: Pick, slug: string): string { return path.join(paths.channelsDir, slug, AVAILABILITY_VERDICT_FILENAME); } function coerce(value: unknown): AvailabilityVerdictRecord | null { const v = value as Partial | null; if (!v || typeof v !== "object" || !Array.isArray(v.ids)) return null; return { version: 1, checkedAt: typeof v.checkedAt === "string" ? v.checkedAt : null, ids: v.ids.filter((x): x is string => typeof x === "string"), ...(typeof v.requestedAt === "string" ? { requestedAt: v.requestedAt } : {}), }; } export async function readAvailabilityVerdict( paths: Pick, slug: string, ): Promise { const read = await readJsonFile(availabilityVerdictPath(paths, slug)); return read.ok ? coerce(read.value) : null; } async function update( paths: Pick, slug: string, fn: (r: AvailabilityVerdictRecord) => AvailabilityVerdictRecord, ): Promise { const file = availabilityVerdictPath(paths, slug); await withJsonFileLock(file, async () => { const cur = (await readAvailabilityVerdict(paths, slug)) ?? { version: 1, checkedAt: null, ids: [] }; await writeJsonAtomic(file, fn(cur)); }); } // The quick check's half: what the listing named, and when. export function writeAvailabilityVerdict( paths: Pick, slug: string, listing: { checkedAt: string; ids: Iterable }, ): Promise { return update(paths, slug, (r) => ({ ...r, checkedAt: listing.checkedAt, ids: [...new Set(listing.ids)].sort(), })); } export function markAvailabilityCheckRequested( paths: Pick, slug: string, at: string, ): Promise { return update(paths, slug, (r) => ({ ...r, requestedAt: at })); } export type VideoVerdict = "listed" | "absent" | "stale" | "none"; const HOUR = 3_600_000; // PURE. export function verdictFor( record: AvailabilityVerdictRecord | null, videoId: string, maxAgeHours: number, now: number = Date.now(), ): VideoVerdict { if (!record?.checkedAt) return "none"; const at = Date.parse(record.checkedAt); if (!Number.isFinite(at) || now - at > maxAgeHours * HOUR) return "stale"; return record.ids.includes(videoId) ? "listed" : "absent"; } // PURE: may clean-after-capture ask for another check of this channel now? // Not when one was asked for within the max age (it is queued, running, or // failed — and a failure is not a reason to ask again sooner). export function mayRequestCheck( record: AvailabilityVerdictRecord | null, maxAgeHours: number, now: number = Date.now(), ): boolean { const at = record?.requestedAt ? Date.parse(record.requestedAt) : NaN; return !Number.isFinite(at) || now - at > maxAgeHours * HOUR; } // --------------------------------------------------------------------------- // Asking for a check — never doing one. // The quick availability check as a job on the channel's PLATFORM queue — the // one the channel page's Quick check button runs (kind // quick-availability-check, network: so runManagedFunction's network guard // applies: never unqueued, and an X job only on a fresh jar with no alert up). export async function startQuickAvailabilityCheckJob(opts: { paths: Paths; slug: string; queueKey?: string; onDone?: () => void; }): Promise { const config = await readChannelConfig(opts.paths, opts.slug); const defaultQueue = config?.platform ? platformQueueKey(config.platform) : queueKeyForUrl(config?.url); return runManagedFunction({ kind: "quick-availability-check", queueKey: resolveQueueKey(defaultQueue, opts.queueKey), paths: opts.paths, channelSlug: opts.slug, fn: async (onLog, signal) => { await runQuickAvailabilityCheck({ channelSlug: opts.slug, paths: opts.paths, onLog, signal }); opts.onDone?.(); }, }); } export type CheckRequestDeps = { start?: (paths: Paths, slug: string) => Promise; platformRefusal?: (platform: string) => Promise; // The platform's open cookie/service alert (the store `get services` // reads), as its evidence line, or null. serviceAlert?: (platform: string) => Promise; now?: () => number; }; export type CheckRequest = | { status: "requested"; jobId?: string } | { status: "already-requested"; at: string } | { status: "platform-held"; why: string } | { status: "service-alert"; why: string } | { status: "refused"; why: string } | { status: "no-url" }; // At most one check per channel per max age, and none while its platform is // held: a hold is the platform asking us to stop, and a check is a request. export async function requestAvailabilityCheck( paths: Paths, slug: string, maxAgeHours: number, deps: CheckRequestDeps = {}, ): Promise { const now = deps.now?.() ?? Date.now(); const config = await readChannelConfig(paths, slug); if (!config?.url) return { status: "no-url" }; const platform = config.platform ?? detectPlatform(config.url) ?? "unknown"; const held = await (deps.platformRefusal ?? ((p: string) => heldPlatformRefusal(p, "An availability check", paths)))(platform); if (held) return { status: "platform-held", why: held }; // An open cookie alert is the platform answering with a challenge or a // login wall: a listing now would only add to it. Asked nothing until the // operator's Recheck or Dismiss clears it. const alert = await ( deps.serviceAlert ?? (async (p: string) => { const e = await raisedServiceAlert(paths, p); return e ? (e.evidence?.line ?? "alert raised") : null; }) )(platform); if (alert) return { status: "service-alert", why: alert }; const record = await readAvailabilityVerdict(paths, slug); if (!mayRequestCheck(record, maxAgeHours, now)) { return { status: "already-requested", at: record!.requestedAt! }; } // Marked BEFORE the start, so two units finishing at once cannot both ask. await markAvailabilityCheckRequested(paths, slug, new Date(now).toISOString()); const started = await (deps.start ?? ((p: Paths, s: string) => startQuickAvailabilityCheckJob({ paths: p, slug: s })))(paths, slug); if (!started.ok) return { status: "refused", why: started.error ?? "the check could not be queued" }; return { status: "requested", jobId: started.jobId }; }