diff --git a/docs/video-clips.md b/docs/video-clips.md
index 3faf4d2..c83f006 100644
--- a/docs/video-clips.md
+++ b/docs/video-clips.md
@@ -14,6 +14,12 @@ it: **Save to library** and **Save to Drive** on the download itself.
It stays on the server to cut clips from either way (until the day's
sweep).
+The same tools take stills: a video featured card's Image field has
+**Frame at** (editors and up), which saves the frame at a typed time to
+`/uploads/thumbnails/` (`grabFrame` in `server/src/clips.js`). It
+downloads only that frame, outside the queue. A link's own `t=` (eg.
+`?t=83`) fills in the time.
+
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
diff --git a/server/src/clips.js b/server/src/clips.js
index 97c71d4..b8fec0e 100644
--- a/server/src/clips.js
+++ b/server/src/clips.js
@@ -49,7 +49,7 @@
import { spawn } from "node:child_process";
import { randomBytes } from "node:crypto";
-import { access, constants, copyFile, mkdir, readdir, rm, stat } from "node:fs/promises";
+import { access, constants, copyFile, mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
import path from "node:path";
import { UPLOADS_DIR, PUBLIC_PREFIX } from "./media.js";
@@ -446,6 +446,63 @@ async function cut(db, job) {
});
}
+/* ── A single frame ──────────────────────────────────────── */
+
+/* One frame of a YouTube or Facebook video as a JPEG, for a card's
+ picture. yt-dlp only finds the stream's address and ffmpeg seeks
+ in it, so nothing is downloaded but that frame; light enough to
+ run in the request, outside the queue. */
+export async function grabFrame(sourceUrl, seconds) {
+ const link = checkSourceUrl(sourceUrl);
+ if (!Number.isFinite(seconds) || seconds < 0 || seconds > MAX_SOURCE_SECONDS) {
+ throw new ClipError(400, "That isn't a time in the video.");
+ }
+ await mkdir(CLIPS_DIR, { recursive: true });
+ const id = `frame-${randomBytes(6).toString("hex")}`;
+ const out = path.join(CLIPS_DIR, `${id}.jpg`);
+ const cookies = await cookieArgs(id);
+ let stream = null;
+ try {
+ await run(
+ YTDLP,
+ [
+ "--ignore-config",
+ ...cookies.args,
+ "--js-runtimes",
+ `node:${process.execPath}`,
+ "--no-playlist",
+ "-f",
+ "bv*[height<=1080]/b[height<=1080]/b",
+ "--get-url",
+ "--",
+ link,
+ ],
+ { onLine: (line) => (stream ??= /^https:\/\//.test(line.trim()) ? line.trim() : null) },
+ );
+ } catch (err) {
+ if (err instanceof ClipError) throw err;
+ console.error(`frame ${link}: ${err.message}`);
+ throw new ClipError(422, "The video couldn't be opened. It may be private or removed.");
+ } finally {
+ await cookies.cleanup();
+ }
+ if (!stream) throw new ClipError(422, "The video couldn't be opened. It may be private or removed.");
+
+ try {
+ // -ss before -i seeks in the stream instead of reading up to it.
+ await run(FFMPEG, ["-hide_banner", "-loglevel", "error", "-ss", String(seconds), "-i", stream, "-frames:v", "1", "-q:v", "2", "-y", out]);
+ return await readFile(out);
+ } catch (err) {
+ // Past the end, ffmpeg finishes without writing anything.
+ if (err.code === "ENOENT") throw new ClipError(422, "The video doesn't run that long.");
+ if (err instanceof ClipError) throw err;
+ console.error(`frame ${link} at ${seconds}: ${err.message}`);
+ throw new ClipError(422, "The frame couldn't be taken from the video.");
+ } finally {
+ await rm(out, { force: true });
+ }
+}
+
let running = false;
let dbRef = null;
diff --git a/server/src/routes/media.js b/server/src/routes/media.js
index 907c924..41e15e0 100644
--- a/server/src/routes/media.js
+++ b/server/src/routes/media.js
@@ -41,6 +41,7 @@ import {
store,
} from "../media.js";
import { fetchImage, previewLink } from "../linkPreview.js";
+import { ClipError, grabFrame } from "../clips.js";
import { NO_STORE } from "../shape.js";
const media = new Hono();
@@ -204,6 +205,26 @@ media.post("/link-preview", requireRole("editor"), async (c) => {
);
});
+/* A frame of a YouTube or Facebook video at `seconds`, saved as a
+ thumbnail for a video card's picture. */
+media.post("/video-frame", requireRole("editor"), async (c) => {
+ const user = c.get("user");
+ let body;
+ try {
+ body = (await c.req.json()) ?? {};
+ } catch {
+ return c.json({ error: "Expected a JSON body." }, 400);
+ }
+ const row = await addToLibrary(c.get("db"), await grabFrame(body.url, Number(body.seconds)), {
+ originalName: `video frame ${Math.floor(Number(body.seconds))}s`,
+ folder: "thumbnails",
+ keepOriginal: false,
+ userId: user.id,
+ });
+ console.log(`video frame ${String(body.url).slice(0, 200)} at ${body.seconds}s by ${user.email}`);
+ return c.json({ media: shape(row) }, 201, NO_STORE);
+});
+
/* Every TEXT column of every content table, searched for any of the
exact values a record can use to name the file: its /uploads/
path, that path escaped, or (for a file copied in by hand and
@@ -273,7 +294,7 @@ media.delete("/media/:id", requireRole("admin"), async (c) => {
});
media.onError((err, c) => {
- if (err instanceof MediaError) return c.json({ error: err.message }, err.status, NO_STORE);
+ if (err instanceof MediaError || err instanceof ClipError) return c.json({ error: err.message }, err.status, NO_STORE);
console.error(err);
return c.json({ error: "Something went wrong." }, 500);
});
diff --git a/src/components/admin/MediaLibrary.tsx b/src/components/admin/MediaLibrary.tsx
index 53308a3..4423916 100644
--- a/src/components/admin/MediaLibrary.tsx
+++ b/src/components/admin/MediaLibrary.tsx
@@ -44,6 +44,7 @@ import { useLocation } from "react-router-dom";
import { ApiError, get, post, upload } from "../../lib/api.ts";
import { useAuth } from "../../lib/auth.tsx";
+import { clock, parseClock } from "../../lib/clock.ts";
import { canWrite as roleCanWrite } from "../../lib/roles.ts";
import { useSmallImage } from "../../lib/useSmallImage.ts";
@@ -524,6 +525,7 @@ export function ImageInput({
value,
resolve,
folder,
+ videoUrl,
locked,
className,
onChange,
@@ -533,6 +535,8 @@ export function ImageInput({
resolve?: (file?: string | null) => string | null;
/** The field's `folder` (logos for logo fields); default images. */
folder?: string;
+ /** A video link to take a frame from (the field's `frameFrom`). */
+ videoUrl?: string | null;
locked: boolean;
className: string;
onChange: (value: string) => void;
@@ -587,6 +591,7 @@ export function ImageInput({
)}
)}
+ {editable && videoUrl && }
{picking && (
@@ -601,6 +606,55 @@ export function ImageInput({
);
}
+/* ── Frame from a video ──────────────────────────────────────── */
+
+/* A link's own start time (YouTube's t=83 or t=83s), so a link
+ copied at the moment wanted starts the picker there. */
+function startOf(url: string): number {
+ try {
+ const t = new URL(url).searchParams.get("t") ?? "";
+ return /^\d+s?$/.test(t) ? parseInt(t, 10) : 0;
+ } catch {
+ return 0;
+ }
+}
+
+function FrameFromVideo({ url, className, onSaved }: { url: string; className: string; onSaved: (value: string) => void }) {
+ const [text, setText] = useState(() => clock(startOf(url)));
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ const timeId = useId();
+ const seconds = parseClock(text);
+
+ async function take() {
+ setBusy(true);
+ setError(null);
+ try {
+ const { media } = await post("/admin/video-frame", { url, seconds });
+ onSaved(media.url);
+ } catch (err) {
+ setError(err instanceof ApiError ? err.message : "Couldn't take that frame.");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+