Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(anytype import): store a bookmark card's pictures as attachments
Elian Doran3d04e4b95892
diff --git a/packages/trilium-core/src/services/import/anytype/content.ts b/packages/trilium-core/src/services/import/anytype/content.tsindex a57890ac3a..807ffe4de4 100644--- a/packages/trilium-core/src/services/import/anytype/content.ts+++ b/packages/trilium-core/src/services/import/anytype/content.ts@@ -441,10 +441,10 @@ function paletteValue(covering: AppliedMark[], type: string, palette: Record<str* open-graph-preview markup the Notion importer produces and CKEditor's LinkEmbed plugin round-trips. The* card's `url`, `title` and `description` map to `data-url` / `data-title` / `data-description`. The* favicon/preview are content-addressed file CIDs (`faviconHash`/`imageHash`), emitted as-is in- * `data-favicon` / `data-image` as placeholders — the importer resolves each to an inline base64 `data:` URI- * (the form Trilium natively stores a link-embed favicon/image in), or drops the attribute when the export- * has no bytes for it. Optional fields are only written when present. A card with no url (still fetching, or- * a broken export) is dropped.+ * `data-favicon` / `data-image` as placeholders — the importer saves each as an attachment of the note and+ * rewrites the attribute to point at it (the form Trilium stores a link-embed's pictures in), or drops the+ * attribute when the export has no usable bytes for it. Optional fields are only written when present. A+ * card with no url (still fetching, or a broken export) is dropped.*/export function renderBookmark(bookmark: NonNullable<AnytypeBlock["bookmark"]>): string {const url = (bookmark.url ?? "").trim();diff --git a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.tsindex 79a0888eb4..340f0993cb 100644--- a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts@@ -99,6 +99,22 @@ function fileObjectJson(cid: string, name: string, fileExt: string, fileMimeTypereturn JSON.stringify({ sbType: "FileObject", snapshot: { data: { details: { id: cid, name, fileExt, fileMimeType, source } } } });}+/**+ * A real icon directory of one entry. The importer asks the bytes what they are rather than taking+ * the export's word for it, so a placeholder needs bytes that genuinely are a picture.+ */+function icoBytes(): Buffer {+ const directory = Buffer.alloc(22);+ directory.writeUInt16LE(1, 2); // type: icon+ directory.writeUInt16LE(1, 4); // one entry+ directory.writeUInt8(16, 6); // width+ directory.writeUInt8(16, 7); // height+ directory.writeUInt32LE(4, 14); // payload length+ directory.writeUInt32LE(directory.length, 18); // where the payload starts++ return Buffer.concat([ directory, Buffer.from([ 0, 0, 0, 0 ]) ]);+}+/** A title-less "row" object whose content is its custom property values (keyed by relation key). */function memberObject(id: string, props: Record<string, unknown>): string {return JSON.stringify({@@ -137,10 +153,11 @@ describe("Anytype importer — integration", () => {expect(decodeUtf8(first?.getContent() ?? "")).toBe("<p>Hello world</p><p>Second paragraph</p>");});- it("keeps a bookmark block as a link-embed, inlining its favicon as a base64 data URI", async () => {+ it("keeps a bookmark block as a link-embed, storing its favicon as an attachment", async () => {// A page holding a bookmark card. The card's target is a separate `ot-bookmark` object (a non-page- // layout, so not imported); the card carries the url/title/description and a favicon file id (resolved- // from the export's filesObjects/files to an inline data URI, how Trilium natively stores a favicon).+ // layout, so not imported); the card carries the url/title/description and a favicon file id, which+ // is saved as an attachment of the note and referenced from the card — the shape a preview fetched+ // live is stored in, rather than base64 inside the note's HTML.const page = JSON.stringify({sbType: "Page",snapshot: {@@ -161,24 +178,65 @@ describe("Anytype importer — integration", () => {sbType: "Page",snapshot: { data: { blocks: [{ id: "bookmark-obj", childrenIds: [] }], details: { id: "bookmark-obj", name: "Trilium Notes", resolvedLayout: 11, source: "https://triliumnotes.org/" }, objectTypes: ["ot-bookmark"] } }});- const faviconBytes = Buffer.from([0x00, 0x01, 0x02, 0x03]);-const importRoot = await importAnytype({"objects/page1.pb.json": page,"objects/bookmark.pb.json": bookmarkObject,"filesObjects/fav.pb.json": fileObjectJson("fav-cid", "triliumnotes_org_icon", "ico", "image/x-icon", "files\\triliumnotes_org_icon.ico"),- "files/triliumnotes_org_icon.ico": faviconBytes+ "files/triliumnotes_org_icon.ico": icoBytes()});const children = importRoot.getChildNotes();expect(children.map((note) => note.title)).toEqual(["Links"]);- // The favicon file id has been resolved to an inline data URI (mime derived from the .ico name).++ // Under the role that says which of a card's two pictures it is, and titled after the site —+ // which is the key a second card for the same site reuses it by.+ const [ favicon ] = children[0]?.getAttachments() ?? [];+ expect(favicon).toMatchObject({ role: "favicon", title: "triliumnotes.org.ico" });+expect(decodeUtf8(children[0]?.getContent() ?? "")).toBe(- `<section class="link-embed" data-url="https://triliumnotes.org/" data-embed-type="opengraph" data-title="Trilium Notes" data-description="An open-source note-taking app." data-favicon="data:image/vnd.microsoft.icon;base64,${faviconBytes.toString("base64")}"></section>`+ `<section class="link-embed" data-url="https://triliumnotes.org/" data-embed-type="opengraph" data-title="Trilium Notes"`+ + ` data-description="An open-source note-taking app."`+ + ` data-favicon="api/attachments/${favicon?.attachmentId}/image/triliumnotes.org.ico"></section>`);});- it("leaves a card with no favicon/preview untouched, and falls back to a generic MIME for an unrecognized one", async () => {+ it("keeps one picture for a site linked by more than one card", async () => {+ // Two cards for the same site, each carrying its own copy of the icon — as an export does,+ // the files being content-addressed per object rather than shared.+ const page = JSON.stringify({+ sbType: "Page",+ snapshot: {+ data: {+ blocks: [+ { id: "page1", childrenIds: ["header", "one", "two"] },+ { id: "header", childrenIds: ["title"] },+ { id: "title", text: { text: "", style: "Title" } },+ { id: "one", bookmark: { url: "https://example.com/a", title: "A", faviconHash: "fav-a" } },+ { id: "two", bookmark: { url: "https://example.com/b", title: "B", faviconHash: "fav-b" } }+ ],+ details: { id: "page1", name: "Links", resolvedLayout: 0 }+ }+ }+ });++ const importRoot = await importAnytype({+ "objects/page1.pb.json": page,+ "filesObjects/a.pb.json": fileObjectJson("fav-a", "icon_a", "ico", "image/x-icon", "files\\icon_a.ico"),+ "filesObjects/b.pb.json": fileObjectJson("fav-b", "icon_b", "ico", "image/x-icon", "files\\icon_b.ico"),+ "files/icon_a.ico": icoBytes(),+ "files/icon_b.ico": icoBytes()+ });++ // One attachment, titled by the site rather than by either file, and both cards point at it.+ const attachments = importRoot.getChildNotes()[0]?.getAttachments() ?? [];+ expect(attachments.map((a) => a.title)).toEqual([ "example.com.ico" ]);++ const referenced = decodeUtf8(importRoot.getChildNotes()[0]?.getContent() ?? "").match(/data-favicon="[^"]+"/g) ?? [];+ expect(referenced).toHaveLength(2);+ expect(new Set(referenced).size).toBe(1);+ });++ it("leaves a card with no favicon/preview untouched, and drops one whose bytes are not a picture", async () => {const bookmarkPage = (bookmark: Record<string, unknown>) => JSON.stringify({sbType: "Page",snapshot: {@@ -200,15 +258,18 @@ describe("Anytype importer — integration", () => {'<section class="link-embed" data-url="https://example.com/" data-embed-type="opengraph" data-title="Example"></section>');- // A favicon whose file carries neither a known extension nor an exported MIME falls back to octet-stream.- const bytes = Buffer.from([0x09]);+ // Bytes that are not a picture: the attribute goes, rather than a card being given something+ // it cannot draw. The export's own metadata is not taken for it — the bytes are asked.const odd = await importAnytype({"objects/page1.pb.json": bookmarkPage({ url: "https://example.com/", faviconHash: "fav-cid" }),- "filesObjects/fav.pb.json": fileObjectJson("fav-cid", "icon", "", "", "files\\icon.weirdext"),- "files/icon.weirdext": bytes+ "filesObjects/fav.pb.json": fileObjectJson("fav-cid", "icon", "ico", "image/x-icon", "files\\icon.ico"),+ "files/icon.ico": Buffer.from([ 0x09 ])});- expect(decodeUtf8(odd.getChildNotes()[0]?.getContent() ?? ""))- .toContain(`data-favicon="data:application/octet-stream;base64,${bytes.toString("base64")}"`);++ expect(decodeUtf8(odd.getChildNotes()[0]?.getContent() ?? "")).toBe(+ '<section class="link-embed" data-url="https://example.com/" data-embed-type="opengraph"></section>'+ );+ expect(odd.getChildNotes()[0]?.getAttachments()).toHaveLength(0);});it("drops a bookmark's favicon placeholder when the export has no bytes for it", async () => {diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.tsindex bef0f58512..06bff51fca 100644--- a/packages/trilium-core/src/services/import/anytype/importer.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.ts@@ -27,6 +27,7 @@*/import { t } from "i18next";+import { imageExtensionForMime, linkPreviewImageName, safeHostname } from "@triliumnext/commons";import { parse } from "node-html-parser";import type BNote from "../../../becca/entities/bnote.js";@@ -36,7 +37,8 @@ import imageService from "../../image.js";import noteService from "../../notes.js";import protectedSessionService from "../../protected_session.js";import type TaskContext from "../../task_context.js";-import { decodeUtf8, encodeBase64 } from "../../utils/binary.js";+import { inspectImage, UNKNOWN_FORMAT } from "../../image_inspect.js";+import { decodeUtf8 } from "../../utils/binary.js";import date_utils from "../../utils/date.js";import { newEntityId } from "../../utils/index.js";import { basename } from "../../utils/path.js";@@ -462,10 +464,12 @@ function createFileMemberNote(parentNoteId: string, info: FileObjectInfo, bytes:* `section.link-embed`). For a file placeholder it looks the id up in the export's file metadata and bytes,* then saves the bytes as an attachment and rewrites the reference to point at it — an inline `role:"image"`* for an image, a `role:"file"` attachment reference-link for any other file type (matching the Notion- * importer). A bookmark's favicon/preview id is instead resolved to an inline base64 `data:` URI (the form- * Trilium natively stores a link-embed favicon/image in), never an attachment. A placeholder whose file is- * missing from the export (no metadata or bytes — e.g. a still-uploading file) is dropped (image /- * favicon / preview) or left as plain text (other file). Only re-saves the content when something changed.+ * importer). A bookmark's favicon/cover goes the same way, under the `favicon` / `coverImage` role and+ * titled after the site or page it belongs to, which is the shape a preview fetched live is stored in and+ * what lets a card that recurs across an export keep one picture rather than one per card. A placeholder+ * whose file is missing from the export (no metadata or bytes — e.g. a still-uploading file), or whose+ * bytes are not a picture at all, is dropped (image / favicon / cover) or left as plain text (other file).+ * Only re-saves the content when something changed.*/function applyInlineFiles(note: BNote, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>, shrinkImages: boolean) {const content = decodeUtf8(note.getContent());@@ -477,18 +481,21 @@ function applyInlineFiles(note: BNote, fileObjects: Map<string, FileObjectInfo>,const root = parse(content);let changed = false;- // A bookmark card's favicon/preview: resolve each file-id placeholder to an inline base64 data URI, or- // drop the attribute when the export has no bytes for it (rather than leaving a bare id that renders as a- // broken image; the client already falls back to a placeholder when the attribute is absent).+ // A bookmark card's favicon/cover: save each file-id placeholder as an attachment and point the+ // attribute at it, or drop the attribute when the export has no usable bytes for it (rather than+ // leaving a bare id that renders as a broken image; the client already falls back to a placeholder+ // when the attribute is absent).for (const section of root.querySelectorAll("section.link-embed")) {- for (const attr of ["data-favicon", "data-image"]) {+ const url = section.getAttribute("data-url") ?? "";++ for (const [ attr, role ] of [ [ "data-favicon", "favicon" ], [ "data-image", "coverImage" ] ] as const) {const targetId = section.getAttribute(attr);if (!targetId) {continue;}- const dataUri = inlineFileDataUri(targetId, fileObjects, files);- if (dataUri) {- section.setAttribute(attr, dataUri);+ const reference = saveBookmarkPicture(note, url, role, targetId, fileObjects, files, shrinkImages);+ if (reference) {+ section.setAttribute(attr, reference);} else {section.removeAttribute(attr);}@@ -555,15 +562,57 @@ function inlineFileBytes(targetId: string, fileObjects: Map<string, FileObjectInreturn info ? files.get(normalizePath(info.source)) : undefined;}-/** A file id resolved to an inline `data:<mime>;base64,<bytes>` URI (for a bookmark card's favicon/preview,- * stored inline rather than as an attachment), or undefined when the export has no bytes for it. */-function inlineFileDataUri(targetId: string, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>): string | undefined {+/**+ * Saves one of a bookmark card's two pictures as an attachment of the note the card sits in, and+ * answers with the URL that references it — or undefined when the export carries no usable bytes.+ *+ * The same shape a preview fetched live is stored in, so an imported card is indistinguishable from+ * one made here: the picture is a note attachment rather than base64 inside the note's HTML, under+ * the role that says which of the two it is, and titled after the thing it is a picture of. The+ * title is what a deduplicated role reuses an existing attachment by, so an export whose pages link+ * one site many times ends up with one icon rather than one per card.+ *+ * The bytes are asked what they are rather than the export's own metadata being taken for it, and+ * anything that is not a picture is refused — a card is not a place to put a PDF.+ */+function saveBookmarkPicture(+ note: BNote,+ url: string,+ role: "favicon" | "coverImage",+ targetId: string,+ fileObjects: Map<string, FileObjectInfo>,+ files: Map<string, Uint8Array>,+ shrinkImages: boolean+): string | undefined {const bytes = inlineFileBytes(targetId, fileObjects, files);+if (!bytes) {return undefined;}- const mime = fileObjects.get(targetId)?.mime || "application/octet-stream";- return `data:${mime};base64,${encodeBase64(bytes)}`;++ const { format, mime } = inspectImage(bytes);++ if (format === UNKNOWN_FORMAT) {+ return undefined;+ }++ const baseName = role === "favicon" ? safeHostname(url) : linkPreviewImageName(url);+ const { attachmentId, title } = imageService.saveImageToAttachment(+ note.noteId,+ bytes,+ `${baseName}.${imageExtensionForMime(mime)}`,+ // An icon has nothing to gain from being put through the compression pipeline — it is a few+ // KB of flat colour already, and far below any size it would be scaled to. A cover may be a+ // full-size social image, so it follows whatever the import was told to do with pictures.+ role === "coverImage" && shrinkImages,+ // The title is the key the attachment is reused by; shortening it would have every site+ // past the length limit share one picture.+ false,+ role+ );++ /* v8 ignore next -- saveImageToAttachment always returns the id of the attachment it just created */+ return attachmentId ? `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}` : undefined;}/**diff --git a/packages/trilium-core/src/services/import/anytype/model.ts b/packages/trilium-core/src/services/import/anytype/model.tsindex 9e1ef8982c..5c5fd7eb14 100644--- a/packages/trilium-core/src/services/import/anytype/model.ts+++ b/packages/trilium-core/src/services/import/anytype/model.ts@@ -79,8 +79,8 @@ export interface AnytypeBlock {};/** A "bookmark" block — Anytype's web-link card. It carries the target site's `url`, `title` and* `description` inline (fetched by Anytype when the card was created); `faviconHash`/`imageHash` are the- * CIDs of the fetched icon/preview `FileObject`s (content-addressed, not URLs — the importer resolves them- * to inline base64 `data:` URIs), and `targetObjectId` is the separate `ot-bookmark` object the card+ * CIDs of the fetched icon/preview `FileObject`s (content-addressed, not URLs — the importer saves each+ * as an attachment of the note), and `targetObjectId` is the separate `ot-bookmark` object the card* mirrors (a non-page layout, so not imported). Rendered as a Trilium link-embed (open-graph preview),* like the Notion importer's bookmark cards. */bookmark?: {