/** * The media library and storage (WEBSITE-1.0-PLAN §10, ROADMAP-v3 §10): uploads of photos (JPEG, * PNG, WebP), checked by their bytes, not their name. 5 GB included; the licence's * `limits.storageBytes` says more once extra storage is bought. **When it's full, uploads stop** * (decision 12) until more is bought; what's already uploaded keeps showing. * * Every photo is turned upright and **stripped of its metadata** (a phone photo can carry the place * it was taken), kept at most 2400 px wide, and saved in responsive sizes (WebP and JPEG at 480, * 960 and 1600 px wide, each smaller than the photo), all counted towards storage (§3). */ import crypto from 'node:crypto'; import fs from 'node:fs/promises'; import path from 'node:path'; import sharp, { type Metadata, type Sharp } from 'sharp'; import type { Ctx } from '../context.js'; import { defaultUploadDir } from '../demo/demoChurch.js'; import { INCLUDED_STORAGE_BYTES } from '../hub/client.js'; import { hubPublicKey, verifyToken } from '../hub/licence.js'; import { ApiError } from '../http.js'; import { mediaUrl } from '../site/snapshot.js'; export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024; type Kind = { ext: string; mime: string }; /** What the bytes are, whatever the name says. */ export function sniff(b: Buffer): Kind | null { if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' }; if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' }; if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' }; return null; } /** Width and height from the file's header (PNG, JPEG, WebP), or nulls. */ export function dimensions(b: Buffer, kind: Kind): { width: number | null; height: number | null } { try { if (kind.ext === 'png') return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) }; if (kind.ext === 'webp') { const chunk = b.toString('ascii', 12, 16); if (chunk === 'VP8X') return { width: 1 + b.readUIntLE(24, 3), height: 1 + b.readUIntLE(27, 3) }; if (chunk === 'VP8 ') return { width: b.readUInt16LE(26) & 0x3fff, height: b.readUInt16LE(28) & 0x3fff }; if (chunk === 'VP8L') { const bits = b.readUInt32LE(21); return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }; } } if (kind.ext === 'jpg') { let i = 2; while (i < b.length) { if (b[i] !== 0xff) break; const marker = b[i + 1]!; const len = b.readUInt16BE(i + 2); if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { height: b.readUInt16BE(i + 5), width: b.readUInt16BE(i + 7) }; i += 2 + len; } } } catch { // A header we can't read: no dimensions, the image still shows. } return { width: null, height: null }; } export async function storage(ctx: Ctx): Promise<{ usedBytes: number; limitBytes: number; full: boolean; percent: number }> { const [sum, token, installId] = await Promise.all([ ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }), ctx.settings.get('hub_licence'), ctx.settings.get('hub_install_id'), ]); const claims = verifyToken(token, hubPublicKey(ctx)) as { installId?: string; limits?: { storageBytes?: number } } | null; const fromLicence = claims && claims.installId === installId ? claims.limits?.storageBytes : undefined; const limitBytes = typeof fromLicence === 'number' ? fromLicence : INCLUDED_STORAGE_BYTES; const usedBytes = sum._sum.bytes ?? 0; return { usedBytes, limitBytes, full: usedBytes >= limitBytes, percent: limitBytes ? Math.min(100, Math.round((usedBytes / limitBytes) * 100)) : 100 }; } export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defaultUploadDir()); export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) { if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.'); if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.'); const kind = sniff(body); if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.'); const s = await storage(ctx); if (s.usedBytes + body.length > s.limitBytes) { throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. To get more (5 GB at a time), contact Cross Code; everything already uploaded keeps showing.'); } const now = ctx.now(); const base = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}`; const dir = uploadDir(ctx); await fs.mkdir(path.join(dir, path.dirname(base)), { recursive: true }); const made = await processImage(body, kind, path.join(dir, base)); const bytes = made.files.reduce((t, f) => t + f.bytes, 0); if (s.usedBytes + bytes > s.limitBytes) { await Promise.all(made.files.map((f) => fs.rm(path.join(dir, path.dirname(base), f.name), { force: true }))); throw new ApiError(409, 'STORAGE_FULL', 'That photo doesn\'t fit in the storage that\'s left, so it wasn\'t added. To get more (5 GB at a time), contact Cross Code.'); } const filename = `${base}.${made.main.ext}`; const row = await ctx.db.mediaAsset.create({ data: { filename, mime: made.main.mime, bytes, width: made.width, height: made.height, alt: alt.trim().slice(0, 500), sizes: made.sizes as never, uploadedBy: by }, }); return { ...row, url: mediaUrl(row.filename) }; } export const MAX_WIDTH = 2400; export const WIDTHS = [480, 960, 1600] as const; export type Sizes = { w: number; webp: string; jpg: string }[]; /** * The photo as kept (upright, no metadata, at most MAX_WIDTH wide, in its own format) and its * responsive sizes, written next to `basePath` (`.`, `-.webp`, `-.jpg`). * A photo the library can't read is refused rather than kept as uploaded. */ export async function processImage(body: Buffer, kind: Kind, basePath: string) { let img: Sharp; let meta: Metadata; try { img = sharp(body, { failOn: 'error' }).rotate(); meta = await img.metadata(); } catch { throw new ApiError(415, 'NOT_AN_IMAGE', 'That photo can\'t be read. Save it again as JPEG, PNG or WebP and try again.'); } // After rotate(), width and height follow the EXIF orientation. const swap = (meta.orientation ?? 1) >= 5; const fullW = (swap ? meta.height : meta.width) ?? dimensions(body, kind).width ?? MAX_WIDTH; const fullH = (swap ? meta.width : meta.height) ?? dimensions(body, kind).height ?? null; const width = Math.min(fullW, MAX_WIDTH); const height = fullH ? Math.round((fullH * width) / fullW) : null; const name = path.basename(basePath); const files: { name: string; bytes: number }[] = []; const write = async (pipeline: Sharp, file: string) => { const info = await pipeline.toFile(path.join(path.dirname(basePath), file)); files.push({ name: file, bytes: info.size }); }; // sharp writes no metadata unless asked (withMetadata), so EXIF, GPS and XMP are gone. const main = kind.ext === 'png' ? { ext: 'png', mime: 'image/png' } : kind.ext === 'webp' ? { ext: 'webp', mime: 'image/webp' } : { ext: 'jpg', mime: 'image/jpeg' }; const resized = () => img.clone().resize({ width, withoutEnlargement: true }); await write(main.ext === 'png' ? resized().png({ compressionLevel: 9 }) : main.ext === 'webp' ? resized().webp({ quality: 82 }) : resized().jpeg({ quality: 82, mozjpeg: true }), `${name}.${main.ext}`); const sizes: Sizes = []; for (const w of WIDTHS) { if (w >= width) continue; await write(img.clone().resize({ width: w }).webp({ quality: 78 }), `${name}-${w}.webp`); await write(img.clone().resize({ width: w }).flatten({ background: '#ffffff' }).jpeg({ quality: 80, mozjpeg: true }), `${name}-${w}.jpg`); sizes.push({ w, webp: `${name}-${w}.webp`, jpg: `${name}-${w}.jpg` }); } return { main, width, height, sizes, files }; }