Skip to content

Build your personal knowledge base with Trilium Notes

refactor(link previews): store a preview's pictures where they are fetched

Elian Doranf732968820d3
diff --git a/apps/client/src/services/image_upload.spec.ts b/apps/client/src/services/image_upload.spec.ts
index b7baf964a4..5abf518c62 100644
--- a/apps/client/src/services/image_upload.spec.ts
+++ b/apps/client/src/services/image_upload.spec.ts
@@ -55,28 +55,7 @@ describe("uploadImageAttachment", () => {
const url = await uploadImageAttachment("note1", "data:image/png;base64,QUJD");
expect(url).toBe("api/attachments/new1/image/image.png");
- // The role travels in the URL and defaults to a plain image, which is what a caller that
- // says nothing means.
- expect(serverUpload).toHaveBeenCalledWith("notes/note1/attachments/upload?role=image", expect.any(File), undefined, "POST");
- });
-
- it("asks for the role it was given, so a fetched picture is not stored as the user's own", async () => {
- serverUpload.mockResolvedValue({ uploaded: true, url: "api/attachments/new1/image/favicon.ico" });
-
- await uploadImageAttachment("note1", "data:image/png;base64,QUJD", "favicon");
-
- 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");
+ expect(serverUpload).toHaveBeenCalledWith("notes/note1/attachments/upload", expect.any(File), undefined, "POST");
});
it("returns null when the server reports the upload did not succeed", async () => {
diff --git a/apps/client/src/services/image_upload.ts b/apps/client/src/services/image_upload.ts
index 4cea92cf28..76cdb22714 100644
--- a/apps/client/src/services/image_upload.ts
+++ b/apps/client/src/services/image_upload.ts
@@ -1,4 +1,4 @@
-import { type ImageAttachmentRole, imageExtensionForMime } from "@triliumnext/commons";
+import { imageExtensionForMime } from "@triliumnext/commons";
import server from "./server.js";
@@ -11,27 +11,15 @@ import server from "./server.js";
* Format-agnostic: used by any rich note type that needs to offload inline base64 images to
* attachments (e.g. the spreadsheet drawing layer).
*
- * `role` says which kind of picture it is. The default is a plain image — the user's own — and a
- * 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.
+ * Always the user's own image. The pictures the app fetches on their behalf — a link preview's
+ * favicon and cover — are downloaded and stored server-side, and never travel through here.
*/
-export async function uploadImageAttachment(
- noteId: string,
- dataUrl: string,
- role: ImageAttachmentRole = "image",
- baseName = "image"
-): Promise<string | null> {
- const file = dataUrlToImageFile(dataUrl, baseName);
+export async function uploadImageAttachment(noteId: string, dataUrl: string): Promise<string | null> {
+ const file = dataUrlToImageFile(dataUrl);
if (!file) return null;
try {
- const url = `notes/${noteId}/attachments/upload?role=${encodeURIComponent(role)}`;
- const response = await server.upload(url, file, undefined, "POST") as { uploaded?: boolean; url?: string };
+ const response = await server.upload(`notes/${noteId}/attachments/upload`, file, undefined, "POST") as { uploaded?: boolean; url?: string };
return response?.uploaded && response.url ? response.url : null;
} catch (e) {
console.error("Failed to upload image attachment", e);
@@ -41,9 +29,9 @@ export async function uploadImageAttachment(
/**
* 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.
+ * `image.<ext>` — the extension coming from the data URL's own media type.
*/
-export function dataUrlToImageFile(dataUrl: string, baseName = "image"): File | null {
+export function dataUrlToImageFile(dataUrl: string): File | null {
const parsed = parseImageDataUrl(dataUrl);
if (!parsed) return null;
@@ -57,7 +45,7 @@ export function dataUrlToImageFile(dataUrl: string, baseName = "image"): File |
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
- return new File([ bytes ], `${baseName}.${parsed.ext}`, { type: parsed.mime });
+ return new File([ bytes ], `image.${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 32eea2374d..90b1adc96a 100644
--- a/apps/client/src/services/link_embed.spec.ts
+++ b/apps/client/src/services/link_embed.spec.ts
@@ -1,6 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { uploadImageAttachment } from "./image_upload.js";
import {
applyLinkEmbeds,
detectEmbedType,
@@ -11,12 +10,6 @@ import {
} from "./link_embed.js";
import server from "./server.js";
-vi.mock("./image_upload.js", () => ({
- uploadImageAttachment: vi.fn()
-}));
-
-const uploadImageAttachmentMock = vi.mocked(uploadImageAttachment);
-
let container: HTMLDivElement | undefined;
function makeContainer() {
@@ -80,11 +73,12 @@ describe("fetchMetadata", () => {
};
server.post = vi.fn(async () => fromServer) as typeof server.post;
- const result = await fetchMetadata(url);
+ const result = await fetchMetadata(url, "note1");
// The URL travels in the body, so it never reaches an access log — a pasted URL can carry a
- // one-time token or a signature in its query string.
- expect(server.post).toHaveBeenCalledWith("link-embed/metadata", { url });
+ // one-time token or a signature in its query string. The note id goes with it: the server
+ // stores the preview's pictures as that note's attachments and answers with their URLs.
+ expect(server.post).toHaveBeenCalledWith("link-embed/metadata", { url, noteId: "note1" });
expect(result).toEqual(fromServer);
});
@@ -93,7 +87,7 @@ describe("fetchMetadata", () => {
throw new Error("network down");
}) as typeof server.post;
- const result = await fetchMetadata("https://youtu.be/abcdefghijk");
+ const result = await fetchMetadata("https://youtu.be/abcdefghijk", "note1");
expect(result).toEqual({
url: "https://youtu.be/abcdefghijk",
embedType: "youtube",
@@ -111,79 +105,26 @@ describe("fetchMetadata", () => {
unresolved: true
})) as typeof server.post;
- const result = await fetchMetadata("https://blocked.example.com/x");
+ const result = await fetchMetadata("https://blocked.example.com/x", "note1");
expect(result.unresolved).toBe(true);
});
- describe("picture offload to attachments", () => {
- const metaWithDataUriImage = {
+ it("takes the server's attachment URLs as they come, having nothing left to upload", async () => {
+ // The pictures are stored server-side now: the metadata answers with
+ // `api/attachments/...` URLs and the client's only job is to put them in the note.
+ const fromServer = {
url: "https://example.com",
embedType: "opengraph",
title: "Title",
- favicon: "data:image/x-icon;base64,FAV",
- image: "data:image/jpeg;base64,IMG"
+ favicon: "api/attachments/att1/image/example.com.ico",
+ image: "api/attachments/att2/image/example.com-1a2b3c4d.jpeg"
};
+ server.post = vi.fn(async () => fromServer) as typeof server.post;
- it("stores both the card image and the favicon as attachments of the owning note", async () => {
- server.post = vi.fn(async () => metaWithDataUriImage) as typeof server.post;
- uploadImageAttachmentMock
- .mockResolvedValueOnce("api/attachments/att1/image/favicon.ico")
- .mockResolvedValueOnce("api/attachments/att2/image/image.jpg");
-
- const result = await fetchMetadata("https://example.com", "note1");
-
- // Stored under different roles: the card image is a picture of the page and belongs
- // 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.
- // Each is named after the thing it is of, which is the key the note reuses one by: the
- // favicon by its site, so linking that site many times keeps one icon; the cover by its
- // page, so pasting the same URL twice keeps one cover.
- expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/x-icon;base64,FAV", "favicon", "example.com");
- expect(uploadImageAttachmentMock).toHaveBeenCalledWith(
- "note1",
- "data:image/jpeg;base64,IMG",
- "coverImage",
- expect.stringMatching(/^example\.com-[0-9a-f]{8}$/)
- );
- // 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.
- expect(result.favicon).toBe("api/attachments/att1/image/favicon.ico");
- expect(result.image).toBe("api/attachments/att2/image/image.jpg");
- });
-
- it("keeps the data URI when the upload fails, so the preview still persists", async () => {
- server.post = vi.fn(async () => metaWithDataUriImage) as typeof server.post;
- uploadImageAttachmentMock.mockResolvedValue(null);
-
- const result = await fetchMetadata("https://example.com", "note1");
-
- expect(result.image).toBe("data:image/jpeg;base64,IMG");
- expect(result.favicon).toBe("data:image/x-icon;base64,FAV");
- });
-
- it("does not upload without an owning note, a non-data-URI picture, or a missing one", async () => {
- uploadImageAttachmentMock.mockClear();
-
- server.post = vi.fn(async () => metaWithDataUriImage) as typeof server.post;
- const withoutNote = await fetchMetadata("https://example.com");
- expect(withoutNote.image).toBe("data:image/jpeg;base64,IMG");
- expect(withoutNote.favicon).toBe("data:image/x-icon;base64,FAV");
-
- const remote = { ...metaWithDataUriImage, image: "https://img.example/x.png", favicon: "https://img.example/f.ico" };
- server.post = vi.fn(async () => remote) as typeof server.post;
- const remotePictures = await fetchMetadata("https://example.com", "note1");
- expect(remotePictures.image).toBe("https://img.example/x.png");
- expect(remotePictures.favicon).toBe("https://img.example/f.ico");
-
- server.post = vi.fn(async () => ({ ...metaWithDataUriImage, image: undefined, favicon: undefined })) as typeof server.post;
- const noPictures = await fetchMetadata("https://example.com", "note1");
- expect(noPictures.image).toBeUndefined();
- expect(noPictures.favicon).toBeUndefined();
+ const result = await fetchMetadata("https://example.com", "note1");
- expect(uploadImageAttachmentMock).not.toHaveBeenCalled();
- });
+ expect(result.favicon).toBe("api/attachments/att1/image/example.com.ico");
+ expect(result.image).toBe("api/attachments/att2/image/example.com-1a2b3c4d.jpeg");
});
});
diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsx
index a4965374cf..882f9f3084 100644
--- a/apps/client/src/services/link_embed.tsx
+++ b/apps/client/src/services/link_embed.tsx
@@ -1,13 +1,14 @@
import "../widgets/type_widgets/text/LinkEmbed.css";
-import { extractYouTubeVideoId, type ImageAttachmentRole, type LinkEmbedMetadata, linkPreviewImageName, safeLinkPreviewHref, safeLinkPreviewImageSrc, YOUTUBE_REGEX } from "@triliumnext/commons";
+import { extractYouTubeVideoId, type LinkEmbedMetadata, safeHostname, safeLinkPreviewHref, safeLinkPreviewImageSrc, YOUTUBE_REGEX } from "@triliumnext/commons";
import { render } from "preact";
import { useState } from "preact/hooks";
import { t } from "./i18n.js";
-import { uploadImageAttachment } from "./image_upload.js";
import server from "./server.js";
+export { safeHostname };
+
export interface EmbedMetadata {
url: string;
embedType: string;
@@ -25,82 +26,53 @@ export function detectEmbedType(url: string): "youtube" | "opengraph" {
return YOUTUBE_REGEX.test(url) ? "youtube" : "opengraph";
}
-export function safeHostname(url: string): string {
- try { return new URL(url).hostname; } catch { return url; }
-}
-
/**
* Fetches link metadata from the server. Called once at link creation time.
* The returned metadata is then stored in the note's HTML as data attributes.
*
- * When `ownerNoteId` is given, both pictures a preview carries — the card image and the favicon —
- * are stored as attachments of that note, and only their `api/attachments/...` URLs end up in the
- * metadata. Inlined as base64 data URIs they are 10–140KB of note content for a card image and
- * 1–10KB for a favicon, and that lands in the note's HTML, where it is synced and revisioned like
- * any other content. A single card is enough to push a note past the `autoReadonlySizeText`
- * threshold (32KB by default) and flip it read-only; favicons get there by repetition instead,
- * since a note that links a site once usually links it many times and each copy carries the icon
- * again.
+ * Both pictures a preview carries — the cover image and the favicon — are stored by the server as
+ * attachments of `ownerNoteId`, and only their `api/attachments/...` URLs come back. That is why
+ * the note id is required rather than optional: the pictures have nowhere else to live, and
+ * carrying them in the note's HTML instead would be 10–140KB of content for a cover and 1–10KB for
+ * a favicon, synced and revisioned like anything else the note holds. A single card is enough to
+ * push a note past the `autoReadonlySizeText` threshold (32KB by default) and flip it read-only;
+ * favicons get there by repetition, a note that links a site once usually linking it many times.
*/
-export async function fetchMetadata(url: string, ownerNoteId?: string): Promise<EmbedMetadata> {
+export async function fetchMetadata(url: string, ownerNoteId: string): Promise<EmbedMetadata> {
try {
// POSTed rather than passed in the query string: a URL can carry a one-time token or a
// signed signature, and a query string ends up in every access log along the way.
- 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.
- // Each picture is named after the thing it is of — the favicon by its site, the cover by
- // its page — which is what lets a note that links the same site many times keep one icon,
- // and the same URL pasted twice keep one cover.
- const [ favicon, image ] = await Promise.all([
- offloadPictureToAttachment(metadata.favicon, ownerNoteId, "favicon", safeHostname(metadata.url)),
- offloadPictureToAttachment(metadata.image, ownerNoteId, "coverImage", linkPreviewImageName(metadata.url))
- ]);
+ const metadata = await server.post<LinkEmbedMetadata>("link-embed/metadata", { url, noteId: ownerNoteId });
return {
url: metadata.url,
embedType: metadata.embedType,
title: metadata.title,
description: metadata.description,
- favicon,
+ favicon: metadata.favicon,
siteName: metadata.siteName,
- image,
+ image: metadata.image,
unresolved: metadata.unresolved
};
} catch {
- return {
- url,
- embedType: detectEmbedType(url),
- title: safeHostname(url),
- unresolved: true
- };
+ return unresolvedMetadata(url);
}
}
/**
- * Converts one of a preview's base64 pictures into an attachment of the owning note, returning its
- * `api/attachments/...` URL — or the data URI unchanged when the upload fails, so the preview still
- * persists and renders, just at the old inline cost.
- *
- * Both pictures go through this, so both are subject to the same rule at the render sinks: only an
- * inline image or an attachment of this instance is ever loaded (see `isLocalPreviewImageSrc`).
+ * What a URL is worth when nothing could be learned about it: the hostname, and a flag saying so.
*
- * They are stored under different roles all the same. A card image is a picture of the page and
- * belongs with the note's own images; a favicon is the site's mark, fetched rather than chosen, and
- * telling the two apart is what lets icons be deduplicated and kept out of the tools that reason
- * about what the user put in the note.
+ * The caller keeps it as a plain link rather than rendering a preview that shows less than the URL
+ * did. Reached when the metadata request fails, and when there is no note yet to store the
+ * preview's pictures on.
*/
-async function offloadPictureToAttachment(
- picture: string | undefined,
- ownerNoteId: string | undefined,
- role: ImageAttachmentRole = "image",
- baseName?: string
-): Promise<string | undefined> {
- if (!picture || !ownerNoteId || !picture.startsWith("data:")) {
- return picture;
- }
-
- return await uploadImageAttachment(ownerNoteId, picture, role, baseName) ?? picture;
+export function unresolvedMetadata(url: string): EmbedMetadata {
+ return {
+ url,
+ embedType: detectEmbedType(url),
+ title: safeHostname(url),
+ unresolved: true
+ };
}
// ---------------------------------------------------------------------------
@@ -298,6 +270,7 @@ export function applyLinkEmbeds(container: HTMLElement) {
export default {
fetchMetadata,
+ unresolvedMetadata,
detectEmbedType,
safeHostname,
renderEmbedPreview,
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index 9e07823622..14bd45d8d5 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -162,7 +162,15 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
await link.loadReferenceLinkTitle($el, href);
},
async fetchLinkMetadata(url: string) {
- return await linkEmbedService.fetchMetadata(url, note?.noteId);
+ // The preview's pictures are stored as attachments of the note being edited, so there
+ // is nothing to fetch into before the note context has resolved one. Answering as
+ // unresolved leaves the URL a plain link, which is what the editor does with any
+ // preview it could not build.
+ if (!note) {
+ return linkEmbedService.unresolvedMetadata(url);
+ }
+
+ return await linkEmbedService.fetchMetadata(url, note.noteId);
},
detectEmbedType(url: string) {
return linkEmbedService.detectEmbedType(url);
diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.ts
index d521ac2469..ba348fbb28 100644
--- a/apps/server/src/routes/api/link_embed.spec.ts
+++ b/apps/server/src/routes/api/link_embed.spec.ts
@@ -2,7 +2,7 @@ import { extractYouTubeVideoId } from "@triliumnext/commons";
import { ValidationError } from "@triliumnext/core";
import type { Request } from "express";
import { Jimp } from "jimp";
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
const safeFetch = vi.hoisted(() => vi.fn());
@@ -12,8 +12,39 @@ vi.mock("../../services/safe_fetch.js", () => ({
safeFetch: (...args: unknown[]) => safeFetch(...args)
}));
+const saveImageToAttachment = vi.hoisted(() => vi.fn());
+const awaitImageWrite = vi.hoisted(() => vi.fn(async () => {}));
+
+/**
+ * The route stores each picture it downloads as an attachment of the note the preview is going
+ * into. What matters here is which picture was handed over, under which role and name — not that a
+ * database took it — so the store is stood in for.
+ */
+vi.mock("@triliumnext/core", async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ imageService: { saveImageToAttachment, awaitImageWrite }
+}));
+
import linkEmbedRoute from "./link_embed.js";
+let attachmentCounter = 0;
+
+beforeEach(() => {
+ attachmentCounter = 0;
+ saveImageToAttachment.mockReset();
+ saveImageToAttachment.mockImplementation((_noteId: string, _buffer: Buffer, fileName: string) => ({
+ attachmentId: `att${++attachmentCounter}`,
+ title: fileName
+ }));
+});
+
+/** What was handed to the attachment store under a given role, if anything was. */
+function stored(role: "favicon" | "coverImage") {
+ const call = saveImageToAttachment.mock.calls.find((args: unknown[]) => args[5] === role);
+
+ return call ? { buffer: call[1] as Buffer, fileName: call[2] as string } : undefined;
+}
+
function oneShotReader(bytes: Buffer) {
let sent = false;
return {
@@ -63,13 +94,6 @@ function makeIco(): Buffer {
return Buffer.concat([ directory, Buffer.from([ 0, 0, 0, 0 ]) ]);
}
-/** Decodes a `data:` URI back into its media type and bytes. */
-function parseDataUri(dataUri: string) {
- const match = /^data:([^;]+);base64,(.+)$/.exec(dataUri);
- if (!match) throw new Error(`Not a base64 data URI: ${dataUri.slice(0, 40)}`);
- return { contentType: match[1], buffer: Buffer.from(match[2], "base64") };
-}
-
describe("extractYouTubeVideoId", () => {
it("extracts ids and rejects non-YouTube URLs", () => {
expect(extractYouTubeVideoId("https://www.youtube.com/watch?v=dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
@@ -81,13 +105,23 @@ describe("extractYouTubeVideoId", () => {
describe("link-embed getMetadata", () => {
// The URL is POSTed in the body, never in the query string: a query string ends up in every
// access log along the way, and a pasted URL can carry a one-time token or a signature.
- function req(url?: unknown) { return { body: { url } } as unknown as Request; }
+ function req(url?: unknown, noteId: unknown = "note1") { return { body: { url, noteId } } as unknown as Request; }
it("requires a url in the body", async () => {
await expect(linkEmbedRoute.getMetadata(req())).rejects.toBeInstanceOf(ValidationError);
await expect(linkEmbedRoute.getMetadata({} as unknown as Request)).rejects.toBeInstanceOf(ValidationError);
});
+ it("requires the note the preview is going into", async () => {
+ // The pictures are stored as that note's attachments, so there is nowhere to put them
+ // without it — and nothing to answer with, the metadata carrying their URLs.
+ // Built directly rather than through req(), whose default would supply the very thing
+ // these are checking the absence of.
+ const withoutNote = { body: { url: "https://example.com" } } as unknown as Request;
+ await expect(linkEmbedRoute.getMetadata(withoutNote)).rejects.toBeInstanceOf(ValidationError);
+ await expect(linkEmbedRoute.getMetadata(req("https://example.com", 42))).rejects.toBeInstanceOf(ValidationError);
+ });
+
it("returns YouTube metadata via the oEmbed endpoint", async () => {
safeFetch.mockImplementation(async (url: string) => {
if (url.includes("favicon")) return fakeResponse(makeIco(), { contentType: "image/x-icon" });
@@ -98,7 +132,10 @@ describe("link-embed getMetadata", () => {
expect(result.embedType).toBe("youtube");
expect(result.title).toBe("Cool Video");
expect(result.description).toBe("Channel");
- expect(result.favicon).toMatch(/^data:image\//);
+ // Stored as an attachment of the note, titled by the site it belongs to, and referenced
+ // from the note by the URL the store answered with.
+ expect(stored("favicon")?.fileName).toBe("www.youtube.com.ico");
+ expect(result.favicon).toMatch(/^api\/attachments\/att\d+\/image\/www\.youtube\.com\.ico$/);
});
it("parses OpenGraph metadata from an HTML page", async () => {
@@ -121,8 +158,10 @@ describe("link-embed getMetadata", () => {
expect(result.title).toBe("OG Title");
expect(result.description).toBe("OG Desc");
expect(result.siteName).toBe("Example");
- // Embedded, not hotlinked; opaque, so re-encoded as JPEG.
- expect(result.image).toMatch(/^data:image\/jpeg;base64,/);
+ // Stored, not hotlinked; opaque, so re-encoded as JPEG. Named after the page it is a
+ // picture of, which is what a second paste of the same URL reuses it by.
+ expect(stored("coverImage")?.fileName).toMatch(/^example\.com-page-[0-9a-f]{8}\.jpeg$/);
+ expect(result.image).toMatch(/^api\/attachments\/att\d+\/image\/example\.com-page-[0-9a-f]{8}\.jpeg$/);
});
it("resolves a relative og:image against the page URL before downloading it", async () => {
@@ -162,20 +201,25 @@ describe("link-embed getMetadata", () => {
});
}
+ /**
+ * Runs the route and answers with the cover picture it handed to the store, if any.
+ * Earlier runs are forgotten first, so a test that fetches twice reads only the second.
+ */
async function imageOf() {
+ saveImageToAttachment.mockClear();
const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));
// The rest of the preview must survive whatever happens to the image.
expect(result.title).toBe("T");
- return result.image;
+ return stored("coverImage");
}
it("scales an oversized image down to the 256px limit, preserving the aspect ratio", async () => {
serveImage({ payload: await makePng(1024, 512, 0x00ff00ff), contentType: "image/png" });
const image = await imageOf();
- expect(image).toMatch(/^data:image\/jpeg;base64,/);
+ expect(image?.fileName).toMatch(/\.jpeg$/);
- const decoded = await Jimp.read(parseDataUri(image ?? "").buffer);
+ const decoded = await Jimp.read(image?.buffer ?? Buffer.alloc(0));
expect(decoded.bitmap.width).toBe(256);
expect(decoded.bitmap.height).toBe(128);
});
@@ -184,9 +228,9 @@ describe("link-embed getMetadata", () => {
serveImage({ payload: await makePng(400, 400, 0x00000000), contentType: "image/png" });
const image = await imageOf();
- expect(image).toMatch(/^data:image\/png;base64,/);
+ expect(image?.fileName).toMatch(/\.png$/);
- const decoded = await Jimp.read(parseDataUri(image ?? "").buffer);
+ const decoded = await Jimp.read(image?.buffer ?? Buffer.alloc(0));
expect(decoded.bitmap.width).toBe(256);
expect(decoded.hasAlpha()).toBe(true);
});
@@ -194,15 +238,15 @@ describe("link-embed getMetadata", () => {
it("does not enlarge an image that is already smaller than the limit", async () => {
serveImage({ payload: await makePng(64, 32, 0xff0000ff), contentType: "image/png" });
- const decoded = await Jimp.read(parseDataUri(await imageOf() ?? "").buffer);
+ const decoded = await Jimp.read((await imageOf())?.buffer ?? Buffer.alloc(0));
expect(decoded.bitmap.width).toBe(64);
expect(decoded.bitmap.height).toBe(32);
});
- it("embeds an SVG verbatim, but drops one over 100KB", async () => {
+ it("stores an SVG verbatim, but drops one over 100KB", async () => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10"/></svg>`;
serveImage({ payload: svg, contentType: "image/svg+xml" });
- expect(parseDataUri(await imageOf() ?? "")).toMatchObject({ contentType: "image/svg+xml" });
+ expect((await imageOf())?.fileName).toMatch(/\.svg$/);
const hugeSvg = svg.replace("<rect", `<!--${"x".repeat(100 * 1024)}--><rect`);
serveImage({ payload: hugeSvg, contentType: "image/svg+xml" });
@@ -213,7 +257,7 @@ describe("link-embed getMetadata", () => {
// Jimp bundles no WebP decoder, so these bytes cannot be resized — but they must still not
// be hotlinked. Anything over the verbatim cap is dropped instead.
serveImage({ payload: Buffer.from("RIFF????WEBPVP8 not-really"), contentType: "image/webp" });
- expect(await imageOf()).toMatch(/^data:image\/webp;base64,/);
+ expect((await imageOf())?.fileName).toMatch(/\.webp$/);
serveImage({ payload: Buffer.alloc(150 * 1024, 1), contentType: "image/webp" });
expect(await imageOf()).toBeUndefined();
@@ -245,15 +289,16 @@ describe("link-embed getMetadata", () => {
});
}
- const metadataFor = () => linkEmbedRoute.getMetadata(req("https://example.com/page"));
+ const metadataFor = () => {
+ saveImageToAttachment.mockClear();
+ return linkEmbedRoute.getMetadata(req("https://example.com/page"));
+ };
it("uses a large apple-touch-icon as the image", async () => {
servePage(`<link rel="apple-touch-icon" href="/touch.png">`, { "/touch.png": { width: 180, height: 180 } });
- const result = await metadataFor();
- expect(result.image).toMatch(/^data:image\//);
-
- const decoded = await Jimp.read(parseDataUri(result.image ?? "").buffer);
+ await metadataFor();
+ const decoded = await Jimp.read(stored("coverImage")?.buffer ?? Buffer.alloc(0));
expect(decoded.bitmap.width).toBe(180);
});
@@ -279,14 +324,16 @@ describe("link-embed getMetadata", () => {
{ "/medium.png": { width: 96, height: 96 }, "/large.png": { width: 192, height: 192 } }
);
- const decoded = await Jimp.read(parseDataUri((await metadataFor()).image ?? "").buffer);
+ await metadataFor();
+ const decoded = await Jimp.read(stored("coverImage")?.buffer ?? Buffer.alloc(0));
expect(decoded.bitmap.width).toBe(192);
});
it("falls back to the conventional /apple-touch-icon.png when none is declared", async () => {
servePage("", { "/apple-touch-icon.png": { width: 180, height: 180 } });
- expect((await metadataFor()).image).toMatch(/^data:image\//);
+ await metadataFor();
+ expect(stored("coverImage")).toBeDefined();
});
it("prefers a real og:image over the site icon", async () => {
@@ -295,7 +342,8 @@ describe("link-embed getMetadata", () => {
{ "/cover.png": { width: 600, height: 300 }, "/touch.png": { width: 180, height: 180 } }
);
- const decoded = await Jimp.read(parseDataUri((await metadataFor()).image ?? "").buffer);
+ await metadataFor();
+ const decoded = await Jimp.read(stored("coverImage")?.buffer ?? Buffer.alloc(0));
// The og:image is 2:1, the icon is square — the aspect ratio identifies which one was used.
expect(decoded.bitmap.width).toBe(256);
expect(decoded.bitmap.height).toBe(128);
@@ -382,16 +430,15 @@ describe("link-embed getMetadata", () => {
it("names a favicon by its own bytes rather than by the content type it was served under", async () => {
const html = `<html><head><title>Plain</title><link rel="icon" href="/fav.ico"></head></html>`;
// Serving favicon.ico as an octet-stream is common enough to be the normal case on some
- // hosts. The media type decides whether the client's upload of it is stored as a picture at
- // all, so taking the header's word for it would leave the icon as a file attachment, which
- // comes back as a `#root/...` reference the render sinks reject.
+ // hosts. The media type names the extension the attachment is stored under and the type it
+ // is later served as, so taking the header's word for it would file the icon as a `.dat`.
safeFetch.mockImplementation(async (url: string) => {
if (url.includes("fav.ico")) return fakeResponse(makeIco(), { contentType: "application/octet-stream" });
return fakeResponse(html, { contentType: "text/html" });
});
let result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));
- expect(parseDataUri(result.favicon ?? "").contentType).toBe("image/x-icon");
+ expect(stored("favicon")?.fileName).toBe("example.com.ico");
// And the same reading in the other direction: an error page served where the icon should
// be is not made into one by a content type claiming it is.
@@ -457,9 +504,9 @@ describe("link-embed getMetadata", () => {
return fakeResponse("", { ok: false });
});
- const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));
+ await linkEmbedRoute.getMetadata(req("https://example.com/page"));
// "any" declares a scalable icon — the best possible candidate, tried (and kept) first.
- expect(result.image).toMatch(/^data:image\/svg\+xml;base64,/);
+ expect(stored("coverImage")?.fileName).toMatch(/\.svg$/);
// The declared apple-touch-icon href dedupes against the conventional fallback path, so it
// is never requested twice.
const touchIconRequests = safeFetch.mock.calls
@@ -483,7 +530,7 @@ describe("link-embed getMetadata", () => {
// used either, and the thumbnail comes from the conventional hqdefault URL.
expect(result.title).toBeUndefined();
expect(result.description).toBeUndefined();
- expect(result.image).toMatch(/^data:image\/jpeg;base64,/);
+ expect(stored("coverImage")?.fileName).toMatch(/\.jpeg$/);
});
it("ignores meta tags whose content is empty, falling back to the document title", async () => {
diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.ts
index cd1cda1f3c..8702cf2e4f 100644
--- a/apps/server/src/routes/api/link_embed.ts
+++ b/apps/server/src/routes/api/link_embed.ts
@@ -1,5 +1,12 @@
-import { extractYouTubeVideoId, type LinkEmbedMetadata } from "@triliumnext/commons";
-import { getLog, ValidationError } from "@triliumnext/core";
+import {
+ extractYouTubeVideoId,
+ type ImageAttachmentRole,
+ imageExtensionForMime,
+ type LinkEmbedMetadata,
+ linkPreviewImageName,
+ safeHostname
+} from "@triliumnext/commons";
+import { getLog, imageService, ValidationError } from "@triliumnext/core";
import type { Request } from "express";
import isSvg from "is-svg";
import { Jimp } from "jimp";
@@ -97,8 +104,71 @@ async function downloadBinary(url: string, maxBytes: number, defaultContentType:
}
}
-function toDataUri(contentType: string, buffer: Buffer): string {
- return `data:${contentType};base64,${buffer.toString("base64")}`;
+/** A picture that has been fetched and identified, but not yet stored anywhere. */
+interface DownloadedPicture {
+ buffer: Buffer;
+ mime: string;
+}
+
+/**
+ * A preview as it comes back from the site: everything the note will carry as text, and the
+ * pictures still holding their bytes.
+ *
+ * They are kept apart until the very end so that storing them happens once, in one place, rather
+ * than at each of the several points a picture can be found. The note only ever receives the
+ * `api/attachments/...` URLs.
+ */
+interface FetchedPreview {
+ metadata: LinkEmbedMetadata;
+ favicon?: DownloadedPicture;
+ image?: DownloadedPicture;
+}
+
+/**
+ * Stores one of a preview's pictures on the note the preview is going into, and answers with the
+ * URL the note will reference it by.
+ *
+ * `shrink` is off: {@link downloadPreviewImage} has already scaled and re-encoded what it fetched,
+ * and a favicon arrives at the size the site published it. The generic compression pass would only
+ * decode a picture that has nothing left to give, and it holds a slot sized for the user's own
+ * photographs while it does.
+ */
+async function storePicture(
+ noteId: string,
+ picture: DownloadedPicture | undefined,
+ role: ImageAttachmentRole,
+ baseName: string
+): Promise<string | undefined> {
+ if (!picture) {
+ return undefined;
+ }
+
+ const fileName = `${baseName}.${imageExtensionForMime(picture.mime)}`;
+ const attachment = imageService.saveImageToAttachment(noteId, picture.buffer, fileName, false, false, role);
+
+ if (!attachment.attachmentId) {
+ return undefined;
+ }
+
+ // The client renders the preview the moment this answers, so the URL it is handed has to be
+ // fetchable by then; otherwise the picture draws broken and stays that way until a reload.
+ await imageService.awaitImageWrite(attachment.attachmentId);
+
+ return `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}`;
+}
+
+/**
+ * Stores both of a preview's pictures, naming each after the thing it is of — the favicon by its
+ * site, the cover by its page — which is what lets a note that links one site many times keep a
+ * single icon, and the same URL pasted twice keep a single cover.
+ */
+async function storePictures(noteId: string, url: string, fetched: FetchedPreview): Promise<LinkEmbedMetadata> {
+ const [ favicon, image ] = await Promise.all([
+ storePicture(noteId, fetched.favicon, "favicon", safeHostname(url)),
+ storePicture(noteId, fetched.image, "coverImage", linkPreviewImageName(url))
+ ]);
+
+ return { ...fetched.metadata, favicon, image };
}
/**
@@ -106,10 +176,8 @@ function toDataUri(contentType: string, buffer: Buffer): string {
* bytes are not a picture at all.
*
* The response header cannot answer this. `favicon.ico` is routinely served as
- * `application/octet-stream` or `text/plain`, and the media type is not decoration: the client
- * offloads these into attachments, and the upload endpoint decides whether it is storing a picture
- * from the type the data URI declares. A favicon named by a careless header would be stored as a
- * file, come back as a `#root/...` reference, and be rejected at the render sink.
+ * `application/octet-stream` or `text/plain`, and the media type is not decoration: it decides the
+ * extension the attachment is titled with and the type the picture is later served under.
*
* Undefined also covers the case the header hides in the other direction — an HTML error page
* served in place of an image, which is not something to keep whatever it claims to be.
@@ -118,27 +186,34 @@ async function detectImageMime(buffer: Buffer): Promise<string | undefined> {
return (await getImageTypeFromBuffer(buffer))?.mime;
}
+/** Downloads a picture and names it by its own bytes, or nothing if those are not a picture. */
+async function asPicture(buffer: Buffer): Promise<DownloadedPicture | undefined> {
+ const mime = await detectImageMime(buffer);
+
+ return mime ? { buffer, mime } : undefined;
+}
+
/**
- * Downloads a favicon and returns it as a base64 data URI, named by its own bytes.
+ * Downloads a favicon.
* Returns undefined if the download fails, the image is too large, or it is not an image.
*/
-async function downloadFaviconAsDataUri(faviconUrl: string): Promise<string | undefined> {
+async function downloadFavicon(faviconUrl: string): Promise<DownloadedPicture | undefined> {
const downloaded = await downloadBinary(faviconUrl, MAX_FAVICON_SIZE, "image/x-icon");
- if (!downloaded) return undefined;
- const mime = await detectImageMime(downloaded.buffer);
-
- return mime ? toDataUri(mime, downloaded.buffer) : undefined;
+ return downloaded ? await asPicture(downloaded.buffer) : undefined;
}
/**
- * Downloads the preview image, scales it down to {@link IMAGE_MAX_DIMENSION} and returns it as a
- * base64 data URI, so the note carries the image itself instead of hotlinking the origin site (which
- * would leak every reader's IP to it, and break whenever the remote URL rots).
+ * Downloads the preview image and scales it down to {@link IMAGE_MAX_DIMENSION}, so the note holds
+ * the picture itself instead of hotlinking the origin site (which would leak every reader's IP to
+ * it, and break whenever the remote URL rots).
+ *
+ * Sized here rather than left to the generic image pipeline because these bytes make a round trip:
+ * they are downloaded here and stored here, and a 5MB `og:image` has no business being carried
+ * through that as a card thumbnail nobody will see above 256 pixels.
*
* Transparency is preserved by re-encoding to PNG only when the image actually has non-opaque
- * pixels; an opaque image becomes a JPEG, which is several times smaller — and this ends up inside
- * the note's HTML, so every byte is synced and stored forever.
+ * pixels; an opaque image becomes a JPEG, which is several times smaller.
*
* Returns undefined when the image cannot be had at a reasonable size, in which case the preview is
* still shown without it — the title and description carry the value, not the picture.
@@ -146,7 +221,7 @@ async function downloadFaviconAsDataUri(faviconUrl: string): Promise<string | un
* `minSourceDimension` rejects a source whose longest edge is below it, used when falling back to a
* site icon: a 16x16 favicon blown up into a card thumbnail looks worse than no image at all.
*/
-async function downloadImageAsDataUri(imageUrl: string, minSourceDimension = 0): Promise<string | undefined> {
+async function downloadPreviewImage(imageUrl: string, minSourceDimension = 0): Promise<DownloadedPicture | undefined> {
const downloaded = await downloadBinary(imageUrl, MAX_IMAGE_DOWNLOAD_SIZE, "image/jpeg");
if (!downloaded) return undefined;
@@ -157,7 +232,7 @@ async function downloadImageAsDataUri(imageUrl: string, minSourceDimension = 0):
// and it satisfies any minimum dimension by definition.
// The isSvg() sniff only runs on a buffer we would be willing to keep, to avoid stringifying megabytes.
if (contentType.includes("svg") || (isSmallEnoughToKeepVerbatim && isSvg(buffer.toString()))) {
- return isSmallEnoughToKeepVerbatim ? toDataUri("image/svg+xml", buffer) : undefined;
+ return isSmallEnoughToKeepVerbatim ? { buffer, mime: "image/svg+xml" } : undefined;
}
try {
@@ -175,8 +250,8 @@ async function downloadImageAsDataUri(imageUrl: string, minSourceDimension = 0):
// hasAlpha() inspects the pixels, not just the channel, so an opaque PNG still takes the
// JPEG path. An animated GIF/WebP collapses to its first frame, which is fine for a thumbnail.
return image.hasAlpha()
- ? toDataUri("image/png", Buffer.from(await image.getBuffer("image/png")))
- : toDataUri("image/jpeg", Buffer.from(await image.getBuffer("image/jpeg", { quality: IMAGE_JPEG_QUALITY })));
+ ? { buffer: Buffer.from(await image.getBuffer("image/png")), mime: "image/png" }
+ : { buffer: Buffer.from(await image.getBuffer("image/jpeg", { quality: IMAGE_JPEG_QUALITY })), mime: "image/jpeg" };
} catch (e: unknown) {
// Jimp bundles decoders for PNG/JPEG/GIF/BMP/TIFF only, so a WebP or AVIF lands here. Keep
// the original bytes when they are small enough — unresized, but still not hotlinked. The
@@ -189,9 +264,7 @@ async function downloadImageAsDataUri(imageUrl: string, minSourceDimension = 0):
// match a log line against the paste that caused it.
getLog().info(`Could not decode a link preview image: ${e}`);
- const mime = isSmallEnoughToKeepVerbatim && !minSourceDimension ? await detectImageMime(buffer) : undefined;
-
- return mime ? toDataUri(mime, buffer) : undefined;
+ return isSmallEnoughToKeepVerbatim && !minSourceDimension ? await asPicture(buffer) : undefined;
}
}
@@ -219,9 +292,9 @@ function toAbsoluteUrl(href: string | undefined, pageUrl: string): string | unde
* {@link MIN_ICON_AS_IMAGE_DIMENSION} across — the declared `sizes` attribute is a hint used for
* ordering, never trusted as fact, since the actual bytes decide.
*/
-async function resolveIconAsImage(document: ReturnType<typeof parse>, pageUrl: string): Promise<string | undefined> {
+async function resolveIconAsImage(document: ReturnType<typeof parse>, pageUrl: string): Promise<DownloadedPicture | undefined> {
for (const candidate of collectIconCandidates(document, pageUrl).slice(0, MAX_ICON_CANDIDATES)) {
- const image = await downloadImageAsDataUri(candidate, MIN_ICON_AS_IMAGE_DIMENSION);
+ const image = await downloadPreviewImage(candidate, MIN_ICON_AS_IMAGE_DIMENSION);
if (image) return image;
}
@@ -276,9 +349,9 @@ function largestDeclaredSize(sizes: string | undefined): number {
}
/**
- * Resolves a favicon URL from the parsed HTML, then downloads it as a data URI.
+ * Resolves a favicon URL from the parsed HTML, then downloads it.
*/
-async function resolveFavicon(document: ReturnType<typeof parse>, pageUrl: string): Promise<string | undefined> {
+async function resolveFavicon(document: ReturnType<typeof parse>, pageUrl: string): Promise<DownloadedPicture | undefined> {
const faviconEl = document.querySelector('link[rel="icon"]')
|| document.querySelector('link[rel="shortcut icon"]')
|| document.querySelector('link[rel="apple-touch-icon"]');
@@ -287,22 +360,21 @@ async function resolveFavicon(document: ReturnType<typeof parse>, pageUrl: strin
const faviconUrl = toAbsoluteUrl(faviconEl?.getAttribute("href"), pageUrl)
?? new URL("/favicon.ico", pageUrl).toString();
- return await downloadFaviconAsDataUri(faviconUrl);
+ return await downloadFavicon(faviconUrl);
}
/**
* Fetches YouTube metadata via the public oEmbed endpoint.
* This works reliably unlike scraping youtube.com (which blocks bots).
*/
-async function fetchYouTubeMetadata(url: string, videoId: string): Promise<LinkEmbedMetadata> {
+async function fetchYouTubeMetadata(url: string, videoId: string): Promise<FetchedPreview> {
const metadata: LinkEmbedMetadata = {
url,
siteName: "YouTube",
embedType: "youtube"
};
- // Download YouTube favicon as data URI
- metadata.favicon = await downloadFaviconAsDataUri("https://www.youtube.com/favicon.ico");
+ const favicon = await downloadFavicon("https://www.youtube.com/favicon.ico");
let thumbnailUrl = `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`;
@@ -320,11 +392,9 @@ async function fetchYouTubeMetadata(url: string, videoId: string): Promise<LinkE
metadata.title = "YouTube Video";
}
- // The thumbnail is embedded like any other preview image: it is what Card display mode shows, and
+ // The thumbnail is stored like any other preview image: it is what Card display mode shows, and
// hotlinking it would tell YouTube every time the note is opened.
- metadata.image = await downloadImageAsDataUri(thumbnailUrl);
-
- return metadata;
+ return { metadata, favicon, image: await downloadPreviewImage(thumbnailUrl) };
}
async function fetchOpenGraphData(url: string) {
@@ -360,14 +430,14 @@ async function fetchOpenGraphData(url: string) {
const imageUrl = toAbsoluteUrl(getMeta("og:image"), url);
// A site with no og:image (or one that fails to download) still usually has a large home-screen
// icon, which makes a far better card than an empty placeholder.
- const image = (imageUrl ? await downloadImageAsDataUri(imageUrl) : undefined)
+ const image = (imageUrl ? await downloadPreviewImage(imageUrl) : undefined)
?? await resolveIconAsImage(document, url);
return {
title: getMeta("og:title") || document.querySelector("title")?.textContent?.trim() || undefined,
description: getMeta("og:description") || getMeta("description") || undefined,
- image,
siteName: getMeta("og:site_name") || undefined,
+ image,
favicon
};
}
@@ -375,11 +445,19 @@ async function fetchOpenGraphData(url: string) {
async function getMetadata(req: Request) {
// Taken from the body, not the query string: see the route registration for why.
const urlParam = req.body?.url;
+ const noteIdParam = req.body?.noteId;
if (!urlParam || typeof urlParam !== "string") {
throw new ValidationError("'url' is required");
}
+ // The note the preview is going into. Required, because the pictures are stored as its
+ // attachments and there is nowhere else for them to live — a preview that belongs to no note
+ // is a preview nothing will ever render.
+ if (!noteIdParam || typeof noteIdParam !== "string") {
+ throw new ValidationError("'noteId' is required");
+ }
+
const validatedUrl = validateUrl(urlParam);
const url = validatedUrl.toString();
const videoId = extractYouTubeVideoId(url);
@@ -387,27 +465,30 @@ async function getMetadata(req: Request) {
// A YouTube link stays resolved even when oEmbed is unreachable: the player embeds from the
// video ID alone, so the preview is worth showing with or without the title and channel.
if (videoId) {
- return await fetchYouTubeMetadata(url, videoId);
+ return await storePictures(noteIdParam, url, await fetchYouTubeMetadata(url, videoId));
}
try {
const ogData = await fetchOpenGraphData(url);
// A page that answered but names itself nowhere (no og:title, no <title>) leaves us with
- // the hostname we already had, which is no better than a failed fetch.
+ // the hostname we already had, which is no better than a failed fetch. Nothing is stored
+ // for it: the pictures are dropped along with the preview they would have belonged to.
if (!ogData.title) {
return unresolvedMetadata(validatedUrl);
}
- return {
- url,
- title: ogData.title,
- description: ogData.description,
- image: ogData.image,
+ return await storePictures(noteIdParam, url, {
+ metadata: {
+ url,
+ title: ogData.title,
+ description: ogData.description,
+ siteName: ogData.siteName,
+ embedType: "opengraph"
+ },
favicon: ogData.favicon,
- siteName: ogData.siteName,
- embedType: "opengraph"
- } satisfies LinkEmbedMetadata;
+ image: ogData.image
+ });
} catch (e: unknown) {
// No URL here either — see the note above the image-decode log.
getLog().info(`Failed to fetch link preview metadata: ${e}`);
diff --git a/packages/commons/src/lib/link_embed.ts b/packages/commons/src/lib/link_embed.ts
index 91052699fb..c624288b1a 100644
--- a/packages/commons/src/lib/link_embed.ts
+++ b/packages/commons/src/lib/link_embed.ts
@@ -84,6 +84,20 @@ export function safeLinkPreviewImageSrc(src: string | undefined | null): string
return isLocalPreviewImageSrc(src) ? String(src).trim() : undefined;
}
+/**
+ * The host a URL points at, or the URL itself when it cannot be read as one.
+ *
+ * Both the site name a preview falls back to showing and the title its favicon is stored under, so
+ * it lives here rather than on either side: the picture and the label have to name the same site.
+ */
+export function safeHostname(url: string): string {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return url;
+ }
+}
+
/**
* The attachment title a link preview's cover image is stored under.
*
diff --git a/packages/trilium-core/src/routes/api/attachments.spec.ts b/packages/trilium-core/src/routes/api/attachments.spec.ts
index 04a40813f2..9a227502d7 100644
--- a/packages/trilium-core/src/routes/api/attachments.spec.ts
+++ b/packages/trilium-core/src/routes/api/attachments.spec.ts
@@ -236,109 +236,6 @@ describe("Attachments API (core)", () => {
expect(attachment).toMatchObject({ role: "image", mime: "image/x-icon" });
});
- it("stores an upload under a requested picture role, and serves it like any other", async () => {
- const { noteId } = await createTextNote(api, { title: "Favicon target" });
-
- const res = await api.post<{ uploaded: boolean; url: string }>(
- `/api/notes/${noteId}/attachments/upload?role=favicon`,
- { file: { originalname: "favicon.ico", mimetype: "image/x-icon", buffer: icoWrapping(PIXEL_PNG) } }
- );
- expect(res.status).toBe(200);
- expect(res.body.url).toContain("/image/");
-
- const [ attachment ] = (await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`)).body;
- expect(attachment.role).toBe("favicon");
-
- // The role decides whether the image route will serve it at all — a role it does not
- // know is answered with a 400, which would leave every preview showing a placeholder.
- 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("reuses a cover image of the same title, which is what the same URL pasted twice gives", async () => {
- const { noteId } = await createTextNote(api, { title: "Cover dedup target" });
- const upload = (title: string) => api.post<{ url: string }>(
- `/api/notes/${noteId}/attachments/upload?role=coverImage`,
- { file: { originalname: title, mimetype: "image/jpeg", buffer: PIXEL_PNG } }
- );
-
- const first = await upload("en.wikipedia.org-Russo-Japanese-War-1a2b3c4d.jpeg");
- const again = await upload("en.wikipedia.org-Russo-Japanese-War-1a2b3c4d.jpeg");
- await upload("en.wikipedia.org-Crimean-War-5e6f7a8b.jpeg");
-
- expect(again.body.url).toBe(first.body.url);
- expect((await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`)).body).toHaveLength(2);
- });
-
- 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.
- const { noteId } = await createTextNote(api, { title: "Bogus role target" });
-
- await api.post(
- `/api/notes/${noteId}/attachments/upload?role=viewConfig`,
- { file: { originalname: "pixel.png", mimetype: "image/png", buffer: PIXEL_PNG } }
- );
-
- const [ attachment ] = (await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`)).body;
- expect(attachment.role).toBe("image");
- });
-
it("reports a missing upload when no file is present", async () => {
const { noteId } = await createTextNote(api, { title: "No file target" });
diff --git a/packages/trilium-core/src/routes/api/attachments.ts b/packages/trilium-core/src/routes/api/attachments.ts
index 752eeaf65c..16f52fec7b 100644
--- a/packages/trilium-core/src/routes/api/attachments.ts
+++ b/packages/trilium-core/src/routes/api/attachments.ts
@@ -1,4 +1,4 @@
-import { ConvertAttachmentToNoteResponse, type ImageAttachmentRole, isAcceptedImageMime, isImageAttachmentRole } from "@triliumnext/commons";
+import { ConvertAttachmentToNoteResponse, isAcceptedImageMime } from "@triliumnext/commons";
import { ValidationError } from "../../errors";
import type { Request } from "express";
import type { File } from "../../services/import/common.js";
@@ -65,7 +65,9 @@ async function uploadAttachment(req: FileRequest<{ noteId: string }>) {
const buffer = wrapStringOrBuffer(file.buffer as string | Uint8Array);
if (isAcceptedImageMime(file.mimetype)) {
- const attachment = imageService.saveImageToAttachment(noteId, buffer, file.originalname, true, true, requestedImageRole(req));
+ // Always the user's own image: the pictures the app fetches for itself — a link preview's
+ // favicon and cover — are stored by the code that fetched them, never uploaded through here.
+ const attachment = imageService.saveImageToAttachment(noteId, buffer, file.originalname, true, true);
// The URL below is fetched the moment this answers — the editor puts it straight into the
// document as the source of an image. Answering before the bytes are stored hands it the
@@ -91,19 +93,6 @@ async function uploadAttachment(req: FileRequest<{ noteId: string }>) {
};
}
-/**
- * Which kind of picture the caller says it is uploading, defaulting to a plain image.
- *
- * Read from a fixed set rather than taken at its word: the role is what decides whether an
- * attachment is served, listed and cleaned up, so an arbitrary string from a request would be a way
- * to create attachments that no code path looks at again.
- */
-function requestedImageRole(req: FileRequest<{ noteId: string }>): ImageAttachmentRole {
- const requested = req.query?.role;
-
- return typeof requested === "string" && isImageAttachmentRole(requested) ? requested : "image";
-}
-
function renameAttachment(req: Request<{ attachmentId: string }>) {
const { title } = req.body;
const { attachmentId } = req.params;
diff --git a/packages/trilium-core/src/routes/api/image.spec.ts b/packages/trilium-core/src/routes/api/image.spec.ts
index 80f8c4a792..ea0703b2c4 100644
--- a/packages/trilium-core/src/routes/api/image.spec.ts
+++ b/packages/trilium-core/src/routes/api/image.spec.ts
@@ -215,13 +215,25 @@ describe("Image API (core)", () => {
expect(res.status).toBe(404);
});
- it("400s when the attachment role is not image", async () => {
+ it("400s when the attachment role is not a picture", async () => {
const attachmentId = await createAttachment({ role: "file", mime: "text/plain", content: "hi" });
const res = await api.get<string>(`/api/attachments/${attachmentId}/image/file.png`);
expect(res.status).toBe(400);
expect(res.headers["Content-Type"]).toBe("text/plain");
});
+ it("serves every picture role, not just the user's own images", async () => {
+ // A link preview's favicon and cover are pictures under their own roles; a route that
+ // knew only "image" would answer 400 and leave every preview showing a placeholder.
+ for (const role of [ "favicon", "coverImage" ]) {
+ const attachmentId = await createAttachment({ role, mime: "image/png", content: PNG_BYTES });
+ const res = await api.get(`/api/attachments/${attachmentId}/image/file.png`);
+
+ expect(res.status, role).toBe(200);
+ expect(Buffer.from(res.body as Buffer), role).toEqual(PNG_BYTES);
+ }
+ });
+
it("serves a real raster attachment image", async () => {
const attachmentId = await createAttachment({ mime: "image/png", content: PNG_BYTES });
const res = await api.get(`/api/attachments/${attachmentId}/image/file.png`);
diff --git a/packages/trilium-core/src/services/image.spec.ts b/packages/trilium-core/src/services/image.spec.ts
index e1efc71490..494ef7102b 100644
--- a/packages/trilium-core/src/services/image.spec.ts
+++ b/packages/trilium-core/src/services/image.spec.ts
@@ -165,6 +165,45 @@ describe("image service (real DB)", () => {
).toThrow();
});
+ it("reuses a deduplicated role's attachment of the same title rather than storing it twice", () => {
+ // A note that links a site many times, or pastes one URL twice, would otherwise carry a
+ // copy of that site's icon and that page's cover for every use.
+ const host = createTargetNote();
+ const store = (title: string, role: "favicon" | "coverImage") =>
+ getContext().init(() => imageService.saveImageToAttachment(host.noteId, fakeBuffer, title, false, false, role));
+
+ const first = store("example.com.ico", "favicon");
+ const again = store("example.com.ico", "favicon");
+ const otherSite = store("other.example.ico", "favicon");
+ const cover = store("example.com-page-1a2b3c4d.jpeg", "coverImage");
+
+ expect(again.attachmentId).toBe(first.attachmentId);
+ // A different site, and a different kind of picture, are different things.
+ expect(otherSite.attachmentId).not.toBe(first.attachmentId);
+ expect(cover.attachmentId).not.toBe(first.attachmentId);
+ });
+
+ it("stores the user's own images separately however they are named", () => {
+ // Two pictures the user gave one name are two pictures; collapsing them would lose one.
+ const host = createTargetNote();
+ const store = () =>
+ getContext().init(() => imageService.saveImageToAttachment(host.noteId, fakeBuffer, "photo.png", false));
+
+ expect(store().attachmentId).not.toBe(store().attachmentId);
+ });
+
+ it("keeps a long title whole for a deduplicated role, that being what identifies it", () => {
+ // Ordinary uploads collapse a title past 40 characters to "image"; doing that here
+ // would make every hostname past the limit share one icon.
+ const host = createTargetNote();
+ const longHost = `${"a-very-long-subdomain".repeat(3)}.example.com.ico`;
+
+ const stored = getContext().init(() =>
+ imageService.saveImageToAttachment(host.noteId, fakeBuffer, longHost, false, true, "favicon"));
+
+ expect(stored.title).toBe(longHost);
+ });
+
it("post-processes the note five seconds later, and lets it go quietly once deleted", () => {
const postProcessSpy = vi.spyOn(noteService, "asyncPostProcessContent").mockResolvedValue(undefined);
stubProcessImage({ ext: "png" });