Skip to content

Build your personal knowledge base with Trilium Notes

refactor(link-preview): store pictures through core, drop the server-only inspectors

Elian Doran02c832003c2a
diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.ts
index 80dd8b29e1..8e1b348c76 100644
--- a/apps/server/src/routes/api/link_embed.spec.ts
+++ b/apps/server/src/routes/api/link_embed.spec.ts
@@ -1,5 +1,6 @@
import { extractYouTubeVideoId } from "@triliumnext/commons";
import { ValidationError } from "@triliumnext/core";
+import imageService from "@triliumnext/core/src/services/image.js";
import type { Request } from "express";
import { Jimp } from "jimp";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -15,34 +16,36 @@ vi.mock("../../services/safe_fetch.js", () => ({
const saveImageToAttachment = vi.hoisted(() => vi.fn());
const awaitImageWrite = vi.hoisted(() => vi.fn(async () => {}));
+import linkEmbedRoute from "./link_embed.js";
+
+let attachmentCounter = 0;
+
/**
* 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.
+ *
+ * Spied on the singleton rather than mocked as a module: the storing itself lives in core now, and
+ * core reaches its image service by a relative import that a mock of the package barrel would never
+ * intercept.
*/
-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) => ({
+ saveImageToAttachment.mockImplementation((_noteId: string, _bytes: Uint8Array, fileName: string) => ({
attachmentId: `att${++attachmentCounter}`,
title: fileName
}));
+
+ vi.spyOn(imageService, "saveImageToAttachment").mockImplementation(saveImageToAttachment);
+ vi.spyOn(imageService, "awaitImageWrite").mockImplementation(awaitImageWrite);
});
/** 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;
+ return call ? { buffer: Buffer.from(call[1] as Uint8Array), fileName: call[2] as string } : undefined;
}
function oneShotReader(bytes: Buffer) {
diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.ts
index 6a4106a90b..cc58bd41ce 100644
--- a/apps/server/src/routes/api/link_embed.ts
+++ b/apps/server/src/routes/api/link_embed.ts
@@ -1,20 +1,19 @@
import {
extractYouTubeVideoId,
type ImageAttachmentRole,
- imageExtensionForMime,
type LinkEmbedMetadata,
linkPreviewImageName,
safeHostname
} from "@triliumnext/commons";
import { getLog, imageService, ValidationError } from "@triliumnext/core";
import { trimIcoToSmallestEntry } from "@triliumnext/core/src/services/ico.js";
+import { storePictureBytes } from "@triliumnext/core/src/services/image_download.js";
+import { inspectImage, UNKNOWN_FORMAT } from "@triliumnext/core/src/services/image_inspect.js";
import { findPageDescription } from "@triliumnext/core/src/services/page_description.js";
import type { Request } from "express";
-import isSvg from "is-svg";
import { Jimp } from "jimp";
import { parse } from "node-html-parser";
-import { getImageTypeFromBuffer } from "../../services/image_codec.js";
import { safeFetch, validateUrl } from "../../services/safe_fetch.js";
const MAX_RESPONSE_SIZE = 512 * 1024; // 512KB
@@ -98,7 +97,7 @@ async function readResponseText(response: Response, maxBytes: number): Promise<s
* advertises the size, and while streaming, when it does not.
* Returns undefined if the download fails or the resource is too large.
*/
-async function downloadBinary(url: string, maxBytes: number, defaultContentType: string): Promise<{ buffer: Buffer; contentType: string } | undefined> {
+async function downloadBinary(url: string, maxBytes: number, defaultContentType: string): Promise<{ bytes: Uint8Array; contentType: string } | undefined> {
try {
const response = await safeFetch(url);
@@ -129,16 +128,28 @@ async function downloadBinary(url: string, maxBytes: number, defaultContentType:
chunks.push(value);
}
- return { buffer: Buffer.concat(chunks), contentType };
+ return { bytes: concatChunks(chunks, bytesRead), contentType };
} catch {
return undefined;
}
}
+/** Joins the pieces a streamed body arrived in into the single buffer the rest of the code wants. */
+function concatChunks(chunks: Uint8Array[], totalLength: number): Uint8Array {
+ const joined = new Uint8Array(totalLength);
+ let offset = 0;
+
+ for (const chunk of chunks) {
+ joined.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+
+ return joined;
+}
+
/** A picture that has been fetched and identified, but not yet stored anywhere. */
interface DownloadedPicture {
- buffer: Buffer;
- mime: string;
+ bytes: Uint8Array;
}
/**
@@ -174,18 +185,17 @@ async function storePicture(
return undefined;
}
- const fileName = `${baseName}.${imageExtensionForMime(picture.mime)}`;
- const attachment = imageService.saveImageToAttachment(noteId, picture.buffer, fileName, false, false, role);
+ const stored = storePictureBytes(noteId, picture.bytes, { role, title: baseName, shrink: false });
- if (!attachment.attachmentId) {
+ if (!stored) {
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);
+ await imageService.awaitImageWrite(stored.attachmentId);
- return `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}`;
+ return stored.url;
}
/**
@@ -203,25 +213,19 @@ async function storePictures(noteId: string, url: string, fetched: FetchedPrevie
}
/**
- * The media type to name a downloaded picture by, read from its own bytes, or undefined when the
- * bytes are not a picture at all.
+ * Bytes that really are a picture, or nothing.
*
* 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: it decides the
- * extension the attachment is titled with and the type the picture is later served under.
+ * `application/octet-stream` or `text/plain`, and the answer is not decoration: what a picture is
+ * decides the extension its attachment is titled with and the type it is later served under, which
+ * is why {@link storePictureBytes} reads it off the bytes again at the moment it stores them.
*
- * 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.
+ * Asking here as well is what lets a candidate be rejected while there are still others to try: an
+ * HTML error page served where an icon should be has to fail now, so the next `<link rel="icon">`
+ * gets its turn, rather than at store time when the search is already over.
*/
-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;
+function asPicture(bytes: Uint8Array): DownloadedPicture | undefined {
+ return inspectImage(bytes).format === UNKNOWN_FORMAT ? undefined : { bytes };
}
/**
@@ -236,12 +240,11 @@ async function downloadFavicon(faviconUrl: string): Promise<DownloadedPicture |
}
// An icon directory gives up the sizes nothing will look at; anything else is kept as it came.
- const trimmed = trimIcoToSmallestEntry(downloaded.buffer, FAVICON_TARGET_EDGE);
- const bytes = trimmed ? Buffer.from(trimmed) : downloaded.buffer;
+ const bytes = trimIcoToSmallestEntry(downloaded.bytes, FAVICON_TARGET_EDGE) ?? downloaded.bytes;
// The ceiling is on what is kept, not on what arrived: a file that is one large picture has
// nothing to give up, and is the case this refuses.
- return bytes.byteLength <= MAX_FAVICON_SIZE ? await asPicture(bytes) : undefined;
+ return bytes.byteLength <= MAX_FAVICON_SIZE ? asPicture(bytes) : undefined;
}
/**
@@ -266,18 +269,18 @@ async function downloadPreviewImage(imageUrl: string, minSourceDimension = 0): P
const downloaded = await downloadBinary(imageUrl, MAX_IMAGE_DOWNLOAD_SIZE, "image/jpeg");
if (!downloaded) return undefined;
- const { buffer, contentType } = downloaded;
- const isSmallEnoughToKeepVerbatim = buffer.byteLength <= MAX_VERBATIM_IMAGE_SIZE;
+ const { bytes, contentType } = downloaded;
+ const isSmallEnoughToKeepVerbatim = bytes.byteLength <= MAX_VERBATIM_IMAGE_SIZE;
// An SVG scales natively, so it is kept as-is rather than rasterised (Jimp cannot read it anyway),
- // 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 ? { buffer, mime: "image/svg+xml" } : undefined;
+ // and it satisfies any minimum dimension by definition. The sniff reads the opening bytes only,
+ // so it costs the same whatever the file weighs.
+ if (contentType.includes("svg") || inspectImage(bytes).format === "svg") {
+ return isSmallEnoughToKeepVerbatim ? { bytes } : undefined;
}
try {
- const image = await Jimp.read(buffer);
+ const image = await Jimp.read(Buffer.from(bytes));
if (Math.max(image.bitmap.width, image.bitmap.height) < minSourceDimension) {
return undefined;
@@ -291,8 +294,8 @@ async function downloadPreviewImage(imageUrl: string, minSourceDimension = 0): P
// 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()
- ? { 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" };
+ ? { bytes: new Uint8Array(await image.getBuffer("image/png")) }
+ : { bytes: new Uint8Array(await image.getBuffer("image/jpeg", { quality: IMAGE_JPEG_QUALITY })) };
} 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
@@ -305,7 +308,7 @@ async function downloadPreviewImage(imageUrl: string, minSourceDimension = 0): P
// match a log line against the paste that caused it.
getLog().info(`Could not decode a link preview image: ${e}`);
- return isSmallEnoughToKeepVerbatim && !minSourceDimension ? await asPicture(buffer) : undefined;
+ return isSmallEnoughToKeepVerbatim && !minSourceDimension ? asPicture(bytes) : undefined;
}
}
diff --git a/packages/trilium-core/src/services/image_download.ts b/packages/trilium-core/src/services/image_download.ts
index 0c510859e9..6d30de9729 100644
--- a/packages/trilium-core/src/services/image_download.ts
+++ b/packages/trilium-core/src/services/image_download.ts
@@ -35,6 +35,18 @@ import { decodeBase64 } from "./utils/binary.js";
import { quoteRegex, unescapeHtml } from "./utils/index.js";
import { basename } from "./utils/path.js";
+/** A picture that has been stored, and the two ways the rest of the code refers to it. */
+export interface StoredPicture {
+ /** The `api/attachments/...` address the note references the picture by. */
+ url: string;
+ /**
+ * The attachment now holding it, for a caller that has to know when the bytes are readable —
+ * `saveImageToAttachment` returns before the write lands. Anything that hands the URL straight
+ * to a client should pass this to {@link imageService.awaitImageWrite} first.
+ */
+ attachmentId: string;
+}
+
/**
* Keeps a picture's bytes as an attachment of `noteId`, answering with the URL that references it —
* or nothing when the bytes are not a picture at all.
@@ -42,11 +54,11 @@ import { basename } from "./utils/path.js";
* The bytes are asked what they are rather than the address, the server or the `data:` prefix being
* taken for it, so a 404 page served where a picture should be is refused rather than stored.
*/
-function storePictureBytes(
+export function storePictureBytes(
noteId: string,
bytes: Uint8Array,
{ role, title, shrink }: { role: ImageAttachmentRole; title: string; shrink: boolean }
-): string | undefined {
+): StoredPicture | undefined {
const { format, mime } = inspectImage(bytes);
if (format === UNKNOWN_FORMAT) {
@@ -64,7 +76,10 @@ function storePictureBytes(
);
return attachment.attachmentId
- ? `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}`
+ ? {
+ url: `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}`,
+ attachmentId: attachment.attachmentId
+ }
: undefined;
}
@@ -93,7 +108,7 @@ export async function downloadPictureToAttachment(
try {
const bytes = new Uint8Array(await request.getImage(pictureUrl));
- return storePictureBytes(noteId, bytes, { role, title, shrink });
+ return storePictureBytes(noteId, bytes, { role, title, shrink })?.url;
} 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.
@@ -392,7 +407,7 @@ function storeInlinePicture(
// The picture was sized by whoever made the preview — ours are stored at an icon's and a
// thumbnail's size already — so this only moves bytes, and recompressing them would be a
// second lossy pass over a picture that has had one.
- return storePictureBytes(noteId, decodeBase64(inline[1]), { role, title, shrink: false });
+ return storePictureBytes(noteId, decodeBase64(inline[1]), { role, title, shrink: false })?.url;
} catch (e: unknown) {
getLog().info(`Could not store an inline preview picture of note '${noteId}': ${e}`);
return undefined;
diff --git a/packages/trilium-core/src/services/page_description.ts b/packages/trilium-core/src/services/page_description.ts
index 12c45899b9..81fae1ee55 100644
--- a/packages/trilium-core/src/services/page_description.ts
+++ b/packages/trilium-core/src/services/page_description.ts
@@ -1,5 +1,3 @@
-import type { HTMLElement } from "node-html-parser";
-
/**
* A description read out of a page's own text, for a page that publishes none of itself.
*
@@ -11,6 +9,23 @@ import type { HTMLElement } from "node-html-parser";
* always preferred to anything found here.
*/
+/**
+ * The part of a parsed document this reads.
+ *
+ * Described structurally rather than as node-html-parser's own `HTMLElement`, so that a caller is
+ * not obliged to hold the very copy of the parser core resolves. A monorepo routinely ends up with
+ * two, and two copies of the same parser are two nominally different types — which has nothing to
+ * do with whether the tree can be read, and is not a constraint core has any business imposing on
+ * the app that parsed the page.
+ */
+export interface PageElement {
+ textContent: string;
+ rawTagName?: string | null;
+ parentNode: PageElement | null;
+ querySelector(selector: string): PageElement | null;
+ querySelectorAll(selector: string): PageElement[];
+}
+
/** Below this a paragraph is a caption, a byline or a stray line of chrome rather than a summary. */
const MIN_LENGTH = 80;
/** What is kept. This ends up in the note's HTML, so it is bounded rather than left to the page. */
@@ -45,7 +60,7 @@ const IGNORED_ANCESTORS = new Set([
"nav", "aside", "header", "footer", "form", "figure", "figcaption", "table", "script", "style", "noscript", "template"
]);
-export function findPageDescription(document: HTMLElement): string | undefined {
+export function findPageDescription(document: PageElement): string | undefined {
for (const scope of [ ...CONTENT_SCOPES.map((selector) => document.querySelector(selector)), document ]) {
const summary = firstSummaryParagraph(scope);
@@ -57,7 +72,7 @@ export function findPageDescription(document: HTMLElement): string | undefined {
return undefined;
}
-function firstSummaryParagraph(scope: HTMLElement | null): string | undefined {
+function firstSummaryParagraph(scope: PageElement | null): string | undefined {
for (const paragraph of scope?.querySelectorAll("p") ?? []) {
const text = collapseWhitespace(paragraph.textContent);
@@ -75,7 +90,7 @@ function collapseWhitespace(text: string): string {
return text.replace(/\s+/g, " ").trim();
}
-function hasIgnoredAncestor(element: HTMLElement): boolean {
+function hasIgnoredAncestor(element: PageElement): boolean {
for (let node = element.parentNode; node; node = node.parentNode) {
if (IGNORED_ANCESTORS.has(node.rawTagName?.toLowerCase() ?? "")) {
return true;
@@ -89,7 +104,7 @@ function hasIgnoredAncestor(element: HTMLElement): boolean {
* A cookie notice, a row of breadcrumbs or a footer of policy links can all be long enough to pass
* for a summary. What they are not is prose: nearly every word in them is a link.
*/
-function isMostlyLinks(paragraph: HTMLElement, text: string): boolean {
+function isMostlyLinks(paragraph: PageElement, text: string): boolean {
const linked = paragraph.querySelectorAll("a")
.reduce((total, anchor) => total + collapseWhitespace(anchor.textContent).length, 0);