Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(import): descend into Notion's nested export zip
Elian Doran7b436f559162
diff --git a/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts b/packages/trilium-core/src/services/import/notion/importer.integration.spec.tsnew file mode 100644index 0000000000..962450fa9c--- /dev/null+++ b/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts@@ -0,0 +1,52 @@+import { ZipArchive } from "archiver";+import { PassThrough } from "stream";+import { describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import type BNote from "../../../becca/entities/bnote.js";+import { getContext } from "../../context.js";+import TaskContext from "../../task_context.js";+import notionImporter from "./importer.js";++/** Builds an in-memory zip from a map of entry name -> contents. */+async function createZipBuffer(files: Record<string, string | Buffer>): Promise<Buffer> {+ const archive = new ZipArchive();+ const chunks: Buffer[] = [];+ const passthrough = new PassThrough();+ passthrough.on("data", (chunk: Buffer) => chunks.push(chunk));+ archive.pipe(passthrough);+ for (const [name, content] of Object.entries(files)) {+ archive.append(content, { name });+ }+ await archive.finalize();+ return Buffer.concat(chunks);+}++/** Runs the Notion importer over `files` and returns the import root note. */+async function importNotion(files: Record<string, string | Buffer>): Promise<BNote> {+ const buffer = await createZipBuffer(files);+ const taskContext = TaskContext.getInstance("notion-integration", "importNotes", { safeImport: true });++ return new Promise<BNote>((resolve, reject) => {+ void getContext().init(async () => {+ try {+ const root = becca.getNoteOrThrow("root");+ resolve(await notionImporter.importNotion(taskContext, new Uint8Array(buffer), root));+ } catch (e) {+ reject(e);+ }+ });+ });+}++const pageHtml = (title: string) =>+ `<html><head><title>${title}</title></head><body><div id="386c5eca1b8b80439520cad27a0d2749" class="page"><div class="page-body"><p>Hello</p></div></div></body></html>`;++describe("Notion importer — integration", () => {+ it("recurses into a root-level nested export zip (the part Notion makes you extract)", async () => {+ const innerZip = await createZipBuffer({ "Inner page 386c5eca1b8b80439520cad27a0d2749.html": pageHtml("Inner page") });+ const importRoot = await importNotion({ "Export-Part-1.zip": innerZip });++ expect(importRoot.getChildNotes().map((note) => note.title)).toContain("Inner page");+ });+});diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.tsindex ecc084ef93..4add4f01e2 100644--- a/packages/trilium-core/src/services/import/notion/importer.ts+++ b/packages/trilium-core/src/services/import/notion/importer.ts@@ -48,32 +48,42 @@ async function importNotion(taskContext: TaskContext<"importNotes">, fileBuffer:}/**- * Reads the zip once: HTML entries become parsed pages; every other file (images, attachments) is kept- * by its normalized path so page content can later reference it. The `index.html` summary is skipped.+ * Reads the zip: HTML entries become parsed pages; every other file (images, attachments) is kept by its+ * normalized path so page content can later reference it. The `index.html` summary is skipped.+ *+ * A Notion workspace export wraps its content in one (or more) nested zips at the archive root — the part+ * you'd otherwise have to extract by hand — so root-level `.zip` entries are descended into. Nested zips+ * sitting inside a page folder are treated as ordinary attachments, not export structure.*/async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[]; resources: Map<string, Uint8Array> }> {const provider = getZipProvider();- const filenameEncoding = await provider.detectFilenameEncoding(fileBuffer);-const pages: ParsedPage[] = [];const resources = new Map<string, Uint8Array>();- await provider.readZipFile(fileBuffer, async (entry, readContent) => {- const path = entry.fileName;- if (isDirectory(path)) {- return;- }- if (path.toLowerCase().endsWith(".html")) {- if (baseName(path) === "index.html") {++ const readArchive = async (buffer: Uint8Array): Promise<void> => {+ const filenameEncoding = await provider.detectFilenameEncoding(buffer);+ await provider.readZipFile(buffer, async (entry, readContent) => {+ const path = entry.fileName;+ if (isDirectory(path)) {return;}- const parsed = parsePage(path, new TextDecoder().decode(await readContent()));- if (parsed) {- pages.push(parsed);+ if (path.toLowerCase().endsWith(".zip") && !path.includes("/")) {+ await readArchive(await readContent());+ } else if (path.toLowerCase().endsWith(".html")) {+ if (baseName(path) === "index.html") {+ return;+ }+ const parsed = parsePage(path, new TextDecoder().decode(await readContent()));+ if (parsed) {+ pages.push(parsed);+ }+ } else {+ resources.set(normalizePath(path), await readContent());}- } else {- resources.set(normalizePath(path), await readContent());- }- }, filenameEncoding);+ }, filenameEncoding);+ };++ await readArchive(fileBuffer);return { pages, resources };}