Skip to content

Build your personal knowledge base with Trilium Notes

fix(import): restore a link preview's pictures on ZIP import

Elian Doran6ebe4d83ac93
diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.ts
index 19104debd4..5d1ca9a34c 100644
--- a/packages/trilium-core/src/services/export/zip.spec.ts
+++ b/packages/trilium-core/src/services/export/zip.spec.ts
@@ -4,6 +4,9 @@ import { join } from "path";
import { PassThrough } from "stream";
import { beforeAll, describe, expect, it } from "vitest";
+import { isLocalPreviewImageSrc } from "@triliumnext/commons";
+
+import becca from "../../becca/becca.js";
import type BBranch from "../../becca/entities/bbranch.js";
import type BNote from "../../becca/entities/bnote.js";
import type { ExportFormat, NoteMetaFile } from "../../meta.js";
@@ -389,6 +392,53 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {
}
});
+ it("carries a link preview's pictures through an export and back", async () => {
+ // The two halves of the rewrite above are each tested against a fixed archive shape, which
+ // leaves the seam between them untested — and the seam is where this broke: the export
+ // learned about `data-image`/`data-favicon` while the import kept rewriting `src` alone, so
+ // both pictures imported as attachments with the right roles and neither one rendered.
+ // A title with a space in it, as the default "New note" has: the export prefixes it onto
+ // both attachment file names, and a space is exactly what the render sinks reject.
+ const { note } = createNote("root", { title: "Round Trip Host", content: "" });
+ getContext().init(() => {
+ const cover = note.saveAttachment({ role: "coverImage", mime: "image/jpeg", title: "https://example.com/page", content: "jpeg-bytes" });
+ const favicon = note.saveAttachment({ role: "favicon", mime: "image/png", title: "example.com", content: "png-bytes" });
+ note.setContent(`<section class="link-embed" data-url="https://example.com/page" data-embed-type="opengraph"`
+ + ` data-title="Example" data-image="api/attachments/${cover.attachmentId}/image/page.jpg"`
+ + ` data-favicon="api/attachments/${favicon.attachmentId}/image/example.com.png"></section>`);
+ });
+
+ const taskContext = (await import("../task_context.js")).default;
+ const importZip = (await import("../import/zip.js")).default;
+
+ // Markdown too: that export keeps the preview's raw HTML, so it carries the same two
+ // attributes and needs the same journey back.
+ for (const format of ["html", "markdown"] as const) {
+ const { buffer } = await exportSubtree(note.getParentBranches()[0], format);
+ const imported = await getContext().init(async () => await importZip.importZip(
+ new taskContext("no-progress-reporting", "importNotes", {}),
+ buffer,
+ becca.getNoteOrThrow("root")
+ ));
+
+ const content = imported.getContent().toString();
+ const idOf = (role: string) => imported.getAttachments().find((a) => a.role === role)?.attachmentId;
+
+ // New ids on the far side, so the references have to have been rewritten twice over...
+ expect(content, format).toContain(`data-image="api/attachments/${idOf("coverImage")}/image/`);
+ expect(content, format).toContain(`data-favicon="api/attachments/${idOf("favicon")}/image/`);
+
+ // ...and into something the render sinks will actually load. Pointing at the right
+ // attachment is only half of it: this note's title has a space in it, which the export
+ // prefixes onto both file names, and the pattern below admits none.
+ const sources = [...content.matchAll(/data-(?:image|favicon)="([^"]*)"/g)];
+ expect(sources, format).toHaveLength(2);
+ for (const [, src] of sources) {
+ expect(isLocalPreviewImageSrc(src), `${format}: ${src}`).toBe(true);
+ }
+ }
+ });
+
it("pipes the archive to the response before appending any content", async () => {
// Memory efficiency: the archive must start streaming to the response
// before note/attachment content is appended, so blobs drain to the
diff --git a/packages/trilium-core/src/services/import/zip.spec.ts b/packages/trilium-core/src/services/import/zip.spec.ts
index cac2d00447..e4d31ea9cb 100644
--- a/packages/trilium-core/src/services/import/zip.spec.ts
+++ b/packages/trilium-core/src/services/import/zip.spec.ts
@@ -12,7 +12,7 @@ import BNote from "../../becca/entities/bnote.js";
import noteService from "../notes.js";
import TaskContext from "../task_context.js";
import sql_init from "../sql_init.js";
-import { trimIndentation } from "@triliumnext/commons";
+import { isLocalPreviewImageSrc, trimIndentation } from "@triliumnext/commons";
import { getContext } from "../context.js";
const scriptDir = dirname(fileURLToPath(import.meta.url));
@@ -936,6 +936,66 @@ describe("link and image rewriting on import", () => {
expect(content).toContain(`href="#root/`);
});
+ it("rewrites a link preview's picture references back onto the imported attachments", async () => {
+ // The counterpart of the export's `data-image`/`data-favicon` rewrite. A preview keeps its two
+ // pictures in those attributes rather than in an <img src>, and the render sinks accept only an
+ // `api/attachments/…` URL (see `isLocalPreviewImageSrc`), so an archived relative filename left
+ // as it stands renders as no picture at all — with both attachments sitting right there.
+ const metaFile = {
+ formatVersion: 2,
+ appVersion: "0.0.0",
+ files: [{
+ noteId: "previewHost01",
+ title: "Preview Host",
+ type: "text",
+ mime: "text/html",
+ format: "html",
+ dataFileName: "Preview Host.html",
+ attributes: [],
+ attachments: [{
+ attachmentId: "previewCover01",
+ title: "https://example.com/page",
+ role: "coverImage",
+ mime: "image/jpeg",
+ position: 10,
+ dataFileName: "Preview Host_cover.jpg"
+ }, {
+ attachmentId: "previewIcon001",
+ title: "example.com",
+ role: "favicon",
+ mime: "image/png",
+ position: 20,
+ dataFileName: "Preview Host_example.com.png"
+ }]
+ }]
+ };
+
+ const zipBuffer = await createZipBuffer({
+ "!!!meta.json": JSON.stringify(metaFile),
+ "Preview Host.html": `<section class="link-embed" data-url="https://example.com/page"`
+ + ` data-embed-type="opengraph" data-title="Example"`
+ + ` data-image="Preview Host_cover.jpg"`
+ + ` data-favicon="Preview Host_example.com.png"></section>`,
+ "Preview Host_cover.jpg": Buffer.from("jpeg-bytes"),
+ "Preview Host_example.com.png": Buffer.from("png-bytes")
+ });
+
+ const { importedNote } = await testImportBuffer(zipBuffer, "import-link-preview-pictures");
+ const content = importedNote.getContent().toString();
+ const idOf = (role: string) => importedNote.getAttachments().find((a) => a.role === role)?.attachmentId;
+
+ // The attachment's title, encoded — not the archive file name. The owner note's title is
+ // prefixed onto that, so with a space in it ("Preview Host_cover.jpg", and "New note_…" for
+ // anyone who never renamed the note) the reference would be right and still render nothing:
+ // the sink admits no whitespace.
+ expect(content).toContain(`data-image="api/attachments/${idOf("coverImage")}/image/https%3A%2F%2Fexample.com%2Fpage"`);
+ expect(content).toContain(`data-favicon="api/attachments/${idOf("favicon")}/image/example.com"`);
+
+ for (const [, src] of content.matchAll(/data-(?:image|favicon)="([^"]*)"/g)) {
+ expect(isLocalPreviewImageSrc(src), src).toBe(true);
+ }
+ });
+
it("remaps an includeNoteLink target inside the note's own content", async () => {
const metaFile = {
formatVersion: 2,
diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.ts
index 9c1f6de6c8..de11df0caa 100644
--- a/packages/trilium-core/src/services/import/zip.ts
+++ b/packages/trilium-core/src/services/import/zip.ts
@@ -389,7 +389,13 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou
content = content.replace(/<html.*<body[^>]*>/gis, "");
content = content.replace(/<\/body>.*<\/html>/gis, "");
- content = content.replace(/src="([^"]*)"/g, (match, url) => {
+ // `data-image` and `data-favicon` are where a link preview (section.link-embed /
+ // span.link-mention) keeps its two pictures, which the export rewrites to attachment files
+ // alongside any <img src> — so they have to come back the same way. They are only ever an
+ // attachment of the note, and the render sinks accept nothing else (see
+ // `isLocalPreviewImageSrc`), so the note-image fallback below is deliberately not offered to
+ // them: an unresolvable reference stays as it is and the preview falls back to its placeholder.
+ content = content.replace(/(src|data-image|data-favicon)="([^"]*)"/g, (match, attrName, url) => {
if (url.startsWith("data:image")) {
// inline images are parsed and saved into attachments in the note service
return match;
@@ -399,7 +405,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou
url = decodeURIComponent(url).trim();
} catch (e: any) {
getLog().error(`Cannot parse image URL '${url}', keeping original. Error: ${e.message}.`);
- return `src="${url}"`;
+ return `${attrName}="${url}"`;
}
if (isUrlAbsolute(url)) {
@@ -409,11 +415,20 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou
const target = getEntityIdFromRelativeUrl(url, filePath);
if (target.attachmentId && !target.isRenderedNoteImage) {
- return `src="api/attachments/${target.attachmentId}/image/${basename(url)}"`;
- } else if (target.noteId) {
+ // The attachment's own title, encoded — not the archive's file name, which is prefixed
+ // with the owner note's title and so carries whatever spaces and punctuation that had.
+ // A space there is fatal rather than untidy: `isLocalPreviewImageSrc` guards the render
+ // sinks with an anchored pattern that admits no whitespace, so a preview whose owner
+ // was called "New note" imports with correct references that draw nothing. Every other
+ // producer of one of these URLs already encodes the title, the Markdown branch below
+ // included.
+ const title = encodeURIComponent(target.attachmentTitle || basename(url));
+
+ return `${attrName}="api/attachments/${target.attachmentId}/image/${title}"`;
+ } else if (target.noteId && attrName === "src") {
return `src="api/images/${target.noteId}/${basename(url)}"`;
}
- /* v8 ignore next -- unreachable: getEntityIdFromRelativeUrl always yields a noteId; kept so the callback returns a string on every path */
+
return match;
});