diff --git a/CLAUDE.md b/CLAUDE.md index 8b009f1..eca7b75 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,7 +37,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - Word import: Blog posts → Import from Word turns a .docx into an unpublished post (headings, paragraphs, lists, tables, links); nginx needs a block for `/api/admin/import/docx` with an 11m body limit: `docs/importing.md`. - Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`. - Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`. -- Request form (`/request`): files go to the "Requests" folder of a Google shared drive and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`). `driveUpload(folder, ...)` finds or makes the named folder in the shared drive, so other uses get their own folder. Tools → Media → Files uploads to "Media" and shares each file as anyone-with-the-link (`server/src/routes/files.js`, migration 048); link fields with `files: true` pick from it ("Choose a file"), and link cards take its first-page preview. Needs a `/api/admin/files` nginx block (51m). Off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_SHARED_DRIVE` (the bare id, not a URL) / `GOOGLE_MAIL_FROM` are set. Needs its own nginx block. Setup: `docs/google-drive-and-mail.md`. +- Request form (`/request`): files go to the "Requests" folder of a Google shared drive and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`). `driveUpload(folder, ...)` finds or makes the named folder in the shared drive, so other uses get their own folder. Tools → Media → Files uploads to "Blog" and shares each file as anyone-with-the-link (`server/src/routes/files.js`, migration 048); link fields with `files: true` pick from it ("Choose a file"), and link cards take its first-page preview. Needs a `/api/admin/files` nginx block (51m). Off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_SHARED_DRIVE` (the bare id, not a URL) / `GOOGLE_MAIL_FROM` are set. Needs its own nginx block. Setup: `docs/google-drive-and-mail.md`. - Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Accounts made by admin-cli get in; with access groups set (Site settings → Access, plus `GOOGLE_DIRECTORY_AS`), anyone in one gets a Google-only account whose role follows the group, rechecked at sign-in, hourly and by Panel → Re-sync now (`server/src/accessGroups.js`); superadmins and admin-cli accounts are never changed by groups. Passwords still work. Setup: `docs/google-sign-in.md`. ## Git workflow diff --git a/docs/google-drive-and-mail.md b/docs/google-drive-and-mail.md index c105d45..f61183b 100644 --- a/docs/google-drive-and-mail.md +++ b/docs/google-drive-and-mail.md @@ -3,7 +3,7 @@ The site keeps files in one Google **shared drive**: the Request form (`/request`) puts what people send in its "Requests" folder, and files uploaded in Tools → Media → Files, for pages to link to, go in its -"Media" folder (see "Files for pages" below). New requests can be emailed to whoever is listed in +"Blog" folder (see "Files for pages" below). New requests can be emailed to whoever is listed in Panel → Site settings → Notices. Both go through one Google **service account** (`server/src/googleService.js`). Nothing here is needed for the rest of the site; until it's set up, the form takes no files and no @@ -61,16 +61,12 @@ 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` | +| `Blog` | Files for pages to link to (Tools → Media → Files) | `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 +`server/src/googleService.js`; a path such as `"Blog/2026"` makes each level. Add it to this table. -Files for pages went in a folder called `Blog` before v1.9.10. If the -shared drive has one, rename it to `Media` in Drive: the files inside -keep working and stay listed, and nothing is made twice. - Folders are matched by name, so renaming or moving one in Drive makes the site start a new one under the old name (files already stored keep working: they're found by their own id). People can add their own @@ -177,7 +173,7 @@ from it"), the same conversion as Blog posts → Import from Word ## Files for pages Tools → Media → **Files** (editors and up upload, admins and up delete) -puts a file in the shared drive's `Media` folder and shares it as +puts a file in the shared drive's `Blog` folder and shares it as **anyone with the link can view**, so visitors open it in Drive's viewer without signing in. Content block links pick from it with **Choose a file**: paragraph, button and image links, list and link-button items, @@ -193,24 +189,10 @@ Drive" above the title. little after upload. The server asks at once and again over the next few minutes, and saves it into the image library as an ordinary upload. Audio and zips get an icon in the admin and no picture. -- **Files put in the Media folder in Drive itself** (dragged in, made - there, moved there) are listed too: opening the Files tab or a - "Choose a file" picker looks in the folder (at most every 30 - seconds), adds anything new, shares it the same way and fetches its - preview. Google's own Docs, Sheets and Slides count; folders inside it - 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 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. -- **"Too large for the web server (HTTP 413)"** on upload (older builds - said "Server did not return JSON", with nothing in the journal): nginx - refused the file before it reached the API, because the site has no - `location = /api/admin/files` block (above), so the 64k `/api/` limit - applies. `sudo tail /var/log/nginx/error.log` shows "client intended - to send too large body". **Sharing has to be allowed.** Uploads fail with "Drive wouldn't share it with anyone who has the link" unless both allow it: diff --git a/server/src/googleService.js b/server/src/googleService.js index 15f5406..dc51e17 100644 --- a/server/src/googleService.js +++ b/server/src/googleService.js @@ -10,7 +10,7 @@ its own), with a folder per use: "Requests" for files sent with the Request form, and so on. Each folder is found by name, or made, the first time it's needed; a path such as - "Media/2026" makes each level. + "Blog/2026" makes each level. Gmail new-request notices, sent as a Workspace user through domain-wide delegation. Groups who is in the admin access groups (accessGroups.js), read @@ -121,7 +121,7 @@ const FOLDER = "application/vnd.google-apps.folder"; const folders = new Map(); /* The id of a folder in the shared drive, eg. "Requests" or - "Media/2026", made if it isn't there. Found by name, so a folder + "Blog/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) { let pending = folders.get(path); @@ -187,31 +187,6 @@ 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); - const found = []; - let pageToken = ""; - do { - const query = new URLSearchParams({ - q: `'${parent}' in parents and trashed = false and mimeType != '${FOLDER}'`, - corpora: "drive", - driveId: process.env.GOOGLE_SHARED_DRIVE, - includeItemsFromAllDrives: "true", - supportsAllDrives: "true", - pageSize: "200", - fields: "nextPageToken,files(id,name,mimeType,size,webViewLink)", - ...(pageToken ? { pageToken } : {}), - }); - const page = await (await call(`${DRIVE}?${query}`, {}, DRIVE_SCOPE)).json(); - found.push(...(page.files ?? [])); - pageToken = page.nextPageToken ?? ""; - } while (pageToken); - return found; -} - /* 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. */ diff --git a/server/src/routes/files.js b/server/src/routes/files.js index 0c72958..0521125 100644 --- a/server/src/routes/files.js +++ b/server/src/routes/files.js @@ -1,10 +1,7 @@ /* ═══════════════════════════════════════════════════════════════ FILE ROUTES: mounted under /api/admin - GET /files the files, newest first, ?q=name. - Picks up files put in the folder - in Drive by hand first (pickUp, at - most every SCAN_EVERY_MS) + GET /files the files, newest first, ?q=name POST /files upload one (multipart: file) GET /files/:id/uses which records link to it DELETE /files/:id out of Drive and the list @@ -20,12 +17,6 @@ again over the next few minutes (PREVIEW_TRIES), and saved into the media library as an ordinary upload when it comes. - Files added to the folder in Drive itself (not through here) are - listed too: the next look at the list finds them, shares them the - same way and fetches their previews. Google's own Docs, Sheets and - Slides count; folders and shortcuts don't. One that Drive won't - share is left out and named in the list's `refused`. - The same ladder as media: reading needs a session, uploading editor, deleting admin. nginx needs a block for POST /files (docs/google-drive-and-mail.md). @@ -35,21 +26,18 @@ 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, driveReady, driveShareWithAnyone, driveThumbnail, driveUpload } from "../googleService.js"; import { addToLibrary, recordsNaming } from "./media.js"; import { NO_STORE } from "../shape.js"; const files = new Hono(); files.use("*", requireAuth); -const FOLDER = "Media"; +const FOLDER = "Blog"; const MAX_FILE_BYTES = 50 * 1024 * 1024; const MAX_LIST = 500; // Seconds after upload to ask Drive for the preview again. const PREVIEW_TRIES = [0, 5, 20, 60, 180]; -// How often listing the files looks in the Drive folder for new ones. -const SCAN_EVERY_MS = 30_000; -const SKIP_TYPES = new Set(["application/vnd.google-apps.folder", "application/vnd.google-apps.shortcut"]); /* What a file is: its first bytes and its name have to agree (Office files are zips, so for them the name is what tells them apart). A @@ -113,52 +101,13 @@ function fetchPreview(db, row, userId) { return next(); } -/* Files put in the folder in Drive by hand, added to the list and - shared. A file Drive won't share is tried again after RETRY_MS, not - on every look (a sharing setting fixed in the meantime then takes). - Never throws: the list still shows what's known. */ -const RETRY_MS = 10 * 60 * 1000; -let lastScan = 0; -const refused = new Map(); // drive id → { name, at } -async function pickUp(db) { - if (!driveReady() || Date.now() - lastScan < SCAN_EVERY_MS) return; - lastScan = Date.now(); - let found; - try { - found = await driveList(FOLDER); - } 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; - if (Date.now() - (refused.get(file.id)?.at ?? 0) < RETRY_MS) continue; - try { - await driveShareWithAnyone(file.id); - } catch (err) { - console.warn(`files: ${file.name} (added in Drive) not shared: ${err.message}`); - refused.set(file.id, { name: file.name, at: Date.now() }); - continue; - } - 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; - 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); - } -} - -files.get("/files", async (c) => { - await pickUp(c.get("db")); +files.get("/files", (c) => { const q = (c.req.query("q") ?? "").trim().slice(0, 100); const rows = 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); + return c.json({ files: rows.map(shape), ready: driveReady() }, 200, NO_STORE); }); files.post( diff --git a/src/components/admin/DriveFiles.tsx b/src/components/admin/DriveFiles.tsx index c81b163..7c6fd22 100644 --- a/src/components/admin/DriveFiles.tsx +++ b/src/components/admin/DriveFiles.tsx @@ -13,8 +13,7 @@ file" (a field with `files: true`, fields.tsx) 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 - folder by hand are listed too (the server picks them up). + else needs to know where it came from. ═══════════════════════════════════════════════════════════════ */ import { @@ -55,19 +54,20 @@ export const FILE_HELP = const ACCEPT = ".pdf,.docx,.xlsx,.pptx,.mp3,.m4a,.zip"; -/* An icon per kind of file; Google's own Docs, Sheets and Slides - (application/vnd.google-apps.*) count as their Office kin. */ -const TYPE_ICONS: [RegExp, typeof FileIcon][] = [ - [/pdf$/, FilePdf], - [/wordprocessing|google-apps\.document$/, FileDoc], - [/spreadsheet/, FileXls], - [/presentation/, FilePpt], - [/^audio\//, FileAudio], - [/zip$/, FileZip], -]; - function TypeIcon({ mime }: { mime: string }) { - const Icon = TYPE_ICONS.find(([test]) => test.test(mime))?.[1] ?? FileIcon; + const Icon = mime === "application/pdf" + ? FilePdf + : mime.includes("wordprocessing") + ? FileDoc + : mime.includes("spreadsheet") + ? FileXls + : mime.includes("presentation") + ? FilePpt + : mime.startsWith("audio/") + ? FileAudio + : mime === "application/zip" + ? FileZip + : FileIcon; return