feat(website): photos upright, without metadata, in responsive sizes
Every upload is turned upright, stripped of its metadata (EXIF, GPS), kept at most 2400 px wide and saved at 480/960/1600 px in WebP and JPEG; the pages pick the size with <picture> and srcset. Every file counts towards storage; a photo that can't be read is refused. sharp 0.35 (prebuilt, no build step on the servers). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,11 +4,14 @@
|
||||
* `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.
|
||||
* 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';
|
||||
@@ -82,11 +85,63 @@ export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
|
||||
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 } });
|
||||
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` (`<base>.<ext>`, `<base>-<w>.webp`, `<base>-<w>.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 };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user