Notes/src/services/notes.js

882 lines
28 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 entityChangesService = require('./entity_changes.js');
const eventService = require('./events');
const repository = require('./repository');
const cls = require('../services/cls');
2021-04-25 21:19:18 +02:00
const BeccaNote = require('../services/becca/entities/note.js');
const BeccaBranch = require('../services/becca/entities/branch.js');
const BeccaAttribute = require('../services/becca/entities/attribute.js');
const protectedSessionService = require('../services/protected_session');
const log = require('../services/log');
const utils = require('../services/utils');
2019-11-09 11:58:52 +01:00
const noteRevisionService = require('../services/note_revisions');
2020-03-25 11:28:44 +01:00
const attributeService = require('../services/attributes');
const request = require('./request');
const path = require('path');
const url = require('url');
2021-04-17 20:52:46 +02:00
const becca = require('../services/becca/becca');
2020-06-20 12:31:38 +02:00
function getNewNotePosition(parentNoteId) {
2021-04-17 20:52:46 +02:00
const note = becca.notes[parentNoteId];
2019-11-14 23:10:56 +01:00
2021-04-17 20:52:46 +02:00
if (!note) {
throw new Error(`Can't find note ${parentNoteId}`);
}
const maxNotePos = note.getChildBranches()
.reduce((max, note) => Math.max(max, note.notePosition), 0);
return maxNotePos + 10;
2018-03-31 22:23:40 -04:00
}
2020-06-20 12:31:38 +02:00
function triggerChildNoteCreated(childNote, parentNote) {
eventService.emit(eventService.CHILD_NOTE_CREATED, { childNote, parentNote });
}
2020-06-20 12:31:38 +02:00
function triggerNoteTitleChanged(note) {
eventService.emit(eventService.NOTE_TITLE_CHANGED, note);
}
2019-11-16 11:09:52 +01:00
function deriveMime(type, mime) {
if (!type) {
throw new Error(`Note type is a required param`);
}
2019-11-16 11:09:52 +01:00
if (mime) {
return mime;
}
if (type === 'text') {
mime = 'text/html';
} else if (type === 'code') {
mime = 'text/plain';
} else if (['relation-map', 'search'].includes(type)) {
mime = 'application/json';
} else if (['render', 'book'].includes(type)) {
mime = '';
2020-09-16 20:32:20 +02:00
} else {
mime = 'application/octet-stream';
}
2019-11-16 11:09:52 +01:00
return mime;
2019-11-14 23:10:56 +01:00
}
2020-06-20 12:31:38 +02:00
function copyChildAttributes(parentNote, childNote) {
for (const attr of parentNote.getAttributes()) {
2019-11-14 23:10:56 +01:00
if (attr.name.startsWith("child:")) {
2021-04-25 21:19:18 +02:00
new BeccaAttribute({
2019-11-14 23:10:56 +01:00
noteId: childNote.noteId,
type: attr.type,
name: attr.name.substr(6),
value: attr.value,
position: attr.position,
isInheritable: attr.isInheritable
}).save();
}
}
2019-11-14 23:10:56 +01:00
}
2019-11-14 23:10:56 +01:00
/**
* Following object properties are mandatory:
* - {string} parentNoteId
* - {string} title
* - {*} content
* - {string} type - text, code, file, image, search, book, relation-map, render
2019-11-14 23:10:56 +01:00
*
* Following are optional (have defaults)
* - {string} mime - value is derived from default mimes for type
* - {boolean} isProtected - default is false
* - {boolean} isExpanded - default is false
* - {string} prefix - default is empty string
* - {integer} notePosition - default is last existing notePosition in a parent + 10
*
* @param params
2020-08-20 15:23:24 +02:00
* @return {{note: Note, branch: Branch}}
2019-11-14 23:10:56 +01:00
*/
2020-06-20 12:31:38 +02:00
function createNewNote(params) {
2021-04-25 21:19:18 +02:00
const parentNote = becca.notes[params.parentNoteId];
2019-11-14 23:10:56 +01:00
if (!parentNote) {
2020-06-02 23:13:55 +02:00
throw new Error(`Parent note "${params.parentNoteId}" not found.`);
2019-11-14 23:10:56 +01:00
}
if (!params.title || params.title.trim().length === 0) {
throw new Error(`Note title must not be empty`);
}
return sql.transactional(() => {
2021-04-30 22:13:13 +02:00
const note = new BeccaNote({
2020-08-18 21:32:45 +02:00
noteId: params.noteId, // optionally can force specific noteId
title: params.title,
isProtected: !!params.isProtected,
type: params.type,
mime: deriveMime(params.type, params.mime)
}).save();
note.setContent(params.content);
2021-04-30 22:13:13 +02:00
const branch = new BeccaBranch({
2020-08-18 21:32:45 +02:00
noteId: note.noteId,
parentNoteId: params.parentNoteId,
notePosition: params.notePosition !== undefined ? params.notePosition : getNewNotePosition(params.parentNoteId),
prefix: params.prefix,
isExpanded: !!params.isExpanded
}).save();
scanForLinks(note);
copyChildAttributes(parentNote, note);
triggerNoteTitleChanged(note);
triggerChildNoteCreated(note, parentNote);
return {
note,
branch
};
});
}
2020-06-20 12:31:38 +02:00
function createNewNoteWithTarget(target, targetBranchId, params) {
2019-11-16 17:00:22 +01:00
if (!params.type) {
2021-04-25 21:24:32 +02:00
const parentNote = becca.notes[params.parentNoteId];
2019-11-16 17:00:22 +01:00
// code note type can be inherited, otherwise text is default
params.type = parentNote.type === 'code' ? 'code' : 'text';
params.mime = parentNote.type === 'code' ? parentNote.mime : 'text/html';
}
2019-11-16 12:28:47 +01:00
if (target === 'into') {
2020-06-20 12:31:38 +02:00
return createNewNote(params);
2019-11-16 12:28:47 +01:00
}
else if (target === 'after') {
2021-04-25 21:24:32 +02:00
const afterBranch = becca.branches[targetBranchId];
2019-11-16 12:28:47 +01:00
2021-04-25 21:24:32 +02:00
// not updating utcDateModified to avoid having to sync whole rows
2020-06-20 12:31:38 +02:00
sql.execute('UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition > ? AND isDeleted = 0',
2021-04-25 21:24:32 +02:00
[params.parentNoteId, afterBranch.notePosition]);
2019-11-16 12:28:47 +01:00
2021-04-25 21:24:32 +02:00
params.notePosition = afterBranch.notePosition + 10;
2019-11-16 12:28:47 +01:00
2020-06-20 12:31:38 +02:00
const retObject = createNewNote(params);
2019-11-16 12:28:47 +01:00
entityChangesService.addNoteReorderingEntityChange(params.parentNoteId);
2019-11-24 22:15:33 +01:00
return retObject;
2019-11-16 12:28:47 +01:00
}
else {
throw new Error(`Unknown target ${target}`);
}
}
2020-06-20 12:31:38 +02:00
function protectNoteRecursively(note, protect, includingSubTree, taskContext) {
protectNote(note, protect);
2017-11-15 00:04:26 -05:00
taskContext.increaseProgressCount();
if (includingSubTree) {
2020-06-20 12:31:38 +02:00
for (const child of note.getChildNotes()) {
protectNoteRecursively(child, protect, includingSubTree, taskContext);
}
2017-11-15 00:04:26 -05:00
}
}
2020-06-20 12:31:38 +02:00
function protectNote(note, protect) {
2020-12-09 22:49:55 +01:00
try {
if (protect !== note.isProtected) {
const content = note.getContent();
2020-12-09 22:49:55 +01:00
note.isProtected = protect;
2017-11-15 00:04:26 -05:00
2020-12-09 22:49:55 +01:00
// this will force de/encryption
note.setContent(content);
2020-12-09 22:49:55 +01:00
note.save();
}
noteRevisionService.protectNoteRevisions(note);
2017-11-15 00:04:26 -05:00
}
2020-12-09 22:49:55 +01:00
catch (e) {
log.error("Could not un/protect note ID = " + note.noteId);
2017-11-15 00:04:26 -05:00
2020-12-09 22:49:55 +01:00
throw e;
}
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({
name: 'imageLink',
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({
name: 'internalLink',
2019-08-19 20:12:00 +02:00
value: match[1]
});
}
// removing absolute references to server to keep it working between instances
return content.replace(/href="[^"]*#root/g, 'href="#root');
}
function findIncludeNoteLinks(content, foundLinks) {
const re = /<section class="include-note[^>]+data-note-id="([a-zA-Z0-9]+)"[^>]*>/g;
let match;
while (match = re.exec(content)) {
foundLinks.push({
name: 'includeNoteLink',
value: match[1]
});
}
return content;
}
function findRelationMapLinks(content, foundLinks) {
const obj = JSON.parse(content);
for (const note of obj.notes) {
foundLinks.push({
name: 'relationMapLink',
2019-08-19 20:12:00 +02:00
value: note.noteId
});
}
}
2020-03-25 11:28:44 +01:00
const imageUrlToNoteIdMapping = {};
async function downloadImage(noteId, imageUrl) {
try {
const imageBuffer = await request.getImage(imageUrl);
const parsedUrl = url.parse(imageUrl);
const title = path.basename(parsedUrl.pathname);
const imageService = require('../services/image');
2020-06-20 12:31:38 +02:00
const {note} = imageService.saveImage(noteId, imageBuffer, title, true);
2020-03-25 11:28:44 +01:00
2020-06-20 12:31:38 +02:00
note.addLabel('imageUrl', imageUrl);
2020-03-25 11:28:44 +01:00
imageUrlToNoteIdMapping[imageUrl] = note.noteId;
2020-03-25 11:28:44 +01:00
log.info(`Download of ${imageUrl} succeeded and was saved as image note ${note.noteId}`);
}
catch (e) {
2020-04-02 22:55:11 +02:00
log.error(`Download of ${imageUrl} for note ${noteId} failed with error: ${e.message} ${e.stack}`);
}
2020-03-25 11:28:44 +01:00
}
/** url => download promise */
2020-03-25 11:28:44 +01:00
const downloadImagePromises = {};
function replaceUrl(content, url, imageNote) {
const quotedUrl = utils.quoteRegex(url);
2020-03-25 18:21:55 +01:00
return content.replace(new RegExp(`\\s+src=[\"']${quotedUrl}[\"']`, "ig"), ` src="api/images/${imageNote.noteId}/${imageNote.title}"`);
2020-03-25 11:28:44 +01:00
}
2020-06-20 12:31:38 +02:00
function downloadImages(noteId, content) {
const imageRe = /<img[^>]*?\ssrc=['"]([^'">]+)['"]/ig;
let imageMatch;
2020-03-25 11:28:44 +01:00
while (imageMatch = imageRe.exec(content)) {
const url = imageMatch[1];
const inlineImageMatch = /^data:image\/[a-z]+;base64,/.exec(url);
if (inlineImageMatch) {
const imageBase64 = url.substr(inlineImageMatch[0].length);
const imageBuffer = Buffer.from(imageBase64, 'base64');
const imageService = require('../services/image');
const {note} = imageService.saveImage(noteId, imageBuffer, "inline image", true);
content = content.substr(0, imageMatch.index)
+ `<img src="api/images/${note.noteId}/${note.title}"`
+ content.substr(imageMatch.index + imageMatch[0].length);
}
else if (!url.includes('api/images/')
// this is an exception for the web clipper's "imageId"
&& (url.length !== 20 || url.toLowerCase().startsWith('http'))) {
2020-03-25 11:28:44 +01:00
if (url in imageUrlToNoteIdMapping) {
2021-05-02 11:23:58 +02:00
const imageNote = becca.getNote(imageUrlToNoteIdMapping[url]);
2020-03-25 11:28:44 +01:00
2020-05-06 23:11:34 +02:00
if (!imageNote || imageNote.isDeleted) {
2020-03-25 11:28:44 +01:00
delete imageUrlToNoteIdMapping[url];
}
else {
content = replaceUrl(content, url, imageNote);
continue;
}
}
2020-06-20 12:31:38 +02:00
const existingImage = (attributeService.getNotesWithLabel('imageUrl', url))
2020-03-25 11:28:44 +01:00
.find(note => note.type === 'image');
if (existingImage) {
imageUrlToNoteIdMapping[url] = existingImage.noteId;
content = replaceUrl(content, url, existingImage);
continue;
}
2020-05-06 23:11:34 +02:00
if (url in downloadImagePromises) {
// download is already in progress
continue;
}
// this is done asynchronously, it would be too slow to wait for the download
// given that save can be triggered very often
2020-03-25 11:28:44 +01:00
downloadImagePromises[url] = downloadImage(noteId, url);
}
}
2020-03-25 18:21:55 +01:00
Promise.all(Object.values(downloadImagePromises)).then(() => {
2020-06-20 12:31:38 +02:00
setTimeout(() => {
// the normal expected flow of the offline image saving is that users will paste the image(s)
// which will get asynchronously downloaded, during that time they keep editing the note
// once the download is finished, the image note representing downloaded image will be used
// to replace the IMG link.
// However there's another flow where user pastes the image and leaves the note before the images
// are downloaded and the IMG references are not updated. For this occassion we have this code
// which upon the download of all the images will update the note if the links have not been fixed before
2020-06-20 12:31:38 +02:00
sql.transactional(() => {
2021-05-02 11:23:58 +02:00
const imageNotes = becca.getNotes(Object.values(imageUrlToNoteIdMapping));
2020-03-25 11:28:44 +01:00
2021-05-02 11:23:58 +02:00
const origNote = becca.getNote(noteId);
2020-06-20 12:31:38 +02:00
const origContent = origNote.getContent();
2020-05-06 23:11:34 +02:00
let updatedContent = origContent;
2020-03-25 11:28:44 +01:00
2020-05-06 23:11:34 +02:00
for (const url in imageUrlToNoteIdMapping) {
const imageNote = imageNotes.find(note => note.noteId === imageUrlToNoteIdMapping[url]);
2020-03-25 11:28:44 +01:00
2020-05-06 23:11:34 +02:00
if (imageNote && !imageNote.isDeleted) {
updatedContent = replaceUrl(updatedContent, url, imageNote);
}
2020-03-25 11:28:44 +01:00
}
2020-05-06 23:11:34 +02:00
// update only if the links have not been already fixed.
if (updatedContent !== origContent) {
2020-06-20 12:31:38 +02:00
origNote.setContent(updatedContent);
2020-06-20 12:31:38 +02:00
scanForLinks(origNote);
2020-05-06 23:11:34 +02:00
console.log(`Fixed the image links for note ${noteId} to the offline saved.`);
}
});
2020-03-25 11:28:44 +01:00
}, 5000);
});
2020-03-25 18:21:55 +01:00
return content;
2020-03-25 11:28:44 +01:00
}
2020-06-20 12:31:38 +02:00
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 = [];
2020-01-11 09:50:05 +01:00
if (note.type === 'text') {
2020-06-20 12:31:38 +02:00
content = downloadImages(note.noteId, content);
content = findImageLinks(content, foundLinks);
2019-08-19 20:12:00 +02:00
content = findInternalLinks(content, foundLinks);
content = findIncludeNoteLinks(content, foundLinks);
}
else if (note.type === 'relation-map') {
findRelationMapLinks(content, foundLinks);
}
else {
throw new Error("Unrecognized type " + note.type);
}
2021-04-25 21:19:18 +02:00
const existingLinks = note.getRelations().filter(rel =>
['internalLink', 'imageLink', 'relationMapLink', 'includeNoteLink'].includes(rel.name));
2018-01-06 22:38:53 -05:00
for (const foundLink of foundLinks) {
2021-04-25 21:19:18 +02:00
const targetNote = becca.notes[foundLink.value];
if (!targetNote) {
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) {
2021-04-25 21:19:18 +02:00
const newLink = new BeccaAttribute({
2018-03-31 22:15:06 -04:00
noteId: note.noteId,
type: 'relation',
2019-08-19 20:12:00 +02:00
name: foundLink.name,
2019-08-27 22:47:10 +02:00
value: foundLink.value,
2018-04-02 22:53:01 -04:00
}).save();
2020-04-05 15:35:01 +02:00
existingLinks.push(newLink);
2018-01-06 22:38:53 -05:00
}
2018-11-08 11:08:16 +01:00
// 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) {
2021-04-25 21:19:18 +02:00
unusedLink.markAsDeleted();
2018-01-06 22:38:53 -05:00
}
return content;
2018-01-06 22:38:53 -05:00
}
2020-06-20 12:31:38 +02:00
function saveNoteRevision(note) {
// files and images are versioned separately
2020-06-20 12:31:38 +02:00
if (note.type === 'file' || note.type === 'image' || note.hasLabel('disableVersioning')) {
2019-02-06 21:29:23 +01:00
return;
}
const now = new Date();
2020-06-20 12:31:38 +02:00
const noteRevisionSnapshotTimeInterval = parseInt(optionService.getOption('noteRevisionSnapshotTimeInterval'));
2019-03-31 12:49:42 +02:00
const revisionCutoff = dateUtils.utcDateStr(new Date(now.getTime() - noteRevisionSnapshotTimeInterval * 1000));
2020-06-20 12:31:38 +02:00
const existingNoteRevisionId = sql.getValue(
2020-12-18 22:35:40 +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) {
noteRevisionService.createNoteRevision(note);
2018-03-31 22:15:06 -04:00
}
}
2020-06-20 12:31:38 +02:00
function updateNote(noteId, noteUpdates) {
2021-05-02 11:23:58 +02:00
const note = becca.getNote(noteId);
if (!note.isContentAvailable) {
throw new Error(`Note ${noteId} is not available for change!`);
}
2020-06-20 12:31:38 +02:00
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) {
2020-06-20 12:31:38 +02:00
noteUpdates.content = note.getContent();
2019-05-04 16:05:28 +02:00
}
const noteTitleChanged = note.title !== noteUpdates.title;
2018-03-31 22:15:06 -04:00
note.title = noteUpdates.title;
note.isProtected = noteUpdates.isProtected;
2020-06-20 12:31:38 +02:00
note.save();
2019-11-08 22:34:30 +01:00
if (noteUpdates.content !== undefined && noteUpdates.content !== null) {
2020-06-20 12:31:38 +02:00
noteUpdates.content = saveLinks(note, noteUpdates.content);
2020-06-20 12:31:38 +02:00
note.setContent(noteUpdates.content);
2019-02-06 21:29:23 +01:00
}
if (noteTitleChanged) {
2020-06-20 12:31:38 +02:00
triggerNoteTitleChanged(note);
}
2020-06-20 12:31:38 +02:00
noteRevisionService.protectNoteRevisions(note);
return {
dateModified: note.dateModified,
utcDateModified: note.utcDateModified
};
}
2020-01-03 10:48:36 +01:00
/**
* @param {Branch} branch
* @param {string} deleteId
* @param {TaskContext} taskContext
*
* @return {boolean} - true if note has been deleted, false otherwise
*/
2020-06-20 12:31:38 +02:00
function deleteBranch(branch, deleteId, taskContext) {
2019-10-18 22:27:38 +02:00
taskContext.increaseProgressCount();
if (!branch || branch.isDeleted) {
return false;
2018-01-14 21:39:21 -05:00
}
if (branch.branchId === 'root'
|| branch.noteId === 'root'
2020-11-23 22:52:48 +01:00
|| branch.noteId === cls.getHoistedNoteId()) {
2018-08-30 22:38:34 +02:00
throw new Error("Can't delete root branch/note");
}
branch.markAsDeleted(deleteId);
2017-11-19 23:12:39 -05:00
2020-06-20 12:31:38 +02:00
const note = branch.getNote();
const notDeletedBranches = note.getBranches();
2018-03-31 23:08:22 -04:00
if (notDeletedBranches.length === 0) {
2020-06-20 12:31:38 +02:00
for (const childBranch of note.getChildBranches()) {
deleteBranch(childBranch, deleteId, taskContext);
2017-11-19 23:12:39 -05:00
}
2018-08-15 15:27:22 +02:00
2020-01-03 13:41:44 +01:00
// first delete children and then parent - this will show up better in recent changes
note.markAsDeleted(deleteId);
2020-01-03 13:41:44 +01:00
2020-04-06 22:08:54 +02:00
log.info("Deleting note " + note.noteId);
2020-04-06 20:59:04 +02:00
2020-06-20 12:31:38 +02:00
for (const attribute of note.getOwnedAttributes()) {
attribute.markAsDeleted(deleteId);
2018-08-15 15:27:22 +02:00
}
2018-08-22 14:40:49 +02:00
2020-06-20 12:31:38 +02:00
for (const relation of note.getTargetRelations()) {
relation.markAsDeleted(deleteId);
}
return true;
}
else {
return false;
2017-11-19 23:12:39 -05:00
}
}
2020-01-03 13:14:43 +01:00
/**
* @param {Note} note
* @param {string} deleteId
* @param {TaskContext} taskContext
*/
2020-06-20 12:31:38 +02:00
function undeleteNote(note, deleteId, taskContext) {
const undeletedParentBranches = getUndeletedParentBranches(note.noteId, deleteId);
2020-01-03 13:14:43 +01:00
if (undeletedParentBranches.length === 0) {
// cannot undelete if there's no undeleted parent
return;
}
for (const parentBranch of undeletedParentBranches) {
2020-06-20 12:31:38 +02:00
undeleteBranch(parentBranch, deleteId, taskContext);
2020-01-03 13:14:43 +01:00
}
}
/**
* @param {Branch} branch
* @param {string} deleteId
* @param {TaskContext} taskContext
*/
2020-06-20 12:31:38 +02:00
function undeleteBranch(branch, deleteId, taskContext) {
2020-01-03 13:14:43 +01:00
if (!branch.isDeleted) {
return;
}
2020-06-20 12:31:38 +02:00
const note = branch.getNote();
2020-01-03 13:14:43 +01:00
if (note.isDeleted && note.deleteId !== deleteId) {
return;
}
branch.isDeleted = false;
2020-06-20 12:31:38 +02:00
branch.save();
2020-01-03 13:14:43 +01:00
taskContext.increaseProgressCount();
if (note.isDeleted && note.deleteId === deleteId) {
note.isDeleted = false;
2020-06-20 12:31:38 +02:00
note.save();
2020-01-03 13:14:43 +01:00
2021-05-02 19:59:16 +02:00
const attributeIds = sql.getColumn(`
SELECT attributeId FROM attributes
2020-01-03 13:14:43 +01:00
WHERE isDeleted = 1
AND deleteId = ?
AND (noteId = ?
OR (type = 'relation' AND value = ?))`, [deleteId, note.noteId, note.noteId]);
2021-05-02 19:59:16 +02:00
for (const attr of attributeIds) {
2020-01-03 13:14:43 +01:00
attr.isDeleted = false;
2020-06-20 12:31:38 +02:00
attr.save();
2020-01-03 13:14:43 +01:00
}
2020-06-20 12:31:38 +02:00
const childBranches = repository.getEntities(`
2020-01-03 13:14:43 +01:00
SELECT branches.*
FROM branches
WHERE branches.isDeleted = 1
AND branches.deleteId = ?
AND branches.parentNoteId = ?`, [deleteId, note.noteId]);
for (const childBranch of childBranches) {
2020-06-20 12:31:38 +02:00
undeleteBranch(childBranch, deleteId, taskContext);
2020-01-03 13:14:43 +01:00
}
}
}
/**
* @return return deleted branches of an undeleted parent note
*/
2020-06-20 12:31:38 +02:00
function getUndeletedParentBranches(noteId, deleteId) {
2021-05-02 19:59:16 +02:00
const branchIds = sql.getColumn(`
SELECT branches.branchId
2020-01-03 13:14:43 +01:00
FROM branches
JOIN notes AS parentNote ON parentNote.noteId = branches.parentNoteId
WHERE branches.noteId = ?
AND branches.isDeleted = 1
AND branches.deleteId = ?
AND parentNote.isDeleted = 0`, [noteId, deleteId]);
2021-05-02 19:59:16 +02:00
return branchIds.map(branchId => becca.getBranch(branchId));
2020-01-03 13:14:43 +01:00
}
2020-06-20 12:31:38 +02:00
function scanForLinks(note) {
if (!note || !['text', 'relation-map'].includes(note.type)) {
return;
}
try {
2020-06-20 12:31:38 +02:00
const content = note.getContent();
const newContent = saveLinks(note, content);
if (content !== newContent) {
2020-06-20 12:31:38 +02:00
note.setContent(newContent);
}
}
catch (e) {
2020-03-26 16:59:40 +01:00
log.error(`Could not scan for links note ${note.noteId}: ${e.message} ${e.stack}`);
}
}
2020-12-14 13:47:33 +01:00
function eraseNotes(noteIdsToErase) {
if (noteIdsToErase.length === 0) {
return;
}
2020-12-14 13:47:33 +01:00
sql.executeMany(`DELETE FROM notes WHERE noteId IN (???)`, noteIdsToErase);
sql.executeMany(`UPDATE entity_changes SET isErased = 1 WHERE entityName = 'notes' AND entityId IN (???)`, noteIdsToErase);
2020-12-14 13:47:33 +01:00
sql.executeMany(`DELETE FROM note_contents WHERE noteId IN (???)`, noteIdsToErase);
sql.executeMany(`UPDATE entity_changes SET isErased = 1 WHERE entityName = 'note_contents' AND entityId IN (???)`, noteIdsToErase);
2019-11-01 22:09:51 +01:00
2020-12-14 13:47:33 +01:00
// we also need to erase all "dependent" entities of the erased notes
const branchIdsToErase = sql.getManyRows(`SELECT branchId FROM branches WHERE noteId IN (???)`, noteIdsToErase)
.map(row => row.branchId);
eraseBranches(branchIdsToErase);
const attributeIdsToErase = sql.getManyRows(`SELECT attributeId FROM attributes WHERE noteId IN (???)`, noteIdsToErase)
.map(row => row.attributeId);
eraseAttributes(attributeIdsToErase);
const noteRevisionIdsToErase = sql.getManyRows(`SELECT noteRevisionId FROM note_revisions WHERE noteId IN (???)`, noteIdsToErase)
.map(row => row.noteRevisionId);
2020-12-16 14:36:24 +01:00
noteRevisionService.eraseNoteRevisions(noteRevisionIdsToErase);
2020-12-14 13:47:33 +01:00
log.info(`Erased notes: ${JSON.stringify(noteIdsToErase)}`);
}
function eraseBranches(branchIdsToErase) {
if (branchIdsToErase.length === 0) {
2019-11-12 22:26:25 +01:00
return;
}
2020-12-14 13:47:33 +01:00
sql.executeMany(`DELETE FROM branches WHERE branchId IN (???)`, branchIdsToErase);
2020-12-14 13:47:33 +01:00
sql.executeMany(`UPDATE entity_changes SET isErased = 1 WHERE entityName = 'branches' AND entityId IN (???)`, branchIdsToErase);
}
function eraseAttributes(attributeIdsToErase) {
if (attributeIdsToErase.length === 0) {
return;
}
sql.executeMany(`DELETE FROM attributes WHERE attributeId IN (???)`, attributeIdsToErase);
sql.executeMany(`UPDATE entity_changes SET isErased = 1 WHERE entityName = 'attributes' AND entityId IN (???)`, attributeIdsToErase);
}
function eraseDeletedEntities(eraseEntitiesAfterTimeInSeconds = null) {
if (eraseEntitiesAfterTimeInSeconds === null) {
eraseEntitiesAfterTimeInSeconds = optionService.getOptionInt('eraseEntitiesAfterTimeInSeconds');
}
const cutoffDate = new Date(Date.now() - eraseEntitiesAfterTimeInSeconds * 1000);
const noteIdsToErase = sql.getColumn("SELECT noteId FROM notes WHERE isDeleted = 1 AND utcDateModified <= ?", [dateUtils.utcDateStr(cutoffDate)]);
eraseNotes(noteIdsToErase);
const branchIdsToErase = sql.getColumn("SELECT branchId FROM branches WHERE isDeleted = 1 AND utcDateModified <= ?", [dateUtils.utcDateStr(cutoffDate)]);
eraseBranches(branchIdsToErase);
const attributeIdsToErase = sql.getColumn("SELECT attributeId FROM attributes WHERE isDeleted = 1 AND utcDateModified <= ?", [dateUtils.utcDateStr(cutoffDate)]);
eraseAttributes(attributeIdsToErase);
}
function eraseDeletedNotesNow() {
2020-12-14 13:47:33 +01:00
eraseDeletedEntities(0);
}
// do a replace in str - all keys should be replaced by the corresponding values
function replaceByMap(str, mapObj) {
const re = new RegExp(Object.keys(mapObj).join("|"),"g");
return str.replace(re, matched => mapObj[matched]);
}
function duplicateSubtree(origNoteId, newParentNoteId) {
if (origNoteId === 'root') {
throw new Error('Duplicating root is not possible');
}
2021-02-14 11:43:31 +01:00
log.info(`Duplicating ${origNoteId} subtree into ${newParentNoteId}`);
2020-12-18 22:35:40 +01:00
2021-04-25 22:02:32 +02:00
const origNote = becca.notes[origNoteId];
// might be null if orig note is not in the target newParentNoteId
const origBranch = origNote.getBranches().find(branch => branch.parentNoteId === newParentNoteId);
const noteIdMapping = getNoteIdMapping(origNote);
const res = duplicateSubtreeInner(origNote, origBranch, newParentNoteId, noteIdMapping);
if (!res.note.title.endsWith('(dup)')) {
res.note.title += " (dup)";
}
res.note.save();
2019-10-19 12:36:16 +02:00
return res;
}
function duplicateSubtreeWithoutRoot(origNoteId, newNoteId) {
if (origNoteId === 'root') {
throw new Error('Duplicating root is not possible');
}
2021-05-02 11:23:58 +02:00
const origNote = becca.getNote(origNoteId);
const noteIdMapping = getNoteIdMapping(origNote);
for (const childBranch of origNote.getChildBranches()) {
duplicateSubtreeInner(childBranch.getNote(), childBranch, newNoteId, noteIdMapping);
}
}
function duplicateSubtreeInner(origNote, origBranch, newParentNoteId, noteIdMapping) {
2019-10-19 12:36:16 +02:00
if (origNote.isProtected && !protectedSessionService.isProtectedSessionAvailable()) {
2021-02-14 11:43:31 +01:00
throw new Error(`Cannot duplicate note=${origNote.noteId} because it is protected and protected session is not available. Enter protected session and try again.`);
2019-10-19 12:36:16 +02:00
}
const newNoteId = noteIdMapping[origNote.noteId];
2021-04-30 22:13:13 +02:00
const newBranch = new BeccaBranch({
noteId: newNoteId,
parentNoteId: newParentNoteId,
// here increasing just by 1 to make sure it's directly after original
notePosition: origBranch ? origBranch.notePosition + 1 : null
}).save();
2021-04-25 22:02:32 +02:00
const existingNote = becca.notes[newNoteId];
2021-04-25 22:02:32 +02:00
if (existingNote.title !== undefined) { // checking that it's not just note's skeleton created because of Branch above
// note has multiple clones and was already created from another placement in the tree
// so a branch is all we need for this clone
return {
note: existingNote,
branch: newBranch
}
}
2021-04-30 22:13:13 +02:00
const newNote = new BeccaNote(origNote);
newNote.noteId = newNoteId;
newNote.dateCreated = dateUtils.localNowDateTime();
newNote.utcDateCreated = dateUtils.utcNowDateTime();
2020-06-20 12:31:38 +02:00
newNote.save();
let content = origNote.getContent();
if (['text', 'relation-map', 'search'].includes(origNote.type)) {
// fix links in the content
content = replaceByMap(content, noteIdMapping);
}
newNote.setContent(content);
2019-10-19 12:36:16 +02:00
2020-06-20 12:31:38 +02:00
for (const attribute of origNote.getOwnedAttributes()) {
2021-04-30 22:13:13 +02:00
const attr = new BeccaAttribute(attribute);
2019-10-19 12:36:16 +02:00
attr.attributeId = undefined; // force creation of new attribute
attr.noteId = newNote.noteId;
// if relation points to within the duplicated tree then replace the target to the duplicated note
// if it points outside of duplicated tree then keep the original target
if (attr.type === 'relation' && attr.value in noteIdMapping) {
attr.value = noteIdMapping[attr.value];
}
2020-06-20 12:31:38 +02:00
attr.save();
2019-10-19 12:36:16 +02:00
}
for (const childBranch of origNote.getChildBranches()) {
duplicateSubtreeInner(childBranch.getNote(), childBranch, newNote.noteId, noteIdMapping);
}
2019-10-19 12:36:16 +02:00
return {
note: newNote,
branch: newBranch
};
}
function getNoteIdMapping(origNote) {
const noteIdMapping = {};
// pregenerate new noteIds since we'll need to fix relation references even for not yet created notes
for (const origNoteId of origNote.getDescendantNoteIds()) {
noteIdMapping[origNoteId] = utils.newEntityId();
}
return noteIdMapping;
}
2020-06-20 21:42:41 +02:00
sqlInit.dbReady.then(() => {
// first cleanup kickoff 5 minutes after startup
2020-12-14 13:47:33 +01:00
setTimeout(cls.wrap(() => eraseDeletedEntities()), 5 * 60 * 1000);
2020-12-14 13:47:33 +01:00
setInterval(cls.wrap(() => eraseDeletedEntities()), 4 * 3600 * 1000);
2020-06-20 21:42:41 +02:00
});
module.exports = {
createNewNote,
2019-11-16 12:28:47 +01:00
createNewNoteWithTarget,
updateNote,
deleteBranch,
2020-01-03 13:14:43 +01:00
undeleteNote,
protectNoteRecursively,
2019-10-19 12:36:16 +02:00
scanForLinks,
duplicateSubtree,
duplicateSubtreeWithoutRoot,
getUndeletedParentBranches,
triggerNoteTitleChanged,
eraseDeletedNotesNow
};