/** * 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. * * Responsive sizes (WebP and JPEG per width) come next; for now the file is served as uploaded. */ import crypto from 'node:crypto'; import fs from 'node:fs/promises'; import path from 'node:path'; 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 rel = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.${kind.ext}`; const file = path.join(uploadDir(ctx), rel); await fs.mkdir(path.dirname(file), { recursive: true }); await fs.writeFile(file, body, { mode: 0o644 }); const { width, height } = dimensions(body, kind); const row = await ctx.db.mediaAsset.create({ data: { filename: rel, mime: kind.mime, bytes: body.length, width, height, alt: alt.trim().slice(0, 500), uploadedBy: by } }); return { ...row, url: mediaUrl(row.filename) }; }