NGU-Web/server/src/routes/clips.js
Zaldimmar f934b1dd93 Tidy the structure the audit found
- The colour defaults have one source, server/src/themeDefaults.js,
  read by the server and the admin; the build stops if src/index.css
  disagrees with it
- server/src/admin-schema.js split into admin-schema/, one file per
  entity plus columns.js (the registry checked identical)
- loadOwned() in shape.js replaces the same three loads on four
  detail routes (every public route checked identical); one NO_STORE
- One OrgLogo component for the org lists and the chapter map; an
  organization's own page now shows the same initials as the lists
- One localISO() for the viewer's calendar day, in place of three
- Boot refuses a descriptor dropdown value the table's CHECK doesn't
  allow, instead of it failing on save
- Deleted the unused Other.tsx and white-background logo;
  chapters.ts is useCommunity.ts; isSuper() in the Panel; stale
  comments and docs corrected

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 03:02:21 -05:00

226 lines
8.2 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
VIDEO CLIP ROUTES: mounted under /api/admin, admins and up
GET /clips tools present, and recent jobs
POST /clips/sources { url }: queue a download
POST /clips { source_id, start, end, shape,
focus, format }: queue a clip
GET /clips/:id one job, for polling progress
GET /clips/:id/video a source's video, streamed with
Range support, for the editor
GET /clips/:id/download a finished clip, as an attachment;
its file is deleted once it has
gone out in full, unless saved
POST /clips/:id/save a finished clip into the media
library
DELETE /clips/:id a job and its files (a source
takes its clips)
The work itself is in clips.js. Admins only: this downloads and
encodes video on the VPS, which is heavy, and pulls from sites
outside ours.
═══════════════════════════════════════════════════════════════ */
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { Hono } from "hono";
import { requireAuth, requireRole } from "../auth.js";
import {
ClipError,
checkClip,
checkSourceUrl,
fileOf,
forgetDownloaded,
kick,
removeJob,
saveToLibrary,
toolVersions,
} from "../clips.js";
import { NO_STORE } from "../shape.js";
const clips = new Hono();
clips.use("/clips", requireAuth, requireRole("admin"));
clips.use("/clips/*", requireAuth, requireRole("admin"));
const RECENT = 50;
function shape(job) {
let params = null;
try {
params = job.params ? JSON.parse(job.params) : null;
} catch {
params = null;
}
return {
id: job.id,
kind: job.kind,
status: job.status,
progress: job.progress,
source_url: job.source_url,
source_id: job.source_id,
params,
title: job.title,
duration: job.duration,
bytes: job.bytes,
error: job.error,
has_file: Boolean(job.file),
saved_media_id: job.saved_media_id,
saved_url: job.saved_filename ? `/uploads/${job.saved_filename}` : null,
downloaded_at: job.downloaded_at,
created_at: job.created_at,
finished_at: job.finished_at,
};
}
const SELECT = `SELECT j.*, m.filename AS saved_filename
FROM clip_jobs j
LEFT JOIN media m ON m.id = j.saved_media_id`;
function findOr404(c) {
const id = Number(c.req.param("id"));
const job = Number.isInteger(id) ? c.get("db").prepare(`${SELECT} WHERE j.id = ?`).get(id) : null;
if (!job) throw new ClipError(404, "No such job.");
return job;
}
async function body(c) {
try {
return await c.req.json();
} catch {
throw new ClipError(400, "Expected a JSON body.");
}
}
clips.get("/clips", async (c) => {
const db = c.get("db");
const rows = db.prepare(`${SELECT} ORDER BY j.id DESC LIMIT ${RECENT * 2}`).all();
return c.json(
{
tools: await toolVersions(),
sources: rows.filter((r) => r.kind === "source").slice(0, RECENT).map(shape),
clips: rows.filter((r) => r.kind === "clip").slice(0, RECENT).map(shape),
},
200,
NO_STORE,
);
});
clips.post("/clips/sources", async (c) => {
const db = c.get("db");
const url = checkSourceUrl((await body(c)).url);
const { lastInsertRowid } = db
.prepare(`INSERT INTO clip_jobs (kind, source_url, created_by) VALUES ('source', ?, ?)`)
.run(url, c.get("user").id);
console.log(`clips: download of ${url} queued by ${c.get("user").email}`);
kick(db);
return c.json({ job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(lastInsertRowid)) }, 201, NO_STORE);
});
clips.post("/clips", async (c) => {
const db = c.get("db");
const input = await body(c);
const source = db
.prepare(`SELECT * FROM clip_jobs WHERE id = ? AND kind = 'source'`)
.get(Number(input.source_id));
if (!source) throw new ClipError(404, "No such source.");
if (source.status !== "done" || !source.file) throw new ClipError(409, "That video hasn't finished downloading.");
const params = checkClip(input, source);
const { lastInsertRowid } = db
.prepare(`INSERT INTO clip_jobs (kind, source_id, params, title, created_by) VALUES ('clip', ?, ?, ?, ?)`)
.run(source.id, JSON.stringify(params), source.title, c.get("user").id);
kick(db);
return c.json({ job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(lastInsertRowid)) }, 201, NO_STORE);
});
clips.get("/clips/:id", (c) => c.json({ job: shape(findOr404(c)) }, 200, NO_STORE));
/* A byte range of a file, or all of it: what <video> needs to seek. */
async function streamFile(c, file, { type, attachment, onComplete } = {}) {
const { size } = await stat(file);
const range = c.req.header("range")?.match(/^bytes=(\d*)-(\d*)$/);
let start = 0;
let end = size - 1;
let status = 200;
if (range && !attachment) {
start = range[1] ? Number(range[1]) : Math.max(0, size - Number(range[2]));
end = range[1] && range[2] ? Math.min(Number(range[2]), size - 1) : size - 1;
if (start > end || start >= size) {
return c.body(null, 416, { "Content-Range": `bytes */${size}` });
}
status = 206;
}
const stream = createReadStream(file, { start, end });
if (onComplete) stream.on("end", onComplete);
const headers = {
"Content-Type": type,
"Content-Length": String(end - start + 1),
"Accept-Ranges": "bytes",
"Cache-Control": "no-store",
};
if (status === 206) headers["Content-Range"] = `bytes ${start}-${end}/${size}`;
if (attachment) headers["Content-Disposition"] = `attachment; filename="${attachment}"`;
return c.body(Readable.toWeb(stream), status, headers);
}
clips.get("/clips/:id/video", async (c) => {
const job = findOr404(c);
const file = fileOf(job);
if (!file) throw new ClipError(410, "That video's file is gone.");
return streamFile(c, file, { type: "video/mp4" });
});
clips.get("/clips/:id/download", async (c) => {
const db = c.get("db");
const job = findOr404(c);
if (job.kind !== "clip") throw new ClipError(400, "Only clips are downloaded.");
const file = fileOf(job);
if (!file) {
throw new ClipError(410, job.saved_filename ? "It's in the media library now." : "That clip's file is gone. Make it again.");
}
const audio = job.file.endsWith(".mp3");
const stem = (job.title ?? "clip").replace(/[^\w\- ]+/g, "").trim().slice(0, 60) || "clip";
return streamFile(c, file, {
type: audio ? "audio/mpeg" : "video/mp4",
attachment: `${stem}-${job.id}.${audio ? "mp3" : "mp4"}`,
// Only once the whole file has been read out: a cancelled
// download keeps it for another try.
onComplete: () =>
forgetDownloaded(db, job).catch((err) => console.warn(`clips: couldn't delete ${job.file}: ${err.message}`)),
});
});
clips.post("/clips/:id/save", async (c) => {
const db = c.get("db");
const job = findOr404(c);
if (job.kind !== "clip" || job.status !== "done") throw new ClipError(400, "Only a finished clip can be saved.");
if (job.saved_media_id) throw new ClipError(409, "It's already in the media library.");
const media = await saveToLibrary(db, job, c.get("user").id);
console.log(`clips: clip ${job.id} saved to the library by ${c.get("user").email}`);
return c.json({ media, job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(job.id)) }, 200, NO_STORE);
});
clips.delete("/clips/:id", async (c) => {
const job = findOr404(c);
if (job.status === "running") throw new ClipError(409, "It's running. Wait for it to finish.");
await removeJob(c.get("db"), job);
return c.body(null, 204);
});
clips.onError((err, c) => {
if (err instanceof ClipError) return c.json({ error: err.message }, err.status, NO_STORE);
console.error(err);
return c.json({ error: "Something went wrong." }, 500);
});
export default clips;