94 lines
2.5 KiB
JavaScript
Raw Normal View History

"use strict";
const utils = require('../utils');
2021-05-17 22:09:49 +02:00
const becca = require("../../becca/becca.js");
2020-06-20 12:31:38 +02:00
function exportToOpml(taskContext, branch, version, res) {
2019-02-16 23:58:42 +01:00
if (!['1.0', '2.0'].includes(version)) {
throw new Error("Unrecognized OPML version " + version);
}
const opmlVersion = parseInt(version);
2019-02-16 23:33:40 +01:00
2020-06-20 12:31:38 +02:00
const note = branch.getNote();
2020-06-20 12:31:38 +02:00
function exportNoteInner(branchId) {
2021-05-02 11:23:58 +02:00
const branch = becca.getBranch(branchId);
2020-06-20 12:31:38 +02:00
const note = branch.getNote();
2018-11-19 09:34:05 +01:00
2020-06-20 12:31:38 +02:00
if (note.hasOwnedLabel('excludeFromExport')) {
2018-11-19 09:34:05 +01:00
return;
}
const title = (branch.prefix ? (branch.prefix + ' - ') : '') + note.title;
2019-02-16 23:58:42 +01:00
if (opmlVersion === 1) {
const preparedTitle = escapeXmlAttribute(title);
2020-06-20 12:31:38 +02:00
const preparedContent = note.isStringNote() ? prepareText(note.getContent()) : '';
2019-02-16 23:58:42 +01:00
res.write(`<outline title="${preparedTitle}" text="${preparedContent}">\n`);
}
else if (opmlVersion === 2) {
const preparedTitle = escapeXmlAttribute(title);
2020-06-20 12:31:38 +02:00
const preparedContent = note.isStringNote() ? escapeXmlAttribute(note.getContent()) : '';
2019-02-16 23:58:42 +01:00
res.write(`<outline text="${preparedTitle}" _note="${preparedContent}">\n`);
}
else {
throw new Error("Unrecognized OPML version " + opmlVersion);
}
2019-10-18 22:27:38 +02:00
taskContext.increaseProgressCount();
2019-02-10 22:30:55 +01:00
2020-06-20 12:31:38 +02:00
for (const child of note.getChildBranches()) {
exportNoteInner(child.branchId);
}
res.write('</outline>');
}
2019-02-16 23:58:42 +01:00
const filename = (branch.prefix ? (branch.prefix + ' - ') : '') + note.title + ".opml";
res.setHeader('Content-Disposition', utils.getContentDisposition(filename));
res.setHeader('Content-Type', 'text/x-opml');
res.write(`<?xml version="1.0" encoding="UTF-8"?>
<opml version="${version}">
<head>
<title>Trilium export</title>
</head>
<body>`);
2020-06-20 12:31:38 +02:00
exportNoteInner(branch.branchId);
res.write(`</body>
</opml>`);
res.end();
2019-02-10 22:30:55 +01:00
2019-10-18 22:27:38 +02:00
taskContext.taskSucceeded();
}
function prepareText(text) {
const newLines = text.replace(/(<p[^>]*>|<br\s*\/?>)/g, '\n')
.replace(/&nbsp;/g, ' '); // nbsp isn't in XML standard (only HTML)
const stripped = utils.stripTags(newLines);
const escaped = escapeXmlAttribute(stripped);
return escaped.replace(/\n/g, '&#10;');
}
function escapeXmlAttribute(text) {
return text.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
module.exports = {
exportToOpml
2020-06-20 12:31:38 +02:00
};