Compare commits

..

74 Commits

Author SHA1 Message Date
zadam ddc79b2517 release 0.29.1 2019-02-12 20:30:07 +01:00
zadam 8b250ed523 fix upload of the same file in succession, #388 2019-02-03 17:44:06 +01:00
zadam d8b78d8025 check reference issues only for non deleted entities 2019-02-03 16:27:26 +01:00
zadam 42112b8053 fix consistency check 2019-02-03 16:22:45 +01:00
zadam 6cc0dd5a80 release 0.29.0-beta 2019-02-03 15:44:19 +01:00
zadam afd5f4823f added Steel Blue theme to demo document 2019-02-03 15:39:27 +01:00
zadam b0cf82c91b fix 2019-02-03 15:37:01 +01:00
zadam 6a67cdd5af appThemeClass is redundant 2019-02-03 15:35:37 +01:00
zadam bad7b84993 error handling in custom request handler 2019-02-03 11:15:32 +01:00
zadam d3ca6b5ae6 styling for scrollbar which looks ugly otherwise in dark themes 2019-02-03 10:21:28 +01:00
zadam da5009f089 main border color CSS variable 2019-02-03 10:09:59 +01:00
zadam c08524c977 fix CSS class of user theme 2019-02-03 00:12:57 +01:00
zadam f89537037e small styling fixes 2019-02-02 23:51:00 +01:00
zadam c153793766 added CSS variable for disabled button background 2019-02-02 23:26:39 +01:00
zadam 0aec5927d5 added missing labels customRequestHandler, customResourceProvider to autocomplete 2019-02-02 22:33:02 +01:00
zadam 8aea9a1801 added font family CSS variables to theming API 2019-02-02 20:45:38 +01:00
zadam 73247e3220 minor library updates 2019-02-02 19:21:30 +01:00
zadam 89344a6eda final fixes and refactorings for consistency checks 2019-02-02 12:41:20 +01:00
zadam 40d2e6ea83 refactoring consistency checks WIP 2019-02-02 11:26:27 +01:00
zadam 910cfe9a17 refactoring consistency checks WIP 2019-02-02 10:38:33 +01:00
zadam e58a80fc00 consistency checks WIP 2019-02-02 09:26:57 +01:00
zadam 4a2319cb33 refactoring of consistency checks plus some autofixers 2019-02-01 22:48:51 +01:00
zadam 5619088c41 raise payload size limit to 500 MB #395 2019-01-29 21:19:08 +01:00
zadam 60271993eb Merge pull request #392 from jkurei/ios_favicon
Better icon for iOS' homescreen
2019-01-28 23:01:12 +01:00
jkurei 6695e8b011 Better icon for iOS' homescreen 2019-01-28 22:48:01 +01:00
zadam 707df18b93 added type and mime classes on body as well #383 2019-01-28 21:42:37 +01:00
zadam 90895f1288 added noteId to file view 2019-01-27 23:10:37 +01:00
zadam ba1ca506af change in referencing CSS resources to allow easier relative linking 2019-01-27 22:34:41 +01:00
zadam f90ed99a40 fix leaf node having angle bracket in dark & black themes, closes #387 2019-01-27 21:54:24 +01:00
zadam 67630b1a22 options now allow selecting user theme 2019-01-27 21:18:11 +01:00
zadam 2c1580ea65 appCss/appTheme are now loaded as external CSS files instead of inline styles 2019-01-27 17:01:37 +01:00
zadam 840a0b5f64 custom handler refactoring 2019-01-27 16:37:18 +01:00
zadam b39f6ef7ad bug fixes for custom handlers 2019-01-27 15:47:40 +01:00
zadam fb27088fcd smaller children overview font 2019-01-27 14:26:39 +01:00
azivner 76fbff68ba added readOnly attribute which puts text editor into readonly mode #371 2019-01-27 13:10:03 +01:00
azivner 54de4d236d custom HTTP handler which triggers associated script notes WIP, #356 2019-01-27 12:28:20 +01:00
azivner e211dd65ad exit on detection of not supported node version, #324 2019-01-26 19:59:51 +01:00
azivner a87f4d8653 search can be triggered from URL, closes #385 2019-01-25 22:18:34 +01:00
azivner b59c175c2e add HTML header with UTF-8 meta encoding declaration to exported HTML files, fixes #384 2019-01-25 21:34:14 +01:00
azivner 580104c4c5 using trilium's confirm dialog, small refactoring 2019-01-24 22:18:31 +01:00
zadam 0fc3053b0a Merge pull request #377 from flurmbo/master
add confirm type change dialog when note not empty
2019-01-24 22:12:09 +01:00
Phil Marshall 929e0f69c2 add confirm type change dialog when note not empty 2019-01-23 15:15:24 -06:00
azivner e70af1300a drag and drop moves multiple items only if CTRL is pressed, active note has now bold text for more differentiation from selected note 2019-01-23 21:13:04 +01:00
azivner 4d0e46021b Mac uses CMD+Left, CMD+Right for history navigation, closes #376 2019-01-23 20:15:33 +01:00
azivner 1a9a49b739 release 0.28.3 2019-01-22 23:01:32 +01:00
azivner 2ac560c56e text note should change its icon after having new note inserted into, fixes #361 2019-01-22 21:21:44 +01:00
azivner c23387c0fb make search dialog more responsive in narrow sidebar, fixes #367 2019-01-22 20:54:00 +01:00
azivner 0ff250fe15 font sizes were not created for new documents - fix plus migration for existing ones 2019-01-22 20:34:45 +01:00
azivner 52b1e58b26 make tree selection more visually consistent 2019-01-22 20:23:54 +01:00
azivner 484715e440 fix icon in desktop linux build, fixes #372 2019-01-22 19:49:33 +01:00
azivner 9d42c3d802 release 0.28.2 2019-01-21 22:55:12 +01:00
azivner c654172d33 auto fixer for "undeleted branch of deleted note" consistency check 2019-01-21 22:51:49 +01:00
azivner e17b26c883 revert consistency checks refactoring for now 2019-01-21 22:46:27 +01:00
azivner 24d02d9cf5 fix in task manager script to not error out so much on deletion 2019-01-21 22:05:37 +01:00
azivner 7208a311ac check that note is not deleted before creating a branch 2019-01-21 21:55:40 +01:00
azivner ad7355372b issue template 2019-01-21 19:55:07 +01:00
azivner f18b5babad uncommented issue template 2019-01-20 16:47:49 +01:00
azivner 9831ec0ca9 added issue template 2019-01-20 16:46:56 +01:00
azivner 596544eca3 fix setNoteToParent API method, closes #360 2019-01-20 16:33:09 +01:00
azivner 1f853024ee more autofixers WIP 2019-01-19 09:57:51 +01:00
azivner 0308b13460 expose app info on the backend script api #345 2019-01-18 23:57:08 +01:00
azivner 06b8a82f70 refactoring of consistency checks + some auto fixers 2019-01-18 19:32:59 +01:00
azivner 91ca07929d before we clone the note we must make sure it's not deleted 2019-01-17 23:24:59 +01:00
azivner afabaa5fdb workaround for hidden last line on mobile 2019-01-17 21:13:53 +01:00
azivner a6fd3fa77c release 0.28.1-beta 2019-01-17 00:03:17 +01:00
azivner 58a2c08dcd release 0.28.1-beta 2019-01-16 23:58:10 +01:00
azivner 299bbff2f4 fix too large font on mobile 2019-01-16 23:57:09 +01:00
azivner 19d8947123 runOnNoteChange fires also on the frontend, closes #340 2019-01-16 22:52:32 +01:00
azivner 35edce7523 fix crazy clipboard operation on mac setup, closes #348 2019-01-16 22:03:30 +01:00
azivner bc4cec69a5 use local dates to create day notes, closes #337 2019-01-15 23:46:01 +01:00
azivner cce8c1b674 create top level note and collapse tree now work relative to hoisted note, closes #343 2019-01-15 20:30:54 +01:00
azivner aa58788769 added basic DB size diagnostic log 2019-01-15 20:00:24 +01:00
azivner 6c62ab7a52 removing logging params for slow queries 2019-01-15 19:36:04 +01:00
azivner d6ab638b30 fix file names in github release script 2019-01-15 00:10:47 +01:00
72 changed files with 2809 additions and 892 deletions
+5 -1
View File
@@ -11,10 +11,14 @@ cp -r bin/deps/linux-x64/sqlite/* node_modules/sqlite3/lib/binding/
mv "./dist/Trilium Notes-linux-x64" $BUILD_DIR
cp src/public/images/app-icons/png/128x128.png $BUILD_DIR/icon.png
# removing software WebGL binaries because they are pretty huge and not necessary
rm -r $BUILD_DIR/swiftshader
echo "Packaging linux x64 electron distribution..."
VERSION=`jq -r ".version" package.json`
tar cJf $BUILD_DIR-${VERSION}.tar.xz $BUILD_DIR
cd dist
tar cJf trilium-linux-x64-${VERSION}.tar.xz trilium-linux-x64
+1 -1
View File
@@ -35,4 +35,4 @@ cd ..
VERSION=`jq -r ".version" ../package.json`
tar cJf trilium-linux-x64-server-${VERSION}.tar.gz trilium-linux-x64-server
tar cJf trilium-linux-x64-server-${VERSION}.tar.xz trilium-linux-x64-server
+2 -2
View File
@@ -42,10 +42,10 @@ git push origin $TAG
bin/build.sh
LINUX_X64_BUILD=trilium-linux-x64-$VERSION.tar.gz
LINUX_X64_BUILD=trilium-linux-x64-$VERSION.tar.xz
WINDOWS_X64_BUILD=trilium-windows-x64-$VERSION.zip
MAC_X64_BUILD=trilium-mac-x64-$VERSION.zip
SERVER_BUILD=trilium-linux-x64-server-$VERSION.tar.gz
SERVER_BUILD=trilium-linux-x64-server-$VERSION.tar.xz
echo "Creating release in GitHub"
BIN
View File
Binary file not shown.
+11
View File
@@ -0,0 +1,11 @@
INSERT INTO options (name, value, dateCreated, dateModified, isSynced)
SELECT 'mainFontSize', '100', '2019-01-13T18:31:00.874Z', '2019-01-13T18:31:00.874Z', 0
WHERE NOT EXISTS (SELECT 1 FROM options WHERE name = 'mainFontSize');
INSERT INTO options (name, value, dateCreated, dateModified, isSynced)
SELECT 'treeFontSize', '100', '2019-01-13T18:31:00.874Z', '2019-01-13T18:31:00.874Z', 0
WHERE NOT EXISTS (SELECT 1 FROM options WHERE name = 'treeFontSize');
INSERT INTO options (name, value, dateCreated, dateModified, isSynced)
SELECT 'detailFontSize', '110', '2019-01-13T18:31:00.874Z', '2019-01-13T18:31:00.874Z', 0
WHERE NOT EXISTS (SELECT 1 FROM options WHERE name = 'detailFontSize');
+1 -1
View File
@@ -81,7 +81,7 @@ app.on('ready', async () => {
const dateNoteService = require('./src/services/date_notes');
const dateUtils = require('./src/services/date_utils');
const parentNote = await dateNoteService.getDateNote(dateUtils.nowDate());
const parentNote = await dateNoteService.getDateNote(dateUtils.nowLocalDate());
// window may be hidden / not in focus
mainWindow.focus();
+5
View File
@@ -0,0 +1,5 @@
For bug reports, please mention **version of the application** and include **log files** from following location:
* `/home/[user]/.local/share/trilium-data/log` for Linux
* `C:\Users\[user]\AppData\Roaming\trilium-data\log` for Windows Vista and up
* `/Users/[user]/Library/Application Support/trilium-data/log` for Mac OS
+1829 -480
View File
File diff suppressed because it is too large Load Diff
+18 -17
View File
@@ -2,7 +2,7 @@
"name": "trilium",
"productName": "Trilium Notes",
"description": "Trilium Notes",
"version": "0.28.0-beta",
"version": "0.29.1",
"license": "AGPL-3.0-only",
"main": "electron.js",
"bin": {
@@ -29,53 +29,54 @@
"cookie-parser": "1.4.3",
"debug": "4.1.1",
"ejs": "2.6.1",
"electron-debug": "2.0.0",
"electron-dl": "1.12.0",
"electron-debug": "2.1.0",
"electron-dl": "1.13.0",
"electron-in-page-search": "1.3.2",
"express": "4.16.4",
"express-session": "1.15.6",
"file-type": "10.7.0",
"file-type": "10.7.1",
"fs-extra": "7.0.1",
"get-port": "4.1.0",
"helmet": "3.15.0",
"html": "1.0.0",
"image-type": "3.0.0",
"imagemin": "6.0.0",
"imagemin": "6.1.0",
"imagemin-giflossy": "5.1.10",
"imagemin-mozjpeg": "8.0.0",
"imagemin-pngquant": "6.0.0",
"imagemin-pngquant": "7.0.0",
"ini": "1.3.5",
"jimp": "0.6.0",
"mime-types": "^2.1.21",
"moment": "2.23.0",
"moment": "2.24.0",
"multer": "1.4.1",
"node-abi": "2.5.1",
"node-abi": "2.6.0",
"open": "0.0.5",
"rand-token": "0.4.0",
"rcedit": "1.1.1",
"rimraf": "2.6.2",
"rimraf": "2.6.3",
"sanitize-filename": "1.6.1",
"sax": "^1.2.4",
"semver": "^5.6.0",
"serve-favicon": "2.5.0",
"session-file-store": "1.2.0",
"simple-node-logger": "18.12.21",
"sqlite": "3.0.0",
"sqlite": "3.0.1",
"tar-stream": "1.6.2",
"turndown": "5.0.1",
"turndown": "5.0.3",
"unescape": "1.0.1",
"ws": "6.1.2",
"ws": "6.1.3",
"xml2js": "0.4.19"
},
"devDependencies": {
"devtron": "1.4.0",
"electron": "4.0.1",
"electron-builder": "20.38.4",
"electron-compile": "6.4.3",
"electron": "4.0.3",
"electron-builder": "20.38.5",
"electron-compile": "6.4.4",
"electron-packager": "13.0.1",
"electron-rebuild": "1.8.2",
"lorem-ipsum": "1.0.6",
"tape": "4.9.1",
"xo": "0.23.0"
"tape": "4.9.2",
"xo": "0.24.0"
},
"xo": {
"envs": [
+3 -1
View File
@@ -39,7 +39,7 @@ app.use((req, res, next) => {
});
});
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.json({limit: '500mb'}));
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
@@ -63,6 +63,8 @@ app.use(favicon(__dirname + '/public/images/app-icons/win/icon.ico'));
require('./routes/routes').register(app);
require('./routes/custom').register(app);
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Router not found for request ' + req.url);
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

+7
View File
@@ -37,6 +37,7 @@ import noteTypeService from './services/note_type.js';
import linkService from './services/link.js';
import noteAutocompleteService from './services/note_autocomplete.js';
import macInit from './services/mac_init.js';
import cssLoader from './services/css_loader.js';
// required for CKEditor image upload plugin
window.glob.getCurrentNode = treeService.getCurrentNode;
@@ -79,6 +80,10 @@ window.onerror = function (msg, url, lineNo, columnNo, error) {
return false;
};
for (const appCssNoteId of window.appCssNoteIds) {
cssLoader.requireCss(`/api/notes/download/${appCssNoteId}`);
}
const wikiBaseUrl = "https://github.com/zadam/trilium/wiki/";
$(document).on("click", "button[data-help-page]", e => {
@@ -121,6 +126,8 @@ $("#export-note-button").click(function () {
macInit.init();
searchNotesService.init(); // should be in front of treeService since that one manipulates address bar hash
treeService.showTree();
entrypoints.registerEntrypoints();
+1 -1
View File
@@ -97,7 +97,7 @@ function AttributesModel() {
await showAttributes(attributes);
// attribute might not be rendered immediatelly so could not focus
setTimeout(() => $(".attribute-type-select:last").focus(), 100);
setTimeout(() => $(".attribute-type-select:last").focus(), 1000);
};
this.deleteAttribute = function(data, event) {
+26 -2
View File
@@ -5,6 +5,7 @@ import server from '../services/server.js';
import infoService from "../services/info.js";
import zoomService from "../services/zoom.js";
import utils from "../services/utils.js";
import cssLoader from "../services/css_loader.js";
const $dialog = $("#options-dialog");
@@ -50,7 +51,22 @@ addTabHandler((function() {
const $body = $("body");
const $container = $("#container");
function optionsLoaded(options) {
async function optionsLoaded(options) {
const themes = [
{ val: 'white', title: 'White' },
{ val: 'dark', title: 'Dark' },
{ val: 'black', title: 'Black' }
].concat(await server.get('options/user-themes'));
$themeSelect.empty();
for (const theme of themes) {
$themeSelect.append($("<option>")
.attr("value", theme.val)
.attr("data-note-id", theme.noteId)
.html(theme.title));
}
$themeSelect.val(options.theme);
if (utils.isElectron()) {
@@ -71,12 +87,20 @@ addTabHandler((function() {
$themeSelect.change(function() {
const newTheme = $(this).val();
for (const clazz of $body[0].classList) {
for (const clazz of Array.from($body[0].classList)) { // create copy to safely iterate over while removing classes
if (clazz.startsWith("theme-")) {
$body.removeClass(clazz);
}
}
const noteId = $(this).find(":selected").attr("data-note-id");
if (noteId) {
// make sure the CSS is loaded
// if the CSS has been loaded and then updated then the changes won't take effect though
cssLoader.requireCss(`/api/notes/download/${noteId}`);
}
$body.addClass("theme-" + newTheme);
server.put('options/theme/' + newTheme);
@@ -160,7 +160,7 @@ async function createPromotedAttributeRow(definitionAttr, valueAttr) {
$input.autocomplete({
appendTo: document.querySelector('body'),
hint: false,
autoselect: true,
autoselect: false,
openOnFocus: true,
minLength: 0,
tabAutocomplete: false
+6 -2
View File
@@ -30,9 +30,13 @@ async function executeStartupBundles() {
}
async function executeRelationBundles(note, relationName) {
const bundlesToRun = await server.get("script/relation/" + note.noteId + "/" + relationName);
note.bundleCache = note.bundleCache || {};
for (const bundle of bundlesToRun) {
if (!note.bundleCache[relationName]) {
note.bundleCache[relationName] = await server.get("script/relation/" + note.noteId + "/" + relationName);
}
for (const bundle of note.bundleCache[relationName]) {
await executeBundle(bundle, note);
}
}
@@ -0,0 +1,13 @@
async function requireCss(url) {
const css = Array
.from(document.querySelectorAll('link'))
.map(scr => scr.href);
if (!css.includes(url)) {
$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', url));
}
}
export default {
requireCss
}
@@ -9,6 +9,14 @@ const dragAndDropSetup = {
return false;
}
if (!data.originalEvent.ctrlKey) {
// keep existing selection only if CTRL key is pressed
for (const selectedNode of treeService.getSelectedNodes()) {
selectedNode.setSelected(false);
selectedNode.renderTitle();
}
}
node.setSelected(true);
// this is for dragging notes into relation map
@@ -61,8 +61,15 @@ function registerEntrypoints() {
$("#history-back-button").click(window.history.back);
$("#history-forward-button").click(window.history.forward);
utils.bindShortcut('alt+left', window.history.back);
utils.bindShortcut('alt+right', window.history.forward);
if (utils.isMac()) {
// Mac has a different history navigation shortcuts - https://github.com/zadam/trilium/issues/376
utils.bindShortcut('meta+left', window.history.back);
utils.bindShortcut('meta+right', window.history.forward);
}
else {
utils.bindShortcut('alt+left', window.history.back);
utils.bindShortcut('alt+right', window.history.forward);
}
}
utils.bindShortcut('alt+m', e => {
@@ -23,6 +23,10 @@ $("#import-upload").change(async function() {
const formData = new FormData();
formData.append('upload', this.files[0]);
// this is done to reset the field otherwise triggering import same file again would not work
// https://github.com/zadam/trilium/issues/388
$("#import-upload").val('');
await $.ajax({
url: baseApiUrl + 'notes/' + importNoteId + '/import',
headers: server.getHeaders(),
+4
View File
@@ -10,6 +10,10 @@ $("#file-upload").change(async function() {
const formData = new FormData();
formData.append('upload', this.files[0]);
// this is done to reset the field otherwise triggering import same file again would not work
// https://github.com/zadam/trilium/issues/388
$("#file-upload").val('');
const resp = await $.ajax({
url: baseApiUrl + 'notes/' + noteDetailService.getCurrentNoteId() + '/upload',
headers: server.getHeaders(),
@@ -1,3 +1,5 @@
import cssLoader from './css_loader.js';
const CKEDITOR = {"js": ["libraries/ckeditor/ckeditor.js"]};
const CODE_MIRROR = {
@@ -34,7 +36,7 @@ const RELATION_MAP = {
async function requireLibrary(library) {
if (library.css) {
library.css.map(cssUrl => requireCss(cssUrl));
library.css.map(cssUrl => cssLoader.requireCss(cssUrl));
}
if (library.js) {
@@ -59,16 +61,6 @@ async function requireScript(url) {
await loadedScriptPromises[url];
}
async function requireCss(url) {
const css = Array
.from(document.querySelectorAll('link'))
.map(scr => scr.href);
if (!css.includes(url)) {
$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', url));
}
}
export default {
requireLibrary,
CKEDITOR,
+1
View File
@@ -107,6 +107,7 @@ function init() {
$(document).on('click', "a[data-action='note']", goToLink);
$(document).on('click', 'div.popover-content a, div.ui-tooltip-content a', goToLink);
$(document).on('dblclick', '#note-detail-text a', goToLink);
$(document).on('click', '#note-detail-text.ck-read-only a', goToLink);
$(document).on('click', 'span.ck-button__label', e => {
// this is a link preview dialog from CKEditor link editing
// for some reason clicked element is span
+22 -9
View File
@@ -30,6 +30,7 @@ const $noteIdDisplay = $("#note-id-display");
const $childrenOverview = $("#children-overview");
const $scriptArea = $("#note-detail-script-area");
const $savedIndicator = $("#saved-indicator");
const $body = $("body");
let currentNote = null;
@@ -131,6 +132,9 @@ async function saveNote() {
}
$savedIndicator.fadeIn();
// run async
bundleService.executeRelationBundles(getCurrentNote(), 'runOnNoteChange');
}
async function saveNoteIfChanged() {
@@ -142,12 +146,21 @@ async function saveNoteIfChanged() {
$savedIndicator.fadeIn();
}
function setNoteBackgroundIfProtected(note) {
$noteDetailWrapper.toggleClass("protected", note.isProtected);
$protectButton.toggleClass("active", note.isProtected);
$protectButton.prop("disabled", note.isProtected);
$unprotectButton.toggleClass("active", !note.isProtected);
$unprotectButton.prop("disabled", !note.isProtected || !protectedSessionHolder.isProtectedSessionAvailable());
function updateNoteView() {
$noteDetailWrapper.toggleClass("protected", currentNote.isProtected);
$protectButton.toggleClass("active", currentNote.isProtected);
$protectButton.prop("disabled", currentNote.isProtected);
$unprotectButton.toggleClass("active", !currentNote.isProtected);
$unprotectButton.prop("disabled", !currentNote.isProtected || !protectedSessionHolder.isProtectedSessionAvailable());
for (const clazz of Array.from($body[0].classList)) { // create copy to safely iterate over while removing classes
if (clazz.startsWith("type-") || clazz.startsWith("mime-")) {
$body.removeClass(clazz);
}
}
$body.addClass(utils.getNoteTypeClass(currentNote.type));
$body.addClass(utils.getMimeTypeClass(currentNote.mime));
}
async function handleProtectedSession() {
@@ -190,7 +203,7 @@ async function loadNoteDetail(noteId) {
$noteIdDisplay.html(noteId);
setNoteBackgroundIfProtected(currentNote);
updateNoteView();
$noteDetailWrapper.show();
@@ -267,7 +280,7 @@ async function showChildrenOverview() {
text: await treeUtils.getNoteTitle(childBranch.noteId, childBranch.parentNoteId)
}).attr('data-action', 'note').attr('data-note-path', notePath + '/' + childBranch.noteId);
const childEl = $('<div class="child-overview">').html(link);
const childEl = $('<div class="child-overview-item">').html(link);
$childrenOverview.append(childEl);
}
@@ -341,7 +354,7 @@ setInterval(saveNoteIfChanged, 3000);
export default {
reload,
switchToNote,
setNoteBackgroundIfProtected,
updateNoteView,
loadNote,
getCurrentNote,
getCurrentNoteType,
@@ -5,6 +5,7 @@ import noteDetailService from "./note_detail.js";
const $component = $('#note-detail-file');
const $fileNoteId = $("#file-note-id");
const $fileName = $("#file-filename");
const $fileType = $("#file-filetype");
const $fileSize = $("#file-filesize");
@@ -21,6 +22,7 @@ async function show() {
$component.show();
$fileNoteId.text(currentNote.noteId);
$fileName.text(attributeMap.originalFileName || "?");
$fileSize.text((attributeMap.fileSize || "?") + " bytes");
$fileType.text(currentNote.mime);
@@ -1,6 +1,7 @@
import libraryLoader from "./library_loader.js";
import noteDetailService from './note_detail.js';
import treeService from './tree.js';
import attributeService from "./attributes.js";
const $component = $('#note-detail-text');
@@ -19,6 +20,8 @@ async function show() {
}
}
textEditor.isReadOnly = await isReadOnly();
textEditor.setData(noteDetailService.getCurrentNote().content);
$component.show();
@@ -36,6 +39,12 @@ function getContent() {
return content;
}
async function isReadOnly() {
const attributes = await attributeService.getAttributes();
return attributes.some(attr => attr.type === 'label' && attr.name === 'readOnly');
}
function focus() {
$component.focus();
}
+36 -7
View File
@@ -2,6 +2,7 @@ import treeService from './tree.js';
import noteDetailService from './note_detail.js';
import server from './server.js';
import infoService from "./info.js";
import confirmDialog from "../dialogs/confirm.js";
const $executeScriptButton = $("#execute-script-button");
const $toggleEditButton = $('#toggle-edit-button');
@@ -110,35 +111,63 @@ function NoteTypeModel() {
self.updateExecuteScriptButtonVisibility();
}
this.selectText = function() {
function confirmChangeIfContent() {
if (!noteDetailService.getCurrentNoteContent()) {
return true;
}
return confirmDialog.confirm("It is not recommended to change note type when note content is not empty. Do you want to continue anyway?");
}
this.selectText = async function() {
if (!await confirmChangeIfContent()) {
return;
}
self.type('text');
self.mime('');
self.mime('text/html');
save();
};
this.selectRender = function() {
this.selectRender = async function() {
if (!await confirmChangeIfContent()) {
return;
}
self.type('render');
self.mime('text/html');
save();
};
this.selectRelationMap = function() {
this.selectRelationMap = async function() {
if (!await confirmChangeIfContent()) {
return;
}
self.type('relation-map');
self.mime('application/json');
save();
};
this.selectCode = function() {
this.selectCode = async function() {
if (!await confirmChangeIfContent()) {
return;
}
self.type('code');
self.mime('');
self.mime('text/plain');
save();
};
this.selectCodeMime = function(el) {
this.selectCodeMime = async function(el) {
if (!await confirmChangeIfContent()) {
return;
}
self.type('code');
self.mime(el.mime);
@@ -125,7 +125,7 @@ async function protectNoteAndSendToServer() {
treeService.setProtected(note.noteId, note.isProtected);
noteDetailService.setNoteBackgroundIfProtected(note);
noteDetailService.updateNoteView();
}
async function unprotectNoteAndSendToServer() {
@@ -152,7 +152,7 @@ async function unprotectNoteAndSendToServer() {
treeService.setProtected(currentNote.noteId, currentNote.isProtected);
noteDetailService.setNoteBackgroundIfProtected(currentNote);
noteDetailService.updateNoteView();
}
async function protectSubtree(noteId, protect) {
@@ -76,6 +76,15 @@ async function saveSearch() {
await treeService.activateNote(noteId);
}
function init() {
const hashValue = treeService.getHashValueFromAddress();
if (hashValue.startsWith("search=")) {
showSearch();
doSearch(hashValue.substr(7));
}
}
$searchInput.keyup(e => {
const searchText = $searchInput.val();
@@ -100,5 +109,6 @@ export default {
toggleSearch,
resetSearch,
showSearch,
doSearch
doSearch,
init
};
+27 -13
View File
@@ -483,24 +483,30 @@ async function reload() {
await getTree().reload(notes);
}
function getNotePathFromAddress() {
return document.location.hash.substr(1); // strip initial #
function isNotePathInAddress() {
return getHashValueFromAddress().startsWith("root");
}
function getHashValueFromAddress() {
return document.location.hash ? document.location.hash.substr(1) : ""; // strip initial #
}
async function loadTree() {
const resp = await server.get('tree');
startNotePath = resp.startNotePath;
if (document.location.hash) {
startNotePath = getNotePathFromAddress();
if (isNotePathInAddress()) {
startNotePath = getHashValueFromAddress();
}
return await treeBuilder.prepareTree(resp.notes, resp.branches, resp.relations);
}
function collapseTree(node = null) {
async function collapseTree(node = null) {
if (!node) {
node = $tree.fancytree("getRootNode");
const hoistedNoteId = await hoistedNoteService.getHoistedNoteId();
node = getNodesByNoteId(hoistedNoteId)[0];
}
node.setExpanded(false);
@@ -541,9 +547,11 @@ async function setNoteTitle(noteId, title) {
}
async function createNewTopLevelNote() {
const rootNode = getNodesByNoteId('root')[0];
const hoistedNoteId = await hoistedNoteService.getHoistedNoteId();
await createNote(rootNode, "root", "into", false);
const rootNode = getNodesByNoteId(hoistedNoteId)[0];
await createNote(rootNode, hoistedNoteId, "into", false);
}
async function createNote(node, parentNoteId, target, isProtected, saveSelection = false) {
@@ -619,7 +627,10 @@ async function createNote(node, parentNoteId, target, isProtected, saveSelection
await node.getLastChild().setActive(true);
const parentNoteEntity = await treeCache.getNote(node.data.noteId);
node.folder = true;
node.icon = await treeBuilder.getIcon(parentNoteEntity); // icon might change into folder
node.renderTitle();
}
else {
@@ -700,12 +711,14 @@ utils.bindShortcut('ctrl+p', createNoteInto);
utils.bindShortcut('ctrl+.', scrollToCurrentNote);
$(window).bind('hashchange', function() {
const notePath = getNotePathFromAddress();
if (isNotePathInAddress()) {
const notePath = getHashValueFromAddress();
if (notePath !== '-' && getCurrentNotePath() !== notePath) {
console.debug("Switching to " + notePath + " because of hash change");
if (notePath !== '-' && getCurrentNotePath() !== notePath) {
console.debug("Switching to " + notePath + " because of hash change");
activateNote(notePath);
activateNote(notePath);
}
}
});
@@ -738,5 +751,6 @@ export default {
showTree,
loadTree,
treeInitialized,
setExpandedToServer
setExpandedToServer,
getHashValueFromAddress
};
@@ -166,26 +166,15 @@ async function getExtraClasses(note) {
extraClasses.push(note.cssClass);
}
extraClasses.push(note.type);
extraClasses.push(utils.getNoteTypeClass(note.type));
if (note.mime) { // some notes should not have mime type (e.g. render)
extraClasses.push(getMimeTypeClass(note.mime));
extraClasses.push(utils.getMimeTypeClass(note.mime));
}
return extraClasses.join(" ");
}
function getMimeTypeClass(mime) {
const semicolonIdx = mime.indexOf(';');
if (semicolonIdx !== -1) {
// stripping everything following the semicolon
mime = mime.substr(0, semicolonIdx);
}
return 'mime-' + mime.toLowerCase().replace(/[\W_]+/g,"-");
}
export default {
prepareTree,
prepareBranch,
+21 -1
View File
@@ -23,6 +23,7 @@ function formatTimeWithSeconds(date) {
return padNum(date.getHours()) + ":" + padNum(date.getMinutes()) + ":" + padNum(date.getSeconds());
}
// this is producing local time!
function formatDate(date) {
// return padNum(date.getDate()) + ". " + padNum(date.getMonth() + 1) + ". " + date.getFullYear();
// instead of european format we'll just use ISO as that's pretty unambiguous
@@ -30,6 +31,7 @@ function formatDate(date) {
return formatDateISO(date);
}
// this is producing local time!
function formatDateISO(date) {
return date.getFullYear() + "-" + padNum(date.getMonth() + 1) + "-" + padNum(date.getDate());
}
@@ -143,6 +145,7 @@ function bindShortcut(keyboardShortcut, handler) {
}
$(document).bind('keydown', keyboardShortcut, e => {
console.log(e);
handler();
e.preventDefault();
@@ -169,6 +172,21 @@ function setCookie(name, value) {
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getNoteTypeClass(type) {
return "type-" + type;
}
function getMimeTypeClass(mime) {
const semicolonIdx = mime.indexOf(';');
if (semicolonIdx !== -1) {
// stripping everything following the semicolon
mime = mime.substr(0, semicolonIdx);
}
return 'mime-' + mime.toLowerCase().replace(/[\W_]+/g,"-");
}
export default {
reloadApp,
parseDate,
@@ -195,5 +213,7 @@ export default {
bindShortcut,
isMobile,
isDesktop,
setCookie
setCookie,
getNoteTypeClass,
getMimeTypeClass
};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+11 -1
View File
@@ -30,6 +30,7 @@ body {
flex-shrink: 1;
flex-basis: 60%;
margin-top: 10px;
font-family: var(--tree-font-family);
font-size: var(--tree-font-size);
}
@@ -66,7 +67,7 @@ body {
justify-content: space-around;
padding: 10px 0 10px 0;
margin: 0 20px 0 10px;
border: 1px solid #ddd;
border: 1px solid var(--main-border-color);
border-radius: 7px;
}
@@ -94,4 +95,13 @@ body {
#note-detail-wrapper {
font-size: var(--detail-font-size);
}
::-webkit-scrollbar {
width: 12px;
}
::-webkit-scrollbar-thumb {
border-radius: 3px;
border: 1px solid var(--main-border-color);
}
+2 -2
View File
@@ -24,7 +24,6 @@ html, body {
}
#tree {
font-size: larger;
width: 100%;
overflow: auto;
}
@@ -45,7 +44,8 @@ html, body {
position: relative;
overflow: auto;
flex-direction: column;
height: 100%;
/* for some reason detail overflows a little bit so we subtract few pixels */
height: calc(100% - 25px);
/* large left padding is necessary for ckeditor gutter in detail-only (smartphone) layout */
padding-left: 35px;
}
+56 -17
View File
@@ -1,14 +1,20 @@
:root {
--main-font-family: inherit;
--main-font-size: normal;
--tree-font-family: inherit;
--tree-font-size: normal;
--detail-font-family: inherit;
--detail-font-size: normal;
--detail-text-font-family: inherit;
--main-background-color: white;
--main-text-color: black;
--main-border-color: #ccc;
--accented-background-color: #eee;
--more-accented-background-color: #ccc;
--header-background-color: #f8f8f8;
--button-background-color: #eee;
--button-disabled-background-color: #ccc;
--button-border-color: #ddd;
--button-text-color: black;
--button-border-radius: 5px;
@@ -27,6 +33,7 @@
body.theme-black {
--main-background-color: black;
--main-text-color: white;
--main-border-color: #ddd;
--accented-background-color: #222;
--more-accented-background-color: #444;
--header-background-color: black;
@@ -53,6 +60,7 @@ body.theme-black .CodeMirror {
body.theme-dark {
--main-background-color: #333;
--main-text-color: white;
--main-border-color: #ddd;
--accented-background-color: #555;
--more-accented-background-color: #777;
--header-background-color: #333;
@@ -88,6 +96,7 @@ body {
width: 100%;
background-color: var(--main-background-color);
color: var(--main-text-color);
font-family: var(--main-font-family);
}
input, select {
@@ -157,7 +166,7 @@ ul.fancytree-container {
/* this is done to preserve correct indentation. Better solution would be preferable */
.fancytree-node:not(.fancytree-folder) .fancytree-expander:before {
color: white;
color: var(--main-background-color); /* setting to background color makes this invisible */
}
.fancytree-node.fancytree-expanded .fancytree-expander:before {
@@ -180,6 +189,7 @@ ul.fancytree-container {
padding-top: 10px;
display: flex;
flex-direction: column;
font-family: var(--detail-font-family);
}
#note-detail-component-wrapper {
@@ -211,6 +221,11 @@ ul.fancytree-container {
/* This is because with empty content height of editor is 0 and it's impossible to click into it */
min-height: 200px;
overflow: auto;
font-family: var(--detail-text-font-family);
}
#note-detail-text p:first-child, #note-detail-text::before {
margin-top: 0;
}
/** we disable shield background when in distraction free mode because I couldn't get it to stay static
@@ -256,21 +271,31 @@ span.fancytree-node.fancytree-active-clone:not(.fancytree-active) .fancytree-tit
span.fancytree-active.fancytree-focused .fancytree-title {
color: var(--active-item-text-color) !important;
background-color: var(--active-item-background-color) !important;
border-color: #ddd !important;
border-color: var(--main-border-color) !important;
border-radius: 3px;
font-weight: bold;
}
span.fancytree-active:not(.fancytree-focused) .fancytree-title {
color: var(--hover-item-text-color) !important;
background-color: var(--hover-item-background-color) !important;
border-color: #ddd !important;
border-color: var(--main-border-color) !important;
border-radius: 3px;
font-weight: bold;
}
span.fancytree-selected:not(.fancytree-active) .fancytree-title {
color: var(--hover-item-text-color) !important;
background-color: var(--hover-item-background-color) !important;
border-color: var(--main-border-color) !important;
border-radius: 3px;
font-style: italic;
}
span.fancytree-node:not(.fancytree-active):hover span.fancytree-title {
color: var(--hover-item-text-color) !important;
background-color: var(--hover-item-background-color) !important;
border-color: #ddd !important;
border-color: var(--main-border-color) !important;
border-radius: 3px;
}
@@ -313,13 +338,17 @@ div.ui-tooltip {
margin-top: 10px;
display: none;
overflow: auto;
border-bottom: 2px solid #ddd;
border-bottom: 2px solid var(--main-border-color);
}
#search-results ul {
padding: 5px 5px 5px 15px;
}
#search-text {
border: 1px solid var(--main-border-color);
}
/*
* .electron-in-page-search-window is a class specified to default
* <webview> element for search window.
@@ -430,6 +459,11 @@ div.ui-tooltip {
min-height: 200px;
}
.CodeMirror-gutters {
background-color: inherit !important;
border-right: none;
}
#note-id-display {
position: absolute;
right: 10px;
@@ -450,10 +484,12 @@ div.ui-tooltip {
overflow: auto;
/* limiting the size since actual note content is more important */
max-height: 30%;
flex-shrink: 0;
flex-basis: 2em;
}
#label-list, #relation-list, #attribute-list {
color: #777777;
color: var(--muted-text-color);
padding: 5px;
display: none;
}
@@ -479,9 +515,8 @@ div.ui-tooltip {
overflow: auto;
}
.child-overview {
.child-overview-item {
font-weight: bold;
font-size: larger;
padding: 10px;
background: var(--accented-background-color);
width: 150px;
@@ -496,7 +531,7 @@ div.ui-tooltip {
word-wrap: break-word;
}
.child-overview a {
.child-overview-item a {
color: var(--muted-text-color);
}
@@ -522,7 +557,7 @@ div.ui-tooltip {
}
.btn.active:not(.btn-primary) {
background-color: #ccc !important;
background-color: var(--button-disabled-background-color) !important;
}
#note-path-list a.current {
@@ -569,8 +604,12 @@ button.icon-button {
max-width: 100%;
}
pre:not(.CodeMirror-line) {
color: var(--main-text-color) !important;
}
#file-preview-content {
background-color: #f6f6f6;
background-color: var(--accented-background-color);
padding: 15px;
max-width: 600px;
max-height: 300px;
@@ -612,7 +651,7 @@ button.icon-button {
.go-to-selected-note-button.disabled, .go-to-selected-note-button.disabled:hover {
cursor: inherit;
color: #ccc !important;
color: var(--button-disabled-background-color) !important;
}
.note-autocomplete-input {
@@ -651,7 +690,7 @@ table.promoted-attributes-in-tooltip td, table.promoted-attributes-in-tooltip th
max-height: 300px;
overflow: hidden;
color: var(--main-text-color);
border: 1px solid #ccc;
border: 1px solid var(--main-border-color);
border-radius: 5px;
text-align: left;
}
@@ -681,7 +720,7 @@ table.promoted-attributes-in-tooltip td, table.promoted-attributes-in-tooltip th
.algolia-autocomplete .aa-dropdown-menu {
width: 100%;
background-color: var(--main-background-color);
border: 1px solid #999;
border: 1px solid var(--main-border-color);
border-top: none;
z-index: 2000 !important;
max-height: 500px;
@@ -768,9 +807,9 @@ div[data-notify="container"] {
#saved-indicator {
position: absolute;
right: 10px;
top: 11px;
top: -7px;
font-size: 150%;
color: #777;
color: var(--main-text-color);
z-index: 100;
}
@@ -807,7 +846,7 @@ div[data-notify="container"] {
margin: var(--ck-spacing-large) 0;
color: #aaa;
color: var(--muted-text-color);
}
.fancytree-loading span.fancytree-expander {
+11 -5
View File
@@ -34,8 +34,7 @@ async function uploadFile(req) {
};
}
async function downloadFile(req, res) {
const noteId = req.params.noteId;
async function downloadNoteFile(noteId, res) {
const note = await repository.getNote(noteId);
if (!note) {
@@ -43,8 +42,7 @@ async function downloadFile(req, res) {
}
if (note.isProtected && !protectedSessionService.isProtectedSessionAvailable()) {
res.status(401).send("Protected session not available");
return;
return res.status(401).send("Protected session not available");
}
const originalFileName = await note.getLabel('originalFileName');
@@ -56,7 +54,15 @@ async function downloadFile(req, res) {
res.send(note.content);
}
async function downloadFile(req, res) {
const noteId = req.params.noteId;
return await downloadNoteFile(noteId, res);
}
module.exports = {
uploadFile,
downloadFile
downloadFile,
downloadNoteFile
};
+25 -2
View File
@@ -1,8 +1,8 @@
"use strict";
const sql = require('../../services/sql');
const optionService = require('../../services/options');
const log = require('../../services/log');
const attributes = require('../../services/attributes');
// options allowed to be updated directly in options dialog
const ALLOWED_OPTIONS = ['protectedSessionTimeout', 'noteRevisionSnapshotTimeInterval',
@@ -42,8 +42,31 @@ async function update(name, value) {
return true;
}
async function getUserThemes() {
const notes = await attributes.getNotesWithLabel('appTheme');
const ret = [];
for (const note of notes) {
let value = await note.getLabelValue('appTheme');
if (!value) {
value = note.title.toLowerCase().replace(/[^a-z0-9]/gi, '-');
}
ret.push({
val: value,
title: note.title,
noteId: note.noteId
});
}
return ret;
}
module.exports = {
getOptions,
updateOption,
updateOptions
updateOptions,
getUserThemes
};
+6 -1
View File
@@ -19,7 +19,7 @@ async function exec(req) {
async function run(req) {
const note = await repository.getNote(req.params.noteId);
const result = await scriptService.executeNote(note, note);
const result = await scriptService.executeNote(note, { originEntity: note });
return { executionResult: result };
}
@@ -54,6 +54,11 @@ async function getRelationBundles(req) {
for (const noteId of uniqueNoteIds) {
const note = await repository.getNote(noteId);
if (!note.isJavaScript() || note.getScriptEnv() !== 'frontend') {
continue;
}
const bundle = await scriptService.getScriptBundleForFrontend(note);
if (bundle) {
+66
View File
@@ -0,0 +1,66 @@
const repository = require('../services/repository');
const log = require('../services/log');
const fileUploadService = require('./api/file_upload');
const scriptService = require('../services/script');
function register(router) {
router.all('/custom/:path*', async (req, res, next) => {
// express puts content after first slash into 0 index element
const path = req.params.path + req.params[0];
const attrs = await repository.getEntities("SELECT * FROM attributes WHERE isDeleted = 0 AND type = 'label' AND name IN ('customRequestHandler', 'customResourceProvider')");
for (const attr of attrs) {
const regex = new RegExp(attr.value);
let match;
try {
match = path.match(regex);
}
catch (e) {
log.error(`Testing path for label ${attr.attributeId}, regex=${attr.value} failed with error ` + e.stack);
continue;
}
if (!match) {
continue;
}
if (attr.name === 'customRequestHandler') {
const note = await attr.getNote();
log.info(`Handling custom request "${path}" with note ${note.noteId}`);
try {
await scriptService.executeNote(note, {
pathParams: match.slice(1),
req,
res
});
}
catch (e) {
log.error(`Custom handler ${note.noteId} failed with ${e.message}`);
res.status(500).send(e.message);
}
}
else if (attr.name === 'customResourceProvider') {
await fileUploadService.downloadNoteFile(attr.noteId, res);
}
else {
throw new Error("Unrecognized attribute name " + attr.name);
}
return; // only first handler is executed
}
const message = `No handler matched for custom ${path} request.`;
log.info(message);
res.status(404).send(message);
});
}
module.exports = {
register
};
+4 -13
View File
@@ -22,22 +22,13 @@ async function index(req, res) {
sourceId: await sourceIdService.generateSourceId(),
maxSyncIdAtLoad: await sql.getValue("SELECT MAX(id) FROM sync"),
instanceName: config.General ? config.General.instanceName : null,
appCss: await getAppCss()
appCssNoteIds: await getAppCssNoteIds()
});
}
async function getAppCss() {
let css = '';
const notes = attributeService.getNotesWithLabel('appCss');
for (const note of await notes) {
css += `/* ${note.noteId} */
${note.content}
`;
}
return css;
async function getAppCssNoteIds() {
return (await attributeService.getNotesWithLabels(['appCss', 'appTheme']))
.map(note => note.noteId);
}
module.exports = {
+3
View File
@@ -135,6 +135,8 @@ function register(app) {
filesRoute.uploadFile, apiResultHandler);
route(GET, '/api/notes/:noteId/download', [auth.checkApiAuthOrElectron], filesRoute.downloadFile);
// this "hacky" path is used for easier referencing of CSS resources
route(GET, '/api/notes/download/:noteId', [auth.checkApiAuthOrElectron], filesRoute.downloadFile);
apiRoute(GET, '/api/notes/:noteId/attributes', attributesRoute.getEffectiveNoteAttributes);
apiRoute(PUT, '/api/notes/:noteId/attributes', attributesRoute.updateNoteAttributes);
@@ -153,6 +155,7 @@ function register(app) {
apiRoute(GET, '/api/options', optionsApiRoute.getOptions);
apiRoute(PUT, '/api/options/:name/:value*', optionsApiRoute.updateOption);
apiRoute(PUT, '/api/options', optionsApiRoute.updateOptions);
apiRoute(GET, '/api/options/user-themes', optionsApiRoute.getUserThemes);
apiRoute(POST, '/api/password/change', passwordApiRoute.changePassword);
+3 -3
View File
@@ -1,7 +1,7 @@
"use strict";
const path = require('path');
const {APP_PNG_ICON_DIR, ELECTRON_APP_ROOT_DIR} = require("./resource_dir");
const {ELECTRON_APP_ROOT_DIR} = require("./resource_dir");
const log = require("./log");
const os = require('os');
const fs = require('fs');
@@ -11,7 +11,7 @@ const utils = require('./utils');
const template = `[Desktop Entry]
Type=Application
Name=Trilium Notes
Icon=#APP_PNG_ICON_DIR#/128x128.png
Icon=#APP_ROOT_DIR#/icon.png
Exec=#EXE_PATH#
Categories=Office
Terminal=false
@@ -50,7 +50,7 @@ function installLocalAppIcon() {
function getDesktopFileContent() {
return template
.replace("#APP_PNG_ICON_DIR#", escapePath(APP_PNG_ICON_DIR))
.replace("#APP_ROOT_DIR#", escapePath(ELECTRON_APP_ROOT_DIR))
.replace("#EXE_PATH#", escapePath(getExePath()));
}
+1 -1
View File
@@ -4,7 +4,7 @@ const build = require('./build');
const packageJson = require('../../package');
const {TRILIUM_DATA_DIR} = require('./data_dir');
const APP_DB_VERSION = 123;
const APP_DB_VERSION = 124;
const SYNC_VERSION = 4;
module.exports = {
+12
View File
@@ -15,8 +15,12 @@ const BUILTIN_ATTRIBUTES = [
{ type: 'label', name: 'manualTransactionHandling' },
{ type: 'label', name: 'disableInclusion' },
{ type: 'label', name: 'appCss' },
{ type: 'label', name: 'appTheme' },
{ type: 'label', name: 'hideChildrenOverview' },
{ type: 'label', name: 'hidePromotedAttributes' },
{ type: 'label', name: 'readOnly' },
{ type: 'label', name: 'customRequestHandler' },
{ type: 'label', name: 'customResourceProvider' },
// relation names
{ type: 'relation', name: 'runOnNoteView' },
@@ -43,6 +47,13 @@ async function getNotesWithLabel(name, value) {
WHERE notes.isDeleted = 0 AND attributes.isDeleted = 0 AND attributes.name = ? ${valueCondition} ORDER BY position`, params);
}
async function getNotesWithLabels(names) {
const questionMarks = names.map(() => "?").join(", ");
return await repository.getEntities(`SELECT notes.* FROM notes JOIN attributes USING(noteId)
WHERE notes.isDeleted = 0 AND attributes.isDeleted = 0 AND attributes.name IN (${questionMarks}) ORDER BY position`, names);
}
async function getNoteWithLabel(name, value) {
const notes = await getNotesWithLabel(name, value);
@@ -85,6 +96,7 @@ async function getAttributeNames(type, nameLike) {
module.exports = {
getNotesWithLabel,
getNotesWithLabels,
getNoteWithLabel,
createLabel,
createAttribute,
+31 -4
View File
@@ -11,6 +11,7 @@ const repository = require('./repository');
const axios = require('axios');
const cloningService = require('./cloning');
const messagingService = require('./messaging');
const appInfo = require('./app_info');
/**
* This is the main backend API interface for scripts. It's published in the local "api" object.
@@ -18,13 +19,17 @@ const messagingService = require('./messaging');
* @constructor
* @hideconstructor
*/
function BackendScriptApi(startNote, currentNote, originEntity) {
function BackendScriptApi(currentNote, apiParams) {
/** @property {Note} note where script started executing */
this.startNote = startNote;
this.startNote = apiParams.startNote;
/** @property {Note} note where script is currently executing */
this.currentNote = currentNote;
/** @property {Entity} entity whose event triggered this executions */
this.originEntity = originEntity;
this.originEntity = apiParams.originEntity;
for (const key in apiParams) {
this[key] = apiParams[key];
}
this.axios = axios;
@@ -168,6 +173,23 @@ function BackendScriptApi(startNote, currentNote, originEntity) {
*/
this.createNote = noteService.createNote;
/**
* Creates new note according to given params and force all connected clients to refresh their tree.
*
* @method
*
* @param {string} parentNoteId - create new note under this parent
* @param {string} title
* @param {string} [content=""]
* @param {CreateNoteExtraOptions} [extraOptions={}]
* @returns {Promise<{note: Note, branch: Branch}>} object contains newly created entities note and branch
*/
this.createNoteAndRefresh = async function(parentNoteId, title, content, extraOptions) {
await noteService.createNote(parentNoteId, title, content, extraOptions);
messagingService.refreshTree();
};
/**
* Log given message to trilium logs.
*
@@ -233,7 +255,12 @@ function BackendScriptApi(startNote, currentNote, originEntity) {
*
* @returns {Promise<void>}
*/
this.refreshTree = () => messagingService.sendMessageToAllClients({ type: 'refresh-tree' });
this.refreshTree = messagingService.refreshTree;
/**
* @return {{syncVersion, appVersion, buildRevision, dbVersion, dataDirectory, buildDate}|*} - object representing basic info about running Trilium version
*/
this.getAppInfo = () => appInfo
}
module.exports = BackendScriptApi;
+1 -1
View File
@@ -1 +1 @@
module.exports = { buildDate:"2019-01-14T23:51:55+01:00", buildRevision: "e50f9cd0a354e29bb40c161cf7288e13b732e0d3" };
module.exports = { buildDate:"2019-02-12T20:30:07+01:00", buildRevision: "8b250ed523f851afc0923342827679e805329838" };
+18
View File
@@ -8,6 +8,10 @@ const repository = require('./repository');
const Branch = require('../entities/branch');
async function cloneNoteToParent(noteId, parentNoteId, prefix) {
if (await isNoteDeleted(noteId) || await isNoteDeleted(parentNoteId)) {
return { success: false, message: 'Note is deleted.' };
}
const validationResult = await treeService.validateParentChild(parentNoteId, noteId);
if (!validationResult.success) {
@@ -27,6 +31,10 @@ async function cloneNoteToParent(noteId, parentNoteId, prefix) {
}
async function ensureNoteIsPresentInParent(noteId, parentNoteId, prefix) {
if (await isNoteDeleted(noteId) || await isNoteDeleted(parentNoteId)) {
return { success: false, message: 'Note is deleted.' };
}
const validationResult = await treeService.validateParentChild(parentNoteId, noteId);
if (!validationResult.success) {
@@ -61,6 +69,10 @@ async function toggleNoteInParent(present, noteId, parentNoteId, prefix) {
async function cloneNoteAfter(noteId, afterBranchId) {
const afterNote = await treeService.getBranch(afterBranchId);
if (await isNoteDeleted(noteId) || await isNoteDeleted(afterNote.parentNoteId)) {
return { success: false, message: 'Note is deleted.' };
}
const validationResult = await treeService.validateParentChild(afterNote.parentNoteId, noteId);
if (!validationResult.result) {
@@ -84,6 +96,12 @@ async function cloneNoteAfter(noteId, afterBranchId) {
return { success: true };
}
async function isNoteDeleted(noteId) {
const note = await repository.getNote(noteId);
return note.isDeleted;
}
module.exports = {
cloneNoteToParent,
ensureNoteIsPresentInParent,
+341 -218
View File
@@ -5,23 +5,39 @@ const sqlInit = require('./sql_init');
const log = require('./log');
const messagingService = require('./messaging');
const syncMutexService = require('./sync_mutex');
const repository = require('./repository.js');
const repository = require('./repository');
const cls = require('./cls');
const syncTableService = require('./sync_table');
const Branch = require('../entities/branch');
async function runCheck(query, errorText, errorList) {
const result = await sql.getColumn(query);
let unrecoverableConsistencyErrors = false;
let fixedIssues = false;
if (result.length > 0) {
const resultText = result.map(val => "'" + val + "'").join(', ');
async function findIssues(query, errorCb) {
const results = await sql.getRows(query);
const err = errorText + ": " + resultText;
errorList.push(err);
for (const res of results) {
logError(errorCb(res));
log.error(err);
unrecoverableConsistencyErrors = true;
}
return results;
}
async function checkTreeCycles(errorList) {
async function findAndFixIssues(query, fixerCb) {
const results = await sql.getRows(query);
for (const res of results) {
await fixerCb(res);
fixedIssues = true;
}
return results;
}
async function checkTreeCycles() {
const childToParents = {};
const rows = await sql.getRows("SELECT noteId, parentNoteId FROM branches WHERE isDeleted = 0");
@@ -33,25 +49,29 @@ async function checkTreeCycles(errorList) {
childToParents[childNoteId].push(parentNoteId);
}
function checkTreeCycle(noteId, path, errorList) {
function checkTreeCycle(noteId, path) {
if (noteId === 'root') {
return;
}
if (!childToParents[noteId] || childToParents[noteId].length === 0) {
errorList.push(`No parents found for noteId=${noteId}`);
logError(`No parents found for note ${noteId}`);
unrecoverableConsistencyErrors = true;
return;
}
for (const parentNoteId of childToParents[noteId]) {
if (path.includes(parentNoteId)) {
errorList.push(`Tree cycle detected at parent-child relationship: ${parentNoteId} - ${noteId}, whole path: ${path}`);
logError(`Tree cycle detected at parent-child relationship: ${parentNoteId} - ${noteId}, whole path: ${path}`);
unrecoverableConsistencyErrors = true;
}
else {
const newPath = path.slice();
newPath.push(noteId);
checkTreeCycle(parentNoteId, newPath, errorList);
checkTreeCycle(parentNoteId, newPath);
}
}
}
@@ -59,268 +79,365 @@ async function checkTreeCycles(errorList) {
const noteIds = Object.keys(childToParents);
for (const noteId of noteIds) {
checkTreeCycle(noteId, [], errorList);
checkTreeCycle(noteId, []);
}
if (childToParents['root'].length !== 1 || childToParents['root'][0] !== 'none') {
errorList.push('Incorrect root parent: ' + JSON.stringify(childToParents['root']));
logError('Incorrect root parent: ' + JSON.stringify(childToParents['root']));
unrecoverableConsistencyErrors = true;
}
}
async function runSyncRowChecks(table, key, errorList) {
await runCheck(`
SELECT
${key}
FROM
${table}
LEFT JOIN sync ON sync.entityName = '${table}' AND entityId = ${key}
WHERE
sync.id IS NULL AND ` + (table === 'options' ? 'isSynced = 1' : '1'),
`Missing sync records for ${key} in table ${table}`, errorList);
async function findBrokenReferenceIssues() {
await findIssues(`
SELECT branchId, branches.noteId
FROM branches LEFT JOIN notes USING(noteId)
WHERE branches.isDeleted = 0 AND notes.noteId IS NULL`,
({branchId, noteId}) => `Branch ${branchId} references missing note ${noteId}`);
await runCheck(`
SELECT
entityId
FROM
sync
LEFT JOIN ${table} ON entityId = ${key}
WHERE
sync.entityName = '${table}'
AND ${key} IS NULL`,
`Missing ${table} records for existing sync rows`, errorList);
await findIssues(`
SELECT branchId, branches.noteId AS parentNoteId
FROM branches LEFT JOIN notes ON notes.noteId = branches.parentNoteId
WHERE branches.isDeleted = 0 AND branches.branchId != 'root' AND notes.noteId IS NULL`,
({branchId, noteId}) => `Branch ${branchId} references missing parent note ${noteId}`);
await findIssues(`
SELECT attributeId, attributes.noteId
FROM attributes LEFT JOIN notes USING(noteId)
WHERE attributes.isDeleted = 0 AND notes.noteId IS NULL`,
({attributeId, noteId}) => `Attribute ${attributeId} references missing source note ${noteId}`);
// empty targetNoteId for relations is a special fixable case so not covered here
await findIssues(`
SELECT attributeId, attributes.value AS noteId
FROM attributes LEFT JOIN notes ON notes.noteId = attributes.value
WHERE attributes.isDeleted = 0 AND attributes.type = 'relation'
AND attributes.value != '' AND notes.noteId IS NULL`,
({attributeId, noteId}) => `Relation ${attributeId} references missing note ${noteId}`);
await findIssues(`
SELECT linkId, links.noteId
FROM links LEFT JOIN notes USING(noteId)
WHERE links.isDeleted = 0 AND notes.noteId IS NULL`,
({linkId, noteId}) => `Link ${linkId} references missing source note ${noteId}`);
await findIssues(`
SELECT linkId, links.noteId
FROM links LEFT JOIN notes ON notes.noteId = links.targetNoteId
WHERE links.isDeleted = 0 AND notes.noteId IS NULL`,
({linkId, noteId}) => `Link ${linkId} references missing target note ${noteId}`);
await findIssues(`
SELECT noteRevisionId, note_revisions.noteId
FROM note_revisions LEFT JOIN notes USING(noteId)
WHERE notes.noteId IS NULL`,
({noteRevisionId, noteId}) => `Note revision ${noteRevisionId} references missing note ${noteId}`);
}
async function fixEmptyRelationTargets(errorList) {
const emptyRelations = await repository.getEntities("SELECT * FROM attributes WHERE isDeleted = 0 AND type = 'relation' AND value = ''");
async function findExistencyIssues() {
// principle for fixing inconsistencies is that if the note itself is deleted (isDeleted=true) then all related entities should be also deleted (branches, links, attributes)
// but if note is not deleted, then at least one branch should exist.
for (const relation of emptyRelations) {
relation.isDeleted = true;
await relation.save();
errorList.push(`Relation ${relation.attributeId} of name "${relation.name} has empty target. Autofixed.`);
}
}
async function runAllChecks() {
const errorList = [];
await runCheck(`
SELECT
noteId
FROM
notes
LEFT JOIN branches USING(noteId)
WHERE
noteId != 'root'
AND branches.branchId IS NULL`,
"Missing branches records for following note IDs", errorList);
await runCheck(`
SELECT
branchId || ' > ' || branches.noteId
FROM
branches
LEFT JOIN notes USING(noteId)
WHERE
notes.noteId IS NULL`,
"Missing notes records for following branch ID > note ID", errorList);
await runCheck(`
SELECT
branchId
FROM
branches
JOIN notes USING(noteId)
WHERE
notes.isDeleted = 1
AND branches.isDeleted = 0`,
"Branch is not deleted even though main note is deleted for following branch IDs", errorList);
await runCheck(`
SELECT
child.branchId
FROM
branches AS child
WHERE
child.isDeleted = 0
AND child.parentNoteId != 'none'
AND (SELECT COUNT(*) FROM branches AS parent WHERE parent.noteId = child.parentNoteId
AND parent.isDeleted = 0) = 0`,
"All parent branches are deleted but child branch is not for these child branch IDs", errorList);
// we do extra JOIN to eliminate orphan notes without branches (which are reported separately)
await runCheck(`
// the order here is important - first we might need to delete inconsistent branches and after that
// another check might create missing branch
await findAndFixIssues(`
SELECT
DISTINCT noteId
branchId, noteId
FROM
notes
JOIN branches USING(noteId)
branches
JOIN notes USING(noteId)
WHERE
(SELECT COUNT(*) FROM branches WHERE notes.noteId = branches.noteId AND branches.isDeleted = 0) = 0
AND notes.isDeleted = 0
`, 'No undeleted branches for note IDs', errorList);
notes.isDeleted = 1
AND branches.isDeleted = 0`,
async ({branchId, noteId}) => {
const branch = await repository.getBranch(branchId);
branch.isDeleted = true;
await branch.save();
await runCheck(`
SELECT
child.parentNoteId || ' > ' || child.noteId
FROM branches
AS child
LEFT JOIN branches AS parent ON parent.noteId = child.parentNoteId
WHERE
parent.noteId IS NULL
AND child.parentNoteId != 'none'`,
"Not existing parent in the following parent > child relations", errorList);
logFix(`Branch ${branchId} has been deleted since associated note ${noteId} is deleted.`);
});
await runCheck(`
SELECT
noteRevisionId || ' > ' || note_revisions.noteId
FROM
note_revisions LEFT JOIN notes USING(noteId)
WHERE
notes.noteId IS NULL`,
"Missing notes records for following note revision ID > note ID", errorList);
await findAndFixIssues(`
SELECT
branchId, parentNoteId
FROM
branches
JOIN notes AS parentNote ON parentNote.noteId = branches.parentNoteId
WHERE
parentNote.isDeleted = 1
AND branches.isDeleted = 0
`, async ({branchId, parentNoteId}) => {
const branch = await repository.getBranch(branchId);
branch.isDeleted = true;
await branch.save();
await runCheck(`
SELECT
branches.parentNoteId || ' > ' || branches.noteId
FROM
branches
WHERE
branches.isDeleted = 0
GROUP BY
branches.parentNoteId,
branches.noteId
HAVING
COUNT(*) > 1`,
"Duplicate undeleted parent note <-> note relationship - parent note ID > note ID", errorList);
logFix(`Branch ${branchId} has been deleted since associated parent note ${parentNoteId} is deleted.`);
});
await runCheck(`
SELECT
noteId
FROM
notes
WHERE
type != 'text'
AND type != 'code'
AND type != 'render'
AND type != 'file'
AND type != 'image'
AND type != 'search'
AND type != 'relation-map'`,
"Note has invalid type", errorList);
await findAndFixIssues(`
SELECT
DISTINCT notes.noteId
FROM
notes
LEFT JOIN branches ON notes.noteId = branches.noteId AND branches.isDeleted = 0
WHERE
notes.isDeleted = 0
AND branches.branchId IS NULL
`, async ({noteId}) => {
const branch = await new Branch({
parentNoteId: 'root',
noteId: noteId,
prefix: 'recovered'
}).save();
await runCheck(`
SELECT
noteId
FROM
notes
logFix(`Created missing branch ${branch.branchId} for note ${noteId}`);
});
// there should be a unique relationship between note and its parent
await findAndFixIssues(`
SELECT
noteId, parentNoteId
FROM
branches
WHERE
branches.isDeleted = 0
GROUP BY
branches.parentNoteId,
branches.noteId
HAVING
COUNT(*) > 1`,
async ({noteId, parentNoteId}) => {
const branches = await repository.getEntities(`SELECT * FROM branches WHERE noteId = ? and parentNoteId = ? and isDeleted = 1`, [noteId, parentNoteId]);
// it's not necessarily "original" branch, it's just the only one which will survive
const origBranch = branches.get(0);
// delete all but the first branch
for (const branch of branches.slice(1)) {
branch.isDeleted = true;
await branch.save();
logFix(`Removing branch ${branch.branchId} since it's parent-child duplicate of branch ${origBranch.branchId}`);
}
});
}
async function findLogicIssues() {
await findIssues( `
SELECT noteId, type
FROM notes
WHERE
isDeleted = 0
AND type NOT IN ('text', 'code', 'render', 'file', 'image', 'search', 'relation-map')`,
({noteId, type}) => `Note ${noteId} has invalid type=${type}`);
await findIssues(`
SELECT noteId
FROM notes
WHERE
isDeleted = 0
AND content IS NULL`,
"Note content is null even though it is not deleted", errorList);
({noteId}) => `Note ${noteId} content is null even though it is not deleted`);
await runCheck(`
SELECT
parentNoteId
await findIssues(`
SELECT parentNoteId
FROM
branches
JOIN notes ON notes.noteId = branches.parentNoteId
WHERE
notes.isDeleted = 0
AND notes.type == 'search'
AND branches.isDeleted = 0`,
({parentNoteId}) => `Search note ${parentNoteId} has children`);
await findAndFixIssues(`
SELECT attributeId
FROM attributes
WHERE
type == 'search'`,
"Search note has children", errorList);
isDeleted = 0
AND type = 'relation'
AND value = ''`,
async ({attributeId}) => {
const relation = await repository.getAttribute(attributeId);
relation.isDeleted = true;
await relation.save();
await fixEmptyRelationTargets(errorList);
logFix(`Removed relation ${relation.attributeId} of name "${relation.name} with empty target.`);
});
await runCheck(`
await findIssues(`
SELECT
attributeId
FROM
attributes
attributeId,
type
FROM attributes
WHERE
type != 'label'
isDeleted = 0
AND type != 'label'
AND type != 'label-definition'
AND type != 'relation'
AND type != 'relation-definition'`,
"Attribute has invalid type", errorList);
({attributeId, type}) => `Attribute ${attributeId} has invalid type '${type}'`);
await runCheck(`
SELECT
attributeId
FROM
attributes
LEFT JOIN notes ON attributes.noteId = notes.noteId AND notes.isDeleted = 0
WHERE
attributes.isDeleted = 0
AND notes.noteId IS NULL`,
"Attribute reference to the owning note is broken", errorList);
await runCheck(`
await findAndFixIssues(`
SELECT
attributeId
attributeId,
attributes.noteId
FROM
attributes
LEFT JOIN notes AS targetNote ON attributes.value = targetNote.noteId AND targetNote.isDeleted = 0
JOIN notes ON attributes.noteId = notes.noteId
WHERE
attributes.isDeleted = 0
AND notes.isDeleted = 1`,
async ({attributeId, noteId}) => {
const attribute = await repository.getAttribute(attributeId);
attribute.isDeleted = true;
await attribute.save();
logFix(`Removed attribute ${attributeId} because owning note ${noteId} is also deleted.`);
});
await findAndFixIssues(`
SELECT
attributeId,
attributes.value AS targetNoteId
FROM
attributes
JOIN notes ON attributes.value = notes.noteId
WHERE
attributes.type = 'relation'
AND attributes.isDeleted = 0
AND targetNote.noteId IS NULL`,
"Relation reference to the target note is broken", errorList);
AND notes.isDeleted = 1`,
async ({attributeId, targetNoteId}) => {
const attribute = await repository.getAttribute(attributeId);
attribute.isDeleted = true;
await attribute.save();
await runCheck(`
SELECT
linkId
FROM
links
WHERE
type != 'image'
AND type != 'hyper'
AND type != 'relation-map'`,
"Link type is invalid", errorList);
logFix(`Removed attribute ${attributeId} because target note ${targetNoteId} is also deleted.`);
});
await runCheck(`
SELECT
linkId
FROM
await findIssues(`
SELECT linkId
FROM links
WHERE type NOT IN ('image', 'hyper', 'relation-map')`,
({linkId, type}) => `Link ${linkId} has invalid type '${type}'`);
await findAndFixIssues(`
SELECT
linkId,
links.noteId AS sourceNoteId
FROM
links
LEFT JOIN notes AS sourceNote ON sourceNote.noteId = links.noteId AND sourceNote.isDeleted = 0
LEFT JOIN notes AS targetNote ON targetNote.noteId = links.noteId AND targetNote.isDeleted = 0
WHERE
JOIN notes AS sourceNote ON sourceNote.noteId = links.noteId
WHERE
links.isDeleted = 0
AND (sourceNote.noteId IS NULL
OR targetNote.noteId IS NULL)`,
"Link to source/target note link is broken", errorList);
AND sourceNote.isDeleted = 1`,
async ({linkId, sourceNoteId}) => {
const link = await repository.getLink(linkId);
link.isDeleted = true;
await link.save();
await runSyncRowChecks("notes", "noteId", errorList);
await runSyncRowChecks("note_revisions", "noteRevisionId", errorList);
await runSyncRowChecks("branches", "branchId", errorList);
await runSyncRowChecks("recent_notes", "branchId", errorList);
await runSyncRowChecks("attributes", "attributeId", errorList);
await runSyncRowChecks("api_tokens", "apiTokenId", errorList);
await runSyncRowChecks("options", "name", errorList);
logFix(`Removed link ${linkId} because source note ${sourceNoteId} is also deleted.`);
});
if (errorList.length === 0) {
await findAndFixIssues(`
SELECT
linkId,
links.targetNoteId
FROM
links
JOIN notes AS targetNote ON targetNote.noteId = links.targetNoteId
WHERE
links.isDeleted = 0
AND targetNote.isDeleted = 1`,
async ({linkId, targetNoteId}) => {
const link = await repository.getLink(linkId);
link.isDeleted = true;
await link.save();
logFix(`Removed link ${linkId} because target note ${targetNoteId} is also deleted.`);
});
}
async function runSyncRowChecks(entityName, key) {
await findAndFixIssues(`
SELECT
${key} as entityId
FROM
${entityName}
LEFT JOIN sync ON sync.entityName = '${entityName}' AND entityId = ${key}
WHERE
sync.id IS NULL AND ` + (entityName === 'options' ? 'isSynced = 1' : '1'),
async ({entityId}) => {
await syncTableService.addEntitySync(entityName, entityId);
logFix(`Created missing sync record entityName=${entityName}, entityId=${entityId}`);
});
await findAndFixIssues(`
SELECT
id, entityId
FROM
sync
LEFT JOIN ${entityName} ON entityId = ${key}
WHERE
sync.entityName = '${entityName}'
AND ${key} IS NULL`,
async ({id, entityId}) => {
await sql.execute("DELETE FROM sync WHERE entityName = ? AND entityId = ?", [entityName, entityId]);
logFix(`Deleted extra sync record id=${id}, entityName=${entityName}, entityId=${entityId}`);
});
}
async function findSyncRowsIssues() {
await runSyncRowChecks("notes", "noteId");
await runSyncRowChecks("note_revisions", "noteRevisionId");
await runSyncRowChecks("branches", "branchId");
await runSyncRowChecks("recent_notes", "branchId");
await runSyncRowChecks("attributes", "attributeId");
await runSyncRowChecks("api_tokens", "apiTokenId");
await runSyncRowChecks("options", "name");
}
async function runAllChecks() {
unrecoverableConsistencyErrors = false;
fixedIssues = false;
await findBrokenReferenceIssues();
await findExistencyIssues();
await findLogicIssues();
await findSyncRowsIssues();
if (unrecoverableConsistencyErrors) {
// we run this only if basic checks passed since this assumes basic data consistency
await checkTreeCycles(errorList);
await checkTreeCycles();
}
return errorList;
return !unrecoverableConsistencyErrors;
}
async function runChecks() {
let errorList;
let elapsedTimeMs;
await syncMutexService.doExclusively(async () => {
const startTime = new Date();
errorList = await runAllChecks();
await runAllChecks();
elapsedTimeMs = new Date().getTime() - startTime.getTime();
});
if (errorList.length > 0) {
log.info(`Consistency checks failed (took ${elapsedTimeMs}ms) with these errors: ` + JSON.stringify(errorList));
if (fixedIssues) {
messagingService.refreshTree();
}
if (unrecoverableConsistencyErrors) {
log.info(`Consistency checks failed (took ${elapsedTimeMs}ms)`);
messagingService.sendMessageToAllClients({type: 'consistency-checks-failed'});
}
@@ -329,13 +446,19 @@ async function runChecks() {
}
}
function logFix(message) {
log.info("Consistency issue fixed: " + message);
}
function logError(message) {
log.info("Consistency error: " + message);
}
sqlInit.dbReady.then(() => {
setInterval(cls.wrap(runChecks), 60 * 60 * 1000);
// kickoff backup immediately
setTimeout(cls.wrap(runChecks), 10000);
// kickoff checks soon after startup (to not block the initial load)
setTimeout(cls.wrap(runChecks), 10 * 1000);
});
module.exports = {
runChecks
};
module.exports = {};
+11 -12
View File
@@ -47,8 +47,8 @@ async function getRootCalendarNote() {
return rootNote;
}
async function getYearNote(dateTimeStr, rootNote) {
const yearStr = dateTimeStr.substr(0, 4);
async function getYearNote(dateStr, rootNote) {
const yearStr = dateStr.substr(0, 4);
let yearNote = await attributeService.getNoteWithLabel(YEAR_LABEL, yearStr);
@@ -66,19 +66,19 @@ async function getYearNote(dateTimeStr, rootNote) {
return yearNote;
}
async function getMonthNote(dateTimeStr, rootNote) {
const monthStr = dateTimeStr.substr(0, 7);
const monthNumber = dateTimeStr.substr(5, 2);
async function getMonthNote(dateStr, rootNote) {
const monthStr = dateStr.substr(0, 7);
const monthNumber = dateStr.substr(5, 2);
let monthNote = await attributeService.getNoteWithLabel(MONTH_LABEL, monthStr);
if (!monthNote) {
const yearNote = await getYearNote(dateTimeStr, rootNote);
const yearNote = await getYearNote(dateStr, rootNote);
monthNote = await getNoteStartingWith(yearNote.noteId, monthNumber);
if (!monthNote) {
const dateObj = dateUtils.parseDate(dateTimeStr);
const dateObj = dateUtils.parseLocalDate(dateStr);
const noteTitle = monthNumber + " - " + MONTHS[dateObj.getMonth()];
@@ -92,21 +92,20 @@ async function getMonthNote(dateTimeStr, rootNote) {
return monthNote;
}
async function getDateNote(dateTimeStr) {
async function getDateNote(dateStr) {
const rootNote = await getRootCalendarNote();
const dateStr = dateTimeStr.substr(0, 10);
const dayNumber = dateTimeStr.substr(8, 2);
const dayNumber = dateStr.substr(8, 2);
let dateNote = await attributeService.getNoteWithLabel(DATE_LABEL, dateStr);
if (!dateNote) {
const monthNote = await getMonthNote(dateTimeStr, rootNote);
const monthNote = await getMonthNote(dateStr, rootNote);
dateNote = await getNoteStartingWith(monthNote.noteId, dayNumber);
if (!dateNote) {
const dateObj = dateUtils.parseDate(dateTimeStr);
const dateObj = dateUtils.parseLocalDate(dateStr);
const noteTitle = dayNumber + " - " + DAYS[dateObj.getDay()];
+19
View File
@@ -2,6 +2,16 @@ function nowDate() {
return dateStr(new Date());
}
function nowLocalDate() {
const date = new Date();
return date.getFullYear() + "-" + pad(date.getMonth() + 1) + "-" + pad(date.getDate());
}
function pad(num) {
return num <= 9 ? `0${num}` : `${num}`;
}
function dateStr(date) {
return date.toISOString();
}
@@ -25,14 +35,23 @@ function parseDate(str) {
return parseDateTime(datePart + "T12:00:00.000Z");
}
function parseLocalDate(str) {
const datePart = str.substr(0, 10);
// not specifying the timezone and specifying the time means Date.parse() will use the local timezone
return parseDateTime(datePart + " 12:00:00.000");
}
function getDateTimeForFile() {
return new Date().toISOString().substr(0, 19).replace(/:/g, '');
}
module.exports = {
nowDate,
nowLocalDate,
dateStr,
parseDate,
parseDateTime,
parseLocalDate,
getDateTimeForFile
};
+4
View File
@@ -20,6 +20,10 @@ async function exportSingleNote(branch, format, res) {
if (note.type === 'text') {
if (format === 'html') {
if (!note.content.toLowerCase().includes("<html")) {
note.content = '<html><head><meta charset="utf-8"></head><body>' + note.content + '</body></html>';
}
payload = html.prettyPrint(note.content, {indent_size: 2});
extension = 'html';
mime = 'text/html';
+6 -3
View File
@@ -74,11 +74,10 @@ async function exportToTar(branch, format, res) {
return;
}
const baseFileName = branch.prefix ? (branch.prefix + ' - ' + note.title) : note.title;
const baseFileName = sanitize(branch.prefix ? (branch.prefix + ' - ' + note.title) : note.title);
if (note.noteId in noteIdToMeta) {
const sanitizedFileName = sanitize(baseFileName + ".clone");
const fileName = getUniqueFilename(existingFileNames, sanitizedFileName);
const fileName = getUniqueFilename(existingFileNames, baseFileName + ".clone");
return {
isClone: true,
@@ -150,6 +149,10 @@ async function exportToTar(branch, format, res) {
function prepareContent(note, format) {
if (format === 'html') {
if (!note.content.toLowerCase().includes("<html")) {
note.content = '<html><head><meta charset="utf-8"></head><body>' + note.content + '</body></html>';
}
return html.prettyPrint(note.content, {indent_size: 2});
}
else if (format === 'markdown') {
+2 -2
View File
@@ -12,7 +12,7 @@ async function runAttachedRelations(note, relationName, originEntity) {
const scriptNote = await relation.getTargetNote();
if (scriptNote) {
await scriptService.executeNote(scriptNote, originEntity);
await scriptService.executeNoteNoException(scriptNote, { originEntity });
}
else {
log.error(`Target note ${relation.value} of atttribute ${relation.attributeId} has not been found.`);
@@ -30,7 +30,7 @@ eventService.subscribe(eventService.NOTE_TITLE_CHANGED, async note => {
if (await parent.hasLabel("sorted")) {
await treeService.sortNotesAlphabetically(parent.noteId);
messagingService.sendMessageToAllClients({ type: 'refresh-tree' });
messagingService.refreshTree();
break; // sending the message once is enough
}
}
+5
View File
@@ -49,6 +49,10 @@ async function sendMessage(client, message) {
}
}
async function refreshTree() {
await sendMessageToAllClients({ type: 'refresh-tree' });
}
async function sendMessageToAllClients(message) {
const jsonStr = JSON.stringify(message);
@@ -76,5 +80,6 @@ async function sendPing(client, lastSentSyncId) {
module.exports = {
init,
refreshTree,
sendMessageToAllClients
};
+4
View File
@@ -49,6 +49,10 @@ async function initNotSyncedOptions(initialized, startNotePath = 'root', syncSer
await optionService.createOption('syncServerTimeout', 5000, false);
await optionService.createOption('syncProxy', syncProxy, false);
await optionService.createOption('mainFontSize', '100', false);
await optionService.createOption('treeFontSize', '100', false);
await optionService.createOption('detailFontSize', '110', false);
await optionService.createOption('initialized', initialized ? 'true' : 'false', false);
}
+6
View File
@@ -57,6 +57,11 @@ async function getOption(name) {
return await getEntity("SELECT * FROM options WHERE name = ?", [name]);
}
/** @returns {Link|null} */
async function getLink(linkId) {
return await getEntity("SELECT * FROM links WHERE linkId = ?", [linkId]);
}
async function updateEntity(entity) {
const entityName = entity.constructor.entityName;
const primaryKeyName = entity.constructor.primaryKeyName;
@@ -119,6 +124,7 @@ module.exports = {
getBranch,
getAttribute,
getOption,
getLink,
updateEntity,
setEntityConstructor
};
+1 -3
View File
@@ -7,7 +7,6 @@ const RESOURCE_DIR = path.resolve(__dirname, "../..");
// where "trilium" executable is
const ELECTRON_APP_ROOT_DIR = path.resolve(RESOURCE_DIR, "../..");
const DB_INIT_DIR = path.resolve(RESOURCE_DIR, "db");
const APP_PNG_ICON_DIR = path.resolve(RESOURCE_DIR, "src/public/images/app-icons/png");
if (!fs.existsSync(DB_INIT_DIR)) {
log.error("Could not find DB initialization directory: " + DB_INIT_DIR);
@@ -25,6 +24,5 @@ module.exports = {
RESOURCE_DIR,
MIGRATIONS_DIR,
DB_INIT_DIR,
ELECTRON_APP_ROOT_DIR,
APP_PNG_ICON_DIR
ELECTRON_APP_ROOT_DIR
};
+1 -1
View File
@@ -17,7 +17,7 @@ async function runNotesWithLabel(runAttrValue) {
AND notes.isDeleted = 0`, [runAttrValue]);
for (const note of notes) {
scriptService.executeNote(note, note);
scriptService.executeNoteNoException(note, { originEntity: note });
}
}
+23 -11
View File
@@ -5,37 +5,48 @@ const cls = require('./cls');
const sourceIdService = require('./source_id');
const log = require('./log');
async function executeNote(note, originEntity) {
if (!note.isJavaScript() || !note.isContentAvailable) {
async function executeNote(note, apiParams) {
if (!note.isJavaScript() || note.getScriptEnv() !== 'backend' || !note.isContentAvailable) {
return;
}
const bundle = await getScriptBundle(note);
await executeBundle(bundle, note, originEntity);
await executeBundle(bundle, apiParams);
}
async function executeBundle(bundle, startNote, originEntity = null) {
if (!startNote) {
async function executeNoteNoException(note, apiParams) {
try {
await executeNote(note, apiParams);
}
catch (e) {
// just swallow, exception is logged already in executeNote
}
}
async function executeBundle(bundle, apiParams = {}) {
if (!apiParams.startNote) {
// this is the default case, the only exception is when we want to preserve frontend startNote
startNote = bundle.note;
apiParams.startNote = bundle.note;
}
// last \r\n is necessary if script contains line comment on its last line
const script = "async function() {\r\n" + bundle.script + "\r\n}";
const ctx = new ScriptContext(startNote, bundle.allNotes, originEntity);
const ctx = new ScriptContext(bundle.allNotes, apiParams);
try {
if (await bundle.note.hasLabel('manualTransactionHandling')) {
return await execute(ctx, script, '');
return await execute(ctx, script);
}
else {
return await sql.transactional(async () => await execute(ctx, script, ''));
return await sql.transactional(async () => await execute(ctx, script));
}
}
catch (e) {
log.error(`Execution of script "${bundle.note.title}" (${bundle.note.noteId}) failed with error: ${e.message}`);
throw e;
}
}
@@ -57,11 +68,11 @@ async function executeScript(script, params, startNoteId, currentNoteId, originE
return await executeBundle(bundle, startNote, originEntity);
}
async function execute(ctx, script, paramsStr) {
async function execute(ctx, script, params = []) {
// scripts run as "server" sourceId so clients recognize the changes as "foreign" and update themselves
cls.namespace.set('sourceId', sourceIdService.getCurrentSourceId());
return await (function() { return eval(`const apiContext = this;\r\n(${script}\r\n)(${paramsStr})`); }.call(ctx));
return await (function() { return eval(`const apiContext = this;\r\n(${script}\r\n)()`); }.call(ctx));
}
function getParams(params) {
@@ -168,6 +179,7 @@ function sanitizeVariableName(str) {
module.exports = {
executeNote,
executeNoteNoException,
executeScript,
getScriptBundleForFrontend
};
+2 -2
View File
@@ -1,10 +1,10 @@
const utils = require('./utils');
const BackendScriptApi = require('./backend_script_api');
function ScriptContext(startNote, allNotes, originEntity = null) {
function ScriptContext(allNotes, apiParams = {}) {
this.modules = {};
this.notes = utils.toObject(allNotes, note => [note.noteId, note]);
this.apis = utils.toObject(allNotes, note => [note.noteId, new BackendScriptApi(startNote, note, originEntity)]);
this.apis = utils.toObject(allNotes, note => [note.noteId, new BackendScriptApi(note, apiParams)]);
this.require = moduleNoteIds => {
return moduleName => {
const candidates = allNotes.filter(note => moduleNoteIds.includes(note.noteId));
+1 -1
View File
@@ -123,7 +123,7 @@ async function execute(query, params = []) {
const milliseconds = Date.now() - startTimestamp;
if (milliseconds >= 200) {
log.info(`Slow query took ${milliseconds}ms: ${query}, params=${params}`);
log.info(`Slow query took ${milliseconds}ms: ${query}`);
}
return result;
+4
View File
@@ -155,6 +155,10 @@ async function dbInitialized() {
await initDbConnection();
}
dbReady.then(async () => {
log.info("DB size: " + await sql.getValue("SELECT page_count * page_size / 1000 as size FROM pragma_page_count(), pragma_page_size()") + " KB");
});
module.exports = {
dbReady,
schemaExists,
+12
View File
@@ -111,6 +111,12 @@ async function sortNotesAlphabetically(parentNoteId) {
}
async function setNoteToParent(noteId, prefix, parentNoteId) {
const parentNote = await repository.getNote(parentNoteId);
if (parentNote && parentNote.isDeleted) {
throw new Error(`Cannot move note to deleted parent note ${parentNoteId}`);
}
// case where there might be more such branches is ignored. It's expected there should be just one
const branch = await repository.getEntity("SELECT * FROM branches WHERE isDeleted = 0 AND noteId = ? AND prefix = ?", [noteId, prefix]);
@@ -126,6 +132,12 @@ async function setNoteToParent(noteId, prefix, parentNoteId) {
await branch.save();
}
else if (parentNoteId) {
const note = await repository.getNote(noteId);
if (note.isDeleted) {
throw new Error(`Cannot create a branch for ${noteId} which is deleted.`);
}
await new Branch({
noteId: noteId,
parentNoteId: parentNoteId,
+3 -6
View File
@@ -75,8 +75,8 @@
<input type="file" id="import-upload" style="display: none" />
<div id="search-box">
<div style="display: flex; align-items: center;">
<input name="search-text" placeholder="Search text, labels" style="flex-grow: 100; margin-left: 5px; margin-right: 5px;" autocomplete="off">
<div style="display: flex; align-items: center; flex-wrap: wrap;">
<input name="search-text" id="search-text" placeholder="Search text, labels" style="flex-grow: 100; margin-left: 5px; margin-right: 5px; flex-basis: 5em; min-width: 0;" autocomplete="off">
<button id="do-search-button" class="btn btn-sm icon-button jam jam-search" title="Search (enter)"></button>
&nbsp;
@@ -212,6 +212,7 @@
maxSyncIdAtLoad: <%= maxSyncIdAtLoad %>,
instanceName: '<%= instanceName %>'
};
window.appCssNoteIds = <%- JSON.stringify(appCssNoteIds) %>;
</script>
<!-- Required for correct loading of scripts in Electron -->
@@ -247,9 +248,5 @@
// final form which is pretty ugly.
$("#container").show();
</script>
<style type="text/css">
<%= appCss %>
</style>
</body>
</html>
+5 -1
View File
@@ -1,5 +1,9 @@
<div id="note-detail-file" class="note-detail-component">
<table id="file-table">
<tr>
<th>Note ID:</th>
<td id="file-note-id"></td>
</tr>
<tr>
<th>Original file name:</th>
<td id="file-filename"></td>
@@ -19,7 +23,7 @@
</td>
</tr>
<tr>
<td>
<td colspan="2">
<button id="file-download" class="btn btn-primary" type="button">Download</button>
&nbsp;
<button id="file-open" class="btn btn-primary" type="button">Open</button>
+1 -5
View File
@@ -40,11 +40,7 @@
<form>
<div class="form-group">
<label for="theme-select">Theme</label>
<select class="form-control" id="theme-select">
<option value="white">White</option>
<option value="dark">Dark</option>
<option value="black">Black</option>
</select>
<select class="form-control" id="theme-select"></select>
</div>
<div class="form-group">
+4 -3
View File
@@ -4,6 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Login</title>
<link rel="apple-touch-icon" sizes="180x180" href="/images/app-icons/ios/apple-touch-icon.png">
</head>
<body>
<div class="container">
@@ -71,7 +72,7 @@
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
</script>
<link href="libraries/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</body>
<link href="libraries/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</body>
</html>
+4 -3
View File
@@ -4,6 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Trilium Notes</title>
<link rel="apple-touch-icon" sizes="180x180" href="/images/app-icons/ios/apple-touch-icon.png">
</head>
<body class="mobile">
<div class="row" id="container-row" style="display: none;">
@@ -101,7 +102,7 @@
<script type="text/javascript">
// we hide container initally because otherwise it is rendered first without CSS and then flickers into
// final form which is pretty ugly.
$("#container-row").show();
</script>
</body>
$("#container-row").show();
</script>
</body>
</html>
+1
View File
@@ -128,6 +128,7 @@
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>
<script src="libraries/jquery.min.js"></script>
<script src="libraries/jquery.hotkeys.js"></script>
<link href="libraries/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="libraries/bootstrap/js/bootstrap.bundle.min.js"></script>
+6
View File
@@ -20,6 +20,12 @@ const messagingService = require('./services/messaging');
const utils = require('./services/utils');
const sqlInit = require('./services/sql_init');
const port = require('./services/port');
const semver = require('semver');
if (!semver.satisfies(process.version, ">=10.5.0")) {
console.error("Trilium only supports node.js 10.5 and later");
process.exit(1);
}
let httpServer;