From 982b7236474215cac731823775a77b71e20c4358 Mon Sep 17 00:00:00 2001 From: azivner Date: Fri, 2 Mar 2018 20:56:58 -0500 Subject: [PATCH] basic scheduling of backend scripts using attributes --- src/app.js | 2 ++ src/services/attributes.js | 3 ++- src/services/scheduler.js | 26 ++++++++++++++++++++++++++ src/services/script.js | 13 +++++++++++++ 4 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/services/scheduler.js diff --git a/src/app.js b/src/app.js index e36391bfb..38936ff5e 100644 --- a/src/app.js +++ b/src/app.js @@ -73,6 +73,8 @@ require('./services/backup'); // trigger consistency checks timer require('./services/consistency_checks'); +require('./services/scheduler'); + module.exports = { app, sessionParser diff --git a/src/services/attributes.js b/src/services/attributes.js index c597c766e..8ba17cd81 100644 --- a/src/services/attributes.js +++ b/src/services/attributes.js @@ -10,7 +10,8 @@ const BUILTIN_ATTRIBUTES = [ 'disable_versioning', 'calendar_root', 'hide_in_autocomplete', - 'exclude_from_export' + 'exclude_from_export', + 'run' ]; async function getNoteAttributeMap(noteId) { diff --git a/src/services/scheduler.js b/src/services/scheduler.js new file mode 100644 index 000000000..8d296e833 --- /dev/null +++ b/src/services/scheduler.js @@ -0,0 +1,26 @@ +const script = require('./script'); +const Repository = require('./repository'); + +const repo = new Repository(); + +async function runNotesWithAttribute(runAttrValue) { + const notes = await repo.getEntities(` + SELECT notes.* + FROM notes + JOIN attributes ON attributes.noteId = notes.noteId + AND attributes.name = 'run' + AND attributes.value = ? + WHERE + notes.type = 'code' + AND notes.isDeleted = 0`, [runAttrValue]); + + for (const note of notes) { + script.executeNote(note); + } +} + +setTimeout(() => runNotesWithAttribute('on_startup'), 10 * 1000); + +setInterval(() => runNotesWithAttribute('hourly'), 3600 * 1000); + +setInterval(() => runNotesWithAttribute('daily'), 24 * 3600 * 1000); \ No newline at end of file diff --git a/src/services/script.js b/src/services/script.js index 7021393d1..0de7c47c0 100644 --- a/src/services/script.js +++ b/src/services/script.js @@ -1,6 +1,18 @@ const sql = require('./sql'); const ScriptContext = require('./script_context'); +async function executeNote(note) { + if (note.isProtected || !note.isJavaScript()) { + return; + } + + const ctx = new ScriptContext(); + + return await sql.doInTransaction(async () => { + return await (function() { return eval(`const api = this; (async function() {${note.content}\n\r})()`); }.call(ctx)); + }); +} + async function executeScript(dataKey, script, params) { const ctx = new ScriptContext(dataKey); const paramsStr = getParams(params); @@ -73,6 +85,7 @@ function getParams(params) { } module.exports = { + executeNote, executeScript, setJob }; \ No newline at end of file