Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): import Notion file attachments

Elian Doran780c61dd22b0
diff --git a/packages/trilium-core/src/services/import/notion/converter.spec.ts b/packages/trilium-core/src/services/import/notion/converter.spec.ts
index 03c7e92dfd..c061985084 100644
--- a/packages/trilium-core/src/services/import/notion/converter.spec.ts
+++ b/packages/trilium-core/src/services/import/notion/converter.spec.ts
@@ -230,6 +230,22 @@ describe("convertNotionHtml — images", () => {
});
});
+describe("convertNotionHtml — attachments", () => {
+ it("rewrites a Notion file block into a marked anchor for the importer to bind", () => {
+ const input = `<div style="display:contents" dir="ltr"><figure id="386c5eca"><div class="source"><a href="Attachment%20test/demo.rtf">demo.rtf</a></div></figure></div>`;
+ expect(convertNotionHtml(input)).toBe(
+ `<p><a href="Attachment%20test/demo.rtf" class="notion-attachment">demo.rtf</a></p>`
+ );
+ });
+
+ it("does not touch a bookmark card (its source class is on the anchor, not a wrapping div)", () => {
+ const input = `<figure><a href="https://example.com/" class="bookmark source"><div class="bookmark-info"><div class="bookmark-text"><div class="bookmark-title">Example</div></div></div></a></figure>`;
+ expect(convertNotionHtml(input)).toBe(
+ `<section class="link-embed" data-url="https://example.com/" data-embed-type="opengraph" data-title="Example"></section>`
+ );
+ });
+});
+
describe("convertNotionHtml — code blocks", () => {
it("maps a known Notion code language to Trilium's mime class and drops the Prism includes", () => {
const input = `<div style="display:contents" dir="auto"><script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css"/><script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-c.min.js"></script><pre id="386c5eca" class="code code-wrap"><code class="language-c" style="white-space:pre-wrap;word-break:break-all">void main() {}</code></pre></div>`;
diff --git a/packages/trilium-core/src/services/import/notion/converter.ts b/packages/trilium-core/src/services/import/notion/converter.ts
index 2da20cecf2..75afff9cc8 100644
--- a/packages/trilium-core/src/services/import/notion/converter.ts
+++ b/packages/trilium-core/src/services/import/notion/converter.ts
@@ -21,6 +21,7 @@ export function convertNotionHtml(html: string): string {
unwrapDisplayContents(root);
convertTables(root);
convertImages(root);
+ convertAttachments(root);
convertCodeBlocks(root);
convertCallouts(root);
convertBookmarks(root);
@@ -285,6 +286,27 @@ function convertImages(root: HTMLElement) {
}
// #endregion
+// #region Attachments
+/**
+ * Notion file blocks are `<figure><div class="source"><a href="…file">name</a></div></figure>`, where the
+ * href is a zip-relative path to the bundled file. Reduce each to a paragraph holding a marked anchor
+ * (`<a class="notion-attachment" href="…">`); the importer resolves that file from the zip, saves it as a
+ * `role:"file"` attachment on the note and rewrites the anchor into a Trilium attachment reference-link.
+ * The marker distinguishes it from page links and bookmarks (whose `source` class sits on the `<a>` itself).
+ */
+function convertAttachments(root: HTMLElement) {
+ for (const figure of root.querySelectorAll("figure")) {
+ const anchor = figure.querySelector("div.source a");
+ if (!anchor) {
+ continue;
+ }
+ anchor.setAttribute("class", "notion-attachment");
+ figure.insertAdjacentHTML("beforebegin", `<p>${anchor.toString()}</p>`);
+ figure.remove();
+ }
+}
+// #endregion
+
// #region Code blocks
/**
* Notion code blocks ship as `<pre class="code"><code class="language-<prism>">…</code></pre>`, preceded
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.ts
index 27385ead9e..1a86a7766b 100644
--- a/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts
@@ -82,6 +82,25 @@ describe("Notion importer — integration", () => {
expect(fortyFive[0].getChildNotes().map((note) => note.title)).toEqual(["Brown fox"]);
});
+ it("saves a referenced file as a role:file attachment and links to it from the content", async () => {
+ // Notion exports a file block as <figure><div class="source"><a href="<file>">name</a></figure>,
+ // with the file bundled in the zip alongside the page.
+ const attachmentFigure = `<figure id="386c5eca-1b8b-808b-84d3-cea5b6510570"><div class="source"><a href="Notes/demo.rtf">demo.rtf</a></div></figure>`;
+ const importRoot = await importNotion({
+ "Notes 386c5eca1b8b80439520cad27a0d2749.html": `<html><head><title>Notes</title></head><body><div id="386c5eca1b8b80439520cad27a0d2749" class="page"><div class="page-body"><div style="display:contents" dir="ltr">${attachmentFigure}</div></div></div></body></html>`,
+ "Notes/demo.rtf": "{\\rtf1 hello}"
+ });
+
+ const notes = importRoot.getChildNotes().find((note) => note.title === "Notes");
+ if (!notes) {
+ throw new Error("imported 'Notes' page not found");
+ }
+ const attachment = notes.getAttachmentsByRole("file").find((a) => a.title === "demo.rtf");
+ expect(attachment).toBeDefined();
+ expect(notes.getContent()).toContain(`href="#root/${notes.noteId}?viewMode=attachments&attachmentId=${attachment?.attachmentId}"`);
+ expect(notes.getContent()).toContain(`class="reference-link"`);
+ });
+
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 });
diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.ts
index e73517e6f8..d4f57a5db7 100644
--- a/packages/trilium-core/src/services/import/notion/importer.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.ts
@@ -23,6 +23,7 @@ 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 mimeService from "../mime.js";
import { convertNotionHtml } from "./converter.js";
import { getNotionId, stripNotionId } from "./notion_id.js";
@@ -179,8 +180,9 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<
targetByPageId.set(page.id, { noteId: note.noteId, title: page.title });
// Attachments hang off the note, so this must run after creation; it returns the content with the
- // <img> srcs pointing at the saved attachments.
- created.push({ note, content: rewriteImages(note, page.content, page.path, resources), page });
+ // <img> srcs and file links pointing at the saved attachments.
+ const withImages = rewriteImages(note, page.content, page.path, resources);
+ created.push({ note, content: rewriteAttachments(note, withImages, page.path, resources), page });
taskContext.increaseProgressCount();
}
@@ -230,6 +232,41 @@ function rewriteImages(note: BNote, content: string, pagePath: string, resources
return changed ? root.toString() : content;
}
+/**
+ * Saves each in-zip file a page attaches (`<a class="notion-attachment">`, produced by the converter) as a
+ * `role:"file"` attachment on `note`, and rewrites the anchor into a Trilium attachment reference-link
+ * (the same shape the ENEX importer and CKEditor use). Anchors whose file isn't bundled lose the marker
+ * class and stay plain links. Returns the (possibly unchanged) content.
+ */
+function rewriteAttachments(note: BNote, content: string, pagePath: string, resources: Map<string, Uint8Array>): string {
+ const root = parse(content);
+ let changed = false;
+
+ for (const anchor of root.querySelectorAll("a.notion-attachment")) {
+ anchor.removeAttribute("class");
+ changed = true;
+
+ const href = anchor.getAttribute("href");
+ const resourcePath = href ? resolveResourcePath(pagePath, href) : "";
+ const bytes = resources.get(resourcePath);
+ if (!bytes) {
+ continue;
+ }
+
+ const title = anchor.textContent.trim() || baseName(resourcePath);
+ const attachment = note.saveAttachment({
+ role: "file",
+ mime: mimeService.getMime(baseName(resourcePath)) || "application/octet-stream",
+ title,
+ content: bytes
+ });
+ anchor.setAttribute("href", `#root/${note.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}`);
+ anchor.setAttribute("class", "reference-link");
+ }
+
+ return changed ? root.toString() : content;
+}
+
/** A resolved import target: the note created for a Notion page, plus that page's title. */
export interface LinkTarget {
noteId: string;