Add Drive folders: per request type, and managed from the Media page

Request files go in Requests/<type> (Chapters, Events...). Media →
Files shows a tab per folder under Media, up to three deep, and can
make, rename (files follow) and delete empty folders, move a file with
its Folder dropdown, and upload into the folder showing; Choose a file
has the same tabs. A folder made, or a file moved, in Drive by hand is
followed on the next look (migration 050 records each file's folder).

Deletes now move to Drive's trash: a shared drive's Content manager,
the service account's role, can't delete outright, so request and file
deletes would have failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-29 22:34:27 -05:00
parent 9854da965e
commit 7f05076a86
7 changed files with 479 additions and 38 deletions

View file

@ -5,9 +5,19 @@
Picks up files put in the folder
in Drive by hand first (pickUp, at
most every SCAN_EVERY_MS)
POST /files upload one (multipart: file)
POST /files upload one (multipart: file, folder)
PATCH /files/:id { folder }: move it to another folder
GET /files/:id/uses which records link to it
DELETE /files/:id out of Drive and the list
DELETE /files/:id into Drive's trash, out of the list
POST /files/folders { path }: make a folder
PATCH /files/folders { path, name }: rename one
DELETE /files/folders?path= delete an empty one
Folders: under FOLDER, at most MAX_DEPTH deep, named by a path
relative to it ('' is FOLDER itself, 'Slides/2026' below it). The
list's `folders` are every one Drive has there, so one made in
Drive by hand shows up too.
Files for the public site to link to, kept in the shared drive's
FOLDER (googleService.js) and shared as "anyone with the link can
@ -35,7 +45,19 @@ import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import { driveDelete, driveList, driveReady, driveShareWithAnyone, driveThumbnail, driveUpload } from "../googleService.js";
import {
driveDelete,
driveFolder,
driveFolderEmpty,
driveMove,
driveReady,
driveRename,
driveShareWithAnyone,
driveThumbnail,
driveTree,
driveUpload,
forgetFolders,
} from "../googleService.js";
import { addToLibrary, recordsNaming } from "./media.js";
import { publicPath } from "../media.js";
import { NO_STORE } from "../shape.js";
@ -44,6 +66,20 @@ const files = new Hono();
files.use("*", requireAuth);
const FOLDER = "Media";
const MAX_DEPTH = 3;
/* A folder path as given, cleaned: '' for FOLDER itself, or up to
MAX_DEPTH names of 1 to 60 characters, none of them "." or "..",
joined by "/". null when it can't be one. */
export function cleanFolder(value) {
const parts = String(value ?? "")
.split("/")
.map((part) => part.replace(/[\u0000-\u001f\\]+/g, " ").trim())
.filter(Boolean);
if (parts.length > MAX_DEPTH || parts.some((part) => part.length > 60 || part === "." || part === "..")) return null;
return parts.join("/");
}
const inDrive = (folder) => (folder ? `${FOLDER}/${folder}` : FOLDER);
const MAX_FILE_BYTES = 50 * 1024 * 1024;
const MAX_LIST = 500;
// Seconds after upload to ask Drive for the preview again.
@ -89,6 +125,7 @@ const shape = (row) => ({
bytes: row.bytes,
url: row.url,
preview: row.preview,
folder: row.folder,
uploaded_by: row.uploaded_by_name ?? row.uploaded_by_email ?? null,
created_at: row.created_at,
});
@ -120,20 +157,29 @@ function fetchPreview(db, row, userId) {
Never throws: the list still shows what's known. */
const RETRY_MS = 10 * 60 * 1000;
let lastScan = 0;
let folderPaths = [];
const refused = new Map(); // drive id → { name, at }
async function pickUp(db) {
if (!driveReady() || Date.now() - lastScan < SCAN_EVERY_MS) return;
async function pickUp(db, force = false) {
if (!driveReady() || (!force && Date.now() - lastScan < SCAN_EVERY_MS)) return;
lastScan = Date.now();
let found;
let tree;
try {
found = await driveList(FOLDER);
tree = await driveTree(FOLDER, MAX_DEPTH);
} catch (err) {
console.warn(`files: couldn't list the ${FOLDER} folder: ${err.message}`);
return;
}
const known = new Set(db.prepare(`SELECT drive_id FROM drive_files`).all().map((r) => r.drive_id));
for (const file of found) {
if (known.has(file.id) || SKIP_TYPES.has(file.mimeType)) continue;
folderPaths = tree.folders.map((f) => f.path).filter(Boolean).sort((a, b) => a.localeCompare(b));
const known = new Map(db.prepare(`SELECT drive_id, folder FROM drive_files`).all().map((r) => [r.drive_id, r.folder]));
for (const file of tree.files) {
// Moved in Drive by hand: follow it.
if (known.has(file.id)) {
if (known.get(file.id) !== file.folder) {
db.prepare(`UPDATE drive_files SET folder = ? WHERE drive_id = ?`).run(file.folder, file.id);
}
continue;
}
if (SKIP_TYPES.has(file.mimeType)) continue;
if (Date.now() - (refused.get(file.id)?.at ?? 0) < RETRY_MS) continue;
try {
await driveShareWithAnyone(file.id);
@ -144,8 +190,8 @@ async function pickUp(db) {
}
refused.delete(file.id);
const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url) VALUES (?, ?, ?, ?, ?)`)
.run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink).lastInsertRowid;
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder) VALUES (?, ?, ?, ?, ?, ?)`)
.run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink, file.folder).lastInsertRowid;
console.log(`files: ${file.name} picked up from Drive`);
// In the background: a folder of new files shouldn't hold the list.
fetchPreview(db, db.prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id), null);
@ -159,7 +205,16 @@ files.get("/files", async (c) => {
.get("db")
.prepare(`${SELECT} ${q ? "WHERE f.name LIKE ?" : ""} ORDER BY f.created_at DESC, f.id DESC LIMIT ${MAX_LIST}`)
.all(...(q ? [`%${q}%`] : []));
return c.json({ files: rows.map(shape), ready: driveReady(), refused: [...refused.values()].map((r) => r.name) }, 200, NO_STORE);
// Every folder Drive has, and any a file names that the last look
// didn't reach (made since, or Drive unreachable).
const folders = [...new Set([...folderPaths, ...rows.map((r) => r.folder).filter(Boolean)])].sort((a, b) =>
a.localeCompare(b),
);
return c.json(
{ files: rows.map(shape), folders, ready: driveReady(), refused: [...refused.values()].map((r) => r.name) },
200,
NO_STORE,
);
});
files.post(
@ -190,10 +245,12 @@ files.post(
return c.json({ error: "Only PDF, Word, Excel, PowerPoint (.docx, .xlsx, .pptx), MP3, M4A and zip files." }, 415);
}
const name = safeName(file.name);
const folder = cleanFolder(body.folder);
if (folder === null) return c.json({ error: "That isn't a folder name." }, 422);
let uploaded;
try {
uploaded = await driveUpload(FOLDER, name, mime, buffer);
uploaded = await driveUpload(inDrive(folder), name, mime, buffer);
} catch (err) {
console.warn(`files: upload of ${name} failed: ${err.message}`);
return c.json({ error: `Google Drive didn't take it: ${err.message}` }, 502);
@ -214,8 +271,8 @@ files.post(
}
const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, uploaded_by) VALUES (?, ?, ?, ?, ?, ?)`)
.run(uploaded.id, name, mime, buffer.length, uploaded.webViewLink, user.id).lastInsertRowid;
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)`)
.run(uploaded.id, name, mime, buffer.length, uploaded.webViewLink, folder, user.id).lastInsertRowid;
const row = db.prepare(`${SELECT} WHERE f.id = ?`).get(id);
console.log(`files: ${name} uploaded by ${user.email}`);
@ -230,6 +287,86 @@ function findOr404(c) {
return Number.isInteger(id) ? c.get("db").prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id) : null;
}
/* ── Folders ────────────────────────────────────────────────── */
const pathOf = async (c, from = "json") => {
const body = from === "json" ? ((await c.req.json().catch(() => null)) ?? {}) : { path: c.req.query("path") };
return { body, path: cleanFolder(body.path) };
};
files.post("/files/folders", requireRole("editor"), async (c) => {
const { path } = await pathOf(c);
if (!path) return c.json({ error: "Give the folder a name." }, 422);
try {
await driveFolder(inDrive(path));
} catch (err) {
return c.json({ error: `Google Drive didn't make it: ${err.message}` }, 502);
}
await pickUp(c.get("db"), true);
console.log(`files: folder ${path} made by ${c.get("user").email}`);
return c.json({ path }, 201, NO_STORE);
});
files.patch("/files/folders", requireRole("editor"), async (c) => {
const { body, path } = await pathOf(c);
const name = cleanFolder(body.name);
if (!path) return c.json({ error: "Which folder?" }, 422);
if (!name || name.includes("/")) return c.json({ error: "Give it a new name (no slashes)." }, 422);
const renamed = [...path.split("/").slice(0, -1), name].join("/");
const db = c.get("db");
try {
await driveRename(await driveFolder(inDrive(path)), name);
} catch (err) {
return c.json({ error: `Google Drive didn't rename it: ${err.message}` }, 502);
}
forgetFolders(inDrive(path));
// The folder and everything under it.
db.prepare(
`UPDATE drive_files SET folder = ? || substr(folder, ?) WHERE folder = ? OR folder LIKE ? ESCAPE '\\'`,
).run(renamed, path.length + 1, path, `${path.replace(/[\\%_]/g, "\\$&")}/%`);
await pickUp(db, true);
console.log(`files: folder ${path} renamed to ${renamed} by ${c.get("user").email}`);
return c.json({ path: renamed }, 200, NO_STORE);
});
files.delete("/files/folders", requireRole("admin"), async (c) => {
const { path } = await pathOf(c, "query");
if (!path) return c.json({ error: "Which folder?" }, 422);
const db = c.get("db");
let id;
try {
id = await driveFolder(inDrive(path));
if (!(await driveFolderEmpty(id))) {
return c.json({ error: "That folder isn't empty: move or delete what's in it first." }, 409);
}
await driveDelete(id);
} catch (err) {
return c.json({ error: `Google Drive didn't delete it: ${err.message}` }, 502);
}
forgetFolders(inDrive(path));
await pickUp(db, true);
console.log(`files: folder ${path} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
files.patch("/files/:id", requireRole("editor"), async (c) => {
const row = findOr404(c);
if (!row) return c.json({ error: "No such file." }, 404);
const body = (await c.req.json().catch(() => null)) ?? {};
const folder = cleanFolder(body.folder);
if (folder === null) return c.json({ error: "That isn't a folder name." }, 422);
if (folder !== row.folder) {
try {
await driveMove(row.drive_id, await driveFolder(inDrive(row.folder)), await driveFolder(inDrive(folder)));
} catch (err) {
return c.json({ error: `Google Drive didn't move it: ${err.message}` }, 502);
}
c.get("db").prepare(`UPDATE drive_files SET folder = ? WHERE id = ?`).run(folder, row.id);
console.log(`files: ${row.name} moved to ${folder || FOLDER} by ${c.get("user").email}`);
}
return c.json({ file: shape(c.get("db").prepare(`${SELECT} WHERE f.id = ?`).get(row.id)) }, 200, NO_STORE);
});
files.get("/files/:id/uses", (c) => {
const row = findOr404(c);
if (!row) return c.json({ error: "No such file." }, 404);

View file

@ -63,8 +63,19 @@ export function cleanDetails(raw) {
return Object.keys(out).length ? out : null;
}
const MIN_MESSAGE = 10;
// Where in the shared drive the files go (googleService.js).
// 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 = {
blog: "Blog posts",
event: "Events",
chapter: "Chapters",
region: "Regions",
partner: "Partners",
team: "Teams",
award: "Awards",
person: "People",
};
export const MAX_FILES = 3;
export const MAX_FILE_BYTES = 10 * 1024 * 1024;
@ -168,7 +179,7 @@ requests.post(
const stored = [];
try {
for (const file of uploads) {
stored.push({ ...file, driveId: (await driveUpload(DRIVE_FOLDER, `Request ${id} - ${file.name}`, file.mime, file.buffer)).id });
stored.push({ ...file, driveId: (await driveUpload(`${DRIVE_FOLDER}/${TYPE_FOLDERS[category]}`, `Request ${id} - ${file.name}`, file.mime, file.buffer)).id });
}
} catch (err) {
console.warn(`feedback #${id}: Drive upload failed: ${err.message}`);