Skip to content

Build your personal knowledge base with Trilium Notes

feat(notion import): fetch the pictures a bookmark card names but does not carry

Elian Doranbf3842b6b8ba
diff --git a/packages/trilium-core/src/services/image_download.spec.ts b/packages/trilium-core/src/services/image_download.spec.ts
new file mode 100644
index 0000000000..bc622ebefe
--- /dev/null
+++ b/packages/trilium-core/src/services/image_download.spec.ts
@@ -0,0 +1,202 @@
+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 noteService from "./notes.js";
+import optionService from "./options.js";
+import { initRequest } from "./request.js";
+
+/**
+ * Runs against the real in-memory fixture DB booted by the server suite setup, through which
+ * co-located trilium-core specs run. The network is the only thing stood in for.
+ */
+
+let counter = 0;
+
+/** Creates a fresh text note under root, uniquely titled since the fixture DB is shared. */
+function createNote(content: string): BNote {
+ counter++;
+
+ return getContext().init(() =>
+ noteService.createNewNote({
+ parentNoteId: "root",
+ title: `image-download-spec-${counter}`,
+ content,
+ type: "text"
+ })
+ ).note;
+}
+
+/** 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"
+);
+
+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>`;
+
+/**
+ * Stands in for the network. The suite boots no request provider, so one is installed here and
+ * taken away again — leaving a stub in place would answer for whatever else shares this worker.
+ */
+let asked: string[] = [];
+let answerWith: (url: string) => Buffer | undefined = () => PIXEL_PNG;
+
+beforeAll(() => {
+ initRequest({
+ exec: async () => { throw new Error("Not used by these tests."); },
+ getImage: async (url: string) => {
+ asked.push(url);
+ const bytes = answerWith(url);
+
+ if (!bytes) {
+ throw new Error(`404 ${url}`);
+ }
+
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
+ }
+ });
+});
+
+afterAll(() => {
+ initRequest({
+ exec: async () => { throw new Error("Request provider not initialized. Call initRequest() first."); },
+ getImage: async () => { throw new Error("Request provider not initialized. Call initRequest() first."); }
+ });
+});
+
+beforeEach(() => {
+ asked = [];
+ answerWith = () => PIXEL_PNG;
+});
+
+describe("downloadPictureToAttachment (real DB)", () => {
+ it("keeps the picture as an attachment under the role and title it is given", async () => {
+ const note = createNote("<p>x</p>");
+
+ const reference = await getContext().init(() => downloadPictureToAttachment(note.noteId, "https://example.com/icon.png", {
+ role: "favicon",
+ title: "example.com"
+ }));
+
+ const [ attachment ] = note.getAttachments();
+ // The extension comes from what the bytes are, not from the address they came from.
+ expect(attachment).toMatchObject({ role: "favicon", title: "example.com.png" });
+ expect(reference).toBe(`api/attachments/${attachment.attachmentId}/image/example.com.png`);
+ });
+
+ it("asks for nothing at an address that is not a website", async () => {
+ // The address reaches this from note content, so it is whatever was written there.
+ const note = createNote("<p>x</p>");
+
+ for (const address of [ "file:///etc/passwd", "data:image/png;base64,AAAA", "api/attachments/a/image/b.png", "" ]) {
+ expect(await getContext().init(() => downloadPictureToAttachment(note.noteId, address, { role: "image", title: "x" }))).toBeUndefined();
+ }
+
+ expect(asked).toEqual([]);
+ });
+
+ it("refuses what comes back if it is not a picture", async () => {
+ // A 404 page served where a picture should be is the ordinary case.
+ const note = createNote("<p>x</p>");
+ answerWith = () => Buffer.from("<html>Not found</html>");
+
+ expect(await getContext().init(() => downloadPictureToAttachment(note.noteId, "https://example.com/gone.png", {
+ role: "image",
+ title: "x"
+ }))).toBeUndefined();
+ expect(note.getAttachments()).toHaveLength(0);
+ });
+
+ it("answers with nothing when the address cannot be reached", async () => {
+ const note = createNote("<p>x</p>");
+ answerWith = () => undefined;
+
+ expect(await getContext().init(() => downloadPictureToAttachment(note.noteId, "https://example.com/x.png", {
+ role: "image",
+ title: "x"
+ }))).toBeUndefined();
+ });
+});
+
+describe("downloadLinkPreviewPictures (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));
+
+ expect(asked).toEqual([ "https://example.com/favicon.png", "https://cdn.example.com/cover.png" ]);
+
+ // Roled and named exactly as a preview fetched here would be.
+ 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.png" ]
+ ]);
+
+ const content = String(note.getContent());
+ expect(content).not.toContain("https://example.com/favicon.png");
+ expect(content).not.toContain("https://cdn.example.com/cover.png");
+ for (const attachment of attachments) {
+ expect(content).toContain(`api/attachments/${attachment.attachmentId}/image/`);
+ }
+ });
+
+ it("keeps one icon for a site named by more than one card", async () => {
+ const note = createNote(
+ card("https://example.com/a", "https://example.com/favicon.png")
+ + card("https://example.com/b", "https://example.com/favicon.png")
+ );
+
+ await getContext().init(() => downloadLinkPreviewPictures(note));
+
+ expect(note.getAttachments().map((a) => a.title)).toStrictEqual([ "example.com.png" ]);
+ });
+
+ it("asks for nothing when the setting says not to", async () => {
+ // The same setting that decides whether a remote <img> in note content is fetched.
+ const note = createNote(card("https://example.com/page", "https://example.com/favicon.png"));
+ const previously = optionService.getOptionBool("downloadImagesAutomatically");
+ getContext().init(() => optionService.setOption("downloadImagesAutomatically", "false"));
+
+ try {
+ await getContext().init(() => downloadLinkPreviewPictures(note));
+ } finally {
+ getContext().init(() => optionService.setOption("downloadImagesAutomatically", String(previously)));
+ }
+
+ expect(asked).toEqual([]);
+ expect(note.getAttachments()).toHaveLength(0);
+ // Left as it was: nothing was fetched, so nothing is rewritten.
+ 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.
+ 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")
+ );
+
+ await getContext().init(() => downloadLinkPreviewPictures(note));
+
+ expect(asked).toEqual([]);
+ });
+
+ it("drops nothing and keeps going when a picture cannot be had", async () => {
+ // One address answers, the other does not: the card that can be completed is, and the one
+ // that cannot keeps what it had rather than the note failing to save.
+ 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));
+
+ 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.ts
new file mode 100644
index 0000000000..c55315699a
--- /dev/null
+++ b/packages/trilium-core/src/services/image_download.ts
@@ -0,0 +1,320 @@
+/**
+ * Fetching the pictures a note's content names at a third party, and keeping them as its own.
+ *
+ * Note content arrives from places that reference pictures by URL rather than carrying them: a page
+ * pasted from a browser, a clipping, an export from another app. Left alone those references keep
+ * the note dependent on someone else's server — every reader fetches from it, and the picture
+ * disappears the day the URL rots. So the bytes are fetched once, stored as attachments of the note,
+ * and the references rewritten to point at them.
+ *
+ * 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.
+ */
+
+import { type ImageAttachmentRole, imageExtensionForMime, isHttpUrl, linkPreviewImageName, safeHostname } from "@triliumnext/commons";
+import url from "url";
+
+import becca from "../becca/becca.js";
+import type BNote from "../becca/entities/bnote.js";
+import * as cls from "./context.js";
+import imageService from "./image.js";
+import { inspectImage, UNKNOWN_FORMAT } from "./image_inspect.js";
+import { getLog } from "./log.js";
+import noteService from "./notes.js";
+import optionService from "./options.js";
+import request from "./request.js";
+import { getSql } from "./sql/index.js";
+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)}`;
+}
+
+/**
+ * Fetches one picture and keeps it as an attachment of `noteId`, answering with the URL that
+ * references it — or nothing when it could not be had, or is not a picture at all.
+ *
+ * The step both passes below share, and the one worth reaching for from anywhere else that finds a
+ * picture named by an address: an importer, a clipper, a repair that fills in what a preview is
+ * missing. The bytes are asked what they are rather than the address or its server being taken for
+ * it, so a 404 page served where a picture should be is refused rather than stored.
+ *
+ * `title` is what the attachment is called, and for a role that deduplicates it is also the key a
+ * second use of the same picture reuses it by — so it should say which thing this is rather than
+ * describe it.
+ */
+export async function downloadPictureToAttachment(
+ noteId: string,
+ pictureUrl: string,
+ { role, title, shrink = false }: { role: ImageAttachmentRole; title: string; shrink?: boolean }
+): Promise<string | undefined> {
+ if (!isHttpUrl(pictureUrl)) {
+ return undefined;
+ }
+
+ 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;
+ } 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.
+ getLog().info(`Could not download a picture for note '${noteId}': ${e}`);
+ return undefined;
+ }
+}
+
+const imageUrlToAttachmentIdMapping: Record<string, string> = {};
+
+async function downloadImage(noteId: string, imageUrl: string) {
+ const unescapedUrl = unescapeHtml(imageUrl);
+
+ // SSRF protection: only allow http(s) URLs and block file:// and other schemes.
+ try {
+ const parsed = new URL(unescapedUrl);
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
+ getLog().error(`Download of '${imageUrl}' for note '${noteId}' rejected: only http/https URLs are allowed.`);
+ return;
+ }
+ } catch {
+ getLog().error(`Download of '${imageUrl}' for note '${noteId}' rejected: invalid URL.`);
+ return;
+ }
+
+ try {
+ const imageBuffer = new Uint8Array(await request.getImage(unescapedUrl));
+
+ const parsedUrl = url.parse(unescapedUrl);
+ const title = basename(parsedUrl.pathname || "");
+
+ const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, title, true, true);
+
+ if (attachment.attachmentId) {
+ imageUrlToAttachmentIdMapping[imageUrl] = attachment.attachmentId;
+ } else {
+ getLog().error(`Download of '${imageUrl}' for note '${noteId}' failed due to no attachment ID.`);
+ }
+
+ getLog().info(`Download of '${imageUrl}' succeeded and was saved as image attachment '${attachment.attachmentId}' of note '${noteId}'`);
+ } catch (e: any) {
+ getLog().error(`Download of '${imageUrl}' for note '${noteId}' failed with error: ${e.message} ${e.stack}`);
+ }
+}
+
+/** url => download promise */
+const downloadImagePromises: Record<string, Promise<void>> = {};
+
+function replaceUrl(content: string, url: string, attachment: { attachmentId?: string; title: string }) {
+ const quotedUrl = quoteRegex(url);
+
+ return content.replace(new RegExp(`\\s+src=[\"']${quotedUrl}[\"']`, "ig"), ` src="api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}"`);
+}
+
+export function downloadImages(noteId: string, content: string) {
+ const imageRe = /<img[^>]*?\ssrc=['"]([^'">]+)['"]/gi;
+ let imageMatch;
+
+ while ((imageMatch = imageRe.exec(content))) {
+ const url = imageMatch[1];
+ const inlineImageMatch = /^data:image\/[a-z]+;base64,/.exec(url);
+
+ if (inlineImageMatch) {
+ const imageBase64 = url.substring(inlineImageMatch[0].length);
+ const imageBuffer = decodeBase64(imageBase64);
+
+ const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, "inline image", true, true);
+
+ const encodedTitle = encodeURIComponent(attachment.title);
+
+ content = `${content.substring(0, imageMatch.index)}<img src="api/attachments/${attachment.attachmentId}/image/${encodedTitle}"${content.substring(imageMatch.index + imageMatch[0].length)}`;
+ } else if (
+ !url.includes("api/images/") &&
+ !/api\/attachments\/.+\/image\/?.*/.test(url) &&
+ // this is an exception for the web clipper's "imageId"
+ (url.length !== 20 || url.toLowerCase().startsWith("http"))
+ ) {
+ if (!optionService.getOptionBool("downloadImagesAutomatically")) {
+ continue;
+ }
+
+ if (url in imageUrlToAttachmentIdMapping) {
+ const attachment = becca.getAttachment(imageUrlToAttachmentIdMapping[url]);
+
+ if (!attachment) {
+ delete imageUrlToAttachmentIdMapping[url];
+ } else {
+ content = replaceUrl(content, url, attachment);
+ continue;
+ }
+ }
+
+ if (url in downloadImagePromises) {
+ // download is already in progress
+ continue;
+ }
+
+ // this is done asynchronously, it would be too slow to wait for the download
+ // given that save can be triggered very often
+ downloadImagePromises[url] = downloadImage(noteId, url);
+ }
+ }
+
+ Promise.all(Object.values(downloadImagePromises)).then(() => {
+ setTimeout(() => {
+ // the normal expected flow of the offline image saving is that users will paste the image(s)
+ // which will get asynchronously downloaded, during that time they keep editing the note
+ // once the download is finished, the image note representing the downloaded image will be used
+ // to replace the IMG link.
+ // However, there's another flow where the user pastes the image and leaves the note before the images
+ // are downloaded and the IMG references are not updated. For this occasion we have this code
+ // which upon the download of all the images will update the note if the links have not been fixed before
+
+ cls.getContext().init(() => {
+ getSql().transactional(() => {
+ const imageNotes = becca.getNotes(Object.values(imageUrlToAttachmentIdMapping), true);
+ const log = getLog();
+
+ const origNote = becca.getNote(noteId);
+
+ if (!origNote) {
+ log.error(`Cannot find note '${noteId}' to replace image link.`);
+ return;
+ }
+
+ const origContent = origNote.getContent();
+ let updatedContent = origContent;
+
+ if (typeof updatedContent !== "string") {
+ log.error(`Note '${noteId}' has a non-string content, cannot replace image link.`);
+ return;
+ }
+
+ for (const url in imageUrlToAttachmentIdMapping) {
+ const imageNote = imageNotes.find((note) => note.noteId === imageUrlToAttachmentIdMapping[url]);
+
+ if (imageNote) {
+ updatedContent = replaceUrl(updatedContent, url, imageNote);
+ }
+ }
+
+ // update only if the links have not been already fixed.
+ if (updatedContent !== origContent) {
+ origNote.setContent(updatedContent);
+
+ void noteService.asyncPostProcessContent(origNote, updatedContent);
+
+ console.log(`Fixed the image links for note '${noteId}' to the offline saved.`);
+ }
+ });
+ });
+ }, 5000);
+ });
+
+ return content;
+}
+
+/** Which of a link preview's picture attributes holds what, and under which role it is stored. */
+const PREVIEW_PICTURE_ROLES = [
+ [ "data-favicon", "favicon" ],
+ [ "data-image", "coverImage" ]
+] as const;
+
+/** The opening tag of a link preview, block or inline. Its attributes are read and rewritten in place. */
+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.
+ *
+ * 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.
+ *
+ * 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.
+ */
+export async function downloadLinkPreviewPictures(note: BNote) {
+ if (note.type !== "text" || !optionService.getOptionBool("downloadImagesAutomatically")) {
+ return;
+ }
+
+ const content = note.getContent();
+
+ // Cheap guard: parse nothing for the overwhelming majority of notes, which hold no preview.
+ if (typeof content !== "string" || !content.includes("link-embed") && !content.includes("link-mention")) {
+ return;
+ }
+
+ const tags = [ ...content.matchAll(PREVIEW_TAG_REGEX) ];
+ let rewritten = "";
+ let cursor = 0;
+
+ for (const tag of tags) {
+ rewritten += content.slice(cursor, tag.index) + await downloadPicturesOf(note.noteId, tag[0]);
+ cursor = tag.index + tag[0].length;
+ }
+
+ rewritten += content.slice(cursor);
+
+ if (rewritten !== content) {
+ getSql().transactional(() => note.setContent(rewritten));
+ }
+}
+
+/** 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> {
+ 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))) {
+ continue;
+ }
+
+ // 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"
+ });
+
+ if (reference) {
+ rewritten = rewritten.replace(`${attribute}="${stored}"`, `${attribute}="${reference}"`);
+ }
+ }
+
+ return rewritten;
+}
+
+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.integration.spec.ts b/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts
index 4fb321ada8..2478eb5ed0 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
@@ -5,9 +5,16 @@ import { describe, expect, it } from "vitest";
import becca from "../../../becca/becca.js";
import type BNote from "../../../becca/entities/bnote.js";
import { getContext } from "../../context.js";
+import { initRequest } from "../../request.js";
import TaskContext from "../../task_context.js";
import notionImporter from "./importer.js";
+/** 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"
+);
+
/** Builds an in-memory zip from a map of entry name -> contents. */
async function createZipBuffer(files: Record<string, string | Buffer>): Promise<Buffer> {
const archive = new ZipArchive();
@@ -1067,6 +1074,52 @@ describe("Notion importer — integration", () => {
expect(container?.getChildNotes().map((note) => note.title)).toEqual(["Row"]);
});
+ it("fetches a bookmark card's icon and cover, which the export names but does not carry", async () => {
+ // The whole of a Notion bookmark: an <a class="bookmark source"> whose pictures are the
+ // origin's own addresses. The export ships no bytes for them, so unless they are fetched
+ // the card renders with placeholders — the render sinks refuse a remote address outright.
+ const bookmark = `<figure id="3b1c5eca-1b8b-8099-be42-da0f9203f06f">`
+ + `<a href="https://example.com/page" class="bookmark source"><div class="bookmark-info">`
+ + `<div class="bookmark-text"><div class="bookmark-title">A page</div>`
+ + `<div class="bookmark-description">About the page.</div></div>`
+ + `<div class="bookmark-href"><img src="https://example.com/favicon.png" class="icon bookmark-icon"/>`
+ + `https://example.com/page</div></div>`
+ + `<img src="https://cdn.example.com/cover.png" class="bookmark-image"/></a></figure>`;
+
+ const asked: string[] = [];
+ initRequest({
+ exec: async () => { throw new Error("Not used by this test."); },
+ getImage: async (address: string) => {
+ asked.push(address);
+ return PIXEL_PNG.buffer.slice(PIXEL_PNG.byteOffset, PIXEL_PNG.byteOffset + PIXEL_PNG.byteLength) as ArrayBuffer;
+ }
+ });
+
+ try {
+ const importRoot = await importNotion({
+ "Links 386c5eca1b8b80439520cad27a0d2749.html":
+ `<html><head><title>Links</title></head><body>`
+ + `<div id="386c5eca1b8b80439520cad27a0d2749" class="page"><div class="page-body">${bookmark}</div></div>`
+ + `</body></html>`
+ });
+
+ const note = importRoot.getChildNotes().find((child) => child.title === "Links") ?? importRoot;
+ expect(asked).toEqual([ "https://example.com/favicon.png", "https://cdn.example.com/cover.png" ]);
+
+ expect(note.getAttachments().map((a) => a.role).sort()).toStrictEqual([ "coverImage", "favicon" ]);
+
+ const content = String(note.getContent());
+ expect(content).not.toContain("https://example.com/favicon.png");
+ expect(content).not.toContain("https://cdn.example.com/cover.png");
+ expect(content).toContain("api/attachments/");
+ } finally {
+ initRequest({
+ exec: async () => { throw new Error("Request provider not initialized. Call initRequest() first."); },
+ getImage: async () => { throw new Error("Request provider not initialized. Call initRequest() first."); }
+ });
+ }
+ });
+
it("synthesizes a container named after a CSV that carries no Notion id", async () => {
// A CSV with no id at all keeps its (non-empty) filename as the container title and an empty id.
const importRoot = await importNotion({
diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.ts
index 02d542b579..3c5f8faa0e 100644
--- a/packages/trilium-core/src/services/import/notion/importer.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.ts
@@ -20,6 +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 noteService from "../../notes.js";
import protectedSessionService from "../../protected_session.js";
import { sanitizeHtml } from "../../sanitizer.js";
@@ -63,7 +64,25 @@ async function importNotion(taskContext: TaskContext<"importNotes">, source: Zip
reconcileDateColumns(pages);
taskContext.setTotalCount(pages.length);
- return createNotes(importRootNote, pages, resources, taskContext, csvColumnsByFolder);
+ const rootNote = createNotes(importRootNote, pages, resources, taskContext, csvColumnsByFolder);
+
+ // A Notion export ships no bytes for a bookmark card's icon or cover — only the origin's
+ // 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);
+ }
+
+ return rootNote;
+}
+
+/** Every note the import produced, the root included. */
+function* createdNotes(rootNote: BNote): Generator<{ note: BNote }> {
+ yield { note: rootNote };
+
+ for (const child of rootNote.getChildNotes()) {
+ yield* createdNotes(child);
+ }
}
/**
diff --git a/packages/trilium-core/src/services/notes.spec.ts b/packages/trilium-core/src/services/notes.spec.ts
index 0025493247..c053af830a 100644
--- a/packages/trilium-core/src/services/notes.spec.ts
+++ b/packages/trilium-core/src/services/notes.spec.ts
@@ -7,6 +7,7 @@ import { disableEntityEvents, getContext } from "./context.js";
import { getLog } from "./log.js";
import noteService, { prepareTitle, saveLinks } from "./notes.js";
import optionService from "./options.js";
+import { initRequest } from "./request.js";
import { getSql } from "./sql/index.js";
/**
@@ -392,6 +393,35 @@ describe("notes service (real DB)", () => {
});
});
+ describe("asyncPostProcessContent", () => {
+ it("sets the link preview picture download going", async () => {
+ // The pass itself is covered in image_download.spec.ts. What matters here is the wiring:
+ // saving content is the only thing that starts it.
+ const asked: string[] = [];
+ initRequest({
+ exec: async () => { throw new Error("Not used by this test."); },
+ getImage: async (address: string) => {
+ asked.push(address);
+ const png = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC",
+ "base64"
+ );
+ return png.buffer.slice(png.byteOffset, png.byteOffset + png.byteLength) as ArrayBuffer;
+ }
+ });
+
+ const { note } = createNote("root", {
+ title: "spec-preview-wiring",
+ content: `<section class="link-embed" data-url="https://example.com/p" data-favicon="https://example.com/f.png"></section>`
+ });
+
+ await getContext().init(() => noteService.asyncPostProcessContent(note, note.getContent()));
+
+ expect(asked).toEqual([ "https://example.com/f.png" ]);
+ expect(note.getAttachments().map((a) => a.role)).toStrictEqual([ "favicon" ]);
+ });
+ });
+
describe("updateNoteData", () => {
it("persists new content and extracts link relations", () => {
const target = createNote("root", { title: "spec-update-target" });
diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.ts
index 0f39e7a023..f38af803d5 100644
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@ -1,7 +1,6 @@
import { type AttachmentRow, attachmentRoleTraits, type AttributeRow, type BranchRow, dayjs, isEmbeddedAttachmentRole, isImageAttachmentRole, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType } from "@triliumnext/commons";
import { t } from "i18next";
import { parse as parseHtml } from "node-html-parser";
-import url from "url";
import becca from "../becca/becca.js";
import BAttachment from "../becca/entities/battachment.js";
@@ -15,9 +14,9 @@ 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 noteTypesService from "./note_types.js";
import optionService from "./options.js";
-import request from "./request.js";
import revisionService from "./revisions.js";
import { evaluateTemplateSafe } from "./safe_template.js";
import { sanitizeHtml } from "./sanitizer.js";
@@ -25,8 +24,7 @@ import { getSql } from "./sql/index.js";
import type TaskContext from "./task_context.js";
import { decodeBase64 } from "./utils/binary.js";
import date_utils from "./utils/date.js";
-import { newEntityId, quoteRegex, replaceAll, toMap, unescapeHtml } from "./utils/index.js";
-import { basename } from "./utils/path.js";
+import { newEntityId, replaceAll, toMap, unescapeHtml } from "./utils/index.js";
import ws from "./ws.js";
interface FoundLink {
@@ -813,154 +811,6 @@ function findRelationMapLinks(content: string, foundLinks: FoundLink[]) {
}
}
-const imageUrlToAttachmentIdMapping: Record<string, string> = {};
-
-async function downloadImage(noteId: string, imageUrl: string) {
- const unescapedUrl = unescapeHtml(imageUrl);
-
- // SSRF protection: only allow http(s) URLs and block file:// and other schemes.
- try {
- const parsed = new URL(unescapedUrl);
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
- getLog().error(`Download of '${imageUrl}' for note '${noteId}' rejected: only http/https URLs are allowed.`);
- return;
- }
- } catch {
- getLog().error(`Download of '${imageUrl}' for note '${noteId}' rejected: invalid URL.`);
- return;
- }
-
- try {
- const imageBuffer = new Uint8Array(await request.getImage(unescapedUrl));
-
- const parsedUrl = url.parse(unescapedUrl);
- const title = basename(parsedUrl.pathname || "");
-
- const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, title, true, true);
-
- if (attachment.attachmentId) {
- imageUrlToAttachmentIdMapping[imageUrl] = attachment.attachmentId;
- } else {
- getLog().error(`Download of '${imageUrl}' for note '${noteId}' failed due to no attachment ID.`);
- }
-
- getLog().info(`Download of '${imageUrl}' succeeded and was saved as image attachment '${attachment.attachmentId}' of note '${noteId}'`);
- } catch (e: any) {
- getLog().error(`Download of '${imageUrl}' for note '${noteId}' failed with error: ${e.message} ${e.stack}`);
- }
-}
-
-/** url => download promise */
-const downloadImagePromises: Record<string, Promise<void>> = {};
-
-function replaceUrl(content: string, url: string, attachment: Attachment) {
- const quotedUrl = quoteRegex(url);
-
- return content.replace(new RegExp(`\\s+src=[\"']${quotedUrl}[\"']`, "ig"), ` src="api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}"`);
-}
-
-function downloadImages(noteId: string, content: string) {
- const imageRe = /<img[^>]*?\ssrc=['"]([^'">]+)['"]/gi;
- let imageMatch;
-
- while ((imageMatch = imageRe.exec(content))) {
- const url = imageMatch[1];
- const inlineImageMatch = /^data:image\/[a-z]+;base64,/.exec(url);
-
- if (inlineImageMatch) {
- const imageBase64 = url.substring(inlineImageMatch[0].length);
- const imageBuffer = decodeBase64(imageBase64);
-
- const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, "inline image", true, true);
-
- const encodedTitle = encodeURIComponent(attachment.title);
-
- content = `${content.substring(0, imageMatch.index)}<img src="api/attachments/${attachment.attachmentId}/image/${encodedTitle}"${content.substring(imageMatch.index + imageMatch[0].length)}`;
- } else if (
- !url.includes("api/images/") &&
- !/api\/attachments\/.+\/image\/?.*/.test(url) &&
- // this is an exception for the web clipper's "imageId"
- (url.length !== 20 || url.toLowerCase().startsWith("http"))
- ) {
- if (!optionService.getOptionBool("downloadImagesAutomatically")) {
- continue;
- }
-
- if (url in imageUrlToAttachmentIdMapping) {
- const attachment = becca.getAttachment(imageUrlToAttachmentIdMapping[url]);
-
- if (!attachment) {
- delete imageUrlToAttachmentIdMapping[url];
- } else {
- content = replaceUrl(content, url, attachment);
- continue;
- }
- }
-
- if (url in downloadImagePromises) {
- // download is already in progress
- continue;
- }
-
- // this is done asynchronously, it would be too slow to wait for the download
- // given that save can be triggered very often
- downloadImagePromises[url] = downloadImage(noteId, url);
- }
- }
-
- Promise.all(Object.values(downloadImagePromises)).then(() => {
- setTimeout(() => {
- // the normal expected flow of the offline image saving is that users will paste the image(s)
- // which will get asynchronously downloaded, during that time they keep editing the note
- // once the download is finished, the image note representing the downloaded image will be used
- // to replace the IMG link.
- // However, there's another flow where the user pastes the image and leaves the note before the images
- // are downloaded and the IMG references are not updated. For this occasion we have this code
- // which upon the download of all the images will update the note if the links have not been fixed before
-
- cls.getContext().init(() => {
- getSql().transactional(() => {
- const imageNotes = becca.getNotes(Object.values(imageUrlToAttachmentIdMapping), true);
- const log = getLog();
-
- const origNote = becca.getNote(noteId);
-
- if (!origNote) {
- log.error(`Cannot find note '${noteId}' to replace image link.`);
- return;
- }
-
- const origContent = origNote.getContent();
- let updatedContent = origContent;
-
- if (typeof updatedContent !== "string") {
- log.error(`Note '${noteId}' has a non-string content, cannot replace image link.`);
- return;
- }
-
- for (const url in imageUrlToAttachmentIdMapping) {
- const imageNote = imageNotes.find((note) => note.noteId === imageUrlToAttachmentIdMapping[url]);
-
- if (imageNote) {
- updatedContent = replaceUrl(updatedContent, url, imageNote);
- }
- }
-
- // update only if the links have not been already fixed.
- if (updatedContent !== origContent) {
- origNote.setContent(updatedContent);
-
- asyncPostProcessContent(origNote, updatedContent);
-
- console.log(`Fixed the image links for note '${noteId}' to the offline saved.`);
- }
- });
- });
- }, 5000);
- });
-
- return content;
-}
/**
* Derives a plain-text attachment title from the inner HTML of an inline
@@ -1371,8 +1221,11 @@ async function asyncPostProcessContent(note: BNote, content: string | Uint8Array
}
scanForLinks(note, content);
+ // Read from the note rather than from `content`: scanForLinks may just have rewritten it.
+ await downloadLinkPreviewPictures(note);
}
+
// all keys should be replaced by the corresponding values
function replaceByMap(str: string, mapObj: Record<string, string>) {
if (!mapObj) {