From 934598f95438705a7b790fc353b91bf33f74cce8 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Tue, 29 Sep 2026 18:37:15 -0500 Subject: [PATCH] Add a file library in Google Drive for pages to link to MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tools → Media → Files uploads PDF, Office (.docx, .xlsx, .pptx), MP3, M4A and zip files, up to 50 MB, to the shared drive's Blog folder and shares each as anyone with the link can view (migration 048). A file's name and contents must agree. Content block links get "Choose a file" (paragraph, button and image links, list and link items, link cards). A link card also takes the file's name and Drive's picture of its first page, fetched after upload and saved into the image library; cards to Drive say "Google Drive". Deleting a file says first what still links to it. Setup and the nginx block: docs/google-drive-and-mail.md. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/google-drive-and-mail.md | 57 ++++- server/src/googleService.js | 33 ++- server/src/index.js | 2 + server/src/migrations/048_drive_files.sql | 28 +++ server/src/routes/files.js | 203 +++++++++++++++ server/src/routes/media.js | 23 +- server/src/routes/requests.js | 2 +- src/components/ContentBlocks.tsx | 4 +- src/components/admin/DriveFiles.tsx | 286 ++++++++++++++++++++++ src/components/admin/fields.tsx | 23 ++ src/lib/adminSchema/shared.ts | 7 +- src/pages/admin/AdminMedia.tsx | 135 +++++++++- 13 files changed, 772 insertions(+), 33 deletions(-) create mode 100644 server/src/migrations/048_drive_files.sql create mode 100644 server/src/routes/files.js create mode 100644 src/components/admin/DriveFiles.tsx diff --git a/CLAUDE.md b/CLAUDE.md index c641daa..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. 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 74492e0..f61183b 100644 --- a/docs/google-drive-and-mail.md +++ b/docs/google-drive-and-mail.md @@ -1,9 +1,9 @@ -# Google Drive and Gmail (the Request form) +# Google Drive and Gmail The site keeps files in one Google **shared drive**: the Request form -(`/request`) puts what people send in its "Requests" folder, and later -uses (eg. files linked from blog posts) get folders of their own. New -requests can be emailed to whoever is listed in +(`/request`) puts what people send in its "Requests" folder, and files +uploaded in Tools → Media → Files, for pages to link to, go in its +"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,6 +61,7 @@ hand. | Folder | Used by | Set in | | --- | --- | --- | | `Requests` | Files sent with the Request form | `DRIVE_FOLDER` in `server/src/routes/requests.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 `"Blog/2026"` makes each @@ -129,6 +130,14 @@ location = /api/requests { proxy_read_timeout 120s; client_max_body_size 31m; } + +# Tools → Media → Files: one file of up to 50 MB +location = /api/admin/files { + proxy_pass http://127.0.0.1:3001; + # the usual proxy_set_header lines + proxy_read_timeout 180s; + client_max_body_size 51m; +} ``` `sudo nginx -t && sudo systemctl reload nginx && sudo systemctl restart ngu-api`. @@ -160,3 +169,43 @@ checked by their contents rather than their names turned into an unpublished blog post from the queue ("Make a blog post from it"), the same conversion as Blog posts → Import from Word (`docs/importing.md`). + +## Files for pages + +Tools → Media → **Files** (editors and up upload, admins and up delete) +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, +and link cards. A link card also takes the file's name as its title and +Drive's picture of the first page as its picture; the card says "Google +Drive" above the title. + +- Types: PDF, Word, Excel and PowerPoint (.docx, .xlsx, .pptx), MP3, + M4A and zip, up to 50 MB. The name and the contents must agree (a PDF + named `.mp3` is refused). Older Office formats (.doc, .ppt) aren't + taken: save them in the new format first. +- The first-page picture: Drive draws one for PDFs and Office files a + 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. +- 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. + +**Sharing has to be allowed.** Uploads fail with "Drive wouldn't share +it with anyone who has the link" unless both allow it: + +1. Admin console → Apps → Google Workspace → Drive and Docs → Sharing + settings: sharing outside nextgenerationofunity.org is on (at least + for the organizational unit the service account's delegated user is + in, and for shared drives: "Allow people outside ... to access files + in shared drives"). +2. The shared drive itself → Shared drive settings: "Allow people who + aren't shared drive members to access files" and sharing outside the + organization are on. + +Files the Request form stores are never shared this way; only files +uploaded in Tools → Media → Files are. + diff --git a/server/src/googleService.js b/server/src/googleService.js index 9812620..dc51e17 100644 --- a/server/src/googleService.js +++ b/server/src/googleService.js @@ -167,7 +167,7 @@ async function findOrMakeFolder(path) { } /* One file into a folder of the shared drive (driveFolder). Returns - Drive's id for it. */ + { id, webViewLink }: Drive's id, and the page that shows it. */ export async function driveUpload(folder, name, mime, buffer) { const boundary = `ngu${Date.now().toString(36)}`; const meta = JSON.stringify({ name, parents: [await driveFolder(folder)] }); @@ -180,11 +180,38 @@ export async function driveUpload(folder, name, mime, buffer) { Buffer.from(`\r\n--${boundary}--`), ]); const res = await call( - `${DRIVE_UPLOAD}?uploadType=multipart&supportsAllDrives=true&fields=id`, + `${DRIVE_UPLOAD}?uploadType=multipart&supportsAllDrives=true&fields=id,webViewLink`, { method: "POST", headers: { "Content-Type": `multipart/related; boundary=${boundary}` }, body }, DRIVE_SCOPE, ); - return (await res.json()).id; + return await res.json(); +} + +/* 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. */ +export async function driveShareWithAnyone(id) { + await call( + `${DRIVE}/${encodeURIComponent(id)}/permissions?supportsAllDrives=true`, + { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ type: "anyone", role: "reader" }) }, + DRIVE_SCOPE, + ); +} + +/* Drive's picture of a file's first page (PDFs, Office files), as + image bytes about `edge` pixels on the long side, or null while + Drive hasn't drawn one (it does so a little after upload) or can't. */ +export async function driveThumbnail(id, edge = 1280) { + const res = await call( + `${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true&fields=hasThumbnail,thumbnailLink`, + {}, + DRIVE_SCOPE, + ); + const { hasThumbnail, thumbnailLink } = await res.json(); + if (!hasThumbnail || !thumbnailLink) return null; + // The link ends in its size, eg. =s220; ask for a bigger one. + const image = await call(thumbnailLink.replace(/=s\d+$/, `=s${edge}`), {}, DRIVE_SCOPE); + return Buffer.from(await image.arrayBuffer()); } export async function driveDownload(id) { diff --git a/server/src/index.js b/server/src/index.js index d89b987..f9c99f1 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -36,6 +36,7 @@ import adminEntities from "./routes/admin-entities.js"; import media from "./routes/media.js"; import clips from "./routes/clips.js"; import imports from "./routes/import.js"; +import files from "./routes/files.js"; import { CLIPS_DIR, startClipWorker } from "./clips.js"; import { UPLOADS_DIR, writeMissingThumbs } from "./media.js"; import { logSafe, startSessionSweeper } from "./auth.js"; @@ -186,6 +187,7 @@ app.route("/api/admin", admin); // Before the entity routes, whose /:entity would claim /media. app.route("/api/admin", media); app.route("/api/admin", imports); +app.route("/api/admin", files); app.route("/api/admin", clips); app.route("/api/admin", adminEntities); diff --git a/server/src/migrations/048_drive_files.sql b/server/src/migrations/048_drive_files.sql new file mode 100644 index 0000000..710de12 --- /dev/null +++ b/server/src/migrations/048_drive_files.sql @@ -0,0 +1,28 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 048 FILES IN GOOGLE DRIVE +-- +-- Files for the public site to link to (a handout, slides, a talk's +-- audio, a brand kit), uploaded from Tools → Media → Files into the +-- shared drive's "Blog" folder (routes/files.js) and shared as +-- "anyone with the link can view". Content blocks link to `url`, +-- Drive's page for the file. +-- +-- preview /uploads/... of Drive's picture of the first page, in +-- the media library, once Drive has drawn one (PDFs and +-- Office files); a link card to the file takes it as its +-- picture +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE drive_files ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + drive_id TEXT NOT NULL UNIQUE, + name TEXT NOT NULL, + mime TEXT NOT NULL, + bytes INTEGER NOT NULL CHECK (bytes >= 0), + url TEXT NOT NULL, + preview TEXT, + uploaded_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +) STRICT; + +CREATE INDEX drive_files_created_idx ON drive_files (created_at DESC); diff --git a/server/src/routes/files.js b/server/src/routes/files.js new file mode 100644 index 0000000..0521125 --- /dev/null +++ b/server/src/routes/files.js @@ -0,0 +1,203 @@ +/* ═══════════════════════════════════════════════════════════════ + FILE ROUTES: mounted under /api/admin + + 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 + + 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 + view", so a link opens Drive's viewer. Content blocks' link fields + pick from here ("Choose a file"); a link card takes the file's name + and its first-page preview too. + + The preview: Drive draws a picture of a PDF's or Office file's + first page a little after upload. It's asked for straight away and + again over the next few minutes (PREVIEW_TRIES), and saved into the + media library as an ordinary upload when it comes. + + 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). + ═══════════════════════════════════════════════════════════════ */ + +import { Hono } from "hono"; +import { bodyLimit } from "hono/body-limit"; + +import { requireAuth, requireRole } from "../auth.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 = "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]; + +/* 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 + PDF named .mp3 is refused, so a download is always what it says. */ +const ZIPPED = { + docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation", + zip: "application/zip", +}; +export function kindOf(bytes, name) { + const ext = String(name).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1]; + const starts = (at, ...sig) => sig.every((b, i) => bytes[at + i] === b); + if (ext === "pdf" && starts(0, 0x25, 0x50, 0x44, 0x46, 0x2d)) return "application/pdf"; + if (starts(0, 0x50, 0x4b, 0x03, 0x04) && ZIPPED[ext]) return ZIPPED[ext]; + if (ext === "mp3" && (starts(0, 0x49, 0x44, 0x33) || (bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0))) return "audio/mpeg"; + if (ext === "m4a" && starts(4, 0x66, 0x74, 0x79, 0x70)) return "audio/mp4"; + return null; +} + +const safeName = (name) => + String(name ?? "file") + .replace(/[\u0000-\u001f"\\/]+/g, " ") + .trim() + .slice(0, 150) || "file"; + +const SELECT = `SELECT f.*, u.name AS uploaded_by_name, u.email AS uploaded_by_email + FROM drive_files f LEFT JOIN admin_users u ON u.id = f.uploaded_by`; + +const shape = (row) => ({ + id: row.id, + name: row.name, + // What a link card calls it: the name without its extension. + title: row.name.replace(/\.[a-z0-9]+$/i, ""), + mime: row.mime, + bytes: row.bytes, + url: row.url, + preview: row.preview, + uploaded_by: row.uploaded_by_name ?? row.uploaded_by_email ?? null, + created_at: row.created_at, +}); + +/* Asks Drive for the first-page picture until it has one or the + tries run out; saved into the media library. Never throws. */ +function fetchPreview(db, row, userId) { + let attempt = 0; + const next = async () => { + try { + const image = await driveThumbnail(row.drive_id); + if (image) { + const saved = await addToLibrary(db, image, { originalName: `${shape(row).title} (preview)`, userId }); + db.prepare(`UPDATE drive_files SET preview = ? WHERE id = ?`).run(`/uploads/${saved.filename}`, row.id); + return; + } + } catch (err) { + console.warn(`files: preview for ${row.name}: ${err.message}`); + } + attempt++; + if (attempt < PREVIEW_TRIES.length) setTimeout(next, (PREVIEW_TRIES[attempt] - PREVIEW_TRIES[attempt - 1]) * 1000).unref(); + }; + return next(); +} + +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() }, 200, NO_STORE); +}); + +files.post( + "/files", + requireRole("editor"), + bodyLimit({ + maxSize: MAX_FILE_BYTES + 64 * 1024, + onError: (c) => c.json({ error: `Files can be ${MAX_FILE_BYTES / 1024 / 1024} MB at most.` }, 413), + }), + async (c) => { + if (!driveReady()) { + return c.json({ error: "Google Drive isn't set up on the server (docs/google-drive-and-mail.md)." }, 400); + } + const db = c.get("db"); + const user = c.get("user"); + let body; + try { + body = await c.req.parseBody(); + } catch { + return c.json({ error: "Expected a file upload." }, 400); + } + const file = body.file; + if (!(file instanceof File) || file.size === 0) return c.json({ error: "No file was sent." }, 400); + + const buffer = Buffer.from(await file.arrayBuffer()); + const mime = kindOf(buffer, file.name); + if (!mime) { + return c.json({ error: "Only PDF, Word, Excel, PowerPoint (.docx, .xlsx, .pptx), MP3, M4A and zip files." }, 415); + } + const name = safeName(file.name); + + let uploaded; + try { + uploaded = await driveUpload(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); + } + try { + await driveShareWithAnyone(uploaded.id); + } catch (err) { + console.warn(`files: sharing ${name} failed: ${err.message}`); + await driveDelete(uploaded.id).catch(() => {}); + return c.json( + { + error: + `Drive wouldn't share it with anyone who has the link (${err.message}). ` + + "The shared drive's settings, or the Workspace's sharing settings, must allow sharing outside the organization.", + }, + 502, + ); + } + + 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; + const row = db.prepare(`${SELECT} WHERE f.id = ?`).get(id); + console.log(`files: ${name} uploaded by ${user.email}`); + + // The first try is waited for; Drive often has the picture already. + await fetchPreview(db, row, user.id); + return c.json({ file: shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id)) }, 201, NO_STORE); + }, +); + +function findOr404(c) { + const id = Number(c.req.param("id")); + return Number.isInteger(id) ? c.get("db").prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id) : null; +} + +files.get("/files/:id/uses", (c) => { + const row = findOr404(c); + if (!row) return c.json({ error: "No such file." }, 404); + return c.json({ uses: recordsNaming(c.get("db"), [row.url]) }, 200, NO_STORE); +}); + +files.delete("/files/:id", requireRole("admin"), async (c) => { + const row = findOr404(c); + if (!row) return c.json({ error: "No such file." }, 404); + try { + await driveDelete(row.drive_id); + } catch (err) { + // Already gone from Drive (deleted by hand): 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 drive_files WHERE id = ?`).run(row.id); + console.log(`files: ${row.name} deleted by ${c.get("user").email}`); + return c.body(null, 204); +}); + +export default files; diff --git a/server/src/routes/media.js b/server/src/routes/media.js index 23a76b3..07a55c1 100644 --- a/server/src/routes/media.js +++ b/server/src/routes/media.js @@ -52,7 +52,7 @@ const SCAN_EVERY_MS = 30_000; let lastScan = 0; /* Tables that can't hold an image path, or mustn't be searched. */ -const NOT_CONTENT = new Set(["media", "admin_users", "sessions", "feedback", "sqlite_sequence"]); +const NOT_CONTENT = new Set(["media", "drive_files", "admin_users", "sessions", "feedback", "feedback_files", "sqlite_sequence"]); function shape(row) { return { @@ -77,7 +77,7 @@ const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_e /* Writes the file, then its row; a failed insert takes the file back out so nothing is left on disk that the library can't see. */ -async function addToLibrary(db, buf, { originalName, keepOriginal, userId }) { +export async function addToLibrary(db, buf, { originalName, keepOriginal, userId }) { const stored = await store(buf, { keepOriginal }); try { const { lastInsertRowid } = db @@ -203,13 +203,18 @@ media.post("/link-preview", requireRole("editor"), async (c) => { same place. Read from the live schema rather than a list of image columns, so a new image field is covered the day it's added. */ function usesOf(db, filename) { - const values = [ - ...new Set([ - `${PUBLIC_PREFIX}${filename}`, - `${PUBLIC_PREFIX}${encodeURIComponent(filename)}`, - filename, - ]), - ]; + return recordsNaming(db, [ + `${PUBLIC_PREFIX}${filename}`, + `${PUBLIC_PREFIX}${encodeURIComponent(filename)}`, + filename, + ]); +} + +/* Which content tables have a TEXT column holding exactly one of + `values`: [{ table, count }]. Also how Tools → Media → Files finds + what links to a file (routes/files.js). */ +export function recordsNaming(db, values) { + values = [...new Set(values)]; const tables = db .prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`) .all() diff --git a/server/src/routes/requests.js b/server/src/routes/requests.js index a918a4c..9412837 100644 --- a/server/src/routes/requests.js +++ b/server/src/routes/requests.js @@ -134,7 +134,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) }); + stored.push({ ...file, driveId: (await driveUpload(DRIVE_FOLDER, `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/ContentBlocks.tsx b/src/components/ContentBlocks.tsx index b6cf9c5..ec4ef8c 100644 --- a/src/components/ContentBlocks.tsx +++ b/src/components/ContentBlocks.tsx @@ -79,7 +79,9 @@ function LinkCard({ item }: { item: ContentBlockItem }) { const where = isExternalUrl(url) ? (() => { try { - return new URL(url).hostname.replace(/^www\./, '') + const host = new URL(url).hostname.replace(/^www\./, '') + // A file from Tools → Media → Files (routes/files.js). + return /^(drive|docs)\.google\.com$/.test(host) ? 'Google Drive' : host } catch { return url } diff --git a/src/components/admin/DriveFiles.tsx b/src/components/admin/DriveFiles.tsx new file mode 100644 index 0000000..7c6fd22 --- /dev/null +++ b/src/components/admin/DriveFiles.tsx @@ -0,0 +1,286 @@ +/* ═══════════════════════════════════════════════════════════════ + DRIVE FILES + + Files for the site to link to (server/src/routes/files.js), kept in + the shared Google Drive and shared as "anyone with the link can + view". The admin side, in one file: + + FileUploadButton upload one or more files + FileList the list both the picker and Tools → Media → + Files draw, each with its first-page preview + or an icon for its type + FilePicker the dialog behind a link field's "Choose a + 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. + ═══════════════════════════════════════════════════════════════ */ + +import { + File as FileIcon, + FileAudio, + FileDoc, + FilePdf, + FilePpt, + FileXls, + FileZip, + X, +} from "@phosphor-icons/react"; +import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; + +import { ApiError, get, upload } from "../../lib/api.ts"; +import { useAuth } from "../../lib/auth.tsx"; +import { canWrite as roleCanWrite } from "../../lib/roles.ts"; +import { formatBytes } from "./MediaLibrary.tsx"; + +export type DriveFile = { + id: number; + name: string; + title: string; + mime: string; + bytes: number; + url: string; + preview: string | null; + uploaded_by: string | null; + created_at: string; +}; + +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"; + +export const FILE_HELP = + "PDF, Word, Excel, PowerPoint (.docx, .xlsx, .pptx), MP3, M4A or zip, up to 50 MB. Stored in the shared Google Drive and viewable by anyone with the link."; + +const ACCEPT = ".pdf,.docx,.xlsx,.pptx,.mp3,.m4a,.zip"; + +function TypeIcon({ mime }: { mime: string }) { + 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