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
fix(export): name an exported image after its mime, not its title
Elian Doran98b6a682e082
diff --git a/apps/client/src/services/image_upload.spec.ts b/apps/client/src/services/image_upload.spec.tsindex 5abf518c62..72f38608ce 100644--- a/apps/client/src/services/image_upload.spec.ts+++ b/apps/client/src/services/image_upload.spec.ts@@ -10,10 +10,11 @@ const serverUpload = vi.mocked(server.upload);describe("parseImageDataUrl", () => {it("splits a base64 data URL into its mime, raw base64 and extension", () => {expect(parseImageDataUrl("data:image/png;base64,AAAA")).toEqual({ mime: "image/png", base64: "AAAA", ext: "png" });- expect(parseImageDataUrl("data:image/jpeg;base64,BBBB")?.ext).toBe("jpeg");});it("names a format the way people write it", () => {+ // ".jpg", not the ".jpeg" its subtype reads as — the same name a JPEG gets everywhere else.+ expect(parseImageDataUrl("data:image/jpeg;base64,BBBB")?.ext).toBe("jpg");expect(parseImageDataUrl("data:image/svg+xml;base64,Q0M=")?.ext).toBe("svg");// A favicon used to be stored as "example.com.xicon", the subtype having had its// punctuation stripped out rather than being recognised.diff --git a/packages/commons/src/lib/image_mimes.spec.ts b/packages/commons/src/lib/image_mimes.spec.tsindex 83e00a5de7..ab069e5ffe 100644--- a/packages/commons/src/lib/image_mimes.spec.ts+++ b/packages/commons/src/lib/image_mimes.spec.ts@@ -38,9 +38,17 @@ describe("imageExtensionForMime", () => {expect(imageExtensionForMime("image/svg+xml")).toBe("svg");});+ it("settles on one name for a JPEG, whichever of its two media types it arrived as", () => {+ // The format is spelled two ways on each side, and a picture converted to it is named by+ // its media type alone — the title it was uploaded under describes the format it used to+ // be. Answering ".jpeg" for one spelling and ".jpg" for the other would make that renaming+ // depend on which spelling happened to be stored.+ expect(imageExtensionForMime("image/jpeg")).toBe("jpg");+ expect(imageExtensionForMime("image/jpg")).toBe("jpg");+ });+it("takes the subtype where the subtype is the name", () => {expect(imageExtensionForMime("image/png")).toBe("png");- expect(imageExtensionForMime("image/jpeg")).toBe("jpeg");expect(imageExtensionForMime("image/webp")).toBe("webp");expect(imageExtensionForMime("image/avif")).toBe("avif");expect(imageExtensionForMime("image/bmp")).toBe("bmp");@@ -66,6 +74,11 @@ describe("imageMimeForExtension", () => {// Two media types share ".ico"; the one a reader will recognise wins.expect(imageMimeForExtension("ico")).toBe("image/x-icon");expect(imageMimeForExtension("svg")).toBe("image/svg+xml");+ // Both spellings of a JPEG resolve to the registered one. `image/jpg` is a thing clients+ // send, not a thing to store — reaching it from a ".jpg" file is how it used to end up in+ // the database, and from there in an export's file names.+ expect(imageMimeForExtension("jpg")).toBe("image/jpeg");+ expect(imageMimeForExtension("jpeg")).toBe("image/jpeg");});it("builds the media type from the extension otherwise", () => {diff --git a/packages/commons/src/lib/image_mimes.ts b/packages/commons/src/lib/image_mimes.tsindex 5dd3c156ca..75d6058df8 100644--- a/packages/commons/src/lib/image_mimes.ts+++ b/packages/commons/src/lib/image_mimes.ts@@ -64,8 +64,16 @@ export const IMAGE_UPLOAD_SUBTYPES: readonly string[] = IMAGE_MIMES.map((mime) =* `image/png` is `.png`. These are the ones where deriving it that way produces something nobody* has ever seen — an icon written `.xicon`, an SVG written `.svgxml` — because the subtype carries* a prefix or a suffix that is not part of the name anyone uses for the format.+ *+ * JPEG is here for a second reason: the format has two spellings on each side, and picking one of+ * each is what lets the two directions agree. `.jpg` is the name overwhelmingly written, and+ * `image/jpeg` is the only registered media type of the two — `image/jpg` is a thing clients send,+ * not a thing to store. Without this entry the reverse lookup builds `image/jpg` out of a `.jpg`+ * file and puts an unregistered media type in the database, which every reader downstream then+ * needs its own special case for.*/const IMAGE_EXTENSION_OVERRIDES: Record<string, string> = {+ "image/jpeg": "jpg","image/svg+xml": "svg","image/x-icon": "ico","image/vnd.microsoft.icon": "ico"diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.tsindex 5d1ca9a34c..933a3a7c71 100644--- a/packages/trilium-core/src/services/export/zip.spec.ts+++ b/packages/trilium-core/src/services/export/zip.spec.ts@@ -305,6 +305,31 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {expect(entries[attFileName]).toBeDefined();});+ it("names a converted image after its mime, not after the title it was uploaded under", async () => {+ // Uploading a PNG with compression on stores JPEG bytes under the name the upload+ // arrived with: the mime follows the conversion, the title deliberately does not.+ // The export is the last point at which the file name can still describe the bytes.+ //+ // This is the shape of the 51 mislabelled files in docs/User Guide — JPEGs written+ // to a .png name, each one recorded as image/jpg in the meta beside it.+ const { note } = createNote("root", { title: "ConvertedImageHost", content: "<p>host</p>" });+ const jpegBytes = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46]);+ getContext().init(() =>+ note.saveAttachment({ role: "image", mime: "image/jpg", title: "image.png", content: jpegBytes })+ );+ const branch = note.getParentBranches()[0];++ const { entries } = await exportSubtree(branch, "markdown");+ const rootMeta = parseMeta(entries).files[0];++ const attFileName = (rootMeta.attachments ?? [])[0]?.dataFileName ?? "";+ expect(attFileName).toMatch(/\.jpe?g$/);+ expect(attFileName).not.toMatch(/\.png$/);+ // The renamed file is the one actually written, and its bytes are the JPEG's.+ expect(entries[attFileName]).toBeDefined();+ expect(Buffer.compare(entries[attFileName], jpegBytes)).toBe(0);+ });+it("round-trips binary attachment content byte-for-byte", async () => {const { note } = createNote("root", { title: "BinaryAttachHost", content: "<p>host</p>" });// Bytes that are not valid UTF-8 (0x00, 0xFF, lone 0x80 continuation byte)diff --git a/packages/trilium-core/src/services/export/zip/abstract_provider.spec.ts b/packages/trilium-core/src/services/export/zip/abstract_provider.spec.tsindex d93fe9be17..076a66380e 100644--- a/packages/trilium-core/src/services/export/zip/abstract_provider.spec.ts+++ b/packages/trilium-core/src/services/export/zip/abstract_provider.spec.ts@@ -89,15 +89,50 @@ describe("ZipExportProvider", () => {expect(provider.mapExtension("file", "application/json", "", "html")).toBe("json");});- it("preserves an existing extension (returns null) ahead of jpg/mermaid/fallback handling", () => {- // existingExtension is checked before the jpg/mermaid special cases,- // so a set extension short-circuits even for those mimes.+ it("preserves an existing extension (returns null) ahead of mermaid/fallback handling", () => {+ // existingExtension is checked before the mermaid special case, so a set extension+ // short-circuits even for that mime.expect(provider.mapExtension("image", "image/png", ".png", "html")).toBeNull();expect(provider.mapExtension("image", "image/jpg", ".jpeg", "html")).toBeNull();expect(provider.mapExtension("code", "text/mermaid", ".mmd", "html")).toBeNull();});- it("normalises image/jpg and text/mermaid special cases when no extension exists", () => {+ it("names an image from its mime where the existing extension contradicts it", () => {+ // An image converted on upload keeps the title it arrived under — attachments are+ // deliberately never renamed, since a canvas addresses its images by title — while+ // its mime follows the bytes. The file name is the only thing left that can still+ // describe them, so where the two disagree the mime is the one that saw the bytes.+ //+ // Trusting the title instead is what put 51 JPEGs under a .png name in+ // docs/User Guide, every one of them recorded as image/jpg in !!!meta.json.+ expect(provider.mapExtension("image", "image/jpeg", ".png", "markdown")).toBe("jpg");+ expect(provider.mapExtension("image", "image/jpg", ".png", "markdown")).toBe("jpg");+ expect(provider.mapExtension("image", "image/png", ".jpg", "html")).toBe("png");+ expect(provider.mapExtension("image", "image/webp", ".png", "html")).toBe("webp");+ expect(provider.mapExtension("image", "image/gif", ".PNG", "html")).toBe("gif");+ });++ it("keeps an extension that already names the mime's format, whatever its spelling", () => {+ // Only a genuine disagreement is worth renaming over: correcting ".jpeg" to ".jpg"+ // churns file names across an export for no gain, and the case of an extension+ // carries no meaning at all.+ expect(provider.mapExtension("image", "image/jpeg", ".jpg", "html")).toBeNull();+ expect(provider.mapExtension("image", "image/jpg", ".jpeg", "html")).toBeNull();+ expect(provider.mapExtension("image", "image/png", ".PNG", "html")).toBeNull();+ expect(provider.mapExtension("image", "image/svg+xml", ".svg", "html")).toBeNull();+ expect(provider.mapExtension("image", "image/x-icon", ".ico", "html")).toBeNull();+ });++ it("leaves a non-image extension alone, having nothing better to offer than the title", () => {+ // The correction is scoped to pictures, where the mime is authoritative about the+ // encoding. Elsewhere the title is usually the more informative of the two: a+ // mermaid source is better named .mmd than the .txt its mime maps to.+ expect(provider.mapExtension("code", "text/mermaid", ".mmd", "html")).toBeNull();+ expect(provider.mapExtension("file", "application/pdf", ".bak", "html")).toBeNull();+ expect(provider.mapExtension("file", "application/totally-unknown", ".bin", "html")).toBeNull();+ });++ it("reads a media type however it was written when no extension exists", () => {expect(provider.mapExtension("image", "image/jpg", "", "html")).toBe("jpg");expect(provider.mapExtension("image", " IMAGE/JPG ", "", "html")).toBe("jpg");expect(provider.mapExtension("code", "text/mermaid", "", "html")).toBe("txt");diff --git a/packages/trilium-core/src/services/export/zip/abstract_provider.ts b/packages/trilium-core/src/services/export/zip/abstract_provider.tsindex ce20d1886a..3aa7fd06af 100644--- a/packages/trilium-core/src/services/export/zip/abstract_provider.ts+++ b/packages/trilium-core/src/services/export/zip/abstract_provider.ts@@ -1,4 +1,4 @@-import { NoteType } from "@triliumnext/commons";+import { imageExtensionForMime, imageMimeForExtension, isAcceptedImageMime, NoteType } from "@triliumnext/commons";import mimeTypes from "mime-types";import type BBranch from "../../../becca/entities/bbranch.js";@@ -74,13 +74,33 @@ export abstract class ZipExportProvider {return "js";} else if (type === "canvas" || mime === "application/json") {return "json";- } else if (existingExtension.length > 0) {- // if the page already has an extension, then we'll just keep it+ }++ const pictureExtension = pictureExtensionFor(mime);++ if (pictureExtension) {+ // A picture is named after its media type rather than after its title, that being the+ // only way round which survives the upload having converted it. An image compressed+ // from PNG to JPEG keeps the title it arrived under — an attachment is never renamed,+ // a canvas addressing its images by title being the reason — while its mime follows+ // the new bytes. Take the title's word for it and a JPEG is written to a `.png` name,+ // which every reader downstream then believes.+ //+ // Only a real disagreement is worth renaming over: `.jpg` and `.jpeg` are one format+ // under either spelling of the media type, and the case of an extension means nothing.+ const titleExtension = existingExtension && pictureExtensionFor(imageMimeForExtension(existingExtension));++ return titleExtension === pictureExtension ? null : pictureExtension;+ }++ if (existingExtension.length > 0) {+ // Outside pictures the title tends to be the better informed of the two, so it keeps+ // the last word: a mermaid source is named `.mmd` far more usefully than the `.txt`+ // its media type maps to.return null;}- if (mime?.toLowerCase()?.trim() === "image/jpg") {- return "jpg";- } else if (mime?.toLowerCase()?.trim() === "text/mermaid") {++ if (mime?.toLowerCase()?.trim() === "text/mermaid") {return "txt";}return mapCodeMimeToExtension(mime) || mimeTypes.extension(mime) || "dat";@@ -89,3 +109,15 @@ export abstract class ZipExportProvider {}}++/**+ * The extension a picture of this media type is written with, or null where it is not a picture.+ *+ * Trims and lowercases first, so the reading survives a media type stored untidily, and answers+ * for one spelling of a format exactly as it does for the other.+ */+function pictureExtensionFor(mime: string): string | null {+ const normalized = mime?.trim().toLowerCase() ?? "";++ return isAcceptedImageMime(normalized) ? imageExtensionForMime(normalized) : null;+}diff --git a/packages/trilium-core/src/services/image.spec.ts b/packages/trilium-core/src/services/image.spec.tsindex 494ef7102b..ce8103c6e0 100644--- a/packages/trilium-core/src/services/image.spec.ts+++ b/packages/trilium-core/src/services/image.spec.ts@@ -1,5 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";+import { imageMimeForExtension } from "@triliumnext/commons";+import becca from "../becca/becca.js";import type BNote from "../becca/entities/bnote.js";import { getContext } from "./context.js";@@ -27,10 +29,13 @@ const fakeBuffer = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);* Replaces the provider's processImage with one that resolves to the given* processed image, so the async persistence branch runs deterministically.*/-function stubProcessImage(format: { ext: string }, buffer: Uint8Array = fakeBuffer) {+function stubProcessImage(format: { ext: string; mime?: string }, buffer: Uint8Array = fakeBuffer) {const processed: ProcessedImage = {+ // A real provider reports both halves and they agree — `{ ext: "jpg", mime: "image/jpeg" }`+ // is what the codec hands back. Deriving the default the same way keeps a stub from+ // describing an image no provider would ever produce.buffer,- format: { ext: format.ext, mime: `image/${format.ext}` }+ format: { ext: format.ext, mime: format.mime ?? imageMimeForExtension(format.ext) }};return vi.spyOn(getImageProvider(), "processImage").mockResolvedValue(processed);}@@ -113,7 +118,7 @@ describe("image service (real DB)", () => {expect(bytesOf(note.getContent())).toEqual(Array.from(fakeBuffer));});- it("maps the svg extension to the svg+xml mime and appends the extension when missing", async () => {+ it("stores the svg+xml mime whole and appends the extension when the name has none", async () => {stubProcessImage({ ext: "svg" });counter++;const baseName = `nodotsvg${counter}`;@@ -276,10 +281,30 @@ describe("image service (real DB)", () => {await flushAsync();const attachment = becca.getAttachment(att.attachmentId!)!;- expect(attachment.mime).toBe("image/jpg");+ expect(attachment.mime).toBe("image/jpeg");expect(attachment.title).toBe("nodotattach.jpg");expect(bytesOf(attachment.getContent())).toEqual(Array.from(fakeBuffer));});++ it("records the media type the provider reported rather than rebuilding one from its extension", async () => {+ // The codec names JPEG `{ ext: "jpg", mime: "image/jpeg" }`, so the correct media+ // type is already in hand. Deriving it from the extension instead yields the+ // unregistered "image/jpg", which every consumer downstream then needs a special+ // case for — mapExtension carries one, and IMAGE_MIMES has to list it.+ const host = createTargetNote();+ stubProcessImage({ ext: "jpg", mime: "image/jpeg" });++ const att = getContext().init(() =>+ imageService.saveImageToAttachment(host.noteId, fakeBuffer, "screenshot.png", false)+ );+ await flushAsync();++ const attachment = becca.getAttachment(att.attachmentId ?? "");+ expect(attachment?.mime).toBe("image/jpeg");+ // The title is left alone on purpose (a canvas addresses its images by it), which is+ // precisely why the mime has to be right — it is all the export has left to go on.+ expect(attachment?.title).toBe("screenshot.png");+ });});describe("updateImage", () => {@@ -327,7 +352,7 @@ describe("image service (real DB)", () => {expect(note.getOwnedLabelValue("originalFileName")).toBe("renamed.png");// Mime/content now reflect updateImage's distinct provider output, which// differs from the PNG/[1,2,3] state saveImage produced.- expect(note.mime).toBe("image/jpg");+ expect(note.mime).toBe("image/jpeg");expect(bytesOf(note.getContent())).toEqual(Array.from(updatedBuffer));});});diff --git a/packages/trilium-core/src/services/image.ts b/packages/trilium-core/src/services/image.tsindex 1b159b6fe4..8a1cf594c5 100644--- a/packages/trilium-core/src/services/image.ts+++ b/packages/trilium-core/src/services/image.ts@@ -3,7 +3,7 @@* Uses ImageProvider for platform-specific processing (compression, format detection).*/-import { type ImageAttachmentRole, imageMimeForExtension, isDeduplicatedAttachmentRole } from "@triliumnext/commons";+import { type ImageAttachmentRole, isDeduplicatedAttachmentRole } from "@triliumnext/commons";import sanitizeFilename from "sanitize-filename";import becca from "../becca/becca.js";@@ -109,7 +109,7 @@ function updateImage(noteId: string, uploadBuffer: Uint8Array, originalName: strtrackWrite(getImageProvider().processImage(uploadBuffer, originalName, true).then(({ buffer, format }) => {getContext().init(() => {getSql().transactional(() => {- note.mime = imageMimeForExtension(format.ext);+ note.mime = format.mime;note.save();note.setContent(buffer);});@@ -151,7 +151,7 @@ function saveImage(trackWrite(getImageProvider().processImage(uploadBuffer, originalName, shrinkImageSwitch).then(({ buffer, format }) => {getContext().init(() => {getSql().transactional(() => {- note.mime = imageMimeForExtension(format.ext);+ note.mime = format.mime;if (!originalName.includes(".")) {originalName += `.${format.ext}`;@@ -251,7 +251,7 @@ function saveImageToAttachment(return;}- savedAttachment.mime = imageMimeForExtension(format.ext);+ savedAttachment.mime = format.mime;if (!originalName.includes(".")) {originalName += `.${format.ext}`;diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex 08b74735c0..9eb0e70e8f 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -246,8 +246,12 @@ export const HEADER_BYTES = 64 * 1024;* One image the run can act on, hiding whether it lives in a note's content or in an attachment.** Neither kind is renamed when its format changes: an attachment's title is a reference elsewhere- * (a canvas addresses its images by the Excalidraw file id stored as the title), and download and- * export filenames already derive their extension from the mime when the title disagrees.+ * (a canvas addresses its images by the Excalidraw file id stored as the title), so the mime is+ * left to carry the format on its own.+ *+ * That makes the mime load-bearing rather than merely informative, since it is then the only+ * record of what the bytes are: download and export filenames both derive their extension from it+ * where the title disagrees, which is the whole reason they may be left disagreeing.*/export interface CompressionTarget {entityType: "note" | "attachment";