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
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;
|
||||
Loading…
Add table
Add a link
Reference in a new issue