From 10dbd8c3c3bfddb96d21c53b5db95ea263b04a88 Mon Sep 17 00:00:00 2001 From: bordun Date: Tue, 27 Oct 2020 09:51:09 +0100 Subject: [PATCH] custom module: refactor custom module and add autoreload --- CHANGELOG.md | 3 + package.json | 1 + src/server/custom-module.js | 162 ++++++++++++++++++++++++++++++++++++ src/server/osc/index.js | 114 ++++++------------------- 4 files changed, 191 insertions(+), 89 deletions(-) create mode 100644 src/server/custom-module.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 4184e622..a135cfdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ - widgets - all: add `html` property to allow inserting custom content in widgets (label, value, etc) and style it with the `css` property. +- custom module + - automatically reload custom module when the file is modified + ## 1.5.4 - bug fixes diff --git a/package.json b/package.json index b101d936..3566ac61 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "babelify": "10.0.0", "bonjour": "github:jean-emmanuel/bonjour", "browserify": "16.5.1", + "chokidar": "3.4.3", "chroma-js": "2.1.0", "core-js": "3.6.5", "cpr": "3.0.1", diff --git a/src/server/custom-module.js b/src/server/custom-module.js new file mode 100644 index 00000000..12a977a0 --- /dev/null +++ b/src/server/custom-module.js @@ -0,0 +1,162 @@ +var settings = require('./settings'), + fs = require('fs'), + vm = require('vm'), + chokidar = require('chokidar') + + +class CustomModule { + + constructor(file, context) { + + this.init = null + this.oscInFilter = null + this.oscOutFilter = null + + this.filename = file + + this.timeouts = [] + this.intervals = [] + + this.context = { + ...context, + loadJSON: (url)=>{ + if (url.split('.').pop() === 'json') { + try { + url = path.resolve(path.dirname(customModule), url) + return JSON.parse(fs.readFileSync(url, 'utf8')) + } catch(e) { + console.error('(ERROR) could not load json file from ' + url) + console.error(e.message) + } + } else { + console.error('(ERROR) unauthorized file type for loadJSON') + } + }, + saveJSON: (url, data)=>{ + if (url.split('.').pop() === 'json') { + url = path.resolve(path.dirname(customModule), url) + try { + return fs.writeFileSync(url, JSON.stringify(data, null, ' ')) + } catch(e) { + console.error('(ERROR) could not save json file to ' + url) + console.error(e.message) + } + } else { + console.error('(ERROR) unauthorized file type for saveJSON') + } + }, + console: console, + settings: settings, + setTimeout: this.setTimeout.bind(this), + clearTimeout: this.clearTimeout.bind(this), + setInterval: this.setInterval.bind(this), + clearInterval: this.clearInterval.bind(this), + module: {exports: {}} + } + + this.load() + + chokidar.watch(this.filename).on('change', ()=>{ + this.reload() + }) + + } + + load() { + + var code + + try { + code = fs.readFileSync(this.filename, 'utf8') + } catch(err) { + console.error('(ERROR) Custom module not found: ' + this.filename) + return false + } + + var context = vm.createContext({ + ...this.context + }) + + try { + vm.runInContext(code, context, { + filename: this.filename + }) + } catch(err) { + console.error('(ERROR) Custom module loading error') + console.error(err) + return false + } + + this.init = context.module.exports.init || null + this.oscInFilter = context.module.exports.oscInFilter || null + this.oscOutFilter = context.module.exports.oscOutFilter || null + + return true + + } + + unload() { + + this.init = null + this.oscInFilter = null + this.oscOutFilter = null + + for (let timeout of this.timeouts) { + clearTimeout(timeout) + } + + for (let interval of this.intervals) { + clearInterval(interval) + } + + this.timeouts = [] + this.intervals = [] + + for (let name of this.context.app.eventNames()) { + this.context.app.removeAllListeners(name) + } + + } + + reload() { + + this.unload() + console.log('(INFO) Reloading custom module: ' + this.filename) + if (this.load()) { + console.log('(INFO) Custom module reloaded successfully') + } else { + console.log('(ERROR) Failed to reload custom module') + this.unload() + } + } + + setTimeout(fn, t) { + var timeout = setTimeout(fn, t) + this.timeouts.push(timeout) + return timeout + } + + setInterval(fn, t) { + var interval = setInterval(fn, t) + this.intervals.push(interval) + return interval + } + + clearTimeout(timeout) { + clearTimeout(timeout) + if (this.timeouts.includes(timeout)) { + this.timeouts.splice(this.timeouts.indexOf(timeout), 1) + } + } + + clearInterval(id) { + clearInterval(interval) + if (this.intervals.includes(interval)) { + this.intervals.splice(this.intervals.indexOf(interval), 1) + } + } + +} + + +module.exports = CustomModule diff --git a/src/server/osc/index.js b/src/server/osc/index.js index 7ea0eac3..b9c3140c 100644 --- a/src/server/osc/index.js +++ b/src/server/osc/index.js @@ -8,7 +8,8 @@ var path = require('path'), midi = settings.read('midi') ? require('../midi') : false, oscUDPServer = require('./udp'), oscTCPServer = require('./tcp'), - EventEmitter = require('events').EventEmitter + EventEmitter = require('events').EventEmitter, + CustomModule = require('../custom-module') if (midi) midi = new midi() @@ -18,94 +19,29 @@ class OscServer { constructor(){ this.customModuleEventEmitter = new EventEmitter() - this.customModule = (()=>{ - - var customModule = settings.read('custom-module') - - if (!customModule) return false - - var file = (()=>{ - try { - return fs.readFileSync(customModule, 'utf8') - } catch(err) { - console.error('(ERROR) Custom module not found: ' + customModule) - return false - } - })(), - mod, - context = vm.createContext({ - console, - sendOsc: this.sendOsc.bind(this), - receiveOsc: this.receiveOsc.bind(this), - send: (host, port, address, ...args)=>{ - this.sendOsc({host, port, address, args:args.map(x=>this.parseArg(x))}) - }, - receive: (host, port, address, ...args)=>{ - if (host[0] === '/') { - // host and port can be skipped - if (address !== undefined) args.unshift(address) - if (port !== undefined) args.unshift(port) - address = host - host = port = undefined - } - var lastArg = args[args.length - 1], - options = {} - if (typeof lastArg === 'object' && lastArg !== null && lastArg.clientId !== undefined) { - options = args.pop() - } - this.receiveOsc({host, port, address, args:args.map(x=>this.parseArg(x))}, options.clientId) - }, - loadJSON: (url)=>{ - if (url.split('.').pop() === 'json') { - try { - url = path.resolve(path.dirname(customModule), url) - return JSON.parse(fs.readFileSync(url, 'utf8')) - } catch(e) { - console.error('(ERROR) could not load json file from ' + url) - console.error(e.message) - } - } else { - console.error('(ERROR) unauthorized file type for loadJSON') - } - }, - saveJSON: (url, data)=>{ - if (url.split('.').pop() === 'json') { - url = path.resolve(path.dirname(customModule), url) - try { - return fs.writeFileSync(url, JSON.stringify(data, null, ' ')) - } catch(e) { - console.error('(ERROR) could not save json file to ' + url) - console.error(e.message) - } - } else { - console.error('(ERROR) unauthorized file type for saveJSON') - } - }, - app: this.customModuleEventEmitter, - setTimeout, clearTimeout, - setInterval, clearInterval, - settings, - module: {}, - }) - - try { - // remove require function (not needed at runtime) - // wrong: this.constructor.constructor("return process")().mainModule.require - process.mainModule.require = process.dlopen = null - // run - mod = vm.runInContext(file, context, { - filename: customModule - }) - if (context.module.exports) mod = context.module.exports - } catch(err) { - console.error(err) - return false - } - - return mod - - })() - + this.customModule = settings.read('custom-module') ? new CustomModule(settings.read('custom-module'), { + app: this.customModuleEventEmitter, + sendOsc: this.sendOsc.bind(this), + receiveOsc: this.receiveOsc.bind(this), + send: (host, port, address, ...args)=>{ + this.sendOsc({host, port, address, args:args.map(x=>this.parseArg(x))}) + }, + receive: (host, port, address, ...args)=>{ + if (host[0] === '/') { + // host and port can be skipped + if (address !== undefined) args.unshift(address) + if (port !== undefined) args.unshift(port) + address = host + host = port = undefined + } + var lastArg = args[args.length - 1], + options = {} + if (typeof lastArg === 'object' && lastArg !== null && lastArg.clientId !== undefined) { + options = args.pop() + } + this.receiveOsc({host, port, address, args:args.map(x=>this.parseArg(x))}, options.clientId) + }, + }) : null }