Compare commits

..

2 commits

Author SHA1 Message Date
Zaldimmar
b8012c75e9 Video frame stills for featured cards; newsletter Pick from fix
- Image fields take frameFrom/frameWhen: "Frame at" saves a still from
  the row's YouTube or Facebook link to /uploads/thumbnails/
  (POST /api/admin/video-frame, grabFrame in clips.js). Used on video
  featured cards.
- clock/parseClock moved to src/lib/clock.ts, shared with Video clips.
- Newsletter: new drafts no longer store source 'events' (the Pick from
  select's blank choice), which showed as "events no longer exists";
  older drafts load it as blank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 21:35:08 -05:00
3b45944094 Merge pull request 'People directories, ministries, organization contacts (v1.13.0-data)' (#27) from data into main 2026-10-04 08:04:09 +01:00
9 changed files with 172 additions and 25 deletions

View file

@ -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 It stays on the server to cut clips from either way (until the day's
sweep). 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 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, 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 which puts it in the media library as an upload (usable as a featured

View file

@ -49,7 +49,7 @@
import { spawn } from "node:child_process"; import { spawn } from "node:child_process";
import { randomBytes } from "node:crypto"; 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 path from "node:path";
import { UPLOADS_DIR, PUBLIC_PREFIX } from "./media.js"; 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 running = false;
let dbRef = null; let dbRef = null;

View file

@ -41,6 +41,7 @@ import {
store, store,
} from "../media.js"; } from "../media.js";
import { fetchImage, previewLink } from "../linkPreview.js"; import { fetchImage, previewLink } from "../linkPreview.js";
import { ClipError, grabFrame } from "../clips.js";
import { NO_STORE } from "../shape.js"; import { NO_STORE } from "../shape.js";
const media = new Hono(); 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 /* Every TEXT column of every content table, searched for any of the
exact values a record can use to name the file: its /uploads/ 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 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) => { 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); console.error(err);
return c.json({ error: "Something went wrong." }, 500); return c.json({ error: "Something went wrong." }, 500);
}); });

View file

@ -44,6 +44,7 @@ import { useLocation } from "react-router-dom";
import { ApiError, get, post, upload } from "../../lib/api.ts"; import { ApiError, get, post, upload } from "../../lib/api.ts";
import { useAuth } from "../../lib/auth.tsx"; import { useAuth } from "../../lib/auth.tsx";
import { clock, parseClock } from "../../lib/clock.ts";
import { canWrite as roleCanWrite } from "../../lib/roles.ts"; import { canWrite as roleCanWrite } from "../../lib/roles.ts";
import { useSmallImage } from "../../lib/useSmallImage.ts"; import { useSmallImage } from "../../lib/useSmallImage.ts";
@ -524,6 +525,7 @@ export function ImageInput({
value, value,
resolve, resolve,
folder, folder,
videoUrl,
locked, locked,
className, className,
onChange, onChange,
@ -533,6 +535,8 @@ export function ImageInput({
resolve?: (file?: string | null) => string | null; resolve?: (file?: string | null) => string | null;
/** The field's `folder` (logos for logo fields); default images. */ /** The field's `folder` (logos for logo fields); default images. */
folder?: string; folder?: string;
/** A video link to take a frame from (the field's `frameFrom`). */
videoUrl?: string | null;
locked: boolean; locked: boolean;
className: string; className: string;
onChange: (value: string) => void; onChange: (value: string) => void;
@ -587,6 +591,7 @@ export function ImageInput({
)} )}
</div> </div>
)} )}
{editable && videoUrl && <FrameFromVideo url={videoUrl} className={className} onSaved={onChange} />}
</div> </div>
{picking && ( {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<string | null>(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 (
<div className="flex flex-wrap items-center gap-2">
<label htmlFor={timeId} className="text-sm text-muted">
Frame at
</label>
<div className="w-24">
<input id={timeId} type="text" value={text} onChange={(e) => setText(e.target.value)} placeholder="eg. 1:23" className={className} />
</div>
<button type="button" className={button} disabled={busy || seconds == null} onClick={take}>
{busy ? "Taking…" : "Use this frame"}
</button>
{error && <span className="text-xs text-danger">{error}</span>}
</div>
);
}
/* ── Link preview field ──────────────────────────────────────── */ /* ── Link preview field ──────────────────────────────────────── */
/* Fills only what's empty: a title somebody already typed is theirs, /* Fills only what's empty: a title somebody already typed is theirs,

View file

@ -71,7 +71,9 @@
`resolve` option is the media.ts helper for the field's public/ `resolve` option is the media.ts helper for the field's public/
directory, so a bare filename previews from the right place. Its directory, so a bare filename previews from the right place. Its
`folder` ("logos" for logo and icon fields) is where uploads go and `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: 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} value={value}
resolve={field.resolve} resolve={field.resolve}
folder={field.folder} folder={field.folder}
videoUrl={field.frameFrom && fieldShown({ when: field.frameWhen }, row) ? getPath(row, field.frameFrom) : null}
locked={locked} locked={locked}
className={locked ? inputLocked : common.className} className={locked ? inputLocked : common.className}
onChange={onChange} onChange={onChange}

View file

@ -191,7 +191,9 @@ export const featuredCardsChild = {
widget: "image", widget: "image",
resolve: mediaUrl, resolve: mediaUrl,
full: true, 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.",
}, },
], ],
}; };

21
src/lib/clock.ts Normal file
View file

@ -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);
}

View file

@ -18,6 +18,7 @@ import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { ApiError, del, get, post } from "../../lib/api.ts"; import { ApiError, del, get, post } from "../../lib/api.ts";
import { clock, parseClock } from "../../lib/clock.ts";
import { accentText, BRAND } from '../../lib/color.ts' import { accentText, BRAND } from '../../lib/color.ts'
const MUTED = "var(--color-muted)"; 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], ["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 { function sizeOf(bytes: number | null): string {
if (!bytes) return ""; if (!bytes) return "";
return bytes > 1024 * 1024 * 1024 return bytes > 1024 * 1024 * 1024

View file

@ -230,7 +230,7 @@ const STARTER: NewsletterPart[] = [
{ type: 'header' }, { type: 'header' },
{ type: 'title', text: '' }, { type: 'title', text: '' },
{ type: 'paragraph', text: '' }, { type: 'paragraph', text: '' },
{ type: 'picks', source: 'events', picked: [] }, { type: 'picks', picked: [] },
{ type: 'picks', source: 'posts', picked: [] }, { type: 'picks', source: 'posts', picked: [] },
{ type: 'picks', source: 'cards', picked: [] }, { type: 'picks', source: 'cards', picked: [] },
{ type: 'footer' }, { type: 'footer' },
@ -287,7 +287,8 @@ export default function AdminNewsletter() {
if (row) { if (row) {
try { try {
const parsed = JSON.parse(row.layout || '[]') 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 { } catch {
// A hand-edited draft: start its parts over. // A hand-edited draft: start its parts over.
} }