mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-10 18:03:47 +00:00
Merge commit master into google-sheets-lite
This commit is contained in:
@@ -3,7 +3,7 @@ import { LogOrigin, OSCSettings } from 'ontime-types';
|
||||
import { Server } from 'node-osc';
|
||||
|
||||
import { IAdapter } from './IAdapter.js';
|
||||
import { dispatchFromAdapter } from '../controllers/integrationController.js';
|
||||
import { dispatchFromAdapter, type ChangeOptions } from '../controllers/integrationController.js';
|
||||
import { logger } from '../classes/Logger.js';
|
||||
|
||||
export class OscServer implements IAdapter {
|
||||
@@ -36,12 +36,36 @@ export class OscServer implements IAdapter {
|
||||
return;
|
||||
}
|
||||
|
||||
let transformedPayload: unknown = args;
|
||||
// we need to transform the params for the change endpoint
|
||||
// OSC: ontime/change/{eventID}/{propertyName} value
|
||||
if (path === 'change') {
|
||||
if (params.length < 2) {
|
||||
logger.error(LogOrigin.Rx, 'OSC IN: No params provided for change');
|
||||
return;
|
||||
}
|
||||
|
||||
if (args === undefined) {
|
||||
logger.error(LogOrigin.Rx, 'OSC IN: No valid payload provided for change');
|
||||
return;
|
||||
}
|
||||
|
||||
const eventId = params[0];
|
||||
const property = params[1];
|
||||
const value: string | number | boolean = args as string | number | boolean;
|
||||
|
||||
transformedPayload = {
|
||||
eventId,
|
||||
property,
|
||||
value,
|
||||
} satisfies ChangeOptions;
|
||||
}
|
||||
|
||||
try {
|
||||
const reply = dispatchFromAdapter(
|
||||
path,
|
||||
{
|
||||
payload: args,
|
||||
params,
|
||||
payload: transformedPayload,
|
||||
},
|
||||
'osc',
|
||||
);
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
import { LogOrigin } from 'ontime-types';
|
||||
|
||||
import { WebSocket, WebSocketServer } from 'ws';
|
||||
import type { Server } from 'http';
|
||||
|
||||
import getRandomName from '../utils/getRandomName.js';
|
||||
import { IAdapter } from './IAdapter.js';
|
||||
@@ -43,7 +44,7 @@ export class SocketServer implements IAdapter {
|
||||
this.wss = null;
|
||||
}
|
||||
|
||||
init(server) {
|
||||
init(server: Server) {
|
||||
this.wss = new WebSocketServer({ path: '/ws', server });
|
||||
|
||||
this.wss.on('connection', (ws) => {
|
||||
|
||||
+22
-12
@@ -1,9 +1,9 @@
|
||||
import { LogOrigin, OSCSettings } from 'ontime-types';
|
||||
import { HttpSettings, LogOrigin, OSCSettings } from 'ontime-types';
|
||||
|
||||
import 'dotenv/config';
|
||||
import express from 'express';
|
||||
import expressStaticGzip from 'express-static-gzip';
|
||||
import http from 'http';
|
||||
import http, { type Server } from 'http';
|
||||
import cors from 'cors';
|
||||
|
||||
// import utils
|
||||
@@ -29,6 +29,7 @@ import { eventLoader } from './classes/event-loader/EventLoader.js';
|
||||
import { integrationService } from './services/integration-service/IntegrationService.js';
|
||||
import { logger } from './classes/Logger.js';
|
||||
import { oscIntegration } from './services/integration-service/OscIntegration.js';
|
||||
import { httpIntegration } from './services/integration-service/HttpIntegration.js';
|
||||
import { populateStyles } from './modules/loadStyles.js';
|
||||
import { eventStore, getInitialPayload } from './stores/EventStore.js';
|
||||
import { PlaybackService } from './services/PlaybackService.js';
|
||||
@@ -107,8 +108,8 @@ enum OntimeStartOrder {
|
||||
}
|
||||
|
||||
let step = OntimeStartOrder.InitAssets;
|
||||
let expressServer = null;
|
||||
let oscServer = null;
|
||||
let expressServer: Server | null = null;
|
||||
let oscServer: OscServer | null = null;
|
||||
|
||||
const checkStart = (currentState: OntimeStartOrder) => {
|
||||
if (step !== currentState) {
|
||||
@@ -165,7 +166,6 @@ export const startServer = async () => {
|
||||
};
|
||||
|
||||
/**
|
||||
* @description starts OSC server
|
||||
* @description starts OSC server
|
||||
* @param overrideConfig
|
||||
* @return {Promise<void>}
|
||||
@@ -194,20 +194,30 @@ export const startOSCServer = async (overrideConfig = null) => {
|
||||
/**
|
||||
* starts integrations
|
||||
*/
|
||||
export const startIntegrations = async (config?: { osc: OSCSettings }) => {
|
||||
export const startIntegrations = async (config?: { osc: OSCSettings; http: HttpSettings }) => {
|
||||
checkStart(OntimeStartOrder.InitIO);
|
||||
|
||||
const { osc } = config ?? DataProvider.getData();
|
||||
const { osc, http } = config ?? DataProvider.getData();
|
||||
|
||||
if (!osc) {
|
||||
return 'OSC Invalid configuration';
|
||||
} else {
|
||||
const { success, message } = oscIntegration.init(osc);
|
||||
logger.info(LogOrigin.Tx, message);
|
||||
|
||||
if (success) {
|
||||
integrationService.register(oscIntegration);
|
||||
}
|
||||
}
|
||||
if (!http) {
|
||||
return 'HTTP Invalid configuration';
|
||||
} else {
|
||||
const { success, message } = httpIntegration.init(http);
|
||||
logger.info(LogOrigin.Tx, message);
|
||||
|
||||
const { success, message } = oscIntegration.init(osc);
|
||||
logger.info(LogOrigin.Tx, message);
|
||||
|
||||
if (success) {
|
||||
integrationService.register(oscIntegration);
|
||||
if (success) {
|
||||
integrationService.register(httpIntegration);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -72,6 +72,10 @@ export class DataProvider {
|
||||
return data.osc;
|
||||
}
|
||||
|
||||
static getHttp() {
|
||||
return data.http;
|
||||
}
|
||||
|
||||
static getAliases() {
|
||||
return data.aliases;
|
||||
}
|
||||
@@ -104,6 +108,11 @@ export class DataProvider {
|
||||
await this.persist();
|
||||
}
|
||||
|
||||
static async setHttp(newData) {
|
||||
data.http = { ...newData };
|
||||
await this.persist();
|
||||
}
|
||||
|
||||
static getRundown() {
|
||||
return [...data.rundown];
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { LogOrigin, OntimeEvent } from 'ontime-types';
|
||||
import { EventLoader } from '../classes/event-loader/EventLoader.js';
|
||||
import { editEvent } from '../services/rundown-service/RundownService.js';
|
||||
import { coerceString, coerceNumber, coerceBoolean } from '../utils/coerceType.js';
|
||||
import { coerceString, coerceNumber, coerceBoolean, coerceColour } from '../utils/coerceType.js';
|
||||
import { logger } from '../classes/Logger.js';
|
||||
import { isKeyOfType, isOntimeEvent } from 'ontime-types/src/utils/guards.js';
|
||||
|
||||
const whitelistedPayload = {
|
||||
title: coerceString,
|
||||
@@ -16,7 +17,8 @@ const whitelistedPayload = {
|
||||
isPublic: coerceBoolean,
|
||||
skip: coerceBoolean,
|
||||
|
||||
colour: coerceString,
|
||||
colour: coerceColour,
|
||||
|
||||
user0: coerceString,
|
||||
user1: coerceString,
|
||||
user2: coerceString,
|
||||
@@ -29,12 +31,12 @@ const whitelistedPayload = {
|
||||
user9: coerceString,
|
||||
};
|
||||
|
||||
export function parse(field: string, value: unknown) {
|
||||
if (!Object.hasOwn(whitelistedPayload, field)) {
|
||||
throw new Error(`Field ${field} not permitted`);
|
||||
export function parse(property: string, value: unknown) {
|
||||
if (!isKeyOfType(property, whitelistedPayload)) {
|
||||
throw new Error(`Property ${property} not permitted`);
|
||||
}
|
||||
const parserFn = whitelistedPayload[field];
|
||||
return parserFn(value);
|
||||
const parserFn = whitelistedPayload[property];
|
||||
return { parsedProperty: property, parsedPayload: parserFn(value) };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -49,8 +51,10 @@ export function updateEvent(
|
||||
newValue: OntimeEvent[typeof propertyName],
|
||||
) {
|
||||
const event = EventLoader.getEventWithId(eventId);
|
||||
|
||||
if (event) {
|
||||
if (!isOntimeEvent(event)) {
|
||||
throw new Error(`Can only update events`);
|
||||
}
|
||||
const propertiesToUpdate = { [propertyName]: newValue };
|
||||
|
||||
// Handles the special case for duration
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
import { OntimeEvent } from 'ontime-types';
|
||||
|
||||
import { messageService } from '../services/message-service/MessageService.js';
|
||||
import { PlaybackService } from '../services/PlaybackService.js';
|
||||
import { eventStore } from '../stores/EventStore.js';
|
||||
import { parse, updateEvent } from './integrationController.config.js';
|
||||
import { isKeyOfType } from 'ontime-types/src/utils/guards.js';
|
||||
import { event } from '../models/eventsDefinition.js';
|
||||
|
||||
export type ChangeOptions = {
|
||||
eventId: string;
|
||||
property: string;
|
||||
value: unknown;
|
||||
};
|
||||
|
||||
//TODO: re-throwing the error does not add any extra information or value
|
||||
export function dispatchFromAdapter(
|
||||
type: string,
|
||||
args: {
|
||||
payload: unknown;
|
||||
params?: Array<string>;
|
||||
},
|
||||
_source?: 'osc' | 'ws',
|
||||
) {
|
||||
const payload = args.payload;
|
||||
const typeComponents = type.toLowerCase().split('/');
|
||||
const mainType = typeComponents[0];
|
||||
const params = args.params || [];
|
||||
|
||||
switch (mainType) {
|
||||
case 'test-ontime': {
|
||||
@@ -267,21 +267,11 @@ export function dispatchFromAdapter(
|
||||
return { topic: 'timer', payload: timer };
|
||||
}
|
||||
|
||||
// ontime/change/{eventID}/{propertyName}
|
||||
// WS: {type: 'change', payload: { eventId, property, value } }
|
||||
case 'change': {
|
||||
if (params.length < 2) {
|
||||
throw new Error('Too few parameters, 3 expected');
|
||||
}
|
||||
if (payload === undefined) {
|
||||
throw new Error('No payload found');
|
||||
}
|
||||
const eventID = params[0];
|
||||
const propertyName = params[1] as keyof OntimeEvent;
|
||||
if (!isKeyOfType(propertyName, event)) {
|
||||
throw new Error(`Cannot update unknown event property ${propertyName}`);
|
||||
}
|
||||
const parsedPayload = parse(propertyName, payload);
|
||||
return updateEvent(eventID, propertyName, parsedPayload);
|
||||
const { eventId, property, value } = payload as ChangeOptions;
|
||||
const { parsedPayload, parsedProperty } = parse(property, value);
|
||||
return updateEvent(eventId, parsedProperty, parsedPayload);
|
||||
}
|
||||
|
||||
default: {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Alias, DatabaseModel, GetInfo, LogOrigin, ProjectData } from 'ontime-types';
|
||||
import { LogOrigin } from 'ontime-types';
|
||||
import type { Alias, DatabaseModel, GetInfo, HttpSettings, ProjectData } from 'ontime-types';
|
||||
|
||||
import { RequestHandler, Request, Response } from 'express';
|
||||
import fs from 'fs';
|
||||
@@ -11,11 +12,13 @@ import { PlaybackService } from '../services/PlaybackService.js';
|
||||
import { eventStore } from '../stores/EventStore.js';
|
||||
import { isDocker, pathToStartStyles, resolveDbPath } from '../setup.js';
|
||||
import { oscIntegration } from '../services/integration-service/OscIntegration.js';
|
||||
import { httpIntegration } from '../services/integration-service/HttpIntegration.js';
|
||||
import { logger } from '../classes/Logger.js';
|
||||
import { deleteAllEvents, notifyChanges } from '../services/rundown-service/RundownService.js';
|
||||
import { deepmerge } from 'ontime-utils';
|
||||
import { runtimeCacheStore } from '../stores/cachingStore.js';
|
||||
import { delayedRundownCacheKey } from '../services/rundown-service/delayedRundown.utils.js';
|
||||
import { integrationService } from '../services/integration-service/IntegrationService.js';
|
||||
|
||||
import { Sheet } from '../utils/sheetsAuth.js';
|
||||
|
||||
@@ -285,15 +288,42 @@ export const getOSC = async (req, res) => {
|
||||
res.status(200).send(osc);
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/ontime/osc'
|
||||
// Returns ACK message
|
||||
export const postOSC = async (req, res) => {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const oscSettings = req.body;
|
||||
await DataProvider.setOsc(oscSettings);
|
||||
|
||||
integrationService.unregister(oscIntegration);
|
||||
|
||||
// TODO: this update could be more granular, checking that relevant data was changed
|
||||
const { success, message } = oscIntegration.init(oscSettings);
|
||||
logger.info(LogOrigin.Tx, message);
|
||||
|
||||
if (success) {
|
||||
integrationService.register(oscIntegration);
|
||||
}
|
||||
|
||||
res.send(oscSettings).status(200);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
export const postOscSubscriptions = async (req, res) => {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const oscSubscriptions = req.body;
|
||||
const subscriptions = req.body;
|
||||
const oscSettings = DataProvider.getOsc();
|
||||
oscSettings.subscriptions = oscSubscriptions;
|
||||
oscSettings.subscriptions = subscriptions;
|
||||
await DataProvider.setOsc(oscSettings);
|
||||
|
||||
// TODO: this update could be more granular, checking that relevant data was changed
|
||||
@@ -306,22 +336,33 @@ export const postOscSubscriptions = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/ontime/osc'
|
||||
// Returns ACK message
|
||||
export const postOSC = async (req, res) => {
|
||||
// Create controller for GET request to '/ontime/http'
|
||||
export const getHTTP = async (_req, res: Response<HttpSettings>) => {
|
||||
const http = DataProvider.getHttp();
|
||||
res.status(200).send(http);
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/ontime/http'
|
||||
export const postHTTP = async (req, res) => {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const oscSettings = req.body;
|
||||
await DataProvider.setOsc(oscSettings);
|
||||
const httpSettings = req.body;
|
||||
await DataProvider.setHttp(httpSettings);
|
||||
|
||||
integrationService.unregister(httpIntegration);
|
||||
|
||||
// TODO: this update could be more granular, checking that relevant data was changed
|
||||
const { message } = oscIntegration.init(oscSettings);
|
||||
const { success, message } = httpIntegration.init(httpSettings);
|
||||
logger.info(LogOrigin.Tx, message);
|
||||
|
||||
res.send(oscSettings).status(200);
|
||||
if (success) {
|
||||
integrationService.register(httpIntegration);
|
||||
}
|
||||
|
||||
res.send(httpSettings).status(200);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { body, check, validationResult } from 'express-validator';
|
||||
import { validateOscObject, validateOscSubscriptionEntry } from '../utils/parserFunctions.js';
|
||||
import {
|
||||
validateHttpSubscriptionObject,
|
||||
validateOscSubscriptionObject,
|
||||
validateOscSubscriptionCycle,
|
||||
} from '../utils/parserFunctions.js';
|
||||
|
||||
/**
|
||||
* @description Validates object for POST /ontime/views
|
||||
@@ -82,7 +86,22 @@ export const validateOSC = [
|
||||
body('enabledOut').exists().isBoolean(),
|
||||
body('subscriptions')
|
||||
.isObject()
|
||||
.custom((value) => validateOscObject(value)),
|
||||
.custom((value) => validateOscSubscriptionObject(value)),
|
||||
(req, res, next) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* @description Validates object for POST /ontime/http
|
||||
*/
|
||||
export const validateHTTP = [
|
||||
body('enabledOut').exists().isBoolean(),
|
||||
body('subscriptions')
|
||||
.isObject()
|
||||
.custom((value) => validateHttpSubscriptionObject(value)),
|
||||
(req, res, next) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
@@ -96,22 +115,22 @@ export const validateOSC = [
|
||||
export const validateOscSubscription = [
|
||||
body('onLoad')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionEntry(value)),
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
body('onStart')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionEntry(value)),
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
body('onPause')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionEntry(value)),
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
body('onStop')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionEntry(value)),
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
body('onUpdate')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionEntry(value)),
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
body('onFinish')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionEntry(value)),
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
(req, res, next) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
|
||||
@@ -61,4 +61,15 @@ export const dbModel: DatabaseModel = {
|
||||
onFinish: [],
|
||||
},
|
||||
},
|
||||
http: {
|
||||
enabledOut: false,
|
||||
subscriptions: {
|
||||
onLoad: [],
|
||||
onStart: [],
|
||||
onPause: [],
|
||||
onStop: [],
|
||||
onUpdate: [],
|
||||
onFinish: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
getAliases,
|
||||
getInfo,
|
||||
getOSC,
|
||||
getHTTP,
|
||||
getSettings,
|
||||
getUserFields,
|
||||
getViewSettings,
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
postUserFields,
|
||||
postViewSettings,
|
||||
previewExcel,
|
||||
postHTTP,
|
||||
sheetAuthUrl,
|
||||
uploadGoogleSheetClientFile,
|
||||
previewSheet,
|
||||
@@ -32,12 +34,13 @@ import {
|
||||
validateAliases,
|
||||
validateGoogleSheetSettings,
|
||||
validateOSC,
|
||||
validateOscSubscription,
|
||||
validatePatchProjectFile,
|
||||
validateSettings,
|
||||
validateSheetPreview,
|
||||
validateUserFields,
|
||||
viewValidator,
|
||||
validateHTTP,
|
||||
validateOscSubscription,
|
||||
} from '../controllers/ontimeController.validate.js';
|
||||
import { projectSanitiser } from '../controllers/projectController.validate.js';
|
||||
|
||||
@@ -94,6 +97,12 @@ router.post('/osc', validateOSC, postOSC);
|
||||
// create route between controller and '/ontime/osc-subscriptions' endpoint
|
||||
router.post('/osc-subscriptions', validateOscSubscription, postOscSubscriptions);
|
||||
|
||||
// create route between controller and '/ontime/http' endpoint
|
||||
router.get('/http', getHTTP);
|
||||
|
||||
// create route between controller and '/ontime/http' endpoint
|
||||
router.post('/http', validateHTTP, postHTTP);
|
||||
|
||||
// create route between controller and '/ontime/new' endpoint
|
||||
router.post('/new', projectSanitiser, postNew);
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { eventStore } from '../stores/EventStore.js';
|
||||
import { PlaybackService } from './PlaybackService.js';
|
||||
import { updateRoll } from './rollUtils.js';
|
||||
import { integrationService } from './integration-service/IntegrationService.js';
|
||||
import { getCurrent, getExpectedFinish } from './timerUtils.js';
|
||||
import { getCurrent, getExpectedFinish, skippedOutOfEvent } from './timerUtils.js';
|
||||
import { clock } from './Clock.js';
|
||||
import { logger } from '../classes/Logger.js';
|
||||
import type { RestorePoint } from './RestoreService.js';
|
||||
@@ -18,10 +18,13 @@ type initialLoadingData = {
|
||||
|
||||
type RestoreCallback = (newState: RestorePoint) => Promise<void>;
|
||||
|
||||
export const timeSkipLimit = 3 * 32;
|
||||
|
||||
export class TimerService {
|
||||
private readonly _interval: NodeJS.Timer;
|
||||
private _updateInterval: number;
|
||||
private _lastUpdate: number | null;
|
||||
private _skipThreshold: number;
|
||||
|
||||
playback: Playback;
|
||||
timer: TimerState;
|
||||
@@ -40,11 +43,13 @@ export class TimerService {
|
||||
* @param {object} [timerConfig]
|
||||
* @param {number} [timerConfig.refresh]
|
||||
* @param {number} [timerConfig.updateInterval]
|
||||
* @param {number} [timerConfig.skipThreshold]
|
||||
*/
|
||||
constructor(timerConfig: { refresh?: number; updateInterval?: number } = {}) {
|
||||
constructor(timerConfig: { refresh: number; updateInterval: number; skipThreshold: number }) {
|
||||
this._clear();
|
||||
this._interval = setInterval(() => this.update(), timerConfig?.refresh ?? 1000);
|
||||
this._updateInterval = timerConfig?.updateInterval ?? 1000;
|
||||
this._interval = setInterval(() => this.update(), timerConfig.refresh);
|
||||
this._updateInterval = timerConfig.updateInterval;
|
||||
this._skipThreshold = timerConfig.skipThreshold;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -339,7 +344,6 @@ export class TimerService {
|
||||
this.timer.expectedFinish >= this.timer.startedAt
|
||||
? this.timer.expectedFinish
|
||||
: this.timer.expectedFinish + dayInMs,
|
||||
|
||||
clock: this.timer.clock,
|
||||
secondaryTimer: this.timer.secondaryTimer,
|
||||
secondaryTarget: this.secondaryTarget,
|
||||
@@ -405,7 +409,19 @@ export class TimerService {
|
||||
let shouldNotify = false;
|
||||
if (this.playback === Playback.Roll) {
|
||||
shouldNotify = true;
|
||||
this.updateRoll();
|
||||
if (
|
||||
skippedOutOfEvent(
|
||||
previousTime,
|
||||
this.timer.clock,
|
||||
this.timer.startedAt,
|
||||
this.timer.expectedFinish,
|
||||
this._skipThreshold,
|
||||
)
|
||||
) {
|
||||
PlaybackService.roll();
|
||||
} else {
|
||||
this.updateRoll();
|
||||
}
|
||||
} else if (this.timer.startedAt !== null) {
|
||||
// we only update timer if a timer has been started
|
||||
shouldNotify = true;
|
||||
@@ -505,4 +521,5 @@ export class TimerService {
|
||||
}
|
||||
|
||||
// calculate at 30fps, refresh at 1fps
|
||||
export const eventTimer = new TimerService({ refresh: 32, updateInterval: 1000 });
|
||||
// we consider a skip at 3 lost updates
|
||||
export const eventTimer = new TimerService({ refresh: 32, updateInterval: 1000, skipThreshold: 32 * 3 });
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { dayInMs } from 'ontime-utils';
|
||||
import { TimerType } from 'ontime-types';
|
||||
|
||||
import { getCurrent, getExpectedFinish } from '../timerUtils.js';
|
||||
import { getCurrent, getExpectedFinish, skippedOutOfEvent } from '../timerUtils.js';
|
||||
|
||||
describe('getExpectedFinish()', () => {
|
||||
it('is null if we havent started', () => {
|
||||
@@ -354,3 +354,106 @@ describe('getExpectedFinish() and getCurrentTime() combined', () => {
|
||||
expect(current).toBe(8);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skippedOutOfEvent()', () => {
|
||||
const testSkipLimit = 32;
|
||||
it('does not consider an event end as a skip', () => {
|
||||
const startedAt = 1000;
|
||||
const duration = 1000;
|
||||
const expectedFinish = startedAt + duration;
|
||||
const previousTime = expectedFinish - testSkipLimit / 2;
|
||||
|
||||
let clock = previousTime;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
|
||||
clock += testSkipLimit;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
});
|
||||
|
||||
it('allows rolling backwards in an event', () => {
|
||||
const startedAt = 1000;
|
||||
const duration = 1000;
|
||||
const expectedFinish = startedAt + duration;
|
||||
const previousTime = startedAt + testSkipLimit / 2;
|
||||
|
||||
let clock = previousTime;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
|
||||
clock -= testSkipLimit;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
});
|
||||
|
||||
it('accounts for crossing midnight', () => {
|
||||
const startedAt = dayInMs - testSkipLimit;
|
||||
const expectedFinish = 10;
|
||||
const previousTime = dayInMs - 1;
|
||||
|
||||
let clock = previousTime;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
|
||||
clock = testSkipLimit - 2;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
});
|
||||
|
||||
it('allows rolling backwards in an event across midnight', () => {
|
||||
const startedAt = dayInMs - testSkipLimit;
|
||||
const expectedFinish = 10;
|
||||
const previousTime = startedAt + 1;
|
||||
|
||||
let clock = previousTime;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
|
||||
clock -= testSkipLimit;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
});
|
||||
|
||||
it('finds skip forwards out of event', () => {
|
||||
const startedAt = 1000;
|
||||
const duration = 1000;
|
||||
const expectedFinish = startedAt + duration;
|
||||
const previousTime = expectedFinish - testSkipLimit / 2;
|
||||
|
||||
let clock = previousTime;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
|
||||
clock += testSkipLimit + 1;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(true);
|
||||
});
|
||||
|
||||
it('finds skip backwards out of event', () => {
|
||||
const startedAt = 1000;
|
||||
const duration = 1000;
|
||||
const expectedFinish = startedAt + duration;
|
||||
const previousTime = startedAt + testSkipLimit / 2;
|
||||
|
||||
let clock = previousTime;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
|
||||
clock -= testSkipLimit + 1;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(true);
|
||||
});
|
||||
|
||||
it('finds skip forwards out of event across midnight', () => {
|
||||
const startedAt = dayInMs - testSkipLimit;
|
||||
const expectedFinish = 10;
|
||||
const previousTime = dayInMs - 3;
|
||||
|
||||
let clock = previousTime;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
|
||||
clock = testSkipLimit - 2;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(true);
|
||||
});
|
||||
|
||||
it('finds skip backwards out of event across midnight', () => {
|
||||
const startedAt = dayInMs - testSkipLimit;
|
||||
const expectedFinish = 10;
|
||||
const previousTime = startedAt + 1;
|
||||
|
||||
let clock = previousTime;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
|
||||
|
||||
clock -= testSkipLimit + 1;
|
||||
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import got from 'got';
|
||||
|
||||
import { HttpSettings, HttpSubscription, HttpSubscriptionOptions, LogOrigin } from 'ontime-types';
|
||||
|
||||
import IIntegration, { TimerLifeCycleKey } from './IIntegration.js';
|
||||
import { parseTemplateNested } from './integrationUtils.js';
|
||||
import { dbModel } from '../../models/dataModel.js';
|
||||
import { logger } from '../../classes/Logger.js';
|
||||
import { validateHttpSubscriptionObject } from '../../utils/parserFunctions.js';
|
||||
|
||||
type Action = TimerLifeCycleKey | string;
|
||||
|
||||
/**
|
||||
* @description Class contains logic towards outgoing HTTP communications
|
||||
* @class
|
||||
*/
|
||||
export class HttpIntegration implements IIntegration<HttpSubscriptionOptions> {
|
||||
subscriptions: HttpSubscription;
|
||||
constructor() {
|
||||
this.subscriptions = dbModel.http.subscriptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes httpClient
|
||||
*/
|
||||
init(config: HttpSettings) {
|
||||
const { subscriptions, enabledOut } = config;
|
||||
|
||||
if (!enabledOut) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'HTTP output disabled',
|
||||
};
|
||||
}
|
||||
|
||||
this.initSubscriptions(subscriptions);
|
||||
|
||||
try {
|
||||
return {
|
||||
success: true,
|
||||
message: `HTTP integration client ready`,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: `Failed initialising HTTP integration: ${error}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
initSubscriptions(subscriptionOptions: HttpSubscription) {
|
||||
if (validateHttpSubscriptionObject(subscriptionOptions)) {
|
||||
this.subscriptions = { ...subscriptionOptions };
|
||||
}
|
||||
}
|
||||
|
||||
dispatch(action: Action, state?: object) {
|
||||
if (!action) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'HTTP called with no action',
|
||||
};
|
||||
}
|
||||
|
||||
// check subscriptions for action
|
||||
const eventSubscriptions = this.subscriptions?.[action] || [];
|
||||
|
||||
eventSubscriptions.forEach((sub) => {
|
||||
const { enabled, message } = sub;
|
||||
if (enabled && message) {
|
||||
const parsedMessage = parseTemplateNested(message, state || {});
|
||||
try {
|
||||
const parsedUrl = new URL(parsedMessage);
|
||||
this.emit(parsedUrl);
|
||||
} catch (err) {
|
||||
logger.error(LogOrigin.Tx, `HTTP Integration: ${err}`);
|
||||
return {
|
||||
success: false,
|
||||
message: `${err}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async emit(path: URL) {
|
||||
try {
|
||||
await got.get(path, {
|
||||
retry: { limit: 0 },
|
||||
});
|
||||
} catch (err) {
|
||||
logger.error(LogOrigin.Tx, `HTTP integration: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
shutdown() {}
|
||||
}
|
||||
|
||||
export const httpIntegration = new HttpIntegration();
|
||||
@@ -1,9 +1,9 @@
|
||||
import { TimerLifeCycle, OscSubscription } from 'ontime-types';
|
||||
import { TimerLifeCycle, Subscription } from 'ontime-types';
|
||||
|
||||
export type TimerLifeCycleKey = keyof typeof TimerLifeCycle;
|
||||
|
||||
export default interface IIntegration {
|
||||
subscriptions: OscSubscription;
|
||||
export default interface IIntegration<T> {
|
||||
subscriptions: Subscription<T>;
|
||||
init: (config: unknown) => OperationReturn;
|
||||
dispatch: (action: TimerLifeCycleKey, state?: object) => OperationReturn;
|
||||
emit: (...args: unknown[]) => unknown;
|
||||
|
||||
@@ -2,17 +2,17 @@ import IIntegration, { TimerLifeCycleKey } from './IIntegration.js';
|
||||
import { eventStore } from '../../stores/EventStore.js';
|
||||
|
||||
class IntegrationService {
|
||||
private integrations: IIntegration[];
|
||||
private integrations: IIntegration<unknown>[];
|
||||
|
||||
constructor() {
|
||||
this.integrations = [];
|
||||
}
|
||||
|
||||
register(integrationService: IIntegration) {
|
||||
register(integrationService: IIntegration<unknown>) {
|
||||
this.integrations.push(integrationService);
|
||||
}
|
||||
|
||||
unregister(integrationService: IIntegration) {
|
||||
unregister(integrationService: IIntegration<unknown>) {
|
||||
this.integrations = this.integrations.filter((int) => int !== integrationService);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { ArgumentType, Client, Message } from 'node-osc';
|
||||
import { OSCSettings, OscSubscription } from 'ontime-types';
|
||||
import { OSCSettings, OscSubscription, OscSubscriptionOptions } from 'ontime-types';
|
||||
|
||||
import IIntegration, { TimerLifeCycleKey } from './IIntegration.js';
|
||||
import { parseTemplateNested } from './integrationUtils.js';
|
||||
import { isObject } from '../../utils/varUtils.js';
|
||||
import { dbModel } from '../../models/dataModel.js';
|
||||
import { validateOscObject } from '../../utils/parserFunctions.js';
|
||||
import { validateOscSubscriptionObject } from '../../utils/parserFunctions.js';
|
||||
|
||||
type Action = TimerLifeCycleKey | string;
|
||||
|
||||
@@ -13,7 +13,7 @@ type Action = TimerLifeCycleKey | string;
|
||||
* @description Class contains logic towards outgoing OSC communications
|
||||
* @class
|
||||
*/
|
||||
export class OscIntegration implements IIntegration {
|
||||
export class OscIntegration implements IIntegration<OscSubscriptionOptions> {
|
||||
protected oscClient: null | Client;
|
||||
subscriptions: OscSubscription;
|
||||
|
||||
@@ -26,7 +26,15 @@ export class OscIntegration implements IIntegration {
|
||||
* Initializes oscClient
|
||||
*/
|
||||
init(config: OSCSettings) {
|
||||
const { targetIP, portOut, subscriptions } = config;
|
||||
const { targetIP, portOut, subscriptions, enabledOut } = config;
|
||||
|
||||
if (!enabledOut) {
|
||||
this.oscClient?.close();
|
||||
return {
|
||||
success: false,
|
||||
message: 'OSC output disabled',
|
||||
};
|
||||
}
|
||||
|
||||
this.initSubscriptions(subscriptions);
|
||||
|
||||
@@ -58,7 +66,7 @@ export class OscIntegration implements IIntegration {
|
||||
}
|
||||
|
||||
initSubscriptions(subscriptionOptions: OscSubscription) {
|
||||
if (validateOscObject(subscriptionOptions)) {
|
||||
if (validateOscSubscriptionObject(subscriptionOptions)) {
|
||||
this.subscriptions = { ...subscriptionOptions };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,3 +64,20 @@ export function getCurrent(
|
||||
}
|
||||
return startedAt + duration + addedTime + pausedTime - clock;
|
||||
}
|
||||
|
||||
export function skippedOutOfEvent(
|
||||
previousTime: number,
|
||||
clock: number,
|
||||
startedAt: number,
|
||||
expectedFinish: number,
|
||||
skipLimit: number,
|
||||
): boolean {
|
||||
const hasPassedMidnight = previousTime > dayInMs - skipLimit && clock < skipLimit;
|
||||
const adjustedClock = hasPassedMidnight ? clock + dayInMs : clock;
|
||||
|
||||
const timeDifference = previousTime - adjustedClock;
|
||||
const hasSkipped = Math.abs(timeDifference) > skipLimit;
|
||||
const adjustedExpectedFinish = expectedFinish >= startedAt ? expectedFinish : expectedFinish + dayInMs;
|
||||
|
||||
return hasSkipped && (adjustedClock > adjustedExpectedFinish || adjustedClock < startedAt);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { coerceColour } from '../coerceType.js';
|
||||
|
||||
describe('parses a colour string that is', () => {
|
||||
it('valid hex', () => {
|
||||
const color = coerceColour('#000');
|
||||
expect(color).toBe('#000');
|
||||
});
|
||||
it('valid name', () => {
|
||||
const color = coerceColour('darkgoldenrod');
|
||||
expect(color).toBe('darkgoldenrod');
|
||||
});
|
||||
it('invalid hex', () => {
|
||||
expect(() => coerceColour('#not a hex color')).toThrowError(Error('Invalid hex colour received'));
|
||||
});
|
||||
it('invalid name', () => {
|
||||
expect(() => coerceColour('bad name')).toThrowError(Error('Invalid colour name received'));
|
||||
});
|
||||
it('not a string', () => {
|
||||
expect(() => coerceColour(5)).toThrowError(Error('Invalid colour value received'));
|
||||
});
|
||||
});
|
||||
@@ -1,91 +0,0 @@
|
||||
import { validateOscObject } from '../parserFunctions.ts';
|
||||
|
||||
test('validateOscSubscription()', () => {
|
||||
it('should return true when given a valid OscSubscription', () => {
|
||||
const validSubscription = {
|
||||
onLoad: [{ id: '1', message: 'test', enabled: true }],
|
||||
onStart: [{ id: '2', message: 'test', enabled: false }],
|
||||
onPause: [{ id: '3', message: 'test', enabled: true }],
|
||||
onStop: [{ id: '4', message: 'test', enabled: false }],
|
||||
onUpdate: [{ id: '5', message: 'test', enabled: true }],
|
||||
onFinish: [{ id: '6', message: 'test', enabled: false }],
|
||||
};
|
||||
|
||||
const result = validateOscObject(validSubscription);
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when given undefined', () => {
|
||||
const result = validateOscObject(undefined);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given null', () => {
|
||||
const result = validateOscObject(null);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an empty object', () => {
|
||||
const result = validateOscObject({});
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an empty array', () => {
|
||||
const result = validateOscObject([]);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an object that is not an OscSubscription', () => {
|
||||
const invalidObject = { foo: 'bar' };
|
||||
|
||||
const result = validateOscObject(invalidObject);
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an OscSubscription with a missing property', () => {
|
||||
const invalidSubscription = {
|
||||
onLoad: [{ id: '1', message: 'test', enabled: true }],
|
||||
onStart: [{ id: '2', message: 'test', enabled: false }],
|
||||
onPause: [{ id: '3', message: 'test', enabled: true }],
|
||||
// Missing onStop
|
||||
onUpdate: [{ id: '5', message: 'test', enabled: true }],
|
||||
onFinish: [{ id: '6', message: 'test', enabled: false }],
|
||||
};
|
||||
|
||||
const result = validateOscObject(invalidSubscription);
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an OscSubscription with an invalid property value', () => {
|
||||
const invalidSubscription = {
|
||||
onLoad: [{ id: '1', message: 'test', enabled: true }],
|
||||
onStart: [{ id: '2', message: 'test', enabled: false }],
|
||||
onPause: [{ id: '3', message: 'test', enabled: true }],
|
||||
onStop: [{ id: '4', message: 'test', enabled: false }],
|
||||
onUpdate: [{ id: '5', message: 'test', enabled: true }],
|
||||
onFinish: [{ id: '6', message: 'test', enabled: 'not a boolean' }],
|
||||
};
|
||||
|
||||
const result = validateOscObject(invalidSubscription);
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true if the message field is empty', () => {
|
||||
const invalidSubscription = {
|
||||
onLoad: [{ id: '1', message: 'test', enabled: true }],
|
||||
onStart: [{ id: '2', message: '', enabled: false }],
|
||||
onPause: [{ id: '3', message: '', enabled: true }],
|
||||
onStop: [{ id: '4', message: 'test', enabled: false }],
|
||||
onUpdate: [{ id: '5', message: 'test', enabled: true }],
|
||||
onFinish: [{ id: '6', message: 'test', enabled: 'not a boolean' }],
|
||||
};
|
||||
|
||||
const result = validateOscObject(invalidSubscription);
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import { HttpSubscription, OscSubscription } from 'ontime-types';
|
||||
import {
|
||||
validateOscSubscriptionObject,
|
||||
validateOscSubscriptionCycle,
|
||||
validateHttpSubscriptionCycle,
|
||||
validateHttpSubscriptionObject,
|
||||
} from '../parserFunctions.js';
|
||||
|
||||
describe('validateOscSubscriptionCycle()', () => {
|
||||
it('should return false when given an OscSubscription with an invalid property value', () => {
|
||||
const invalidEntry = [{ message: 'test', enabled: 'not a boolean' }];
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionCycle(invalidEntry);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateOscSubscriptionObject()', () => {
|
||||
it('should return true when given a valid OscSubscription', () => {
|
||||
const validSubscription: OscSubscription = {
|
||||
onLoad: [{ message: 'test', enabled: true }],
|
||||
onStart: [{ message: 'test', enabled: false }],
|
||||
onPause: [{ message: 'test', enabled: true }],
|
||||
onStop: [{ message: 'test', enabled: false }],
|
||||
onUpdate: [{ message: 'test', enabled: true }],
|
||||
onFinish: [{ message: 'test', enabled: false }],
|
||||
};
|
||||
|
||||
const result = validateOscSubscriptionObject(validSubscription);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when given undefined', () => {
|
||||
const result = validateOscSubscriptionObject(undefined);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given null', () => {
|
||||
const result = validateOscSubscriptionObject(null);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an empty object', () => {
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionObject({});
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an empty array', () => {
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionObject([]);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an object that is not an OscSubscription', () => {
|
||||
const invalidObject = { foo: 'bar' };
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionObject(invalidObject);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an OscSubscription with a missing property', () => {
|
||||
const invalidSubscription = {
|
||||
onLoad: [{ message: 'test', enabled: true }],
|
||||
onStart: [{ message: 'test', enabled: false }],
|
||||
onPause: [{ message: 'test', enabled: true }],
|
||||
// Missing onStop
|
||||
onUpdate: [{ message: 'test', enabled: true }],
|
||||
onFinish: [{ message: 'test', enabled: false }],
|
||||
};
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionObject(invalidSubscription);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateHttpSubscriptionCycle()', () => {
|
||||
it('should return false when given an HttpSubscription with an invalid property value', () => {
|
||||
const invalidBoolean = [{ message: 'http://', enabled: 'not a boolean' }];
|
||||
const invalidHttp = [{ message: 'test', enabled: true }];
|
||||
const noFtp = [{ message: 'ftp://test', enabled: true }];
|
||||
const noEmpty = [{ message: '', enabled: true }];
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
expect(validateHttpSubscriptionCycle(invalidBoolean)).toBe(false);
|
||||
|
||||
expect(validateHttpSubscriptionCycle(invalidHttp)).toBe(false);
|
||||
expect(validateHttpSubscriptionCycle(noFtp)).toBe(false);
|
||||
expect(validateHttpSubscriptionCycle(noEmpty)).toBe(false);
|
||||
});
|
||||
it('should return true when given an HttpSubscription matches definition', () => {
|
||||
const validHttp = [{ message: 'http://', enabled: true }];
|
||||
const invalidHttps = [{ message: 'https://', enabled: true }];
|
||||
|
||||
expect(validateHttpSubscriptionCycle(validHttp)).toBe(true);
|
||||
expect(validateHttpSubscriptionCycle(invalidHttps)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateHttpSubscriptionObject()', () => {
|
||||
it('should return true when given a valid HttpSubscription', () => {
|
||||
const validSubscription: HttpSubscription = {
|
||||
onLoad: [{ message: 'http://', enabled: true }],
|
||||
onStart: [{ message: 'http://', enabled: false }],
|
||||
onPause: [{ message: 'http://', enabled: true }],
|
||||
onStop: [{ message: 'http://', enabled: false }],
|
||||
onUpdate: [{ message: 'http://', enabled: true }],
|
||||
onFinish: [{ message: 'http://', enabled: false }],
|
||||
};
|
||||
|
||||
const result = validateHttpSubscriptionObject(validSubscription);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when given undefined', () => {
|
||||
const result = validateHttpSubscriptionObject(undefined);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given null', () => {
|
||||
const result = validateHttpSubscriptionObject(null);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an empty object', () => {
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionObject({});
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an empty array', () => {
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateHttpSubscriptionObject([]);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an object that is not an HttpSubscription', () => {
|
||||
const invalidObject = { foo: 'bar' };
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateHttpSubscriptionObject(invalidObject);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an HttpSubscription with a missing property', () => {
|
||||
const invalidSubscription = {
|
||||
onLoad: [{ message: 'http://', enabled: true }],
|
||||
onStart: [{ message: 'http://', enabled: false }],
|
||||
onPause: [{ message: 'http://', enabled: true }],
|
||||
// Missing onStop
|
||||
onUpdate: [{ message: 'http://', enabled: true }],
|
||||
onFinish: [{ message: 'http://', enabled: false }],
|
||||
};
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateHttpSubscriptionObject(invalidSubscription);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,8 @@
|
||||
import { isColourHex } from 'ontime-utils';
|
||||
|
||||
//TODO: write tests
|
||||
/**
|
||||
* @description Converts a value to a number if possible, throws otherwise
|
||||
* @description Converts a value to a string if possible, throws otherwise
|
||||
* @param {unknown} value - Value to be converted to a string.
|
||||
* @returns {string} - The converted value as a string.
|
||||
* @throws {Error} Throws an error if the value is null or undefined.
|
||||
@@ -11,8 +14,9 @@ export function coerceString(value: unknown): string {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
//TODO: write tests
|
||||
/**
|
||||
* @description Converts a value to a number if possible, throws otherwise
|
||||
* @description Converts a value to a boolean if possible, throws otherwise
|
||||
* @param {unknown} value - Value to be converted to a boolean.
|
||||
* @returns {boolean} - The converted value as a boolean.
|
||||
* @throws {Error} Throws an error if the value is null or undefined.
|
||||
@@ -21,9 +25,26 @@ export function coerceBoolean(value: unknown): boolean {
|
||||
if (value == null) {
|
||||
throw new Error('Invalid value received');
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
const lowerCaseValue = value.toLocaleLowerCase();
|
||||
switch (lowerCaseValue) {
|
||||
case 'true':
|
||||
case '1':
|
||||
case 'yes':
|
||||
return true;
|
||||
case 'false':
|
||||
case '0':
|
||||
case 'no':
|
||||
case '':
|
||||
return false;
|
||||
default:
|
||||
throw new Error('Invalid value received');
|
||||
}
|
||||
}
|
||||
return Boolean(value);
|
||||
}
|
||||
|
||||
//TODO: write tests
|
||||
/**
|
||||
* @description Converts a value to a number if possible, throws otherwise
|
||||
* @param {unknown} value - Value to be converted to a number.
|
||||
@@ -40,3 +61,176 @@ export function coerceNumber(value: unknown): number {
|
||||
}
|
||||
return parsedValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts a value to a colour if possible, throws otherwise
|
||||
* @param {unknown} value - Value to be converted to a colour.
|
||||
* @returns {string} - The converted value as a string.
|
||||
* @throws {Error} Throws an error if the value is null or undefined.
|
||||
*/
|
||||
export function coerceColour(value: unknown): string {
|
||||
if (typeof value !== 'string') {
|
||||
throw new Error('Invalid colour value received');
|
||||
}
|
||||
const lowerCaseValue = value.toLocaleLowerCase();
|
||||
if (lowerCaseValue.startsWith('#')) {
|
||||
if (!isColourHex(lowerCaseValue)) {
|
||||
throw new Error('Invalid hex colour received');
|
||||
}
|
||||
} else if (!(lowerCaseValue in cssColours)) {
|
||||
throw new Error('Invalid colour name received');
|
||||
}
|
||||
return lowerCaseValue;
|
||||
}
|
||||
|
||||
//https://developer.mozilla.org/en-US/docs/Web/CSS/named-color
|
||||
const cssColours = {
|
||||
aliceblue: '#f0f8ff',
|
||||
antiquewhite: '#faebd7',
|
||||
aqua: '#00ffff',
|
||||
aquamarine: '#7fffd4',
|
||||
azure: '#f0ffff',
|
||||
beige: '#f5f5dc',
|
||||
bisque: '#ffe4c4',
|
||||
black: '#000000',
|
||||
blanchedalmond: '#ffebcd',
|
||||
blue: '#0000ff',
|
||||
blueviolet: '#8a2be2',
|
||||
brown: '#a52a2a',
|
||||
burlywood: '#deb887',
|
||||
cadetblue: '#5f9ea0',
|
||||
chartreuse: '#7fff00',
|
||||
chocolate: '#d2691e',
|
||||
coral: '#ff7f50',
|
||||
cornflowerblue: '#6495ed',
|
||||
cornsilk: '#fff8dc',
|
||||
crimson: '#dc143c',
|
||||
cyan: '#00ffff',
|
||||
darkblue: '#00008b',
|
||||
darkcyan: '#008b8b',
|
||||
darkgoldenrod: '#b8860b',
|
||||
darkgray: '#a9a9a9',
|
||||
darkgreen: '#006400',
|
||||
darkgrey: '#a9a9a9',
|
||||
darkkhaki: '#bdb76b',
|
||||
darkmagenta: '#8b008b',
|
||||
darkolivegreen: '#556b2f',
|
||||
darkorange: '#ff8c00',
|
||||
darkorchid: '#9932cc',
|
||||
darkred: '#8b0000',
|
||||
darksalmon: '#e9967a',
|
||||
darkseagreen: '#8fbc8f',
|
||||
darkslateblue: '#483d8b',
|
||||
darkslategray: '#2f4f4f',
|
||||
darkslategrey: '#2f4f4f',
|
||||
darkturquoise: '#00ced1',
|
||||
darkviolet: '#9400d3',
|
||||
deeppink: '#ff1493',
|
||||
deepskyblue: '#00bfff',
|
||||
dimgray: '#696969',
|
||||
dimgrey: '#696969',
|
||||
dodgerblue: '#1e90ff',
|
||||
firebrick: '#b22222',
|
||||
floralwhite: '#fffaf0',
|
||||
forestgreen: '#228b22',
|
||||
fuchsia: '#ff00ff',
|
||||
gainsboro: '#dcdcdc',
|
||||
ghostwhite: '#f8f8ff',
|
||||
goldenrod: '#daa520',
|
||||
gold: '#ffd700',
|
||||
gray: '#808080',
|
||||
green: '#008000',
|
||||
greenyellow: '#adff2f',
|
||||
grey: '#808080',
|
||||
honeydew: '#f0fff0',
|
||||
hotpink: '#ff69b4',
|
||||
indianred: '#cd5c5c',
|
||||
indigo: '#4b0082',
|
||||
ivory: '#fffff0',
|
||||
khaki: '#f0e68c',
|
||||
lavenderblush: '#fff0f5',
|
||||
lavender: '#e6e6fa',
|
||||
lawngreen: '#7cfc00',
|
||||
lemonchiffon: '#fffacd',
|
||||
lightblue: '#add8e6',
|
||||
lightcoral: '#f08080',
|
||||
lightcyan: '#e0ffff',
|
||||
lightgoldenrodyellow: '#fafad2',
|
||||
lightgray: '#d3d3d3',
|
||||
lightgreen: '#90ee90',
|
||||
lightgrey: '#d3d3d3',
|
||||
lightpink: '#ffb6c1',
|
||||
lightsalmon: '#ffa07a',
|
||||
lightseagreen: '#20b2aa',
|
||||
lightskyblue: '#87cefa',
|
||||
lightslategray: '#778899',
|
||||
lightslategrey: '#778899',
|
||||
lightsteelblue: '#b0c4de',
|
||||
lightyellow: '#ffffe0',
|
||||
lime: '#00ff00',
|
||||
limegreen: '#32cd32',
|
||||
linen: '#faf0e6',
|
||||
magenta: '#ff00ff',
|
||||
maroon: '#800000',
|
||||
mediumaquamarine: '#66cdaa',
|
||||
mediumblue: '#0000cd',
|
||||
mediumorchid: '#ba55d3',
|
||||
mediumpurple: '#9370db',
|
||||
mediumseagreen: '#3cb371',
|
||||
mediumslateblue: '#7b68ee',
|
||||
mediumspringgreen: '#00fa9a',
|
||||
mediumturquoise: '#48d1cc',
|
||||
mediumvioletred: '#c71585',
|
||||
midnightblue: '#191970',
|
||||
mintcream: '#f5fffa',
|
||||
mistyrose: '#ffe4e1',
|
||||
moccasin: '#ffe4b5',
|
||||
navajowhite: '#ffdead',
|
||||
navy: '#000080',
|
||||
oldlace: '#fdf5e6',
|
||||
olive: '#808000',
|
||||
olivedrab: '#6b8e23',
|
||||
orange: '#ffa500',
|
||||
orangered: '#ff4500',
|
||||
orchid: '#da70d6',
|
||||
palegoldenrod: '#eee8aa',
|
||||
palegreen: '#98fb98',
|
||||
paleturquoise: '#afeeee',
|
||||
palevioletred: '#db7093',
|
||||
papayawhip: '#ffefd5',
|
||||
peachpuff: '#ffdab9',
|
||||
peru: '#cd853f',
|
||||
pink: '#ffc0cb',
|
||||
plum: '#dda0dd',
|
||||
powderblue: '#b0e0e6',
|
||||
purple: '#800080',
|
||||
rebeccapurple: '#663399',
|
||||
red: '#ff0000',
|
||||
rosybrown: '#bc8f8f',
|
||||
royalblue: '#4169e1',
|
||||
saddlebrown: '#8b4513',
|
||||
salmon: '#fa8072',
|
||||
sandybrown: '#f4a460',
|
||||
seagreen: '#2e8b57',
|
||||
seashell: '#fff5ee',
|
||||
sienna: '#a0522d',
|
||||
silver: '#c0c0c0',
|
||||
skyblue: '#87ceeb',
|
||||
slateblue: '#6a5acd',
|
||||
slategray: '#708090',
|
||||
slategrey: '#708090',
|
||||
snow: '#fffafa',
|
||||
springgreen: '#00ff7f',
|
||||
steelblue: '#4682b4',
|
||||
tan: '#d2b48c',
|
||||
teal: '#008080',
|
||||
thistle: '#d8bfd8',
|
||||
tomato: '#ff6347',
|
||||
turquoise: '#40e0d0',
|
||||
violet: '#ee82ee',
|
||||
wheat: '#f5deb3',
|
||||
white: '#ffffff',
|
||||
whitesmoke: '#f5f5f5',
|
||||
yellow: '#ffff00',
|
||||
yellowgreen: '#9acd3',
|
||||
} as const;
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
parseAliases,
|
||||
parseProject,
|
||||
parseOsc,
|
||||
parseHttp,
|
||||
parseRundown,
|
||||
parseSettings,
|
||||
parseUserFields,
|
||||
@@ -368,7 +369,7 @@ export const parseJson = async (jsonData): Promise<DatabaseModel | null> => {
|
||||
// Import OSC settings if any
|
||||
returnData.osc = parseOsc(jsonData) ?? dbModel.osc;
|
||||
// Import HTTP settings if any
|
||||
// returnData.http = parseHttp(jsonData, enforce);
|
||||
returnData.http = parseHttp(jsonData) ?? dbModel.http;
|
||||
// Import GoogleSheet settings if any
|
||||
returnData.googleSheet = parseGoogleSheet(jsonData, true);
|
||||
|
||||
|
||||
@@ -3,14 +3,17 @@ import {
|
||||
Alias,
|
||||
GoogleSheet,
|
||||
OntimeRundown,
|
||||
HttpSettings,
|
||||
OSCSettings,
|
||||
OscSubscription,
|
||||
OscSubscriptionOptions,
|
||||
ProjectData,
|
||||
Settings,
|
||||
TimerLifeCycle,
|
||||
UserFields,
|
||||
ViewSettings,
|
||||
OscSubscription,
|
||||
HttpSubscription,
|
||||
OscSubscriptionOptions,
|
||||
HttpSubscriptionOptions,
|
||||
} from 'ontime-types';
|
||||
|
||||
import { block as blockDef, delay as delayDef } from '../models/eventsDefinition.js';
|
||||
@@ -160,12 +163,12 @@ export const parseViewSettings = (data): ViewSettings => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses and validates subscription entry
|
||||
* Parses and validates OSC subscription cycle options
|
||||
* @param data
|
||||
*/
|
||||
export const validateOscSubscriptionEntry = (data: OscSubscriptionOptions): boolean => {
|
||||
for (const subscription in data) {
|
||||
if (typeof data[subscription].message !== 'string' || typeof data[subscription].enabled !== 'boolean') {
|
||||
export const validateOscSubscriptionCycle = (data: OscSubscriptionOptions[]): boolean => {
|
||||
for (const subscriptionOption of data) {
|
||||
if (typeof subscriptionOption.message !== 'string' || typeof subscriptionOption.enabled !== 'boolean') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -173,22 +176,23 @@ export const validateOscSubscriptionEntry = (data: OscSubscriptionOptions): bool
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses and validates subscription object
|
||||
* Parses and validates OSC subscription object
|
||||
* @param data
|
||||
*/
|
||||
export const validateOscObject = (data: OscSubscription): boolean => {
|
||||
export const validateOscSubscriptionObject = (data: OscSubscription): boolean => {
|
||||
if (!data) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const timerKeys = Object.keys(TimerLifeCycle);
|
||||
for (const key of timerKeys) {
|
||||
// must contains all keys and be an array
|
||||
if (!(key in data) || !Array.isArray(data[key])) {
|
||||
return false;
|
||||
}
|
||||
for (const subscription of data[key]) {
|
||||
if (typeof subscription.message !== 'string' || typeof subscription.enabled !== 'boolean') {
|
||||
return false;
|
||||
}
|
||||
const isValid = validateOscSubscriptionCycle(data[key]);
|
||||
if (!isValid) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -201,8 +205,9 @@ export const parseOsc = (data: { osc?: Partial<OSCSettings> }): OSCSettings => {
|
||||
if ('osc' in data) {
|
||||
console.log('Found OSC definition, importing...');
|
||||
|
||||
// TODO: this can be improved by only merging known keys
|
||||
const loadedConfig = data.osc || {};
|
||||
const validatedSubscriptions = validateOscObject(loadedConfig.subscriptions)
|
||||
const validatedSubscriptions = validateOscSubscriptionObject(loadedConfig.subscriptions)
|
||||
? loadedConfig.subscriptions
|
||||
: dbModel.osc.subscriptions;
|
||||
|
||||
@@ -217,20 +222,63 @@ export const parseOsc = (data: { osc?: Partial<OSCSettings> }): OSCSettings => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses and validates HTTP subscription cycle options
|
||||
* @param data
|
||||
*/
|
||||
export const validateHttpSubscriptionCycle = (data: HttpSubscriptionOptions[]): boolean => {
|
||||
for (const subscriptionOption of data) {
|
||||
const isHttp = subscriptionOption.message?.startsWith('http://');
|
||||
if (typeof subscriptionOption.message !== 'string' || !isHttp || typeof subscriptionOption.enabled !== 'boolean') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses and validates HTTP subscription object
|
||||
* @param data
|
||||
*/
|
||||
export const validateHttpSubscriptionObject = (data: HttpSubscription): boolean => {
|
||||
if (!data) {
|
||||
return false;
|
||||
}
|
||||
const timerKeys = Object.keys(TimerLifeCycle);
|
||||
// must contains all keys and be an array
|
||||
for (const key of timerKeys) {
|
||||
if (!(key in data) || !Array.isArray(data[key])) {
|
||||
return false;
|
||||
}
|
||||
const isValid = validateHttpSubscriptionCycle(data[key]);
|
||||
if (!isValid) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse Http portion of an entry
|
||||
* @param {object} data - data object
|
||||
* @param {boolean} enforce - whether to create a definition if one is missing
|
||||
* @returns {object} - event object data
|
||||
*/
|
||||
export const parseHttp = (data, enforce) => {
|
||||
const newHttp = {};
|
||||
export const parseHttp = (data: { http?: Partial<HttpSettings> }): HttpSettings => {
|
||||
if ('http' in data) {
|
||||
console.log('Found HTTP definition, importing...');
|
||||
} else if (enforce) {
|
||||
/* Not yet */
|
||||
|
||||
// TODO: this can be improved by only merging known keys
|
||||
const loadedConfig = data?.http || {};
|
||||
const validatedSubscriptions = validateHttpSubscriptionObject(loadedConfig.subscriptions)
|
||||
? loadedConfig.subscriptions
|
||||
: dbModel.http.subscriptions;
|
||||
|
||||
return {
|
||||
enabledOut: loadedConfig.enabledOut ?? dbModel.http.enabledOut,
|
||||
subscriptions: validatedSubscriptions,
|
||||
};
|
||||
}
|
||||
return newHttp;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user