trilium/src/services/note_cache.js

475 lines
14 KiB
JavaScript
Raw Normal View History

2018-04-18 12:26:42 +08:00
const sql = require('./sql');
const sqlInit = require('./sql_init');
const eventService = require('./events');
const repository = require('./repository');
const protectedSessionService = require('./protected_session');
const utils = require('./utils');
const hoistedNoteService = require('./hoisted_note');
const stringSimilarity = require('string-similarity');
2018-04-18 12:26:42 +08:00
let loaded = false;
let noteTitles = {};
let protectedNoteTitles = {};
2018-04-18 12:26:42 +08:00
let noteIds;
2018-06-05 11:21:45 +08:00
let childParentToBranchId = {};
2018-04-18 12:26:42 +08:00
const childToParent = {};
let archived = {};
2018-04-18 12:26:42 +08:00
2018-04-20 08:59:44 +08:00
// key is 'childNoteId-parentNoteId' as a replacement for branchId which we don't use here
let prefixes = {};
2018-04-18 12:26:42 +08:00
async function load() {
noteTitles = await sql.getMap(`SELECT noteId, title FROM notes WHERE isDeleted = 0 AND isProtected = 0`);
2018-04-18 12:26:42 +08:00
noteIds = Object.keys(noteTitles);
prefixes = await sql.getMap(`SELECT noteId || '-' || parentNoteId, prefix FROM branches WHERE prefix IS NOT NULL AND prefix != ''`);
2018-04-20 08:59:44 +08:00
2018-06-05 11:21:45 +08:00
const relations = await sql.getRows(`SELECT branchId, noteId, parentNoteId FROM branches WHERE isDeleted = 0`);
2018-04-18 12:26:42 +08:00
for (const rel of relations) {
childToParent[rel.noteId] = childToParent[rel.noteId] || [];
childToParent[rel.noteId].push(rel.parentNoteId);
2018-06-05 11:21:45 +08:00
childParentToBranchId[`${rel.noteId}-${rel.parentNoteId}`] = rel.branchId;
2018-04-18 12:26:42 +08:00
}
archived = await sql.getMap(`SELECT noteId, isInheritable FROM attributes WHERE isDeleted = 0 AND type = 'label' AND name = 'archived'`);
if (protectedSessionService.isProtectedSessionAvailable()) {
await loadProtectedNotes();
}
for (const noteId in childToParent) {
resortChildToParent(noteId);
}
loaded = true;
2018-04-18 12:26:42 +08:00
}
async function loadProtectedNotes() {
protectedNoteTitles = await sql.getMap(`SELECT noteId, title FROM notes WHERE isDeleted = 0 AND isProtected = 1`);
for (const noteId in protectedNoteTitles) {
protectedNoteTitles[noteId] = protectedSessionService.decryptNoteTitle(noteId, protectedNoteTitles[noteId]);
}
}
function highlightResults(results, allTokens) {
// we remove < signs because they can cause trouble in matching and overwriting existing highlighted chunks
// which would make the resulting HTML string invalid.
// { and } are used for marking <b> and </b> tag (to avoid matches on single 'b' character)
allTokens = allTokens.map(token => token.replace('/[<\{\}]/g', ''));
// sort by the longest so we first highlight longest matches
allTokens.sort((a, b) => a.length > b.length ? -1 : 1);
2018-11-08 00:16:33 +08:00
for (const result of results) {
result.highlighted = result.title;
}
for (const token of allTokens) {
const tokenRegex = new RegExp("(" + utils.escapeRegExp(token) + ")", "gi");
for (const result of results) {
result.highlighted = result.highlighted.replace(tokenRegex, "{$1}");
}
}
for (const result of results) {
result.highlighted = result.highlighted
.replace(/{/g, "<b>")
.replace(/}/g, "</b>");
}
}
async function findNotes(query) {
if (!noteTitles || !query.length) {
2018-04-18 12:26:42 +08:00
return [];
}
// trim is necessary because even with .split() trailing spaces are tokens which causes havoc
2018-11-08 00:16:33 +08:00
// filtering '/' because it's used as separator
const allTokens = query.trim().toLowerCase().split(" ").filter(token => token !== '/');
const tokens = allTokens.slice();
let results = [];
2018-04-18 12:26:42 +08:00
let noteIds = Object.keys(noteTitles);
if (protectedSessionService.isProtectedSessionAvailable()) {
noteIds = noteIds.concat(Object.keys(protectedNoteTitles));
}
for (const noteId of noteIds) {
// autocomplete should be able to find notes by their noteIds as well (only leafs)
if (noteId === query) {
search(noteId, [], [], results);
continue;
}
// for leaf note it doesn't matter if "archived" label is inheritable or not
if (noteId in archived) {
continue;
}
2018-04-20 08:59:44 +08:00
const parents = childToParent[noteId];
if (!parents) {
continue;
}
2018-04-18 12:26:42 +08:00
2018-04-20 08:59:44 +08:00
for (const parentNoteId of parents) {
// for parent note archived needs to be inheritable
if (archived[parentNoteId] === 1) {
2018-05-26 22:50:13 +08:00
continue;
}
2018-06-05 08:22:41 +08:00
const title = getNoteTitle(noteId, parentNoteId).toLowerCase();
2018-04-20 08:59:44 +08:00
const foundTokens = [];
for (const token of tokens) {
if (title.includes(token)) {
foundTokens.push(token);
}
2018-04-18 12:26:42 +08:00
}
2018-04-20 08:59:44 +08:00
if (foundTokens.length > 0) {
const remainingTokens = tokens.filter(token => !foundTokens.includes(token));
2018-04-18 12:26:42 +08:00
2018-04-20 08:59:44 +08:00
search(parentNoteId, remainingTokens, [noteId], results);
}
2018-04-18 12:26:42 +08:00
}
}
if (hoistedNoteService.getHoistedNoteId() !== 'root') {
results = results.filter(res => res.pathArray.includes(hoistedNoteService.getHoistedNoteId()));
}
// sort results by depth of the note. This is based on the assumption that more important results
// are closer to the note root.
results.sort((a, b) => {
if (a.pathArray.length === b.pathArray.length) {
return a.title < b.title ? -1 : 1;
}
return a.pathArray.length < b.pathArray.length ? -1 : 1;
});
const apiResults = results.slice(0, 200).map(res => {
return {
noteId: res.noteId,
branchId: res.branchId,
path: res.pathArray.join('/'),
title: res.titleArray.join(' / ')
};
});
highlightResults(apiResults, allTokens);
return apiResults;
2018-04-18 12:26:42 +08:00
}
function isArchived(notePath) {
// if the note is archived directly
if (archived[notePath[notePath.length - 1]] !== undefined) {
return true;
}
for (let i = 0; i < notePath.length - 1; i++) {
// this is going through parents so archived must be inheritable
if (archived[notePath[i]] === 1) {
return true;
}
}
return false;
}
2018-04-20 08:59:44 +08:00
function search(noteId, tokens, path, results) {
if (tokens.length === 0) {
2018-04-20 08:59:44 +08:00
const retPath = getSomePath(noteId, path);
2018-04-18 12:26:42 +08:00
if (retPath && !isArchived(retPath)) {
2018-06-05 11:21:45 +08:00
const thisNoteId = retPath[retPath.length - 1];
const thisParentNoteId = retPath[retPath.length - 2];
2018-04-18 12:26:42 +08:00
results.push({
2018-06-05 11:21:45 +08:00
noteId: thisNoteId,
branchId: childParentToBranchId[`${thisNoteId}-${thisParentNoteId}`],
pathArray: retPath,
titleArray: getNoteTitleArrayForPath(retPath)
});
}
return;
}
2018-04-20 08:59:44 +08:00
const parents = childToParent[noteId];
if (!parents || noteId === 'root') {
2018-04-20 08:59:44 +08:00
return;
}
for (const parentNoteId of parents) {
// archived must be inheritable
if (archived[parentNoteId] === 1) {
2018-04-18 12:26:42 +08:00
continue;
}
2018-05-26 22:50:13 +08:00
const title = getNoteTitle(noteId, parentNoteId).toLowerCase();
2018-04-18 12:26:42 +08:00
const foundTokens = [];
for (const token of tokens) {
if (title.includes(token)) {
foundTokens.push(token);
}
}
if (foundTokens.length > 0) {
const remainingTokens = tokens.filter(token => !foundTokens.includes(token));
2018-04-20 08:59:44 +08:00
search(parentNoteId, remainingTokens, path.concat([noteId]), results);
2018-04-18 12:26:42 +08:00
}
else {
2018-04-20 08:59:44 +08:00
search(parentNoteId, tokens, path.concat([noteId]), results);
2018-04-18 12:26:42 +08:00
}
}
}
2018-06-05 08:22:41 +08:00
function getNoteTitle(noteId, parentNoteId) {
const prefix = prefixes[noteId + '-' + parentNoteId];
let title = noteTitles[noteId];
if (!title) {
if (protectedSessionService.isProtectedSessionAvailable()) {
title = protectedNoteTitles[noteId];
}
else {
title = '[protected]';
}
}
return (prefix ? (prefix + ' - ') : '') + title;
}
function getNoteTitleArrayForPath(path) {
2018-04-20 08:59:44 +08:00
const titles = [];
2018-04-18 12:26:42 +08:00
2018-12-14 04:43:13 +08:00
if (path[0] === hoistedNoteService.getHoistedNoteId() && path.length === 1) {
return [ getNoteTitle(hoistedNoteService.getHoistedNoteId()) ];
2018-06-07 10:38:36 +08:00
}
2018-04-20 08:59:44 +08:00
let parentNoteId = 'root';
let hoistedNotePassed = false;
2018-04-18 12:26:42 +08:00
2018-04-20 08:59:44 +08:00
for (const noteId of path) {
// start collecting path segment titles only after hoisted note
if (hoistedNotePassed) {
const title = getNoteTitle(noteId, parentNoteId);
titles.push(title);
}
if (noteId === hoistedNoteService.getHoistedNoteId()) {
hoistedNotePassed = true;
}
2018-04-20 08:59:44 +08:00
parentNoteId = noteId;
}
return titles;
}
function getNoteTitleForPath(path) {
const titles = getNoteTitleArrayForPath(path);
2018-04-20 08:59:44 +08:00
return titles.join(' / ');
}
/**
* Returns notePath for noteId from cache. Note hoisting is respected.
* Archived notes are also returned, but non-archived paths are preferred if available
* - this means that archived paths is returned only if there's no non-archived path
* - you can check whether returned path is archived using isArchived()
*/
function getSomePath(noteId, path = []) {
2018-04-20 08:59:44 +08:00
if (noteId === 'root') {
2018-12-14 04:43:13 +08:00
path.push(noteId);
path.reverse();
if (!path.includes(hoistedNoteService.getHoistedNoteId())) {
return false;
}
2018-04-20 08:59:44 +08:00
return path;
}
2018-04-20 08:59:44 +08:00
const parents = childToParent[noteId];
if (!parents || parents.length === 0) {
return false;
}
for (const parentNoteId of parents) {
const retPath = getSomePath(parentNoteId, path.concat([noteId]));
if (retPath) {
return retPath;
}
}
return false;
}
function getNotePath(noteId) {
const retPath = getSomePath(noteId);
if (retPath && !isArchived(retPath)) {
const noteTitle = getNoteTitleForPath(retPath);
2018-06-06 10:47:47 +08:00
const parentNoteId = childToParent[noteId][0];
return {
noteId: noteId,
2018-06-06 10:47:47 +08:00
branchId: childParentToBranchId[`${noteId}-${parentNoteId}`],
title: noteTitle,
path: retPath.join('/')
};
}
}
function evaluateSimilarity(text1, text2, noteId, results) {
let coeff = stringSimilarity.compareTwoStrings(text1, text2);
if (coeff > 0.4) {
const notePath = getSomePath(noteId);
// this takes care of note hoisting
if (!notePath) {
return;
}
if (isArchived(notePath)) {
coeff -= 0.2; // archived penalization
}
results.push({coeff, noteId});
}
}
function findSimilarNotes(title) {
const results = [];
for (const noteId in noteTitles) {
evaluateSimilarity(title, noteTitles[noteId], noteId, results);
}
if (protectedSessionService.isProtectedSessionAvailable()) {
for (const noteId in protectedNoteTitles) {
evaluateSimilarity(title, protectedNoteTitles[noteId], noteId, results);
}
}
results.sort((a, b) => a.coeff > b.coeff ? -1 : 1);
return results.length > 50 ? results.slice(0, 50) : results;
}
2019-01-04 06:27:10 +08:00
eventService.subscribe([eventService.ENTITY_CHANGED, eventService.ENTITY_DELETED, eventService.ENTITY_SYNCED], async ({entityName, entity}) => {
// note that entity can also be just POJO without methods if coming from sync
if (!loaded) {
return;
}
if (entityName === 'notes') {
const note = entity;
if (note.isDeleted) {
delete noteTitles[note.noteId];
delete childToParent[note.noteId];
}
else {
if (note.isProtected) {
// we can assume we have protected session since we managed to update
// removing from the maps is important when switching between protected & unprotected
protectedNoteTitles[note.noteId] = note.title;
delete noteTitles[note.noteId];
}
else {
noteTitles[note.noteId] = note.title;
delete protectedNoteTitles[note.noteId];
}
}
}
2018-04-20 08:59:44 +08:00
else if (entityName === 'branches') {
const branch = entity;
2018-04-20 08:59:44 +08:00
// first we remove records for original placement (if they exist)
childToParent[branch.noteId] = childToParent[branch.noteId] || [];
childToParent[branch.noteId] = childToParent[branch.noteId].filter(noteId => noteId !== branch.origParentNoteId);
2018-04-20 08:59:44 +08:00
delete prefixes[branch.noteId + '-' + branch.origParentNoteId];
delete childParentToBranchId[branch.noteId + '-' + branch.origParentNoteId];
if (!branch.isDeleted) {
// ... and then we create new records
2018-04-20 08:59:44 +08:00
if (branch.prefix) {
prefixes[branch.noteId + '-' + branch.parentNoteId] = branch.prefix;
}
childToParent[branch.noteId].push(branch.parentNoteId);
resortChildToParent(branch.noteId);
2018-06-05 11:21:45 +08:00
childParentToBranchId[branch.noteId + '-' + branch.parentNoteId] = branch.branchId;
2018-04-20 08:59:44 +08:00
}
}
else if (entityName === 'attributes') {
const attribute = entity;
if (attribute.type === 'label' && attribute.name === 'archived') {
// we're not using label object directly, since there might be other non-deleted archived label
2018-11-27 05:22:16 +08:00
const archivedLabel = await repository.getEntity(`SELECT * FROM attributes WHERE isDeleted = 0 AND type = 'label'
AND name = 'archived' AND noteId = ?`, [attribute.noteId]);
2018-11-27 05:22:16 +08:00
if (archivedLabel) {
archived[attribute.noteId] = archivedLabel.isInheritable ? 1 : 0;
}
else {
delete archived[attribute.noteId];
}
}
}
});
// will sort the childs so that non-archived are first and archived at the end
// this is done so that non-archived paths are always explored as first when searching for note path
function resortChildToParent(noteId) {
if (!childToParent[noteId]) {
return;
}
childToParent[noteId].sort((a, b) => archived[a] === 1 ? 1 : -1);
}
2019-04-23 00:08:33 +08:00
/**
* @param noteId
* @returns {boolean} - true if note exists (is not deleted) and is not archived.
*/
function isAvailable(noteId) {
const notePath = getNotePath(noteId);
return !!notePath;
}
eventService.subscribe(eventService.ENTER_PROTECTED_SESSION, () => {
if (loaded) {
loadProtectedNotes();
}
});
sqlInit.dbReady.then(() => utils.stopWatch("Autocomplete load", load));
2018-04-18 12:26:42 +08:00
module.exports = {
findNotes,
2018-06-07 10:38:36 +08:00
getNotePath,
getNoteTitleForPath,
2019-04-23 00:08:33 +08:00
isAvailable,
load,
findSimilarNotes
2018-04-18 12:26:42 +08:00
};