From 33be6183318c3e696daaca84d5d236cb1b0c3d95 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 4 Oct 2026 21:55:05 -0500 Subject: [PATCH] Captions for uploaded videos (migration 066) Video blocks get a Captions field and the hero a Video captions field, each a WebVTT upload drawn as on a video file. The media library takes .vtt (sniffed by its WEBVTT header, kept as is, always in /uploads/captions/) with its own tab. Newsletter parts leave the field out. nginx needs text/vtt in mime.types: docs/media-uploads.md, step 5. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/media-uploads.md | 19 ++++++++- server/src/admin-schema/columns.js | 2 + server/src/admin-schema/frontPage.js | 1 + server/src/media.js | 34 +++++++++------- server/src/migrations/066_video_captions.sql | 13 ++++++ server/src/routes/home.js | 2 +- server/src/routes/media.js | 4 +- server/src/shape.js | 3 +- src/components/ContentBlocks.tsx | 2 +- src/components/VideoPlayer.tsx | 7 +++- src/components/admin/MediaLibrary.tsx | 43 ++++++++++++-------- src/lib/adminSchema/frontPage.ts | 9 ++++ src/lib/adminSchema/shared.ts | 10 +++++ src/lib/useContent.ts | 2 + src/lib/useFrontPage.ts | 2 +- src/pages/admin/AdminNewsletter.tsx | 2 +- src/pages/sections/home/HeroStage.tsx | 9 +++- 18 files changed, 123 insertions(+), 43 deletions(-) create mode 100644 server/src/migrations/066_video_captions.sql diff --git a/CLAUDE.md b/CLAUDE.md index b6ea106..53fb340 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -64,7 +64,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages). - `api.ts` is the shared caching client used by frontend data hooks. - `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content. -- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`). +- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews), `/uploads/captions/` (videos' .vtt files); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`). ## Rules and gotchas - **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs. diff --git a/docs/media-uploads.md b/docs/media-uploads.md index a0e025e..6e3bfdb 100644 --- a/docs/media-uploads.md +++ b/docs/media-uploads.md @@ -15,8 +15,10 @@ in the `media` table (`server/src/migrations/028_media.sql`). - **Keep original** stores the file exactly as uploaded (up to 10 MB), metadata and all. - SVGs are always kept as they are. -- Accepted types: JPEG, PNG, GIF, WebP, SVG. The type is read from the - file's contents, not its name. +- Accepted types: JPEG, PNG, GIF, WebP, SVG, and WebVTT captions + (`.vtt`, kept as they are, always in `captions/`). The type is read + from the file's contents, not its name: a captions file has to start + with `WEBVTT`. - Editors and up can upload. Admins and up can delete. The Media page shows which tables still use a file before deleting it, because nothing stops a file a record uses from being deleted. @@ -33,6 +35,7 @@ Images are kept in folders by what they're for (`FOLDERS` in | `logos/` | Uploads from logo and icon fields (organization, team, award and event logos, the favicon and home-screen icon): the fields with `folder: "logos"` in `src/lib/adminSchema/` | | `images/` | Every other upload: photos, backgrounds, covers, block images | | `thumbnails/` | Pictures the site saves by itself: link previews (Fetch preview) and Drive files' first pages | +| `captions/` | WebVTT files for uploaded videos: the Captions field of video blocks and the hero's Video captions (migration 066). YouTube, Vimeo and Facebook videos show their own | Each image's `-640.webp` small copy sits beside it. Video and audio clips (Tools → Video clips) stay in the root. The Media page and every @@ -100,3 +103,15 @@ which git ignores). The API serves `/uploads/` itself, and Vite proxies 4. `sharp` is a server dependency now: run `pnpm install` in `/srv/ngu-api` after the deploy. It ships prebuilt Linux binaries, so no build tools are needed. + +5. Captions need nginx to send `.vtt` files as `text/vtt` (Firefox + won't show them otherwise, and `nosniff` stops guessing). Check: + + ```sh + grep vtt /etc/nginx/mime.types + ``` + + If nothing comes back, add `text/vtt vtt;` inside the `types { }` + block of `/etc/nginx/mime.types`, then + `sudo nginx -t && sudo systemctl reload nginx`. Not in the site's + own file: a `types` block there replaces the whole list. diff --git a/server/src/admin-schema/columns.js b/server/src/admin-schema/columns.js index 49a0f15..bb96ef9 100644 --- a/server/src/admin-schema/columns.js +++ b/server/src/admin-schema/columns.js @@ -159,6 +159,8 @@ export const blocksChild = (ownerKind) => ({ url("href"), text("alt"), text("cite"), + // Video blocks only (066): an uploaded video's WebVTT file. + text("captions"), // People blocks only (054): whose team's tiles to show. text("team_id"), ], diff --git a/server/src/admin-schema/frontPage.js b/server/src/admin-schema/frontPage.js index 346d709..3d11224 100644 --- a/server/src/admin-schema/frontPage.js +++ b/server/src/admin-schema/frontPage.js @@ -44,6 +44,7 @@ export const frontPage = { text("livestream_title"), url("video_url"), text("video_title"), + text("video_captions"), text("countdown_event_id"), text("countdown_scope_id"), enumeration("countdown_event_type", ["retreat", "class", "workshop", "meeting", "other"]), diff --git a/server/src/media.js b/server/src/media.js index ccbe11f..19f3f2c 100644 --- a/server/src/media.js +++ b/server/src/media.js @@ -15,8 +15,9 @@ ── What ── The type is read from the file's first bytes, never from its name or the browser's Content-Type, both of which the uploader - controls. JPEG, PNG, GIF, WebP and SVG are accepted; anything - else is refused. + controls. JPEG, PNG, GIF, WebP and SVG are accepted, and WebVTT + captions (a text file starting "WEBVTT"); anything else is + refused. ── Processing ── By default a raster image is turned upright (EXIF orientation), @@ -25,7 +26,7 @@ `keepOriginal` stores the bytes exactly as uploaded instead, under the tighter KEEP_MAX_BYTES. An SVG is always kept as it is: it's already small, and rasterizing it would lose the point - of it. + of it. So is a WebVTT file, always into captions/. Names are random, so two uploads of "logo.png" can't collide and a filename says nothing about what's in it. @@ -33,8 +34,8 @@ ── Folders ── Each upload goes in a folder by what it's for (FOLDERS): logos/ for logo and icon fields, thumbnails/ for pictures the site saves - by itself (link previews, Drive files' first pages), images/ for - the rest. A stored name includes it: 'logos/3f9c….webp', served at + by itself (link previews, Drive files' first pages), captions/ + for videos' WebVTT files, images/ for the rest. A stored name includes it: 'logos/3f9c….webp', served at /uploads/logos/3f9c….webp. The small copy sits beside it. Clips keep a bare name in the root. @@ -66,7 +67,7 @@ const MB = 1024 * 1024; /* The largest file accepted at all, before processing: room for a full-size phone photo. */ /* Where an upload goes, by what it's for (see Folders above). */ -export const FOLDERS = ["logos", "images", "thumbnails"]; +export const FOLDERS = ["logos", "images", "thumbnails", "captions"]; export const folderOf = (value) => (FOLDERS.includes(value) ? value : "images"); /* A name this library stores: a bare name in the root, or one inside @@ -131,8 +132,12 @@ const TYPES = { gif: { mime: "image/gif", ext: ".gif" }, webp: { mime: "image/webp", ext: ".webp" }, svg: { mime: "image/svg+xml", ext: ".svg" }, + vtt: { mime: "text/vtt", ext: ".vtt" }, }; +/* Kinds stored exactly as uploaded, with no small copy: text, not pixels. */ +const AS_IS = new Set(["svg", "vtt"]); + function startsWith(buf, bytes, offset = 0) { return bytes.every((byte, i) => buf[offset + i] === byte); } @@ -151,6 +156,7 @@ function sniff(buf) { if (/^(<\?xml[\s\S]*?\?>\s*)?(\s*|]*>\s*)*]/i.test(head)) { return "svg"; } + if (/^WEBVTT(\s|$)/.test(head)) return "vtt"; return null; } @@ -169,10 +175,10 @@ export async function store(buf, { keepOriginal = false, folder } = {}) { const kind = sniff(buf); if (!kind) { - throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images can be uploaded."); + throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images, and WebVTT (.vtt) captions, can be uploaded."); } - const convert = kind !== "svg" && !keepOriginal; + const convert = !AS_IS.has(kind) && !keepOriginal; if (!convert && buf.length > KEEP_MAX_BYTES) { throw new MediaError( @@ -200,7 +206,7 @@ export async function store(buf, { keepOriginal = false, folder } = {}) { width = info.width; // An animated image reports the whole strip's height. height = info.pageHeight ?? info.height; - } else if (kind !== "svg") { + } else if (!AS_IS.has(kind)) { const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata(); width = meta.width ?? null; height = meta.pageHeight ?? meta.height ?? null; @@ -209,7 +215,7 @@ export async function store(buf, { keepOriginal = false, folder } = {}) { throw new MediaError(415, "That image couldn't be read. It may be damaged."); } - const dir = folderOf(folder); + const dir = kind === "vtt" ? "captions" : folderOf(folder); const base = `${randomBytes(12).toString("hex")}${type.ext}`; const filename = `${dir}/${base}`; @@ -219,7 +225,7 @@ export async function store(buf, { keepOriginal = false, folder } = {}) { const tmp = path.join(UPLOADS_DIR, dir, `.${base}.tmp`); await writeFile(tmp, out); await rename(tmp, path.join(UPLOADS_DIR, filename)); - if (kind !== "svg") await writeThumb(filename, out); + if (!AS_IS.has(kind)) await writeThumb(filename, out); return { filename, @@ -269,10 +275,10 @@ export async function writeMissingThumbs() { const present = new Set(names); let made = 0; for (const name of names) { - if (THUMB.test(name) || /\.svg$/i.test(name)) continue; + if (THUMB.test(name) || /\.(svg|vtt)$/i.test(name)) continue; if (present.has(thumbName(name))) continue; const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null); - if (!buf || !sniff(buf) || sniff(buf) === "svg") continue; + if (!buf || !sniff(buf) || AS_IS.has(sniff(buf))) continue; await writeThumb(name, buf); made += 1; } @@ -309,7 +315,7 @@ async function describe(filename) { let width = null; let height = null; - if (kind !== "svg") { + if (!AS_IS.has(kind)) { try { const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata(); width = meta.width ?? null; diff --git a/server/src/migrations/066_video_captions.sql b/server/src/migrations/066_video_captions.sql new file mode 100644 index 0000000..50a31e6 --- /dev/null +++ b/server/src/migrations/066_video_captions.sql @@ -0,0 +1,13 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 066 VIDEO CAPTIONS +-- +-- A WebVTT file for an uploaded video, drawn as its captions track +-- (WCAG 1.2.2). YouTube, Vimeo and Facebook embeds bring their own. +-- The file is an upload in /uploads/captions/ (media.js). +-- +-- content_blocks.captions a video block's +-- front_page.video_captions the hero's featured video's +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE content_blocks ADD COLUMN captions TEXT; +ALTER TABLE front_page ADD COLUMN video_captions TEXT; diff --git a/server/src/routes/home.js b/server/src/routes/home.js index 5a8ab80..054a450 100644 --- a/server/src/routes/home.js +++ b/server/src/routes/home.js @@ -225,7 +225,7 @@ home.get("/front-page", (c) => { ? { url: page.livestream_url, title: page.livestream_title } : null, video: page.video_url - ? { url: page.video_url, title: page.video_title } + ? { url: page.video_url, title: page.video_title, captions: page.video_captions } : null, event: shapeHeroEvent(db, heroEvent), }, diff --git a/server/src/routes/media.js b/server/src/routes/media.js index 41e15e0..74b3c4e 100644 --- a/server/src/routes/media.js +++ b/server/src/routes/media.js @@ -3,12 +3,12 @@ GET /media the library, newest first, ?q=name, ?type=image|video|audio, - ?folder=logos|images|thumbnails. + ?folder=logos|images|thumbnails|captions. Picks up images copied into the uploads folder by hand first (registerLooseFiles, at most every SCAN_EVERY_MS) - POST /media upload one image (multipart: file, + POST /media upload one image or .vtt (multipart: file, keep_original, folder: FOLDERS in media.js, default images) GET /media/:id/uses which records name this file diff --git a/server/src/shape.js b/server/src/shape.js index 751bea9..51acb01 100644 --- a/server/src/shape.js +++ b/server/src/shape.js @@ -66,7 +66,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { const blockRows = db .prepare( - `SELECT id, owner_id, type, text, media, href, alt, cite, team_id + `SELECT id, owner_id, type, text, media, href, alt, cite, captions, team_id FROM content_blocks WHERE owner_kind = ? AND slot = ? AND owner_id IN (${placeholders(ids.length)}) ORDER BY owner_id, sort_order`, @@ -85,6 +85,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { href: row.href, alt: row.alt, cite: row.cite, + captions: row.captions, team_id: row.team_id, items: [], }; diff --git a/src/components/ContentBlocks.tsx b/src/components/ContentBlocks.tsx index cb5c621..d0f6cbf 100644 --- a/src/components/ContentBlocks.tsx +++ b/src/components/ContentBlocks.tsx @@ -351,7 +351,7 @@ function Block({ return (
- +
{!reading && }
diff --git a/src/components/VideoPlayer.tsx b/src/components/VideoPlayer.tsx index b8ed3d8..a7f38f7 100644 --- a/src/components/VideoPlayer.tsx +++ b/src/components/VideoPlayer.tsx @@ -33,11 +33,14 @@ export default function VideoPlayer({ url, still, title, + captions, className = '', }: { url?: string | null /** An image URL to show before it plays. */ still?: string | null + /** A WebVTT file's URL, for an uploaded video; embeds bring their own. */ + captions?: string | null title?: string | null className?: string }) { @@ -66,7 +69,9 @@ export default function VideoPlayer({ playsInline aria-label={title || 'Video'} className={`aspect-video w-full rounded-md bg-black ${className}`} - /> + > + {captions && } + ) : (