diff --git a/docs/google-drive-and-mail.md b/docs/google-drive-and-mail.md index 6b72b78..2789404 100644 --- a/docs/google-drive-and-mail.md +++ b/docs/google-drive-and-mail.md @@ -60,7 +60,7 @@ hand. | Folder | Used by | Set in | | --- | --- | --- | -| `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` | +| `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 @@ -81,6 +81,14 @@ matches the one in Forms → Content requests. Deleting a request in the admin deletes its files from Drive too. Request files from before the per-type folders stay where they are, in `Requests` itself. +Tools → Media → **Requests** lists every request file by its type folder, +each with its request; Forms → Content requests lists a request's own. +Both say **Missing from Drive** for a file Drive no longer has under +`Requests` (deleted, or moved out, by hand): it can't be downloaded or +made into a post, but can be taken off the request. **Remove** (admins +and up) trashes a file in Drive and takes it off its request; the +request itself stays. + **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 diff --git a/docs/video-clips.md b/docs/video-clips.md index 3271885..90a558a 100644 --- a/docs/video-clips.md +++ b/docs/video-clips.md @@ -14,6 +14,16 @@ server once it's downloaded, unless **Save to library** is pressed first, which puts it in the media library as an upload (usable as a featured video or in a video block). Everything is cleared a day after it's made. +**Save to Drive** puts a copy in a folder under Media in the shared +Google Drive (pick it, eg. `Media/Videos` or `Media/Audio`; the list is +Tools → Media → Files's folders, and the one named for the clip's kind +is chosen first). It becomes a Files entry, shared with anyone who has +the link, so pages link to it with Choose a file. It's uploaded straight +from the server's copy (the working file, or the library's), streamed +rather than read into memory, so a long clip is fine; nginx isn't in the +way. A clip can be in both the library and Drive. Needs Google Drive set +up (`docs/google-drive-and-mail.md`) and migration 051. + Only YouTube and Facebook links are accepted, and only for videos NGU owns or has permission to use. Sources can be up to 4 hours and 4 GB; clips up to an hour. Limits are constants at the top of `server/src/clips.js`. diff --git a/server/src/googleService.js b/server/src/googleService.js index 31bf976..214edc5 100644 --- a/server/src/googleService.js +++ b/server/src/googleService.js @@ -32,7 +32,9 @@ Setup: docs/google-drive-and-mail.md. ═══════════════════════════════════════════════════════════════ */ -import { readFileSync } from "node:fs"; +import { createReadStream, readFileSync } from "node:fs"; +import { stat } from "node:fs/promises"; +import { Readable } from "node:stream"; import { createSign } from "node:crypto"; const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive"; @@ -99,11 +101,11 @@ async function accessToken(scope, subject) { return data.access_token; } -async function call(url, init, scope, subject) { +async function call(url, init, scope, subject, timeoutMs = 60_000) { const res = await fetch(url, { ...init, headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` }, - signal: AbortSignal.timeout(60_000), + signal: AbortSignal.timeout(timeoutMs), }); if (!res.ok) { const detail = await res.json().catch(() => null); @@ -143,7 +145,12 @@ export function forgetFolders(path) { async function findOrMakeFolder(path) { const drive = process.env.GOOGLE_SHARED_DRIVE; let parent = drive; + const walked = []; for (const name of path.split("/").filter(Boolean)) { + // Each level on the way is known too: "Requests" once + // "Requests/Chapters" has been found. + if (walked.length && !folders.has(walked.join("/"))) folders.set(walked.join("/"), Promise.resolve(parent)); + walked.push(name); const quoted = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'"); const query = new URLSearchParams({ q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`, @@ -265,6 +272,41 @@ export async function driveRename(id, name) { ); } +/* A file on disk into a folder of the shared drive, streamed through + a resumable upload rather than read into memory (a video clip can + be large). Returns { id, webViewLink }, as driveUpload does. */ +export async function driveUploadFile(folder, name, mime, filePath) { + const { size } = await stat(filePath); + const start = await call( + `${DRIVE_UPLOAD}?uploadType=resumable&supportsAllDrives=true&fields=id,webViewLink`, + { + method: "POST", + headers: { + "Content-Type": "application/json; charset=UTF-8", + "X-Upload-Content-Type": mime, + "X-Upload-Content-Length": String(size), + }, + body: JSON.stringify({ name, parents: [await driveFolder(folder)] }), + }, + DRIVE_SCOPE, + ); + const session = start.headers.get("location"); + if (!session) throw new GoogleError("Drive didn't start the upload."); + const res = await call( + session, + { + method: "PUT", + headers: { "Content-Type": mime, "Content-Length": String(size) }, + body: Readable.toWeb(createReadStream(filePath)), + duplex: "half", + }, + DRIVE_SCOPE, + undefined, + 30 * 60_000, + ); + 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. */ diff --git a/server/src/migrations/051_clip_drive.sql b/server/src/migrations/051_clip_drive.sql new file mode 100644 index 0000000..d352968 --- /dev/null +++ b/server/src/migrations/051_clip_drive.sql @@ -0,0 +1,10 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 051 CLIPS SAVED TO DRIVE +-- +-- Tools → Video clips → Save to Drive puts a finished clip in a folder +-- under the shared drive's Media folder, as a Files entry +-- (drive_files, 048). The job keeps which one, as it keeps its media +-- library copy in saved_media_id; a clip can be in both. +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE clip_jobs ADD COLUMN saved_drive_file_id INTEGER REFERENCES drive_files (id) ON DELETE SET NULL; diff --git a/server/src/routes/admin.js b/server/src/routes/admin.js index 85ec0ff..47cc1a1 100644 --- a/server/src/routes/admin.js +++ b/server/src/routes/admin.js @@ -11,7 +11,8 @@ import { Hono } from "hono"; import { requireAuth, requireRole } from "../auth.js"; import { NO_STORE } from "../shape.js"; -import { driveDelete, driveDownload } from "../googleService.js"; +import { driveDelete, driveDownload, driveReady, driveTree } from "../googleService.js"; +import { DRIVE_FOLDER, TYPE_FOLDERS } from "./requests.js"; import { HttpError } from "../admin-crud.js"; import { importDocx } from "./import.js"; @@ -32,12 +33,31 @@ const KIND_WHERE = { const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id, status, admin_note, category, request_action, subject, details`; -/* Each row with its files (content requests), in one query. */ -function withFiles(db, rows) { +/* The ids of every file under Requests in Drive (any type folder), + looked up at most every 30 seconds; null when Drive isn't set up or + didn't answer, which marks nothing missing. A file someone deleted + or moved out of Requests in Drive is then "missing". */ +let inDrive = { at: 0, ids: null }; +async function requestFilesInDrive() { + if (!driveReady()) return null; + if (Date.now() - inDrive.at < 30_000) return inDrive.ids; + try { + const tree = await driveTree(DRIVE_FOLDER, 2); + inDrive = { at: Date.now(), ids: new Set(tree.files.map((f) => f.id)) }; + } catch (err) { + console.warn(`feedback: couldn't list ${DRIVE_FOLDER} in Drive: ${err.message}`); + inDrive = { at: Date.now(), ids: null }; + } + return inDrive.ids; +} + +/* Each row with its files (content requests), in one query. `ids` + (requestFilesInDrive) says which are still in Drive. */ +function withFiles(db, rows, ids = null) { if (rows.length === 0) return rows; const files = db .prepare( - `SELECT id, feedback_id, name, mime, size FROM feedback_files + `SELECT id, feedback_id, drive_id, name, mime, size FROM feedback_files WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`, ) .all(...rows.map((r) => r.id)); @@ -45,7 +65,9 @@ function withFiles(db, rows) { ...row, // Stored as JSON text (049); the admin wants the object. details: row.details ? JSON.parse(row.details) : null, - files: files.filter((f) => f.feedback_id === row.id).map(({ feedback_id, ...f }) => f), + files: files + .filter((f) => f.feedback_id === row.id) + .map(({ feedback_id, drive_id, ...f }) => ({ ...f, missing: ids ? !ids.has(drive_id) : false })), })); } const MAX_LIMIT = 200; @@ -62,7 +84,7 @@ const NOTE_LIMIT = 2000; ?limit=50 ───────────────────────────────────────────────────────────── */ -admin.get("/feedback", (c) => { +admin.get("/feedback", async (c) => { const db = c.get("db"); const { status, type, kind, q, before, limit } = c.req.query(); @@ -102,7 +124,7 @@ admin.get("/feedback", (c) => { .all(...params, take + 1); // one extra to detect a next page const hasMore = rows.length > take; - const page = withFiles(db, hasMore ? rows.slice(0, take) : rows); + const page = withFiles(db, hasMore ? rows.slice(0, take) : rows, kind === "content" ? await requestFilesInDrive() : null); // Status counts cover this queue (kind) but ignore the other // filters: the tabs show what's waiting, not what's left after a @@ -172,7 +194,7 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => { if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400); - const result = db_update(c.get("db"), id, sets, params); + const result = db_update(c.get("db"), id, sets, params, await requestFilesInDrive()); if (!result) return c.json({ error: "No such feedback." }, 404); console.log(`feedback #${id} updated by ${c.get("user").email}`); @@ -180,14 +202,14 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => { return c.json({ feedback: result }, 200, NO_STORE); }); -function db_update(db, id, sets, params) { +function db_update(db, id, sets, params, ids) { const changed = db .prepare(`UPDATE feedback SET ${sets.join(", ")} WHERE id = ?`) .run(...params, id); if (changed.changes === 0) return null; - return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)])[0]; + return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)], ids)[0]; } /* ── DELETE /api/admin/feedback/:id ────────────────────────────── @@ -221,9 +243,13 @@ admin.delete("/feedback/:id", requireRole("admin"), async (c) => { }); /* ── A content request's files ─────────────────────────────────── - GET /feedback/:id/files/:file download, from Drive - POST /feedback/:id/files/:file/blog-post a .docx as a new - unpublished blog post (import.js), editors and up + GET /feedback/:id/files/:file download, from Drive + POST /feedback/:id/files/:file/blog-post a .docx as a new + unpublished blog post (import.js), editors and up + DELETE /feedback/:id/files/:file into Drive's trash and + off the request, admins and up + GET /request-files every request's files, + by type folder, for Tools → Media → Requests ───────────────────────────────────────────────────────────── */ function fileOf(c) { @@ -270,4 +296,45 @@ admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async ( } }); +admin.delete("/feedback/:id/files/:file", requireRole("admin"), async (c) => { + const file = fileOf(c); + if (!file) return c.json({ error: "No such file." }, 404); + try { + await driveDelete(file.drive_id); + } catch (err) { + // Already gone from Drive: 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 feedback_files WHERE id = ?`).run(file.id); + inDrive.ids?.delete(file.drive_id); + console.log(`feedback #${c.req.param("id")}: file ${file.name} removed by ${c.get("user").email}`); + return c.body(null, 204); +}); + +admin.get("/request-files", async (c) => { + const db = c.get("db"); + const ids = await requestFilesInDrive(); + const rows = db + .prepare( + `SELECT f.id, f.feedback_id, f.drive_id, f.name, f.mime, f.size, + r.category, r.subject, r.request_action, r.status, r.created_at + FROM feedback_files f JOIN feedback r ON r.id = f.feedback_id + ORDER BY r.id DESC, f.id`, + ) + .all(); + return c.json( + { + files: rows.map(({ drive_id, ...row }) => ({ + ...row, + folder: TYPE_FOLDERS[row.category] ?? "", + missing: ids ? !ids.has(drive_id) : false, + })), + folders: Object.values(TYPE_FOLDERS), + checked: ids !== null, + }, + 200, + NO_STORE, + ); +}); + export default admin; diff --git a/server/src/routes/clips.js b/server/src/routes/clips.js index 70586ad..c899217 100644 --- a/server/src/routes/clips.js +++ b/server/src/routes/clips.js @@ -13,6 +13,9 @@ gone out in full, unless saved POST /clips/:id/save a finished clip into the media library + POST /clips/:id/drive { folder }: a finished clip into a + folder under Media in Drive, as a + Files entry (routes/files.js) DELETE /clips/:id a job and its files (a source takes its clips) @@ -23,6 +26,7 @@ import { createReadStream } from "node:fs"; import { stat } from "node:fs/promises"; +import path from "node:path"; import { Readable } from "node:stream"; import { Hono } from "hono"; @@ -40,6 +44,9 @@ import { toolVersions, } from "../clips.js"; import { NO_STORE } from "../shape.js"; +import { UPLOADS_DIR } from "../media.js"; +import { driveDelete, driveReady, driveShareWithAnyone, driveUploadFile } from "../googleService.js"; +import { cleanFolder, inDrive, recordDriveUpload } from "./files.js"; const clips = new Hono(); @@ -71,15 +78,19 @@ function shape(job) { has_file: Boolean(job.file), saved_media_id: job.saved_media_id, saved_url: job.saved_filename ? `/uploads/${job.saved_filename}` : null, + saved_drive: job.saved_drive_file_id + ? { id: job.saved_drive_file_id, url: job.saved_drive_url, folder: job.saved_drive_folder } + : null, downloaded_at: job.downloaded_at, created_at: job.created_at, finished_at: job.finished_at, }; } -const SELECT = `SELECT j.*, m.filename AS saved_filename +const SELECT = `SELECT j.*, m.filename AS saved_filename, d.url AS saved_drive_url, d.folder AS saved_drive_folder FROM clip_jobs j - LEFT JOIN media m ON m.id = j.saved_media_id`; + LEFT JOIN media m ON m.id = j.saved_media_id + LEFT JOIN drive_files d ON d.id = j.saved_drive_file_id`; function findOr404(c) { const id = Number(c.req.param("id")); @@ -210,6 +221,49 @@ clips.post("/clips/:id/save", async (c) => { return c.json({ media, job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(job.id)) }, 200, NO_STORE); }); +/* Into Drive: the working file, or once it's gone into the library, + the library's copy. It stays wherever it was, so a clip can be in + both, and the day's sweep still clears the working file. */ +clips.post("/clips/:id/drive", async (c) => { + const db = c.get("db"); + const job = findOr404(c); + if (job.kind !== "clip" || job.status !== "done") throw new ClipError(400, "Only a finished clip can be saved."); + if (job.saved_drive_file_id) throw new ClipError(409, "It's already in Drive."); + if (!driveReady()) throw new ClipError(400, "Google Drive isn't set up on the server (docs/google-drive-and-mail.md)."); + const folder = cleanFolder((await body(c)).folder); + if (folder === null) throw new ClipError(422, "That isn't a folder name."); + + const from = fileOf(job) ?? (job.saved_filename ? path.join(UPLOADS_DIR, job.saved_filename) : null); + if (!from) throw new ClipError(410, "That clip's file is gone. Make it again."); + const audio = from.endsWith(".mp3"); + const mime = audio ? "audio/mpeg" : "video/mp4"; + const params = job.params ? JSON.parse(job.params) : {}; + const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`; + const name = `${(job.title ?? "Clip").replace(/[\u0000-\u001f"\\/]+/g, " ").trim().slice(0, 120) || "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)}).${audio ? "mp3" : "mp4"}`; + + let uploaded; + try { + uploaded = await driveUploadFile(inDrive(folder), name, mime, from); + } catch (err) { + console.warn(`clips: clip ${job.id} to Drive failed: ${err.message}`); + throw new ClipError(502, `Google Drive didn't take it: ${err.message}`); + } + try { + await driveShareWithAnyone(uploaded.id); + } catch (err) { + await driveDelete(uploaded.id).catch(() => {}); + throw new ClipError( + 502, + `Drive wouldn't share it with anyone who has the link (${err.message}). The sharing settings must allow sharing outside the organization.`, + ); + } + const { size } = await stat(from); + const file = await recordDriveUpload(db, uploaded, { name, mime, bytes: size, folder, userId: c.get("user").id }); + db.prepare(`UPDATE clip_jobs SET saved_drive_file_id = ? WHERE id = ?`).run(file.id, job.id); + console.log(`clips: clip ${job.id} saved to Drive (${inDrive(folder)}) by ${c.get("user").email}`); + return c.json({ file, job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(job.id)) }, 200, NO_STORE); +}); + clips.delete("/clips/:id", async (c) => { const job = findOr404(c); if (job.status === "running") throw new ClipError(409, "It's running. Wait for it to finish."); diff --git a/server/src/routes/files.js b/server/src/routes/files.js index 08388f5..0b15465 100644 --- a/server/src/routes/files.js +++ b/server/src/routes/files.js @@ -65,7 +65,7 @@ import { NO_STORE } from "../shape.js"; const files = new Hono(); files.use("*", requireAuth); -const FOLDER = "Media"; +export const FOLDER = "Media"; const MAX_DEPTH = 3; /* A folder path as given, cleaned: '' for FOLDER itself, or up to @@ -79,7 +79,19 @@ export function cleanFolder(value) { 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); +export const inDrive = (folder) => (folder ? `${FOLDER}/${folder}` : FOLDER); + +/* A file just uploaded to Drive (and shared) into the list: its row, + and the first try at its preview (more follow on their own). + Returns what the list shows. Also how the clip tool's Save to Drive + lands (routes/clips.js). */ +export async function recordDriveUpload(db, uploaded, { name, mime, bytes, folder, userId }) { + const id = db + .prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)`) + .run(uploaded.id, name, mime, bytes, uploaded.webViewLink, folder, userId).lastInsertRowid; + await fetchPreview(db, db.prepare(`${SELECT} WHERE f.id = ?`).get(id), userId); + return shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id)); +} const MAX_FILE_BYTES = 50 * 1024 * 1024; const MAX_LIST = 500; // Seconds after upload to ask Drive for the preview again. @@ -270,15 +282,10 @@ files.post( ); } - const id = db - .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}`); - - // 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); + // The first preview try is waited for; Drive often has it already. + const saved = await recordDriveUpload(db, uploaded, { name, mime, bytes: buffer.length, folder, userId: user.id }); + return c.json({ file: saved }, 201, NO_STORE); }, ); diff --git a/server/src/routes/requests.js b/server/src/routes/requests.js index 7a4aa98..f64872d 100644 --- a/server/src/routes/requests.js +++ b/server/src/routes/requests.js @@ -65,9 +65,9 @@ export function cleanDetails(raw) { const MIN_MESSAGE = 10; // 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", +export const DRIVE_FOLDER = "Requests"; +export const TYPE_FOLDERS = { + blog: "Blog Posts", event: "Events", chapter: "Chapters", region: "Regions", diff --git a/src/components/ContentBlocks.tsx b/src/components/ContentBlocks.tsx index ec4ef8c..58bb73b 100644 --- a/src/components/ContentBlocks.tsx +++ b/src/components/ContentBlocks.tsx @@ -24,8 +24,9 @@ a fold-out of description, media, map); text is an optional intro. ScheduleBlock table text: a row per line, cells split by | - cards items as link cards: text the title, - detail, url, media the picture + cards items as link cards, up to three in a row: + text the title, detail, url, media the + picture divider nothing "Formatted" is InlineText.tsx: **bold**, *italic*, [text](url), @@ -95,10 +96,10 @@ function LinkCard({ item }: { item: ContentBlockItem }) { {!img.failed && ( )} - - {where} - {item.text} - {item.detail && {item.detail}} + + {where} + {item.text} + {item.detail && {item.detail}} ) @@ -224,7 +225,9 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; const cards = (block.items ?? []).filter((item) => item.url && item.text) if (cards.length === 0) return null return ( -
    + // One grid whatever the count: a lone card takes a column + // rather than the width, and more sit up to three in a row. +
      {cards.map((item, i) => (
    • diff --git a/src/lib/adminSchema/shared.ts b/src/lib/adminSchema/shared.ts index d97f2cf..9fe4e57 100644 --- a/src/lib/adminSchema/shared.ts +++ b/src/lib/adminSchema/shared.ts @@ -279,7 +279,7 @@ export const BLOCK_TYPES = [ ["video", "Video", "A YouTube, Vimeo or Facebook video, or a video file, played in place."], ["schedule", "Schedule", "Entries in one tab per day, each folding out for more. The text is an optional intro."], ["table", "Table", "A grid of text, eg. a comparison chart: one row per line, cells split by |, the first row the header."], - ["cards", "Link cards", "Cards with a picture, title and description, each a link, like a link shared in a chat. Paste a link and press Fetch preview."], + ["cards", "Link cards", "Cards with a picture, title and description, each a link to a page or a file, like a link shared in a chat; up to three in a row. Paste a link and press Fetch preview, or Choose a file."], ["divider", "Divider", "A thin line between parts."], ]; diff --git a/src/lib/version.ts b/src/lib/version.ts index 63e522a..334a4b6 100644 --- a/src/lib/version.ts +++ b/src/lib/version.ts @@ -7,4 +7,4 @@ box or a build banner can read the same value later. ═══════════════════════════════════════════════════════════════ */ -export const SITE_VERSION = "NGU-Web.v1.9.12-content-display"; +export const SITE_VERSION = "NGU-Web.v1.9.13-content-display"; diff --git a/src/pages/admin/AdminClips.tsx b/src/pages/admin/AdminClips.tsx index 0c27dc7..8a37d43 100644 --- a/src/pages/admin/AdminClips.tsx +++ b/src/pages/admin/AdminClips.tsx @@ -38,6 +38,8 @@ type Job = { has_file: boolean; saved_media_id: number | null; saved_url: string | null; + /** In Drive, under Media (Save to Drive): its Files entry. */ + saved_drive: { id: number; url: string; folder: string } | null; downloaded_at: string | null; }; @@ -87,6 +89,80 @@ const primary = const input = "rounded-lg border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25"; +/* Save to Drive: a folder under Media (Tools → Media → Files), then + the clip goes there as a Files entry. Opens on a folder named for + the clip's kind (Videos, Audio) when there is one. */ +function SaveToDrive({ clip, onSaved }: { clip: Job; onSaved: () => void }) { + const [folders, setFolders] = useState(null); + const [folder, setFolder] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const audio = clip.params?.format === "audio"; + + async function open() { + setError(null); + try { + const data = await get("/admin/files", { ttl: 0 }); + if (!data.ready) return setError("Google Drive isn't set up on the server."); + const list: string[] = data.folders ?? []; + setFolders(list); + const wanted = audio ? /^audio$/i : /^videos?$/i; + setFolder(list.find((f) => wanted.test(f)) ?? ""); + } catch (err) { + setError(err instanceof ApiError ? err.message : "Couldn't load the folders."); + } + } + + async function save() { + setBusy(true); + setError(null); + try { + await post(`/admin/clips/${clip.id}/drive`, { folder }); + onSaved(); + } catch (err) { + setError(err instanceof ApiError ? err.message : "Couldn't save it to Drive."); + setBusy(false); + } + } + + return ( + <> + {folders === null ? ( + + ) : ( + + + + + + + )} + {error && {error}} + + ); +} + function Card({ title, children }: { title: string; children: ReactNode }) { return (
      @@ -484,7 +560,15 @@ export default function AdminClips() { In the media library )} - {clip.status === "done" && !clip.has_file && !clip.saved_url && ( + {clip.status === "done" && !clip.saved_drive && (clip.has_file || clip.saved_url) && ( + + )} + {clip.saved_drive && ( + + In Drive: Media{clip.saved_drive.folder ? `/${clip.saved_drive.folder}` : ""} + + )} + {clip.status === "done" && !clip.has_file && !clip.saved_url && !clip.saved_drive && ( Downloaded, and deleted from the server @@ -505,7 +589,7 @@ export default function AdminClips() { ))}

    - A clip is deleted from the server once it's downloaded, unless it's saved to the library first. + A clip is deleted from the server once it's downloaded, unless it's saved to the library first. Save to Drive puts a copy in a folder under Media in the shared Drive, as a Files entry pages can link to. Everything here is cleared a day after it's made.

    diff --git a/src/pages/admin/AdminFeedback.tsx b/src/pages/admin/AdminFeedback.tsx index 83b2129..705e8fe 100644 --- a/src/pages/admin/AdminFeedback.tsx +++ b/src/pages/admin/AdminFeedback.tsx @@ -52,10 +52,13 @@ const sizeOf = (bytes) => (bytes < 1024 * 1024 ? `${Math.ceil(bytes / 1024)} KB` /* A content request's files: each downloads from Drive through the server, and a Word document can become a draft blog post (the same import as Blog posts → Import from Word). */ -function RequestFiles({ row, canWrite }) { +function RequestFiles({ row, canWrite, canRemove }) { const navigate = useNavigate(); + const [files, setFiles] = useState(row.files); const [busy, setBusy] = useState(null); + const [confirming, setConfirming] = useState(null); const [error, setError] = useState(null); + useEffect(() => setFiles(row.files), [row.files]); async function makePost(file) { setBusy(file.id); @@ -69,29 +72,81 @@ function RequestFiles({ row, canWrite }) { } } + async function remove(file) { + setBusy(file.id); + setError(null); + try { + await del(`/admin/feedback/${row.id}/files/${file.id}`); + setFiles((current) => current.filter((f) => f.id !== file.id)); + } catch (err) { + setError(err instanceof ApiError ? err.message : "Couldn't remove it."); + } finally { + setBusy(null); + setConfirming(null); + } + } + + if (files.length === 0) return null; + const small = "rounded-full border px-3 py-0.5 text-xs font-semibold transition-colors disabled:opacity-60"; return (
      - {row.files.map((file) => ( + {files.map((file) => (
    • - - {file.name} - + {file.missing ? ( + // Deleted or moved out of Requests in Drive: nothing to open. + {file.name} + ) : ( + + {file.name} + + )} {sizeOf(file.size)} - {canWrite && /\.docx$/i.test(file.name) && ( + {file.missing && ( + + Missing from Drive + + )} + {canWrite && !file.missing && /\.docx$/i.test(file.name) && ( )} + {canRemove && + (confirming === file.id ? ( + <> + + + + ) : ( + + ))}
    • ))}
    @@ -276,7 +331,7 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) { {row.subject &&

    {row.subject}

    }

    {row.message}

    {row.feedback_type === "content" && } - {row.files?.length > 0 && } + {row.files?.length > 0 && } {row.feedback_type === "content" && canWrite && }

    diff --git a/src/pages/admin/AdminMedia.tsx b/src/pages/admin/AdminMedia.tsx index 2f91851..f16c784 100644 --- a/src/pages/admin/AdminMedia.tsx +++ b/src/pages/admin/AdminMedia.tsx @@ -7,7 +7,9 @@ (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. + "Choose a file" picks from them. Requests: every file sent with + the Request form, by type folder in Drive, each with its request; + a file Drive no longer has is marked missing. Two ranks, as on the server: editors and up upload, admins and up delete. A delete first asks the server which records still @@ -15,7 +17,8 @@ a page (an image field stores the path, not a foreign key). ═══════════════════════════════════════════════════════════════ */ -import { useState } from "react"; +import { useEffect, useState } from "react"; +import { Link } from "react-router-dom"; import { ApiError, del, get, patch, post } from "../../lib/api.ts"; import { useAuth } from "../../lib/auth.tsx"; @@ -33,6 +36,7 @@ import { } from "../../components/admin/DriveFiles.tsx"; import { FolderTabs, + formatBytes, MediaGrid, UPLOAD_HELP, UploadButton, @@ -356,14 +360,131 @@ function FilesTab() { ); } +/* Request form files, by their type's folder in Drive (Requests/…). */ +function RequestFilesTab() { + const { user } = useAuth(); + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [folder, setFolder] = useState("*"); + const [confirming, setConfirming] = useState(null); + const [busy, setBusy] = useState(false); + + useEffect(() => { + get("/admin/request-files", { ttl: 0 }) + .then(setData) + .catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the request files.")); + }, []); + + async function remove(file) { + setBusy(true); + setError(null); + try { + await del(`/admin/feedback/${file.feedback_id}/files/${file.id}`); + setData((current) => ({ ...current, files: current.files.filter((f) => f.id !== file.id) })); + } catch (err) { + setError(err instanceof ApiError ? err.message : "Couldn't remove it."); + } finally { + setBusy(false); + setConfirming(null); + } + } + + if (error && !data) return

    {error}

    ; + if (!data) return

    Loading…

    ; + const counts = new Map(); + for (const f of data.files) counts.set(f.folder, (counts.get(f.folder) ?? 0) + 1); + const shown = folder === "*" ? data.files : data.files.filter((f) => f.folder === folder); + + return ( +
    +
    + {[["*", "All"], ...data.folders.map((f) => [f, f])].map(([id, label]) => ( + + ))} +
    + {!data.checked && ( +

    Drive couldn't be asked just now, so missing files aren't marked.

    + )} + {error &&

    {error}

    } + + {shown.length === 0 ? ( +

    No request files here.

    + ) : ( +
      + {shown.map((file) => ( +
    • + {file.missing ? ( + {file.name} + ) : ( + + {file.name} + + )} + {formatBytes(file.size)} + {file.missing && ( + Missing from Drive + )} + + Request #{file.feedback_id} + {file.subject ? `: ${file.subject}` : ""} ({file.status}) + + {canDelete(user) && ( + + {confirming === file.id ? ( + <> + {" "} + + + ) : ( + + )} + + )} +
    • + ))} +
    + )} +
    + ); +} + const TABS = [ ["images", "Images"], ["files", "Files"], + ["requests", "Requests"], ] as const; export default function AdminMedia() { const { user } = useAuth(); - const [tab, setTab] = useState<"images" | "files">("images"); + const [tab, setTab] = useState<(typeof TABS)[number][0]>("images"); // The image folder showing; "" is all of them, clips included. const [folder, setFolder] = useState(""); const [query, setQuery] = useState(""); @@ -376,7 +497,9 @@ export default function AdminMedia() {

    {tab === "images" ? "Uploaded images. Image fields in every editor pick from here." - : "Files in the shared Google Drive's Media folder, for pages to link to, including any put there in Drive itself. Link fields pick from here with Choose a file."} + : tab === "files" + ? "Files in the shared Google Drive's Media folder, for pages to link to, including any put there in Drive itself. Link fields pick from here with Choose a file." + : "Files sent with the Request form, in the shared Google Drive's Requests folder. Removing one takes it off its request too."}

    @@ -397,7 +520,9 @@ export default function AdminMedia() { ))} - {tab === "files" ? ( + {tab === "requests" ? ( + + ) : tab === "files" ? ( ) : ( <>