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): import Obsidian file & image attachments
Elian Doran4ad1b21c8335
diff --git a/packages/trilium-core/src/services/import/obsidian/attachments.ts b/packages/trilium-core/src/services/import/obsidian/attachments.tsnew file mode 100644index 0000000000..c9e95d810c--- /dev/null+++ b/packages/trilium-core/src/services/import/obsidian/attachments.ts@@ -0,0 +1,157 @@+/**+ * Resolves Obsidian attachment references in a rendered note's HTML and saves the backing files as Trilium+ * attachments.+ *+ * Obsidian embeds (`![[file]]`) and standard Markdown images (``) arrive here as `<img>` (the+ * Markdown renderer's transclusion), and links (`[[file]]` / `[text](file)`) as `<a>`; both reference a vault+ * file by name. An `<img>` resolving to an image becomes an inline image attachment (its `src` rewritten); an+ * `<img>` resolving to a non-image file (an embedded PDF/RTF/…) becomes a file reference link, as does an+ * `<a>` resolving to any attachment file. References that don't resolve to a bundled attachment are left+ * untouched — a note embed/link, a `.base`/`.canvas`, an external URL or an in-note anchor is never altered+ * here; those belong to later passes.+ */++import { type HTMLElement, parse } from "node-html-parser";++import type BNote from "../../../becca/entities/bnote.js";+import imageService from "../../image.js";+import { escapeHtml } from "../../utils/index.js";+import { basename } from "../../utils/path.js";+import mimeService from "../mime.js";++export interface AttachmentIndex {+ /** Vault-root-relative POSIX path -> file bytes. */+ byPath: Map<string, Uint8Array>;+ /** Lower-cased base name -> the paths carrying it, for Obsidian's shortest-path (by-name) resolution. */+ byBasename: Map<string, string[]>;+}++export function buildAttachmentIndex(attachments: Map<string, Uint8Array>): AttachmentIndex {+ const byBasename = new Map<string, string[]>();+ for (const path of attachments.keys()) {+ const base = basename(path).toLowerCase();+ const paths = byBasename.get(base) ?? [];+ paths.push(path);+ byBasename.set(base, paths);+ }+ return { byPath: attachments, byBasename };+}++export function applyAttachments(note: BNote, html: string, index: AttachmentIndex, shrinkImages: boolean): string {+ if (index.byPath.size === 0 || (!html.includes("<img") && !html.includes("<a"))) {+ return html;+ }+ const root = parse(html);+ let changed = false;++ for (const img of root.querySelectorAll("img")) {+ const ref = attachmentRef(img.getAttribute("src"));+ const resolved = ref && resolveAttachment(index, ref.name);+ if (!ref || !resolved) {+ continue;+ }+ if (isImageMime(resolved.mime)) {+ try {+ const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, resolved.bytes, basename(resolved.path), shrinkImages);+ img.setAttribute("src", `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`);+ if (ref.width) {+ img.setAttribute("width", ref.width);+ }+ } catch {+ replaceWithFileLink(img, note, resolved);+ }+ } else {+ replaceWithFileLink(img, note, resolved);+ }+ changed = true;+ }++ // The file-reference links inserted above carry a `#root/…` href, so they're skipped by this pass.+ for (const anchor of root.querySelectorAll("a")) {+ const ref = attachmentRef(anchor.getAttribute("href"));+ const resolved = ref && resolveAttachment(index, ref.name);+ if (!ref || !resolved) {+ continue;+ }+ const attachment = note.saveAttachment({ role: "file", mime: resolved.mime, title: basename(resolved.path), content: resolved.bytes });+ anchor.setAttribute("href", attachmentHref(note.noteId, attachment.attachmentId));+ anchor.setAttribute("class", "reference-link");+ changed = true;+ }++ return changed ? root.toString() : html;+}++/** Saves `resolved` as a file attachment on `note` and replaces `element` with a reference link to it. */+function replaceWithFileLink(element: HTMLElement, note: BNote, resolved: ResolvedAttachment): void {+ const title = basename(resolved.path);+ const attachment = note.saveAttachment({ role: "file", mime: resolved.mime, title, content: resolved.bytes });+ element.insertAdjacentHTML("beforebegin", `<a class="reference-link" href="${attachmentHref(note.noteId, attachment.attachmentId)}">${escapeHtml(title)}</a>`);+ element.remove();+}++interface ResolvedAttachment {+ path: string;+ bytes: Uint8Array;+ mime: string;+}++/** Resolves a reference name to a bundled attachment: an exact path first, then a unique base-name match. */+function resolveAttachment(index: AttachmentIndex, name: string): ResolvedAttachment | null {+ let path = name;+ let bytes = index.byPath.get(path);+ if (!bytes) {+ const matches = index.byBasename.get(basename(name).toLowerCase());+ if (matches && matches.length === 1) {+ path = matches[0];+ bytes = index.byPath.get(path);+ }+ }+ if (!bytes) {+ return null;+ }+ return { path, bytes, mime: mimeService.getMime(basename(path)) || "application/octet-stream" };+}++/**+ * Extracts the vault file a `src`/`href` points at, or null for an external URL, an in-note anchor, or an+ * empty value. Strips the leading `/` the Markdown renderer adds, URL-decodes, and peels off Obsidian's+ * `#heading` and `|size` suffixes (the numeric size becomes the image width).+ */+function attachmentRef(value: string | undefined | null): { name: string; width?: string } | null {+ if (!value || /^(https?:|data:|mailto:|tel:|#)/i.test(value)) {+ return null;+ }+ let ref = safeDecode(value.replace(/^\//, ""));+ let width: string | undefined;+ const pipe = ref.indexOf("|");+ if (pipe !== -1) {+ const size = /^(\d+)(?:x\d+)?$/.exec(ref.slice(pipe + 1).trim());+ if (size) {+ width = size[1];+ }+ ref = ref.slice(0, pipe);+ }+ const hash = ref.indexOf("#");+ if (hash !== -1) {+ ref = ref.slice(0, hash);+ }+ ref = ref.replace(/\\/g, "/").trim();+ return ref ? { name: ref, width } : null;+}++function safeDecode(value: string): string {+ try {+ return decodeURIComponent(value);+ } catch {+ return value;+ }+}++function isImageMime(mime: string): boolean {+ return mime.startsWith("image/");+}++function attachmentHref(noteId: string, attachmentId: string): string {+ return `#root/${noteId}?viewMode=attachments&attachmentId=${attachmentId}`;+}diff --git a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.tsindex 0f5917fadb..b1f75b4df2 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts@@ -111,4 +111,55 @@ describe("Obsidian importer — integration", () => {expect(importRoot.title).toBe("Wrapper");expect(importRoot.getChildNotes().map((n) => n.title)).toEqual(["A", "B"]);});++ it("imports image embeds as image attachments and non-image embeds as file reference links", async () => {+ const importRoot = await importObsidian({+ "Attachment test.md": "![[shot.png]]\n\n![[doc.rtf]]",+ "shot.png": Buffer.from("\x89PNG\r\n\x1a\nfake-png"),+ "doc.rtf": Buffer.from("{\\rtf1 hello}"),+ ".obsidian/app.json": "{}"+ }, "Vault.zip");++ const note = importRoot.getChildNotes().find((n) => n.title === "Attachment test");+ if (!note) {+ throw new Error("note was not imported");+ }+ const content = decodeUtf8(note.getContent());++ // The image embed becomes a role:image attachment, its <img> src rewritten to point at it.+ const images = note.getAttachmentsByRole("image");+ expect(images.map((a) => a.title)).toEqual(["shot.png"]);+ expect(content).toContain(`<img src="api/attachments/${images[0]?.attachmentId}/image/`);+ expect(content).not.toContain(`src="/shot.png"`);++ // The non-image embed becomes a role:file attachment with a reference link.+ const files = note.getAttachmentsByRole("file");+ expect(files.map((a) => a.title)).toEqual(["doc.rtf"]);+ expect(content).toContain(`class="reference-link"`);+ expect(content).toContain(`attachmentId=${files[0]?.attachmentId}`);+ expect(content).not.toContain("/doc.rtf");+ });++ it("resolves an embed by name even when the attachment lives in a different folder", async () => {+ const importRoot = await importObsidian({+ "Notes/Page.md": "![[pic.png]]",+ "Assets/pic.png": Buffer.from("\x89PNG\r\n\x1a\nfake")+ });++ const page = importRoot.getChildNotes().find((n) => n.title === "Notes")?.getChildNotes()[0];+ expect(page?.getAttachmentsByRole("image").map((a) => a.title)).toEqual(["pic.png"]);+ });++ it("leaves note embeds and non-imported targets untouched (handled by later passes)", async () => {+ const importRoot = await importObsidian({+ "Note.md": "![[Other note]]\n\n![[Untitled.base]]",+ "Other note.md": "I am a note.",+ "Untitled.base": "filters: {}"+ });++ const note = importRoot.getChildNotes().find((n) => n.title === "Note");+ // Neither a note embed nor a .base resolves to an attachment, so nothing is saved in this pass.+ expect(note?.getAttachmentsByRole("image")).toHaveLength(0);+ expect(note?.getAttachmentsByRole("file")).toHaveLength(0);+ });});diff --git a/packages/trilium-core/src/services/import/obsidian/importer.ts b/packages/trilium-core/src/services/import/obsidian/importer.tsindex 3167c6bd2d..834336f267 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.ts@@ -28,6 +28,7 @@ import { decodeUtf8 } from "../../utils/binary.js";import { basename } from "../../utils/path.js";import { getZipProvider } from "../../zip_provider.js";import markdownService from "../markdown.js";+import { applyAttachments, buildAttachmentIndex } from "./attachments.js";interface VaultNote {/** The note's vault-root-relative POSIX path, e.g. `Folder 1/First note.md` (the wrapper folder stripped). */@@ -37,10 +38,10 @@ interface VaultNote {}async function importObsidian(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote, fileName?: string): Promise<BNote> {- const { notes, vaultRoot } = await parseVault(fileBuffer);+ const { notes, attachments, vaultRoot } = await parseVault(fileBuffer);taskContext.setTotalCount(notes.length);- return createNotes(importRootNote, notes, vaultTitle(vaultRoot, fileName), taskContext);+ return createNotes(importRootNote, notes, attachments, vaultTitle(vaultRoot, fileName), taskContext);}/**@@ -49,10 +50,11 @@ async function importObsidian(taskContext: TaskContext<"importNotes">, fileBuffe* folder and any other dot-prefixed entry are skipped, as is every non-Markdown file (handled in later* passes). Sorted by path so the resulting tree is built (and ordered) deterministically.*/-async function parseVault(fileBuffer: Uint8Array): Promise<{ notes: VaultNote[]; vaultRoot: string }> {+async function parseVault(fileBuffer: Uint8Array): Promise<{ notes: VaultNote[]; attachments: Map<string, Uint8Array>; vaultRoot: string }> {const provider = getZipProvider();const allPaths: string[] = [];const raw: { path: string; markdown: string }[] = [];+ const rawAttachments: { path: string; bytes: Uint8Array }[] = [];const filenameEncoding = await provider.detectFilenameEncoding(fileBuffer);await provider.readZipFile(fileBuffer, async (entry, readContent) => {@@ -60,11 +62,18 @@ async function parseVault(fileBuffer: Uint8Array): Promise<{ notes: VaultNote[];if (isDirectory(path)) {return;}+ // Record every entry (including .obsidian/) so the vault root can be detected; only collect content+ // for the kept ones below.allPaths.push(path);- if (isIgnored(path) || !isMarkdown(path)) {+ if (isIgnored(path)) {return;}- raw.push({ path, markdown: decodeUtf8(await readContent()) });+ if (isMarkdown(path)) {+ raw.push({ path, markdown: decodeUtf8(await readContent()) });+ } else if (!isSpecial(path)) {+ // A non-Markdown, non-special file is a candidate attachment (`.canvas`/`.base` are handled later).+ rawAttachments.push({ path, bytes: await readContent() });+ }}, filenameEncoding);const vaultRoot = detectVaultRoot(allPaths);@@ -74,7 +83,12 @@ async function parseVault(fileBuffer: Uint8Array): Promise<{ notes: VaultNote[];});notes.sort((a, b) => a.path.localeCompare(b.path));- return { notes, vaultRoot };+ const attachments = new Map<string, Uint8Array>();+ for (const { path, bytes } of rawAttachments) {+ attachments.set(stripVaultRoot(path, vaultRoot), bytes);+ }++ return { notes, attachments, vaultRoot };}/**@@ -82,20 +96,29 @@ async function parseVault(fileBuffer: Uint8Array): Promise<{ notes: VaultNote[];* container note for its folder (created on demand by {@link ensureFolder}, so a folder note exists before* its children), with its Markdown rendered to HTML. Returns the import root.*/-function createNotes(importRootNote: BNote, notes: VaultNote[], rootTitle: string, taskContext: TaskContext<"importNotes">): BNote {+function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Map<string, Uint8Array>, rootTitle: string, taskContext: TaskContext<"importNotes">): BNote {/* v8 ignore next -- the protected branch needs a protected import root with an active protected session, which the in-memory test DB has no way to set up */const isProtected = !!(importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable());const rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: rootTitle, content: "", type: "text", mime: "text/html", isProtected }).note;rootNote.addLabel("iconClass", "bx bx-import");+ const attachmentIndex = buildAttachmentIndex(attachments);+ const shrinkImages = !!taskContext.data?.shrinkImages;// Folder path (POSIX) -> its container note. The empty path maps to the import root.const folderNotes = new Map<string, BNote>();- for (const note of notes) {- const parent = ensureFolder(parentFolder(note.path), rootNote, folderNotes, isProtected);- const content = markdownService.renderToHtml(note.markdown, note.title);- noteService.createNewNote({ parentNoteId: parent.noteId, title: note.title, content, type: "text", mime: "text/html", isProtected });+ for (const vaultNote of notes) {+ const parent = ensureFolder(parentFolder(vaultNote.path), rootNote, folderNotes, isProtected);+ const html = markdownService.renderToHtml(vaultNote.markdown, vaultNote.title);+ const { note } = noteService.createNewNote({ parentNoteId: parent.noteId, title: vaultNote.title, content: html, type: "text", mime: "text/html", isProtected });++ // Attachments hang off the note, so this runs after creation; it returns the content with embedded+ // images/files rewritten to point at the saved attachments.+ const finalHtml = applyAttachments(note, html, attachmentIndex, shrinkImages);+ if (finalHtml !== html) {+ note.setContent(finalHtml);+ }taskContext.increaseProgressCount();}@@ -193,6 +216,11 @@ function isMarkdown(path: string): boolean {return path.toLowerCase().endsWith(".md");}+/** `.canvas` (whiteboards) and `.base` (Bases) get dedicated handling later, so they're not attachments. */+function isSpecial(path: string): boolean {+ return /\.(canvas|base)$/i.test(path);+}+/** The note title for a Markdown file: its base name without the `.md` extension. */function noteTitle(path: string): string {return basename(path).replace(/\.md$/i, "");