2018-11-16 19:12:04 +08:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
const noteService = require('../../services/notes');
|
|
|
|
const parseString = require('xml2js').parseString;
|
|
|
|
|
2019-02-11 02:36:03 +08:00
|
|
|
/**
|
|
|
|
* @param {ImportContext} importContext
|
|
|
|
* @param {Buffer} fileBuffer
|
|
|
|
* @param {Note} parentNote
|
|
|
|
* @return {Promise<*[]|*>}
|
|
|
|
*/
|
|
|
|
async function importOpml(importContext, fileBuffer, parentNote) {
|
2018-11-16 19:12:04 +08:00
|
|
|
const xml = await new Promise(function(resolve, reject)
|
|
|
|
{
|
2018-11-16 21:36:50 +08:00
|
|
|
parseString(fileBuffer, function (err, result) {
|
2018-11-16 19:12:04 +08:00
|
|
|
if (err) {
|
|
|
|
reject(err);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
resolve(result);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
if (xml.opml.$.version !== '1.0' && xml.opml.$.version !== '1.1') {
|
|
|
|
return [400, 'Unsupported OPML version ' + xml.opml.$.version + ', 1.0 or 1.1 expected instead.'];
|
|
|
|
}
|
|
|
|
|
|
|
|
const outlines = xml.opml.body[0].outline || [];
|
|
|
|
let returnNote = null;
|
|
|
|
|
|
|
|
for (const outline of outlines) {
|
2019-02-11 02:36:03 +08:00
|
|
|
const note = await importOutline(importContext, outline, parentNote.noteId);
|
2018-11-16 19:12:04 +08:00
|
|
|
|
|
|
|
// first created note will be activated after import
|
|
|
|
returnNote = returnNote || note;
|
|
|
|
}
|
|
|
|
|
|
|
|
return returnNote;
|
|
|
|
}
|
|
|
|
|
|
|
|
function toHtml(text) {
|
|
|
|
if (!text) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
|
|
|
return '<p>' + text.replace(/(?:\r\n|\r|\n)/g, '</p><p>') + '</p>';
|
|
|
|
}
|
|
|
|
|
2019-02-11 02:36:03 +08:00
|
|
|
async function importOutline(importContext, outline, parentNoteId) {
|
2018-11-16 19:12:04 +08:00
|
|
|
const {note} = await noteService.createNote(parentNoteId, outline.$.title, toHtml(outline.$.text));
|
|
|
|
|
2019-02-11 05:30:55 +08:00
|
|
|
importContext.increaseProgressCount();
|
2019-02-11 02:36:03 +08:00
|
|
|
|
2018-11-16 19:12:04 +08:00
|
|
|
for (const childOutline of (outline.outline || [])) {
|
|
|
|
await importOutline(childOutline, note.noteId);
|
|
|
|
}
|
|
|
|
|
|
|
|
return note;
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
importOpml
|
|
|
|
};
|