Add image uploads with a media library, and event card backgrounds
Uploads (migration 028, server/src/media.js, routes/media.js): editors and up upload JPEG, PNG, GIF, WebP or SVG. Photos are resized to 2400px and saved as WebP by default, or kept as uploaded on request. Files live in UPLOADS_DIR, served by nginx in production and by the API in dev. Admins and up delete, after seeing what still uses the file. Every image field in the editor is now an image widget: preview, the path as text, Upload and Choose from library. A new Media page lists the library. Org lists and event cards now resolve logos through media.ts, so uploaded paths work there. Events get a card_image (migration 029): a photo behind the card under a light veil so the text stays readable. The card's size is unchanged. Setup for production is in docs/media-uploads.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
cd393e4ab2
commit
eaff23839f
26 changed files with 1234 additions and 22 deletions
181
server/src/routes/media.js
Normal file
181
server/src/routes/media.js
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
MEDIA ROUTES: mounted under /api/admin
|
||||
|
||||
GET /media the library, newest first, ?q=name
|
||||
POST /media upload one image (multipart: file,
|
||||
keep_original)
|
||||
GET /media/:id/uses which records name this file
|
||||
DELETE /media/:id remove the row and the file
|
||||
|
||||
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 { MAX_UPLOAD_BYTES, MediaError, PUBLIC_PREFIX, remove, store } from "../media.js";
|
||||
|
||||
const media = new Hono();
|
||||
|
||||
media.use("*", requireAuth);
|
||||
|
||||
const NO_STORE = { "Cache-Control": "no-store" };
|
||||
|
||||
const MAX_LIST = 500;
|
||||
|
||||
/* 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}`,
|
||||
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`;
|
||||
|
||||
media.get("/media", (c) => {
|
||||
const q = (c.req.query("q") ?? "").trim().slice(0, 100);
|
||||
const rows = c
|
||||
.get("db")
|
||||
.prepare(
|
||||
`${SELECT}
|
||||
${q ? "WHERE m.original_name LIKE ?" : ""}
|
||||
ORDER BY m.created_at DESC, m.id DESC
|
||||
LIMIT ${MAX_LIST}`,
|
||||
)
|
||||
.all(...(q ? [`%${q}%`] : []));
|
||||
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 stored = await store(Buffer.from(await file.arrayBuffer()), {
|
||||
keepOriginal: body.keep_original === "1",
|
||||
});
|
||||
|
||||
let row;
|
||||
try {
|
||||
const { lastInsertRowid } = db
|
||||
.prepare(
|
||||
`INSERT INTO media
|
||||
(filename, original_name, content_type, bytes, width, height, processed, uploaded_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(
|
||||
stored.filename,
|
||||
(file.name || "upload").slice(0, 200),
|
||||
stored.content_type,
|
||||
stored.bytes,
|
||||
stored.width,
|
||||
stored.height,
|
||||
stored.processed,
|
||||
user.id,
|
||||
);
|
||||
row = db.prepare(`${SELECT} WHERE m.id = ?`).get(lastInsertRowid);
|
||||
} catch (err) {
|
||||
await remove(stored.filename);
|
||||
throw err;
|
||||
}
|
||||
|
||||
console.log(`media ${stored.filename} uploaded by ${user.email}`);
|
||||
return c.json({ media: shape(row) }, 201, NO_STORE);
|
||||
},
|
||||
);
|
||||
|
||||
/* Every TEXT column of every content table, searched for the exact
|
||||
path. 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) {
|
||||
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 where = columns.map((col) => `"${col}" = ?`).join(" OR ");
|
||||
const { n } = db
|
||||
.prepare(`SELECT COUNT(*) AS n FROM "${table}" WHERE ${where}`)
|
||||
.get(...columns.map(() => url));
|
||||
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"), `${PUBLIC_PREFIX}${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;
|
||||
Loading…
Add table
Add a link
Reference in a new issue