Files
ontime/apps/server/src/api-integration/integration.controller.ts
T
Alex Christoffer Rasmussen 722e045b20 Revert "Session version" (#1649)
* Revert "refactor: add version to session endpoint"

This reverts commit cd40a6e55e.

* Revert "Remove public event feature (#1645)"

This reverts commit 08d9e24871.

* Revert "Fix: rearrange playing event (#1640)"

This reverts commit 0649678dca.

* Revert "refactor: style tweaks to edit css modal"

This reverts commit a00ec2d02a.

* Revert "refactor: remove usages of framer-motion"

This reverts commit 54a74ccc2a.

* Revert "Upgrade expressjs (#1633)"

This reverts commit 6f3ab274bd.

* Revert "Refactor: require trigger in all events objects (#1636)"

This reverts commit 90870ecfb6.

* Revert "Fix: Correct boundary condition in applyDelay"

This reverts commit b640e0e181.

* Revert "let vite be the proxy to the dev server (#1630)"

This reverts commit c41fe824cf.

* Revert "refactor: migrate custom fields to transactions"

This reverts commit 62c8319d70.

* Revert "refactor: simplify validations"

This reverts commit b1d23467a2.

* Revert "refactor: create transaction system and apply to adding entry (#1620)"

This reverts commit 9a62daf047.

* Revert "Refactor: better rounding (#1594)"

This reverts commit b9ab1c6fd7.

* Revert "refactor: improve reorder logic"

This reverts commit c1054711b0.

* Revert "chore: simplify URLs"

This reverts commit a4d4f29a37.

* Revert "refactor: order is single source of truth"

This reverts commit 2793aadea0.

* Revert "refactor: refetch targets is enum"

This reverts commit e7cfb7d9d9.

* Revert "refactor: small ux improvements"

This reverts commit 256a851c9b.

* Revert "refactor: remove trivially inferred numEvents"

This reverts commit 4ab9c81cb8.

* Revert "feat: duplicate groups"

This reverts commit 2f13d6c89e.

* Revert "feat: create group from entry selection"

This reverts commit f1f7bad25e.

* Revert "feat: create block from rundown empty"

This reverts commit a8b52a48f7.

* Revert "fix: collapsed blocks dont render children"

This reverts commit cd0999b2ab.

* Revert "refactor: type cleanup and test improvements"

This reverts commit b4c60f3f04.

* Revert "feat: allow dissolving a block"

This reverts commit 5cefad3666.

* Revert "fix: uncontrolled prop on controlled component"

This reverts commit 7a6ecd8c34.

* Revert "refactor: improve return of reorder"

This reverts commit ba96ecfd91.

* Revert "refactor: mutations on batch elements must have IDs"

This reverts commit 7bed3757f2.

* Revert "chore: upgrade dependencies"

This reverts commit e2e755b1d2.

* Revert "refactor: extract utility to merge two arrays"

This reverts commit a77d23109d.

* Revert "refactor: change network mode defaults"

This reverts commit 0eb3b8d382.

* Revert "fix: delete nested events"

This reverts commit 0021185288.

* Revert "fix: add event at end of block"

This reverts commit 94c72ff4f6.

* Revert "refactor: make finder available in exported rundown"

This reverts commit e4c08dc9b2.

* Revert "assert non null and update test (#1604)"

This reverts commit ec74af0d62.

* Revert "Fix project renumber (#1597)"

This reverts commit b6d72dd082.

* Revert "Refactor: WebSocket from flush queue to one patch (#1595)"

This reverts commit 31c311daf0.

* Revert "Refactor: ms for api calls (#1593)"

This reverts commit e9b3cc6090.

* Revert "fix test (#1601)"

This reverts commit 543b04a097.

* Revert "fix: rebase master"

This reverts commit d39b85b6e6.

* Revert "chore: correct test path"

This reverts commit bbe107bb2b.

* Revert "refactor: extract rundown parsing"

This reverts commit c616240db1.

* Revert "chore: improve convention entry <> event"

This reverts commit 166be66ce3.

* Revert "refactor: maintain flat orders"

This reverts commit 4180d0a337.

* Revert "refactor: implement operations on nested events"

This reverts commit 78108e316c.

* Revert "refactor: process events in rundown"

This reverts commit 3bb8b70915.

* Revert "chore: improve convention entry <> event"

This reverts commit 1c4f13a0ed.

* Revert "chore: rename currentBlock > parent"

This reverts commit 3ca0abad53.

* Revert "refactor: fix delay positioning in gaps"

This reverts commit 030c8f897f.

* Revert "refactor(e2e): skip flaky test"

This reverts commit 68175cfa3b.

* Revert "refactor: improve project loading"

This reverts commit fd8f757851.

* Revert "refactor: gather group metadata"

This reverts commit 876d111c61.

* Revert "refactor: swap maintains schedule"

This reverts commit 730cb95c04.

* Revert "chore: rename files"

This reverts commit 3c388d4fb5.

* Revert "refactor: restructure model to contain an object of rundowns"

This reverts commit 2e23718d73.

* Revert "refactor: clearer relationship on rundown elements"

This reverts commit 89ea8c470b.

* Revert "refactor: use strict typing"

This reverts commit 178640bfc4.

* Revert "refactor: remove stop as a possible end action"

This reverts commit 4ed38340e0.

* Revert "refactor: restructure model to contain an object of rundowns"

This reverts commit 69eb9a5eff.

* Revert "chore: remove IDE files"

This reverts commit 351425127a.

* Revert "refactor: remove unused and legacy code"

This reverts commit 95f2ba37cc.
2025-06-20 12:28:20 +02:00

328 lines
10 KiB
TypeScript

import { MessageState, OffsetMode, OntimeEvent, SimpleDirection, SimplePlayback } from 'ontime-types';
import { MILLIS_PER_HOUR, MILLIS_PER_SECOND } from 'ontime-utils';
import { DeepPartial } from 'ts-essentials';
import { ONTIME_VERSION } from '../ONTIME_VERSION.js';
import { auxTimerService } from '../services/aux-timer-service/AuxTimerService.js';
import * as 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';
import { socket } from '../adapters/WebsocketAdapter.js';
import { throttle } from '../utils/throttle.js';
import { willCauseRegeneration } from '../services/rundown-service/rundownCacheUtils.js';
import { handleLegacyMessageConversion } from './integration.legacy.js';
import { coerceEnum } from '../utils/coerceType.js';
const throttledUpdateEvent = throttle(updateEvent, 20);
let lastRequest: Date | null = null;
export function dispatchFromAdapter(type: string, payload: unknown, _source?: 'osc' | 'ws' | 'http') {
const action = type.toLowerCase();
const handler = actionHandlers[action];
lastRequest = new Date();
if (handler) {
return handler(payload);
} else {
throw new Error(`Unhandled message ${type}`);
}
}
export function getLastRequest() {
return lastRequest;
}
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 };
let shouldThrottle = false;
Object.entries(data).forEach(([property, value]) => {
if (typeof property !== 'string' || value === undefined) {
throw new Error('Invalid property or value');
}
// parseProperty is async because of the data lock
const newObjectProperty = parseProperty(property, value);
const key = Object.keys(newObjectProperty)[0] as keyof OntimeEvent;
shouldThrottle = shouldThrottle || willCauseRegeneration(key);
if (patchEvent.custom && newObjectProperty.custom) {
Object.assign(patchEvent.custom, newObjectProperty.custom);
} else {
Object.assign(patchEvent, newObjectProperty);
}
});
if (shouldThrottle) {
if (throttledUpdateEvent(patchEvent)) {
return { payload: 'throttled' };
}
} else {
updateEvent(patchEvent);
}
return { payload: 'success' };
},
/* Message Service */
message: (payload) => {
assert.isObject(payload);
// TODO: remove this once we feel its been enough time, ontime 3.6.0, 20/09/2024
const migratedPayload = handleLegacyMessageConversion(payload);
const patch: DeepPartial<MessageState> = {
timer: 'timer' in migratedPayload ? validateTimerMessage(migratedPayload.timer) : undefined,
external: 'external' in migratedPayload ? validateMessage(migratedPayload.external) : undefined,
};
const newMessage = messageService.patch(patch);
return { payload: newMessage };
},
/* Playback */
start: (payload) => {
if (payload === undefined) {
return successPayloadOrError(runtimeService.start(), 'Unable 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' };
}
const timeToAdd = time * MILLIS_PER_SECOND; // frontend is seconds based
if (Math.abs(timeToAdd) > MILLIS_PER_HOUR) {
throw new Error(`Payload too large: ${time}`);
}
runtimeService.addTime(timeToAdd);
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 = auxTimerService.start();
return { payload: reply };
}
if (command === SimplePlayback.Pause) {
const reply = auxTimerService.pause();
return { payload: reply };
}
if (command === SimplePlayback.Stop) {
const reply = auxTimerService.stop();
return { payload: reply };
}
} else if (command && typeof command === 'object') {
const reply = { payload: {} };
if ('duration' in command) {
// convert duration in seconds to ms
const timeInMs = numberOrError(command.duration) * 1000;
reply.payload = auxTimerService.setTime(timeInMs);
}
if ('addtime' in command) {
// convert addTime in seconds to ms
const timeInMs = numberOrError(command.addtime) * 1000;
reply.payload = auxTimerService.addTime(timeInMs);
}
if ('direction' in command) {
if (command.direction === SimpleDirection.CountUp || command.direction === SimpleDirection.CountDown) {
reply.payload = auxTimerService.setDirection(command.direction);
} else {
throw new Error('Invalid direction payload');
}
}
if (!isEmptyObject(reply.payload)) {
return reply;
}
}
throw new Error('No matching method provided');
},
/* Client */
client: (payload) => {
assert.isObject(payload);
if (!('target' in payload) || typeof payload.target != 'string') {
throw new Error('No or invalid client target');
}
if ('rename' in payload && typeof payload.rename == 'string') {
const { target, rename } = payload;
socket.renameClient(target, rename);
return { payload: 'success' };
}
if ('redirect' in payload && typeof payload.redirect == 'string') {
const { target, redirect } = payload;
socket.redirectClient(target, redirect);
return { payload: 'success' };
}
if ('identify' in payload && typeof payload.identify == 'boolean') {
const { target, identify } = payload;
socket.identifyClient(target, identify);
return { payload: 'success' };
}
throw new Error('No matching method provided');
},
offsetmode: (payload) => {
const mode = coerceEnum<OffsetMode>(payload, OffsetMode);
runtimeService.setOffsetMode(mode);
return { payload: 'success' };
},
};
/**
* 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' };
}