NGU-Web/server/src/routes/clips.js
Zaldimmar 06a0e07a79 Let a downloaded video be saved whole, before or without cutting
Save to library and Save to Drive on a finished download, not only on
clips. The download stays on the server to cut clips from either way;
a clip's library save still clears its working file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:14:26 -05:00

287 lines
12 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, or a whole
downloaded video, into the media
library
POST /clips/:id/drive { folder }: a finished clip (or a
whole downloaded video) into a
folder under Media in Drive, as a
Files entry (routes/files.js)
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 path from "node:path";
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";
import { UPLOADS_DIR } from "../media.js";
import { driveDelete, driveReady, driveShareWithAnyone, driveUploadFile } from "../googleService.js";
import { cleanFolder, inDrive, recordDriveUpload } from "./files.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,
saved_drive: job.saved_drive_file_id
? { id: job.saved_drive_file_id, url: job.saved_drive_url, folder: job.saved_drive_folder }
: 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, d.url AS saved_drive_url, d.folder AS saved_drive_folder
FROM clip_jobs j
LEFT JOIN media m ON m.id = j.saved_media_id
LEFT JOIN drive_files d ON d.id = j.saved_drive_file_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.status !== "done") throw new ClipError(400, "Only a finished download or clip can be saved.");
if (job.saved_media_id) throw new ClipError(409, "It's already in the media library.");
if (!job.file) throw new ClipError(410, "Its file is gone from the server.");
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);
});
/* Into Drive: the working file, or once it's gone into the library,
the library's copy. It stays wherever it was, so a clip can be in
both, and the day's sweep still clears the working file. */
clips.post("/clips/:id/drive", async (c) => {
const db = c.get("db");
const job = findOr404(c);
if (job.status !== "done") throw new ClipError(400, "Only a finished download or clip can be saved.");
if (job.saved_drive_file_id) throw new ClipError(409, "It's already in Drive.");
if (!driveReady()) throw new ClipError(400, "Google Drive isn't set up on the server (docs/google-drive-and-mail.md).");
const folder = cleanFolder((await body(c)).folder);
if (folder === null) throw new ClipError(422, "That isn't a folder name.");
const from = fileOf(job) ?? (job.saved_filename ? path.join(UPLOADS_DIR, job.saved_filename) : null);
if (!from) throw new ClipError(410, "That clip's file is gone. Make it again.");
const audio = from.endsWith(".mp3");
const mime = audio ? "audio/mpeg" : "video/mp4";
const params = job.params ? JSON.parse(job.params) : {};
const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
const title = (job.title ?? "").replace(/[\u0000-\u001f"\\/]+/g, " ").trim().slice(0, 120);
const name =
job.kind === "source"
? `${title || "Video"}.mp4`
: `${title || "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)}).${audio ? "mp3" : "mp4"}`;
let uploaded;
try {
uploaded = await driveUploadFile(inDrive(folder), name, mime, from);
} catch (err) {
console.warn(`clips: clip ${job.id} to Drive failed: ${err.message}`);
throw new ClipError(502, `Google Drive didn't take it: ${err.message}`);
}
try {
await driveShareWithAnyone(uploaded.id);
} catch (err) {
await driveDelete(uploaded.id).catch(() => {});
throw new ClipError(
502,
`Drive wouldn't share it with anyone who has the link (${err.message}). The sharing settings must allow sharing outside the organization.`,
);
}
const { size } = await stat(from);
const file = await recordDriveUpload(db, uploaded, { name, mime, bytes: size, folder, userId: c.get("user").id });
db.prepare(`UPDATE clip_jobs SET saved_drive_file_id = ? WHERE id = ?`).run(file.id, job.id);
console.log(`clips: clip ${job.id} saved to Drive (${inDrive(folder)}) by ${c.get("user").email}`);
return c.json({ file, 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;