Add a video clip tool: download our videos, cut, reshape, export

Tools → Video clips (migration 036, admins and up). Paste a YouTube
or Facebook link and the server downloads it with yt-dlp; then cut
clips: start and end set while watching, a shape (as filmed, 16:9,
square or 9:16 at the sizes the platforms ask for, cropped around a
chosen point shown over the video), and MP4 video or MP3 audio.

Jobs queue and run one at a time with progress. Only YouTube and
Facebook links are accepted, and both tools run with argument lists,
never a shell. A clip's file is deleted once it has been downloaded
in full, unless it's saved to the media library first, which now
holds video and audio (image fields still pick images only).
Everything is swept a day after it's made. Setup is in
docs/video-clips.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-28 02:43:05 -05:00
parent 8f3f907311
commit beca01c351
13 changed files with 1431 additions and 17 deletions

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 { SITE_VERSION } from "../../lib/version.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
`after:absolute`, which makes the card clickable without nesting
@ -121,7 +121,7 @@ export default function AdminHome() {
{GROUPS.map((group) => (
<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} />
))}
</CardBlock>

View file

@ -35,7 +35,7 @@
anything.
═══════════════════════════════════════════════════════════════ */
import { isSuper } from "../../lib/roles.ts";
import { atLeast, isSuper } from "../../lib/roles.ts";
export const ADMIN_HOME = "/admin/home";
export const ADMIN_PANEL = "/admin/panel";
@ -132,6 +132,12 @@ export const TOOLS_NAV = {
label: "Media",
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",
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];
/* 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. */
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