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:
parent
9854da965e
commit
7f05076a86
7 changed files with 479 additions and 38 deletions
|
|
@ -124,6 +124,7 @@ const folders = new Map();
|
|||
"Media/2026", made if it isn't there. Found by name, so a folder
|
||||
renamed in Drive is made again under the old name. */
|
||||
export function driveFolder(path) {
|
||||
path = path.split("/").filter(Boolean).join("/");
|
||||
let pending = folders.get(path);
|
||||
if (!pending) {
|
||||
pending = findOrMakeFolder(path);
|
||||
|
|
@ -133,6 +134,12 @@ export function driveFolder(path) {
|
|||
return pending;
|
||||
}
|
||||
|
||||
/* After a folder is renamed or deleted: its path, and the paths
|
||||
under it, are looked up afresh next time. */
|
||||
export function forgetFolders(path) {
|
||||
for (const key of folders.keys()) if (key === path || key.startsWith(`${path}/`)) folders.delete(key);
|
||||
}
|
||||
|
||||
async function findOrMakeFolder(path) {
|
||||
const drive = process.env.GOOGLE_SHARED_DRIVE;
|
||||
let parent = drive;
|
||||
|
|
@ -187,16 +194,15 @@ export async function driveUpload(folder, name, mime, buffer) {
|
|||
return await res.json();
|
||||
}
|
||||
|
||||
/* The files (not folders) directly in a folder of the shared drive:
|
||||
[{ id, name, mimeType, size, webViewLink }]. size is missing for
|
||||
Google's own Docs, Sheets and Slides. */
|
||||
export async function driveList(folder) {
|
||||
const parent = await driveFolder(folder);
|
||||
/* Everything directly in a folder: [{ id, name, mimeType, size,
|
||||
webViewLink }]. size is missing for Google's own Docs, Sheets and
|
||||
Slides. */
|
||||
async function driveChildren(parent) {
|
||||
const found = [];
|
||||
let pageToken = "";
|
||||
do {
|
||||
const query = new URLSearchParams({
|
||||
q: `'${parent}' in parents and trashed = false and mimeType != '${FOLDER}'`,
|
||||
q: `'${parent}' in parents and trashed = false`,
|
||||
corpora: "drive",
|
||||
driveId: process.env.GOOGLE_SHARED_DRIVE,
|
||||
includeItemsFromAllDrives: "true",
|
||||
|
|
@ -212,6 +218,53 @@ export async function driveList(folder) {
|
|||
return found;
|
||||
}
|
||||
|
||||
/* A folder and the folders under it, down to `depth` levels: the
|
||||
folders' paths (relative to it, "" for itself) and ids, and every
|
||||
file with the path of the folder it's in. */
|
||||
export async function driveTree(path, depth = 3) {
|
||||
const folderList = [{ path: "", id: await driveFolder(path) }];
|
||||
const files = [];
|
||||
for (let i = 0; i < folderList.length; i++) {
|
||||
const here = folderList[i];
|
||||
for (const item of await driveChildren(here.id)) {
|
||||
if (item.mimeType === FOLDER) {
|
||||
const sub = here.path ? `${here.path}/${item.name}` : item.name;
|
||||
if (sub.split("/").length <= depth) {
|
||||
folderList.push({ path: sub, id: item.id });
|
||||
// Known now: no lookup needed to upload into it.
|
||||
const full = `${path}/${sub}`;
|
||||
if (!folders.has(full)) folders.set(full, Promise.resolve(item.id));
|
||||
}
|
||||
} else {
|
||||
files.push({ ...item, folder: here.path });
|
||||
}
|
||||
}
|
||||
}
|
||||
return { folders: folderList, files };
|
||||
}
|
||||
|
||||
/* Whether a folder has anything in it (files or folders). */
|
||||
export async function driveFolderEmpty(id) {
|
||||
return (await driveChildren(id)).length === 0;
|
||||
}
|
||||
|
||||
/* A file or folder from one folder into another. */
|
||||
export async function driveMove(id, fromParent, toParent) {
|
||||
await call(
|
||||
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true&addParents=${encodeURIComponent(toParent)}&removeParents=${encodeURIComponent(fromParent)}`,
|
||||
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: "{}" },
|
||||
DRIVE_SCOPE,
|
||||
);
|
||||
}
|
||||
|
||||
export async function driveRename(id, name) {
|
||||
await call(
|
||||
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`,
|
||||
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) },
|
||||
DRIVE_SCOPE,
|
||||
);
|
||||
}
|
||||
|
||||
/* Anyone with the link can view: for files the public site links to.
|
||||
Refused when the shared drive (or the Workspace) doesn't allow
|
||||
sharing outside the organization. */
|
||||
|
|
@ -244,8 +297,15 @@ export async function driveDownload(id) {
|
|||
return Buffer.from(await res.arrayBuffer());
|
||||
}
|
||||
|
||||
/* Into Drive's trash (a shared drive keeps it 30 days), not deleted
|
||||
outright: a shared drive's Content manager, the service account's
|
||||
role, may trash but not permanently delete. */
|
||||
export async function driveDelete(id) {
|
||||
await call(`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`, { method: "DELETE" }, DRIVE_SCOPE);
|
||||
await call(
|
||||
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`,
|
||||
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ trashed: true }) },
|
||||
DRIVE_SCOPE,
|
||||
);
|
||||
}
|
||||
|
||||
/* ── Gmail ───────────────────────────────────────────────────── */
|
||||
|
|
|
|||
10
server/src/migrations/050_drive_file_folders.sql
Normal file
10
server/src/migrations/050_drive_file_folders.sql
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 050 FOLDERS FOR DRIVE FILES
|
||||
--
|
||||
-- The folder a file is in, under the shared drive's Media folder:
|
||||
-- '' for Media itself, 'Slides' or 'Slides/2026' below it. Made,
|
||||
-- renamed and deleted from Tools → Media → Files (routes/files.js);
|
||||
-- a file moved in Drive by hand is followed on the next look.
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
ALTER TABLE drive_files ADD COLUMN folder TEXT NOT NULL DEFAULT '';
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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}`);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue