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/markdown): properly support attachments
Elian Doran06a5f9539962
diff --git a/apps/server/src/services/import/zip.ts b/apps/server/src/services/import/zip.tsindex 0d759f6fb4..1e57773c89 100644--- a/apps/server/src/services/import/zip.ts+++ b/apps/server/src/services/import/zip.ts@@ -23,6 +23,7 @@ import type TaskContext from "../task_context.js";import treeService from "../tree.js";import markdownService from "./markdown.js";import mimeService from "./mime.js";+import { isMarkdownCodeNote } from "../export/rewrite_links.js";interface MetaFile {files: NoteMeta[];@@ -406,6 +407,10 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bucontent = processTextNoteContent(content, noteTitle, filePath, noteMeta);}+ if (type === "code" && isMarkdownCodeNote(mime) && typeof content === "string") {+ content = processMarkdownCodeNoteContent(content, filePath);+ }+if (type === "relationMap" && noteMeta && typeof content === "string") {const relationMapLinks = (noteMeta.attributes || []).filter((attr) => attr.type === "relation" && attr.name === "relationMapLink");@@ -419,6 +424,62 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bureturn content;}+ /**+ * Rewrites relative file paths in markdown code notes back to Trilium internal+ * URLs (counterpart to `rewriteMarkdownContentLinks` in the export).+ */+ function processMarkdownCodeNoteContent(content: string, filePath: string) {+ function isUrlAbsolute(url: string) {+ return /^(?:[a-z]+:)?\/\//i.test(url);+ }++ // Image links: + content = content.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, url) => {+ try {+ url = decodeURIComponent(url).trim();+ } catch {+ return match;+ }++ if (isUrlAbsolute(url) || url.startsWith("api/")) {+ return match;+ }++ const target = getEntityIdFromRelativeUrl(url, filePath);++ if (target.attachmentId) {+ return ``;+ } else if (target.noteId) {+ return ``;+ }+ return match;+ });++ // Non-image links: [text](relative/path)+ content = content.replace(/(?<!!)\[([^\]]*)\]\(([^)]+)\)/g, (match, text, url) => {+ try {+ url = decodeURIComponent(url).trim();+ } catch {+ return match;+ }++ if (isUrlAbsolute(url) || url.startsWith("#") || url.startsWith("api/")) {+ return match;+ }++ const target = getEntityIdFromRelativeUrl(url, filePath);++ if (target.attachmentId) {+ return `[${text}](#root/${target.noteId}?viewMode=attachments&attachmentId=${target.attachmentId})`;+ } else if (target.noteId) {+ return `[${text}](#root/${target.noteId})`;+ }+ return match;+ });++ return content;+ }+function saveNote(filePath: string, content: string | Buffer) {const { parentNoteMeta, noteMeta, attachmentMeta } = getMeta(filePath);