Pick up files added to the Blog folder in Drive, and name nginx errors

Opening Tools → Media → Files (or a Choose a file picker) now looks in
the shared drive's Blog folder, at most every 30 seconds, and adds
anything put there in Drive itself: shared as anyone with the link,
previewed, Google Docs, Sheets and Slides included, folders and
shortcuts left out. A file Drive won't share is named in a note and
tried again every ten minutes.

A reply that isn't the API's (nginx's own error page) now says what it
was: a 413 names nginx's upload limit, a 502 the service, a 504 the
timeout, instead of "Server did not return JSON".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-29 19:14:40 -05:00
parent 5f13273e69
commit 6191322fea
6 changed files with 143 additions and 25 deletions

View file

@ -1,7 +1,10 @@
/* ═══════════════════════════════════════════════════════════════
FILE ROUTES: mounted under /api/admin
GET /files the files, newest first, ?q=name
GET /files the files, newest first, ?q=name.
Picks up files put in the folder
in Drive by hand first (pickUp, at
most every SCAN_EVERY_MS)
POST /files upload one (multipart: file)
GET /files/:id/uses which records link to it
DELETE /files/:id out of Drive and the list
@ -17,6 +20,12 @@
again over the next few minutes (PREVIEW_TRIES), and saved into the
media library as an ordinary upload when it comes.
Files added to the folder in Drive itself (not through here) are
listed too: the next look at the list finds them, shares them the
same way and fetches their previews. Google's own Docs, Sheets and
Slides count; folders and shortcuts don't. One that Drive won't
share is left out and named in the list's `refused`.
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).
@ -26,7 +35,7 @@ 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 { driveDelete, driveList, driveReady, driveShareWithAnyone, driveThumbnail, driveUpload } from "../googleService.js";
import { addToLibrary, recordsNaming } from "./media.js";
import { NO_STORE } from "../shape.js";
@ -38,6 +47,9 @@ 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];
// How often listing the files looks in the Drive folder for new ones.
const SCAN_EVERY_MS = 30_000;
const SKIP_TYPES = new Set(["application/vnd.google-apps.folder", "application/vnd.google-apps.shortcut"]);
/* 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
@ -101,13 +113,52 @@ function fetchPreview(db, row, userId) {
return next();
}
files.get("/files", (c) => {
/* Files put in the folder in Drive by hand, added to the list and
shared. A file Drive won't share is tried again after RETRY_MS, not
on every look (a sharing setting fixed in the meantime then takes).
Never throws: the list still shows what's known. */
const RETRY_MS = 10 * 60 * 1000;
let lastScan = 0;
const refused = new Map(); // drive id → { name, at }
async function pickUp(db) {
if (!driveReady() || Date.now() - lastScan < SCAN_EVERY_MS) return;
lastScan = Date.now();
let found;
try {
found = await driveList(FOLDER);
} catch (err) {
console.warn(`files: couldn't list the ${FOLDER} folder: ${err.message}`);
return;
}
const known = new Set(db.prepare(`SELECT drive_id FROM drive_files`).all().map((r) => r.drive_id));
for (const file of found) {
if (known.has(file.id) || SKIP_TYPES.has(file.mimeType)) continue;
if (Date.now() - (refused.get(file.id)?.at ?? 0) < RETRY_MS) continue;
try {
await driveShareWithAnyone(file.id);
} catch (err) {
console.warn(`files: ${file.name} (added in Drive) not shared: ${err.message}`);
refused.set(file.id, { name: file.name, at: Date.now() });
continue;
}
refused.delete(file.id);
const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url) VALUES (?, ?, ?, ?, ?)`)
.run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink).lastInsertRowid;
console.log(`files: ${file.name} picked up from Drive`);
// In the background: a folder of new files shouldn't hold the list.
fetchPreview(db, db.prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id), null);
}
}
files.get("/files", async (c) => {
await pickUp(c.get("db"));
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);
return c.json({ files: rows.map(shape), ready: driveReady(), refused: [...refused.values()].map((r) => r.name) }, 200, NO_STORE);
});
files.post(