NGU-Web/server/src/routes/media.js
Zaldimmar 6ccbc03b52 Let the image picker take photos sent with requests
A From requests tab in every image picker lists photos from the
Request form (they live in Drive), the request being edited from
first. Picking one copies it into the media library, in the field's
folder, once per file, and the field gets that copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:11:01 -05:00

281 lines
9.8 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
MEDIA ROUTES: mounted under /api/admin
GET /media the library, newest first, ?q=name,
?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, 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
preview image, the image saved into
the library ({ url } in, JSON body)
Reading needs a session, uploading needs editor, deleting needs
admin: the same ladder the entity routes use, so an editor can
add images to what they edit but not take one out from under
somebody else's page.
Mounted before the entity routes, whose /:entity would otherwise
claim /media and answer "Unknown entity."
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import {
FOLDERS,
MAX_UPLOAD_BYTES,
MediaError,
PUBLIC_PREFIX,
publicPath,
registerLooseFiles,
remove,
store,
} from "../media.js";
import { fetchImage, previewLink } from "../linkPreview.js";
import { NO_STORE } from "../shape.js";
const media = new Hono();
media.use("*", requireAuth);
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", "drive_files", "admin_users", "sessions", "feedback", "feedback_files", "sqlite_sequence"]);
export function shape(row) {
return {
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: 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,
width: row.width,
height: row.height,
processed: row.processed === 1,
uploaded_by: row.uploaded_by_name ?? row.uploaded_by_email ?? null,
created_at: row.created_at,
};
}
const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_email
FROM media m
LEFT JOIN admin_users u ON u.id = m.uploaded_by`;
/* 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, folder }) {
const stored = await store(buf, { keepOriginal, folder });
try {
const { lastInsertRowid } = db
.prepare(
`INSERT INTO media
(filename, original_name, content_type, bytes, width, height, processed, uploaded_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
stored.filename,
(originalName || "upload").slice(0, 200),
stored.content_type,
stored.bytes,
stored.width,
stored.height,
stored.processed,
userId,
);
return db.prepare(`${SELECT} WHERE m.id = ?`).get(lastInsertRowid);
} catch (err) {
await remove(stored.filename);
throw err;
}
}
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);
// ?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 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(
`${SELECT}
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
ORDER BY m.created_at DESC, m.id DESC
LIMIT ${MAX_LIST}`,
)
.all(...(q ? [`%${q}%`] : []), ...(type ? [`${type}/%`] : []), ...(folder ? [`${folder}/%`] : []));
return c.json({ media: rows.map(shape) }, 200, NO_STORE);
});
media.post(
"/media",
requireRole("editor"),
// A little over the file limit, for the multipart framing.
bodyLimit({
maxSize: MAX_UPLOAD_BYTES + 64 * 1024,
onError: (c) => c.json({ error: "That file is too large." }, 413),
}),
async (c) => {
const db = c.get("db");
const user = c.get("user");
let body;
try {
body = await c.req.parseBody();
} catch {
return c.json({ error: "Expected a file upload." }, 400);
}
const file = body.file;
if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
const row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), {
originalName: file.name,
keepOriginal: body.keep_original === "1",
folder: body.folder,
userId: user.id,
});
console.log(`media ${row.filename} uploaded by ${user.email}`);
return c.json({ media: shape(row) }, 201, NO_STORE);
},
);
/* The page's text comes back whatever happens to the image: a site
whose preview image is missing or refused still has a title. */
media.post("/link-preview", requireRole("editor"), async (c) => {
const user = c.get("user");
let url;
try {
({ url } = (await c.req.json()) ?? {});
} catch {
return c.json({ error: "Expected a JSON body." }, 400);
}
if (typeof url !== "string" || !url.trim()) return c.json({ error: "No link given." }, 400);
const page = await previewLink(url.trim());
let image = null;
let imageError = null;
if (page.image) {
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,
});
image = shape(row);
} catch (err) {
imageError = err instanceof MediaError ? err.message : "The preview image couldn't be saved.";
}
}
console.log(`link preview ${url.trim().slice(0, 200)} by ${user.email}`);
return c.json(
{ preview: { title: page.title, description: page.description, image, image_error: imageError } },
200,
NO_STORE,
);
});
/* 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, filename) {
return recordsNaming(db, [
`${PUBLIC_PREFIX}${filename}`,
`${PUBLIC_PREFIX}${encodeURIComponent(filename)}`,
publicPath(filename),
filename,
]);
}
/* Which content tables have a TEXT column holding exactly one of
`values`: [{ table, count }]. Also how Tools → Media → Files finds
what links to a file (routes/files.js). */
export function recordsNaming(db, values) {
values = [...new Set(values)];
const tables = db
.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
.all()
.map((t) => t.name)
.filter((name) => !NOT_CONTENT.has(name));
const uses = [];
for (const table of tables) {
const columns = db
.prepare(`SELECT name, type FROM pragma_table_info(?)`)
.all(table)
.filter((col) => col.type.toUpperCase() === "TEXT")
.map((col) => col.name);
if (columns.length === 0) continue;
// Names come from the schema, not the request; quoted anyway.
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.flatMap(() => values));
if (n > 0) uses.push({ table, count: n });
}
return uses;
}
function findOr404(c) {
const id = Number(c.req.param("id"));
const row = Number.isInteger(id)
? c.get("db").prepare(`SELECT * FROM media WHERE id = ?`).get(id)
: null;
if (!row) throw new MediaError(404, "No such file.");
return row;
}
media.get("/media/:id/uses", (c) => {
const row = findOr404(c);
return c.json({ uses: usesOf(c.get("db"), row.filename) }, 200, NO_STORE);
});
media.delete("/media/:id", requireRole("admin"), async (c) => {
const row = findOr404(c);
c.get("db").prepare(`DELETE FROM media WHERE id = ?`).run(row.id);
await remove(row.filename);
console.log(`media ${row.filename} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
media.onError((err, c) => {
if (err instanceof MediaError) return c.json({ error: err.message }, err.status, NO_STORE);
console.error(err);
return c.json({ error: "Something went wrong." }, 500);
});
export default media;