339 lines
12 KiB
JavaScript
Raw Normal View History

2018-11-05 00:06:17 +01:00
const sax = require("sax");
2020-01-11 09:50:05 +01:00
const FileType = require('file-type');
2018-11-05 00:06:17 +01:00
const stream = require('stream');
const log = require("../log");
const utils = require("../utils");
const sql = require("../sql");
const noteService = require("../notes");
const imageService = require("../image");
2019-02-25 21:22:57 +01:00
const protectedSessionService = require('../protected_session');
2018-11-05 00:06:17 +01:00
// date format is e.g. 20181121T193703Z
function parseDate(text) {
// insert - and : to make it ISO format
text = text.substr(0, 4) + "-" + text.substr(4, 2) + "-" + text.substr(6, 2)
+ " " + text.substr(9, 2) + ":" + text.substr(11, 2) + ":" + text.substr(13, 2) + ".000Z";
2018-11-05 00:06:17 +01:00
return text;
}
let note = {};
let resource;
2020-06-20 12:31:38 +02:00
function importEnex(taskContext, file, parentNote) {
2018-11-05 00:06:17 +01:00
const saxStream = sax.createStream(true);
const rootNoteTitle = file.originalname.toLowerCase().endsWith(".enex")
? file.originalname.substr(0, file.originalname.length - 5)
: file.originalname;
// root note is new note into all ENEX/notebook's notes will be imported
2020-06-20 12:31:38 +02:00
const rootNote = (noteService.createNewNote({
2019-11-16 11:09:52 +01:00
parentNoteId: parentNote.noteId,
title: rootNoteTitle,
content: "",
type: 'text',
2019-02-25 21:22:57 +01:00
mime: 'text/html',
isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),
})).note;
2018-11-05 00:06:17 +01:00
// we're persisting notes as we parse the document, but these are run asynchronously and may not be finished
// when we finish parsing. We use this to be sure that all saving has been finished before returning successfully.
const saveNotePromises = [];
2019-11-16 17:56:49 +01:00
function extractContent(content) {
const openingNoteIndex = content.indexOf('<en-note>');
2018-11-05 00:06:17 +01:00
2019-11-16 17:56:49 +01:00
if (openingNoteIndex !== -1) {
content = content.substr(openingNoteIndex + 9);
}
const closingNoteIndex = content.lastIndexOf('</en-note>');
2019-11-16 17:56:49 +01:00
if (closingNoteIndex !== -1) {
content = content.substr(0, closingNoteIndex);
}
2019-11-16 17:56:49 +01:00
content = content.trim();
2018-11-05 00:06:17 +01:00
// workaround for https://github.com/ckeditor/ckeditor5-list/issues/116
content = content.replace(/<li>\s+<div>/g, "<li>");
content = content.replace(/<\/div>\s+<\/li>/g, "</li>");
// workaround for https://github.com/ckeditor/ckeditor5-list/issues/115
content = content.replace(/<ul>\s+<ul>/g, "<ul><li><ul>");
content = content.replace(/<\/li>\s+<ul>/g, "<ul>");
content = content.replace(/<\/ul>\s+<\/ul>/g, "</ul></li></ul>");
content = content.replace(/<\/ul>\s+<li>/g, "</ul></li><li>");
content = content.replace(/<ol>\s+<ol>/g, "<ol><li><ol>");
content = content.replace(/<\/li>\s+<ol>/g, "<ol>");
content = content.replace(/<\/ol>\s+<\/ol>/g, "</ol></li></ol>");
content = content.replace(/<\/ol>\s+<li>/g, "</ol></li><li>");
return content;
}
const path = [];
function getCurrentTag() {
if (path.length >= 1) {
return path[path.length - 1];
}
}
function getPreviousTag() {
if (path.length >= 2) {
return path[path.length - 2];
}
}
saxStream.on("error", e => {
// unhandled errors will throw, since this is a proper node
// event emitter.
log.error("error when parsing ENEX file: " + e);
// clear the error
this._parser.error = null;
this._parser.resume();
});
saxStream.on("text", text => {
const currentTag = getCurrentTag();
const previousTag = getPreviousTag();
if (previousTag === 'note-attributes') {
note.attributes.push({
type: 'label',
name: currentTag,
value: text
});
}
else if (previousTag === 'resource-attributes') {
if (currentTag === 'file-name') {
resource.attributes.push({
type: 'label',
name: 'originalFileName',
value: text
});
resource.title = text;
}
else if (currentTag === 'source-url') {
resource.attributes.push({
type: 'label',
name: 'sourceUrl',
value: text
});
}
}
else if (previousTag === 'resource') {
if (currentTag === 'data') {
text = text.replace(/\s/g, '');
resource.content = utils.fromBase64(text);
}
else if (currentTag === 'mime') {
resource.mime = text.toLowerCase();
2018-11-05 00:06:17 +01:00
if (text.startsWith("image/")) {
resource.title = "image";
// images don't have "file-name" tag so we'll create attribute here
resource.attributes.push({
type: 'label',
name: 'originalFileName',
value: resource.title + "." + text.substr(6) // extension from mime type
});
}
}
}
else if (previousTag === 'note') {
if (currentTag === 'title') {
note.title = text;
} else if (currentTag === 'created') {
2019-03-12 20:58:31 +01:00
note.utcDateCreated = parseDate(text);
2018-11-05 00:06:17 +01:00
} else if (currentTag === 'updated') {
note.utcDateModified = parseDate(text);
2018-11-05 00:06:17 +01:00
} else if (currentTag === 'tag') {
note.attributes.push({
type: 'label',
name: text,
value: ''
})
}
// unknown tags are just ignored
}
});
saxStream.on("attribute", attr => {
// an attribute. attr has "name" and "value"
});
saxStream.on("opentag", tag => {
path.push(tag.name);
if (tag.name === 'note') {
note = {
content: "",
// it's an array, not a key-value object because we don't know if attributes can be duplicated
attributes: [],
resources: []
};
}
else if (tag.name === 'resource') {
resource = {
title: "resource",
attributes: []
};
note.resources.push(resource);
}
});
2020-06-20 12:31:38 +02:00
function updateDates(noteId, utcDateCreated, utcDateModified) {
// it's difficult to force custom dateCreated and dateModified to Note entity so we do it post-creation with SQL
2020-06-20 12:31:38 +02:00
sql.execute(`
UPDATE notes
SET dateCreated = ?,
utcDateCreated = ?,
dateModified = ?,
utcDateModified = ?
WHERE noteId = ?`,
[utcDateCreated, utcDateCreated, utcDateModified, utcDateModified, noteId]);
2020-06-20 12:31:38 +02:00
sql.execute(`
UPDATE note_contents
SET utcDateModified = ?
WHERE noteId = ?`,
[utcDateModified, noteId]);
}
2020-06-20 12:31:38 +02:00
function saveNote() {
// make a copy because stream continues with the next call and note gets overwritten
let {title, content, attributes, resources, utcDateCreated, utcDateModified} = note;
2018-11-05 00:06:17 +01:00
2019-11-16 17:56:49 +01:00
content = extractContent(content);
2018-11-05 00:06:17 +01:00
2020-06-20 12:31:38 +02:00
const noteEntity = (noteService.createNewNote({
2019-11-16 11:09:52 +01:00
parentNoteId: rootNote.noteId,
title,
content,
2019-03-12 20:58:31 +01:00
utcDateCreated,
2018-11-05 00:06:17 +01:00
type: 'text',
2019-02-25 21:22:57 +01:00
mime: 'text/html',
isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),
})).note;
2018-11-05 00:06:17 +01:00
2019-11-16 17:56:49 +01:00
for (const attr of attributes) {
2020-06-20 12:31:38 +02:00
noteEntity.addAttribute(attr.type, attr.name, attr.value);
2019-11-16 11:09:52 +01:00
}
utcDateCreated = utcDateCreated || noteEntity.utcDateCreated;
// sometime date modified is not present in ENEX, then use date created
utcDateModified = utcDateModified || utcDateCreated;
taskContext.increaseProgressCount();
2019-02-10 19:36:03 +01:00
2018-11-05 00:06:17 +01:00
for (const resource of resources) {
const hash = utils.md5(resource.content);
const mediaRegex = new RegExp(`<en-media hash="${hash}"[^>]*>`, 'g');
2020-06-20 12:31:38 +02:00
const fileTypeFromBuffer = FileType.fromBuffer(resource.content);
if (fileTypeFromBuffer) {
// If fileType returns something for buffer, then set the mime given
resource.mime = fileTypeFromBuffer.mime;
}
2020-06-20 12:31:38 +02:00
const createFileNote = () => {
const resourceNote = (noteService.createNewNote({
2019-11-16 11:09:52 +01:00
parentNoteId: noteEntity.noteId,
title: resource.title,
content: resource.content,
2019-02-10 19:36:03 +01:00
type: 'file',
2019-02-25 21:22:57 +01:00
mime: resource.mime,
isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),
2019-02-10 19:36:03 +01:00
})).note;
2019-11-16 11:09:52 +01:00
for (const attr of resource.attributes) {
2020-06-20 12:31:38 +02:00
noteEntity.addAttribute(attr.type, attr.name, attr.value);
2019-11-16 11:09:52 +01:00
}
2020-06-20 12:31:38 +02:00
updateDates(resourceNote.noteId, utcDateCreated, utcDateModified);
taskContext.increaseProgressCount();
2019-02-10 19:36:03 +01:00
const resourceLink = `<a href="#root/${resourceNote.noteId}">${utils.escapeHtml(resource.title)}</a>`;
content = content.replace(mediaRegex, resourceLink);
2019-02-06 21:29:23 +01:00
};
2019-06-23 15:22:05 +02:00
if (["image/jpeg", "image/png", "image/gif", "image/webp"].includes(resource.mime)) {
2019-02-10 19:36:03 +01:00
try {
const originalName = "image." + resource.mime.substr(6);
2020-06-20 12:31:38 +02:00
const {url, note: imageNote} = imageService.saveImage(noteEntity.noteId, resource.content, originalName, taskContext.data.shrinkImages);
2020-06-20 12:31:38 +02:00
updateDates(imageNote.noteId, utcDateCreated, utcDateModified);
2019-02-10 19:36:03 +01:00
const imageLink = `<img src="${url}">`;
content = content.replace(mediaRegex, imageLink);
if (!content.includes(imageLink)) {
2019-02-10 19:36:03 +01:00
// if there wasn't any match for the reference, we'll add the image anyway
// otherwise image would be removed since no note would include it
content += imageLink;
2019-02-10 19:36:03 +01:00
}
} catch (e) {
log.error("error when saving image from ENEX file: " + e);
2020-06-20 12:31:38 +02:00
createFileNote();
}
2019-02-10 19:36:03 +01:00
} else {
2020-06-20 12:31:38 +02:00
createFileNote();
}
2018-11-05 00:06:17 +01:00
}
// save updated content with links to files/images
2020-06-20 12:31:38 +02:00
noteEntity.setContent(content);
2020-06-20 12:31:38 +02:00
noteService.scanForLinks(noteEntity);
2020-06-20 12:31:38 +02:00
updateDates(noteEntity.noteId, utcDateCreated, utcDateModified);
2018-11-05 00:06:17 +01:00
}
2020-06-20 12:31:38 +02:00
saxStream.on("closetag", tag => {
2018-11-05 00:06:17 +01:00
path.pop();
if (tag === 'note') {
saveNotePromises.push(saveNote());
}
});
saxStream.on("opencdata", () => {
//console.log("opencdata");
});
saxStream.on("cdata", text => {
note.content += text;
});
saxStream.on("closecdata", () => {
//console.log("closecdata");
});
return new Promise((resolve, reject) =>
{
// resolve only when we parse the whole document AND saving of all notes have been finished
saxStream.on("end", () => { Promise.all(saveNotePromises).then(() => resolve(rootNote)) });
2018-11-05 00:06:17 +01:00
const bufferStream = new stream.PassThrough();
bufferStream.end(file.buffer);
bufferStream.pipe(saxStream);
});
}
2020-06-20 12:31:38 +02:00
module.exports = { importEnex };