Video clip tool (v1.8.3-video-mgmt) #13

Merged
ngu-git-admin merged 7 commits from feature-tools into main 2026-09-29 03:38:40 +01:00
14 changed files with 1548 additions and 18 deletions

1
.gitignore vendored
View file

@ -24,3 +24,4 @@ Thumbs.db
.txt .txt
# uploaded media (local dev) # uploaded media (local dev)
server/uploads/ server/uploads/
server/clips/

View file

@ -33,6 +33,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Never run commands against the production server or database unless explicitly asked. - Never run commands against the production server or database unless explicitly asked.
- Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`.
- Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`. - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`.
- Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`.
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Only existing accounts (made by admin-cli) get in; passwords still work. Setup: `docs/google-sign-in.md`. - Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Only existing accounts (made by admin-cli) get in; passwords still work. Setup: `docs/google-sign-in.md`.
## Git workflow ## Git workflow

97
docs/video-clips.md Normal file
View file

@ -0,0 +1,97 @@
# Video clips
Admin → Tools → Video clips (admins and up). Paste one of our YouTube or
Facebook links; the server downloads it, then you cut clips from it:
- **Trim**: set the start and end while watching, or type them (`1:23.5`).
- **Shape**: as filmed, landscape 16:9 (1920×1080), square (1080×1080) or
vertical 9:16 (1080×1920, for Reels, Shorts and TikTok). A slider moves
the crop; the white box over the video shows what's kept.
- **Format**: video (MP4, H.264 and AAC) or audio only (MP3).
Clips queue and run one at a time. A finished clip is deleted from the
server once it's downloaded, unless **Save to library** is pressed first,
which puts it in the media library as an upload (usable as a featured
video or in a video block). Everything is cleared a day after it's made.
Only YouTube and Facebook links are accepted, and only for videos NGU owns
or has permission to use. Sources can be up to 4 hours and 4 GB; clips up
to an hour. Limits are constants at the top of `server/src/clips.js`.
## Server setup
1. **ffmpeg** (with ffprobe):
```sh
sudo apt install ffmpeg
```
2. **yt-dlp**: the standalone binary, kept current (YouTube changes often,
and an old yt-dlp is the usual reason downloads start failing):
```sh
sudo curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux -o /usr/local/bin/yt-dlp
sudo chmod a+rx /usr/local/bin/yt-dlp
sudo yt-dlp -U # to update later
```
YouTube needs a JavaScript runtime to list formats; the tool hands
yt-dlp the Node that runs the API, so nothing else is needed.
3. **A working folder** the service can write, and the settings on the
`ngu-api` unit (`systemctl edit ngu-api`):
```sh
sudo mkdir -p /var/lib/ngu/clips
sudo chown <ngu-api user>: /var/lib/ngu/clips
```
```ini
[Service]
Environment=CLIPS_DIR=/var/lib/ngu/clips
# Only if they aren't on the service's PATH:
# Environment=YTDLP_PATH=/usr/local/bin/yt-dlp
# Environment=FFMPEG_PATH=/usr/bin/ffmpeg
# Environment=FFPROBE_PATH=/usr/bin/ffprobe
```
A source can be several GB, so leave room on that disk.
**If YouTube says "Sign in to confirm you're not a bot"**, it's
refusing the VPS's address, and yt-dlp needs a signed-in account's
cookies. Use a separate Google account made for this, never a
personal one: whoever has the cookies is signed in as it. Then set
one of:
```ini
# A cookies.txt exported from a browser signed in to that account
# (a "Get cookies.txt" browser extension, Netscape format). Keep it
# readable only by the service: chmod 600, owned by its user.
Environment=YTDLP_COOKIES=/var/lib/ngu/youtube-cookies.txt
# Or: read them from a browser installed and signed in on the VPS
# itself, as yt-dlp's --cookies-from-browser takes it.
# Environment=YTDLP_COOKIES_FROM_BROWSER=firefox
```
The file is copied for each download, so yt-dlp never rewrites the
original. Cookies expire; when downloads start failing again, export
a fresh file.
4. **nginx**: the editor's video and clip downloads are big streams. Give
them their own block so nginx passes them straight through:
```nginx
location /api/admin/clips/ {
proxy_pass http://127.0.0.1:3001;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
proxy_read_timeout 300s;
}
```
The Video clips page says if yt-dlp or ffmpeg is missing.

594
server/src/clips.js Normal file
View file

@ -0,0 +1,594 @@
/* ═══════════════════════════════════════════════════════════════
VIDEO CLIPS
The work behind Tools → Video clips: download one of our videos
from YouTube or Facebook with yt-dlp, then cut clips from it with
ffmpeg. routes/clips.js is the HTTP around this.
── Configuration (the ngu-api service environment) ──
CLIPS_DIR working files, default ./clips; production
/var/lib/ngu/clips. Temporary: see Cleanup.
YTDLP_PATH default "yt-dlp" on the PATH
FFMPEG_PATH default "ffmpeg"
FFPROBE_PATH default "ffprobe"
When YouTube asks the server to "sign in to confirm you're not a
bot", yt-dlp needs a signed-in account's cookies. One of:
YTDLP_COOKIES a cookies.txt exported from a browser
(Netscape format). Copied per download,
so yt-dlp never writes to the original
YTDLP_COOKIES_FROM_BROWSER a browser on this machine to read them
from, as yt-dlp's --cookies-from-browser
takes it: "firefox", "chrome", or
"firefox:/path/to/profile"
Use a separate Google account, not a personal one: the cookies
are that account's sign-in. If both are set, the file wins.
── Safety ──
Only links on YouTube and Facebook are accepted (SOURCE_HOSTS),
so yt-dlp can't be pointed at anything else, internal addresses
included. Both tools are started with an argument list, never a
shell, so nothing typed can become a command. A source may be at
most MAX_SOURCE_SECONDS long and MAX_SOURCE_SIZE big; a clip at
most MAX_CLIP_SECONDS.
── The queue ──
One job at a time, oldest queued first: video work is heavy for
the VPS, and two at once would only make both slow. A job left
running by a restart is marked failed when the server starts.
── Cleanup ──
A clip's file is deleted as soon as it has been downloaded in
full, unless it was saved to the media library first (then it
lives in the uploads directory like any upload). Every job older
than KEEP_HOURS is deleted with its file, and so is any file in
CLIPS_DIR that no job names.
═══════════════════════════════════════════════════════════════ */
import { spawn } from "node:child_process";
import { randomBytes } from "node:crypto";
import { access, constants, copyFile, mkdir, readdir, rm, stat } from "node:fs/promises";
import path from "node:path";
import { UPLOADS_DIR, PUBLIC_PREFIX } from "./media.js";
export const CLIPS_DIR = path.resolve(process.env.CLIPS_DIR ?? "./clips");
const YTDLP = process.env.YTDLP_PATH ?? "yt-dlp";
const FFMPEG = process.env.FFMPEG_PATH ?? "ffmpeg";
const FFPROBE = process.env.FFPROBE_PATH ?? "ffprobe";
const COOKIES_FILE = process.env.YTDLP_COOKIES || null;
const COOKIES_FROM_BROWSER = process.env.YTDLP_COOKIES_FROM_BROWSER || null;
const MAX_SOURCE_SECONDS = 4 * 60 * 60;
const MAX_SOURCE_SIZE = "4G";
const MAX_CLIP_SECONDS = 60 * 60;
const KEEP_HOURS = 24;
const SWEEP_EVERY_MS = 60 * 60 * 1000;
/* The longest side of a finished video. 1920 covers 1080p landscape
and 1080 × 1920 vertical. */
const MAX_EDGE = 1920;
export const SOURCE_HOSTS = [
"youtube.com",
"www.youtube.com",
"m.youtube.com",
"youtu.be",
"facebook.com",
"www.facebook.com",
"m.facebook.com",
"web.facebook.com",
"fb.watch",
];
/* Output shapes: the aspect a clip is cropped to and the size it's
delivered at, the sizes Instagram, TikTok and YouTube ask for. A
crop from a smaller source is scaled up to it. Original keeps the
source's shape, at most MAX_EDGE on its longer side. */
export const SHAPES = {
original: null,
landscape: { aspect: 16 / 9, width: 1920, height: 1080 },
square: { aspect: 1, width: 1080, height: 1080 },
vertical: { aspect: 9 / 16, width: 1080, height: 1920 },
};
export const FORMATS = ["video", "audio"];
export class ClipError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
/* ── Checking input ────────────────────────────────────────── */
export function checkSourceUrl(raw) {
let url;
try {
url = new URL(String(raw ?? "").trim());
} catch {
throw new ClipError(400, "That isn't a link.");
}
if (url.protocol !== "https:" && url.protocol !== "http:") {
throw new ClipError(400, "Only web links can be downloaded.");
}
if (!SOURCE_HOSTS.includes(url.hostname.toLowerCase())) {
throw new ClipError(400, "Only YouTube and Facebook links can be downloaded.");
}
url.protocol = "https:";
return url.toString();
}
/* A clip request, checked against its source. Times are seconds. */
export function checkClip(input, source) {
const start = Number(input.start);
const end = Number(input.end);
const focus = input.focus == null ? 0.5 : Number(input.focus);
const shape = String(input.shape ?? "original");
const format = String(input.format ?? "video");
if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || end <= start) {
throw new ClipError(400, "Pick a start before the end.");
}
if (source.duration && end > source.duration + 0.5) {
throw new ClipError(400, "The end is past the end of the video.");
}
if (end - start > MAX_CLIP_SECONDS) {
throw new ClipError(400, `A clip can be at most ${MAX_CLIP_SECONDS / 60} minutes long.`);
}
if (!(shape in SHAPES)) throw new ClipError(400, "Unknown shape.");
if (!FORMATS.includes(format)) throw new ClipError(400, "Unknown format.");
if (!Number.isFinite(focus) || focus < 0 || focus > 1) throw new ClipError(400, "Bad focus.");
return { start, end: Math.min(end, source.duration ?? end), shape, format, focus };
}
/* ── Running the tools ─────────────────────────────────────── */
/* Runs a tool, calling onLine for each line of its output, and
resolves with the tail of stderr, or rejects with it. */
function run(command, args, { onLine } = {}) {
return new Promise((resolve, reject) => {
let child;
try {
child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
} catch (err) {
reject(err);
return;
}
let tail = "";
let buffered = "";
child.stdout.on("data", (chunk) => {
buffered += chunk.toString();
const lines = buffered.split(/\r?\n|\r/);
buffered = lines.pop() ?? "";
for (const line of lines) onLine?.(line);
});
child.stderr.on("data", (chunk) => {
tail = (tail + chunk.toString()).slice(-4000);
if (onLine) for (const line of chunk.toString().split(/\r?\n|\r/)) onLine(line);
});
child.on("error", (err) =>
reject(
err.code === "ENOENT"
? new ClipError(503, `${path.basename(command)} isn't installed on the server.`)
: err,
),
);
child.on("close", (code) => {
if (buffered) onLine?.(buffered);
if (code === 0) resolve(tail);
else reject(new Error(lastError(tail) || `${path.basename(command)} exited with ${code}`));
});
});
}
/* The most useful line of a tool's error output. */
function lastError(text) {
const lines = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
return (lines.reverse().find((l) => /error/i.test(l)) ?? lines[0] ?? "").slice(0, 300);
}
/* Width, height and duration of a media file. */
async function probe(file) {
let out = "";
await run(
FFPROBE,
["-v", "error", "-show_entries", "stream=width,height:format=duration", "-of", "json", file],
{ onLine: (line) => (out += line) },
);
const info = JSON.parse(out || "{}");
const video = (info.streams ?? []).find((s) => s.width);
return {
width: video?.width ?? null,
height: video?.height ?? null,
duration: Number(info.format?.duration) || null,
};
}
let toolsCache = null;
/* Which tools are there, and their versions, for the page to say
what's missing before anyone tries. */
export async function toolVersions() {
if (toolsCache) return toolsCache;
const version = async (command, args, pattern) => {
let first = "";
try {
await run(command, args, { onLine: (line) => (first ||= line) });
return first.match(pattern)?.[1] ?? first.slice(0, 40);
} catch {
return null;
}
};
toolsCache = {
ytdlp: await version(YTDLP, ["--version"], /^(\S+)/),
ffmpeg: await version(FFMPEG, ["-version"], /version (\S+)/),
};
// Look again in a while, in case someone installs one.
setTimeout(() => (toolsCache = null), 5 * 60 * 1000).unref?.();
return toolsCache;
}
/* ── Jobs ──────────────────────────────────────────────────── */
const filePath = (name) => path.join(CLIPS_DIR, path.basename(name));
function update(db, id, fields) {
const keys = Object.keys(fields);
db.prepare(`UPDATE clip_jobs SET ${keys.map((k) => `${k} = ?`).join(", ")} WHERE id = ?`).run(
...keys.map((k) => fields[k]),
id,
);
}
/* yt-dlp's cookie options, from the environment. A cookies file is
copied first: yt-dlp saves updated cookies back to the file it's
given, and the original may be read-only to the service. */
async function cookieArgs(jobId) {
if (COOKIES_FILE) {
const copy = path.join(CLIPS_DIR, `.cookies-${jobId}.txt`);
// Two steps, so a failure names the right one: reading the
// original, or writing the copy into CLIPS_DIR.
try {
await access(COOKIES_FILE, constants.R_OK);
} catch (err) {
const why =
err.code === "ENOENT"
? "it isn't there"
: err.code === "EACCES"
? "the service's user isn't allowed to read it (check its owner and permissions)"
: err.code;
throw new Error(`Couldn't read the cookies file at ${COOKIES_FILE} (YTDLP_COOKIES): ${why}.`);
}
try {
await copyFile(COOKIES_FILE, copy);
} catch (err) {
const why =
err.code === "EACCES" || err.code === "EPERM"
? "the service's user isn't allowed to write there"
: err.code;
throw new Error(`Couldn't copy the cookies file into ${CLIPS_DIR} (CLIPS_DIR): ${why}.`);
}
return { args: ["--cookies", copy], cleanup: () => rm(copy, { force: true }) };
}
if (COOKIES_FROM_BROWSER) {
return { args: ["--cookies-from-browser", COOKIES_FROM_BROWSER], cleanup: async () => {} };
}
return { args: [], cleanup: async () => {} };
}
async function download(db, job) {
const template = path.join(CLIPS_DIR, `source-${job.id}.%(ext)s`);
let file = null;
let title = null;
const cookies = await cookieArgs(job.id);
try {
await run(
YTDLP,
[
...cookies.args,
job.source_url,
// YouTube needs a JavaScript runtime to list formats; the one
// running this server will do.
"--js-runtimes",
`node:${process.execPath}`,
"--no-playlist",
"--no-simulate",
"--newline",
"--progress",
"--progress-template",
"download:PROGRESS %(progress._percent_str)s",
"--print",
"before_dl:TITLE %(title)s",
"--print",
"after_move:FILE %(filepath)s",
"-f",
"bv*[height<=1080][ext=mp4]+ba[ext=m4a]/b[height<=1080][ext=mp4]/bv*[height<=1080]+ba/b",
"--merge-output-format",
"mp4",
"--max-filesize",
MAX_SOURCE_SIZE,
"--match-filter",
`duration <= ${MAX_SOURCE_SECONDS}`,
// Only when a path is configured: on the PATH, yt-dlp finds it.
...(process.env.FFMPEG_PATH ? ["--ffmpeg-location", process.env.FFMPEG_PATH] : []),
"-o",
template,
],
{
onLine: (line) => {
const percent = line.match(/^PROGRESS\s+([\d.]+)%/);
if (percent) update(db, job.id, { progress: Math.min(0.99, Number(percent[1]) / 100) });
const t = line.match(/^TITLE (.+)$/);
if (t) title = t[1].slice(0, 300);
const f = line.match(/^FILE (.+)$/);
if (f) file = f[1].trim();
},
},
);
} finally {
await cookies.cleanup();
}
if (!file) throw new Error("The video couldn't be downloaded. It may be private, too long, or too big.");
const info = await probe(file);
const { size } = await stat(file);
update(db, job.id, {
file: path.basename(file),
bytes: size,
title,
duration: info.duration,
});
}
async function cut(db, job) {
const source = db.prepare(`SELECT * FROM clip_jobs WHERE id = ?`).get(job.source_id);
if (!source?.file) throw new Error("Its source video is gone.");
const params = JSON.parse(job.params);
const input = filePath(source.file);
const length = params.end - params.start;
const audio = params.format === "audio";
const name = `clip-${job.id}.${audio ? "mp3" : "mp4"}`;
const args = ["-hide_banner", "-y", "-ss", String(params.start), "-i", input, "-t", String(length)];
if (audio) {
args.push("-vn", "-c:a", "libmp3lame", "-b:a", "192k");
} else {
const filters = [];
const target = SHAPES[params.shape];
const aspect = target?.aspect;
if (aspect) {
const { width, height } = await probe(input);
if (width && height) {
// Crop the source to the shape. The focus is where along the
// cropped direction the frame is centred (0 left/top, 1
// right/bottom); even sizes, as the H.264 encoder needs.
let w = width;
let h = height;
let x = 0;
let y = 0;
if (width / height > aspect) {
w = Math.floor((height * aspect) / 2) * 2;
x = Math.round(Math.min(Math.max(params.focus * width - w / 2, 0), width - w));
} else {
h = Math.floor(width / aspect / 2) * 2;
y = Math.round(Math.min(Math.max(params.focus * height - h / 2, 0), height - h));
}
filters.push(`crop=${w}:${h}:${x}:${y}`);
}
}
filters.push(
target
? `scale=${target.width}:${target.height},setsar=1`
: `scale='if(gte(iw,ih),min(${MAX_EDGE},iw),-2)':'if(gte(iw,ih),-2,min(${MAX_EDGE},ih))'`,
);
args.push(
"-vf",
filters.join(","),
"-c:v",
"libx264",
"-preset",
"veryfast",
"-crf",
"21",
"-pix_fmt",
"yuv420p",
"-c:a",
"aac",
"-b:a",
"160k",
"-movflags",
"+faststart",
);
}
args.push("-progress", "pipe:1", "-nostats", filePath(name));
await run(FFMPEG, args, {
onLine: (line) => {
const us = line.match(/^out_time_us=(\d+)/);
if (us) update(db, job.id, { progress: Math.min(0.99, Number(us[1]) / 1e6 / length) });
},
});
const { size } = await stat(filePath(name));
update(db, job.id, {
file: name,
bytes: size,
title: source.title,
duration: length,
});
}
let running = false;
let dbRef = null;
/* Start the next queued job if nothing is running. Called after a
job is queued and after one finishes. */
export function kick(db = dbRef) {
if (running || !db) return;
const job = db.prepare(`SELECT * FROM clip_jobs WHERE status = 'queued' ORDER BY id LIMIT 1`).get();
if (!job) return;
running = true;
update(db, job.id, { status: "running", progress: 0 });
(async () => {
try {
await mkdir(CLIPS_DIR, { recursive: true }).catch((err) => {
throw new Error(
`Couldn't use the working folder ${CLIPS_DIR} (CLIPS_DIR): ${
err.code === "EACCES" || err.code === "EPERM" ? "the service's user isn't allowed to write there" : err.code
}.`,
);
});
if (job.kind === "source") await download(db, job);
else await cut(db, job);
update(db, job.id, { status: "done", progress: 1, finished_at: new Date().toISOString() });
console.log(`clips: job ${job.id} (${job.kind}) done`);
} catch (err) {
console.warn(`clips: job ${job.id} (${job.kind}) failed: ${err.message}`);
update(db, job.id, {
status: "failed",
error: String(err.message ?? err).slice(0, 500),
finished_at: new Date().toISOString(),
});
} finally {
running = false;
kick(db);
}
})();
}
/* ── Files out ─────────────────────────────────────────────── */
export const fileOf = (job) => (job?.file ? filePath(job.file) : null);
/* A finished clip into the media library: copied into the uploads
directory under a random name, given a media row, and its working
file deleted. Returns the media row's id. */
export async function saveToLibrary(db, job, userId) {
const from = fileOf(job);
if (!from) throw new ClipError(410, "That clip's file is gone. Make it again.");
const audio = job.file.endsWith(".mp3");
const ext = audio ? ".mp3" : ".mp4";
const filename = `${randomBytes(12).toString("hex")}${ext}`;
const to = path.join(UPLOADS_DIR, filename);
// Each step says what it was doing if it fails, so the page can
// tell an admin (this tool is admin-only) what to fix: usually the
// uploads folder's permissions, or UPLOADS_DIR not set.
const step = async (what, fn) => {
try {
return await fn();
} catch (err) {
const why =
err.code === "EACCES" || err.code === "EPERM"
? "the service's user isn't allowed to write there"
: err.message;
throw new ClipError(500, `Couldn't save it to the library: ${what} (${why}).`);
}
};
await step(`making the uploads folder ${UPLOADS_DIR}`, () => mkdir(UPLOADS_DIR, { recursive: true }));
await step(`copying the clip into ${UPLOADS_DIR}`, () => copyFile(from, to));
let id;
try {
const info = audio
? { width: null, height: null }
: await step("reading the clip's size", () => probe(from));
const { size } = await stat(from);
const params = JSON.parse(job.params ?? "{}");
const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
const label = `${job.title ?? "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)})${ext}`;
id = await step("adding it to the media table", () =>
Number(
db
.prepare(
`INSERT INTO media (filename, original_name, content_type, bytes, width, height, processed, uploaded_by)
VALUES (?, ?, ?, ?, ?, ?, 0, ?)`,
)
.run(filename, label.slice(0, 200), audio ? "audio/mpeg" : "video/mp4", size, info.width, info.height, userId)
.lastInsertRowid,
),
);
} catch (err) {
await rm(to, { force: true }); // no file in uploads without its row
throw err;
}
await rm(from, { force: true });
update(db, job.id, { saved_media_id: id, file: null });
return { id, url: `${PUBLIC_PREFIX}${filename}` };
}
/* After a clip has gone out in full: its file isn't needed. */
export async function forgetDownloaded(db, job) {
await rm(fileOf(job) ?? "", { force: true });
update(db, job.id, { file: null, downloaded_at: new Date().toISOString() });
}
/* A job and everything it made: a source takes its clips with it. */
export async function removeJob(db, job) {
const clips = db.prepare(`SELECT file FROM clip_jobs WHERE source_id = ?`).all(job.id);
for (const clip of clips) if (clip.file) await rm(filePath(clip.file), { force: true });
if (job.file) await rm(filePath(job.file), { force: true });
db.prepare(`DELETE FROM clip_jobs WHERE id = ?`).run(job.id);
}
/* ── Cleanup ───────────────────────────────────────────────── */
async function sweep(db) {
const old = db
.prepare(
`SELECT * FROM clip_jobs
WHERE status != 'running' AND created_at < datetime('now', ?)
ORDER BY kind = 'source'`,
)
.all(`-${KEEP_HOURS} hours`);
for (const job of old) await removeJob(db, job);
// Files no job names: a download that died halfway, say.
const named = new Set(db.prepare(`SELECT file FROM clip_jobs WHERE file IS NOT NULL`).all().map((r) => r.file));
let names = [];
try {
names = await readdir(CLIPS_DIR);
} catch {
return;
}
const cutoff = Date.now() - KEEP_HOURS * 3600 * 1000;
for (const name of names) {
if (named.has(name)) continue;
const full = filePath(name);
try {
if ((await stat(full)).mtimeMs < cutoff) await rm(full, { force: true, recursive: true });
} catch {
/* gone already */
}
}
}
/* At boot: fail what a restart interrupted, start the queue, and
sweep now and every hour. */
export function startClipWorker(db) {
dbRef = db;
db.prepare(
`UPDATE clip_jobs SET status = 'failed', error = 'Interrupted by a server restart.',
finished_at = datetime('now')
WHERE status = 'running'`,
).run();
const tick = () => sweep(db).catch((err) => console.warn(`clips: sweep failed: ${err.message}`));
tick();
setInterval(tick, SWEEP_EVERY_MS).unref?.();
kick(db);
}

View file

@ -30,6 +30,8 @@ import admin from "./routes/admin.js";
import panel from "./routes/panel.js"; import panel from "./routes/panel.js";
import adminEntities from "./routes/admin-entities.js"; import adminEntities from "./routes/admin-entities.js";
import media from "./routes/media.js"; import media from "./routes/media.js";
import clips from "./routes/clips.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR } from "./media.js"; import { UPLOADS_DIR } from "./media.js";
import { startSessionSweeper } from "./auth.js"; import { startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
@ -84,6 +86,7 @@ app.route("/api/auth", auth);
app.route("/api/admin", admin); app.route("/api/admin", admin);
// Before the entity routes, whose /:entity would claim /media. // Before the entity routes, whose /:entity would claim /media.
app.route("/api/admin", media); app.route("/api/admin", media);
app.route("/api/admin", clips);
app.route("/api/admin", adminEntities); app.route("/api/admin", adminEntities);
/* ── Uploads ─────────────────────────────────────────────────── /* ── Uploads ───────────────────────────────────────────────────
@ -111,6 +114,8 @@ app.use(
app.route("/", pages); app.route("/", pages);
startSessionSweeper(db); startSessionSweeper(db);
startClipWorker(db);
console.log(`clips ${CLIPS_DIR}`);
app.notFound((c) => c.json({ error: "Not found" }, 404)); app.notFound((c) => c.json({ error: "Not found" }, 404));

View file

@ -0,0 +1,53 @@
-- ═══════════════════════════════════════════════════════════════
-- 036 VIDEO CLIPS
--
-- The admin's video clip tool (Tools → Video clips): download one of
-- our videos from YouTube or Facebook, cut clips from it, and take
-- them away as MP4 or MP3. One row per job, of two kinds:
--
-- source a download (yt-dlp) of source_url. When done, file is
-- the video in CLIPS_DIR and title/duration describe it.
-- clip a cut (ffmpeg) of a source: params holds the JSON
-- { start, end, shape, focus, format }. When done, file
-- is the clip in CLIPS_DIR.
--
-- Jobs run one at a time, oldest queued first (server/src/clips.js).
-- A job left 'running' by a restart is marked failed at boot.
--
-- Files are temporary. A clip's file is deleted once it has been
-- downloaded, unless it was saved to the media library first
-- (saved_media_id), and anything older than a day is swept, sources
-- included. Deleting a source deletes its clips.
--
-- PRAGMA user_version; -- reads 35 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE clip_jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL CHECK (kind IN ('source', 'clip')),
status TEXT NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued', 'running', 'done', 'failed')),
progress REAL NOT NULL DEFAULT 0 CHECK (progress BETWEEN 0 AND 1),
source_url TEXT, -- kind 'source'
source_id INTEGER REFERENCES clip_jobs (id) ON DELETE CASCADE, -- kind 'clip'
params TEXT, -- kind 'clip': JSON
title TEXT,
duration REAL, -- seconds
file TEXT, -- a name in CLIPS_DIR, once done
bytes INTEGER,
error TEXT,
saved_media_id INTEGER REFERENCES media (id) ON DELETE SET NULL,
downloaded_at TEXT, -- a clip's file went out, and was deleted
created_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
finished_at TEXT,
CHECK ((kind = 'source') = (source_url IS NOT NULL)),
CHECK ((kind = 'clip') = (source_id IS NOT NULL))
) STRICT;
CREATE INDEX clip_jobs_queue_idx ON clip_jobs (status, id);
CREATE INDEX clip_jobs_source_idx ON clip_jobs (source_id);

226
server/src/routes/clips.js Normal file
View file

@ -0,0 +1,226 @@
/* ═══════════════════════════════════════════════════════════════
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";
const clips = new Hono();
clips.use("/clips", requireAuth, requireRole("admin"));
clips.use("/clips/*", requireAuth, requireRole("admin"));
const NO_STORE = { "Cache-Control": "no-store" };
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;

View file

@ -1,7 +1,8 @@
/* ═══════════════════════════════════════════════════════════════ /* ═══════════════════════════════════════════════════════════════
MEDIA ROUTES: mounted under /api/admin MEDIA ROUTES: mounted under /api/admin
GET /media the library, newest first, ?q=name. GET /media the library, newest first, ?q=name,
?type=image|video|audio.
Picks up images copied into the Picks up images copied into the
uploads folder by hand first uploads folder by hand first
(registerLooseFiles, at most every (registerLooseFiles, at most every
@ -109,15 +110,19 @@ media.get("/media", async (c) => {
} }
const q = (c.req.query("q") ?? "").trim().slice(0, 100); const q = (c.req.query("q") ?? "").trim().slice(0, 100);
// ?type=image (what image fields pick from), video or audio
// (clips saved from Tools → Video clips); none lists everything.
const type = ["image", "video", "audio"].includes(c.req.query("type")) ? c.req.query("type") : null;
const where = [q && "m.original_name LIKE ?", type && "m.content_type LIKE ?"].filter(Boolean);
const rows = c const rows = c
.get("db") .get("db")
.prepare( .prepare(
`${SELECT} `${SELECT}
${q ? "WHERE m.original_name LIKE ?" : ""} ${where.length ? `WHERE ${where.join(" AND ")}` : ""}
ORDER BY m.created_at DESC, m.id DESC ORDER BY m.created_at DESC, m.id DESC
LIMIT ${MAX_LIST}`, LIMIT ${MAX_LIST}`,
) )
.all(...(q ? [`%${q}%`] : [])); .all(...(q ? [`%${q}%`] : []), ...(type ? [`${type}/%`] : []));
return c.json({ media: rows.map(shape) }, 200, NO_STORE); return c.json({ media: rows.map(shape) }, 200, NO_STORE);
}); });

View file

@ -34,6 +34,7 @@ import AdminPanel from "./pages/admin/AdminPanel.tsx";
import AdminHome from "./pages/admin/AdminHome.tsx"; import AdminHome from "./pages/admin/AdminHome.tsx";
import AdminFeedback from "./pages/admin/AdminFeedback.tsx"; import AdminFeedback from "./pages/admin/AdminFeedback.tsx";
import AdminMedia from "./pages/admin/AdminMedia.tsx"; import AdminMedia from "./pages/admin/AdminMedia.tsx";
import AdminClips from "./pages/admin/AdminClips.tsx";
import EntityList from "./pages/admin/EntityList.tsx"; import EntityList from "./pages/admin/EntityList.tsx";
import EntityEdit from "./pages/admin/EntityEdit.tsx"; import EntityEdit from "./pages/admin/EntityEdit.tsx";
@ -84,6 +85,9 @@ export default function App() {
</Route> </Route>
<Route path="feedback" element={<AdminFeedback />} /> <Route path="feedback" element={<AdminFeedback />} />
<Route path="media" element={<AdminMedia />} /> <Route path="media" element={<AdminMedia />} />
<Route element={<RequireRole role="admin" />}>
<Route path="clips" element={<AdminClips />} />
</Route>
<Route path=":entity" element={<EntityList />} /> <Route path=":entity" element={<EntityList />} />
<Route path=":entity/:id" element={<EntityEdit />} /> <Route path=":entity/:id" element={<EntityEdit />} />
</Route> </Route>

View file

@ -83,19 +83,25 @@ export function uploadImage(file: File, keepOriginal: boolean): Promise<MediaIte
return upload("/admin/media", form).then((data) => data.media); return upload("/admin/media", form).then((data) => data.media);
} }
export function useMediaLibrary(query: string) { /* `type` narrows to one kind of file: image fields pick images only.
Blank lists everything, videos and audio saved from the clip tool
included. */
export function useMediaLibrary(query: string, type?: "image" | "video" | "audio") {
const [items, setItems] = useState<MediaItem[] | null>(null); const [items, setItems] = useState<MediaItem[] | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const reload = useCallback(() => { const reload = useCallback(() => {
const q = query.trim(); const q = query.trim();
const params = new URLSearchParams();
if (q) params.set("q", q);
if (type) params.set("type", type);
setError(null); setError(null);
get(`/admin/media${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 }) get(`/admin/media${params.size ? `?${params}` : ""}`, { ttl: 0 })
.then((data) => setItems(data.media)) .then((data) => setItems(data.media))
.catch((err) => .catch((err) =>
setError(err instanceof ApiError ? err.message : "Couldn't load the library."), setError(err instanceof ApiError ? err.message : "Couldn't load the library."),
); );
}, [query]); }, [query, type]);
useEffect(reload, [reload]); useEffect(reload, [reload]);
@ -204,12 +210,21 @@ export function MediaGrid({
const thumb = ( const thumb = (
<> <>
<div className="aspect-[4/3] overflow-hidden rounded-lg" style={CHECKER}> <div className="aspect-[4/3] overflow-hidden rounded-lg" style={CHECKER}>
<img {item.content_type.startsWith("video/") ? (
src={item.url} // A still of the first frame; metadata only, not the file.
alt="" <video src={item.url} preload="metadata" muted className="h-full w-full bg-black object-contain" />
loading="lazy" ) : item.content_type.startsWith("audio/") ? (
className="h-full w-full object-contain" <div className="flex h-full w-full items-center justify-center bg-[#eef9fb] text-3xl" aria-hidden="true">
/> ♪
</div>
) : (
<img
src={item.url}
alt=""
loading="lazy"
className="h-full w-full object-contain"
/>
)}
</div> </div>
<p className="mt-1.5 truncate text-xs font-medium text-[#26454c]" title={item.original_name}> <p className="mt-1.5 truncate text-xs font-medium text-[#26454c]" title={item.original_name}>
{item.original_name} {item.original_name}
@ -258,7 +273,7 @@ export function MediaPicker({
}) { }) {
const { user } = useAuth(); const { user } = useAuth();
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const { items, error, setItems } = useMediaLibrary(query); const { items, error, setItems } = useMediaLibrary(query, "image");
const dialogRef = useRef<HTMLDialogElement>(null); const dialogRef = useRef<HTMLDialogElement>(null);
// showModal gives focus trapping, Escape and the backdrop for free. // showModal gives focus trapping, Escape and the backdrop for free.

View file

@ -7,4 +7,4 @@
box or a build banner can read the same value later. box or a build banner can read the same value later.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
export const SITE_VERSION = "NGU-Web.v1.8.0-feature-fixes"; export const SITE_VERSION = "NGU-Web.v1.8.3-video-mgmt";

View file

@ -0,0 +1,515 @@
/* ═══════════════════════════════════════════════════════════════
ADMIN: VIDEO CLIPS (Tools → Video clips, admins and up)
Paste one of our YouTube or Facebook links, and the server
downloads it (server/src/clips.js). Then cut clips from it: set
the start and end while watching, pick a shape (16:9, square, or
9:16 for Reels and Shorts, cropped around a point you choose) and
video or audio, and make it. Clips queue on the server and run
one at a time; this page asks for progress every POLL_MS while
anything is queued or running.
A finished clip downloads as a file and is then deleted from the
server, unless it's saved to the media library first. Everything
here is swept a day after it was made.
═══════════════════════════════════════════════════════════════ */
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { Link } from "react-router-dom";
import { ApiError, del, get, post } from "../../lib/api.ts";
const TEAL = "#138ba0";
const MUTED = "#4a6b72";
const POLL_MS = 2000;
type Job = {
id: number;
kind: "source" | "clip";
status: "queued" | "running" | "done" | "failed";
progress: number;
source_url: string | null;
source_id: number | null;
params: { start: number; end: number; shape: string; focus: number; format: string } | null;
title: string | null;
duration: number | null;
bytes: number | null;
error: string | null;
has_file: boolean;
saved_media_id: number | null;
saved_url: string | null;
downloaded_at: string | null;
};
type Listing = {
tools: { ytdlp: string | null; ffmpeg: string | null };
sources: Job[];
clips: Job[];
};
const SHAPES: Array<[string, string, number | null]> = [
["original", "As filmed", null],
["landscape", "Landscape 16:9", 16 / 9],
["square", "Square 1:1", 1],
["vertical", "Vertical 9:16 (Reels, Shorts, TikTok)", 9 / 16],
];
/* 83.5 → "1:23.5"; 3723 → "1:02:03". */
function clock(seconds: number | null | undefined): string {
if (seconds == null || !Number.isFinite(seconds)) return "-";
const whole = Math.floor(seconds);
const tenths = Math.round((seconds - whole) * 10);
const h = Math.floor(whole / 3600);
const m = Math.floor((whole % 3600) / 60);
const s = whole % 60;
const ss = `${String(s).padStart(2, "0")}${tenths ? `.${tenths % 10}` : ""}`;
return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
}
/* "1:23.5", "83.5" or "1:02:03" → seconds; null when it isn't a time. */
function parseClock(text: string): number | null {
const parts = text.trim().split(":");
if (!parts.length || parts.some((p) => !/^\d+(\.\d+)?$/.test(p))) return null;
return parts.reduce((total, part) => total * 60 + Number(part), 0);
}
function sizeOf(bytes: number | null): string {
if (!bytes) return "";
return bytes > 1024 * 1024 * 1024
? `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`
: `${Math.round(bytes / 1024 / 1024)} MB`;
}
const button =
"rounded-full border border-[#138ba0] px-4 py-2 text-sm font-semibold text-[#138ba0] transition-colors hover:bg-[#eef9fb] disabled:cursor-default disabled:opacity-50";
const primary =
"rounded-full bg-[#138ba0] px-5 py-2.5 font-semibold text-white transition-colors hover:bg-[#0f7183] disabled:bg-[#4a6b72]/25";
const input =
"rounded-lg border border-[#4a6b72]/25 bg-white px-3 py-2 text-sm text-[#26454c] outline-none focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25";
function Card({ title, children }: { title: string; children: ReactNode }) {
return (
<section className="mt-6 rounded-2xl border border-[#138ba0]/20 bg-white p-5">
<h2 className="text-lg font-semibold text-[#26454c]">{title}</h2>
<div className="mt-4">{children}</div>
</section>
);
}
function Status({ job }: { job: Job }) {
if (job.status === "failed") return <p className="text-sm text-[#b3261e]">Failed: {job.error}</p>;
if (job.status === "done") return null;
const percent = Math.round(job.progress * 100);
return (
<div className="mt-2">
<div className="h-2 overflow-hidden rounded-full bg-[#eef9fb]">
<div className="h-full bg-[#138ba0] transition-all" style={{ width: `${job.status === "queued" ? 0 : percent}%` }} />
</div>
<p className="mt-1 text-xs" style={{ color: MUTED }}>
{job.status === "queued" ? "Waiting its turn…" : `${percent}%`}
</p>
</div>
);
}
/* ── The editor for one downloaded video ─────────────────────── */
function Editor({ source, onMade }: { source: Job; onMade: () => void }) {
const videoRef = useRef<HTMLVideoElement>(null);
const [aspect, setAspect] = useState<number | null>(null);
const [now, setNow] = useState(0);
const [start, setStart] = useState(0);
const [end, setEnd] = useState(Math.min(source.duration ?? 60, 60));
const [startText, setStartText] = useState(clock(0));
const [endText, setEndText] = useState(clock(Math.min(source.duration ?? 60, 60)));
const [shape, setShape] = useState("original");
const [focus, setFocus] = useState(0.5);
const [format, setFormat] = useState("video");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const target = SHAPES.find(([id]) => id === shape)?.[2] ?? null;
const setStartAt = (s: number) => {
setStart(s);
setStartText(clock(s));
};
const setEndAt = (s: number) => {
setEnd(s);
setEndText(clock(s));
};
// The crop box over the video, in percent of the frame.
let crop: { left: number; top: number; width: number; height: number } | null = null;
if (target && aspect && format === "video") {
if (aspect > target) {
const width = (target / aspect) * 100;
crop = { width, height: 100, top: 0, left: Math.min(Math.max(focus * 100 - width / 2, 0), 100 - width) };
} else {
const height = (aspect / target) * 100;
crop = { width: 100, height, left: 0, top: Math.min(Math.max(focus * 100 - height / 2, 0), 100 - height) };
}
}
async function make() {
setBusy(true);
setError(null);
try {
await post("/admin/clips", { source_id: source.id, start, end, shape, focus, format });
onMade();
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't queue the clip.");
} finally {
setBusy(false);
}
}
return (
<div className="grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
<div>
<div
className="relative overflow-hidden rounded-xl bg-black"
style={{ aspectRatio: aspect ? String(aspect) : "16 / 9" }}
>
<video
ref={videoRef}
src={`/api/admin/clips/${source.id}/video`}
controls
preload="metadata"
className="h-full w-full"
onLoadedMetadata={(e) => {
const v = e.currentTarget;
if (v.videoWidth && v.videoHeight) setAspect(v.videoWidth / v.videoHeight);
}}
onTimeUpdate={(e) => setNow(e.currentTarget.currentTime)}
/>
{crop && (
// Everything outside the box is dimmed by its huge shadow.
<div
aria-hidden="true"
className="pointer-events-none absolute border-2 border-white"
style={{
left: `${crop.left}%`,
top: `${crop.top}%`,
width: `${crop.width}%`,
height: `${crop.height}%`,
boxShadow: "0 0 0 9999px rgba(0,0,0,0.55)",
}}
/>
)}
</div>
<p className="mt-2 text-sm" style={{ color: MUTED }}>
At {clock(now)} of {clock(source.duration)}
</p>
</div>
<div className="space-y-5">
<div className="grid grid-cols-2 gap-4">
{(
[
["Start", startText, setStartText, setStartAt, start],
["End", endText, setEndText, setEndAt, end],
] as const
).map(([label, text, setText, setAt, value]) => (
<div key={label}>
<label className="block text-sm font-medium text-[#26454c]" htmlFor={`clip-${label}`}>
{label}
</label>
<input
id={`clip-${label}`}
value={text}
onChange={(e) => {
setText(e.target.value);
const s = parseClock(e.target.value);
if (s != null) (label === "Start" ? setStart : setEnd)(s);
}}
onBlur={() => setText(clock(value))}
className={`mt-1 w-full ${input}`}
/>
<div className="mt-2 flex gap-2">
<button type="button" className={button} onClick={() => setAt(Math.round(now * 10) / 10)}>
Set to {clock(now)}
</button>
<button
type="button"
className="text-sm underline"
style={{ color: TEAL }}
onClick={() => {
if (videoRef.current) videoRef.current.currentTime = value;
}}
>
Go
</button>
</div>
</div>
))}
</div>
<p className="text-sm" style={{ color: end > start ? MUTED : "#b3261e" }}>
{end > start ? `Clip length: ${clock(end - start)}` : "The start has to be before the end."}
</p>
<div>
<p className="text-sm font-medium text-[#26454c]">Make it</p>
<div className="mt-2 flex gap-4 text-sm">
{[
["video", "Video (MP4)"],
["audio", "Audio only (MP3)"],
].map(([id, label]) => (
<label key={id} className="flex items-center gap-2">
<input type="radio" name="clip-format" checked={format === id} onChange={() => setFormat(id)} />
{label}
</label>
))}
</div>
</div>
{format === "video" && (
<div>
<p className="text-sm font-medium text-[#26454c]">Shape</p>
<div className="mt-2 grid gap-1.5 text-sm">
{SHAPES.map(([id, label]) => (
<label key={id} className="flex items-center gap-2">
<input type="radio" name="clip-shape" checked={shape === id} onChange={() => setShape(id)} />
{label}
</label>
))}
</div>
{target && (
<label className="mt-3 block text-sm text-[#26454c]">
Where to crop
<input
type="range"
min={0}
max={1}
step={0.01}
value={focus}
onChange={(e) => setFocus(Number(e.target.value))}
className="mt-1 w-full accent-[#138ba0]"
/>
<span className="text-xs" style={{ color: MUTED }}>
The white box on the video is what's kept.
</span>
</label>
)}
</div>
)}
<button type="button" className={primary} disabled={busy || end <= start} onClick={make}>
{busy ? "Queuing…" : "Make clip"}
</button>
{error && <p className="text-sm text-[#b3261e]">{error}</p>}
</div>
</div>
);
}
/* ── The page ────────────────────────────────────────────────── */
export default function AdminClips() {
const [data, setData] = useState<Listing | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [url, setUrl] = useState("");
const [adding, setAdding] = useState(false);
const [addError, setAddError] = useState<string | null>(null);
const [openId, setOpenId] = useState<number | null>(null);
const [rowError, setRowError] = useState<string | null>(null);
const load = useCallback(() => {
get("/admin/clips", { ttl: 0 })
.then((d) => {
setData(d);
setLoadError(null);
})
.catch((err) => setLoadError(err instanceof ApiError ? err.message : "Couldn't load the clips."));
}, []);
useEffect(load, [load]);
const busy = data ? [...data.sources, ...data.clips].some((j) => j.status === "queued" || j.status === "running") : false;
useEffect(() => {
if (!busy) return undefined;
const timer = window.setInterval(load, POLL_MS);
return () => window.clearInterval(timer);
}, [busy, load]);
async function addSource(e) {
e.preventDefault();
setAdding(true);
setAddError(null);
try {
await post("/admin/clips/sources", { url });
setUrl("");
load();
} catch (err) {
setAddError(err instanceof ApiError ? err.message : "Couldn't queue the download.");
} finally {
setAdding(false);
}
}
async function act(fn: () => Promise<unknown>) {
setRowError(null);
try {
await fn();
} catch (err) {
setRowError(err instanceof ApiError ? err.message : "That didn't work.");
}
load();
}
if (!data) {
return <p style={{ color: loadError ? "#b3261e" : MUTED }}>{loadError ?? "Loading…"}</p>;
}
const missing = [!data.tools.ytdlp && "yt-dlp", !data.tools.ffmpeg && "ffmpeg"].filter(Boolean);
const open = data.sources.find((s) => s.id === openId && s.status === "done" && s.has_file) ?? null;
const sourceTitle = (id: number | null) => data.sources.find((s) => s.id === id)?.title ?? "Clip";
return (
<div>
<div className="flex flex-wrap items-baseline gap-3">
<h1 className="text-2xl font-bold text-[#138ba0]">Video clips</h1>
<p className="text-sm" style={{ color: MUTED }}>
Cut clips from our YouTube and Facebook videos, for Reels, Shorts, the site or a podcast.
</p>
</div>
{missing.length > 0 && (
<p className="mt-4 rounded-xl bg-[#fdf3f2] px-4 py-3 text-sm text-[#b3261e]">
{missing.join(" and ")} {missing.length > 1 ? "aren't" : "isn't"} installed on the server, so this
won't work until {missing.length > 1 ? "they are" : "it is"}. See docs/video-clips.md.
</p>
)}
<Card title="1. Download a video">
<form onSubmit={addSource} className="flex flex-wrap gap-3">
<input
type="url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://www.youtube.com/watch?v=…"
className={`min-w-0 flex-1 ${input}`}
/>
<button type="submit" className={primary} disabled={adding || !url.trim()}>
{adding ? "Adding…" : "Download"}
</button>
</form>
<p className="mt-2 text-xs" style={{ color: MUTED }}>
YouTube and Facebook links only, and only videos NGU owns or has permission to use. Up to 4 hours long.
</p>
{addError && <p className="mt-2 text-sm text-[#b3261e]">{addError}</p>}
{data.sources.length > 0 && (
<ul className="mt-5 divide-y divide-[#138ba0]/10">
{data.sources.map((s) => (
<li key={s.id} className="py-3">
<div className="flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-[#26454c]">{s.title ?? s.source_url}</p>
<p className="text-xs" style={{ color: MUTED }}>
{[s.duration && clock(s.duration), sizeOf(s.bytes)].filter(Boolean).join(" · ")}
</p>
</div>
{s.status === "done" && s.has_file && (
<button type="button" className={button} onClick={() => setOpenId(openId === s.id ? null : s.id)}>
{openId === s.id ? "Close" : "Make clips"}
</button>
)}
{s.status !== "running" && (
<button
type="button"
className="text-sm hover:text-[#b3261e]"
style={{ color: MUTED }}
onClick={() =>
window.confirm("Delete this video and its clips from the server?") &&
act(() => del(`/admin/clips/${s.id}`))
}
>
Delete
</button>
)}
</div>
<Status job={s} />
</li>
))}
</ul>
)}
</Card>
{open && (
<Card title={`2. Cut: ${open.title ?? "video"}`}>
<Editor source={open} onMade={load} />
</Card>
)}
{data.clips.length > 0 && (
<Card title="Clips">
{rowError && <p className="mb-3 text-sm text-[#b3261e]">{rowError}</p>}
<ul className="divide-y divide-[#138ba0]/10">
{data.clips.map((clip) => (
<li key={clip.id} className="py-3">
<div className="flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-[#26454c]">{sourceTitle(clip.source_id)}</p>
<p className="text-xs" style={{ color: MUTED }}>
{clip.params &&
[
`${clock(clip.params.start)} to ${clock(clip.params.end)}`,
clip.params.format === "audio"
? "MP3"
: SHAPES.find(([id]) => id === clip.params!.shape)?.[1],
sizeOf(clip.bytes),
]
.filter(Boolean)
.join(" · ")}
</p>
</div>
{clip.status === "done" && clip.has_file && (
<>
<a
href={`/api/admin/clips/${clip.id}/download`}
className={primary}
onClick={() => window.setTimeout(load, 3000)}
>
Download
</a>
<button type="button" className={button} onClick={() => act(() => post(`/admin/clips/${clip.id}/save`, {}))}>
Save to library
</button>
</>
)}
{clip.saved_url && (
<Link to="/admin/media" className="text-sm underline" style={{ color: TEAL }}>
In the media library
</Link>
)}
{clip.status === "done" && !clip.has_file && !clip.saved_url && (
<span className="text-sm" style={{ color: MUTED }}>
Downloaded, and deleted from the server
</span>
)}
{clip.status !== "running" && (
<button
type="button"
className="text-sm hover:text-[#b3261e]"
style={{ color: MUTED }}
onClick={() => act(() => del(`/admin/clips/${clip.id}`))}
>
Remove
</button>
)}
</div>
<Status job={clip} />
</li>
))}
</ul>
<p className="mt-3 text-xs" style={{ color: MUTED }}>
A clip is deleted from the server once it's downloaded, unless it's saved to the library first.
Everything here is cleared a day after it's made.
</p>
</Card>
)}
</div>
);
}

View file

@ -20,7 +20,7 @@ import { Link } from "react-router-dom";
import { useAuth } from "../../lib/auth.tsx"; import { useAuth } from "../../lib/auth.tsx";
import { SITE_VERSION } from "../../lib/version.ts"; import { SITE_VERSION } from "../../lib/version.ts";
import { ROLE_LABELS, isSuper } from "../../lib/roles.ts"; import { ROLE_LABELS, isSuper } from "../../lib/roles.ts";
import { DATA_NAV, FORMS_NAV, PAGES_NAV, PANEL_NAV, TOOLS_NAV, target } from "./adminNav.ts"; import { DATA_NAV, FORMS_NAV, PAGES_NAV, PANEL_NAV, TOOLS_NAV, target, visibleItems } from "./adminNav.ts";
/* One card. The title link is stretched over the whole card with /* One card. The title link is stretched over the whole card with
`after:absolute`, which makes the card clickable without nesting `after:absolute`, which makes the card clickable without nesting
@ -121,7 +121,7 @@ export default function AdminHome() {
{GROUPS.map((group) => ( {GROUPS.map((group) => (
<CardBlock key={group.label} title={group.label} blurb={group.blurb}> <CardBlock key={group.label} title={group.label} blurb={group.blurb}>
{group.children.map((item) => ( {visibleItems(group.children, user).map((item) => (
<NavCard key={item.to} item={item} /> <NavCard key={item.to} item={item} />
))} ))}
</CardBlock> </CardBlock>

View file

@ -35,7 +35,7 @@
anything. anything.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { isSuper } from "../../lib/roles.ts"; import { atLeast, isSuper } from "../../lib/roles.ts";
export const ADMIN_HOME = "/admin/home"; export const ADMIN_HOME = "/admin/home";
export const ADMIN_PANEL = "/admin/panel"; export const ADMIN_PANEL = "/admin/panel";
@ -132,6 +132,12 @@ export const TOOLS_NAV = {
label: "Media", label: "Media",
blurb: "Uploaded images: logos, photos and backgrounds, ready to reuse.", blurb: "Uploaded images: logos, photos and backgrounds, ready to reuse.",
}, },
{
to: "/admin/clips",
label: "Video clips",
blurb: "Cut clips from our YouTube and Facebook videos: trimmed, reshaped for Reels, or audio only.",
minRole: "admin",
},
{ {
to: "/qr", to: "/qr",
label: "QR code generator", label: "QR code generator",
@ -165,9 +171,17 @@ export const PANEL_NAV = {
export const NAV: any[] = [DATA_NAV, PAGES_NAV, FORMS_NAV, TOOLS_NAV, PANEL_NAV]; export const NAV: any[] = [DATA_NAV, PAGES_NAV, FORMS_NAV, TOOLS_NAV, PANEL_NAV];
/* A group's items this user may see: one with `minRole` is left out
below that rank (Video clips is admin and up). */
export function visibleItems(items, user) {
return (items ?? []).filter((item) => !item.minRole || atLeast(user, item.minRole));
}
/* What this user may see. Call it with the user from useAuth. */ /* What this user may see. Call it with the user from useAuth. */
export function navFor(user) { export function navFor(user) {
return NAV.filter((item) => !item.superOnly || isSuper(user)); return NAV.filter((item) => !item.superOnly || isSuper(user)).map((item) =>
item.children ? { ...item, children: visibleItems(item.children, user) } : item,
);
} }
/* An item owns its own page and everything below it, so editing /* An item owns its own page and everything below it, so editing