Every upload and save (Upload, Frame at, Video thumbnails, a clip's Save to library) has a prefilled Name box; the name is also the readable part of the file's name, plus a short random ending. Fetch preview names its picture after the page. Rename on the Media page changes both, moving the file and its small copy and pointing every record that names it at the new path in one transaction. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
454 lines
18 KiB
JavaScript
454 lines
18 KiB
JavaScript
/* ═══════════════════════════════════════════════════════════════
|
||
MEDIA STORAGE
|
||
|
||
Where uploads go and what happens to them on the way. The routes
|
||
in routes/media.js are HTTP around this; the rules are here.
|
||
|
||
── Where ──
|
||
UPLOADS_DIR, default ./uploads (next to dev.db when run from
|
||
server/). Production sets /var/lib/ngu/uploads, beside the
|
||
database and outside /srv/ngu-api, so a deploy's rsync never
|
||
deletes anyone's photos. Every file is served at
|
||
/uploads/<filename>: by nginx in production, by the API in
|
||
development (see index.js).
|
||
|
||
── What ──
|
||
The type is read from the file's first bytes, never from its
|
||
name or the browser's Content-Type, both of which the uploader
|
||
controls. JPEG, PNG, GIF, WebP and SVG are accepted, and WebVTT
|
||
captions (a text file starting "WEBVTT"); anything else is
|
||
refused.
|
||
|
||
── Processing ──
|
||
By default a raster image is turned upright (EXIF orientation),
|
||
shrunk to fit MAX_EDGE on its longest side, and saved as WebP,
|
||
which also drops its metadata, camera location included.
|
||
`keepOriginal` stores the bytes exactly as uploaded instead,
|
||
under the tighter KEEP_MAX_BYTES. An SVG is always kept as it
|
||
is: it's already small, and rasterizing it would lose the point
|
||
of it. So is a WebVTT file, always into captions/.
|
||
|
||
A stored name is made from the name it's given (the Name box on
|
||
every upload and save), plus a short random ending, so two
|
||
uploads called "Logo" can't collide: 'images/logo-3f9c1a.webp'.
|
||
The ending also means no name can end in -640, the small copies'
|
||
mark. Renaming (renameStored) makes a new stored name and moves
|
||
the file, its small copy and every record naming it to it.
|
||
|
||
── Folders ──
|
||
Each upload goes in a folder by what it's for (FOLDERS): logos/
|
||
for logo and icon fields, thumbnails/ for pictures the site saves
|
||
by itself (link previews, Drive files' first pages), captions/
|
||
for videos' WebVTT files, images/ for the rest. A stored name includes it: 'logos/3f9c….webp', served at
|
||
/uploads/logos/3f9c….webp. The small copy sits beside it. Clips
|
||
keep a bare name in the root.
|
||
|
||
── Files copied in by hand ──
|
||
A file put straight into UPLOADS_DIR has no media row, so the
|
||
library wouldn't know it. registerLooseFiles() gives each image
|
||
it finds one, under the file's own name, unprocessed, uploaded by
|
||
nobody. The Media routes call it when the library is listed. Only
|
||
images are registered (by their bytes, as for an upload); anything
|
||
else, dotfiles and the temporary names store() writes through
|
||
are left alone.
|
||
═══════════════════════════════════════════════════════════════ */
|
||
|
||
import { randomBytes } from "node:crypto";
|
||
|
||
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
|
||
import path from "node:path";
|
||
|
||
import sharp from "sharp";
|
||
|
||
export const UPLOADS_DIR = path.resolve(process.env.UPLOADS_DIR ?? "./uploads");
|
||
|
||
/* The public path an image field stores. media.ts passes anything
|
||
starting with "/" through untouched. */
|
||
export const PUBLIC_PREFIX = "/uploads/";
|
||
|
||
const MB = 1024 * 1024;
|
||
|
||
/* The largest file accepted at all, before processing: room for a
|
||
full-size phone photo. */
|
||
/* Where an upload goes, by what it's for (see Folders above). */
|
||
export const FOLDERS = ["logos", "images", "thumbnails", "captions"];
|
||
export const folderOf = (value) => (FOLDERS.includes(value) ? value : "images");
|
||
|
||
/* A name this library stores: a bare name in the root, or one inside
|
||
a FOLDER. Anything else (a path out, a dotfile) is refused wherever
|
||
a name is joined onto UPLOADS_DIR. */
|
||
export function isStoredName(name) {
|
||
const parts = String(name ?? "").split("/");
|
||
const base = parts[parts.length - 1];
|
||
if (!base || base.startsWith(".") || path.basename(base) !== base) return false;
|
||
return parts.length === 1 || (parts.length === 2 && FOLDERS.includes(parts[0]));
|
||
}
|
||
|
||
/* A name as the readable part of a stored name: lowercase letters,
|
||
digits and hyphens, accents dropped, at most 60 characters.
|
||
Nothing usable (eg. only emoji) gives `fallback`. */
|
||
export function slugify(name, fallback = "file") {
|
||
const slug = String(name ?? "")
|
||
.normalize("NFKD")
|
||
.replace(/[̀-ͯ]/g, "")
|
||
.toLowerCase()
|
||
.replace(/\.[a-z0-9]{2,4}$/, "") // a typed "photo.jpg" keeps its own ending off
|
||
.replace(/[^a-z0-9]+/g, "-")
|
||
.slice(0, 60)
|
||
.replace(/^-+|-+$/g, "");
|
||
return slug || fallback;
|
||
}
|
||
|
||
/* A new stored name in `dir` ('' for the root) for something called
|
||
`name`, ending in `ext` ('.webp'), that no file has yet: writing
|
||
over one would lose it, and a failed save would then delete it. */
|
||
export async function storedNameFor(name, ext, dir = "") {
|
||
for (let tries = 0; tries < 8; tries++) {
|
||
const filename = `${dir ? `${dir}/` : ""}${slugify(name)}-${randomBytes(3).toString("hex")}${ext}`;
|
||
try {
|
||
await stat(path.join(UPLOADS_DIR, filename));
|
||
} catch (err) {
|
||
if (err.code === "ENOENT") return filename;
|
||
throw err;
|
||
}
|
||
}
|
||
throw new MediaError(500, "Couldn't find a free file name. Try again.");
|
||
}
|
||
|
||
/* The public path of a stored name, each part escaped. */
|
||
export const publicPath = (filename) =>
|
||
`${PUBLIC_PREFIX}${String(filename).split("/").map(encodeURIComponent).join("/")}`;
|
||
|
||
/* Every stored file's name: the root's, then each folder's. */
|
||
async function listStored() {
|
||
const names = [];
|
||
for (const dir of ["", ...FOLDERS]) {
|
||
let entries;
|
||
try {
|
||
entries = await readdir(path.join(UPLOADS_DIR, dir), { withFileTypes: true });
|
||
} catch (err) {
|
||
if (err.code === "ENOENT") continue;
|
||
throw err;
|
||
}
|
||
for (const entry of entries) {
|
||
if (entry.isFile() && !entry.name.startsWith(".")) names.push(dir ? `${dir}/${entry.name}` : entry.name);
|
||
}
|
||
}
|
||
return names;
|
||
}
|
||
|
||
export const MAX_UPLOAD_BYTES = 25 * MB;
|
||
|
||
/* The largest file kept as uploaded, unprocessed. */
|
||
export const KEEP_MAX_BYTES = 10 * MB;
|
||
|
||
/* Longest side after processing, in pixels. Wide enough for a
|
||
full-bleed hero on a large screen. */
|
||
// About 60 megapixels (eg. 9000 x 6700): past any camera an editor
|
||
// uses, and it stops one giant image eating the VPS's memory while
|
||
// it's decoded. sharp's own default is 268 MP.
|
||
const MAX_INPUT_PIXELS = 60_000_000;
|
||
const MAX_EDGE = 2400;
|
||
|
||
const WEBP_QUALITY = 82;
|
||
|
||
export class MediaError extends Error {
|
||
constructor(status, message) {
|
||
super(message);
|
||
this.status = status;
|
||
}
|
||
}
|
||
|
||
/* ── Sniffing ──────────────────────────────────────────────── */
|
||
|
||
const TYPES = {
|
||
jpeg: { mime: "image/jpeg", ext: ".jpg" },
|
||
png: { mime: "image/png", ext: ".png" },
|
||
gif: { mime: "image/gif", ext: ".gif" },
|
||
webp: { mime: "image/webp", ext: ".webp" },
|
||
svg: { mime: "image/svg+xml", ext: ".svg" },
|
||
vtt: { mime: "text/vtt", ext: ".vtt" },
|
||
};
|
||
|
||
/* Kinds stored exactly as uploaded, with no small copy: text, not pixels. */
|
||
const AS_IS = new Set(["svg", "vtt"]);
|
||
|
||
function startsWith(buf, bytes, offset = 0) {
|
||
return bytes.every((byte, i) => buf[offset + i] === byte);
|
||
}
|
||
|
||
function sniff(buf) {
|
||
if (startsWith(buf, [0xff, 0xd8, 0xff])) return "jpeg";
|
||
if (startsWith(buf, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "png";
|
||
if (startsWith(buf, [0x47, 0x49, 0x46, 0x38])) return "gif";
|
||
if (startsWith(buf, [0x52, 0x49, 0x46, 0x46]) && startsWith(buf, [0x57, 0x45, 0x42, 0x50], 8)) {
|
||
return "webp";
|
||
}
|
||
|
||
// SVG is text: an optional BOM, XML declaration, comments or a
|
||
// doctype, then an <svg> element. Look at the head only.
|
||
const head = buf.subarray(0, 1024).toString("utf8").replace(/^/, "").trimStart();
|
||
if (/^(<\?xml[\s\S]*?\?>\s*)?(<!--[\s\S]*?-->\s*|<!DOCTYPE[^>]*>\s*)*<svg[\s>]/i.test(head)) {
|
||
return "svg";
|
||
}
|
||
if (/^WEBVTT(\s|$)/.test(head)) return "vtt";
|
||
|
||
return null;
|
||
}
|
||
|
||
/* ── Store ─────────────────────────────────────────────────────
|
||
Writes the file and returns what the media row needs. The row
|
||
itself is the caller's, so a failed insert can call remove()
|
||
and leave nothing behind.
|
||
───────────────────────────────────────────────────────────── */
|
||
|
||
export async function store(buf, { keepOriginal = false, folder, name } = {}) {
|
||
if (buf.length === 0) throw new MediaError(400, "The file is empty.");
|
||
if (buf.length > MAX_UPLOAD_BYTES) {
|
||
throw new MediaError(413, `Files can be at most ${MAX_UPLOAD_BYTES / MB} MB.`);
|
||
}
|
||
|
||
const kind = sniff(buf);
|
||
if (!kind) {
|
||
throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images, and WebVTT (.vtt) captions, can be uploaded.");
|
||
}
|
||
|
||
const convert = !AS_IS.has(kind) && !keepOriginal;
|
||
|
||
if (!convert && buf.length > KEEP_MAX_BYTES) {
|
||
throw new MediaError(
|
||
413,
|
||
`Files kept as uploaded can be at most ${KEEP_MAX_BYTES / MB} MB. ` +
|
||
"Leave the original unticked to have it shrunk instead.",
|
||
);
|
||
}
|
||
|
||
let out = buf;
|
||
let type = TYPES[kind];
|
||
let width = null;
|
||
let height = null;
|
||
|
||
try {
|
||
if (convert) {
|
||
// animated keeps every frame of a GIF or an animated WebP.
|
||
const { data, info } = await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS })
|
||
.rotate()
|
||
.resize({ width: MAX_EDGE, height: MAX_EDGE, fit: "inside", withoutEnlargement: true })
|
||
.webp({ quality: WEBP_QUALITY })
|
||
.toBuffer({ resolveWithObject: true });
|
||
out = data;
|
||
type = TYPES.webp;
|
||
width = info.width;
|
||
// An animated image reports the whole strip's height.
|
||
height = info.pageHeight ?? info.height;
|
||
} else if (!AS_IS.has(kind)) {
|
||
const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata();
|
||
width = meta.width ?? null;
|
||
height = meta.pageHeight ?? meta.height ?? null;
|
||
}
|
||
} catch {
|
||
throw new MediaError(415, "That image couldn't be read. It may be damaged.");
|
||
}
|
||
|
||
const dir = kind === "vtt" ? "captions" : folderOf(folder);
|
||
await mkdir(path.join(UPLOADS_DIR, dir), { recursive: true });
|
||
const filename = await storedNameFor(name, type.ext, dir);
|
||
const base = path.basename(filename);
|
||
// Written under a temporary name and renamed, so a half-written
|
||
// file is never served under its real one.
|
||
const tmp = path.join(UPLOADS_DIR, dir, `.${base}.tmp`);
|
||
await writeFile(tmp, out);
|
||
await rename(tmp, path.join(UPLOADS_DIR, filename));
|
||
if (!AS_IS.has(kind)) await writeThumb(filename, out);
|
||
|
||
return {
|
||
filename,
|
||
content_type: type.mime,
|
||
bytes: out.length,
|
||
width,
|
||
height,
|
||
processed: convert ? 1 : 0,
|
||
};
|
||
}
|
||
|
||
/* ── Small copies ──────────────────────────────────────────────
|
||
Beside every raster upload, <name>-640.webp: the same image at most
|
||
640px on its longer side. Photos and logos shown small (avatars,
|
||
cards, marks) load it instead of the full file; the page falls back
|
||
to the full file if it's missing (src/lib/media.ts, mediaThumb).
|
||
Made when a file is uploaded, and at boot for any upload that
|
||
doesn't have one yet (files from before this, or copied in by hand).
|
||
───────────────────────────────────────────────────────────── */
|
||
|
||
export const THUMB_EDGE = 640;
|
||
const THUMB = /-640\.webp$/;
|
||
|
||
export const thumbName = (filename) => `${filename.replace(/\.[^.]+$/, "")}-640.webp`;
|
||
|
||
async function writeThumb(filename, buf) {
|
||
const name = thumbName(filename);
|
||
const tmp = path.join(UPLOADS_DIR, path.dirname(name), `.${path.basename(name)}.tmp`);
|
||
try {
|
||
await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS })
|
||
.rotate()
|
||
.resize({ width: THUMB_EDGE, height: THUMB_EDGE, fit: "inside", withoutEnlargement: true })
|
||
.webp({ quality: WEBP_QUALITY })
|
||
.toFile(tmp);
|
||
await rename(tmp, path.join(UPLOADS_DIR, name));
|
||
} catch (err) {
|
||
// The full file is what matters; without a copy the page uses it.
|
||
await unlink(tmp).catch(() => {});
|
||
console.warn(`media: no small copy of ${filename}: ${err.message}`);
|
||
}
|
||
}
|
||
|
||
/* Makes the small copy for every raster upload that lacks one.
|
||
Returns how many it made. */
|
||
export async function writeMissingThumbs() {
|
||
const names = await listStored();
|
||
const present = new Set(names);
|
||
let made = 0;
|
||
for (const name of names) {
|
||
if (THUMB.test(name) || /\.(svg|vtt)$/i.test(name)) continue;
|
||
if (present.has(thumbName(name))) continue;
|
||
const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null);
|
||
if (!buf || !sniff(buf) || AS_IS.has(sniff(buf))) continue;
|
||
await writeThumb(name, buf);
|
||
made += 1;
|
||
}
|
||
return made;
|
||
}
|
||
|
||
/* Deletes one stored file and its small copy. A file that's already
|
||
gone is not an error: the row is what's being removed. */
|
||
export async function remove(filename) {
|
||
// filename comes from our own table, but it's joined onto a
|
||
// directory, so refuse anything that isn't a stored name.
|
||
if (!isStoredName(filename)) return;
|
||
for (const name of [filename, thumbName(filename)]) {
|
||
try {
|
||
await unlink(path.join(UPLOADS_DIR, name));
|
||
} catch (err) {
|
||
if (err.code !== "ENOENT") throw err;
|
||
}
|
||
}
|
||
}
|
||
|
||
/* ── Renaming ──────────────────────────────────────────────────
|
||
Moves a stored file (and its small copy) to a new name made
|
||
from `name`, keeping its folder and ending, and returns the new
|
||
stored name. `commit(newName)` writes the database's side (the
|
||
media row and every record naming the file) and must be
|
||
synchronous, so it runs in one transaction; if it throws, the
|
||
files go back where they were.
|
||
───────────────────────────────────────────────────────────── */
|
||
|
||
export async function renameStored(filename, name, commit) {
|
||
if (!isStoredName(filename)) throw new MediaError(400, "That file can't be renamed.");
|
||
const dir = filename.includes("/") ? filename.split("/")[0] : "";
|
||
const ext = path.extname(filename).toLowerCase();
|
||
const next = await storedNameFor(name, ext, dir);
|
||
|
||
const moves = [[filename, next]];
|
||
const thumb = thumbName(filename);
|
||
if (!THUMB.test(filename) && (await stat(path.join(UPLOADS_DIR, thumb)).catch(() => null))) {
|
||
moves.push([thumb, thumbName(next)]);
|
||
}
|
||
|
||
const done = [];
|
||
try {
|
||
for (const [from, to] of moves) {
|
||
await rename(path.join(UPLOADS_DIR, from), path.join(UPLOADS_DIR, to));
|
||
done.push([from, to]);
|
||
}
|
||
commit(next);
|
||
return next;
|
||
} catch (err) {
|
||
for (const [from, to] of done.reverse()) {
|
||
await rename(path.join(UPLOADS_DIR, to), path.join(UPLOADS_DIR, from)).catch((undo) =>
|
||
console.error(`media: couldn't move ${to} back to ${from}: ${undo.message}`),
|
||
);
|
||
}
|
||
if (err.code === "ENOENT") throw new MediaError(404, "The file is missing from the uploads folder.");
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
/* ── Files copied in by hand ─────────────────────────────────── */
|
||
|
||
/* What a file already on disk is: the fields a media row needs, or
|
||
null when it isn't an image this library takes. */
|
||
async function describe(filename) {
|
||
const full = path.join(UPLOADS_DIR, filename);
|
||
const info = await stat(full);
|
||
if (!info.isFile() || info.size === 0 || info.size > MAX_UPLOAD_BYTES) return null;
|
||
|
||
const buf = await readFile(full);
|
||
const kind = sniff(buf);
|
||
if (!kind) return null;
|
||
|
||
let width = null;
|
||
let height = null;
|
||
if (!AS_IS.has(kind)) {
|
||
try {
|
||
const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata();
|
||
width = meta.width ?? null;
|
||
height = meta.pageHeight ?? meta.height ?? null;
|
||
} catch {
|
||
return null; // looks like an image, won't open as one
|
||
}
|
||
}
|
||
|
||
return {
|
||
filename,
|
||
content_type: TYPES[kind].mime,
|
||
bytes: info.size,
|
||
width,
|
||
height,
|
||
processed: 0,
|
||
};
|
||
}
|
||
|
||
/* Gives every image in UPLOADS_DIR without a media row one. Returns
|
||
how many it added. Safe to run often: it only reads the folder
|
||
and the table, and inserts nothing twice (filename is UNIQUE). */
|
||
export async function registerLooseFiles(db) {
|
||
const names = await listStored();
|
||
|
||
const known = new Set(db.prepare(`SELECT filename FROM media`).all().map((row) => row.filename));
|
||
const insert = db.prepare(
|
||
`INSERT OR IGNORE INTO media
|
||
(filename, original_name, content_type, bytes, width, height, processed, uploaded_by)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`,
|
||
);
|
||
|
||
let added = 0;
|
||
for (const name of names) {
|
||
if (known.has(name) || THUMB.test(name) || !isStoredName(name)) continue;
|
||
let row;
|
||
try {
|
||
row = await describe(name);
|
||
} catch {
|
||
continue;
|
||
}
|
||
if (!row) continue;
|
||
const result = insert.run(
|
||
row.filename,
|
||
path.basename(row.filename),
|
||
row.content_type,
|
||
row.bytes,
|
||
row.width,
|
||
row.height,
|
||
row.processed,
|
||
);
|
||
added += result.changes;
|
||
}
|
||
if (added) console.log(`media: registered ${added} file(s) found in ${UPLOADS_DIR}`);
|
||
return added;
|
||
}
|
||
|
||
/* ── Into folders, once ───────────────────────────────────────── */
|
||
|
||
// Columns that hold a logo or a site icon: an image one of these
|
||
// names goes in logos/.
|
||
|