update API - part 1 (#709)

* api: `test-ontime` -> `version`

* api: `ontime-poll` -> `poll`

* api: `start-next` -> `startnext`

* api: `start-next` ->  `startnext`

---------

Co-authored-by: Carlos Valente <34649812+cpvalente@users.noreply.github.com>
Co-authored-by: Carlos Valente <carlosvalente@pm.me>
This commit is contained in:
Alex Christoffer Rasmussen
2024-01-23 08:43:00 +01:00
committed by GitHub
parent cb8ba776e2
commit 0cd2ca4191
23 changed files with 432 additions and 393 deletions
+5 -2
View File
@@ -5,6 +5,7 @@ import { Server } from 'node-osc';
import { IAdapter } from './IAdapter.js';
import { dispatchFromAdapter, type ChangeOptions } from '../controllers/integrationController.js';
import { logger } from '../classes/Logger.js';
import { objectFromPath } from './utils/parse.js';
export class OscServer implements IAdapter {
private readonly osc: Server;
@@ -18,6 +19,7 @@ export class OscServer implements IAdapter {
// message should look like /ontime/{path}/{params?} {args} where
// ontime: fixed message for app
// path: command to be called
// params: used to create a nested object to patch with
// args: extra data, only used on some API entries (delay, goto)
// split message
@@ -38,7 +40,7 @@ export class OscServer implements IAdapter {
let transformedPayload: unknown = args;
// we need to transform the params for the change endpoint
// OSC: ontime/change/{eventID}/{propertyName} value
// OSC: /ontime/change/{eventID}/{propertyName} value
if (path === 'change') {
if (params.length < 2) {
logger.error(LogOrigin.Rx, 'OSC IN: No params provided for change');
@@ -59,10 +61,11 @@ export class OscServer implements IAdapter {
property,
value,
} satisfies ChangeOptions;
} else if (params.length) {
transformedPayload = objectFromPath(params, args);
}
try {
// we dont reply on OSC
dispatchFromAdapter(
path,
{
@@ -0,0 +1,44 @@
import { objectFromPath } from '../parse.js';
describe('objectFromPath()', () => {
it('start index', () => {
const arr = ['index'];
const value = 1;
const objExpected = { index: 1 };
const obj = objectFromPath(arr, value);
expect(obj).toStrictEqual(objExpected);
});
it('set timer message text', () => {
const arr = ['timer', 'text'];
const value = 'hello';
const objExpected = { timer: { text: value } };
const obj = objectFromPath(arr, value);
expect(obj).toStrictEqual(objExpected);
});
it('set timer message text and visible', () => {
const arr = ['timer'];
const value = { text: 'hello', visible: true };
const objExpected = { timer: value };
const obj = objectFromPath(arr, value);
expect(obj).toStrictEqual(objExpected);
});
it('nests object with undefined value', () => {
const arr = ['a', 'b', 'c', 'd'];
const objExpected = { a: { b: { c: { d: undefined } } } };
const obj = objectFromPath(arr);
expect(obj).toStrictEqual(objExpected);
});
it('empty array creates undefinde object', () => {
const arr = [];
const value = '1234567890';
const objExpected = null;
const obj = objectFromPath(arr, value);
expect(obj).toStrictEqual(objExpected);
});
});
+11
View File
@@ -0,0 +1,11 @@
/**
* @description Creates a nested object with keys from an array and assigns the `value` to the last key
* @param {array} path - array to be nested
* @param {string} value - value to assign
* @returns {object | null} nested object or null if no object was created
*/
export const objectFromPath = (path: string[], value?: unknown): object | null => {
const obj = path.reduceRight((result, key) => ({ [key]: result }), value);
if (typeof obj === 'object') return obj;
return null;
};
+1 -4
View File
@@ -174,10 +174,7 @@ export const startServer = async () => {
* - Runtime Service publicEventNext
*/
eventStore.init({
timerMessage: messageService.timerMessage,
publicMessage: messageService.publicMessage,
lowerMessage: messageService.lowerMessage,
externalMessage: messageService.externalMessage,
message: messageService,
onAir: state.playback !== Playback.Stop,
timer: state.timer,
playback: state.playback,
@@ -1,11 +1,14 @@
import { DeepPartial, MessageState } from 'ontime-types';
// skipcq: JS-C1003 - we like the API
import * as assert from '../utils/assert.js';
import { ONTIME_VERSION } from '../ONTIME_VERSION.js';
import { isPartialTimerMessage, messageService } from '../services/message-service/MessageService.js';
import { messageService } from '../services/message-service/MessageService.js';
import { runtimeService } from '../services/runtime-service/RuntimeService.js';
import { eventStore } from '../stores/EventStore.js';
import { parse, updateEvent } from './integrationController.config.js';
import { validateMessage, validateTimerMessage } from '../services/message-service/messageUtils.js';
export type ChangeOptions = {
eventId: string;
@@ -32,11 +35,10 @@ export function dispatchFromAdapter(
type ActionHandler = (payload: unknown) => { payload: unknown };
// TODO: add data to missing returns once available
const actionHandlers: Record<string, ActionHandler> = {
/* General */
'test-ontime': () => ({ payload: `Hello from Ontime version ${ONTIME_VERSION}` }),
'ontime-poll': () => ({
version: () => ({ payload: ONTIME_VERSION }),
poll: () => ({
payload: eventStore.poll(),
}),
change: (payload) => {
@@ -48,123 +50,56 @@ const actionHandlers: Record<string, ActionHandler> = {
return { payload: updatedEvent };
},
/* Message Service */
'set-timer-message': (payload) => {
if (!isPartialTimerMessage(payload)) {
throw new Error('Payload is not a valid timer message');
}
const newState = messageService.setTimerMessage(payload);
return { payload: newState.timerMessage };
},
'set-timer-blink': (payload) => {
assert.isDefined(payload);
const newState = messageService.setTimerBlink(Boolean(payload));
return { payload: newState.timerMessage };
},
'set-timer-blackout': (payload) => {
assert.isDefined(payload);
const newState = messageService.setTimerBlackout(Boolean(payload));
return { payload: newState.timerMessage };
},
'set-timer-message-text': (payload) => {
assert.isString(payload);
const newState = messageService.setTimerText(payload);
return { payload: newState.timerMessage };
},
'set-timer-message-visible': (payload) => {
assert.isDefined(payload);
const newState = messageService.setTimerVisibility(Boolean(payload));
return { payload: newState.timerMessage };
},
'set-public-message-text': (payload) => {
assert.isString(payload);
const newState = messageService.setPublicText(payload);
return { payload: newState.publicMessage };
},
'set-public-message-visible': (payload) => {
assert.isDefined(payload);
const newState = messageService.setPublicVisibility(Boolean(payload));
return { payload: newState.publicMessage };
},
'set-lower-message-text': (payload) => {
assert.isString(payload);
const newState = messageService.setLowerText(payload);
return { payload: newState.lowerMessage };
},
'set-lower-message-visible': (payload) => {
assert.isDefined(payload);
const newState = messageService.setLowerVisibility(Boolean(payload));
return { payload: newState.lowerMessage };
},
'set-external-message-text': (payload) => {
assert.isString(payload);
const newState = messageService.setExternalText(payload);
return { payload: newState.externalMessage };
},
'set-external-message-visible': (payload) => {
assert.isDefined(payload);
const newState = messageService.setExternalVisibility(Boolean(payload));
return { payload: newState.externalMessage };
message: (payload) => {
assert.isObject(payload);
const patch: DeepPartial<MessageState> = {
timer: 'timer' in payload ? validateTimerMessage(payload.timer) : undefined,
public: 'public' in payload ? validateMessage(payload.public) : undefined,
lower: 'lower' in payload ? validateMessage(payload.lower) : undefined,
external: 'external' in payload ? validateMessage(payload.external) : undefined,
};
const newMessage = messageService.patch(patch);
return { payload: newMessage };
},
/* Playback */
start: (payload) => {
if (payload && typeof payload === 'object') {
if ('next' in payload) {
runtimeService.startNext();
return { payload: 'start' };
}
if ('index' in payload) {
const reply = actionHandlers.startindex(payload.index);
return reply;
const eventIndex = numberOrError(payload.index);
if (eventIndex <= 0) {
throw new Error(`Event index out of range ${eventIndex}`);
}
// Indexes in frontend are 1 based
const success = runtimeService.startByIndex(eventIndex - 1);
if (!success) {
throw new Error(`Event index not recognised or out of range ${eventIndex}`);
}
return { payload: 'success' };
}
if ('id' in payload) {
const reply = actionHandlers.startid(payload.id);
return reply;
assert.isString(payload);
runtimeService.startById(payload);
return { payload: 'success' };
}
if ('cue' in payload) {
const reply = actionHandlers.startcue(payload.cue);
return reply;
assert.isString(payload);
runtimeService.startByCue(payload);
return { payload: 'success' };
}
}
runtimeService.start();
return { payload: 'start' };
},
'start-next': () => {
runtimeService.startNext();
return { payload: 'start' };
},
startindex: (payload) => {
const eventIndex = numberOrError(payload);
if (eventIndex <= 0) {
throw new Error(`Event index out of range ${eventIndex}`);
}
// Indexes in frontend are 1 based
const success = runtimeService.startByIndex(eventIndex - 1);
if (!success) {
throw new Error(`Event index not recognised or out of range ${eventIndex}`);
}
return { payload: 'success' };
},
startid: (payload) => {
assert.isString(payload);
runtimeService.startById(payload);
return { payload: 'success' };
},
startcue: (payload) => {
assert.isString(payload);
runtimeService.startByCue(payload);
return { payload: 'success' };
},
pause: () => {
runtimeService.pause();
return { payload: 'success' };
},
previous: () => {
runtimeService.loadPrevious();
return { payload: 'success' };
},
next: () => {
runtimeService.loadNext();
return { payload: 'success' };
},
stop: () => {
runtimeService.stop();
return { payload: 'success' };
@@ -177,24 +112,37 @@ const actionHandlers: Record<string, ActionHandler> = {
runtimeService.roll();
return { payload: 'success' };
},
loadindex: (payload) => {
const eventIndex = numberOrError(payload);
if (eventIndex <= 0) {
throw new Error(`Event index out of range ${eventIndex}`);
load: (payload) => {
if (payload && typeof payload === 'object') {
if ('index' in payload) {
const eventIndex = numberOrError(payload.index);
if (eventIndex <= 0) {
throw new Error(`Event index out of range ${eventIndex}`);
}
// Indexes in frontend are 1 based
runtimeService.loadByIndex(eventIndex - 1);
return { payload: 'success' };
}
if ('id' in payload) {
assert.isDefined(payload.id);
runtimeService.loadById(payload.id.toString().toLowerCase());
return { payload: 'success' };
}
if ('cue' in payload) {
assert.isString(payload.cue);
runtimeService.loadByCue(payload.cue);
return { payload: 'success' };
}
if ('next' in payload) {
runtimeService.loadNext();
return { payload: 'success' };
}
if ('previous' in payload) {
runtimeService.loadPrevious();
return { payload: 'success' };
}
}
// Indexes in frontend are 1 based
runtimeService.loadByIndex(eventIndex - 1);
return { payload: 'success' };
},
loadid: (payload) => {
assert.isDefined(payload);
runtimeService.loadById(payload.toString().toLowerCase());
return { payload: 'success' };
},
loadcue: (payload) => {
assert.isString(payload);
runtimeService.loadByCue(payload);
return { payload: 'success' };
throw new Error('No load method provided');
},
addtime: (payload) => {
const time = numberOrError(payload);
+10 -2
View File
@@ -2,6 +2,7 @@ import express from 'express';
import { dispatchFromAdapter } from '../controllers/integrationController.js';
import { logger } from '../classes/Logger.js';
import { LogOrigin } from 'ontime-types';
import { objectFromPath } from '../adapters/utils/parse.js';
export const router = express.Router();
@@ -14,8 +15,15 @@ router.get('/', (_req, res) => {
// any GET request in /api is sent to the integration controller
router.get('/*', (req, res) => {
const action = req.path.substring(1);
const params = { payload: req.query };
let action = req.path.substring(1);
const actionArray = action.split('/');
const params = { payload: req.query as object };
if (actionArray.length > 1) {
action = actionArray.shift();
params.payload = objectFromPath(actionArray, params.payload);
}
try {
const reply = dispatchFromAdapter(action, params, 'http');
@@ -1,4 +1,4 @@
import { Message, TimerMessage } from 'ontime-types';
import { DeepPartial, Message, TimerMessage, MessageState } from 'ontime-types';
import { throttle } from '../../utils/throttle.js';
@@ -7,10 +7,10 @@ import type { PublishFn } from '../../stores/EventStore.js';
let instance;
class MessageService {
timerMessage: TimerMessage;
publicMessage: Message;
lowerMessage: Message;
externalMessage: Message;
timer: TimerMessage;
public: Message;
lower: Message;
external: Message;
private throttledSet: PublishFn;
private publish: PublishFn | null;
@@ -23,31 +23,35 @@ class MessageService {
// eslint-disable-next-line @typescript-eslint/no-this-alias -- this logic is used to ensure singleton
instance = this;
this.timerMessage = {
text: '',
visible: false,
timerBlink: false,
timerBlackout: false,
};
this.publicMessage = {
text: '',
visible: false,
};
this.lowerMessage = {
text: '',
visible: false,
};
this.externalMessage = {
text: '',
visible: false,
};
this.throttledSet = () => {
throw new Error('Published called before initialisation');
};
this.clear();
}
clear() {
this.timer = {
text: '',
visible: false,
blink: false,
blackout: false,
};
this.public = {
text: '',
visible: false,
};
this.lower = {
text: '',
visible: false,
};
this.external = {
text: '',
visible: false,
};
}
init(publish: PublishFn) {
@@ -55,144 +59,26 @@ class MessageService {
this.throttledSet = throttle((key, value) => this.publish(key, value), 100);
}
/**
* @description sets message on stage timer screen
*/
setExternalText(payload: string) {
if (this.externalMessage.text !== payload) {
this.externalMessage.text = payload;
this.throttledSet('externalMessage', this.externalMessage);
}
return this.getAll();
}
/**
* @description sets message visibility on stage timer screen
*/
setExternalVisibility(status: boolean) {
this.externalMessage.visible = status;
this.throttledSet('externalMessage', this.externalMessage);
return this.getAll();
}
/**
* @description patches the TimerMessage object
*/
setTimerMessage(payload: Partial<TimerMessage>) {
this.timerMessage = { ...this.timerMessage, ...payload };
this.throttledSet('timerMessage', this.timerMessage);
return this.getAll();
}
/**
* @description sets message on stage timer screen
*/
setTimerText(payload: string) {
this.timerMessage.text = payload;
this.throttledSet('timerMessage', this.timerMessage);
return this.getAll();
}
/**
* @description sets message visibility on stage timer screen
*/
setTimerVisibility(status: boolean) {
this.timerMessage.visible = status;
this.throttledSet('timerMessage', this.timerMessage);
return this.getAll();
}
/**
* @description sets message on public screen
*/
setPublicText(payload: string) {
this.publicMessage.text = payload;
this.throttledSet('publicMessage', this.publicMessage);
return this.getAll();
}
/**
* @description sets message visibility on public screen
*/
setPublicVisibility(status: boolean) {
this.publicMessage.visible = status;
this.throttledSet('publicMessage', this.publicMessage);
return this.getAll();
}
/**
* @description sets message on lower third screen
*/
setLowerText(payload: string) {
this.lowerMessage.text = payload;
this.throttledSet('lowerMessage', this.lowerMessage);
return this.getAll();
}
/**
* @description sets message visibility on lower third screen
*/
setLowerVisibility(status: boolean) {
this.lowerMessage.visible = status;
this.throttledSet('lowerMessage', this.lowerMessage);
return this.getAll();
}
/**
* @description set state of timer blink, toggles if parameters are offered
*/
setTimerBlink(status?: boolean) {
if (typeof status === 'undefined') {
this.timerMessage.timerBlink = !this.timerMessage.timerBlink;
} else {
this.timerMessage.timerBlink = status;
}
this.throttledSet('timerMessage', this.timerMessage);
return this.getAll();
}
/**
* @description set state of timer blackout, toggles if parameters are offered
*/
setTimerBlackout(status?: boolean) {
if (typeof status === 'undefined') {
this.timerMessage.timerBlackout = !this.timerMessage.timerBlackout;
} else {
this.timerMessage.timerBlackout = status;
}
this.throttledSet('timerMessage', this.timerMessage);
return this.getAll();
}
/**
* @description Returns feature data
*/
getAll() {
getState(): MessageState {
return {
timerMessage: this.timerMessage,
publicMessage: this.publicMessage,
lowerMessage: this.lowerMessage,
externalMessage: this.externalMessage,
timer: this.timer,
public: this.public,
lower: this.lower,
external: this.external,
};
}
patch(message: DeepPartial<MessageState>) {
if (message.timer) this.timer = { ...this.timer, ...message.timer };
if (message.public) this.public = { ...this.public, ...message.public };
if (message.lower) this.lower = { ...this.lower, ...message.lower };
if (message.external) this.external = { ...this.external, ...message.external };
const newState = this.getState();
this.throttledSet('message', newState);
return newState;
}
}
export const messageService = new MessageService();
/**
* Asserts whether an object is a valid TimerMessage patch
* @param obj - object to evaluate
* @returns boolean
*/
export function isPartialTimerMessage(obj: any): obj is Partial<TimerMessage> {
return (
obj &&
typeof obj === 'object' &&
(typeof obj.text === 'string' || obj.text === undefined) &&
(typeof obj.visible === 'boolean' || obj.visible === undefined) &&
(typeof obj.timerBlink === 'boolean' || obj.timerBlink === undefined) &&
(typeof obj.timerBlackout === 'boolean' || obj.timerBlackout === undefined)
);
}
@@ -0,0 +1,59 @@
import { messageService } from '../MessageService.js';
describe('MessageService', () => {
const publishFunction = () => {};
beforeAll(() => {
messageService.init(publishFunction);
});
beforeEach(() => {
messageService.clear();
});
it('should patch the message state', () => {
const message = {
timer: { text: 'new text', visible: true },
public: { text: 'public text', visible: false },
lower: { text: 'lower text' },
external: { visible: true },
};
const newState = messageService.patch(message);
expect(newState).toEqual({
timer: { text: 'new text', visible: true, blackout: false, blink: false },
public: { text: 'public text', visible: false },
lower: {
text: 'lower text',
visible: false,
},
external: {
text: '',
visible: true,
},
});
});
it('should not affect other properties when patching', () => {
const initialMessage = {
timer: { text: 'initial text', visible: true },
public: { text: 'public text', visible: false },
};
const newState = messageService.patch(initialMessage);
expect(newState).toEqual({
timer: { text: 'initial text', visible: true, blackout: false, blink: false },
public: { text: 'public text', visible: false },
lower: {
text: '',
visible: false,
},
external: {
text: '',
visible: false,
},
});
});
});
@@ -0,0 +1,55 @@
import { validateMessage, validateTimerMessage } from '../messageUtils.js';
describe('validateMessage()', () => {
it('returns a valid Message object', () => {
const payload = {
text: '12312',
visible: 'true',
};
const expected = {
text: '12312',
visible: true,
};
expect(validateMessage(payload)).toEqual(expected);
});
it('skips keys not given', () => {
const payload = {
visible: 'true',
};
const expected = {
visible: true,
};
expect(validateMessage(payload)).toStrictEqual(expected);
});
});
describe('validateTimerMessage()', () => {
it('returns a valid Timer Message object', () => {
const payload = {
text: '12312',
visible: 'true',
blink: 'true',
blackout: 'true',
};
const expected = {
text: '12312',
visible: true,
blink: true,
blackout: true,
};
expect(validateTimerMessage(payload)).toEqual(expected);
});
it('skips keys not given', () => {
const payload = {
visible: 'true',
};
const expected = {
visible: true,
};
expect(validateTimerMessage(payload)).toStrictEqual(expected);
});
});
@@ -0,0 +1,35 @@
import { Message, TimerMessage } from 'ontime-types';
import * as assert from '../../utils/assert.js';
import { coerceBoolean, coerceString } from '../../utils/coerceType.js';
/**
* Creates a valid Message object from a payload
* @throws if the payload is not an object
*/
export function validateMessage(message: unknown): Partial<Message> {
assert.isObject(message);
const result: Partial<Message> = {};
if ('text' in message) result.text = coerceString(message.text);
if ('visible' in message) result.visible = coerceBoolean(message.visible);
return result;
}
/**
* Creates a valid Timer Message object from a payload
* @throws if the payload is not an object
*/
export function validateTimerMessage(message: unknown): Partial<TimerMessage> {
assert.isObject(message);
const result: Partial<TimerMessage> = {};
if ('text' in message) result.text = coerceString(message.text);
if ('visible' in message) result.visible = coerceBoolean(message.visible);
if ('blink' in message) result.blink = coerceBoolean(message.blink);
if ('blackout' in message) result.blackout = coerceBoolean(message.blackout);
return result;
}
+6
View File
@@ -15,3 +15,9 @@ export function isNumber(value: unknown): asserts value is number {
throw new Error(`Unexpected payload type: ${value}`);
}
}
export function isObject(value: unknown): asserts value is object {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new Error(`Unexpected payload type: ${value}`);
}
}