// The editor's fetch-windows door, stubbed (release 35 O1, montage-ops.spec.ts). // // POST /api/ops/fetch-windows {items, requestedBy, manifest?, storedUrl?, dryRun?} // dryRun -> {ok, dryRun: true, groups: [{platform, queueKey, items}], cached, inFlight, unresolved} // else -> {ok, dryRun: false, groups, cached, inFlight, unresolved, refused, jobs: [{platform, // queueKey, jobId, items}], jobIds}: one job per platform // GET /api/ops/job/ queued, then running, then done (or failed when a window failed) // GET /api/jobs//log the job's log (ungated, as the editor's is): one line per window, // ` ✗ / – (): network — … 403 …` for a refused one // // Only the montage-ops fixture's channels are served (FETCH_WINDOWS_CHANNELS); any other body is a 404. // A window already on disk (//data//clips/-.mp4, or one that holds // it) is cached. A video id starting `vrefuse` is the Rumble embed lookup answering 403: its window // fails. Every other window is written (a real mp4, the stub's writeWindow) when its job finishes. // The platform is the record's (transcript.cues.json), else rumble for a slug with "rumble" in it. import { existsSync, readdirSync, readFileSync } from "node:fs"; import path from "node:path"; // THE CHANNELS THIS DOOR SERVES: the montage-ops fixture's own. Any other // body is answered as an editor without the route (404), as before release 35: // the fixture corpus is shared, and a window written into another spec's // channel (testchan/vid1's clips/, the chain's windows step) changes what that // spec's cache lookup finds — specs must stay order-independent. And the // article chain's `windows` step relies on that 404 to stop (article-iterations.spec). // basicyt: the quick-clip job's recording (basic-mode-fixture.mjs), a channel of its own for the same reason. // railchan: the ingredient rail's recording (ingredient-rail-fixture.mjs), which no other spec reads. export const FETCH_WINDOWS_CHANNELS = new Set(["opsrumble", "opsyt", "basicyt", "railchan"]); const fwJobs = new Map(); let next = 1; function platformOf(channels, slug, id) { try { const p = JSON.parse(readFileSync(path.join(channels, slug, "data", id, "transcript.cues.json"), "utf8")).platform; if (p) return String(p); } catch {} return slug.includes("rumble") ? "rumble" : "youtube"; } function onDisk(channels, it) { const dir = path.join(channels, it.slug, "data", it.id, "clips"); if (!existsSync(dir)) return false; return readdirSync(dir).some((n) => { const m = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)\.mp4$/.exec(n); return m && Number(m[1]) <= it.from + 0.02 && Number(m[2]) >= it.to - 0.02; }); } const label = (it) => `${it.slug}/${it.id} ${it.from.toFixed(2)}–${it.to.toFixed(2)}${it.clipId ? ` (${it.clipId})` : ""}`; /** * @returns {boolean} whether it answered */ export function fetchWindowsRoute(req, res, url, { channels, json, readBody, writeWindow, record }) { if (req.method === "POST" && url.pathname === "/api/ops/fetch-windows") { readBody(req, (body) => { record({ route: "fetch-windows", ...(body ?? {}) }); if (Array.isArray(body?.items) && body.items.some((it) => !FETCH_WINDOWS_CHANNELS.has(String(it?.slug)))) { return json(res, 404, { ok: false, error: "not found" }); } if (!body?.requestedBy || !Array.isArray(body.items) || !body.items.length) return json(res, 400, { ok: false, error: "items and requestedBy are required" }); const cached = []; const groups = new Map(); for (const it of body.items) { if (onDisk(channels, it)) { cached.push(it); continue; } const platform = platformOf(channels, it.slug, it.id); if (!groups.has(platform)) groups.set(platform, { platform, queueKey: `clips:${platform}`, items: [] }); groups.get(platform).items.push(it); } const base = { groups: [...groups.values()], cached, inFlight: [], unresolved: [] }; if (body.dryRun) return json(res, 200, { ok: true, dryRun: true, ...base }); const jobs = base.groups.map((g) => { const jobId = `stub-fw-${next++}`; fwJobs.set(jobId, { id: jobId, platform: g.platform, items: g.items, status: "queued", polls: 0, log: [`Fetch windows: ${g.items.length} window(s) for ${body.requestedBy}${body.manifest ? ` · ${body.manifest}` : ""}`] }); return { platform: g.platform, queueKey: g.queueKey, jobId, items: g.items.length }; }); return json(res, 200, { ok: true, dryRun: false, ...base, refused: [], jobs, jobIds: jobs.map((j) => j.jobId), ...(jobs.length === 1 ? { jobId: jobs[0].jobId } : {}) }); }); return true; } const status = /^\/api\/ops\/job\/([^/]+)$/.exec(url.pathname); if (req.method === "GET" && status && fwJobs.has(status[1])) { req.resume(); const j = fwJobs.get(status[1]); j.polls += 1; if (j.polls === 1) j.status = "running"; else if (j.status === "running") finish(j, channels, writeWindow); return json(res, 200, { ok: true, job: { id: j.id, kind: "fetch-windows", status: j.status, ...(j.status === "running" ? { progress: { done: 0, total: j.items.length } } : {}) } }), true; } const log = /^\/api\/jobs\/([^/]+)\/log$/.exec(url.pathname); if (req.method === "GET" && log && fwJobs.has(log[1])) { req.resume(); const j = fwJobs.get(log[1]); const content = j.log.join("\n") + "\n"; return json(res, 200, { content, nextOffset: content.length, status: j.status === "running" || j.status === "queued" ? j.status : "archived" }), true; } return false; } function finish(j, channels, writeWindow) { let failed = 0; for (const it of j.items) { if (String(it.id).startsWith("vrefuse")) { failed += 1; j.log.push(` ✗ ${label(it)}: network — ERROR: [Rumble] ${it.id}: Unable to download JSON metadata: HTTP Error 403: Forbidden`); continue; } writeWindow(path.join(channels, it.slug, "data", it.id, "clips"), `${it.from.toFixed(2)}-${it.to.toFixed(2)}.mp4`, Math.max(1, Math.round(it.to - it.from))); j.log.push(` ↓ ${label(it)}: fetched`); } j.log.push(`Fetch windows: ${j.items.length - failed} fetched, 0 cached, ${failed} failed.`); j.status = failed ? "failed" : "done"; }