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(share): write image and file notes of a static export beside their pages
Elian Dorand15ffdbb146c
diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.tsindex 9c10b5f758..b4ed7c1d77 100644--- a/packages/trilium-core/src/services/export/zip.spec.ts+++ b/packages/trilium-core/src/services/export/zip.spec.ts@@ -654,6 +654,35 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {expect(parseMeta(entries).files[0].dataFileName).toBe("public-alias.html");});+ it("writes an image or file note of a share export as a page plus its raw file", async () => {+ const bytes = Buffer.from([ 0x89, 0x50, 0x4e, 0x47, 0x00, 0xff, 0x80 ]);+ const { note: host } = createNote("root", { title: "BinaryShareHost", content: "" });+ const { note: image } = createNote(host.noteId, { title: "Photo.png", type: "image", mime: "image/png" });+ const { note: pdf } = createNote(host.noteId, { title: "Manual", type: "file", mime: "application/pdf" });+ const { note: file } = createNote(host.noteId, { title: "Data.bin", type: "file", mime: "application/octet-stream" });+ getContext().init(() => {+ for (const note of [ image, pdf, file ]) note.setContent(bytes);+ host.setContent(`<p><img src="api/images/${image.noteId}/Photo.png"></p>`);+ });++ const { entries } = await exportSubtree(host.getParentBranches()[0], "share");+ const pageOf = (noteId: string) => {+ const meta = (parseMeta(entries).files[0].children ?? []).find((c) => c.noteId === noteId);+ return meta?.dataFileName ?? "";+ };++ expect([ pageOf(image.noteId), pageOf(pdf.noteId), pageOf(file.noteId) ])+ .toEqual([ "Photo.png.html", "Manual.html", "Data.bin.html" ]);+ for (const raw of [ "Photo.png", "Manual.pdf", "Data.bin" ]) {+ expect(Buffer.compare(entries[raw] ?? Buffer.alloc(0), bytes), raw).toBe(0);+ }+ expect(entries["Photo.png.html"].toString("utf-8")).toContain(`<img src="Photo.png"`);+ expect(entries["Manual.html"].toString("utf-8")).toContain(`src="Manual.pdf"`);+ expect(entries["Data.bin.html"].toString("utf-8")).toContain(`location.href='Data.bin'`);+ expect(entries[parseMeta(entries).files[0].dataFileName ?? ""].toString("utf-8"))+ .toContain(`<img src="Photo.png"`);+ });+it("rewrites links to notes inside the export and leaves outside ones alone", async () => {const { note: outside } = createNote("root", { title: "Outside", content: "<p>out</p>" });const { note: parent } = createNote("root", { title: "LinkParent", content: "" });diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.tsindex 1ea0bbe365..c7f3d902f6 100644--- a/packages/trilium-core/src/services/export/zip.ts+++ b/packages/trilium-core/src/services/export/zip.ts@@ -1,4 +1,5 @@import { getImageAttachmentTitle, NoteType } from "@triliumnext/commons";+import mimeTypes from "mime-types";import sanitize from "sanitize-filename";import packageInfo from "../../../package.json" with { type: "json" };@@ -39,6 +40,8 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,const log = getLog();const noteIdToMeta: Record<string, NoteMeta> = {};+ /** The file holding the content of an image or file note in a share export, beside its page. */+ const noteIdToRawFileName: Record<string, string> = {};async function buildProvider() {const providerData: ZipExportProviderData = {@@ -99,6 +102,15 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,return getUniqueFilename(existingFileNames, `${base}${extension}`);}+ /** Names the file that holds a note's content as it is, keeping or deriving its extension. */+ function getRawFileName(mime: string, baseFileName: string, existingFileNames: Record<string, number>): string {+ const fileName = baseFileName.trim() || "note";+ const extension = extname(fileName) ? "" : `.${mimeTypes.extension(mime) || "dat"}`;+ const base = truncateUtf8Bytes(sanitize(fileName), MAX_FILENAME_BYTES - extension.length);++ return getUniqueFilename(existingFileNames, `${base}${extension}`);+ }+function createNoteMeta(branch: BBranch, parentMeta: Partial<NoteMeta>, existingFileNames: Record<string, number>): NoteMeta | null {const note = branch.getNote();@@ -183,6 +195,9 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,// if it's a leaf, then we'll export it even if it's emptyif (shouldIncludeFile) {+ if (format === "share" && (note.type === "image" || note.type === "file")) {+ noteIdToRawFileName[note.noteId] = getRawFileName(note.mime, baseFileName, existingFileNames);+ }meta.dataFileName = getDataFileName(note.type, note.mime, baseFileName, existingFileNames);}@@ -279,7 +294,8 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,: undefined;// Falls back to the note's own data file when the attachment was never generated.- return getNoteTargetUrl(targetNoteId, sourceMeta, attachmentMeta?.dataFileName);+ return getNoteTargetUrl(targetNoteId, sourceMeta,+ attachmentMeta?.dataFileName ?? noteIdToRawFileName[targetNoteId]);}function rewriteLinks(content: string, noteMeta: NoteMeta): string {@@ -311,10 +327,12 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,});if (format === "share") {- content = content.replace(/src="[^"]*api\/notes\/([a-zA-Z0-9_]+)\/download"/g, (match, targetNoteId) => {- const url = getNoteTargetUrl(targetNoteId, noteMeta);+ // A PDF's frame and a file's download button reach the note's content through the API.+ const apiUrl = /(src="|location\.href=')[^"']*api\/notes\/([a-zA-Z0-9_]+)\/(?:download|view)(["'])/g;+ content = content.replace(apiUrl, (match, prefix, targetNoteId, quote) => {+ const url = getNoteTargetUrl(targetNoteId, noteMeta, noteIdToRawFileName[targetNoteId]);- return url ? `src="${url}"` : match;+ return url ? `${prefix}${url}${quote}` : match;});}@@ -400,6 +418,17 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,await archive.waitForCapacity?.();}+ const rawFileName = noteIdToRawFileName[noteMeta.noteId];+ if (rawFileName) {+ archive.append(note.getContent(), {+ name: filePathPrefix + rawFileName,+ date: dateUtils.parseDateTime(note.utcDateModified),+ store: shouldStoreUncompressed(noteMeta.mime)+ });++ await archive.waitForCapacity?.();+ }+taskContext.increaseProgressCount();for (const attachmentMeta of noteMeta.attachments || []) {diff --git a/packages/trilium-core/src/services/export/zip/share_theme.spec.ts b/packages/trilium-core/src/services/export/zip/share_theme.spec.tsindex 1447b0220f..82742ae9a7 100644--- a/packages/trilium-core/src/services/export/zip/share_theme.spec.ts+++ b/packages/trilium-core/src/services/export/zip/share_theme.spec.ts@@ -116,11 +116,13 @@ describe("ShareThemeExportProvider", () => {});describe("mapExtension", () => {- it("returns null for images, js for javascript, null for .zip, html otherwise", () => {+ it("keeps an attachment's image or .zip file, js for javascript, html otherwise", () => {const p = makeProvider();- expect(p.mapExtension("image", "image/png", "", "share")).toBeNull();+ expect(p.mapExtension(null, "image/png", ".png", "share")).toBeNull();+ expect(p.mapExtension(null, "application/zip", ".zip", "share")).toBeNull();expect(p.mapExtension("code", "application/javascript", "", "share")).toBe("js");- expect(p.mapExtension("file", "application/zip", ".zip", "share")).toBeNull();+ expect(p.mapExtension("image", "image/png", ".png", "share")).toBe("html");+ expect(p.mapExtension("file", "application/zip", ".zip", "share")).toBe("html");expect(p.mapExtension("text", "text/html", "", "share")).toBe("html");});});diff --git a/packages/trilium-core/src/services/export/zip/share_theme.ts b/packages/trilium-core/src/services/export/zip/share_theme.tsindex 223a705295..b3d9aa9c68 100644--- a/packages/trilium-core/src/services/export/zip/share_theme.ts+++ b/packages/trilium-core/src/services/export/zip/share_theme.ts@@ -135,16 +135,13 @@ export default class ShareThemeExportProvider extends ZipExportProvider {}mapExtension(type: string | null, mime: string, existingExtension: string, format: ExportFormat): string | null {- if (mime.startsWith("image/")) {- return null;- }-if (mime.startsWith("application/javascript")) {return "js";}- // Don't add .html if the file already has .zip extension (for attachments).- if (existingExtension === ".zip") {+ // An attachment keeps its file; an image or file note becomes a page, with its file+ // written beside it.+ if (type === null && (mime.startsWith("image/") || existingExtension === ".zip")) {return null;}