import { after, test } from "node:test"; import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; const ROOT = mkdtempSync(path.join(tmpdir(), "build-index-local-")); const PINNED: Record = { TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), SITES_DIR: path.join(ROOT, "transcripts", "sites"), SETTINGS_FILE: path.join(ROOT, "settings.json"), EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"), EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"), CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"), SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"), CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"), ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"), ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"), }; Object.assign(process.env, PINNED); delete process.env.ARCHILYZER_INDEX_ALLOW_HELD; after(() => rmSync(ROOT, { recursive: true, force: true })); const { getPaths } = await import("../lib/paths"); const { buildIndex } = await import("./buildIndex"); const { open } = await import("lmdb"); const paths = getPaths(); const { commitLocalMediaRecord } = await import("../lib/localMediaCommit-server"); const { prepareManualLocalRecordingMetadata } = await import("../lib/localRecordingMetadata"); const writeJson = (file: string, value: unknown) => { mkdirSync(path.dirname(file), {recursive: true}); writeFileSync(file, JSON.stringify(value)); }; const channel = "classroom"; const dataDirectory = path.join(paths.channelsDir, channel, "data"); const transcript = "WEBVTT\n\n00:00.000 --> 00:02.000\nSynthetic classroom discovery phrase\n"; const first = "local-" + "a".repeat(32), second = "local-" + "b".repeat(32); const metadata = (id: string, recordedDate?: string) => prepareManualLocalRecordingMetadata({id, filename: "Lesson 2020-01-01.mp4", recordedDate}); async function commit(id: string, recordedDate?: string) { return commitLocalMediaRecord({dataDirectory, directoryId: id, metadata: JSON.stringify(metadata(id, recordedDate)), transcript, reference: {version: 1, kind: "external", sourceId: "library-1", relativePath: "Lesson.mp4"}}); } function summaries(): Array<{id: string; platform: string; uploadDate: string; recordedDate?: string; webpageUrl: string}> { const root = open({path: paths.lmdbPath, maxDbs: 18, compression: true}); try { const sums = root.openDB({name: "sums", encoding: "msgpack"}); return Array.from(sums.getRange(), ({value}) => value); } finally { root.close(); } } // The FULL tree (local recordings included) a private-audience site copies; // the shared tree every other site copies leaves them out (review fix 3). function pages(root = path.join(paths.exportSharedDir, "private", "transcripts")): string { const dir = path.join(root, channel); return readdirSync(dir).filter(f => f.endsWith(".json")).map(f => readFileSync(path.join(dir,f),"utf8")).join("\n"); } test("source-less commits reach real search pages; retries and title rules retain explicit facts", async () => { writeFileSync(paths.settingsFile, "{}"); writeJson(path.join(paths.channelsDir,channel,"config.json"), {handling: "youtube", name: "Classroom"}); mkdirSync(dataDirectory, {recursive: true}); writeJson(path.join(paths.sitesDir,"localtest","site.json"), { siteId: "localtest", siteTitle: "Test", siteDescription: "fixture", headerTitle: "Test", audience: "private", homeTagline: "", socialLinks: [], groups: [{id:"default",name:"All",selectedByDefault:true}], defaultGroupId: "default", channels: [{slug:channel,groupId:"default"}], }); assert.deepEqual(await commit(first), {status:"imported"}); const logs: string[] = []; await buildIndex({paths, onLog: line => logs.push(line)}); assert.deepEqual(summaries().map(s=>s.id), [first]); assert.match(pages(), /Synthetic classroom discovery phrase/); assert.match(pages(), /"platform":\s*"local"/); assert.doesNotMatch(pages(), /youtube.com/); // The shared tree, which a public site copies, carries no local recording. assert.doesNotMatch(pages(paths.exportSharedTranscriptsDir), /"platform":\s*"local"/); assert.deepEqual(await commit(first), {status:"occupied"}); assert.deepEqual(await commit(second, "2024-02-29"), {status:"imported"}); const online = path.join(dataDirectory,"online-no-date"); writeJson(path.join(online,"metadata.info.json"), {id:"online-no-date",title:"Undated online",extractor_key:"Youtube"}); writeFileSync(path.join(online,"transcript.en.vtt"),transcript); await buildIndex({paths, onLog: line => logs.push(line)}); assert.equal(summaries().length, 2); assert.ok(logs.some(line => line.includes("online-no-date: no upload_date"))); writeJson(path.join(paths.channelsDir,channel,"config.json"), {handling:"youtube",name:"Classroom", recordedDate:{titlePattern:String.raw`(?\d{4})-(?\d{2})-(?\d{2})`}}); await buildIndex({paths, onLog: () => {}}); for (const summary of summaries()) { assert.equal(summary.platform,"local"); // The recording date is a local recording's date (review B2); none, undated. assert.equal(summary.uploadDate, summary.id === second ? "20240229" : ""); assert.equal(summary.webpageUrl, ""); assert.equal(summary.recordedDate, summary.id === second ? "20240229" : undefined); } assert.match(pages(), /"recordedDate":\s*"20240229"/); }); test("invalid local metadata cannot create a corpus record", async () => { const id="local-"+"c".repeat(32); for (const value of [{...metadata(id),webpage_url:"https://example.com/video"}, {...metadata(id),id:first}]) { await assert.rejects(commitLocalMediaRecord({dataDirectory,directoryId:id,metadata:JSON.stringify(value),transcript, reference:{version:1,kind:"external",sourceId:"library-1",relativePath:"Lesson.mp4"}})); } assert.equal(readdirSync(dataDirectory).includes(id),false); }); test("a malformed local_recording written past the importer is skipped with a log line, not thrown", async () => { const id = "local-" + "d".repeat(32); const dir = path.join(dataDirectory, id); writeJson(path.join(dir, "metadata.info.json"), {...metadata(id), local_recording: {version: 99}}); writeFileSync(path.join(dir, "transcript.en.vtt"), transcript); const logs: string[] = []; await buildIndex({paths, onLog: line => logs.push(line)}); assert.ok(!summaries().some(s => s.id === id)); assert.ok(logs.some(line => line.includes(`${id}: invalid local_recording metadata`)), logs.join("\n")); assert.ok(!logs.some(line => line.includes("Failed to process")), logs.join("\n")); rmSync(dir, {recursive: true, force: true}); }); // Review B2: an undated local record (uploadDate "") through the index, the // summaries page order, the stats run and the recency index the lanes read. test("an undated local record pages last, keeps a stats row, and reads as unknown to the recency index", async () => { const { siteSummariesDir } = await import("../lib/site"); const { buildStats } = await import("./buildStats"); const { openUploadDateIndex } = await import("./recencyIndex"); // The first test's undated ONLINE record is skipped by the index, and so, // on main, re-"added" by every stats run: out of this one's count. rmSync(path.join(dataDirectory, "online-no-date"), {recursive: true, force: true}); const online = path.join(dataDirectory, "onlinedated"); writeJson(path.join(online, "metadata.info.json"), {id: "onlinedated", title: "Dated online", extractor_key: "Youtube", upload_date: "20250101", webpage_url: "https://www.youtube.com/watch?v=onlinedated"}); writeFileSync(path.join(online, "transcript.en.vtt"), transcript); await buildIndex({paths, onLog: () => {}}); const dir = siteSummariesDir(paths, "localtest"); const listed: Array<{id: string; date: string}> = readdirSync(dir).filter(f => /^page-\d+\.json$/.test(f)).sort() .flatMap(f => JSON.parse(readFileSync(path.join(dir, f), "utf8"))); // Newest first: the dated online record, the dated local one, then the undated one last. assert.deepEqual(listed.map(r => r.id), ["onlinedated", second, first]); assert.deepEqual(listed.map(r => r.date), ["2025-01-01", "2024-02-29", ""]); const logs: string[] = []; const once = await buildStats({paths, onLog: line => logs.push(line)}); assert.ok(once.added >= 3, JSON.stringify(once)); const twice = await buildStats({paths, onLog: () => {}}); // Without a row for the undated record it was "added" every run, and every // site's stats bundle rewritten. assert.equal(twice.added, 0, JSON.stringify(twice)); assert.equal(twice.shortCircuited, true, JSON.stringify(twice)); const recency = openUploadDateIndex(paths, [channel]); try { const dates = recency.datesBySlug.get(channel)!; assert.equal(dates.get(first), ""); assert.equal(dates.get(second), "20240229"); assert.equal(dates.get("onlinedated"), "20250101"); } finally { await recency.close(); } rmSync(online, {recursive: true, force: true}); }); // Review fix 3 (the publish boundary): a PUBLIC site's build leaves local // recordings out — its summaries, counts and stats — and says so once with the // count; a PRIVATE-audience site carries them; compose picks the private // transcript tree for the private site only; the hub's whole-pool stats have none. test("a public site leaves local recordings out and says so; a private one carries them", async () => { const { siteSummariesDir, siteStatsDir } = await import("../lib/site"); const { buildStats } = await import("./buildStats"); const { transcriptsSourceFor } = await import("../bin/compose-site"); const online = path.join(dataDirectory, "onlinepublic"); writeJson(path.join(online, "metadata.info.json"), {id: "onlinepublic", title: "Online public", extractor_key: "Youtube", upload_date: "20250102", webpage_url: "https://www.youtube.com/watch?v=onlinepublic"}); writeFileSync(path.join(online, "transcript.en.vtt"), transcript); writeJson(path.join(paths.sitesDir, "publictest", "site.json"), { siteId: "publictest", siteTitle: "Public", siteDescription: "fixture", headerTitle: "Public", homeTagline: "", socialLinks: [], groups: [{id: "default", name: "All", selectedByDefault: true}], defaultGroupId: "default", channels: [{slug: channel, groupId: "default"}], }); const logs: string[] = []; await buildIndex({paths, onLog: line => logs.push(line)}); const listed = (site: string) => { const dir = siteSummariesDir(paths, site); const ids = readdirSync(dir).filter(f => /^page-\d+\.json$/.test(f)) .flatMap(f => JSON.parse(readFileSync(path.join(dir, f), "utf8")) as Array<{id: string}>).map(r => r.id); const manifest = JSON.parse(readFileSync(path.join(dir, "manifest.json"), "utf8")) as {totalCount: number}; return {ids, total: manifest.totalCount}; }; const pub = listed("publictest"), priv = listed("localtest"); assert.deepEqual(pub.ids, ["onlinepublic"]); assert.equal(pub.total, 1); assert.ok(priv.ids.includes(first) && priv.ids.includes(second) && priv.ids.includes("onlinepublic"), priv.ids.join()); assert.equal(logs.filter(l => /Site publictest: 2 local recording\(s\) left out/.test(l)).length, 1, logs.join("\n")); assert.ok(!logs.some(l => /Site localtest: .* local recording/.test(l))); // Compose's choice of transcript tree: the private one only for a private site. assert.equal(await transcriptsSourceFor(paths, false)(channel), path.join(paths.exportSharedTranscriptsDir, channel)); assert.equal(await transcriptsSourceFor(paths, true)(channel), path.join(paths.exportSharedDir, "private", "transcripts", channel)); assert.equal(await transcriptsSourceFor(paths, true)("no-locals"), path.join(paths.exportSharedTranscriptsDir, "no-locals")); const pool = path.join(ROOT, "pool-stats"); await buildStats({paths, onLog: () => {}, wholePoolStatsDir: pool}); const statsIds = (dir: string) => readdirSync(dir).filter(f => /^page-\d+\.json$/.test(f)) .flatMap(f => JSON.parse(readFileSync(path.join(dir, f), "utf8")) as Array<{id: string}>).map(r => r.id); assert.deepEqual(statsIds(siteStatsDir(paths, "publictest")), ["onlinepublic"]); assert.ok(statsIds(siteStatsDir(paths, "localtest")).includes(first)); assert.deepEqual(statsIds(pool), ["onlinepublic"]); rmSync(online, {recursive: true, force: true}); rmSync(path.join(paths.sitesDir, "publictest"), {recursive: true, force: true}); });