Content display, requests and Google Workspace (v1.9.5 to v1.9.11-content-display) #15
6 changed files with 143 additions and 25 deletions
|
|
@ -189,10 +189,24 @@ Drive" above the title.
|
||||||
little after upload. The server asks at once and again over the next
|
little after upload. The server asks at once and again over the next
|
||||||
few minutes, and saves it into the image library as an ordinary
|
few minutes, and saves it into the image library as an ordinary
|
||||||
upload. Audio and zips get an icon in the admin and no picture.
|
upload. Audio and zips get an icon in the admin and no picture.
|
||||||
|
- **Files put in the Blog folder in Drive itself** (dragged in, made
|
||||||
|
there, moved there) are listed too: opening the Files tab or a
|
||||||
|
"Choose a file" picker looks in the folder (at most every 30
|
||||||
|
seconds), adds anything new, shares it the same way and fetches its
|
||||||
|
preview. Google's own Docs, Sheets and Slides count; folders inside it
|
||||||
|
and shortcuts don't. A file Drive won't share with anyone who has the
|
||||||
|
link is named in a red note instead of listed, and tried again every
|
||||||
|
ten minutes.
|
||||||
- Deleting a file in the admin deletes it from Drive; the delete says
|
- Deleting a file in the admin deletes it from Drive; the delete says
|
||||||
first which records still link to it (those links stop working).
|
first which records still link to it (those links stop working).
|
||||||
Deleting it in Drive by hand leaves a broken link and a list entry
|
Deleting it in Drive by hand leaves a broken link and a list entry
|
||||||
that can still be deleted.
|
that can still be deleted.
|
||||||
|
- **"Too large for the web server (HTTP 413)"** on upload (older builds
|
||||||
|
said "Server did not return JSON", with nothing in the journal): nginx
|
||||||
|
refused the file before it reached the API, because the site has no
|
||||||
|
`location = /api/admin/files` block (above), so the 64k `/api/` limit
|
||||||
|
applies. `sudo tail /var/log/nginx/error.log` shows "client intended
|
||||||
|
to send too large body".
|
||||||
|
|
||||||
**Sharing has to be allowed.** Uploads fail with "Drive wouldn't share
|
**Sharing has to be allowed.** Uploads fail with "Drive wouldn't share
|
||||||
it with anyone who has the link" unless both allow it:
|
it with anyone who has the link" unless both allow it:
|
||||||
|
|
|
||||||
|
|
@ -187,6 +187,31 @@ export async function driveUpload(folder, name, mime, buffer) {
|
||||||
return await res.json();
|
return await res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The files (not folders) directly in a folder of the shared drive:
|
||||||
|
[{ id, name, mimeType, size, webViewLink }]. size is missing for
|
||||||
|
Google's own Docs, Sheets and Slides. */
|
||||||
|
export async function driveList(folder) {
|
||||||
|
const parent = await driveFolder(folder);
|
||||||
|
const found = [];
|
||||||
|
let pageToken = "";
|
||||||
|
do {
|
||||||
|
const query = new URLSearchParams({
|
||||||
|
q: `'${parent}' in parents and trashed = false and mimeType != '${FOLDER}'`,
|
||||||
|
corpora: "drive",
|
||||||
|
driveId: process.env.GOOGLE_SHARED_DRIVE,
|
||||||
|
includeItemsFromAllDrives: "true",
|
||||||
|
supportsAllDrives: "true",
|
||||||
|
pageSize: "200",
|
||||||
|
fields: "nextPageToken,files(id,name,mimeType,size,webViewLink)",
|
||||||
|
...(pageToken ? { pageToken } : {}),
|
||||||
|
});
|
||||||
|
const page = await (await call(`${DRIVE}?${query}`, {}, DRIVE_SCOPE)).json();
|
||||||
|
found.push(...(page.files ?? []));
|
||||||
|
pageToken = page.nextPageToken ?? "";
|
||||||
|
} while (pageToken);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
/* 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. */
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,10 @@
|
||||||
/* ═══════════════════════════════════════════════════════════════
|
/* ═══════════════════════════════════════════════════════════════
|
||||||
FILE ROUTES: mounted under /api/admin
|
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)
|
POST /files upload one (multipart: file)
|
||||||
GET /files/:id/uses which records link to it
|
GET /files/:id/uses which records link to it
|
||||||
DELETE /files/:id out of Drive and the list
|
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
|
again over the next few minutes (PREVIEW_TRIES), and saved into the
|
||||||
media library as an ordinary upload when it comes.
|
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
|
The same ladder as media: reading needs a session, uploading
|
||||||
editor, deleting admin. nginx needs a block for POST /files
|
editor, deleting admin. nginx needs a block for POST /files
|
||||||
(docs/google-drive-and-mail.md).
|
(docs/google-drive-and-mail.md).
|
||||||
|
|
@ -26,7 +35,7 @@ import { Hono } from "hono";
|
||||||
import { bodyLimit } from "hono/body-limit";
|
import { bodyLimit } from "hono/body-limit";
|
||||||
|
|
||||||
import { requireAuth, requireRole } from "../auth.js";
|
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 { addToLibrary, recordsNaming } from "./media.js";
|
||||||
import { NO_STORE } from "../shape.js";
|
import { NO_STORE } from "../shape.js";
|
||||||
|
|
||||||
|
|
@ -38,6 +47,9 @@ 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.
|
||||||
const PREVIEW_TRIES = [0, 5, 20, 60, 180];
|
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
|
/* 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
|
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();
|
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 q = (c.req.query("q") ?? "").trim().slice(0, 100);
|
||||||
const rows = c
|
const rows = c
|
||||||
.get("db")
|
.get("db")
|
||||||
.prepare(`${SELECT} ${q ? "WHERE f.name LIKE ?" : ""} ORDER BY f.created_at DESC, f.id DESC LIMIT ${MAX_LIST}`)
|
.prepare(`${SELECT} ${q ? "WHERE f.name LIKE ?" : ""} ORDER BY f.created_at DESC, f.id DESC LIMIT ${MAX_LIST}`)
|
||||||
.all(...(q ? [`%${q}%`] : []));
|
.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(
|
files.post(
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,8 @@
|
||||||
file" (a field with `files: true`, fields.tsx)
|
file" (a field with `files: true`, fields.tsx)
|
||||||
|
|
||||||
A link field stores the file's Drive link, a plain URL, so nothing
|
A link field stores the file's Drive link, a plain URL, so nothing
|
||||||
else needs to know where it came from.
|
else needs to know where it came from. Files put in the Drive
|
||||||
|
folder by hand are listed too (the server picks them up).
|
||||||
═══════════════════════════════════════════════════════════════ */
|
═══════════════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
|
@ -54,20 +55,19 @@ export const FILE_HELP =
|
||||||
|
|
||||||
const ACCEPT = ".pdf,.docx,.xlsx,.pptx,.mp3,.m4a,.zip";
|
const ACCEPT = ".pdf,.docx,.xlsx,.pptx,.mp3,.m4a,.zip";
|
||||||
|
|
||||||
|
/* An icon per kind of file; Google's own Docs, Sheets and Slides
|
||||||
|
(application/vnd.google-apps.*) count as their Office kin. */
|
||||||
|
const TYPE_ICONS: [RegExp, typeof FileIcon][] = [
|
||||||
|
[/pdf$/, FilePdf],
|
||||||
|
[/wordprocessing|google-apps\.document$/, FileDoc],
|
||||||
|
[/spreadsheet/, FileXls],
|
||||||
|
[/presentation/, FilePpt],
|
||||||
|
[/^audio\//, FileAudio],
|
||||||
|
[/zip$/, FileZip],
|
||||||
|
];
|
||||||
|
|
||||||
function TypeIcon({ mime }: { mime: string }) {
|
function TypeIcon({ mime }: { mime: string }) {
|
||||||
const Icon = mime === "application/pdf"
|
const Icon = TYPE_ICONS.find(([test]) => test.test(mime))?.[1] ?? FileIcon;
|
||||||
? FilePdf
|
|
||||||
: mime.includes("wordprocessing")
|
|
||||||
? FileDoc
|
|
||||||
: mime.includes("spreadsheet")
|
|
||||||
? FileXls
|
|
||||||
: mime.includes("presentation")
|
|
||||||
? FilePpt
|
|
||||||
: mime.startsWith("audio/")
|
|
||||||
? FileAudio
|
|
||||||
: mime === "application/zip"
|
|
||||||
? FileZip
|
|
||||||
: FileIcon;
|
|
||||||
return <Icon aria-hidden="true" weight="bold" className="h-8 w-8 text-link" />;
|
return <Icon aria-hidden="true" weight="bold" className="h-8 w-8 text-link" />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -76,6 +76,8 @@ function TypeIcon({ mime }: { mime: string }) {
|
||||||
export function useDriveFiles(query: string) {
|
export function useDriveFiles(query: string) {
|
||||||
const [items, setItems] = useState<DriveFile[] | null>(null);
|
const [items, setItems] = useState<DriveFile[] | null>(null);
|
||||||
const [ready, setReady] = useState(true);
|
const [ready, setReady] = useState(true);
|
||||||
|
// Files in the Drive folder that Drive wouldn't share publicly.
|
||||||
|
const [refused, setRefused] = useState<string[]>([]);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const reload = useCallback(() => {
|
const reload = useCallback(() => {
|
||||||
|
|
@ -85,12 +87,13 @@ export function useDriveFiles(query: string) {
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
setItems(data.files);
|
setItems(data.files);
|
||||||
setReady(data.ready);
|
setReady(data.ready);
|
||||||
|
setRefused(data.refused ?? []);
|
||||||
})
|
})
|
||||||
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the files."));
|
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the files."));
|
||||||
}, [query]);
|
}, [query]);
|
||||||
|
|
||||||
useEffect(reload, [reload]);
|
useEffect(reload, [reload]);
|
||||||
return { items, ready, error, reload, setItems };
|
return { items, ready, refused, error, reload, setItems };
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Upload ──────────────────────────────────────────────────── */
|
/* ── Upload ──────────────────────────────────────────────────── */
|
||||||
|
|
@ -203,7 +206,7 @@ export function FilePicker({
|
||||||
}) {
|
}) {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
const { items, ready, error, setItems } = useDriveFiles(query);
|
const { items, ready, refused, error, setItems } = useDriveFiles(query);
|
||||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -259,6 +262,7 @@ export function FilePicker({
|
||||||
|
|
||||||
<div className="overflow-y-auto px-5 py-4">
|
<div className="overflow-y-auto px-5 py-4">
|
||||||
{!ready && <p className="mb-3 text-sm text-danger">Google Drive isn't set up on the server, so nothing can be uploaded.</p>}
|
{!ready && <p className="mb-3 text-sm text-danger">Google Drive isn't set up on the server, so nothing can be uploaded.</p>}
|
||||||
|
<RefusedNote names={refused} />
|
||||||
{error ? (
|
{error ? (
|
||||||
<p className="text-sm text-danger">{error}</p>
|
<p className="text-sm text-danger">{error}</p>
|
||||||
) : items === null ? (
|
) : items === null ? (
|
||||||
|
|
@ -272,6 +276,19 @@ export function FilePicker({
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Files someone put in the Drive folder that Drive wouldn't share
|
||||||
|
with anyone who has the link, so they aren't listed. */
|
||||||
|
export function RefusedNote({ names }: { names: string[] }) {
|
||||||
|
if (names.length === 0) return null;
|
||||||
|
return (
|
||||||
|
<p className="mb-3 text-sm text-danger">
|
||||||
|
In the Drive folder but not listed, because Drive wouldn't share {names.length === 1 ? "it" : "them"} with anyone
|
||||||
|
who has the link: {names.join(", ")}. Check the sharing settings (docs/google-drive-and-mail.md); they're tried
|
||||||
|
again every ten minutes.
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/* "Choose a file" under a link field. */
|
/* "Choose a file" under a link field. */
|
||||||
export function ChooseFileButton({ value, onPick }: { value?: string | null; onPick: (file: DriveFile) => void }) {
|
export function ChooseFileButton({ value, onPick }: { value?: string | null; onPick: (file: DriveFile) => void }) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,13 @@ export class ApiError extends Error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* nginx's answers of its own, in words that point at the fix. */
|
||||||
|
const NOT_THE_API: Record<number, string> = {
|
||||||
|
413: "Too large for the web server: nginx's upload limit for this address is lower than the file (HTTP 413). The nginx block for it is in the docs.",
|
||||||
|
502: "The API isn't answering (HTTP 502). Check that the ngu-api service is running.",
|
||||||
|
504: "The API took too long to answer (HTTP 504). Try again; if it keeps happening, nginx's timeout for this address is too short.",
|
||||||
|
};
|
||||||
|
|
||||||
async function request(path, options: RequestInit = {}) {
|
async function request(path, options: RequestInit = {}) {
|
||||||
const response = await fetch(`${BASE}${path}`, {
|
const response = await fetch(`${BASE}${path}`, {
|
||||||
...options,
|
...options,
|
||||||
|
|
@ -39,9 +46,11 @@ async function request(path, options: RequestInit = {}) {
|
||||||
|
|
||||||
const type = response.headers.get("content-type") ?? "";
|
const type = response.headers.get("content-type") ?? "";
|
||||||
if (!type.includes("application/json")) {
|
if (!type.includes("application/json")) {
|
||||||
// Usually the SPA fallback returning index.html for a URL the
|
// Not the API's answer: the SPA fallback returning index.html for
|
||||||
// API doesn't serve. Parsing it would throw something useless.
|
// a URL the API doesn't serve, or nginx's own error page when the
|
||||||
throw new ApiError("Server did not return JSON.", {
|
// request never reached the API (nothing in its journal then).
|
||||||
|
// Parsing it would throw something useless; say what it was.
|
||||||
|
throw new ApiError(NOT_THE_API[response.status] ?? `The server didn't answer as expected (HTTP ${response.status}).`, {
|
||||||
status: response.status,
|
status: response.status,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ import {
|
||||||
FILE_HELP,
|
FILE_HELP,
|
||||||
FileList,
|
FileList,
|
||||||
FileUploadButton,
|
FileUploadButton,
|
||||||
|
RefusedNote,
|
||||||
useDriveFiles,
|
useDriveFiles,
|
||||||
} from "../../components/admin/DriveFiles.tsx";
|
} from "../../components/admin/DriveFiles.tsx";
|
||||||
import {
|
import {
|
||||||
|
|
@ -142,7 +143,7 @@ function CopyPath({ url, label = "Copy path" }: { url: string; label?: string })
|
||||||
function FilesTab() {
|
function FilesTab() {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
const { items, ready, error, setItems } = useDriveFiles(query);
|
const { items, ready, refused, error, setItems } = useDriveFiles(query);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|
@ -167,6 +168,7 @@ function FilesTab() {
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
<div className="mt-6">
|
<div className="mt-6">
|
||||||
|
<RefusedNote names={refused} />
|
||||||
{error ? (
|
{error ? (
|
||||||
<p className="text-sm text-danger">{error}</p>
|
<p className="text-sm text-danger">{error}</p>
|
||||||
) : items === null ? (
|
) : items === null ? (
|
||||||
|
|
@ -217,7 +219,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."
|
||||||
: "Files in the shared Google Drive, for pages to link to. Link fields pick from here with Choose a file."}
|
: "Files in the shared Google Drive's Blog folder, for pages to link to, including any put there in Drive itself. Link fields pick from here with Choose a file."}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue