Skip to content

Build your personal knowledge base with Trilium Notes

feat(link previews): keep one favicon per site, and rewrite every reference to a copied attachment

Elian Doran661f67f27611
diff --git a/apps/client/src/services/image_upload.spec.ts b/apps/client/src/services/image_upload.spec.ts
index 7b36ab8bf0..bbce585539 100644
--- a/apps/client/src/services/image_upload.spec.ts
+++ b/apps/client/src/services/image_upload.spec.ts
@@ -64,6 +64,17 @@ describe("uploadImageAttachment", () => {
expect(serverUpload).toHaveBeenCalledWith("notes/note1/attachments/upload?role=favicon", expect.any(File), undefined, "POST");
});
+ it("names the upload after the base name it was given, keeping the data URL's extension", async () => {
+ // For a deduplicated role the name is the key an existing attachment is reused by, so it
+ // has to reach the server intact.
+ serverUpload.mockResolvedValue({ uploaded: true, url: "api/attachments/new1/image/example.com.png" });
+
+ await uploadImageAttachment("note1", "data:image/png;base64,QUJD", "favicon", "example.com");
+
+ const [ , uploaded ] = serverUpload.mock.calls[0] as [string, File];
+ expect(uploaded.name).toBe("example.com.png");
+ });
+
it("returns null when the server reports the upload did not succeed", async () => {
serverUpload.mockResolvedValue({ uploaded: false });
expect(await uploadImageAttachment("note1", "data:image/png;base64,QUJD")).toBeNull();
diff --git a/apps/client/src/services/image_upload.ts b/apps/client/src/services/image_upload.ts
index 4080ef8091..e646262ba3 100644
--- a/apps/client/src/services/image_upload.ts
+++ b/apps/client/src/services/image_upload.ts
@@ -15,9 +15,18 @@ import server from "./server.js";
* caller passes something else only for a picture the app fetched on its behalf, such as a link
* preview's site icon; see {@link IMAGE_ATTACHMENT_ROLES}. The server checks the value against the
* same list rather than storing whatever it is sent.
+ *
+ * `baseName` names the attachment. For a role that deduplicates it is also the key the note reuses
+ * an existing attachment by, so it has to say which thing this is — a site's hostname for a
+ * favicon — rather than describe it.
*/
-export async function uploadImageAttachment(noteId: string, dataUrl: string, role: ImageAttachmentRole = "image"): Promise<string | null> {
- const file = dataUrlToImageFile(dataUrl);
+export async function uploadImageAttachment(
+ noteId: string,
+ dataUrl: string,
+ role: ImageAttachmentRole = "image",
+ baseName = "image"
+): Promise<string | null> {
+ const file = dataUrlToImageFile(dataUrl, baseName);
if (!file) return null;
try {
@@ -30,8 +39,11 @@ export async function uploadImageAttachment(noteId: string, dataUrl: string, rol
}
}
-/** Decodes a `data:<mime>;base64,<data>` URL into a {@link File} suitable for upload. */
-export function dataUrlToImageFile(dataUrl: string): File | null {
+/**
+ * Decodes a `data:<mime>;base64,<data>` URL into a {@link File} suitable for upload, named
+ * `<baseName>.<ext>` — the extension coming from the data URL's own media type.
+ */
+export function dataUrlToImageFile(dataUrl: string, baseName = "image"): File | null {
const parsed = parseImageDataUrl(dataUrl);
if (!parsed) return null;
@@ -45,7 +57,7 @@ export function dataUrlToImageFile(dataUrl: string): File | null {
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
- return new File([ bytes ], `image.${parsed.ext}`, { type: parsed.mime });
+ return new File([ bytes ], `${baseName}.${parsed.ext}`, { type: parsed.mime });
}
export interface ParsedImageDataUrl {
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.ts
index 2c4c9eddb5..7323294a5b 100644
--- a/apps/client/src/services/link_embed.spec.ts
+++ b/apps/client/src/services/link_embed.spec.ts
@@ -136,8 +136,10 @@ describe("fetchMetadata", () => {
// with the note's own images, while the favicon is the site's mark, fetched rather than
// chosen — which is what lets icons be deduplicated and kept out of the tools that
// reason about the user's own pictures.
- expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/x-icon;base64,FAV", "favicon");
- expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/jpeg;base64,IMG", "image");
+ // The favicon is named by its site, which is the key the note reuses one by: a note
+ // linking the same site many times keeps one icon rather than one per link.
+ expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/x-icon;base64,FAV", "favicon", "example.com");
+ expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/jpeg;base64,IMG", "image", undefined);
// Only the attachment URLs land in the note content — inlined base64 counts against the
// auto-read-only size threshold, and a favicon pays that cost once per link rather than
// once per note.
diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsx
index 92e9e3a8bf..92a7f568b2 100644
--- a/apps/client/src/services/link_embed.tsx
+++ b/apps/client/src/services/link_embed.tsx
@@ -49,8 +49,10 @@ export async function fetchMetadata(url: string, ownerNoteId?: string): Promise<
const metadata = await server.post<LinkEmbedMetadata>("link-embed/metadata", { url });
// Uploaded together: they are two independent requests and a preview needs both before it
// can be stored.
+ // The favicon is named by its site, which is what lets a note that links the same site many
+ // times keep one icon rather than one per link.
const [ favicon, image ] = await Promise.all([
- offloadPictureToAttachment(metadata.favicon, ownerNoteId, "favicon"),
+ offloadPictureToAttachment(metadata.favicon, ownerNoteId, "favicon", safeHostname(metadata.url)),
offloadPictureToAttachment(metadata.image, ownerNoteId)
]);
@@ -90,13 +92,14 @@ export async function fetchMetadata(url: string, ownerNoteId?: string): Promise<
async function offloadPictureToAttachment(
picture: string | undefined,
ownerNoteId: string | undefined,
- role: ImageAttachmentRole = "image"
+ role: ImageAttachmentRole = "image",
+ baseName?: string
): Promise<string | undefined> {
if (!picture || !ownerNoteId || !picture.startsWith("data:")) {
return picture;
}
- return await uploadImageAttachment(ownerNoteId, picture, role) ?? picture;
+ return await uploadImageAttachment(ownerNoteId, picture, role, baseName) ?? picture;
}
// ---------------------------------------------------------------------------
diff --git a/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.ts
index 6d47e606e6..2c93afb154 100644
--- a/apps/server/src/services/notes.spec.ts
+++ b/apps/server/src/services/notes.spec.ts
@@ -150,6 +150,44 @@ describe("checkImageAttachments", () => {
expect(favicon.utcDateScheduledForErasureSince).toBeNull();
});
+ it("rewrites every reference to a foreign attachment, not just the first", () => {
+ // A deduplicated favicon is referenced once per link to its site, so content pasted
+ // into another note arrives holding many references to the one attachment. Rewriting
+ // only the first left the rest pointing at the other note's picture — which a later
+ // save would fix one more of, announcing each with its own toast.
+ const source = buildNote({
+ title: "Source",
+ attachments: [{ id: "foreignAtt1", title: "example.com.ico", role: "favicon", mime: "image/x-icon" }]
+ });
+ const [ foreign ] = source.getAttachments();
+ foreign.blobId = "sharedBlob";
+
+ const target = buildNote({
+ title: "Target",
+ attachments: [{ id: "localAtt1", title: "example.com.ico", role: "favicon", mime: "image/x-icon" }]
+ });
+ mockAttachmentSaves(target);
+ const [ local ] = target.getAttachments();
+ local.blobId = "sharedBlob";
+
+ // The attachment is owned by another note, which is what makes it "unknown" here.
+ const getAttachments = vi.spyOn(becca, "getAttachments").mockReturnValue([ foreign ]);
+
+ try {
+ const mention = (attachmentId: string) =>
+ `<span class="link-mention" data-favicon="api/attachments/${attachmentId}/image/example.com.ico"></span>`;
+ const { content } = checkImageAttachments(
+ target,
+ `<p>${mention("foreignAtt1")} and ${mention("foreignAtt1")} and ${mention("foreignAtt1")}</p>`
+ );
+
+ expect(content).not.toContain("foreignAtt1");
+ expect(content.match(/localAtt1/g)).toHaveLength(3);
+ } finally {
+ getAttachments.mockRestore();
+ }
+ });
+
it("schedules an unreferenced favicon for erasure, its own role notwithstanding", () => {
// The role exists so an icon can be told apart from the user's own pictures, not so it
// can escape the cleanup: nothing else manages a favicon, so deleting the preview that
diff --git a/packages/commons/src/lib/attachment_roles.spec.ts b/packages/commons/src/lib/attachment_roles.spec.ts
index 26397c647a..81b324e72b 100644
--- a/packages/commons/src/lib/attachment_roles.spec.ts
+++ b/packages/commons/src/lib/attachment_roles.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { IMAGE_ATTACHMENT_ROLES, isImageAttachmentRole } from "./attachment_roles.js";
+import { IMAGE_ATTACHMENT_ROLES, isDeduplicatedAttachmentRole, isImageAttachmentRole } from "./attachment_roles.js";
describe("isImageAttachmentRole", () => {
it("recognises every picture role and nothing else", () => {
@@ -24,3 +24,19 @@ describe("isImageAttachmentRole", () => {
expect(isImageAttachmentRole("favicon")).toBe(true);
});
});
+
+describe("isDeduplicatedAttachmentRole", () => {
+ it("deduplicates only what the app named itself", () => {
+ // A site's icon: one per site rather than one per link to it.
+ expect(isDeduplicatedAttachmentRole("favicon")).toBe(true);
+
+ // Never a picture the user placed. Two images they gave the same name are two images, and
+ // collapsing them by title would lose one.
+ for (const role of [ "image", "file", "viewConfig", "importSource", "" ]) {
+ expect(isDeduplicatedAttachmentRole(role), role).toBe(false);
+ }
+
+ expect(isDeduplicatedAttachmentRole(undefined)).toBe(false);
+ expect(isDeduplicatedAttachmentRole(null)).toBe(false);
+ });
+});
diff --git a/packages/commons/src/lib/attachment_roles.ts b/packages/commons/src/lib/attachment_roles.ts
index d6d1c955b4..15d55ad21a 100644
--- a/packages/commons/src/lib/attachment_roles.ts
+++ b/packages/commons/src/lib/attachment_roles.ts
@@ -20,3 +20,26 @@ export type ImageAttachmentRole = typeof IMAGE_ATTACHMENT_ROLES[number];
export function isImageAttachmentRole(role: string | undefined | null): role is ImageAttachmentRole {
return !!role && (IMAGE_ATTACHMENT_ROLES as readonly string[]).includes(role);
}
+
+/**
+ * Roles that keep one attachment per title in a note, rather than one per use.
+ *
+ * Only for pictures the app fetched and named itself, where the title says which thing it is and
+ * the same thing is fetched again and again: a note that links a site once usually links it many
+ * times, and each link would otherwise bring its own copy of that site's icon. One row per site
+ * instead of one per link is the difference between an attachment list a reader can use and a
+ * wall of identical icons.
+ *
+ * Never for a picture the user placed. Two images they happened to give the same name are two
+ * images, and quietly collapsing them would lose one.
+ */
+const DEDUPLICATED_ATTACHMENT_ROLES: readonly string[] = [ "favicon" ];
+
+/**
+ * Whether a second attachment of this role and title should reuse the first rather than be stored
+ * again. The title is the key, so for these roles it is the caller's job to make it identify the
+ * thing — a site's hostname for a favicon — and the server's not to shorten it.
+ */
+export function isDeduplicatedAttachmentRole(role: string | undefined | null): boolean {
+ return !!role && DEDUPLICATED_ATTACHMENT_ROLES.includes(role);
+}
diff --git a/packages/trilium-core/src/routes/api/attachments.spec.ts b/packages/trilium-core/src/routes/api/attachments.spec.ts
index 711ec09649..36a33bbc2e 100644
--- a/packages/trilium-core/src/routes/api/attachments.spec.ts
+++ b/packages/trilium-core/src/routes/api/attachments.spec.ts
@@ -254,6 +254,62 @@ describe("Attachments API (core)", () => {
expect((await api.get(`/${res.body.url}`)).status).toBe(200);
});
+ it("reuses a favicon of the same title rather than storing the site's icon again", async () => {
+ const { noteId } = await createTextNote(api, { title: "Dedup target" });
+ const upload = (title: string) => api.post<{ url: string }>(
+ `/api/notes/${noteId}/attachments/upload?role=favicon`,
+ { file: { originalname: title, mimetype: "image/x-icon", buffer: icoWrapping(PIXEL_PNG) } }
+ );
+
+ const first = await upload("example.com.ico");
+ const again = await upload("example.com.ico");
+
+ // The same attachment, so a note that links a site many times carries one icon rather
+ // than one per link — and the second upload answers with the URL the first got.
+ expect(again.body.url).toBe(first.body.url);
+
+ // A different site is a different icon, identical bytes notwithstanding.
+ await upload("other.example.ico");
+
+ const attachments = (await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`)).body;
+ expect(attachments.map((a) => a.title).sort()).toStrictEqual([ "example.com.ico", "other.example.ico" ]);
+ });
+
+ it("does not deduplicate the user's own images, whatever they are called", async () => {
+ // Two pictures the user gave the same name are two pictures; collapsing them would
+ // lose one. Only roles the app names itself deduplicate.
+ const { noteId } = await createTextNote(api, { title: "No dedup target" });
+ const upload = () => api.post(
+ `/api/notes/${noteId}/attachments/upload`,
+ { file: { originalname: "photo.png", mimetype: "image/png", buffer: PIXEL_PNG } }
+ );
+
+ await upload();
+ await upload();
+
+ expect((await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`)).body).toHaveLength(2);
+ });
+
+ it("keeps a long hostname whole, since it is what one icon is told from another by", async () => {
+ // Ordinary uploads collapse a title past 40 characters to "image". Doing that to a
+ // deduplicated role would make every long hostname share a single icon.
+ const { noteId } = await createTextNote(api, { title: "Long host target" });
+ const hosts = [
+ "a-very-long-subdomain-name-indeed.example.com.ico",
+ "another-very-long-subdomain-name.example.com.ico"
+ ];
+
+ for (const host of hosts) {
+ await api.post(
+ `/api/notes/${noteId}/attachments/upload?role=favicon`,
+ { file: { originalname: host, mimetype: "image/x-icon", buffer: icoWrapping(PIXEL_PNG) } }
+ );
+ }
+
+ const attachments = (await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`)).body;
+ expect(attachments.map((a) => a.title).sort()).toStrictEqual([ ...hosts ].sort());
+ });
+
it("ignores a role it does not know rather than storing it", async () => {
// The role is what decides whether an attachment is served, listed and cleaned up, so a
// request must not be able to invent one and leave an attachment no code path looks at.
diff --git a/packages/trilium-core/src/services/image.ts b/packages/trilium-core/src/services/image.ts
index 8cf549ef4a..dfedb8b513 100644
--- a/packages/trilium-core/src/services/image.ts
+++ b/packages/trilium-core/src/services/image.ts
@@ -3,7 +3,7 @@
* Uses ImageProvider for platform-specific processing (compression, format detection).
*/
-import type { ImageAttachmentRole } from "@triliumnext/commons";
+import { type ImageAttachmentRole, isDeduplicatedAttachmentRole } from "@triliumnext/commons";
import sanitizeFilename from "sanitize-filename";
import becca from "../becca/becca.js";
@@ -196,13 +196,28 @@ function saveImageToAttachment(
): { attachmentId: string | undefined; title: string } {
getLog().info(`Saving image '${originalName}' as attachment into note '${noteId}'`);
- if (trimFilename && originalName.length > 40) {
+ // A deduplicated role's title is what identifies the picture, so it is never collapsed: every
+ // hostname past the limit would otherwise share one icon.
+ if (trimFilename && !isDeduplicatedAttachmentRole(role) && originalName.length > 40) {
originalName = "image";
}
const fileName = sanitizeFilename(originalName);
const note = becca.getNoteOrThrow(noteId);
+ const reusable = isDeduplicatedAttachmentRole(role)
+ ? note.getAttachments().find((existing) => existing.role === role && existing.title === fileName)
+ : undefined;
+
+ if (reusable) {
+ // Handed back untouched rather than rewritten with the same bytes: it already holds them,
+ // and its content is what a blob is keyed by. Any erasure it was scheduled for is cleared
+ // by checkImageAttachments on the save that follows, which owns that state.
+ getLog().info(`Reusing attachment '${reusable.attachmentId}' of note '${noteId}' for '${fileName}'`);
+
+ return { attachmentId: reusable.attachmentId, title: reusable.title };
+ }
+
const attachment = note.saveAttachment({
role,
mime: "unknown",
diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.ts
index 27d72525db..11d1bdab8f 100644
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@ -25,7 +25,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, toMap, unescapeHtml } from "./utils/index.js";
+import { newEntityId, quoteRegex, replaceAll, toMap, unescapeHtml } from "./utils/index.js";
import { basename } from "./utils/path.js";
import ws from "./ws.js";
@@ -551,8 +551,13 @@ export function checkImageAttachments(note: BNote, content: string) {
getLog().info(`Copied attachment '${unknownAttachment.attachmentId}' of note '${unknownAttachment.ownerId}' to new '${localAttachment.attachmentId}' of note '${note.noteId}'`);
}
- // replace image links
- content = content.replace(`api/attachments/${unknownAttachment.attachmentId}/image`, `api/attachments/${localAttachment.attachmentId}/image`);
+ // Replace image links — every one of them. A string first argument to replace() rewrites
+ // only the first match, which was survivable while each reference had an attachment of its
+ // own, but a deduplicated role (a link preview's favicon, one per site rather than one per
+ // link) is referenced as many times as the note links that site. Leaving the rest pointing
+ // at the foreign attachment made them resolve to another note's picture until a later save
+ // happened to fix one more, each one announcing itself with a toast.
+ content = replaceAll(content, `api/attachments/${unknownAttachment.attachmentId}/image`, `api/attachments/${localAttachment.attachmentId}/image`);
// replace reference links
content = content.replace(
new RegExp(`href="[^"]+attachmentId=${unknownAttachment.attachmentId}[^"]*"`, "g"),