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

@ -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) => {