Keep uploaded images in folders by what they're for

logos/ for logo and icon fields, thumbnails/ for previews the site
saves (link previews, Drive first pages), images/ for everything else;
each small copy beside its image. Images from before folders are
sorted once at boot by their uses, and every record naming them is
rewritten in one transaction after the files move.

The Media page and image pickers get a tab per folder; a picker opens
on its field's folder and uploads there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-29 22:29:22 -05:00
parent 4b249c9e52
commit 9854da965e
14 changed files with 283 additions and 51 deletions

View file

@ -38,7 +38,7 @@ import clips from "./routes/clips.js";
import imports from "./routes/import.js";
import files from "./routes/files.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { UPLOADS_DIR, sortIntoFolders, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
@ -57,6 +57,9 @@ syncDescriptorsWithSchema(db, ENTITIES);
console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`);
await mkdir(UPLOADS_DIR, { recursive: true });
console.log(`uploads ${UPLOADS_DIR}`);
// Once: images from before folders into logos/, images/, thumbnails/.
const sorted = await sortIntoFolders(db);
if (sorted) console.log(`uploads: moved ${sorted} image(s) into folders`);
// In the background: pages fall back to the full file until it's done.
writeMissingThumbs()
.then((made) => made && console.log(`uploads: made ${made} small copies`))

View file

@ -30,6 +30,15 @@
Names are random, so two uploads of "logo.png" can't collide
and a filename says nothing about what's in 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), 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
and files from before folders keep a bare name in the root.
sortIntoFolders() moves those older images once, at boot.
── 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
@ -41,6 +50,8 @@
═══════════════════════════════════════════════════════════════ */
import { randomBytes } from "node:crypto";
import { tx } from "./db.js";
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
@ -56,6 +67,42 @@ 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"];
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]));
}
/* 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. */
@ -116,7 +163,7 @@ function sniff(buf) {
and leave nothing behind.
───────────────────────────────────────────────────────────── */
export async function store(buf, { keepOriginal = false } = {}) {
export async function store(buf, { keepOriginal = false, folder } = {}) {
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.`);
@ -164,12 +211,14 @@ export async function store(buf, { keepOriginal = false } = {}) {
throw new MediaError(415, "That image couldn't be read. It may be damaged.");
}
const filename = `${randomBytes(12).toString("hex")}${type.ext}`;
const dir = folderOf(folder);
const base = `${randomBytes(12).toString("hex")}${type.ext}`;
const filename = `${dir}/${base}`;
await mkdir(UPLOADS_DIR, { recursive: true });
await mkdir(path.join(UPLOADS_DIR, dir), { recursive: true });
// 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, `.${filename}.tmp`);
const tmp = path.join(UPLOADS_DIR, dir, `.${base}.tmp`);
await writeFile(tmp, out);
await rename(tmp, path.join(UPLOADS_DIR, filename));
if (kind !== "svg") await writeThumb(filename, out);
@ -200,7 +249,7 @@ export const thumbName = (filename) => `${filename.replace(/\.[^.]+$/, "")}-640.
async function writeThumb(filename, buf) {
const name = thumbName(filename);
const tmp = path.join(UPLOADS_DIR, `.${name}.tmp`);
const tmp = path.join(UPLOADS_DIR, path.dirname(name), `.${path.basename(name)}.tmp`);
try {
await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS })
.rotate()
@ -218,17 +267,11 @@ async function writeThumb(filename, buf) {
/* Makes the small copy for every raster upload that lacks one.
Returns how many it made. */
export async function writeMissingThumbs() {
let names;
try {
names = await readdir(UPLOADS_DIR);
} catch (err) {
if (err.code === "ENOENT") return 0;
throw err;
}
const names = await listStored();
const present = new Set(names);
let made = 0;
for (const name of names) {
if (name.startsWith(".") || THUMB.test(name) || /\.svg$/i.test(name)) continue;
if (THUMB.test(name) || /\.svg$/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) || sniff(buf) === "svg") continue;
@ -242,8 +285,8 @@ export async function writeMissingThumbs() {
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 bare name.
if (path.basename(filename) !== filename) return;
// 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));
@ -292,13 +335,7 @@ async function describe(filename) {
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) {
let names;
try {
names = await readdir(UPLOADS_DIR);
} catch (err) {
if (err.code === "ENOENT") return 0;
throw err;
}
const names = await listStored();
const known = new Set(db.prepare(`SELECT filename FROM media`).all().map((row) => row.filename));
const insert = db.prepare(
@ -309,7 +346,7 @@ export async function registerLooseFiles(db) {
let added = 0;
for (const name of names) {
if (known.has(name) || name.startsWith(".") || THUMB.test(name) || path.basename(name) !== name) continue;
if (known.has(name) || THUMB.test(name) || !isStoredName(name)) continue;
let row;
try {
row = await describe(name);
@ -319,7 +356,7 @@ export async function registerLooseFiles(db) {
if (!row) continue;
const result = insert.run(
row.filename,
row.filename,
path.basename(row.filename),
row.content_type,
row.bytes,
row.width,
@ -331,3 +368,88 @@ export async function registerLooseFiles(db) {
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/.
const LOGO_COLUMNS = new Set(["logo", "org_logo", "event_logo", "favicon", "apple_touch_icon"]);
// Tables whose text never names an upload a page uses.
const NOT_CONTENT = new Set(["media", "admin_users", "sessions", "feedback", "feedback_files", "sqlite_sequence"]);
/* Every image still in the root from before folders, moved into the
folder its uses call for (logos/ if a logo or icon field names it,
thumbnails/ if the site saved it as a preview, else images/), with
every record that names it rewritten to the new path. The files
move first; the rows change in one transaction, and if that fails
the files move back. Returns how many moved; run at boot, and a
no-op once nothing is left in the root. */
export async function sortIntoFolders(db) {
const rows = db
.prepare(
`SELECT id, filename, original_name FROM media
WHERE instr(filename, '/') = 0 AND content_type LIKE 'image/%'`,
)
.all();
if (rows.length === 0) return 0;
const columns = [];
for (const { name: table } of db
.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
.all()) {
if (NOT_CONTENT.has(table)) continue;
for (const col of db.prepare(`SELECT name, type FROM pragma_table_info(?)`).all(table)) {
if (col.type.toUpperCase() === "TEXT") columns.push({ table, column: col.name });
}
}
const namesOf = (filename) => [
...new Set([`${PUBLIC_PREFIX}${filename}`, `${PUBLIC_PREFIX}${encodeURIComponent(filename)}`, filename]),
];
const holds = (table, column, values) =>
db
.prepare(`SELECT 1 FROM "${table}" WHERE "${column}" IN (${values.map(() => "?").join(", ")}) LIMIT 1`)
.get(...values);
const moved = [];
for (const row of rows) {
const values = namesOf(row.filename);
const folder = columns.some(({ table, column }) => LOGO_COLUMNS.has(column) && holds(table, column, values))
? "logos"
: /^preview |\(preview\)$/.test(row.original_name) || holds("drive_files", "preview", values)
? "thumbnails"
: "images";
const to = `${folder}/${row.filename}`;
try {
await mkdir(path.join(UPLOADS_DIR, folder), { recursive: true });
await rename(path.join(UPLOADS_DIR, row.filename), path.join(UPLOADS_DIR, to));
} catch (err) {
// Not on disk (deleted by hand): leave its row as it is.
if (err.code !== "ENOENT") console.warn(`media: couldn't move ${row.filename}: ${err.message}`);
continue;
}
await rename(path.join(UPLOADS_DIR, thumbName(row.filename)), path.join(UPLOADS_DIR, thumbName(to))).catch(() => {});
moved.push({ row, to, values });
}
try {
tx(db, () => {
for (const { row, to, values } of moved) {
db.prepare(`UPDATE media SET filename = ? WHERE id = ?`).run(to, row.id);
for (const { table, column } of columns) {
db.prepare(`UPDATE "${table}" SET "${column}" = ? WHERE "${column}" IN (${values.map(() => "?").join(", ")})`).run(
publicPath(to),
...values,
);
}
}
});
} catch (err) {
for (const { row, to } of moved) {
await rename(path.join(UPLOADS_DIR, to), path.join(UPLOADS_DIR, row.filename)).catch(() => {});
await rename(path.join(UPLOADS_DIR, thumbName(to)), path.join(UPLOADS_DIR, thumbName(row.filename))).catch(() => {});
}
throw err;
}
return moved.length;
}

View file

@ -37,6 +37,7 @@ import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import { driveDelete, driveList, driveReady, driveShareWithAnyone, driveThumbnail, driveUpload } from "../googleService.js";
import { addToLibrary, recordsNaming } from "./media.js";
import { publicPath } from "../media.js";
import { NO_STORE } from "../shape.js";
const files = new Hono();
@ -100,8 +101,8 @@ function fetchPreview(db, row, userId) {
try {
const image = await driveThumbnail(row.drive_id);
if (image) {
const saved = await addToLibrary(db, image, { originalName: `${shape(row).title} (preview)`, userId });
db.prepare(`UPDATE drive_files SET preview = ? WHERE id = ?`).run(`/uploads/${saved.filename}`, row.id);
const saved = await addToLibrary(db, image, { originalName: `${shape(row).title} (preview)`, userId, folder: "thumbnails" });
db.prepare(`UPDATE drive_files SET preview = ? WHERE id = ?`).run(publicPath(saved.filename), row.id);
return;
}
} catch (err) {

View file

@ -2,13 +2,15 @@
MEDIA ROUTES: mounted under /api/admin
GET /media the library, newest first, ?q=name,
?type=image|video|audio.
?type=image|video|audio,
?folder=logos|images|thumbnails.
Picks up images copied into the
uploads folder by hand first
(registerLooseFiles, at most every
SCAN_EVERY_MS)
POST /media upload one image (multipart: file,
keep_original)
keep_original, folder: FOLDERS in
media.js, default images)
GET /media/:id/uses which records name this file
DELETE /media/:id remove the row and the file
POST /link-preview a page's title, description and
@ -29,9 +31,11 @@ import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import {
FOLDERS,
MAX_UPLOAD_BYTES,
MediaError,
PUBLIC_PREFIX,
publicPath,
registerLooseFiles,
remove,
store,
@ -59,7 +63,8 @@ function shape(row) {
id: row.id,
// A hand-copied file keeps its own name, which may need escaping
// in a URL (a space, say); uploads' random names never do.
url: `${PUBLIC_PREFIX}${encodeURIComponent(row.filename)}`,
url: publicPath(row.filename),
folder: row.filename.includes("/") ? row.filename.split("/")[0] : null,
original_name: row.original_name,
content_type: row.content_type,
bytes: row.bytes,
@ -77,8 +82,8 @@ const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_e
/* Writes the file, then its row; a failed insert takes the file
back out so nothing is left on disk that the library can't see. */
export async function addToLibrary(db, buf, { originalName, keepOriginal, userId }) {
const stored = await store(buf, { keepOriginal });
export async function addToLibrary(db, buf, { originalName, keepOriginal, userId, folder }) {
const stored = await store(buf, { keepOriginal, folder });
try {
const { lastInsertRowid } = db
.prepare(
@ -113,7 +118,8 @@ media.get("/media", async (c) => {
// ?type=image (what image fields pick from), video or audio
// (clips saved from Tools → Video clips); none lists everything.
const type = ["image", "video", "audio"].includes(c.req.query("type")) ? c.req.query("type") : null;
const where = [q && "m.original_name LIKE ?", type && "m.content_type LIKE ?"].filter(Boolean);
const folder = FOLDERS.includes(c.req.query("folder")) ? c.req.query("folder") : null;
const where = [q && "m.original_name LIKE ?", type && "m.content_type LIKE ?", folder && "m.filename LIKE ?"].filter(Boolean);
const rows = c
.get("db")
.prepare(
@ -122,7 +128,7 @@ media.get("/media", async (c) => {
ORDER BY m.created_at DESC, m.id DESC
LIMIT ${MAX_LIST}`,
)
.all(...(q ? [`%${q}%`] : []), ...(type ? [`${type}/%`] : []));
.all(...(q ? [`%${q}%`] : []), ...(type ? [`${type}/%`] : []), ...(folder ? [`${folder}/%`] : []));
return c.json({ media: rows.map(shape) }, 200, NO_STORE);
});
@ -151,6 +157,7 @@ media.post(
const row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), {
originalName: file.name,
keepOriginal: body.keep_original === "1",
folder: body.folder,
userId: user.id,
});
@ -179,6 +186,7 @@ media.post("/link-preview", requireRole("editor"), async (c) => {
try {
const row = await addToLibrary(c.get("db"), await fetchImage(page.image), {
originalName: `preview ${new URL(page.image).hostname}`,
folder: "thumbnails",
keepOriginal: false,
userId: user.id,
});
@ -206,6 +214,7 @@ function usesOf(db, filename) {
return recordsNaming(db, [
`${PUBLIC_PREFIX}${filename}`,
`${PUBLIC_PREFIX}${encodeURIComponent(filename)}`,
publicPath(filename),
filename,
]);
}