Add a file library in Google Drive for pages to link to
Tools → Media → Files uploads PDF, Office (.docx, .xlsx, .pptx), MP3, M4A and zip files, up to 50 MB, to the shared drive's Blog folder and shares each as anyone with the link can view (migration 048). A file's name and contents must agree. Content block links get "Choose a file" (paragraph, button and image links, list and link items, link cards). A link card also takes the file's name and Drive's picture of its first page, fetched after upload and saved into the image library; cards to Drive say "Google Drive". Deleting a file says first what still links to it. Setup and the nginx block: docs/google-drive-and-mail.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
36c9226bd9
commit
934598f954
13 changed files with 772 additions and 33 deletions
|
|
@ -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}`);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue