import { readdir, stat } from "node:fs/promises"; import path from "node:path"; import { cardText, excerptErrors, excerptRanges, excerptSpansOf } from "umtool-report-to-video/post-item"; import { pickedTake } from "umtool-report-to-video/post-narration"; import { itemReadRefusals } from "umtool-report-to-video/post-thread"; import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, StructureRefused, manifestToken, updatePostItem } from "@/lib/report/manifest.mjs"; import { attachmentOf } from "@/lib/report/postsCli.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { refuseCaller } from "@/lib/report/caller"; import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; export const dynamic = "force-dynamic"; // A POST ITEM, AS THE INSPECTOR EDITS IT (umtool redesign L6, item 4; 6-8 Nov these were `posts set-item // excerpt=…` and `posts narrate --recording` by hand): the card's words as the excerpt reads them (cardText), // the excerpt's spans and where they stand, the item's attachments and the post's files it does not carry, and // its narration's takes. Its writes are the post bench's: POST /api/report/post-item {op: "set"} (the excerpt, // an attachment off or its sound), the multipart POST /api/report/post-narration (a recording), and here: // // GET ?project=&id= the view above, and the token // POST { project, token, id, op: "media-on", file: "posts-media/…" } a file of the post the item never carried put // on it, measured as `posts set-item media.add=` measures one (refused // when the item carries it, shown or switched off) // POST { project, token, id, op: "media-off", i } attachment i switched OFF, kept whole in `mediaOff` (its crop, // blur, trim, sound kept; nothing draws it) -- `set-item media..shown=off` // POST { project, token, id, op: "media-show", j } the attachment switched off at j shown again, as it was // -- `set-item media-off..shown=on` const noStore = { "cache-control": "no-store" }; const MEDIA_RE = /\.(png|jpe?g|webp|gif|mp4|m4v|mov|webm)$/i; type Entry = Record & { id: string; type?: string; post?: string; media?: Array>; mediaOff?: Array>; narration?: Record }; /** The post's own files in the project (posts-media///), pictures and videos, its screenshots left out. */ async function postFiles(dir: string, e: Entry): Promise { const roots = new Set(); if (typeof e.post === "string" && /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(e.post)) roots.add(`posts-media/${e.post}`); for (const m of [...(e.media ?? []), ...(e.mediaOff ?? [])]) if (typeof m?.src === "string" && m.src.startsWith("posts-media/")) roots.add(path.posix.dirname(m.src)); const out: string[] = []; for (const rel of roots) { if (rel.split("/").includes("..")) continue; const names = await readdir(path.join(dir, ...rel.split("/"))).catch(() => [] as string[]); for (const n of names.sort()) { if (!MEDIA_RE.test(n) || /^shot/i.test(n) || n.startsWith(".")) continue; const st = await stat(path.join(dir, ...rel.split("/"), n)).catch(() => null); if (st?.isFile()) out.push(`${rel}/${n}`); } } return out; } export async function GET(request: Request) { const q = new URL(request.url).searchParams; const r = await resolveReport(q.get("project") ?? ""); if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); const tl = ((r.manifest as { timeline?: Entry[] }).timeline ?? []) as Entry[]; const id = q.get("id") ?? ""; const e = tl.find((x) => x?.type === "post" && x.id === id); if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); const text = cardText(e) as string; const spans = excerptSpansOf(e) as string[] | null; const media = (e.media ?? []).map((m, i) => ({ i, src: typeof m?.src === "string" ? m.src : null, kind: typeof m?.kind === "string" ? m.kind : null, mute: m?.mute === true, seconds: typeof m?.seconds === "number" ? m.seconds : null, audio: m?.audio === true, })); const off = (e.mediaOff ?? []).map((m, j) => ({ j, src: typeof m?.src === "string" ? m.src : null, kind: typeof m?.kind === "string" ? m.kind : null })); const carried = new Set([...media.map((m) => m.src), ...off.map((m) => m.src)]); const takes = Array.isArray(e.narration?.takes) ? (e.narration.takes as Array>) : []; const picked = pickedTake(e) as (Record & { file: string; index: number }) | null; return Response.json( { id: e.id, post: e.post ?? null, author: e.author ?? null, handle: e.handle ?? null, text, excerpt: spans, ranges: spans ? excerptRanges(text, spans) : null, excerptErrors: excerptErrors(e), media, off, files: (await postFiles(r.project.dir, e)).filter((f) => !carried.has(f)), narration: { takes: takes.map((t, i) => ({ i, file: String(t.file ?? ""), engine: typeof t.engine === "string" ? t.engine : null, voice: typeof t.voice === "string" ? t.voice : null, seconds: typeof t.seconds === "number" ? t.seconds : null })), picked: picked ? picked.index : null, off: e.narration?.off === true, // A read the build refuses (post-thread.mjs itemReadRefusals): not played anywhere until it is made again. refused: itemReadRefusals(e) as string[], }, token: await manifestToken(r.project.dir), }, { headers: noStore }, ); } export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/post-item/inspector"); if (refused) return refused; const cross = crossSiteRefusal(request.headers); if (cross) return Response.json({ error: cross }, { status: 403 }); let body: Record; try { body = await request.json(); } catch { return Response.json({ error: "expected JSON" }, { status: 400 }); } const r = await resolveReport(String(body.project ?? "")); if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); if (!["media-on", "media-off", "media-show"].includes(String(body.op))) return Response.json({ error: "op is media-on, media-off or media-show" }, { status: 400 }); const id = String(body.id ?? ""); const tl = ((r.manifest as { timeline?: Entry[] }).timeline ?? []) as Entry[]; const e = tl.find((x) => x?.type === "post" && x.id === id); if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); const token = typeof body.token === "string" ? body.token : null; try { let patch: Record; if (body.op === "media-on") { const file = String(body.file ?? ""); // Only one of the post's own files (the list GET gives): never a path from elsewhere in the project. if (!(await postFiles(r.project.dir, e)).includes(file)) return Response.json({ error: `${file} is not one of ${id}'s post files` }, { status: 400 }); // A file the item carries already -- shown, or switched off with its knobs -- is not added twice. if ([...(e.media ?? []), ...(e.mediaOff ?? [])].some((m) => m?.src === file)) return Response.json({ error: `${id} carries ${file} already (switched off: show it again)` }, { status: 400 }); patch = { mediaAdd: [await attachmentOf(r.project.dir, file)] }; } else if (body.op === "media-off") patch = { mediaHide: [Number(body.i)] }; else patch = { mediaShow: [Number(body.j)] }; const { result, editNotes } = await withEditNotes(r.project, () => updatePostItem(r.project.dir, id, patch, { token })); return Response.json({ ok: true, entry: result.entry, token: result.token, editNotes }, { headers: noStore }); } catch (e2) { if (e2 instanceof StaleToken) return Response.json({ error: e2.message, stale: true }, { status: 409 }); if (e2 instanceof StructureRefused) return Response.json({ error: e2.message, errors: e2.errors }, { status: 400 }); return Response.json({ error: e2 instanceof Error ? e2.message : String(e2) }, { status: 400 }); } }