Skip to content

Build your personal knowledge base with Trilium Notes

fix(images): keep the scans over note content linear in its length

Elian Doranb46f23ef8b39
diff --git a/packages/commons/src/lib/link_embed.spec.ts b/packages/commons/src/lib/link_embed.spec.ts
index 150016986a..aa9ff5c99b 100644
--- a/packages/commons/src/lib/link_embed.spec.ts
+++ b/packages/commons/src/lib/link_embed.spec.ts
@@ -124,7 +124,9 @@ describe("linkPreviewImageName", () => {
it("spells the site the same way its favicon does", () => {
// A favicon is titled by the bare hostname, so reducing the hostname here would put the
// two pictures of one site under two different-looking names in the same list.
- expect(linkPreviewImageName(wiki).startsWith("en.wikipedia.org")).toBe(true);
+ // Matched to where the hostname ends, not merely to where it starts: a bare `startsWith`
+ // says nothing about what follows, which is how a host check is normally got wrong.
+ expect(linkPreviewImageName(wiki)).toMatch(/^en\.wikipedia\.org-/);
expect(linkPreviewImageName("https://example.com/")).toMatch(/^example\.com-[0-9a-f]{8}$/);
});
diff --git a/packages/commons/src/lib/link_embed.ts b/packages/commons/src/lib/link_embed.ts
index c624288b1a..163565a744 100644
--- a/packages/commons/src/lib/link_embed.ts
+++ b/packages/commons/src/lib/link_embed.ts
@@ -141,9 +141,15 @@ export function linkPreviewImageName(url: string): string {
/** How much of the readable part to keep, so a long path does not crowd out the attachment list. */
const PREVIEW_NAME_MAX_READABLE = 60;
-/** Reduces a part of the address that is not already a file name — a path segment, or the lot. */
+/**
+ * Reduces a part of the address that is not already a file name — a path segment, or the lot.
+ *
+ * The trim matches one dash rather than a run of them, which is all there can be: the collapse just
+ * before it leaves no two dashes adjacent. A run would also be an address's to choose — this is
+ * handed whatever a link was pasted as — and `-+$` costs a scan from every position it starts at.
+ */
function toFileNamePart(value: string): string {
- return value.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "");
+ return value.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-|-$/g, "");
}
/** Bounds the readable part, and never lets it end on the punctuation a cut leaves behind. */
diff --git a/packages/trilium-core/src/services/image_download.spec.ts b/packages/trilium-core/src/services/image_download.spec.ts
index c980a10598..b94b780e8e 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 { downloadPictureToAttachment, storeLinkPreviewPictures } from "./image_download.js";
+import { downloadImages, downloadPictureToAttachment, storeLinkPreviewPictures } from "./image_download.js";
import noteService from "./notes.js";
import optionService from "./options.js";
import { initRequest } from "./request.js";
@@ -125,6 +125,25 @@ describe("downloadPictureToAttachment (real DB)", () => {
});
});
+describe("downloadImages (real DB)", () => {
+ it("reads a src past the attributes written before it, and knows an attachment's own", () => {
+ // The tag is bounded in how far it is read for a `src`, so what an editor actually writes
+ // before one — a class, a style, an alt — has to still be found past it.
+ const note = createNote("<p>x</p>");
+ const pasted = `<img class="image_resized" style="width:53.68%;" alt="a pasted picture"`
+ + ` src="data:image/png;base64,${PIXEL_PNG.toString("base64")}">`;
+ const stored = `<img src="api/attachments/abc123456789/image/kept.png">`;
+
+ const rewritten = getContext().init(() => downloadImages(note.noteId, `<p>${pasted}${stored}</p>`));
+
+ const [ attachment ] = note.getAttachments();
+ expect(rewritten).toContain(`<img src="api/attachments/${attachment.attachmentId}/image/`);
+ // A picture this note already holds is not a picture to go and fetch.
+ expect(rewritten).toContain(stored);
+ expect(asked).toEqual([]);
+ });
+});
+
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
diff --git a/packages/trilium-core/src/services/image_download.ts b/packages/trilium-core/src/services/image_download.ts
index a1fb66ad5f..0c510859e9 100644
--- a/packages/trilium-core/src/services/image_download.ts
+++ b/packages/trilium-core/src/services/image_download.ts
@@ -142,6 +142,17 @@ async function downloadImage(noteId: string, imageUrl: string) {
/** url => download promise */
const downloadImagePromises: Record<string, Promise<void>> = {};
+/**
+ * How far into an `<img>` tag to look for its `src`.
+ *
+ * Bounded because the content is whatever was pasted or imported, and an unbounded look costs a
+ * scan from every `<img` in it — text that is nothing but `<img<img<img…` takes time in the square
+ * of its length. What the bound gives up is a picture whose tag carries several KB of other
+ * attributes before its `src`, which is not a tag anything writes: the bytes that make a tag long
+ * are the picture's own, and those are in the `src` this is looking for.
+ */
+const MAX_ATTRIBUTES_BEFORE_SRC = 4096;
+
function replaceUrl(content: string, url: string, attachment: { attachmentId?: string; title: string }) {
const quotedUrl = quoteRegex(url);
@@ -149,7 +160,7 @@ function replaceUrl(content: string, url: string, attachment: { attachmentId?: s
}
export function downloadImages(noteId: string, content: string) {
- const imageRe = /<img[^>]*?\ssrc=['"]([^'">]+)['"]/gi;
+ const imageRe = new RegExp(`<img[^>]{0,${MAX_ATTRIBUTES_BEFORE_SRC}}?\\ssrc=['"]([^'">]+)['"]`, "gi");
let imageMatch;
while ((imageMatch = imageRe.exec(content))) {
@@ -167,7 +178,10 @@ export function downloadImages(noteId: string, content: string) {
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) &&
+ // The id between the two is one path segment, so it is matched as one. Written `.+` it
+ // could stand for any part of any URL, which costs a scan back from every `/image` for
+ // an address that turns out not to be an attachment's.
+ !/api\/attachments\/[^/]+\/image/.test(url) &&
// this is an exception for the web clipper's "imageId"
(url.length !== 20 || url.toLowerCase().startsWith("http"))
) {