Manage request files: mark missing ones, remove them, list them all

Forms → Content requests and a new Tools → Media → Requests tab (by
type folder, each linked to its request) mark a file Drive no longer
has under Requests as Missing from Drive. Remove (admins and up)
trashes a file and takes it off its request. Drive is asked at most
every 30 seconds, and folder lookups now cache every level walked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-29 23:25:58 -05:00
parent 9ff1cd6e99
commit e1542d8d87
6 changed files with 292 additions and 32 deletions

View file

@ -143,7 +143,12 @@ export function forgetFolders(path) {
async function findOrMakeFolder(path) {
const drive = process.env.GOOGLE_SHARED_DRIVE;
let parent = drive;
const walked = [];
for (const name of path.split("/").filter(Boolean)) {
// Each level on the way is known too: "Requests" once
// "Requests/Chapters" has been found.
if (walked.length && !folders.has(walked.join("/"))) folders.set(walked.join("/"), Promise.resolve(parent));
walked.push(name);
const quoted = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const query = new URLSearchParams({
q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`,

View file

@ -11,7 +11,8 @@
import { Hono } from "hono";
import { requireAuth, requireRole } from "../auth.js";
import { NO_STORE } from "../shape.js";
import { driveDelete, driveDownload } from "../googleService.js";
import { driveDelete, driveDownload, driveReady, driveTree } from "../googleService.js";
import { DRIVE_FOLDER, TYPE_FOLDERS } from "./requests.js";
import { HttpError } from "../admin-crud.js";
import { importDocx } from "./import.js";
@ -32,12 +33,31 @@ const KIND_WHERE = {
const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id,
status, admin_note, category, request_action, subject, details`;
/* Each row with its files (content requests), in one query. */
function withFiles(db, rows) {
/* 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, name, mime, size FROM feedback_files
`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));
@ -45,7 +65,9 @@ function withFiles(db, rows) {
...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, ...f }) => f),
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;
@ -62,7 +84,7 @@ const NOTE_LIMIT = 2000;
?limit=50
───────────────────────────────────────────────────────────── */
admin.get("/feedback", (c) => {
admin.get("/feedback", async (c) => {
const db = c.get("db");
const { status, type, kind, q, before, limit } = c.req.query();
@ -102,7 +124,7 @@ admin.get("/feedback", (c) => {
.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);
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
@ -172,7 +194,7 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
const result = db_update(c.get("db"), id, sets, params);
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}`);
@ -180,14 +202,14 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
return c.json({ feedback: result }, 200, NO_STORE);
});
function db_update(db, id, sets, params) {
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)])[0];
return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)], ids)[0];
}
/* ── DELETE /api/admin/feedback/:id ──────────────────────────────
@ -221,9 +243,13 @@ admin.delete("/feedback/:id", requireRole("admin"), async (c) => {
});
/* ── 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
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
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) {
@ -270,4 +296,45 @@ admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async (
}
});
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;

View file

@ -65,8 +65,8 @@ export function cleanDetails(raw) {
const MIN_MESSAGE = 10;
// Where in the shared drive the files go (googleService.js): a
// folder per type under Requests, eg. Requests/Chapters.
const DRIVE_FOLDER = "Requests";
const TYPE_FOLDERS = {
export const DRIVE_FOLDER = "Requests";
export const TYPE_FOLDERS = {
blog: "Blog Posts",
event: "Events",
chapter: "Chapters",