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>
367 lines
14 KiB
JavaScript
367 lines
14 KiB
JavaScript
/* ═══════════════════════════════════════════════════════════════
|
|
ADMIN ROUTES
|
|
|
|
Everything under /api/admin requires a session. Writes require
|
|
the 'admin' role; a 'viewer' can read and nothing else.
|
|
|
|
No response from here is cacheable, and none of it should ever
|
|
sit in a proxy.
|
|
═══════════════════════════════════════════════════════════════ */
|
|
|
|
import { Hono } from "hono";
|
|
import { requireAuth, requireRole } from "../auth.js";
|
|
import { NO_STORE } from "../shape.js";
|
|
import { driveDelete, driveDownload, driveReady, driveTree } from "../googleService.js";
|
|
import { DRIVE_FOLDER, TYPE_FOLDERS } from "./requests.js";
|
|
import { addToLibrary, shape as mediaShape } from "./media.js";
|
|
import { HttpError } from "../admin-crud.js";
|
|
import { importDocx } from "./import.js";
|
|
|
|
const admin = new Hono();
|
|
|
|
admin.use("*", requireAuth);
|
|
|
|
|
|
const STATUSES = ["new", "read", "actioned", "archived", "spam"];
|
|
|
|
// Website feedback, data requests and content requests share the
|
|
// table but are three queues in the admin (Forms).
|
|
const KIND_WHERE = {
|
|
feedback: "feedback_type NOT IN ('privacy', 'content')",
|
|
privacy: "feedback_type = 'privacy'",
|
|
content: "feedback_type = 'content'",
|
|
};
|
|
const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id,
|
|
status, admin_note, category, request_action, subject, details`;
|
|
|
|
/* The ids of every file under Requests in Drive (any type folder),
|
|
looked up at most every 30 seconds; null when Drive isn't set up or
|
|
didn't answer, which marks nothing missing. A file someone deleted
|
|
or moved out of Requests in Drive is then "missing". */
|
|
let inDrive = { at: 0, ids: null };
|
|
async function requestFilesInDrive() {
|
|
if (!driveReady()) return null;
|
|
if (Date.now() - inDrive.at < 30_000) return inDrive.ids;
|
|
try {
|
|
const tree = await driveTree(DRIVE_FOLDER, 2);
|
|
inDrive = { at: Date.now(), ids: new Set(tree.files.map((f) => f.id)) };
|
|
} catch (err) {
|
|
console.warn(`feedback: couldn't list ${DRIVE_FOLDER} in Drive: ${err.message}`);
|
|
inDrive = { at: Date.now(), ids: null };
|
|
}
|
|
return inDrive.ids;
|
|
}
|
|
|
|
/* Each row with its files (content requests), in one query. `ids`
|
|
(requestFilesInDrive) says which are still in Drive. */
|
|
function withFiles(db, rows, ids = null) {
|
|
if (rows.length === 0) return rows;
|
|
const files = db
|
|
.prepare(
|
|
`SELECT id, feedback_id, drive_id, name, mime, size FROM feedback_files
|
|
WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`,
|
|
)
|
|
.all(...rows.map((r) => r.id));
|
|
return rows.map((row) => ({
|
|
...row,
|
|
// Stored as JSON text (049); the admin wants the object.
|
|
details: row.details ? JSON.parse(row.details) : null,
|
|
files: files
|
|
.filter((f) => f.feedback_id === row.id)
|
|
.map(({ feedback_id, drive_id, ...f }) => ({ ...f, missing: ids ? !ids.has(drive_id) : false })),
|
|
}));
|
|
}
|
|
const MAX_LIMIT = 200;
|
|
const NOTE_LIMIT = 2000;
|
|
|
|
/* ── GET /api/admin/feedback ─────────────────────────────────────
|
|
?status=new one of STATUSES, or omitted for all
|
|
?kind=feedback website feedback (every type but the two below)
|
|
?kind=privacy data requests from the Privacy page
|
|
?kind=content content requests from /request, with files
|
|
?type=broken feedback_type
|
|
?q=retreat substring of the message
|
|
?before=41 cursor: rows with a lower id than this
|
|
?limit=50
|
|
───────────────────────────────────────────────────────────── */
|
|
|
|
admin.get("/feedback", async (c) => {
|
|
const db = c.get("db");
|
|
const { status, type, kind, q, before, limit } = c.req.query();
|
|
|
|
const where = [];
|
|
const params = [];
|
|
|
|
const kindWhere = KIND_WHERE[kind] ?? null;
|
|
if (kindWhere) where.push(kindWhere);
|
|
|
|
if (STATUSES.includes(status)) {
|
|
where.push("status = ?");
|
|
params.push(status);
|
|
}
|
|
if (type) {
|
|
where.push("feedback_type = ?");
|
|
params.push(type.slice(0, 40));
|
|
}
|
|
if (q) {
|
|
where.push("(message LIKE ? OR subject LIKE ?)");
|
|
params.push(`%${q.slice(0, 100)}%`, `%${q.slice(0, 100)}%`);
|
|
}
|
|
if (before && Number.isInteger(Number(before))) {
|
|
where.push("id < ?");
|
|
params.push(Number(before));
|
|
}
|
|
|
|
const take = Math.max(1, Math.min(Number(limit) || 50, MAX_LIMIT));
|
|
|
|
const rows = db
|
|
.prepare(
|
|
`SELECT ${COLUMNS}
|
|
FROM feedback
|
|
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
|
|
ORDER BY id DESC
|
|
LIMIT ?`,
|
|
)
|
|
.all(...params, take + 1); // one extra to detect a next page
|
|
|
|
const hasMore = rows.length > take;
|
|
const page = withFiles(db, hasMore ? rows.slice(0, take) : rows, kind === "content" ? await requestFilesInDrive() : null);
|
|
|
|
// Status counts cover this queue (kind) but ignore the other
|
|
// filters: the tabs show what's waiting, not what's left after a
|
|
// search. newByKind is what's new in each queue, for the queue tabs.
|
|
const counts = Object.fromEntries(STATUSES.map((s) => [s, 0]));
|
|
for (const row of db
|
|
.prepare(`SELECT status, COUNT(*) AS n FROM feedback ${kindWhere ? `WHERE ${kindWhere}` : ""} GROUP BY status`)
|
|
.all()) {
|
|
counts[row.status] = row.n;
|
|
}
|
|
const newByKind = db
|
|
.prepare(
|
|
`SELECT SUM(${KIND_WHERE.feedback}) AS feedback, SUM(${KIND_WHERE.privacy}) AS privacy,
|
|
SUM(${KIND_WHERE.content}) AS content
|
|
FROM feedback WHERE status = 'new'`,
|
|
)
|
|
.get();
|
|
|
|
return c.json(
|
|
{
|
|
feedback: page,
|
|
counts,
|
|
newByKind: {
|
|
feedback: newByKind?.feedback ?? 0,
|
|
privacy: newByKind?.privacy ?? 0,
|
|
content: newByKind?.content ?? 0,
|
|
},
|
|
nextCursor: hasMore ? page[page.length - 1].id : null,
|
|
},
|
|
200,
|
|
NO_STORE,
|
|
);
|
|
});
|
|
|
|
/* ── PATCH /api/admin/feedback/:id ───────────────────────────────
|
|
{ status?, admin_note? }: either, both, partial.
|
|
───────────────────────────────────────────────────────────── */
|
|
|
|
admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!Number.isInteger(id)) return c.json({ error: "Bad id." }, 400);
|
|
|
|
let body;
|
|
try {
|
|
// `?? {}`: a body of JSON null parses fine and has no fields.
|
|
body = (await c.req.json()) ?? {};
|
|
} catch {
|
|
return c.json({ error: "Expected a JSON body." }, 400);
|
|
}
|
|
|
|
const sets = [];
|
|
const params = [];
|
|
|
|
if (body.status !== undefined) {
|
|
if (!STATUSES.includes(body.status)) {
|
|
return c.json({ error: "Unknown status." }, 422);
|
|
}
|
|
sets.push("status = ?");
|
|
params.push(body.status);
|
|
}
|
|
|
|
if (body.admin_note !== undefined) {
|
|
const note = String(body.admin_note).trim().slice(0, NOTE_LIMIT);
|
|
sets.push("admin_note = ?");
|
|
params.push(note || null);
|
|
}
|
|
|
|
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
|
|
|
|
const result = db_update(c.get("db"), id, sets, params, await requestFilesInDrive());
|
|
if (!result) return c.json({ error: "No such feedback." }, 404);
|
|
|
|
console.log(`feedback #${id} updated by ${c.get("user").email}`);
|
|
|
|
return c.json({ feedback: result }, 200, NO_STORE);
|
|
});
|
|
|
|
function db_update(db, id, sets, params, ids) {
|
|
const changed = db
|
|
.prepare(`UPDATE feedback SET ${sets.join(", ")} WHERE id = ?`)
|
|
.run(...params, id);
|
|
|
|
if (changed.changes === 0) return null;
|
|
|
|
return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)], ids)[0];
|
|
}
|
|
|
|
/* ── DELETE /api/admin/feedback/:id ──────────────────────────────
|
|
Actually gone. Marking something 'spam' is the reversible
|
|
option and should be the habit; this is for the cases where
|
|
the content itself shouldn't stay on disk.
|
|
───────────────────────────────────────────────────────────── */
|
|
|
|
admin.delete("/feedback/:id", requireRole("admin"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!Number.isInteger(id)) return c.json({ error: "Bad id." }, 400);
|
|
|
|
const db = c.get("db");
|
|
const files = db.prepare(`SELECT drive_id FROM feedback_files WHERE feedback_id = ?`).all(id);
|
|
const result = db.prepare("DELETE FROM feedback WHERE id = ?").run(id);
|
|
if (result.changes === 0) return c.json({ error: "No such feedback." }, 404);
|
|
|
|
// The row is gone either way; a file Drive won't delete is logged
|
|
// for someone to remove from the folder by hand.
|
|
for (const { drive_id } of files) {
|
|
try {
|
|
await driveDelete(drive_id);
|
|
} catch (err) {
|
|
console.warn(`feedback #${id}: Drive file ${drive_id} not deleted: ${err.message}`);
|
|
}
|
|
}
|
|
|
|
console.log(`feedback #${id} deleted by ${c.get("user").email}`);
|
|
|
|
return c.body(null, 204);
|
|
});
|
|
|
|
/* ── A content request's files ───────────────────────────────────
|
|
GET /feedback/:id/files/:file download, from Drive
|
|
POST /feedback/:id/files/:file/blog-post a .docx as a new
|
|
unpublished blog post (import.js), editors and up
|
|
POST /feedback/:id/files/:file/to-library { folder }: a photo
|
|
into the media library, for an image field (the picker's
|
|
From requests tab), editors and up
|
|
DELETE /feedback/:id/files/:file into Drive's trash and
|
|
off the request, admins and up
|
|
GET /request-files every request's files,
|
|
by type folder, for Tools → Media → Requests
|
|
───────────────────────────────────────────────────────────── */
|
|
|
|
function fileOf(c) {
|
|
return c
|
|
.get("db")
|
|
.prepare(`SELECT id, drive_id, name, mime FROM feedback_files WHERE id = ? AND feedback_id = ?`)
|
|
.get(Number(c.req.param("file")), Number(c.req.param("id")));
|
|
}
|
|
|
|
async function fromDrive(file) {
|
|
try {
|
|
return await driveDownload(file.drive_id);
|
|
} catch (err) {
|
|
console.warn(`feedback file ${file.id}: Drive download failed: ${err.message}`);
|
|
throw new HttpError(502, "Google Drive didn't send that file. Try again, or find it in the Drive folder.");
|
|
}
|
|
}
|
|
|
|
admin.get("/feedback/:id/files/:file", async (c) => {
|
|
const file = fileOf(c);
|
|
if (!file) return c.json({ error: "No such file." }, 404);
|
|
try {
|
|
return c.body(await fromDrive(file), 200, {
|
|
...NO_STORE,
|
|
"Content-Type": file.mime,
|
|
"Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(file.name)}`,
|
|
"X-Content-Type-Options": "nosniff",
|
|
});
|
|
} catch (err) {
|
|
if (err instanceof HttpError) return c.json({ error: err.message }, err.status);
|
|
throw err;
|
|
}
|
|
});
|
|
|
|
/* A request's photo as an upload: records' images live in the media
|
|
library, not Drive. Once per file: the copy is found again by name. */
|
|
admin.post("/feedback/:id/files/:file/to-library", requireRole("editor"), async (c) => {
|
|
const file = fileOf(c);
|
|
if (!file) return c.json({ error: "No such file." }, 404);
|
|
if (!file.mime.startsWith("image/")) return c.json({ error: "Only a photo (JPEG or PNG) can go in the library." }, 400);
|
|
const db = c.get("db");
|
|
const name = `${file.name} (request ${c.req.param("id")})`.slice(0, 200);
|
|
const known = db.prepare(`SELECT m.* FROM media m WHERE m.original_name = ?`).get(name);
|
|
if (known) return c.json({ media: mediaShape(known) }, 200, NO_STORE);
|
|
try {
|
|
const bytes = await fromDrive(file);
|
|
const body = (await c.req.json().catch(() => null)) ?? {};
|
|
const row = await addToLibrary(db, bytes, { originalName: name, folder: body.folder, userId: c.get("user").id });
|
|
console.log(`feedback #${c.req.param("id")}: ${file.name} into the media library by ${c.get("user").email}`);
|
|
return c.json({ media: mediaShape(row) }, 201, NO_STORE);
|
|
} catch (err) {
|
|
if (err instanceof HttpError) return c.json({ error: err.message }, err.status);
|
|
if (err?.status && err?.message) return c.json({ error: err.message }, err.status); // MediaError
|
|
throw err;
|
|
}
|
|
});
|
|
|
|
admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async (c) => {
|
|
const file = fileOf(c);
|
|
if (!file) return c.json({ error: "No such file." }, 404);
|
|
if (!/\.docx$/i.test(file.name)) return c.json({ error: "Only a Word document (.docx) can become a post." }, 400);
|
|
try {
|
|
return c.json(importDocx(c.get("db"), await fromDrive(file), file.name, c.get("user").email), 201, NO_STORE);
|
|
} catch (err) {
|
|
if (err instanceof HttpError) return c.json({ error: err.message, fields: err.fields }, err.status);
|
|
throw err;
|
|
}
|
|
});
|
|
|
|
admin.delete("/feedback/:id/files/:file", requireRole("admin"), async (c) => {
|
|
const file = fileOf(c);
|
|
if (!file) return c.json({ error: "No such file." }, 404);
|
|
try {
|
|
await driveDelete(file.drive_id);
|
|
} catch (err) {
|
|
// Already gone from Drive: the row goes anyway.
|
|
if (!/^404 /.test(err.message)) return c.json({ error: `Google Drive didn't delete it: ${err.message}` }, 502);
|
|
}
|
|
c.get("db").prepare(`DELETE FROM feedback_files WHERE id = ?`).run(file.id);
|
|
inDrive.ids?.delete(file.drive_id);
|
|
console.log(`feedback #${c.req.param("id")}: file ${file.name} removed by ${c.get("user").email}`);
|
|
return c.body(null, 204);
|
|
});
|
|
|
|
admin.get("/request-files", async (c) => {
|
|
const db = c.get("db");
|
|
const ids = await requestFilesInDrive();
|
|
const rows = db
|
|
.prepare(
|
|
`SELECT f.id, f.feedback_id, f.drive_id, f.name, f.mime, f.size,
|
|
r.category, r.subject, r.request_action, r.status, r.created_at
|
|
FROM feedback_files f JOIN feedback r ON r.id = f.feedback_id
|
|
ORDER BY r.id DESC, f.id`,
|
|
)
|
|
.all();
|
|
return c.json(
|
|
{
|
|
files: rows.map(({ drive_id, ...row }) => ({
|
|
...row,
|
|
folder: TYPE_FOLDERS[row.category] ?? "",
|
|
missing: ids ? !ids.has(drive_id) : false,
|
|
})),
|
|
folders: Object.values(TYPE_FOLDERS),
|
|
checked: ids !== null,
|
|
},
|
|
200,
|
|
NO_STORE,
|
|
);
|
|
});
|
|
|
|
export default admin;
|