server: migrate to esm, split node and electron code

This commit is contained in:
jean-emmanuel 2025-09-12 02:44:06 +02:00
parent 7ec9e64dc0
commit 3a1a05636b
34 changed files with 1102 additions and 1058 deletions

View file

@ -0,0 +1,10 @@
import {networkInterfaces} from 'os'
export default (proto, port)=>{
var address = Object.values(networkInterfaces())
.reduce((a,b)=>a.concat(b), [])
.filter(i=>i.family === 'IPv4')
.map(i=>i.address + ':')
return address.map(x=>proto + x + port)
}

23
src/server/node/auth.js Normal file
View file

@ -0,0 +1,23 @@
import httpAuth from 'http-auth'
import * as settings from './settings'
var auth = null
if (settings.read('authentication')) {
var [name, pwd] = settings.read('authentication').split(':')
auth = httpAuth.basic(
{
realm: 'Open Stage Control'
},
(username, password, callback) => {
// Custom authentication method.
callback(username === name && password === pwd)
}
)
}
export default auth

View file

@ -0,0 +1,268 @@
import * as settings from './settings'
import fs from 'fs'
import vm from 'vm'
import chokidar from 'chokidar'
import path from 'path'
import {globalPaths} from 'module'
var modulePathExtended = false,
loadedModules = {},
globalObject = {}
class CustomModule {
constructor(file, context, parent=null, mainModule=null) {
this.module = {exports: null}
this.init = null
this.oscInFilter = null
this.oscOutFilter = null
this.mainModule = mainModule
this.parent = parent
this.submodule = !!parent
this.filename = this.submodule ? file : path.resolve(file)
this.timeouts = []
this.intervals = []
this.submodules = {}
this.context = this.submodule ? {
...context,
require: this.require.bind(this),
} : {
...context,
loadJSON: (url, errorCallback)=>{
try {
url = path.resolve(path.dirname(this.filename), url)
var content = fs.readFileSync(url, 'utf8')
if (content[0] === '\ufeff') content = content.slice(1) // remove BOM
return JSON.parse(content)
} catch(e) {
if (typeof(errorCallback) === 'function') {
errorCallback(e)
} else {
console.error('(ERROR, CUSTOM MODULE) could not load json file from ' + url)
console.error(e.message)
}
}
},
saveJSON: (url, data, errorCallback)=>{
url = path.resolve(path.dirname(this.filename), url)
try {
return fs.writeFileSync(url, JSON.stringify(data, null, ' '))
} catch(e) {
if (typeof(errorCallback) === 'function') {
errorCallback(e)
} else {
console.error('(ERROR, CUSTOM MODULE) could not save json file to ' + url)
console.error(e.message)
}
}
},
console: console,
settings: {
read: settings.read,
appAddresses: settings.appAddresses,
},
setTimeout: this.setTimeout.bind(this),
clearTimeout: this.clearTimeout.bind(this),
setInterval: this.setInterval.bind(this),
clearInterval: this.clearInterval.bind(this),
require: this.require.bind(this),
nativeRequire: require,
process: process,
global: globalObject
}
if (!this.submodule && !modulePathExtended) {
globalPaths.push(
path.resolve(path.dirname(this.filename)),
path.resolve(path.dirname(this.filename), 'node_modules')
)
modulePathExtended = true
}
this.load()
this.watcher = chokidar.watch(this.filename, {awaitWriteFinish: {stabilityThreshold: 200}}).on('change', ()=>{
if (this.submodule) {
console.log('(INFO) Submodule changed: ' + this.filename)
this.mainModule.reload()
} else {
console.log('(INFO) Custom module changed: ' + this.filename)
this.reload()
}
})
}
load() {
if (loadedModules[this.filename]) {
this.module.exports = loadedModules[this.filename].module.exports
return true
}
var code
try {
code = fs.readFileSync(this.filename, {encoding: 'utf8', flag: 'rs'}) // flag 'rs' to avoid cache issue on windows
} catch(err) {
console.error(`(ERROR, CUSTOM MODULE) Module not found: ${this.filename}`)
return false
}
var context = vm.createContext({
...this.context,
__dirname: path.resolve(path.dirname(this.filename)),
__filename: path.resolve(this.filename),
module: this.module
})
try {
loadedModules[this.filename] = this
vm.runInContext(code, context, {
filename: this.filename
})
} catch(err) {
loadedModules[this.filename] = null
console.error('(ERROR, CUSTOM MODULE) Error while loading module')
console.log(err)
return false
}
if (typeof this.module.exports === 'object' && this.module.exports !== null) {
this.init = this.module.exports.init || null
this.oscInFilter = this.module.exports.oscInFilter || null
this.oscOutFilter = this.module.exports.oscOutFilter || null
}
return true
}
unload() {
if (!loadedModules[this.filename]) return
loadedModules[this.filename] = null
if (this.module.exports && this.module.exports.unload) {
try {
this.module.exports.unload()
} catch(e) {
console.error('(ERROR, CUSTOM MODULE) Error while calling unload()')
console.error(e)
}
}
this.module = {exports: null}
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)
}
for (let name in this.submodules) {
this.submodules[name].unload()
}
this.submodules = {}
if (this.submodule) {
this.watcher.close()
}
}
reload() {
this.unload()
console.log('(INFO) Reloading custom module...')
if (this.load()) {
console.log('(INFO) Custom module reloaded successfully')
if (this.module.exports && this.module.exports.reload) {
try {
this.module.exports.reload()
} catch(e) {
console.error('(ERROR, CUSTOM MODULE) Error while calling custom module reload function')
console.error(e)
}
}
} else {
console.error('(ERROR, CUSTOM MODULE) Failed to reload custom module')
this.unload()
}
}
stop() {
if (this.module.exports && this.module.exports.stop) {
try {
this.module.exports.stop()
} catch(e) {
console.error('(ERROR, CUSTOM MODULE) Error while calling custom module stop function')
console.error(e)
}
}
}
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(interval) {
clearInterval(interval)
if (this.intervals.includes(interval)) {
this.intervals.splice(this.intervals.indexOf(interval), 1)
}
}
require(filename) {
if (!path.isAbsolute(filename)) {
filename = path.resolve(path.dirname(this.filename), filename)
}
this.submodules[filename] = loadedModules[filename] || new CustomModule(filename, this.context, this, this.mainModule || this)
return this.submodules[filename].module.exports
}
}
export default CustomModule

View file

@ -0,0 +1,90 @@
import {EventEmitter} from 'events'
import http from 'http'
import send from 'send'
import path from 'path'
import fs from 'fs'
import open from 'open'
import address from './address'
class DocsServer extends EventEmitter {
constructor() {
super(...arguments)
this.baseUrl = path.resolve(__dirname + '/../docs')
this.home = '/docs/getting-started/introduction/'
this.server = null
this.started = false
this.port = 0
this.available = true
if (!fs.existsSync(path.join(this.baseUrl, 'index.html'))) {
console.error('(ERROR, DOCS) Documentation assets not found in the app\'s directory.')
this.available = false
}
}
start() {
if (this.started || !this.available) return
this.server = http.createServer(this.route.bind(this))
this.server.on('error', (e)=>{
console.error(`(ERROR, DOCS) ${e.message}`)
})
this.server.listen(0).on('listening', ()=>{
this.port = this.server.address().port
console.log('(INFO) Documentation server started, docs available at \n ' + address('http://', this.port).join('\n '))
this.emit('ready')
})
this.started = true
}
open() {
if (!this.started || !this.port) {
this.start()
this.on('ready', ()=>{
open(address('http://', this.port)[0] + this.home)
console.log('(INFO) Opening documentation with default browser...')
})
} else {
open(address('http://', this.port)[0] + this.home)
console.log('(INFO) Opening documentation with default browser...')
}
}
route(req, res) {
var url = req.url.replace(this.baseUrl, '').split('?')[0]
if (url[url.length-1] === '/') url += 'index.html'
if (url.indexOf('/fonts') === 0) url = '../assets' + url
url = path.join(this.baseUrl, url)
if (!fs.existsSync(url)) {
if (url.indexOf('index.html') !== -1) {
return send(req, path.join(this.baseUrl, '/404.html')).pipe(res)
} else {
res.writeHead(403)
res.end()
}
} else {
return send(req, url).pipe(res)
}
}
}
export default DocsServer

View file

@ -0,0 +1,81 @@
import chokidar from 'chokidar'
class FragmentManager {
constructor(callbacks, ipcServer, webServer) {
this.ipcServer = ipcServer
this.webServer = webServer
this.callbacks = callbacks
this.fragments = {} // fragment files contents
this.watchers = {} // fragment files watchers
this.clients = {} // client ids for each watched fragment file
}
read(path, raw, clientId, then) {
this.callbacks.fileRead({path: path, raw: raw}, clientId, true, (result)=>{
this.fragments[path] = result
then(result)
}, (error)=>{
this.ipcServer.send('errorLog', `Could not open fragment file:\n ${error}`, clientId)
this.ipcServer.send('fragmentLoad', {path: path, notFound: true})
this.deleteFragment(path)
})
}
loadFragment(data, clientId) {
var path = data.path
var resolvedPath = this.webServer.resolvePath(path, clientId)
if (!resolvedPath) {
this.ipcServer.send('fragmentLoad', {path: path, notFound: true})
return
}
if (!this.clients[resolvedPath]) this.clients[resolvedPath] = []
if (!this.clients[resolvedPath].includes(clientId)) this.clients[resolvedPath].push(clientId)
if (!this.fragments[resolvedPath]) {
this.fragments[resolvedPath] = 'LOADING'
this.read(resolvedPath, data.raw, clientId, (result)=>{
this.ipcServer.send('fragmentLoad', {path: path, fileContent: this.fragments[resolvedPath], raw: data.raw}, clientId)
})
this.watchers[resolvedPath] = chokidar.watch(resolvedPath, {awaitWriteFinish: {stabilityThreshold: 200}}).on('change', ()=>{
this.read(resolvedPath, data.raw, clientId, (result)=>{
for (let id of this.clients[resolvedPath]) {
this.ipcServer.send('fragmentLoad', {path: path, fileContent: this.fragments[resolvedPath], raw: data.raw}, id)
}
})
}).on('unlink', ()=>{
this.deleteFragment(resolvedPath)
})
} else if (this.fragments[resolvedPath] !== 'LOADING') {
this.ipcServer.send('fragmentLoad', {path: path, fileContent: this.fragments[resolvedPath], raw: data.raw}, clientId)
}
}
deleteFragment(path) {
this.watchers[path].close()
delete this.clients[path]
delete this.fragments[path]
delete this.fragments[path]
}
}
export default FragmentManager

46
src/server/node/index.js Normal file
View file

@ -0,0 +1,46 @@
import sourceMap from 'source-map-support'
import * as settings from './settings'
import qrcode from './qrcode'
import zeroconf from './zeroconf'
import DocsServer from './docs-server'
import OscServer from './osc'
import WebServer from './server'
import IpcServer from './ipc/server'
sourceMap.install({handleUncaughtExceptions: false})
process.on('uncaughtException', (err)=>{
console.error('(ERROR) A JavaScript error occurred in the main process:')
console.error(err.stack)
})
if (settings.read('docs')) {
var docsServer = new DocsServer()
docsServer.open()
} else {
var webServer = new WebServer(),
oscServer = new OscServer(),
ipcServer = new IpcServer(webServer, oscServer)
webServer.start(ipcServer)
oscServer.start(ipcServer)
process.on('SIGINT', function() {
webServer.stop()
oscServer.stop()
zeroconf.unpublishAll()
process.exit(0)
})
if (!process.env.OSC_SERVER_PROCESS) webServer.on('serverStarted', ()=>{
if (!settings.read('no-qrcode')) {
qrcode('terminal', (qr)=>console.log(qr))
}
})
}

View file

@ -0,0 +1,578 @@
import path from 'path'
import fs from 'fs'
import child_process from 'child_process'
import * as settings from '../settings'
import {deepCopy, resolveHomeDir} from '../utils'
import FragmentManager from '../fragment-manager'
export default class Callbacks {
constructor(ipcServer, webServer, oscServer) {
this.oscServer = oscServer
this.ipcServer = ipcServer
this.webServer = webServer
this.fragmentManager = new FragmentManager(this, ipcServer, webServer)
this.clipboardContent = {clipboard: null, idClipboard: null}
this.widgetHashTable = {}
}
getEvents() {
return Object.getOwnPropertyNames(this.__proto__)
.filter(x=>!['constructor', 'getEvents'].includes(x))
.filter(x=>typeof this[x] == 'function')
}
open(data, clientId) {
// client connected
this.ipcServer.send('connected')
var recentSessions = settings.read('recentSessions')
this.ipcServer.send('sessionList', recentSessions, clientId)
this.ipcServer.send('clipboard', this.clipboardContent, clientId)
this.ipcServer.send('serverTargets', settings.read('send'), clientId)
if (settings.read('load') && !data.hotReload) return this.sessionOpen({path: settings.read('load')}, clientId)
}
close(data, clientId) {
// client disconnected
}
created(data, clientId) {
// client created or reconnected
if (!this.widgetHashTable[clientId]) {
this.widgetHashTable[clientId] = {CONSOLE: {typeTags: ''}}
}
}
destroyed(data, clientId) {
// client removed (timeout)
// clear osc data cache
if (this.widgetHashTable[clientId]) delete this.widgetHashTable[clientId]
}
clipboard(data, clientId) {
// shared clipboard
this.clipboardContent = data
this.ipcServer.send('clipboard', data, null, clientId)
}
sessionAddToHistory(data) {
var recentSessions = settings.read('recentSessions')
fs.lstat(data, (err, stats)=>{
if (err || !stats.isFile()) return
// add session to history
recentSessions.unshift(path.resolve(data))
// remove doubles from history
recentSessions = recentSessions.filter(function(elem, index, self) {
return index == self.indexOf(elem)
})
// history size limit
if (recentSessions.length > 10) recentSessions = recentSessions.slice(0, 10)
// save history
settings.write('recentSessions', recentSessions)
this.ipcServer.send('sessionList', recentSessions)
})
}
sessionRemoveFromHistory(data) {
var recentSessions = settings.read('recentSessions')
if (recentSessions.indexOf(data) > -1) {
recentSessions.splice(recentSessions.indexOf(data),1)
settings.write('recentSessions',recentSessions)
this.ipcServer.send('sessionList', recentSessions)
}
}
sessionSetPath(data, clientId) {
// store client's current session file path
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
if (!settings.read('read-only')) {
this.sessionAddToHistory(data.path)
}
this.ipcServer.clients[clientId].sessionPath = data.path
this.ipcServer.send('setTitle', path.basename(data.path), clientId)
}
sessionOpen(data, clientId) {
// attempt to read session file
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
this.fileRead(data, clientId, true, (result)=>{
this.ipcServer.clients[clientId].sessionPath = data.path // for resolving local file requests
this.ipcServer.send('sessionOpen', {path: data.path, fileContent: result}, clientId)
}, (error)=>{
this.ipcServer.send('error', `Could not open session file:\n ${error}`)
})
}
fragmentLoad(data, clientId) {
// attempt to read session file
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
this.fragmentManager.loadFragment(data, clientId)
}
sessionOpened(data, clientId) {
// session file opened successfully
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
if (settings.read('state')) {
var send = true
for (var id in this.ipcServer.clients) {
// only make the client send its osc state if there are no other active clients
if (id !== clientId && this.ipcServer.clients[id].connected()) {
send = false
}
}
var stateContent = fs.readFileSync(settings.read('state'), 'utf8')
if (stateContent[0] === '\ufeff') stateContent = stateContent.slice(1) // remove BOM
var state = {
state: JSON.parse(stateContent),
send: send
}
this.ipcServer.send('stateLoad', state, clientId)
}
this.ipcServer.send('stateSend', null, null, clientId)
this.sessionSetPath({path: data.path}, clientId)
}
fileRead(data, clientId, ok, callback, errorCallback) {
// private function
if (!ok) return
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
data.path = resolveHomeDir(data.path)
if (!path.isAbsolute(data.path) && settings.read('remote-root')) data.path = path.resolve(resolveHomeDir(settings.read('remote-root')), data.path)
fs.readFile(data.path, 'utf8', (err, result)=>{
var error
if (err) {
error = err
} else {
try {
if (result[0] === '\ufeff') result = result.slice(1) // remove BOM
result = data.raw ? result : JSON.parse(result)
callback(result)
} catch(err) {
error = err
}
}
if (error && errorCallback) errorCallback(error)
})
}
fileSave(data, clientId, ok, callback) {
// private function
if (!ok) return
if (!data.path || settings.read('remote-saving') && !RegExp(settings.read('remote-saving')).test(this.ipcServer.clients[clientId].address)) {
return this.ipcServer.send('notify', {
icon: 'save',
locale: 'remotesave_forbidden',
class: 'error'
}, clientId)
}
if (data.path) {
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
data.path = resolveHomeDir(data.path)
if (!path.isAbsolute(data.path) && settings.read('remote-root')) data.path = path.resolve(settings.read('remote-root'), data.path)
var root = resolveHomeDir(settings.read('remote-root'))
if (root && !path.normalize(data.path).includes(path.normalize(root))) {
console.error('(ERROR) Could not save: path outside of remote-root')
return this.ipcServer.send('notify', {
class: 'error',
locale: 'remotesave_fail',
message: ' (Could not save: path outside of remote-root)'
}, clientId)
}
try {
JSON.parse(data.session)
} catch(e) {
return console.error('(ERROR) Could not save: invalid file')
}
fs.writeFile(data.path, data.session, function(err, fdata) {
if (err) return this.ipcServer.send('notify', {
class: 'error',
locale: 'remotesave_fail',
message: ' (' + err.message + ')'
}, clientId)
this.ipcServer.send('notify', {
icon: 'save',
locale: 'remotesave_success',
class: 'session-save',
message: ' ('+ path.basename(data.path) +')'
}, clientId)
callback()
})
}
}
stateOpen(data, clientId) {
// attempt to open state file
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
this.fileRead(data, clientId, true, (result)=>{
this.ipcServer.send('stateLoad', {state: result, path: data.path, send: true}, clientId)
}, (error)=>{
this.ipcServer.send('error', `Could not open state file:\n ${error}`)
})
}
sessionSave(data, clientId) {
// save session file (.json)
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
if (!path.basename(data.path).match(/.*\.json$/)) return console.error('(ERROR) Sessions must be saved as .json files')
if (data.backup) {
var newpath, i = 0
for (;;) {
newpath = data.path.replace(/\.json$/, '-backup' + String(i).padStart(3, 0) + '.json')
if (fs.existsSync(newpath)) i++
else {
data.path = newpath
break
}
}
}
this.fileSave(data, clientId, true, ()=>{
console.log('(INFO) Session file saved in '+ data.path)
if (!data.backup) this.ipcServer.send('sessionSaved', clientId)
// reload session in other clients
for (var id in this.ipcServer.clients) {
if (id !== clientId && this.ipcServer.clients[id].sessionPath === data.path) {
this.sessionOpen({path: data.path}, id)
}
}
if (!data.backup) this.sessionSetPath({path: data.path}, clientId)
})
}
stateSave(data, clientId) {
// save state file (.json)
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
if (!path.basename(data.path).match(/.*\.state/)) return console.error('(ERROR) Statesaves must be saved as .state files')
this.fileSave(data, clientId, true, ()=>{
console.log('(INFO) State file saved in '+ data.path)
})
}
syncOsc(shortdata, clientId) {
// sync osc (or midi) message with other clients
// if widget hash is provided, look for cached data
if (!(this.widgetHashTable[clientId] && this.widgetHashTable[clientId][shortdata.h])) return
var value = shortdata.v,
data = shortdata.h ? this.widgetHashTable[clientId][shortdata.h] : {}
data = deepCopy(data)
for (var k in shortdata) {
data[k] = shortdata[k]
}
// only rawTarget will be used
delete data.target
data.args = data.preArgs ? data.preArgs.concat(value) : [value]
if (!data.noSync) this.ipcServer.send('receiveOsc', data, null, clientId)
}
sendOsc(shortdata, clientId) {
// send osc (or midi) message and sync with other clients
// shortdata
// {
// h: 'widget_uuid',
// v: widget_value,
// ... // target, preArgs, address, typeTags
// // override cached data
// // required if data.h is not provided
// }
// if widget hash is provided, look for cached data
if (shortdata.h && !(this.widgetHashTable[clientId] && this.widgetHashTable[clientId][shortdata.h])) return
var value = shortdata.v,
data = shortdata.h ? this.widgetHashTable[clientId][shortdata.h] : {}
data = deepCopy(data)
for (var k in shortdata) {
data[k] = shortdata[k]
}
if (data.target) {
var targets = []
if (!shortdata.i && settings.read('send') && !shortdata.target) Array.prototype.push.apply(targets, settings.read('send'))
if (data.target) Array.prototype.push.apply(targets, data.target)
data.args = data.preArgs ? data.preArgs.concat(value) : [value]
for (var i in targets) {
if (targets[i] === 'self') {
this.ipcServer.send('receiveOsc',data,clientId)
continue
} else if (targets[i] === null) {
continue
}
var host = targets[i].split(':')[0],
port = targets[i].split(':')[1]
if (port) {
this.oscServer.send(host, port, data.address, data.args, data.typeTags, clientId)
}
}
}
if (!data.noSync) this.ipcServer.send('receiveOsc', data, null, clientId)
}
addWidget(data, clientId) {
// cache widget osc data to reduce bandwidth usage
// data
// {
// hash: 'widget_uuid',
// data: {
// target: ['host:port', ...],
// preArgs: [arg1, ...],
// address: '/address',
// typeTags: 'iif' // one letter per arg typetag
// }
// }
// preArgs, target and typeTags can be empty strings
if (!this.widgetHashTable[clientId][data.hash]) {
this.widgetHashTable[clientId][data.hash] = {}
}
var cache = this.widgetHashTable[clientId][data.hash],
widgetData = data.data
for (var k in widgetData) {
if ((k === 'target' || k === 'preArgs')) {
if (widgetData[k] !== '') {
cache[k] = Array.isArray(widgetData[k]) ? widgetData[k] : [widgetData[k]]
} else {
cache[k] = []
}
} else {
cache[k] = widgetData[k]
}
}
// store raw target for client sync widget matching
cache._rawTarget = widgetData.target
}
removeWidget(data, clientId) {
// clear widget osc data
delete this.widgetHashTable[clientId][data.hash]
}
reload(data) {
// (dev) hot reload
this.ipcServer.send('reload')
}
reloadCss() {
// (dev) hot css reload
this.ipcServer.send('reloadCss')
}
log(data) {
console.log(data)
}
error(data) {
console.error(data)
}
errorLog(data) {
console.error(data)
}
errorPopup(data) {
this.ipcServer.send('error', data)
}
listDir(data, clientId) {
// remote file browser backend
if (data.path) {
// path is requested
data.path[0] = resolveHomeDir(data.path[0])
} else if (settings.read('last-dir') && fs.existsSync(settings.read('last-dir'))) {
// attempt to use last visited directory
data.path = [settings.read('last-dir')]
} else {
// default directory fallback
data.path = [resolveHomeDir('~/')]
}
var p = path.resolve(...data.path),
root = resolveHomeDir(settings.read('remote-root'))
if (root && !path.normalize(p).includes(path.normalize(root))) p = root
if (process.platform === 'win32' && !root) {
// Drive list hack on windows
if (data.path.length === 2 && data.path[1] === '..' && (data.path[0].match(/^[A-Z]:\\$/) || data.path[0] === '\\')) {
child_process.exec('(get-wmiobject win32_volume | ? { $_.DriveType -eq 3 } | % { get-psdrive $_.DriveLetter[0] }).Root -join " "', {shell: 'powershell.exe'}, (error, stdout) => {
if (error) {
this.ipcServer.send('notify', {class: 'error', message: 'Failed to list available drives (see server console).'}, clientId)
console.error('(ERROR) Failed to list available drives.')
console.error(error.stack)
} else {
this.ipcServer.send('listDir', {
path: '\\',
files: stdout.split(' ')
.filter(value => /[A-Za-z]:/.test(value))
.map(value => {return {name: value.trim(), folder: true}})
}, clientId)
}
})
return
}
}
fs.readdir(p, (err, files)=>{
if (err) {
this.ipcServer.send('notify', {class: 'error', message: err.message}, clientId)
throw err
} else {
var extRe = data.extension ? new RegExp('.*\\.' + data.extension + '$') : /.*/
var list = files.filter(x=>x[0] !== '.').map((x)=>{
var folder = false
try {
folder = fs.statSync(path.resolve(p, x)).isDirectory()
} catch(e) {}
return {
name: x,
folder
}
})
list = list.filter(x=>x.folder || x.name.match(extRe))
this.ipcServer.send('listDir', {
path: p,
files: list
}, clientId)
settings.write('last-dir', p, false, false)
}
})
}
}

View file

@ -0,0 +1,126 @@
import {EventEmitter} from 'events'
var hearbeatInterval = 25000,
hearbeatTimeout = 5000,
dieTimeout = 60000
class Client extends EventEmitter {
constructor(ws, id, address) {
super()
this.id = id
this.address = address.replace('::ffff:', '')
this.socket = null
this.sessionPath = ''
this.queue = []
this.hearbeat = undefined
this.hearbeatTimeout = undefined
this.on('pong', ()=>{
this.hearbeatTimeout = clearTimeout(this.hearbeatTimeout)
})
this.on('ping', ()=>{
this.socket.send('["pong"]')
})
this.dieTimeout = undefined
this.open(ws)
}
open(ws) {
this.socket = ws
this.socket.onmessage = (e)=>{
this.receive(e.data)
}
this.socket.onclose = this.socket.onerror = ()=>{
if (!this.connected()) this.close()
}
this.dieTimeout = clearTimeout(this.dieTimeout)
this.hearbeat = setInterval(()=>{
if (!this.connected()) return
this.socket.send('["ping"]')
this.hearbeatTimeout = setTimeout(()=>{
if (this.connected()) this.socket.close()
}, hearbeatTimeout)
}, hearbeatInterval)
this.emit('created')
}
close() {
this.hearbeat = clearInterval(this.hearbeat)
this.hearbeatTimeout = clearTimeout(this.hearbeatTimeout)
this.dieTimeout = clearTimeout(this.dieTimeout)
this.dieTimeout = setTimeout(()=>{
this.emit('destroyed')
}, dieTimeout)
}
connected() {
return this.socket.readyState == this.socket.OPEN
}
receive(message) {
if (typeof message == 'string') {
var packet = JSON.parse(message)
if (Array.isArray(packet) && typeof packet[0] == 'string') {
this.emit(packet[0], packet[1])
}
}
}
send(event, data) {
var packet = JSON.stringify([event, data])
if (this.connected()) {
this.socket.send(packet)
} else {
this.queue.push(packet)
}
}
flush(){
for (var i in this.queue) {
if (this.connected()) this.socket.send(this.queue[i])
}
this.queue = []
}
}
export default Client

View file

@ -0,0 +1,82 @@
import {WebSocketServer} from 'ws'
import Client from './client'
import * as settings from '../settings'
import Callbacks from './callbacks'
class IpcServer {
constructor(webServer, oscServer) {
this.clients = {}
this.webServer = webServer
this.oscServer = oscServer
this.server = new WebSocketServer({server: webServer.server})
this.callbacks = new Callbacks(this, webServer, oscServer)
this.server.on('connection', (socket, req)=>{
var url = req.url.split('/'),
auth = url.pop().replace('_', '/'),
id = url.pop()
if (settings.read('authentication')) {
if (settings.read('authentication') !== Buffer.from(auth, 'base64').toString()) {
console.log(`(WARNING) Client connexion refused for ${req.connection.remoteAddress} (authentication failed)`)
socket.close()
return
}
}
if (!id) return
id = decodeURI(id)
if (!this.clients[id]) {
var client = new Client(socket, id, req.connection.remoteAddress)
this.clients[id] = client
var customModule = settings.read('custom-module')
for (let name of this.callbacks.getEvents()) {
client.on(name, (data)=>{
if (customModule) {
oscServer.customModuleEventEmitter.emit(name, data, {address: client.address, id: client.id})
}
this.callbacks[name](data, client.id)
})
}
client.on('destroyed', ()=>{
delete this.clients[id]
})
} else {
this.clients[id].open(socket)
this.clients[id].flush()
}
this.clients[id].emit('created')
})
}
send(event, data, id, except) {
var clients = id ? [this.clients[id]] : this.clients
for (var k in clients) {
if (!except || this.clients[k] != this.clients[except]) {
if (clients[k]) clients[k].send(event, data)
}
}
}
}
export default IpcServer

171
src/server/node/midi.js Normal file
View file

@ -0,0 +1,171 @@
import {PythonShell} from 'python-shell'
import fs from 'fs'
import path from 'path'
import * as settings from './settings'
// last o-s-c version that changed midi sources
// must match version in midi.py / bundled midi executable
var midiVersion = '1.23.0'
var pythonOptions = {
scriptPath:__dirname,
mode:'text',
}
var midiBinaries = {
x64: {
linux: 'osc-midi-linux',
darwin: 'osc-midi-osx',
win32: 'osc-midi-windows.exe'
},
arm64:{
darwin: 'osc-midi-osx',
}
}
var expectMidiBinaries = fs.existsSync(path.join(__dirname, '/osc-midi.json')),
expectMidiBinariesError = false
var pythonPathOverride
if (midiBinaries[process.arch] && midiBinaries[process.arch][process.platform]) {
var p = path.resolve(__dirname,midiBinaries[process.arch][process.platform])
if (fs.existsSync(p)) {
pythonPathOverride = p
} else if (expectMidiBinaries) {
expectMidiBinariesError = true
}
}
class MidiConverter {
constructor() {
if (expectMidiBinariesError) MidiConverter.midiBinariesError()
this.py = new PythonShell('python/midi.py', Object.assign({
args: [
'--params',
settings.read('debug') ? 'debug' : '',
...settings.read('midi')
],
pythonPath: MidiConverter.getPythonPath()
}, pythonOptions))
this.py.childProcess.on('error', (e)=>{
if (e.code === 'ENOENT') {
console.error(`(ERROR, MIDI) Could not find python binary: ${e.message.replace(/spawn (.*) ENOENT/, '$1')}`)
} else {
console.error(`(ERROR, MIDI) ${e.message}`)
}
})
this.running = true
this.py.childProcess.on('exit', (code)=>{
if (code === null) console.error('(ERROR, MIDI) Midi bridge process crashed')
this.running = false
})
}
send(data) {
if (!this.running) return
var args = []
for (let i in data.args) {
args.push(data.args[i].value)
}
this.py.send(JSON.stringify([data.port, data.address, ...args]))
}
stop() {
this.py.childProcess.kill()
}
init(receiveOsc) {
this.receiveOsc = receiveOsc
this.py.on('message', (message)=>{
MidiConverter.parseIpc(message, this)
})
}
static parseIpc(message, instance) {
// console.log(message)
var name, data
try {
[name, data] = JSON.parse(message)
} catch (err) {
if (settings.read('debug')) console.error(`(ERROR, MIDI) Unparsed python log:\n ${message}`)
}
if (name == 'log') {
if (data.indexOf('ERROR') > -1) {
console.error(data)
} else {
console.log(data)
}
} else if (name == 'debug') {
if (data.indexOf('in:') === 0) {
console.log('\x1b[36m(DEBUG, MIDI)', data, '\x1b[0m')
} else if (data.indexOf('out:') === 0) {
console.log('\x1b[35m(DEBUG, MIDI)', data, '\x1b[0m')
} else {
console.log('(DEBUG, MIDI) ' + data)
}
} else if (name == 'osc') {
instance.receiveOsc(data)
} else if (name == 'error') {
console.error('(ERROR, MIDI) ' + data)
} else if (name == 'version' && data != midiVersion) {
console.error(`(WARNING, MIDI) binary version mismatch (${data} installed, ${midiVersion} expected)`)
}
}
static list() {
if (expectMidiBinariesError) MidiConverter.midiBinariesError()
PythonShell.run('python/midi.py', Object.assign({pythonPath: MidiConverter.getPythonPath(), args: ['--params', 'list-only']}, pythonOptions), function(e, results) {
if (e) {
if (e.code === 'ENOENT') {
console.error(`(ERROR, MIDI) Could not find python binary: ${e.message.replace(/spawn (.*) ENOENT/, '$1')}`)
} else {
console.error(`(ERROR, MIDI) ${e.message}`)
}
}
for (let r of results) {
MidiConverter.parseIpc(r)
}
})
}
static getPythonPath() {
var pythonPath = settings.read('midi') ? settings.read('midi').filter(x=>x.includes('path=')).map(x=>x.split('=')[1])[0] : undefined
if (!pythonPath && pythonPathOverride) pythonPath = pythonPathOverride
return pythonPath
}
static midiBinariesError() {
console.error(`(ERROR, MIDI) Could not find midi binary file ${p}\nIt may have been deleted by your antivirus.`)
console.log('(INFO, MIDI) Falling back to python implementation (see https://openstagecontrol.ammd.net/docs/midi/midi-configuration/).')
expectMidiBinariesError = false
}
}
export default MidiConverter

110
src/server/node/options.js Normal file
View file

@ -0,0 +1,110 @@
import fs from 'fs'
export default {
's': {alias: 'send', type: 'array', describe: 'default targets for all widgets (ip: port / domain: port / midi: port_name pairs)',
check: (s)=>{
return s.some(item=>!item.match(/^[^:]*:[0-9]{4,5}$/) && !item.match(/^midi:.*$/)) ?
'Targets must be ip:port or hostname:port pairs (port must be >= 1024) or midi:port_name pairs' : true
}
},
'l': {alias: 'load', type: 'string', file: {name: 'OSC Session (.json)', extensions: ['json']}, describe: 'session file to load (.json)',
check: (arg)=>{
return fs.existsSync(arg) ? true : 'Session file not found: ' + arg
}
},
'state': {type: 'string', file: {name: 'OSC State (.state)', extensions: ['state']}, describe: 'state file to load (.state)',
check: (arg)=>{
return fs.existsSync(arg) ? true : 'State file not found: ' + arg
}
},
'c': {alias: 'custom-module', type: 'string', file: {name: 'OSC Custom module (.js)', extensions: ['js']}, describe: 'custom module file to load (.js)\n WARNING: custom module can access the file system, use at your own risk.',
check: (arg)=>{
return fs.existsSync(arg) ? true : 'Custom module file not found: ' + arg
},
},
'p': {alias: 'port', type: 'number', describe: 'http port of the server (default to 8080)',
check: (p)=>{
return (!isNaN(p) && p > 1023 && parseInt(p)===p) ?
true : 'Port must be an integer >= 1024'
}
},
'o': {alias: 'osc-port', type: 'number', describe: 'osc input port (default to --port)',
check: (o)=>{
return (!isNaN(o) && o > 1023 && parseInt(o)===o) ?
true : 'Port must be an integer >= 1024'
}
},
'tcp-port': {type: 'number', describe: 'tcp server input port',
check: (t, argv)=>{
var h = argv['port']
if (t === h) return 'Tcp input port must different from --port'
return (!isNaN(t) && t > 1023 && parseInt(t)===t) ?
true : 'Port must be an integer >= 1024'
}
},
'tcp-targets': {type: 'array', describe: 'tcp servers to connect to (ip: port pairs), does not substitute for --send',
check: (s, argv)=>{
if (!argv['tcp-port']) return '--tcp-port must be set'
return s.some(item=>!item.match(/^[^:]*:[0-9]{4,5}$/)) ?
'Targets must be ip:port or hostname:port pairs (port must be >= 1024)' : true
}
},
'm': {alias: 'midi', type: 'array', describe: 'midi router settings',
check: (o)=>{
var err = o.filter(item=>!item.match(/^(list|debug|jack|sysex|mtc|rpn|nrpn|active_sensing|note_off_velocity|pc_offset|path=(.*)|[^:]+:(virtual|[^,]+,[^,]+))$/))
return err.length ? `Invalid option${err.length > 1 ? 's' : ''}: ${err.join(', ')}` : true
}
},
'd': {alias: 'debug', type: 'boolean', describe: 'log received osc messages in the console'},
'n': {alias: 'no-gui', type: 'boolean', describe: 'disable default gui'},
'fullscreen': {type: 'boolean', describe: 'launch in fullscreen mode (only affects the default client gui)'},
't': {alias: 'theme', type: 'array', file: {name: 'css file (.css)', extensions: ['css']}, describe: 'theme name or path (multiple values allowed)'},
'client-options': {type: 'array', describe: 'client options (opt=value pairs)',
check: (o)=>{
return o.some(item=>!item.match(/^[^=]*=[^=]*$/)) ?
'Options must be key=value pairs' : true
}
},
'disable-vsync': {type: 'boolean', describe: 'disable gui\'s vertical synchronization', restart: true},
'force-gpu': {type: 'boolean', describe: 'ignore chrome\'s gpu blacklist', restart: true},
'read-only': {type: 'boolean', describe: 'disable session editing and session history changes'},
'remote-saving': {type: 'string', describe: 'disable remote session saving for hosts that don\'t match the regular expression',
check: (r, argv)=>{
var msg = true
try {
RegExp(r)
} catch (e) {
msg = e
}
return msg
}
},
'remote-root': {type: 'string', describe: 'set remote file browsing root folder', file: {folder: true}},
'authentication': {type: 'string', describe: 'restrict access to "user:password" (remote clients will be prompted for these credentials)',
check: (a, argv)=>{
return a.match(/[^:]*:[^:]+/) ? true : 'Auth must be a user:password pair.'
}
},
'instance-name': {type: 'string', describe: 'used to differentiate multiple instances in a zeroconf network'},
'use-ssl': {type: 'boolean', describe: 'set to true to use HTTPS protocol instead of HTTP (a self-signed certificate will be created)'},
// cli only
'disable-gpu': {type: 'boolean', describe: 'disable hardware acceleration', launcher: false},
'inspect': {type: 'boolean', describe: 'enable node/electron inspector', launcher: false},
'cache-dir': {type: 'string', describe: 'override default cache directory', launcher: false},
'config-file': {type: 'string', describe: 'override default config file (defaults to cache-dir/config.json)', launcher: false},
'docs': {type: 'boolean', describe: 'serve documentation website locally and open it with the system\'s default browser', launcher: false},
'client-position': {type: 'string', describe: 'position of the client window ("x,y" pair of integers)', launcher: false,
check: (s)=>{
return !s.match(/^[0-9]+,[0-9]+$/) ?
'Position must a x,y pair of integers' : true
}
},
'client-size': {type: 'string', describe: 'size of the client window ("width,height" pair of integers)', launcher: false,
check: (s)=>{
return !s.match(/^[0-9]+,[0-9]+$/) ?
'Size must a x,y pair of integers' : true
}
},
'no-qrcode': {type: 'boolean', describe: 'disable qrcode when the server starts', launcher: false}
}

View file

@ -0,0 +1,272 @@
import * as settings from '../settings'
import OscUDPServer from './udp'
import OscTCPServer from './tcp'
import {EventEmitter} from 'events'
import CustomModule from '../custom-module'
import MidiServer from '../midi'
export default class OscServer {
constructor(){
this.oscUDPServer = new OscUDPServer()
this.oscTCPServer = new OscTCPServer()
this.tcpInPort = settings.read('tcp-port')
this.midiServer = settings.read('midi') ? new MidiServer() : null
this.debug = settings.read('debug')
this.customModuleEventEmitter = new EventEmitter()
this.customModule = settings.read('custom-module') ? new CustomModule(settings.read('custom-module'), {
app: this.customModuleEventEmitter,
tcpServer: this.oscTCPServer,
sendOsc: this.sendOsc.bind(this),
receiveOsc: this.receiveOsc.bind(this),
send: (host, port, address, ...args)=>{
if (host.indexOf(':') > -1) {
args.unshift(address)
address = port
var split = host.split(':')
host = split[0]
port = parseInt(split[1])
}
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
} else if (host.indexOf(':') > -1) {
args.unshift(address)
address = port
var split = host.split(':')
host = split[0]
port = parseInt(split[1])
}
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)), cm: 1}, options.clientId)
},
}) : {}
}
parseArg(arg, type){
if (arg === null) return null
if (typeof arg === 'object' && arg.type && arg.type.length === 1) return arg
if (type && type[0].match(/[bhtdscrmifTFNI]/)) {
type = type[0]
switch (type) {
case 'i':
return {type: type, value: parseInt(arg)}
case 'd':
case 'f':
return {type: type, value: parseFloat(arg)}
case 'T':
case 'F':
case 'N':
return {type: type}
default:
return {type: type, value: arg}
}
}
switch (typeof arg) {
case 'number':
return {type: 'f', value: arg}
case 'boolean':
return {type: arg ? 'T' : 'F', value: arg}
case 'string':
return {type: 's', value: arg}
default:
return {type: 's', value: JSON.stringify(arg)}
}
}
sendOsc(data){
if (!data) return
if (data.host == 'midi') {
if (this.midiServer) this.midiServer.send(data)
} else {
if (typeof data.address !== 'string' || data.address[0] !== '/') {
console.error('(ERROR, OSC) Malformed address: ' + data.address)
return
}
if (isNaN(parseInt(data.port))) {
console.error('(ERROR, OSC) Invalid port: ' + data.port)
return
}
if (this.tcpInPort && this.oscTCPServer.clients[data.host] && this.oscTCPServer.clients[data.host][data.port]) {
this.oscTCPServer.clients[data.host][data.port].send({
address: data.address,
args: data.args
})
} else {
this.oscUDPServer.send({
address: data.address,
args: data.args
}, data.host, data.port)
}
if (this.debug) {
console.log('\x1b[35m(DEBUG, OSC) Out: ', `{ address: '${data.address}', args: `, data.args, '} To: ' + data.host + ':' + data.port, '\x1b[0m')
}
}
}
receiveOsc(data, clientId){
if (!data) return
for (var i in data.args) {
data.args[i] = data.args[i].value
}
if (data.args.length==1) data.args = data.args[0]
this.ipcServer.send('receiveOsc', data, clientId)
if (this.debug) console.log('\x1b[36m(DEBUG, OSC) In: ', {address:data.address, args: data.args}, 'From: ' + data.host + ':' + data.port, '\x1b[0m')
}
oscInFilter(data){
if (this.customModule.oscInFilter) {
try {
return this.customModule.oscInFilter(data)
} catch(e) {
console.error('(ERROR, CUSTOM MODULE)', e)
return data
}
} else {
return data
}
}
oscOutFilter(data){
if (this.customModule.oscOutFilter) {
try {
return this.customModule.oscOutFilter(data)
} catch(e) {
console.error('(ERROR, CUSTOM MODULE)', e)
return data
}
} else {
return data
}
}
oscInHandler(msg, timetag, info){
var data = this.oscInFilter({address: msg.address, args: msg.args, host: info.address, port: info.port})
if (!data) return
this.receiveOsc(data)
}
oscInHandlerWrapper(msg, timetag, info) {
var delay = timetag? Math.max(0,timetag.native - Date.now()) : 0
if (delay) {
setTimeout(()=>{
this.oscInHandler(msg, timetag, info)
}, delay)
} else {
this.oscInHandler(msg, timetag, info)
}
}
start(ipcServer){
this.ipcServer = ipcServer
if (this.midiServer) midi.init((data)=>{
data = this.oscInFilter({address: data.address, args: data.args, host: data.host, port: data.port})
if (!data) return
this.receiveOsc(data)
})
this.oscUDPServer.on('message', this.oscInHandlerWrapper.bind(this))
this.oscUDPServer.start()
if (settings.read('tcp-port')) {
this.oscTCPServer.on('message', this.oscInHandlerWrapper.bind(this))
this.oscTCPServer.start()
}
if (this.customModule.init) {
try {
this.customModule.init()
} catch(e) {
console.error('(ERROR, CUSTOM MODULE)', e)
}
}
}
stop() {
if (this.customModule.stop) this.customModule.stop()
if (this.midiServer) this.midiServer.stop()
}
send(host, port, address, args, typeTags, clientId) {
// public send function
var message = []
if (!Array.isArray(args)) args = [args]
if (typeof args === 'object' && args !== null) {
var typeTag,
arg
for (var i = 0; i < args.length; i++) {
if (typeTags && typeTags[i]) typeTag = typeTags[i]
arg = this.parseArg(args[i], typeTag)
if (arg !== null) message.push(arg)
}
}
var data = this.oscOutFilter({address:address, args: message, host: host, port: port, clientId: clientId})
this.sendOsc(data)
}
}

View file

@ -0,0 +1,7 @@
import osc from 'osc/src/osc.js'
import transports from 'osc/src/platforms/osc-node.js'
osc.UDPPort = transports.UDPPort
osc.TCPSocketPort = transports.TCPSocketPort
export default osc

151
src/server/node/osc/tcp.js Normal file
View file

@ -0,0 +1,151 @@
import osc from './osc'
import {EventEmitter} from 'events'
import * as settings from '../settings'
import zeroconf from '../zeroconf'
import net from 'net'
class OscTCPClient extends EventEmitter {
constructor(options) {
super()
this.options = options
this.remoteAddress = options.address
this.remotePort = options.port
this.open()
}
open() {
this.port = new osc.TCPSocketPort(this.options)
this.port.on('error', (err)=>{
console.error('(ERROR, TCP)', err)
})
this.port.on('close', (hadErr)=>{
console.log(`(TCP) Connection closed (${this.remoteAddress}:${this.remotePort})`)
if (!this.options.socket) {
console.log(`(TCP) Attempting reconnection in 5s (${this.remoteAddress}:${this.remotePort})`)
this.reconnect()
} else {
this.emit('die')
}
})
this.port.on('message', (msg, timetag)=>{
this.emit('message', msg, timetag, {address: this.remoteAddress, port: this.remotePort})
})
this.port.on('ready', ()=>{
console.log(`(TCP) Connection established (${this.remoteAddress}:${this.remotePort})`)
})
if (!this.options.socket) {
this.port.open()
} else {
this.port.emit('ready')
}
}
reconnect() {
setTimeout(()=>{
this.open()
}, 5000)
}
send(msg) {
this.port.send(msg)
}
}
export default class OscTCPServer extends EventEmitter {
constructor() {
super()
this.port = settings.read('tcp-port')
this.targets = settings.read('tcp-targets')
this.clients = {}
this.server = net.createServer(this.bindSocket.bind(this))
this.on = this.server.on.bind(this.server)
}
bindSocket(socket) {
this.addClient(new OscTCPClient({
metadata: true,
socket: socket,
address: socket.remoteAddress.replace('::ffff:', ''),
port: socket.remotePort
}))
}
addClient(client) {
this.clients[client.remoteAddress] = this.clients[client.remoteAddress] || {}
this.clients[client.remoteAddress][client.remotePort] = client
client.on('message', (msg, timetag, info)=>{
this.emit('message', msg, timetag, info)
})
client.on('die', (hadError)=>{
if (this.clients[client.remoteAddress]) delete this.clients[client.remoteAddress][client.remotePort]
})
}
start() {
this.server.listen({port: this.port})
for (var i in this.targets) {
this.addClient(new OscTCPClient({
metadata: true,
address: this.targets[i].split(':')[0],
port: this.targets[i].split(':')[1]
}))
}
zeroconf.publish({
name: settings.infos.productName + (settings.read('instance-name') ? ' (' + settings.read('instance-name') + ')' : ''),
protocol: 'tcp',
type: 'osc',
port: this.port
}).on('error', (e)=>{
console.error(`Error: Zeroconf: ${e.message}`)
})
}
stop() {
this.server.close()
}
}

View file

@ -0,0 +1,48 @@
import osc from './osc'
import * as settings from '../settings'
import zeroconf from '../zeroconf'
export default class OscUDPServer {
constructor() {
this.port = settings.read('osc-port') || settings.read('port') || 8080
this.server = new osc.UDPPort({
localAddress: '0.0.0.0',
localPort: this.port,
metadata: true,
broadcast: true
})
this.server.on('error', function(e) {
if (e.code === 'EADDRINUSE') {
console.error(`(ERROR, UDP) could not open port ${oscInPort} (already in use) `)
} else {
console.error('(ERROR, UDP)', e)
}
})
this.on = this.server.on.bind(this.server)
this.send = this.server.send.bind(this.server)
}
start() {
this.server.open()
zeroconf.publish({
name: settings.infos.productName + (settings.read('instance-name') ? ' (' + settings.read('instance-name') + ')' : ''),
protocol: 'udp',
type: 'osc',
port: this.port
})
}
stop() {
this.server.close()
}
}

39
src/server/node/qrcode.js Normal file
View file

@ -0,0 +1,39 @@
import QRCode from 'qrcode'
import * as settings from './settings'
export default function qrcode(mode, callback){
var qrstring = '',
promises = []
if (mode == 'file') {
promises.push(QRCode.toString(settings.appAddresses().pop(), {type:'svg', small: true, margin: 1}))
} else {
for (var add of settings.appAddresses().filter(a=>!a.includes('127.0.0.1') && !a.includes('localhost'))) {
if (mode == 'svg') {
promises.push(QRCode.toString(add,{type:'svg', small: true, margin: 1}))
} else if (mode == 'terminal') {
promises.push(QRCode.toString(add,{type:'terminal', small: true}))
}
}
}
Promise.all(promises).then(values=>{
for (var qr of values) {
if (mode === 'svg') {
qrstring += '<div class="qrcode" title="' + add + '">' + qr + '</div>'
if (values.length > 1) {
qrstring += '(' + add + ')'
}
} else {
qrstring += '\n' + qr.replace(/^/gm, ' ' + '')
if (values.length > 1) {
qrstring += ' (' + add + ')'
}
}
}
callback(qrstring)
})
}

261
src/server/node/server.js Normal file
View file

@ -0,0 +1,261 @@
import http from 'http'
import https from 'https'
import './ssl'
import {EventEmitter} from 'events'
import path from 'path'
import fs from 'fs'
import send from 'send'
import replaceStream from 'replacestream'
import * as settings from './settings'
import auth from './auth'
import theme from './theme'
import zeroconf from './zeroconf'
import qrcode from './qrcode'
import {resolveHomeDir} from './utils'
class WebServer extends EventEmitter {
constructor() {
super()
this.ipcServer = null
this.qrcode = ''
this.prod = !process.argv[0].includes('node_modules'),
this.debug = settings.read('debug'),
this.remoteRoot = settings.read('remote-root')
var route = auth ? auth.check(this.httpRoute.bind(this)) : this.httpRoute.bind(this)
if (settings.read('use-ssl')) {
this.server = https.createServer(settings.read('ssl-certificate'), route)
} else {
this.server = http.createServer(route)
}
// file request resolution directories
// add theme dirs
this.resolveDirs = theme.files.map(x=>path.dirname(x)),
// dedupe
this.resolveDirs = this.resolveDirs.filter((x, index)=>{return this.resolveDirs.indexOf(x) === index})
// add remote root or absolute
this.resolveDirs.push(this.remoteRoot || '')
}
start(ipcServer) {
this.ipcServer = ipcServer
this.server.listen(settings.read('port') || 8080)
var proto = settings.read('use-ssl') ? https : http
proto.get(settings.appAddresses()[0] + '/osc-ping', {
auth: settings.read('authentication'),
rejectUnauthorized: false
},()=>{}).on('error', ()=>{this.httpCheck(false)})
this.httpCheckTimeout = setTimeout(()=>{this.httpCheck(false)}, 5000)
zeroconf.publish({
name: settings.infos.productName + (settings.read('instanceName') ? ' (' + settings.read('instanceName') + ')' : ''),
type: 'http',
port: settings.read('port') || 8080
}).on('error', (e)=>{
console.error(`(ERROR, ZEROCONF) ${e.message}`)
})
this.server.on('error', (e)=>{
if (e.code === 'EADDRINUSE') {
console.error(`(ERROR, HTTP) Could not open port ${oscInPort} (already in use) `)
} else {
console.error(`(ERROR, HTTP) ${e.message}`)
}
})
}
stop() {
this.server.close()
}
resolvePath(url, clientId) {
var sessionPath
if (this.ipcServer.clients[clientId]) {
sessionPath = path.dirname(this.ipcServer.clients[clientId].sessionPath)
}
url = resolveHomeDir(url)
url = url.split('?')[0]
for (var i = sessionPath ? -1 : 0; i < this.resolveDirs.length; i++) {
var p = i === -1 ? sessionPath : this.resolveDirs[i]
if (i == this.resolveDirs.length - 1 && this.remoteRoot) {
// strip out remote-root path from request url when resolving against it
url = url.replace(settings.read('remote-root'), '')
}
p = path.resolve(path.join(p, url))
if (fs.existsSync(p)) return p
}
if (this.debug && !this.ipcServer.clients[clientId]) {
// safari seems to be picky with cookies
if (clientId === undefined) console.log(`(DEBUG, HTTP) Could not resolve requested url ${url} (client id not found in http cookies)`)
// this should never happen, but just in case...
// it happens when importing css file from theme
else console.log(`(DEBUG, HTTP) Requested url ${url} not resolved against session path (unregistered client id ${clientId})`)
}
return false
}
httpRoute(req, res) {
res.sendFile = (path)=>{
var fpath = path.split('?')[0]
if (!fs.existsSync(fpath)) throw `File "${fpath}" not found.`
return send(req, fpath).pipe(res)
}
var url = req.url
if (url === '/qrcode'){
res.setHeader('Content-Type', 'image/svg+xml')
let str = this.qrcode,
buf = Buffer.from && Buffer.from !== Uint8Array.from ? Buffer.from(str) : new Buffer(str)
res.write(buf)
res.end()
} else if (url === '/' || url.indexOf('/?') === 0) {
var ip = req.connection.remoteAddress.replace('::ffff:', '')
var clientOptions = {}
if (settings.read('client-options')) {
for (var o of settings.read('client-options')) {
if (!o.includes('=')) continue
var [k, v] = o.split('=')
clientOptions[k] = v
}
}
fs.createReadStream(path.resolve(__dirname + '/../../client/index.html'))
.pipe(replaceStream('</body>', `
<script>
window.IP=${JSON.stringify(ip)}
window.ENV=${JSON.stringify(clientOptions)}
window.READ_ONLY=${JSON.stringify(settings.read('read-only'))}
window.KIOSK=${settings.read('read-only') && settings.read('fullscreen') ? 'true' : 'false'}
window.AUTH=\`${(req.headers.authorization || '').replace('Basic ', '').replace('/', '_')}\`
</script></body>`))
.pipe(res)
} else {
if (
url.indexOf('__OSC_ASSET__=1') != -1 ||
url.indexOf('open-stage-control-client.js.map') != -1 ||
url.indexOf('/client/ace/') != -1
) {
// osc asset files
if (url.indexOf('theme.css') != -1) {
res.setHeader('Content-Type', 'text/css')
if (settings.read('theme')) {
let str = theme.get(),
buf = Buffer.from && Buffer.from !== Uint8Array.from ? Buffer.from(str) : new Buffer(str)
res.write(buf)
} else {
res.write('')
}
res.end()
} else {
if (this.prod) res.setHeader('Cache-Control', 'public, max-age=2592000')
try {
res.sendFile(path.resolve(__dirname + '/../../' + url))
return true
} catch(e) {}
console.error(`(ERROR, HTTP) File not found: ${url}`)
res.writeHead(404)
res.end()
}
} else {
// user files
// windows absolute path fix
url = url.replace('_:_', ':') // escaped drive colon
url = url.replace(/^\/([^/]*:)/, '$1') // strip leading slash
if (url.match(/.(svg|jpg|jpeg|png|apng|gif|webp|tiff|xbm|bmp|ico|ttf|otf|woff|woff2|html|css|js)(\?[0-9]*)?$/i)) {
// Resolution order: session path, theme path, absolute path
var id
if (req.headers.cookie) {
id = (req.headers.cookie.match(/client_id=([^;]+)/) || [])[1]
}
resolvedPath = this.resolvePath(decodeURI(url), id)
if (resolvedPath) {
try {
res.sendFile(resolvedPath)
return true
} catch(e) {}
}
console.error(`(ERROR, HTTP) File not found: ${url}`)
res.writeHead(404)
res.end()
} else if (url.includes('/osc-ping')) {
this.httpCheck(true)
} else {
res.writeHead(403)
res.end()
}
}
}
}
httpCheck(ok, error) {
if (!this.httpCheckTimeout) return
clearTimeout(this.httpCheckTimeout)
this.httpCheckTimeout = null
if (ok) {
console.log('(INFO) Server started, app available at \n ' + settings.appAddresses().join('\n '))
this.emit('serverStarted')
qrcode('file', (qr)=>{
this.qrcode = qr
})
} else {
if (error) {
console.error('(ERROR, HTTP) Server setup error: ' + error.message)
}
console.error('(ERROR, HTTP) Could not setup http server, maybe try a different port ?')
}
}
}
export default WebServer

220
src/server/node/settings.js Normal file
View file

@ -0,0 +1,220 @@
import path from 'path'
import fs from 'fs'
import yargs from 'yargs'
import infos from '../../../package.json'
import options from './options'
import address from './address'
import envPaths from 'env-paths'
var argv = process.argv.slice()
// Note : on windows, electron stops parsing after the first argument containing a colon
// https://github.com/electron/electron/pull/13039
// windows cli users need to add a double dash (--) before their options to avoid that
// it must be stripped to let yargs work normally
// rmeove all args before the first actual cli arg
while (argv.length) {
if (argv[0][0] != '-' || argv[0] == '--') {
argv.splice(0, 1)
} else if (argv[0][0] == '-' ) {
break
}
}
argv = yargs(argv)
.parserConfiguration({'boolean-negation': false})
.help('help').usage('\nUsage:\n $0 [options]').alias('h', 'help')
.options(options)
.check((argv)=>{
var err = []
for (key in options) {
if (options[key].check && argv[key] != undefined) {
var c = options[key].check(argv[key],argv)
if (c!==true) {
err.push(`-${key}: ${c}`)
}
}
}
return err.length ? err.join('\n') : true
})
.strict()
.version(infos.version).alias('v','version')
argv = argv.argv
delete argv._
delete argv.$0
// clean argv
var optNames = [],
cliOnly = []
for (let k in options) {
var name = options[k].alias || k
optNames.push(name)
if (options[k].launcher === false) {
cliOnly.push(name)
}
}
for (var i in argv) {
if (argv[i] === false || !optNames.includes(i)) {
delete argv[i]
}
}
delete argv._
delete argv.$0
// are we in a terminal ?
var cli = false
for (let i in argv) {
if (!cliOnly.includes(i)) cli = true
}
if (!process.versions.electron || process.env.ELECTRON_RUN_AS_NODE) {
cli = true
}
var settings = {
options: argv,
recentSessions: [],
checkForUpdates: true
}
// store cli-only options (read-only)
for (let k in argv) {
if (options[k] && options[k].launcher === false) {
settings[k] = argv[k]
}
}
///////////////// config paths
var baseDir, configPath, configPathExists = true, config = {}
if (argv['cache-dir']) {
baseDir = path.isAbsolute(argv['cache-dir']) ? argv['cache-dir'] : path.resolve(process.cwd(), argv['cache-dir'])
} else {
baseDir = envPaths(infos.name, {
suffix: ''
}).config
}
if (!fs.existsSync(baseDir)) {
try {
fs.mkdirSync(baseDir)
} catch(e) {
configPathExists = false
console.error('(ERROR) Could not create config folder:' + baseDir)
console.error(e)
}
}
if (configPathExists) {
if (argv['config-file']) {
configPath = path.isAbsolute(argv['config-file']) ? argv['config-file'] : path.resolve(process.cwd(), argv['config-file'])
} else {
configPath = path.join(baseDir, 'config.json')
}
if (fs.existsSync(configPath)) {
try {
config = JSON.parse(fs.readFileSync(configPath,'utf-8'))
} catch(e) {
console.error('(ERROR) Could not read config from file:' + configPath)
console.error(e)
}
} else {
try {
fs.writeFileSync(configPath, '{}')
} catch(e) {
console.error('(ERROR) Could not create config file:' + configPath)
console.error(e)
}
}
if (cli) {
for (let k in config) {
if (k === 'options') continue
settings[k] = config[k]
}
} else {
for (let k in config) {
if (k === 'options') {
Object.assign(config.options, settings.options)
}
settings[k] = config[k]
}
}
}
if (!configPath) {
console.warn('(WARNING) Config directory not found, settings and session history will not be saved.')
}
/////////////////
export {
options,
cli,
infos,
baseDir as configPath
}
export function read(key){
return settings.options[key] !== undefined ? settings.options[key] : settings[key]
}
export function write(key, value, tmp, sync) {
settings[key] = value
if (!tmp && configPathExists) {
if (process.send) {
// server running as child process of launcher
// -> just pass the modification to the launcher process
process.send(['settings.write', [key, value]])
} else {
config[key] = value
if (config.options) {
// don't save cli-only options
for (var k in config.options) {
if (options[k] && options[k].launcher === false) {
delete config.options[k]
}
}
}
if (sync) {
fs.writeFileSync(configPath, JSON.stringify(config, null, 4))
} else {
fs.writeFile(configPath, JSON.stringify(config, null, 4), function(err, data) {
if (err) throw err
})
}
}
}
// we are in launcher process -> update server process' config
if (global.serverProcess) {
global.serverProcess.send(['settings.write', [key, value]])
}
}
export function appAddresses() {
return address(read('use-ssl') ? 'https://' : 'http://', settings.options.port || 8080)
}
if (process.send) {
// server running as child process of launcher
// update local config when the main config is modified
process.on('message', function(data) {
var [command, args] = data
if (command === 'settings.write') {
write(args[0], args[1], true)
}
})
}

74
src/server/node/ssl.js Normal file
View file

@ -0,0 +1,74 @@
import * as settings from './settings'
import forge from 'node-forge'
var pki = forge.pki,
certificate = settings.read('ssl-certificate')
forge.options.usePureJavaScript = true
// Generate a random Serial number for the certificate
// matth-c3 @ https://github.com/digitalbazaar/forge/issues/673#issuecomment-500900852
function randomSerialNumber() {
var hexString = forge.util.bytesToHex(forge.random.getBytesSync(16))
var mostSiginficativeHexAsInt = parseInt(hexString[0], 16)
if (mostSiginficativeHexAsInt < 8) {
return hexString
}
mostSiginficativeHexAsInt -= 8
return mostSiginficativeHexAsInt.toString() + hexString.substring(1)
}
function createCertificate() {
console.log('(INFO) Creating self signed ssl certificate...')
var keys = pki.rsa.generateKeyPair(2048),
cert = pki.createCertificate()
cert.publicKey = keys.publicKey
cert.validity.notBefore = new Date()
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1)
cert.serialNumber = randomSerialNumber()
var attrs = [
{name:'commonName',value: settings.infos.name},
{name:'subjectAltName',value: settings.infos.productName}
]
cert.setSubject(attrs)
cert.setIssuer(attrs)
cert.sign(keys.privateKey)
settings.write('ssl-certificate', {
key: pki.privateKeyToPem(keys.privateKey),
cert: pki.certificateToPem(cert)
})
}
if (settings.read('use-ssl')){
if (!certificate) {
createCertificate()
} else {
var cert = pki.certificateFromPem(certificate.cert)
if (
cert.serialNumber === '00' ||
new Date() > new Date(cert.validity.notAfter) ||
cert.subject.attributes[1].value !== settings.infos.productName
) {
console.log('(INFO) Self-signed ssl certificate in cache has expired or is invalid')
createCertificate()
} else {
console.log('(INFO) Using self-signed ssl certificate in cache')
}
}
}

81
src/server/node/theme.js Normal file
View file

@ -0,0 +1,81 @@
import fs from 'fs'
import path from 'path'
import * as settings from './settings'
import chokidar from 'chokidar'
import {EventEmitter} from 'events'
class Theme extends EventEmitter {
constructor() {
super()
this.defaultColor = '#151a24'
this.backgroundColor = this.defaultColor
this.css = []
this.watcher = null
this.themes = settings.read('theme') || []
this.files = []
if (!this.themes.length) return this
if (this.themes.length > 1 && fs.existsSync(this.themes.join(' '))) {
this.files.push(this.themes.join(' '))
} else {
for (let theme of this.themes) {
if (theme.includes('.css') && fs.existsSync(theme)) {
this.files.push(theme)
} else if (!theme.includes('.css') && fs.existsSync(path.resolve(__dirname + '/../assets/themes/' + theme + '.css'))) {
this.files.push(path.resolve(__dirname + '/../assets/themes/' + theme + '.css'))
} else {
console.error('(ERROR) Theme not found: "' + theme)
}
}
}
if (this.files.length) {
this.watcher = chokidar.watch(this.files, {awaitWriteFinish: {stabilityThreshold: 200}}).on('change', ()=>{
this.load()
this.emit('update')
})
}
this.load()
}
load() {
this.css = []
for (let i in this.files) {
try {
this.css.push(fs.readFileSync(this.files[i],'utf-8'))
} catch(err) {
console.error('(ERROR) Could not load theme "' + this.files[i])
}
}
}
get() {
return this.css.join('\n')
}
}
var theme = new Theme()
export default theme

24
src/server/node/utils.js Normal file
View file

@ -0,0 +1,24 @@
export function deepCopy(obj) {
var copy = obj
if (obj === null) {
return obj
}
if (typeof obj === 'object') {
copy = Array.isArray(obj) ? [] : {}
for (let key in obj) {
copy[key] = deepCopy(obj[key])
}
}
return copy
}
export function resolveHomeDir(p) {
// Resolve '~' to user's home directory
if (!p) return ''
return String(p).replace(/^(~|\/~)/, process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'])
}

View file

@ -0,0 +1,3 @@
import zeroconf from 'bonjour'
export default zeroconf()