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
feat(export): remove v1 OPML export, always export OPML 2.0
Elian Doran39405d35a2a3
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex dd9747e020..fdc12282bb 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -137,11 +137,16 @@"format_markdown_name": "Markdown","format_markdown_description": "Preserves most formatting","format_opml_name": "OPML",- "format_opml_description": "Outline format, text only",+ "format_opml_description": "Outline format with HTML content","format_share_name": "HTML for web","format_share_description": "Publishable static site using the shared-notes theme",- "opml_version_1": "OPML v1.0 - plain text only",- "opml_version_2": "OPML v2.0 - allows also HTML",+ "recommended": "Recommended",+ "result_subtree_html": "A ZIP archive where text notes are saved as HTML. Code, images and other files keep their original format.",+ "result_subtree_markdown": "A ZIP archive where text notes are saved as Markdown. Code, images and other files keep their original format.",+ "result_share": "A ZIP archive containing a publishable static website that uses the shared-notes theme.",+ "result_opml": "A single OPML outline file. Note titles and text are included; images, code files and attachments are not.",+ "result_single_html": "A single HTML file. Images and attachments are embedded into it.",+ "result_single_markdown": "A single Markdown (.md) file.","export": "Export","choose_export_type": "Choose export type first please","export_in_progress": "Export in progress: {{progressCount}}",diff --git a/apps/client/src/widgets/dialogs/export.css b/apps/client/src/widgets/dialogs/export.cssindex 8a784e6d41..8bf5117744 100644--- a/apps/client/src/widgets/dialogs/export.css+++ b/apps/client/src/widgets/dialogs/export.css@@ -17,7 +17,14 @@flex: 1;}- .opml-versions {- margin-top: 0.75em;+ /* Format name + "Recommended" badge sitting inline on the tile. */+ .export-format-heading {+ display: inline-flex;+ align-items: center;+ gap: 0.5em;+ }++ .export-recommended-badge {+ --color: var(--link-color, var(--main-text-color));}}diff --git a/apps/client/src/widgets/dialogs/export.tsx b/apps/client/src/widgets/dialogs/export.tsxindex c6bfe6ba92..1a2f17e1b0 100644--- a/apps/client/src/widgets/dialogs/export.tsx+++ b/apps/client/src/widgets/dialogs/export.tsx@@ -9,6 +9,8 @@ import toastService, { type ToastOptionsWithRequiredId } from "../../services/toimport tree from "../../services/tree";import utils, { isStandalone } from "../../services/utils";import ws from "../../services/ws";+import { ExtendedAdmonition } from "../react/Admonition";+import { Badge } from "../react/Badge";import Button, { ButtonGroup } from "../react/Button";import { Card, CardSection } from "../react/Card";import { useTriliumEvent } from "../react/hooks";@@ -26,6 +28,7 @@ interface ExportFormat {name: string;description: string;icon: string;+ recommended?: boolean;}export default function ExportDialog() {@@ -33,7 +36,6 @@ export default function ExportDialog() {const [ exportType, setExportType ] = useState<"subtree" | "single">("subtree");const [ subtreeFormat, setSubtreeFormat ] = useState("html");const [ singleFormat, setSingleFormat ] = useState("html");- const [ opmlVersion, setOpmlVersion ] = useState("2.0");const [ shown, setShown ] = useState(false);useTriliumEvent("showExportDialog", async ({ notePath, defaultType }) => {@@ -67,8 +69,7 @@ export default function ExportDialog() {return;}- const version = (selectedFormat === "opml" ? opmlVersion : "1.0");- exportBranch(opts.branchId, exportType, selectedFormat, version);+ exportBranch(opts.branchId, exportType, selectedFormat);setShown(false);}}onHidden={() => setShown(false)}@@ -93,29 +94,26 @@ export default function ExportDialog() {<SelectableCardGrid columns={2}>{formats.map((format) => (<SelectableCard- key={format.value} icon={format.icon} title={format.name} description={format.description}+ key={format.value} icon={format.icon}+ title={format.recommended+ ? <span className="export-format-heading">{format.name}<Badge text={t("export.recommended")} className="export-recommended-badge" outline /></span>+ : format.name}+ description={format.description}selected={selectedFormat === format.value} onSelect={() => setSelectedFormat(format.value)}/>))}</SelectableCardGrid>-- {selectedFormat === "opml" && (- <ButtonGroup className="opml-versions" size="sm">- <button type="button" className={`btn btn-secondary ${opmlVersion === "1.0" ? "active" : ""}`} onClick={() => setOpmlVersion("1.0")}>- {t("export.opml_version_1")}- </button>- <button type="button" className={`btn btn-secondary ${opmlVersion === "2.0" ? "active" : ""}`} onClick={() => setOpmlVersion("2.0")}>- {t("export.opml_version_2")}- </button>- </ButtonGroup>- )}</CardSection></Card>++ <ExtendedAdmonition type="note" icon="bx bx-info-circle">+ {exportResultText(exportType, selectedFormat)}+ </ExtendedAdmonition></Modal>);}-const HTML_FORMAT: ExportFormat = { value: "html", name: t("export.format_html_name"), description: t("export.format_html_description"), icon: "bx bxl-html5" };+const HTML_FORMAT: ExportFormat = { value: "html", name: t("export.format_html_name"), description: t("export.format_html_description"), icon: "bx bxl-html5", recommended: true };const MARKDOWN_FORMAT: ExportFormat = { value: "markdown", name: t("export.format_markdown_name"), description: t("export.format_markdown_description"), icon: "bx bxl-markdown" };const SHARE_FORMAT: ExportFormat = { value: "share", name: t("export.format_share_name"), description: t("export.format_share_description"), icon: "bx bx-globe" };const OPML_FORMAT: ExportFormat = { value: "opml", name: t("export.format_opml_name"), description: t("export.format_opml_description"), icon: "bx bx-list-ul" };@@ -124,9 +122,23 @@ const OPML_FORMAT: ExportFormat = { value: "opml", name: t("export.format_opml_nconst subtreeFormats: ExportFormat[] = [HTML_FORMAT, MARKDOWN_FORMAT, ...(isStandalone ? [] : [SHARE_FORMAT]), OPML_FORMAT];const singleFormats: ExportFormat[] = [HTML_FORMAT, MARKDOWN_FORMAT];-function exportBranch(branchId: string, type: string, format: string, version: string) {+// One-line summary of what the chosen export actually produces, shown in the dialog's result admonition.+function exportResultText(exportType: "subtree" | "single", format: string) {+ if (format === "opml") {+ return t("export.result_opml");+ }+ if (format === "share") {+ return t("export.result_share");+ }+ if (exportType === "single") {+ return format === "markdown" ? t("export.result_single_markdown") : t("export.result_single_html");+ }+ return format === "markdown" ? t("export.result_subtree_markdown") : t("export.result_subtree_html");+}++function exportBranch(branchId: string, type: string, format: string) {const taskId = utils.randomString(10);- const url = open.getUrlForDownload(`api/branches/${branchId}/export/${type}/${format}/${version}/${taskId}`);+ const url = open.getUrlForDownload(`api/branches/${branchId}/export/${type}/${format}/${taskId}`);open.download(url);}diff --git a/apps/desktop/src/services/shell.spec.ts b/apps/desktop/src/services/shell.spec.tsindex 22b4cc3422..00bcb2243e 100644--- a/apps/desktop/src/services/shell.spec.ts+++ b/apps/desktop/src/services/shell.spec.ts@@ -390,8 +390,8 @@ describe("validateDownloadUrl", () => {.toBe("trilium-app://app/api/attachments/xyz/download?123");expect(validateDownloadUrl("trilium-app://app/api/revisions/r1/download", DESKTOP_PAGE_URL).toString()).toBe("trilium-app://app/api/revisions/r1/download");- expect(validateDownloadUrl("trilium-app://app/api/branches/b1/export/subtree/html/1/t1", DESKTOP_PAGE_URL).toString())- .toBe("trilium-app://app/api/branches/b1/export/subtree/html/1/t1");+ expect(validateDownloadUrl("trilium-app://app/api/branches/b1/export/subtree/html/t1", DESKTOP_PAGE_URL).toString())+ .toBe("trilium-app://app/api/branches/b1/export/subtree/html/t1");});it("accepts same-origin downloads via plain HTTP", () => {diff --git a/apps/server/internal.openapi.yaml b/apps/server/internal.openapi.yamlindex 841f45884e..ffea752eaf 100644--- a/apps/server/internal.openapi.yaml+++ b/apps/server/internal.openapi.yaml@@ -2159,7 +2159,7 @@ paths:format: binary# Import/Export- /api/branches/{branchId}/export/{type}/{format}/{version}/{taskId}:+ /api/branches/{branchId}/export/{type}/{format}/{taskId}:get:tags: [Import/Export]summary: Export branch@@ -2182,11 +2182,6 @@ paths:schema:type: stringenum: [html, markdown, opml]- - name: version- in: path- required: true- schema:- type: string- name: taskIdin: pathrequired: truediff --git a/packages/trilium-core/src/routes/api/export.spec.ts b/packages/trilium-core/src/routes/api/export.spec.tsindex ede3eeb10c..82a85bbf96 100644--- a/packages/trilium-core/src/routes/api/export.spec.ts+++ b/packages/trilium-core/src/routes/api/export.spec.ts@@ -12,8 +12,8 @@ import { CoreApiTester } from "../../test/api_tester";let api: CoreApiTester;let branchId: string;-function exportPath(type: string, format: string, version = "1.0", taskId = "exportTask") {- return `/api/branches/${branchId}/export/${type}/${format}/${version}/${taskId}`;+function exportPath(type: string, format: string, taskId = "exportTask") {+ return `/api/branches/${branchId}/export/${type}/${format}/${taskId}`;}/** A real zip always begins with the "PK" local-file-header signature. */@@ -60,7 +60,7 @@ describe("Export API (core)", () => {});it("exports as real opml", async () => {- const res = await api.get(exportPath("subtree", "opml", "2.0"));+ const res = await api.get(exportPath("subtree", "opml"));expect(res.status).toBe(200);expect(res.headers["Content-Type"]).toBe("text/x-opml");expect(res.body?.toString()).toContain("outline");diff --git a/packages/trilium-core/src/routes/api/export.ts b/packages/trilium-core/src/routes/api/export.tsindex 88af5f2e32..59ef56b0ee 100644--- a/packages/trilium-core/src/routes/api/export.ts+++ b/packages/trilium-core/src/routes/api/export.ts@@ -9,8 +9,8 @@ import TaskContext from "../../services/task_context.js";import { safeExtractMessageAndStackFromError } from "../../services/utils/index.js";import { NotFoundError, ValidationError } from "../../errors.js";-async function exportBranch(req: Request<{ branchId: string; type: string; format: string; version: string; taskId: string }>, res: Response) {- const { branchId, type, format, version, taskId } = req.params;+async function exportBranch(req: Request<{ branchId: string; type: string; format: string; taskId: string }>, res: Response) {+ const { branchId, type, format, taskId } = req.params;const branch = becca.getBranch(branchId);if (!branch) {@@ -32,7 +32,7 @@ async function exportBranch(req: Request<{ branchId: string; type: string; forma}singleExportService.exportSingleNote(taskContext, branch, format, res);} else if (format === "opml") {- opmlExportService.exportToOpml(taskContext, branch, version, res);+ opmlExportService.exportToOpml(taskContext, branch, res);} else {throw new NotFoundError(`Unrecognized export format '${format}'`);}diff --git a/packages/trilium-core/src/routes/api/import.spec.ts b/packages/trilium-core/src/routes/api/import.spec.tsindex aa0c31081a..50a8861e2b 100644--- a/packages/trilium-core/src/routes/api/import.spec.ts+++ b/packages/trilium-core/src/routes/api/import.spec.ts@@ -84,7 +84,7 @@ describe("Import API (core)", () => {it("imports a real Trilium .zip produced by a round-trip export", async () => {const zip = await api.get<Buffer>(- `/api/branches/${branchId}/export/subtree/html/1.0/exportTask`+ `/api/branches/${branchId}/export/subtree/html/exportTask`);expect(Buffer.isBuffer(zip.body)).toBe(true);diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex c6a20c409b..3ad3ba703c 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -151,7 +151,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout//#region Import/exportasyncRoute(PST, "/api/notes/:parentNoteId/notes-import", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importNotesToBranch, apiResultHandler);route(PST, "/api/notes/:parentNoteId/attachments-import", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importAttachmentsToNote, apiResultHandler);- asyncRoute(GET, "/api/branches/:branchId/export/:type/:format/:version/:taskId", [checkApiAuthOrElectron], exportRoute.exportBranch);+ asyncRoute(GET, "/api/branches/:branchId/export/:type/:format/:taskId", [checkApiAuthOrElectron], exportRoute.exportBranch);//#endregionapiRoute(GET, "/api/quick-search/:searchString", searchRoute.quickSearch);diff --git a/packages/trilium-core/src/services/export/opml.spec.ts b/packages/trilium-core/src/services/export/opml.spec.tsindex 638bc03f83..192f964fd5 100644--- a/packages/trilium-core/src/services/export/opml.spec.ts+++ b/packages/trilium-core/src/services/export/opml.spec.ts@@ -63,9 +63,9 @@ function getTaskContext() {return TaskContext.getInstance("opml-export-spec", "export", null);}-function runExport(branch: BBranch, version: string): FakeResponse {+function runExport(branch: BBranch): FakeResponse {const res = new FakeResponse();- opml.exportToOpml(getTaskContext(), branch, version, res as unknown as Response);+ opml.exportToOpml(getTaskContext(), branch, res as unknown as Response);return res;}@@ -75,71 +75,43 @@ describe("exportToOpml (real DB)", () => {await sql_init.dbReady;});- it("rejects an unrecognized OPML version before touching the response", () => {- const { branch } = createNote("root");- const res = new FakeResponse();-- expect(() => opml.exportToOpml(getTaskContext(), branch, "9.9", res as unknown as Response)).toThrow(/9\.9/);- // Nothing should have been written when the version is invalid.- expect(res.chunks).toHaveLength(0);- expect(res.ended).toBe(false);- });-- it("exports a v1.0 document with the opml header, download headers and stripped text content", () => {+ it("exports a document with the opml header, download headers and text/_note attribute pair", () => {const { note, branch } = createNote("root", {- title: "Root v1",- content: "<p>line one</p><p>line two</p>"+ title: "Root note",+ content: "<p>body</p>"});- const res = runExport(branch, "1.0");+ const res = runExport(branch);// Streaming the export sets the OPML download headers.expect(res.headers["Content-Type"]).toBe("text/x-opml");- expect(res.headers["Content-Disposition"]).toContain("Root%20v1.opml");+ expect(res.headers["Content-Disposition"]).toContain("Root%20note.opml");expect(res.ended).toBe(true);const body = res.body;- // The XML/opml envelope is emitted with the requested version.- expect(body).toContain(`<opml version="1.0">`);+ // The XML/opml envelope is always emitted as OPML 2.0.+ expect(body).toContain(`<opml version="2.0">`);expect(body).toContain("<title>Trilium export</title>");expect(body.trim().endsWith("</opml>")).toBe(true);- // v1 uses the `title`/`text` attribute pair; every <p> opener (including- // the leading one) becomes a newline encoded as and the surrounding- // tags are stripped.- expect(body).toContain(`<outline title="Root v1" text=" line one line two">`);+ // The title goes in the standard `text` attribute; the raw HTML content is+ // XML-escaped into the `_note` extension attribute.+ expect(body).toContain(`<outline text="Root note" _note="<p>body</p>">`);expect(body).toContain("</outline>");// The note was counted in the export progress (no throw from increaseProgressCount).- expect(note.title).toBe("Root v1");- });-- it("exports a v2.0 document using the text/_note attribute pair with raw escaped HTML", () => {- const { branch } = createNote("root", {- title: "Root v2",- content: "<p>body</p>"- });-- const res = runExport(branch, "2.0");-- expect(res.headers["Content-Type"]).toBe("text/x-opml");- const body = res.body;- expect(body).toContain(`<opml version="2.0">`);- // v2 keeps the raw HTML content but XML-escapes it into the _note attribute.- expect(body).toContain(`<outline text="Root v2" _note="<p>body</p>">`);+ expect(note.title).toBe("Root note");});- it("escapes XML-significant characters in titles for both versions", () => {+ it("escapes XML-significant characters in titles", () => {const { branch } = createNote("root", {title: `A & B <c> "d" 'e'`,content: ""});- const v1 = runExport(branch, "1.0").body;- const v2 = runExport(branch, "2.0").body;+ const body = runExport(branch).body;const escapedTitle = `A & B <c> "d" 'e'`;- expect(v1).toContain(`<outline title="${escapedTitle}" text="">`);- expect(v2).toContain(`<outline text="${escapedTitle}" _note="">`);+ expect(body).toContain(`<outline text="${escapedTitle}" _note="">`);});it("recursively exports child notes nested inside the parent outline", () => {@@ -147,7 +119,7 @@ describe("exportToOpml (real DB)", () => {createNote(parent.noteId, { title: "Child A", content: "<p>a</p>" });createNote(parent.noteId, { title: "Child B", content: "<p>b</p>" });- const body = runExport(branch, "2.0").body;+ const body = runExport(branch).body;// The parent outline is opened, both children appear nested before it closes.const parentIdx = body.indexOf(`text="Parent node"`);@@ -168,7 +140,7 @@ describe("exportToOpml (real DB)", () => {const { note: excluded } = createNote(parent.noteId, { title: "Excluded child", content: "<p>no</p>" });getContext().init(() => excluded.addLabel("excludeFromExport"));- const body = runExport(branch, "2.0").body;+ const body = runExport(branch).body;expect(body).toContain(`text="Kept child"`);expect(body).not.toContain(`text="Excluded child"`);@@ -183,16 +155,16 @@ describe("exportToOpml (real DB)", () => {branch.save();});- const res = runExport(branch, "1.0");+ const res = runExport(branch);expect(res.headers["Content-Disposition"]).toContain("Pre%20-%20Prefixed.opml");- expect(res.body).toContain(`<outline title="Pre - Prefixed" text="">`);+ expect(res.body).toContain(`<outline text="Pre - Prefixed" _note="">`);expect(note.title).toBe("Prefixed");});- it("leaves text empty for non-string (binary) content notes", () => {+ it("leaves the _note attribute empty for non-string (binary) content notes", () => {// An image note has binary content, so hasStringContent() is false and the- // text/_note attribute must be emitted empty rather than dumping the buffer.+ // _note attribute must be emitted empty rather than dumping the buffer.const { branch } = createNote("root", {title: "Binary note",type: "image",@@ -200,10 +172,8 @@ describe("exportToOpml (real DB)", () => {content: "not-really-png-bytes"});- const v1 = runExport(branch, "1.0").body;- const v2 = runExport(branch, "2.0").body;+ const body = runExport(branch).body;- expect(v1).toContain(`<outline title="Binary note" text="">`);- expect(v2).toContain(`<outline text="Binary note" _note="">`);+ expect(body).toContain(`<outline text="Binary note" _note="">`);});}, 60_000);diff --git a/packages/trilium-core/src/services/export/opml.ts b/packages/trilium-core/src/services/export/opml.tsindex e6ca1ce3c2..4786d294e1 100644--- a/packages/trilium-core/src/services/export/opml.ts+++ b/packages/trilium-core/src/services/export/opml.ts@@ -3,15 +3,9 @@ import type { Response } from "express";import becca from "../../becca/becca.js";import type BBranch from "../../becca/entities/bbranch.js";import type TaskContext from "../task_context.js";-import { getContentDisposition, stripTags } from "../utils/index.js";--function exportToOpml(taskContext: TaskContext<"export">, branch: BBranch, version: string, res: Response) {- if (!["1.0", "2.0"].includes(version)) {- throw new Error(`Unrecognized OPML version ${version}`);- }-- const opmlVersion = parseInt(version);+import { getContentDisposition } from "../utils/index.js";+function exportToOpml(taskContext: TaskContext<"export">, branch: BBranch, res: Response) {const note = branch.getNote();function exportNoteInner(branchId: string) {@@ -30,20 +24,10 @@ function exportToOpml(taskContext: TaskContext<"export">, branch: BBranch, versi}const title = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.title}`;+ const preparedTitle = escapeXmlAttribute(title);+ const preparedContent = note.hasStringContent() ? escapeXmlAttribute(note.getContent() as string) : "";- if (opmlVersion === 1) {- const preparedTitle = escapeXmlAttribute(title);- const preparedContent = note.hasStringContent() ? prepareText(note.getContent() as string) : "";-- res.write(`<outline title="${preparedTitle}" text="${preparedContent}">\n`);- } else if (opmlVersion === 2) {- const preparedTitle = escapeXmlAttribute(title);- const preparedContent = note.hasStringContent() ? escapeXmlAttribute(note.getContent() as string) : "";-- res.write(`<outline text="${preparedTitle}" _note="${preparedContent}">\n`);- } else {- throw new Error(`Unrecognized OPML version ${opmlVersion}`);- }+ res.write(`<outline text="${preparedTitle}" _note="${preparedContent}">\n`);taskContext.increaseProgressCount();@@ -62,7 +46,7 @@ function exportToOpml(taskContext: TaskContext<"export">, branch: BBranch, versires.setHeader("Content-Type", "text/x-opml");res.write(`<?xml version="1.0" encoding="UTF-8"?>-<opml version="${version}">+<opml version="2.0"><head><title>Trilium export</title></head>@@ -79,16 +63,6 @@ function exportToOpml(taskContext: TaskContext<"export">, branch: BBranch, versitaskContext.taskSucceeded(null);}-function prepareText(text: string) {- const newLines = text.replace(/(<p[^>]*>|<br\s*\/?>)/g, "\n").replace(/ /g, " "); // nbsp isn't in XML standard (only HTML)-- const stripped = stripTags(newLines);-- const escaped = escapeXmlAttribute(stripped);-- return escaped.replace(/\n/g, " ");-}-function escapeXmlAttribute(text: string) {return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");}