Compare commits
2 commits
36c9226bd9
...
5f13273e69
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f13273e69 | ||
|
|
934598f954 |
14 changed files with 773 additions and 34 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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("<Folder>", 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.
|
||||
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
|
|
|
|||
28
server/src/migrations/048_drive_files.sql
Normal file
28
server/src/migrations/048_drive_files.sql
Normal file
|
|
@ -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);
|
||||
203
server/src/routes/files.js
Normal file
203
server/src/routes/files.js
Normal file
|
|
@ -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;
|
||||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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}`);
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
286
src/components/admin/DriveFiles.tsx
Normal file
286
src/components/admin/DriveFiles.tsx
Normal file
|
|
@ -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 <Icon aria-hidden="true" weight="bold" className="h-8 w-8 text-link" />;
|
||||
}
|
||||
|
||||
/* ── Data ────────────────────────────────────────────────────── */
|
||||
|
||||
export function useDriveFiles(query: string) {
|
||||
const [items, setItems] = useState<DriveFile[] | null>(null);
|
||||
const [ready, setReady] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const reload = useCallback(() => {
|
||||
const q = query.trim();
|
||||
setError(null);
|
||||
get(`/admin/files${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 })
|
||||
.then((data) => {
|
||||
setItems(data.files);
|
||||
setReady(data.ready);
|
||||
})
|
||||
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the files."));
|
||||
}, [query]);
|
||||
|
||||
useEffect(reload, [reload]);
|
||||
return { items, ready, error, reload, setItems };
|
||||
}
|
||||
|
||||
/* ── Upload ──────────────────────────────────────────────────── */
|
||||
|
||||
export function FileUploadButton({ onUploaded, label = "Upload files" }: { onUploaded: (file: DriveFile) => void; label?: string }) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function send(list: FileList | null) {
|
||||
if (!list?.length) return;
|
||||
setError(null);
|
||||
try {
|
||||
// One at a time, so a failure names its file.
|
||||
for (const file of Array.from(list)) {
|
||||
setBusy(file.name);
|
||||
const form = new FormData();
|
||||
form.append("file", file);
|
||||
try {
|
||||
onUploaded((await upload("/admin/files", form)).file);
|
||||
} catch (err) {
|
||||
const why = err instanceof ApiError ? err.message : "Upload failed.";
|
||||
setError(list.length > 1 ? `${file.name}: ${why}` : why);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setBusy(null);
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button type="button" className={button} disabled={busy !== null} onClick={() => inputRef.current?.click()}>
|
||||
{busy ? `Uploading ${busy}…` : label}
|
||||
</button>
|
||||
<input ref={inputRef} type="file" accept={ACCEPT} multiple className="hidden" onChange={(e) => send(e.target.files)} />
|
||||
{error && <p className="mt-1 text-xs text-danger">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── List ────────────────────────────────────────────────────── */
|
||||
|
||||
export function FileList({
|
||||
items,
|
||||
selected,
|
||||
onPick,
|
||||
renderActions,
|
||||
}: {
|
||||
items: DriveFile[];
|
||||
selected?: string | null;
|
||||
onPick?: (file: DriveFile) => void;
|
||||
renderActions?: (file: DriveFile) => ReactNode;
|
||||
}) {
|
||||
if (items.length === 0) return <p className="text-sm text-muted">No files yet.</p>;
|
||||
|
||||
return (
|
||||
<ul className="grid gap-3 sm:grid-cols-2">
|
||||
{items.map((file) => {
|
||||
const isSelected = selected === file.url;
|
||||
const body = (
|
||||
<span className="flex items-center gap-3">
|
||||
<span className="flex h-16 w-14 shrink-0 items-center justify-center overflow-hidden rounded-md border border-muted/20 bg-tint">
|
||||
{file.preview ? (
|
||||
<img src={file.preview} alt="" loading="lazy" className="h-full w-full object-cover object-top" />
|
||||
) : (
|
||||
<TypeIcon mime={file.mime} />
|
||||
)}
|
||||
</span>
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-sm font-medium text-body" title={file.name}>
|
||||
{file.name}
|
||||
</span>
|
||||
<span className="block text-xs text-muted/80">{formatBytes(file.bytes)}</span>
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<li
|
||||
key={file.id}
|
||||
className={`rounded-xl border bg-surface p-2 ${isSelected ? "border-brand ring-2 ring-brand/30" : "border-muted/20"}`}
|
||||
>
|
||||
{onPick ? (
|
||||
<button type="button" onClick={() => onPick(file)} className="block w-full text-left" aria-pressed={isSelected}>
|
||||
{body}
|
||||
</button>
|
||||
) : (
|
||||
body
|
||||
)}
|
||||
{renderActions && <div className="mt-2">{renderActions(file)}</div>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── Picker dialog ───────────────────────────────────────────── */
|
||||
|
||||
export function FilePicker({
|
||||
selected,
|
||||
onPick,
|
||||
onClose,
|
||||
}: {
|
||||
selected?: string | null;
|
||||
onPick: (file: DriveFile) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { user } = useAuth();
|
||||
const [query, setQuery] = useState("");
|
||||
const { items, ready, error, setItems } = useDriveFiles(query);
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
dialogRef.current?.showModal();
|
||||
}, []);
|
||||
|
||||
const pick = (file: DriveFile) => {
|
||||
onPick(file);
|
||||
dialogRef.current?.close();
|
||||
};
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
onClose={onClose}
|
||||
onClick={(e) => {
|
||||
if (e.target === dialogRef.current) dialogRef.current?.close();
|
||||
}}
|
||||
className="w-[min(48rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40"
|
||||
>
|
||||
<div className="flex max-h-[85vh] flex-col">
|
||||
<div className="flex flex-wrap items-center gap-3 border-b border-brand/15 px-5 py-4">
|
||||
<h2 className="text-lg font-semibold text-link">Choose a file</h2>
|
||||
<input
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="Search by file name"
|
||||
className="ml-auto w-56 rounded-lg border border-muted/25 px-3 py-1.5 text-sm outline-none focus:border-brand"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dialogRef.current?.close()}
|
||||
aria-label="Close"
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full text-muted hover:bg-tint"
|
||||
>
|
||||
<X aria-hidden="true" weight="bold" className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{roleCanWrite(user) && ready && (
|
||||
<div className="border-b border-brand/10 px-5 py-3">
|
||||
<FileUploadButton
|
||||
label="Upload new"
|
||||
onUploaded={(file) => {
|
||||
setItems((current) => [file, ...(current ?? [])]);
|
||||
pick(file);
|
||||
}}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-muted">{FILE_HELP}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="overflow-y-auto px-5 py-4">
|
||||
{!ready && <p className="mb-3 text-sm text-danger">Google Drive isn't set up on the server, so nothing can be uploaded.</p>}
|
||||
{error ? (
|
||||
<p className="text-sm text-danger">{error}</p>
|
||||
) : items === null ? (
|
||||
<p className="text-sm text-muted">Loading…</p>
|
||||
) : (
|
||||
<FileList items={items} selected={selected} onPick={pick} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/* "Choose a file" under a link field. */
|
||||
export function ChooseFileButton({ value, onPick }: { value?: string | null; onPick: (file: DriveFile) => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<button type="button" className={button} onClick={() => setOpen(true)}>
|
||||
Choose a file
|
||||
</button>
|
||||
{open && <FilePicker selected={value} onPick={onPick} onClose={() => setOpen(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -56,6 +56,12 @@
|
|||
(LinkPreviewInput in MediaLibrary.tsx) that fills the row's empty
|
||||
title, blurb and image through `onPatch`.
|
||||
|
||||
`files: true` on a link field adds "Choose a file" (FilePicker in
|
||||
DriveFiles.tsx): the field takes the file's Drive link, and with
|
||||
`previewFills` (a link card) the row's empty title and picture take
|
||||
the file's name and first-page preview. `filesWhen` limits it to
|
||||
rows that match, as `when` does for the field.
|
||||
|
||||
`widget: "testNotice"` is a text box of email addresses with a
|
||||
"Send a test notice" button (TestNoticeInput below), for Site
|
||||
settings → Notices.
|
||||
|
|
@ -85,6 +91,7 @@ import { useRef, useState } from "react";
|
|||
import { ApiError, post } from "../../lib/api.ts";
|
||||
import ContentBlocks from "../ContentBlocks.tsx";
|
||||
import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx";
|
||||
import { ChooseFileButton } from "./DriveFiles.tsx";
|
||||
|
||||
/* Live previews a collection can name with `preview`. Each gets the
|
||||
row as the form holds it, which is the API's shape. */
|
||||
|
|
@ -235,6 +242,17 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
|
|||
!list.some(([optionId]) => String(optionId) === String(value));
|
||||
}
|
||||
|
||||
// A file from the Drive library into this link field (`files`).
|
||||
const pickFile = (file) => {
|
||||
const fills = field.previewFills;
|
||||
const patch = { [field.path]: file.url };
|
||||
if (fills && !row?.[fills.title]) patch[fills.title] = file.title;
|
||||
if (fills && !row?.[fills.image] && file.preview) patch[fills.image] = file.preview;
|
||||
if (onPatch && !field.path.includes(".")) onPatch(patch);
|
||||
else onChange(file.url);
|
||||
};
|
||||
const showFiles = field.files && !locked && (!field.filesWhen || fieldShown({ when: field.filesWhen }, row));
|
||||
|
||||
const common = {
|
||||
id,
|
||||
className: `${input} ${error ? inputError : ""}`,
|
||||
|
|
@ -371,6 +389,11 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
|
|||
className={locked ? inputLocked : common.className}
|
||||
/>
|
||||
)}
|
||||
{showFiles && (
|
||||
<div className="mt-2">
|
||||
<ChooseFileButton value={value} onPick={pickFile} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
|
|
|
|||
|
|
@ -362,6 +362,8 @@ export const blocksChild = {
|
|||
path: "href",
|
||||
label: "Link",
|
||||
full: true,
|
||||
files: true,
|
||||
filesWhen: { path: "type", value: ["paragraph", "button", "image"] },
|
||||
when: { path: "type", value: ["paragraph", "button", "image", "video"] },
|
||||
help: (row) => HREF_HELP[row?.type],
|
||||
},
|
||||
|
|
@ -405,8 +407,9 @@ export const blocksChild = {
|
|||
label: "Link",
|
||||
widget: "linkPreview",
|
||||
previewFills: { title: "text", blurb: "detail", image: "media" },
|
||||
files: true,
|
||||
full: true,
|
||||
help: "A page on this site (eg. /retreats) or anywhere else. Fetch preview fills the title, description and picture.",
|
||||
help: "A page on this site (eg. /retreats), anywhere else, or a file (Choose a file). Fetch preview fills the title, description and picture from a page; a file fills its name and first-page picture.",
|
||||
when: CARD_ITEM,
|
||||
},
|
||||
{ path: "text", label: "Text", required: true, help: "Schedules: the entry's title. Cards: the card's title" },
|
||||
|
|
@ -427,7 +430,7 @@ export const blocksChild = {
|
|||
},
|
||||
{ path: "detail", label: "Detail", help: "A line under the text. Lists: shown after the text", when: NOT_CARD_ITEM },
|
||||
{ path: "detail", label: "Description", widget: "textarea", full: true, when: CARD_ITEM },
|
||||
{ path: "url", label: "URL", help: "Blank for plain text. Link buttons need one.", when: NOT_CARD_ITEM },
|
||||
{ path: "url", label: "URL", help: "Blank for plain text. Link buttons need one.", files: true, when: NOT_CARD_ITEM },
|
||||
{
|
||||
path: "media",
|
||||
label: "Picture",
|
||||
|
|
|
|||
|
|
@ -7,4 +7,4 @@
|
|||
box or a build banner can read the same value later.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
export const SITE_VERSION = "NGU-Web.v1.9.8-content-display";
|
||||
export const SITE_VERSION = "NGU-Web.v1.9.9-content-display";
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
ADMIN: MEDIA
|
||||
|
||||
The uploaded-image library: search it, add to it, copy a file's
|
||||
path, delete what nothing needs. Image fields in the editors
|
||||
upload and pick from the same library (MediaLibrary.tsx), so this
|
||||
page is for housekeeping rather than the way images get in.
|
||||
Two tabs. Images: the uploaded-image library: search it, add to
|
||||
it, copy a file's path, delete what nothing needs. Image fields in
|
||||
the editors upload and pick from the same library
|
||||
(MediaLibrary.tsx), so this is housekeeping rather than the way
|
||||
images get in. Files: documents, audio and zips in the shared
|
||||
Google Drive, for pages to link to (DriveFiles.tsx); link fields'
|
||||
"Choose a file" picks from them.
|
||||
|
||||
Two ranks, as on the server: editors and up upload, admins and
|
||||
up delete. A delete first asks the server which records still
|
||||
|
|
@ -17,6 +20,12 @@ import { useState } from "react";
|
|||
import { ApiError, del, get } from "../../lib/api.ts";
|
||||
import { useAuth } from "../../lib/auth.tsx";
|
||||
import { canDelete, canWrite as roleCanWrite } from "../../lib/roles.ts";
|
||||
import {
|
||||
FILE_HELP,
|
||||
FileList,
|
||||
FileUploadButton,
|
||||
useDriveFiles,
|
||||
} from "../../components/admin/DriveFiles.tsx";
|
||||
import {
|
||||
MediaGrid,
|
||||
UPLOAD_HELP,
|
||||
|
|
@ -27,7 +36,18 @@ import {
|
|||
|
||||
type Use = { table: string; count: number };
|
||||
|
||||
function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () => void }) {
|
||||
/* `base` is where the item lives: /admin/media or /admin/files. */
|
||||
function DeleteControl({
|
||||
item,
|
||||
base = "/admin/media",
|
||||
broken = "Those will show no image.",
|
||||
onDeleted,
|
||||
}: {
|
||||
item: { id: number };
|
||||
base?: string;
|
||||
broken?: string;
|
||||
onDeleted: () => void;
|
||||
}) {
|
||||
const [uses, setUses] = useState<Use[] | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
|
@ -36,7 +56,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
|
|||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await get(`/admin/media/${item.id}/uses`, { ttl: 0 });
|
||||
const data = await get(`${base}/${item.id}/uses`, { ttl: 0 });
|
||||
setUses(data.uses);
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Couldn't check where it's used.");
|
||||
|
|
@ -49,7 +69,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
|
|||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await del(`/admin/media/${item.id}`);
|
||||
await del(`${base}/${item.id}`);
|
||||
onDeleted();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Couldn't delete that.");
|
||||
|
|
@ -78,8 +98,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
|
|||
{uses.length > 0 ? (
|
||||
<p>
|
||||
Still used by{" "}
|
||||
{uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. Those
|
||||
will show no image.
|
||||
{uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. {broken}
|
||||
</p>
|
||||
) : (
|
||||
<p>Nothing uses this file.</p>
|
||||
|
|
@ -102,7 +121,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
|
|||
);
|
||||
}
|
||||
|
||||
function CopyPath({ url }: { url: string }) {
|
||||
function CopyPath({ url, label = "Copy path" }: { url: string; label?: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
return (
|
||||
<button
|
||||
|
|
@ -115,13 +134,79 @@ function CopyPath({ url }: { url: string }) {
|
|||
}}
|
||||
className="text-xs text-link hover:underline"
|
||||
>
|
||||
{copied ? "Copied" : "Copy path"}
|
||||
{copied ? "Copied" : label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function FilesTab() {
|
||||
const { user } = useAuth();
|
||||
const [query, setQuery] = useState("");
|
||||
const { items, ready, error, setItems } = useDriveFiles(query);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mt-6 flex flex-wrap items-start gap-6">
|
||||
{roleCanWrite(user) && ready && (
|
||||
<div className="max-w-md">
|
||||
<FileUploadButton onUploaded={(file) => setItems((current) => [file, ...(current ?? [])])} />
|
||||
<p className="mt-1 text-xs text-muted">{FILE_HELP}</p>
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="Search by file name"
|
||||
className="ml-auto w-64 rounded-lg border border-muted/25 px-3 py-2 text-sm outline-none focus:border-brand"
|
||||
/>
|
||||
</div>
|
||||
{!ready && (
|
||||
<p className="mt-4 text-sm text-danger">
|
||||
Google Drive isn't set up on the server (docs/google-drive-and-mail.md), so files can't be uploaded.
|
||||
</p>
|
||||
)}
|
||||
<div className="mt-6">
|
||||
{error ? (
|
||||
<p className="text-sm text-danger">{error}</p>
|
||||
) : items === null ? (
|
||||
<p className="text-sm text-muted">Loading…</p>
|
||||
) : (
|
||||
<FileList
|
||||
items={items}
|
||||
renderActions={(file) => (
|
||||
<div className="flex flex-wrap items-start gap-x-3 gap-y-1">
|
||||
<CopyPath url={file.url} label="Copy link" />
|
||||
<a href={file.url} target="_blank" rel="noreferrer" className="text-xs text-link hover:underline">
|
||||
Open in Drive
|
||||
</a>
|
||||
{canDelete(user) && (
|
||||
<div className="w-full">
|
||||
<DeleteControl
|
||||
item={file}
|
||||
base="/admin/files"
|
||||
broken="Those links will stop working."
|
||||
onDeleted={() => setItems((current) => (current ?? []).filter((f) => f.id !== file.id))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const TABS = [
|
||||
["images", "Images"],
|
||||
["files", "Files"],
|
||||
] as const;
|
||||
|
||||
export default function AdminMedia() {
|
||||
const { user } = useAuth();
|
||||
const [tab, setTab] = useState<"images" | "files">("images");
|
||||
const [query, setQuery] = useState("");
|
||||
const { items, error, setItems } = useMediaLibrary(query);
|
||||
|
||||
|
|
@ -130,10 +215,34 @@ export default function AdminMedia() {
|
|||
<div className="flex flex-wrap items-baseline gap-3">
|
||||
<h1 className="text-2xl font-bold text-link">Media</h1>
|
||||
<p className="text-sm text-muted">
|
||||
Uploaded images. Image fields in every editor pick from here.
|
||||
{tab === "images"
|
||||
? "Uploaded images. Image fields in every editor pick from here."
|
||||
: "Files in the shared Google Drive, for pages to link to. Link fields pick from here with Choose a file."}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<nav aria-label="Media" className="mt-4 flex gap-1 border-b border-brand/15">
|
||||
{TABS.map(([id, label]) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
aria-current={tab === id ? "page" : undefined}
|
||||
onClick={() => setTab(id)}
|
||||
className={
|
||||
"-mb-px border-b-2 px-4 py-2 text-sm font-semibold transition-colors " +
|
||||
(tab === id ? "border-link text-link" : "border-transparent text-muted hover:text-link")
|
||||
}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{tab === "files" ? (
|
||||
<FilesTab />
|
||||
) : (
|
||||
<>
|
||||
|
||||
<div className="mt-6 flex flex-wrap items-start gap-6">
|
||||
{roleCanWrite(user) && (
|
||||
<div className="max-w-md">
|
||||
|
|
@ -188,6 +297,8 @@ export default function AdminMedia() {
|
|||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue