mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-13 11:23:50 +00:00
V3 (#657)
* refactor: cleanup routes * style: smaller base font * chore: upgrade dependencies * chore: lock node version to electron * refactor: pass HTTP to integration controller (#652) * refactor: deprecate onair control * refactor: remove playback router * Several project files user folder (#617) * chore: automated screenshots (#667) * feat: app settings (#658) * refactor: remove deprecated event data (#674) * Studio clock (#663) --------- Co-authored-by: Carlos Valente <carlosvalente@pm.me> * Feat: reorder events with alt+ctrl + arrow up/down (#645) * Warning and danger per event (#677) --------- Co-authored-by: Fabian Posenau <fabian@fphome.de> * refactor: stabilise actionHandler (#683) Co-authored-by: Fabian Posenau <fabian@fphome.de> * improvement: hide seconds (#675) * wip: overview (#688) * fix: focus cursor (#695) * refactor: update lower third (#665) * Refactor/time formatting (#696) --------- Co-authored-by: Carlos Valente <34649812+cpvalente@users.noreply.github.com> Co-authored-by: Carlos Valente <carlosvalente@pm.me> * feat: multiple selection (#703) --------- Co-authored-by: asharonbaltazar <asharonbaltazar@outlook.com> Co-authored-by: Alex <ac@omnivox.dk> * fix: test - go to `Edit mode` befor tying to click `Event options` button (#708) * refactor: runtime service (#715) * fix: issue with loosing cursor position on message (#719) * remove info panel (#721) * Event editor continue (#722) * update API - part (#709) --------- Co-authored-by: Carlos Valente <34649812+cpvalente@users.noreply.github.com> Co-authored-by: Carlos Valente <carlosvalente@pm.me> * refactor: update timers (#729) * feat: many timers (#706) --------- Co-authored-by: arc-alex <ac@omnivox.dk> * refactor: excel cleanup (#734) * refactor: allow import of blocks and skip import (#735) * Project manager (#697) * refactor: UI for linking events (#763) * upgraded pipeline actions (#777) * Over under (#771) * custom fields (#744) --------- Co-authored-by: Carlos Valente <carlosvalente@pm.me> * Sheets settings (#774) --------- Co-authored-by: arc-alex <ac@omnivox.dk> * style: tweaks to lower thirds (#785) * refactor: delays account for gaps (#784) * refactor: partial state updates (#780) * feat: generate crash report (#787) * Sheet use limited input device auth flow (#782) --------- Co-authored-by: cv <34649812+cpvalente@users.noreply.github.com> Co-authored-by: Carlos Valente <carlosvalente@pm.me> * Custom fields views (#789) * refactor: deprecate presenter and subtitle (#795) * refactor: organise API around resources (#798) --------- Co-authored-by: Bianca Procopio <biancahprocopio@gmail.com> * Time to end (#804) * Skip fixes (#805) * fix: onair derives from playback * Param nav (#822) --------- Co-authored-by: Alex Christoffer Rasmussen <ac@omnivox.dk> * refactor: download files from interface (#831) * Quick options (#814) * End pause (#832) * chore: bump node version in docker (#834) * refactor: follow in run mode (#840) * fix: uncaught error in http integration (#837) * Apply project (#843) Co-authored-by: Matteo Gheza <matteo.gheza07@gmail.com> Co-authored-by: Ary <arylmoraesn@gmail.com> Co-authored-by: Alex Christoffer Rasmussen <ac@omnivox.dk> Co-authored-by: Fabian Posenau <19673098+kellhogs@users.noreply.github.com> Co-authored-by: Fabian Posenau <fabian@fphome.de> Co-authored-by: Alex Rohleder <alexrohleder96@gmail.com> Co-authored-by: asharonbaltazar <asharonbaltazar@outlook.com> Co-authored-by: Bianca Procopio <biancahprocopio@gmail.com> Co-authored-by: Fabian Posenau <fabianpos99+github@gmail.com>
This commit is contained in:
@@ -1,27 +1,29 @@
|
||||
import { LogOrigin, OSCSettings } from 'ontime-types';
|
||||
import { LogOrigin } from 'ontime-types';
|
||||
|
||||
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 { integrationPayloadFromPath } from './utils/parse.js';
|
||||
import { dispatchFromAdapter } from '../api-integration/integration.controller.js';
|
||||
|
||||
export class OscServer implements IAdapter {
|
||||
private readonly osc: Server;
|
||||
|
||||
constructor(config: OSCSettings) {
|
||||
this.osc = new Server(config.portIn, '0.0.0.0');
|
||||
constructor(portIn: number) {
|
||||
this.osc = new Server(portIn, '0.0.0.0');
|
||||
|
||||
this.osc.on('error', (error) => logger.error(LogOrigin.Rx, `OSC IN: ${error}`));
|
||||
|
||||
this.osc.on('message', (msg) => {
|
||||
// message should look like /ontime/{path}/{params?} {args} where
|
||||
// message should look like /ontime/{command}/{params?} {args} where
|
||||
// ontime: fixed message for app
|
||||
// path: command to be called
|
||||
// args: extra data, only used on some API entries (delay, goto)
|
||||
// command: command to be called
|
||||
// params: used to create a nested object to patch with
|
||||
// args: extra data, only used on some API entries
|
||||
|
||||
// split message
|
||||
const [, address, path, ...params] = msg[0].split('/');
|
||||
const [, address, command, ...params] = msg[0].split('/');
|
||||
const args = msg[1];
|
||||
|
||||
// get first part before (ontime)
|
||||
@@ -31,48 +33,19 @@ export class OscServer implements IAdapter {
|
||||
}
|
||||
|
||||
// get second part (command)
|
||||
if (!path) {
|
||||
if (!command) {
|
||||
logger.error(LogOrigin.Rx, 'OSC IN: No path found');
|
||||
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;
|
||||
// we need to transform the params for the more complex endpoints
|
||||
if (params.length) {
|
||||
transformedPayload = integrationPayloadFromPath(params, args);
|
||||
}
|
||||
|
||||
try {
|
||||
const reply = dispatchFromAdapter(
|
||||
path,
|
||||
{
|
||||
payload: transformedPayload,
|
||||
},
|
||||
'osc',
|
||||
);
|
||||
if (reply) {
|
||||
const { topic, payload } = reply;
|
||||
this.osc.emit(topic, payload);
|
||||
}
|
||||
dispatchFromAdapter(command, transformedPayload, 'osc');
|
||||
} catch (error) {
|
||||
logger.error(LogOrigin.Rx, `OSC IN: ${error}`);
|
||||
}
|
||||
@@ -80,7 +53,6 @@ export class OscServer implements IAdapter {
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
console.log('Shutting down OSC Server');
|
||||
this.osc?.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,10 +22,10 @@ import type { Server } from 'http';
|
||||
import getRandomName from '../utils/getRandomName.js';
|
||||
import { IAdapter } from './IAdapter.js';
|
||||
import { eventStore } from '../stores/EventStore.js';
|
||||
import { dispatchFromAdapter } from '../controllers/integrationController.js';
|
||||
import { logger } from '../classes/Logger.js';
|
||||
import { dispatchFromAdapter } from '../api-integration/integration.controller.js';
|
||||
|
||||
let instance;
|
||||
let instance: SocketServer | null = null;
|
||||
|
||||
export class SocketServer implements IAdapter {
|
||||
private readonly MAX_PAYLOAD = 1024 * 256; // 256Kb
|
||||
@@ -45,12 +45,12 @@ export class SocketServer implements IAdapter {
|
||||
}
|
||||
|
||||
init(server: Server) {
|
||||
this.wss = new WebSocketServer({ path: '/ws', server });
|
||||
this.wss = new WebSocketServer({ path: '/ws', server, maxPayload: this.MAX_PAYLOAD });
|
||||
|
||||
this.wss.on('connection', (ws) => {
|
||||
let clientId = getRandomName();
|
||||
this.clientIds.add(clientId);
|
||||
logger.info(LogOrigin.Client, `${this.wss.clients.size} Connections with new: ${clientId}`);
|
||||
logger.info(LogOrigin.Client, `${this.clientIds.size} Connections with new: ${clientId}`);
|
||||
|
||||
// send store payload on connect
|
||||
ws.send(
|
||||
@@ -70,16 +70,13 @@ export class SocketServer implements IAdapter {
|
||||
ws.on('error', console.error);
|
||||
|
||||
ws.on('close', () => {
|
||||
logger.info(LogOrigin.Client, `${this.wss.clients.size} Connections with disconnected: ${clientId}`);
|
||||
this.clientIds.delete(clientId);
|
||||
logger.info(LogOrigin.Client, `${this.clientIds.size} Connections with disconnected: ${clientId}`);
|
||||
});
|
||||
|
||||
ws.on('message', (data) => {
|
||||
if (data.length > this.MAX_PAYLOAD) {
|
||||
ws.close();
|
||||
}
|
||||
|
||||
try {
|
||||
// @ts-expect-error -- ??
|
||||
const message = JSON.parse(data);
|
||||
const { type, payload } = message;
|
||||
|
||||
@@ -110,11 +107,6 @@ export class SocketServer implements IAdapter {
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === 'hello') {
|
||||
ws.send('hi');
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === 'ontime-log') {
|
||||
if (payload.level && payload.origin && payload.text) {
|
||||
logger.emit(payload.level, payload.origin, payload.text);
|
||||
@@ -124,16 +116,14 @@ export class SocketServer implements IAdapter {
|
||||
|
||||
// Protocol specific stuff handled above
|
||||
try {
|
||||
const reply = dispatchFromAdapter(
|
||||
type,
|
||||
{
|
||||
payload,
|
||||
},
|
||||
'ws',
|
||||
);
|
||||
const reply = dispatchFromAdapter(type, payload, 'ws');
|
||||
if (reply) {
|
||||
const { topic, payload } = reply;
|
||||
ws.send(topic, payload);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'ontime-change',
|
||||
payload: reply.payload,
|
||||
}),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(LogOrigin.Rx, `WS IN: ${error}`);
|
||||
@@ -148,8 +138,12 @@ export class SocketServer implements IAdapter {
|
||||
// message is any serializable value
|
||||
sendAsJson(message: unknown) {
|
||||
this.wss?.clients.forEach((client) => {
|
||||
if (client !== this.wss && client.readyState === WebSocket.OPEN) {
|
||||
client.send(JSON.stringify(message));
|
||||
try {
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
client.send(JSON.stringify(message));
|
||||
}
|
||||
} catch (_) {
|
||||
/** We do not handle this error */
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { integrationPayloadFromPath } from '../parse.js';
|
||||
|
||||
describe('objectFromPath()', () => {
|
||||
it('start index', () => {
|
||||
const arr = ['index'];
|
||||
const value = 1;
|
||||
const objExpected = { index: 1 };
|
||||
|
||||
const obj = integrationPayloadFromPath(arr, value);
|
||||
expect(obj).toStrictEqual(objExpected);
|
||||
});
|
||||
it('start next', () => {
|
||||
const arr = ['next'];
|
||||
const value = undefined;
|
||||
const objExpected = 'next';
|
||||
|
||||
const obj = integrationPayloadFromPath(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 = integrationPayloadFromPath(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 = integrationPayloadFromPath(arr, value);
|
||||
expect(obj).toStrictEqual(objExpected);
|
||||
});
|
||||
|
||||
it('nests object with undefined value', () => {
|
||||
const arr = ['a', 'b', 'c', 'd'];
|
||||
const objExpected = { a: { b: { c: 'd' } } };
|
||||
|
||||
const obj = integrationPayloadFromPath(arr);
|
||||
expect(obj).toStrictEqual(objExpected);
|
||||
});
|
||||
it('empty array creates undefined object', () => {
|
||||
const arr: string[] = [];
|
||||
const value = '1234567890';
|
||||
const objExpected = null;
|
||||
|
||||
const obj = integrationPayloadFromPath(arr, value);
|
||||
expect(obj).toStrictEqual(objExpected);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* @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 | string | null} nested object or null if no object was created
|
||||
*/
|
||||
export const integrationPayloadFromPath = (path: string[], value?: unknown): object | string | null => {
|
||||
if (path.length === 1) {
|
||||
const key = path[0];
|
||||
return value === undefined ? key : { [key]: value };
|
||||
}
|
||||
|
||||
const parsedValue = value === undefined ? path.at(-1) : value;
|
||||
const shortenedPath = value === undefined ? path.slice(0, -1) : path;
|
||||
|
||||
const obj = shortenedPath.reduceRight((result, key) => ({ [key]: result }), parsedValue);
|
||||
|
||||
return typeof obj === 'object' ? obj : null;
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
import { CustomField, CustomFields, ErrorResponse } from 'ontime-types';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
import {
|
||||
createCustomField,
|
||||
editCustomField,
|
||||
getCustomFields as getCustomFieldsFromCache,
|
||||
removeCustomField,
|
||||
} from '../../services/rundown-service/rundownCache.js';
|
||||
|
||||
export async function getCustomFields(_req: Request, res: Response<CustomFields>) {
|
||||
const customFields = getCustomFieldsFromCache();
|
||||
res.json(customFields);
|
||||
}
|
||||
|
||||
export async function postCustomField(req: Request, res: Response<CustomFields | ErrorResponse>) {
|
||||
try {
|
||||
const newField = req.body as CustomField;
|
||||
const allFields = await createCustomField(newField);
|
||||
res.status(201).send(allFields);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function putCustomField(req: Request, res: Response<CustomFields | ErrorResponse>) {
|
||||
try {
|
||||
const oldLabel = req.params.label;
|
||||
const { colour, type, label } = req.body;
|
||||
const newFields = await editCustomField(oldLabel, { label, colour, type });
|
||||
res.status(200).send(newFields);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
// Expects { label: <label> }
|
||||
export async function deleteCustomField(req: Request, res: Response<CustomFields | ErrorResponse>) {
|
||||
try {
|
||||
const fieldToDelete = req.params.label;
|
||||
await removeCustomField(fieldToDelete);
|
||||
res.sendStatus(204);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import express from 'express';
|
||||
|
||||
import { deleteCustomField, getCustomFields, postCustomField, putCustomField } from './customFields.controller.js';
|
||||
import { validateCustomField, validateDeleteCustomField, validateEditCustomField } from './customFields.validation.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
router.get('/', getCustomFields);
|
||||
|
||||
router.post('/', validateCustomField, postCustomField);
|
||||
|
||||
router.put('/:label', validateEditCustomField, putCustomField);
|
||||
|
||||
router.delete('/:label', validateDeleteCustomField, deleteCustomField);
|
||||
@@ -0,0 +1,45 @@
|
||||
import { isAlphanumeric } from 'ontime-utils';
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { body, param, validationResult } from 'express-validator';
|
||||
|
||||
export const validateCustomField = [
|
||||
body('label')
|
||||
.exists()
|
||||
.isString()
|
||||
.trim()
|
||||
.custom((value) => {
|
||||
return isAlphanumeric(value);
|
||||
}),
|
||||
body('type').exists().isString().trim(),
|
||||
body('colour').exists().isString().trim(),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
export const validateEditCustomField = [
|
||||
param('label').exists().isString().trim(),
|
||||
body('label').exists().isString().trim(),
|
||||
body('type').exists().isString().trim(),
|
||||
body('colour').exists().isString().trim(),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
export const validateDeleteCustomField = [
|
||||
param('label').exists().isString(),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,253 @@
|
||||
import {
|
||||
DatabaseModel,
|
||||
ErrorResponse,
|
||||
GetInfo,
|
||||
MessageResponse,
|
||||
ProjectData,
|
||||
ProjectFileListResponse,
|
||||
} from 'ontime-types';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
|
||||
import { failEmptyObjects } from '../../utils/routerUtils.js';
|
||||
import { resolveDbPath, resolveProjectsDirectory } from '../../setup/index.js';
|
||||
|
||||
import * as projectService from '../../services/project-service/ProjectService.js';
|
||||
import { ensureJsonExtension } from '../../utils/fileManagement.js';
|
||||
import { generateUniqueFileName } from '../../utils/generateUniqueFilename.js';
|
||||
import { appStateService } from '../../services/app-state-service/AppStateService.js';
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
|
||||
export async function patchPartialProjectFile(req: Request, res: Response<DatabaseModel | ErrorResponse>) {
|
||||
// all fields are optional in validation
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
res.status(400).send({ message: 'No field found to patch' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { rundown, project, settings, viewSettings, urlPresets, customFields, osc, http } = req.body;
|
||||
const patchDb: DatabaseModel = { rundown, project, settings, viewSettings, urlPresets, customFields, osc, http };
|
||||
|
||||
const newData = await projectService.applyDataModel(patchDb);
|
||||
res.status(200).send(newData);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new project file.
|
||||
* Receives the project filename (`filename`) from the request body.
|
||||
*
|
||||
* @param {Request} req - The express request object. Expects `filename` in the request body.
|
||||
* @param {Response} res - The express response object. Sends a 200 status with a success message upon successful creation,
|
||||
* a 409 status if there are validation errors,
|
||||
* or a 500 status with an error message in case of an exception.
|
||||
*/
|
||||
export async function createProjectFile(req: Request, res: Response<{ filename: string } | ErrorResponse>) {
|
||||
try {
|
||||
const originalFilename = ensureJsonExtension(req.body.title || 'Untitled');
|
||||
const filename = generateUniqueFileName(resolveProjectsDirectory, originalFilename);
|
||||
const errors = projectService.validateProjectFiles({ newFilename: filename });
|
||||
|
||||
if (errors.length) {
|
||||
return res.status(409).send({ message: 'Project with title already exists' });
|
||||
}
|
||||
|
||||
const newProjectData: ProjectData = {
|
||||
title: req.body?.title ?? '',
|
||||
description: req.body?.description ?? '',
|
||||
publicUrl: req.body?.publicUrl ?? '',
|
||||
publicInfo: req.body?.publicInfo ?? '',
|
||||
backstageUrl: req.body?.backstageUrl ?? '',
|
||||
backstageInfo: req.body?.backstageInfo ?? '',
|
||||
};
|
||||
|
||||
projectService.createProjectFile(filename, newProjectData);
|
||||
|
||||
res.status(200).send({
|
||||
filename,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function projectDownload(_req: Request, res: Response) {
|
||||
const fileTitle = projectService.getProjectTitle();
|
||||
res.download(resolveDbPath, `${fileTitle}.json`, (error) => {
|
||||
if (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* uploads, parses and applies the data from a given file
|
||||
*/
|
||||
export async function postProjectFile(req: Request, res: Response<MessageResponse | ErrorResponse>) {
|
||||
if (!req.file) {
|
||||
res.status(400).send({ message: 'File not found' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const options = req.query;
|
||||
const { filename, path } = req.file;
|
||||
|
||||
await projectService.handleUploadedFile(path, filename);
|
||||
await projectService.applyProjectFile(filename, options);
|
||||
|
||||
res.status(201).send({
|
||||
message: `Loaded project ${filename}`,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves and lists all project files from the uploads directory.
|
||||
*/
|
||||
export async function listProjects(_req: Request, res: Response<ProjectFileListResponse | ErrorResponse>) {
|
||||
try {
|
||||
const data = await projectService.getProjectList();
|
||||
res.status(200).send(data);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Receives a `filename` from the request body and loads the project file from the uploads directory.
|
||||
*/
|
||||
export async function loadProject(req: Request, res: Response<MessageResponse | ErrorResponse>) {
|
||||
try {
|
||||
const name = req.body.filename;
|
||||
if (!projectService.doesProjectExist(name)) {
|
||||
return res.status(404).send({ message: 'File not found' });
|
||||
}
|
||||
|
||||
await projectService.applyProjectFile(name);
|
||||
|
||||
res.status(201).send({
|
||||
message: `Loaded project ${name}`,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Duplicates a project file.
|
||||
* Receives the original project filename (`filename`) from the request parameters
|
||||
* and the filename for the duplicate (`newFilename`) from the request body.
|
||||
*
|
||||
* @param {Request} req - The express request object. Expects `filename` in the request parameters and `newFilename` in the request body.
|
||||
* @param {Response} res - The express response object. Sends a 201 status with a success message upon successful duplication,
|
||||
* a 409 status if there are validation errors,
|
||||
* or a 500 status with an error message in case of an exception.
|
||||
*/
|
||||
export async function duplicateProjectFile(req: Request, res: Response<MessageResponse | ErrorResponse>) {
|
||||
try {
|
||||
const { filename } = req.params;
|
||||
const { newFilename } = req.body;
|
||||
|
||||
const errors = projectService.validateProjectFiles({ filename, newFilename });
|
||||
|
||||
if (errors.length) {
|
||||
return res.status(409).send({ message: errors.join(', ') });
|
||||
}
|
||||
|
||||
await projectService.duplicateProjectFile(filename, newFilename);
|
||||
|
||||
res.status(201).send({
|
||||
message: `Duplicated project ${filename} to ${newFilename}`,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames a project file.
|
||||
* Receives the current filename (`filename`) from the request parameters
|
||||
* and the new filename (`newFilename`) from the request body.
|
||||
*
|
||||
* @param {Request} req - The express request object. Expects `filename` in the request parameters and `newFilename` in the request body.
|
||||
* @param {Response} res - The express response object. Sends a 201 status with a success message upon successful renaming,
|
||||
* a 409 status if there are validation errors,
|
||||
* or a 500 status with an error message in case of an exception.
|
||||
*/
|
||||
export async function renameProjectFile(req: Request, res: Response<MessageResponse | ErrorResponse>) {
|
||||
try {
|
||||
const { newFilename } = req.body;
|
||||
const { filename } = req.params;
|
||||
|
||||
const errors = projectService.validateProjectFiles({ filename, newFilename });
|
||||
|
||||
if (errors.length) {
|
||||
return res.status(409).send({ message: errors.join(', ') });
|
||||
}
|
||||
|
||||
// Rename the file
|
||||
await projectService.renameProjectFile(filename, newFilename);
|
||||
|
||||
res.status(201).send({
|
||||
message: `Renamed project ${filename} to ${newFilename}`,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an existing project file.
|
||||
* Receives the project filename (`filename`) from the request parameters.
|
||||
*
|
||||
* @param {Request} req - The express request object. Expects `filename` in the request parameters.
|
||||
* @param {Response} res - The express response object. Sends a 204 status with a success message upon successful deletion,
|
||||
* a 403 status if attempting to delete the currently loaded project,
|
||||
* a 409 status if there are validation errors,
|
||||
* or a 500 status with an error message in case of an exception.
|
||||
*/
|
||||
export async function deleteProjectFile(req: Request, res: Response<MessageResponse | ErrorResponse>) {
|
||||
try {
|
||||
const { filename } = req.params;
|
||||
|
||||
const { lastLoadedProject } = await appStateService.get();
|
||||
|
||||
if (lastLoadedProject === filename) {
|
||||
return res.status(403).send({ message: 'Cannot delete currently loaded project' });
|
||||
}
|
||||
|
||||
const errors = projectService.validateProjectFiles({ filename });
|
||||
|
||||
if (errors.length) {
|
||||
return res.status(409).send({ message: errors.join(', ') });
|
||||
}
|
||||
|
||||
await projectService.deleteProjectFile(filename);
|
||||
|
||||
res.status(204).send({
|
||||
message: `Deleted project ${filename}`,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function getInfo(_req: Request, res: Response<GetInfo>) {
|
||||
const info = await projectService.getInfo();
|
||||
res.status(200).send(info);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Request } from 'express';
|
||||
import multer, { FileFilterCallback } from 'multer';
|
||||
|
||||
import { JSON_MIME } from '../../utils/parser.js';
|
||||
import { storage } from '../../utils/upload.js';
|
||||
|
||||
const filterProjectFile = (_req: Request, file: Express.Multer.File, cb: FileFilterCallback) => {
|
||||
if (file.mimetype.includes(JSON_MIME)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(null, false);
|
||||
}
|
||||
};
|
||||
|
||||
// Build multer uploader for a single file
|
||||
export const uploadProjectFile = multer({
|
||||
storage,
|
||||
fileFilter: filterProjectFile,
|
||||
}).single('project');
|
||||
@@ -0,0 +1,40 @@
|
||||
import express from 'express';
|
||||
|
||||
import {
|
||||
createProjectFile,
|
||||
deleteProjectFile,
|
||||
duplicateProjectFile,
|
||||
getInfo,
|
||||
listProjects,
|
||||
loadProject,
|
||||
patchPartialProjectFile,
|
||||
postProjectFile,
|
||||
projectDownload,
|
||||
renameProjectFile,
|
||||
} from './db.controller.js';
|
||||
import { uploadProjectFile } from './db.middleware.js';
|
||||
import {
|
||||
projectSanitiser,
|
||||
sanitizeProjectFilename,
|
||||
validateLoadProjectFile,
|
||||
validatePatchProjectFile,
|
||||
validateProjectDuplicate,
|
||||
validateProjectRename,
|
||||
} from './db.validation.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
router.get('/download', projectDownload);
|
||||
router.post('/upload', uploadProjectFile, postProjectFile);
|
||||
|
||||
router.patch('/', validatePatchProjectFile, patchPartialProjectFile);
|
||||
router.post('/new', projectSanitiser, createProjectFile);
|
||||
|
||||
router.get('/all', listProjects);
|
||||
|
||||
router.post('/load', validateLoadProjectFile, sanitizeProjectFilename, loadProject);
|
||||
router.post('/:filename/duplicate', validateProjectDuplicate, sanitizeProjectFilename, duplicateProjectFile);
|
||||
router.put('/:filename/rename', validateProjectRename, sanitizeProjectFilename, renameProjectFile);
|
||||
router.delete('/:filename', sanitizeProjectFilename, deleteProjectFile);
|
||||
|
||||
router.get('/info', getInfo);
|
||||
@@ -0,0 +1,106 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { body, validationResult } from 'express-validator';
|
||||
|
||||
import { ensureJsonExtension } from '../../utils/fileManagement.js';
|
||||
|
||||
export const projectSanitiser = [
|
||||
body('title').optional().isString().trim(),
|
||||
body('description').optional().isString().trim(),
|
||||
body('publicUrl').optional().isString().trim(),
|
||||
body('publicInfo').optional().isString().trim(),
|
||||
body('backstageUrl').optional().isString().trim(),
|
||||
body('backstageInfo').optional().isString().trim(),
|
||||
body('endMessage').optional().isString().trim(),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
export const sanitizeProjectFilename = (req: Request, _res: Response, next: NextFunction) => {
|
||||
const { filename, newFilename } = req.body;
|
||||
const { filename: projectName } = req.params;
|
||||
|
||||
req.body.filename = ensureJsonExtension(filename);
|
||||
req.body.newFilename = ensureJsonExtension(newFilename);
|
||||
req.params.filename = ensureJsonExtension(projectName);
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
export const validatePatchProjectFile = [
|
||||
body('rundown').isArray().optional({ nullable: false }),
|
||||
body('project').isObject().optional({ nullable: false }),
|
||||
body('settings').isObject().optional({ nullable: false }),
|
||||
body('viewSettings').isObject().optional({ nullable: false }),
|
||||
body('aliases').isArray().optional({ nullable: false }),
|
||||
body('customFields').isObject().optional({ nullable: false }),
|
||||
body('osc').isObject().optional({ nullable: false }),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* @description Validates the filename for loading a project file.
|
||||
*/
|
||||
export const validateLoadProjectFile = [
|
||||
body('filename').exists().withMessage('Filename is required').isString().withMessage('Filename must be a string'),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(422).json({ errors: errors.array() });
|
||||
}
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* @description Validates the filenames for duplicating a project.
|
||||
*/
|
||||
export const validateProjectDuplicate = [
|
||||
body('newFilename')
|
||||
.exists()
|
||||
.withMessage('New project filename is required')
|
||||
.isString()
|
||||
.withMessage('New project filename must be a string')
|
||||
.isLength({ min: 1, max: 255 })
|
||||
.withMessage('New project filename must be between 1 and 255 characters'),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(422).json({ errors: errors.array() });
|
||||
}
|
||||
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* @description Validates the filenames for renaming a project.
|
||||
*/
|
||||
export const validateProjectRename = [
|
||||
body('newFilename')
|
||||
.exists()
|
||||
.withMessage('Duplicate project filename is required')
|
||||
.isString()
|
||||
.withMessage('Duplicate project filename must be a string')
|
||||
.isLength({ min: 1, max: 255 })
|
||||
.withMessage('Duplicate project filename must be between 1 and 255 characters'),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(422).json({ errors: errors.array() });
|
||||
}
|
||||
|
||||
next();
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* This module encapsulates logic related to
|
||||
* Google Sheets
|
||||
*/
|
||||
|
||||
import { Request, Response } from 'express';
|
||||
import { generateRundownPreview, listWorksheets, saveExcelFile } from './excel.service.js';
|
||||
|
||||
export async function postExcel(req: Request, res: Response) {
|
||||
try {
|
||||
const filePath = req.file.path;
|
||||
await saveExcelFile(filePath);
|
||||
res.status(200).send();
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: String(error) });
|
||||
}
|
||||
}
|
||||
|
||||
export async function getWorksheets(req: Request, res: Response) {
|
||||
try {
|
||||
const names = listWorksheets();
|
||||
res.status(200).send(names);
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: String(error) });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* parses an Excel spreadsheet
|
||||
* @returns parsed result
|
||||
*/
|
||||
export async function previewExcel(req: Request, res: Response) {
|
||||
try {
|
||||
const { options } = req.body;
|
||||
const data = generateRundownPreview(options);
|
||||
res.status(200).send(data);
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: String(error) });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Request } from 'express';
|
||||
import multer, { FileFilterCallback } from 'multer';
|
||||
|
||||
import { EXCEL_MIME } from '../../utils/parser.js';
|
||||
import { storage } from '../../utils/upload.js';
|
||||
|
||||
const filterExcel = (_req: Request, file: Express.Multer.File, cb: FileFilterCallback) => {
|
||||
if (file.mimetype.includes(EXCEL_MIME)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(null, false);
|
||||
}
|
||||
};
|
||||
export const uploadExcel = multer({
|
||||
storage,
|
||||
fileFilter: filterExcel,
|
||||
}).single('excel');
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* This is a feature specific router for integration with Excel
|
||||
*/
|
||||
|
||||
import express from 'express';
|
||||
import { uploadExcel } from './excel.middleware.js';
|
||||
import { getWorksheets, postExcel, previewExcel } from './excel.controller.js';
|
||||
import { validateFileExists, validateImportMapOptions } from './excel.validation.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
router.post('/upload', uploadExcel, validateFileExists, postExcel);
|
||||
router.get('/worksheets', getWorksheets);
|
||||
router.post('/preview', validateImportMapOptions, previewExcel);
|
||||
|
||||
// TODO: validate import map
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* This module encapsulates logic related to
|
||||
* Google Sheets
|
||||
*/
|
||||
|
||||
import { CustomFields, OntimeRundown } from 'ontime-types';
|
||||
import { ImportMap } from 'ontime-utils';
|
||||
|
||||
import { extname } from 'path';
|
||||
import { existsSync } from 'fs';
|
||||
import xlsx from 'node-xlsx';
|
||||
|
||||
import { parseExcel } from '../../utils/parser.js';
|
||||
import { parseCustomFields, parseRundown } from '../../utils/parserFunctions.js';
|
||||
import { deleteFile } from '../../utils/parserUtils.js';
|
||||
|
||||
let excelData: { name: string; data: unknown[][] }[] = [];
|
||||
|
||||
export async function saveExcelFile(filePath: string) {
|
||||
if (!existsSync(filePath)) {
|
||||
throw new Error('Upload of excel file failed');
|
||||
}
|
||||
if (extname(filePath) != '.xlsx') {
|
||||
throw new Error('Wrong file format');
|
||||
}
|
||||
excelData = xlsx.parse(filePath, { cellDates: true });
|
||||
|
||||
await deleteFile(filePath);
|
||||
}
|
||||
|
||||
export function listWorksheets() {
|
||||
return excelData.map((value) => value.name);
|
||||
}
|
||||
|
||||
export function generateRundownPreview(options: ImportMap): { rundown: OntimeRundown; customFields: CustomFields } {
|
||||
const data = excelData.find(({ name }) => name.toLowerCase() === options.worksheet.toLowerCase())?.data;
|
||||
|
||||
if (!data) {
|
||||
throw new Error(`Could not find data to import, maybe the worksheet name is incorrect: ${options.worksheet}`);
|
||||
}
|
||||
|
||||
const dataFromExcel = parseExcel(data, options);
|
||||
|
||||
// we run the parsed data through an extra step to ensure the objects shape
|
||||
const rundown = parseRundown(dataFromExcel);
|
||||
if (rundown.length === 0) {
|
||||
throw new Error(`Could not find data to import in the worksheet: ${options.worksheet}`);
|
||||
}
|
||||
const customFields = parseCustomFields(dataFromExcel);
|
||||
|
||||
// clear the data
|
||||
excelData = [];
|
||||
|
||||
return { rundown, customFields };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { isImportMap } from 'ontime-utils';
|
||||
|
||||
import { body, validationResult } from 'express-validator';
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
|
||||
export const validateFileExists = [
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
if (!req.file) {
|
||||
return res.status(422).json({ errors: 'File not found' });
|
||||
}
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
export const validateImportMapOptions = [
|
||||
body('options')
|
||||
.exists()
|
||||
.isObject()
|
||||
.custom((content) => {
|
||||
return isImportMap(content);
|
||||
}),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { ErrorResponse, HttpSettings } from 'ontime-types';
|
||||
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
import { DataProvider } from '../../classes/data-provider/DataProvider.js';
|
||||
import { failEmptyObjects } from '../../utils/routerUtils.js';
|
||||
import { httpIntegration } from '../../services/integration-service/HttpIntegration.js';
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
|
||||
export async function getHTTP(_req: Request, res: Response<HttpSettings>) {
|
||||
const http = DataProvider.getHttp();
|
||||
res.status(200).send(http);
|
||||
}
|
||||
|
||||
export async function postHTTP(req: Request, res: Response<HttpSettings | ErrorResponse>) {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const httpSettings = req.body;
|
||||
|
||||
httpIntegration.init(httpSettings);
|
||||
// we persist the data after init to avoid persisting invalid data
|
||||
const result = await DataProvider.setHttp(httpSettings);
|
||||
res.send(result).status(200);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import express from 'express';
|
||||
|
||||
import { validateHTTP } from './http.validation.js';
|
||||
import { getHTTP, postHTTP } from './http.controller.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
router.get('/', getHTTP);
|
||||
router.post('/', validateHTTP, postHTTP);
|
||||
@@ -0,0 +1,21 @@
|
||||
import { body, validationResult } from 'express-validator';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
import { sanitiseHttpSubscriptions } from '../../utils/parserFunctions.js';
|
||||
|
||||
/**
|
||||
* @description Validates object for POST /ontime/http
|
||||
*/
|
||||
export const validateHTTP = [
|
||||
body('enabledOut').exists().isBoolean(),
|
||||
body('subscriptions')
|
||||
.exists()
|
||||
.isArray()
|
||||
.custom((value) => sanitiseHttpSubscriptions(value)),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,32 @@
|
||||
import express from 'express';
|
||||
|
||||
import { router as urlPresetsRouter } from './url-presets/urlPresets.router.js';
|
||||
import { router as customFieldsRouter } from './custom-fields/customFields.router.js';
|
||||
import { router as dbRouter } from './db/db.router.js';
|
||||
import { router as httpRouter } from './http/http.router.js';
|
||||
import { router as oscRouter } from './osc/osc.router.js';
|
||||
import { router as projectRouter } from './project/project.router.js';
|
||||
import { router as rundownRouter } from './rundown/rundown.router.js';
|
||||
import { router as settingsRouter } from './settings/settings.router.js';
|
||||
import { router as sheetsRouter } from './sheets/sheets.router.js';
|
||||
import { router as excelRouter } from './excel/excel.router.js';
|
||||
import { router as viewSettingsRouter } from './view-settings/viewSettings.router.js';
|
||||
|
||||
export const appRouter = express.Router();
|
||||
|
||||
appRouter.use('/custom-fields', customFieldsRouter);
|
||||
appRouter.use('/db', dbRouter);
|
||||
appRouter.use('/http', httpRouter);
|
||||
appRouter.use('/osc', oscRouter);
|
||||
appRouter.use('/project', projectRouter);
|
||||
appRouter.use('/rundown', rundownRouter);
|
||||
appRouter.use('/settings', settingsRouter);
|
||||
appRouter.use('/sheets', sheetsRouter);
|
||||
appRouter.use('/excel', excelRouter);
|
||||
appRouter.use('/url-presets', urlPresetsRouter);
|
||||
appRouter.use('/view-settings', viewSettingsRouter);
|
||||
|
||||
//we don't want to redirect to react index when using api routes
|
||||
appRouter.all('/*', (_req, res) => {
|
||||
res.status(404).send();
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { ErrorResponse, OSCSettings } from 'ontime-types';
|
||||
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
import { DataProvider } from '../../classes/data-provider/DataProvider.js';
|
||||
import { failEmptyObjects } from '../../utils/routerUtils.js';
|
||||
import { oscIntegration } from '../../services/integration-service/OscIntegration.js';
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
|
||||
export async function getOSC(_req: Request, res: Response<OSCSettings>) {
|
||||
const osc = DataProvider.getOsc();
|
||||
res.status(200).send(osc);
|
||||
}
|
||||
|
||||
export async function postOSC(req: Request, res: Response<OSCSettings | ErrorResponse>) {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const oscSettings = req.body;
|
||||
|
||||
oscIntegration.init(oscSettings);
|
||||
// we persist the data after init to avoid persisting invalid data
|
||||
const result = await DataProvider.setOsc(oscSettings);
|
||||
|
||||
res.send(result).status(200);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import express from 'express';
|
||||
import { getOSC, postOSC } from './osc.controller.js';
|
||||
import { validateOSC } from './osc.validation.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
router.get('/', getOSC);
|
||||
router.post('/', validateOSC, postOSC);
|
||||
@@ -0,0 +1,25 @@
|
||||
import { body, validationResult } from 'express-validator';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
import { sanitiseOscSubscriptions } from '../../utils/parserFunctions.js';
|
||||
|
||||
/**
|
||||
* @description Validates object for POST /ontime/osc
|
||||
*/
|
||||
export const validateOSC = [
|
||||
body('portIn').exists().isPort(),
|
||||
body('portOut').exists().isPort(),
|
||||
body('targetIP').exists().isIP(),
|
||||
body('enabledIn').exists().isBoolean(),
|
||||
body('enabledOut').exists().isBoolean(),
|
||||
body('subscriptions')
|
||||
.exists()
|
||||
.isArray()
|
||||
.custom((value) => sanitiseOscSubscriptions(value)),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,34 @@
|
||||
import { ErrorResponse, ProjectData } from 'ontime-types';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import { DataProvider } from '../../classes/data-provider/DataProvider.js';
|
||||
import { removeUndefined } from '../../utils/parserUtils.js';
|
||||
import { failEmptyObjects } from '../../utils/routerUtils.js';
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
|
||||
export async function getProjectData(_req: Request, res: Response<ProjectData>) {
|
||||
res.json(DataProvider.getProjectData());
|
||||
}
|
||||
|
||||
export async function postProjectData(req: Request, res: Response<ProjectData | ErrorResponse>) {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const newEvent: Partial<ProjectData> = removeUndefined({
|
||||
title: req.body?.title,
|
||||
description: req.body?.description,
|
||||
publicUrl: req.body?.publicUrl,
|
||||
publicInfo: req.body?.publicInfo,
|
||||
backstageUrl: req.body?.backstageUrl,
|
||||
backstageInfo: req.body?.backstageInfo,
|
||||
endMessage: req.body?.endMessage,
|
||||
});
|
||||
const newData = await DataProvider.setProjectData(newEvent);
|
||||
res.status(200).send(newData);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import express from 'express';
|
||||
|
||||
import { getProjectData, postProjectData } from './project.controller.js';
|
||||
import { projectSanitiser } from './project.validation.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
router.get('/', getProjectData);
|
||||
router.post('/', projectSanitiser, postProjectData);
|
||||
+3
-1
@@ -1,3 +1,4 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { body, validationResult } from 'express-validator';
|
||||
|
||||
export const projectSanitiser = [
|
||||
@@ -8,7 +9,8 @@ export const projectSanitiser = [
|
||||
body('backstageUrl').optional().isString().trim(),
|
||||
body('backstageInfo').optional().isString().trim(),
|
||||
body('endMessage').optional().isString().trim(),
|
||||
(req, res, next) => {
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
@@ -0,0 +1,130 @@
|
||||
import { ErrorResponse, MessageResponse, OntimeRundown, OntimeRundownEntry, RundownCached } from 'ontime-types';
|
||||
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
import { failEmptyObjects } from '../../utils/routerUtils.js';
|
||||
import {
|
||||
addEvent,
|
||||
applyDelay,
|
||||
batchEditEvents,
|
||||
deleteAllEvents,
|
||||
deleteEvent,
|
||||
editEvent,
|
||||
reorderEvent,
|
||||
swapEvents,
|
||||
} from '../../services/rundown-service/RundownService.js';
|
||||
import { getNormalisedRundown, getRundown } from '../../services/rundown-service/rundownUtils.js';
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
|
||||
export async function rundownGetAll(_req: Request, res: Response<OntimeRundown>) {
|
||||
const rundown = getRundown();
|
||||
res.json(rundown);
|
||||
}
|
||||
|
||||
export async function rundownGetNormalised(_req: Request, res: Response<RundownCached>) {
|
||||
const cachedRundown = getNormalisedRundown();
|
||||
res.json(cachedRundown);
|
||||
}
|
||||
|
||||
export async function rundownPost(req: Request, res: Response<OntimeRundownEntry | ErrorResponse>) {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const newEvent = await addEvent(req.body);
|
||||
res.status(201).send(newEvent);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function rundownPut(req: Request, res: Response<OntimeRundownEntry | ErrorResponse>) {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const event = await editEvent(req.body);
|
||||
res.status(200).send(event);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function rundownBatchPut(req: Request, res: Response<MessageResponse | ErrorResponse>) {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return res.status(404);
|
||||
}
|
||||
|
||||
try {
|
||||
const { data, ids } = req.body;
|
||||
await batchEditEvents(ids, data);
|
||||
res.status(200).send({ message: 'Batch edit successful' });
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function rundownReorder(req: Request, res: Response<OntimeRundownEntry | ErrorResponse>) {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { eventId, from, to } = req.body;
|
||||
const event = await reorderEvent(eventId, from, to);
|
||||
res.status(200).send(event.newEvent);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function rundownSwap(req: Request, res: Response<MessageResponse | ErrorResponse>) {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { from, to } = req.body;
|
||||
await swapEvents(from, to);
|
||||
res.status(200).send({ message: 'Swap successful' });
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function rundownApplyDelay(req: Request, res: Response<MessageResponse | ErrorResponse>) {
|
||||
try {
|
||||
await applyDelay(req.params.eventId);
|
||||
res.status(200).send({ message: 'Delay applied' });
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function rundownDelete(_req: Request, res: Response<MessageResponse | ErrorResponse>) {
|
||||
try {
|
||||
await deleteAllEvents();
|
||||
res.status(204).send({ message: 'All events deleted' });
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteEventById(req: Request, res: Response<MessageResponse | ErrorResponse>) {
|
||||
try {
|
||||
await deleteEvent(req.params.eventId);
|
||||
res.status(204).send({ message: 'Event deleted' });
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
+9
-17
@@ -1,47 +1,39 @@
|
||||
import express from 'express';
|
||||
|
||||
import {
|
||||
deleteEventById,
|
||||
rundownApplyDelay,
|
||||
rundownBatchPut,
|
||||
rundownDelete,
|
||||
rundownGetAll,
|
||||
rundownGetCached,
|
||||
rundownGetNormalised,
|
||||
rundownPost,
|
||||
rundownPut,
|
||||
rundownReorder,
|
||||
rundownSwap,
|
||||
} from '../controllers/rundownController.js';
|
||||
} from './rundown.controller.js';
|
||||
import {
|
||||
paramsMustHaveEventId,
|
||||
rundownBatchPutValidator,
|
||||
rundownPostValidator,
|
||||
rundownPutValidator,
|
||||
rundownReorderValidator,
|
||||
rundownSwapValidator,
|
||||
} from '../controllers/rundownController.validate.js';
|
||||
} from './rundown.validation.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
// create route between controller and '/events/cached' endpoint
|
||||
router.get('/cached', rundownGetCached);
|
||||
router.get('/', rundownGetAll); // not used in Ontime frontend
|
||||
router.get('/normalised', rundownGetNormalised);
|
||||
|
||||
// create route between controller and '/events/' endpoint
|
||||
router.get('/', rundownGetAll);
|
||||
|
||||
// create route between controller and '/events/' endpoint
|
||||
router.post('/', rundownPostValidator, rundownPost);
|
||||
|
||||
// create route between controller and '/events/' endpoint
|
||||
router.put('/', rundownPutValidator, rundownPut);
|
||||
router.put('/batch', rundownBatchPutValidator, rundownBatchPut);
|
||||
|
||||
// create route between controller and '/events/reorder' endpoint
|
||||
router.patch('/reorder/', rundownReorderValidator, rundownReorder);
|
||||
|
||||
router.patch('/swap', rundownSwapValidator, rundownSwap);
|
||||
|
||||
// create route between controller and '/events/applydelay/:eventId' endpoint
|
||||
router.patch('/applydelay/:eventId', paramsMustHaveEventId, rundownApplyDelay);
|
||||
|
||||
// create route between controller and '/events/all' endpoint
|
||||
router.delete('/all', rundownDelete);
|
||||
|
||||
// create route between controller and '/events/:eventId' endpoint
|
||||
router.delete('/:eventId', paramsMustHaveEventId, deleteEventById);
|
||||
+22
-5
@@ -1,8 +1,10 @@
|
||||
import { body, param, validationResult } from 'express-validator';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
export const rundownPostValidator = [
|
||||
body('type').isString().exists().isIn(['event', 'delay', 'block']),
|
||||
(req, res, next) => {
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
@@ -11,7 +13,19 @@ export const rundownPostValidator = [
|
||||
|
||||
export const rundownPutValidator = [
|
||||
body('id').isString().exists(),
|
||||
(req, res, next) => {
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
export const rundownBatchPutValidator = [
|
||||
body('data').isObject().exists(),
|
||||
body('ids').isArray().exists(),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
@@ -22,7 +36,8 @@ export const rundownReorderValidator = [
|
||||
body('eventId').isString().exists(),
|
||||
body('from').isNumeric().exists(),
|
||||
body('to').isNumeric().exists(),
|
||||
(req, res, next) => {
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
@@ -32,7 +47,8 @@ export const rundownReorderValidator = [
|
||||
export const rundownSwapValidator = [
|
||||
body('from').isString().exists(),
|
||||
body('to').isString().exists(),
|
||||
(req, res, next) => {
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
@@ -41,7 +57,8 @@ export const rundownSwapValidator = [
|
||||
|
||||
export const paramsMustHaveEventId = [
|
||||
param('eventId').exists(),
|
||||
(req, res, next) => {
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
@@ -0,0 +1,67 @@
|
||||
import { ErrorResponse, Settings } from 'ontime-types';
|
||||
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
import { DataProvider } from '../../classes/data-provider/DataProvider.js';
|
||||
import { failEmptyObjects } from '../../utils/routerUtils.js';
|
||||
import { extractPin } from '../../services/project-service/ProjectService.js';
|
||||
import { isDocker } from '../../setup/index.js';
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
import { obfuscate } from 'ontime-utils';
|
||||
|
||||
export async function getSettings(_req: Request, res: Response<Settings>) {
|
||||
const settings = DataProvider.getSettings();
|
||||
const obfuscatedSettings = { ...settings };
|
||||
if (settings.editorKey) {
|
||||
obfuscatedSettings.editorKey = obfuscate(settings.editorKey);
|
||||
}
|
||||
|
||||
if (settings.operatorKey) {
|
||||
obfuscatedSettings.editorKey = obfuscate(settings.editorKey);
|
||||
}
|
||||
|
||||
res.status(200).send(obfuscatedSettings);
|
||||
}
|
||||
|
||||
export async function postSettings(req: Request, res: Response<Settings | ErrorResponse>) {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const settings = DataProvider.getSettings();
|
||||
const editorKey = extractPin(req.body?.editorKey, settings.editorKey);
|
||||
const operatorKey = extractPin(req.body?.operatorKey, settings.operatorKey);
|
||||
const serverPort = Number(req.body?.serverPort);
|
||||
//TODO: should this not be part of the validator?
|
||||
if (isNaN(serverPort)) {
|
||||
return res.status(400).send({ message: `Invalid value found for server port: ${req.body?.serverPort}` });
|
||||
}
|
||||
|
||||
const hasChangedPort = settings.serverPort !== serverPort;
|
||||
|
||||
if (isDocker && hasChangedPort) {
|
||||
return res.status(403).json({ message: 'Can`t change port when running inside docker' });
|
||||
}
|
||||
|
||||
let timeFormat = settings.timeFormat;
|
||||
if (req.body?.timeFormat === '12' || req.body?.timeFormat === '24') {
|
||||
timeFormat = req.body.timeFormat;
|
||||
}
|
||||
|
||||
const language = req.body?.language || 'en';
|
||||
|
||||
const newData = {
|
||||
...settings,
|
||||
editorKey,
|
||||
operatorKey,
|
||||
timeFormat,
|
||||
language,
|
||||
serverPort,
|
||||
};
|
||||
await DataProvider.setSettings(newData);
|
||||
res.status(200).send(newData);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import express from 'express';
|
||||
import { getSettings, postSettings } from './settings.controller.js';
|
||||
import { validateSettings } from './settings.validation.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
router.get('/', getSettings);
|
||||
router.post('/', validateSettings, postSettings);
|
||||
@@ -0,0 +1,19 @@
|
||||
import { body, validationResult } from 'express-validator';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
/**
|
||||
* @description Validates object for POST /ontime/settings
|
||||
*/
|
||||
export const validateSettings = [
|
||||
body('editorKey').isString().isLength({ min: 0, max: 4 }).optional({ nullable: true }),
|
||||
body('operatorKey').isString().isLength({ min: 0, max: 4 }).optional({ nullable: true }),
|
||||
body('timeFormat').isString().isIn(['12', '24']),
|
||||
body('language').isString(),
|
||||
body('serverPort').isPort().optional(),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* This module encapsulates logic related to
|
||||
* Google Sheets
|
||||
*/
|
||||
|
||||
import { Request, Response } from 'express';
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
import type { AuthenticationStatus, CustomFields, ErrorResponse, OntimeRundown } from 'ontime-types';
|
||||
|
||||
import { deleteFile } from '../../utils/parserUtils.js';
|
||||
import {
|
||||
revoke,
|
||||
handleClientSecret,
|
||||
handleInitialConnection,
|
||||
hasAuth,
|
||||
download,
|
||||
upload,
|
||||
getWorksheetOptions,
|
||||
} from '../../services/sheet-service/SheetService.js';
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
|
||||
export async function requestConnection(
|
||||
req: Request,
|
||||
res: Response<{ verification_url: string; user_code: string } | ErrorResponse>,
|
||||
) {
|
||||
const { sheetId } = req.params;
|
||||
const file = req.file.path;
|
||||
|
||||
try {
|
||||
const client = readFileSync(file, 'utf-8');
|
||||
const clientSecret = handleClientSecret(client);
|
||||
const { verification_url, user_code } = await handleInitialConnection(clientSecret, sheetId);
|
||||
|
||||
res.status(200).send({ verification_url, user_code });
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
|
||||
// delete uploaded file after parsing
|
||||
try {
|
||||
deleteFile(file);
|
||||
} catch (_error) {
|
||||
/** we dont handle failure here */
|
||||
}
|
||||
}
|
||||
|
||||
export async function verifyAuthentication(
|
||||
_req: Request,
|
||||
res: Response<{ authenticated: AuthenticationStatus } | ErrorResponse>,
|
||||
) {
|
||||
try {
|
||||
const authenticated = hasAuth();
|
||||
res.status(200).send(authenticated);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function revokeAuthentication(
|
||||
_req: Request,
|
||||
res: Response<{ authenticated: AuthenticationStatus } | ErrorResponse>,
|
||||
) {
|
||||
try {
|
||||
const authenticated = revoke();
|
||||
res.status(200).send(authenticated);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function getWorksheetNamesFromSheet(req: Request, res: Response<string[] | ErrorResponse>) {
|
||||
try {
|
||||
const { sheetId } = req.params;
|
||||
const { worksheetOptions } = await getWorksheetOptions(sheetId);
|
||||
res.status(200).send(worksheetOptions);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function readFromSheet(
|
||||
req: Request,
|
||||
res: Response<
|
||||
| {
|
||||
rundown: OntimeRundown;
|
||||
customFields: CustomFields;
|
||||
}
|
||||
| ErrorResponse
|
||||
>,
|
||||
) {
|
||||
try {
|
||||
const { sheetId } = req.params;
|
||||
const { options } = req.body;
|
||||
const data = await download(sheetId, options);
|
||||
res.status(200).send(data);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeToSheet(req: Request, res: Response<void | ErrorResponse>) {
|
||||
try {
|
||||
const { sheetId } = req.params;
|
||||
const { options } = req.body;
|
||||
await upload(sheetId, options);
|
||||
res.status(200).send();
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Request } from 'express';
|
||||
import multer, { FileFilterCallback } from 'multer';
|
||||
|
||||
import { JSON_MIME } from '../../utils/parser.js';
|
||||
import { storage } from '../../utils/upload.js';
|
||||
|
||||
const filterClientSecret = (_req: Request, file: Express.Multer.File, cb: FileFilterCallback) => {
|
||||
if (file.mimetype.includes(JSON_MIME)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(null, false);
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadClientSecret = multer({
|
||||
storage,
|
||||
fileFilter: filterClientSecret,
|
||||
}).single('client_secret');
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* This is a feature specific router for integration with google sheets
|
||||
*/
|
||||
|
||||
import express from 'express';
|
||||
|
||||
import {
|
||||
getWorksheetNamesFromSheet,
|
||||
readFromSheet,
|
||||
requestConnection,
|
||||
revokeAuthentication,
|
||||
verifyAuthentication,
|
||||
writeToSheet,
|
||||
} from './sheets.controller.js';
|
||||
import { uploadClientSecret } from './sheets.middleware.js';
|
||||
import { validateRequestConnection, validateSheetId, validateSheetOptions } from './sheets.validation.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
router.get('/connect', verifyAuthentication);
|
||||
router.post('/:sheetId/connect', uploadClientSecret, validateRequestConnection, requestConnection);
|
||||
|
||||
router.post('/revoke', revokeAuthentication);
|
||||
|
||||
router.post('/:sheetId/worksheets', validateSheetId, getWorksheetNamesFromSheet);
|
||||
|
||||
router.post('/:sheetId/read', validateSheetOptions, readFromSheet);
|
||||
router.post('/:sheetId/write', validateSheetOptions, writeToSheet);
|
||||
@@ -0,0 +1,48 @@
|
||||
import { isImportMap } from 'ontime-utils';
|
||||
|
||||
import { body, param, validationResult } from 'express-validator';
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
|
||||
export const validateRequestConnection = [
|
||||
param('sheetId')
|
||||
.exists()
|
||||
.isString()
|
||||
.isLength({
|
||||
min: 40,
|
||||
max: 100,
|
||||
})
|
||||
.withMessage('Sheet ID is usually 44 characters long'),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
export const validateSheetId = [
|
||||
param('sheetId').exists().isString(),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
export const validateSheetOptions = [
|
||||
param('sheetId').exists().isString(),
|
||||
body('options')
|
||||
.exists()
|
||||
.isObject()
|
||||
.custom((content) => {
|
||||
const isValid = isImportMap(content);
|
||||
return isValid;
|
||||
}),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { ErrorResponse, URLPreset } from 'ontime-types';
|
||||
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
import { DataProvider } from '../../classes/data-provider/DataProvider.js';
|
||||
import { failIsNotArray } from '../../utils/routerUtils.js';
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
|
||||
export async function getUrlPresets(_req: Request, res: Response<URLPreset[]>) {
|
||||
const presets = DataProvider.getUrlPresets();
|
||||
res.status(200).send(presets as URLPreset[]);
|
||||
}
|
||||
|
||||
export async function postUrlPresets(req: Request, res: Response<URLPreset[] | ErrorResponse>) {
|
||||
if (failIsNotArray(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const newPresets: URLPreset[] = req.body.map((preset) => ({
|
||||
enabled: preset.enabled,
|
||||
alias: preset.alias,
|
||||
pathAndParams: preset.pathAndParams,
|
||||
}));
|
||||
await DataProvider.setUrlPresets(newPresets);
|
||||
res.status(200).send(newPresets);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import express from 'express';
|
||||
import { getUrlPresets, postUrlPresets } from './urlPresets.controller.js';
|
||||
import { validateUrlPresets } from './urlPresets.validation.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
router.get('/', getUrlPresets);
|
||||
router.post('/', validateUrlPresets, postUrlPresets);
|
||||
@@ -0,0 +1,18 @@
|
||||
import { body, validationResult } from 'express-validator';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
/**
|
||||
* validate array of URL preset objects
|
||||
*/
|
||||
export const validateUrlPresets = [
|
||||
body().isArray(),
|
||||
body('*.enabled').isBoolean(),
|
||||
body('*.alias').isString().trim(),
|
||||
body('*.pathAndParams').isString().trim(),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { ErrorResponse, ViewSettings } from 'ontime-types';
|
||||
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
import { DataProvider } from '../../classes/data-provider/DataProvider.js';
|
||||
import { failEmptyObjects } from '../../utils/routerUtils.js';
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
|
||||
export async function getViewSettings(_req: Request, res: Response<ViewSettings>) {
|
||||
const views = DataProvider.getViewSettings();
|
||||
res.status(200).send(views);
|
||||
}
|
||||
|
||||
export async function postViewSettings(req: Request, res: Response<ViewSettings | ErrorResponse>) {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const newData = {
|
||||
dangerColor: req.body.dangerColor,
|
||||
endMessage: req.body?.endMessage ?? '',
|
||||
freezeEnd: req.body.freezeEnd,
|
||||
normalColor: req.body.normalColor,
|
||||
overrideStyles: req.body.overrideStyles,
|
||||
warningColor: req.body.warningColor,
|
||||
};
|
||||
await DataProvider.setViewSettings(newData);
|
||||
res.status(200).send(newData);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(400).send({ message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import express from 'express';
|
||||
|
||||
import { validateViewSettings } from './viewSettings.validation.js';
|
||||
import { getViewSettings, postViewSettings } from './viewSettings.controller.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
router.get('/', getViewSettings);
|
||||
router.post('/', validateViewSettings, postViewSettings);
|
||||
@@ -0,0 +1,19 @@
|
||||
import { check, validationResult } from 'express-validator';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
/**
|
||||
* @description Validates object for POST /ontime/views
|
||||
*/
|
||||
export const validateViewSettings = [
|
||||
check('overrideStyles').isBoolean().withMessage('overrideStyles value must be boolean'),
|
||||
check('endMessage').isString().trim().withMessage('endMessage value must be string'),
|
||||
check('normalColor').isString().trim().withMessage('normalColor value must be string'),
|
||||
check('warningColor').isString().trim().withMessage('warningColor value must be string'),
|
||||
check('dangerColor').isString().trim().withMessage('dangerColor value must be string'),
|
||||
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,256 @@
|
||||
import { DeepPartial, MessageState, OntimeEvent, SimpleDirection, SimplePlayback } from 'ontime-types';
|
||||
|
||||
import { ONTIME_VERSION } from '../ONTIME_VERSION.js';
|
||||
import { extraTimerService } from '../services/extra-timer-service/ExtraTimerService.js';
|
||||
import { messageService } from '../services/message-service/MessageService.js';
|
||||
import { validateMessage, validateTimerMessage } from '../services/message-service/messageUtils.js';
|
||||
import { runtimeService } from '../services/runtime-service/RuntimeService.js';
|
||||
import { eventStore } from '../stores/EventStore.js';
|
||||
import * as assert from '../utils/assert.js';
|
||||
import { isEmptyObject } from '../utils/parserUtils.js';
|
||||
import { parseProperty, updateEvent } from './integration.utils.js';
|
||||
|
||||
export function dispatchFromAdapter(type: string, payload: unknown, _source?: 'osc' | 'ws' | 'http') {
|
||||
const action = type.toLowerCase();
|
||||
const handler = actionHandlers[action];
|
||||
if (handler) {
|
||||
return handler(payload);
|
||||
} else {
|
||||
throw new Error(`Unhandled message ${type}`);
|
||||
}
|
||||
}
|
||||
|
||||
type ActionHandler = (payload: unknown) => { payload: unknown };
|
||||
|
||||
const actionHandlers: Record<string, ActionHandler> = {
|
||||
/* General */
|
||||
version: () => ({ payload: ONTIME_VERSION }),
|
||||
poll: () => ({
|
||||
payload: eventStore.poll(),
|
||||
}),
|
||||
change: (payload) => {
|
||||
assert.isObject(payload);
|
||||
if (Object.keys(payload).length === 0) {
|
||||
throw new Error('Payload is empty');
|
||||
}
|
||||
|
||||
const id = Object.keys(payload).at(0);
|
||||
if (!id) {
|
||||
throw new Error('Missing Event ID');
|
||||
}
|
||||
|
||||
const data = payload[id as keyof typeof payload];
|
||||
const patchEvent: Partial<OntimeEvent> & { id: string } = { id };
|
||||
|
||||
Object.entries(data).forEach(([property, value]) => {
|
||||
if (typeof property !== 'string' || value === undefined) {
|
||||
throw new Error('Invalid property or value');
|
||||
}
|
||||
const newObjectProperty = parseProperty(property, value);
|
||||
|
||||
if (patchEvent.custom && newObjectProperty.custom) {
|
||||
Object.assign(patchEvent.custom, newObjectProperty.custom);
|
||||
} else {
|
||||
Object.assign(patchEvent, newObjectProperty);
|
||||
}
|
||||
});
|
||||
|
||||
updateEvent(patchEvent);
|
||||
Object.assign(patchEvent);
|
||||
|
||||
return { payload: 'success' };
|
||||
},
|
||||
/* Message Service */
|
||||
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 === undefined) {
|
||||
return successPayloadOrError(runtimeService.start(), 'Uable to start');
|
||||
}
|
||||
|
||||
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
|
||||
return successPayloadOrError(
|
||||
runtimeService.startByIndex(eventIndex - 1),
|
||||
`Event index not recognised or out of range ${eventIndex}`,
|
||||
);
|
||||
}
|
||||
|
||||
if ('id' in payload) {
|
||||
assert.isString(payload.id);
|
||||
return successPayloadOrError(runtimeService.startById(payload.id), `Unable to start ID: ${payload.id}`);
|
||||
}
|
||||
|
||||
if ('cue' in payload) {
|
||||
const cue = extractCue(payload.cue);
|
||||
return successPayloadOrError(runtimeService.startByCue(cue), `Unable to start CUE: ${cue}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (payload === 'next') {
|
||||
return successPayloadOrError(runtimeService.startNext(), 'Unable to start next event');
|
||||
}
|
||||
|
||||
if (payload === 'previous') {
|
||||
return successPayloadOrError(runtimeService.startPrevious(), 'Unable to start previous event');
|
||||
}
|
||||
|
||||
throw new Error('No matching start function');
|
||||
},
|
||||
pause: () => {
|
||||
runtimeService.pause();
|
||||
return { payload: 'success' };
|
||||
},
|
||||
stop: () => {
|
||||
runtimeService.stop();
|
||||
return { payload: 'success' };
|
||||
},
|
||||
reload: () => {
|
||||
runtimeService.reload();
|
||||
return { payload: 'success' };
|
||||
},
|
||||
roll: () => {
|
||||
runtimeService.roll();
|
||||
return { payload: 'success' };
|
||||
},
|
||||
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
|
||||
return successPayloadOrError(
|
||||
runtimeService.loadByIndex(eventIndex - 1),
|
||||
`Event index not recognised or out of range ${eventIndex}`,
|
||||
);
|
||||
}
|
||||
|
||||
if ('id' in payload) {
|
||||
assert.isString(payload.id);
|
||||
return successPayloadOrError(runtimeService.loadById(payload.id), `Unable to load ID: ${payload.id}`);
|
||||
}
|
||||
|
||||
if ('cue' in payload) {
|
||||
const cue = extractCue(payload.cue);
|
||||
return successPayloadOrError(runtimeService.loadByCue(cue), `Unable to load CUE: ${cue}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (payload === 'next') {
|
||||
return successPayloadOrError(runtimeService.loadNext(), 'Unable to load next event');
|
||||
}
|
||||
|
||||
if (payload === 'previous') {
|
||||
return successPayloadOrError(runtimeService.loadPrevious(), 'Unable to load previous event');
|
||||
}
|
||||
throw new Error('No matching method provided');
|
||||
},
|
||||
addtime: (payload) => {
|
||||
let time = 0;
|
||||
if (payload && typeof payload === 'object') {
|
||||
if ('add' in payload) {
|
||||
time = numberOrError(payload.add);
|
||||
} else if ('remove' in payload) {
|
||||
time = numberOrError(payload.remove) * -1;
|
||||
}
|
||||
} else {
|
||||
time = numberOrError(payload);
|
||||
}
|
||||
assert.isNumber(time);
|
||||
if (time === 0) {
|
||||
return { payload: 'success' };
|
||||
}
|
||||
runtimeService.addTime(time * 1000); //frontend is seconds based
|
||||
return { payload: 'success' };
|
||||
},
|
||||
/* Extra timers */
|
||||
auxtimer: (payload) => {
|
||||
assert.isObject(payload);
|
||||
if (!('1' in payload)) {
|
||||
throw new Error('Invalid auxtimer index');
|
||||
}
|
||||
const command = payload['1'];
|
||||
if (typeof command === 'string') {
|
||||
if (command === SimplePlayback.Start) {
|
||||
const reply = extraTimerService.start();
|
||||
return { payload: reply };
|
||||
}
|
||||
if (command === SimplePlayback.Pause) {
|
||||
const reply = extraTimerService.pause();
|
||||
return { payload: reply };
|
||||
}
|
||||
if (command === SimplePlayback.Stop) {
|
||||
const reply = extraTimerService.stop();
|
||||
return { payload: reply };
|
||||
}
|
||||
} else if (command && typeof command === 'object') {
|
||||
const reply = { payload: {} };
|
||||
if ('duration' in command) {
|
||||
const time = numberOrError(command.duration);
|
||||
reply.payload = extraTimerService.setTime(time * 1000); //frontend is seconds based
|
||||
}
|
||||
if ('direction' in command) {
|
||||
if (command.direction === SimpleDirection.CountUp || command.direction === SimpleDirection.CountDown) {
|
||||
reply.payload = extraTimerService.setDirection(command.direction);
|
||||
} else {
|
||||
throw new Error('Invalid direction payload');
|
||||
}
|
||||
}
|
||||
if (!isEmptyObject(reply.payload)) {
|
||||
return reply;
|
||||
}
|
||||
}
|
||||
throw new Error('No matching method provided');
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a value of type number, converting if necessary
|
||||
* Otherwise throws
|
||||
* @param value
|
||||
* @returns number
|
||||
* @throws
|
||||
*/
|
||||
function numberOrError(value: unknown) {
|
||||
const converted = Number(value);
|
||||
if (isNaN(converted)) {
|
||||
throw new Error('Payload is not a valid number');
|
||||
}
|
||||
return converted;
|
||||
}
|
||||
|
||||
function extractCue(value: unknown): string {
|
||||
if (typeof value === 'number') {
|
||||
return String(value);
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
throw new Error('Payload is not a valid string or number');
|
||||
}
|
||||
|
||||
function successPayloadOrError(success: boolean, error: string) {
|
||||
if (!success) {
|
||||
throw new Error(error);
|
||||
}
|
||||
return { payload: 'success' };
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* API Router
|
||||
* User to handle all requests which affect runtime
|
||||
* It is a mirror implementation of OSC and Websocket Adapters
|
||||
*
|
||||
*/
|
||||
|
||||
import { ErrorResponse, LogOrigin, RuntimeStore } from 'ontime-types';
|
||||
|
||||
import express, { type Request, type Response } from 'express';
|
||||
|
||||
import { logger } from '../classes/Logger.js';
|
||||
import { integrationPayloadFromPath } from '../adapters/utils/parse.js';
|
||||
|
||||
import { dispatchFromAdapter } from './integration.controller.js';
|
||||
import { getErrorMessage } from 'ontime-utils';
|
||||
import { eventStore } from '../stores/EventStore.js';
|
||||
import { isEmptyObject } from '../utils/parserUtils.js';
|
||||
|
||||
export const integrationRouter = express.Router();
|
||||
|
||||
const helloMessage = 'You have reached Ontime API server';
|
||||
|
||||
integrationRouter.get('/', (_req: Request, res: Response<{ message: string }>) => {
|
||||
res.status(200).json({ message: helloMessage });
|
||||
});
|
||||
|
||||
/**
|
||||
* All calls are sent to the dispatcher
|
||||
*/
|
||||
integrationRouter.get('/*', (req: Request, res: Response) => {
|
||||
let action = req.path.substring(1);
|
||||
if (!action) {
|
||||
return res.status(400).json({ error: 'No action found' });
|
||||
}
|
||||
|
||||
try {
|
||||
const actionArray = action.split('/');
|
||||
const query = isEmptyObject(req.query) ? undefined : (req.query as object);
|
||||
let payload = {};
|
||||
if (actionArray.length > 1) {
|
||||
action = actionArray.shift();
|
||||
payload = integrationPayloadFromPath(actionArray, query);
|
||||
} else {
|
||||
payload = query;
|
||||
}
|
||||
const reply = dispatchFromAdapter(action, payload, 'http');
|
||||
res.status(202).json(reply);
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorMessage(error);
|
||||
logger.error(LogOrigin.Rx, `HTTP IN: ${errorMessage}`);
|
||||
res.status(500).send({ message: errorMessage });
|
||||
}
|
||||
});
|
||||
|
||||
integrationRouter.get('/poll', (_req: Request, res: Response<Partial<RuntimeStore> | ErrorResponse>) => {
|
||||
try {
|
||||
const state = eventStore.poll();
|
||||
res.status(200).send(state);
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error);
|
||||
res.status(500).send({ message: `Could not get sync data: ${message}` });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { OntimeEvent, isKeyOfType, isOntimeEvent } from 'ontime-types';
|
||||
|
||||
import { DataProvider } from '../classes/data-provider/DataProvider.js';
|
||||
import { editEvent } from '../services/rundown-service/RundownService.js';
|
||||
import { getEventWithId } from '../services/rundown-service/rundownUtils.js';
|
||||
import { coerceBoolean, coerceColour, coerceNumber, coerceString } from '../utils/coerceType.js';
|
||||
|
||||
const whitelistedPayload = {
|
||||
title: coerceString,
|
||||
note: coerceString,
|
||||
cue: coerceString,
|
||||
|
||||
duration: (value: unknown) => coerceNumber(value) * 1000, //frontend is seconds based
|
||||
|
||||
isPublic: coerceBoolean,
|
||||
skip: coerceBoolean,
|
||||
|
||||
colour: coerceColour,
|
||||
|
||||
custom: coerceString,
|
||||
};
|
||||
|
||||
export function parseProperty(property: string, value: unknown) {
|
||||
if (property.startsWith('custom:')) {
|
||||
const customKey = property.split(':')[1];
|
||||
if (!(customKey in DataProvider.getCustomFields())) {
|
||||
throw new Error(`Custom field ${customKey} not found`);
|
||||
}
|
||||
const parserFn = whitelistedPayload.custom;
|
||||
return { custom: { [customKey]: { value: parserFn(value) } } };
|
||||
}
|
||||
|
||||
if (!isKeyOfType(property, whitelistedPayload)) {
|
||||
throw new Error(`Property ${property} not permitted`);
|
||||
}
|
||||
const parserFn = whitelistedPayload[property];
|
||||
return { [property]: parserFn(value) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a property of the event with the given id
|
||||
* @param {Partial<OntimeEvent>} patchEvent
|
||||
*/
|
||||
export function updateEvent(patchEvent: Partial<OntimeEvent> & { id: string }) {
|
||||
const event = getEventWithId(patchEvent?.id ?? '');
|
||||
if (!event) {
|
||||
throw new Error(`Event with ID ${patchEvent?.id} not found`);
|
||||
}
|
||||
|
||||
if (!isOntimeEvent(event)) {
|
||||
throw new Error('Can only update events');
|
||||
}
|
||||
|
||||
editEvent(patchEvent);
|
||||
}
|
||||
+87
-84
@@ -1,58 +1,63 @@
|
||||
import { HttpSettings, LogOrigin, OSCSettings } from 'ontime-types';
|
||||
import { HttpSettings, LogOrigin, OSCSettings, Playback, SimpleDirection, SimplePlayback } from 'ontime-types';
|
||||
|
||||
import 'dotenv/config';
|
||||
import express from 'express';
|
||||
import expressStaticGzip from 'express-static-gzip';
|
||||
import http, { type Server } from 'http';
|
||||
import cors from 'cors';
|
||||
import serverTiming from 'server-timing';
|
||||
|
||||
// import utils
|
||||
import { join, resolve } from 'path';
|
||||
import { resolve } from 'path';
|
||||
import {
|
||||
currentDirectory,
|
||||
srcDirectory,
|
||||
environment,
|
||||
isProduction,
|
||||
resolveDbPath,
|
||||
resolveExternalsDirectory,
|
||||
resolveStylesDirectory,
|
||||
resolvedPath,
|
||||
} from './setup.js';
|
||||
} from './setup/index.js';
|
||||
import { ONTIME_VERSION } from './ONTIME_VERSION.js';
|
||||
|
||||
// Import Routes
|
||||
import { router as rundownRouter } from './routes/rundownRouter.js';
|
||||
import { router as projectRouter } from './routes/projectRouter.js';
|
||||
import { router as ontimeRouter } from './routes/ontimeRouter.js';
|
||||
import { router as playbackRouter } from './routes/playbackRouter.js';
|
||||
// Import Routers
|
||||
import { appRouter } from './api-data/index.js';
|
||||
import { integrationRouter } from './api-integration/integration.router.js';
|
||||
|
||||
// Import adapters
|
||||
import { OscServer } from './adapters/OscAdapter.js';
|
||||
import { socket } from './adapters/WebsocketAdapter.js';
|
||||
import { DataProvider } from './classes/data-provider/DataProvider.js';
|
||||
import { dbLoadingProcess } from './modules/loadDb.js';
|
||||
import { dbLoadingProcess } from './setup/loadDb.js';
|
||||
|
||||
// Services
|
||||
import { eventTimer } from './services/TimerService.js';
|
||||
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';
|
||||
import { RestorePoint, restoreService } from './services/RestoreService.js';
|
||||
import { populateStyles } from './setup/loadStyles.js';
|
||||
import { eventStore } from './stores/EventStore.js';
|
||||
import { runtimeService } from './services/runtime-service/RuntimeService.js';
|
||||
import { restoreService } from './services/RestoreService.js';
|
||||
import { messageService } from './services/message-service/MessageService.js';
|
||||
import { populateDemo } from './modules/loadDemo.js';
|
||||
import { populateDemo } from './setup/loadDemo.js';
|
||||
import { getState } from './stores/runtimeState.js';
|
||||
import { initRundown } from './services/rundown-service/RundownService.js';
|
||||
import { generateCrashReport } from './utils/generateCrashReport.js';
|
||||
|
||||
console.log(`Starting Ontime version ${ONTIME_VERSION}`);
|
||||
|
||||
if (!isProduction) {
|
||||
console.log(`Ontime running in ${environment} environment`);
|
||||
console.log(`Ontime directory at ${currentDirectory} `);
|
||||
console.log(`Ontime directory at ${srcDirectory} `);
|
||||
console.log(`Ontime database at ${resolveDbPath}`);
|
||||
}
|
||||
|
||||
// Create express APP
|
||||
const app = express();
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
// log more serever timings
|
||||
app.use(serverTiming());
|
||||
}
|
||||
app.disable('x-powered-by');
|
||||
|
||||
// setup cors for all routes
|
||||
@@ -66,10 +71,8 @@ app.use(express.urlencoded({ extended: true }));
|
||||
app.use(express.json({ limit: '1mb' }));
|
||||
|
||||
// Implement route endpoints
|
||||
app.use('/events', rundownRouter);
|
||||
app.use('/project', projectRouter);
|
||||
app.use('/ontime', ontimeRouter);
|
||||
app.use('/playback', playbackRouter);
|
||||
app.use('/data', appRouter); // router for application data
|
||||
app.use('/api', integrationRouter); // router for integrations
|
||||
|
||||
// serve static - css
|
||||
app.use('/external/styles', express.static(resolveStylesDirectory));
|
||||
@@ -79,20 +82,24 @@ app.use('/external', (req, res) => {
|
||||
});
|
||||
|
||||
// serve static - react, in dev/test mode we fetch the React app from module
|
||||
const reactAppPath = join(currentDirectory, resolvedPath());
|
||||
const reactAppPath = resolvedPath();
|
||||
app.use(
|
||||
expressStaticGzip(reactAppPath, {
|
||||
enableBrotli: true,
|
||||
orderPreference: ['br'],
|
||||
// when we build the client all the react subfiles will get a hashed name we can the immutable tag
|
||||
// as the contents of a build file will never change without also changing its name
|
||||
// so the client dose not need to revalidate the file contetnts with the server
|
||||
serveStatic: { etag: false, lastModified: false, immutable: true, maxAge: '1y' },
|
||||
}),
|
||||
);
|
||||
|
||||
app.get('*', (req, res) => {
|
||||
res.sendFile(resolve(currentDirectory, resolvedPath(), 'index.html'));
|
||||
app.get('*', (_req, res) => {
|
||||
res.sendFile(resolve(reactAppPath, 'index.html'));
|
||||
});
|
||||
|
||||
// Implement catch all
|
||||
app.use((error, response) => {
|
||||
app.use((_error, response) => {
|
||||
response.status(400).send('Unhandled request');
|
||||
});
|
||||
|
||||
@@ -121,7 +128,6 @@ enum OntimeStartOrder {
|
||||
|
||||
let step = OntimeStartOrder.InitAssets;
|
||||
let expressServer: Server | null = null;
|
||||
let oscServer: OscServer | null = null;
|
||||
|
||||
const checkStart = (currentState: OntimeStartOrder) => {
|
||||
if (step !== currentState) {
|
||||
@@ -149,26 +155,45 @@ export const startServer = async () => {
|
||||
checkStart(OntimeStartOrder.InitServer);
|
||||
|
||||
const { serverPort } = DataProvider.getSettings();
|
||||
|
||||
const returnMessage = `Ontime is listening on port ${serverPort}`;
|
||||
|
||||
expressServer = http.createServer(app);
|
||||
|
||||
socket.init(expressServer);
|
||||
eventLoader.init();
|
||||
logger.info(LogOrigin.Server, returnMessage);
|
||||
|
||||
/**
|
||||
* Module initialises the services and provides initial payload for the store
|
||||
*/
|
||||
const state = getState();
|
||||
eventStore.init({
|
||||
clock: state.clock,
|
||||
timer: state.timer,
|
||||
onAir: state.timer.playback !== Playback.Stop,
|
||||
message: messageService.getState(),
|
||||
runtime: state.runtime,
|
||||
eventNow: state.eventNow,
|
||||
publicEventNow: state.publicEventNow,
|
||||
eventNext: state.eventNext,
|
||||
publicEventNext: state.publicEventNext,
|
||||
auxtimer1: {
|
||||
duration: 0,
|
||||
current: 0,
|
||||
playback: SimplePlayback.Stop,
|
||||
direction: SimpleDirection.CountDown,
|
||||
},
|
||||
});
|
||||
|
||||
// initialise rundown service
|
||||
const persistedRundown = DataProvider.getRundown();
|
||||
const persistedCustomFields = DataProvider.getCustomFields();
|
||||
initRundown(persistedRundown, persistedCustomFields);
|
||||
|
||||
// load restore point if it exists
|
||||
const maybeRestorePoint = restoreService.load();
|
||||
const maybeRestorePoint = await restoreService.load();
|
||||
|
||||
if (maybeRestorePoint) {
|
||||
logger.info(LogOrigin.Server, 'Found resumable state');
|
||||
PlaybackService.resume(maybeRestorePoint);
|
||||
}
|
||||
|
||||
eventTimer.setRestoreCallback(async (newState: RestorePoint) => restoreService.save(newState));
|
||||
|
||||
// provide initial payload to event store
|
||||
const initialPayload = getInitialPayload();
|
||||
eventStore.init(initialPayload);
|
||||
// TODO: pass event store to rundownservice
|
||||
runtimeService.init(maybeRestorePoint);
|
||||
|
||||
// eventStore set is a dependency of the services that publish to it
|
||||
messageService.init(eventStore.set.bind(eventStore));
|
||||
@@ -178,58 +203,32 @@ export const startServer = async () => {
|
||||
return { message: returnMessage, serverPort };
|
||||
};
|
||||
|
||||
/**
|
||||
* @description starts OSC server
|
||||
* @param overrideConfig
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
export const startOSCServer = async (overrideConfig = null) => {
|
||||
checkStart(OntimeStartOrder.InitIO);
|
||||
|
||||
const { osc } = DataProvider.getData();
|
||||
|
||||
if (!osc.enabledIn) {
|
||||
logger.info(LogOrigin.Rx, 'OSC Input Disabled');
|
||||
return;
|
||||
}
|
||||
|
||||
// Setup default port
|
||||
const oscSettings = {
|
||||
...osc,
|
||||
portIn: overrideConfig?.port || osc.portIn,
|
||||
};
|
||||
|
||||
// Start OSC Server
|
||||
logger.info(LogOrigin.Rx, `Starting OSC Server on port: ${oscSettings.portIn}`);
|
||||
oscServer = new OscServer(oscSettings);
|
||||
};
|
||||
|
||||
/**
|
||||
* starts integrations
|
||||
*/
|
||||
export const startIntegrations = async (config?: { osc: OSCSettings; http: HttpSettings }) => {
|
||||
checkStart(OntimeStartOrder.InitIO);
|
||||
|
||||
// if a config is not provided, we use the persisted one
|
||||
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) {
|
||||
if (osc) {
|
||||
logger.info(LogOrigin.Tx, 'Initialising OSC Integration...');
|
||||
try {
|
||||
oscIntegration.init(osc);
|
||||
integrationService.register(oscIntegration);
|
||||
} catch (error) {
|
||||
logger.error(LogOrigin.Tx, 'OSC Integration initialisation failed');
|
||||
}
|
||||
}
|
||||
if (!http) {
|
||||
return 'HTTP Invalid configuration';
|
||||
} else {
|
||||
const { success, message } = httpIntegration.init(http);
|
||||
logger.info(LogOrigin.Tx, message);
|
||||
|
||||
if (success) {
|
||||
if (http) {
|
||||
logger.info(LogOrigin.Tx, 'Initialising HTTP Integration...');
|
||||
try {
|
||||
httpIntegration.init(http);
|
||||
integrationService.register(httpIntegration);
|
||||
} catch (error) {
|
||||
logger.error(LogOrigin.Tx, `HTTP Integration initialisation failed: ${error}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -245,28 +244,32 @@ export const shutdown = async (exitCode = 0) => {
|
||||
// clear the restore file if it was a normal exit
|
||||
// 0 means it was a SIGNAL
|
||||
// 1 means crash -> keep the file
|
||||
// 99 means it was the UI
|
||||
// 99 means there was a shutdown request from the UI
|
||||
if (exitCode === 0 || exitCode === 99) {
|
||||
await restoreService.clear();
|
||||
}
|
||||
|
||||
// TODO: Clear token
|
||||
expressServer?.close();
|
||||
oscServer?.shutdown();
|
||||
eventTimer.shutdown();
|
||||
runtimeService.shutdown();
|
||||
integrationService.shutdown();
|
||||
logger.shutdown();
|
||||
socket.shutdown();
|
||||
process.exit(exitCode);
|
||||
};
|
||||
|
||||
process.on('exit', (code) => console.log(`Ontime exited with code: ${code}`));
|
||||
process.on('exit', (code) => console.log(`Ontime shutdown with code: ${code}`));
|
||||
|
||||
process.on('unhandledRejection', async (error) => {
|
||||
console.error('Error: unhandled rejection', error);
|
||||
generateCrashReport(error);
|
||||
logger.error(LogOrigin.Server, `Error: unhandled rejection ${error}`);
|
||||
await shutdown(1);
|
||||
});
|
||||
|
||||
process.on('uncaughtException', async (error) => {
|
||||
console.error('Error: uncaught exception', error);
|
||||
generateCrashReport(error);
|
||||
logger.error(LogOrigin.Server, `Error: uncaught exception ${error}`);
|
||||
await shutdown(1);
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Log, LogLevel } from 'ontime-types';
|
||||
import { generateId, millisToString } from 'ontime-utils';
|
||||
|
||||
import { clock } from '../services/Clock.js';
|
||||
import { isProduction } from '../setup.js';
|
||||
import { isProduction } from '../setup/index.js';
|
||||
import { socket } from '../adapters/WebsocketAdapter.js';
|
||||
|
||||
class Logger {
|
||||
@@ -54,7 +54,7 @@ class Logger {
|
||||
* @param origin
|
||||
* @param text
|
||||
*/
|
||||
emit(level, origin: string, text: string) {
|
||||
emit(level: LogLevel, origin: string, text: string) {
|
||||
const log = {
|
||||
id: generateId(),
|
||||
level,
|
||||
|
||||
@@ -8,118 +8,123 @@ import {
|
||||
ViewSettings,
|
||||
DatabaseModel,
|
||||
OSCSettings,
|
||||
UserFields,
|
||||
Alias,
|
||||
Settings,
|
||||
CustomFields,
|
||||
HttpSettings,
|
||||
URLPreset,
|
||||
} from 'ontime-types';
|
||||
|
||||
import { data, db } from '../../modules/loadDb.js';
|
||||
import { data, db } from '../../setup/loadDb.js';
|
||||
import { safeMerge } from './DataProvider.utils.js';
|
||||
import { isTest } from '../../setup/index.js';
|
||||
|
||||
type ReadonlyPromise<T> = Promise<Readonly<T>>;
|
||||
|
||||
export class DataProvider {
|
||||
static getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
static async setProjectData(newData: Partial<ProjectData>) {
|
||||
static async setProjectData(newData: Partial<ProjectData>): ReadonlyPromise<ProjectData> {
|
||||
data.project = { ...data.project, ...newData };
|
||||
await this.persist();
|
||||
this.persist();
|
||||
return data.project;
|
||||
}
|
||||
|
||||
static getProjectData() {
|
||||
static getProjectData(): Readonly<ProjectData> {
|
||||
return data.project;
|
||||
}
|
||||
|
||||
static async setRundown(newData: OntimeRundown) {
|
||||
static async setCustomFields(newData: CustomFields): ReadonlyPromise<CustomFields> {
|
||||
data.customFields = { ...newData };
|
||||
this.persist();
|
||||
return data.customFields;
|
||||
}
|
||||
|
||||
static getCustomFields(): Readonly<CustomFields> {
|
||||
return data.customFields;
|
||||
}
|
||||
|
||||
static async setRundown(newData: OntimeRundown): ReadonlyPromise<OntimeRundown> {
|
||||
data.rundown = [...newData];
|
||||
await this.persist();
|
||||
this.persist();
|
||||
return data.rundown;
|
||||
}
|
||||
|
||||
static getIndexOf(eventId: string) {
|
||||
return data.rundown.findIndex((e) => e.id === eventId);
|
||||
}
|
||||
|
||||
static getRundownLength() {
|
||||
return data.rundown.length;
|
||||
}
|
||||
|
||||
static async clearRundown() {
|
||||
data.rundown = [];
|
||||
await db.write();
|
||||
}
|
||||
|
||||
static getSettings() {
|
||||
static getSettings(): Readonly<Settings> {
|
||||
return data.settings;
|
||||
}
|
||||
|
||||
static async setSettings(newData: Settings) {
|
||||
static async setSettings(newData: Settings): ReadonlyPromise<Settings> {
|
||||
data.settings = { ...newData };
|
||||
await this.persist();
|
||||
this.persist();
|
||||
return data.settings;
|
||||
}
|
||||
|
||||
static getOsc() {
|
||||
static getOsc(): Readonly<OSCSettings> {
|
||||
return data.osc;
|
||||
}
|
||||
|
||||
static getHttp() {
|
||||
static getHttp(): Readonly<HttpSettings> {
|
||||
return data.http;
|
||||
}
|
||||
|
||||
static getAliases() {
|
||||
return data.aliases;
|
||||
static getUrlPresets(): Readonly<URLPreset[]> {
|
||||
return data.urlPresets;
|
||||
}
|
||||
|
||||
static async setAliases(newData: Alias[]) {
|
||||
data.aliases = newData;
|
||||
await this.persist();
|
||||
static async setUrlPresets(newData: URLPreset[]): ReadonlyPromise<URLPreset[]> {
|
||||
data.urlPresets = newData;
|
||||
this.persist();
|
||||
return data.urlPresets;
|
||||
}
|
||||
|
||||
static getUserFields() {
|
||||
return { ...data.userFields };
|
||||
static getViewSettings(): Readonly<ViewSettings> {
|
||||
return data.viewSettings;
|
||||
}
|
||||
|
||||
static getViewSettings() {
|
||||
return { ...data.viewSettings };
|
||||
}
|
||||
|
||||
static async setViewSettings(newData: ViewSettings) {
|
||||
static async setViewSettings(newData: ViewSettings): ReadonlyPromise<ViewSettings> {
|
||||
data.viewSettings = { ...newData };
|
||||
await this.persist();
|
||||
this.persist();
|
||||
return data.viewSettings;
|
||||
}
|
||||
|
||||
static async setUserFields(newData: UserFields) {
|
||||
data.userFields = { ...newData };
|
||||
await this.persist();
|
||||
}
|
||||
|
||||
static async setOsc(newData: OSCSettings) {
|
||||
static async setOsc(newData: OSCSettings): ReadonlyPromise<OSCSettings> {
|
||||
data.osc = { ...newData };
|
||||
await this.persist();
|
||||
this.persist();
|
||||
return data.osc;
|
||||
}
|
||||
|
||||
static async setHttp(newData) {
|
||||
static async setHttp(newData: HttpSettings): ReadonlyPromise<HttpSettings> {
|
||||
data.http = { ...newData };
|
||||
await this.persist();
|
||||
this.persist();
|
||||
return data.http;
|
||||
}
|
||||
|
||||
static getRundown() {
|
||||
return [...data.rundown];
|
||||
static getRundown(): Readonly<OntimeRundown> {
|
||||
return data.rundown;
|
||||
}
|
||||
|
||||
static async persist() {
|
||||
private static async persist() {
|
||||
if (isTest) {
|
||||
return;
|
||||
}
|
||||
await db.write();
|
||||
}
|
||||
|
||||
static async mergeIntoData(newData: Partial<DatabaseModel>) {
|
||||
static async mergeIntoData(newData: Partial<DatabaseModel>): ReadonlyPromise<DatabaseModel> {
|
||||
const mergedData = safeMerge(data, newData);
|
||||
data.project = mergedData.project;
|
||||
data.settings = mergedData.settings;
|
||||
data.viewSettings = mergedData.viewSettings;
|
||||
data.osc = mergedData.osc;
|
||||
data.aliases = mergedData.aliases;
|
||||
data.userFields = mergedData.userFields;
|
||||
data.http = mergedData.http;
|
||||
data.urlPresets = mergedData.urlPresets;
|
||||
data.customFields = mergedData.customFields;
|
||||
data.rundown = mergedData.rundown;
|
||||
await this.persist();
|
||||
|
||||
this.persist();
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,33 +6,17 @@ import { DatabaseModel } from 'ontime-types';
|
||||
* @param {object} newData
|
||||
*/
|
||||
export function safeMerge(existing: DatabaseModel, newData: Partial<DatabaseModel>) {
|
||||
const { rundown, project, settings, viewSettings, osc, aliases, userFields } = newData || {};
|
||||
const { rundown, project, settings, viewSettings, urlPresets, customFields, osc, http } = newData || {};
|
||||
|
||||
return {
|
||||
...existing,
|
||||
rundown: rundown ?? existing.rundown,
|
||||
project: { ...existing.project, ...project },
|
||||
settings: { ...existing.settings, ...settings },
|
||||
viewSettings: { ...existing.viewSettings, ...viewSettings },
|
||||
aliases: aliases ?? existing.aliases,
|
||||
userFields: {
|
||||
...existing.userFields,
|
||||
...(userFields && Object.fromEntries(Object.entries(userFields).filter(([_, value]) => value !== null))),
|
||||
},
|
||||
osc: {
|
||||
...existing.osc,
|
||||
...osc,
|
||||
subscriptions: {
|
||||
...existing.osc?.subscriptions,
|
||||
...(newData?.osc?.subscriptions || {}),
|
||||
...(existing.osc?.subscriptions && newData?.osc?.subscriptions
|
||||
? Object.keys(existing.osc.subscriptions).reduce((acc, key) => {
|
||||
if (!(key in newData.osc.subscriptions)) {
|
||||
acc[key] = existing.osc.subscriptions[key];
|
||||
}
|
||||
return acc;
|
||||
}, {})
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
urlPresets: urlPresets ?? existing.urlPresets,
|
||||
customFields: customFields ?? existing.customFields,
|
||||
osc: { ...existing.osc, ...osc },
|
||||
http: { ...existing.http, ...http },
|
||||
};
|
||||
}
|
||||
|
||||
+47
-75
@@ -1,4 +1,4 @@
|
||||
import { Alias, DatabaseModel, OntimeRundown, Settings } from 'ontime-types';
|
||||
import { DatabaseModel, OntimeRundown, Settings, URLPreset } from 'ontime-types';
|
||||
import { safeMerge } from '../DataProvider.utils.js';
|
||||
|
||||
describe('safeMerge', () => {
|
||||
@@ -23,12 +23,16 @@ describe('safeMerge', () => {
|
||||
},
|
||||
viewSettings: {
|
||||
overrideStyles: false,
|
||||
freezeEnd: false,
|
||||
endMessage: 'existing endMessage',
|
||||
normalColor: '#ffffffcc',
|
||||
warningColor: '#FFAB33',
|
||||
dangerColor: '#ED3333',
|
||||
},
|
||||
aliases: [],
|
||||
userFields: {
|
||||
user0: 'existing user0',
|
||||
user1: 'existing user1',
|
||||
urlPresets: [],
|
||||
customFields: {
|
||||
lighting: { type: 'string', label: 'lighting', colour: 'red' },
|
||||
vfx: { type: 'string', label: 'vfx', colour: 'blue' },
|
||||
},
|
||||
osc: {
|
||||
portIn: 8888,
|
||||
@@ -36,14 +40,11 @@ describe('safeMerge', () => {
|
||||
targetIP: '127.0.0.1',
|
||||
enabledIn: false,
|
||||
enabledOut: false,
|
||||
subscriptions: {
|
||||
onLoad: [],
|
||||
onStart: [],
|
||||
onPause: [],
|
||||
onStop: [],
|
||||
onUpdate: [],
|
||||
onFinish: [],
|
||||
},
|
||||
subscriptions: [],
|
||||
},
|
||||
http: {
|
||||
enabledOut: false,
|
||||
subscriptions: [],
|
||||
},
|
||||
} as DatabaseModel;
|
||||
|
||||
@@ -101,43 +102,36 @@ describe('safeMerge', () => {
|
||||
const newData = {
|
||||
osc: {
|
||||
portIn: 7777,
|
||||
subscriptions: {
|
||||
onStart: [
|
||||
{
|
||||
id: 'unique',
|
||||
message: 'new message',
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
subscriptions: [
|
||||
{
|
||||
id: 'unique',
|
||||
cycle: 'onStart',
|
||||
message: 'new message',
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
//@ts-expect-error -- testing partial merge
|
||||
const mergedData = safeMerge(existing, newData);
|
||||
expect(mergedData.osc).toEqual({
|
||||
expect(mergedData.osc).toMatchObject({
|
||||
portIn: 7777,
|
||||
portOut: 9999,
|
||||
targetIP: '127.0.0.1',
|
||||
enabledIn: false,
|
||||
enabledOut: false,
|
||||
subscriptions: {
|
||||
onLoad: [],
|
||||
onStart: [
|
||||
{
|
||||
id: 'unique',
|
||||
message: 'new message',
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
onPause: [],
|
||||
onStop: [],
|
||||
onUpdate: [],
|
||||
onFinish: [],
|
||||
},
|
||||
subscriptions: [
|
||||
{
|
||||
id: 'unique',
|
||||
cycle: 'onStart',
|
||||
message: 'new message',
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('should merge the aliases key when present', () => {
|
||||
it('should merge the urlPresets key when present', () => {
|
||||
const existingData = {
|
||||
rundown: [],
|
||||
project: {
|
||||
@@ -160,73 +154,51 @@ describe('safeMerge', () => {
|
||||
overrideStyles: false,
|
||||
endMessage: '',
|
||||
},
|
||||
aliases: [],
|
||||
userFields: {
|
||||
user0: 'user0',
|
||||
user1: 'user1',
|
||||
user2: 'user2',
|
||||
user3: 'user3',
|
||||
user4: 'user4',
|
||||
user5: 'user5',
|
||||
user6: 'user6',
|
||||
user7: 'user7',
|
||||
user8: 'user8',
|
||||
user9: 'user9',
|
||||
},
|
||||
urlPresets: [],
|
||||
osc: {
|
||||
portIn: 8888,
|
||||
portOut: 9999,
|
||||
targetIP: '127.0.0.1',
|
||||
enabledIn: false,
|
||||
enabledOut: false,
|
||||
subscriptions: {
|
||||
onLoad: [],
|
||||
onStart: [],
|
||||
onPause: [],
|
||||
onStop: [],
|
||||
onUpdate: [],
|
||||
onFinish: [],
|
||||
},
|
||||
subscriptions: [],
|
||||
},
|
||||
} as DatabaseModel;
|
||||
|
||||
const newData = {
|
||||
aliases: [
|
||||
urlPresets: [
|
||||
{ enabled: true, alias: 'alias1', pathAndParams: '' },
|
||||
{ enabled: true, alias: 'alias2', pathAndParams: '' },
|
||||
] as Alias[],
|
||||
] as URLPreset[],
|
||||
};
|
||||
|
||||
const mergedData = safeMerge(existingData, newData);
|
||||
|
||||
expect(mergedData.aliases).toEqual(newData.aliases);
|
||||
expect(mergedData.urlPresets).toEqual(newData.urlPresets);
|
||||
});
|
||||
|
||||
it('merges userFields into existing object', () => {
|
||||
it('merges customFields into existing object', () => {
|
||||
const existing = {
|
||||
userFields: {
|
||||
user0: 'Alice',
|
||||
user1: 'Bob',
|
||||
customFields: {
|
||||
lighting: { type: 'string', label: 'lighting' },
|
||||
sound: { type: 'string', label: 'sound' },
|
||||
},
|
||||
};
|
||||
|
||||
const newData = {
|
||||
userFields: {
|
||||
user2: 'Charlie',
|
||||
user3: 'David',
|
||||
user4: null,
|
||||
customFields: {
|
||||
switcher: { type: 'string', label: 'switcher' },
|
||||
vfx: { type: 'string', label: 'vfx' },
|
||||
},
|
||||
};
|
||||
|
||||
const expected = {
|
||||
user0: 'Alice',
|
||||
user1: 'Bob',
|
||||
user2: 'Charlie',
|
||||
user3: 'David',
|
||||
switcher: { type: 'string', label: 'switcher' },
|
||||
vfx: { type: 'string', label: 'vfx' },
|
||||
};
|
||||
|
||||
//@ts-expect-error -- testing partial merge
|
||||
const result = safeMerge(existing, newData);
|
||||
expect(result.userFields).toEqual(expected);
|
||||
expect(result.customFields).toEqual(expected);
|
||||
});
|
||||
});
|
||||
@@ -1,347 +0,0 @@
|
||||
import { Loaded, OntimeEvent, SupportedEvent } from 'ontime-types';
|
||||
|
||||
import { DataProvider } from '../data-provider/DataProvider.js';
|
||||
import { getRollTimers } from '../../services/rollUtils.js';
|
||||
import { eventStore } from '../../stores/EventStore.js';
|
||||
|
||||
let instance;
|
||||
|
||||
/**
|
||||
* Manages business logic around loading events
|
||||
*/
|
||||
export class EventLoader {
|
||||
loaded: Loaded;
|
||||
eventNow: OntimeEvent | null;
|
||||
publicEventNow: OntimeEvent | null;
|
||||
eventNext: OntimeEvent | null;
|
||||
publicEventNext: OntimeEvent | null;
|
||||
|
||||
constructor() {
|
||||
if (instance) {
|
||||
throw new Error('There can be only one');
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-this-alias -- this logic is used to ensure singleton
|
||||
instance = this;
|
||||
this.eventNow = null;
|
||||
this.publicEventNow = null;
|
||||
this.eventNext = null;
|
||||
this.publicEventNext = null;
|
||||
this.loaded = {
|
||||
selectedEventIndex: null,
|
||||
selectedEventId: null,
|
||||
selectedPublicEventId: null,
|
||||
nextEventId: null,
|
||||
nextPublicEventId: null,
|
||||
numEvents: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// we need to delay init until the store is ready
|
||||
init() {
|
||||
this.reset(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* returns all events that contain time data
|
||||
* @return {array}
|
||||
*/
|
||||
static getTimedEvents(): OntimeEvent[] {
|
||||
return DataProvider.getRundown().filter((event) => event.type === SupportedEvent.Event) as OntimeEvent[];
|
||||
}
|
||||
|
||||
/**
|
||||
* returns all events that can be loaded
|
||||
* @return {array}
|
||||
*/
|
||||
static getPlayableEvents(): OntimeEvent[] {
|
||||
return DataProvider.getRundown().filter(
|
||||
(event) => event.type === SupportedEvent.Event && !event.skip,
|
||||
) as OntimeEvent[];
|
||||
}
|
||||
|
||||
/**
|
||||
* returns number of events
|
||||
* @return {number}
|
||||
*/
|
||||
static getNumEvents() {
|
||||
return EventLoader.getTimedEvents().length;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns an event given its index after filtering for OntimeEvents
|
||||
* @param {number} eventIndex
|
||||
* @return {OntimeEvent | undefined}
|
||||
*/
|
||||
static getEventAtIndex(eventIndex: number): OntimeEvent | undefined {
|
||||
const timedEvents = EventLoader.getTimedEvents();
|
||||
return timedEvents?.[eventIndex];
|
||||
}
|
||||
|
||||
/**
|
||||
* returns an event given its id
|
||||
* @param {string} eventId
|
||||
* @return {object | undefined}
|
||||
*/
|
||||
static getEventWithId(eventId): OntimeEvent | undefined {
|
||||
const timedEvents = EventLoader.getTimedEvents();
|
||||
return timedEvents.find((event) => event.id === eventId);
|
||||
}
|
||||
|
||||
/**
|
||||
* returns first event given its cue
|
||||
* @param {string} cue
|
||||
* @return {object | undefined}
|
||||
*/
|
||||
static getEventWithCue(cue) {
|
||||
const timedEvents = EventLoader.getTimedEvents();
|
||||
return timedEvents.find((event) => event.cue === cue);
|
||||
}
|
||||
|
||||
/**
|
||||
* loads an event given its id
|
||||
* @param {string} eventId
|
||||
* @returns {{loadedEvent: null, selectedEventId: null, nextEventId: null, selectedPublicEventId: null, nextPublicEventId: null, numEvents: null, titles: {presenterNext: null, titleNow: null, subtitleNow: null, titleNext: null, subtitleNext: null, presenterNow: null, noteNow: null, noteNext: null}, titlesPublic: {presenterNext: null, titleNow: null, subtitleNow: null, titleNext: null, subtitleNext: null, presenterNow: null}, selectedEventIndex: null}}
|
||||
*/
|
||||
loadById(eventId) {
|
||||
const event = EventLoader.getEventWithId(eventId);
|
||||
return this.loadEvent(event);
|
||||
}
|
||||
|
||||
/**
|
||||
* loads an event given its index
|
||||
* @param {number} eventIndex
|
||||
* @returns {{loadedEvent: null, selectedEventId: null, nextEventId: null, selectedPublicEventId: null, nextPublicEventId: null, numEvents: null, titles: {presenterNext: null, titleNow: null, subtitleNow: null, titleNext: null, subtitleNext: null, presenterNow: null, noteNow: null, noteNext: null}, titlesPublic: {presenterNext: null, titleNow: null, subtitleNow: null, titleNext: null, subtitleNext: null, presenterNow: null}, selectedEventIndex: null}}
|
||||
*/
|
||||
loadByIndex(eventIndex) {
|
||||
const event = EventLoader.getEventAtIndex(eventIndex);
|
||||
return this.loadEvent(event);
|
||||
}
|
||||
|
||||
/**
|
||||
* finds the previous event
|
||||
* @return {object | undefined}
|
||||
*/
|
||||
findPrevious() {
|
||||
const timedEvents = EventLoader.getPlayableEvents();
|
||||
if (timedEvents === null || !timedEvents.length || this.loaded.selectedEventIndex === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// if there is no event running, go to first
|
||||
if (this.loaded.selectedEventIndex === null) {
|
||||
return timedEvents[0];
|
||||
}
|
||||
|
||||
const newIndex = this.loaded.selectedEventIndex - 1;
|
||||
return timedEvents?.[newIndex];
|
||||
}
|
||||
|
||||
/**
|
||||
* finds the next event
|
||||
* @return {object | undefined}
|
||||
*/
|
||||
findNext() {
|
||||
const timedEvents = EventLoader.getPlayableEvents();
|
||||
if (timedEvents === null || !timedEvents.length || this.loaded.selectedEventIndex === this.loaded.numEvents - 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// if there is no event running, go to first
|
||||
if (this.loaded.selectedEventIndex === null) {
|
||||
return timedEvents[0];
|
||||
}
|
||||
const newIndex = this.loaded.selectedEventIndex + 1;
|
||||
return timedEvents?.[newIndex];
|
||||
}
|
||||
|
||||
/**
|
||||
* finds next event within Roll context
|
||||
* @param {number} timeNow - current time in ms
|
||||
*/
|
||||
findRoll(timeNow) {
|
||||
const timedEvents = EventLoader.getPlayableEvents();
|
||||
if (!timedEvents.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { nowIndex, timeToNext, nextEvent, nextPublicEvent, currentEvent, currentPublicEvent } = getRollTimers(
|
||||
timedEvents,
|
||||
timeNow,
|
||||
);
|
||||
|
||||
// load events
|
||||
this.eventNow = currentEvent;
|
||||
this.publicEventNow = currentPublicEvent;
|
||||
this.eventNext = nextEvent;
|
||||
this.publicEventNext = nextPublicEvent;
|
||||
|
||||
// loaded data summary
|
||||
this.loaded.selectedEventIndex = nowIndex;
|
||||
this.loaded.selectedEventId = currentEvent?.id || null;
|
||||
this.loaded.numEvents = timedEvents.length;
|
||||
this.loaded.nextEventId = nextEvent?.id || null;
|
||||
this.loaded.nextPublicEventId = nextPublicEvent?.id || null;
|
||||
|
||||
this._loadEvent();
|
||||
|
||||
return { currentEvent, nextEvent, timeToNext };
|
||||
}
|
||||
|
||||
/**
|
||||
* returns data for currently loaded event
|
||||
* @returns {{loadedEvent: null, selectedEventId: (null|*), nextEventId: (null|*), selectedPublicEventId: (null|*), nextPublicEventId: (null|*), numEvents: (null|number|*), titles: (*|{presenterNext: null, titleNow: null, subtitleNow: null, titleNext: null, subtitleNext: null, presenterNow: null, noteNow: null, noteNext: null}), titlesPublic: (*|{presenterNext: null, titleNow: null, subtitleNow: null, titleNext: null, subtitleNext: null, presenterNow: null}), selectedEventIndex: (null|number|*)}}
|
||||
*/
|
||||
getLoaded() {
|
||||
return {
|
||||
loaded: this.loaded,
|
||||
eventNow: this.eventNow,
|
||||
publicEventNow: this.publicEventNow,
|
||||
eventNext: this.eventNext,
|
||||
publicEventNext: this.publicEventNext,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Forces event loader to update the event count
|
||||
*/
|
||||
updateNumEvents() {
|
||||
this.loaded.numEvents = EventLoader.getPlayableEvents().length;
|
||||
eventStore.set('loaded', this.loaded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets instance state
|
||||
*/
|
||||
reset(emit = true) {
|
||||
this.eventNow = null;
|
||||
this.publicEventNow = null;
|
||||
this.eventNext = null;
|
||||
this.publicEventNext = null;
|
||||
this.loaded = {
|
||||
selectedEventIndex: null,
|
||||
selectedEventId: null,
|
||||
selectedPublicEventId: null,
|
||||
nextEventId: null,
|
||||
nextPublicEventId: null,
|
||||
numEvents: EventLoader.getPlayableEvents().length,
|
||||
};
|
||||
|
||||
// workaround for socket not being ready in constructor
|
||||
if (emit) {
|
||||
this._loadEvent();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* loads an event given its id
|
||||
* @param {object} event
|
||||
*/
|
||||
loadEvent(event?: OntimeEvent) {
|
||||
if (typeof event === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
const timedEvents = EventLoader.getPlayableEvents();
|
||||
const eventIndex = timedEvents.findIndex((eventInMemory) => eventInMemory.id === event.id);
|
||||
const playableEvents = EventLoader.getPlayableEvents();
|
||||
|
||||
// we know some stuff now
|
||||
this.loaded.selectedEventIndex = eventIndex;
|
||||
this.loaded.selectedEventId = event.id;
|
||||
this.loaded.numEvents = timedEvents.length;
|
||||
this.eventNow = event;
|
||||
this._loadEventNow(event, playableEvents);
|
||||
this._loadEventNext(playableEvents);
|
||||
|
||||
this._loadEvent();
|
||||
|
||||
return this.getLoaded();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle side effects from event loading
|
||||
*/
|
||||
private _loadEvent() {
|
||||
eventStore.batchSet({
|
||||
loaded: this.loaded,
|
||||
eventNow: this.eventNow,
|
||||
publicEventNow: this.publicEventNow,
|
||||
eventNext: this.eventNext,
|
||||
publicEventNext: this.publicEventNext,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @description loads currently running events
|
||||
* @private
|
||||
* @param {object} event
|
||||
* @param {array} rundown
|
||||
*/
|
||||
private _loadEventNow(event, rundown) {
|
||||
this.eventNow = event;
|
||||
|
||||
// check if current is also public
|
||||
if (event.isPublic) {
|
||||
this.publicEventNow = event;
|
||||
this.loaded.selectedPublicEventId = event.id;
|
||||
} else {
|
||||
// assume there is no public event
|
||||
this.publicEventNow = null;
|
||||
this.loaded.selectedPublicEventId = null;
|
||||
|
||||
// if there is nothing before, return
|
||||
if (this.loaded.selectedEventIndex === 0) return;
|
||||
|
||||
// iterate backwards to find it
|
||||
for (let i = this.loaded.selectedEventIndex; i >= 0; i--) {
|
||||
if (rundown[i].isPublic) {
|
||||
this.publicEventNow = rundown[i];
|
||||
this.loaded.selectedPublicEventId = rundown[i].id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description look for next events
|
||||
* @private
|
||||
*/
|
||||
private _loadEventNext(rundown) {
|
||||
// assume there are no next events
|
||||
this.eventNext = null;
|
||||
this.publicEventNext = null;
|
||||
this.loaded.nextEventId = null;
|
||||
this.loaded.nextPublicEventId = null;
|
||||
|
||||
if (this.loaded.selectedEventIndex === null) return;
|
||||
|
||||
const numEvents = rundown.length;
|
||||
|
||||
if (this.loaded.selectedEventIndex < numEvents - 1) {
|
||||
let nextPublic = false;
|
||||
let nextProduction = false;
|
||||
|
||||
for (let i = this.loaded.selectedEventIndex + 1; i < numEvents; i++) {
|
||||
// if we have not set private
|
||||
if (!nextProduction) {
|
||||
this.eventNext = rundown[i];
|
||||
this.loaded.nextEventId = rundown[i].id;
|
||||
nextProduction = true;
|
||||
}
|
||||
|
||||
// if event is public
|
||||
if (rundown[i].isPublic) {
|
||||
this.publicEventNext = rundown[i];
|
||||
this.loaded.nextPublicEventId = rundown[i].id;
|
||||
nextPublic = true;
|
||||
}
|
||||
|
||||
// Stop if both are set
|
||||
if (nextPublic && nextProduction) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const eventLoader = new EventLoader();
|
||||
@@ -0,0 +1,78 @@
|
||||
import { SimpleDirection, SimplePlayback, SimpleTimerState } from 'ontime-types';
|
||||
|
||||
export class SimpleTimer {
|
||||
state: SimpleTimerState = {
|
||||
duration: 0,
|
||||
current: 0,
|
||||
playback: SimplePlayback.Stop,
|
||||
direction: SimpleDirection.CountDown,
|
||||
};
|
||||
private startedAt: number | null = null;
|
||||
private pausedAt: number | null = null;
|
||||
|
||||
public reset() {
|
||||
this.state = {
|
||||
duration: 0,
|
||||
current: 0,
|
||||
playback: SimplePlayback.Stop,
|
||||
direction: SimpleDirection.CountDown,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the duration of the timer
|
||||
* @param time - time in milliseconds
|
||||
*/
|
||||
public setTime(time: number): SimpleTimerState {
|
||||
this.state.duration = time;
|
||||
this.state.current = time;
|
||||
return this.state;
|
||||
}
|
||||
|
||||
public setDirection(direction: SimpleDirection): SimpleTimerState {
|
||||
this.state.playback = SimplePlayback.Stop;
|
||||
this.state.current = this.state.duration;
|
||||
this.state.direction = direction;
|
||||
return this.state;
|
||||
}
|
||||
|
||||
public start(timeNow: number): SimpleTimerState {
|
||||
if (this.state.playback === SimplePlayback.Pause) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- we know these are not null in a timer that is paused
|
||||
const elapsedSincePause = this.pausedAt! - this.startedAt!;
|
||||
this.startedAt = timeNow - elapsedSincePause;
|
||||
} else if (this.state.playback === SimplePlayback.Stop) {
|
||||
this.startedAt = timeNow;
|
||||
}
|
||||
this.state.playback = SimplePlayback.Start;
|
||||
return this.update(timeNow);
|
||||
}
|
||||
|
||||
public pause(timeNow: number): SimpleTimerState {
|
||||
if (this.state.playback !== SimplePlayback.Start) return this.state;
|
||||
this.state.playback = SimplePlayback.Pause;
|
||||
this.pausedAt = timeNow;
|
||||
return this.state;
|
||||
}
|
||||
|
||||
public stop(): SimpleTimerState {
|
||||
this.state.playback = SimplePlayback.Stop;
|
||||
this.state.current = this.state.duration;
|
||||
this.startedAt = null;
|
||||
return this.state;
|
||||
}
|
||||
|
||||
public update(timeNow: number): SimpleTimerState {
|
||||
if (this.state.playback === SimplePlayback.Start) {
|
||||
// we know startedAt is not null since we are in play mode
|
||||
const elapsed = timeNow - this.startedAt;
|
||||
if (this.state.direction === SimpleDirection.CountDown) {
|
||||
this.state.current = this.state.duration - elapsed;
|
||||
} else if (this.state.direction === SimpleDirection.CountUp) {
|
||||
this.state.current = this.state.duration + elapsed;
|
||||
}
|
||||
}
|
||||
|
||||
return this.state;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { SimpleDirection, SimplePlayback, SimpleTimerState } from 'ontime-types';
|
||||
|
||||
import { SimpleTimer } from '../SimpleTimer.js';
|
||||
|
||||
describe('SimpleTimer count-down', () => {
|
||||
let timer: SimpleTimer;
|
||||
|
||||
describe('normal timer flow', () => {
|
||||
const initialTime = 1000;
|
||||
timer = new SimpleTimer();
|
||||
|
||||
test('setting the timer duration', () => {
|
||||
const newState = timer.setTime(initialTime);
|
||||
const expected: SimpleTimerState = {
|
||||
duration: initialTime,
|
||||
current: initialTime,
|
||||
direction: SimpleDirection.CountDown,
|
||||
playback: SimplePlayback.Stop,
|
||||
};
|
||||
expect(newState).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
test('setting the timer to play', () => {
|
||||
const newState = timer.start(0);
|
||||
const expected: SimpleTimerState = {
|
||||
duration: initialTime,
|
||||
current: initialTime,
|
||||
direction: SimpleDirection.CountDown,
|
||||
playback: SimplePlayback.Start,
|
||||
};
|
||||
expect(newState).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
test('updating the timer', () => {
|
||||
let newState = timer.update(100);
|
||||
const expected: SimpleTimerState = {
|
||||
duration: initialTime,
|
||||
current: initialTime - 100,
|
||||
direction: SimpleDirection.CountDown,
|
||||
playback: SimplePlayback.Start,
|
||||
};
|
||||
expect(newState).toStrictEqual(expected);
|
||||
|
||||
newState = timer.update(500);
|
||||
expected.current = initialTime - 500;
|
||||
expect(newState).toStrictEqual(expected);
|
||||
|
||||
newState = timer.update(1500);
|
||||
expected.current = initialTime - 1500;
|
||||
expect(newState).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
test('pausing the time doesnt affect the current', () => {
|
||||
const pausedTime = 200;
|
||||
let newState = timer.pause(1500);
|
||||
const expected: SimpleTimerState = {
|
||||
duration: initialTime,
|
||||
current: initialTime - 1500,
|
||||
direction: SimpleDirection.CountDown,
|
||||
playback: SimplePlayback.Pause,
|
||||
};
|
||||
expect(newState).toStrictEqual(expected);
|
||||
|
||||
newState = timer.update(1600);
|
||||
expect(newState).toStrictEqual(expected);
|
||||
|
||||
newState = timer.update(1700);
|
||||
expect(newState).toStrictEqual(expected);
|
||||
|
||||
newState = timer.start(1700);
|
||||
expected.playback = SimplePlayback.Start;
|
||||
expect(newState).toStrictEqual(expected);
|
||||
|
||||
newState = timer.update(1800);
|
||||
expected.current = initialTime - 1800 + pausedTime;
|
||||
expect(newState).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
test('stopping the timer clears the running data', () => {
|
||||
const newState = timer.stop();
|
||||
const expected: SimpleTimerState = {
|
||||
duration: initialTime,
|
||||
current: initialTime,
|
||||
direction: SimpleDirection.CountDown,
|
||||
playback: SimplePlayback.Stop,
|
||||
};
|
||||
expect(newState).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
test('count-up mode', () => {
|
||||
const initialState = timer.setDirection(SimpleDirection.CountUp);
|
||||
expect(initialState.current).toBe(initialTime);
|
||||
|
||||
let newState = timer.start(0);
|
||||
const expected: SimpleTimerState = {
|
||||
duration: initialTime,
|
||||
current: initialTime,
|
||||
direction: SimpleDirection.CountUp,
|
||||
playback: SimplePlayback.Start,
|
||||
};
|
||||
|
||||
newState = timer.update(100);
|
||||
expected.current = initialTime + 100;
|
||||
expect(newState).toStrictEqual(expected);
|
||||
|
||||
expect(newState).toStrictEqual(expected);
|
||||
|
||||
newState = timer.update(500);
|
||||
expected.current = initialTime + 500;
|
||||
expect(newState).toStrictEqual(expected);
|
||||
|
||||
newState = timer.update(1500);
|
||||
expected.current = initialTime + 1500;
|
||||
expect(newState).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
test('changing direction stops the timer', () => {
|
||||
const newState = timer.setDirection(SimpleDirection.CountDown);
|
||||
const expected: SimpleTimerState = {
|
||||
duration: initialTime,
|
||||
current: initialTime,
|
||||
direction: SimpleDirection.CountDown,
|
||||
playback: SimplePlayback.Stop,
|
||||
};
|
||||
|
||||
expect(newState).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
export const timerConfig = {
|
||||
skipLimit: 1000, // threshold of skip for recalculating
|
||||
updateRate: 32, // how often do we update the timer
|
||||
notificationRate: 1000, // how often do we notify clients and integrations
|
||||
triggerAhead: 16, // how far ahead do we trigger the end event
|
||||
};
|
||||
@@ -1,73 +0,0 @@
|
||||
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, 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,
|
||||
subtitle: coerceString,
|
||||
presenter: coerceString,
|
||||
note: coerceString,
|
||||
cue: coerceString,
|
||||
|
||||
duration: coerceNumber,
|
||||
|
||||
isPublic: coerceBoolean,
|
||||
skip: coerceBoolean,
|
||||
|
||||
colour: coerceColour,
|
||||
|
||||
user0: coerceString,
|
||||
user1: coerceString,
|
||||
user2: coerceString,
|
||||
user3: coerceString,
|
||||
user4: coerceString,
|
||||
user5: coerceString,
|
||||
user6: coerceString,
|
||||
user7: coerceString,
|
||||
user8: coerceString,
|
||||
user9: coerceString,
|
||||
};
|
||||
|
||||
export function parse(property: string, value: unknown) {
|
||||
if (!isKeyOfType(property, whitelistedPayload)) {
|
||||
throw new Error(`Property ${property} not permitted`);
|
||||
}
|
||||
const parserFn = whitelistedPayload[property];
|
||||
return { parsedProperty: property, parsedPayload: parserFn(value) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a property of the event with the given id
|
||||
* @param {string} eventId
|
||||
* @param {keyof OntimeEvent} propertyName
|
||||
* @param {OntimeEvent[typeof propertyName]} newValue
|
||||
*/
|
||||
export function updateEvent(
|
||||
eventId: string,
|
||||
propertyName: keyof OntimeEvent,
|
||||
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
|
||||
// needs to be converted to milliseconds
|
||||
if (propertyName === 'duration') {
|
||||
propertiesToUpdate.duration = (newValue as number) * 1000;
|
||||
propertiesToUpdate.timeEnd = event.timeStart + propertiesToUpdate.duration;
|
||||
}
|
||||
|
||||
editEvent({ id: eventId, ...propertiesToUpdate }).then(() => {
|
||||
logger.info(LogOrigin.Playback, `Updated ${propertyName} of event with ID ${eventId} to ${newValue}`);
|
||||
});
|
||||
} else {
|
||||
throw new Error(`Event with ID ${eventId} not found`);
|
||||
}
|
||||
}
|
||||
@@ -1,270 +0,0 @@
|
||||
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';
|
||||
|
||||
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;
|
||||
},
|
||||
_source?: 'osc' | 'ws',
|
||||
) {
|
||||
const payload = args.payload;
|
||||
const typeComponents = type.toLowerCase().split('/');
|
||||
const mainType = typeComponents[0];
|
||||
|
||||
switch (mainType) {
|
||||
case 'test-ontime': {
|
||||
return { topic: 'hello' };
|
||||
}
|
||||
|
||||
case 'ontime-poll': {
|
||||
return {
|
||||
topic: 'poll',
|
||||
payload: eventStore.poll(),
|
||||
};
|
||||
}
|
||||
|
||||
case 'set-onair': {
|
||||
if (typeof payload !== 'undefined') {
|
||||
messageService.setOnAir(Boolean(payload));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'onair': {
|
||||
messageService.setOnAir(true);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'offair': {
|
||||
messageService.setOnAir(false);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'set-timer-blink': {
|
||||
if (typeof payload !== 'undefined') {
|
||||
messageService.setTimerBlink(Boolean(payload));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'set-timer-blackout': {
|
||||
if (typeof payload !== 'undefined') {
|
||||
messageService.setTimerBlackout(Boolean(payload));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'set-timer-message-text': {
|
||||
if (typeof payload !== 'string') {
|
||||
throw new Error(`Unable to parse payload: ${payload}`);
|
||||
}
|
||||
messageService.setTimerText(payload);
|
||||
break;
|
||||
}
|
||||
case 'set-timer-message-visible': {
|
||||
if (typeof payload === 'undefined') {
|
||||
throw new Error(`Unable to parse payload: ${payload}`);
|
||||
}
|
||||
messageService.setTimerVisibility(Boolean(payload));
|
||||
break;
|
||||
}
|
||||
|
||||
case 'set-public-message-text': {
|
||||
if (typeof payload !== 'string') {
|
||||
throw new Error(`Unable to parse payload: ${payload}`);
|
||||
}
|
||||
messageService.setPublicText(payload);
|
||||
break;
|
||||
}
|
||||
case 'set-public-message-visible': {
|
||||
if (typeof payload === 'undefined') {
|
||||
throw new Error(`Unable to parse payload: ${payload}`);
|
||||
}
|
||||
messageService.setPublicVisibility(Boolean(payload));
|
||||
break;
|
||||
}
|
||||
|
||||
case 'set-lower-message-text': {
|
||||
if (typeof payload !== 'string') {
|
||||
throw new Error(`Unable to parse payload: ${payload}`);
|
||||
}
|
||||
messageService.setLowerText(payload);
|
||||
break;
|
||||
}
|
||||
case 'set-lower-message-visible': {
|
||||
if (typeof payload === 'undefined') {
|
||||
throw new Error(`Unable to parse payload: ${payload}`);
|
||||
}
|
||||
messageService.setLowerVisibility(Boolean(payload));
|
||||
break;
|
||||
}
|
||||
|
||||
case 'set-external-message-text': {
|
||||
if (typeof payload !== 'string') {
|
||||
throw new Error(`Unable to parse payload: ${payload}`);
|
||||
}
|
||||
messageService.setExternalText(payload);
|
||||
return;
|
||||
}
|
||||
case 'set-external-message-visible': {
|
||||
if (typeof payload === 'undefined') {
|
||||
throw new Error(`Unable to parse payload: ${payload}`);
|
||||
}
|
||||
messageService.setExternalVisibility(Boolean(payload));
|
||||
break;
|
||||
}
|
||||
case 'start': {
|
||||
PlaybackService.start();
|
||||
break;
|
||||
}
|
||||
|
||||
case 'start-next': {
|
||||
PlaybackService.startNext();
|
||||
break;
|
||||
}
|
||||
|
||||
case 'startindex': {
|
||||
const eventIndex = Number(payload);
|
||||
if (isNaN(eventIndex) || eventIndex <= 0) {
|
||||
throw new Error(`Event index not recognised or out of range ${eventIndex}`);
|
||||
}
|
||||
|
||||
// Indexes in frontend are 1 based
|
||||
const success = PlaybackService.startByIndex(eventIndex - 1);
|
||||
if (!success) {
|
||||
throw new Error(`Event index not recognised or out of range ${eventIndex}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'startid': {
|
||||
if (!payload || typeof payload !== 'string') {
|
||||
throw new Error(`Event ID not recognised: ${payload}`);
|
||||
}
|
||||
PlaybackService.startById(payload);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'startcue': {
|
||||
if (!payload || typeof payload !== 'string') {
|
||||
throw new Error(`Event cue not recognised: ${payload}`);
|
||||
}
|
||||
PlaybackService.startByCue(payload);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'pause': {
|
||||
PlaybackService.pause();
|
||||
break;
|
||||
}
|
||||
case 'previous': {
|
||||
PlaybackService.loadPrevious();
|
||||
break;
|
||||
}
|
||||
case 'next': {
|
||||
PlaybackService.loadNext();
|
||||
break;
|
||||
}
|
||||
case 'unload':
|
||||
case 'stop': {
|
||||
PlaybackService.stop();
|
||||
break;
|
||||
}
|
||||
case 'reload': {
|
||||
PlaybackService.reload();
|
||||
break;
|
||||
}
|
||||
case 'roll': {
|
||||
PlaybackService.roll();
|
||||
break;
|
||||
}
|
||||
case 'addtime': {
|
||||
const time = Number(payload);
|
||||
if (isNaN(time)) {
|
||||
throw new Error(`Time not recognised ${payload}`);
|
||||
}
|
||||
|
||||
PlaybackService.addTime(time);
|
||||
break;
|
||||
}
|
||||
//deprecated
|
||||
case 'delay': {
|
||||
const delayTime = Number(payload);
|
||||
if (isNaN(delayTime)) {
|
||||
throw new Error(`Delay time not recognised ${payload}`);
|
||||
}
|
||||
|
||||
PlaybackService.setDelay(delayTime);
|
||||
break;
|
||||
}
|
||||
case 'gotoindex':
|
||||
case 'loadindex': {
|
||||
const eventIndex = Number(payload);
|
||||
if (isNaN(eventIndex) || eventIndex <= 0) {
|
||||
throw new Error(`Event index not recognised or out of range ${eventIndex}`);
|
||||
}
|
||||
|
||||
// Indexes in frontend are 1 based
|
||||
const success = PlaybackService.loadByIndex(eventIndex - 1);
|
||||
if (!success) {
|
||||
throw new Error(`Event index not recognised or out of range ${eventIndex}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'gotoid':
|
||||
case 'loadid': {
|
||||
if (!payload) {
|
||||
throw new Error(`Event ID not recognised: ${payload}`);
|
||||
}
|
||||
|
||||
const success = PlaybackService.loadById(payload.toString().toLowerCase());
|
||||
if (!success) {
|
||||
throw new Error(`Event ID not found: ${payload}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'gotocue':
|
||||
case 'loadcue': {
|
||||
if (!payload || typeof payload !== 'string') {
|
||||
throw new Error(`Event cue not recognised: ${payload}`);
|
||||
}
|
||||
|
||||
const success = PlaybackService.loadByCue(payload);
|
||||
if (!success) {
|
||||
throw new Error(`Event cue not found: ${payload}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'get-playback': {
|
||||
const playback = eventStore.get('playback');
|
||||
return { topic: 'playback', payload: playback };
|
||||
}
|
||||
|
||||
case 'get-timer': {
|
||||
const timer = eventStore.get('timer');
|
||||
return { topic: 'timer', payload: timer };
|
||||
}
|
||||
|
||||
// WS: {type: 'change', payload: { eventId, property, value } }
|
||||
case 'change': {
|
||||
const { eventId, property, value } = payload as ChangeOptions;
|
||||
const { parsedPayload, parsedProperty } = parse(property, value);
|
||||
return updateEvent(eventId, parsedProperty, parsedPayload);
|
||||
}
|
||||
|
||||
default: {
|
||||
throw new Error(`Unhandled message ${type}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,578 +0,0 @@
|
||||
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';
|
||||
import { networkInterfaces } from 'os';
|
||||
|
||||
import { fileHandler } from '../utils/parser.js';
|
||||
import { DataProvider } from '../classes/data-provider/DataProvider.js';
|
||||
import { failEmptyObjects, failIsNotArray } from '../utils/routerUtils.js';
|
||||
import { PlaybackService } from '../services/PlaybackService.js';
|
||||
import { eventStore } from '../stores/EventStore.js';
|
||||
import { isDocker, resolveDbPath, resolveStylesPath } 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';
|
||||
|
||||
// Create controller for GET request to '/ontime/poll'
|
||||
// Returns data for current state
|
||||
export const poll = async (req, res) => {
|
||||
try {
|
||||
const s = eventStore.poll();
|
||||
res.status(200).send(s);
|
||||
} catch (error) {
|
||||
res.status(500).send({
|
||||
message: `Could not get sync data: ${error}`,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Create controller for GET request to '/ontime/db'
|
||||
// Returns -
|
||||
export const dbDownload = async (req, res) => {
|
||||
const { title } = DataProvider.getProjectData();
|
||||
const fileTitle = title || 'ontime data';
|
||||
|
||||
res.download(resolveDbPath, `${fileTitle}.json`, (err) => {
|
||||
if (err) {
|
||||
res.status(500).send({
|
||||
message: `Could not download the file: ${err}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses a file and returns the result objects
|
||||
* @param file
|
||||
* @param _req
|
||||
* @param _res
|
||||
* @param options
|
||||
*/
|
||||
async function parseFile(file, _req, _res, options) {
|
||||
if (!fs.existsSync(file)) {
|
||||
throw new Error('Upload failed');
|
||||
}
|
||||
const result = await fileHandler(file, options);
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* parse an uploaded file and apply its parsed objects
|
||||
* @param file
|
||||
* @param req
|
||||
* @param res
|
||||
* @param [options]
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const parseAndApply = async (file, _req, res, options) => {
|
||||
const result = await parseFile(file, _req, res, options);
|
||||
|
||||
PlaybackService.stop();
|
||||
|
||||
const newRundown = result.rundown || [];
|
||||
if (options?.onlyRundown === 'true') {
|
||||
await DataProvider.setRundown(newRundown);
|
||||
} else {
|
||||
await DataProvider.mergeIntoData(result);
|
||||
}
|
||||
notifyChanges({ timer: true, external: true, reset: true });
|
||||
};
|
||||
|
||||
/**
|
||||
* @description Gets information on IPV4 non-internal interfaces
|
||||
* @returns {array} - Array of objects {name: ip}
|
||||
*/
|
||||
const getNetworkInterfaces = () => {
|
||||
const nets = networkInterfaces();
|
||||
const results = [];
|
||||
|
||||
for (const name of Object.keys(nets)) {
|
||||
for (const net of nets[name]) {
|
||||
// Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
|
||||
if (net.family === 'IPv4' && !net.internal) {
|
||||
results.push({
|
||||
name: name,
|
||||
address: net.address,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
};
|
||||
|
||||
// Create controller for GET request to '/ontime/info'
|
||||
// Returns -
|
||||
export const getInfo = async (req: Request, res: Response<GetInfo>) => {
|
||||
const { version, serverPort } = DataProvider.getSettings();
|
||||
const osc = DataProvider.getOsc();
|
||||
|
||||
// get nif and inject localhost
|
||||
const ni = getNetworkInterfaces();
|
||||
ni.unshift({ name: 'localhost', address: '127.0.0.1' });
|
||||
const cssOverride = resolveStylesPath;
|
||||
|
||||
// send object with network information
|
||||
res.status(200).send({
|
||||
networkInterfaces: ni,
|
||||
version,
|
||||
serverPort,
|
||||
osc,
|
||||
cssOverride,
|
||||
});
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/ontime/aliases'
|
||||
// Returns -
|
||||
export const getAliases = async (req, res) => {
|
||||
const aliases = DataProvider.getAliases();
|
||||
res.status(200).send(aliases);
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/ontime/aliases'
|
||||
// Returns ACK message
|
||||
export const postAliases = async (req, res) => {
|
||||
if (failIsNotArray(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const newAliases: Alias[] = [];
|
||||
req.body.forEach((a) => {
|
||||
newAliases.push({
|
||||
enabled: a.enabled,
|
||||
alias: a.alias,
|
||||
pathAndParams: a.pathAndParams,
|
||||
});
|
||||
});
|
||||
await DataProvider.setAliases(newAliases);
|
||||
res.status(200).send(newAliases);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
// Create controller for GET request to '/ontime/userfields'
|
||||
// Returns -
|
||||
export const getUserFields = async (req, res) => {
|
||||
const userFields = DataProvider.getUserFields();
|
||||
res.status(200).send(userFields);
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/ontime/userfields'
|
||||
// Returns ACK message
|
||||
export const postUserFields = async (req, res) => {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const persistedData = DataProvider.getUserFields();
|
||||
const newData = deepmerge(persistedData, req.body);
|
||||
await DataProvider.setUserFields(newData);
|
||||
res.status(200).send(newData);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/ontime/settings'
|
||||
// Returns -
|
||||
export const getSettings = async (req, res) => {
|
||||
const settings = DataProvider.getSettings();
|
||||
res.status(200).send(settings);
|
||||
};
|
||||
|
||||
function extractPin(value: string | undefined | null, fallback: string | null): string | null {
|
||||
if (value === null) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'undefined') {
|
||||
return fallback;
|
||||
}
|
||||
if (value.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// Create controller for POST request to '/ontime/settings'
|
||||
// Returns ACK message
|
||||
export const postSettings = async (req, res) => {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const settings = DataProvider.getSettings();
|
||||
const editorKey = extractPin(req.body?.editorKey, settings.editorKey);
|
||||
const operatorKey = extractPin(req.body?.operatorKey, settings.operatorKey);
|
||||
const serverPort = Number(req.body?.serverPort);
|
||||
if (isNaN(serverPort)) {
|
||||
return res.status(400).send(`Invalid value found for server port: ${req.body?.serverPort}`);
|
||||
}
|
||||
|
||||
const hasChangedPort = settings.serverPort !== serverPort;
|
||||
|
||||
if (isDocker && hasChangedPort) {
|
||||
return res.status(403).json({ message: 'Can`t change port when running inside docker' });
|
||||
}
|
||||
|
||||
let timeFormat = settings.timeFormat;
|
||||
if (req.body?.timeFormat === '12' || req.body?.timeFormat === '24') {
|
||||
timeFormat = req.body.timeFormat;
|
||||
}
|
||||
|
||||
const language = req.body?.language || 'en';
|
||||
|
||||
const newData = {
|
||||
...settings,
|
||||
editorKey,
|
||||
operatorKey,
|
||||
timeFormat,
|
||||
language,
|
||||
serverPort,
|
||||
};
|
||||
await DataProvider.setSettings(newData);
|
||||
res.status(200).send(newData);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @description Get view Settings
|
||||
* @method GET
|
||||
*/
|
||||
export const getViewSettings = async (req, res) => {
|
||||
const views = DataProvider.getViewSettings();
|
||||
res.status(200).send(views);
|
||||
};
|
||||
|
||||
/**
|
||||
* @description Change view Settings
|
||||
* @method POST
|
||||
*/
|
||||
export const postViewSettings = async (req, res) => {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const newData = {
|
||||
overrideStyles: req.body.overrideStyles,
|
||||
endMessage: req.body?.endMessage || '',
|
||||
normalColor: req.body.normalColor,
|
||||
warningColor: req.body.warningColor,
|
||||
warningThreshold: req.body.warningThreshold,
|
||||
dangerColor: req.body.dangerColor,
|
||||
dangerThreshold: req.body.dangerThreshold,
|
||||
};
|
||||
await DataProvider.setViewSettings(newData);
|
||||
res.status(200).send(newData);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
// Create controller for GET request to '/ontime/osc'
|
||||
// Returns -
|
||||
export const getOSC = async (req, res) => {
|
||||
const osc = DataProvider.getOsc();
|
||||
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 subscriptions = req.body;
|
||||
const oscSettings = DataProvider.getOsc();
|
||||
oscSettings.subscriptions = subscriptions;
|
||||
await DataProvider.setOsc(oscSettings);
|
||||
|
||||
// TODO: this update could be more granular, checking that relevant data was changed
|
||||
const { message } = oscIntegration.init(oscSettings);
|
||||
logger.info(LogOrigin.Tx, message);
|
||||
|
||||
res.send(oscSettings).status(200);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
// 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 httpSettings = req.body;
|
||||
await DataProvider.setHttp(httpSettings);
|
||||
|
||||
integrationService.unregister(httpIntegration);
|
||||
|
||||
// TODO: this update could be more granular, checking that relevant data was changed
|
||||
const { success, message } = httpIntegration.init(httpSettings);
|
||||
logger.info(LogOrigin.Tx, message);
|
||||
|
||||
if (success) {
|
||||
integrationService.register(httpIntegration);
|
||||
}
|
||||
|
||||
res.send(httpSettings).status(200);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
export async function patchPartialProjectFile(req, res) {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const patchDb: Partial<DatabaseModel> = {
|
||||
project: req.body?.project,
|
||||
settings: req.body?.settings,
|
||||
viewSettings: req.body?.viewSettings,
|
||||
osc: req.body?.osc,
|
||||
aliases: req.body?.aliases,
|
||||
userFields: req.body?.userFields,
|
||||
rundown: req.body?.rundown,
|
||||
};
|
||||
|
||||
await DataProvider.mergeIntoData(patchDb);
|
||||
if (patchDb.rundown !== undefined) {
|
||||
// it is likely cheaper to invalidate cache than to calculate diff
|
||||
PlaybackService.stop();
|
||||
runtimeCacheStore.invalidate(delayedRundownCacheKey);
|
||||
notifyChanges({ external: true, reset: true });
|
||||
}
|
||||
res.status(200).send();
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* uploads, parses and applies the data from a given file
|
||||
*/
|
||||
export const dbUpload = async (req, res) => {
|
||||
if (!req.file) {
|
||||
res.status(400).send({ message: 'File not found' });
|
||||
return;
|
||||
}
|
||||
const options = req.query;
|
||||
const file = req.file.path;
|
||||
try {
|
||||
await parseAndApply(file, req, res, options);
|
||||
res.status(200).send();
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: `Failed parsing ${error}` });
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* uploads and parses an excel file
|
||||
* @returns parsed result
|
||||
*/
|
||||
export async function previewExcel(req, res) {
|
||||
if (!req.file) {
|
||||
res.status(400).send({ message: 'File not found' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const options = JSON.parse(req.body.options);
|
||||
const file = req.file.path;
|
||||
const data = await parseFile(file, req, res, options);
|
||||
res.status(200).send(data);
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: error.toString() });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Meant to create a new project file, it will clear only fields which are specific to a project
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const postNew: RequestHandler = async (req, res) => {
|
||||
try {
|
||||
const newProjectData: ProjectData = {
|
||||
title: req.body?.title ?? '',
|
||||
description: req.body?.description ?? '',
|
||||
publicUrl: req.body?.publicUrl ?? '',
|
||||
publicInfo: req.body?.publicInfo ?? '',
|
||||
backstageUrl: req.body?.backstageUrl ?? '',
|
||||
backstageInfo: req.body?.backstageInfo ?? '',
|
||||
};
|
||||
const newData = await DataProvider.setProjectData(newProjectData);
|
||||
await deleteAllEvents();
|
||||
res.status(201).send(newData);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
//SHEET Functions
|
||||
/**
|
||||
* @description SETP-1 POST Client Secrect
|
||||
* @returns parsed result
|
||||
*/
|
||||
export async function uploadSheetClientFile(req, res) {
|
||||
if (!req.file.path) {
|
||||
res.status(400).send({ message: 'File not found' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const client = JSON.parse(fs.readFileSync(req.file.path as string, 'utf-8'));
|
||||
await sheet.saveClientSecrets(client);
|
||||
res.status(200).send('OK');
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: error.toString() });
|
||||
}
|
||||
fs.unlink(req.file.path, (err) => {
|
||||
if (err) logger.error(LogOrigin.Server, err.message);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @description SETP-1 GET Client Secrect status
|
||||
*/
|
||||
export const getClientSecrect = async (req, res) => {
|
||||
try {
|
||||
const clientSecrectExists = await sheet.testClientSecret();
|
||||
if (clientSecrectExists) {
|
||||
res.status(200).send();
|
||||
} else {
|
||||
res.status(500).send({ message: 'The Client ID does not exist' });
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @description SETP-2 GET sheet authentication url
|
||||
*/
|
||||
export async function getAuthenticationUrl(req, res) {
|
||||
try {
|
||||
const authUrl = await sheet.openAuthServer();
|
||||
res.status(200).send(authUrl);
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: error.toString() });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description SETP-2 GET sheet authentication status
|
||||
*/
|
||||
export const getAuthentication = async (req, res) => {
|
||||
try {
|
||||
await sheet.testAuthentication();
|
||||
res.status(200).send();
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @description SETP-3 POST sheet id
|
||||
* @returns list of worksheets
|
||||
*/
|
||||
export const postId = async (req, res) => {
|
||||
try {
|
||||
const { id } = req.body;
|
||||
if (id.lenght < 40) {
|
||||
res.status(400).send({ message: 'ID is usualy 44 characters long' });
|
||||
}
|
||||
const state = await sheet.testSheetId(id);
|
||||
res.status(200).send(state);
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @description SETP-4 POST worksheet
|
||||
*/
|
||||
export const postWorksheet = async (req, res) => {
|
||||
try {
|
||||
const { worksheet, id } = req.body;
|
||||
const state = await sheet.testWorksheet(worksheet, id);
|
||||
res.status(200).send(state);
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @description STEP-5 POST download undown to sheet
|
||||
* @returns parsed result
|
||||
*/
|
||||
export async function pullSheet(req, res) {
|
||||
try {
|
||||
const { id, options } = req.body;
|
||||
const data = await sheet.pull(id, options);
|
||||
res.status(200).send(data);
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: error.toString() });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description STEP-5 POST upload rundown to sheet
|
||||
*/
|
||||
export async function pushSheet(req, res) {
|
||||
try {
|
||||
const { id, options } = req.body;
|
||||
await sheet.push(id, options);
|
||||
res.status(200).send();
|
||||
} catch (error) {
|
||||
res.status(500).send({ message: error.toString() });
|
||||
}
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
import { body, check, validationResult } from 'express-validator';
|
||||
import {
|
||||
validateHttpSubscriptionObject,
|
||||
validateOscSubscriptionObject,
|
||||
validateOscSubscriptionCycle,
|
||||
} from '../utils/parserFunctions.js';
|
||||
|
||||
/**
|
||||
* @description Validates object for POST /ontime/views
|
||||
*/
|
||||
export const viewValidator = [
|
||||
check('overrideStyles').isBoolean().withMessage('overrideStyles value must be boolean'),
|
||||
check('endMessage').isString().trim().withMessage('endMessage value must be string'),
|
||||
check('normalColor').isString().trim().withMessage('normalColor value must be string'),
|
||||
check('warningColor').isString().trim().withMessage('warningColor value must be string'),
|
||||
check('dangerColor').isString().trim().withMessage('dangerColor value must be string'),
|
||||
check('warningThreshold').isNumeric().withMessage('warningThreshold value must be a number'),
|
||||
check('dangerThreshold').isNumeric().withMessage('dangerThreshold value must a number'),
|
||||
(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/aliases
|
||||
*/
|
||||
export const validateAliases = [
|
||||
body().isArray(),
|
||||
body('*.enabled').isBoolean(),
|
||||
body('*.alias').isString().trim(),
|
||||
body('*.pathAndParams').isString().trim(),
|
||||
(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/userfields
|
||||
*/
|
||||
export const validateUserFields = [
|
||||
body('user0').exists().isString().trim(),
|
||||
body('user1').exists().isString().trim(),
|
||||
body('user2').exists().isString().trim(),
|
||||
body('user3').exists().isString().trim(),
|
||||
body('user4').exists().isString().trim(),
|
||||
body('user5').exists().isString().trim(),
|
||||
body('user6').exists().isString().trim(),
|
||||
body('user7').exists().isString().trim(),
|
||||
body('user8').exists().isString().trim(),
|
||||
body('user9').exists().isString().trim(),
|
||||
(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/settings
|
||||
*/
|
||||
export const validateSettings = [
|
||||
body('editorKey').isString().isLength({ min: 0, max: 4 }).optional({ nullable: true }),
|
||||
body('operatorKey').isString().isLength({ min: 0, max: 4 }).optional({ nullable: true }),
|
||||
body('timeFormat').isString().isIn(['12', '24']),
|
||||
body('language').isString(),
|
||||
body('serverPort').isPort().optional(),
|
||||
(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/osc
|
||||
*/
|
||||
export const validateOSC = [
|
||||
body('portIn').exists().isInt({ min: 1024, max: 65535 }),
|
||||
body('portOut').exists().isInt({ min: 1024, max: 65535 }),
|
||||
body('targetIP').exists().isIP(),
|
||||
body('enabledIn').exists().isBoolean(),
|
||||
body('enabledOut').exists().isBoolean(),
|
||||
body('subscriptions')
|
||||
.isObject()
|
||||
.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() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* @description Validates object for POST /ontime/osc-subscriptions
|
||||
*/
|
||||
export const validateOscSubscription = [
|
||||
body('onLoad')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
body('onStart')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
body('onPause')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
body('onStop')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
body('onUpdate')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
body('onFinish')
|
||||
.isArray()
|
||||
.custom((value) => validateOscSubscriptionCycle(value)),
|
||||
(req, res, next) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
export const validatePatchProjectFile = [
|
||||
body('rundown').isArray().optional({ nullable: false }),
|
||||
body('project').isObject().optional({ nullable: false }),
|
||||
body('settings').isObject().optional({ nullable: false }),
|
||||
body('viewSettings').isObject().optional({ nullable: false }),
|
||||
body('aliases').isArray().optional({ nullable: false }),
|
||||
body('userFields').isObject().optional({ nullable: false }),
|
||||
body('osc').isObject().optional({ nullable: false }),
|
||||
(req, res, next) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
export const validateSheetid = [
|
||||
body('id').exists().isString(),
|
||||
(req, res, next) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
export const validateWorksheet = [
|
||||
body('id').exists().isString(),
|
||||
body('worksheet').exists().isString(),
|
||||
(req, res, next) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
|
||||
export const validateSheetOptions = [
|
||||
body('id').exists().isString(),
|
||||
// body('options').exists().isObject(), TODO:
|
||||
(req, res, next) => {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
|
||||
next();
|
||||
},
|
||||
];
|
||||
@@ -1,98 +0,0 @@
|
||||
import { PlaybackService } from '../services/PlaybackService.js';
|
||||
import { eventStore } from '../stores/EventStore.js';
|
||||
|
||||
// Create controller for POST request to '/playback'
|
||||
// Returns playback state
|
||||
export const pbGet = async (req, res) => {
|
||||
res.send({ playback: eventStore.get('playback') });
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/playback/start'
|
||||
// Starts timer object
|
||||
export const pbStart = async (req, res) => {
|
||||
const { eventId, eventIndex } = req.query;
|
||||
if (eventId) {
|
||||
const success = PlaybackService.startById(eventId);
|
||||
success ? res.sendStatus(202) : res.status(400).send({ message: 'Invalid event ID' });
|
||||
} else if (eventIndex) {
|
||||
const index = Number(eventIndex);
|
||||
if (!isNaN(index)) {
|
||||
const success = PlaybackService.startByIndex(eventIndex - 1);
|
||||
success ? res.sendStatus(202) : res.status(400).send({ message: 'Invalid event index' });
|
||||
} else {
|
||||
res.status(400).send({ message: 'Invalid event index' });
|
||||
}
|
||||
} else {
|
||||
PlaybackService.start();
|
||||
res.sendStatus(202);
|
||||
}
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/playback/pause'
|
||||
// Pauses timer object
|
||||
export const pbPause = async (req, res) => {
|
||||
PlaybackService.pause();
|
||||
res.sendStatus(202);
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/playback/stop'
|
||||
// Stops timer object
|
||||
export const pbStop = async (req, res) => {
|
||||
PlaybackService.stop();
|
||||
res.sendStatus(202);
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/playback/roll'
|
||||
// Sets timer object to roll mode
|
||||
export const pbRoll = async (req, res) => {
|
||||
PlaybackService.roll();
|
||||
res.sendStatus(202);
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/playback/previous'
|
||||
// Loads previous event
|
||||
export const pbPrevious = async (req, res) => {
|
||||
PlaybackService.loadPrevious();
|
||||
res.sendStatus(202);
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/playback/next'
|
||||
// Loads Next event
|
||||
export const pbNext = async (req, res) => {
|
||||
PlaybackService.loadNext();
|
||||
res.sendStatus(202);
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/playback/load'
|
||||
// Load requested event
|
||||
export const pbLoad = async (req, res) => {
|
||||
const { eventId, eventIndex } = req.query;
|
||||
if (eventId) {
|
||||
const success = PlaybackService.loadById(eventId);
|
||||
success ? res.sendStatus(202) : res.status(400).send({ message: 'Invalid event ID' });
|
||||
} else if (eventIndex) {
|
||||
const index = Number(eventIndex);
|
||||
if (!isNaN(index)) {
|
||||
const success = PlaybackService.loadByIndex(eventIndex - 1);
|
||||
success ? res.sendStatus(202) : res.status(400).send({ message: 'Invalid event index' });
|
||||
} else {
|
||||
res.status(400).send({ message: 'Invalid event index' });
|
||||
}
|
||||
} else {
|
||||
res.status(400).send({ message: 'No event given' });
|
||||
}
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/playback/unload'
|
||||
// Unloads any events
|
||||
export const pbUnload = async (req, res) => {
|
||||
PlaybackService.stop();
|
||||
res.sendStatus(202);
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/playback/reload'
|
||||
// Reloads current event
|
||||
export const pbReload = async (req, res) => {
|
||||
PlaybackService.reload();
|
||||
res.sendStatus(202);
|
||||
};
|
||||
@@ -1,35 +0,0 @@
|
||||
import { RequestHandler } from 'express';
|
||||
|
||||
import { ProjectData } from 'ontime-types';
|
||||
|
||||
import { removeUndefined } from '../utils/parserUtils.js';
|
||||
import { failEmptyObjects } from '../utils/routerUtils.js';
|
||||
import { DataProvider } from '../classes/data-provider/DataProvider.js';
|
||||
|
||||
// Create controller for GET request to 'project'
|
||||
export const getProject: RequestHandler = async (req, res) => {
|
||||
res.json(DataProvider.getProjectData());
|
||||
};
|
||||
|
||||
// Create controller for POST request to 'project'
|
||||
export const postProject: RequestHandler = async (req, res) => {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const newEvent: Partial<ProjectData> = removeUndefined({
|
||||
title: req.body?.title,
|
||||
description: req.body?.description,
|
||||
publicUrl: req.body?.publicUrl,
|
||||
publicInfo: req.body?.publicInfo,
|
||||
backstageUrl: req.body?.backstageUrl,
|
||||
backstageInfo: req.body?.backstageInfo,
|
||||
endMessage: req.body?.endMessage,
|
||||
});
|
||||
const newData = await DataProvider.setProjectData(newEvent);
|
||||
res.status(200).send(newData);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
@@ -1,120 +0,0 @@
|
||||
import { GetRundownCached } from 'ontime-types';
|
||||
|
||||
import { Request, Response, RequestHandler } from 'express';
|
||||
|
||||
import { failEmptyObjects } from '../utils/routerUtils.js';
|
||||
import {
|
||||
addEvent,
|
||||
applyDelay,
|
||||
deleteAllEvents,
|
||||
deleteEvent,
|
||||
editEvent,
|
||||
reorderEvent,
|
||||
swapEvents,
|
||||
} from '../services/rundown-service/RundownService.js';
|
||||
import { getDelayedRundown, getRundownCache } from '../services/rundown-service/delayedRundown.utils.js';
|
||||
|
||||
// Create controller for GET request to '/events'
|
||||
// Returns -
|
||||
export const rundownGetAll: RequestHandler = async (_req, res) => {
|
||||
const delayedRundown = getDelayedRundown();
|
||||
res.json(delayedRundown);
|
||||
};
|
||||
|
||||
// Create controller for GET request to '/events/cached'
|
||||
// Returns -
|
||||
export const rundownGetCached: RequestHandler = async (_req: Request, res: Response<GetRundownCached>) => {
|
||||
const cachedRundown = getRundownCache();
|
||||
res.json(cachedRundown);
|
||||
};
|
||||
|
||||
// Create controller for POST request to '/events/'
|
||||
// Returns -
|
||||
export const rundownPost: RequestHandler = async (req, res) => {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const newEvent = await addEvent(req.body);
|
||||
res.status(201).send(newEvent);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
// Create controller for PUT request to '/events/'
|
||||
// Returns -
|
||||
export const rundownPut: RequestHandler = async (req, res) => {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const event = await editEvent(req.body);
|
||||
res.status(200).send(event);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
export const rundownReorder: RequestHandler = async (req, res) => {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { eventId, from, to } = req.body;
|
||||
const event = await reorderEvent(eventId, from, to);
|
||||
res.status(200).send(event);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
export const rundownSwap: RequestHandler = async (req, res) => {
|
||||
if (failEmptyObjects(req.body, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { from, to } = req.body;
|
||||
await swapEvents(from, to);
|
||||
res.sendStatus(200);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
// Create controller for PATCH request to '/events/applydelay/:eventId'
|
||||
// Returns -
|
||||
export const rundownApplyDelay: RequestHandler = async (req, res) => {
|
||||
try {
|
||||
await applyDelay(req.params.eventId);
|
||||
res.sendStatus(200);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
// Create controller for DELETE request to '/events/:eventId'
|
||||
// Returns -
|
||||
export const deleteEventById: RequestHandler = async (req, res) => {
|
||||
try {
|
||||
await deleteEvent(req.params.eventId);
|
||||
res.sendStatus(204);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
// Create controller for DELETE request to '/events/'
|
||||
// Returns -
|
||||
export const rundownDelete: RequestHandler = async (req, res) => {
|
||||
try {
|
||||
await deleteAllEvents();
|
||||
res.sendStatus(204);
|
||||
} catch (error) {
|
||||
res.status(400).send({ message: error.toString() });
|
||||
}
|
||||
};
|
||||
Vendored
+30
-14
@@ -12,6 +12,23 @@ const leftPad = (number) => {
|
||||
return Math.floor(number).toString().padStart(2, '0');
|
||||
};
|
||||
|
||||
const formatTimer = (number) => {
|
||||
const millis = Math.abs(number);
|
||||
const isNegative = number < 0;
|
||||
return `${isNegative ? '-' : ''}${leftPad(millis / mth)}:${leftPad((millis % mth) / mtm)}:${leftPad(
|
||||
(millis % mtm) / mts,
|
||||
)}`;
|
||||
};
|
||||
|
||||
function updateTimerElement(playback, timerValue) {
|
||||
const timerElement = document.getElementById('timer');
|
||||
if (playback === 'stop') {
|
||||
timerElement.innerText = '--:--:--';
|
||||
} else {
|
||||
timerElement.innerText = formatTimer(timerValue);
|
||||
}
|
||||
}
|
||||
|
||||
let reconnectTimeout;
|
||||
const reconnectInterval = 1000;
|
||||
let reconnectAttempts = 0;
|
||||
@@ -22,7 +39,7 @@ const connectSocket = () => {
|
||||
websocket.onopen = () => {
|
||||
clearTimeout(reconnectTimeout);
|
||||
reconnectAttempts = 0;
|
||||
console.info('WebSocket connected');
|
||||
console.warn('WebSocket connected');
|
||||
};
|
||||
|
||||
websocket.onclose = () => {
|
||||
@@ -46,19 +63,18 @@ const connectSocket = () => {
|
||||
const { type, payload } = data;
|
||||
|
||||
// we only need to read message type of ontime
|
||||
if (type === 'ontime') {
|
||||
// destructure known data from ontime
|
||||
// see https://cpvalente.gitbook.io/ontime/control-and-feedback/websocket-api
|
||||
const { timer, playback } = payload;
|
||||
const timerElement = document.getElementById('timer');
|
||||
if (playback == 'stop') {
|
||||
timerElement.innerText = '--:--:--';
|
||||
} else {
|
||||
const millis = Math.abs(timer.current);
|
||||
const isNegative = timer.current < 0;
|
||||
timerElement.innerText = `${isNegative ? '-' : ''}${leftPad(millis / mth)}:${leftPad(
|
||||
(millis % mth) / mtm,
|
||||
)}:${leftPad((millis % mtm) / mts)}`;
|
||||
switch (type) {
|
||||
case 'ontime': {
|
||||
// destructure known data from ontime
|
||||
// see https://docs.getontime.no/api/osc-and-ws/
|
||||
const { timer, playback } = payload;
|
||||
updateTimerElement(playback, timer);
|
||||
break;
|
||||
}
|
||||
case 'ontime-timer': {
|
||||
const { current, playback } = payload;
|
||||
updateTimerElement(playback, current);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+2
-2
@@ -10,5 +10,5 @@
|
||||
|
||||
<body>
|
||||
<div id="timer"></div>
|
||||
<script src="./app.js" type="module"></script>
|
||||
</html>
|
||||
<script src="./app.js" type="text/javascript"></script>
|
||||
</html>
|
||||
|
||||
@@ -23,6 +23,15 @@
|
||||
--studio-idle: #cfcfcf;
|
||||
--studio-active-label: #101010;
|
||||
--studio-idle-label: #595959;
|
||||
--studio-overtime: #101010;
|
||||
|
||||
--lowerThird-font-family-override: 'Times New Roman';
|
||||
--lowerThird-top-font-weight-override: bold;
|
||||
--lowerThird-bottom-font-weight-override: bold;
|
||||
--lowerThird-top-font-style-override: normal;
|
||||
--lowerThird-bottom-font-style-override: italic;
|
||||
--lowerThird-line-height-override: 1vh;
|
||||
--lowerThird-text-align-override: center;
|
||||
}
|
||||
|
||||
.timer {
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
import { initAssets, startIntegrations, startOSCServer, startServer } from './app.js';
|
||||
/* eslint-disable no-console */
|
||||
import { initAssets, startIntegrations, startServer } from './app.js';
|
||||
|
||||
async function startOntime() {
|
||||
try {
|
||||
console.log('Starting Ontime');
|
||||
console.log('Loading Assets');
|
||||
console.log('Request: Initialise assets...');
|
||||
await initAssets();
|
||||
console.log('Starting Server');
|
||||
console.log('Request: Start server...');
|
||||
await startServer();
|
||||
console.log('Starting OSC Server');
|
||||
await startOSCServer();
|
||||
console.log('Starting Integrations');
|
||||
console.log('Request: Start integrations...');
|
||||
await startIntegrations();
|
||||
} catch (error) {
|
||||
console.log('Error starting Ontime');
|
||||
console.log(error);
|
||||
console.log(`Request failed: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
export const alias = {
|
||||
enabled: false,
|
||||
alias: '',
|
||||
pathAndParams: '',
|
||||
};
|
||||
@@ -24,48 +24,22 @@ export const dbModel: DatabaseModel = {
|
||||
overrideStyles: false,
|
||||
normalColor: '#ffffffcc',
|
||||
warningColor: '#FFAB33',
|
||||
warningThreshold: 120000,
|
||||
dangerColor: '#ED3333',
|
||||
dangerThreshold: 60000,
|
||||
freezeEnd: false,
|
||||
endMessage: '',
|
||||
},
|
||||
aliases: [],
|
||||
userFields: {
|
||||
user0: 'user0',
|
||||
user1: 'user1',
|
||||
user2: 'user2',
|
||||
user3: 'user3',
|
||||
user4: 'user4',
|
||||
user5: 'user5',
|
||||
user6: 'user6',
|
||||
user7: 'user7',
|
||||
user8: 'user8',
|
||||
user9: 'user9',
|
||||
},
|
||||
urlPresets: [],
|
||||
customFields: {},
|
||||
osc: {
|
||||
portIn: 8888,
|
||||
portOut: 9999,
|
||||
targetIP: '127.0.0.1',
|
||||
enabledIn: false,
|
||||
enabledOut: false,
|
||||
subscriptions: {
|
||||
onLoad: [],
|
||||
onStart: [],
|
||||
onPause: [],
|
||||
onStop: [],
|
||||
onUpdate: [],
|
||||
onFinish: [],
|
||||
},
|
||||
subscriptions: [],
|
||||
},
|
||||
http: {
|
||||
enabledOut: false,
|
||||
subscriptions: {
|
||||
onLoad: [],
|
||||
onStart: [],
|
||||
onPause: [],
|
||||
onStop: [],
|
||||
onUpdate: [],
|
||||
onFinish: [],
|
||||
},
|
||||
subscriptions: [],
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
import { EndAction, OntimeBlock, OntimeDelay, OntimeEvent, SupportedEvent, TimerType } from 'ontime-types';
|
||||
import {
|
||||
EndAction,
|
||||
OntimeBlock,
|
||||
OntimeDelay,
|
||||
OntimeEvent,
|
||||
SupportedEvent,
|
||||
TimeStrategy,
|
||||
TimerType,
|
||||
} from 'ontime-types';
|
||||
|
||||
export const event: Omit<OntimeEvent, 'id' | 'delay' | 'cue'> = {
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockDuration,
|
||||
linkStart: null,
|
||||
timeStart: 0,
|
||||
timeEnd: 0,
|
||||
duration: 0,
|
||||
isPublic: false,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
custom: {},
|
||||
};
|
||||
|
||||
export const delay: Omit<OntimeDelay, 'id'> = {
|
||||
duration: 0,
|
||||
type: SupportedEvent.Delay,
|
||||
revision: 0,
|
||||
};
|
||||
|
||||
export const block: Omit<OntimeBlock, 'id'> = {
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
import { Low } from 'lowdb';
|
||||
import { JSONFile } from 'lowdb/node';
|
||||
import { copyFileSync, existsSync } from 'fs';
|
||||
import { DatabaseModel } from 'ontime-types';
|
||||
|
||||
import { ensureDirectory } from '../utils/fileManagement.js';
|
||||
import { validateFile } from '../utils/parserUtils.js';
|
||||
import { dbModel } from '../models/dataModel.js';
|
||||
import { parseJson } from '../utils/parser.js';
|
||||
import { pathToStartDb, resolveDbDirectory, resolveDbPath } from '../setup.js';
|
||||
|
||||
/**
|
||||
* @description ensures directories exist and populates database
|
||||
* @return {string} - path to db file
|
||||
*/
|
||||
const populateDb = () => {
|
||||
const dbInDisk = resolveDbPath;
|
||||
ensureDirectory(resolveDbDirectory);
|
||||
|
||||
// if dbInDisk doesn't exist we want to use startup db
|
||||
if (!existsSync(dbInDisk)) {
|
||||
try {
|
||||
copyFileSync(pathToStartDb, dbInDisk);
|
||||
} catch (_) {
|
||||
/* we do not handle this */
|
||||
}
|
||||
}
|
||||
|
||||
return dbInDisk;
|
||||
};
|
||||
|
||||
/**
|
||||
* @description parses a json file to the adapter
|
||||
* @param fileToRead
|
||||
* @param adapterToUse
|
||||
* @return {Promise<number|*>}
|
||||
*/
|
||||
const parseDb = async (fileToRead, adapterToUse) => {
|
||||
if (validateFile(fileToRead)) {
|
||||
await adapterToUse.read();
|
||||
} else {
|
||||
adapterToUse.data = dbModel;
|
||||
}
|
||||
|
||||
return parseJson(adapterToUse.data);
|
||||
};
|
||||
|
||||
/**
|
||||
* @description loads ontime db
|
||||
* @return {Promise<{data: (*), db: Low<unknown>}>}
|
||||
*/
|
||||
async function loadDb() {
|
||||
const dbInDisk = populateDb();
|
||||
|
||||
const adapter = new JSONFile<DatabaseModel>(dbInDisk);
|
||||
const db = new Low(adapter);
|
||||
|
||||
const data = await parseDb(dbInDisk, db);
|
||||
if (data === null) {
|
||||
console.log('ERROR: Invalid JSON format');
|
||||
return;
|
||||
}
|
||||
|
||||
db.data = data;
|
||||
await db.write();
|
||||
|
||||
return { db, data };
|
||||
}
|
||||
|
||||
export let db = {} as Low<DatabaseModel>;
|
||||
export let data = {} as DatabaseModel;
|
||||
export const dbLoadingProcess = loadDb();
|
||||
|
||||
const init = async () => {
|
||||
const dbProvider = await dbLoadingProcess;
|
||||
db = dbProvider.db;
|
||||
data = dbProvider.data;
|
||||
};
|
||||
|
||||
init();
|
||||
@@ -0,0 +1 @@
|
||||
This directory holds the demo file shipped with Ontime
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
import express from 'express';
|
||||
import { uploadFile } from '../utils/upload.js';
|
||||
import {
|
||||
dbDownload,
|
||||
dbUpload,
|
||||
getAliases,
|
||||
getInfo,
|
||||
getOSC,
|
||||
getHTTP,
|
||||
getSettings,
|
||||
getUserFields,
|
||||
getViewSettings,
|
||||
patchPartialProjectFile,
|
||||
poll,
|
||||
postAliases,
|
||||
postNew,
|
||||
postOSC,
|
||||
postOscSubscriptions,
|
||||
postSettings,
|
||||
postUserFields,
|
||||
postViewSettings,
|
||||
previewExcel,
|
||||
postHTTP,
|
||||
getAuthenticationUrl,
|
||||
uploadSheetClientFile as uploadClientSecret,
|
||||
pullSheet,
|
||||
pushSheet,
|
||||
postId,
|
||||
getAuthentication,
|
||||
getClientSecrect as getClientSecret,
|
||||
} from '../controllers/ontimeController.js';
|
||||
|
||||
import {
|
||||
validateAliases,
|
||||
validateOSC,
|
||||
validatePatchProjectFile,
|
||||
validateSettings,
|
||||
validateUserFields,
|
||||
viewValidator,
|
||||
validateHTTP,
|
||||
validateOscSubscription,
|
||||
validateSheetid,
|
||||
validateWorksheet,
|
||||
validateSheetOptions,
|
||||
} from '../controllers/ontimeController.validate.js';
|
||||
import { projectSanitiser } from '../controllers/projectController.validate.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
// create route between controller and '/ontime/sync' endpoint
|
||||
router.get('/poll', poll);
|
||||
|
||||
// create route between controller and '/ontime/db' endpoint
|
||||
router.get('/db', dbDownload);
|
||||
|
||||
// create route between controller and '/ontime/db' endpoint
|
||||
router.post('/db', uploadFile, dbUpload);
|
||||
|
||||
// create route between controller and '/ontime/excel' endpoint
|
||||
router.patch('/db', validatePatchProjectFile, patchPartialProjectFile);
|
||||
|
||||
// create route between controller and '/ontime/preview-spreadsheet' endpoint
|
||||
router.post('/preview-spreadsheet', uploadFile, previewExcel);
|
||||
|
||||
// create route between controller and '/ontime/settings' endpoint
|
||||
router.get('/settings', getSettings);
|
||||
|
||||
// create route between controller and '/ontime/settings' endpoint
|
||||
router.post('/settings', validateSettings, postSettings);
|
||||
|
||||
// create route between controller and '/ontime/views' endpoint
|
||||
router.get('/views', getViewSettings);
|
||||
|
||||
// create route between controller and '/ontime/views' endpoint
|
||||
router.post('/views', viewValidator, postViewSettings);
|
||||
|
||||
// create route between controller and '/ontime/aliases' endpoint
|
||||
router.get('/aliases', getAliases);
|
||||
|
||||
// create route between controller and '/ontime/aliases' endpoint
|
||||
router.post('/aliases', validateAliases, postAliases);
|
||||
|
||||
// create route between controller and '/ontime/aliases' endpoint
|
||||
router.get('/userfields', getUserFields);
|
||||
|
||||
// create route between controller and '/ontime/aliases' endpoint
|
||||
router.post('/userfields', validateUserFields, postUserFields);
|
||||
|
||||
// create route between controller and '/ontime/info' endpoint
|
||||
router.get('/info', getInfo);
|
||||
|
||||
// create route between controller and '/ontime/osc' endpoint
|
||||
router.get('/osc', getOSC);
|
||||
|
||||
// create route between controller and '/ontime/osc' endpoint
|
||||
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);
|
||||
|
||||
//SETP-1
|
||||
router.post('/sheet/clientsecret', uploadFile, uploadClientSecret);
|
||||
router.get('/sheet/clientsecret', uploadFile, getClientSecret);
|
||||
|
||||
//SETP-2
|
||||
router.get('/sheet/authentication/url', getAuthenticationUrl);
|
||||
router.get('/sheet/authentication', getAuthentication);
|
||||
|
||||
//STEP-3
|
||||
router.post('/sheet/id', validateSheetid, postId);
|
||||
|
||||
//STEP-4
|
||||
router.post('/sheet/worksheet', validateWorksheet, postId);
|
||||
|
||||
//STEP-5 download and generate preview
|
||||
router.post('/sheet/pull', validateSheetOptions, pullSheet);
|
||||
|
||||
//STEP-5 upload
|
||||
router.post('/sheet-push', validateSheetOptions, pushSheet);
|
||||
@@ -1,47 +0,0 @@
|
||||
import express from 'express';
|
||||
import {
|
||||
pbGet,
|
||||
pbLoad,
|
||||
pbNext,
|
||||
pbPause,
|
||||
pbPrevious,
|
||||
pbReload,
|
||||
pbRoll,
|
||||
pbStart,
|
||||
pbStop,
|
||||
pbUnload,
|
||||
} from '../controllers/playbackController.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
// create route between controller and '/playback/' endpoint
|
||||
router.get('/', pbGet);
|
||||
|
||||
// create route between controller and '/playback/start' endpoint
|
||||
router.post('/start', pbStart);
|
||||
|
||||
// create route between controller and '/playback/pause' endpoint
|
||||
router.post('/pause', pbPause);
|
||||
|
||||
// create route between controller and '/playback/stop' endpoint
|
||||
router.post('/stop', pbStop);
|
||||
|
||||
// create route between controller and '/playback/roll' endpoint
|
||||
router.post('/roll', pbRoll);
|
||||
|
||||
// create route between controller and '/playback/previous' endpoint
|
||||
router.post('/previous', pbPrevious);
|
||||
|
||||
// create route between controller and '/playback/next' endpoint
|
||||
router.post('/next', pbNext);
|
||||
|
||||
// create route between controller and '/playback/load' endpoint
|
||||
router.post('/load', pbLoad);
|
||||
|
||||
// create route between controller and '/playback/unload' endpoint
|
||||
router.post('/unload', pbUnload);
|
||||
|
||||
// create route between controller and '/playback/reload' endpoint
|
||||
router.post('/reload', pbReload);
|
||||
|
||||
// router.post('*', (req, res) => res.return(404))
|
||||
@@ -1,11 +0,0 @@
|
||||
import express from 'express';
|
||||
import { getProject, postProject } from '../controllers/projectController.js';
|
||||
import { projectSanitiser } from '../controllers/projectController.validate.js';
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
// create route between controller and 'GET /project' endpoint
|
||||
router.get('/', getProject);
|
||||
|
||||
// create route between controller and 'POST /project' endpoint
|
||||
router.post('/', projectSanitiser, postProject);
|
||||
@@ -3,6 +3,9 @@ enum Source {
|
||||
MIDI = 'MIDI',
|
||||
}
|
||||
|
||||
/**
|
||||
* Service manages retrieving current time from a managed time source
|
||||
*/
|
||||
class Clock {
|
||||
private static instance: Clock;
|
||||
private readonly source: Source;
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
import { LogOrigin, OntimeEvent, Playback } from 'ontime-types';
|
||||
import { validatePlayback } from 'ontime-utils';
|
||||
|
||||
import { eventLoader, EventLoader } from '../classes/event-loader/EventLoader.js';
|
||||
import { eventStore } from '../stores/EventStore.js';
|
||||
import { eventTimer } from './TimerService.js';
|
||||
import { clock } from './Clock.js';
|
||||
import { logger } from '../classes/Logger.js';
|
||||
import { RestorePoint } from './RestoreService.js';
|
||||
|
||||
/**
|
||||
* Service manages playback status of app
|
||||
* Coordinating with necessary services
|
||||
*/
|
||||
export class PlaybackService {
|
||||
/**
|
||||
* makes calls for loading and starting given event
|
||||
* @param {OntimeEvent} event
|
||||
* @return {boolean} success
|
||||
*/
|
||||
static loadEvent(event: OntimeEvent): boolean {
|
||||
let success = false;
|
||||
if (!event) {
|
||||
logger.error(LogOrigin.Playback, 'No event found');
|
||||
} else if (event.skip) {
|
||||
logger.warning(LogOrigin.Playback, `Refused playback of skipped event ID ${event.id}`);
|
||||
} else {
|
||||
eventLoader.loadEvent(event);
|
||||
eventTimer.load(event);
|
||||
success = true;
|
||||
}
|
||||
eventStore.broadcast();
|
||||
return success;
|
||||
}
|
||||
|
||||
/**
|
||||
* starts event matching given ID
|
||||
* @param {string} eventId
|
||||
* @return {boolean} success
|
||||
*/
|
||||
static startById(eventId: string): boolean {
|
||||
const event = EventLoader.getEventWithId(eventId);
|
||||
const success = PlaybackService.loadEvent(event);
|
||||
if (success) {
|
||||
logger.info(LogOrigin.Playback, `Loaded event with ID ${event.id}`);
|
||||
PlaybackService.start();
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
/**
|
||||
* starts an event at index
|
||||
* @param {number} eventIndex
|
||||
* @return {boolean} success
|
||||
*/
|
||||
static startByIndex(eventIndex: number): boolean {
|
||||
const event = EventLoader.getEventAtIndex(eventIndex);
|
||||
const success = PlaybackService.loadEvent(event);
|
||||
if (success) {
|
||||
logger.info(LogOrigin.Playback, `Loaded event with ID ${event.id}`);
|
||||
PlaybackService.start();
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
/**
|
||||
* starts first event matching given cue
|
||||
* @param {string} cue
|
||||
* @return {boolean} success
|
||||
*/
|
||||
static startByCue(cue: string): boolean {
|
||||
const event = EventLoader.getEventWithCue(cue);
|
||||
const success = PlaybackService.loadEvent(event);
|
||||
if (success) {
|
||||
logger.info(LogOrigin.Playback, `Loaded event with ID ${event.id}`);
|
||||
PlaybackService.start();
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
/**
|
||||
* loads event matching given ID
|
||||
* @param {string} eventId
|
||||
* @return {boolean} success
|
||||
*/
|
||||
static loadById(eventId: string): boolean {
|
||||
const event = EventLoader.getEventWithId(eventId);
|
||||
const success = PlaybackService.loadEvent(event);
|
||||
if (success) {
|
||||
logger.info(LogOrigin.Playback, `Loaded event with ID ${event.id}`);
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
/**
|
||||
* loads event matching given ID
|
||||
* @param {number} eventIndex
|
||||
* @return {boolean} success
|
||||
*/
|
||||
static loadByIndex(eventIndex: number): boolean {
|
||||
const event = EventLoader.getEventAtIndex(eventIndex);
|
||||
const success = PlaybackService.loadEvent(event);
|
||||
if (success) {
|
||||
logger.info(LogOrigin.Playback, `Loaded event with ID ${event.id}`);
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
/**
|
||||
* loads first event matching given cue
|
||||
* @param {string} cue
|
||||
* @return {boolean} success
|
||||
*/
|
||||
static loadByCue(cue: string): boolean {
|
||||
const event = EventLoader.getEventWithCue(cue);
|
||||
const success = PlaybackService.loadEvent(event);
|
||||
if (success) {
|
||||
logger.info(LogOrigin.Playback, `Loaded event with ID ${event.id}`);
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads event before currently selected
|
||||
*/
|
||||
static loadPrevious() {
|
||||
const previousEvent = eventLoader.findPrevious();
|
||||
if (previousEvent) {
|
||||
const success = PlaybackService.loadEvent(previousEvent);
|
||||
if (success) {
|
||||
logger.info(LogOrigin.Playback, `Loaded event with ID ${previousEvent.id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads event after currently selected
|
||||
* @param {string} [fallbackAction] - 'stop', 'pause'
|
||||
* @return {boolean} success
|
||||
*/
|
||||
static loadNext(fallbackAction?: 'stop' | 'pause'): boolean {
|
||||
const nextEvent = eventLoader.findNext();
|
||||
if (nextEvent) {
|
||||
const success = PlaybackService.loadEvent(nextEvent);
|
||||
if (success) {
|
||||
logger.info(LogOrigin.Playback, `Loaded event with ID ${nextEvent.id}`);
|
||||
return true;
|
||||
}
|
||||
} else if (fallbackAction === 'stop') {
|
||||
logger.info(LogOrigin.Playback, 'No next event found! Stopping playback');
|
||||
PlaybackService.stop();
|
||||
return false;
|
||||
} else if (fallbackAction === 'pause') {
|
||||
logger.info(LogOrigin.Playback, 'No next event found! Pausing playback');
|
||||
PlaybackService.pause();
|
||||
return false;
|
||||
} else {
|
||||
logger.info(LogOrigin.Playback, 'No next event found! Continuing playback');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts playback on selected event
|
||||
*/
|
||||
static start() {
|
||||
if (validatePlayback(eventTimer.playback).start) {
|
||||
eventTimer.start();
|
||||
const newState = eventTimer.playback;
|
||||
logger.info(LogOrigin.Playback, `Play Mode ${newState.toUpperCase()}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts playback on next event
|
||||
* @param {string} [fallbackAction] - 'stop', 'pause'
|
||||
*/
|
||||
static startNext(fallbackAction?: 'stop' | 'pause') {
|
||||
const success = PlaybackService.loadNext(fallbackAction);
|
||||
if (success) {
|
||||
PlaybackService.start();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pauses playback on selected event
|
||||
*/
|
||||
static pause() {
|
||||
if (validatePlayback(eventTimer.playback).pause) {
|
||||
eventTimer.pause();
|
||||
const newState = eventTimer.playback;
|
||||
logger.info(LogOrigin.Playback, `Play Mode ${newState.toUpperCase()}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops timer and unloads any events
|
||||
*/
|
||||
static stop() {
|
||||
if (validatePlayback(eventTimer.playback).stop) {
|
||||
eventLoader.reset();
|
||||
eventTimer.stop();
|
||||
const newState = eventTimer.playback;
|
||||
logger.info(LogOrigin.Playback, `Play Mode ${newState.toUpperCase()}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads current event
|
||||
*/
|
||||
static reload() {
|
||||
if (eventTimer.loadedTimerId) {
|
||||
this.loadById(eventTimer.loadedTimerId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets playback to roll
|
||||
*/
|
||||
static roll() {
|
||||
if (EventLoader.getPlayableEvents()) {
|
||||
const rollTimers = eventLoader.findRoll(clock.timeNow());
|
||||
|
||||
// nothing to play
|
||||
if (rollTimers === null) {
|
||||
logger.warning(LogOrigin.Server, 'Roll: no events found');
|
||||
PlaybackService.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
const { currentEvent, nextEvent } = rollTimers;
|
||||
if (!currentEvent && !nextEvent) {
|
||||
logger.warning(LogOrigin.Server, 'Roll: no events found');
|
||||
PlaybackService.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
eventTimer.roll(currentEvent, nextEvent);
|
||||
|
||||
const newState = eventTimer.playback;
|
||||
logger.info(LogOrigin.Playback, `Play Mode ${newState.toUpperCase()}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description resume playback state given a restore point
|
||||
* @param restorePoint
|
||||
*/
|
||||
static resume(restorePoint: RestorePoint) {
|
||||
const willResume = () => logger.info(LogOrigin.Server, 'Resuming playback');
|
||||
|
||||
if (restorePoint.playback === Playback.Roll) {
|
||||
willResume();
|
||||
PlaybackService.roll();
|
||||
}
|
||||
|
||||
if (restorePoint.selectedEventId) {
|
||||
const event = EventLoader.getEventWithId(restorePoint.selectedEventId);
|
||||
// the db would have to change for the event not to exist
|
||||
// we do not kow the reason for the crash, so we check anyway
|
||||
if (!event) {
|
||||
return;
|
||||
}
|
||||
|
||||
eventLoader.loadEvent(event);
|
||||
eventTimer.resume(event, restorePoint);
|
||||
eventStore.broadcast();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds time to current event
|
||||
* @param {number} time - time to add in seconds
|
||||
*/
|
||||
static addTime(time: number) {
|
||||
if (eventTimer.loadedTimerId) {
|
||||
const timeInMs = time * 1000;
|
||||
eventTimer.addTime(timeInMs);
|
||||
timeInMs > 0
|
||||
? logger.info(LogOrigin.Playback, `Added ${time} sec`)
|
||||
: logger.info(LogOrigin.Playback, `Removed ${time} sec`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds delay to current event
|
||||
* @deprecated Use addTime
|
||||
* @param {number} delayTime time in minutes
|
||||
*/
|
||||
static setDelay(delayTime: number) {
|
||||
this.addTime(delayTime * 60);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
import { Playback } from 'ontime-types';
|
||||
import { MaybeNumber, MaybeString, Playback } from 'ontime-types';
|
||||
|
||||
import { readFileSync } from 'fs';
|
||||
import { Writer } from 'steno';
|
||||
|
||||
import { resolveRestoreFile } from '../setup.js';
|
||||
import { JSONFile } from 'lowdb/node';
|
||||
import { resolveRestoreFile } from '../setup/index.js';
|
||||
import { deepEqual } from 'fast-equals';
|
||||
|
||||
export type RestorePoint = {
|
||||
playback: Playback;
|
||||
selectedEventId: string | null;
|
||||
startedAt: number | null;
|
||||
addedTime: number | null;
|
||||
pausedAt: number | null;
|
||||
selectedEventId: MaybeString;
|
||||
startedAt: MaybeNumber;
|
||||
addedTime: number;
|
||||
pausedAt: MaybeNumber;
|
||||
firstStart: MaybeNumber;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -37,7 +37,7 @@ export function isRestorePoint(obj: unknown): obj is RestorePoint {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof restorePoint.addedTime !== 'number' && restorePoint.addedTime !== null) {
|
||||
if (typeof restorePoint.addedTime !== 'number') {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -45,6 +45,10 @@ export function isRestorePoint(obj: unknown): obj is RestorePoint {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof restorePoint.firstStart !== 'number' && restorePoint.pausedAt !== null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -57,33 +61,25 @@ export function isRestorePoint(obj: unknown): obj is RestorePoint {
|
||||
* that can then be restored when reopening
|
||||
*/
|
||||
export class RestoreService {
|
||||
private readonly filePath: string | null;
|
||||
|
||||
private lastStore: string | null;
|
||||
private file: Writer | null;
|
||||
private readonly filePath: MaybeString;
|
||||
private readonly file: JSONFile<RestorePoint | null>;
|
||||
private failedCreateAttempts: number;
|
||||
private savedState: RestorePoint | null;
|
||||
|
||||
constructor(filePath: string) {
|
||||
this.filePath = filePath;
|
||||
|
||||
this.lastStore = null;
|
||||
this.file = null;
|
||||
this.savedState = null;
|
||||
this.file = new JSONFile(this.filePath);
|
||||
this.failedCreateAttempts = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility, creates a restore file
|
||||
*/
|
||||
create() {
|
||||
this.file = new Writer(this.filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility, reads from file
|
||||
* @private
|
||||
*/
|
||||
private read() {
|
||||
return readFileSync(this.filePath, 'utf-8');
|
||||
private async read() {
|
||||
return this.file.read();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,13 +87,8 @@ export class RestoreService {
|
||||
* @throws
|
||||
* @param stringifiedState
|
||||
*/
|
||||
private async write(stringifiedState: string) {
|
||||
// Create a file if it doesnt exist
|
||||
if (!this.file) {
|
||||
this.create();
|
||||
}
|
||||
// steno is async, and it uses a queue to avoid unnecessary re-writes
|
||||
await this.file.write(stringifiedState);
|
||||
private async write(data: RestorePoint) {
|
||||
await this.file.write(data);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,15 +101,16 @@ export class RestoreService {
|
||||
return;
|
||||
}
|
||||
|
||||
const stringifiedStore = JSON.stringify(newState);
|
||||
if (stringifiedStore !== this.lastStore) {
|
||||
try {
|
||||
await this.write(stringifiedStore);
|
||||
this.lastStore = stringifiedStore;
|
||||
this.failedCreateAttempts = 0;
|
||||
} catch (_err) {
|
||||
this.failedCreateAttempts += 1;
|
||||
}
|
||||
if (deepEqual(newState, this.savedState)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.write(newState);
|
||||
this.savedState = { ...newState };
|
||||
this.failedCreateAttempts = 0;
|
||||
} catch (_error) {
|
||||
this.failedCreateAttempts += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,34 +118,27 @@ export class RestoreService {
|
||||
* Attempts reading a restore point from a given file path
|
||||
* Returns null if none found, restore point otherwise
|
||||
*/
|
||||
load(): RestorePoint | null {
|
||||
async load(): Promise<RestorePoint | null> {
|
||||
try {
|
||||
const data = this.read();
|
||||
const maybeRestorePoint = JSON.parse(data);
|
||||
|
||||
if (!isRestorePoint(maybeRestorePoint)) {
|
||||
return null;
|
||||
const maybeRestorePoint = await this.read();
|
||||
if (isRestorePoint(maybeRestorePoint)) {
|
||||
return maybeRestorePoint;
|
||||
}
|
||||
|
||||
return maybeRestorePoint;
|
||||
} catch (_error) {
|
||||
// no need to notify the user
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the restore file
|
||||
*/
|
||||
async clear() {
|
||||
if (this.file && this.failedCreateAttempts <= 3) {
|
||||
try {
|
||||
await this.file.write('');
|
||||
} catch (_error) {
|
||||
// nothing to do
|
||||
}
|
||||
try {
|
||||
await this.file.write(null);
|
||||
} catch (_error) {
|
||||
// nothing to do
|
||||
}
|
||||
this.file = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,525 +1,224 @@
|
||||
import { EndAction, LogOrigin, OntimeEvent, Playback, TimerLifeCycle, TimerState, TimerType } from 'ontime-types';
|
||||
import { calculateDuration, dayInMs } from 'ontime-utils';
|
||||
import { OntimeEvent, Playback, RuntimeStore } from 'ontime-types';
|
||||
|
||||
import { deepEqual } from 'fast-equals';
|
||||
|
||||
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, skippedOutOfEvent } from './timerUtils.js';
|
||||
import { clock } from './Clock.js';
|
||||
import { logger } from '../classes/Logger.js';
|
||||
import type { RestorePoint } from './RestoreService.js';
|
||||
import * as runtimeState from '../stores/runtimeState.js';
|
||||
import type { RuntimeState, UpdateResult } from '../stores/runtimeState.js';
|
||||
|
||||
type initialLoadingData = {
|
||||
startedAt?: number | null;
|
||||
expectedFinish?: number | null;
|
||||
current?: number | null;
|
||||
};
|
||||
|
||||
type RestoreCallback = (newState: RestorePoint) => Promise<void>;
|
||||
|
||||
export const timeSkipLimit = 3 * 32;
|
||||
import { restoreService } from './RestoreService.js';
|
||||
|
||||
/**
|
||||
* Service manages Ontime's main timer
|
||||
* It is responsible for streaming the data to the event store
|
||||
*/
|
||||
export class TimerService {
|
||||
private readonly _interval: NodeJS.Timer;
|
||||
private _updateInterval: number;
|
||||
private _lastUpdate: number | null;
|
||||
private _skipThreshold: number;
|
||||
/** how often we update the socket */
|
||||
static _updateInterval: number;
|
||||
/** how often we recalculate */
|
||||
static _refreshInterval: number;
|
||||
/** last time we updated the socket */
|
||||
static previousUpdate: number;
|
||||
/** last known state */
|
||||
static previousState: RuntimeState;
|
||||
|
||||
playback: Playback;
|
||||
timer: TimerState;
|
||||
/** when timer will be finished */
|
||||
private endCallback: NodeJS.Timer;
|
||||
|
||||
loadedTimerId: string | null;
|
||||
private loadedTimerStart: number | null;
|
||||
private loadedTimerEnd: number | null;
|
||||
private onUpdateCallback: (updateResult: UpdateResult) => void;
|
||||
|
||||
private pausedTime: number;
|
||||
private pausedAt: number | null;
|
||||
private secondaryTarget: number | null;
|
||||
|
||||
private saveRestorePoint: RestoreCallback;
|
||||
/**
|
||||
* @constructor
|
||||
* @param {object} [timerConfig]
|
||||
* @param {number} [timerConfig.refresh]
|
||||
* @param {number} [timerConfig.updateInterval]
|
||||
* @param {number} [timerConfig.skipThreshold]
|
||||
* @param {number} [timerConfig.refresh] how often we recalculate
|
||||
* @param {number} [timerConfig.updateInterval] how often we update the socket
|
||||
* @param {function} [timerConfig.onUpdateCallback] how often we update the socket
|
||||
*/
|
||||
constructor(timerConfig: { refresh: number; updateInterval: number; skipThreshold: number }) {
|
||||
this._clear();
|
||||
this._interval = setInterval(() => this.update(), timerConfig.refresh);
|
||||
this._updateInterval = timerConfig.updateInterval;
|
||||
this._skipThreshold = timerConfig.skipThreshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides callback to save restore point
|
||||
* @param cb
|
||||
*/
|
||||
setRestoreCallback(cb: RestoreCallback) {
|
||||
this.saveRestorePoint = cb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears internal state
|
||||
* @private
|
||||
*/
|
||||
_clear() {
|
||||
this.playback = Playback.Stop;
|
||||
this.timer = {
|
||||
clock: clock.timeNow(),
|
||||
current: null,
|
||||
elapsed: null,
|
||||
expectedFinish: null,
|
||||
addedTime: 0,
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
secondaryTimer: null,
|
||||
selectedEventId: null,
|
||||
duration: null,
|
||||
timerType: null,
|
||||
endAction: null,
|
||||
};
|
||||
this.loadedTimerId = null;
|
||||
this.loadedTimerStart = null;
|
||||
this.loadedTimerEnd = null;
|
||||
|
||||
this.pausedTime = 0;
|
||||
this.pausedAt = null;
|
||||
this.secondaryTarget = null;
|
||||
|
||||
this._lastUpdate = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes a given playback state, same as load
|
||||
* @param {RestorePoint} restorePoint
|
||||
* @param {OntimeEvent} timer
|
||||
*/
|
||||
resume(timer: OntimeEvent, restorePoint: RestorePoint) {
|
||||
this._clear();
|
||||
|
||||
// this is pretty much the same as load, with a few exceptions
|
||||
this.loadedTimerId = timer.id;
|
||||
this.loadedTimerStart = timer.timeStart;
|
||||
this.loadedTimerEnd = timer.timeEnd;
|
||||
|
||||
this.timer.duration = calculateDuration(timer.timeStart, timer.timeEnd);
|
||||
this.playback = restorePoint.playback;
|
||||
this.timer.timerType = timer.timerType;
|
||||
this.timer.endAction = timer.endAction;
|
||||
this.timer.startedAt = restorePoint.startedAt;
|
||||
this.timer.addedTime = restorePoint.addedTime;
|
||||
this.pausedTime = 0;
|
||||
this.pausedAt = restorePoint.pausedAt;
|
||||
|
||||
this.timer.current = this.timer.duration;
|
||||
if (this.timer.timerType === TimerType.TimeToEnd) {
|
||||
const now = clock.timeNow();
|
||||
this.timer.current = getCurrent(now, this.timer.duration, 0, 0, now, timer.timeEnd, this.timer.timerType);
|
||||
}
|
||||
|
||||
this._onResume();
|
||||
}
|
||||
|
||||
_onResume() {
|
||||
eventStore.batchSet({
|
||||
playback: this.playback,
|
||||
timer: this.timer,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads information for currently running timer
|
||||
* @param timer
|
||||
*/
|
||||
hotReload(timer) {
|
||||
if (typeof timer === 'undefined') {
|
||||
this.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (timer?.id !== this.loadedTimerId) {
|
||||
// event timer only concerns itself with current event
|
||||
return;
|
||||
}
|
||||
|
||||
if (timer?.skip) {
|
||||
this.stop();
|
||||
}
|
||||
|
||||
// TODO: check if any relevant information warrants update
|
||||
|
||||
// update relevant information and force update
|
||||
this.timer.duration = calculateDuration(timer.timeStart, timer.timeEnd);
|
||||
this.timer.timerType = timer.timerType;
|
||||
this.timer.endAction = timer.endAction;
|
||||
this.loadedTimerStart = timer.timeStart;
|
||||
this.loadedTimerEnd = timer.timeEnd;
|
||||
|
||||
// this might not be ideal
|
||||
this.timer.finishedAt = null;
|
||||
this.timer.expectedFinish = getExpectedFinish(
|
||||
this.timer.startedAt,
|
||||
this.timer.finishedAt,
|
||||
this.timer.duration,
|
||||
this.pausedTime,
|
||||
this.timer.addedTime,
|
||||
this.loadedTimerEnd,
|
||||
this.timer.timerType,
|
||||
);
|
||||
if (this.timer.startedAt === null) {
|
||||
this.timer.current = this.timer.duration;
|
||||
}
|
||||
this.update(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads given timer to object
|
||||
* @param {OntimeEvent} timer
|
||||
* @param {initialLoadingData} initialData
|
||||
*/
|
||||
load(timer: OntimeEvent, initialData?: initialLoadingData) {
|
||||
if (timer.skip) {
|
||||
throw new Error('Refuse load of skipped event');
|
||||
}
|
||||
|
||||
this._clear();
|
||||
|
||||
this.loadedTimerId = timer.id;
|
||||
this.loadedTimerStart = timer.timeStart;
|
||||
this.loadedTimerEnd = timer.timeEnd;
|
||||
|
||||
this.timer.duration = calculateDuration(timer.timeStart, timer.timeEnd);
|
||||
this.playback = Playback.Armed;
|
||||
this.timer.timerType = timer.timerType;
|
||||
this.timer.endAction = timer.endAction;
|
||||
this.pausedTime = 0;
|
||||
this.pausedAt = 0;
|
||||
|
||||
this.timer.current = this.timer.duration;
|
||||
if (this.timer.timerType === TimerType.TimeToEnd) {
|
||||
const now = clock.timeNow();
|
||||
this.timer.current = getCurrent(now, this.timer.duration, 0, 0, now, timer.timeEnd, this.timer.timerType);
|
||||
}
|
||||
|
||||
if (initialData) {
|
||||
this.timer = { ...this.timer, ...initialData };
|
||||
}
|
||||
|
||||
this._onLoad();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles side effects related to onLoad event
|
||||
* @private
|
||||
*/
|
||||
_onLoad() {
|
||||
eventStore.batchSet({
|
||||
playback: this.playback,
|
||||
timer: this.timer,
|
||||
});
|
||||
integrationService.dispatch(TimerLifeCycle.onLoad);
|
||||
this._saveState();
|
||||
constructor(timerConfig: {
|
||||
refresh: number;
|
||||
updateInterval: number;
|
||||
onUpdateCallback: (updateResult: UpdateResult) => void;
|
||||
}) {
|
||||
TimerService.previousUpdate = -1;
|
||||
TimerService.previousState = {} as RuntimeState;
|
||||
|
||||
TimerService._updateInterval = timerConfig.updateInterval;
|
||||
TimerService._refreshInterval = timerConfig.refresh;
|
||||
|
||||
this.onUpdateCallback = timerConfig.onUpdateCallback;
|
||||
this._interval = setInterval(() => {
|
||||
this.update();
|
||||
}, TimerService._refreshInterval);
|
||||
}
|
||||
|
||||
@broadcastResult
|
||||
start() {
|
||||
if (!this.loadedTimerId) {
|
||||
if (this.playback === Playback.Roll) {
|
||||
logger.error(LogOrigin.Playback, 'Cannot start while waiting for event');
|
||||
}
|
||||
return;
|
||||
if (!runtimeState.start()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.playback === Playback.Play) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.timer.clock = clock.timeNow();
|
||||
this.timer.secondaryTimer = null;
|
||||
this.secondaryTarget = null;
|
||||
|
||||
// add paused time if it exists
|
||||
if (this.pausedTime) {
|
||||
this.timer.addedTime += this.pausedTime;
|
||||
this.pausedAt = null;
|
||||
this.pausedTime = 0;
|
||||
} else if (this.timer.startedAt === null) {
|
||||
this.timer.startedAt = this.timer.clock;
|
||||
}
|
||||
|
||||
this.playback = Playback.Play;
|
||||
this.timer.expectedFinish = getExpectedFinish(
|
||||
this.timer.startedAt,
|
||||
this.timer.finishedAt,
|
||||
this.timer.duration,
|
||||
this.pausedTime,
|
||||
this.timer.addedTime,
|
||||
this.loadedTimerEnd,
|
||||
this.timer.timerType,
|
||||
);
|
||||
this._onStart();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles side effects related to onStart event
|
||||
* @private
|
||||
*/
|
||||
_onStart() {
|
||||
eventStore.batchSet({
|
||||
playback: this.playback,
|
||||
timer: this.timer,
|
||||
});
|
||||
integrationService.dispatch(TimerLifeCycle.onStart);
|
||||
this._saveState();
|
||||
const state = runtimeState.getState();
|
||||
const endTime = state.timer.current - 10;
|
||||
this.endCallback = setTimeout(() => this.update(), endTime);
|
||||
return true;
|
||||
}
|
||||
|
||||
@broadcastResult
|
||||
pause() {
|
||||
this.playback = Playback.Pause;
|
||||
this.timer.clock = clock.timeNow();
|
||||
this.pausedAt = this.timer.clock;
|
||||
this._onPause();
|
||||
}
|
||||
|
||||
_onPause() {
|
||||
eventStore.batchSet({
|
||||
playback: this.playback,
|
||||
timer: this.timer,
|
||||
});
|
||||
integrationService.dispatch(TimerLifeCycle.onPause);
|
||||
this._saveState();
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (this.playback === Playback.Stop) {
|
||||
return;
|
||||
if (!runtimeState.pause()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._clear();
|
||||
this._onStop();
|
||||
// cancel end callback
|
||||
clearTimeout(this.endCallback);
|
||||
return true;
|
||||
}
|
||||
|
||||
_onStop() {
|
||||
eventStore.batchSet({
|
||||
playback: this.playback,
|
||||
timer: this.timer,
|
||||
});
|
||||
integrationService.dispatch(TimerLifeCycle.onStop);
|
||||
this._saveState();
|
||||
@broadcastResult
|
||||
stop() {
|
||||
if (!runtimeState.stop()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// cancel end callback
|
||||
clearTimeout(this.endCallback);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds time to running timer by given amount
|
||||
* @param {number} amount
|
||||
*/
|
||||
addTime(amount: number) {
|
||||
if (!this.loadedTimerId) {
|
||||
return;
|
||||
@broadcastResult
|
||||
addTime(amount: number): boolean {
|
||||
if (!runtimeState.addTime(amount)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.timer.addedTime += amount;
|
||||
|
||||
// handle edge cases
|
||||
if (amount < 0 && Math.abs(amount) > this.timer.current) {
|
||||
if (this.timer.finishedAt === null) {
|
||||
// if we will make the clock negative
|
||||
this.timer.finishedAt = clock.timeNow();
|
||||
}
|
||||
} else if (this.timer.current < 0 && this.timer.current + amount > 0) {
|
||||
// clock will go from negative to positive
|
||||
this.timer.finishedAt = null;
|
||||
}
|
||||
|
||||
// force an update
|
||||
this.update(true);
|
||||
this._saveState();
|
||||
// renew end callback
|
||||
clearTimeout(this.endCallback);
|
||||
const state = runtimeState.getState();
|
||||
this.endCallback = setTimeout(() => this.update(), state.timer.expectedFinish);
|
||||
return true;
|
||||
}
|
||||
|
||||
private updateRoll() {
|
||||
const tempCurrentTimer = {
|
||||
selectedEventId: this.loadedTimerId,
|
||||
current: this.timer.current,
|
||||
// safeguard on midnight rollover
|
||||
_finishAt:
|
||||
this.timer.expectedFinish >= this.timer.startedAt
|
||||
? this.timer.expectedFinish
|
||||
: this.timer.expectedFinish + dayInMs,
|
||||
clock: this.timer.clock,
|
||||
secondaryTimer: this.timer.secondaryTimer,
|
||||
secondaryTarget: this.secondaryTarget,
|
||||
};
|
||||
const { updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished } = updateRoll(tempCurrentTimer);
|
||||
|
||||
this.timer.current = updatedTimer;
|
||||
this.timer.secondaryTimer = updatedSecondaryTimer;
|
||||
this.timer.elapsed = this.timer.duration - this.timer.current;
|
||||
|
||||
if (isFinished) {
|
||||
this.timer.selectedEventId = null;
|
||||
this.loadedTimerId = null;
|
||||
this._onFinish();
|
||||
}
|
||||
|
||||
// to load the next event we have to escalate to parent service
|
||||
if (doRollLoad) {
|
||||
PlaybackService.roll();
|
||||
}
|
||||
}
|
||||
|
||||
private updatePlay() {
|
||||
if (this.playback === Playback.Pause) {
|
||||
this.pausedTime = this.timer.clock - this.pausedAt;
|
||||
}
|
||||
|
||||
const finishedNow = this.timer.current <= 0 && this.timer.finishedAt === null;
|
||||
if (this.playback === Playback.Play && finishedNow) {
|
||||
this.timer.finishedAt = this.timer.clock;
|
||||
this._onFinish();
|
||||
} else {
|
||||
this.timer.expectedFinish = getExpectedFinish(
|
||||
this.timer.startedAt,
|
||||
this.timer.finishedAt,
|
||||
this.timer.duration,
|
||||
this.pausedTime,
|
||||
this.timer.addedTime,
|
||||
this.loadedTimerEnd,
|
||||
this.timer.timerType,
|
||||
);
|
||||
}
|
||||
this.timer.current = getCurrent(
|
||||
this.timer.startedAt,
|
||||
this.timer.duration,
|
||||
this.timer.addedTime,
|
||||
this.pausedTime,
|
||||
this.timer.clock,
|
||||
this.loadedTimerEnd,
|
||||
this.timer.timerType,
|
||||
);
|
||||
this.timer.elapsed = this.timer.duration - this.timer.current;
|
||||
}
|
||||
|
||||
update(force = false) {
|
||||
const previousTime = this.timer.clock;
|
||||
this.timer.clock = clock.timeNow();
|
||||
if (previousTime > this.timer.clock) {
|
||||
force = true;
|
||||
}
|
||||
|
||||
// we call integrations if we update timers
|
||||
let shouldNotify = false;
|
||||
if (this.playback === Playback.Roll) {
|
||||
shouldNotify = true;
|
||||
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;
|
||||
this.updatePlay();
|
||||
}
|
||||
|
||||
// we only update the store at the updateInterval
|
||||
// side effects such as onFinish will still be triggered in the update functions
|
||||
if (force || this.timer.clock > this._lastUpdate + this._updateInterval) {
|
||||
this._lastUpdate = this.timer.clock;
|
||||
this._onUpdate(shouldNotify);
|
||||
}
|
||||
}
|
||||
|
||||
_onUpdate(shouldNotify: boolean) {
|
||||
eventStore.set('timer', this.timer);
|
||||
if (shouldNotify) {
|
||||
integrationService.dispatch(TimerLifeCycle.onUpdate);
|
||||
}
|
||||
}
|
||||
|
||||
_onFinish() {
|
||||
eventStore.set('timer', this.timer);
|
||||
integrationService.dispatch(TimerLifeCycle.onFinish);
|
||||
if (this.playback === Playback.Play) {
|
||||
if (this.timer.endAction === EndAction.Stop) {
|
||||
PlaybackService.stop();
|
||||
} else if (this.timer.endAction === EndAction.LoadNext) {
|
||||
// we need to delay here to put this action in the queue stack. otherwise it won't be executed properly
|
||||
setTimeout(() => {
|
||||
PlaybackService.loadNext();
|
||||
}, 0);
|
||||
} else if (this.timer.endAction === EndAction.PlayNext) {
|
||||
PlaybackService.startNext();
|
||||
}
|
||||
}
|
||||
this._saveState();
|
||||
/**
|
||||
* Update the app at regular intervals
|
||||
*/
|
||||
@broadcastResult
|
||||
update() {
|
||||
const updateResult = runtimeState.update();
|
||||
// pass the result to the parent
|
||||
this.onUpdateCallback(updateResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads roll information into timer service
|
||||
* @param {OntimeEvent | null} currentEvent -- both current event and next event cant be null
|
||||
* @param {OntimeEvent | null} nextEvent -- both current event and next event cant be null
|
||||
* @param {OntimeEvent[]} rundown -- list of events to run
|
||||
*/
|
||||
roll(currentEvent: OntimeEvent | null, nextEvent: OntimeEvent | null) {
|
||||
this._clear();
|
||||
this.timer.clock = clock.timeNow();
|
||||
|
||||
if (currentEvent) {
|
||||
// there is something running, load
|
||||
this.timer.secondaryTimer = null;
|
||||
this.secondaryTarget = null;
|
||||
|
||||
// account for event that finishes the day after
|
||||
const endTime =
|
||||
currentEvent.timeEnd < currentEvent.timeStart ? currentEvent.timeEnd + dayInMs : currentEvent.timeEnd;
|
||||
|
||||
// when we load a timer in roll, we do the same things as before
|
||||
// but also pre-populate some data as to the running state
|
||||
this.load(currentEvent, {
|
||||
startedAt: currentEvent.timeStart,
|
||||
expectedFinish: currentEvent.timeEnd,
|
||||
current: endTime - this.timer.clock,
|
||||
});
|
||||
} else if (nextEvent) {
|
||||
// account for day after
|
||||
const nextStart = nextEvent.timeStart < this.timer.clock ? nextEvent.timeStart + dayInMs : nextEvent.timeStart;
|
||||
// nothing now, but something coming up
|
||||
this.timer.secondaryTimer = nextStart - this.timer.clock;
|
||||
this.secondaryTarget = nextStart;
|
||||
}
|
||||
this.playback = Playback.Roll;
|
||||
this._onRoll();
|
||||
this.update(true);
|
||||
}
|
||||
|
||||
_onRoll() {
|
||||
eventStore.set('playback', this.playback);
|
||||
this._saveState();
|
||||
}
|
||||
|
||||
async _saveState() {
|
||||
if (this.saveRestorePoint) {
|
||||
await this.saveRestorePoint({
|
||||
playback: this.playback,
|
||||
selectedEventId: this.loadedTimerId,
|
||||
startedAt: this.timer.startedAt,
|
||||
addedTime: this.timer.addedTime,
|
||||
pausedAt: this.pausedAt,
|
||||
});
|
||||
}
|
||||
@broadcastResult
|
||||
roll(rundown: OntimeEvent[]) {
|
||||
runtimeState.roll(rundown);
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
clearInterval(this._interval);
|
||||
clearTimeout(this.endCallback);
|
||||
}
|
||||
}
|
||||
|
||||
// calculate at 30fps, refresh at 1fps
|
||||
// we consider a skip at 3 lost updates
|
||||
export const eventTimer = new TimerService({ refresh: 32, updateInterval: 1000, skipThreshold: 32 * 3 });
|
||||
function broadcastResult(_target: any, _propertyKey: string, descriptor: PropertyDescriptor) {
|
||||
const originalMethod = descriptor.value;
|
||||
|
||||
descriptor.value = function (...args: any[]) {
|
||||
// call the original method and get the state
|
||||
const result = originalMethod.apply(this, args);
|
||||
const state = runtimeState.getState();
|
||||
|
||||
// we do the comparison by explicitly for each property
|
||||
// to apply custom logic for different datasets
|
||||
|
||||
// some of the data, we only update at intervals
|
||||
const isTimeToUpdate =
|
||||
state.clock < TimerService.previousUpdate ||
|
||||
state.clock - TimerService.previousUpdate >= TimerService._updateInterval;
|
||||
|
||||
// some changes need an immediate update
|
||||
const hasNewLoaded = state.eventNow?.id !== TimerService.previousState?.eventNow?.id;
|
||||
|
||||
const hasSkippedBack = state.clock < TimerService.previousUpdate;
|
||||
const justStarted = !TimerService.previousState?.timer;
|
||||
const hasChangedPlayback = TimerService.previousState.timer?.playback !== state.timer.playback;
|
||||
const hasImmediateChanges = hasNewLoaded || hasSkippedBack || justStarted || hasChangedPlayback;
|
||||
|
||||
if (hasChangedPlayback) {
|
||||
eventStore.set('onAir', state.timer.playback !== Playback.Stop);
|
||||
}
|
||||
|
||||
if (hasImmediateChanges || (isTimeToUpdate && !deepEqual(TimerService.previousState?.timer, state.timer))) {
|
||||
eventStore.set('timer', state.timer);
|
||||
TimerService.previousState.timer = { ...state.timer };
|
||||
}
|
||||
|
||||
if (hasChangedPlayback || (isTimeToUpdate && !deepEqual(TimerService.previousState?.runtime, state.runtime))) {
|
||||
eventStore.set('runtime', state.runtime);
|
||||
TimerService.previousState.runtime = { ...state.runtime };
|
||||
}
|
||||
|
||||
// Update the events if they have changed
|
||||
updateEventIfChanged('eventNow', state);
|
||||
updateEventIfChanged('publicEventNow', state);
|
||||
updateEventIfChanged('eventNext', state);
|
||||
updateEventIfChanged('publicEventNext', state);
|
||||
|
||||
if (isTimeToUpdate) {
|
||||
TimerService.previousUpdate = state.clock;
|
||||
eventStore.set('clock', state.clock);
|
||||
saveRestoreState(state);
|
||||
}
|
||||
|
||||
// Helper function to update an event if it has changed
|
||||
function updateEventIfChanged(eventKey: keyof RuntimeStore, state: RuntimeState) {
|
||||
const previous = TimerService.previousState?.[eventKey];
|
||||
const now = state[eventKey];
|
||||
|
||||
// if there was nothing, and there is nothing, noop
|
||||
if (!previous?.id && !now?.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if load status changed, save new
|
||||
if (previous?.id !== now?.id) {
|
||||
storeKey(eventKey);
|
||||
return;
|
||||
}
|
||||
|
||||
// maybe the event itself has changed
|
||||
if (!deepEqual(TimerService.previousState?.[eventKey], state[eventKey])) {
|
||||
storeKey(eventKey);
|
||||
return;
|
||||
}
|
||||
|
||||
function storeKey(eventKey: keyof RuntimeStore) {
|
||||
eventStore.set(eventKey, state[eventKey]);
|
||||
TimerService.previousState[eventKey] = { ...state[eventKey] };
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to save the restore state
|
||||
function saveRestoreState(state: RuntimeState) {
|
||||
restoreService.save({
|
||||
playback: state.timer.playback,
|
||||
selectedEventId: state.eventNow?.id ?? null,
|
||||
startedAt: state.timer.startedAt,
|
||||
addedTime: state.timer.addedTime,
|
||||
pausedAt: state._timer.pausedAt,
|
||||
firstStart: state.runtime.actualStart,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
@@ -7,21 +7,23 @@ import { isRestorePoint, RestorePoint, RestoreService } from '../RestoreService.
|
||||
|
||||
describe('isRestorePoint()', () => {
|
||||
it('validates a well defined object', () => {
|
||||
let restorePoint = {
|
||||
playback: 'play',
|
||||
let restorePoint: RestorePoint = {
|
||||
playback: Playback.Roll,
|
||||
selectedEventId: '123',
|
||||
startedAt: 1,
|
||||
addedTime: 2,
|
||||
pausedAt: 3,
|
||||
firstStart: 1,
|
||||
};
|
||||
expect(isRestorePoint(restorePoint)).toBe(true);
|
||||
|
||||
restorePoint = {
|
||||
playback: 'roll',
|
||||
playback: Playback.Roll,
|
||||
selectedEventId: '123',
|
||||
startedAt: null,
|
||||
addedTime: null,
|
||||
addedTime: 0,
|
||||
pausedAt: null,
|
||||
firstStart: 1,
|
||||
};
|
||||
expect(isRestorePoint(restorePoint)).toBe(true);
|
||||
});
|
||||
@@ -32,7 +34,7 @@ describe('isRestorePoint()', () => {
|
||||
playback: 'unknown',
|
||||
selectedEventId: '123',
|
||||
startedAt: null,
|
||||
addedTime: null,
|
||||
addedTime: 0,
|
||||
pausedAt: null,
|
||||
};
|
||||
expect(isRestorePoint(restorePoint)).toBe(false);
|
||||
@@ -41,17 +43,17 @@ describe('isRestorePoint()', () => {
|
||||
const restorePoint = {
|
||||
selectedEventId: '123',
|
||||
startedAt: null,
|
||||
addedTime: null,
|
||||
addedTime: 0,
|
||||
pausedAt: null,
|
||||
};
|
||||
expect(isRestorePoint(restorePoint)).toBe(false);
|
||||
});
|
||||
it('with incorrect value', () => {
|
||||
const restorePoint = {
|
||||
playback: 'roll',
|
||||
playback: Playback.Roll,
|
||||
selectedEventId: '123',
|
||||
startedAt: 'testing',
|
||||
addedTime: null,
|
||||
addedTime: 0,
|
||||
pausedAt: null,
|
||||
};
|
||||
expect(isRestorePoint(restorePoint)).toBe(false);
|
||||
@@ -61,51 +63,54 @@ describe('isRestorePoint()', () => {
|
||||
|
||||
describe('RestoreService()', () => {
|
||||
describe('load()', () => {
|
||||
it('loads working file with times', () => {
|
||||
const expected = {
|
||||
it('loads working file with times', async () => {
|
||||
const expected: RestorePoint = {
|
||||
playback: Playback.Play,
|
||||
selectedEventId: 'da5b4',
|
||||
startedAt: 1234,
|
||||
addedTime: 5678,
|
||||
pausedAt: 9087,
|
||||
firstStart: 1234,
|
||||
};
|
||||
|
||||
const restoreService = new RestoreService('/path/to/restore/file');
|
||||
vi.spyOn<any, any>(restoreService, 'read').mockImplementation(() => JSON.stringify(expected));
|
||||
vi.spyOn<any, any>(restoreService, 'read').mockImplementation(() => expected);
|
||||
|
||||
const testLoad = restoreService.load();
|
||||
const testLoad = await restoreService.load();
|
||||
expect(testLoad).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('loads working file without times', () => {
|
||||
const expected = {
|
||||
it('loads working file without times', async () => {
|
||||
const expected: RestorePoint = {
|
||||
playback: Playback.Stop,
|
||||
selectedEventId: null,
|
||||
startedAt: null,
|
||||
addedTime: null,
|
||||
addedTime: 0,
|
||||
pausedAt: null,
|
||||
firstStart: 1234,
|
||||
};
|
||||
|
||||
const restoreService = new RestoreService('/path/to/restore/file');
|
||||
vi.spyOn<any, any>(restoreService, 'read').mockImplementation(() => JSON.stringify(expected));
|
||||
vi.spyOn<any, any>(restoreService, 'read').mockImplementation(() => expected);
|
||||
|
||||
const testLoad = restoreService.load();
|
||||
const testLoad = await restoreService.load();
|
||||
expect(testLoad).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('does not load wrong play state', () => {
|
||||
it('does not load wrong play state', async () => {
|
||||
const expected = {
|
||||
playback: 'does-not-exist',
|
||||
selectedEventId: 'da5b4',
|
||||
startedAt: 1234,
|
||||
addedTime: 1234,
|
||||
pausedAt: 1234,
|
||||
firstStart: 1234,
|
||||
};
|
||||
|
||||
const restoreService = new RestoreService('/path/to/restore/file');
|
||||
vi.spyOn<any, any>(restoreService, 'read').mockImplementation(() => JSON.stringify(expected));
|
||||
vi.spyOn<any, any>(restoreService, 'read').mockImplementation(() => expected);
|
||||
|
||||
const testLoad = restoreService.load();
|
||||
const testLoad = await restoreService.load();
|
||||
expect(testLoad).toBe(null);
|
||||
});
|
||||
});
|
||||
@@ -118,12 +123,13 @@ describe('RestoreService()', () => {
|
||||
startedAt: 1234,
|
||||
addedTime: 1234,
|
||||
pausedAt: 1234,
|
||||
firstStart: 1234,
|
||||
};
|
||||
|
||||
const restoreService = new RestoreService('/path/to/restore/file');
|
||||
const writeSpy = vi.spyOn<any, any>(restoreService, 'write').mockImplementation(() => undefined);
|
||||
await restoreService.save(testData);
|
||||
expect(writeSpy).toHaveBeenCalledWith(JSON.stringify(testData));
|
||||
expect(writeSpy).toHaveBeenCalledWith(testData);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,776 +0,0 @@
|
||||
import { OntimeEvent } from 'ontime-types';
|
||||
import { dayInMs } from 'ontime-utils';
|
||||
|
||||
import { getRollTimers, normaliseEndTime, sortArrayByProperty, updateRoll } from '../rollUtils.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 }];
|
||||
|
||||
const arr1Expected = [{ timeStart: 1 }, { timeStart: 2 }, { timeStart: 3 }, { timeStart: 4 }, { timeStart: 5 }];
|
||||
|
||||
const sorted = sortArrayByProperty(arr1, 'timeStart');
|
||||
expect(sorted).toStrictEqual(arr1Expected);
|
||||
});
|
||||
|
||||
it('sort array 1-5 with null', () => {
|
||||
const arr1 = [
|
||||
{ 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 },
|
||||
];
|
||||
|
||||
const sorted = sortArrayByProperty(arr1, 'timeStart');
|
||||
expect(sorted).toStrictEqual(arr1Expected);
|
||||
});
|
||||
});
|
||||
|
||||
// test getRollTimers()
|
||||
describe('test that roll loads selection in right order', () => {
|
||||
const eventlist: Partial<OntimeEvent>[] = [
|
||||
{
|
||||
id: '1',
|
||||
timeStart: 5,
|
||||
timeEnd: 10,
|
||||
isPublic: false,
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
timeStart: 10,
|
||||
timeEnd: 20,
|
||||
isPublic: false,
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
timeStart: 20,
|
||||
timeEnd: 30,
|
||||
isPublic: false,
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
timeStart: 30,
|
||||
timeEnd: 40,
|
||||
isPublic: false,
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
timeStart: 40,
|
||||
timeEnd: 50,
|
||||
isPublic: true,
|
||||
},
|
||||
{
|
||||
id: '6',
|
||||
timeStart: 50,
|
||||
timeEnd: 60,
|
||||
isPublic: false,
|
||||
},
|
||||
{
|
||||
id: '7',
|
||||
timeStart: 60,
|
||||
timeEnd: 70,
|
||||
isPublic: true,
|
||||
},
|
||||
{
|
||||
id: '8',
|
||||
timeStart: 70,
|
||||
timeEnd: 80,
|
||||
isPublic: false,
|
||||
},
|
||||
];
|
||||
|
||||
it('if timer is at 0', () => {
|
||||
const now = 0;
|
||||
const expected = {
|
||||
nowIndex: null,
|
||||
nowId: null,
|
||||
publicIndex: null,
|
||||
nextIndex: 0,
|
||||
publicNextIndex: 4,
|
||||
timeToNext: 5,
|
||||
nextEvent: eventlist[0],
|
||||
nextPublicEvent: eventlist[4],
|
||||
currentEvent: null,
|
||||
currentPublicEvent: null,
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if timer is at 5', () => {
|
||||
const now = 5;
|
||||
const expected = {
|
||||
nowIndex: 0,
|
||||
nowId: eventlist[0].id,
|
||||
publicIndex: null,
|
||||
nextIndex: 1,
|
||||
publicNextIndex: 4,
|
||||
timeToNext: 5,
|
||||
nextEvent: eventlist[1],
|
||||
nextPublicEvent: eventlist[4],
|
||||
currentEvent: eventlist[0],
|
||||
currentPublicEvent: null,
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if timer is at 15', () => {
|
||||
const now = 15;
|
||||
const expected = {
|
||||
nowIndex: 1,
|
||||
nowId: eventlist[1].id,
|
||||
publicIndex: null,
|
||||
nextIndex: 2,
|
||||
publicNextIndex: 4,
|
||||
timeToNext: 5,
|
||||
nextEvent: eventlist[2],
|
||||
nextPublicEvent: eventlist[4],
|
||||
currentEvent: eventlist[1],
|
||||
currentPublicEvent: null,
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if timer is at 20', () => {
|
||||
const now = 20;
|
||||
const expected = {
|
||||
nowIndex: 2,
|
||||
nowId: eventlist[2].id,
|
||||
publicIndex: null,
|
||||
nextIndex: 3,
|
||||
publicNextIndex: 4,
|
||||
timeToNext: 10,
|
||||
nextEvent: eventlist[3],
|
||||
nextPublicEvent: eventlist[4],
|
||||
currentEvent: eventlist[2],
|
||||
currentPublicEvent: null,
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if timer is at 49', () => {
|
||||
const now = 49;
|
||||
const expected = {
|
||||
nowIndex: 4,
|
||||
nowId: eventlist[4].id,
|
||||
publicIndex: 4,
|
||||
nextIndex: 5,
|
||||
publicNextIndex: 6,
|
||||
timeToNext: 1,
|
||||
nextEvent: eventlist[5],
|
||||
nextPublicEvent: eventlist[6],
|
||||
currentEvent: eventlist[4],
|
||||
currentPublicEvent: eventlist[4],
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if timer is at 63', () => {
|
||||
const now = 63;
|
||||
const expected = {
|
||||
nowIndex: 6,
|
||||
nowId: eventlist[6].id,
|
||||
publicIndex: 6,
|
||||
nextIndex: 7,
|
||||
publicNextIndex: null,
|
||||
timeToNext: 7,
|
||||
nextEvent: eventlist[7],
|
||||
nextPublicEvent: null,
|
||||
currentEvent: eventlist[6],
|
||||
currentPublicEvent: eventlist[6],
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if timer is at 75', () => {
|
||||
const now = 75;
|
||||
const expected = {
|
||||
nowIndex: 7,
|
||||
nowId: eventlist[7].id,
|
||||
publicIndex: 6,
|
||||
nextIndex: null,
|
||||
publicNextIndex: null,
|
||||
timeToNext: null,
|
||||
nextEvent: null,
|
||||
nextPublicEvent: null,
|
||||
currentEvent: eventlist[7],
|
||||
currentPublicEvent: eventlist[6],
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if timer is at 100 we roll to day after', () => {
|
||||
const now = 100;
|
||||
const expected = {
|
||||
nowIndex: null,
|
||||
nowId: null,
|
||||
publicIndex: null,
|
||||
nextIndex: 0,
|
||||
publicNextIndex: 4,
|
||||
timeToNext: dayInMs - now + eventlist[0].timeStart,
|
||||
nextEvent: eventlist[0],
|
||||
nextPublicEvent: eventlist[4],
|
||||
currentEvent: null,
|
||||
currentPublicEvent: null,
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('handles rolls to next day with real values', () => {
|
||||
const singleEventList: Partial<OntimeEvent>[] = [
|
||||
{
|
||||
id: '1',
|
||||
timeStart: 36000000, // 10:00
|
||||
timeEnd: 39600000, // 11:00
|
||||
isPublic: true,
|
||||
},
|
||||
];
|
||||
const now = 64800000; // 18:00
|
||||
const expected = {
|
||||
nowIndex: null,
|
||||
nowId: null,
|
||||
publicIndex: null,
|
||||
nextIndex: 0,
|
||||
publicNextIndex: 0,
|
||||
timeToNext: dayInMs - now + singleEventList[0].timeStart,
|
||||
nextEvent: singleEventList[0],
|
||||
nextPublicEvent: singleEventList[0],
|
||||
currentEvent: null,
|
||||
currentPublicEvent: null,
|
||||
};
|
||||
const state = getRollTimers(singleEventList as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('handles rolls to next day with real values', () => {
|
||||
const singleEventList: Partial<OntimeEvent>[] = [
|
||||
{
|
||||
id: '1',
|
||||
timeStart: 36000000, // 10:00
|
||||
timeEnd: 3600000, // 01:00
|
||||
isPublic: true,
|
||||
},
|
||||
];
|
||||
const now = 60000; // 00:01
|
||||
const expected = {
|
||||
nowIndex: 0,
|
||||
nowId: singleEventList[0].id,
|
||||
publicIndex: 0,
|
||||
nextIndex: null,
|
||||
publicNextIndex: null,
|
||||
timeToNext: null,
|
||||
nextEvent: null,
|
||||
nextPublicEvent: null,
|
||||
currentEvent: singleEventList[0],
|
||||
currentPublicEvent: singleEventList[0],
|
||||
};
|
||||
const state = getRollTimers(singleEventList as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
it('handles rolls to next day with real values', () => {
|
||||
const singleEventList: Partial<OntimeEvent>[] = [
|
||||
{
|
||||
id: '1',
|
||||
timeStart: 36000000, // 10:00
|
||||
timeEnd: 3600000, // 01:00
|
||||
isPublic: true,
|
||||
},
|
||||
];
|
||||
const now = 60000; // 00:01
|
||||
const expected = {
|
||||
nowIndex: 0,
|
||||
nowId: singleEventList[0].id,
|
||||
publicIndex: 0,
|
||||
nextIndex: null,
|
||||
publicNextIndex: null,
|
||||
timeToNext: null,
|
||||
nextEvent: null,
|
||||
nextPublicEvent: null,
|
||||
currentEvent: singleEventList[0],
|
||||
currentPublicEvent: singleEventList[0],
|
||||
};
|
||||
const state = getRollTimers(singleEventList as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('handles roll that goes over midnight', () => {
|
||||
const singleEventList: Partial<OntimeEvent>[] = [
|
||||
{
|
||||
id: '1',
|
||||
timeStart: 72000000, // 20:00
|
||||
timeEnd: 60000, // 00:10
|
||||
isPublic: true,
|
||||
},
|
||||
];
|
||||
const now = 6000; // 00:01
|
||||
const expected = {
|
||||
nowIndex: 0,
|
||||
nowId: singleEventList[0].id,
|
||||
publicIndex: 0,
|
||||
nextIndex: null,
|
||||
publicNextIndex: null,
|
||||
timeToNext: null,
|
||||
nextEvent: null,
|
||||
nextPublicEvent: null,
|
||||
currentEvent: singleEventList[0],
|
||||
currentPublicEvent: singleEventList[0],
|
||||
};
|
||||
const state = getRollTimers(singleEventList as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
// test getRollTimers()
|
||||
describe('test that roll behaviour with overlapping times', () => {
|
||||
const eventlist: Partial<OntimeEvent>[] = [
|
||||
{
|
||||
id: '1',
|
||||
timeStart: 10,
|
||||
timeEnd: 10,
|
||||
isPublic: false,
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
timeStart: 10,
|
||||
timeEnd: 20,
|
||||
isPublic: true,
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
timeStart: 10,
|
||||
timeEnd: 30,
|
||||
isPublic: false,
|
||||
},
|
||||
];
|
||||
|
||||
it('if timer is at 0', () => {
|
||||
const now = 0;
|
||||
const expected = {
|
||||
nowIndex: null,
|
||||
nowId: null,
|
||||
publicIndex: null,
|
||||
nextIndex: 0,
|
||||
publicNextIndex: 1,
|
||||
timeToNext: 10,
|
||||
nextEvent: eventlist[0],
|
||||
nextPublicEvent: eventlist[1],
|
||||
currentEvent: null,
|
||||
currentPublicEvent: null,
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if timer is at 10', () => {
|
||||
const now = 10;
|
||||
const expected = {
|
||||
nowIndex: 1,
|
||||
nowId: eventlist[1].id,
|
||||
publicIndex: 1,
|
||||
nextIndex: 2,
|
||||
publicNextIndex: null,
|
||||
timeToNext: 0,
|
||||
nextEvent: eventlist[2],
|
||||
nextPublicEvent: null,
|
||||
currentEvent: eventlist[1],
|
||||
currentPublicEvent: eventlist[1],
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if timer is at 15', () => {
|
||||
const now = 15;
|
||||
const expected = {
|
||||
nowIndex: 1,
|
||||
nowId: eventlist[1].id,
|
||||
publicIndex: 1,
|
||||
nextIndex: 2,
|
||||
publicNextIndex: null,
|
||||
timeToNext: -5,
|
||||
nextEvent: eventlist[2],
|
||||
nextPublicEvent: null,
|
||||
currentEvent: eventlist[1],
|
||||
currentPublicEvent: eventlist[1],
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if timer is at 20', () => {
|
||||
const now = 20;
|
||||
const expected = {
|
||||
nowIndex: 2,
|
||||
nowId: eventlist[2].id,
|
||||
publicIndex: 1,
|
||||
nextIndex: null,
|
||||
publicNextIndex: null,
|
||||
timeToNext: null,
|
||||
nextEvent: null,
|
||||
nextPublicEvent: null,
|
||||
currentEvent: eventlist[2],
|
||||
currentPublicEvent: eventlist[1],
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if timer is at 25', () => {
|
||||
const now = 25;
|
||||
const expected = {
|
||||
nowIndex: 2,
|
||||
nowId: eventlist[2].id,
|
||||
publicIndex: 1,
|
||||
nextIndex: null,
|
||||
publicNextIndex: null,
|
||||
timeToNext: null,
|
||||
nextEvent: null,
|
||||
nextPublicEvent: null,
|
||||
currentEvent: eventlist[2],
|
||||
currentPublicEvent: eventlist[1],
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
// test getRollTimers() on issue #58
|
||||
describe('test that roll behaviour multi day event edge cases', () => {
|
||||
it('if the start time is the day after end time, and start time is earlier than now', () => {
|
||||
const now = 66600000; // 19:30
|
||||
const eventlist: Partial<OntimeEvent>[] = [
|
||||
{
|
||||
id: '1',
|
||||
timeStart: 66000000, // 19:20
|
||||
timeEnd: 54600000, // 16:10
|
||||
isPublic: false,
|
||||
},
|
||||
];
|
||||
const expected = {
|
||||
nowIndex: 0,
|
||||
nowId: '1',
|
||||
publicIndex: null,
|
||||
nextIndex: null,
|
||||
publicNextIndex: null,
|
||||
timeToNext: null,
|
||||
nextEvent: null,
|
||||
nextPublicEvent: null,
|
||||
currentEvent: eventlist[0],
|
||||
currentPublicEvent: null,
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('if the start time is the day after end time, and both are later than now', () => {
|
||||
const now = 66840000; // 19:34
|
||||
const eventlist: Partial<OntimeEvent>[] = [
|
||||
{
|
||||
id: '1',
|
||||
timeStart: 67200000, // 19:40
|
||||
timeEnd: 66900000, // 19:35
|
||||
isPublic: false,
|
||||
},
|
||||
];
|
||||
const expected = {
|
||||
currentEvent: {
|
||||
id: '1',
|
||||
isPublic: false,
|
||||
timeEnd: 66900000,
|
||||
timeStart: 67200000,
|
||||
},
|
||||
currentPublicEvent: null,
|
||||
nextEvent: null,
|
||||
nextIndex: null,
|
||||
nextPublicEvent: null,
|
||||
nowId: '1',
|
||||
nowIndex: 0,
|
||||
publicIndex: null,
|
||||
publicNextIndex: null,
|
||||
timeToNext: null,
|
||||
};
|
||||
|
||||
const state = getRollTimers(eventlist as OntimeEvent[], now);
|
||||
expect(state).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
// test getRollTimers() on issue #757
|
||||
describe('it handles timeEnd over day', () => {
|
||||
it('ignores events with timeEnd larger than a day', () => {
|
||||
const testRundown = [
|
||||
{
|
||||
title: 'Setup',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: 'BMA, Nebelfluid, Shooter, Akkus, UHF11, Getränke, Kaffee, Strom, ELA, Text für Holger',
|
||||
endAction: 'play-next',
|
||||
timerType: 'count-down',
|
||||
timeStart: 66600000,
|
||||
timeEnd: 68400000,
|
||||
duration: 1800000,
|
||||
isPublic: false,
|
||||
skip: false,
|
||||
colour: '#2fa9e5',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: 'event',
|
||||
revision: 0,
|
||||
cue: 'PRE',
|
||||
id: 'b2f8d',
|
||||
},
|
||||
{
|
||||
title: 'Künstliche Intelligenz',
|
||||
subtitle: ' -> Vorstellung Maske',
|
||||
presenter: 'Engel und Teufel',
|
||||
note: 'Melli Kleben! Sofa',
|
||||
endAction: 'play-next',
|
||||
timerType: 'count-down',
|
||||
timeStart: 86100000,
|
||||
// timeEnd: 1020000, <--- this would have been equivalent
|
||||
timeEnd: 87420000,
|
||||
duration: 1320000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '#a8ec31',
|
||||
user0: 'UHF1 Melli (Korsett)',
|
||||
user1: 'UHF2 Reinhold (unter Flügel)',
|
||||
user2: 'UHF3 Oli (Sport-Unterhose Rechts)',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: 'event',
|
||||
revision: 0,
|
||||
cue: '16',
|
||||
id: '8b970',
|
||||
},
|
||||
];
|
||||
|
||||
const timeNow = 64488675; // 17:55-something
|
||||
|
||||
const timers = getRollTimers(testRundown as OntimeEvent[], timeNow);
|
||||
expect(timers.currentEvent).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// test normaliseEndTime() on issue #58
|
||||
test('test typical scenarios', () => {
|
||||
const t1 = {
|
||||
start: 10,
|
||||
end: 20,
|
||||
};
|
||||
const t1_expected = 20;
|
||||
|
||||
expect(normaliseEndTime(t1.start, t1.end)).toBe(t1_expected);
|
||||
|
||||
const t2 = {
|
||||
start: 10 + dayInMs,
|
||||
end: 20,
|
||||
};
|
||||
const t2_expected = 20 + dayInMs;
|
||||
|
||||
expect(normaliseEndTime(t2.start, t2.end)).toBe(t2_expected);
|
||||
|
||||
const t3 = {
|
||||
start: 10,
|
||||
end: 10,
|
||||
};
|
||||
const t3_expected = 10;
|
||||
|
||||
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: -1,
|
||||
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);
|
||||
});
|
||||
|
||||
it('when a secondary timer is finished, it prompts for new event load', () => {
|
||||
const timers = {
|
||||
selectedEventId: null,
|
||||
current: null,
|
||||
_finishAt: null,
|
||||
clock: 15,
|
||||
secondaryTimer: 0,
|
||||
secondaryTarget: 15,
|
||||
};
|
||||
|
||||
const expected = {
|
||||
updatedTimer: null,
|
||||
updatedSecondaryTimer: timers.secondaryTarget - timers.clock,
|
||||
doRollLoad: true,
|
||||
isFinished: false,
|
||||
};
|
||||
|
||||
expect(updateRoll(timers)).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('counts over midnight', () => {
|
||||
const timers = {
|
||||
selectedEventId: '1',
|
||||
current: 25,
|
||||
_finishAt: 10 + dayInMs,
|
||||
clock: dayInMs - 10,
|
||||
secondaryTimer: null,
|
||||
secondaryTarget: null,
|
||||
};
|
||||
|
||||
const expected = {
|
||||
updatedTimer: 20,
|
||||
updatedSecondaryTimer: null,
|
||||
doRollLoad: false,
|
||||
isFinished: false,
|
||||
};
|
||||
|
||||
expect(updateRoll(timers)).toStrictEqual(expected);
|
||||
});
|
||||
|
||||
it('rolls over midnight', () => {
|
||||
const timers = {
|
||||
selectedEventId: '1',
|
||||
current: dayInMs,
|
||||
_finishAt: 10 + dayInMs,
|
||||
clock: 10,
|
||||
secondaryTimer: null,
|
||||
secondaryTarget: null,
|
||||
};
|
||||
|
||||
const expected = {
|
||||
updatedTimer: dayInMs,
|
||||
updatedSecondaryTimer: null,
|
||||
doRollLoad: false,
|
||||
isFinished: false,
|
||||
};
|
||||
|
||||
expect(updateRoll(timers)).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,44 @@
|
||||
import { Low } from 'lowdb';
|
||||
import { JSONFile } from 'lowdb/node';
|
||||
|
||||
import { appStatePath, isTest } from '../../setup/index.js';
|
||||
|
||||
interface Config {
|
||||
lastLoadedProject: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service manages Ontime's runtime memory between boots
|
||||
*/
|
||||
|
||||
class AppStateService {
|
||||
private config: Low<Config>;
|
||||
private pathToFile: string;
|
||||
|
||||
constructor(appStatePath: string) {
|
||||
this.pathToFile = appStatePath;
|
||||
const adapter = new JSONFile<Config>(this.pathToFile);
|
||||
this.config = new Low<Config>(adapter, null);
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
private async init() {
|
||||
await this.config.read();
|
||||
await this.config.write();
|
||||
}
|
||||
|
||||
async get(): Promise<Config> {
|
||||
await this.config.read();
|
||||
return this.config.data;
|
||||
}
|
||||
|
||||
async updateDatabaseConfig(filename: string): Promise<void> {
|
||||
if (isTest) return;
|
||||
|
||||
this.config.data.lastLoadedProject = filename;
|
||||
await this.config.write();
|
||||
}
|
||||
}
|
||||
|
||||
export const appStateService = new AppStateService(appStatePath);
|
||||
@@ -1,37 +0,0 @@
|
||||
import { isOntimeBlock, isOntimeEvent, OntimeRundown, SupportedEvent } from 'ontime-types';
|
||||
|
||||
import { deleteAtIndex } from '../utils/arrayUtils.js';
|
||||
|
||||
export function _applyDelay(eventId: string, rundown: OntimeRundown): OntimeRundown {
|
||||
const delayIndex = rundown.findIndex((event) => event.id === eventId);
|
||||
const delayEvent = rundown.at(delayIndex);
|
||||
|
||||
if (delayEvent.type !== SupportedEvent.Delay) {
|
||||
throw new Error('Given event ID is not a delay');
|
||||
}
|
||||
|
||||
const updatedRundown = [...rundown];
|
||||
const delayValue = delayEvent.duration;
|
||||
|
||||
if (delayValue === 0 || delayIndex === rundown.length - 1) {
|
||||
// nothing to apply
|
||||
return updatedRundown;
|
||||
}
|
||||
|
||||
for (let i = delayIndex + 1; i < rundown.length; i++) {
|
||||
const currentEvent = updatedRundown[i];
|
||||
|
||||
if (isOntimeBlock(currentEvent)) {
|
||||
break;
|
||||
} else if (isOntimeEvent(currentEvent)) {
|
||||
currentEvent.timeStart = Math.max(0, currentEvent.timeStart + delayValue);
|
||||
currentEvent.timeEnd = Math.max(currentEvent.duration, currentEvent.timeEnd + delayValue);
|
||||
if (currentEvent.delay) {
|
||||
currentEvent.delay = currentEvent.delay - delayValue;
|
||||
}
|
||||
currentEvent.revision += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return deleteAtIndex(delayIndex, updatedRundown);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { SimpleDirection, SimpleTimerState } from 'ontime-types';
|
||||
|
||||
import { SimpleTimer } from '../../classes/simple-timer/SimpleTimer.js';
|
||||
import { eventStore } from '../../stores/EventStore.js';
|
||||
|
||||
export type EmitFn = (state: SimpleTimerState) => void;
|
||||
export type GetTimeFn = () => number;
|
||||
|
||||
export class ExtraTimerService {
|
||||
private timer: SimpleTimer;
|
||||
private interval: NodeJS.Timer | null = null;
|
||||
private emit: EmitFn;
|
||||
private getTime: GetTimeFn;
|
||||
|
||||
constructor(emit: EmitFn, getTime: GetTimeFn) {
|
||||
this.timer = new SimpleTimer();
|
||||
this.emit = emit;
|
||||
this.getTime = getTime;
|
||||
}
|
||||
|
||||
private startInterval() {
|
||||
this.interval = setInterval(this.update.bind(this), 500);
|
||||
}
|
||||
|
||||
private stopInterval() {
|
||||
if (this.interval) {
|
||||
clearInterval(this.interval);
|
||||
}
|
||||
}
|
||||
|
||||
@broadcastReturn
|
||||
setDirection(direction: SimpleDirection) {
|
||||
return this.timer.setDirection(direction);
|
||||
}
|
||||
|
||||
@broadcastReturn
|
||||
start() {
|
||||
this.startInterval();
|
||||
return this.timer.start(this.getTime());
|
||||
}
|
||||
|
||||
@broadcastReturn
|
||||
pause() {
|
||||
return this.timer.pause(this.getTime());
|
||||
}
|
||||
|
||||
@broadcastReturn
|
||||
stop() {
|
||||
this.stopInterval();
|
||||
return this.timer.stop();
|
||||
}
|
||||
|
||||
@broadcastReturn
|
||||
setTime(duration: number) {
|
||||
return this.timer.setTime(duration);
|
||||
}
|
||||
|
||||
@broadcastReturn
|
||||
private update() {
|
||||
return this.timer.update(this.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
function broadcastReturn(_target: any, _propertyKey: string, descriptor: PropertyDescriptor) {
|
||||
const originalMethod = descriptor.value;
|
||||
|
||||
descriptor.value = function (...args: any[]) {
|
||||
const result = originalMethod.apply(this, args);
|
||||
this.emit(result);
|
||||
return result;
|
||||
};
|
||||
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
const emit = (state: SimpleTimerState) => eventStore.set('auxtimer1', state);
|
||||
const timeNow = () => Date.now();
|
||||
|
||||
export const extraTimerService = new ExtraTimerService(emit, timeNow);
|
||||
@@ -1,23 +1,22 @@
|
||||
import got from 'got';
|
||||
|
||||
import { HttpSettings, HttpSubscription, HttpSubscriptionOptions, LogOrigin } from 'ontime-types';
|
||||
import { HttpSettings, HttpSubscription, 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;
|
||||
export class HttpIntegration implements IIntegration<HttpSubscription, HttpSettings> {
|
||||
subscriptions: HttpSubscription[];
|
||||
enabled: boolean;
|
||||
|
||||
constructor() {
|
||||
this.subscriptions = dbModel.http.subscriptions;
|
||||
this.subscriptions = [];
|
||||
this.enabled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,75 +24,40 @@ export class HttpIntegration implements IIntegration<HttpSubscriptionOptions> {
|
||||
*/
|
||||
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}`,
|
||||
};
|
||||
}
|
||||
this.enabled = enabledOut;
|
||||
}
|
||||
|
||||
initSubscriptions(subscriptionOptions: HttpSubscription) {
|
||||
if (validateHttpSubscriptionObject(subscriptionOptions)) {
|
||||
this.subscriptions = { ...subscriptionOptions };
|
||||
}
|
||||
initSubscriptions(subscriptions: HttpSubscription[]) {
|
||||
this.subscriptions = subscriptions;
|
||||
}
|
||||
|
||||
dispatch(action: Action, state?: object) {
|
||||
if (!action) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'HTTP called with no action',
|
||||
};
|
||||
dispatch(action: TimerLifeCycleKey, state?: object) {
|
||||
// noop
|
||||
if (!this.enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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}`,
|
||||
};
|
||||
}
|
||||
for (let i = 0; i < this.subscriptions.length; i++) {
|
||||
const { cycle, message, enabled } = this.subscriptions[i];
|
||||
if (cycle !== action || !enabled || !message) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const parsedMessage = parseTemplateNested(message, state || {});
|
||||
this.emit(parsedMessage);
|
||||
}
|
||||
}
|
||||
|
||||
emit(path: string) {
|
||||
got.get(path, { retry: { limit: 0 } }).catch((err) => {
|
||||
logger.error(LogOrigin.Tx, `HTTP Integration: ${err.code}`);
|
||||
});
|
||||
}
|
||||
|
||||
async emit(path: URL) {
|
||||
try {
|
||||
await got.get(path, {
|
||||
retry: { limit: 0 },
|
||||
});
|
||||
} catch (err) {
|
||||
logger.error(LogOrigin.Tx, `HTTP integration: ${err}`);
|
||||
}
|
||||
shutdown() {
|
||||
/** shutdown is a no-op here*/
|
||||
}
|
||||
|
||||
shutdown() {}
|
||||
}
|
||||
|
||||
export const httpIntegration = new HttpIntegration();
|
||||
|
||||
@@ -1,24 +1,11 @@
|
||||
import { TimerLifeCycle, Subscription } from 'ontime-types';
|
||||
import { TimerLifeCycle } from 'ontime-types';
|
||||
|
||||
export type TimerLifeCycleKey = keyof typeof TimerLifeCycle;
|
||||
|
||||
export default interface IIntegration<T> {
|
||||
subscriptions: Subscription<T>;
|
||||
init: (config: unknown) => OperationReturn;
|
||||
dispatch: (action: TimerLifeCycleKey, state?: object) => OperationReturn;
|
||||
emit: (...args: unknown[]) => unknown;
|
||||
export default interface IIntegration<T, C> {
|
||||
subscriptions: T[];
|
||||
init: (config: C) => void;
|
||||
dispatch: (action: TimerLifeCycleKey, state?: object) => void;
|
||||
emit: (...args: never[]) => unknown;
|
||||
shutdown: () => void;
|
||||
}
|
||||
|
||||
// either went well, or explain what failed
|
||||
type OperationReturn = ReturnOnSuccess | ReturnOnError;
|
||||
|
||||
type ReturnOnSuccess = {
|
||||
success: true;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
type ReturnOnError = {
|
||||
success: false;
|
||||
message: string;
|
||||
};
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
import { LogOrigin } from 'ontime-types';
|
||||
|
||||
import IIntegration, { TimerLifeCycleKey } from './IIntegration.js';
|
||||
import { eventStore } from '../../stores/EventStore.js';
|
||||
import { logger } from '../../classes/Logger.js';
|
||||
|
||||
class IntegrationService {
|
||||
private integrations: IIntegration<unknown>[];
|
||||
private integrations: IIntegration<unknown, unknown>[];
|
||||
|
||||
constructor() {
|
||||
this.integrations = [];
|
||||
}
|
||||
|
||||
register(integrationService: IIntegration<unknown>) {
|
||||
register(integrationService: IIntegration<unknown, unknown>) {
|
||||
this.integrations.push(integrationService);
|
||||
}
|
||||
|
||||
unregister(integrationService: IIntegration<unknown>) {
|
||||
unregister(integrationService: IIntegration<unknown, unknown>) {
|
||||
this.integrations = this.integrations.filter((int) => int !== integrationService);
|
||||
}
|
||||
|
||||
@@ -24,7 +27,7 @@ class IntegrationService {
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
console.log('Shutdown integrations');
|
||||
logger.info(LogOrigin.Tx, 'Shutdown Integrations');
|
||||
this.integrations.forEach((integration) => {
|
||||
integration.shutdown();
|
||||
});
|
||||
|
||||
@@ -1,133 +1,144 @@
|
||||
import { ArgumentType, Client, Message } from 'node-osc';
|
||||
import { OSCSettings, OscSubscription, OscSubscriptionOptions } from 'ontime-types';
|
||||
import { LogOrigin, MaybeNumber, MaybeString, OSCSettings, OscSubscription } 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 { validateOscSubscriptionObject } from '../../utils/parserFunctions.js';
|
||||
|
||||
type Action = TimerLifeCycleKey | string;
|
||||
import { logger } from '../../classes/Logger.js';
|
||||
import { OscServer } from '../../adapters/OscAdapter.js';
|
||||
|
||||
/**
|
||||
* @description Class contains logic towards outgoing OSC communications
|
||||
* @class
|
||||
*/
|
||||
export class OscIntegration implements IIntegration<OscSubscriptionOptions> {
|
||||
export class OscIntegration implements IIntegration<OscSubscription, OSCSettings> {
|
||||
protected oscClient: null | Client;
|
||||
subscriptions: OscSubscription;
|
||||
protected oscServer: OscServer | null = null;
|
||||
|
||||
subscriptions: OscSubscription[];
|
||||
targetIP: MaybeString;
|
||||
portOut: MaybeNumber;
|
||||
portIn: MaybeNumber;
|
||||
enabledOut: boolean;
|
||||
enabledIn: boolean;
|
||||
|
||||
constructor() {
|
||||
this.oscClient = null;
|
||||
this.subscriptions = dbModel.osc.subscriptions;
|
||||
this.subscriptions = [];
|
||||
this.targetIP = null;
|
||||
this.portOut = null;
|
||||
this.portIn = null;
|
||||
this.enabledOut = false;
|
||||
this.enabledIn = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes oscClient
|
||||
*/
|
||||
init(config: OSCSettings) {
|
||||
const { targetIP, portOut, subscriptions, enabledOut } = config;
|
||||
const { targetIP, portOut, subscriptions, enabledOut, enabledIn, portIn } = config;
|
||||
|
||||
if (!enabledOut) {
|
||||
this.oscClient?.close();
|
||||
return {
|
||||
success: false,
|
||||
message: 'OSC output disabled',
|
||||
};
|
||||
this.initTX(enabledOut, targetIP, portOut, subscriptions);
|
||||
this.initRX(enabledIn, portIn);
|
||||
// return `OSC integration client connected to ${targetIP}:${portOut}`;
|
||||
}
|
||||
|
||||
private initSubscriptions(subscriptions: OscSubscription[]) {
|
||||
this.subscriptions = subscriptions;
|
||||
}
|
||||
|
||||
dispatch(action: TimerLifeCycleKey, state?: object) {
|
||||
// noop
|
||||
if (!this.oscClient) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < this.subscriptions.length; i++) {
|
||||
const { cycle, address, payload, enabled } = this.subscriptions[i];
|
||||
if (cycle !== action || !enabled || !address) {
|
||||
continue;
|
||||
}
|
||||
const parsedAddress = parseTemplateNested(address, state || {});
|
||||
const parsedPayload = payload ? parseTemplateNested(payload, state || {}) : undefined;
|
||||
try {
|
||||
this.emit(parsedAddress, parsedPayload);
|
||||
} catch (error) {
|
||||
logger.error(LogOrigin.Tx, `OSC Integration: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
emit(address: string, payload?: ArgumentType) {
|
||||
if (!this.oscClient) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = new Message(address);
|
||||
if (payload) {
|
||||
if (isObject(payload)) {
|
||||
message.append(JSON.stringify(payload));
|
||||
} else {
|
||||
message.append(payload);
|
||||
}
|
||||
}
|
||||
|
||||
this.oscClient.send(message);
|
||||
}
|
||||
|
||||
private initTX(enabledOut: boolean, targetIP: string, portOut: number, subscriptions: OscSubscription[]) {
|
||||
this.initSubscriptions(subscriptions);
|
||||
|
||||
// runtime validation
|
||||
const validateType = typeof targetIP !== 'string' || typeof portOut !== 'number';
|
||||
const validateNull = !targetIP || !portOut;
|
||||
|
||||
if (validateType || validateNull) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Config options incorrect',
|
||||
};
|
||||
if (!enabledOut && this.enabledOut) {
|
||||
this.targetIP = targetIP;
|
||||
this.portOut = portOut;
|
||||
this.enabledOut = enabledOut;
|
||||
this.shutdownTX();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.oscClient && targetIP === this.targetIP && portOut === this.portOut) {
|
||||
// nothing changed that would mean we need a new client
|
||||
return;
|
||||
}
|
||||
|
||||
this.targetIP = targetIP;
|
||||
this.portOut = portOut;
|
||||
this.enabledOut = enabledOut;
|
||||
|
||||
try {
|
||||
// this allows re-calling the init function during runtime
|
||||
this.oscClient?.close();
|
||||
this.oscClient = new Client(targetIP, portOut);
|
||||
return {
|
||||
success: true,
|
||||
message: `OSC integration client connected to ${targetIP}:${portOut}`,
|
||||
};
|
||||
} catch (error) {
|
||||
this.oscClient = null;
|
||||
return {
|
||||
success: false,
|
||||
message: `Failed initialising OSC Client: ${error}`,
|
||||
};
|
||||
throw new Error(`Failed initialising OSC client: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
initSubscriptions(subscriptionOptions: OscSubscription) {
|
||||
if (validateOscSubscriptionObject(subscriptionOptions)) {
|
||||
this.subscriptions = { ...subscriptionOptions };
|
||||
}
|
||||
}
|
||||
|
||||
dispatch(action: Action, state?: object) {
|
||||
if (!this.oscClient) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Client not initialised',
|
||||
};
|
||||
private initRX(enabledIn: boolean, portIn: number) {
|
||||
if (!enabledIn && this.enabledIn) {
|
||||
this.shutdownRX();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!action) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'OSC 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 || {});
|
||||
this.emit(parsedMessage);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
emit(path: string, payload?: ArgumentType) {
|
||||
const message = new Message(path);
|
||||
if (payload) {
|
||||
try {
|
||||
if (isObject(payload)) {
|
||||
message.append(JSON.stringify(payload));
|
||||
} else {
|
||||
message.append(payload);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('OSC ERROR', error, payload);
|
||||
}
|
||||
}
|
||||
|
||||
this.oscClient.send(message, (error) => {
|
||||
if (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: `Error sending message: ${JSON.stringify(error)}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
message: 'OSC Message sent',
|
||||
};
|
||||
});
|
||||
// Start OSC Server
|
||||
logger.info(LogOrigin.Rx, `Starting OSC Server on port: ${portIn}`);
|
||||
this.oscServer = new OscServer(portIn);
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
console.log('Shutting down OSC integration');
|
||||
this.shutdownTX();
|
||||
this.shutdownRX();
|
||||
}
|
||||
|
||||
private shutdownTX() {
|
||||
logger.info(LogOrigin.Rx, 'Shutting down OSC integration');
|
||||
if (this.oscServer) {
|
||||
this.oscServer?.shutdown();
|
||||
this.oscServer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private shutdownRX() {
|
||||
logger.info(LogOrigin.Tx, 'Shutting down OSC integration');
|
||||
if (this.oscClient) {
|
||||
this.oscClient?.close();
|
||||
this.oscClient = null;
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// any value inside double curly braces {{val}}
|
||||
import { formatDisplay } from 'ontime-utils';
|
||||
import { MaybeNumber } from 'ontime-types';
|
||||
import { millisToString, removeLeadingZero } from 'ontime-utils';
|
||||
|
||||
// any value inside double curly braces {{val}}
|
||||
const placeholderRegex = /{{(.*?)}}/g;
|
||||
|
||||
function formatDisplayFromString(value: string, hideZero = false): string {
|
||||
let valueInNumber = null;
|
||||
let valueInNumber: MaybeNumber = null;
|
||||
|
||||
if (value !== 'null') {
|
||||
const parsedValue = Number(value);
|
||||
@@ -12,12 +13,16 @@ function formatDisplayFromString(value: string, hideZero = false): string {
|
||||
valueInNumber = parsedValue;
|
||||
}
|
||||
}
|
||||
return formatDisplay(valueInNumber, hideZero);
|
||||
let formatted = millisToString(valueInNumber, { fallback: hideZero ? '00:00' : '00:00:00' });
|
||||
if (hideZero) {
|
||||
formatted = removeLeadingZero(formatted);
|
||||
}
|
||||
return formatted;
|
||||
}
|
||||
|
||||
type AliasesDefinition = Record<string, { key: string; cb: (value: unknown) => string }>;
|
||||
type AliasesDefinition = Record<string, { key: string; cb: (value: string) => string }>;
|
||||
const quickAliases: AliasesDefinition = {
|
||||
clock: { key: 'timer.clock', cb: (value: string) => formatDisplayFromString(value) },
|
||||
clock: { key: 'clock', cb: (value: string) => formatDisplayFromString(value) },
|
||||
duration: { key: 'timer.duration', cb: (value: string) => formatDisplayFromString(value, true) },
|
||||
expectedEnd: {
|
||||
key: 'timer.expectedFinish',
|
||||
@@ -44,7 +49,7 @@ export function parseTemplateNested(template: string, state: object, humanReadab
|
||||
for (const match of matches) {
|
||||
const variableName = match[1];
|
||||
const variableParts = variableName.split('.');
|
||||
let value = undefined;
|
||||
let value: string | undefined = undefined;
|
||||
|
||||
if (variableParts[0] === 'human') {
|
||||
const lookupKey = variableParts[1];
|
||||
@@ -57,9 +62,9 @@ export function parseTemplateNested(template: string, state: object, humanReadab
|
||||
}
|
||||
} else {
|
||||
// iterate through variable parts, and look for the property in the state object
|
||||
value = variableParts.reduce((obj, key) => obj && obj[key], state);
|
||||
value = variableParts.reduce((obj, key) => obj?.[key], state);
|
||||
}
|
||||
if (typeof value !== 'undefined') {
|
||||
if (value !== undefined) {
|
||||
parsedTemplate = parsedTemplate.replace(match[0], value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
import { Message } from 'ontime-types';
|
||||
import { DeepPartial, Message, TimerMessage, MessageState } from 'ontime-types';
|
||||
|
||||
import { TimerMessage } from 'ontime-types/src/definitions/runtime/MessageControl.type.js';
|
||||
import { throttle } from '../../utils/throttle.js';
|
||||
|
||||
import type { PublishFn } from '../../stores/EventStore.js';
|
||||
|
||||
let instance;
|
||||
let instance: MessageService | null = null;
|
||||
|
||||
class MessageService {
|
||||
timerMessage: TimerMessage;
|
||||
publicMessage: Message;
|
||||
lowerMessage: Message;
|
||||
externalMessage: Message;
|
||||
onAir: boolean;
|
||||
timer: TimerMessage;
|
||||
public: Message;
|
||||
lower: Message;
|
||||
external: Message;
|
||||
|
||||
private throttledSet: PublishFn;
|
||||
private publish: PublishFn | null;
|
||||
@@ -25,165 +23,62 @@ 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.onAir = 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) {
|
||||
this.publish = publish;
|
||||
this.throttledSet = throttle((key, value) => this.publish(key, value), 100);
|
||||
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 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 onAir, toggles if parameters are offered
|
||||
*/
|
||||
setOnAir(status?: boolean) {
|
||||
if (typeof status === 'undefined') {
|
||||
this.onAir = !this.onAir;
|
||||
} else {
|
||||
this.onAir = status;
|
||||
}
|
||||
this.throttledSet('onAir', this.onAir);
|
||||
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,
|
||||
onAir: this.onAir,
|
||||
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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
import { DatabaseModel, GetInfo, ProjectData, ProjectFile, ProjectFileListResponse } from 'ontime-types';
|
||||
|
||||
import { copyFile, rename, stat, writeFile } from 'fs/promises';
|
||||
import { existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { initRundown } from '../rundown-service/RundownService.js';
|
||||
import { DataProvider } from '../../classes/data-provider/DataProvider.js';
|
||||
import { runtimeService } from '../runtime-service/RuntimeService.js';
|
||||
import { getNetworkInterfaces } from '../../utils/networkInterfaces.js';
|
||||
import { resolveProjectsDirectory, resolveStylesPath } from '../../setup/index.js';
|
||||
import { filterProjectFiles, parseProjectFile } from './projectFileUtils.js';
|
||||
import { appStateService } from '../app-state-service/AppStateService.js';
|
||||
import { ensureDirectory, getFilesFromFolder, removeFileExtension } from '../../utils/fileManagement.js';
|
||||
import { dbModel } from '../../models/dataModel.js';
|
||||
import { deleteFile } from '../../utils/parserUtils.js';
|
||||
import { switchDb } from '../../setup/loadDb.js';
|
||||
|
||||
// init dependencies
|
||||
init();
|
||||
|
||||
/**
|
||||
* Ensure services has its dependencies initialized
|
||||
*/
|
||||
function init() {
|
||||
ensureDirectory(resolveProjectsDirectory);
|
||||
}
|
||||
|
||||
type Options = {
|
||||
onlyRundown?: 'true' | 'false';
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles a file from the upload folder and applies its data
|
||||
*/
|
||||
export async function applyProjectFile(name: string, options?: Options) {
|
||||
const filePath = join(resolveProjectsDirectory, name);
|
||||
const data = parseProjectFile(filePath);
|
||||
|
||||
// change LowDB to point to new file
|
||||
await switchDb(name);
|
||||
|
||||
// apply data model
|
||||
await applyDataModel(data, options);
|
||||
|
||||
// persist the project selection
|
||||
await appStateService.updateDatabaseConfig(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a file from upload folder to the projects folder
|
||||
* @param filePath
|
||||
* @param name
|
||||
* @returns
|
||||
*/
|
||||
export async function handleUploadedFile(filePath: string, name: string) {
|
||||
const newFilePath = join(resolveProjectsDirectory, name);
|
||||
await rename(filePath, newFilePath);
|
||||
await deleteFile(filePath);
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asynchronously retrieves and returns an array of project files from the 'uploads' folder.
|
||||
* Each file in the 'uploads' folder is checked, and only those with a '.json' extension are processed.
|
||||
* For each qualifying file, its metadata is retrieved, including filename, creation time, and last modification time.
|
||||
*
|
||||
* @returns {Promise<Array<ProjectFile>>} A promise that resolves to an array of ProjectFile objects,
|
||||
* each representing a file in the 'uploads' folder with its metadata.
|
||||
* The metadata includes the filename, creation or overwriting time (updatedAt)
|
||||
*
|
||||
* @throws {Error} Throws an error if there is an issue in reading the directory or fetching file statistics.
|
||||
*/
|
||||
export async function getProjectFiles(): Promise<ProjectFile[]> {
|
||||
const allFiles = await getFilesFromFolder(resolveProjectsDirectory);
|
||||
const filteredFiles = filterProjectFiles(allFiles);
|
||||
|
||||
const projectFiles: ProjectFile[] = [];
|
||||
for (const file of filteredFiles) {
|
||||
const filePath = join(resolveProjectsDirectory, file);
|
||||
const stats = await stat(filePath);
|
||||
|
||||
projectFiles.push({
|
||||
filename: removeFileExtension(file),
|
||||
updatedAt: stats.mtime.toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
return projectFiles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gathers data related to the project list
|
||||
*/
|
||||
export async function getProjectList(): Promise<ProjectFileListResponse> {
|
||||
const files = await getProjectFiles();
|
||||
const appState = await appStateService.get();
|
||||
const lastLoadedProject = removeFileExtension(appState.lastLoadedProject);
|
||||
|
||||
return {
|
||||
files,
|
||||
lastLoadedProject,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Duplicates an existing project file
|
||||
*/
|
||||
export async function duplicateProjectFile(existingProjectFile: string, newProjectFile: string) {
|
||||
const projectFilePath = join(resolveProjectsDirectory, existingProjectFile);
|
||||
const duplicateProjectFilePath = join(resolveProjectsDirectory, newProjectFile);
|
||||
|
||||
return copyFile(projectFilePath, duplicateProjectFilePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames an existing project file
|
||||
*/
|
||||
export async function renameProjectFile(existingProjectFile: string, newName: string) {
|
||||
const projectFilePath = join(resolveProjectsDirectory, existingProjectFile);
|
||||
const newProjectFilePath = join(resolveProjectsDirectory, newName);
|
||||
|
||||
await rename(projectFilePath, newProjectFilePath);
|
||||
|
||||
// Update the last loaded project config if current loaded project is the one being renamed
|
||||
const { lastLoadedProject } = await appStateService.get();
|
||||
|
||||
if (lastLoadedProject === existingProjectFile) {
|
||||
await appStateService.updateDatabaseConfig(newName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new project file and applies its result
|
||||
*/
|
||||
export async function createProjectFile(filename: string, projectData: ProjectData) {
|
||||
const data = {
|
||||
...dbModel,
|
||||
project: {
|
||||
...dbModel.project,
|
||||
...projectData,
|
||||
},
|
||||
};
|
||||
|
||||
// create new file
|
||||
const newFile = join(resolveProjectsDirectory, filename);
|
||||
await writeFile(newFile, JSON.stringify(data));
|
||||
|
||||
// change LowDB to point to new file
|
||||
await switchDb(filename);
|
||||
|
||||
// apply its data
|
||||
await applyDataModel(data);
|
||||
|
||||
appStateService.updateDatabaseConfig(filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a project file
|
||||
*/
|
||||
export async function deleteProjectFile(filename: string) {
|
||||
const projectFilePath = join(resolveProjectsDirectory, filename);
|
||||
await deleteFile(projectFilePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds business logic to gathering data for the info endpoint
|
||||
*/
|
||||
export async function getInfo(): Promise<GetInfo> {
|
||||
const { version, serverPort } = DataProvider.getSettings();
|
||||
const osc = DataProvider.getOsc();
|
||||
|
||||
// get nif and inject localhost
|
||||
const ni = getNetworkInterfaces();
|
||||
ni.unshift({ name: 'localhost', address: '127.0.0.1' });
|
||||
const cssOverride = resolveStylesPath;
|
||||
|
||||
return {
|
||||
networkInterfaces: ni,
|
||||
version,
|
||||
serverPort,
|
||||
osc,
|
||||
cssOverride,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Business logic for resolving a string
|
||||
*/
|
||||
export function extractPin(value: string | undefined | null, fallback: string | null): string | null {
|
||||
if (value === null) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'undefined') {
|
||||
return fallback;
|
||||
}
|
||||
if (value.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* applies a partial database model
|
||||
*/
|
||||
export async function applyDataModel(data: Partial<DatabaseModel>, _options?: Options) {
|
||||
runtimeService.stop();
|
||||
|
||||
// TODO: allow partial project merge from options
|
||||
const { rundown, customFields, ...rest } = data;
|
||||
const newData = await DataProvider.mergeIntoData(rest);
|
||||
|
||||
if (rundown != null) {
|
||||
initRundown(rundown, customFields ?? {});
|
||||
}
|
||||
|
||||
return newData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a project of a given name exists
|
||||
* @param name
|
||||
*/
|
||||
export function doesProjectExist(name: string): boolean {
|
||||
const projectFilePath = join(resolveProjectsDirectory, name);
|
||||
return existsSync(projectFilePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Validates the existence of project files.
|
||||
* @param {object} projectFiles
|
||||
* @param {string} projectFiles.projectFilename
|
||||
* @param {string} projectFiles.newFilename
|
||||
*
|
||||
* @returns {Promise<Array<string>>} Array of errors
|
||||
*
|
||||
*/
|
||||
export const validateProjectFiles = (projectFiles: { filename?: string; newFilename?: string }): Array<string> => {
|
||||
const errors: string[] = [];
|
||||
|
||||
if (projectFiles.filename) {
|
||||
const projectFilePath = join(resolveProjectsDirectory, projectFiles.filename);
|
||||
|
||||
if (!existsSync(projectFilePath)) {
|
||||
errors.push('Project file does not exist');
|
||||
}
|
||||
}
|
||||
|
||||
if (projectFiles.newFilename) {
|
||||
const projectFilePath = join(resolveProjectsDirectory, projectFiles.newFilename);
|
||||
|
||||
if (existsSync(projectFilePath)) {
|
||||
errors.push('New project file already exists');
|
||||
}
|
||||
}
|
||||
|
||||
return errors;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get current project title or fallback
|
||||
*/
|
||||
export function getProjectTitle(): string {
|
||||
const { title } = DataProvider.getProjectData();
|
||||
return title || 'ontime data';
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { expect, vi } from 'vitest';
|
||||
|
||||
import { getProjectFiles } from '../ProjectService.js';
|
||||
|
||||
vi.mock('fs/promises', () => {
|
||||
const mockFiles = ['file1.json', 'file2.json', 'file3.json', 'document.txt', 'image.png'];
|
||||
const mockStats = {
|
||||
birthtime: new Date('2020-01-01'),
|
||||
mtime: new Date('2021-01-01'),
|
||||
};
|
||||
|
||||
return {
|
||||
readdir: vi.fn().mockResolvedValue(mockFiles),
|
||||
stat: vi.fn().mockResolvedValue(mockStats),
|
||||
};
|
||||
});
|
||||
|
||||
describe('getProjectFiles test', () => {
|
||||
it('should return a list of project .json files', async () => {
|
||||
const { readdir, stat } = await import('fs/promises');
|
||||
|
||||
const result = await getProjectFiles();
|
||||
|
||||
const expectedFiles = ['file1', 'file2', 'file3'].map((file) => ({
|
||||
filename: file,
|
||||
updatedAt: new Date('2021-01-01').toISOString(),
|
||||
}));
|
||||
|
||||
expect(result).toEqual(expectedFiles);
|
||||
expect(readdir).toHaveBeenCalled();
|
||||
expect(stat).toHaveBeenCalledTimes(expectedFiles.length);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { extname } from 'path';
|
||||
|
||||
/**
|
||||
* Given an array of file names, filters out any files that do not have a '.json' extension.
|
||||
* We assume these are project files
|
||||
* @param files
|
||||
* @returns
|
||||
*/
|
||||
export function filterProjectFiles(files: Array<string>): Array<string> {
|
||||
return files.filter((file) => {
|
||||
const ext = extname(file).toLowerCase();
|
||||
return ext === '.json';
|
||||
});
|
||||
}
|
||||
|
||||
export function parseProjectFile(filePath: string): object {
|
||||
if (!filePath.endsWith('.json')) {
|
||||
throw new Error('Invalid file type');
|
||||
}
|
||||
|
||||
const rawdata = readFileSync(filePath, 'utf-8');
|
||||
const uploadedJson = JSON.parse(rawdata);
|
||||
|
||||
// at this point, we think this is a DatabaseModel
|
||||
// verify by looking for the required fields
|
||||
if (uploadedJson?.settings?.app !== 'ontime') {
|
||||
throw new Error('Not a ontime project file');
|
||||
}
|
||||
return uploadedJson;
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
import { OntimeEvent } from 'ontime-types';
|
||||
import { dayInMs } from 'ontime-utils';
|
||||
|
||||
/**
|
||||
* handle events that span over midnight
|
||||
*/
|
||||
export const normaliseEndTime = (start: number, end: number) => (end < start ? end + dayInMs : end);
|
||||
|
||||
/**
|
||||
* @description Sorts an array of objects by given property
|
||||
* @param {array} arr - array to be sorted
|
||||
* @param {string} property - property to compare
|
||||
* @returns {array} copy of array sorted in ascending order
|
||||
*/
|
||||
|
||||
export const sortArrayByProperty = <T>(arr: T[], property: string): T[] => {
|
||||
return [...arr].sort((a, b) => {
|
||||
return a[property] - b[property];
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds loading information given a current rundown and time
|
||||
* @param {OntimeEvent[]} rundown - List of playable events
|
||||
* @param {number} timeNow - time now in ms
|
||||
* @returns {{}}
|
||||
*/
|
||||
export const getRollTimers = (rundown: OntimeEvent[], timeNow: number) => {
|
||||
let nowIndex: number | null = null; // index of event now
|
||||
let nowId: string | null = null; // id of event now
|
||||
let publicIndex: number | null = null; // index of public event now
|
||||
let nextIndex: number | null = null; // index of next event
|
||||
let publicNextIndex: number | null = null; // index of next public event
|
||||
let timeToNext: number | null = null; // counter: time for next event
|
||||
let publicTimeToNext: number | null = null; // counter: time for next public event
|
||||
|
||||
const orderedEvents = sortArrayByProperty(rundown, 'timeStart');
|
||||
const lastEvent = orderedEvents[orderedEvents.length - 1];
|
||||
const lastNormalEnd = normaliseEndTime(lastEvent.timeStart, lastEvent.timeEnd);
|
||||
|
||||
let nextEvent: OntimeEvent | null = null;
|
||||
let nextPublicEvent: OntimeEvent | null = null;
|
||||
let currentEvent: OntimeEvent | null = null;
|
||||
let currentPublicEvent: OntimeEvent | null = null;
|
||||
|
||||
if (timeNow > lastNormalEnd) {
|
||||
// we are past last end
|
||||
// preload first and find next
|
||||
|
||||
const firstEvent = orderedEvents[0];
|
||||
nextIndex = 0;
|
||||
nextEvent = firstEvent;
|
||||
timeToNext = firstEvent.timeStart + dayInMs - timeNow;
|
||||
|
||||
if (firstEvent.isPublic) {
|
||||
nextPublicEvent = firstEvent;
|
||||
publicNextIndex = 0;
|
||||
} else {
|
||||
// look for next public
|
||||
// dev note: we feel that this is more efficient than filtering
|
||||
// since the next event will likely be close to the one playing
|
||||
for (const event of orderedEvents) {
|
||||
if (event.isPublic) {
|
||||
nextPublicEvent = event;
|
||||
// we need the index before this was sorted
|
||||
publicNextIndex = rundown.findIndex((rundownEvent) => rundownEvent.id === event.id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// flags: select first event if several overlapping
|
||||
let nowFound = false;
|
||||
// keep track of the end times when looking for public
|
||||
let publicTime = -1;
|
||||
|
||||
for (const event of orderedEvents) {
|
||||
// When does the event end (handle midnight)
|
||||
const normalEnd = normaliseEndTime(event.timeStart, event.timeEnd);
|
||||
|
||||
const hasNotEnded = normalEnd > timeNow;
|
||||
// TODO: we will likely want a better solution than the modulus here
|
||||
const isFromDayBefore = normalEnd > dayInMs && timeNow < event.timeEnd % dayInMs;
|
||||
const hasStarted = isFromDayBefore || timeNow >= event.timeStart;
|
||||
|
||||
if (normalEnd <= timeNow) {
|
||||
// event ran already
|
||||
|
||||
if (event.isPublic && normalEnd > publicTime) {
|
||||
// public event might not be the one running
|
||||
publicTime = normalEnd;
|
||||
currentPublicEvent = event;
|
||||
publicIndex = rundown.findIndex((rundownEvent) => rundownEvent.id === event.id);
|
||||
}
|
||||
} else if (hasNotEnded && hasStarted && !nowFound) {
|
||||
// event is running
|
||||
currentEvent = event;
|
||||
nowIndex = rundown.findIndex((rundownEvent) => rundownEvent.id === event.id);
|
||||
nowId = event.id;
|
||||
nowFound = true;
|
||||
|
||||
// it could also be public
|
||||
if (event.isPublic) {
|
||||
publicTime = normalEnd;
|
||||
currentPublicEvent = event;
|
||||
publicIndex = rundown.findIndex((rundownEvent) => rundownEvent.id === event.id);
|
||||
}
|
||||
} else if (normalEnd > timeNow) {
|
||||
// event will run
|
||||
|
||||
// we already know whats next and next-public
|
||||
if (nextIndex !== null && publicNextIndex !== null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// look for next events
|
||||
// check how far the start is from now
|
||||
const timeToEventStart = event.timeStart - timeNow;
|
||||
|
||||
// we don't have a next or this one starts sooner than current next
|
||||
if (nextIndex === null || timeToEventStart < timeToNext) {
|
||||
timeToNext = timeToEventStart;
|
||||
nextEvent = event;
|
||||
nextIndex = rundown.findIndex((rundownEvent) => rundownEvent.id === event.id);
|
||||
}
|
||||
|
||||
if (event.isPublic) {
|
||||
// if we don't have a public next or this one start sooner than assigned next
|
||||
if (publicNextIndex === null || timeToEventStart < publicTimeToNext) {
|
||||
publicTimeToNext = timeToEventStart;
|
||||
nextPublicEvent = event;
|
||||
publicNextIndex = rundown.findIndex((rundownEvent) => rundownEvent.id === event.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
nowIndex,
|
||||
nowId,
|
||||
publicIndex,
|
||||
nextIndex,
|
||||
publicNextIndex,
|
||||
timeToNext,
|
||||
nextEvent,
|
||||
nextPublicEvent,
|
||||
currentEvent,
|
||||
currentPublicEvent,
|
||||
};
|
||||
};
|
||||
|
||||
type CurrentTimers = {
|
||||
selectedEventId: string | null;
|
||||
current: number | null;
|
||||
_finishAt: number | null;
|
||||
clock: number | null;
|
||||
secondaryTimer: number | null;
|
||||
secondaryTarget: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* @description Implements update functions for roll mode
|
||||
* @param {CurrentTimers} currentTimers
|
||||
* @returns {object} object with selection variables
|
||||
*/
|
||||
export const updateRoll = (currentTimers: CurrentTimers) => {
|
||||
const { selectedEventId, current, _finishAt, clock, secondaryTimer, secondaryTarget } = currentTimers;
|
||||
|
||||
// timers
|
||||
let updatedTimer = current;
|
||||
let updatedSecondaryTimer = secondaryTimer;
|
||||
// whether rollLoad should be called: force reload of events
|
||||
let doRollLoad = false;
|
||||
// whether finished event should trigger
|
||||
let isPrimaryFinished = false;
|
||||
|
||||
if (selectedEventId && current !== null) {
|
||||
// if we have something selected and a timer, we are running
|
||||
|
||||
updatedTimer = _finishAt - clock;
|
||||
if (updatedTimer > dayInMs) {
|
||||
updatedTimer -= dayInMs;
|
||||
}
|
||||
|
||||
if (updatedTimer < 0) {
|
||||
isPrimaryFinished = true;
|
||||
// we need a new event
|
||||
doRollLoad = true;
|
||||
}
|
||||
} else if (secondaryTimer >= 0) {
|
||||
// if secondaryTimer is running we are in waiting to roll
|
||||
|
||||
updatedSecondaryTimer = secondaryTarget - clock;
|
||||
|
||||
if (updatedSecondaryTimer <= 0) {
|
||||
// we need a new event
|
||||
doRollLoad = true;
|
||||
}
|
||||
}
|
||||
|
||||
return { updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished: isPrimaryFinished };
|
||||
};
|
||||
@@ -1,212 +1,87 @@
|
||||
import {
|
||||
CustomFields,
|
||||
LogOrigin,
|
||||
OntimeBaseEvent,
|
||||
OntimeBlock,
|
||||
OntimeDelay,
|
||||
OntimeEvent,
|
||||
Playback,
|
||||
SupportedEvent,
|
||||
OntimeRundownEntry,
|
||||
isOntimeBlock,
|
||||
isOntimeDelay,
|
||||
isOntimeEvent,
|
||||
OntimeRundown,
|
||||
} from 'ontime-types';
|
||||
import { generateId, getCueCandidate } from 'ontime-utils';
|
||||
import { DataProvider } from '../../classes/data-provider/DataProvider.js';
|
||||
import { getCueCandidate } from 'ontime-utils';
|
||||
|
||||
import { block as blockDef, delay as delayDef } from '../../models/eventsDefinition.js';
|
||||
import { MAX_EVENTS } from '../../settings.js';
|
||||
import { EventLoader, eventLoader } from '../../classes/event-loader/EventLoader.js';
|
||||
import { eventTimer } from '../TimerService.js';
|
||||
import { sendRefetch } from '../../adapters/websocketAux.js';
|
||||
import { runtimeCacheStore } from '../../stores/cachingStore.js';
|
||||
import {
|
||||
cachedAdd,
|
||||
cachedApplyDelay,
|
||||
cachedClear,
|
||||
cachedDelete,
|
||||
cachedEdit,
|
||||
cachedReorder,
|
||||
cachedSwap,
|
||||
delayedRundownCacheKey,
|
||||
} from './delayedRundown.utils.js';
|
||||
import { logger } from '../../classes/Logger.js';
|
||||
import { validateEvent } from '../../utils/parser.js';
|
||||
import { clock } from '../Clock.js';
|
||||
import { createEvent } from '../../utils/parser.js';
|
||||
import { updateRundownData } from '../../stores/runtimeState.js';
|
||||
import { runtimeService } from '../runtime-service/RuntimeService.js';
|
||||
|
||||
/**
|
||||
* Forces rundown to be recalculated
|
||||
* To be used when we know the rundown has changed completely
|
||||
*/
|
||||
export function forceReset() {
|
||||
eventLoader.reset();
|
||||
runtimeCacheStore.invalidate(delayedRundownCacheKey);
|
||||
}
|
||||
import * as cache from './rundownCache.js';
|
||||
import { getPlayableEvents } from './rundownUtils.js';
|
||||
|
||||
/**
|
||||
* Checks if a list of IDs is in the current selection
|
||||
*/
|
||||
const affectedLoaded = (affectedIds: string[]) => {
|
||||
const now = eventLoader.loaded.selectedEventId;
|
||||
const nowPublic = eventLoader.loaded.selectedPublicEventId;
|
||||
const next = eventLoader.loaded.nextEventId;
|
||||
const nextPublic = eventLoader.loaded.nextPublicEventId;
|
||||
return (
|
||||
affectedIds.includes(now) ||
|
||||
affectedIds.includes(nowPublic) ||
|
||||
affectedIds.includes(next) ||
|
||||
affectedIds.includes(nextPublic)
|
||||
);
|
||||
};
|
||||
type PatchWithId = (Partial<OntimeEvent> | Partial<OntimeBlock> | Partial<OntimeDelay>) & { id: string };
|
||||
|
||||
/**
|
||||
* Checks if timer replaces the loaded next
|
||||
*/
|
||||
const isNewNext = () => {
|
||||
const timedEvents = EventLoader.getTimedEvents();
|
||||
const now = eventLoader.loaded.selectedEventId;
|
||||
const next = eventLoader.loaded.nextEventId;
|
||||
type CompleteEntry<T> = T extends Partial<OntimeEvent>
|
||||
? OntimeEvent
|
||||
: T extends Partial<OntimeDelay>
|
||||
? OntimeDelay
|
||||
: T extends Partial<OntimeBlock>
|
||||
? OntimeBlock
|
||||
: never;
|
||||
|
||||
// check whether the index of now and next are consecutive
|
||||
const indexNow = timedEvents.findIndex((event) => event.id === now);
|
||||
const indexNext = timedEvents.findIndex((event) => event.id === next);
|
||||
function generateEvent<T extends Partial<OntimeEvent> | Partial<OntimeDelay> | Partial<OntimeBlock>>(
|
||||
eventData: T,
|
||||
): CompleteEntry<T> {
|
||||
// we discard any UI provided IDs and add our own
|
||||
const id = cache.getUniqueId();
|
||||
|
||||
if (indexNext - indexNow !== 1) {
|
||||
return true;
|
||||
}
|
||||
// iterate through timed events and see if there are public events between nowPublic and nextPublic
|
||||
const nowPublic = eventLoader.loaded.selectedPublicEventId;
|
||||
const nextPublic = eventLoader.loaded.nextPublicEventId;
|
||||
|
||||
let foundNew = false;
|
||||
let isAfter = false;
|
||||
for (const event of timedEvents) {
|
||||
if (!isAfter) {
|
||||
if (event.id === nowPublic) {
|
||||
isAfter = true;
|
||||
}
|
||||
} else {
|
||||
if (event.id === nextPublic) {
|
||||
break;
|
||||
}
|
||||
if (event.isPublic) {
|
||||
foundNew = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isOntimeEvent(eventData)) {
|
||||
return createEvent(eventData, getCueCandidate(cache.getPersistedRundown(), eventData?.after)) as CompleteEntry<T>;
|
||||
}
|
||||
|
||||
return foundNew;
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates timer service when a relevant piece of data changes
|
||||
*/
|
||||
export function updateTimer(affectedIds?: string[]) {
|
||||
const runningEventId = eventLoader.loaded.selectedEventId;
|
||||
const nextEventId = eventLoader.loaded.nextEventId;
|
||||
|
||||
if (runningEventId === null && nextEventId === null) {
|
||||
return false;
|
||||
if (isOntimeDelay(eventData)) {
|
||||
return { ...delayDef, duration: eventData.duration ?? 0, id } as CompleteEntry<T>;
|
||||
}
|
||||
|
||||
// we need to reload in a few scenarios:
|
||||
// 1. we are not confident that changes do not affect running event
|
||||
const safeOption = typeof affectedIds === 'undefined';
|
||||
// 2. the edited event is in memory (now or next) running
|
||||
const eventInMemory = safeOption ? false : affectedLoaded(affectedIds);
|
||||
// 3. the edited event replaces next event
|
||||
const isNext = isNewNext();
|
||||
|
||||
if (safeOption) {
|
||||
eventLoader.reset();
|
||||
const { eventNow } = eventLoader.loadById(runningEventId) || {};
|
||||
eventTimer.hotReload(eventNow);
|
||||
return true;
|
||||
if (isOntimeBlock(eventData)) {
|
||||
return { ...blockDef, title: eventData?.title ?? '', id } as CompleteEntry<T>;
|
||||
}
|
||||
|
||||
if (eventInMemory) {
|
||||
eventLoader.reset();
|
||||
|
||||
if (eventTimer.playback === Playback.Roll) {
|
||||
const rollTimers = eventLoader.findRoll(clock.timeNow());
|
||||
if (rollTimers === null) {
|
||||
eventTimer.stop();
|
||||
} else {
|
||||
const { currentEvent, nextEvent } = rollTimers;
|
||||
eventTimer.roll(currentEvent, nextEvent);
|
||||
}
|
||||
} else {
|
||||
const { eventNow } = eventLoader.loadById(runningEventId) || {};
|
||||
if (eventNow) {
|
||||
eventTimer.hotReload(eventNow);
|
||||
} else {
|
||||
eventTimer.stop();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isNext) {
|
||||
const { eventNow } = eventLoader.loadById(runningEventId) || {};
|
||||
eventTimer.hotReload(eventNow);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
throw new Error('Invalid event type');
|
||||
}
|
||||
|
||||
/**
|
||||
* @description creates a new event with given data
|
||||
* @param {object} eventData
|
||||
* @return {unknown[]}
|
||||
* @return {OntimeRundownEntry}
|
||||
*/
|
||||
export async function addEvent(eventData: Partial<OntimeEvent> | Partial<OntimeDelay> | Partial<OntimeBlock>) {
|
||||
const numEvents = DataProvider.getRundownLength();
|
||||
if (numEvents > MAX_EVENTS) {
|
||||
throw new Error(`Reached limit number of ${MAX_EVENTS} events`);
|
||||
}
|
||||
|
||||
let newEvent: Partial<OntimeBaseEvent> = {};
|
||||
const id = generateId();
|
||||
|
||||
let insertIndex = 0;
|
||||
export async function addEvent(eventData: PatchWithId & { after?: string }): Promise<OntimeRundownEntry> {
|
||||
// if the user didnt provide an index, we add the event to start
|
||||
let atIndex = 0;
|
||||
if (eventData?.after !== undefined) {
|
||||
const index = DataProvider.getIndexOf(eventData.after);
|
||||
if (index < 0) {
|
||||
const previousIndex = cache.getIndexOf(eventData.after);
|
||||
if (previousIndex < 0) {
|
||||
logger.warning(LogOrigin.Server, `Could not find event with id ${eventData.after}`);
|
||||
} else {
|
||||
insertIndex = index + 1;
|
||||
atIndex = previousIndex + 1;
|
||||
}
|
||||
}
|
||||
|
||||
switch (eventData.type) {
|
||||
case SupportedEvent.Event: {
|
||||
newEvent = validateEvent(eventData, getCueCandidate(DataProvider.getRundown(), eventData?.after)) as OntimeEvent;
|
||||
break;
|
||||
}
|
||||
case SupportedEvent.Delay:
|
||||
newEvent = { ...delayDef, duration: eventData.duration, id } as OntimeDelay;
|
||||
break;
|
||||
case SupportedEvent.Block:
|
||||
newEvent = { ...blockDef, title: eventData.title, id } as OntimeBlock;
|
||||
break;
|
||||
}
|
||||
delete eventData.after;
|
||||
// generate a fully formed event from the patch
|
||||
const eventToAdd = generateEvent(eventData);
|
||||
|
||||
// modify rundown
|
||||
await cachedAdd(insertIndex, newEvent as OntimeEvent | OntimeDelay | OntimeBlock);
|
||||
const scopedMutation = cache.mutateCache(cache.add);
|
||||
const { newEvent } = await scopedMutation({ atIndex, event: eventToAdd });
|
||||
|
||||
notifyChanges({ timer: [id], external: true });
|
||||
// notify runtime that rundown has changed
|
||||
updateRuntimeOnChange();
|
||||
|
||||
// notify event loader that rundown size has changed
|
||||
updateChangeNumEvents();
|
||||
|
||||
return newEvent;
|
||||
}
|
||||
|
||||
export async function editEvent(eventData: Partial<OntimeEvent> | Partial<OntimeBlock> | Partial<OntimeDelay>) {
|
||||
if (eventData.type === SupportedEvent.Event && eventData?.cue === '') {
|
||||
throw new Error('Cue value invalid');
|
||||
}
|
||||
|
||||
const newEvent = await cachedEdit(eventData.id, eventData);
|
||||
|
||||
notifyChanges({ timer: [newEvent.id], external: true });
|
||||
// notify timer and external services of change
|
||||
notifyChanges({ timer: [eventData.id], external: true });
|
||||
|
||||
return newEvent;
|
||||
}
|
||||
@@ -214,24 +89,76 @@ export async function editEvent(eventData: Partial<OntimeEvent> | Partial<Ontime
|
||||
/**
|
||||
* deletes event by its ID
|
||||
* @param eventId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function deleteEvent(eventId) {
|
||||
await cachedDelete(eventId);
|
||||
export async function deleteEvent(eventId: string) {
|
||||
const scopedMutation = cache.mutateCache(cache.remove);
|
||||
const { didMutate } = await scopedMutation({ eventId });
|
||||
|
||||
if (didMutate === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
// notify runtime that rundown has changed
|
||||
updateRuntimeOnChange();
|
||||
|
||||
// notify timer and external services of change
|
||||
notifyChanges({ timer: [eventId], external: true });
|
||||
// notify event loader that rundown size has changed
|
||||
updateChangeNumEvents();
|
||||
}
|
||||
|
||||
/**
|
||||
* deletes all events in database
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function deleteAllEvents() {
|
||||
await cachedClear();
|
||||
const scopedMutation = cache.mutateCache(cache.removeAll);
|
||||
await scopedMutation({});
|
||||
|
||||
notifyChanges({ timer: true, external: true, reset: true });
|
||||
// notify event loader that rundown has changed
|
||||
updateRuntimeOnChange();
|
||||
|
||||
// notify timer and external services of change
|
||||
notifyChanges({ timer: true, external: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply patch to an element in rundown
|
||||
* @param patch
|
||||
*/
|
||||
export async function editEvent(patch: PatchWithId) {
|
||||
if (isOntimeEvent(patch) && patch?.cue === '') {
|
||||
throw new Error('Cue value invalid');
|
||||
}
|
||||
|
||||
const scopedMutation = cache.mutateCache(cache.edit);
|
||||
const { newEvent, didMutate } = await scopedMutation({ patch, eventId: patch.id });
|
||||
|
||||
// short circuit if nothing changed
|
||||
if (didMutate === false) {
|
||||
return newEvent;
|
||||
}
|
||||
|
||||
// notify runtime that rundown has changed
|
||||
updateRuntimeOnChange();
|
||||
|
||||
// notify timer and external services of change
|
||||
notifyChanges({ timer: [patch.id], external: true });
|
||||
|
||||
return newEvent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a patch to several elements in a rundown
|
||||
* @param ids
|
||||
* @param data
|
||||
*/
|
||||
export async function batchEditEvents(ids: string[], data: Partial<OntimeEvent>) {
|
||||
const scopedMutation = cache.mutateCache(cache.batchEdit);
|
||||
await scopedMutation({ patch: data, eventIds: ids });
|
||||
|
||||
// notify runtime that rundown has changed
|
||||
updateRuntimeOnChange();
|
||||
|
||||
// notify timer and external services of change
|
||||
notifyChanges({ timer: ids, external: true });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -239,19 +166,28 @@ export async function deleteAllEvents() {
|
||||
* @param {string} eventId - ID of event from, for sanity check
|
||||
* @param {number} from - index of event from
|
||||
* @param {number} to - index of event to
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function reorderEvent(eventId: string, from: number, to: number) {
|
||||
const reorderedItem = await cachedReorder(eventId, from, to);
|
||||
const scopedMutation = cache.mutateCache(cache.reorder);
|
||||
const reorderedItem = await scopedMutation({ eventId, from, to });
|
||||
|
||||
// notify runtime that rundown has changed
|
||||
updateRuntimeOnChange();
|
||||
|
||||
// notify timer and external services of change
|
||||
notifyChanges({ timer: true, external: true });
|
||||
|
||||
return reorderedItem;
|
||||
}
|
||||
|
||||
export async function applyDelay(eventId: string) {
|
||||
await cachedApplyDelay(eventId);
|
||||
const scopedMutation = cache.mutateCache(cache.applyDelay);
|
||||
await scopedMutation({ eventId });
|
||||
|
||||
// notify runtime that rundown has changed
|
||||
updateRuntimeOnChange();
|
||||
|
||||
// notify timer and external services of change
|
||||
notifyChanges({ timer: true, external: true });
|
||||
}
|
||||
|
||||
@@ -262,8 +198,13 @@ export async function applyDelay(eventId: string) {
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function swapEvents(from: string, to: string) {
|
||||
await cachedSwap(from, to);
|
||||
const scopedMutation = cache.mutateCache(cache.swap);
|
||||
await scopedMutation({ fromId: from, toId: to });
|
||||
|
||||
// notify runtime that rundown has changed
|
||||
updateRuntimeOnChange();
|
||||
|
||||
// notify timer and external services of change
|
||||
notifyChanges({ timer: true, external: true });
|
||||
}
|
||||
|
||||
@@ -271,25 +212,35 @@ export async function swapEvents(from: string, to: string) {
|
||||
* Forces update in the store
|
||||
* Called when we make changes to the rundown object
|
||||
*/
|
||||
function updateChangeNumEvents() {
|
||||
eventLoader.updateNumEvents();
|
||||
function updateRuntimeOnChange() {
|
||||
const playableEvents = getPlayableEvents();
|
||||
const numEvents = playableEvents.length;
|
||||
const metadata = cache.getMetadata();
|
||||
|
||||
// schedule an update for the end of the event loop
|
||||
setImmediate(() =>
|
||||
updateRundownData({
|
||||
numEvents,
|
||||
...metadata,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify services of changes in the rundown
|
||||
*/
|
||||
export function notifyChanges(options: { timer?: boolean | string[]; external?: boolean; reset?: boolean }) {
|
||||
function notifyChanges(options: { timer?: boolean | string[]; external?: boolean }) {
|
||||
if (options.timer) {
|
||||
// notify timer service of changed events
|
||||
if (Array.isArray(options.timer)) {
|
||||
updateTimer(options.timer);
|
||||
}
|
||||
updateTimer();
|
||||
}
|
||||
const playableEvents = getPlayableEvents();
|
||||
|
||||
if (options.reset) {
|
||||
// force rundown to be recalculated
|
||||
forceReset();
|
||||
if (playableEvents.length === 0) {
|
||||
runtimeService.stop();
|
||||
} else {
|
||||
// notify timer service of changed events
|
||||
// timer can be true or an array of changed IDs
|
||||
const affected = Array.isArray(options.timer) ? options.timer : undefined;
|
||||
runtimeService.maybeUpdate(playableEvents, affected);
|
||||
}
|
||||
}
|
||||
|
||||
if (options.external) {
|
||||
@@ -297,3 +248,17 @@ export function notifyChanges(options: { timer?: boolean | string[]; external?:
|
||||
sendRefetch();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides the rundown with the given
|
||||
* @param rundown
|
||||
*/
|
||||
export async function initRundown(rundown: Readonly<OntimeRundown>, customFields: Readonly<CustomFields>) {
|
||||
await cache.init(rundown, customFields);
|
||||
|
||||
// notify runtime that rundown has changed
|
||||
updateRuntimeOnChange();
|
||||
|
||||
// notify timer of change
|
||||
notifyChanges({ timer: true });
|
||||
}
|
||||
|
||||
+8
-8
@@ -1,7 +1,7 @@
|
||||
import { OntimeBlock, OntimeDelay, OntimeEvent, OntimeRundown, SupportedEvent } from 'ontime-types';
|
||||
import { _applyDelay } from '../delayUtils.js';
|
||||
import { apply } from '../delayUtils.js';
|
||||
|
||||
describe('_applyDelay() ', () => {
|
||||
describe('apply() ', () => {
|
||||
describe('in a rundown without the delay field, persisted rundown', () => {
|
||||
it('applies delays', () => {
|
||||
const delayId = '1';
|
||||
@@ -20,7 +20,7 @@ describe('_applyDelay() ', () => {
|
||||
{ id: '5', type: SupportedEvent.Event, timeStart: 0, timeEnd: 10, duration: 10, revision: 1 } as OntimeEvent,
|
||||
];
|
||||
|
||||
const updatedRundown = _applyDelay(delayId, testRundown);
|
||||
const updatedRundown = apply(delayId, testRundown);
|
||||
expect(updatedRundown).toStrictEqual(expected);
|
||||
});
|
||||
it('applies negative delays', () => {
|
||||
@@ -40,7 +40,7 @@ describe('_applyDelay() ', () => {
|
||||
{ id: '5', type: SupportedEvent.Event, timeStart: 0, timeEnd: 10, duration: 10, revision: 1 } as OntimeEvent,
|
||||
];
|
||||
|
||||
const updatedRundown = _applyDelay(delayId, testRundown);
|
||||
const updatedRundown = apply(delayId, testRundown);
|
||||
expect(updatedRundown).toStrictEqual(expected);
|
||||
});
|
||||
it('maintains constant duration', () => {
|
||||
@@ -56,7 +56,7 @@ describe('_applyDelay() ', () => {
|
||||
{ id: '3', type: SupportedEvent.Event, timeStart: 0, timeEnd: 20, duration: 20, revision: 2 } as OntimeEvent,
|
||||
];
|
||||
|
||||
const updatedRundown = _applyDelay(delayId, testRundown);
|
||||
const updatedRundown = apply(delayId, testRundown);
|
||||
expect(updatedRundown).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
@@ -126,7 +126,7 @@ describe('_applyDelay() ', () => {
|
||||
} as OntimeEvent,
|
||||
];
|
||||
|
||||
const updatedRundown = _applyDelay(delayId, testRundown);
|
||||
const updatedRundown = apply(delayId, testRundown);
|
||||
expect(updatedRundown).toStrictEqual(expected);
|
||||
});
|
||||
it('applies negative delays', () => {
|
||||
@@ -194,7 +194,7 @@ describe('_applyDelay() ', () => {
|
||||
} as OntimeEvent,
|
||||
];
|
||||
|
||||
const updatedRundown = _applyDelay(delayId, testRundown);
|
||||
const updatedRundown = apply(delayId, testRundown);
|
||||
expect(updatedRundown).toStrictEqual(expected);
|
||||
});
|
||||
it('maintains constant duration', () => {
|
||||
@@ -242,7 +242,7 @@ describe('_applyDelay() ', () => {
|
||||
} as OntimeEvent,
|
||||
];
|
||||
|
||||
const updatedRundown = _applyDelay(delayId, testRundown);
|
||||
const updatedRundown = apply(delayId, testRundown);
|
||||
expect(updatedRundown).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
@@ -1,457 +0,0 @@
|
||||
import { EndAction, OntimeEvent, OntimeRundown, SupportedEvent, TimerType } from 'ontime-types';
|
||||
|
||||
import { calculateRuntimeDelays, calculateRuntimeDelaysFrom, getDelayAt } from '../delayedRundown.utils.js';
|
||||
|
||||
describe('calculateRuntimeDelays', () => {
|
||||
it('calculates all delays in a given rundown', () => {
|
||||
const rundown: OntimeRundown = [
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: '659e1',
|
||||
cue: '1',
|
||||
},
|
||||
{
|
||||
duration: 600000,
|
||||
type: SupportedEvent.Delay,
|
||||
revision: 0,
|
||||
id: '07986',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1200000,
|
||||
duration: 0,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: '1c48f',
|
||||
cue: '2',
|
||||
},
|
||||
{
|
||||
duration: 1200000,
|
||||
type: SupportedEvent.Delay,
|
||||
revision: 0,
|
||||
id: '7db42',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: 'd48c2',
|
||||
cue: '3',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
type: SupportedEvent.Block,
|
||||
id: '9870d',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1800000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: '2f185',
|
||||
cue: '4',
|
||||
},
|
||||
];
|
||||
|
||||
const updatedRundown = calculateRuntimeDelays(rundown);
|
||||
|
||||
expect(rundown.length).toBe(updatedRundown.length);
|
||||
expect((updatedRundown[0] as OntimeEvent).delay).toBe(0);
|
||||
expect((updatedRundown[2] as OntimeEvent).delay).toBe(600000);
|
||||
expect((updatedRundown[4] as OntimeEvent).delay).toBe(600000 + 1200000);
|
||||
expect((updatedRundown[6] as OntimeEvent).delay).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDelayAt()', () => {
|
||||
const delayedRundown: OntimeRundown = [
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: '659e1',
|
||||
delay: 0,
|
||||
cue: '1',
|
||||
},
|
||||
{
|
||||
duration: 600000,
|
||||
type: SupportedEvent.Delay,
|
||||
revision: 0,
|
||||
id: '07986',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1200000,
|
||||
duration: 0,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: '1c48f',
|
||||
delay: 600000,
|
||||
cue: '2',
|
||||
},
|
||||
{
|
||||
duration: 1200000,
|
||||
type: SupportedEvent.Delay,
|
||||
revision: 0,
|
||||
id: '7db42',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: 'd48c2',
|
||||
delay: 1800000,
|
||||
cue: '3',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
type: SupportedEvent.Block,
|
||||
id: '9870d',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1800000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: '2f185',
|
||||
delay: 0,
|
||||
cue: '4',
|
||||
},
|
||||
];
|
||||
|
||||
it('calculates delay in a rundown', () => {
|
||||
const delayAtStart = getDelayAt(0, delayedRundown);
|
||||
const delayOnFirstEvent = getDelayAt(2, delayedRundown);
|
||||
const delayOnSecondEvent = getDelayAt(4, delayedRundown);
|
||||
const delayOnBlockedEvent = getDelayAt(0, delayedRundown);
|
||||
|
||||
expect(delayAtStart).toBe(0);
|
||||
expect(delayOnFirstEvent).toBe(600000);
|
||||
expect(delayOnSecondEvent).toBe(600000 + 1200000);
|
||||
expect(delayOnBlockedEvent).toBe(0);
|
||||
});
|
||||
it('finds delay before a delay block', () => {
|
||||
const valueOnFirstDelayBlock = getDelayAt(1, delayedRundown);
|
||||
const valueOnSecondDelayBlock = getDelayAt(3, delayedRundown);
|
||||
const valueAfterSecondDelayBlock = getDelayAt(4, delayedRundown);
|
||||
|
||||
expect(valueOnFirstDelayBlock).toBe(0);
|
||||
expect(valueOnSecondDelayBlock).toBe(600000);
|
||||
expect(valueAfterSecondDelayBlock).toBe(600000 + 1200000);
|
||||
});
|
||||
it('returns 0 after blocks', () => {
|
||||
const valueOnBlock = getDelayAt(6, delayedRundown);
|
||||
expect(valueOnBlock).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('calculateRuntimeDelaysFrom()', () => {
|
||||
it('updates delays from given id', () => {
|
||||
const delayedRundown: OntimeRundown = [
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: '659e1',
|
||||
delay: 0,
|
||||
cue: '1',
|
||||
},
|
||||
{
|
||||
duration: 600000,
|
||||
type: SupportedEvent.Delay,
|
||||
revision: 0,
|
||||
id: '07986',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1200000,
|
||||
duration: 0,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: '1c48f',
|
||||
delay: 0,
|
||||
cue: '2',
|
||||
},
|
||||
{
|
||||
duration: 1200000,
|
||||
type: SupportedEvent.Delay,
|
||||
revision: 0,
|
||||
id: '7db42',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: 'd48c2',
|
||||
delay: 1800000,
|
||||
cue: '3',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
type: SupportedEvent.Block,
|
||||
id: '9870d',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
subtitle: '',
|
||||
presenter: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1800000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
user0: '',
|
||||
user1: '',
|
||||
user2: '',
|
||||
user3: '',
|
||||
user4: '',
|
||||
user5: '',
|
||||
user6: '',
|
||||
user7: '',
|
||||
user8: '',
|
||||
user9: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
id: '2f185',
|
||||
delay: 0,
|
||||
cue: '4',
|
||||
},
|
||||
];
|
||||
|
||||
const updatedRundown = calculateRuntimeDelaysFrom('07986', delayedRundown);
|
||||
|
||||
// we only update from the 4th on
|
||||
expect((updatedRundown[0] as OntimeEvent).delay).toBe(0);
|
||||
// 1 + 3
|
||||
expect((updatedRundown[4] as OntimeEvent).delay).toBe(600000 + 1200000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,893 @@
|
||||
import {
|
||||
CustomFields,
|
||||
EndAction,
|
||||
EventCustomFields,
|
||||
OntimeBlock,
|
||||
OntimeDelay,
|
||||
OntimeEvent,
|
||||
OntimeRundown,
|
||||
SupportedEvent,
|
||||
TimeStrategy,
|
||||
TimerType,
|
||||
} from 'ontime-types';
|
||||
import { MILLIS_PER_HOUR, dayInMs, millisToString } from 'ontime-utils';
|
||||
|
||||
import { calculateRuntimeDelays, getDelayAt, calculateRuntimeDelaysFrom } from '../delayUtils.js';
|
||||
import {
|
||||
add,
|
||||
batchEdit,
|
||||
edit,
|
||||
generate,
|
||||
remove,
|
||||
reorder,
|
||||
swap,
|
||||
createCustomField,
|
||||
editCustomField,
|
||||
removeCustomField,
|
||||
} from '../rundownCache.js';
|
||||
|
||||
describe('generate()', () => {
|
||||
it('creates normalised versions of a given rundown', () => {
|
||||
const testRundown: OntimeRundown = [
|
||||
{ type: SupportedEvent.Event, id: '1' } as OntimeEvent,
|
||||
{ type: SupportedEvent.Block, id: '2' } as OntimeBlock,
|
||||
{ type: SupportedEvent.Delay, id: '3' } as OntimeDelay,
|
||||
];
|
||||
|
||||
const initResult = generate(testRundown);
|
||||
expect(initResult.order.length).toBe(3);
|
||||
expect(initResult.order).toStrictEqual(['1', '2', '3']);
|
||||
expect(initResult.rundown['1'].type).toBe(SupportedEvent.Event);
|
||||
expect(initResult.rundown['2'].type).toBe(SupportedEvent.Block);
|
||||
expect(initResult.rundown['3'].type).toBe(SupportedEvent.Delay);
|
||||
});
|
||||
|
||||
it('calculates delays versions of a given rundown', () => {
|
||||
const testRundown: OntimeRundown = [
|
||||
{ type: SupportedEvent.Delay, id: '1', duration: 100 } as OntimeDelay,
|
||||
{ type: SupportedEvent.Event, id: '2', timeStart: 1, timeEnd: 100 } as OntimeEvent,
|
||||
];
|
||||
|
||||
const initResult = generate(testRundown);
|
||||
expect(initResult.order.length).toBe(2);
|
||||
expect((initResult.rundown['2'] as OntimeEvent).delay).toBe(100);
|
||||
expect(initResult.totalDelay).toBe(100);
|
||||
});
|
||||
|
||||
it('accounts for gaps in rundown when calculating delays', () => {
|
||||
const testRundown: OntimeRundown = [
|
||||
{ type: SupportedEvent.Event, id: '1', timeStart: 100, timeEnd: 200 } as OntimeEvent,
|
||||
{ type: SupportedEvent.Delay, id: 'delay', duration: 200 } as OntimeDelay,
|
||||
{ type: SupportedEvent.Event, id: '2', timeStart: 200, timeEnd: 300 } as OntimeEvent,
|
||||
{ type: SupportedEvent.Block, id: 'block', title: 'break' } as OntimeBlock,
|
||||
{ type: SupportedEvent.Event, id: '3', timeStart: 400, timeEnd: 500 } as OntimeEvent,
|
||||
{ type: SupportedEvent.Block, id: 'another-block', title: 'another-break' } as OntimeBlock,
|
||||
{ type: SupportedEvent.Event, id: '4', timeStart: 600, timeEnd: 700 } as OntimeEvent,
|
||||
];
|
||||
|
||||
const initResult = generate(testRundown);
|
||||
expect(initResult.order.length).toBe(7);
|
||||
expect((initResult.rundown['1'] as OntimeEvent).delay).toBe(0);
|
||||
expect((initResult.rundown['2'] as OntimeEvent).delay).toBe(200);
|
||||
expect((initResult.rundown['3'] as OntimeEvent).delay).toBe(100);
|
||||
expect((initResult.rundown['4'] as OntimeEvent).delay).toBe(0);
|
||||
expect(initResult.totalDelay).toBe(0);
|
||||
expect(initResult.totalDuration).toBe(700 - 100);
|
||||
});
|
||||
|
||||
it('handles negative delays', () => {
|
||||
const testRundown: OntimeRundown = [
|
||||
{ type: SupportedEvent.Event, id: '1', timeStart: 100, timeEnd: 200 } as OntimeEvent,
|
||||
{ type: SupportedEvent.Delay, id: 'delay', duration: -200 } as OntimeDelay,
|
||||
{ type: SupportedEvent.Event, id: '2', timeStart: 200, timeEnd: 300 } as OntimeEvent,
|
||||
{ type: SupportedEvent.Block, id: 'block', title: 'break' } as OntimeBlock,
|
||||
{ type: SupportedEvent.Event, id: '3', timeStart: 400, timeEnd: 500 } as OntimeEvent,
|
||||
{ type: SupportedEvent.Block, id: 'another-block', title: 'another-break' } as OntimeBlock,
|
||||
{ type: SupportedEvent.Event, id: '4', timeStart: 600, timeEnd: 700 } as OntimeEvent,
|
||||
];
|
||||
|
||||
const initResult = generate(testRundown);
|
||||
expect(initResult.order.length).toBe(7);
|
||||
expect((initResult.rundown['1'] as OntimeEvent).delay).toBe(0);
|
||||
expect((initResult.rundown['2'] as OntimeEvent).delay).toBe(-200);
|
||||
expect((initResult.rundown['3'] as OntimeEvent).delay).toBe(-200);
|
||||
expect((initResult.rundown['4'] as OntimeEvent).delay).toBe(-200);
|
||||
expect(initResult.totalDelay).toBe(-200);
|
||||
expect(initResult.totalDuration).toBe(700 - 100);
|
||||
});
|
||||
|
||||
it('links times across events', () => {
|
||||
const testRundown: OntimeRundown = [
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '1',
|
||||
timeStart: 1,
|
||||
duration: 1,
|
||||
timeEnd: 2,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
} as OntimeEvent,
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '2',
|
||||
timeStart: 11,
|
||||
duration: 1,
|
||||
timeEnd: 12,
|
||||
linkStart: '1',
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
} as OntimeEvent,
|
||||
{ type: SupportedEvent.Block, id: 'block' } as OntimeBlock,
|
||||
{ type: SupportedEvent.Delay, id: 'delay' } as OntimeDelay,
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '3',
|
||||
timeStart: 21,
|
||||
duration: 1,
|
||||
timeEnd: 22,
|
||||
linkStart: '2',
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
} as OntimeEvent,
|
||||
];
|
||||
|
||||
const initResult = generate(testRundown);
|
||||
expect(initResult.order.length).toBe(5);
|
||||
expect((initResult.rundown['2'] as OntimeEvent).timeStart).toBe(2);
|
||||
expect((initResult.rundown['2'] as OntimeEvent).timeEnd).toBe(12);
|
||||
expect((initResult.rundown['2'] as OntimeEvent).duration).toBe(10);
|
||||
|
||||
expect((initResult.rundown['3'] as OntimeEvent).timeStart).toBe(12);
|
||||
expect((initResult.rundown['3'] as OntimeEvent).timeEnd).toBe(22);
|
||||
expect((initResult.rundown['3'] as OntimeEvent).duration).toBe(10);
|
||||
|
||||
expect(initResult.links['1']).toBe('2');
|
||||
expect(initResult.links['2']).toBe('3');
|
||||
});
|
||||
|
||||
it('links times across events, reordered', () => {
|
||||
const testRundown: OntimeRundown = [
|
||||
{ type: SupportedEvent.Event, id: '1', timeStart: 1, timeEnd: 2 } as OntimeEvent,
|
||||
{ type: SupportedEvent.Event, id: '3', timeStart: 21, timeEnd: 22, linkStart: '2' } as OntimeEvent,
|
||||
{ type: SupportedEvent.Event, id: '2', timeStart: 11, timeEnd: 12, linkStart: '1' } as OntimeEvent,
|
||||
];
|
||||
|
||||
const initResult = generate(testRundown);
|
||||
expect(initResult.order.length).toBe(3);
|
||||
expect((initResult.rundown['3'] as OntimeEvent).timeStart).toBe(2);
|
||||
expect(initResult.links['1']).toBe('3');
|
||||
expect(initResult.links['3']).toBe('2');
|
||||
});
|
||||
|
||||
it('calculates total duration', () => {
|
||||
const testRundown: OntimeRundown = [
|
||||
{ type: SupportedEvent.Event, id: '1', timeStart: 100, timeEnd: 200 } as OntimeEvent,
|
||||
{ type: SupportedEvent.Event, id: '2', timeStart: 200, timeEnd: 300 } as OntimeEvent,
|
||||
{ type: SupportedEvent.Event, id: '3', timeStart: 300, timeEnd: 400 } as OntimeEvent,
|
||||
];
|
||||
|
||||
const initResult = generate(testRundown);
|
||||
expect(initResult.order.length).toBe(3);
|
||||
expect(initResult.totalDuration).toBe(400 - 100);
|
||||
});
|
||||
|
||||
it('calculates total duration across days with gap', () => {
|
||||
const testRundown: OntimeRundown = [
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '1',
|
||||
timeStart: new Date(0).setHours(9),
|
||||
timeEnd: new Date(0).setHours(23),
|
||||
} as OntimeEvent,
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '2',
|
||||
timeStart: new Date(0).setHours(9),
|
||||
timeEnd: new Date(0).setHours(23),
|
||||
} as OntimeEvent,
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '3',
|
||||
timeStart: new Date(0).setHours(9),
|
||||
timeEnd: new Date(0).setHours(23),
|
||||
} as OntimeEvent,
|
||||
];
|
||||
|
||||
const initResult = generate(testRundown);
|
||||
const expectedDuration = (23 - 9 + 48) * MILLIS_PER_HOUR;
|
||||
expect(millisToString(initResult.totalDuration)).toBe('62:00:00');
|
||||
expect(initResult.totalDuration).toBe(expectedDuration);
|
||||
});
|
||||
|
||||
it('calculates total duration across days', () => {
|
||||
const testRundown: OntimeRundown = [
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '1',
|
||||
timeStart: new Date(0).setHours(12),
|
||||
timeEnd: new Date(0).setHours(22),
|
||||
} as OntimeEvent,
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '2',
|
||||
timeStart: new Date(0).setHours(22),
|
||||
timeEnd: new Date(0).setHours(8),
|
||||
} as OntimeEvent,
|
||||
];
|
||||
|
||||
const initResult = generate(testRundown);
|
||||
const expectedDuration = 8 * MILLIS_PER_HOUR + (dayInMs - 12 * MILLIS_PER_HOUR);
|
||||
expect(millisToString(initResult.totalDuration)).toBe('20:00:00');
|
||||
expect(initResult.totalDuration).toBe(expectedDuration);
|
||||
});
|
||||
|
||||
it('handles updating event sequence', () => {
|
||||
const testRundown: OntimeRundown = [
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '97cc3e',
|
||||
timeStart: 0,
|
||||
timeEnd: 600000,
|
||||
duration: 600000,
|
||||
timeStrategy: TimeStrategy.LockDuration,
|
||||
linkStart: null,
|
||||
} as OntimeEvent,
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: 'e01948',
|
||||
timeStart: 600000,
|
||||
timeEnd: 601000,
|
||||
duration: 85801000, // <------------- value out of sync
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: '97cc3e',
|
||||
} as OntimeEvent,
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '25c1af',
|
||||
timeStart: 100, // <------------- value out of sync
|
||||
timeEnd: 602000,
|
||||
duration: 0,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: 'e01948',
|
||||
} as OntimeEvent,
|
||||
];
|
||||
|
||||
const initResult = generate(testRundown);
|
||||
expect(initResult.rundown).toMatchObject({
|
||||
'97cc3e': {
|
||||
timeStart: 0,
|
||||
timeEnd: 600000,
|
||||
duration: 600000,
|
||||
timeStrategy: 'lock-duration',
|
||||
linkStart: null,
|
||||
},
|
||||
e01948: {
|
||||
timeStart: 600000,
|
||||
timeEnd: 601000,
|
||||
duration: 1000,
|
||||
timeStrategy: 'lock-end',
|
||||
linkStart: '97cc3e',
|
||||
},
|
||||
'25c1af': {
|
||||
timeStart: 601000,
|
||||
timeEnd: 602000,
|
||||
duration: 1000,
|
||||
timeStrategy: 'lock-end',
|
||||
linkStart: 'e01948',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes links if invalid', () => {
|
||||
const testRundown: OntimeRundown = [
|
||||
{ type: SupportedEvent.Event, id: '1', timeStart: 1, linkStart: '10' } as OntimeEvent,
|
||||
];
|
||||
const initResult = generate(testRundown);
|
||||
expect(initResult.order.length).toBe(1);
|
||||
expect((initResult.rundown['1'] as OntimeEvent).timeStart).toBe(1);
|
||||
expect(Object.keys(initResult.links).length).toBe(0);
|
||||
});
|
||||
|
||||
describe('custom properties feature', () => {
|
||||
it('creates a map of custom properties', () => {
|
||||
const customProperties: CustomFields = {
|
||||
lighting: {
|
||||
label: 'lighting',
|
||||
type: 'string',
|
||||
colour: 'red',
|
||||
},
|
||||
sound: {
|
||||
label: 'sound',
|
||||
type: 'string',
|
||||
colour: 'red',
|
||||
},
|
||||
};
|
||||
const testRundown: OntimeRundown = [
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '1',
|
||||
custom: {
|
||||
lighting: { value: 'event 1 lx' },
|
||||
} as EventCustomFields,
|
||||
} as OntimeEvent,
|
||||
{
|
||||
type: SupportedEvent.Event,
|
||||
id: '2',
|
||||
custom: {
|
||||
lighting: { value: 'event 2 lx' },
|
||||
sound: { value: 'event 2 sound' },
|
||||
} as EventCustomFields,
|
||||
} as OntimeEvent,
|
||||
];
|
||||
const initResult = generate(testRundown, customProperties);
|
||||
expect(initResult.order.length).toBe(2);
|
||||
expect(initResult.assignedCustomProperties).toMatchObject({
|
||||
lighting: ['1', '2'],
|
||||
sound: ['2'],
|
||||
});
|
||||
expect((initResult.rundown['1'] as OntimeEvent).custom).toMatchObject({ lighting: { value: 'event 1 lx' } });
|
||||
expect((initResult.rundown['2'] as OntimeEvent).custom).toMatchObject({
|
||||
lighting: { value: 'event 2 lx' },
|
||||
sound: { value: 'event 2 sound' },
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('add() mutation', () => {
|
||||
test('adds an event to the rundown', () => {
|
||||
const mockEvent = { id: 'mock', cue: 'mock', type: SupportedEvent.Event } as OntimeEvent;
|
||||
const testRundown: OntimeRundown = [];
|
||||
const { newRundown } = add({ atIndex: 0, event: mockEvent, persistedRundown: testRundown });
|
||||
expect(newRundown.length).toBe(1);
|
||||
expect(newRundown[0]).toMatchObject(mockEvent);
|
||||
});
|
||||
});
|
||||
|
||||
describe('remove() mutation', () => {
|
||||
test('deletes an event from the rundown', () => {
|
||||
const mockEvent = { id: 'mock', cue: 'mock', type: SupportedEvent.Event } as OntimeEvent;
|
||||
const testRundown: OntimeRundown = [mockEvent];
|
||||
const { newRundown } = remove({ eventId: mockEvent.id, persistedRundown: testRundown });
|
||||
expect(newRundown.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edit() mutation', () => {
|
||||
test('edits an event in the rundown', () => {
|
||||
const mockEvent = { id: 'mock', cue: 'mock', type: SupportedEvent.Event } as OntimeEvent;
|
||||
const mockEventPatch = { cue: 'patched' } as OntimeEvent;
|
||||
const testRundown: OntimeRundown = [mockEvent];
|
||||
const { newRundown, newEvent } = edit({
|
||||
eventId: mockEvent.id,
|
||||
patch: mockEventPatch,
|
||||
persistedRundown: testRundown,
|
||||
});
|
||||
expect(newRundown.length).toBe(1);
|
||||
expect(newEvent).toMatchObject({
|
||||
id: 'mock',
|
||||
cue: 'patched',
|
||||
type: SupportedEvent.Event,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('batchEdit() mutation', () => {
|
||||
it('should correctly apply the patch to the events with the given IDs', () => {
|
||||
const persistedRundown: OntimeRundown = [
|
||||
{ id: '1', type: SupportedEvent.Event, cue: 'data1' } as OntimeEvent,
|
||||
{ id: '2', type: SupportedEvent.Event, cue: 'data2' } as OntimeEvent,
|
||||
{ id: '3', type: SupportedEvent.Event, cue: 'data3' } as OntimeEvent,
|
||||
];
|
||||
const eventIds = ['1', '3'];
|
||||
const patch = { cue: 'newData' };
|
||||
|
||||
const { newRundown } = batchEdit({ persistedRundown, eventIds, patch });
|
||||
|
||||
expect(newRundown).toMatchObject([
|
||||
{ id: '1', type: SupportedEvent.Event, cue: 'newData' },
|
||||
{ id: '2', type: SupportedEvent.Event, cue: 'data2' },
|
||||
{ id: '3', type: SupportedEvent.Event, cue: 'newData' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reorder() mutation', () => {
|
||||
it('should correctly reorder two events', () => {
|
||||
const persistedRundown: OntimeRundown = [
|
||||
{ id: '1', type: SupportedEvent.Event, cue: 'data1', revision: 0 } as OntimeEvent,
|
||||
{ id: '2', type: SupportedEvent.Event, cue: 'data2', revision: 0 } as OntimeEvent,
|
||||
{ id: '3', type: SupportedEvent.Event, cue: 'data3', revision: 0 } as OntimeEvent,
|
||||
];
|
||||
const { newRundown } = reorder({
|
||||
persistedRundown,
|
||||
eventId: persistedRundown[0].id,
|
||||
from: 0,
|
||||
to: persistedRundown.length - 1,
|
||||
});
|
||||
|
||||
expect(newRundown).toMatchObject([
|
||||
{ id: '2', type: SupportedEvent.Event, cue: 'data2', revision: 1 },
|
||||
{ id: '3', type: SupportedEvent.Event, cue: 'data3', revision: 1 },
|
||||
{ id: '1', type: SupportedEvent.Event, cue: 'data1', revision: 1 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('swap() mutation', () => {
|
||||
it('should correctly swap data between events', () => {
|
||||
const persistedRundown: OntimeRundown = [
|
||||
{ id: '1', type: SupportedEvent.Event, cue: 'data1', timeStart: 1, revision: 0 } as OntimeEvent,
|
||||
{ id: '2', type: SupportedEvent.Event, cue: 'data2', timeStart: 2, revision: 0 } as OntimeEvent,
|
||||
{ id: '3', type: SupportedEvent.Event, cue: 'data3', timeStart: 3, revision: 0 } as OntimeEvent,
|
||||
];
|
||||
const { newRundown } = swap({
|
||||
persistedRundown,
|
||||
fromId: persistedRundown[0].id,
|
||||
toId: persistedRundown[1].id,
|
||||
});
|
||||
|
||||
expect((newRundown[0] as OntimeEvent).id).toBe('1');
|
||||
expect((newRundown[0] as OntimeEvent).cue).toBe('data2');
|
||||
expect((newRundown[0] as OntimeEvent).timeStart).toBe(1);
|
||||
expect((newRundown[0] as OntimeEvent).revision).toBe(1);
|
||||
|
||||
expect((newRundown[1] as OntimeEvent).id).toBe('2');
|
||||
expect((newRundown[1] as OntimeEvent).cue).toBe('data1');
|
||||
expect((newRundown[1] as OntimeEvent).timeStart).toBe(2);
|
||||
expect((newRundown[1] as OntimeEvent).revision).toBe(1);
|
||||
|
||||
expect((newRundown[2] as OntimeEvent).id).toBe('3');
|
||||
expect((newRundown[2] as OntimeEvent).cue).toBe('data3');
|
||||
expect((newRundown[2] as OntimeEvent).timeStart).toBe(3);
|
||||
expect((newRundown[2] as OntimeEvent).revision).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
describe('calculateRuntimeDelays', () => {
|
||||
it('calculates all delays in a given rundown', () => {
|
||||
const rundown: OntimeRundown = [
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: '659e1',
|
||||
cue: '1',
|
||||
custom: {},
|
||||
},
|
||||
{
|
||||
duration: 600000,
|
||||
type: SupportedEvent.Delay,
|
||||
id: '07986',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1200000,
|
||||
duration: 0,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: '1c48f',
|
||||
cue: '2',
|
||||
custom: {},
|
||||
},
|
||||
{
|
||||
duration: 1200000,
|
||||
type: SupportedEvent.Delay,
|
||||
id: '7db42',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: 'd48c2',
|
||||
cue: '3',
|
||||
custom: {},
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
type: SupportedEvent.Block,
|
||||
id: '9870d',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1800000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: '2f185',
|
||||
cue: '4',
|
||||
custom: {},
|
||||
},
|
||||
];
|
||||
|
||||
const updatedRundown = calculateRuntimeDelays(rundown);
|
||||
|
||||
expect(rundown.length).toBe(updatedRundown.length);
|
||||
expect((updatedRundown[0] as OntimeEvent).delay).toBe(0);
|
||||
expect((updatedRundown[2] as OntimeEvent).delay).toBe(600000);
|
||||
expect((updatedRundown[4] as OntimeEvent).delay).toBe(600000 + 1200000);
|
||||
expect((updatedRundown[6] as OntimeEvent).delay).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDelayAt()', () => {
|
||||
const delayedRundown: OntimeRundown = [
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: '659e1',
|
||||
delay: 0,
|
||||
cue: '1',
|
||||
custom: {},
|
||||
},
|
||||
{
|
||||
duration: 600000,
|
||||
type: SupportedEvent.Delay,
|
||||
id: '07986',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1200000,
|
||||
duration: 0,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: '1c48f',
|
||||
delay: 600000,
|
||||
cue: '2',
|
||||
custom: {},
|
||||
},
|
||||
{
|
||||
duration: 1200000,
|
||||
type: SupportedEvent.Delay,
|
||||
id: '7db42',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: 'd48c2',
|
||||
delay: 1800000,
|
||||
cue: '3',
|
||||
custom: {},
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
type: SupportedEvent.Block,
|
||||
id: '9870d',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1800000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: '2f185',
|
||||
delay: 0,
|
||||
cue: '4',
|
||||
custom: {},
|
||||
},
|
||||
];
|
||||
|
||||
it('calculates delay in a rundown', () => {
|
||||
const delayAtStart = getDelayAt(0, delayedRundown);
|
||||
const delayOnFirstEvent = getDelayAt(2, delayedRundown);
|
||||
const delayOnSecondEvent = getDelayAt(4, delayedRundown);
|
||||
const delayOnBlockedEvent = getDelayAt(0, delayedRundown);
|
||||
|
||||
expect(delayAtStart).toBe(0);
|
||||
expect(delayOnFirstEvent).toBe(600000);
|
||||
expect(delayOnSecondEvent).toBe(600000 + 1200000);
|
||||
expect(delayOnBlockedEvent).toBe(0);
|
||||
});
|
||||
it('finds delay before a delay block', () => {
|
||||
const valueOnFirstDelayBlock = getDelayAt(1, delayedRundown);
|
||||
const valueOnSecondDelayBlock = getDelayAt(3, delayedRundown);
|
||||
const valueAfterSecondDelayBlock = getDelayAt(4, delayedRundown);
|
||||
|
||||
expect(valueOnFirstDelayBlock).toBe(0);
|
||||
expect(valueOnSecondDelayBlock).toBe(600000);
|
||||
expect(valueAfterSecondDelayBlock).toBe(600000 + 1200000);
|
||||
});
|
||||
it('returns 0 after blocks', () => {
|
||||
const valueOnBlock = getDelayAt(6, delayedRundown);
|
||||
expect(valueOnBlock).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('calculateRuntimeDelaysFrom()', () => {
|
||||
it('updates delays from given id', () => {
|
||||
const delayedRundown: OntimeRundown = [
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: '659e1',
|
||||
delay: 0,
|
||||
cue: '1',
|
||||
custom: {},
|
||||
},
|
||||
{
|
||||
duration: 600000,
|
||||
type: SupportedEvent.Delay,
|
||||
id: '07986',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1200000,
|
||||
duration: 0,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: '1c48f',
|
||||
delay: 0,
|
||||
cue: '2',
|
||||
custom: {},
|
||||
},
|
||||
{
|
||||
duration: 1200000,
|
||||
type: SupportedEvent.Delay,
|
||||
id: '7db42',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 600000,
|
||||
timeEnd: 1200000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: 'd48c2',
|
||||
delay: 1800000,
|
||||
cue: '3',
|
||||
custom: {},
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
type: SupportedEvent.Block,
|
||||
id: '9870d',
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
note: '',
|
||||
endAction: EndAction.None,
|
||||
timerType: TimerType.CountDown,
|
||||
timeStrategy: TimeStrategy.LockEnd,
|
||||
linkStart: null,
|
||||
timeStart: 1200000,
|
||||
timeEnd: 1800000,
|
||||
duration: 600000,
|
||||
isPublic: true,
|
||||
skip: false,
|
||||
colour: '',
|
||||
type: SupportedEvent.Event,
|
||||
revision: 0,
|
||||
timeWarning: 120000,
|
||||
timeDanger: 60000,
|
||||
id: '2f185',
|
||||
delay: 0,
|
||||
cue: '4',
|
||||
custom: {},
|
||||
},
|
||||
];
|
||||
|
||||
const updatedRundown = calculateRuntimeDelaysFrom('07986', delayedRundown);
|
||||
|
||||
// we only update from the 4th on
|
||||
expect((updatedRundown[0] as OntimeEvent).delay).toBe(0);
|
||||
// 1 + 3
|
||||
expect((updatedRundown[4] as OntimeEvent).delay).toBe(600000 + 1200000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('custom fields', () => {
|
||||
describe('createCustomField()', () => {
|
||||
beforeEach(() => {
|
||||
vi.mock('../../classes/data-provider/DataProvider.js', () => {
|
||||
return {
|
||||
DataProvider: {
|
||||
...vi.fn().mockImplementation(() => {
|
||||
return {};
|
||||
}),
|
||||
getCustomFields: vi.fn().mockReturnValue({}),
|
||||
setCustomFields: vi.fn().mockImplementation((newData) => {
|
||||
return newData;
|
||||
}),
|
||||
persist: vi.fn().mockReturnValue({}),
|
||||
},
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a field from given parameters', async () => {
|
||||
const expected = {
|
||||
lighting: {
|
||||
label: 'Lighting',
|
||||
type: 'string',
|
||||
colour: 'blue',
|
||||
},
|
||||
};
|
||||
|
||||
const customField = await createCustomField({ label: 'Lighting', type: 'string', colour: 'blue' });
|
||||
expect(customField).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('editCustomField()', () => {
|
||||
it('edits a field with a given label', async () => {
|
||||
await createCustomField({ label: 'Sound', type: 'string', colour: 'blue' });
|
||||
|
||||
const expected = {
|
||||
lighting: {
|
||||
label: 'Lighting',
|
||||
type: 'string',
|
||||
colour: 'blue',
|
||||
},
|
||||
sound: {
|
||||
label: 'Sound',
|
||||
type: 'string',
|
||||
colour: 'green',
|
||||
},
|
||||
};
|
||||
|
||||
const customField = await editCustomField('sound', { label: 'Sound', type: 'string', colour: 'green' });
|
||||
|
||||
expect(customField).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeCustomField()', () => {
|
||||
it('deletes a field with a given label', async () => {
|
||||
const expected = {
|
||||
lighting: {
|
||||
label: 'Lighting',
|
||||
type: 'string',
|
||||
colour: 'blue',
|
||||
},
|
||||
};
|
||||
|
||||
const customField = await removeCustomField('sound');
|
||||
|
||||
expect(customField).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user