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

@ -9,12 +9,15 @@ var commonjs = require('@rollup/plugin-commonjs'),
path = require('path')
module.exports = {
input: 'src/server/index.js',
input: {
'node/index': 'src/server/node/index.js',
'electron/index': 'src/server/electron/index.js'
},
output: [
{
file: 'app/server/open-stage-control-server.js',
inlineDynamicImports: true,
dir: 'app/server/',
format: 'commonjs',
sourcemap: true,
strict: false,
name: '_',
},
@ -40,9 +43,18 @@ module.exports = {
},
}
}),
terser({
sourceMap: true,
keep_classnames: true,
keep_fnames: true,
output: {
comments: false,
},
}),
copy({
targets: [
{src: 'src/app/index.js', dest: 'app/'},
{src: 'src/server/index.js', dest: 'app/server/'},
{src: 'src/python/*', dest: 'app/server/python/'},
{src: 'node_modules/fsevents/fsevents.node', dest: 'app/server/'},
{src: 'LICENSE', dest: 'app/'},

View file

@ -1 +1 @@
require('./server/open-stage-control-server')
require('./server/')

View file

@ -1,6 +1,6 @@
var {app, Menu, shell, BrowserWindow} = require('electron'),
settings = require('./settings'),
infos = require('../package.json')
import {app, Menu, shell, BrowserWindow} from 'electron'
import * as settings from '../node/settings'
import infos from '../../../package.json'
app.setPath('userData', settings.configPath)
@ -127,4 +127,4 @@ app.on('window-all-closed', function() {
}
})
module.exports = app
export default app

View file

@ -1,18 +1,17 @@
var path = require('path'),
{BrowserWindow, dialog, shell, screen, Menu, MenuItem} = require('electron'),
shortcut = require('electron-localshortcut'),
app = require('./electron-app'),
settings = require('./settings'),
theme = require('./theme')
import path from 'path'
import {BrowserWindow, dialog, shell, screen, Menu, MenuItem} from 'electron'
import shortcut from 'electron-localshortcut'
import app from './electron-app'
import * as settings from '../node/settings'
module.exports = function(options={}) {
export default function(options={}) {
var window
window = new BrowserWindow({
title: options.title || settings.infos.productName,
icon: path.resolve(__dirname + '/../assets/logo.png'),
backgroundColor: options.color || theme.backgroundColor,
backgroundColor: options.color,
type: options.type,
useContentSize: true,
autoHideMenuBar: true,

View file

@ -0,0 +1,308 @@
import sourceMap from 'source-map-support'
import * as settings from '../node/settings'
import DocsServer from '../node/docs-server'
import {fork} from 'child_process'
import path from 'path'
import app from './electron-app'
import window from './electron-window'
import {ipcMain} from 'electron'
import electronRemote from '@electron/remote/main'
import createTray from './tray'
import midi from '../node/midi'
import qrcode from '../node/qrcode'
var dev = process.argv[0].includes('node_modules'),
docsServer,
launcher = null,
tray = null,
clientWindows = [],
serverProcess = null,
node = false
sourceMap.install({handleUncaughtExceptions: false})
function openDocs() {
if (!docsServer) docsServer = new DocsServer()
docsServer.open()
}
function openClient() {
var address = settings.appAddresses()[0]
function launch() {
var win = window({
address:address,
shortcuts:true,
fullscreen: settings.read('fullscreen'),
noFocus: settings.read('client-options') && settings.read('client-options').some(x=>x.match(/nofocus=1/i)),
id: 'client'
})
win.on('error', ()=>{
console.log('ERR')
})
clientWindows.push(win)
}
if (app.isReady()) {
launch()
} else {
app.on('ready',function(){
launch()
})
}
}
function startServerProcess() {
var args = [ '--no-gui']
for (var k in settings.read('options')) {
args.push('--' + k)
var val = settings.read(k)
if (typeof val === 'object') {
args = args.concat(val)
} else if (typeof val !== 'boolean') {
args.push(val)
}
}
serverProcess = fork(app.getAppPath(), args, {stdio: 'pipe', env: {...process.env, OSC_SERVER_PROCESS: 1}})
var cb = (data)=>{
if (data.indexOf('(INFO) Server started') > -1) {
if (!settings.read('no-gui')) openClient()
if (!settings.read('no-qrcode')) setTimeout(()=>{
qrcode(launcher ? 'svg' : 'terminal', (qrstring)=>{
if (launcher) {
launcher.webContents.send('stdout', qrstring)
} else {
console.log(qrstring)
}
})
})
serverProcess.stdout.off('data', cb)
}
}
serverProcess.stdout.on('data', cb)
serverProcess.stdout.on('data', (data) => {
console.log(String(data).trim())
})
serverProcess.stderr.on('data', (data) => {
var str = String(data).trim()
if (str.includes('--debug')) return
console.error(str)
})
serverProcess.on('message', (data) => {
var [command, args] = data
if (command === 'settings.write') {
settings.write(args[0], args[1], false)
}
})
serverProcess.on('close', (code) => {
console.log('(INFO) Server stopped')
serverProcess = null
if (global.defaultClient) global.defaultClient.close()
})
if (launcher) {
serverProcess.on('close', (code) => {
if (!launcher.isDestroyed()) launcher.webContents.send('server-stopped')
})
launcher.webContents.send('server-starting')
}
}
function stopServerProcess() {
if (settings.read('no-gui')) {
if (serverProcess) serverProcess.kill('SIGINT')
serverProcess = null
return
}
var toClose = clientWindows.filter(w=>w && !w.isDestroyed()),
closed = 0
if (toClose.length === 0) {
serverProcess.kill('SIGINT')
serverProcess = null
}
for (var w of toClose) {
w.on('closed', ()=>{
closed++
if (closed === toClose.length) {
clientWindows = []
if (serverProcess) {
serverProcess.kill('SIGINT')
serverProcess = null
}
}
})
w.close()
}
}
function startLauncher() {
global.launcherSharedGlobals = {
settings: settings,
openDocs: openDocs,
midilist: midi.list
}
var address = 'file://' + path.resolve(__dirname + '/../../launcher/' + 'index.html')
// @electron/remote won't work without this hack
process.mainModule = {require}
electronRemote.initialize()
app.on('ready', function(){
launcher = window({address:address, shortcuts:dev, width:680, height:(40 + 200 + 20 + 24 * Object.keys(settings.options).filter(x=>settings.options[x].launcher !== false).length / 2), node:true, color:'#151a24', id: 'launcher'})
electronRemote.enable(launcher.webContents)
if (settings.read('useTray')) {
tray = createTray({
window: launcher,
openClient: openClient,
app: app,
startServer: startServerProcess,
stopServer: stopServerProcess
})
launcher.on('will-close', ()=>{
if (clientWindows.some(w=>w && !w.isDestroyed())) {
launcher.hide()
e.preventDefault()
}
})
}
launcher.on('close', (e)=>{
if (tray && clientWindows.some(w=>w && !w.isDestroyed()) && serverProcess) {
launcher.hide()
e.preventDefault()
return
}
process.stdout.write = stdoutWrite
process.stderr.write = stderrWrite
if (process.log) process.log = processLog
if (tray) tray.destroy()
})
})
let processLog = process.log,
stdoutWrite = process.stdout.write,
stderrWrite = process.stderr.write
if (process.log) {
process.log = function(string, encoding, fd) {
processLog.apply(process, arguments)
launcher.webContents.send('stdout', string)
}
}
process.stdout.write = function(string, encoding, fd) {
stdoutWrite.apply(process.stdout, arguments)
launcher.webContents.send('stdout', string)
}
process.stderr.write = function(string, encoding, fd) {
stderrWrite.apply(process.stderr, arguments)
launcher.webContents.send('stderr', string)
}
ipcMain.on('start',function(e, options){
startServerProcess()
})
ipcMain.on('stop',function(e, options){
stopServerProcess()
})
ipcMain.on('openClient',function(e, options){
openClient()
})
ipcMain.on('showQRCode',function(e, options){
qrcode('svg', (qrstring)=>{
launcher.webContents.send('stdout', qrstring)
})
})
ipcMain.on('hide',function(e, options){
launcher.hide()
})
}
if (settings.read('docs')) {
openDocs()
} else {
// normal mode:
// - electron process: launcher and/or built-in client(s)
// - node process: server (node mode in a forked process)
app.on('ready', ()=>{
process.on('SIGINT', function() {
if (serverProcess) {
serverProcess.kill('SIGINT')
serverProcess = null
}
process.exit(0)
})
})
app.on('before-quit',()=>{
if (serverProcess) {
serverProcess.kill('SIGINT')
serverProcess = null
}
})
if (settings.cli) {
startServerProcess()
} else {
startLauncher()
}
}

View file

@ -1,10 +1,11 @@
var {Menu, Tray, ipcMain} = require('electron'),
settings = require('./settings'),
tray = null,
import {Menu, Tray, ipcMain} from 'electron'
import * as settings from '../node/settings'
var tray = null,
contextMenu = null,
isServerRunning = false
module.exports = function(options = {}) {
export default function(options = {}) {
var icon = __dirname + '/../assets/logo.png'
if (process.platform === 'darwin') {

View file

@ -1,393 +1,15 @@
require('source-map-support').install({handleUncaughtExceptions: false})
var dev = process.argv[0].includes('node_modules'),
settings = require('./settings'),
docsServer,
app = null,
launcher = null,
tray = null,
clientWindows = [],
serverProcess = null,
node = false
function openDocs() {
if (!docsServer) {
var DocsServer = require('./docs-server')
docsServer = new DocsServer()
}
docsServer.open()
}
function nodeMode() {
if (!settings.read('no-gui') && !process.env.OSC_SERVER_PROCESS) {
settings.write('no-gui', true, true)
console.warn('(INFO) Headless mode (--no-gui) enabled automatically (running with node)')
}
process.on('uncaughtException', (err)=>{
console.error('(ERROR) A JavaScript error occurred in the main process:')
console.error(err.stack)
})
node = true
}
if (!process.versions.electron || process.env.ELECTRON_RUN_AS_NODE) {
nodeMode()
} else {
var runtime = 'node'
if (!process.argv.includes('-n') && !process.argv.includes('--no-gui')
&& process.versions.electron && !process.env.ELECTRON_RUN_AS_NODE)
{
try {
require('electron').dialog.showErrorBox = (title, err)=>{
var electron = require('electron')
electron.dialog.showErrorBox = (title, err)=>{
console.error(title + ': ' + err)
}
} catch(e) {
nodeMode()
}
runtime = 'electron'
} catch {}
}
function openClient() {
var app = require('./electron-app')
var address = settings.appAddresses()[0]
var launch = ()=>{
var win = require('./electron-window')({
address:address,
shortcuts:true,
fullscreen: settings.read('fullscreen'),
noFocus: settings.read('client-options') && settings.read('client-options').some(x=>x.match(/nofocus=1/i)),
id: 'client'
})
win.on('error', ()=>{
console.log('ERR')
})
clientWindows.push(win)
}
if (app.isReady()) {
launch()
} else {
app.on('ready',function(){
launch()
})
}
}
function showQRCode(){
var QRCode = require('qrcode'),
addresses = settings.appAddresses().filter(a=>!a.includes('127.0.0.1') && !a.includes('localhost'))
for (var add of addresses) {
if (launcher) {
QRCode.toString(add,{type:'svg', small: true, margin: 1}, (err, qr)=>{
launcher.webContents.send('stdout', '<div class="qrcode" title="' + add + '">' + qr + '</div>')
})
if (addresses.length > 1) {
launcher.webContents.send('stdout', '(' + add + ')')
}
} else {
QRCode.toString(add,{type:'terminal', small: true}, (err, qr)=>{
console.log('\n' + qr.replace(/^/gm, ' '))
})
if (addresses.length > 1) {
console.log(' (' + add + ')')
}
}
}
}
function startServerProcess() {
var args = [ '--no-gui']
for (var k in settings.read('options')) {
args.push('--' + k)
var val = settings.read(k)
if (typeof val === 'object') {
args = args.concat(val)
} else if (typeof val !== 'boolean') {
args.push(val)
}
}
var {fork} = require('child_process')
serverProcess = fork(app.getAppPath(), args, {stdio: 'pipe', env: {...process.env, OSC_SERVER_PROCESS: 1}})
var cb = (data)=>{
if (data.indexOf('(INFO) Server started') > -1) {
if (!settings.read('no-gui')) openClient()
if (!settings.read('no-qrcode')) setTimeout(()=>{
showQRCode()
})
serverProcess.stdout.off('data', cb)
}
}
serverProcess.stdout.on('data', cb)
serverProcess.stdout.on('data', (data) => {
console.log(String(data).trim())
})
serverProcess.stderr.on('data', (data) => {
var str = String(data).trim()
if (str.includes('--debug')) return
console.error(str)
})
serverProcess.on('message', (data) => {
var [command, args] = data
if (command === 'settings.write') {
settings.write(args[0], args[1], false)
}
})
serverProcess.on('close', (code) => {
console.log('(INFO) Server stopped')
serverProcess = null
if (global.defaultClient) global.defaultClient.close()
})
if (launcher) {
serverProcess.on('close', (code) => {
if (!launcher.isDestroyed()) launcher.webContents.send('server-stopped')
})
launcher.webContents.send('server-starting')
}
}
function stopServerProcess() {
if (settings.read('no-gui')) {
if (serverProcess) serverProcess.kill('SIGINT')
serverProcess = null
return
}
var toClose = clientWindows.filter(w=>w && !w.isDestroyed()),
closed = 0
if (toClose.length === 0) {
serverProcess.kill('SIGINT')
serverProcess = null
}
for (var w of toClose) {
w.on('closed', ()=>{
closed++
if (closed === toClose.length) {
clientWindows = []
if (serverProcess) {
serverProcess.kill('SIGINT')
serverProcess = null
}
}
})
w.close()
}
}
function startLauncher() {
global.launcherSharedGlobals = {
settings: settings,
openDocs: openDocs,
midilist: require('./midi').list
}
var path = require('path'),
address = 'file://' + path.resolve(__dirname + '/../launcher/' + 'index.html'),
{ipcMain} = require('electron')
// @electron/remote won't work without this hack
process.mainModule = {require}
require('@electron/remote/main').initialize()
app.on('ready',function(){
launcher = require('./electron-window')({address:address, shortcuts:dev, width:680, height:(40 + 200 + 20 + 24 * Object.keys(settings.options).filter(x=>settings.options[x].launcher !== false).length / 2), node:true, color:'#151a24', id: 'launcher'})
require('@electron/remote/main').enable(launcher.webContents)
if (settings.read('useTray')) {
tray = require('./tray')({
window: launcher,
openClient: openClient,
app: app,
startServer: startServerProcess,
stopServer: stopServerProcess
})
launcher.on('will-close', ()=>{
if (clientWindows.some(w=>w && !w.isDestroyed())) {
launcher.hide()
e.preventDefault()
}
})
}
launcher.on('close', (e)=>{
if (tray && clientWindows.some(w=>w && !w.isDestroyed()) && serverProcess) {
launcher.hide()
e.preventDefault()
return
}
process.stdout.write = stdoutWrite
process.stderr.write = stderrWrite
if (process.log) process.log = processLog
if (tray) tray.destroy()
})
})
let processLog = process.log,
stdoutWrite = process.stdout.write,
stderrWrite = process.stderr.write
if (process.log) {
process.log = function(string, encoding, fd) {
processLog.apply(process, arguments)
launcher.webContents.send('stdout', string)
}
}
process.stdout.write = function(string, encoding, fd) {
stdoutWrite.apply(process.stdout, arguments)
launcher.webContents.send('stdout', string)
}
process.stderr.write = function(string, encoding, fd) {
stderrWrite.apply(process.stderr, arguments)
launcher.webContents.send('stderr', string)
}
ipcMain.on('start',function(e, options){
startServerProcess()
})
ipcMain.on('stop',function(e, options){
stopServerProcess()
})
ipcMain.on('openClient',function(e, options){
openClient()
})
ipcMain.on('showQRCode',function(e, options){
showQRCode()
})
ipcMain.on('hide',function(e, options){
launcher.hide()
})
}
if (settings.read('docs')) {
openDocs()
} else if (node || (settings.cli && settings.read('no-gui'))) {
// node mode: minimal server startup
var server = require('./server'),
osc = require('./osc'),
callbacks = require('./callbacks'),
zeroconf = require('./zeroconf')
server.bindCallbacks(callbacks)
serverStarted = true
var closeServer = ()=>{
osc.server.stop()
zeroconf.unpublishAll()
}
try {
let {app} = require('electron')
app.on('ready', ()=>{
process.on('SIGINT', function() {
closeServer()
process.exit(0)
})
})
} catch(e) {
process.on('SIGINT', function() {
closeServer()
process.exit(0)
})
}
if (!process.env.OSC_SERVER_PROCESS) server.eventEmitter.on('serverStarted', ()=>{
if (!settings.read('no-qrcode')) showQRCode()
})
} else {
// normal mode:
// - electron process: launcher and/or built-in client(s)
// - node process: server (node mode in a forked process)
app = require('./electron-app')
app.on('ready', ()=>{
process.on('SIGINT', function() {
if (serverProcess) {
serverProcess.kill('SIGINT')
serverProcess = null
}
process.exit(0)
})
})
app.on('before-quit',()=>{
if (serverProcess) {
serverProcess.kill('SIGINT')
serverProcess = null
}
})
if (settings.cli) {
startServerProcess()
} else {
startLauncher()
}
}
require(`./${runtime}/`)

View file

@ -1,6 +1,6 @@
var networkInterfaces = require('os').networkInterfaces
import {networkInterfaces} from 'os'
module.exports = (proto, port)=>{
export default (proto, port)=>{
var address = Object.values(networkInterfaces())
.reduce((a,b)=>a.concat(b), [])
.filter(i=>i.family === 'IPv4')

View file

@ -1,10 +1,11 @@
var settings = require('./settings'),
auth = null
import httpAuth from 'http-auth'
import * as settings from './settings'
var auth = null
if (settings.read('authentication')) {
var [name, pwd] = settings.read('authentication').split(':'),
httpAuth = require('http-auth')
var [name, pwd] = settings.read('authentication').split(':')
auth = httpAuth.basic(
{
@ -19,4 +20,4 @@ if (settings.read('authentication')) {
}
module.exports = auth
export default auth

View file

@ -1,9 +1,11 @@
var settings = require('./settings'),
fs = require('fs'),
vm = require('vm'),
chokidar = require('chokidar'),
path = require('path'),
modulePathExtended = false,
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 = {}
@ -77,7 +79,7 @@ class CustomModule {
}
if (!this.submodule && !modulePathExtended) {
require('module').globalPaths.push(
globalPaths.push(
path.resolve(path.dirname(this.filename)),
path.resolve(path.dirname(this.filename), 'node_modules')
)
@ -263,4 +265,4 @@ class CustomModule {
}
module.exports = CustomModule
export default CustomModule

View file

@ -1,10 +1,10 @@
var EventEmitter = require('events').EventEmitter,
http = require('http'),
send = require('send'),
path = require('path'),
fs = require('fs'),
open = require('open'),
address = require('./address')
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 {
@ -87,4 +87,4 @@ class DocsServer extends EventEmitter {
}
module.exports = DocsServer
export default DocsServer

View file

@ -1,10 +1,12 @@
var {resolvePath, ipc} = require('./server'),
callbacks = require('./callbacks'),
chokidar = require('chokidar')
import chokidar from 'chokidar'
class FragmentManager {
constructor() {
constructor(callbacks, ipcServer, webServer) {
this.ipcServer = ipcServer
this.webServer = webServer
this.callbacks = callbacks
this.fragments = {} // fragment files contents
this.watchers = {} // fragment files watchers
@ -14,12 +16,12 @@ class FragmentManager {
read(path, raw, clientId, then) {
callbacks.fileRead({path: path, raw: raw}, clientId, true, (result)=>{
this.callbacks.fileRead({path: path, raw: raw}, clientId, true, (result)=>{
this.fragments[path] = result
then(result)
}, (error)=>{
ipc.send('errorLog', `Could not open fragment file:\n ${error}`, clientId)
ipc.send('fragmentLoad', {path: path, notFound: true})
this.ipcServer.send('errorLog', `Could not open fragment file:\n ${error}`, clientId)
this.ipcServer.send('fragmentLoad', {path: path, notFound: true})
this.deleteFragment(path)
})
@ -28,10 +30,10 @@ class FragmentManager {
loadFragment(data, clientId) {
var path = data.path
var resolvedPath = resolvePath(path, clientId)
var resolvedPath = this.webServer.resolvePath(path, clientId)
if (!resolvedPath) {
ipc.send('fragmentLoad', {path: path, notFound: true})
this.ipcServer.send('fragmentLoad', {path: path, notFound: true})
return
}
@ -43,13 +45,13 @@ class FragmentManager {
this.fragments[resolvedPath] = 'LOADING'
this.read(resolvedPath, data.raw, clientId, (result)=>{
ipc.send('fragmentLoad', {path: path, fileContent: this.fragments[resolvedPath], raw: data.raw}, clientId)
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]) {
ipc.send('fragmentLoad', {path: path, fileContent: this.fragments[resolvedPath], raw: data.raw}, id)
this.ipcServer.send('fragmentLoad', {path: path, fileContent: this.fragments[resolvedPath], raw: data.raw}, id)
}
})
}).on('unlink', ()=>{
@ -58,7 +60,7 @@ class FragmentManager {
} else if (this.fragments[resolvedPath] !== 'LOADING') {
ipc.send('fragmentLoad', {path: path, fileContent: this.fragments[resolvedPath], raw: data.raw}, clientId)
this.ipcServer.send('fragmentLoad', {path: path, fileContent: this.fragments[resolvedPath], raw: data.raw}, clientId)
}
@ -76,4 +78,4 @@ class FragmentManager {
}
module.exports = new FragmentManager()
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

@ -1,61 +1,76 @@
var path = require('path'),
fs = require('fs'),
settings = require('./settings'),
osc = require('./osc'),
{ipc} = require('./server'),
{deepCopy, resolveHomeDir} = require('./utils'),
child_process = require('child_process'),
fragmentManager
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'
var widgetHashTable = {},
clipboard = {clipboard: null, idClipboard: null}
export default class Callbacks {
module.exports = {
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
ipc.send('connected')
this.ipcServer.send('connected')
var recentSessions = settings.read('recentSessions')
ipc.send('sessionList', recentSessions, clientId)
ipc.send('clipboard', clipboard, clientId)
ipc.send('serverTargets', settings.read('send'), clientId)
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 (!widgetHashTable[clientId]) {
widgetHashTable[clientId] = {CONSOLE: {typeTags: ''}}
if (!this.widgetHashTable[clientId]) {
this.widgetHashTable[clientId] = {CONSOLE: {typeTags: ''}}
}
},
}
destroyed(data, clientId) {
// client removed (timeout)
// clear osc data cache
if (widgetHashTable[clientId]) delete widgetHashTable[clientId]
if (this.widgetHashTable[clientId]) delete this.widgetHashTable[clientId]
},
}
clipboard(data, clientId) {
// shared clipboard
clipboard = data
ipc.send('clipboard', data, null, clientId)
this.clipboardContent = data
this.ipcServer.send('clipboard', data, null, clientId)
},
}
sessionAddToHistory(data) {
@ -78,10 +93,10 @@ module.exports = {
// save history
settings.write('recentSessions', recentSessions)
ipc.send('sessionList', recentSessions)
this.ipcServer.send('sessionList', recentSessions)
})
},
}
sessionRemoveFromHistory(data) {
@ -89,10 +104,10 @@ module.exports = {
if (recentSessions.indexOf(data) > -1) {
recentSessions.splice(recentSessions.indexOf(data),1)
settings.write('recentSessions',recentSessions)
ipc.send('sessionList', recentSessions)
this.ipcServer.send('sessionList', recentSessions)
}
},
}
sessionSetPath(data, clientId) {
// store client's current session file path
@ -100,43 +115,41 @@ module.exports = {
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
if (!settings.read('read-only')) {
module.exports.sessionAddToHistory(data.path)
this.sessionAddToHistory(data.path)
}
ipc.clients[clientId].sessionPath = data.path
this.ipcServer.clients[clientId].sessionPath = data.path
ipc.send('setTitle', path.basename(data.path), clientId)
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)
module.exports.fileRead(data, clientId, true, (result)=>{
this.fileRead(data, clientId, true, (result)=>{
ipc.clients[clientId].sessionPath = data.path // for resolving local file requests
ipc.send('sessionOpen', {path: data.path, fileContent: result}, clientId)
this.ipcServer.clients[clientId].sessionPath = data.path // for resolving local file requests
this.ipcServer.send('sessionOpen', {path: data.path, fileContent: result}, clientId)
}, (error)=>{
ipc.send('error', `Could not open session file:\n ${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)
fragmentManager = fragmentManager || require('./fragment-manager')
this.fragmentManager.loadFragment(data, clientId)
fragmentManager.loadFragment(data, clientId)
},
}
sessionOpened(data, clientId) {
// session file opened successfully
@ -145,9 +158,9 @@ module.exports = {
if (settings.read('state')) {
var send = true
for (var id in ipc.clients) {
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 && ipc.clients[id].connected()) {
if (id !== clientId && this.ipcServer.clients[id].connected()) {
send = false
}
}
@ -158,14 +171,14 @@ module.exports = {
state: JSON.parse(stateContent),
send: send
}
ipc.send('stateLoad', state, clientId)
this.ipcServer.send('stateLoad', state, clientId)
}
ipc.send('stateSend', null, null, clientId)
this.ipcServer.send('stateSend', null, null, clientId)
module.exports.sessionSetPath({path: data.path}, clientId)
this.sessionSetPath({path: data.path}, clientId)
},
}
fileRead(data, clientId, ok, callback, errorCallback) {
// private function
@ -198,16 +211,16 @@ module.exports = {
})
},
}
fileSave(data, clientId, ok, callback) {
// private function
if (!ok) return
if (!data.path || settings.read('remote-saving') && !RegExp(settings.read('remote-saving')).test(ipc.clients[clientId].address)) {
if (!data.path || settings.read('remote-saving') && !RegExp(settings.read('remote-saving')).test(this.ipcServer.clients[clientId].address)) {
return ipc.send('notify', {
return this.ipcServer.send('notify', {
icon: 'save',
locale: 'remotesave_forbidden',
class: 'error'
@ -226,7 +239,7 @@ module.exports = {
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 ipc.send('notify', {
return this.ipcServer.send('notify', {
class: 'error',
locale: 'remotesave_fail',
message: ' (Could not save: path outside of remote-root)'
@ -241,14 +254,14 @@ module.exports = {
fs.writeFile(data.path, data.session, function(err, fdata) {
if (err) return ipc.send('notify', {
if (err) return this.ipcServer.send('notify', {
class: 'error',
locale: 'remotesave_fail',
message: ' (' + err.message + ')'
}, clientId)
ipc.send('notify', {
this.ipcServer.send('notify', {
icon: 'save',
locale: 'remotesave_success',
class: 'session-save',
@ -261,24 +274,24 @@ module.exports = {
}
},
}
stateOpen(data, clientId) {
// attempt to open state file
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
module.exports.fileRead(data, clientId, true, (result)=>{
this.fileRead(data, clientId, true, (result)=>{
ipc.send('stateLoad', {state: result, path: data.path, send: true}, clientId)
this.ipcServer.send('stateLoad', {state: result, path: data.path, send: true}, clientId)
}, (error)=>{
ipc.send('error', `Could not open state file:\n ${error}`)
this.ipcServer.send('error', `Could not open state file:\n ${error}`)
})
},
}
sessionSave(data, clientId) {
// save session file (.json)
@ -300,24 +313,24 @@ module.exports = {
}
module.exports.fileSave(data, clientId, true, ()=>{
this.fileSave(data, clientId, true, ()=>{
console.log('(INFO) Session file saved in '+ data.path)
if (!data.backup) ipc.send('sessionSaved', clientId)
if (!data.backup) this.ipcServer.send('sessionSaved', clientId)
// reload session in other clients
for (var id in ipc.clients) {
if (id !== clientId && ipc.clients[id].sessionPath === data.path) {
module.exports.sessionOpen({path: data.path}, id)
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) module.exports.sessionSetPath({path: data.path}, clientId)
if (!data.backup) this.sessionSetPath({path: data.path}, clientId)
})
},
}
stateSave(data, clientId) {
// save state file (.json)
@ -326,22 +339,22 @@ module.exports = {
if (!path.basename(data.path).match(/.*\.state/)) return console.error('(ERROR) Statesaves must be saved as .state files')
module.exports.fileSave(data, clientId, true, ()=>{
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 (!(widgetHashTable[clientId] && widgetHashTable[clientId][shortdata.h])) return
if (!(this.widgetHashTable[clientId] && this.widgetHashTable[clientId][shortdata.h])) return
var value = shortdata.v,
data = shortdata.h ? widgetHashTable[clientId][shortdata.h] : {}
data = shortdata.h ? this.widgetHashTable[clientId][shortdata.h] : {}
data = deepCopy(data)
for (var k in shortdata) {
@ -353,10 +366,10 @@ module.exports = {
data.args = data.preArgs ? data.preArgs.concat(value) : [value]
if (!data.noSync) ipc.send('receiveOsc', data, null, clientId)
if (!data.noSync) this.ipcServer.send('receiveOsc', data, null, clientId)
},
}
sendOsc(shortdata, clientId) {
// send osc (or midi) message and sync with other clients
@ -371,10 +384,10 @@ module.exports = {
// if widget hash is provided, look for cached data
if (shortdata.h && !(widgetHashTable[clientId] && widgetHashTable[clientId][shortdata.h])) return
if (shortdata.h && !(this.widgetHashTable[clientId] && this.widgetHashTable[clientId][shortdata.h])) return
var value = shortdata.v,
data = shortdata.h ? widgetHashTable[clientId][shortdata.h] : {}
data = shortdata.h ? this.widgetHashTable[clientId][shortdata.h] : {}
data = deepCopy(data)
for (var k in shortdata) {
@ -393,7 +406,7 @@ module.exports = {
for (var i in targets) {
if (targets[i] === 'self') {
ipc.send('receiveOsc',data,clientId)
this.ipcServer.send('receiveOsc',data,clientId)
continue
} else if (targets[i] === null) {
continue
@ -404,7 +417,7 @@ module.exports = {
if (port) {
osc.send(host, port, data.address, data.args, data.typeTags, clientId)
this.oscServer.send(host, port, data.address, data.args, data.typeTags, clientId)
}
@ -412,9 +425,9 @@ module.exports = {
}
if (!data.noSync) ipc.send('receiveOsc', data, null, clientId)
if (!data.noSync) this.ipcServer.send('receiveOsc', data, null, clientId)
},
}
addWidget(data, clientId) {
// cache widget osc data to reduce bandwidth usage
@ -430,11 +443,11 @@ module.exports = {
// }
// preArgs, target and typeTags can be empty strings
if (!widgetHashTable[clientId][data.hash]) {
widgetHashTable[clientId][data.hash] = {}
if (!this.widgetHashTable[clientId][data.hash]) {
this.widgetHashTable[clientId][data.hash] = {}
}
var cache = widgetHashTable[clientId][data.hash],
var cache = this.widgetHashTable[clientId][data.hash],
widgetData = data.data
for (var k in widgetData) {
@ -452,41 +465,41 @@ module.exports = {
// store raw target for client sync widget matching
cache._rawTarget = widgetData.target
},
}
removeWidget(data, clientId) {
// clear widget osc data
delete widgetHashTable[clientId][data.hash]
delete this.widgetHashTable[clientId][data.hash]
},
}
reload(data) {
// (dev) hot reload
ipc.send('reload')
this.ipcServer.send('reload')
},
}
reloadCss() {
// (dev) hot css reload
ipc.send('reloadCss')
},
this.ipcServer.send('reloadCss')
}
log(data) {
console.log(data)
},
}
error(data) {
console.error(data)
},
}
errorLog(data) {
console.error(data)
},
}
errorPopup(data) {
ipc.send('error', data)
},
this.ipcServer.send('error', data)
}
listDir(data, clientId) {
// remote file browser backend
@ -516,13 +529,13 @@ module.exports = {
if (error) {
ipc.send('notify', {class: 'error', message: 'Failed to list available drives (see server console).'}, clientId)
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 {
ipc.send('listDir', {
this.ipcServer.send('listDir', {
path: '\\',
files: stdout.split(' ')
.filter(value => /[A-Za-z]:/.test(value))
@ -537,7 +550,7 @@ module.exports = {
fs.readdir(p, (err, files)=>{
if (err) {
ipc.send('notify', {class: 'error', message: err.message}, clientId)
this.ipcServer.send('notify', {class: 'error', message: err.message}, clientId)
throw err
} else {
var extRe = data.extension ? new RegExp('.*\\.' + data.extension + '$') : /.*/
@ -552,7 +565,7 @@ module.exports = {
}
})
list = list.filter(x=>x.folder || x.name.match(extRe))
ipc.send('listDir', {
this.ipcServer.send('listDir', {
path: p,
files: list
}, clientId)
@ -560,8 +573,6 @@ module.exports = {
}
})
},
}
}

View file

@ -1,10 +1,10 @@
var EventEmitter = require('events').EventEmitter
import {EventEmitter} from 'events'
var hearbeatInterval = 25000,
hearbeatTimeout = 5000,
dieTimeout = 60000
class Socket extends EventEmitter {
class Client extends EventEmitter {
constructor(ws, id, address) {
@ -123,4 +123,4 @@ class Socket extends EventEmitter {
}
module.exports = Socket
export default Client

View file

@ -1,21 +1,20 @@
var EventEmitter = require('events').EventEmitter,
WebSocketServer = require('ws').Server,
Client = require('./client'),
settings = require('../settings')
import {WebSocketServer} from 'ws'
import Client from './client'
import * as settings from '../settings'
import Callbacks from './callbacks'
class Ipc extends EventEmitter {
class IpcServer {
constructor(server) {
super()
constructor(webServer, oscServer) {
this.clients = {}
this.server = null
this.webServer = webServer
this.oscServer = oscServer
this.server = new WebSocketServer({server: webServer.server})
this.callbacks = new Callbacks(this, webServer, oscServer)
this.server = new WebSocketServer({server: server})
this.server.on('connection', (socket, req)=>{
var url = req.url.split('/'),
auth = url.pop().replace('_', '/'),
id = url.pop()
@ -38,7 +37,15 @@ class Ipc extends EventEmitter {
var client = new Client(socket, id, req.connection.remoteAddress)
this.clients[id] = client
this.emit('connection', 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]
@ -72,4 +79,4 @@ class Ipc extends EventEmitter {
}
module.exports = Ipc
export default IpcServer

View file

@ -1,7 +1,7 @@
var {PythonShell} = require('python-shell'),
fs = require('fs'),
path = require('path'),
settings = require('./settings')
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
@ -168,4 +168,4 @@ class MidiConverter {
}
module.exports = MidiConverter
export default MidiConverter

View file

@ -1,6 +1,6 @@
var fs = require('fs')
import fs from 'fs'
module.exports = {
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:.*$/)) ?

View file

@ -1,24 +1,25 @@
var ipc = require('../server').ipc,
settings = require('../settings'),
tcpInPort = settings.read('tcp-port'),
debug = settings.read('debug'),
midi = settings.read('midi') ? require('../midi') : false,
oscUDPServer = require('./udp'),
oscTCPServer = require('./tcp'),
EventEmitter = require('events').EventEmitter,
CustomModule = require('../custom-module')
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'
if (midi) midi = new midi()
class OscServer {
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: oscTCPServer,
tcpServer: this.oscTCPServer,
sendOsc: this.sendOsc.bind(this),
receiveOsc: this.receiveOsc.bind(this),
send: (host, port, address, ...args)=>{
@ -103,7 +104,7 @@ class OscServer {
if (data.host == 'midi') {
if (midi) midi.send(data)
if (this.midiServer) this.midiServer.send(data)
} else {
@ -117,23 +118,23 @@ class OscServer {
return
}
if (tcpInPort && oscTCPServer.clients[data.host] && oscTCPServer.clients[data.host][data.port]) {
if (this.tcpInPort && this.oscTCPServer.clients[data.host] && this.oscTCPServer.clients[data.host][data.port]) {
oscTCPServer.clients[data.host][data.port].send({
this.oscTCPServer.clients[data.host][data.port].send({
address: data.address,
args: data.args
})
} else {
oscUDPServer.send({
this.oscUDPServer.send({
address: data.address,
args: data.args
}, data.host, data.port)
}
if (debug) {
if (this.debug) {
console.log('\x1b[35m(DEBUG, OSC) Out: ', `{ address: '${data.address}', args: `, data.args, '} To: ' + data.host + ':' + data.port, '\x1b[0m')
}
@ -152,9 +153,9 @@ class OscServer {
if (data.args.length==1) data.args = data.args[0]
ipc.send('receiveOsc', data, clientId)
this.ipcServer.send('receiveOsc', data, clientId)
if (debug) console.log('\x1b[36m(DEBUG, OSC) In: ', {address:data.address, args: data.args}, 'From: ' + data.host + ':' + data.port, '\x1b[0m')
if (this.debug) console.log('\x1b[36m(DEBUG, OSC) In: ', {address:data.address, args: data.args}, 'From: ' + data.host + ':' + data.port, '\x1b[0m')
}
@ -201,11 +202,11 @@ class OscServer {
}
}
start(ipcServer){
this.ipcServer = ipcServer
init(){
if (midi) midi.init((data)=>{
if (this.midiServer) midi.init((data)=>{
data = this.oscInFilter({address: data.address, args: data.args, host: data.host, port: data.port})
@ -215,12 +216,12 @@ class OscServer {
})
oscUDPServer.on('message', this.oscInHandlerWrapper.bind(this))
oscUDPServer.open()
this.oscUDPServer.on('message', this.oscInHandlerWrapper.bind(this))
this.oscUDPServer.start()
if (settings.read('tcp-port')) {
oscTCPServer.on('message', this.oscInHandlerWrapper.bind(this))
oscTCPServer.open()
this.oscTCPServer.on('message', this.oscInHandlerWrapper.bind(this))
this.oscTCPServer.start()
}
if (this.customModule.init) {
@ -236,20 +237,12 @@ class OscServer {
stop() {
if (this.customModule.stop) this.customModule.stop()
if (midi) midi.stop()
if (this.midiServer) this.midiServer.stop()
}
}
var oscServer = new OscServer()
oscServer.init()
module.exports = {
server: oscServer,
send: function(host, port, address, args, typeTags, clientId) {
send(host, port, address, args, typeTags, clientId) {
// public send function
var message = []
@ -263,17 +256,17 @@ module.exports = {
for (var i = 0; i < args.length; i++) {
if (typeTags && typeTags[i]) typeTag = typeTags[i]
arg = oscServer.parseArg(args[i], typeTag)
arg = this.parseArg(args[i], typeTag)
if (arg !== null) message.push(arg)
}
}
var data = oscServer.oscOutFilter({address:address, args: message, host: host, port: port, clientId: clientId})
var data = this.oscOutFilter({address:address, args: message, host: host, port: port, clientId: clientId})
oscServer.sendOsc(data)
this.sendOsc(data)
}
},
midi:midi
}

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

View file

@ -1,10 +1,8 @@
var osc = require('./osc'),
EventEmitter = require('events').EventEmitter,
settings = require('../settings'),
zeroconf = require('../zeroconf'),
tcpInPort = settings.read('tcp-port'),
tcpTargets = settings.read('tcp-targets'),
net = require('net')
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 {
@ -76,14 +74,19 @@ class OscTCPClient extends EventEmitter {
}
class OscTCPServer extends EventEmitter {
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) {
@ -113,17 +116,17 @@ class OscTCPServer extends EventEmitter {
}
open() {
start() {
this.server = net.createServer(this.bindSocket.bind(this))
this.server.listen({port: tcpInPort})
for (var i in tcpTargets) {
this.server.listen({port: this.port})
for (var i in this.targets) {
this.addClient(new OscTCPClient({
metadata: true,
address: tcpTargets[i].split(':')[0],
port: tcpTargets[i].split(':')[1]
address: this.targets[i].split(':')[0],
port: this.targets[i].split(':')[1]
}))
}
@ -132,15 +135,17 @@ class OscTCPServer extends EventEmitter {
name: settings.infos.productName + (settings.read('instance-name') ? ' (' + settings.read('instance-name') + ')' : ''),
protocol: 'tcp',
type: 'osc',
port: tcpInPort
port: this.port
}).on('error', (e)=>{
console.error(`Error: Zeroconf: ${e.message}`)
})
}
stop() {
this.server.close()
}
}
var oscTCPServer = new OscTCPServer()
module.exports = oscTCPServer

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

View file

@ -1,10 +1,12 @@
var path = require('path'),
fs = require('fs'),
yargs = require('yargs'),
infos = require('../../package.json'),
options = require('./options'),
address = require('./address'),
argv = process.argv.slice()
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
@ -95,7 +97,6 @@ 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 {
envPaths = require('env-paths')
baseDir = envPaths(infos.name, {
suffix: ''
}).config
@ -154,54 +155,57 @@ if (!configPath) {
/////////////////
export {
options,
cli,
infos,
baseDir as configPath
}
module.exports = {
options: options,
read: function(key){
return settings.options[key] !== undefined ? settings.options[key] : settings[key]
},
write:function(key, value, tmp, sync) {
export function read(key){
return settings.options[key] !== undefined ? settings.options[key] : settings[key]
}
export function write(key, value, tmp, sync) {
settings[key] = value
settings[key] = value
if (!tmp && configPathExists) {
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 (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
})
}
}
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]])
}
}
},
cli: cli,
configPath: baseDir,
infos: infos,
appAddresses: ()=>address(module.exports.read('use-ssl') ? 'https://' : 'http://', settings.options.port || 8080)
// 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) {
@ -210,7 +214,7 @@ if (process.send) {
process.on('message', function(data) {
var [command, args] = data
if (command === 'settings.write') {
module.exports.write(args[0], args[1], true)
write(args[0], args[1], true)
}
})
}

View file

@ -1,6 +1,7 @@
var settings = require('./settings'),
forge = require('node-forge'),
pki = forge.pki,
import * as settings from './settings'
import forge from 'node-forge'
var pki = forge.pki,
certificate = settings.read('ssl-certificate')
forge.options.usePureJavaScript = true
@ -47,24 +48,27 @@ function createCertificate() {
}
if (!certificate) {
if (settings.read('use-ssl')){
createCertificate()
if (!certificate) {
} 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')
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')
}
}
}

View file

@ -1,25 +1,20 @@
var fs = require('fs'),
path = require('path'),
settings = require('./settings'),
chokidar = require('chokidar'),
ipc
import fs from 'fs'
import path from 'path'
import * as settings from './settings'
import chokidar from 'chokidar'
import {EventEmitter} from 'events'
class Theme {
class Theme extends EventEmitter {
constructor() {
this.themes = []
this.files = []
this.css = []
this.watcher = null
super()
this.defaultColor = '#151a24'
this.backgroundColor = this.defaultColor
}
init() {
this.css = []
this.watcher = null
this.themes = settings.read('theme') || []
this.files = []
@ -47,17 +42,14 @@ class Theme {
if (this.files.length) {
this.watcher = chokidar.watch(this.files, {awaitWriteFinish: {stabilityThreshold: 200}}).on('change', ()=>{
if (!ipc) ipc = require('./server').ipc
this.load()
ipc.send('reloadCss')
this.emit('update')
})
}
this.load()
return this
}
load() {
@ -74,16 +66,6 @@ class Theme {
}
var css = this.get()
if (css.includes('--color-background:')) {
this.backgroundColor = css.match(/--color-background:([^;\n]*)/)[1].trim()
} else {
this.backgroundColor = this.defaultColor
}
return this
}
get() {
@ -96,4 +78,4 @@ class Theme {
var theme = new Theme()
module.exports = 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()

View file

@ -1,7 +0,0 @@
var osc = require('osc/src/osc.js'),
transports = require('osc/src/platforms/osc-node.js')
osc.UDPPort = transports.UDPPort
osc.TCPSocketPort = transports.TCPSocketPort
module.exports = osc

View file

@ -1,28 +0,0 @@
var osc = require('./osc'),
settings = require('../settings'),
zeroconf = require('../zeroconf'),
oscInPort = settings.read('osc-port') || settings.read('port') || 8080
var oscUDPServer = new osc.UDPPort({
localAddress: '0.0.0.0',
localPort: oscInPort,
metadata: true,
broadcast: true
})
oscUDPServer.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)
}
})
zeroconf.publish({
name: settings.infos.productName + (settings.read('instance-name') ? ' (' + settings.read('instance-name') + ')' : ''),
protocol: 'udp',
type: 'osc',
port: oscInPort
})
module.exports = oscUDPServer

View file

@ -1,270 +0,0 @@
var settings = require('./settings'),
http = require('http'),
EventEmitter = require('events').EventEmitter,
eventEmitter = new EventEmitter(),
QRCode = require('qrcode'),
qrcode = ''
function createServer(route) {
if (settings.read('use-ssl')) {
http = require('https')
require('./ssl')
return http.createServer(settings.read('ssl-certificate'), route)
} else {
return http.createServer(route)
}
}
var path = require('path'),
fs = require('fs'),
send = require('send'),
replaceStream = require('replacestream'),
auth = require('./auth'),
server = createServer(auth ? auth.check(httpRoute) : httpRoute),
Ipc = require('./ipc/server'),
ipc = new Ipc(server),
theme = require('./theme').init(),
zeroconf = require('./zeroconf'),
{resolveHomeDir} = require('./utils'),
prod = !process.argv[0].includes('node_modules'),
debug = settings.read('debug'),
osc = {},
clients = {},
httpCheckTimeout
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
}
}
var resolveDirs = theme.files.map(x=>path.dirname(x)),
remoteRoot = settings.read('remote-root')
resolveDirs = resolveDirs.filter((x, index)=>{return resolveDirs.indexOf(x) === index})
resolveDirs.push(remoteRoot || '') // remote-root / absolute
function resolvePath(url, clientId) {
var sessionPath
if (ipc.clients[clientId]) {
sessionPath = path.dirname(ipc.clients[clientId].sessionPath)
}
url = resolveHomeDir(url)
url = url.split('?')[0]
for (var i = sessionPath ? -1 : 0; i < resolveDirs.length; i++) {
var p = i === -1 ? sessionPath : resolveDirs[i]
if (i == resolveDirs.length - 1 && 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 (debug && !ipc.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
}
function 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 = 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:', '')
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)
// res.sendFile(path.resolve(__dirname + '/../client/index.html'))
} 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 (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 = 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')) {
httpCheck(true)
} else {
res.writeHead(403)
res.end()
}
}
}
}
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}`)
}
})
server.listen(settings.read('port') || 8080)
http.get(settings.appAddresses()[0] + '/osc-ping', {
auth: settings.read('authentication'),
rejectUnauthorized: false
},()=>{}).on('error', ()=>{httpCheck(false)})
httpCheckTimeout = setTimeout(()=>{httpCheck(false)}, 5000)
function httpCheck(ok, error){
if (!httpCheckTimeout) return
clearTimeout(httpCheckTimeout)
httpCheckTimeout = null
if (ok) {
console.log('(INFO) Server started, app available at \n ' + settings.appAddresses().join('\n '))
eventEmitter.emit('serverStarted')
QRCode.toString(settings.appAddresses().pop(),{type:'svg', small: true, margin: 1}, (err, qr)=>{
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 ?')
}
}
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}`)
})
var bindCallbacks = function(callbacks) {
ipc.on('connection', function(client) {
var clientInfos = {address: client.address, id: client.id}
var customModule = settings.read('custom-module')
for (let name in callbacks) {
client.on(name, (data)=>{
if (customModule) {
osc.customModuleEventEmitter.emit(name, data, clientInfos)
}
callbacks[name](data, client.id)
})
}
})
}
module.exports = {
ipc:ipc,
bindCallbacks:bindCallbacks,
clients:clients,
resolvePath:resolvePath,
eventEmitter:eventEmitter
}
osc = require('./osc').server

View file

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

View file

@ -1,3 +0,0 @@
var zeroconf = require('bonjour')()
module.exports = zeroconf