Skip to content

Build your personal knowledge base with Trilium Notes

fix(attachments): a picture copied by hand belongs to whoever copied it

Elian Doranb5b9038111f8
diff --git a/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.ts
index 2c93afb154..34c3b6868c 100644
--- a/apps/server/src/services/notes.spec.ts
+++ b/apps/server/src/services/notes.spec.ts
@@ -466,6 +466,117 @@ describe("checkImageAttachments", () => {
expect(result.content).not.toContain("foreignAtt1");
});
+ /**
+ * Copies for real, so the role the copy ends up with is the one production put there, and
+ * hands the copy back to the test. Only the writing is stood in for: `setContent` and `save`
+ * reach blobs and the DB, which this spec has no room for.
+ */
+ function captureRealCopy(foreign: ReturnType<typeof buildNote>["getAttachments"] extends () => (infer A)[] ? A : never) {
+ const copies: typeof foreign[] = [];
+ const realCopy = foreign.copy.bind(foreign);
+ foreign.copy = () => {
+ const copy = realCopy();
+ copy.setContent = vi.fn();
+ copy.save = vi.fn();
+ copies.push(copy);
+ return copy;
+ };
+ foreign.getContent = () => Buffer.from("picture data");
+ return copies;
+ }
+
+ it("hands a preview's picture over as the reader's own when it is pasted as a plain image", () => {
+ // "Copy reference to clipboard" on a link preview's favicon puts a bare <img> on the
+ // clipboard. Carried into another note that way it is a picture someone placed, not a
+ // preview's any more — and keeping the role would leave it deduplicated by title against
+ // that note's own previews, denied OCR and compression, and filed under "System".
+ const source = buildNote({
+ title: "Source",
+ attachments: [{ id: "foreignFavicon", title: "example.com.ico", role: "favicon", mime: "image/x-icon" }]
+ });
+ const [ foreign ] = source.getAttachments();
+ const copies = captureRealCopy(foreign);
+
+ const target = buildNote({ title: "Target" });
+ target.getAttachments = () => [];
+ const getAttachments = vi.spyOn(becca, "getAttachments").mockReturnValue([ foreign ]);
+
+ try {
+ checkImageAttachments(target, `<img src="api/attachments/foreignFavicon/image/example.com.ico">`);
+
+ expect(copies).toHaveLength(1);
+ expect(copies[0].role).toBe("image");
+ } finally {
+ getAttachments.mockRestore();
+ }
+ });
+
+ it("keeps a preview's pictures its own when the whole preview is pasted", () => {
+ // The same copy, reached the other way: the pictures still belong to a preview in the new
+ // note, and demoting them would give every link to the site its own icon again.
+ const source = buildNote({
+ title: "Source",
+ attachments: [
+ { id: "foreignCover", title: "https://example.com", role: "coverImage", mime: "image/jpeg" },
+ { id: "foreignIcon", title: "example.com", role: "favicon", mime: "image/x-icon" }
+ ]
+ });
+ const [ cover, icon ] = source.getAttachments();
+ const coverCopies = captureRealCopy(cover);
+ const iconCopies = captureRealCopy(icon);
+
+ const target = buildNote({ title: "Target" });
+ target.getAttachments = () => [];
+ const getAttachments = vi.spyOn(becca, "getAttachments").mockReturnValue([ cover, icon ]);
+
+ try {
+ checkImageAttachments(
+ target,
+ `<section class="link-embed" data-url="https://example.com"`
+ + ` data-image="api/attachments/foreignCover/image/cover.jpg"`
+ + ` data-favicon="api/attachments/foreignIcon/image/example.com.ico"></section>`
+ );
+
+ expect([ ...coverCopies, ...iconCopies ].map((copy) => copy.role)).toStrictEqual([ "coverImage", "favicon" ]);
+ } finally {
+ getAttachments.mockRestore();
+ }
+ });
+
+ it("reuses an equivalent local picture under the role the copy would have taken", () => {
+ // The equivalent-attachment lookup matches on role, so it has to ask for the role the copy
+ // is going to land on. Asking for the foreign one would never match the note's own picture,
+ // and every save would copy the bytes again.
+ const source = buildNote({
+ title: "Source",
+ attachments: [{ id: "foreignIcon", title: "example.com.ico", role: "favicon", mime: "image/x-icon" }]
+ });
+ const [ foreign ] = source.getAttachments();
+ foreign.blobId = "sharedBlob";
+ const copies = captureRealCopy(foreign);
+
+ const target = buildNote({
+ title: "Target",
+ attachments: [{ id: "localPicture", title: "example.com.ico", role: "image", mime: "image/x-icon" }]
+ });
+ mockAttachmentSaves(target);
+ target.getAttachments()[0].blobId = "sharedBlob";
+
+ const getAttachments = vi.spyOn(becca, "getAttachments").mockReturnValue([ foreign ]);
+
+ try {
+ const { content } = checkImageAttachments(
+ target,
+ `<img src="api/attachments/foreignIcon/image/example.com.ico">`
+ );
+
+ expect(copies).toHaveLength(0);
+ expect(content).toContain("localPicture");
+ } finally {
+ getAttachments.mockRestore();
+ }
+ });
+
it("replaces foreign attachment IDs in markdown content", () => {
const note = buildNote({ title: "Test", type: "code", mime: "text/x-markdown" });
const foreignNote = buildNote({ title: "Foreign", attachments: [{ id: "foreignAtt2", title: "test.png", role: "image", mime: "image/png" }] });
diff --git a/packages/commons/src/lib/attachment_roles.spec.ts b/packages/commons/src/lib/attachment_roles.spec.ts
index 5366825056..aaf9e04e08 100644
--- a/packages/commons/src/lib/attachment_roles.spec.ts
+++ b/packages/commons/src/lib/attachment_roles.spec.ts
@@ -61,7 +61,7 @@ describe("attachmentRoleTraits", () => {
// The types already refuse a role that arrives without one; this says the same at runtime,
// for the shape the table is actually read with.
for (const [ role, traits ] of Object.entries(ATTACHMENT_ROLES)) {
- expect(Object.keys(traits).sort(), role).toStrictEqual([ "deduplicated", "embedded", "picture" ]);
+ expect(Object.keys(traits).sort(), role).toStrictEqual([ "copiedAs", "deduplicated", "embedded", "picture" ]);
}
});
@@ -74,6 +74,40 @@ describe("attachmentRoleTraits", () => {
});
});
+describe("copiedAs", () => {
+ it("hands a copy to whoever made it: a picture the app fetched becomes one the reader placed", () => {
+ // The point of the column. A link preview's pictures are the app's while they belong to the
+ // preview; carried into a note by hand they are a picture like any other, and keeping the
+ // role would leave them deduplicated by title against that note's own previews, denied OCR
+ // and compression, and filed under the half of the list nobody opens.
+ expect(ATTACHMENT_ROLES.favicon.copiedAs).toBe("image");
+ expect(ATTACHMENT_ROLES.coverImage.copiedAs).toBe("image");
+ });
+
+ it("leaves the roles a reader already owns as they are", () => {
+ expect(ATTACHMENT_ROLES.image.copiedAs).toBe("image");
+ expect(ATTACHMENT_ROLES.file.copiedAs).toBe("file");
+ });
+
+ it("hands over what the app kept for itself as a plain file", () => {
+ // None of these is reachable by copying today — nothing in a note's content refers to them —
+ // but the question has an answer all the same, and it is not "carry on managing yourself in
+ // a note that has no idea you exist".
+ expect(ATTACHMENT_ROLES.viewConfig.copiedAs).toBe("file");
+ expect(ATTACHMENT_ROLES.canvasLibraryItem.copiedAs).toBe("file");
+ expect(ATTACHMENT_ROLES.importSource.copiedAs).toBe("file");
+ });
+
+ it("only ever hands over something the reader can own", () => {
+ // A copy lands on a role that means "someone put this here" — never on another of the app's,
+ // which would only move the problem.
+ for (const [ role, traits ] of Object.entries(ATTACHMENT_ROLES)) {
+ expect([ "image", "file" ], role).toContain(traits.copiedAs);
+ expect(ATTACHMENT_ROLES[traits.copiedAs].picture, role).toBe(traits.picture);
+ }
+ });
+});
+
describe("isDeduplicatedAttachmentRole", () => {
it("deduplicates only what the app named itself", () => {
// A site's icon: one per site rather than one per link to it.
diff --git a/packages/commons/src/lib/attachment_roles.ts b/packages/commons/src/lib/attachment_roles.ts
index 6795f68d1b..f9ff11fea8 100644
--- a/packages/commons/src/lib/attachment_roles.ts
+++ b/packages/commons/src/lib/attachment_roles.ts
@@ -38,6 +38,20 @@ export interface AttachmentRoleTraits {
* leaving them to the cleanup would erase every one of them on the next save.
*/
embedded: boolean;
+ /**
+ * What a copy of this becomes when a person carries it into a note themselves.
+ *
+ * A role says who made the attachment and why, so a copy made by hand has a new answer: the
+ * pictures a link preview fetched are the app's while they belong to that preview, but pasted
+ * into a note as a picture they are one the reader placed, and nothing about them is the app's to
+ * manage any more. Keeping the role would leave the copy deduplicated by title against that
+ * note's own previews, denied the OCR and compression offered to a picture, and filed under the
+ * half of the attachment list nobody opens.
+ *
+ * Always one of the two roles that mean "someone put this here" — handing a copy to another of
+ * the app's roles would only move the problem. A picture stays a picture: see the spec.
+ */
+ copiedAs: "image" | "file";
}
/**
@@ -49,24 +63,25 @@ export interface AttachmentRoleTraits {
*/
export const ATTACHMENT_ROLES = {
/** A picture the user placed in the note. */
- image: { picture: true, deduplicated: false, embedded: true },
+ image: { picture: true, deduplicated: false, embedded: true, copiedAs: "image" },
/** A file the user attached to the note. */
- file: { picture: false, deduplicated: false, embedded: true },
+ file: { picture: false, deduplicated: false, embedded: true, copiedAs: "file" },
/**
* A link preview's two pictures, kept apart from `image` so they can be told from one the user
* chose. Both arrive already sized by the server (a 16x16 icon, a 256px thumbnail), so the
* compression inventory has nothing to gain from either and offering to recompress one is noise.
* They are embedded all the same: nothing else manages them, so deleting the preview has to be
- * what eventually takes them with it.
+ * what eventually takes them with it. Carried into a note by hand, though, they are pictures like
+ * any other — the preview they belonged to stayed behind.
*/
- favicon: { picture: true, deduplicated: true, embedded: true },
- coverImage: { picture: true, deduplicated: true, embedded: true },
+ favicon: { picture: true, deduplicated: true, embedded: true, copiedAs: "image" },
+ coverImage: { picture: true, deduplicated: true, embedded: true, copiedAs: "image" },
/** How a collection remembers the way it is being looked at, and a PDF where the reader had got to. */
- viewConfig: { picture: false, deduplicated: false, embedded: false },
+ viewConfig: { picture: false, deduplicated: false, embedded: false, copiedAs: "file" },
/** Shapes saved into an Excalidraw canvas's library. */
- canvasLibraryItem: { picture: false, deduplicated: false, embedded: false },
+ canvasLibraryItem: { picture: false, deduplicated: false, embedded: false, copiedAs: "file" },
/** The file an import was read from, kept so an import that went wrong can be looked at again. */
- importSource: { picture: false, deduplicated: false, embedded: false }
+ importSource: { picture: false, deduplicated: false, embedded: false, copiedAs: "file" }
} as const satisfies Record<string, AttachmentRoleTraits>;
/** A role the app itself creates. Arbitrary strings reach the same fields — see {@link ATTACHMENT_ROLES}. */
diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.ts
index 3bb9300f55..0f39e7a023 100644
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@ -1,4 +1,4 @@
-import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, isEmbeddedAttachmentRole, isImageAttachmentRole, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType } from "@triliumnext/commons";
+import { type AttachmentRow, attachmentRoleTraits, type AttributeRow, type BranchRow, dayjs, isEmbeddedAttachmentRole, isImageAttachmentRole, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType } from "@triliumnext/commons";
import { t } from "i18next";
import { parse as parseHtml } from "node-html-parser";
import url from "url";
@@ -447,6 +447,12 @@ export function checkImageAttachments(note: BNote, content: string) {
// embedded in the content (an image URL or attachment link).
const isCanvas = note.type === "canvas";
const foundAttachmentIds = new Set<string>();
+ /**
+ * Of those, the ones the content refers to as a link preview's own pictures rather than as a
+ * picture of its own. A copy of one of these is still a preview's, so it keeps its role; a copy
+ * reached any other way was put there by hand and takes the role that says so.
+ */
+ const previewPictureIds = new Set<string>();
const foundCanvasFileIds = isCanvas ? collectCanvasImageFileIds(content) : new Set<string>();
if (!isCanvas) {
@@ -454,28 +460,32 @@ export function checkImageAttachments(note: BNote, content: string) {
// Spreadsheet content is JSON storing inline images as bare `api/attachments/{id}/image/...`
// URLs (no `src="..."` wrapper), so it scans with the same loose pattern as Markdown.
- const patterns = (note.isMarkdown() || note.type === "spreadsheet")
+ const patterns: { pattern: RegExp, previewPicture?: boolean }[] = (note.isMarkdown() || note.type === "spreadsheet")
? [
// ![...](api/attachments/{id}/image/...) or similar markdown image syntax
- /api\/attachments\/([a-zA-Z0-9_]+)\/image/g,
+ { pattern: /api\/attachments\/([a-zA-Z0-9_]+)\/image/g },
// [...](#root/{noteId}?viewMode=attachments&attachmentId={id})
- /attachmentId=([a-zA-Z0-9_]+)/g
+ { pattern: /attachmentId=([a-zA-Z0-9_]+)/g }
]
: [
// <img src="api/attachments/{id}/image/...">
- /src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g,
+ { pattern: /src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g },
// Link previews reference both of their pictures from data attributes rather than
// from an <img>: the card image, and the favicon that an inline mention carries on
// its own. <section class="link-embed" data-image="api/attachments/{id}/image/..."
// data-favicon="api/attachments/{id}/image/...">
- /data-(?:image|favicon)="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g,
+ { pattern: /data-(?:image|favicon)="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g, previewPicture: true },
// <a href="...attachmentId={id}">
- /href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g
+ { pattern: /href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g }
];
- for (const pattern of patterns) {
+ for (const { pattern, previewPicture } of patterns) {
while ((match = pattern.exec(content))) {
- foundAttachmentIds.add(match[1]);
+ foundAttachmentIds.add(match[1]);
+
+ if (previewPicture) {
+ previewPictureIds.add(match[1]);
+ }
}
}
}
@@ -526,9 +536,21 @@ export function checkImageAttachments(note: BNote, content: string) {
const unknownAttachments = becca.getAttachments(unknownAttachmentIds);
for (const unknownAttachment of unknownAttachments) {
+ // A role says who made the attachment and why, so the copy's role is decided by how this note
+ // refers to it. Still a link preview's picture here — the whole preview having been pasted —
+ // and it stays the preview's. Reached any other way it is a picture or a file someone placed,
+ // and carrying the app's role over would leave the copy deduplicated against this note's own
+ // previews, denied the OCR and compression a picture is offered, and filed out of sight. A
+ // role we know nothing about is left alone: there is nothing better to say about it.
+ const copiedRole = previewPictureIds.has(unknownAttachment.attachmentId ?? "")
+ ? unknownAttachment.role
+ : attachmentRoleTraits(unknownAttachment.role)?.copiedAs ?? unknownAttachment.role;
+
// the attachment belongs to a different note (was copy-pasted). Attachments can be linked only from the note
// which owns it, so either find an existing attachment having the same content or make a copy.
- let localAttachment = note.getAttachments().find((att) => att.role === unknownAttachment.role && att.blobId === unknownAttachment.blobId);
+ // Matched on the role the copy would take, not the one it came with, or a picture this note
+ // already holds would never be recognised and every save would copy the bytes again.
+ let localAttachment = note.getAttachments().find((att) => att.role === copiedRole && att.blobId === unknownAttachment.blobId);
if (localAttachment) {
if (localAttachment.utcDateScheduledForErasureSince) {
@@ -543,6 +565,7 @@ export function checkImageAttachments(note: BNote, content: string) {
} else {
localAttachment = unknownAttachment.copy();
localAttachment.ownerId = note.noteId;
+ localAttachment.role = copiedRole;
localAttachment.setContent(unknownAttachment.getContent(), { forceSave: true });
ws.sendMessageToAllClients({ type: "toast", message: `Attachment '${localAttachment.title}' has been copied to note '${note.title}'.` });