website 1.11.0: layouts and backgrounds for the blocks; a video for the top of the page

- Blocks get layouts (BLOCK_VARIANTS: text standard/centred; image and text photo left,
  right or above; quote centred/with a line; call to action centred/banner), stored on
  Section.variant and checked against the type; an unknown one draws as the default, as
  every block looked before. The demo's image-text block id is now image-left.
- Each block has its own background (Section.background, migration
  20261201000000_block_background), in the published source only when set, put back by
  Discard and Restore, drawn as the homepage's (data-bg).
- MP4 uploads up to 20 MB for the hero's Video layout: QuickTime refused, metadata boxes
  (udta, meta, uuid) blanked into free boxes of the same size so where it was filmed is
  gone and the frame offsets hold; size read from tkhd. GET /media lists mime.
- Admin: a block's Layout and Background when open; the hero's Video field (only videos;
  photo fields only photos); the media library shows and takes videos. An upload over the
  limit says so instead of "That request isn't valid."
- Tests: backend (152, three new); e2e for block layouts and a video upload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 09:57:02 +02:00
co-authored by Claude Opus 5.5
parent a38468ba47
commit f5f778f0d7
28 changed files with 543 additions and 69 deletions
+91 -2
View File
@@ -21,11 +21,21 @@ import { audit } from '../lib/audit.js';
import { mediaUrl } from '../site/snapshot.js';
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
/**
* A video for the top of the page's Video layout: a short muted loop, so 20 MB is plenty, and it
* stays under the installers' nginx `client_max_body_size 25m`.
*/
export const MAX_VIDEO_BYTES = 20 * 1024 * 1024;
/** The most the upload route reads, photo or video. */
export const MAX_BODY_BYTES = Math.max(MAX_UPLOAD_BYTES, MAX_VIDEO_BYTES);
type Kind = { ext: string; mime: string };
/** What the bytes are, whatever the name says. */
export function sniff(b: Buffer): Kind | null {
// An ISO media file (MP4): its first box is `ftyp`. QuickTime (.mov, brand `qt `) is left out:
// browsers other than Safari often can't play it.
if (b.length > 12 && b.toString('ascii', 4, 8) === 'ftyp') return b.toString('ascii', 8, 12) === 'qt ' ? { ext: 'mov', mime: 'video/quicktime' } : { ext: 'mp4', mime: 'video/mp4' };
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' };
@@ -78,9 +88,10 @@ export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defa
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.');
if (kind?.mime.startsWith('video/')) return uploadVideo(ctx, body, kind, alt, by);
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.');
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP, or a video as MP4.');
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. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.');
@@ -102,6 +113,84 @@ export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
return { ...row, url: mediaUrl(row.filename) };
}
/**
* A video (MP4), kept as uploaded apart from its metadata (cleanVideo), with no other sizes: the
* site plays it as it is. Counted towards storage like a photo.
*/
async function uploadVideo(ctx: Ctx, body: Buffer, kind: Kind, alt: string, by: string) {
if (kind.ext !== 'mp4') throw new ApiError(415, 'NOT_MP4', 'That video is a QuickTime (.mov) file, which most browsers can\'t play. Save or export it as MP4 and try again.');
if (body.length > MAX_VIDEO_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That video is larger than 20 MB. Use a shorter clip (10 to 20 seconds is plenty for a loop), or make it smaller, and try again.');
const clean = cleanVideo(body);
if (!clean) throw new ApiError(415, 'NOT_A_VIDEO', 'That video can\'t be read. Save it again as MP4 and try again.');
const s = await storage(ctx);
if (s.usedBytes + clean.bytes.length > s.limitBytes) {
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.');
}
const now = ctx.now();
const filename = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.mp4`;
const dir = uploadDir(ctx);
await fs.mkdir(path.join(dir, path.dirname(filename)), { recursive: true });
await fs.writeFile(path.join(dir, filename), clean.bytes);
const row = await ctx.db.mediaAsset.create({
data: { filename, mime: kind.mime, bytes: clean.bytes.length, width: clean.width, height: clean.height, alt: alt.trim().slice(0, 500), sizes: [] as never, uploadedBy: by },
});
return { ...row, url: mediaUrl(row.filename) };
}
/** Boxes that hold a video's own boxes, which are searched for metadata. */
const VIDEO_CONTAINERS = new Set(['moov', 'trak', 'mdia', 'minf', 'edts']);
/** Boxes that hold metadata: where and when it was filmed (`©xyz`, Apple's location keys), the camera, XMP. */
const VIDEO_METADATA = new Set(['udta', 'meta', 'uuid']);
/**
* An MP4 without its metadata, as photos lose theirs (a phone video can carry the place it was
* filmed): every metadata box is turned into a `free` box of the same size, filled with zeros, so
* nothing moves and the offsets to the frames stay right. Also reads the picture's size from the
* first video track (`tkhd`). Null when the boxes don't add up or there's no `moov` (not a video).
*/
export function cleanVideo(input: Buffer): { bytes: Buffer; width: number | null; height: number | null } | null {
const b = Buffer.from(input);
let moov = false;
let width: number | null = null;
let height: number | null = null;
const walk = (start: number, end: number, depth: number): boolean => {
let i = start;
while (i < end) {
if (end - i < 8) return false;
let size = b.readUInt32BE(i);
const type = b.toString('latin1', i + 4, i + 8);
let header = 8;
if (size === 1) {
if (end - i < 16) return false;
const big = b.readBigUInt64BE(i + 8);
if (big > BigInt(end - i)) return false;
size = Number(big);
header = 16;
} else if (size === 0) size = end - i;
if (size < header || i + size > end) return false;
if (depth === 0 && type === 'moov') moov = true;
if (VIDEO_METADATA.has(type)) {
b.write('free', i + 4, 'latin1');
b.fill(0, i + header, i + size);
} else if (VIDEO_CONTAINERS.has(type)) {
if (!walk(i + header, i + size, depth + 1)) return false;
} else if (type === 'tkhd' && width === null) {
const v1 = b[i + header] === 1;
const at = i + header + (v1 ? 88 : 76);
if (at + 8 <= i + size) {
const w = b.readUInt32BE(at) >>> 16;
const h = b.readUInt32BE(at + 4) >>> 16;
if (w > 0 && h > 0) [width, height] = [w, h];
}
}
i += size;
}
return true;
};
if (!walk(0, b.length, 0) || !moov) return null;
return { bytes: b, width, height };
}
export const MAX_WIDTH = 2400;
export const WIDTHS = [480, 960, 1600] as const;