From b8012c75e99c098bd01f5a606870aa25729f0833 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 4 Oct 2026 21:35:08 -0500 Subject: [PATCH 01/16] 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 --- docs/video-clips.md | 6 +++ server/src/clips.js | 59 ++++++++++++++++++++++++++- server/src/routes/media.js | 23 ++++++++++- src/components/admin/MediaLibrary.tsx | 54 ++++++++++++++++++++++++ src/components/admin/fields.tsx | 5 ++- src/lib/adminSchema/shared.ts | 4 +- src/lib/clock.ts | 21 ++++++++++ src/pages/admin/AdminClips.tsx | 20 +-------- src/pages/admin/AdminNewsletter.tsx | 5 ++- 9 files changed, 172 insertions(+), 25 deletions(-) create mode 100644 src/lib/clock.ts 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. } From 636388730fb71f2ea3ca925b09eb4f6e51bee717 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 4 Oct 2026 21:44:25 -0500 Subject: [PATCH 02/16] Plausible analytics reports to Discord (migration 065) Daily (yesterday) and weekly (Mondays, last 7 days vs the 7 before) summaries: visitors, pageviews, bounce rate, visit length, top pages and sources. Each has its own switch in Site settings > Reports; off until PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL are set. Sent at 8:00 REPORT_TZ (default America/Chicago); analytics_reports keeps one a day. node src/analyticsReport.js daily|weekly sends one by hand. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- server/src/admin-schema/siteSettings.js | 2 + server/src/analyticsReport.js | 203 ++++++++++++++++++ server/src/index.js | 2 + .../src/migrations/065_analytics_reports.sql | 19 ++ src/lib/adminSchema/siteSettings.ts | 27 +++ 6 files changed, 254 insertions(+), 1 deletion(-) create mode 100644 server/src/analyticsReport.js create mode 100644 server/src/migrations/065_analytics_reports.sql diff --git a/CLAUDE.md b/CLAUDE.md index f4630a0..6d667e5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,7 +32,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service. - Never run commands against the production server or database unless explicitly asked. - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. -- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. +- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`). - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`. - Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`. - Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`. diff --git a/server/src/admin-schema/siteSettings.js b/server/src/admin-schema/siteSettings.js index 2947291..41c7f89 100644 --- a/server/src/admin-schema/siteSettings.js +++ b/server/src/admin-schema/siteSettings.js @@ -34,6 +34,8 @@ export const siteSettings = { text("access_group_viewer"), text("access_group_editor"), text("access_group_admin"), + enumeration("report_daily", ["on", "off"]), + enumeration("report_weekly", ["on", "off"]), ], children: [ diff --git a/server/src/analyticsReport.js b/server/src/analyticsReport.js new file mode 100644 index 0000000..10cc4eb --- /dev/null +++ b/server/src/analyticsReport.js @@ -0,0 +1,203 @@ +/* ═══════════════════════════════════════════════════════════════ + ANALYTICS REPORTS + + Plausible's numbers for this site, posted to a Discord channel: + daily yesterday: visitors, pageviews, bounce rate, visit + length, top pages and sources + weekly Mondays: the last 7 days, with the change from the 7 + before + Each is switched on in Panel → Site settings → Reports. Both go + out at SEND_HOUR in REPORT_TZ, or as soon after as the server is + up that day; analytics_reports (065) keeps it to one a day. + + ── Configuration (the ngu-api service environment) ── + PLAUSIBLE_API_KEY a Stats API key (Plausible → Account + settings → API keys) + DISCORD_WEBHOOK_URL the channel's webhook (Discord → channel + settings → Integrations → Webhooks) + PLAUSIBLE_URL default http://127.0.0.1:8000, where the + self-hosted Plausible listens + REPORT_TZ default America/Chicago + Off until the first two are set. The site counted is the hostname + of site.json's url, as in pageMeta.js's analyticsTag. + + To send one now (eg. to try the setup), whatever the switches say: + DB_PATH=/var/lib/ngu/ngu.db node src/analyticsReport.js daily|weekly + ═══════════════════════════════════════════════════════════════ */ + +import { pathToFileURL } from "node:url"; + +import { siteFor } from "./pageMeta.js"; + +const PLAUSIBLE_URL = (process.env.PLAUSIBLE_URL || "http://127.0.0.1:8000").replace(/\/$/, ""); +const PLAUSIBLE_API_KEY = process.env.PLAUSIBLE_API_KEY || null; +const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL || null; +const REPORT_TZ = process.env.REPORT_TZ || "America/Chicago"; +const SEND_HOUR = 8; +const TICK_MS = 15 * 60 * 1000; +const KINDS = ["daily", "weekly"]; + +export const reportsReady = () => Boolean(PLAUSIBLE_API_KEY && DISCORD_WEBHOOK_URL); + +/* Today's date and the hour in REPORT_TZ, and whether it's Monday. */ +function localNow(now = new Date()) { + const parts = Object.fromEntries( + new Intl.DateTimeFormat("en-US", { + timeZone: REPORT_TZ, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + hourCycle: "h23", + weekday: "short", + }) + .formatToParts(now) + .map((part) => [part.type, part.value]), + ); + return { date: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour), monday: parts.weekday === "Mon" }; +} + +/* "2026-10-04" moved by `days`. */ +function shift(date, days) { + const d = new Date(`${date}T00:00:00Z`); + d.setUTCDate(d.getUTCDate() + days); + return d.toISOString().slice(0, 10); +} + +/* ── Plausible ─────────────────────────────────────────────── */ + +async function query(siteId, body) { + const res = await fetch(`${PLAUSIBLE_URL}/api/v2/query`, { + method: "POST", + headers: { Authorization: `Bearer ${PLAUSIBLE_API_KEY}`, "Content-Type": "application/json" }, + body: JSON.stringify({ site_id: siteId, ...body }), + signal: AbortSignal.timeout(20_000), + }); + if (!res.ok) throw new Error(`Plausible answered ${res.status}: ${(await res.text()).slice(0, 200)}`); + return (await res.json()).results ?? []; +} + +const METRICS = ["visitors", "pageviews", "bounce_rate", "visit_duration"]; + +async function totals(siteId, range) { + const [row] = await query(siteId, { metrics: METRICS, date_range: range }); + return Object.fromEntries(METRICS.map((metric, i) => [metric, row?.metrics[i] ?? 0])); +} + +async function top(siteId, dimension, range, limit) { + const rows = await query(siteId, { + metrics: ["visitors"], + dimensions: [dimension], + date_range: range, + order_by: [["visitors", "desc"]], + pagination: { limit }, + }); + return rows.length ? rows.map((r) => `${r.dimensions[0]}: ${r.metrics[0]}`).join("\n") : "-"; +} + +/* ── The message ───────────────────────────────────────────── */ + +const duration = (seconds) => `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`; + +function change(now, before) { + if (!before) return now ? " (new)" : ""; + const percent = Math.round(((now - before) / before) * 100); + return ` (${percent >= 0 ? "+" : ""}${percent}%)`; +} + +/* The Discord message for `kind` as of `today` (a REPORT_TZ date): + yesterday, or the 7 days ending yesterday. */ +export async function buildReport(db, kind, today) { + const siteId = new URL(siteFor(db).url).hostname; + const to = shift(today, -1); + const from = kind === "weekly" ? shift(to, -6) : to; + const range = [from, to]; + const limit = kind === "weekly" ? 5 : 3; + + const [now, before, pages, sources] = await Promise.all([ + totals(siteId, range), + kind === "weekly" ? totals(siteId, [shift(from, -7), shift(to, -7)]) : null, + top(siteId, "event:page", range, limit), + top(siteId, "visit:source", range, limit), + ]); + const vs = (metric) => (before ? change(now[metric], before[metric]) : ""); + + return { + embeds: [ + { + title: kind === "weekly" ? `${siteId}: week of ${from} to ${to}` : `${siteId}: ${to}`, + fields: [ + { name: "Visitors", value: `${now.visitors}${vs("visitors")}`, inline: true }, + { name: "Pageviews", value: `${now.pageviews}${vs("pageviews")}`, inline: true }, + { name: "Bounce rate", value: `${now.bounce_rate}%`, inline: true }, + { name: "Visit length", value: duration(now.visit_duration), inline: true }, + { name: "Top pages", value: pages }, + { name: "Top sources", value: sources }, + ], + }, + ], + }; +} + +export async function sendReport(db, kind, today = localNow().date) { + const res = await fetch(DISCORD_WEBHOOK_URL, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(await buildReport(db, kind, today)), + signal: AbortSignal.timeout(20_000), + }); + if (!res.ok) throw new Error(`Discord answered ${res.status}: ${(await res.text()).slice(0, 200)}`); +} + +/* ── Schedule ──────────────────────────────────────────────── */ + +export function startAnalyticsReports(db) { + if (!reportsReady()) return; + let running = false; + const tick = async () => { + const { date, hour, monday } = localNow(); + if (running || hour < SEND_HOUR) return; + running = true; + try { + const settings = db.prepare(`SELECT report_daily, report_weekly FROM site_settings WHERE id = 'site'`).get() ?? {}; + for (const kind of KINDS) { + if (settings[`report_${kind}`] !== "on" || (kind === "weekly" && !monday)) continue; + if (db.prepare(`SELECT 1 FROM analytics_reports WHERE kind = ? AND sent_for = ?`).get(kind, date)) continue; + // Marked before sending: a Plausible or Discord failure is + // logged once that day, not every tick. + db.prepare( + `INSERT INTO analytics_reports (kind, sent_for) VALUES (?, ?) + ON CONFLICT (kind) DO UPDATE SET sent_for = excluded.sent_for`, + ).run(kind, date); + try { + await sendReport(db, kind, date); + console.log(`analytics ${kind} report sent for ${date}`); + } catch (err) { + console.error(`analytics ${kind} report failed: ${err.message}`); + } + } + } finally { + running = false; + } + }; + tick(); + setInterval(tick, TICK_MS).unref(); +} + +/* ── By hand ───────────────────────────────────────────────── */ + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + const kind = process.argv[2]; + if (!KINDS.includes(kind)) { + console.error("usage: node src/analyticsReport.js daily|weekly"); + process.exit(1); + } + if (!reportsReady()) { + console.error("Set PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL first."); + process.exit(1); + } + const { openDatabase } = await import("./db.js"); + const db = await openDatabase(process.env.DB_PATH ?? "./ngu.db"); + await sendReport(db, kind); + console.log(`Sent the ${kind} report.`); +} diff --git a/server/src/index.js b/server/src/index.js index 1014a53..873fdcc 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -45,6 +45,7 @@ import { UPLOADS_DIR, writeMissingThumbs } from "./media.js"; import { logSafe, startSessionSweeper } from "./auth.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { startGroupSync } from "./accessGroups.js"; +import { startAnalyticsReports } from "./analyticsReport.js"; import { ENTITIES } from "./admin-schema.js"; const HOST = process.env.HOST ?? "127.0.0.1"; @@ -241,6 +242,7 @@ app.route("/", pages); startSessionSweeper(db); startGroupSync(db); startClipWorker(db); +startAnalyticsReports(db); console.log(`clips ${CLIPS_DIR}`); app.notFound((c) => c.json({ error: "Not found" }, 404)); diff --git a/server/src/migrations/065_analytics_reports.sql b/server/src/migrations/065_analytics_reports.sql new file mode 100644 index 0000000..fec1e6f --- /dev/null +++ b/server/src/migrations/065_analytics_reports.sql @@ -0,0 +1,19 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 065 ANALYTICS REPORTS +-- +-- Plausible's numbers posted to Discord (server/src/analyticsReport.js). +-- +-- site_settings.report_daily 'on': yesterday's numbers each morning +-- site_settings.report_weekly 'on': last week's each Monday morning +-- Blank or 'off': not sent +-- analytics_reports the local date each kind was last sent +-- for, so a restart doesn't post twice +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE site_settings ADD COLUMN report_daily TEXT CHECK (report_daily IN ('on', 'off')); +ALTER TABLE site_settings ADD COLUMN report_weekly TEXT CHECK (report_weekly IN ('on', 'off')); + +CREATE TABLE analytics_reports ( + kind TEXT PRIMARY KEY CHECK (kind IN ('daily', 'weekly')), + sent_for TEXT NOT NULL +) STRICT; diff --git a/src/lib/adminSchema/siteSettings.ts b/src/lib/adminSchema/siteSettings.ts index fe74e66..3dbee2e 100644 --- a/src/lib/adminSchema/siteSettings.ts +++ b/src/lib/adminSchema/siteSettings.ts @@ -145,6 +145,33 @@ export const siteSettings = { }, ], }, + { + legend: "Reports", + fields: [ + { + path: "report_daily", + label: "Daily analytics report", + widget: "select", + options: [ + ["on", "On"], + ["off", "Off"], + ], + blankLabel: "Default: off", + help: "Yesterday's visitors, pageviews and top pages from Plausible, posted to Discord each morning. Needs PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL on the server (server/src/analyticsReport.js).", + }, + { + path: "report_weekly", + label: "Weekly analytics report", + widget: "select", + options: [ + ["on", "On"], + ["off", "Off"], + ], + blankLabel: "Default: off", + help: "The last 7 days, with the change from the week before, posted to Discord each Monday morning.", + }, + ], + }, { legend: "Notices", fields: [ From aaab1a945c991d5f1941d106dfb9c83c5f2e5303 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 4 Oct 2026 21:46:32 -0500 Subject: [PATCH 03/16] Docs: setting up the Plausible reports to Discord Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/analytics-reports.md | 162 ++++++++++++++++++++++++++++++++++ server/src/analyticsReport.js | 2 + 3 files changed, 165 insertions(+), 1 deletion(-) create mode 100644 docs/analytics-reports.md diff --git a/CLAUDE.md b/CLAUDE.md index 6d667e5..b6ea106 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,7 +32,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service. - Never run commands against the production server or database unless explicitly asked. - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. -- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`). +- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`): `docs/analytics-reports.md`. - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`. - Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`. - Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`. diff --git a/docs/analytics-reports.md b/docs/analytics-reports.md new file mode 100644 index 0000000..f506f05 --- /dev/null +++ b/docs/analytics-reports.md @@ -0,0 +1,162 @@ +# Analytics reports to Discord + +The API can post the site's Plausible numbers to a Discord channel +(`server/src/analyticsReport.js`, migration 065): + +- **Daily**: yesterday's visitors, pageviews, bounce rate, visit length, + and the top 3 pages and sources. +- **Weekly**, on Mondays: the last 7 days (Monday to Sunday), each + total with its change from the week before, and the top 5 pages and + sources. + +Each one has its own switch in Panel → Site settings → Reports, and both +are off until it's turned on. They go out at 8:00 in `REPORT_TZ`. If the +server is down then, they go out when it comes back up later that day. +A restart never posts the same report twice. Nothing else on the site +depends on this. + +| Setting on the `ngu-api` service | What it is | +| --- | --- | +| `PLAUSIBLE_API_KEY` | A Plausible Stats API key (step 1) | +| `DISCORD_WEBHOOK_URL` | The channel's webhook address (step 2) | +| `PLAUSIBLE_URL` | Where the API can reach Plausible. Default `http://127.0.0.1:8000` | +| `REPORT_TZ` | The time zone for "yesterday" and 8:00. Default `America/Chicago` | + +Without the first two, no reports are sent, whatever the switches say. + +## 1. The Plausible API key + +1. Sign in to Plausible (the self-hosted one behind `/pa/`) as an owner + of the site. +2. Account settings → API keys → New API key. Pick **Stats API** if it + asks for a type, and name it eg. `ngu-api reports`. +3. Copy the key now. Plausible shows it only once. + +The site has to exist in Plausible under the same domain the pages count +under: the hostname of `site.json`'s `url`, eg. `nextgenerationofunity.org` +(not `www.` and not `https://`). It already does if the dashboard shows +visits. + +The reports use the Stats API v2 (`/api/v2/query`), which needs +Plausible Community Edition 2.1 or later. Check Settings or the page +footer for the version, and upgrade an older one first. + +### Where Plausible listens + +`PLAUSIBLE_URL` is the address the API calls directly, not the public +`/pa/` path. nginx's proxy for `/pa/` already points at it: + +```sh +grep proxy_pass /etc/nginx/snippets/plausible-proxy.conf +``` + +If that shows `http://127.0.0.1:8000`, leave `PLAUSIBLE_URL` unset. +Otherwise set it to that address, eg. `http://127.0.0.1:8001`, or +`https://plausible.io` for Plausible's own hosting. + +## 2. The Discord webhook + +1. In Discord, open the channel's settings (the gear by its name) → + Integrations → Webhooks → New Webhook. +2. Name it eg. `NGU analytics`, give it an avatar if you like, and check + that it posts to the right channel. +3. Copy Webhook URL. It looks like + `https://discord.com/api/webhooks/123456789/AbCdEf...`. + +You need Manage Webhooks on the channel. Anyone who has the address can +post to the channel, so treat it as a password. + +## 3. The service + +Both values are secrets, so put them in a file only root can read +rather than in the unit itself (a `systemctl edit` override is readable +by every user on the box): + +```sh +sudo mkdir -p /etc/ngu +sudo tee /etc/ngu/analytics-reports.env >/dev/null <<'EOF' +PLAUSIBLE_API_KEY= +DISCORD_WEBHOOK_URL= +EOF +sudo chmod 600 /etc/ngu/analytics-reports.env +``` + +Add `PLAUSIBLE_URL=` or `REPORT_TZ=` lines to the same file if you need +them. Then point the service at it: + +```sh +sudo systemctl edit ngu-api +``` + +```ini +[Service] +EnvironmentFile=/etc/ngu/analytics-reports.env +``` + +systemd reads the file as root before it starts the service, so the +service's own user doesn't need to be able to read it. + +Back up the database first (migration 065 adds the switches and runs at +the next start), then: + +```sh +sudo systemctl restart ngu-api +``` + +No nginx change is needed: the API calls Plausible and Discord itself. + +## 4. Try it + +Send one straight away, whatever the switches say, while the service is +running: + +```sh +cd /srv/ngu-api +sudo bash -c 'set -a; . /etc/ngu/analytics-reports.env; set +a; + SITE_CONFIG=/srv/ngu-api/site.json DB_PATH=/var/lib/ngu/ngu.db \ + node src/analyticsReport.js daily' +``` + +`Sent the daily report.` means it's in the channel. Use `weekly` for the +weekly one. Sending one by hand doesn't stop that day's scheduled +report. + +## 5. Turn them on + +Panel → Site settings → Reports: set **Daily analytics report** and/or +**Weekly analytics report** to On, and save. Set one back to Off (or +blank) to stop it. The change counts from the next check, within 15 +minutes. + +The switches are per database, so the dev server only posts if its own +database has them on and its own service has the settings. Leave the +settings off dev, or it reports as `dev.nextgenerationofunity.org`. + +## Checking it + +Every report is logged: + +```sh +journalctl -u ngu-api --since today --no-pager | grep analytics +``` + +- `analytics daily report sent for 2026-10-05`: it went out. +- `Plausible answered 401`: the API key is wrong or was deleted. Make a + new one (step 1). +- `Plausible answered 400` or `404` naming the site: Plausible has no + site under that domain. Compare `site.json`'s `url` with the domain in + Plausible's site list. +- `Plausible answered 404` with no site named: Plausible is older than + 2.1 and has no v2 API. +- `fetch failed` or `ECONNREFUSED`: Plausible isn't at `PLAUSIBLE_URL` + (see Where Plausible listens). +- `Discord answered 401` or `404`: the webhook was deleted or the + address is wrong. Make a new one (step 2). +- Nothing at all: check that both settings are in the service's + environment (`sudo systemctl show ngu-api -p EnvironmentFiles`), that + the switch is On, that it's past 8:00 in `REPORT_TZ`, and for the + weekly report, that it's Monday. + +A failed report isn't retried that day, so a broken setup logs one line +a day, not one every 15 minutes. Fix the cause, then send it by hand +(step 4) if you still want it. diff --git a/server/src/analyticsReport.js b/server/src/analyticsReport.js index 10cc4eb..3f5b36c 100644 --- a/server/src/analyticsReport.js +++ b/server/src/analyticsReport.js @@ -23,6 +23,8 @@ To send one now (eg. to try the setup), whatever the switches say: DB_PATH=/var/lib/ngu/ngu.db node src/analyticsReport.js daily|weekly + + Setup: docs/analytics-reports.md. ═══════════════════════════════════════════════════════════════ */ import { pathToFileURL } from "node:url"; From 33be6183318c3e696daaca84d5d236cb1b0c3d95 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 4 Oct 2026 21:55:05 -0500 Subject: [PATCH 04/16] 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 && } + ) : (