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 ( +
+ +
+ setText(e.target.value)} placeholder="eg. 1:23" className={className} /> +
+ + {error && {error}} +
+ ); +} + /* ── Link preview field ──────────────────────────────────────── */ /* Fills only what's empty: a title somebody already typed is theirs, diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index 023f9b8..d6b6b14 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -71,7 +71,9 @@ `resolve` option is the media.ts helper for the field's public/ directory, so a bare filename previews from the right place. Its `folder` ("logos" for logo and icon fields) is where uploads go and - the tab the library opens on. + the tab the library opens on. `frameFrom` names the row's video + link field and adds "Frame at" (a still at a typed time, saved to + thumbnails/); `frameWhen` limits it to rows that match. Two options change the box itself rather than what goes in it: @@ -383,6 +385,7 @@ export function Field({ field, value, row, options, error, onChange, onPatch }: value={value} resolve={field.resolve} folder={field.folder} + videoUrl={field.frameFrom && fieldShown({ when: field.frameWhen }, row) ? getPath(row, field.frameFrom) : null} locked={locked} className={locked ? inputLocked : common.className} onChange={onChange} diff --git a/src/lib/adminSchema/shared.ts b/src/lib/adminSchema/shared.ts index e994c81..492c562 100644 --- a/src/lib/adminSchema/shared.ts +++ b/src/lib/adminSchema/shared.ts @@ -191,7 +191,9 @@ export const featuredCardsChild = { widget: "image", resolve: mediaUrl, full: true, - help: "Default: the record's own picture, or for a YouTube video, its thumbnail.", + frameFrom: "url", + frameWhen: { path: "kind", value: "video" }, + help: "Default: the record's own picture, or for a YouTube video, its thumbnail. For a video, Frame at takes a still from it instead.", }, ], }; diff --git a/src/lib/clock.ts b/src/lib/clock.ts new file mode 100644 index 0000000..34d93e0 --- /dev/null +++ b/src/lib/clock.ts @@ -0,0 +1,21 @@ +/* Times in a video, as typed and shown: Tools → Video clips and the + image field's frame picker. */ + +/* 83.5 → "1:23.5"; 3723 → "1:02:03". */ +export 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. */ +export 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); +} diff --git a/src/pages/admin/AdminClips.tsx b/src/pages/admin/AdminClips.tsx index cb86a8d..3db94f8 100644 --- a/src/pages/admin/AdminClips.tsx +++ b/src/pages/admin/AdminClips.tsx @@ -18,6 +18,7 @@ import { useCallback, useEffect, useRef, useState, type ReactNode } from "react" import { Link } from "react-router-dom"; import { ApiError, del, get, post } from "../../lib/api.ts"; +import { clock, parseClock } from "../../lib/clock.ts"; import { accentText, BRAND } from '../../lib/color.ts' const MUTED = "var(--color-muted)"; @@ -56,25 +57,6 @@ const SHAPES: Array<[string, string, number | null]> = [ ["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 diff --git a/src/pages/admin/AdminNewsletter.tsx b/src/pages/admin/AdminNewsletter.tsx index 0bf8c73..b81d442 100644 --- a/src/pages/admin/AdminNewsletter.tsx +++ b/src/pages/admin/AdminNewsletter.tsx @@ -230,7 +230,7 @@ const STARTER: NewsletterPart[] = [ { type: 'header' }, { type: 'title', text: '' }, { type: 'paragraph', text: '' }, - { type: 'picks', source: 'events', picked: [] }, + { type: 'picks', picked: [] }, { type: 'picks', source: 'posts', picked: [] }, { type: 'picks', source: 'cards', picked: [] }, { type: 'footer' }, @@ -287,7 +287,8 @@ export default function AdminNewsletter() { if (row) { try { const parsed = JSON.parse(row.layout || '[]') - layout = Array.isArray(parsed) ? parsed : [] + // Events is the blank choice of Pick from, so an older draft's 'events' reads as blank. + layout = Array.isArray(parsed) ? parsed.map((part) => (part.source === 'events' ? { ...part, source: '' } : part)) : [] } catch { // A hand-edited draft: start its parts over. }