import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { persistSourceVideo } from "../lib/savedVideo-server"; import { persistKept } from "./persistKept"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/persistKept.test.ts // // These cover the orchestration paths that don't reach downloadOneManaged (no // network): keep-latest off, and an all-already-saved window. The download path // is exercised via redownloadToArchiveAction in the editor e2e suite. async function withPaths(fn: (paths: Paths) => Promise): Promise { const dir = await mkdtemp(path.join(tmpdir(), "ttb-persistkept-")); const paths = { channelsDir: path.join(dir, "channels"), savedVideosDir: path.join(dir, "saved"), } as Paths; try { await fn(paths); } finally { await rm(dir, { recursive: true, force: true }); } } // Seed a data dir whose dir name carries a YYYYMMDD_ recency prefix (so // computeKeptVideoIds can order it without metadata) and persist its container. async function seedSaved( paths: Paths, slug: string, id: string, ): Promise { const videoDir = path.join(paths.channelsDir, slug, "data", id); await mkdir(videoDir, { recursive: true }); await writeFile(path.join(videoDir, "source-media.mp4"), id); await persistSourceVideo({ videoDir, sourceFilename: "source-media.mp4", storeDir: path.join(paths.savedVideosDir, slug, id), keepReason: "keep-latest", }); } test("persistKept is a no-op when keep-latest is off", async () => { await withPaths(async (paths) => { await seedSaved(paths, "alpha", "20240101_a"); const res = await persistKept({ paths, channelSlug: "alpha", channelConfig: { handling: "transcribe" }, }); assert.deepEqual(res, { kept: 0, alreadySaved: 0, persisted: 0, failed: 0, skippedNoUrl: 0, skippedLowDisk: 0, }); }); }); test("persistKept counts in-window videos already saved without re-downloading", async () => { await withPaths(async (paths) => { await seedSaved(paths, "alpha", "20240101_a"); await seedSaved(paths, "alpha", "20240202_b"); await seedSaved(paths, "alpha", "20240303_c"); // Window of 2 -> the two newest (c, b) are kept; both are already saved, so // no download is attempted (which would fail in this offline test). const res = await persistKept({ paths, channelSlug: "alpha", channelConfig: { handling: "transcribe", keepLatest: 2 }, }); assert.equal(res.kept, 2); assert.equal(res.alreadySaved, 2); assert.equal(res.persisted, 0); assert.equal(res.failed, 0); assert.equal(res.skippedNoUrl, 0); }); });