import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; import { projectRef } from "@/lib/projects"; import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; import { refuseCaller } from "@/lib/report/caller"; import { EXPORT_KINDS, ExportRefused, contextSeconds, exportNeeds, exportSteps, spanOf } from "@/lib/report/clipExport.mjs"; import { cannotOpen, localRequest } from "@/lib/report/openFolder.mjs"; export const dynamic = "force-dynamic"; // EXPORT ONE CLIP (umtool/docs/knobs.md, "Export one clip"): a clean mp4 of a // clip, no deck chrome, into /exports/ -- as the cut plays it (`cut`: // its edges, its gaps out as jump cuts, its mute), with N s either side // (`context`), or a stretch as recorded (`raw`: the fetched window, or a // `span` -- the full exchange). // // POST { project, clip, take?, kind?: "cut" | "context" | "raw", context?: N, span?: {from, to}, fetch?: true, uncensoredRaw?: true } // (`uncensoredRaw`: a raw export of a clip that hides regions is refused unless asked for as recorded, regions shown) // -> 202 { job } ONE umtool job on the app's runner (lib/jobs.ts: one at a // time, a log, Stop): `fetch: true` asks the editor first for what a // context or raw export needs that is not on disk (the bench's own // fetch-window path), then `umtool export … --progress ndjson`, which // runs in the machine's heavy slot. 409 when a cut's window is not on // disk ("fetch it first"), when a context/raw export needs a fetch and // `fetch` was not asked, or when another job is running. // GET ?job= -> { job, done?: { name, rel, size, seconds, summary, notes, download, canOpen, openWhy? }, error? } // // Names, never paths: a project of the scan, a clip of its cut. const headers = { "cache-control": "no-store" }; export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/clip-export"); if (refused) return refused; const body = (await request.json().catch(() => null)) as Record | null; if (!body || typeof body !== "object") return Response.json({ error: "expected JSON" }, { status: 400, headers }); const project = await projectRef(String(body.project ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); if (!kindMakesTakes(project.kind)) return Response.json({ error: "an export is made of a report video's clip" }, { status: 400, headers }); const clip = String(body.clip ?? ""); if (!clip) return Response.json({ error: "which clip?" }, { status: 400, headers }); const take = typeof body.take === "string" && body.take ? body.take : null; const kind = (body.kind === undefined || body.kind === null || body.kind === "" ? "cut" : String(body.kind)) as "cut" | "context" | "raw"; if (!(EXPORT_KINDS as readonly string[]).includes(kind)) { return Response.json({ error: `kind is one of ${EXPORT_KINDS.join(", ")}` }, { status: 400, headers }); } try { const context = kind === "context" ? contextSeconds(body.context) : undefined; const span = kind === "raw" ? spanOf(body.span) : null; const need = await exportNeeds(project, clip, { take, kind, ...(context !== undefined ? { context } : {}), span }); if (kind === "cut" && !need.held) { throw new ExportRefused(`${clip}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)`, 409); } if (!need.held && body.fetch !== true) { throw new ExportRefused( `${clip}: what this export needs is not on disk (−${need.padBefore} s / +${need.padAfter} s around the clip) — ask again with fetch, which asks the editor first`, 409, ); } const running = runningJob(); if (running) return Response.json({ error: `a job is already running (${running.kind}) — export when it is done`, running: jobView(running) }, { status: 409, headers }); let manifestPath: string | null = null; if (take && !need.held) { // The take's own manifest (a take-only clip, a take's bounds), never the project's under the take's name. const { resolveTakeManifest, writePlayManifest } = await import("@/lib/report/takeManifest.mjs"); manifestPath = await writePlayManifest(project.dir, take, (await resolveTakeManifest(project.dir, take)).manifest); } const steps = await exportSteps(project, clip, { take, kind, ...(context !== undefined ? { context } : {}), span, fetch: need.held ? null : { padBefore: need.padBefore, padAfter: need.padAfter }, manifestPath, uncensoredRaw: kind === "raw" && body.uncensoredRaw === true, }); const job = startJob(`export ${project.id}/${clip}`, steps, { project: project.id }); return Response.json({ ok: true, fetching: !need.held, job: jobView(job) }, { status: 202, headers }); } catch (e) { const status = e instanceof ExportRefused ? e.status : 500; return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); } } export async function GET(request: Request) { const url = new URL(request.url); const id = url.searchParams.get("job"); const job = id ? getJob(id) : null; if (!job) return Response.json({ error: "no such job" }, { status: 404, headers }); const view = jobView(job, Math.max(0, job.log.length - 12)); const ev = [...job.events].reverse().find((e) => e.ev === "export" || e.ev === "export-failed") as Record | undefined; if (ev?.ev === "export" && typeof ev.name === "string" && job.project) { const no = cannotOpen(); const local = localRequest(request.headers); const openWhy = no ?? (local.ok ? null : `Open folder works on the machine umtool runs on: ${local.why}`); return Response.json( { job: view, done: { clip: ev.clip, kind: ev.kind, name: ev.name, rel: ev.rel, size: ev.size, mtimeMs: ev.mtimeMs, seconds: ev.seconds, summary: ev.summary, notes: ev.notes ?? [], download: `/api/report/exports?${new URLSearchParams({ project: job.project, name: ev.name, v: String(ev.mtimeMs ?? "") }).toString()}`, canOpen: !openWhy, ...(openWhy ? { openWhy } : {}), }, }, { headers }, ); } const error = ev?.ev === "export-failed" ? String(ev.error ?? "the export failed") : job.state === "failed" ? (job.error ?? "the export failed") : null; return Response.json({ job: view, ...(error ? { error } : {}) }, { headers }); }