import { isStoredUrlMode } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import { fetchCitedClip, targetOf } from "@/lib/clips/cited"; import { SourceError } from "@/lib/research/sources"; import { fail, ok } from "../../research/_respond"; export const dynamic = "force-dynamic"; // POST { channel, video, from, to, project?, clip?, reason, report?, storedUrl? } // | { job, channel?, video?, from?, to?, … } (a poll) // -> { state: "ready", cached, play } | { state: "queued", job, status } // | { state: "failed", message, detail?, job? } // // Fetch clip, from the player (lib/clips/cited.ts): the editor's fetch-window // route exactly as fetch_clip asks for it, never yt-dlp, never waiting. A poll // that names its span answers ready with what plays now. export async function POST(request: Request) { try { const b = (await request.json().catch(() => null)) as Record | null; if (!b) throw new SourceError("expected a JSON body"); const target = typeof b.channel === "string" && b.channel ? targetOf((k) => b[k]) : undefined; if (typeof b.job === "string" && b.job.trim()) return ok(await fetchCitedClip({ job: b.job.trim(), ...(target ? { target } : {}) })); if (!target) throw new SourceError("channel, video, from and to are required"); const reason = String(b.reason ?? "").trim().slice(0, 400) || "umtool: play the cited span"; const report = typeof b.report === "string" && b.report.trim() ? b.report.trim() : undefined; // "Cut from the stored media URL" (release 32 R6): the editor's mode, as given. if (b.storedUrl !== undefined && !isStoredUrlMode(b.storedUrl)) throw new SourceError('storedUrl must be "never", "fallback" or "only"'); const storedUrl = isStoredUrlMode(b.storedUrl) && b.storedUrl !== "never" ? b.storedUrl : undefined; return ok(await fetchCitedClip({ target, reason, ...(report ? { report } : {}), ...(storedUrl ? { storedUrl } : {}) })); } catch (e) { return fail(e); } }