NGU-Web/server/src/routes/import.js
Zaldimmar dc53af238f Add a Request form, with files in Google Drive and email notices
One form at /request for blog posts, events, and new or updated
chapters, regions (updates only), partners, teams, awards and people.
?type= opens it on one; buttons on the Community sections, blog posts,
Retreats and the front page calendar do. Files (.docx, PDF, JPEG, PNG)
go to a Google Drive folder through a service account.

Requests are feedback rows of type 'content' (migration 046), in a
third Forms queue: files download from Drive, a .docx can become a
draft blog post, and deleting a request deletes its files. New content
and data requests email the addresses in Site settings through Gmail.

Setup: docs/google-drive-and-mail.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:54:00 -05:00

123 lines
4.3 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
IMPORT ROUTES (mounted under /api/admin)
POST /import/docx a Word document → a new blog post, unpublished
Blog posts → Import from Word. The document becomes a draft post
(docx.js decides what each part becomes), created through the same
CRUD engine as the editor, so it's validated the same way. The
reply says what came over and what didn't (images), and the admin
opens the new post for review before anyone publishes it.
nginx caps /api/ bodies at 64k; this path needs its own block
with a larger client_max_body_size (docs/media-uploads.md).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import { createRow, HttpError } from "../admin-crud.js";
import { ENTITIES } from "../admin-schema.js";
import { DocxError, readDocx } from "../docx.js";
import { NO_STORE } from "../shape.js";
const MAX_DOCX_BYTES = 10 * 1024 * 1024;
const imports = new Hono();
imports.use("*", requireAuth);
const slug = (text) =>
String(text ?? "")
.toLowerCase()
.normalize("NFKD")
.replace(/[^\w\s-]/g, "")
.trim()
.replace(/[\s_]+/g, "-")
.replace(/-+/g, "-")
.slice(0, 64)
.replace(/-$/, "") || "imported-post";
/* A free URL ID: the title's slug, or it with -2, -3... */
function freeId(db, base) {
const taken = (id) => db.prepare(`SELECT 1 FROM blog_posts WHERE id = ?`).get(id);
let id = base;
for (let n = 2; taken(id); n++) id = `${base.slice(0, 60)}-${n}`;
return id;
}
/* A Word document as a new unpublished blog post, through the CRUD
engine. Returns { id, summary }; an unreadable document is a 400
HttpError. Also used by Forms → Content requests, on a file someone
sent with the Request form. */
export function importDocx(db, buffer, fileName, byEmail) {
let doc;
try {
doc = readDocx(buffer);
} catch (err) {
throw new HttpError(400, err instanceof DocxError ? err.message : "That document couldn't be read. Save it again as .docx and retry.");
}
if (doc.blocks.length === 0) throw new HttpError(400, "That document has no text to import.");
const title = doc.title || String(fileName ?? "").replace(/\.docx$/i, "") || "Imported post";
const headings = doc.blocks.filter((b) => b.type === "heading" || b.type === "subheading").length;
const row = createRow(db, ENTITIES.blog_posts, {
id: freeId(db, slug(title)),
title: title.slice(0, 200),
published_on: doc.date,
is_published: 0,
is_listed: 1,
// A long document with sections reads better with its contents.
show_contents: headings >= 3 ? 1 : 0,
content_blocks: doc.blocks.map((block) => ({
slot: "body",
type: block.type,
text: block.text ?? null,
items: block.items ?? [],
})),
});
const count = (type) => doc.blocks.filter((b) => b.type === type).length;
console.log(`blog_posts ${row.id} imported from Word by ${byEmail}`);
return {
id: row.id,
summary: {
blocks: doc.blocks.length,
headings,
paragraphs: count("paragraph"),
lists: count("list"),
tables: count("table"),
skipped: doc.skipped,
},
};
}
imports.post(
"/import/docx",
requireRole("editor"),
bodyLimit({
maxSize: MAX_DOCX_BYTES + 64 * 1024,
onError: (c) => c.json({ error: "That document is too large (10 MB at most)." }, 413),
}),
async (c) => {
const db = c.get("db");
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)) return c.json({ error: "No file was sent." }, 400);
try {
const result = importDocx(db, Buffer.from(await file.arrayBuffer()), file.name, c.get("user").email);
return c.json(result, 201, NO_STORE);
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message, fields: err.fields }, err.status);
throw err;
}
},
);
export default imports;