v1.13.1-data: links/redirects, captions, partner picks, Plausible reports, migration baseline #28

Merged
ngu-git-admin merged 16 commits from data into main 2026-10-06 10:10:57 +01:00
18 changed files with 123 additions and 43 deletions
Showing only changes of commit 33be618331 - Show all commits

View file

@ -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/<file>` (`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/<file>` (`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.

View file

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

View file

@ -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"),
],

View file

@ -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"]),

View file

@ -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]*?-->\s*|<!DOCTYPE[^>]*>\s*)*<svg[\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;

View file

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

View file

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

View file

@ -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

View file

@ -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: [],
};

View file

@ -351,7 +351,7 @@ function Block({
return (
<figure>
<div className="overflow-hidden">
<VideoPlayer url={block.href} still={mediaUrl(block.media)} title={text || null} />
<VideoPlayer url={block.href} still={mediaUrl(block.media)} captions={mediaUrl(block.captions)} title={text || null} />
</div>
{!reading && <Caption text={text} />}
</figure>

View file

@ -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 && <track kind="captions" src={captions} srcLang="en" label="Captions" default />}
</video>
) : (
<iframe
ref={focusOnMount}

View file

@ -37,7 +37,7 @@
cached list would lie.
═══════════════════════════════════════════════════════════════ */
import { FileAudio, X } from "@phosphor-icons/react";
import { ClosedCaptioning, FileAudio, X } from "@phosphor-icons/react";
import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react";
import { useLocation } from "react-router-dom";
@ -59,7 +59,7 @@ export type MediaItem = {
processed: boolean;
uploaded_by: string | null;
created_at: string;
/** logos, images or thumbnails; null for clips and older files in the root. */
/** logos, images, thumbnails or captions; null for clips and older files in the root. */
folder: string | null;
};
@ -69,6 +69,7 @@ export const IMAGE_FOLDERS = [
["logos", "Logos"],
["images", "Images"],
["thumbnails", "Previews"],
["captions", "Captions"],
] as const;
export type ImageFolder = (typeof IMAGE_FOLDERS)[number][0];
@ -198,6 +199,8 @@ export function UploadButton({
const [keepOriginal, setKeepOriginal] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// Captions are kept as they are, so there's no original to keep.
const captions = folder === "captions";
async function send(files: FileList | null) {
if (!files || files.length === 0) return;
@ -235,11 +238,12 @@ export function UploadButton({
<input
ref={inputRef}
type="file"
accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml"
accept={captions ? ".vtt,text/vtt" : "image/jpeg,image/png,image/gif,image/webp,image/svg+xml"}
multiple={multiple}
className="hidden"
onChange={(e) => send(e.target.files)}
/>
{!captions && (
<label htmlFor={keepId} className="flex items-center gap-1.5 text-xs text-muted">
<input
id={keepId}
@ -250,6 +254,7 @@ export function UploadButton({
/>
Keep original
</label>
)}
</div>
{error && <p className="mt-1 text-xs text-danger">{error}</p>}
</div>
@ -293,6 +298,10 @@ export function MediaGrid({
<div className="flex h-full w-full items-center justify-center bg-tint" aria-hidden="true">
<FileAudio weight="bold" className="h-10 w-10 text-link" />
</div>
) : item.content_type === "text/vtt" ? (
<div className="flex h-full w-full items-center justify-center bg-tint" aria-hidden="true">
<ClosedCaptioning weight="bold" className="h-10 w-10 text-link" />
</div>
) : (
<Thumb url={item.url} />
)}
@ -429,7 +438,7 @@ export function MediaPicker({
const [query, setQuery] = useState("");
const [tab, setTab] = useState<string>(folder);
const fromRequests = tab === REQUESTS_TAB;
const { items, error, setItems } = useMediaLibrary(query, "image", fromRequests ? undefined : tab);
const { items, error, setItems } = useMediaLibrary(query, tab === "captions" ? undefined : "image", fromRequests ? undefined : tab);
const dialogRef = useRef<HTMLDialogElement>(null);
// showModal gives focus trapping, Escape and the backdrop for free.
@ -556,11 +565,13 @@ export function ImageInput({
className="flex h-20 w-20 shrink-0 items-center justify-center overflow-hidden border border-muted/20"
style={CHECKER}
>
{src && !broken ? (
{folder === "captions" && src ? (
<ClosedCaptioning weight="bold" className="h-8 w-8 text-link" aria-label="Captions file" />
) : src && !broken ? (
<img src={src} alt="" className="h-full w-full object-contain" onError={() => setBroken(true)} />
) : (
<span className="px-1 text-center text-[10px] text-muted/70">
{src ? "Not found" : "No image"}
{src ? "Not found" : folder === "captions" ? "No file" : "No image"}
</span>
)}
</div>

View file

@ -107,6 +107,15 @@ export const frontPage = {
"A YouTube, Vimeo or Facebook link, or a video file: a filename in " +
"the uploads folder, or a link ending in .mp4 or .webm",
},
{
path: "video_captions",
label: "Video captions",
widget: "image",
folder: "captions",
resolve: mediaUrl,
full: true,
help: "A WebVTT (.vtt) file, for a video file; YouTube, Vimeo and Facebook show their own. Default: none.",
},
{ path: "video_title", label: "Video title", full: true, help: "Shown after \"Featured video\" above the headline" },
{
path: "hero_event_id",

View file

@ -396,6 +396,16 @@ export const blocksChild = {
help: (row) =>
row?.type === "video" ? "Still shown before it plays. Default: YouTube's own thumbnail." : undefined,
},
{
path: "captions",
label: "Captions",
widget: "image",
folder: "captions",
resolve: mediaUrl,
full: true,
when: { path: "type", value: "video" },
help: "A WebVTT (.vtt) file, for an uploaded video; YouTube, Vimeo and Facebook show their own. Default: none.",
},
{
path: "alt",
label: "Alt text",

View file

@ -48,6 +48,8 @@ export type ContentBlock = {
team_id?: string | null
/** Who a quote is by. */
cite?: string | null
/** A video block's WebVTT file, for an uploaded video (066). */
captions?: string | null
items?: ContentBlockItem[]
}

View file

@ -51,7 +51,7 @@ export type Hero = {
slides: HeroSlide[]
livestream: { url: string; title?: string | null } | null
/** A link to embed or a video file; see videoSource in embeds.ts. */
video: { url: string; title?: string | null } | null
video: { url: string; title?: string | null; captions?: string | null } | null
/** With the 'event' feature: the pinned event, else the countdown's. */
event: HeroEvent | null
}

View file

@ -107,7 +107,7 @@ const sourceOf = (part: NewsletterPart): PickSource => (SOURCES.includes(part.so
/* Every part is a row: one editor for blocks and the email's own
parts, so any of them can be moved, copied or removed. */
const blockFields = blocksChild.fields.filter((field) => !['slot', 'team_id', 'type'].includes(field.path))
const blockFields = blocksChild.fields.filter((field) => !['slot', 'team_id', 'type', 'captions'].includes(field.path))
const PARTS_SPEC = {
key: 'parts',
label: 'Parts',

View file

@ -113,7 +113,7 @@ export default function HeroStage({ hero }: { hero: Hero | null }) {
{feature === 'video' && hero?.video && (
<div className="lg:col-span-7">
<VideoFrame source={video} url={hero.video.url} title={hero.video.title} />
<VideoFrame source={video} url={hero.video.url} title={hero.video.title} captions={mediaUrl(hero.video.captions)} />
</div>
)}
@ -498,10 +498,13 @@ function VideoFrame({
source,
url,
title,
captions,
}: {
source: VideoSource | null
url: string
title?: string | null
/** A WebVTT file's URL; only a file plays it, an embed has its own. */
captions?: string | null
}) {
return (
<div
@ -517,7 +520,9 @@ function VideoFrame({
controls
playsInline
preload="metadata"
/>
>
{captions && <track kind="captions" src={captions} srcLang="en" label="Captions" default />}
</video>
) : source?.kind === 'embed' ? (
<VideoPlayer url={url} title={title || 'Featured video'} className="h-full" />
) : (