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
fix(import): reconstruct a link preview's inlined pictures as attachments
Elian Doranb38fcb06ff76
diff --git a/packages/trilium-core/src/services/export/single.spec.ts b/packages/trilium-core/src/services/export/single.spec.tsindex 0d469a08f5..e635686129 100644--- a/packages/trilium-core/src/services/export/single.spec.ts+++ b/packages/trilium-core/src/services/export/single.spec.ts@@ -150,14 +150,30 @@ describe("inlineAttachments", () => {}});- it("leaves an embedded image alone when the note is missing, not an image, or holds text", () => {+ it("inlines an image note whose content is text, an SVG being the case in point", () => {+ // An SVG is markup, so its content comes back as a string rather than as bytes. Skipping it on+ // that basis left the exported file naming `api/images/<id>` — an address that resolves only+ // in the instance it came from, and there to whatever note holds that id now.+ const svgNote = buildNote({ type: "image", mime: "image/svg+xml", title: "icon.svg" });+ vi.spyOn(svgNote, "getContent").mockReturnValue("<svg/>");+ const getNote = vi.spyOn(becca, "getNote").mockReturnValue(svgNote);++ try {+ const payload = exportHtml(`<p><img src="api/images/img1/icon.svg"></p>`);++ expect(payload).toContain(`src="data:image/svg+xml;base64,${btoa("<svg/>")}"`);+ expect(payload).not.toContain("api/images");+ } finally {+ getNote.mockRestore();+ }+ });++ it("leaves an embedded image alone when the note is missing or is not an image", () => {const textNote = buildNote({ type: "text", mime: "text/html", title: "Not an image" });- const stringImage = buildNote({ type: "image", mime: "image/png", title: "odd.png" });- vi.spyOn(stringImage, "getContent").mockReturnValue("not binary");const getNote = vi.spyOn(becca, "getNote");try {- for (const stub of [null, textNote, stringImage]) {+ for (const stub of [null, textNote]) {getNote.mockReturnValue(stub as never);expect(exportHtml(`<p><img src="api/images/img1/pic.png"></p>`)).toContain(`src="api/images/img1/pic.png"`);}@@ -185,7 +201,23 @@ describe("inlineAttachments", () => {}});- it("leaves an attachment reference alone when it is missing, not an image, or holds text", () => {+ it("inlines an SVG favicon, whose content is markup rather than bytes", () => {+ // What a link preview of a site serving an SVG icon holds — GitHub, for one. Left behind, the+ // favicon was the one picture of the exported card that pointed back at the source instance.+ const svg = { mime: "image/svg+xml", title: "github.com.svg", getContent: () => "<svg/>" } as unknown as BAttachment;+ const getAttachment = vi.spyOn(becca, "getAttachment").mockReturnValue(svg);++ try {+ const payload = exportHtml(`<section data-favicon="api/attachments/att1/image/github.com.svg"></section>`);++ expect(payload).toContain(`data-favicon="data:image/svg+xml;base64,${btoa("<svg/>")}"`);+ expect(payload).not.toContain("api/attachments");+ } finally {+ getAttachment.mockRestore();+ }+ });++ it("leaves an attachment reference alone when it is missing or is not an image", () => {const getAttachment = vi.spyOn(becca, "getAttachment");const textAttachment = { mime: "text/plain", title: "notes.txt", getContent: () => "plain text" } as unknown as BAttachment;@@ -195,19 +227,14 @@ describe("inlineAttachments", () => {expect(exportHtml(`<section data-image="api/attachments/att1/image/x.png"></section>`)).toContain(`data-image="api/attachments/att1/image/x.png"`);- // ... as is an image attachment whose content came back as text ...- getAttachment.mockReturnValue({ mime: "image/png", title: "x.png", getContent: () => "text" } as unknown as BAttachment);- expect(exportHtml(`<section data-image="api/attachments/att1/image/x.png"></section>`))- .toContain(`data-image="api/attachments/att1/image/x.png"`);-- // ... and an href to an attachment that no longer exists, or whose content is text.+ // ... whereas an href inlines an attachment of any type, so only a missing one survives.getAttachment.mockReturnValue(null as never);expect(exportHtml(`<p><a href="#root/abc?viewMode=attachments&attachmentId=att1">x</a></p>`)).toContain("attachmentId=att1");getAttachment.mockReturnValue(textAttachment);expect(exportHtml(`<p><a href="#root/abc?viewMode=attachments&attachmentId=att1">x</a></p>`))- .toContain("attachmentId=att1");+ .toContain(`href="data:text/plain;base64,${btoa("plain text")}" download="notes.txt"`);} finally {getAttachment.mockRestore();}diff --git a/packages/trilium-core/src/services/export/single.ts b/packages/trilium-core/src/services/export/single.tsindex d05c41e8f4..ba4209ed04 100644--- a/packages/trilium-core/src/services/export/single.ts+++ b/packages/trilium-core/src/services/export/single.ts@@ -122,6 +122,15 @@ export function mapByNoteType(note: BNote, content: string | Uint8Array, format:return { payload, extension, mime };}+/**+ * Carries every picture and file the content points at into the content itself, as base64 `data:`+ * URIs — the whole point of a single-file export being that the one file stands alone.+ *+ * Anything left un-inlined leaves behind a reference to `api/attachments/<id>` or `api/images/<id>`,+ * which is not merely unresolvable outside this instance but actively misleading: the ids are this+ * database's, so the file names an attachment that exists, somewhere else, belonging to someone+ * else's note. Hence no bail-out here is by choice — each one is a case that could not be encoded.+ */function inlineAttachments(content: string) {content = content.replace(/src="[^"]*api\/images\/([a-zA-Z0-9_]+)\/?[^"]+"/g, (match, noteId) => {const note = becca.getNote(noteId);@@ -129,12 +138,7 @@ function inlineAttachments(content: string) {return match;}- const imageContent = note.getContent();- if (typeof imageContent === "string") {- return match;- }-- const base64Content = encodeBase64(imageContent);+ const base64Content = encodeBase64(note.getContent());const srcValue = `data:${note.mime};base64,${base64Content}`;return `src="${srcValue}"`;@@ -149,12 +153,7 @@ function inlineAttachments(content: string) {return match;}- const attachmentContent = attachment.getContent();- if (typeof attachmentContent === "string") {- return match;- }-- const base64Content = encodeBase64(attachmentContent);+ const base64Content = encodeBase64(attachment.getContent());const srcValue = `data:${attachment.mime};base64,${base64Content}`;return `${attrName}="${srcValue}"`;@@ -166,12 +165,7 @@ function inlineAttachments(content: string) {return match;}- const attachmentContent = attachment.getContent();- if (typeof attachmentContent === "string") {- return match;- }-- const base64Content = encodeBase64(attachmentContent);+ const base64Content = encodeBase64(attachment.getContent());const hrefValue = `data:${attachment.mime};base64,${base64Content}`;return `href="${hrefValue}" download="${escapeHtml(attachment.title)}"`;diff --git a/packages/trilium-core/src/services/image_download.spec.ts b/packages/trilium-core/src/services/image_download.spec.tsindex bc622ebefe..c980a10598 100644--- a/packages/trilium-core/src/services/image_download.spec.ts+++ b/packages/trilium-core/src/services/image_download.spec.ts@@ -2,7 +2,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import type BNote from "../becca/entities/bnote.js";import { getContext } from "./context.js";-import { downloadLinkPreviewPictures, downloadPictureToAttachment } from "./image_download.js";+import { downloadPictureToAttachment, storeLinkPreviewPictures } from "./image_download.js";import noteService from "./notes.js";import optionService from "./options.js";import { initRequest } from "./request.js";@@ -34,6 +34,9 @@ const PIXEL_PNG = Buffer.from("base64");+/** A vector icon, as GitHub and a good many other sites serve. Markup, so its bytes are text. */+const TINY_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M0 0h16v16H0z"/></svg>`;+const card = (url: string, favicon: string, image?: string) =>`<section class="link-embed" data-url="${url}" data-embed-type="opengraph" data-favicon="${favicon}"`+ `${image ? ` data-image="${image}"` : ""}></section>`;@@ -122,13 +125,13 @@ describe("downloadPictureToAttachment (real DB)", () => {});});-describe("downloadLinkPreviewPictures (real DB)", () => {+describe("storeLinkPreviewPictures (real DB)", () => {it("stores each as an attachment and points the card at it", async () => {// What a Notion export leaves behind: the origin's addresses and no bytes, which the render// sinks refuse outright — so until they are fetched the card shows placeholders.const note = createNote(card("https://example.com/page", "https://example.com/favicon.png", "https://cdn.example.com/cover.png"));- await getContext().init(() => downloadLinkPreviewPictures(note));+ await getContext().init(() => storeLinkPreviewPictures(note));expect(asked).toEqual([ "https://example.com/favicon.png", "https://cdn.example.com/cover.png" ]);@@ -153,7 +156,7 @@ describe("downloadLinkPreviewPictures (real DB)", () => {+ card("https://example.com/b", "https://example.com/favicon.png"));- await getContext().init(() => downloadLinkPreviewPictures(note));+ await getContext().init(() => storeLinkPreviewPictures(note));expect(note.getAttachments().map((a) => a.title)).toStrictEqual([ "example.com.png" ]);});@@ -165,7 +168,7 @@ describe("downloadLinkPreviewPictures (real DB)", () => {getContext().init(() => optionService.setOption("downloadImagesAutomatically", "false"));try {- await getContext().init(() => downloadLinkPreviewPictures(note));+ await getContext().init(() => storeLinkPreviewPictures(note));} finally {getContext().init(() => optionService.setOption("downloadImagesAutomatically", String(previously)));}@@ -176,16 +179,84 @@ describe("downloadLinkPreviewPictures (real DB)", () => {expect(String(note.getContent())).toContain("https://example.com/favicon.png");});- it("leaves a picture that is already local alone", async () => {- // A preview made here, or one already fetched: neither is a third party's address.+ it("leaves a picture that is already an attachment alone", async () => {+ // A preview made here, or one already stored: nothing left to do and nobody to ask.+ const note = createNote(card("https://example.com/page", "api/attachments/att1/image/example.com.ico"));++ await getContext().init(() => storeLinkPreviewPictures(note));++ expect(asked).toEqual([]);+ expect(note.getAttachments()).toHaveLength(0);+ expect(String(note.getContent())).toContain(`data-favicon="api/attachments/att1/image/example.com.ico"`);+ });++ it("lifts a picture carried inline out into an attachment", async () => {+ // Our own single-file export inlines both pictures as base64, having nowhere else to put them,+ // and every preview made before the pictures became attachments carried them the same way.+ // Left inline they cost a third more than the bytes they encode, in every revision of the note.+ const note = createNote(card(+ "https://example.com/page",+ `data:image/svg+xml;base64,${btoa(TINY_SVG)}`,+ `data:image/png;base64,${PIXEL_PNG.toString("base64")}`+ ));++ await getContext().init(() => storeLinkPreviewPictures(note));++ // Nothing was fetched — the bytes were already here — and both are roled and named exactly as+ // a preview made here would have stored them.+ expect(asked).toEqual([]);+ const attachments = note.getAttachments();+ expect(attachments.map((a) => [ a.role, a.title ]).sort()).toStrictEqual([+ [ "coverImage", expect.stringMatching(/^example\.com-page-[0-9a-f]{8}\.png$/) ],+ [ "favicon", "example.com.svg" ]+ ]);++ const content = String(note.getContent());+ expect(content).not.toContain("base64");+ for (const attachment of attachments) {+ expect(content).toContain(`api/attachments/${attachment.attachmentId}/image/`);+ }+ });++ it("lifts an inline picture whatever the setting says, having nobody to ask", async () => {+ // `downloadImagesAutomatically` governs reaching out to a third party on the reader's behalf.+ // Unpacking bytes the note already carries asks nothing of anyone, so the setting has no say —+ // and gating it there would leave the base64 in place for anyone who had turned it off.+ const note = createNote(card("https://example.com/page", `data:image/png;base64,${PIXEL_PNG.toString("base64")}`));+ const previously = optionService.getOptionBool("downloadImagesAutomatically");+ getContext().init(() => optionService.setOption("downloadImagesAutomatically", "false"));++ try {+ await getContext().init(() => storeLinkPreviewPictures(note));+ } finally {+ getContext().init(() => optionService.setOption("downloadImagesAutomatically", String(previously)));+ }++ expect(note.getAttachments().map((a) => a.title)).toStrictEqual([ "example.com.png" ]);+ expect(String(note.getContent())).not.toContain("base64");+ });++ it("keeps one icon when the same inline picture repeats across cards", async () => {+ // The saving that makes this worth doing: a site linked a dozen times inlines its icon a+ // dozen times, and a deduplicated role keys on the title, so those dozen become one.+ const icon = `data:image/png;base64,${PIXEL_PNG.toString("base64")}`;const note = createNote(- card("https://example.com/page", "api/attachments/att1/image/example.com.ico")- + card("https://other.example/x", "data:image/png;base64,AAAA")+ card("https://example.com/a", icon) + card("https://example.com/b", icon));- await getContext().init(() => downloadLinkPreviewPictures(note));+ await getContext().init(() => storeLinkPreviewPictures(note));- expect(asked).toEqual([]);+ expect(note.getAttachments().map((a) => a.title)).toStrictEqual([ "example.com.png" ]);+ });++ it("leaves an inline value alone when it is not a picture at all", async () => {+ // The bytes are asked what they are rather than the `data:` prefix being taken for it.+ const note = createNote(card("https://example.com/page", "data:image/png;base64,AAAA"));++ await getContext().init(() => storeLinkPreviewPictures(note));++ expect(note.getAttachments()).toHaveLength(0);+ expect(String(note.getContent())).toContain(`data-favicon="data:image/png;base64,AAAA"`);});it("drops nothing and keeps going when a picture cannot be had", async () => {@@ -194,7 +265,7 @@ describe("downloadLinkPreviewPictures (real DB)", () => {const note = createNote(card("https://example.com/page", "https://example.com/favicon.png", "https://cdn.example.com/gone.png"));answerWith = (url) => (url.includes("gone") ? undefined : PIXEL_PNG);- await getContext().init(() => downloadLinkPreviewPictures(note));+ await getContext().init(() => storeLinkPreviewPictures(note));expect(note.getAttachments().map((a) => a.role)).toStrictEqual([ "favicon" ]);expect(String(note.getContent())).toContain(`data-image="https://cdn.example.com/gone.png"`);diff --git a/packages/trilium-core/src/services/image_download.ts b/packages/trilium-core/src/services/image_download.tsindex c55315699a..a1fb66ad5f 100644--- a/packages/trilium-core/src/services/image_download.ts+++ b/packages/trilium-core/src/services/image_download.ts@@ -10,8 +10,12 @@* Governed throughout by `downloadImagesAutomatically`: fetching is the note reaching out to a third* party on the reader's behalf, which is the user's decision rather than ours.*- * Two shapes of reference are handled, and {@link downloadPictureToAttachment} is the step they- * share — give it an address and it answers with the attachment URL that replaces it.+ * A picture carried *inline*, as a base64 `data:` URI, is moved out here for the same reasons minus+ * the fetch: base64 costs a third more than the bytes it encodes, is copied into every revision of+ * the note, and repeats in full for each place the same picture appears.+ *+ * Two shapes of reference are handled, and {@link storePictureBytes} is the step they share — give+ * it bytes and it answers with the attachment URL that references them.*/import { type ImageAttachmentRole, imageExtensionForMime, isHttpUrl, linkPreviewImageName, safeHostname } from "@triliumnext/commons";@@ -31,9 +35,37 @@ import { decodeBase64 } from "./utils/binary.js";import { quoteRegex, unescapeHtml } from "./utils/index.js";import { basename } from "./utils/path.js";-/** What a stored picture is referenced by, once it belongs to the note rather than to a website. */-function attachmentReference(attachmentId: string, title: string): string {- return `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`;+/**+ * Keeps a picture's bytes as an attachment of `noteId`, answering with the URL that references it —+ * or nothing when the bytes are not a picture at all.+ *+ * The bytes are asked what they are rather than the address, the server or the `data:` prefix being+ * taken for it, so a 404 page served where a picture should be is refused rather than stored.+ */+function storePictureBytes(+ noteId: string,+ bytes: Uint8Array,+ { role, title, shrink }: { role: ImageAttachmentRole; title: string; shrink: boolean }+): string | undefined {+ const { format, mime } = inspectImage(bytes);++ if (format === UNKNOWN_FORMAT) {+ return undefined;+ }++ const attachment = imageService.saveImageToAttachment(+ noteId,+ bytes,+ `${title}.${imageExtensionForMime(mime)}`,+ shrink,+ // The title is the key a deduplicated role is reused by, so it is never shortened.+ false,+ role+ );++ return attachment.attachmentId+ ? `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}`+ : undefined;}/**@@ -60,23 +92,8 @@ export async function downloadPictureToAttachment(try {const bytes = new Uint8Array(await request.getImage(pictureUrl));- const { format, mime } = inspectImage(bytes);- if (format === UNKNOWN_FORMAT) {- return undefined;- }-- const attachment = imageService.saveImageToAttachment(- noteId,- bytes,- `${title}.${imageExtensionForMime(mime)}`,- shrink,- // The title is the key a deduplicated role is reused by, so it is never shortened.- false,- role- );-- return attachment.attachmentId ? attachmentReference(attachment.attachmentId, attachment.title) : undefined;+ return storePictureBytes(noteId, bytes, { role, title, shrink });} catch (e: unknown) {// The address is deliberately left out of the line: it is a page the user was reading, and// the note it came from is enough to find this again.@@ -244,20 +261,29 @@ const PREVIEW_PICTURE_ROLES = [const PREVIEW_TAG_REGEX = /<(?:section|span)\b[^>]*\bclass="[^"]*link-(?:embed|mention)[^"]*"[^>]*>/gi;/**- * Fetches the pictures a link preview names at a third party, storing each as an attachment.+ * Makes a link preview's two pictures attachments of the note, wherever they currently are.+ *+ * A preview made here already has both stored server-side, so this is entirely about content that+ * arrived from elsewhere, and such content carries its pictures one of two ways:*- * Only imported and pasted content ever holds such a URL: a preview made here has its pictures- * downloaded and stored server-side already, and the render sinks refuse a remote one outright, so- * until they are fetched these cards show placeholders. A Notion export is the case in point — it- * ships no bytes at all, only the origin's addresses.+ * - **named at a third party**, which is what a Notion export ships — the origin's addresses and no+ * bytes at all. Fetching them is the note reaching out on the reader's behalf, so it is governed+ * by `downloadImagesAutomatically`, the same setting that decides whether a remote `<img>` in note+ * content is fetched. They belong to that question and were only ever outside it by accident: they+ * arrive in an export as ordinary `<img>` elements and become attributes when the importer+ * rewrites the card, which took them out of the pass that would have handled them.+ * - **carried inline**, as a base64 `data:` URI. Our own single-file export writes them that way (it+ * has nowhere else to put them), as did every preview made before the pictures became attachments.+ * Nothing is fetched to unpack one, so the setting above has no say — the bytes are already here,+ * and the only question is whether they sit in the content or beside it.*- * Governed by `downloadImagesAutomatically`, the same setting that decides whether a remote `<img>`- * in note content is fetched. These pictures belong to that question and were only ever outside it- * by accident: they arrive in an export as ordinary `<img>` elements and become attributes when the- * importer rewrites the card, which took them out of the pass that would have handled them.+ * Both are worth undoing, for the same reason the pictures became attachments in the first place. An+ * inline picture is base64 in the note's content, a third again larger than the bytes it encodes,+ * duplicated into every revision of the note and reread on every load. A site linked a dozen times+ * inlines its icon a dozen times; stored under a deduplicating role, those dozen become one.*/-export async function downloadLinkPreviewPictures(note: BNote) {- if (note.type !== "text" || !optionService.getOptionBool("downloadImagesAutomatically")) {+export async function storeLinkPreviewPictures(note: BNote) {+ if (note.type !== "text") {return;}@@ -273,7 +299,7 @@ export async function downloadLinkPreviewPictures(note: BNote) {let cursor = 0;for (const tag of tags) {- rewritten += content.slice(cursor, tag.index) + await downloadPicturesOf(note.noteId, tag[0]);+ rewritten += content.slice(cursor, tag.index) + await storePicturesOf(note.noteId, tag[0]);cursor = tag.index + tag[0].length;}@@ -284,28 +310,42 @@ export async function downloadLinkPreviewPictures(note: BNote) {}}-/** One preview's opening tag, with any picture it names at a third party fetched and pointed at. */-async function downloadPicturesOf(noteId: string, tag: string): Promise<string> {+/** One preview's opening tag, with each picture it holds or names stored and pointed at. */+async function storePicturesOf(noteId: string, tag: string): Promise<string> {const cardUrl = unescapeHtml(attributeOf(tag, "data-url") ?? "");let rewritten = tag;for (const [ attribute, role ] of PREVIEW_PICTURE_ROLES) {const stored = attributeOf(tag, attribute);- // Anything already local — an attachment of this note, or an inline image — is left alone.- if (!stored || !isHttpUrl(unescapeHtml(stored))) {++ if (!stored) {continue;}+ const value = unescapeHtml(stored);// Named and roled exactly as a preview fetched here would be, so an imported card ends up// indistinguishable from a made one — and a site named by several cards keeps one icon// between them, the title being what a deduplicated role reuses an attachment by.- const reference = await downloadPictureToAttachment(noteId, unescapeHtml(stored), {- role,- title: role === "favicon" ? safeHostname(cardUrl) : linkPreviewImageName(cardUrl),- // An icon is a few KB of flat colour with nothing for the compression pipeline to find;- // a cover may be a full-size social image.- shrink: role === "coverImage"- });+ const title = role === "favicon" ? safeHostname(cardUrl) : linkPreviewImageName(cardUrl);+ let reference: string | undefined;++ if (isHttpUrl(value)) {+ if (!optionService.getOptionBool("downloadImagesAutomatically")) {+ continue;+ }++ reference = await downloadPictureToAttachment(noteId, value, {+ role,+ title,+ // An icon is a few KB of flat colour with nothing for the compression pipeline to+ // find; a cover may be a full-size social image.+ shrink: role === "coverImage"+ });+ } else {+ // Anything that is neither inline nor remote — an attachment of this note already — is+ // left alone by `storeInlinePicture` answering with nothing.+ reference = storeInlinePicture(noteId, value, { role, title });+ }if (reference) {rewritten = rewritten.replace(`${attribute}="${stored}"`, `${attribute}="${reference}"`);@@ -315,6 +355,36 @@ async function downloadPicturesOf(noteId: string, tag: string): Promise<string>return rewritten;}+/**+ * Lifts a picture carried inline in the content out into an attachment, answering with the URL that+ * replaces it — or nothing when the value is not an inline picture to begin with.+ *+ * Only base64 is read. A `data:` URI may also carry its payload percent-encoded, but nothing that+ * reaches here writes one that way: it is the form for short text, and our own exporter, the old+ * preview pipeline and every browser encoding a picture all use base64.+ */+function storeInlinePicture(+ noteId: string,+ value: string,+ { role, title }: { role: ImageAttachmentRole; title: string }+): string | undefined {+ const inline = /^data:image\/[a-z0-9.+-]+;base64,(.*)$/is.exec(value.trim());++ if (!inline) {+ return undefined;+ }++ try {+ // The picture was sized by whoever made the preview — ours are stored at an icon's and a+ // thumbnail's size already — so this only moves bytes, and recompressing them would be a+ // second lossy pass over a picture that has had one.+ return storePictureBytes(noteId, decodeBase64(inline[1]), { role, title, shrink: false });+ } catch (e: unknown) {+ getLog().info(`Could not store an inline preview picture of note '${noteId}': ${e}`);+ return undefined;+ }+}+function attributeOf(tag: string, name: string): string | undefined {return new RegExp(`\\b${name}="([^"]*)"`, "i").exec(tag)?.[1];}diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.tsindex 3c5f8faa0e..b7c3aacf5f 100644--- a/packages/trilium-core/src/services/import/notion/importer.ts+++ b/packages/trilium-core/src/services/import/notion/importer.ts@@ -20,7 +20,7 @@ import { type HTMLElement, parse } from "node-html-parser";import type BNote from "../../../becca/entities/bnote.js";import * as cls from "../../context.js";import imageService from "../../image.js";-import { downloadLinkPreviewPictures } from "../../image_download.js";+import { storeLinkPreviewPictures } from "../../image_download.js";import noteService from "../../notes.js";import protectedSessionService from "../../protected_session.js";import { sanitizeHtml } from "../../sanitizer.js";@@ -70,7 +70,7 @@ async function importNotion(taskContext: TaskContext<"importNotes">, source: Zip// address — so those have to be fetched if the cards are to show anything. Done here rather// than inside createNotes, which is synchronous, and only once every page's content is final.for (const { note } of createdNotes(rootNote)) {- await downloadLinkPreviewPictures(note);+ await storeLinkPreviewPictures(note);}return rootNote;diff --git a/packages/trilium-core/src/services/import/single.spec.ts b/packages/trilium-core/src/services/import/single.spec.tsindex 8f05cb6ec2..62981444da 100644--- a/packages/trilium-core/src/services/import/single.spec.ts+++ b/packages/trilium-core/src/services/import/single.spec.ts@@ -13,8 +13,18 @@ import sql_init from "../sql_init.js";import single from "./single.js";import { encodeUtf8, stripBom } from "../utils/binary.js";import { getContext } from "../context.js";+import { mapByNoteType } from "../export/single.js";const scriptDir = dirname(fileURLToPath(import.meta.url));+/** A vector icon, as GitHub and many other sites serve — markup, so its content is a string. */+const TINY_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M0 0h16v16H0z"/></svg>`;++/** A 1x1 PNG. The bytes are asked what they are, so a placeholder buffer would rightly be refused. */+const PIXEL_PNG = Buffer.from(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC",+ "base64"+);+async function testImport(fileName: string, mimetype: string, bufferOverride?: Buffer, extraOptions?: Record<string, unknown>) {const buffer = bufferOverride ?? fs.readFileSync(`${scriptDir}/samples/${fileName}`);// getInstance caches by task id, so a caller needing distinct options (e.g. safeImport) must@@ -205,6 +215,47 @@ describe("processNoteContent", () => {expect(sheet.cellData[1][1].v).toBe(2);});+ it("carries a link preview's pictures through a single-file export and back", async () => {+ // A single-file export has nowhere to put an attachment, so it inlines every picture as base64+ // — which is only half an answer unless the import unpacks them again. Left inline they cost a+ // third more than the bytes they encode, in every revision of the note, once per card.+ //+ // The favicon is deliberately an SVG: its content is markup rather than bytes, and the export+ // used to skip it on exactly that basis, writing out `api/attachments/<id>` instead. That is+ // not merely unresolvable elsewhere — the id is the source instance's, so the file names an+ // attachment belonging to somebody else's note.+ const { note: source } = getContext().init(() => noteService.createNewNote({+ parentNoteId: "root", title: "Preview Source", type: "text", content: ""+ }));+ getContext().init(() => {+ const favicon = source.saveAttachment({ role: "favicon", mime: "image/svg+xml", title: "example.com.svg", content: TINY_SVG });+ const cover = source.saveAttachment({ role: "coverImage", mime: "image/png", title: "example.com-page", content: PIXEL_PNG });+ source.setContent(`<section class="link-embed" data-url="https://example.com/page" data-embed-type="opengraph"`+ + ` data-favicon="api/attachments/${favicon.attachmentId}/image/example.com.svg"`+ + ` data-image="api/attachments/${cover.attachmentId}/image/example.com-page"></section>`);+ });++ const exported = String(mapByNoteType(source, source.getContent(), "html").payload);+ // Both pictures travel in the file itself, naming nothing back in this instance.+ expect(exported).toContain("data-favicon=\"data:image/svg+xml;base64,");+ expect(exported).toContain("data-image=\"data:image/png;base64,");+ expect(exported).not.toContain("api/attachments");++ const { importedNote } = await testImport("Preview Source.html", "text/html", Buffer.from(exported));++ // Back to attachments on the far side, roled and named as a preview made here would store them.+ expect(importedNote.getAttachments().map((a) => [a.role, a.title]).sort()).toStrictEqual([+ ["coverImage", expect.stringMatching(/^example\.com-page-[0-9a-f]{8}\.png$/)],+ ["favicon", "example.com.svg"]+ ]);++ const content = importedNote.getContent().toString();+ expect(content).not.toContain("base64");+ for (const attachment of importedNote.getAttachments()) {+ expect(content).toContain(`api/attachments/${attachment.attachmentId}/image/`);+ }+ });+it("sanitizes rendered Markdown when safeImport is on", async () => {const md = `# Heading\n\n<img src=x onerror="alert(1)">`;const { importedNote } = await testImport("Unsafe.md", "text/markdown", Buffer.from(md), { safeImport: true });diff --git a/packages/trilium-core/src/services/import/single.ts b/packages/trilium-core/src/services/import/single.tsindex b7ff66d370..7a1c578d45 100644--- a/packages/trilium-core/src/services/import/single.ts+++ b/packages/trilium-core/src/services/import/single.ts@@ -19,7 +19,29 @@ const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.s// MIME of a `.csv` upload, as resolved by `mime-types`.const CSV_MIME = "text/csv";+/**+ * Imports one uploaded file as a note, then puts it through the same post-processing every other+ * importer runs (`zip.importZip` does it per created note).+ *+ * `createNewNote` deliberately does none of that itself, so without this step a single-file import+ * produced a note whose links were never scanned and whose pictures were never taken in hand — a+ * gap the single-file *export* makes plain, since it inlines every picture as base64 and this is+ * what unpacks them again.+ */async function importSingleFile(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {+ const note = await importSingleFileAs(taskContext, file, parentNote);++ // The types the pass acts on at all, checked here rather than left to it: reading the content is+ // what costs, and an uploaded video or disk image would be pulled into memory in full only to be+ // handed to a step that returns immediately on seeing what type it is.+ if (note.type === "text" || note.type === "relationMap") {+ await noteService.asyncPostProcessContent(note, note.getContent());+ }++ return note;+}++async function importSingleFileAs(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {const mime = mimeService.getMime(file.originalname) || file.mimetype;if (taskContext?.data?.textImportedAsText) {diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex f38af803d5..1e6a93dbd0 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -14,7 +14,7 @@ import * as cls from "./context.js";import entityChangesService from "./entity_changes.js";import eventService from "./events.js";import imageService from "./image.js";-import { downloadImages, downloadLinkPreviewPictures } from "./image_download.js";+import { downloadImages, storeLinkPreviewPictures } from "./image_download.js";import noteTypesService from "./note_types.js";import optionService from "./options.js";import revisionService from "./revisions.js";@@ -1222,7 +1222,7 @@ async function asyncPostProcessContent(note: BNote, content: string | Uint8ArrayscanForLinks(note, content);// Read from the note rather than from `content`: scanForLinks may just have rewritten it.- await downloadLinkPreviewPictures(note);+ await storeLinkPreviewPictures(note);}