diff --git a/docs/google-drive-and-mail.md b/docs/google-drive-and-mail.md index c105d45..6b72b78 100644 --- a/docs/google-drive-and-mail.md +++ b/docs/google-drive-and-mail.md @@ -60,8 +60,8 @@ hand. | Folder | Used by | Set in | | --- | --- | --- | -| `Requests` | Files sent with the Request form | `DRIVE_FOLDER` in `server/src/routes/requests.js` | -| `Media` | Files for pages to link to (Tools → Media → Files) | `FOLDER` in `server/src/routes/files.js` | +| `Requests/` | Files sent with the Request form, a folder per type (`Requests/Chapters`, `Requests/Blog posts`...) | `DRIVE_FOLDER` and `TYPE_FOLDERS` in `server/src/routes/requests.js` | +| `Media` and folders in it | Files for pages to link to (Tools → Media → Files), in folders you make there | `FOLDER` in `server/src/routes/files.js` | A new use calls `driveUpload("", name, mime, bytes)` from `server/src/googleService.js`; a path such as `"Media/2026"` makes each @@ -78,7 +78,14 @@ folders to the drive; the site ignores them. Request files are named `Request 12 - original name.docx`, so the number matches the one in Forms → Content requests. Deleting a request in the -admin deletes its files from Drive too. +admin deletes its files from Drive too. Request files from before the +per-type folders stay where they are, in `Requests` itself. + +**Deleting means Drive's trash.** Whatever the admin deletes (a +request's files, a file, an empty folder) goes to the shared drive's +trash, which keeps it 30 days; restore it from there if needed. A +shared drive's Content manager, the service account's role, can trash +but not permanently delete. ## 3. Gmail (domain-wide delegation) @@ -201,7 +208,14 @@ Drive" above the title. and shortcuts don't. A file Drive won't share with anyone who has the link is named in a red note instead of listed, and tried again every ten minutes. -- Deleting a file in the admin deletes it from Drive; the delete says +- **Folders:** Media → Files has a tab per folder under `Media` (up to + three deep), and uploads go into the one showing. **New folder** makes + one inside it, **Rename** renames it (and everything in it follows), + and **Delete** (admins and up) removes it once it's empty. Each file + has a Folder dropdown to move it. Choose a file has the same tabs. A + folder made in Drive itself, and a file moved there by hand, show up + on the next look. +- Deleting a file in the admin moves it to Drive's trash; the delete says first which records still link to it (those links stop working). Deleting it in Drive by hand leaves a broken link and a list entry that can still be deleted. diff --git a/server/src/googleService.js b/server/src/googleService.js index 15f5406..31bf976 100644 --- a/server/src/googleService.js +++ b/server/src/googleService.js @@ -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 ───────────────────────────────────────────────────── */ diff --git a/server/src/migrations/050_drive_file_folders.sql b/server/src/migrations/050_drive_file_folders.sql new file mode 100644 index 0000000..146a8cf --- /dev/null +++ b/server/src/migrations/050_drive_file_folders.sql @@ -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 ''; diff --git a/server/src/routes/files.js b/server/src/routes/files.js index 68e27fd..08388f5 100644 --- a/server/src/routes/files.js +++ b/server/src/routes/files.js @@ -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); diff --git a/server/src/routes/requests.js b/server/src/routes/requests.js index 38c1609..7a4aa98 100644 --- a/server/src/routes/requests.js +++ b/server/src/routes/requests.js @@ -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}`); diff --git a/src/components/admin/DriveFiles.tsx b/src/components/admin/DriveFiles.tsx index 452afd9..ef53e90 100644 --- a/src/components/admin/DriveFiles.tsx +++ b/src/components/admin/DriveFiles.tsx @@ -11,6 +11,9 @@ or an icon for its type FilePicker the dialog behind a link field's "Choose a file" (a field with `files: true`, fields.tsx) + DriveFolderTabs a tab per folder under Media in Drive; both + the picker and the Files tab filter by it, and + upload into the one showing A link field stores the file's Drive link, a plain URL, so nothing else needs to know where it came from. Files put in the Drive @@ -42,10 +45,42 @@ export type DriveFile = { bytes: number; url: string; preview: string | null; + /** Its folder under Media: "" for Media itself. */ + folder: string; uploaded_by: string | null; created_at: string; }; +/* Which tab: every file, Media's own (not in a folder), or a folder's. */ +export const ALL_FOLDERS = "*"; + +export function inFolder(files: DriveFile[], tab: string) { + return tab === ALL_FOLDERS ? files : files.filter((f) => f.folder === tab); +} + +export function DriveFolderTabs({ folders, value, onChange }: { folders: string[]; value: string; onChange: (tab: string) => void }) { + const tabs: [string, string][] = [[ALL_FOLDERS, "All"], ["", "Not in a folder"], ...folders.map((f): [string, string] => [f, f])]; + return ( +
+ {tabs.map(([tab, label]) => ( + + ))} +
+ ); +} + const button = "rounded-full border border-brand px-3 py-1 text-sm font-medium text-link " + "transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50"; @@ -75,6 +110,7 @@ function TypeIcon({ mime }: { mime: string }) { export function useDriveFiles(query: string) { const [items, setItems] = useState(null); + const [folders, setFolders] = useState([]); const [ready, setReady] = useState(true); // Files in the Drive folder that Drive wouldn't share publicly. const [refused, setRefused] = useState([]); @@ -86,6 +122,7 @@ export function useDriveFiles(query: string) { get(`/admin/files${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 }) .then((data) => { setItems(data.files); + setFolders(data.folders ?? []); setReady(data.ready); setRefused(data.refused ?? []); }) @@ -93,12 +130,21 @@ export function useDriveFiles(query: string) { }, [query]); useEffect(reload, [reload]); - return { items, ready, refused, error, reload, setItems }; + return { items, folders, ready, refused, error, reload, setItems }; } /* ── Upload ──────────────────────────────────────────────────── */ -export function FileUploadButton({ onUploaded, label = "Upload files" }: { onUploaded: (file: DriveFile) => void; label?: string }) { +export function FileUploadButton({ + onUploaded, + label = "Upload files", + folder = "", +}: { + onUploaded: (file: DriveFile) => void; + label?: string; + /** Under Media; "" for Media itself. */ + folder?: string; +}) { const inputRef = useRef(null); const [busy, setBusy] = useState(null); const [error, setError] = useState(null); @@ -112,6 +158,7 @@ export function FileUploadButton({ onUploaded, label = "Upload files" }: { onUpl setBusy(file.name); const form = new FormData(); form.append("file", file); + form.append("folder", folder); try { onUploaded((await upload("/admin/files", form)).file); } catch (err) { @@ -206,7 +253,8 @@ export function FilePicker({ }) { const { user } = useAuth(); const [query, setQuery] = useState(""); - const { items, ready, refused, error, setItems } = useDriveFiles(query); + const { items, folders, ready, refused, error, setItems } = useDriveFiles(query); + const [tab, setTab] = useState(ALL_FOLDERS); const dialogRef = useRef(null); useEffect(() => { @@ -247,10 +295,17 @@ export function FilePicker({ + {folders.length > 0 && ( +
+ +
+ )} + {roleCanWrite(user) && ready && (
{ setItems((current) => [file, ...(current ?? [])]); pick(file); @@ -268,7 +323,7 @@ export function FilePicker({ ) : items === null ? (

Loading…

) : ( - + )}
diff --git a/src/pages/admin/AdminMedia.tsx b/src/pages/admin/AdminMedia.tsx index 842558d..2f91851 100644 --- a/src/pages/admin/AdminMedia.tsx +++ b/src/pages/admin/AdminMedia.tsx @@ -17,15 +17,19 @@ import { useState } from "react"; -import { ApiError, del, get } from "../../lib/api.ts"; +import { ApiError, del, get, patch, post } from "../../lib/api.ts"; import { useAuth } from "../../lib/auth.tsx"; import { canDelete, canWrite as roleCanWrite } from "../../lib/roles.ts"; import { + ALL_FOLDERS, + DriveFolderTabs, FILE_HELP, FileList, FileUploadButton, RefusedNote, + inFolder, useDriveFiles, + type DriveFile, } from "../../components/admin/DriveFiles.tsx"; import { FolderTabs, @@ -141,17 +145,153 @@ function CopyPath({ url, label = "Copy path" }: { url: string; label?: string }) ); } +/* The folder showing: make one inside it, rename it, or delete it + when it's empty. Drive is the source; the list reloads after. */ +function FolderControls({ tab, onChanged }: { tab: string; onChanged: (tab: string) => void }) { + const { user } = useAuth(); + const [mode, setMode] = useState<"new" | "rename" | null>(null); + const [name, setName] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const inside = tab === ALL_FOLDERS ? "" : tab; + const button = "rounded-full border border-brand px-3 py-1 text-xs font-medium text-link transition-colors hover:bg-tint disabled:opacity-50"; + + async function run(work: () => Promise) { + setBusy(true); + setError(null); + try { + onChanged(await work()); + setMode(null); + setName(""); + } catch (err) { + setError(err instanceof ApiError ? err.message : "Couldn't reach the server."); + } finally { + setBusy(false); + } + } + const submit = () => + run(async () => + mode === "new" + ? (await post("/admin/files/folders", { path: inside ? `${inside}/${name}` : name })).path + : (await patch("/admin/files/folders", { path: inside, name })).path, + ); + const remove = () => + run(async () => { + await del(`/admin/files/folders?path=${encodeURIComponent(inside)}`); + return inside.split("/").slice(0, -1).join("/") || ALL_FOLDERS; + }); + + if (!roleCanWrite(user)) return null; + return ( +
+ {mode ? ( + <> + + setName(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && name.trim()) submit(); + if (e.key === "Escape") setMode(null); + }} + placeholder={mode === "new" ? "New folder's name" : "New name"} + className="rounded-lg border border-muted/25 bg-surface px-3 py-1 text-sm text-body outline-none focus:border-brand" + /> + + + + ) : ( + <> + + {inside && ( + + )} + {inside && canDelete(user) && ( + + )} + + )} + {error && {error}} +
+ ); +} + +/* A file's folder, changed in place. */ +function MoveControl({ file, folders, onMoved }: { file: DriveFile; folders: string[]; onMoved: (file: DriveFile) => void }) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + return ( +
+ + {error &&

{error}

} +
+ ); +} + function FilesTab() { const { user } = useAuth(); const [query, setQuery] = useState(""); - const { items, ready, refused, error, setItems } = useDriveFiles(query); + const { items, folders, ready, refused, error, reload, setItems } = useDriveFiles(query); + const [tab, setTab] = useState(ALL_FOLDERS); + const replace = (file: DriveFile) => setItems((current) => (current ?? []).map((f) => (f.id === file.id ? file : f))); return ( <>
{roleCanWrite(user) && ready && (
- setItems((current) => [file, ...(current ?? [])])} /> + setItems((current) => [file, ...(current ?? [])])} + />

{FILE_HELP}

)} @@ -168,6 +308,19 @@ function FilesTab() { Google Drive isn't set up on the server (docs/google-drive-and-mail.md), so files can't be uploaded.

)} + {ready && ( +
+ + { + setTab(next); + reload(); + }} + /> +
+ )} +
{error ? ( @@ -176,9 +329,10 @@ function FilesTab() {

Loading…

) : ( (
+ {roleCanWrite(user) && } Open in Drive