/* ═══════════════════════════════════════════════════════════════ 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 = "#0f7183"; 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-[#0f7183] transition-colors hover:bg-[#eef9fb] disabled:cursor-default disabled:opacity-50"; const primary = "rounded-full bg-[#0f7183] px-5 py-2.5 font-semibold text-white transition-colors hover:bg-[#0b5c6a] 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 (

{title}

{children}
); } function Status({ job }: { job: Job }) { if (job.status === "failed") return

Failed: {job.error}

; if (job.status === "done") return null; const percent = Math.round(job.progress * 100); return (

{job.status === "queued" ? "Waiting its turn…" : `${percent}%`}

); } /* ── The editor for one downloaded video ─────────────────────── */ function Editor({ source, onMade }: { source: Job; onMade: () => void }) { const videoRef = useRef(null); const [aspect, setAspect] = useState(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(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 (
{( [ ["Start", startText, setStartText, setStartAt, start], ["End", endText, setEndText, setEndAt, end], ] as const ).map(([label, text, setText, setAt, value]) => (
{ 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}`} />
))}

start ? MUTED : "#b3261e" }}> {end > start ? `Clip length: ${clock(end - start)}` : "The start has to be before the end."}

Make it

{[ ["video", "Video (MP4)"], ["audio", "Audio only (MP3)"], ].map(([id, label]) => ( ))}
{format === "video" && (

Shape

{SHAPES.map(([id, label]) => ( ))}
{target && ( )}
)} {error &&

{error}

}
); } /* ── The page ────────────────────────────────────────────────── */ export default function AdminClips() { const [data, setData] = useState(null); const [loadError, setLoadError] = useState(null); const [url, setUrl] = useState(""); const [adding, setAdding] = useState(false); const [addError, setAddError] = useState(null); const [openId, setOpenId] = useState(null); const [rowError, setRowError] = useState(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) { setRowError(null); try { await fn(); } catch (err) { setRowError(err instanceof ApiError ? err.message : "That didn't work."); } load(); } if (!data) { return

{loadError ?? "Loading…"}

; } 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 (

Video clips

Cut clips from our YouTube and Facebook videos, for Reels, Shorts, the site or a podcast.

{missing.length > 0 && (

{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.

)}
setUrl(e.target.value)} placeholder="https://www.youtube.com/watch?v=…" className={`min-w-0 flex-1 ${input}`} />

YouTube and Facebook links only, and only videos NGU owns or has permission to use. Up to 4 hours long.

{addError &&

{addError}

} {data.sources.length > 0 && (
    {data.sources.map((s) => (
  • {s.title ?? s.source_url}

    {[s.duration && clock(s.duration), sizeOf(s.bytes)].filter(Boolean).join(" · ")}

    {s.status === "done" && s.has_file && ( )} {s.status !== "running" && ( )}
  • ))}
)}
{open && ( )} {data.clips.length > 0 && ( {rowError &&

{rowError}

}
    {data.clips.map((clip) => (
  • {sourceTitle(clip.source_id)}

    {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(" · ")}

    {clip.status === "done" && clip.has_file && ( <> window.setTimeout(load, 3000)} > Download )} {clip.saved_url && ( In the media library )} {clip.status === "done" && !clip.has_file && !clip.saved_url && ( Downloaded, and deleted from the server )} {clip.status !== "running" && ( )}
  • ))}

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.

)}
); }