Skip to content

Build your personal knowledge base with Trilium Notes

refactor(import): route Notion through the shared file-import endpoint

Elian Doran1b82343847de
diff --git a/apps/client/src/services/import.ts b/apps/client/src/services/import.ts
index a0cc992587..5edcf7769c 100644
--- a/apps/client/src/services/import.ts
+++ b/apps/client/src/services/import.ts
@@ -9,6 +9,8 @@ import { WebSocketMessage } from "@triliumnext/commons";
type BooleanLike = boolean | "true" | "false";
export interface UploadFilesOptions {
+ /** Routes the upload to a specific importer (e.g. "notion"), overriding extension-based detection. */
+ format?: string;
safeImport?: BooleanLike;
shrinkImages: BooleanLike;
textImportedAsText?: BooleanLike;
diff --git a/apps/client/src/services/notion_import.ts b/apps/client/src/services/notion_import.ts
deleted file mode 100644
index eefb0444bd..0000000000
--- a/apps/client/src/services/notion_import.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-// Loading import.ts registers the shared "importNotes" WebSocket toast handlers (progress + success).
-// The Notion import reuses that taskType, but the import-provider dialog never loads import.ts on its
-// own, so without this side-effect import the progress/finished toasts would never appear.
-import "./import.js";
-
-import server from "./server.js";
-import utils from "./utils.js";
-
-/**
- * Uploads a Notion export zip and returns as soon as the server has accepted it. The import itself runs
- * in the background on the server; progress, completion (navigation to the imported note) and any error
- * all arrive over the WebSocket via the shared "importNotes" toast handlers in import.ts.
- */
-async function runImport({ parentNoteId, file }: { parentNoteId: string; file: File }) {
- const formData = new FormData();
- formData.append("upload", file);
- formData.append("parentNoteId", parentNoteId);
- formData.append("taskId", utils.randomString(10));
-
- await $.ajax({
- url: `${window.glob.baseApiUrl}notion-import/import`,
- headers: await server.getHeaders(),
- data: formData,
- type: "POST",
- timeout: 60 * 60 * 1000,
- contentType: false, // NEEDED, DON'T REMOVE THIS
- processData: false // NEEDED, DON'T REMOVE THIS
- });
-}
-
-export default { runImport };
diff --git a/apps/client/src/widgets/dialogs/import_providers/notion.tsx b/apps/client/src/widgets/dialogs/import_providers/notion.tsx
index b8f7c91820..7c17f15ed4 100644
--- a/apps/client/src/widgets/dialogs/import_providers/notion.tsx
+++ b/apps/client/src/widgets/dialogs/import_providers/notion.tsx
@@ -1,8 +1,7 @@
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n.js";
-import notionImport from "../../../services/notion_import.js";
-import toast from "../../../services/toast.js";
+import importService from "../../../services/import.js";
import Button from "../../react/Button.js";
import FormFileUpload from "../../react/FormFileUpload.js";
import FormGroup from "../../react/FormGroup.js";
@@ -18,15 +17,13 @@ function NotionPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPan
return;
}
- // Close immediately and let the shared import toasts report progress, completion and any error.
- // The request returns as soon as the server accepts it (the import runs in the background), so the
- // only errors caught here are upfront ones like an upload failure.
+ // Close immediately and let the shared import toasts (registered in import.ts) report progress,
+ // completion and any error. `format: "notion"` routes the upload to the Notion importer on the
+ // shared file-import endpoint, overriding the .zip extension's default (the generic zip importer).
+ // uploadFiles surfaces any upload error via its own toast; swallow the rejection so this void-ed
+ // call doesn't raise an unhandled rejection.
closeDialog();
- try {
- await notionImport.runImport({ parentNoteId, file });
- } catch (e) {
- toast.showError(e instanceof Error ? e.message : String(e));
- }
+ await importService.uploadFiles("notes", parentNoteId, [file], { format: "notion", safeImport: "true", shrinkImages: "false" }).catch(() => {});
}, [file, parentNoteId, closeDialog]);
// Keep the latest import handler in a ref so the footer effect depends only on `file` being present,
diff --git a/apps/server/src/routes/api/notion_import.ts b/apps/server/src/routes/api/notion_import.ts
deleted file mode 100644
index cc0b4f5a0e..0000000000
--- a/apps/server/src/routes/api/notion_import.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * REST endpoint for the Notion importer. Accepts a multipart upload of a Notion HTML-export zip and
- * kicks off the structural import in the background, reporting progress over the WebSocket via the
- * shared "importNotes" task type.
- *
- * POST /api/notion-import/import (multipart: `upload` = .zip, `parentNoteId`, `taskId`) -> {}
- */
-
-import { becca, ValidationError } from "@triliumnext/core";
-import type { Request } from "express";
-
-import importer from "../../services/import/notion/importer.js";
-
-function runImport(req: Request) {
- const { parentNoteId, taskId } = req.body as { parentNoteId?: string; taskId?: string };
- if (!parentNoteId || !taskId) {
- throw new ValidationError("parentNoteId and taskId are required.");
- }
-
- const file = req.file;
- if (!file || typeof file.buffer === "string") {
- throw new ValidationError("No zip file has been uploaded.");
- }
-
- becca.getNoteOrThrow(parentNoteId);
-
- // Fire-and-forget: a large export can take far longer than the client's HTTP request timeout, so we
- // return immediately and let the import report progress, completion and any error over the WebSocket
- // (taskType "importNotes"). importZip catches and reports its own failures, so it never rejects here.
- void importer.importZip({ fileBuffer: file.buffer, parentNoteId, taskId });
- return {};
-}
-
-export default { runImport };
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 91e1158a7f..47eb056b77 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -29,7 +29,6 @@ import llmChatRoute from "./api/llm_chat.js";
import llmSpecialNotesRoute from "./api/llm_special_notes.js";
import loginApiRoute from "./api/login.js";
import metricsRoute from "./api/metrics.js";
-import notionImportRoute from "./api/notion_import.js";
import ocrRoute from "./api/ocr.js";
import onenoteImportRoute from "./api/onenote_import.js";
import recoveryCodes from './api/recovery_codes.js';
@@ -192,10 +191,6 @@ function register(app: express.Application) {
asyncApiRoute(GET, "/api/onenote-import/notebooks", onenoteImportRoute.getNotebooks);
asyncApiRoute(PST, "/api/onenote-import/import", onenoteImportRoute.runImport);
- // Notion importer: a multipart upload of the export zip (vs OneNote's API), so it needs the upload
- // middleware + CSRF guard rather than the plain JSON `apiRoute` helper.
- route(PST, "/api/notion-import/import", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], notionImportRoute.runImport, apiResultHandler);
-
shareRoutes.register(router);
etapiAuthRoutes.register(router, [loginRateLimiter]);
diff --git a/packages/trilium-core/src/routes/api/import.ts b/packages/trilium-core/src/routes/api/import.ts
index 5b263bc7dc..a8290b05fb 100644
--- a/packages/trilium-core/src/routes/api/import.ts
+++ b/packages/trilium-core/src/routes/api/import.ts
@@ -1,25 +1,27 @@
import type { Request } from "express";
+
import type { File } from "../../services/import/common.js";
type ImportRequest<P> = Omit<Request<P>, "file"> & { file?: File };
import becca from "../../becca/becca.js";
+import becca_loader from "../../becca/becca_loader.js";
import type BNote from "../../becca/entities/bnote.js";
+import { ValidationError } from "../../errors.js";
+import * as cls from "../../services/context.js";
import enexImportService from "../../services/import/enex.js";
+import notionImportService from "../../services/import/notion/importer.js";
import opmlImportService from "../../services/import/opml.js";
import singleImportService from "../../services/import/single.js";
import zipImportService from "../../services/import/zip.js";
import { getLog } from "../../services/log.js";
import TaskContext from "../../services/task_context.js";
import { safeExtractMessageAndStackFromError } from "../../services/utils/index.js";
-import * as cls from "../../services/context.js";
-import { ValidationError } from "../../errors.js";
-import becca_loader from "../../becca/becca_loader.js";
import { extname } from "../../services/utils/path.js";
async function importNotesToBranch(req: ImportRequest<{ parentNoteId: string }>) {
const { parentNoteId } = req.params;
- const { taskId, last } = req.body;
+ const { taskId, last, format } = req.body;
const options = {
safeImport: req.body.safeImport !== "false",
@@ -53,7 +55,12 @@ async function importNotesToBranch(req: ImportRequest<{ parentNoteId: string }>)
const taskContext = TaskContext.getInstance(taskId, "importNotes", options);
try {
- if (extension === ".zip" && options.explodeArchives && typeof file.buffer !== "string") {
+ if (format === "notion" && typeof file.buffer !== "string") {
+ // An explicit format always wins over extension sniffing: a Notion export is just a `.zip`,
+ // indistinguishable from a Trilium export without inspecting its contents. The Notion import
+ // dialog tags the upload, so we route it to the Notion importer rather than the generic zip.
+ note = await notionImportService.importNotion(taskContext, file.buffer, parentNote);
+ } else if (extension === ".zip" && options.explodeArchives && typeof file.buffer !== "string") {
note = await zipImportService.importZip(taskContext, file.buffer, parentNote);
} else if (extension === ".opml" && options.explodeArchives) {
const importResult = await opmlImportService.importOpml(taskContext, file.buffer, parentNote);
diff --git a/apps/server/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.ts
similarity index 72%
rename from apps/server/src/services/import/notion/importer.ts
rename to packages/trilium-core/src/services/import/notion/importer.ts
index c6085519b1..63f7e5d188 100644
--- a/apps/server/src/services/import/notion/importer.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.ts
@@ -7,15 +7,21 @@
* and original timestamps — copying each page's body HTML across roughly as-is. Faithful HTML cleanup,
* link rewriting, images/attachments and database (CSV) handling are deliberately deferred.
*
- * Like the OneNote importer, it runs in the background and reports progress, completion and failure over
- * the WebSocket via an "importNotes" TaskContext, so it never throws to the caller.
+ * Invoked from the shared file-import dispatcher (routes/api/import.ts) when the upload is tagged
+ * `format=notion`, so progress, completion and failure are reported by that dispatcher's TaskContext —
+ * this service just builds the tree and returns its root note, like the zip/enex importers.
*/
-import { becca, date_utils, getLog, getZipProvider, note_service as noteService, protected_session as protectedSession, sanitize, TaskContext } from "@triliumnext/core";
import { t } from "i18next";
import { type HTMLElement, parse } from "node-html-parser";
-import sql from "../../sql.js";
+import type BNote from "../../../becca/entities/bnote.js";
+import noteService from "../../notes.js";
+import protectedSessionService from "../../protected_session.js";
+import { sanitizeHtml } from "../../sanitizer.js";
+import type TaskContext from "../../task_context.js";
+import dateUtils from "../../utils/date.js";
+import { getZipProvider } from "../../zip_provider.js";
import { getNotionId, parseParentIds, stripNotionId } from "./notion_id.js";
interface ParsedPage {
@@ -32,20 +38,11 @@ interface ParsedPage {
utcDateModified?: string;
}
-export async function importZip({ fileBuffer, parentNoteId, taskId }: { fileBuffer: Uint8Array; parentNoteId: string; taskId: string }): Promise<void> {
- const taskContext = TaskContext.getInstance(taskId, "importNotes", { safeImport: true });
+async function importNotion(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote): Promise<BNote> {
+ const pages = await parsePages(fileBuffer);
+ taskContext.setTotalCount(pages.length);
- try {
- const pages = await parsePages(fileBuffer);
- taskContext.setTotalCount(pages.length);
-
- const rootNoteId = sql.transactional(() => createNotes(parentNoteId, pages, taskContext));
-
- taskContext.taskSucceeded({ parentNoteId, importedNoteId: rootNoteId });
- } catch (e: unknown) {
- getLog().error(`Notion import failed: ${e instanceof Error ? (e.stack ?? e.message) : e}`);
- taskContext.reportError(e instanceof Error ? e.message : String(e));
- }
+ return createNotes(importRootNote, pages, taskContext);
}
/** Reads every page (.html entry) out of the zip, parsing its title, ancestry, dates and body HTML. */
@@ -86,7 +83,7 @@ function parsePage(path: string, html: string): ParsedPage | null {
const title = root.querySelector("title")?.textContent?.trim() || stripNotionId(removeExtension(baseName(path))) || "Untitled";
const pageBody = root.querySelector(".page-body");
- const content = pageBody ? sanitize.sanitizeHtml(pageBody.innerHTML) : "";
+ const content = pageBody ? sanitizeHtml(pageBody.innerHTML) : "";
return {
id,
@@ -100,15 +97,14 @@ function parsePage(path: string, html: string): ParsedPage | null {
}
/**
- * Creates the note tree. Pages are created shallowest-first so a page's parent always exists before it;
- * each page is parented under the note created for its immediate-parent id, or under the import root when
- * it has no (resolvable) parent. Returns the import root's note id.
+ * Creates the note tree under a fresh "Notion import" root. Pages are created shallowest-first so a
+ * page's parent always exists before it; each page is parented under the note created for its
+ * immediate-parent id, or under the import root when it has no (resolvable) parent. Returns that root.
*/
-function createNotes(parentNoteId: string, pages: ParsedPage[], taskContext: TaskContext<"importNotes">): string {
- const parentNote = becca.getNoteOrThrow(parentNoteId);
- const isProtected = parentNote.isProtected && protectedSession.isProtectedSessionAvailable();
+function createNotes(importRootNote: BNote, pages: ParsedPage[], taskContext: TaskContext<"importNotes">): BNote {
+ const isProtected = importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable();
- const rootNote = noteService.createNewNote({ parentNoteId, title: t("notion_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;
+ const rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: t("notion_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;
rootNote.addLabel("iconClass", "bx bx-import");
const noteIdByPageId = new Map<string, string>();
@@ -137,7 +133,7 @@ function createNotes(parentNoteId: string, pages: ParsedPage[], taskContext: Tas
taskContext.increaseProgressCount();
}
- return rootNote.noteId;
+ return rootNote;
}
/** Returns the Notion id of the first child element of `body` that carries one (Notion's page wrapper). */
@@ -165,7 +161,7 @@ function extractDate(root: HTMLElement, rowClass: string): string | undefined {
return undefined;
}
const date = new Date(text);
- return Number.isNaN(date.getTime()) ? undefined : date_utils.utcDateTimeStr(date);
+ return Number.isNaN(date.getTime()) ? undefined : dateUtils.utcDateTimeStr(date);
}
function isDirectory(path: string): boolean {
@@ -180,4 +176,4 @@ function removeExtension(name: string): string {
return name.replace(/\.[^.]+$/, "");
}
-export default { importZip };
+export default { importNotion };
diff --git a/apps/server/src/services/import/notion/notion_id.spec.ts b/packages/trilium-core/src/services/import/notion/notion_id.spec.ts
similarity index 100%
rename from apps/server/src/services/import/notion/notion_id.spec.ts
rename to packages/trilium-core/src/services/import/notion/notion_id.spec.ts
diff --git a/apps/server/src/services/import/notion/notion_id.ts b/packages/trilium-core/src/services/import/notion/notion_id.ts
similarity index 100%
rename from apps/server/src/services/import/notion/notion_id.ts
rename to packages/trilium-core/src/services/import/notion/notion_id.ts