Notes/src/services/notes.js

546 lines
17 KiB
JavaScript
Raw Normal View History

const sql = require('./sql');
2019-01-05 21:49:40 +01:00
const sqlInit = require('./sql_init');
const optionService = require('./options');
2018-04-02 20:46:46 -04:00
const dateUtils = require('./date_utils');
const syncTableService = require('./sync_table');
const attributeService = require('./attributes');
const eventService = require('./events');
const repository = require('./repository');
const cls = require('../services/cls');
2018-03-31 22:23:40 -04:00
const Note = require('../entities/note');
2018-03-31 22:15:06 -04:00
const NoteRevision = require('../entities/note_revision');
2018-03-31 22:23:40 -04:00
const Branch = require('../entities/branch');
const Attribute = require('../entities/attribute');
const hoistedNoteService = require('../services/hoisted_note');
const protectedSessionService = require('../services/protected_session');
const log = require('../services/log');
2019-11-09 11:58:52 +01:00
const noteRevisionService = require('../services/note_revisions');
2018-04-01 17:38:24 -04:00
async function getNewNotePosition(parentNoteId, noteData) {
let newNotePos = 0;
2018-04-01 17:38:24 -04:00
if (noteData.target === 'into') {
2018-03-24 21:39:15 -04:00
const maxNotePos = await sql.getValue('SELECT MAX(notePosition) FROM branches WHERE parentNoteId = ? AND isDeleted = 0', [parentNoteId]);
2019-10-19 12:36:16 +02:00
newNotePos = maxNotePos === null ? 0 : maxNotePos + 10;
}
2018-04-01 17:38:24 -04:00
else if (noteData.target === 'after') {
const afterNote = await sql.getRow('SELECT notePosition FROM branches WHERE branchId = ?', [noteData.target_branchId]);
2019-10-19 12:36:16 +02:00
newNotePos = afterNote.notePosition + 10;
2019-03-12 20:58:31 +01:00
// not updating utcDateModified to avoig having to sync whole rows
2019-10-19 12:36:16 +02:00
await sql.execute('UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition > ? AND isDeleted = 0',
2018-01-28 19:30:14 -05:00
[parentNoteId, afterNote.notePosition]);
await syncTableService.addNoteReorderingSync(parentNoteId);
}
else {
2018-04-01 17:38:24 -04:00
throw new Error('Unknown target: ' + noteData.target);
}
2018-03-31 22:23:40 -04:00
return newNotePos;
}
async function triggerChildNoteCreated(childNote, parentNote) {
await eventService.emit(eventService.CHILD_NOTE_CREATED, { childNote, parentNote });
}
async function triggerNoteTitleChanged(note) {
await eventService.emit(eventService.NOTE_TITLE_CHANGED, note);
}
2018-11-08 11:08:16 +01:00
/**
* FIXME: noteData has mandatory property "target", it might be better to add it as parameter to reflect this
*/
2018-04-01 17:38:24 -04:00
async function createNewNote(parentNoteId, noteData) {
let newNotePos;
if (noteData.notePosition !== undefined) {
newNotePos = noteData.notePosition;
}
else {
newNotePos = await getNewNotePosition(parentNoteId, noteData);
}
const parentNote = await repository.getNote(parentNoteId);
2017-11-29 21:04:30 -05:00
2018-11-26 20:30:43 +01:00
if (!parentNote) {
throw new Error(`Parent note ${parentNoteId} not found.`);
}
if (!noteData.type) {
if (parentNote.type === 'text' || parentNote.type === 'code') {
noteData.type = parentNote.type;
noteData.mime = parentNote.mime;
}
else {
// inheriting note type makes sense only for text and code
noteData.type = 'text';
noteData.mime = 'text/html';
}
}
if (!noteData.mime) {
if (noteData.type === 'text') {
noteData.mime = 'text/html';
}
else if (noteData.type === 'code') {
noteData.mime = 'text/plain';
}
else if (noteData.type === 'relation-map' || noteData.type === 'search') {
noteData.mime = 'application/json';
}
}
noteData.type = noteData.type || parentNote.type;
noteData.mime = noteData.mime || parentNote.mime;
2018-04-02 22:53:01 -04:00
const note = await new Note({
noteId: noteData.noteId, // optionally can force specific noteId
2018-04-01 17:38:24 -04:00
title: noteData.title,
isProtected: noteData.isProtected,
type: noteData.type || 'text',
mime: noteData.mime || 'text/html'
2018-04-02 22:53:01 -04:00
}).save();
if (note.isStringNote() || this.type === 'render') { // render to just make sure it's not null
noteData.content = noteData.content || "";
}
await note.setContent(noteData.content);
2019-02-06 21:29:23 +01:00
2018-04-02 22:53:01 -04:00
const branch = await new Branch({
2018-03-31 22:23:40 -04:00
noteId: note.noteId,
2018-01-28 19:30:14 -05:00
parentNoteId: parentNoteId,
notePosition: newNotePos,
prefix: noteData.prefix,
isExpanded: !!noteData.isExpanded
2018-04-02 22:53:01 -04:00
}).save();
for (const attr of await parentNote.getOwnedAttributes()) {
if (attr.name.startsWith("child:")) {
await new Attribute({
noteId: note.noteId,
type: attr.type,
name: attr.name.substr(6),
value: attr.value,
position: attr.position,
isInheritable: attr.isInheritable
}).save();
note.invalidateAttributeCache();
}
}
await triggerNoteTitleChanged(note);
await triggerChildNoteCreated(note, parentNote);
return {
note,
branch
};
}
async function createNote(parentNoteId, title, content = "", extraOptions = {}) {
if (!parentNoteId) throw new Error("Empty parentNoteId");
if (!title) throw new Error("Empty title");
2018-04-01 11:42:12 -04:00
const noteData = {
title: title,
content: extraOptions.json ? JSON.stringify(content, null, '\t') : content,
target: 'into',
noteId: extraOptions.noteId,
2018-04-01 17:38:24 -04:00
isProtected: !!extraOptions.isProtected,
type: extraOptions.type,
2018-11-05 00:06:17 +01:00
mime: extraOptions.mime,
dateCreated: extraOptions.dateCreated,
isExpanded: extraOptions.isExpanded,
notePosition: extraOptions.notePosition
};
2018-04-01 11:42:12 -04:00
if (extraOptions.json && !noteData.type) {
noteData.type = "code";
noteData.mime = "application/json";
}
const {note, branch} = await createNewNote(parentNoteId, noteData);
for (const attr of extraOptions.attributes || []) {
await attributeService.createAttribute({
noteId: note.noteId,
type: attr.type,
name: attr.name,
value: attr.value,
isInheritable: !!attr.isInheritable
});
}
return {note, branch};
}
async function protectNoteRecursively(note, protect, taskContext) {
await protectNote(note, protect);
2017-11-15 00:04:26 -05:00
taskContext.increaseProgressCount();
2018-03-31 23:08:22 -04:00
for (const child of await note.getChildNotes()) {
await protectNoteRecursively(child, protect, taskContext);
2017-11-15 00:04:26 -05:00
}
}
async function protectNote(note, protect) {
2018-03-31 22:15:06 -04:00
if (protect !== note.isProtected) {
const content = await note.getContent();
2018-03-31 22:15:06 -04:00
note.isProtected = protect;
2017-11-15 00:04:26 -05:00
// this will force de/encryption
await note.setContent(content);
2018-04-01 17:38:24 -04:00
await note.save();
2017-11-15 00:04:26 -05:00
}
2019-11-09 11:58:52 +01:00
await noteRevisionService.protectNoteRevisions(note);
2017-11-15 00:04:26 -05:00
}
function findImageLinks(content, foundLinks) {
const re = /src="[^"]*api\/images\/([a-zA-Z0-9]+)\//g;
let match;
while (match = re.exec(content)) {
foundLinks.push({
2019-08-29 23:08:30 +02:00
name: 'image-link',
2019-08-19 20:12:00 +02:00
value: match[1]
});
}
// removing absolute references to server to keep it working between instances
2019-02-22 23:03:20 +01:00
// we also omit / at the beginning to keep the paths relative
return content.replace(/src="[^"]*\/api\/images\//g, 'src="api/images/');
}
2019-08-19 20:12:00 +02:00
function findInternalLinks(content, foundLinks) {
const re = /href="[^"]*#root[a-zA-Z0-9\/]*\/([a-zA-Z0-9]+)\/?"/g;
let match;
while (match = re.exec(content)) {
foundLinks.push({
2019-08-19 20:12:00 +02:00
name: 'internal-link',
value: match[1]
});
}
// removing absolute references to server to keep it working between instances
return content.replace(/href="[^"]*#root/g, 'href="#root');
}
function findRelationMapLinks(content, foundLinks) {
const obj = JSON.parse(content);
for (const note of obj.notes) {
foundLinks.push({
2019-08-29 23:08:30 +02:00
name: 'relation-map-link',
2019-08-19 20:12:00 +02:00
value: note.noteId
});
}
}
async function saveLinks(note, content) {
if (note.type !== 'text' && note.type !== 'relation-map') {
2018-11-19 23:11:36 +01:00
return content;
}
if (note.isProtected && !protectedSessionService.isProtectedSessionAvailable()) {
return content;
}
const foundLinks = [];
if (note.type === 'text') {
content = findImageLinks(content, foundLinks);
2019-08-19 20:12:00 +02:00
content = findInternalLinks(content, foundLinks);
}
else if (note.type === 'relation-map') {
findRelationMapLinks(content, foundLinks);
}
else {
throw new Error("Unrecognized type " + note.type);
}
2018-11-08 11:08:16 +01:00
const existingLinks = await note.getLinks();
2018-01-06 22:38:53 -05:00
for (const foundLink of foundLinks) {
const targetNote = await repository.getNote(foundLink.value);
if (!targetNote || targetNote.isDeleted) {
continue;
}
const existingLink = existingLinks.find(existingLink =>
2019-08-19 20:12:00 +02:00
existingLink.value === foundLink.value
&& existingLink.name === foundLink.name);
2018-01-06 22:38:53 -05:00
2018-11-08 11:08:16 +01:00
if (!existingLink) {
2019-08-19 20:12:00 +02:00
await new Attribute({
2018-03-31 22:15:06 -04:00
noteId: note.noteId,
2019-08-19 20:12:00 +02:00
type: 'relation',
name: foundLink.name,
2019-08-27 22:47:10 +02:00
value: foundLink.value,
2018-04-02 22:53:01 -04:00
}).save();
2018-01-06 22:38:53 -05:00
}
2018-11-08 11:08:16 +01:00
else if (existingLink.isDeleted) {
existingLink.isDeleted = false;
await existingLink.save();
}
// else the link exists so we don't need to do anything
2018-01-06 22:38:53 -05:00
}
2018-11-08 11:08:16 +01:00
// marking links as deleted if they are not present on the page anymore
const unusedLinks = existingLinks.filter(existingLink => !foundLinks.some(foundLink =>
2019-08-19 20:12:00 +02:00
existingLink.value === foundLink.value
&& existingLink.name === foundLink.name));
2018-01-06 22:38:53 -05:00
2018-11-08 11:08:16 +01:00
for (const unusedLink of unusedLinks) {
unusedLink.isDeleted = true;
await unusedLink.save();
2018-01-06 22:38:53 -05:00
}
return content;
2018-01-06 22:38:53 -05:00
}
2018-03-31 22:15:06 -04:00
async function saveNoteRevision(note) {
2019-02-06 21:29:23 +01:00
// files and images are immutable, they can't be updated
// but we don't even version titles which is probably not correct
2019-02-27 22:15:52 +01:00
if (note.type === 'file' || note.type === 'image' || await note.hasLabel('disableVersioning')) {
2019-02-06 21:29:23 +01:00
return;
}
const now = new Date();
2018-04-02 21:47:46 -04:00
const noteRevisionSnapshotTimeInterval = parseInt(await optionService.getOption('noteRevisionSnapshotTimeInterval'));
2019-03-31 12:49:42 +02:00
const revisionCutoff = dateUtils.utcDateStr(new Date(now.getTime() - noteRevisionSnapshotTimeInterval * 1000));
const existingNoteRevisionId = await sql.getValue(
2019-11-01 19:21:48 +01:00
"SELECT noteRevisionId FROM note_revisions WHERE noteId = ? AND utcDateCreated >= ?", [note.noteId, revisionCutoff]);
2018-03-31 22:15:06 -04:00
2019-03-31 12:49:42 +02:00
const msSinceDateCreated = now.getTime() - dateUtils.parseDateTime(note.utcDateCreated).getTime();
2018-03-31 22:15:06 -04:00
2019-02-06 21:29:23 +01:00
if (!existingNoteRevisionId && msSinceDateCreated >= noteRevisionSnapshotTimeInterval * 1000) {
2019-11-01 19:21:48 +01:00
const noteRevision = await new NoteRevision({
2018-03-31 22:15:06 -04:00
noteId: note.noteId,
// title and text should be decrypted now
title: note.title,
2019-11-01 19:21:48 +01:00
contentLength: -1, // will be updated in .setContent()
2018-04-08 11:57:14 -04:00
type: note.type,
mime: note.mime,
isProtected: false, // will be fixed in the protectNoteRevisions() call
2019-11-01 19:21:48 +01:00
utcDateLastEdited: note.utcDateModified,
utcDateCreated: dateUtils.utcNowDateTime(),
utcDateModified: dateUtils.utcNowDateTime(),
dateLastEdited: note.dateModified,
dateCreated: dateUtils.localNowDateTime()
2018-04-02 22:53:01 -04:00
}).save();
2019-11-01 19:21:48 +01:00
await noteRevision.setContent(await note.getContent());
2018-03-31 22:15:06 -04:00
}
}
2018-03-31 22:15:06 -04:00
async function updateNote(noteId, noteUpdates) {
const note = await repository.getNote(noteId);
if (!note.isContentAvailable) {
throw new Error(`Note ${noteId} is not available for change!`);
}
2018-03-31 22:15:06 -04:00
await saveNoteRevision(note);
2019-05-04 16:05:28 +02:00
// if protected status changed, then we need to encrypt/decrypt the content anyway
if (['file', 'image'].includes(note.type) && note.isProtected !== noteUpdates.isProtected) {
noteUpdates.content = await note.getContent();
}
const noteTitleChanged = note.title !== noteUpdates.title;
2018-03-31 22:15:06 -04:00
note.title = noteUpdates.title;
note.isProtected = noteUpdates.isProtected;
2018-04-01 17:38:24 -04:00
await note.save();
2019-11-08 22:34:30 +01:00
if (noteUpdates.content !== undefined && noteUpdates.content !== null) {
2019-03-31 12:49:42 +02:00
noteUpdates.content = await saveLinks(note, noteUpdates.content);
2019-03-31 12:49:42 +02:00
await note.setContent(noteUpdates.content);
2019-02-06 21:29:23 +01:00
}
if (noteTitleChanged) {
await triggerNoteTitleChanged(note);
}
2019-11-09 11:58:52 +01:00
await noteRevisionService.protectNoteRevisions(note);
return {
dateModified: note.dateModified,
utcDateModified: note.utcDateModified
};
}
/** @return {boolean} - true if note has been deleted, false otherwise */
2019-10-18 22:27:38 +02:00
async function deleteBranch(branch, taskContext) {
taskContext.increaseProgressCount();
if (!branch || branch.isDeleted) {
return false;
2018-01-14 21:39:21 -05:00
}
if (branch.branchId === 'root'
|| branch.noteId === 'root'
|| branch.noteId === await hoistedNoteService.getHoistedNoteId()) {
2018-08-30 22:38:34 +02:00
throw new Error("Can't delete root branch/note");
}
2018-03-31 23:08:22 -04:00
branch.isDeleted = true;
await branch.save();
2017-11-19 23:12:39 -05:00
2018-03-31 23:08:22 -04:00
const note = await branch.getNote();
const notDeletedBranches = await note.getBranches();
2018-03-31 23:08:22 -04:00
if (notDeletedBranches.length === 0) {
note.isDeleted = true;
await note.save();
2018-03-31 23:08:22 -04:00
for (const childBranch of await note.getChildBranches()) {
2019-10-18 22:27:38 +02:00
await deleteBranch(childBranch, taskContext);
2017-11-19 23:12:39 -05:00
}
2018-08-15 15:27:22 +02:00
for (const attribute of await note.getOwnedAttributes()) {
attribute.isDeleted = true;
await attribute.save();
}
2018-08-22 14:40:49 +02:00
for (const relation of await note.getTargetRelations()) {
relation.isDeleted = true;
await relation.save();
}
return true;
}
else {
return false;
2017-11-19 23:12:39 -05:00
}
}
async function scanForLinks(noteId) {
const note = await repository.getNote(noteId);
if (!note || !['text', 'relation-map'].includes(note.type)) {
return;
}
try {
const content = await note.getContent();
const newContent = await saveLinks(note, content);
await note.setContent(newContent);
}
catch (e) {
log.error(`Could not scan for links note ${noteId}: ${e.message}`);
}
}
2019-11-01 22:09:51 +01:00
async function eraseDeletedNotes() {
2019-02-10 16:36:25 +01:00
const cutoffDate = new Date(Date.now() - 48 * 3600 * 1000);
2019-11-01 22:09:51 +01:00
const noteIdsToErase = await sql.getColumn("SELECT noteId FROM notes WHERE isDeleted = 1 AND isErased = 0 AND notes.utcDateModified <= ?", [dateUtils.utcDateStr(cutoffDate)]);
2019-11-12 22:26:25 +01:00
if (noteIdsToErase.length === 0) {
return;
}
2019-11-01 22:09:51 +01:00
const utcNowDateTime = dateUtils.utcNowDateTime();
const localNowDateTime = dateUtils.localNowDateTime();
// it's better to not use repository for this because it will complain about saving protected notes
// out of protected session
2019-11-09 09:36:08 +01:00
// setting contentLength to zero would serve no benefit and it leaves potentially useful trail
2019-11-01 22:09:51 +01:00
await sql.executeMany(`
UPDATE notes
2019-11-09 09:36:08 +01:00
SET isErased = 1,
2019-11-01 22:09:51 +01:00
utcDateModified = '${utcNowDateTime}',
dateModified = '${localNowDateTime}'
WHERE noteId IN (???)`, noteIdsToErase);
await sql.executeMany(`
UPDATE note_contents
SET content = NULL,
utcDateModified = '${utcNowDateTime}'
WHERE noteId IN (???)`, noteIdsToErase);
2019-11-09 15:21:14 +01:00
// deleting first contents since the WHERE relies on isErased = 0
2019-11-01 22:09:51 +01:00
await sql.executeMany(`
2019-11-09 15:21:14 +01:00
UPDATE note_revision_contents
2019-11-01 22:09:51 +01:00
SET content = NULL,
utcDateModified = '${utcNowDateTime}'
2019-11-09 15:21:14 +01:00
WHERE noteRevisionId IN
2019-11-30 11:36:36 +01:00
(SELECT noteRevisionId FROM note_revisions WHERE isErased = 0 AND noteId IN (???))`, noteIdsToErase);
2019-11-09 15:21:14 +01:00
await sql.executeMany(`
UPDATE note_revisions
SET isErased = 1,
title = NULL,
utcDateModified = '${utcNowDateTime}'
WHERE isErased = 0 AND noteId IN (???)`, noteIdsToErase);
}
2019-10-19 12:36:16 +02:00
async function duplicateNote(noteId, parentNoteId) {
const origNote = await repository.getNote(noteId);
if (origNote.isProtected && !protectedSessionService.isProtectedSessionAvailable()) {
throw new Error(`Cannot duplicate note=${origNote.noteId} because it is protected and protected session is not available`);
}
// might be null if orig note is not in the target parentNoteId
const origBranch = (await origNote.getBranches()).find(branch => branch.parentNoteId === parentNoteId);
const newNote = new Note(origNote);
newNote.noteId = undefined; // force creation of new note
newNote.title += " (dup)";
await newNote.save();
await newNote.setContent(await origNote.getContent());
const newBranch = await new Branch({
noteId: newNote.noteId,
parentNoteId: parentNoteId,
// here increasing just by 1 to make sure it's directly after original
notePosition: origBranch ? origBranch.notePosition + 1 : null
}).save();
for (const attribute of await origNote.getAttributes()) {
const attr = new Attribute(attribute);
attr.attributeId = undefined; // force creation of new attribute
attr.noteId = newNote.noteId;
await attr.save();
}
return {
note: newNote,
branch: newBranch
};
}
2019-01-05 21:49:40 +01:00
sqlInit.dbReady.then(() => {
// first cleanup kickoff 5 minutes after startup
2019-11-30 11:36:36 +01:00
setTimeout(cls.wrap(eraseDeletedNotes), 0 * 60 * 1000);
2019-11-01 22:09:51 +01:00
setInterval(cls.wrap(eraseDeletedNotes), 4 * 3600 * 1000);
2019-01-05 21:49:40 +01:00
});
module.exports = {
createNewNote,
createNote,
updateNote,
deleteBranch,
protectNoteRecursively,
2019-10-19 12:36:16 +02:00
scanForLinks,
2019-11-09 11:58:52 +01:00
duplicateNote
};