Compare commits

..

No commits in common. "f983ecf26c132d2ee3ce7055da23ce102a836361" and "a98aea6bca4ae853666e95aabc83fb4c1e90ef1a" have entirely different histories.

14 changed files with 60 additions and 525 deletions

View file

@ -60,7 +60,7 @@ hand.
| Folder | Used by | Set in | | Folder | Used by | Set in |
| --- | --- | --- | | --- | --- | --- |
| `Requests/<type>` | 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/<type>` | 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` | | `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("<Folder>", name, mime, bytes)` from A new use calls `driveUpload("<Folder>", name, mime, bytes)` from
@ -81,14 +81,6 @@ matches the one in Forms → Content requests. Deleting a request in the
admin deletes its files from Drive too. Request files from before the admin deletes its files from Drive too. Request files from before the
per-type folders stay where they are, in `Requests` itself. 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 **Deleting means Drive's trash.** Whatever the admin deletes (a
request's files, a file, an empty folder) goes to the shared drive's 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 trash, which keeps it 30 days; restore it from there if needed. A

View file

@ -14,16 +14,6 @@ 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 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. 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 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 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`. to an hour. Limits are constants at the top of `server/src/clips.js`.

View file

@ -32,9 +32,7 @@
Setup: docs/google-drive-and-mail.md. Setup: docs/google-drive-and-mail.md.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { createReadStream, readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { createSign } from "node:crypto"; import { createSign } from "node:crypto";
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive"; const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
@ -101,11 +99,11 @@ async function accessToken(scope, subject) {
return data.access_token; return data.access_token;
} }
async function call(url, init, scope, subject, timeoutMs = 60_000) { async function call(url, init, scope, subject) {
const res = await fetch(url, { const res = await fetch(url, {
...init, ...init,
headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` }, headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` },
signal: AbortSignal.timeout(timeoutMs), signal: AbortSignal.timeout(60_000),
}); });
if (!res.ok) { if (!res.ok) {
const detail = await res.json().catch(() => null); const detail = await res.json().catch(() => null);
@ -145,12 +143,7 @@ export function forgetFolders(path) {
async function findOrMakeFolder(path) { async function findOrMakeFolder(path) {
const drive = process.env.GOOGLE_SHARED_DRIVE; const drive = process.env.GOOGLE_SHARED_DRIVE;
let parent = drive; let parent = drive;
const walked = [];
for (const name of path.split("/").filter(Boolean)) { 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 quoted = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const query = new URLSearchParams({ const query = new URLSearchParams({
q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`, q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`,
@ -272,41 +265,6 @@ 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. /* Anyone with the link can view: for files the public site links to.
Refused when the shared drive (or the Workspace) doesn't allow Refused when the shared drive (or the Workspace) doesn't allow
sharing outside the organization. */ sharing outside the organization. */

View file

@ -1,10 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 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;

View file

@ -11,8 +11,7 @@
import { Hono } from "hono"; import { Hono } from "hono";
import { requireAuth, requireRole } from "../auth.js"; import { requireAuth, requireRole } from "../auth.js";
import { NO_STORE } from "../shape.js"; import { NO_STORE } from "../shape.js";
import { driveDelete, driveDownload, driveReady, driveTree } from "../googleService.js"; import { driveDelete, driveDownload } from "../googleService.js";
import { DRIVE_FOLDER, TYPE_FOLDERS } from "./requests.js";
import { HttpError } from "../admin-crud.js"; import { HttpError } from "../admin-crud.js";
import { importDocx } from "./import.js"; import { importDocx } from "./import.js";
@ -33,31 +32,12 @@ const KIND_WHERE = {
const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id, const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id,
status, admin_note, category, request_action, subject, details`; status, admin_note, category, request_action, subject, details`;
/* The ids of every file under Requests in Drive (any type folder), /* Each row with its files (content requests), in one query. */
looked up at most every 30 seconds; null when Drive isn't set up or function withFiles(db, rows) {
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; if (rows.length === 0) return rows;
const files = db const files = db
.prepare( .prepare(
`SELECT id, feedback_id, drive_id, name, mime, size FROM feedback_files `SELECT id, feedback_id, name, mime, size FROM feedback_files
WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`, WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`,
) )
.all(...rows.map((r) => r.id)); .all(...rows.map((r) => r.id));
@ -65,9 +45,7 @@ function withFiles(db, rows, ids = null) {
...row, ...row,
// Stored as JSON text (049); the admin wants the object. // Stored as JSON text (049); the admin wants the object.
details: row.details ? JSON.parse(row.details) : null, details: row.details ? JSON.parse(row.details) : null,
files: files files: files.filter((f) => f.feedback_id === row.id).map(({ feedback_id, ...f }) => f),
.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; const MAX_LIMIT = 200;
@ -84,7 +62,7 @@ const NOTE_LIMIT = 2000;
?limit=50 ?limit=50
───────────────────────────────────────────────────────────── */ ───────────────────────────────────────────────────────────── */
admin.get("/feedback", async (c) => { admin.get("/feedback", (c) => {
const db = c.get("db"); const db = c.get("db");
const { status, type, kind, q, before, limit } = c.req.query(); const { status, type, kind, q, before, limit } = c.req.query();
@ -124,7 +102,7 @@ admin.get("/feedback", async (c) => {
.all(...params, take + 1); // one extra to detect a next page .all(...params, take + 1); // one extra to detect a next page
const hasMore = rows.length > take; const hasMore = rows.length > take;
const page = withFiles(db, hasMore ? rows.slice(0, take) : rows, kind === "content" ? await requestFilesInDrive() : null); const page = withFiles(db, hasMore ? rows.slice(0, take) : rows);
// Status counts cover this queue (kind) but ignore the other // Status counts cover this queue (kind) but ignore the other
// filters: the tabs show what's waiting, not what's left after a // filters: the tabs show what's waiting, not what's left after a
@ -194,7 +172,7 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400); if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
const result = db_update(c.get("db"), id, sets, params, await requestFilesInDrive()); const result = db_update(c.get("db"), id, sets, params);
if (!result) return c.json({ error: "No such feedback." }, 404); if (!result) return c.json({ error: "No such feedback." }, 404);
console.log(`feedback #${id} updated by ${c.get("user").email}`); console.log(`feedback #${id} updated by ${c.get("user").email}`);
@ -202,14 +180,14 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
return c.json({ feedback: result }, 200, NO_STORE); return c.json({ feedback: result }, 200, NO_STORE);
}); });
function db_update(db, id, sets, params, ids) { function db_update(db, id, sets, params) {
const changed = db const changed = db
.prepare(`UPDATE feedback SET ${sets.join(", ")} WHERE id = ?`) .prepare(`UPDATE feedback SET ${sets.join(", ")} WHERE id = ?`)
.run(...params, id); .run(...params, id);
if (changed.changes === 0) return null; if (changed.changes === 0) return null;
return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)], ids)[0]; return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)])[0];
} }
/* ── DELETE /api/admin/feedback/:id ────────────────────────────── /* ── DELETE /api/admin/feedback/:id ──────────────────────────────
@ -246,10 +224,6 @@ admin.delete("/feedback/:id", requireRole("admin"), async (c) => {
GET /feedback/:id/files/:file download, from Drive GET /feedback/:id/files/:file download, from Drive
POST /feedback/:id/files/:file/blog-post a .docx as a new POST /feedback/:id/files/:file/blog-post a .docx as a new
unpublished blog post (import.js), editors and up 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) { function fileOf(c) {
@ -296,45 +270,4 @@ 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; export default admin;

View file

@ -13,9 +13,6 @@
gone out in full, unless saved gone out in full, unless saved
POST /clips/:id/save a finished clip into the media POST /clips/:id/save a finished clip into the media
library 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 DELETE /clips/:id a job and its files (a source
takes its clips) takes its clips)
@ -26,7 +23,6 @@
import { createReadStream } from "node:fs"; import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises"; import { stat } from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream"; import { Readable } from "node:stream";
import { Hono } from "hono"; import { Hono } from "hono";
@ -44,9 +40,6 @@ import {
toolVersions, toolVersions,
} from "../clips.js"; } from "../clips.js";
import { NO_STORE } from "../shape.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(); const clips = new Hono();
@ -78,19 +71,15 @@ function shape(job) {
has_file: Boolean(job.file), has_file: Boolean(job.file),
saved_media_id: job.saved_media_id, saved_media_id: job.saved_media_id,
saved_url: job.saved_filename ? `/uploads/${job.saved_filename}` : null, 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, downloaded_at: job.downloaded_at,
created_at: job.created_at, created_at: job.created_at,
finished_at: job.finished_at, finished_at: job.finished_at,
}; };
} }
const SELECT = `SELECT j.*, m.filename AS saved_filename, d.url AS saved_drive_url, d.folder AS saved_drive_folder const SELECT = `SELECT j.*, m.filename AS saved_filename
FROM clip_jobs j 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) { function findOr404(c) {
const id = Number(c.req.param("id")); const id = Number(c.req.param("id"));
@ -221,49 +210,6 @@ 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); 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) => { clips.delete("/clips/:id", async (c) => {
const job = findOr404(c); const job = findOr404(c);
if (job.status === "running") throw new ClipError(409, "It's running. Wait for it to finish."); if (job.status === "running") throw new ClipError(409, "It's running. Wait for it to finish.");

View file

@ -65,7 +65,7 @@ import { NO_STORE } from "../shape.js";
const files = new Hono(); const files = new Hono();
files.use("*", requireAuth); files.use("*", requireAuth);
export const FOLDER = "Media"; const FOLDER = "Media";
const MAX_DEPTH = 3; const MAX_DEPTH = 3;
/* A folder path as given, cleaned: '' for FOLDER itself, or up to /* A folder path as given, cleaned: '' for FOLDER itself, or up to
@ -79,19 +79,7 @@ export function cleanFolder(value) {
if (parts.length > MAX_DEPTH || parts.some((part) => part.length > 60 || part === "." || part === "..")) return null; if (parts.length > MAX_DEPTH || parts.some((part) => part.length > 60 || part === "." || part === "..")) return null;
return parts.join("/"); return parts.join("/");
} }
export const inDrive = (folder) => (folder ? `${FOLDER}/${folder}` : FOLDER); 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_FILE_BYTES = 50 * 1024 * 1024;
const MAX_LIST = 500; const MAX_LIST = 500;
// Seconds after upload to ask Drive for the preview again. // Seconds after upload to ask Drive for the preview again.
@ -282,10 +270,15 @@ 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}`); console.log(`files: ${name} uploaded by ${user.email}`);
// 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 }); // The first try is waited for; Drive often has the picture already.
return c.json({ file: saved }, 201, NO_STORE); await fetchPreview(db, row, user.id);
return c.json({ file: shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id)) }, 201, NO_STORE);
}, },
); );

View file

@ -65,9 +65,9 @@ export function cleanDetails(raw) {
const MIN_MESSAGE = 10; const MIN_MESSAGE = 10;
// Where in the shared drive the files go (googleService.js): a // Where in the shared drive the files go (googleService.js): a
// folder per type under Requests, eg. Requests/Chapters. // folder per type under Requests, eg. Requests/Chapters.
export const DRIVE_FOLDER = "Requests"; const DRIVE_FOLDER = "Requests";
export const TYPE_FOLDERS = { const TYPE_FOLDERS = {
blog: "Blog Posts", blog: "Blog posts",
event: "Events", event: "Events",
chapter: "Chapters", chapter: "Chapters",
region: "Regions", region: "Regions",

View file

@ -24,9 +24,8 @@
a fold-out of description, media, map); a fold-out of description, media, map);
text is an optional intro. ScheduleBlock text is an optional intro. ScheduleBlock
table text: a row per line, cells split by | table text: a row per line, cells split by |
cards items as link cards, up to three in a row: cards items as link cards: text the title,
text the title, detail, url, media the detail, url, media the picture
picture
divider nothing divider nothing
"Formatted" is InlineText.tsx: **bold**, *italic*, [text](url), "Formatted" is InlineText.tsx: **bold**, *italic*, [text](url),
@ -96,10 +95,10 @@ function LinkCard({ item }: { item: ContentBlockItem }) {
{!img.failed && ( {!img.failed && (
<img src={img.src} alt="" loading="lazy" onError={img.onError} className="aspect-video w-full object-cover" /> <img src={img.src} alt="" loading="lazy" onError={img.onError} className="aspect-video w-full object-cover" />
)} )}
<span className="flex flex-1 flex-col gap-1 p-4"> <span className="flex flex-1 flex-col gap-1 p-5">
<span className="truncate text-xs font-semibold text-muted">{where}</span> <span className="text-xs font-semibold text-muted">{where}</span>
<span className="font-display text-base font-bold leading-snug text-ink group-hover:text-link">{item.text}</span> <span className="font-display text-lg font-bold leading-snug text-ink group-hover:text-link">{item.text}</span>
{item.detail && <span className="line-clamp-3 text-sm leading-snug text-body">{item.detail}</span>} {item.detail && <span className="line-clamp-3 text-sm text-body">{item.detail}</span>}
</span> </span>
</Anchor> </Anchor>
) )
@ -225,9 +224,7 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string;
const cards = (block.items ?? []).filter((item) => item.url && item.text) const cards = (block.items ?? []).filter((item) => item.url && item.text)
if (cards.length === 0) return null if (cards.length === 0) return null
return ( return (
// One grid whatever the count: a lone card takes a column <ul className={cards.length === 1 ? 'max-w-xl' : 'grid gap-4 sm:grid-cols-2'}>
// rather than the width, and more sit up to three in a row.
<ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{cards.map((item, i) => ( {cards.map((item, i) => (
<li key={i}> <li key={i}>
<LinkCard item={item} /> <LinkCard item={item} />

View file

@ -279,7 +279,7 @@ export const BLOCK_TYPES = [
["video", "Video", "A YouTube, Vimeo or Facebook video, or a video file, played in place."], ["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."], ["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."], ["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 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."], ["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."],
["divider", "Divider", "A thin line between parts."], ["divider", "Divider", "A thin line between parts."],
]; ];

View file

@ -7,4 +7,4 @@
box or a build banner can read the same value later. box or a build banner can read the same value later.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
export const SITE_VERSION = "NGU-Web.v1.9.13-content-display"; export const SITE_VERSION = "NGU-Web.v1.9.12-content-display";

View file

@ -38,8 +38,6 @@ type Job = {
has_file: boolean; has_file: boolean;
saved_media_id: number | null; saved_media_id: number | null;
saved_url: string | 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; downloaded_at: string | null;
}; };
@ -89,80 +87,6 @@ const primary =
const input = 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"; "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<string[] | null>(null);
const [folder, setFolder] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(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 ? (
<button type="button" className={button} onClick={open}>
Save to Drive
</button>
) : (
<span className="flex flex-wrap items-center gap-2">
<label className="sr-only" htmlFor={`drive-folder-${clip.id}`}>
Folder in Drive
</label>
<select
id={`drive-folder-${clip.id}`}
value={folder}
disabled={busy}
onChange={(e) => setFolder(e.target.value)}
className="rounded-lg border border-muted/25 bg-surface px-2 py-1 text-sm text-body"
>
<option value="">Media (not in a folder)</option>
{folders.map((f) => (
<option key={f} value={f}>
Media/{f}
</option>
))}
</select>
<button type="button" className={button} disabled={busy} onClick={save}>
{busy ? "Uploading…" : "Save"}
</button>
<button type="button" className="text-sm" style={{ color: MUTED }} onClick={() => setFolders(null)}>
Cancel
</button>
</span>
)}
{error && <span className="text-sm text-danger">{error}</span>}
</>
);
}
function Card({ title, children }: { title: string; children: ReactNode }) { function Card({ title, children }: { title: string; children: ReactNode }) {
return ( return (
<section className="mt-6 rounded-2xl border border-brand/20 bg-surface p-5"> <section className="mt-6 rounded-2xl border border-brand/20 bg-surface p-5">
@ -560,15 +484,7 @@ export default function AdminClips() {
In the media library In the media library
</Link> </Link>
)} )}
{clip.status === "done" && !clip.saved_drive && (clip.has_file || clip.saved_url) && ( {clip.status === "done" && !clip.has_file && !clip.saved_url && (
<SaveToDrive clip={clip} onSaved={load} />
)}
{clip.saved_drive && (
<a href={clip.saved_drive.url} target="_blank" rel="noreferrer" className="text-sm underline" style={{ color: accentText(BRAND) }}>
In Drive: Media{clip.saved_drive.folder ? `/${clip.saved_drive.folder}` : ""}
</a>
)}
{clip.status === "done" && !clip.has_file && !clip.saved_url && !clip.saved_drive && (
<span className="text-sm" style={{ color: MUTED }}> <span className="text-sm" style={{ color: MUTED }}>
Downloaded, and deleted from the server Downloaded, and deleted from the server
</span> </span>
@ -589,7 +505,7 @@ export default function AdminClips() {
))} ))}
</ul> </ul>
<p className="mt-3 text-xs" style={{ color: MUTED }}> <p className="mt-3 text-xs" style={{ color: MUTED }}>
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. A clip is deleted from the server once it's downloaded, unless it's saved to the library first.
Everything here is cleared a day after it's made. Everything here is cleared a day after it's made.
</p> </p>
</Card> </Card>

View file

@ -52,13 +52,10 @@ const sizeOf = (bytes) => (bytes < 1024 * 1024 ? `${Math.ceil(bytes / 1024)} KB`
/* A content request's files: each downloads from Drive through the /* A content request's files: each downloads from Drive through the
server, and a Word document can become a draft blog post server, and a Word document can become a draft blog post
(the same import as Blog posts → Import from Word). */ (the same import as Blog posts → Import from Word). */
function RequestFiles({ row, canWrite, canRemove }) { function RequestFiles({ row, canWrite }) {
const navigate = useNavigate(); const navigate = useNavigate();
const [files, setFiles] = useState<any[]>(row.files);
const [busy, setBusy] = useState<number | null>(null); const [busy, setBusy] = useState<number | null>(null);
const [confirming, setConfirming] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
useEffect(() => setFiles(row.files), [row.files]);
async function makePost(file) { async function makePost(file) {
setBusy(file.id); setBusy(file.id);
@ -72,31 +69,11 @@ function RequestFiles({ row, canWrite, canRemove }) {
} }
} }
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 ( return (
<div className="mt-4"> <div className="mt-4">
<ul className="space-y-2"> <ul className="space-y-2">
{files.map((file) => ( {row.files.map((file) => (
<li key={file.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm"> <li key={file.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
{file.missing ? (
// Deleted or moved out of Requests in Drive: nothing to open.
<span className="font-medium text-muted line-through">{file.name}</span>
) : (
<a <a
href={`/api/admin/feedback/${row.id}/files/${file.id}`} href={`/api/admin/feedback/${row.id}/files/${file.id}`}
download={file.name} download={file.name}
@ -104,49 +81,17 @@ function RequestFiles({ row, canWrite, canRemove }) {
> >
{file.name} {file.name}
</a> </a>
)}
<span className="text-xs text-muted">{sizeOf(file.size)}</span> <span className="text-xs text-muted">{sizeOf(file.size)}</span>
{file.missing && ( {canWrite && /\.docx$/i.test(file.name) && (
<span className="rounded-full bg-danger-tint px-2 py-0.5 text-xs font-medium text-danger">
Missing from Drive
</span>
)}
{canWrite && !file.missing && /\.docx$/i.test(file.name) && (
<button <button
type="button" type="button"
disabled={busy !== null} disabled={busy !== null}
onClick={() => makePost(file)} onClick={() => makePost(file)}
className={`${small} border-link text-link hover:bg-tint`} className="rounded-full border border-link px-3 py-0.5 text-xs font-semibold text-link transition-colors hover:bg-tint disabled:opacity-60"
> >
{busy === file.id ? "Making the post…" : "Make a blog post from it"} {busy === file.id ? "Making the post…" : "Make a blog post from it"}
</button> </button>
)} )}
{canRemove &&
(confirming === file.id ? (
<>
<button
type="button"
disabled={busy !== null}
onClick={() => remove(file)}
className={`${small} border-danger bg-danger text-white`}
>
{busy === file.id ? "Removing…" : "Remove it"}
</button>
<button type="button" onClick={() => setConfirming(null)} className="text-xs text-muted hover:underline">
Keep it
</button>
</>
) : (
<button
type="button"
disabled={busy !== null}
onClick={() => setConfirming(file.id)}
className="text-xs text-muted hover:text-danger"
title={file.missing ? "Take it off this request" : "Into Drive's trash, and off this request"}
>
Remove
</button>
))}
</li> </li>
))} ))}
</ul> </ul>
@ -331,7 +276,7 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
{row.subject && <h2 className="mt-4 text-lg font-semibold text-body">{row.subject}</h2>} {row.subject && <h2 className="mt-4 text-lg font-semibold text-body">{row.subject}</h2>}
<p className={`${row.subject ? "mt-2" : "mt-4"} whitespace-pre-wrap text-body`}>{row.message}</p> <p className={`${row.subject ? "mt-2" : "mt-4"} whitespace-pre-wrap text-body`}>{row.message}</p>
{row.feedback_type === "content" && <RequestDetails row={row} />} {row.feedback_type === "content" && <RequestDetails row={row} />}
{row.files?.length > 0 && <RequestFiles row={row} canWrite={canWrite} canRemove={canRemove} />} {row.files?.length > 0 && <RequestFiles row={row} canWrite={canWrite} />}
{row.feedback_type === "content" && canWrite && <RequestRecord row={row} />} {row.feedback_type === "content" && canWrite && <RequestRecord row={row} />}
<p className="mt-4 text-sm text-muted"> <p className="mt-4 text-sm text-muted">

View file

@ -7,9 +7,7 @@
(MediaLibrary.tsx), so this is housekeeping rather than the way (MediaLibrary.tsx), so this is housekeeping rather than the way
images get in. Files: documents, audio and zips in the shared images get in. Files: documents, audio and zips in the shared
Google Drive, for pages to link to (DriveFiles.tsx); link fields' Google Drive, for pages to link to (DriveFiles.tsx); link fields'
"Choose a file" picks from them. Requests: every file sent with "Choose a file" picks from them.
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 Two ranks, as on the server: editors and up upload, admins and
up delete. A delete first asks the server which records still up delete. A delete first asks the server which records still
@ -17,8 +15,7 @@
a page (an image field stores the path, not a foreign key). a page (an image field stores the path, not a foreign key).
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { useEffect, useState } from "react"; import { useState } from "react";
import { Link } from "react-router-dom";
import { ApiError, del, get, patch, post } from "../../lib/api.ts"; import { ApiError, del, get, patch, post } from "../../lib/api.ts";
import { useAuth } from "../../lib/auth.tsx"; import { useAuth } from "../../lib/auth.tsx";
@ -36,7 +33,6 @@ import {
} from "../../components/admin/DriveFiles.tsx"; } from "../../components/admin/DriveFiles.tsx";
import { import {
FolderTabs, FolderTabs,
formatBytes,
MediaGrid, MediaGrid,
UPLOAD_HELP, UPLOAD_HELP,
UploadButton, UploadButton,
@ -360,131 +356,14 @@ function FilesTab() {
); );
} }
/* Request form files, by their type's folder in Drive (Requests/…). */
function RequestFilesTab() {
const { user } = useAuth();
const [data, setData] = useState<any>(null);
const [error, setError] = useState<string | null>(null);
const [folder, setFolder] = useState("*");
const [confirming, setConfirming] = useState<number | null>(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 <p className="mt-6 text-sm text-danger">{error}</p>;
if (!data) return <p className="mt-6 text-sm text-muted">Loading…</p>;
const counts = new Map<string, number>();
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 (
<div className="mt-6">
<div role="tablist" aria-label="Request folders" className="flex flex-wrap gap-1">
{[["*", "All"], ...data.folders.map((f) => [f, f])].map(([id, label]) => (
<button
key={id}
type="button"
role="tab"
aria-selected={folder === id}
onClick={() => setFolder(id)}
className={
"rounded-full px-3 py-1 text-sm transition-colors " +
(folder === id ? "bg-action font-semibold text-white" : "border border-muted/25 text-muted hover:border-brand/50")
}
>
{label}
{id !== "*" && counts.get(id) ? ` (${counts.get(id)})` : ""}
</button>
))}
</div>
{!data.checked && (
<p className="mt-3 text-sm text-muted">Drive couldn't be asked just now, so missing files aren't marked.</p>
)}
{error && <p className="mt-3 text-sm text-danger">{error}</p>}
{shown.length === 0 ? (
<p className="mt-6 text-sm text-muted">No request files here.</p>
) : (
<ul className="mt-6 divide-y divide-brand/10 rounded-2xl border border-brand/20 bg-surface">
{shown.map((file) => (
<li key={file.id} className="flex flex-wrap items-center gap-x-4 gap-y-1 px-4 py-3 text-sm">
{file.missing ? (
<span className="font-medium text-muted line-through">{file.name}</span>
) : (
<a
href={`/api/admin/feedback/${file.feedback_id}/files/${file.id}`}
download={file.name}
className="font-medium text-link underline underline-offset-2"
>
{file.name}
</a>
)}
<span className="text-xs text-muted">{formatBytes(file.size)}</span>
{file.missing && (
<span className="rounded-full bg-danger-tint px-2 py-0.5 text-xs font-medium text-danger">Missing from Drive</span>
)}
<Link to="/admin/requests" className="text-xs text-muted hover:text-link hover:underline">
Request #{file.feedback_id}
{file.subject ? `: ${file.subject}` : ""} ({file.status})
</Link>
{canDelete(user) && (
<span className="ml-auto">
{confirming === file.id ? (
<>
<button
type="button"
disabled={busy}
onClick={() => remove(file)}
className="rounded-full bg-danger px-3 py-0.5 text-xs font-semibold text-white disabled:opacity-60"
>
{busy ? "Removing…" : "Remove it"}
</button>{" "}
<button type="button" onClick={() => setConfirming(null)} className="text-xs text-muted hover:underline">
Keep it
</button>
</>
) : (
<button type="button" onClick={() => setConfirming(file.id)} className="text-xs text-muted hover:text-danger">
Remove
</button>
)}
</span>
)}
</li>
))}
</ul>
)}
</div>
);
}
const TABS = [ const TABS = [
["images", "Images"], ["images", "Images"],
["files", "Files"], ["files", "Files"],
["requests", "Requests"],
] as const; ] as const;
export default function AdminMedia() { export default function AdminMedia() {
const { user } = useAuth(); const { user } = useAuth();
const [tab, setTab] = useState<(typeof TABS)[number][0]>("images"); const [tab, setTab] = useState<"images" | "files">("images");
// The image folder showing; "" is all of them, clips included. // The image folder showing; "" is all of them, clips included.
const [folder, setFolder] = useState(""); const [folder, setFolder] = useState("");
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
@ -497,9 +376,7 @@ export default function AdminMedia() {
<p className="text-sm text-muted"> <p className="text-sm text-muted">
{tab === "images" {tab === "images"
? "Uploaded images. Image fields in every editor pick from here." ? "Uploaded images. Image fields in every editor pick from here."
: 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 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."}
</p> </p>
</div> </div>
@ -520,9 +397,7 @@ export default function AdminMedia() {
))} ))}
</nav> </nav>
{tab === "requests" ? ( {tab === "files" ? (
<RequestFilesTab />
) : tab === "files" ? (
<FilesTab /> <FilesTab />
) : ( ) : (
<> <>