import { SPACE_SCAN_VERSION, type SpaceScanResult, type SpaceSuggestion } from "yt-dlp-transcript-common/lib/spaceSuggestions"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; // THE PAGE'S BUTTON, ON THE SERVER. It names a suggestion by its key; what runs // is the `actions` the SCAN wrote for it (`pnpm ops --json `), each // through the same action its ops route calls — compress-text, the cleanup // sweeps, relocate, evict-clips, delete-file, compact-saved-videos, // drop-saved-alternate, kept-failed-encodes, live-recording-verify. Nothing // else: an op not in the table is refused, no body comes from the browser, // and a body of the wrong shape (a slug, an id or a file name that is not one // path segment) is refused. // // THE WRITERS DO NOT ALL GUARD WHAT THIS PAGE PROMISES (review 1, B4): the // Files list's delete, for one, asks no do-not-clean, recording, job or // marker. So before anything runs the row is RE-CHECKED against the disk as // it is now (controller/spaceHold.ts recheckSpaceRow): a scan older than a day // is refused, then the held predicate (do-not-clean, a must-keep or // unfinished live recording, a job for the video, a relocation marker of the // channel or of the store), then each target file's size, mtime and single // link, and a channel-wide eviction's whole set of old windows. A mismatch // refuses the row and says why. // // NOT "use server" (every export there is an endpoint): actions.ts wraps it. export type SpaceRunOutcome = { ok: boolean; lines: string[]; jobIds: string[]; dryRun: boolean }; export type SpaceRunner = (body: Record, o: { dryRun: boolean }) => Promise; // The writers whose dry run answers at once (a job's would be a job). export const SPACE_DRY_RUNNABLE: ReadonlySet = new Set(["compress-text", "compact-saved-videos", "drop-saved-alternate"]); const str = (v: unknown): string => (typeof v === "string" ? v : ""); const strs = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []); function fromStream(r: StreamActionResult): SpaceRunOutcome { if (!r.ok) return { ok: false, lines: [r.error], jobIds: [], dryRun: false }; void r.stream.cancel(); return { ok: true, lines: ["queued"], jobIds: [r.jobId], dryRun: false }; } const fail = (error: string): SpaceRunOutcome => ({ ok: false, lines: [error], jobIds: [], dryRun: false }); // The real table: the same calls the ops routes make. Imported lazily, so the // dispatcher's test (and a page that only renders) loads none of them. export const SPACE_RUNNERS: Record = { "compress-text": async (body, o) => { const { compressTextAction } = await import("../../../storage/compressTextActions"); const kinds = strs(body.kinds) as ("live-chat" | "captions")[]; const r = await compressTextAction({ slugs: strs(body.slugs), ...(kinds.length ? { kinds } : {}), dryRun: o.dryRun }); if (!r.ok) return fail(r.error); if (r.dryRun) return { ok: true, lines: r.result.lines, jobIds: [], dryRun: true }; return { ok: true, lines: [`${r.jobIds.length} job(s) queued`, ...r.skipped.map((s) => `${s.slug}: ${s.reason}`)], jobIds: r.jobIds, dryRun: false }; }, cleanup: async (body) => { const w = await import("../../../channels/[slug]/whisperActions"); const slug = str(body.slug); if (body.sweep === "transcribed") return fromStream(await w.cleanAudioAction(slug)); if (body.sweep === "extra-formats") return fromStream(await w.cleanExtraAudioFormatsAction(slug)); return fail(`sweep "${str(body.sweep)}" is not one this page runs`); }, relocate: async (body) => { const { bulkRelocateChannelMediaAction } = await import("../../../channels/bulkStorageActions"); const r = await bulkRelocateChannelMediaAction(strs(body.slugs), { kind: "location", locationId: str(body.locationId) }); return { ok: r.queued.length > 0, lines: [...r.queued.map((s) => `${s}: queued`), ...r.skipped.map((s) => `${s.slug}: ${s.reason}`)], jobIds: r.jobIds, dryRun: false, }; }, "evict-clips": async (body) => { const { evictClipWindowsAction } = await import("../../../storage/actions"); return fromStream( await evictClipWindowsAction({ ...(body.slug ? { slug: str(body.slug) } : {}), ...(body.id ? { id: str(body.id) } : {}), ...(typeof body.olderThanDays === "number" ? { olderThanDays: body.olderThanDays } : {}), }), ); }, "delete-file": async (body) => { const { deleteVideoFileAction } = await import("../../../channels/[slug]/videos/[id]/videoActions"); const r = await deleteVideoFileAction(str(body.slug), str(body.id), str(body.file)); return r.ok ? { ok: true, lines: [`${str(body.file)} removed${r.note ? ` (${r.note})` : ""}`], jobIds: [], dryRun: false } : fail(r.error); }, "compact-saved-videos": async (body, o) => { const { compactSavedVideosAction } = await import("../../../saved-videos/compactActions"); const items = (Array.isArray(body.items) ? body.items : []).map((i) => ({ slug: str((i as Record).slug), id: str((i as Record).id) })); const r = await compactSavedVideosAction({ items, dryRun: o.dryRun }); if (!r.ok) return fail(r.error); if (r.dryRun) return { ok: true, lines: r.plan.lines, jobIds: [], dryRun: true }; return { ok: true, lines: [`${r.jobIds.length} job(s) queued on the compact queue`, ...r.skipped.map((s) => `${s.slug}: ${s.reason}`)], jobIds: r.jobIds, dryRun: false }; }, "drop-saved-alternate": async (body, o) => { const { dropSavedAlternateAction } = await import("../../../channels/[slug]/videos/[id]/videoActions"); const r = await dropSavedAlternateAction(str(body.slug), str(body.id), str(body.file), { dryRun: o.dryRun, confirmOriginal: body.confirmOriginal === true, }); if (!r.ok) return fail(r.error); const verb = r.result.dryRun ? "would free" : "freed"; return { ok: true, lines: [`${r.result.alternate.file}: ${verb} ${formatBytes(r.result.bytes)}${r.result.existed ? "" : " (already gone: only its entry)"}`], jobIds: [], dryRun: r.result.dryRun }; }, "kept-failed-encodes": async (body) => { const { keptFailedEncodesAction } = await import("../../../saved-videos/compactActions"); const c = (body.clear ?? {}) as Record; const r = await keptFailedEncodesAction({ clear: { slug: str(c.slug), id: str(c.id) } }); const cleared = r.cleared; return cleared?.cleared ? { ok: true, lines: [cleared.why], jobIds: [], dryRun: false } : fail(cleared?.why ?? "not cleared"); }, "live-recording-verify": async (body) => { const { reverifyLiveRecordingAction } = await import("../../../channels/[slug]/liveMediaActions"); const r = await reverifyLiveRecordingAction({ slug: str(body.slug), id: str(body.id), ...(body.startedAt ? { startedAt: str(body.startedAt) } : {}) }); if (!r.ok) return fail(r.error); return { ok: true, lines: [r.verified ? `verified: ${r.removed.length} stream file(s) removed` : `not verified: ${r.why ?? "nothing removed"}`], jobIds: [], dryRun: false, }; }, }; // THE BODY'S SHAPE: every slug a channel slug, every id and file one path // segment. The scan writes these; a file edited by hand is refused here. const SEGMENT = /^(?!\.\.?$)[\w.-]+$/; export function bodyShapeProblem(body: Record): string | null { const slugs = [body.slug, ...(Array.isArray(body.slugs) ? body.slugs : [])]; const items = Array.isArray(body.items) ? (body.items as Record[]) : []; const clear = body.clear && typeof body.clear === "object" ? (body.clear as Record) : null; for (const it of [...items, ...(clear ? [clear] : [])]) slugs.push(it.slug); for (const v of slugs) if (v !== undefined && (typeof v !== "string" || !isValidChannelSlug(v))) return `"${String(v)}" is not a channel slug`; const ids = [body.id, ...items.map((i) => i.id), ...(clear ? [clear.id] : [])]; for (const v of ids) if (v !== undefined && (typeof v !== "string" || !SEGMENT.test(v))) return `"${String(v)}" is not a video id`; if (body.file !== undefined && (typeof body.file !== "string" || !SEGMENT.test(body.file))) return `"${String(body.file)}" is not a file name in one path segment`; return null; } // The click-time re-check (controller/spaceHold.ts), loaded lazily so a test // that names its own never reaches the registry or the disk. async function defaultRecheck(result: Pick, row: SpaceSuggestion): Promise { const { recheckSpaceRow, SpaceHolds } = await import("yt-dlp-transcript-common/controller/spaceHold"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); const paths = getPaths(); return recheckSpaceRow({ paths, result, row, holds: new SpaceHolds(paths) }); } export async function runSpaceSuggestion(opts: { result: Pick | null; // The version the file on disk says, when it did not parse as this // editor's (`result` null): an older format is "rescan first" (F2). fileVersion?: number | null; key: string; dryRun: boolean; runners?: Record; recheck?: (row: SpaceSuggestion) => Promise; }): Promise { const runners = opts.runners ?? SPACE_RUNNERS; if (!opts.result && typeof opts.fileVersion === "number" && opts.fileVersion !== SPACE_SCAN_VERSION) { return fail(`the last scan is of an older format (version ${opts.fileVersion}, this editor writes ${SPACE_SCAN_VERSION}): rescan first`); } const s = opts.result?.suggestions.find((x) => x.key === opts.key); if (!s || !opts.result) return fail(`no suggestion "${opts.key}" in the last scan: refresh the page`); if (!s.actions?.length) return fail(`nothing to run here: ${s.link ? `see ${s.link.label}` : "this row is for information"}`); if (s.disabled) return fail(s.disabled); const unknown = s.actions.find((a) => !runners[a.op]); if (unknown) return fail(`not a writer this page runs: ${unknown.op}`); for (const a of s.actions) { const bad = bodyShapeProblem(a.body); if (bad) return fail(`refused: ${bad}`); } const result = opts.result; const problem = await (opts.recheck ?? ((row: SpaceSuggestion) => defaultRecheck(result, row)))(s); if (problem) return fail(`refused: ${problem}`); if (opts.dryRun && s.actions.some((a) => !SPACE_DRY_RUNNABLE.has(a.op))) { return fail(`${s.actions[0].op} has no dry run that answers here: the numbers above are the scan's`); } const out: SpaceRunOutcome = { ok: true, lines: [], jobIds: [], dryRun: opts.dryRun }; for (let i = 0; i < s.actions.length; i++) { const a = s.actions[i]; const r = await runners[a.op](a.body, { dryRun: opts.dryRun }).catch((e: Error) => fail(e.message)); out.lines.push(...r.lines); out.jobIds.push(...r.jobIds); if (!r.ok) { out.ok = false; const rest = s.actions.length - i - 1; if (rest > 0) out.lines.push(`${rest} more not run`); break; } } return out; }