event cucle (#76)

* install sass
* refact: integration settings
- OSC in its own HTTP endpoint
- OSC settings have own object in db
* refact: simplify event cycle
* refact: restructure external triggers http
* refact: restructure external triggers osc+socket
* refact: restructure data updates
* feat: osc integration class
* IO improvements
- timer uses osc integration
- create trigger handler to manage external triggers
* refact: refract state machine update
* Integration: simple HTTP Client
* Integration: http options in datamodel
* Integration: call http send on life cycle
* feat/62-logging: fix issue #71
This commit is contained in:
Carlos Valente
2021-12-22 18:17:48 +01:00
committed by GitHub
parent 2b2bafa8c6
commit ac0d5832b6
53 changed files with 2041 additions and 1948 deletions
+17 -26
View File
@@ -22,7 +22,6 @@ const adapter = new JSONFile(file);
export const db = new Low(adapter);
// dependencies
import { Client } from 'node-osc';
import express from 'express';
import http from 'http';
import cors from 'cors';
@@ -48,8 +47,8 @@ if (db.data == null || !isValid) {
// get data
// there is also the case of the db being corrupt
// try to parse the data
export const data = await parseJson(db.data);
// try to parse the data, make sure that all fields exist (enforce)
export const data = await parseJson(db.data, true);
db.data = data;
await db.write();
@@ -113,17 +112,17 @@ app.use((err, req, res, next) => {
* ----------------
*
* Configuration of services comes from app general config
* It can be overriden here by the settings in the db
* It can also be overriden on call
* It can be overridden here by the settings in the db
* It can also be overridden on call
*
*/
const s = data.settings;
const oscIP = s.oscOutIP || config.osc.ipOut;
const oscOutPort = s.oscOutPort || config.osc.portOut;
const oscInPort = s.oscInPort || config.osc.port;
const osc = data.osc;
const oscIP = osc?.targetIP || config.osc.targetIP;
const oscOutPort = osc?.portOut || config.osc.portOut;
const oscInPort = osc?.port || config.osc.port;
const serverPort = s.serverPort || config.server.port;
const serverPort = data.settings.serverPort || config.server.port;
// Start OSC server
import { initiateOSC, shutdownOSCServer } from './controllers/OscController.js';
@@ -140,17 +139,6 @@ export const startOSCServer = async (overrideConfig = null) => {
initiateOSC(oscSettings);
};
// Start OSC Client
let oscClient = null;
export const startOSCClient = async (overrideConfig = null) => {
// Setup default port
const port = overrideConfig?.port || oscOutPort;
console.log('initialise OSC Client on port: ', port);
oscClient = new Client(oscIP, oscOutPort);
};
// create HTTP server
const server = http.createServer(app);
@@ -168,8 +156,14 @@ export const startServer = async (overrideConfig = null) => {
const returnMessage = `HTTP Server is listening on port ${port}`;
server.listen(port, '0.0.0.0', () => console.log(returnMessage));
// OSC Config
const oscConfig = {
ip: oscIP,
port: overrideConfig?.port || oscOutPort
}
// init timer
global.timer = new EventTimer(server, oscClient, config);
global.timer = new EventTimer(server, config.timer, oscConfig, data.http);
global.timer.setupWithEventList(data.events);
return returnMessage;
@@ -178,7 +172,7 @@ export const startServer = async (overrideConfig = null) => {
export const shutdown = async () => {
console.log('Node service shutdown');
user.event('NODE', 'shutdown', 'requesting node shutfown').send();
user.event('NODE', 'shutdown', 'requesting node shutdown').send();
// shutdown express server
server.close();
@@ -186,9 +180,6 @@ export const shutdown = async () => {
// shutdown OSC Server
shutdownOSCServer();
// shutdown OSC Client
oscClient.close();
// shutdown timer
global.timer.shutdown();
};
+429 -212
View File
@@ -1,6 +1,9 @@
import { Timer } from './Timer.js';
import { Server } from 'socket.io';
import {DAYMS, getSelectionByRoll} from './classUtils.js';
import {Timer} from './Timer.js';
import {Server} from 'socket.io';
import {DAY_TO_MS, getSelectionByRoll, replacePlaceholder, updateRoll} from './classUtils.js';
import {OSCIntegration} from './integrations/Osc.js';
import {HTTPIntegration} from "./integrations/Http.js";
import {cleanURL} from "../utils/url.js";
/*
* EventTimer adds functions specific to APP
@@ -11,11 +14,35 @@ import {DAYMS, getSelectionByRoll} from './classUtils.js';
*/
export class EventTimer extends Timer {
// Keep track of Timer lifecycle
// idle: before it is initialised
// load: when a new event is loaded
// update: every update call cycle (1 x second)
// stop: when the timer is stopped
// finish: when a timer finishes
cycleState = {
idle: 'idle',
onLoad: 'onLoad',
armed: 'armed',
onStart: 'onStart',
onUpdate: 'onUpdate',
onPause: 'onPause',
onStop: 'onStop',
onFinish: 'onFinish',
};
ontimeCycle = 'idle';
prevCycle = null;
lastUpdate = null;
// Socket IO Object
io = null;
// OSC Client
oscClient = null;
// OSC Object
osc = null;
// HTTP Client Object
http = null;
_numClients = 0;
_interval = null;
@@ -62,10 +89,21 @@ export class EventTimer extends Timer {
_eventlist = null;
onAir = false;
constructor(httpServer, oscClient, config) {
/**
* Instantiates an event timer object
* @param httpServer
* @param timerConfig
* @param [oscConfig]
* @param [httpConfig]
*/
constructor(httpServer, timerConfig, oscConfig, httpConfig) {
// call super constructor
super();
// initialise class variables
this.numEvents = 0;
// initialise socketIO server
this.io = new Server(httpServer, {
cors: {
@@ -76,135 +114,47 @@ export class EventTimer extends Timer {
},
});
// Todo: extract
// initialise osc object
if (oscConfig != null) {
console.log('initialise OSC Client on port: ', oscConfig?.port);
this.osc = new OSCIntegration();
this.osc.init(oscConfig);
}
// Todo: extract
// initialise http object
if (httpConfig != null) {
this.http = new HTTPIntegration();
this.http.init(httpConfig);
this.httpMessages = httpConfig.messages;
}
// set recurrent emits
this._interval = setInterval(
() => this.broadcastTimer(),
config.timer.refresh
() => this.runCycle(),
timerConfig?.refresh || 1000
);
// listen to new connections
this._listenToConnections();
// set oscClient
this.updateOSCClient(oscClient);
}
/**
* @description Updates the osc client used in the object
* @param {object} oscClient
*/
updateOSCClient(oscClient) {
this.oscClient = oscClient;
}
/**
* @description Sends osc value from predefined messages
* @param {string} event - message to be sent
*/
sendOSC(event) {
if (this.oscClient == null) return;
const add = '/ontime';
const play = 'play';
const pause = 'pause';
const stop = 'stop';
const prev = 'prev';
const next = 'next';
const reload = 'reload';
const finished = 'finished';
const time = this.timeTag;
const overtime = this.current > 0 ? 0 : 1;
const title = this.titles?.titleNow || '';
const presenter = this.titles?.presenterNow || '';
switch (event) {
case 'time':
// Send Timetag Message
this.oscClient.send(add + '/time', time, (err) => {
if (err) console.error(err);
});
break;
case 'finished':
// Runs when timer reaches 0
this.oscClient.send(add, finished, (err) => {
if (err) console.error(err);
});
break;
case 'overtime':
// Whether timer is negative
this.oscClient.send(add + '/overtime', overtime, (err) => {
if (err) console.error(err);
});
break;
case 'titles':
// Send Title of current event
this.oscClient.send(add + '/title', title, (err) => {
if (err) console.error(err);
});
// Send presenter data on current event
this.oscClient.send(add + '/presenter', presenter, (err) => {
if (err) console.error(err);
});
break;
case 'play':
// Play Message
this.oscClient.send(add, play, (err) => {
if (err) console.error(err);
});
break;
case 'pause':
// Pause Message
this.oscClient.send(add, pause, (err) => {
if (err) console.error(err);
});
break;
case 'stop':
// Stop Message
this.oscClient.send(add, stop, (err) => {
if (err) console.error(err);
});
break;
case 'prev':
this.oscClient.send(add, prev, (err) => {
if (err) console.error(err);
});
break;
case 'next':
this.oscClient.send(add, next, (err) => {
if (err) console.error(err);
});
break;
case 'reload':
this.oscClient.send(add, reload, (err) => {
if (err) console.error(err);
});
break;
default:
break;
}
}
/**
* @description Shutdown process
*/
shutdown() {
console.log('Closing socket server');
console.log('Shutting down integrations')
console.log('... Closing socket server');
this.io.close();
console.log('... Closing osc server');
this.osc.shutdown();
}
// send current timer
broadcastTimer() {
// through websockets
this.io.emit('timer', this.getTimes());
// through OSC, only if running
if (this.state === 'start' || this.state === 'roll') {
this.sendOSC('time');
this.sendOSC('overtime');
this.sendOSC('titles');
}
}
// broadcast state
@@ -230,11 +180,239 @@ export class EventTimer extends Timer {
this.io.emit(address, payload);
}
/**
* @description Interface for triggering playback actions
* @param {string} action - state to be triggered
* @returns {boolean} Whether action was called
*/
trigger(action) {
// Todo: reply should come from status change
let reply = true;
switch (action) {
case 'start':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.start();
this.runCycle();
break;
case 'pause':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.pause();
this.runCycle();
break;
case 'stop':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.stop();
this.runCycle();
break;
case 'roll':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.roll();
this.runCycle();
break;
case 'previous':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.previous();
this.runCycle();
break;
case 'next':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.next();
this.runCycle();
break;
case 'unload':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.unload();
this.runCycle();
break;
case 'reload':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.reload();
this.runCycle();
break;
case 'onAir':
// Call action
this.setonAir(true);
break;
case 'offAir':
// Call action and force update
this.setonAir(false);
break;
default:
// Error, disable flag
console.log('ERROR: Unhandled action triggered')
reply = false;
break;
}
return reply;
}
/**
* @description State machine checks what actions need to
* happen at every app cycle
*/
runCycle() {
const h = this.httpMessages?.messages;
let httpMessage = null;
switch (this.ontimeCycle) {
case "idle":
break;
case "armed":
// if we come from roll, see if we can start
if (this.state === 'roll') {
this.update();
}
break;
case "onLoad":
// broadcast change
this.broadcastState();
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onLoad?.url !== '') {
httpMessage = h?.onLoad?.url;
}
}
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
break;
case "onStart":
// broadcast current state
this.broadcastState();
// send OSC if there is something running
// _finish at is only set when an event is loaded
if (this._finishAt > 0) {
this.osc.send(this.osc.implemented.play);
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onStart?.url !== '') {
httpMessage = h?.onStart?.url;
}
}
// update lifecycle: onUpdate
this.ontimeCycle = this.cycleState.onUpdate;
break;
case "onUpdate":
// call update
this.update();
// broadcast current state
this.broadcastTimer();
// through OSC, only if running
if (this.state === 'start' || this.state === 'roll') {
if (this.current != null && this.secondaryTimer == null) {
this.osc.send(this.osc.implemented.time, this.timeTag);
this.osc.send(this.osc.implemented.overtime, this.current > 0 ? 0 : 1);
this.osc.send(this.osc.implemented.title, this.titles?.titleNow || '');
}
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onUpdate?.url !== '') {
httpMessage = h?.onUpdate?.url;
}
}
break;
case "onPause":
// broadcast current state
this.broadcastState();
// send OSC
this.osc.send(this.osc.implemented.pause);
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onPause?.url !== '') {
httpMessage = h?.onPause?.url;
}
}
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
break;
case "onStop":
// broadcast change
this.broadcastState();
// send OSC if something was actually stopped
if (this.prevCycle === this.cycleState.onUpdate) {
this.osc.send(this.osc.implemented.stop);
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onStop?.url !== '') {
httpMessage = h?.onStop?.url;
}
}
// update lifecycle: idle
this.ontimeCycle = this.cycleState.idle;
break;
case "onFinish":
console.log('onFinish')
// broadcast change
this.broadcastState(false);
// finished an event
this.osc.send(this.osc.implemented.finished);
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onFinish?.url !== '') {
httpMessage = h?.onFinish?.url;
}
}
// update lifecycle: onUpdate
this.ontimeCycle = this.cycleState.onUpdate;
break;
default:
console.log(`ERROR: Unhandled cycle: ${this.ontimeCycle}`)
}
// send http message if any
if (httpMessage != null) {
const v = {
'$timer': this.timeTag,
'$title': this.titles.titleNow,
'$presenter': this.titles.presenterNow,
'$subtitle': this.titles.subtitleNow,
'$next-title': this.titles.titleNext,
'$next-presenter': this.titles.presenterNext,
'$next-subtitle': this.titles.subtitleNext,
}
const m = cleanURL(replacePlaceholder(httpMessage, v));
this.http.send(m);
}
// update
this.update();
// reset cycle
this.prevCycle = this.ontimeCycle;
}
update() {
// if there is nothing selected, update clock
const now = this._getCurrentTime();
// if there is nothing selected, update only clock
if (this.selectedEventId == null && this.state !== 'roll') {
// if we are not updating, send the timers
if (this.ontimeCycle !== this.cycleState.onUpdate) {
this.clock = now;
this.broadcastThis('timer', {
clock: now,
@@ -244,81 +422,59 @@ export class EventTimer extends Timer {
expectedFinish: this._getExpectedFinish(),
startedAt: this._startedAt,
});
return;
}
// only implement roll here
if (this.state !== 'roll') {
super.update();
} else {
// update timer as usual
this.clock = now;
if (this.selectedEventId && this.current > 0) {
// something is running, update
this.current = this._finishAt - now;
} else if (this.secondaryTimer > 0) {
// waiting to start, update secondary
this.secondaryTimer = this._secondaryTarget - now;
// Have we skipped onStart?
if (this.state === 'start' || this.state === 'roll') {
if (this.ontimeCycle === this.cycleState.armed) {
// update lifecycle: onStart
this.ontimeCycle = this.cycleState.onStart;
this.runCycle();
}
}
// update default functions
super.update();
if (this._finishedFlag) {
// update lifecycle: onFinish and call cycle
this.ontimeCycle = this.cycleState.onFinish;
this._finishedFlag = false;
this.runCycle();
}
// only implement roll here, rest implemented in super
if (this.state === 'roll') {
const u = {
selectedEventId: this.selectedEventId,
current: this.current,
// safeguard on midnight rollover
_finishAt: this._finishAt >= this._startedAt ? this._finishAt : this._finishAt + DAY_TO_MS,
clock: this.clock,
secondaryTimer: this.secondaryTimer,
_secondaryTarget: this._secondaryTarget,
}
// look for event if none is loaded
const currentRunning = this.current <= 0 && this.current !== null;
const secondaryRunning =
this.secondaryTimer <= 0 && this.secondaryTimer !== null;
const {updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished} = updateRoll(u);
if (currentRunning) {
// finished an event
this.sendOSC('finished');
this._finishedFlag = true;
this.current = updatedTimer;
this.secondaryTimer = updatedSecondaryTimer;
if (isFinished) {
// update lifecycle: onFinish
this.ontimeCycle = this.cycleState.onFinish;
this.runCycle();
}
if (currentRunning || secondaryRunning) {
// look for events
if (doRollLoad) {
this.rollLoad();
// broadcast state without recalculating timer
this.broadcastState(false);
}
}
// if event is finished
if (
this.current <= 0 &&
(this.state === 'start' || this.state === 'roll') &&
!this._finishedFlag
) {
if (this._finishedAt === null) {
this._finishedAt = now;
}
this.sendOSC('finished');
this._finishedFlag = true;
}
}
_setterManager(action, payload) {
switch (action) {
/*******************************************/
// playstate
case 'set-playstate':
// check state is defined
if (payload === 'start') this.start();
else if (payload === 'pause') this.pause();
else if (payload === 'stop') this.stop();
else if (payload === 'previous') this.previous();
else if (payload === 'next') this.next();
else if (payload === 'reload') this.reload();
else if (payload === 'unload') this.unload();
else if (payload === 'roll') this.roll();
// TODO: Cleanup
// here tdo this.broadcastState;
// remove broadcast from functions
this.broadcastThis('playstate', this.state);
this.broadcastThis('selected-id', this.selectedEventId);
this.broadcastThis('titles', this.titles);
break;
/*******************************************/
// Presenter message
case 'set-presenter-text':
@@ -423,7 +579,7 @@ export class EventTimer extends Timer {
/*******************************************/
// playstate
socket.on('set-playstate', (data) => {
this._setterManager('set-playstate', data);
this.trigger(data);
});
socket.on('get-playstate', () => {
@@ -453,6 +609,10 @@ export class EventTimer extends Timer {
socket.emit('selected-id', this.selectedEventId);
});
socket.on('get-numevents', () => {
socket.emit('numevents', this.numEvents);
});
socket.on('get-next-id', () => {
socket.emit('next-id', this.nextEventId);
});
@@ -539,8 +699,11 @@ export class EventTimer extends Timer {
this._eventlist = [];
this.numEvents = 0;
// broadcast change
this.broadcastState();
// update lifecycle: onStop
this.ontimeCycle = this.cycleState.onStop;
// update clients
this.broadcastThis('numevents', this.numEvents);
}
setupWithEventList(eventlist) {
@@ -559,6 +722,12 @@ export class EventTimer extends Timer {
// load first event
this.loadEvent(0);
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
updateEventList(eventlist) {
@@ -601,7 +770,11 @@ export class EventTimer extends Timer {
this.loadEvent(eventIndex, type);
}
this.broadcastState();
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
updateSingleEvent(id, entry) {
@@ -640,7 +813,11 @@ export class EventTimer extends Timer {
console.log(error);
}
this.broadcastState();
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
deleteId(eventId) {
@@ -670,37 +847,53 @@ export class EventTimer extends Timer {
this._loadTitlesNow();
}
this.broadcastState();
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
/**
* @description loads an event with a given Id
* @param eventId - ID of event in eventlist
*/
loadEventById(eventId) {
const eventIndex = this._eventlist.findIndex((e) => e.id === eventId);
if (eventIndex === -1) return;
this.pause();
this.loadEvent(eventIndex, 'load', true);
// run cycle
this.runCycle();
}
/**
* @description loads an event with a given index
* @param eventIndex - Index of event in eventlist
*/
loadEventByIndex(eventIndex) {
if (eventIndex === -1 || eventIndex > this.numEvents) return;
this.pause();
this.loadEvent(eventIndex, 'load', true);
// run cycle
this.runCycle();
}
// Loads a given event
// load timers
// load selectedEventIndex
// load titles
loadEvent(eventIndex, type = 'load', broadcastChange = 'false') {
loadEvent(eventIndex, type = 'load') {
const e = this._eventlist[eventIndex];
if (e == null) return;
const start = e.timeStart == null || e.timeStart === '' ? 0 : e.timeStart;
let end = e.timeEnd == null || e.timeEnd === '' ? 0 : e.timeEnd;
// in case the end is earlier than start, we assume is the day after
if (end < start) end += DAYMS;
if (end < start) end += DAY_TO_MS;
// time stuff changes on wheter we keep the running clock
// time stuff changes on whether we keep the running clock
if (type === 'load') {
this._resetTimers();
@@ -724,9 +917,8 @@ export class EventTimer extends Timer {
// look for event after
this._loadTitlesNext();
if (broadcastChange)
// broadcast current state
this.broadcastState();
// update lifecycle: onLoad
this.ontimeCycle = this.cycleState.onLoad;
}
_loadTitlesNow() {
@@ -980,54 +1172,55 @@ export class EventTimer extends Timer {
}
start() {
// do we need to change
if (this.state === 'start') return;
// if there is nothing selected, no nothing
if (this.selectedEventId == null) return;
// call super
super.start();
// broadcast current state
this.broadcastState();
// send OSC
this.sendOSC('play');
// update lifecycle: onStart
this.ontimeCycle = this.cycleState.onStart;
}
pause() {
// do we need to change
if (this.state === 'pause') return;
// if there is nothing selected, no nothing
if (this.selectedEventId == null) return;
// call super
super.pause();
// broadcast current state
this.broadcastState();
// send OSC
this.sendOSC('pause');
// update lifecycle: onPause
this.ontimeCycle = this.cycleState.onPause;
}
stop() {
// do we need to change
if (this.state === 'stop') return;
// call super
super.stop();
// broadcast current state
this.broadcastState();
// send OSC
this.sendOSC('stop');
// update lifecycle: onPause
this.ontimeCycle = this.cycleState.onStop;
}
increment(amount) {
// call super
super.increment(amount);
// broadcast current state
this.broadcastState();
// run cycle
this.runCycle();
}
rollLoad() {
const now = this._getCurrentTime();
let prevLoaded = this.selectedEventId;
// maybe roll has already been loaded
if (this.secondaryTimer === null) {
@@ -1103,18 +1296,31 @@ export class EventTimer extends Timer {
if (publicIndex !== null) {
this._loadThisTitles(this._eventlist[publicIndex], 'now-public');
}
if (prevLoaded !== this.selectedEventId) {
// update lifecycle: onLoad
this.ontimeCycle = this.cycleState.onLoad;
// ensure we go through onLoad cycle
this.runCycle();
}
}
roll() {
// do we need to change
if (this.state === 'roll') return;
if (this.numEvents === 0 || this.numEvents == null) return;
// set state
this.state = 'roll';
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
// load into event
this.rollLoad();
// broadcast change
this.broadcastState();
}
@@ -1122,6 +1328,9 @@ export class EventTimer extends Timer {
// check that we have events to run
if (this.numEvents < 1) return;
// maybe this is the first event?
if (this.selectedEventIndex === 0) return;
// if there is no event running, go to first
if (this.selectedEventIndex == null) {
this.loadEvent(0);
@@ -1129,7 +1338,7 @@ export class EventTimer extends Timer {
}
// send OSC
this.sendOSC('prev');
this.osc.send(this.osc.implemented.previous);
// change playstate
this.pause();
@@ -1145,6 +1354,9 @@ export class EventTimer extends Timer {
// check that we have events to run
if (this.numEvents < 1) return;
// maybe this is the last event?
if (this.selectedEventIndex === this.numEvents - 1) return;
// if there is no event running, go to first
if (this.selectedEventIndex == null) {
this.loadEvent(0);
@@ -1152,7 +1364,7 @@ export class EventTimer extends Timer {
}
// send OSC
this.sendOSC('next');
this.osc.send(this.osc.implemented.next);
// change playstate
this.pause();
@@ -1173,16 +1385,21 @@ export class EventTimer extends Timer {
// reset selected
this._resetSelection();
// broadcast state
this.broadcastState();
// reset playstate
this.stop();
}
reload() {
// reset playstate
if (this.numEvents === 0 || this.numEvents == null) return;
// change playstate
this.pause();
// send OSC
this.sendOSC('reload');
this.osc.send(this.osc.implemented.reload);
// reload data
this.loadEvent(this.selectedEventIndex);
+46 -11
View File
@@ -24,11 +24,35 @@ export class Timer {
constructor() {}
// call setup separately
setupWithSeconds(seconds, autoStart = false) {
// aux
const now = this._getCurrentTime();
this.clock = now;
// populate targets
this.duration = seconds * 1000;
this._finishAt = now + seconds * 1000;
// start counting
this._startedAt = now;
if (autoStart) {
this.state = 'start';
} else {
this._pausedAt = now;
this._pausedInterval = 0;
}
this._pausedTotal = 0;
this.update();
}
// update()
update() {
// get current time
const now = this._getCurrentTime();
this.clock = now;
let checkFinish = false;
// check playstate
switch (this.state) {
@@ -40,6 +64,8 @@ export class Timer {
this.current =
this._startedAt + this.duration + this._pausedTotal - now;
// enable flag
checkFinish = true;
break;
case 'pause':
// update paused time
@@ -48,28 +74,37 @@ export class Timer {
if (this._startedAt != null) {
// update current timer
this.current =
this._startedAt +
this.duration +
this._pausedTotal +
this._pausedInterval -
now;
this._startedAt
+ this.duration
+ this._pausedTotal
+ this._pausedInterval
- now;
}
// enable flag
checkFinish = true;
break;
case 'stop':
// nothing here yet
break;
default:
console.error('Timer: no playstate on update call', this.state);
break;
}
if (checkFinish) {
// is event finished?
const isTimeOver = this.current <= 0;
const isUpdating = (this.state !== 'pause');
if (isTimeOver && isUpdating && this._finishedAt == null) {
if (this._finishedAt === null) this._finishedAt = now;
this._finishedFlag = true;
}
}
}
// helpers
static toSeconds(millis) {
if (millis == null) return null;
return Math.ceil(millis * 0.001);
}
// get current time in epoc
@@ -148,7 +183,7 @@ export class Timer {
// do we need to change
if (this.state === 'start') return;
else if (this._startedAt == null) {
// it hasnt started yet
// it hasn't started yet
const now = this._getCurrentTime();
// set start time as now
this._startedAt = now;
+187 -28
View File
@@ -1,22 +1,29 @@
import {DAYMS, getSelectionByRoll, normaliseEndTime, sortArrayByProperty} from '../classUtils.js';
import {
DAY_TO_MS,
getSelectionByRoll,
replacePlaceholder,
normaliseEndTime,
sortArrayByProperty,
updateRoll
} from '../classUtils.js';
// test sortArrayByProperty()
describe('sort simple arrays of objects', () => {
it('sort array 1-5', () => {
const arr1 = [
{ timeStart: 1 },
{ timeStart: 5 },
{ timeStart: 3 },
{ timeStart: 2 },
{ timeStart: 4 },
{timeStart: 1},
{timeStart: 5},
{timeStart: 3},
{timeStart: 2},
{timeStart: 4},
];
const arr1Expected = [
{ timeStart: 1 },
{ timeStart: 2 },
{ timeStart: 3 },
{ timeStart: 4 },
{ timeStart: 5 },
{timeStart: 1},
{timeStart: 2},
{timeStart: 3},
{timeStart: 4},
{timeStart: 5},
];
const sorted = sortArrayByProperty(arr1, 'timeStart');
@@ -25,21 +32,21 @@ describe('sort simple arrays of objects', () => {
it('sort array 1-5 with null', () => {
const arr1 = [
{ timeStart: 1 },
{ timeStart: 5 },
{ timeStart: 3 },
{ timeStart: 2 },
{ timeStart: 4 },
{ timeStart: null },
{timeStart: 1},
{timeStart: 5},
{timeStart: 3},
{timeStart: 2},
{timeStart: 4},
{timeStart: null},
];
const arr1Expected = [
{ timeStart: null },
{ timeStart: 1 },
{ timeStart: 2 },
{ timeStart: 3 },
{ timeStart: 4 },
{ timeStart: 5 },
{timeStart: null},
{timeStart: 1},
{timeStart: 2},
{timeStart: 3},
{timeStart: 4},
{timeStart: 5},
];
const sorted = sortArrayByProperty(arr1, 'timeStart');
@@ -244,7 +251,6 @@ describe('test that roll loads selection in right order', () => {
});
// test getSelectionByRoll()
describe('test that roll behaviour with overlapping times', () => {
const eventlist = [
{
@@ -384,6 +390,68 @@ describe('test that roll behaviour with overlapping times', () => {
});
});
// test replacePlaceholder()
describe('test that it replaces data correctly', () => {
const values = {
$timer: "timer",
$title: "title",
$presenter: "presenter",
$subtitle: "subtitle",
"$next-title": "next title",
"$next-presenter": "next presenter",
"$next-subtitle": "next subtitle"
};
it('replaces timer', () => {
const test = '___1232132 $timer';
const expected = '___1232132 timer';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces title', () => {
const test = '___1232132 $title';
const expected = '___1232132 title';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces presenter', () => {
const test = '___1232132 $presenter';
const expected = '___1232132 presenter';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces subtitle', () => {
const test = '___1232132 $subtitle';
const expected = '___1232132 subtitle';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces next next title', () => {
const test = '___1232132 $next-title';
const expected = '___1232132 next title';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces next presenter', () => {
const test = '___1232132 $next-presenter';
const expected = '___1232132 next presenter';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces next subtitle', () => {
const test = '___1232132 $next-subtitle';
const expected = '___1232132 next subtitle';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
});
// test getSelectionByRoll() on issue #58
describe('test that roll behaviour multi day event edge cases', () => {
@@ -407,8 +475,8 @@ describe('test that roll behaviour multi day event edge cases', () => {
timers: {
_startedAt: eventlist[0].timeStart,
_finishAt: eventlist[0].timeEnd,
current: eventlist[0].timeEnd + DAYMS - now,
duration: DAYMS - eventlist[0].timeStart + eventlist[0].timeEnd,
current: eventlist[0].timeEnd + DAY_TO_MS - now,
duration: DAY_TO_MS - eventlist[0].timeStart + eventlist[0].timeEnd,
},
timeToNext: null,
};
@@ -454,10 +522,10 @@ test('test typical scenarios', () => {
expect(normaliseEndTime(t1.start, t1.end)).toBe(t1_expected);
const t2 = {
start: 10+DAYMS,
start: 10 + DAY_TO_MS,
end: 20,
}
const t2_expected = 20+DAYMS;
const t2_expected = 20 + DAY_TO_MS;
expect(normaliseEndTime(t2.start, t2.end)).toBe(t2_expected);
@@ -470,3 +538,94 @@ test('test typical scenarios', () => {
expect(normaliseEndTime(t3.start, t3.end)).toBe(t3_expected);
});
// test updateRoll()
describe('typical scenarios', () => {
it('it updates running events correctly', () => {
const timers = {
selectedEventId: 1,
current: 10,
_finishAt: 15,
clock: 11,
secondaryTimer: null,
_secondaryTarget: null,
};
const expected = {
updatedTimer: timers._finishAt - timers.clock,
updatedSecondaryTimer: null,
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
// test that it can jump time
timers._finishAt = 1000;
timers.clock = 600;
expected.updatedTimer = timers._finishAt - timers.clock;
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('it updates secondary timer', () => {
const timers = {
selectedEventId: null,
current: null,
_finishAt: null,
clock: 11,
secondaryTimer: 1,
_secondaryTarget: 15,
};
const expected = {
updatedTimer: null,
updatedSecondaryTimer: timers._secondaryTarget - timers.clock,
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('flags an event end', () => {
const timers = {
selectedEventId: 1,
current: 10,
_finishAt: 11,
clock: 12,
secondaryTimer: null,
_secondaryTarget: null,
};
const expected = {
updatedTimer: timers._finishAt - timers.clock,
updatedSecondaryTimer: null,
doRollLoad: true,
isFinished: true,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('secondary events do not trigger event ends', () => {
const timers = {
selectedEventId: null,
current: null,
_finishAt: null,
clock: 16,
secondaryTimer: 1,
_secondaryTarget: 15,
};
const expected = {
updatedTimer: null,
updatedSecondaryTimer: timers._secondaryTarget - timers.clock,
doRollLoad: true,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
});
@@ -0,0 +1,137 @@
import {EventTimer} from "../EventTimer";
import http from 'http';
import express from "express";
// Create server
const app = express();
const server = http.createServer(app);
// necessary config
const timerConfig = {refresh: 1000};
beforeEach(async () => {
server.listen(0, '0.0.0.0');
});
afterEach(async () => {
await server.close();
});
test('object instantiates correctly', async () => {
const t = new EventTimer(server, timerConfig);
// it contains everything from Timer
expect(t.clock).toBeNull();
expect(t.duration).toBeNull();
expect(t.current).toBeNull();
expect(t.timeTag).toBeNull();
expect(t.secondaryTimer).toBeNull();
expect(t._secondaryTarget).toBeNull();
expect(t._finishAt).toBeNull();
expect(t._finishedAt).toBeNull();
expect(t._finishedFlag).toBeFalsy();
expect(t._startedAt).toBeNull();
expect(t._pausedAt).toBeNull();
expect(t._pausedInterval).toBeNull();
expect(t._pausedTotal).toBeNull();
expect(t.state).toBe('stop');
// and its own properties
expect(t.ontimeCycle).toBe('idle');
expect(t.prevCycle).toBeNull();
expect(t.lastUpdate).toBeNull();
expect(t.io).not.toBeNull();
expect(t.osc).toBeNull();
expect(t.http).toBeNull();
expect(t._numClients).toBe(0);
expect(t._interval).not.toBeNull();
expect(t.presenter).toStrictEqual({text: '', visible: false});
expect(t.public).toStrictEqual({text: '', visible: false});
expect(t.lower).toStrictEqual({text: '', visible: false});
expect(t.lower).toStrictEqual({text: '', visible: false});
const expectTitlesPublic = {
titleNow: null,
subtitleNow: null,
presenterNow: null,
titleNext: null,
subtitleNext: null,
presenterNext: null,
};
const expectTitles = {
...expectTitlesPublic,
noteNow: null,
noteNext: null,
};
expect(t.titlesPublic).toStrictEqual(expectTitlesPublic);
expect(t.titles).toStrictEqual(expectTitles);
expect(t.selectedEventIndex).toBeNull();
expect(t.selectedEventId).toBeNull();
expect(t.nextEventId).toBeNull();
expect(t.selectedPublicEventId).toBeNull();
expect(t.nextPublicEventId).toBeNull();
expect(t.numEvents).toBe(0);
expect(t._eventlist).toBeNull();
expect(t.onAir).toBeFalsy();
});
describe('test triggers behaviour', () => {
const t = new EventTimer(server, timerConfig);
it('ignores bad commands', () => {
const success = t.trigger('test');
expect(success).toBeFalsy();
})
it('does not allow triggering events with an empty list', () => {
expect(t.numEvents).toBe(0);
expect(t.trigger('start')).toBeFalsy();
expect(t.trigger('pause')).toBeFalsy();
expect(t.trigger('stop')).toBeFalsy();
expect(t.trigger('roll')).toBeFalsy();
expect(t.trigger('previous')).toBeFalsy();
expect(t.trigger('next')).toBeFalsy();
expect(t.trigger('reload')).toBeFalsy();
expect(t.onAir).toBeFalsy();
expect(t.trigger('onAir')).toBeTruthy();
expect(t.onAir).toBeTruthy();
expect(t.trigger('offAir')).toBeTruthy();
expect(t.onAir).toBeFalsy();
});
it('...and is consistent by calling the class methods', () => {
expect(t.numEvents).toBe(0);
expect(t.state).toBe('stop');
t.start();
expect(t.state).toBe('stop');
t.pause();
expect(t.state).toBe('stop');
t.stop();
expect(t.state).toBe('stop');
t.roll();
expect(t.state).toBe('stop');
t.previous();
expect(t.state).toBe('stop');
t.next();
expect(t.state).toBe('stop');
t.reload();
expect(t.state).toBe('stop');
});
})
+81 -6
View File
@@ -1,13 +1,17 @@
export const DAYMS = 86400000;
/**
* Utility variable: 24 hour in milliseconds .
* @type {number}
*/
export const DAY_TO_MS = 86400000;
/**
* @description handle events that span over midnight
* @param {num} start - When does the event start
* @param {num} end - When does the event end
* @returns {num} normalised time
* @param {number} start - When does the event start
* @param {number} end - When does the event end
* @returns {number} normalised time
*/
export const normaliseEndTime = (start, end) => (end < start ? end + DAYMS : end);
export const normaliseEndTime = (start, end) => (end < start ? end + DAY_TO_MS : end);
/**
* @description Sorts an array of objects by given property
@@ -22,6 +26,21 @@ export const sortArrayByProperty = (arr, property) => {
});
};
/**
* @description Replaces placeholder variables in string with given data
* @param {string} str - string to analyse
* @param {object} values - map of variables: values to use
* @returns {string} finished string
*/
export const replacePlaceholder = (str, values) => {
for (let [k, v] of Object.entries(values)) {
str = str.replace(k, v);
console.log(k, v);
}
return str;
};
/**
* @description Used in roll mode, returns selection variables from array
* @param {array} arr - event list
@@ -130,3 +149,59 @@ export const getSelectionByRoll = (arr, now) => {
};
};
/**
* @description Implements update functions for roll mode
* @param {object} currentTimers
* @param {object} currentTimers.selectedEventId - Id of currently selected event
* @param {object} currentTimers.current - Running timer
* @param {object} currentTimers._finishAt - Expected finish time
* @param {object} currentTimers.clock - time now
* @param {object} currentTimers.secondaryTimer - secondary timer
* @param {object} currentTimers._secondaryTarget - finish time of secondary timer
* @returns {object} object with selection variables
*/
export const updateRoll = (currentTimers) => {
const {selectedEventId,current,_finishAt,clock,secondaryTimer,_secondaryTarget} = currentTimers;
// timers
let updatedTimer = current;
let updatedSecondaryTimer = secondaryTimer;
// whether rollLoad should be called
let doRollLoad = false;
// whether runCycle should be called
let isFinished = false;
if (selectedEventId && current >= 0) {
// if we have something selected and a timer, we are running
// this is true because roll never goes into negative times
// update timer
updatedTimer = _finishAt - clock;
if (updatedTimer < 0) {
isFinished = true;
}
console.log(updatedTimer, isFinished, _finishAt)
} else if (secondaryTimer >= 0) {
// if secondaryTimer is running we are in waiting to roll
// update secondary
updatedSecondaryTimer = _secondaryTarget - clock;
}
// if nothing is running, we need to find out if
// a) we just finished an event (finished was set to true)
// b) we need to look for events
// this could be caused by a secondary timer or event finished
const secondaryRunning =
updatedSecondaryTimer <= 0 && updatedSecondaryTimer != null;
if (isFinished || secondaryRunning) {
// look for events
doRollLoad = true;
}
return {updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished};
}
+52
View File
@@ -0,0 +1,52 @@
/** Class contains logic towards outgoing HTTP communications. */
import * as http from 'http';
export class HTTPIntegration {
constructor() {
// nothing to do here
}
/**
* @description Initializes oscClient
* @param {object} httpConfig - Http configurations options
*/
init(httpConfig) {
}
/**
* @description Sends http get request from predefined messages
* @param {string} path - complete http path
*/
async send(path) {
if (path == null) {
console.log('HTTP ERROR: Message undefined');
return;
}
const options = new URL(path);
let str = '';
const req = http.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', function (chunk) {
str += chunk;
});
res.on('end', function () {
console.log(str);
});
})
req.on('error', error => {
console.error(error)
})
req.end()
}
shutdown() { /* Nothing to shutdown */ }
}
+107
View File
@@ -0,0 +1,107 @@
/** Class contains logic towards outgoing OSC communications. */
import {Client, Message} from 'node-osc';
export class OSCIntegration {
ADDRESS = '/ontime';
constructor() {
// OSC Client
this.oscClient = null;
}
/**
* @description Returns list of implemented messages
* @returns {object} implemented messages
*/
get implemented() {
return {
play: 'play',
pause: 'pause',
stop: 'stop',
previous: 'prev',
next: 'next',
reload: 'reload',
finished: 'finished',
time: 'time',
overtime: 'overtime',
title: 'title',
presenter:'presenter',
}
}
/**
* @description Initializes oscClient
* @param {object} oscConfig - oscClient configuration options
* @param {string} oscConfig.ip - oscClient object
* @param {number} oscConfig.port - OSC Destination Port
*/
init(oscConfig) {
const {ip, port} = oscConfig;
try {
this.oscClient = new Client(ip, port);
console.log(`Initialised OSC Client at ${ip}:${port}`);
} catch (error) {
this.oscClient = null;
console.log(`Failed initialising OSC Client: ${error}`);
}
}
/**
* @description Sends osc from predefined messages
* @param {string} messageType - message to be sent
* @param {string} [payload] - optional payload required in some message types
*/
async send(messageType, payload) {
if (this.oscClient == null) {
console.log('OSC ERROR: Client not initialised');
return;
}
if (messageType == null) {
console.log('OSC ERROR: Message undefined');
return;
}
// only specify special cases
switch (payload) {
case 'overtime':
// Whether timer is negative
this.oscClient.send(`${this.ADDRESS}/overtime`, payload, (err) => {
if (err) console.error(err);
});
break;
case 'title':
if (payload != null && payload !== "") {
// Send Title of current event
this.oscClient.send(`${this.ADDRESS}/title`, payload, (err) => {
if (err) console.error(err);
});
}
break;
case 'presenter':
if (payload != null && payload !== "") {
// Send presenter data on current event
this.oscClient.send(`${this.ADDRESS}/presenter`, payload, (err) => {
if (err) console.error(err);
});
}
break;
default:
// catch all for messages, allows to add new messages
// but should be used with the integrations definition
const message = new Message(`${this.ADDRESS}/${messageType}`)
if (payload != null) message.append(payload)
this.oscClient.send(message, (err) => {
if (err) console.error(err);
});
break;
}
}
shutdown() {
// Shutdown client object
this.oscClient.close();
this.oscClient = null;
}
}
+7 -1
View File
@@ -11,7 +11,13 @@ export const config = {
},
osc: {
port: 8888,
ipOut: '127.0.0.1',
portOut: 9999,
targetIP: '127.0.0.1',
enabled: true,
},
http: {
user: '',
pwd: '',
enabled: true,
},
};
+7 -7
View File
@@ -47,32 +47,32 @@ export const initiateOSC = (config) => {
case 'start':
case 'play':
console.log('calling play');
global.timer.start();
global.timer.trigger('start');
break;
case 'pause':
console.log('calling pause');
global.timer.pause();
global.timer.trigger('pause');
break;
case 'prev':
console.log('calling prev');
global.timer.previous();
global.timer.trigger('previous');
break;
case 'next':
console.log('calling next');
global.timer.next();
global.timer.trigger('next');
break;
case 'unload':
case 'stop':
console.log('calling unload');
global.timer.unload();
global.timer.trigger('unload');
break;
case 'reload':
console.log('calling reload');
global.timer.reload();
global.timer.trigger('reload');
break;
case 'roll':
console.log('calling roll');
global.timer.roll();
global.timer.trigger('roll');
break;
case 'delay':
console.log('calling delay with', args);
+9 -17
View File
@@ -9,14 +9,6 @@ import {
block as blockDef,
} from '../models/eventsDefinition.js';
function _getEventsCount() {
return Array.from(data.events).length;
}
function _pushNew(entry) {
return data.events.push(entry).write();
}
async function _insertAt(entry, index) {
// get events
let events = data.events;
@@ -26,7 +18,7 @@ async function _insertAt(entry, index) {
// Remove order field from object
delete entry.order;
// Insert at beggining
// Insert at beginning
if (order === 0) {
events.unshift(entry);
}
@@ -47,7 +39,7 @@ async function _insertAt(entry, index) {
}
async function _removeById(eventId) {
data.events = Array.from(data.events).filter((e) => e.id != eventId);
data.events = Array.from(data.events).filter((e) => e.id !== eventId);
await db.write();
}
@@ -122,7 +114,7 @@ export const eventsPost = async (req, res) => {
const index = newEvent.order || 0;
// add new event in place
_insertAt(newEvent, index);
await _insertAt(newEvent, index);
// update timers
_updateTimers();
@@ -160,7 +152,7 @@ export const eventsPut = async (req, res) => {
const e = data.events[eventIndex];
data.events[eventIndex] = { ...e, ...req.body };
data.events[eventIndex].revision++;
db.write();
await db.write();
// update timer
_updateTimersSingle(eventId, req.body);
@@ -176,7 +168,7 @@ export const eventsPut = async (req, res) => {
// Returns -
export const eventsPatch = async (req, res) => {
// Code is the same as put, call that
eventsPut(req, res);
await eventsPut(req, res);
};
export const eventsReorder = async (req, res) => {
@@ -207,7 +199,7 @@ export const eventsReorder = async (req, res) => {
// save events
data.events = events;
db.write();
await db.write();
// TODO: would it be more efficient to reorder at timer?
// update timer
@@ -273,7 +265,7 @@ export const eventsApplyDelay = async (req, res) => {
// update events
data.events = events;
db.write();
await db.write();
// update timer
_updateTimers();
@@ -297,7 +289,7 @@ export const eventsDelete = async (req, res) => {
try {
// remove new event
_removeById(req.params.eventId);
await _removeById(req.params.eventId);
// update timer
_deleteTimerId(req.params.eventId);
@@ -316,7 +308,7 @@ export const eventsDeleteAll = async (req, res) => {
try {
// set with nothing
data.events = [];
db.write();
await db.write();
// update timer object
global.timer.clearEventList();
+33 -6
View File
@@ -95,9 +95,13 @@ const getNetworkInterfaces = () => {
export const getInfo = async (req, res) => {
const version = data.settings.version;
const serverPort = data.settings.serverPort;
const oscInPort = data.settings.oscInPort;
const oscOutPort = data.settings.oscOutPort;
const oscOutIP = data.settings.oscOutIP;
const osc = {
port: data.osc.port,
portOut: data.osc.portOut,
targetIP: data.osc.targetIP,
enabled: data.osc.enabled,
};
// get nif and inject localhost
const ni = getNetworkInterfaces();
@@ -108,9 +112,7 @@ export const getInfo = async (req, res) => {
networkInterfaces: ni,
version,
serverPort,
oscInPort,
oscOutPort,
oscOutIP,
osc,
});
};
@@ -132,6 +134,31 @@ export const postInfo = async (req, res) => {
}
};
// Create controller for POST request to '/ontime/osc'
// Returns -
export const getOSC = async (req, res) => {
// send object with network information
res.status(200).send(data.osc);
};
// Create controller for POST request to '/ontime/osc'
// Returns ACK message
export const postOSC = async (req, res) => {
if (!req.body) {
res.status(400).send('No object found in request');
return;
}
// TODO: validate data
try {
data.osc = { ...data.osc, ...req.body };
await db.write();
res.sendStatus(200);
} catch (error) {
res.status(400).send(error);
console.log(error);
}
};
// Create controller for POST request to '/ontime/db'
// Returns -
export const dbUpload = async (req, res) => {
+10 -21
View File
@@ -8,79 +8,68 @@ export const pbGet = async (req, res) => {
// Turns onAir flag to true
export const onAir = async (req, res) => {
console.log('Setting onAir to true');
global.timer.setonAir(true);
res.sendStatus(200);
global.timer.trigger('onAir') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/onAir'
// Turns onAir flag to true
export const offAir = async (req, res) => {
console.log('Setting onAir to false');
global.timer.setonAir(false);
res.sendStatus(200);
global.timer.trigger('offAir') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/start'
// Starts timer object
export const pbStart = async (req, res) => {
console.log('Calling start');
global.timer.start();
res.sendStatus(200);
global.timer.trigger('start') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/pause'
// Pauses timer object
export const pbPause = async (req, res) => {
console.log('Calling pause');
global.timer.pause();
res.sendStatus(200);
global.timer.trigger('pause') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/stop'
// Stops timer object
export const pbStop = async (req, res) => {
console.log('Calling stop');
global.timer.stop();
res.sendStatus(200);
global.timer.trigger('stop') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/roll'
// Sets timer object to roll mode
export const pbRoll = async (req, res) => {
console.log('Calling roll');
global.timer.roll();
res.sendStatus(501);
global.timer.trigger('roll') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/previous'
// Sets timer object to roll mode
export const pbPrevious = async (req, res) => {
console.log('Calling previous');
global.timer.previous();
res.sendStatus(200);
global.timer.trigger('previous') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/next'
// Sets timer object to roll mode
export const pbNext = async (req, res) => {
console.log('Calling next');
global.timer.next();
res.sendStatus(200);
global.timer.trigger('next') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/unload'
// Unloads any events
export const pbUnload = async (req, res) => {
console.log('Calling unload');
global.timer.unload();
res.sendStatus(200);
global.timer.trigger('unload') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/reload'
// Reloads current event
export const pbReload = async (req, res) => {
console.log('Calling reload');
global.timer.reload();
res.sendStatus(200);
global.timer.trigger('reload') ? res.sendStatus(200) : res.sendStatus(400);
};
+38 -5
View File
@@ -11,10 +11,43 @@ export const dbModelv1 = {
app: 'ontime',
version: 1,
serverPort: 4001,
oscInPort: 8888,
oscOutPort: 9999,
oscOutIP: '127.0.0.1',
oscEnabled: false,
lock: false,
lock: null,
},
osc: {
port: 8888,
portOut: 9999,
targetIP: '127.0.0.1',
enabled: true,
},
http: {
user: null,
pwd: null,
messages: {
onLoad: {
url: '',
enabled: false,
},
onStart: {
url: '',
enabled: false,
},
onUpdate: {
url: '',
enabled: false,
},
onPause: {
url: '',
enabled: false,
},
onStop: {
url: '',
enabled: false,
},
onFinish: {
url: '',
enabled: false,
},
},
enabled: true,
},
};
+1 -9
View File
@@ -15,15 +15,7 @@
"socket.io": "^4.3.1",
"universal-analytics": "^0.4.23"
},
"devDependencies": {
"eslint": "^7.26.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.23.2",
"eslint-plugin-react-hooks": "^4.2.0",
"eslint-plugin-simple-import-sort": "^7.0.0"
},
"devDependencies": {},
"scripts": {
"nodestart": "nodemon app.js",
"start": "node app.js"
+9 -1
View File
@@ -8,6 +8,8 @@ import {
getInfo,
postInfo,
dbPathToUpload,
getOSC,
postOSC,
} from '../controllers/ontimeController.js';
// create route between controller and '/ontime/db' endpoint
@@ -17,10 +19,16 @@ router.get('/db', dbDownload);
router.post('/db', uploadFile, dbUpload);
// create route between controller and '/ontime/info' endpoint
router.get('/info', uploadFile, getInfo);
router.get('/info', getInfo);
// create route between controller and '/ontime/info' endpoint
router.post('/info', postInfo);
// create route between controller and '/ontime/osc' endpoint
router.get('/osc', getOSC);
// create route between controller and '/ontime/osc' endpoint
router.post('/osc', postOSC);
// create route between controller and '/ontime/dbpath' endpoint
router.post('/dbpath', dbPathToUpload);
+9 -22
View File
@@ -6,7 +6,6 @@ import {
validateEventv1,
} from '../parser.js';
import { dbModelv1 as dbModel } from '../../models/dataModel.js';
import { describe } from 'jest-circus';
describe('test json parser with valid def', () => {
const testData = {
@@ -133,6 +132,7 @@ describe('test json parser with valid def', () => {
revision: 0,
id: '4b31',
};
expect(first).toStrictEqual(expected);
});
it('loaded event settings', () => {
@@ -192,7 +192,7 @@ describe('test parser edge cases', () => {
const parseResponse = await parseJsonv1(testData);
expect(console.log).toHaveBeenCalledWith(
'ERROR: ID colision on import, skipping'
'ERROR: ID collision on import, skipping'
);
expect(parseResponse?.events.length).toBe(1);
});
@@ -267,11 +267,7 @@ describe('test corrupt data', () => {
app: 'ontime',
version: 1,
serverPort: 4001,
oscInPort: 8888,
oscOutPort: 9999,
oscOutIP: '127.0.0.1',
oscEnabled: false,
lock: false,
lock: null,
},
};
@@ -293,11 +289,7 @@ describe('test corrupt data', () => {
app: 'ontime',
version: 1,
serverPort: 4001,
oscInPort: 8888,
oscOutPort: 9999,
oscOutIP: '127.0.0.1',
oscEnabled: false,
lock: false,
lock: null,
},
};
@@ -313,11 +305,7 @@ describe('test corrupt data', () => {
app: 'ontime',
version: 1,
serverPort: 4001,
oscInPort: 8888,
oscOutPort: 9999,
oscOutIP: '127.0.0.1',
oscEnabled: false,
lock: false,
lock: null,
},
};
@@ -430,7 +418,6 @@ describe('test makeString function', () => {
expect(converted).toBe(expected);
val = { doing: 'testing' };
expected = 'testing';
converted = makeString(val, 'fallback');
expect(converted).toBe('fallback');
});
@@ -477,8 +464,8 @@ describe('test parseExcel function', () => {
const expectedParsedEvents = [
{
timeStart: 28800000,
timeEnd: 32410000,
timeStart: 25200000,
timeEnd: 28810000,
title: 'Guest Welcome',
presenter: 'Carlos',
subtitle: 'Getting things started',
@@ -487,8 +474,8 @@ describe('test parseExcel function', () => {
type: 'event',
},
{
timeStart: 32400000,
timeEnd: 34200000,
timeStart: 28800000,
timeEnd: 30600000,
title: 'A song from the hearth',
presenter: 'Still Carlos',
subtitle: 'Derailing early',
+3 -1
View File
@@ -1,4 +1,3 @@
import { describe } from 'jest-circus';
import { excelDateStringToMillis, stringFromMillis } from '../time.js';
describe('test string to milis function', () => {
@@ -60,12 +59,15 @@ describe('test string to milis function', () => {
describe('test excel date parser', () => {
it('parses the given dates correctly', () => {
const d0 = '1899-12-30T00:00:00.000Z';
const d1 = '1899-12-30T08:00:00.000Z';
const d2 = '1899-12-30T08:30:00.000Z';
const d0Millis = 0;
const d1Millis = 28800000;
const d2Millis = 30600000;
expect(excelDateStringToMillis(d0)).toBe(d0Millis);
expect(excelDateStringToMillis(d1)).toBe(d1Millis);
expect(excelDateStringToMillis(d2)).toBe(d2Millis);
});
+36
View File
@@ -0,0 +1,36 @@
// test cleanURL()
import {cleanURL} from "../url";
describe('url is correctly formatted', () => {
it('has no leading spaces', () => {
const test = ' http://testing';
const expected = 'http://testing';
expect(cleanURL(test)).toBe(expected);
});
it('has no trailing spaces', () => {
const test = 'http://testing ';
const expected = 'http://testing';
expect(cleanURL(test)).toBe(expected);
});
it('doesnt contain spaces', () => {
const test = 'http://t e s t i n g';
const expected = 'http://t%20e%20s%20t%20i%20n%20g';
expect(cleanURL(test)).toBe(expected);
});
it('only contains allowed characters', () => {
const test = 'http://<>[]{}|\^';
const expected = 'http://';
expect(cleanURL(test)).toBe(expected);
});
it('begins with http://', () => {
const test = 'ontime.com';
const expected = 'http://ontime.com';
expect(cleanURL(test)).toBe(expected);
});
});
+66 -19
View File
@@ -16,7 +16,7 @@ export const ALLOWED_TYPES = ['JSON', 'EXCEL'];
/**
* @description Middleware function that checks file type and calls relevant parser
* @argument {string} file - reference to file
* @param {string} file - reference to file
* @return {object} - parse result message
*/
export const fileHandler = async (file) => {
@@ -82,7 +82,7 @@ export const fileHandler = async (file) => {
/**
* @description Excel array parser
* @argument {array} excelData - array with excel sheet
* @param {array} excelData - array with excel sheet
* @returns {object} - parsed object
*/
export const parseExcelv1 = async (excelData) => {
@@ -196,11 +196,12 @@ export const parseExcelv1 = async (excelData) => {
/**
* @description JSON parser function for v1 of data system
* @argument {object} jsonData - json data JSON object to be parsed
* @param {object} jsonData - json data JSON object to be parsed
* @param {boolean} [enforce=false] - flag, tells to create an object anyway
* @returns {object} - parsed object
*/
export const parseJsonv1 = async (jsonData) => {
export const parseJsonv1 = async (jsonData, enforce=false) => {
if (!jsonData || typeof jsonData !== 'object') {
console.log('ERROR: Invalid JSON format');
return -1;
@@ -213,9 +214,9 @@ export const parseJsonv1 = async (jsonData) => {
let events = [];
let ids = [];
for (const e of jsonData.events) {
// doublecheck unique ids
// double check unique ids
if (ids.indexOf(e?.id) !== -1) {
console.log('ERROR: ID colision on import, skipping');
console.log('ERROR: ID collision on import, skipping');
continue;
}
@@ -243,13 +244,17 @@ export const parseJsonv1 = async (jsonData) => {
// write to db
returnData.events = events;
console.log(`Uploaded file with ${numEntries} entries`);
} else if (enforce) {
returnData.events = [];
console.log(`Created events object in db`);
}
if ('event' in jsonData) {
console.log('Found event data, importing...');
const e = jsonData.event;
// filter known properties
const event = {
// filter known properties and write to db
returnData.event = {
...dbModelv1.event,
title: e.title || dbModelv1.event.title,
url: e.url || dbModelv1.event.url,
@@ -257,9 +262,9 @@ export const parseJsonv1 = async (jsonData) => {
backstageInfo: e.backstageInfo || dbModelv1.event.backstageInfo,
endMessage: e.endMessage || dbModelv1.event.endMessage,
};
// write to db
returnData.event = event;
} else if (enforce) {
returnData.event = dbModelv1.event;
console.log(`Created event object in db`);
}
// Settings handled partially
@@ -271,11 +276,9 @@ export const parseJsonv1 = async (jsonData) => {
if (s.app == null || s.version == null) {
console.log('ERROR: unknown app version, skipping');
} else {
let settings = {};
if (s.oscInPort) settings.oscInPort = s.oscInPort;
if (s.oscOutPort) settings.oscOutPort = s.oscOutPort;
if (s.oscOutIP) settings.oscOutIP = s.oscOutIP;
let settings = {
lock: s.lock || null,
};
// write to db
returnData.settings = {
@@ -283,6 +286,49 @@ export const parseJsonv1 = async (jsonData) => {
...settings,
};
}
} else if (enforce) {
returnData.settings = dbModelv1.settings;
console.log(`Created settings object in db`);
}
// Import OSC settings if any
if ('osc' in jsonData) {
console.log('Found OSC definition, importing...');
const s = jsonData.osc;
let osc = {};
if (s.port) osc.port = s.port;
if (s.portOut) osc.portOut = s.portOut;
if (s.targetIP) osc.targetIP = s.targetIP;
if (s.enabled) osc.enabled = s.enabled;
// write to db
returnData.osc = {
...dbModelv1.osc,
...osc,
};
} else if (enforce) {
returnData.osc = dbModelv1.osc;
console.log(`Created osc object in db`);
}
// Import HTTP settings if any
if ('http' in jsonData) {
console.log('Found HTTP definition, importing...');
const h = jsonData.osc;
let http = {};
if (h.user) http.user = h.user;
if (h.pwd) http.pwd = h.pwd;
// write to db
returnData.http = {
...dbModelv1.http,
...http,
};
} else if (enforce) {
returnData.http = dbModelv1.http;
console.log(`Created http object in db`);
}
return returnData;
@@ -292,7 +338,7 @@ export const parseJsonv1 = async (jsonData) => {
* @description Ensures variable is string, it skips object types
* @param {any} val - variable to convert
* @param {string} [fallback=''] - fallback value
* @returns {string} - value as string or fallback if not possibe
* @returns {string} - value as string or fallback if not possible
*/
export const makeString = (val, fallback = '') => {
if (typeof val === 'string') return val;
@@ -348,7 +394,7 @@ export const validateEventv1 = (eventArgs) => {
/**
* @description Delete file from system
* @argument {string} file - reference to file
* @param {string} file - reference to file
*/
const deleteFile = async (file) => {
// delete a file
@@ -361,7 +407,8 @@ const deleteFile = async (file) => {
/**
* @description Delete file from system
* @argument {string} file - reference to file
* @param {string} file - reference to file
* @returns {boolean} - whether file is valid JSON
*/
export const validateFile = (file) => {
try {
+1 -2
View File
@@ -40,9 +40,8 @@ export const stringFromMillis = (
*/
export const excelDateStringToMillis = (excelDate) => {
const date = new Date(excelDate);
if (date instanceof Date && !isNaN(date)) {
const h = date.getHours();
const h = date.getUTCHours();
const m = date.getMinutes();
const s = date.getSeconds();
+21
View File
@@ -0,0 +1,21 @@
/**
* @description Cleans given url
* @param {string} url - URL to be checked
* @returns {string} Sanitized url
*/
export const cleanURL = (url) => {
// trim whitespaces
let r = url.trim();
// clear any whitespaces
r = r.split(' ').join('%20');
// contain only allowed characters
r = r.replace(/([^\x00-\x7F]|[@\s<>\[\]{}|\\^])+/g, '')
// starts with http://
if (!r.startsWith('http://')) r = `http://${r}`
return r;
}
+9 -1367
View File
File diff suppressed because it is too large Load Diff