- The messages' YouTube thumbnails are served from the site (/api/thumbnails/<id>.jpg): the backend fetches a message's thumbnail once and keeps it in uploads/.thumbnails (only the site's own videos, only a JPEG), so visitors ask nothing of YouTube before pressing play. The messages page preloads the first one (its LCP: Heritage 89 -> 95). - Calendar events' dates read "Sun · November", not "Sun (month: November)". - e2e: no request to YouTube or Spotify before play; the variant screenshots round section heights to whole pixels (a one-pixel flake); the e2e thumbnail is one of the demo's illustrations. - crosscode script: a Website's export leaves out uploads/.thumbnails. - docs: release checks on 1.0.1, VERSIONS, handover. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
71 lines
2.9 KiB
TypeScript
71 lines
2.9 KiB
TypeScript
/**
|
|
* A message's YouTube thumbnail, served from the site (WEBSITE-1.0-PLAN §7: nothing loads from
|
|
* YouTube until a visitor clicks play). The backend fetches `i.ytimg.com/vi/<id>/hqdefault.jpg`
|
|
* once and keeps it in `<uploads>/.thumbnails/` (not served from /api/uploads, which denies dot
|
|
* folders, and not counted as the church's storage). Only the ids of the site's own messages are
|
|
* fetched, so the route is never a proxy for anything else.
|
|
*/
|
|
import fs from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import type { Ctx } from '../context.js';
|
|
import { defaultUploadDir } from '../demo/demoChurch.js';
|
|
import { youtubeId } from './content.js';
|
|
|
|
export { thumbnailPath } from './content.js';
|
|
export type Fetcher = (url: string) => Promise<Response>;
|
|
|
|
const ID = /^[A-Za-z0-9_-]{6,20}$/;
|
|
const MAX_BYTES = 1024 * 1024;
|
|
|
|
const cacheDir = (ctx: Ctx) => path.join(path.resolve(ctx.config.uploadDir ?? defaultUploadDir()), '.thumbnails');
|
|
|
|
const defaultFetcher: Fetcher = (url) => fetch(url, { signal: AbortSignal.timeout(10_000) });
|
|
|
|
/** One fetch per video at a time, however many visitors ask at once. */
|
|
const inFlight = new Map<string, Promise<Buffer | null>>();
|
|
|
|
async function isOurVideo(ctx: Ctx, videoId: string) {
|
|
const rows = await ctx.db.message.findMany({ where: { mediaUrl: { contains: videoId } }, select: { mediaUrl: true, source: true }, take: 5 });
|
|
return rows.some((m) => m.source !== 'spotify' && youtubeId(m.mediaUrl) === videoId);
|
|
}
|
|
|
|
async function download(fetcher: Fetcher, videoId: string): Promise<Buffer | null> {
|
|
try {
|
|
const res = await fetcher(`https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`);
|
|
if (!res.ok || !/^image\/jpe?g/.test(res.headers.get('content-type') ?? '')) return null;
|
|
const body = Buffer.from(await res.arrayBuffer());
|
|
// A JPEG by its bytes, and a sensible size.
|
|
if (body.length > MAX_BYTES || body.length < 3 || body[0] !== 0xff || body[1] !== 0xd8 || body[2] !== 0xff) return null;
|
|
return body;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** The thumbnail's bytes, from the cache or YouTube; null when it isn't one of the site's videos or YouTube has none. */
|
|
export async function thumbnail(ctx: Ctx, videoId: string, fetcher: Fetcher = ctx.fetch ?? defaultFetcher): Promise<Buffer | null> {
|
|
if (!ID.test(videoId)) return null;
|
|
const file = path.join(cacheDir(ctx), `${videoId}.jpg`);
|
|
try {
|
|
return await fs.readFile(file);
|
|
} catch {
|
|
// Not cached yet.
|
|
}
|
|
if (!(await isOurVideo(ctx, videoId))) return null;
|
|
let pending = inFlight.get(videoId);
|
|
if (!pending) {
|
|
pending = (async () => {
|
|
const body = await download(fetcher, videoId);
|
|
if (body) {
|
|
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
await fs.writeFile(tmp, body);
|
|
await fs.rename(tmp, file);
|
|
}
|
|
return body;
|
|
})().finally(() => inFlight.delete(videoId));
|
|
inFlight.set(videoId, pending);
|
|
}
|
|
return pending;
|
|
}
|