List files copied into the uploads folder by hand in the media library

The library only knew files uploaded through the admin. Listing it
now registers any image in the uploads folder that has no media row,
under its own name and unprocessed, at most every 30 seconds.
Non-images, dotfiles and temporary names are skipped. The delete
check also counts records that name a file by its bare filename, and
a hand-copied name is escaped in its URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-27 23:53:09 -05:00
parent dad3803ccc
commit 8ec34ea185
3 changed files with 144 additions and 11 deletions

View file

@ -23,6 +23,17 @@ in the `media` table (`server/src/migrations/028_media.sql`).
Limits and sizes are constants at the top of `server/src/media.js`.
## Files copied in by hand
A file put straight into the uploads directory (with `scp`, say) shows
up in the library the next time the Media page or an image picker opens:
the server registers any image it finds there without a record, under
the file's own name, kept as it is (not resized). Anything that isn't a
JPEG, PNG, GIF, WebP or SVG is ignored. A record can name such a file by
its bare filename (eg. `fall-retreat-logo.svg`), which resolves to
`/uploads/<file>`, and the delete check counts those uses too. Keep the
files readable by the `ngu-api` user.
## Local development
The API reads `UPLOADS_DIR` (default `./uploads`, so `server/uploads/`,

View file

@ -29,10 +29,19 @@
Names are random, so two uploads of "logo.png" can't collide
and a filename says nothing about what's in it.
── 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, rename, unlink, writeFile } from "node:fs/promises";
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
@ -182,3 +191,82 @@ export async function remove(filename) {
if (err.code !== "ENOENT") 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 (kind !== "svg") {
try {
const meta = await sharp(buf).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) {
let names;
try {
names = await readdir(UPLOADS_DIR);
} catch (err) {
if (err.code === "ENOENT") return 0;
throw err;
}
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) || name.startsWith(".") || path.basename(name) !== name) continue;
let row;
try {
row = await describe(name);
} catch {
continue;
}
if (!row) continue;
const result = insert.run(
row.filename,
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;
}

View file

@ -1,7 +1,11 @@
/* ═══════════════════════════════════════════════════════════════
MEDIA ROUTES: mounted under /api/admin
GET /media the library, newest first, ?q=name
GET /media the library, newest first, ?q=name.
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)
GET /media/:id/uses which records name this file
@ -23,7 +27,14 @@ import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import { MAX_UPLOAD_BYTES, MediaError, PUBLIC_PREFIX, remove, store } from "../media.js";
import {
MAX_UPLOAD_BYTES,
MediaError,
PUBLIC_PREFIX,
registerLooseFiles,
remove,
store,
} from "../media.js";
import { fetchImage, previewLink } from "../linkPreview.js";
const media = new Hono();
@ -34,13 +45,20 @@ const NO_STORE = { "Cache-Control": "no-store" };
const MAX_LIST = 500;
/* How often listing the library looks in the uploads folder for
files copied there by hand. */
const SCAN_EVERY_MS = 30_000;
let lastScan = 0;
/* Tables that can't hold an image path, or mustn't be searched. */
const NOT_CONTENT = new Set(["media", "admin_users", "sessions", "feedback", "sqlite_sequence"]);
function shape(row) {
return {
id: row.id,
url: `${PUBLIC_PREFIX}${row.filename}`,
// 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)}`,
original_name: row.original_name,
content_type: row.content_type,
bytes: row.bytes,
@ -84,7 +102,12 @@ async function addToLibrary(db, buf, { originalName, keepOriginal, userId }) {
}
}
media.get("/media", (c) => {
media.get("/media", async (c) => {
if (Date.now() - lastScan > SCAN_EVERY_MS) {
lastScan = Date.now();
await registerLooseFiles(c.get("db"));
}
const q = (c.req.query("q") ?? "").trim().slice(0, 100);
const rows = c
.get("db")
@ -168,10 +191,20 @@ media.post("/link-preview", requireRole("editor"), async (c) => {
);
});
/* Every TEXT column of every content table, searched for the exact
path. Read from the live schema rather than a list of image
/* Every TEXT column of every content table, searched for any of the
exact values a record can use to name the file: its /uploads/
path, that path escaped, or (for a file copied in by hand and
typed into a field) its bare name, which media.ts resolves to the
same place. Read from the live schema rather than a list of image
columns, so a new image field is covered the day it's added. */
function usesOf(db, url) {
function usesOf(db, filename) {
const values = [
...new Set([
`${PUBLIC_PREFIX}${filename}`,
`${PUBLIC_PREFIX}${encodeURIComponent(filename)}`,
filename,
]),
];
const tables = db
.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
.all()
@ -188,10 +221,11 @@ function usesOf(db, url) {
if (columns.length === 0) continue;
// Names come from the schema, not the request; quoted anyway.
const where = columns.map((col) => `"${col}" = ?`).join(" OR ");
const marks = values.map(() => "?").join(", ");
const where = columns.map((col) => `"${col}" IN (${marks})`).join(" OR ");
const { n } = db
.prepare(`SELECT COUNT(*) AS n FROM "${table}" WHERE ${where}`)
.get(...columns.map(() => url));
.get(...columns.flatMap(() => values));
if (n > 0) uses.push({ table, count: n });
}
return uses;
@ -208,7 +242,7 @@ function findOr404(c) {
media.get("/media/:id/uses", (c) => {
const row = findOr404(c);
return c.json({ uses: usesOf(c.get("db"), `${PUBLIC_PREFIX}${row.filename}`) }, 200, NO_STORE);
return c.json({ uses: usesOf(c.get("db"), row.filename) }, 200, NO_STORE);
});
media.delete("/media/:id", requireRole("admin"), async (c) => {