/** * 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//hqdefault.jpg` * once and keeps it in `/.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; 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>(); 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 { 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 { 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; }