commit 31dc985afdfea9377fb8b74ece1ac17ba92b7bd6
parent d682870141d9237ef20f23100baa3d332f0ed8cb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 6 Nov 2026 21:10:41 -0500
umtool: a Rumble clip is fetched whole, never seeked, and asked for by its directory id
The 6 Nov windows were remote seeks: umtool's per-clip fetch (the bench's
fetch more, build-video's --fetch-only through fetch-via-editor) asked the
single /api/media/fetch-window, which seeks when no saved video covers -- and
it asked by the EMBED id the manifest cites, whose data/<embed>/ does not
exist, so no saved video was ever found (and c43's re-fetch went to the embed
page: a 403).
recording-ids.mjs decides both before the editor is asked: the directory id
the corpus keeps a recording under (common's resolveVideoDirId: the Rumble
embed id -> its URL slug's directory), and whether its platform is on
settings.clips.wholeRecordingPlatforms (default rumble; the channel's
platform, else the page URL's). A whole-recording clip is asked of
fetch-windows -- the whole recording saved once on the platform's download
queue, its clock made current, the window cut on the cue clock -- waited for,
and read off the corpus; a failed run exits naming the failure, and nothing
falls back to a seek. `--all`, `umtool fetch` and the umtool app's fetch route
post directory ids too (said once: "asked by directory id: rc/v7drc5w ->
v7fxp3e"); --refetch-video accepts the cited id.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
8 files changed, 442 insertions(+), 35 deletions(-)
diff --git a/umtool/app/api/report/fetch-windows/route.ts b/umtool/app/api/report/fetch-windows/route.ts
@@ -75,7 +75,7 @@ export async function POST(request: Request) {
if (action !== "dry-run" && action !== "start") {
return Response.json({ error: 'action must be "dry-run", "start" or "follow"' }, { status: 400, headers });
}
- const { body, skipped } = await projectFetchBody(project);
+ const { body, skipped } = await projectFetchBody(project, { localIds: true });
if (!body.items.length) return Response.json({ error: "no clip windows to fetch" }, { status: 400, headers });
const answer = await postFetchWindows(cfg, body, { dryRun: action === "dry-run" });
const run = await recordFetchRun(project.dir, { body, answer });
diff --git a/umtool/lib/report/fetchCli.mjs b/umtool/lib/report/fetchCli.mjs
@@ -140,7 +140,7 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con
let fetched;
try {
- fetched = await projectFetchBody(project, { reason, take });
+ fetched = await projectFetchBody(project, { reason, take, localIds: true });
} catch (e) {
if (take) throw new CliError(`${project.id}: ${e instanceof Error ? e.message : String(e)}`);
throw e;
@@ -154,12 +154,23 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con
out(`${who}: no clip windows to fetch${skipped.length ? ` (${skipped.length} skipped)` : ""}`);
return 0;
}
+ if (fetched.mapped?.length && !json) {
+ const { mappedLine } = await import("umtool-report-to-video/recording-ids");
+ out(`${who}: asked by directory id: ${mappedLine(fetched.mapped)}`);
+ }
const dryRun = args.includes("--dry-run");
// A REFETCH EVICTS FIRST, and waits: the fetch takes a cache hit before
// anything else, so it must not be asked until the eviction has ended.
let refetch = null;
if (refetchClips.length || refetchVideos.length) {
- const plan = refetchEvictions(body, skipped, { clipIds: refetchClips, videos: refetchVideos });
+ // A video named by its cited id (a Rumble embed id) is the directory the body asks for.
+ const { localVideoId } = await import("umtool-report-to-video/recording-ids");
+ const videos = [];
+ for (const v of refetchVideos) {
+ const at = String(v).indexOf("/");
+ videos.push(at > 0 ? `${v.slice(0, at)}/${await localVideoId({ slug: v.slice(0, at), id: v.slice(at + 1) })}` : v);
+ }
+ const plan = refetchEvictions(body, skipped, { clipIds: refetchClips, videos });
if (!plan.ok) throw new CliError(plan.error);
refetch = [];
for (const req of plan.requests) {
diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs
@@ -177,10 +177,15 @@ export function bodyHash(body) {
* patch, not the cut) is asked for, and a DRAFT take needs no render first.
* The body names takes/<id>/take.json as the manifest it came from.
*
+ * `localIds` (what is POSTED, never what a page shows): each item's id is the
+ * DIRECTORY id the corpus keeps the recording under -- a Rumble embed id, which
+ * the manifest cites, becomes its URL slug's directory (recording-ids.mjs) --
+ * and `mapped` lists the ids that changed.
+ *
* @param {{ id: string, dir: string }} project
- * @param {{ reason?: string | null, take?: string | null }} [opts]
+ * @param {{ reason?: string | null, take?: string | null, localIds?: boolean }} [opts]
*/
-export async function projectFetchBody(project, { reason = null, take = null } = {}) {
+export async function projectFetchBody(project, { reason = null, take = null, localIds = false } = {}) {
let manifestPath = path.join(project.dir, MANIFEST_FILE);
let manifest;
if (take) {
@@ -191,7 +196,11 @@ export async function projectFetchBody(project, { reason = null, take = null } =
manifest = JSON.parse(await readFile(manifestPath, "utf8"));
}
const rulings = await readMontageRulings(project.dir);
- return { manifest, manifestPath, ...fetchWindowsBody(manifest, { manifestPath, project: project.id, rulings, reason }) };
+ const built = fetchWindowsBody(manifest, { manifestPath, project: project.id, rulings, reason });
+ if (!localIds) return { manifest, manifestPath, ...built, mapped: [] };
+ const { withLocalIds } = await import("umtool-report-to-video/recording-ids");
+ const local = await withLocalIds(built.body.items);
+ return { manifest, manifestPath, ...built, body: { ...built.body, items: local.items }, mapped: local.mapped };
}
// ---------------------------------------------------------------------------
diff --git a/umtool/report-to-video/fetch-via-editor.mjs b/umtool/report-to-video/fetch-via-editor.mjs
@@ -28,6 +28,8 @@
import path from "node:path";
import { readFile } from "node:fs/promises";
+import { corpusChannelsDir, isWholeRecording, localVideoId, mappedLine, recordingPlatform, withLocalIds } from "./recording-ids.mjs";
+import { resolveLocalSource } from "./sources.mjs";
const DEFAULT_EDITOR = "http://localhost:3001";
// One poll a second while a job runs, one every five while it waits its turn.
@@ -226,6 +228,37 @@ async function notePlace(jobId, label, last) {
return line;
}
+// Every fetch-windows job, polled to its end; the failed ones' reasons. A job
+// that stopped short (a rate limit, two 403s) fails with the reason; asking
+// again later resumes it, the fetched windows answering from the cache.
+// No deadline: a batch queued behind hours of other work is waited for.
+async function waitForJobs(jobs) {
+ const pending = new Map(jobs.map((j) => [j.jobId, j]));
+ for (const jobId of pending.keys()) waitingOn.add(jobId);
+ const failed = [];
+ const last = new Map();
+ const places = new Map();
+ while (pending.size > 0) {
+ await sleep(QUEUED_POLL_MS);
+ for (const [jobId, j] of pending) {
+ const p = await pollJob(jobId);
+ const label = j.platform ? ` (${j.platform}, ${j.items} window(s))` : "";
+ if (p.status !== last.get(jobId)) {
+ last.set(jobId, p.status);
+ EMIT("note", { message: ` editor job ${jobId}${label}: ${p.status}` });
+ }
+ if (p.status === "queued") places.set(jobId, await notePlace(jobId, label, places.get(jobId)));
+ if (p.status === "done") pending.delete(jobId);
+ else if (p.status === "failed" || p.status === "cancelled") {
+ pending.delete(jobId);
+ failed.push(`${jobId} ${p.status}: ${String(p.error ?? "").split("\n").slice(-3).join(" / ")}`);
+ }
+ if (!pending.has(jobId)) waitingOn.delete(jobId);
+ }
+ }
+ return failed;
+}
+
if (wantAll) {
if (argv.includes("--full")) die("--all fetches windows; --full is one clip's whole recording");
const clips = (whole.timeline ?? []).filter((e) => e.type === "clip");
@@ -248,11 +281,15 @@ if (wantAll) {
EMIT("done", { out: null, nothingToFetch: true });
process.exit(0);
}
+ // Each recording asked for by its DIRECTORY id (a Rumble embed id → its URL
+ // slug's directory: recording-ids.mjs).
+ const local = await withLocalIds(items);
+ if (local.mapped.length) EMIT("note", { message: ` asked by directory id: ${mappedLine(local.mapped)}` });
const res = await ask(`${editorUrl}/api/ops/fetch-windows`, {
method: "POST",
headers,
body: JSON.stringify({
- items,
+ items: local.items,
requestedBy: "umtool",
manifest: manifestId,
...(maxHeight !== undefined ? { maxHeight } : {}),
@@ -274,33 +311,7 @@ if (wantAll) {
for (const r of body.refused ?? []) {
EMIT("note", { message: ` ${r.platform}: ${r.items} window(s) not started — ${r.error}` });
}
- // Every job, polled to its end. A job that stopped short (a rate limit, two
- // 403s) fails with the reason; asking again later resumes it, the fetched
- // windows answering from the cache.
- // No deadline: a batch queued behind hours of other work is waited for.
- const pending = new Map(body.jobs.map((j) => [j.jobId, j]));
- for (const jobId of pending.keys()) waitingOn.add(jobId);
- const failed = [];
- const last = new Map();
- const places = new Map();
- while (pending.size > 0) {
- await sleep(QUEUED_POLL_MS);
- for (const [jobId, j] of pending) {
- const p = await pollJob(jobId);
- const label = ` (${j.platform}, ${j.items} window(s))`;
- if (p.status !== last.get(jobId)) {
- last.set(jobId, p.status);
- EMIT("note", { message: ` editor job ${jobId}${label}: ${p.status}` });
- }
- if (p.status === "queued") places.set(jobId, await notePlace(jobId, label, places.get(jobId)));
- if (p.status === "done") pending.delete(jobId);
- else if (p.status === "failed" || p.status === "cancelled") {
- pending.delete(jobId);
- failed.push(`${jobId} ${p.status}: ${String(p.error ?? "").split("\n").slice(-3).join(" / ")}`);
- }
- if (!pending.has(jobId)) waitingOn.delete(jobId);
- }
- }
+ const failed = await waitForJobs(body.jobs);
const unfinished = failed.length + (body.refused?.length ?? 0) + (body.unresolved?.length ?? 0);
if (unfinished > 0) {
die(`not every window was fetched:\n ${[...failed, ...(body.refused ?? []).map((r) => `${r.platform}: ${r.error}`)].join("\n ") || "see the notes above"}`);
@@ -345,6 +356,14 @@ if (!channelSlug) {
const { from, to } = windowOf(entry);
+// THE DIRECTORY ID the corpus keeps this recording under (a Rumble embed id →
+// its URL slug's directory), asked here so the editor is never sent to a
+// data/<embed>/ that does not exist.
+const videoId = await localVideoId({ slug: channelSlug, id: entry.video });
+if (videoId !== entry.video) {
+ EMIT("note", { message: ` ${entry.id}: ${channelSlug}/${entry.video} is the directory ${videoId} here (a Rumble embed id)` });
+}
+
// WHY THESE SECONDS. Stored beside the file so a directory of windows can be
// read back months later. The clip's own note is the closest thing the manifest
// has to a reason; the manifest id and the clip id say the rest.
@@ -360,6 +379,66 @@ EMIT("fetch", {
cached: false,
});
+// A WHOLE-RECORDING PLATFORM'S WINDOW (settings.clips.wholeRecordingPlatforms,
+// default Rumble) is NEVER a remote seek: it is asked of fetch-windows, which
+// saves the whole recording once (on the platform's download queue), makes its
+// clock current and cuts the window from it on the cue clock. The window is
+// then read off this corpus. Nothing here falls back to a seek.
+if (!wantFull && (await isWholeRecording({ slug: channelSlug, webpageUrl: entry.webpageUrl ?? null }))) {
+ const platform = await recordingPlatform({ slug: channelSlug, webpageUrl: entry.webpageUrl ?? null });
+ EMIT("note", {
+ message: ` ${entry.id}: a ${platform} window is cut from the whole recording, never seeked — asking fetch-windows for ${channelSlug}/${videoId}`,
+ });
+ const res = await ask(`${editorUrl}/api/ops/fetch-windows`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ items: [
+ {
+ slug: channelSlug,
+ id: videoId,
+ from,
+ to,
+ clipId: entry.id,
+ pad: Math.max(padBefore, padAfter),
+ reason: String(reason).slice(0, 400),
+ ...(entry.webpageUrl ? { webpageUrl: entry.webpageUrl } : {}),
+ },
+ ],
+ requestedBy: "umtool",
+ manifest: manifestId,
+ ...(maxHeight !== undefined ? { maxHeight } : {}),
+ }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok || !body.ok) die(`the editor refused (HTTP ${res.status}): ${body.error ?? "no reason given"}`);
+ const refusals = [
+ ...(body.unresolved ?? []).map((u) => u.error),
+ ...(body.refused ?? []).map((r) => `${r.platform}: ${r.error}`),
+ ];
+ if (refusals.length) die(`the editor did not start the whole-recording fetch: ${refusals.join(" / ")}`);
+ const jobs = [
+ ...(body.jobs ?? []),
+ ...(body.inFlight ?? []).map((f) => ({ jobId: f.jobId, platform: platform ?? "", items: 1 })),
+ ];
+ for (const j of jobs) EMIT("note", { message: ` queued on the editor as job ${j.jobId} (the whole recording, then the cut)` });
+ const failed = await waitForJobs(jobs);
+ if (failed.length) die(`the whole-recording fetch failed (no seek was tried):\n ${failed.join("\n ")}`);
+ const hit = await resolveLocalSource(
+ { video: videoId, slug: channelSlug, from, to },
+ { channelsDir: corpusChannelsDir(), kinds: ["corpus-window"] },
+ );
+ if (!hit) {
+ die(
+ `fetch-windows finished, but no window holding ${from}–${to} of ${channelSlug}/${videoId} is in ` +
+ `${corpusChannelsDir()} — not seeking; see the editor's /jobs log`,
+ );
+ }
+ EMIT("fetch", { id: entry.id, video: entry.video, from: hit.windowStart, to: hit.windowEnd, cached: true, reuse: hit.name });
+ EMIT("done", { out: hit.path, fetchStart: hit.windowStart, cached: jobs.length === 0 });
+ process.exit(0);
+}
+
const res = await ask(`${editorUrl}/api/media/fetch-window`, {
method: "POST",
headers,
@@ -368,7 +447,7 @@ const res = await ask(`${editorUrl}/api/media/fetch-window`, {
// describe a request the editor does not have.
body: JSON.stringify({
channelSlug,
- videoId: entry.video,
+ videoId,
webpageUrl: entry.webpageUrl ?? undefined,
...(wantFull ? { full: true } : { from, to, pad: Math.max(padBefore, padAfter) }),
...(maxHeight !== undefined ? { maxHeight } : {}),
diff --git a/umtool/report-to-video/fetch-via-editor.test.mjs b/umtool/report-to-video/fetch-via-editor.test.mjs
@@ -291,3 +291,120 @@ test("a window already being fetched (the editor's dedupe) is followed, and says
await ed.close();
}
});
+
+// ONE CLOCK PER RECORDING (lane one-clock): a clip on a whole-recording
+// platform is asked of fetch-windows by its DIRECTORY id (the Rumble embed id
+// the manifest cites → the URL slug's directory), waited for, and read off the
+// corpus — never a /api/media/fetch-window seek.
+async function rumbleCorpus() {
+ const root = await mkdtemp(path.join(os.tmpdir(), "fve-rumble-"));
+ const { mkdir } = await import("node:fs/promises");
+ const videoDir = path.join(root, "channels", "rc", "data", "v7fxp3e");
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(path.join(root, "channels", "rc", "config.json"), JSON.stringify({ platform: "rumble" }));
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id: "v7drc5w", webpage_url: "https://rumble.com/v7fxp3e-x.html" }));
+ return { root, channelsDir: path.join(root, "channels"), videoDir };
+}
+
+async function routedEditor(routes) {
+ const seen = [];
+ const server = http.createServer((req, res) => {
+ let raw = "";
+ req.on("data", (c) => (raw += c));
+ req.on("end", async () => {
+ seen.push({ method: req.method, url: req.url, body: raw ? JSON.parse(raw) : null });
+ const key = Object.keys(routes).find((k) => req.url.startsWith(k));
+ const a = key ? await routes[key](raw ? JSON.parse(raw) : null) : { status: 404, body: { error: "no route" } };
+ res.writeHead(a.status, { "content-type": "application/json" });
+ res.end(JSON.stringify(a.body));
+ });
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const { port } = /** @type {import("node:net").AddressInfo} */ (server.address());
+ return { seen, url: `http://127.0.0.1:${port}`, close: () => new Promise((r) => server.close(r)) };
+}
+
+async function runRumble(editorUrl, channelsDir) {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "fve-m-"));
+ try {
+ const manifest = path.join(dir, "video.manifest.json");
+ await writeFile(
+ manifest,
+ JSON.stringify({ provenance: { manifestId: "d" }, timeline: [{ id: "c43", type: "clip", channel: "rc", video: "v7drc5w", start: 10, end: 20 }] }),
+ );
+ return await new Promise((resolve) => {
+ execFile(
+ process.execPath,
+ [SCRIPT, manifest, "--fetch-only", "c43", "--progress", "ndjson"],
+ {
+ env: {
+ ...process.env,
+ ARCHILYZER_EDITOR_URL: editorUrl,
+ WORKER_TOKEN: "tok",
+ CHANNELS_DIR: channelsDir,
+ SETTINGS_FILE: path.join(dir, "no-settings.json"),
+ FETCH_VIA_EDITOR_POLL_MS: "5",
+ },
+ },
+ (err, stdout) => resolve({ code: err ? err.code : 0, events: stdout.split("\n").filter(Boolean).map((l) => JSON.parse(l)) }),
+ );
+ });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+test("a Rumble clip: fetch-windows by the directory id, then the window off the corpus; no seek", async () => {
+ const c = await rumbleCorpus();
+ const { mkdir } = await import("node:fs/promises");
+ const ed = await routedEditor({
+ "/api/ops/fetch-windows": async () => ({
+ status: 200,
+ body: { ok: true, dryRun: false, jobs: [{ platform: "rumble", queueKey: "platform:rumble", jobId: "j1", items: 1 }], groups: [], refused: [], cached: [], inFlight: [], unresolved: [] },
+ }),
+ "/api/media/fetch-window/j1": async () => {
+ // The job "ran": the editor cut the window on the cue clock.
+ await mkdir(path.join(c.videoDir, "clips"), { recursive: true });
+ await writeFile(path.join(c.videoDir, "clips", "7.00-23.00.mp4"), "mp4");
+ return { status: 200, body: { status: "done" } };
+ },
+ "/api/ops/job/": async () => ({ status: 200, body: { job: {} } }),
+ });
+ try {
+ const { code, events } = await runRumble(ed.url, c.channelsDir);
+ assert.equal(code, 0, JSON.stringify(events));
+ const post = ed.seen.find((s) => s.url === "/api/ops/fetch-windows");
+ assert.equal(post.body.items[0].id, "v7fxp3e");
+ assert.deepEqual([post.body.items[0].from, post.body.items[0].to], [7, 23]);
+ assert.equal(ed.seen.some((s) => s.method === "POST" && s.url === "/api/media/fetch-window"), false, "never a seek");
+ const done = events.find((e) => e.ev === "done");
+ assert.equal(done.out, path.join(c.videoDir, "clips", "7.00-23.00.mp4"));
+ assert.equal(done.fetchStart, 7);
+ assert.ok(events.some((e) => e.ev === "note" && /rc\/v7drc5w is the directory v7fxp3e/.test(e.message)));
+ assert.ok(events.some((e) => e.ev === "note" && /a rumble window is cut from the whole recording, never seeked/.test(e.message)));
+ } finally {
+ await ed.close();
+ await rm(c.root, { recursive: true, force: true });
+ }
+});
+
+test("a Rumble clip whose whole-recording fetch fails: exit 1, and still no seek", async () => {
+ const c = await rumbleCorpus();
+ const ed = await routedEditor({
+ "/api/ops/fetch-windows": async () => ({
+ status: 200,
+ body: { ok: true, dryRun: false, jobs: [{ platform: "rumble", queueKey: "platform:rumble", jobId: "j2", items: 1 }], groups: [], refused: [], cached: [], inFlight: [], unresolved: [] },
+ }),
+ "/api/media/fetch-window/j2": async () => ({ status: 200, body: { status: "failed", error: "the whole recording was not saved: HTTP Error 403" } }),
+ "/api/ops/job/": async () => ({ status: 200, body: { job: {} } }),
+ });
+ try {
+ const { code, events } = await runRumble(ed.url, c.channelsDir);
+ assert.equal(code, 1);
+ assert.ok(events.some((e) => e.ev === "note" && /no seek was tried/.test(e.message) && /403/.test(e.message)));
+ assert.equal(ed.seen.some((s) => s.method === "POST" && s.url === "/api/media/fetch-window"), false);
+ } finally {
+ await ed.close();
+ await rm(c.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -28,6 +28,7 @@
"./reframe": "./reframe.mjs",
"./side-card": "./side-card.mjs",
"./check-availability": "./check-availability.mjs",
+ "./recording-ids": "./recording-ids.mjs",
"./check-joins": "./check-joins.mjs",
"./chunked-encode": "./chunked-encode.mjs",
"./claims": "./claims.mjs",
diff --git a/umtool/report-to-video/recording-ids.mjs b/umtool/report-to-video/recording-ids.mjs
@@ -0,0 +1,126 @@
+// recording-ids — which recording, and how to fetch it (lane one-clock).
+//
+// TWO THINGS umtool's fetch path must decide before it asks the editor:
+//
+// 1. THE DIRECTORY ID. A manifest cites a Rumble clip by its EMBED id (the
+// archive's), while the corpus names the video's directory for the URL
+// slug. Asked by the embed id, the editor looked in a `data/<embed>/` that
+// does not exist: no saved video, no metadata, the URL guessed as the embed
+// page (6 Nov: a 403), persist-videos "unknown". common's resolveVideoDirId
+// maps the two through the channel's metadata (videoDir-server.mjs); this
+// asks it HERE, on the corpus this checkout reads, so every request names
+// the directory — whichever editor build answers.
+//
+// 2. WHOLE OR WINDOW. A clip on a whole-recording platform
+// (settings.clips.wholeRecordingPlatforms, default ["rumble"]) is never a
+// remote seek: it goes through fetch-windows, which saves the whole
+// recording once, measures its clock and cuts the window from it. A remote
+// Rumble seek put the picture 1–4 s off the sound, and the 6 Nov windows
+// played words 13 s away from their cues.
+//
+// Plain ESM for bare node (fetch-via-editor.mjs, lib/report/fetchWindows.mjs).
+
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { readChannelPlatform, resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { detectPlatform } from "yt-dlp-transcript-common/lib/detectPlatform.mjs";
+
+const REPO_ROOT = path.resolve(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)), "..", "..");
+
+/** The default when settings.json says nothing (common/lib/clipSettings.ts DEFAULT_CLIPS_SETTINGS). */
+export const DEFAULT_WHOLE_RECORDING_PLATFORMS = Object.freeze(["rumble"]);
+
+/** The corpus whose directories the ids are resolved in: CHANNELS_DIR, else the checkout's. */
+export function corpusChannelsDir(env = process.env) {
+ return env.CHANNELS_DIR ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "transcripts", "channels");
+}
+
+/**
+ * settings.json's `clips.wholeRecordingPlatforms` (the editor's file: SETTINGS_FILE,
+ * else the checkout's), normalized as clipSettings.ts does; the default when the
+ * file or the key is absent.
+ * @param {string} [file]
+ * @returns {string[]}
+ */
+export function wholeRecordingPlatforms(file = process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json")) {
+ let raw;
+ try {
+ raw = JSON.parse(readFileSync(file, "utf8"))?.clips?.wholeRecordingPlatforms;
+ } catch {
+ raw = undefined;
+ }
+ if (!Array.isArray(raw)) return [...DEFAULT_WHOLE_RECORDING_PLATFORMS];
+ const out = [];
+ for (const p of raw) {
+ const v = String(p ?? "").trim().toLowerCase();
+ if (v && !out.includes(v)) out.push(v);
+ }
+ return out;
+}
+
+/**
+ * The directory id the corpus keeps a cited recording under (a Rumble embed id
+ * → its URL slug's directory); the id itself when the corpus is not here or
+ * names no other.
+ * @param {{ channelsDir?: string, slug: string, id: string }} a
+ */
+export async function localVideoId({ channelsDir = corpusChannelsDir(), slug, id }) {
+ if (!slug || !id) return id;
+ try {
+ return await resolveVideoDirId(channelsDir, slug, String(id));
+ } catch {
+ return id;
+ }
+}
+
+/**
+ * The platform a clip's recording is on: its channel's (config.json, on this
+ * corpus), else its own page URL's host. Null for neither.
+ * @param {{ channelsDir?: string, slug: string, webpageUrl?: string | null }} a
+ */
+export async function recordingPlatform({ channelsDir = corpusChannelsDir(), slug, webpageUrl = null }) {
+ const own = slug ? await readChannelPlatform(channelsDir, slug) : null;
+ if (own) return String(own).toLowerCase();
+ const fromUrl = webpageUrl ? detectPlatform(webpageUrl) : null;
+ return fromUrl ? String(fromUrl).toLowerCase() : null;
+}
+
+/**
+ * Is this clip's recording one whose windows are cut from the whole recording?
+ * @param {{ channelsDir?: string, slug: string, webpageUrl?: string | null, platforms?: string[] }} a
+ */
+export async function isWholeRecording({ channelsDir = corpusChannelsDir(), slug, webpageUrl = null, platforms = wholeRecordingPlatforms() }) {
+ const p = await recordingPlatform({ channelsDir, slug, webpageUrl });
+ return !!p && platforms.includes(p);
+}
+
+/**
+ * fetch-windows items with each `id` resolved to its directory id, and the ids
+ * that changed (`{slug, cited, dir}`, once each) for the log. The editor's
+ * route refuses an unknown item key, so the cited id travels beside, not in.
+ * @template {{ slug: string, id: string }} I
+ * @param {I[]} items
+ * @param {{ channelsDir?: string }} [opts]
+ * @returns {Promise<{ items: I[], mapped: { slug: string, cited: string, dir: string }[] }>}
+ */
+export async function withLocalIds(items, { channelsDir = corpusChannelsDir() } = {}) {
+ const memo = new Map();
+ const out = [];
+ const mapped = [];
+ for (const it of items) {
+ const key = `${it.slug}\u0000${it.id}`;
+ if (!memo.has(key)) {
+ const dir = await localVideoId({ channelsDir, slug: it.slug, id: it.id });
+ memo.set(key, dir);
+ if (dir && dir !== it.id) mapped.push({ slug: it.slug, cited: it.id, dir });
+ }
+ const dirId = memo.get(key);
+ out.push(dirId && dirId !== it.id ? { ...it, id: dirId } : it);
+ }
+ return { items: out, mapped };
+}
+
+/** "the-quartering-rumble/v7drc5w → v7fxp3e, …" */
+export const mappedLine = (mapped) =>
+ mapped.map((m) => `${m.slug}/${m.cited} → ${m.dir}`).join(", ");
diff --git a/umtool/report-to-video/recording-ids.test.mjs b/umtool/report-to-video/recording-ids.test.mjs
@@ -0,0 +1,64 @@
+// recording-ids.mjs (lane one-clock): a cited Rumble embed id is asked for by
+// its directory, and the settings' whole-recording list decides whole or window.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import path from "node:path";
+import os from "node:os";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { isWholeRecording, localVideoId, mappedLine, recordingPlatform, wholeRecordingPlatforms, withLocalIds } from "./recording-ids.mjs";
+
+async function corpus() {
+ const root = await mkdtemp(path.join(os.tmpdir(), "rec-ids-"));
+ const channelsDir = path.join(root, "channels");
+ await mkdir(path.join(channelsDir, "rc", "data", "v7fxp3e"), { recursive: true });
+ await writeFile(path.join(channelsDir, "rc", "config.json"), JSON.stringify({ platform: "rumble" }));
+ await writeFile(path.join(channelsDir, "rc", "data", "v7fxp3e", "metadata.info.json"), JSON.stringify({ id: "v7drc5w" }));
+ await mkdir(path.join(channelsDir, "yt"), { recursive: true });
+ await writeFile(path.join(channelsDir, "yt", "config.json"), JSON.stringify({ url: "https://www.youtube.com/@x" }));
+ return { root, channelsDir };
+}
+
+test("ids: an embed id becomes its directory; items keep everything else; the mapping is said once", async () => {
+ const c = await corpus();
+ try {
+ assert.equal(await localVideoId({ channelsDir: c.channelsDir, slug: "rc", id: "v7drc5w" }), "v7fxp3e");
+ assert.equal(await localVideoId({ channelsDir: c.channelsDir, slug: "rc", id: "v7fxp3e" }), "v7fxp3e");
+ const { items, mapped } = await withLocalIds(
+ [
+ { slug: "rc", id: "v7drc5w", from: 1, to: 2, clipId: "c43" },
+ { slug: "rc", id: "v7drc5w", from: 5, to: 9, clipId: "c44" },
+ { slug: "yt", id: "abcdefghijk", from: 1, to: 2 },
+ ],
+ { channelsDir: c.channelsDir },
+ );
+ assert.deepEqual(items.map((i) => i.id), ["v7fxp3e", "v7fxp3e", "abcdefghijk"]);
+ assert.deepEqual(items[0], { slug: "rc", id: "v7fxp3e", from: 1, to: 2, clipId: "c43" });
+ assert.deepEqual(mapped, [{ slug: "rc", cited: "v7drc5w", dir: "v7fxp3e" }]);
+ assert.equal(mappedLine(mapped), "rc/v7drc5w → v7fxp3e");
+ } finally {
+ await rm(c.root, { recursive: true, force: true });
+ }
+});
+
+test("whole or window: the channel's platform (else the page URL's) against the settings' list", async () => {
+ const c = await corpus();
+ try {
+ const none = path.join(c.root, "missing-settings.json");
+ assert.deepEqual(wholeRecordingPlatforms(none), ["rumble"]);
+ const listed = path.join(c.root, "settings.json");
+ await writeFile(listed, JSON.stringify({ clips: { wholeRecordingPlatforms: ["Rumble", "youtube", "rumble", ""] } }));
+ assert.deepEqual(wholeRecordingPlatforms(listed), ["rumble", "youtube"]);
+ await writeFile(listed, JSON.stringify({ clips: { wholeRecordingPlatforms: [] } }));
+ assert.deepEqual(wholeRecordingPlatforms(listed), []);
+ assert.equal(await recordingPlatform({ channelsDir: c.channelsDir, slug: "rc" }), "rumble");
+ assert.equal(await recordingPlatform({ channelsDir: c.channelsDir, slug: "yt" }), "youtube");
+ assert.equal(await recordingPlatform({ channelsDir: c.channelsDir, slug: "nope", webpageUrl: "https://rumble.com/v1-x.html" }), "rumble");
+ assert.equal(await isWholeRecording({ channelsDir: c.channelsDir, slug: "rc", platforms: ["rumble"] }), true);
+ assert.equal(await isWholeRecording({ channelsDir: c.channelsDir, slug: "yt", platforms: ["rumble"] }), false);
+ assert.equal(await isWholeRecording({ channelsDir: c.channelsDir, slug: "rc", platforms: [] }), false);
+ } finally {
+ await rm(c.root, { recursive: true, force: true });
+ }
+});