feat: send http

This commit is contained in:
Carlos Valente
2025-01-11 14:39:58 +01:00
committed by Carlos Valente
parent 8b84963e17
commit ab4dd300ca
8 changed files with 138 additions and 52 deletions
+2 -2
View File
@@ -80,6 +80,6 @@ export function deleteBlueprint(id: string): Promise<void> {
* HTTP request to test automation output * HTTP request to test automation output
* The return is irrelevant as we care for the resolution of the promise * The return is irrelevant as we care for the resolution of the promise
*/ */
export async function testOutput(output: AutomationOutput): Promise<void> { export function testOutput(output: AutomationOutput): Promise<void> {
return axios.post(automationsPath, output); return axios.post(`${automationsPath}/test`, output);
} }
@@ -6,13 +6,14 @@ import { IoTrash } from '@react-icons/all-files/io5/IoTrash';
import { import {
AutomationBlueprint, AutomationBlueprint,
AutomationBlueprintDTO, AutomationBlueprintDTO,
CustomFields,
HTTPOutput, HTTPOutput,
isHTTPOutput, isHTTPOutput,
isOSCOutput, isOSCOutput,
OSCOutput, OntimeEvent,
} from 'ontime-types'; } from 'ontime-types';
import { addBlueprint, editBlueprint } from '../../../../common/api/automation'; import { addBlueprint, editBlueprint, testOutput } from '../../../../common/api/automation';
import { maybeAxiosError } from '../../../../common/api/utils'; import { maybeAxiosError } from '../../../../common/api/utils';
import Tag from '../../../../common/components/tag/Tag'; import Tag from '../../../../common/components/tag/Tag';
import useAutomationSettings from '../../../../common/hooks-query/useAutomationSettings'; import useAutomationSettings from '../../../../common/hooks-query/useAutomationSettings';
@@ -40,6 +41,7 @@ export default function BlueprintForm(props: BlueprintFormProps) {
const { const {
control, control,
handleSubmit, handleSubmit,
getValues,
register, register,
setError, setError,
setFocus, setFocus,
@@ -364,7 +366,6 @@ export default function BlueprintForm(props: BlueprintFormProps) {
url?: { message?: string }; url?: { message?: string };
} }
| undefined; | undefined;
const canTest = output.url;
return ( return (
<div key={output.id} className={style.outputCard}> <div key={output.id} className={style.outputCard}>
<Tag>HTTP</Tag> <Tag>HTTP</Tag>
@@ -387,7 +388,7 @@ export default function BlueprintForm(props: BlueprintFormProps) {
<Panel.Error>{rowErrors?.url?.message}</Panel.Error> <Panel.Error>{rowErrors?.url?.message}</Panel.Error>
</label> </label>
<Panel.InlineElements relation='inner'> <Panel.InlineElements relation='inner'>
<Button size='sm' variant='ontime-ghosted' isDisabled={!canTest} onClick={handleTestHTTPOutput}> <Button size='sm' variant='ontime-ghosted' onClick={() => handleTestHTTPOutput(index)}>
Test Test
</Button> </Button>
<IconButton <IconButton
@@ -444,3 +445,38 @@ export default function BlueprintForm(props: BlueprintFormProps) {
</Panel.Indent> </Panel.Indent>
); );
} }
/**
* We use this guard to find out if the form is receiving an existing blueprint or creating a DTO
* We do this by checking whether an ID has been generated
*/
function isBlueprint(blueprint: AutomationBlueprintDTO | AutomationBlueprint): blueprint is AutomationBlueprint {
return Object.hasOwn(blueprint, 'id');
}
export const staticSelectProperties = [
{ value: 'id', label: 'ID' },
{ value: 'title', label: 'Title' },
{ value: 'cue', label: 'Cue' },
{ value: 'countToEnd', label: 'Count to end' },
{ value: 'isPublic', label: 'Is public' },
{ value: 'skip', label: 'Skip' },
{ value: 'note', label: 'Note' },
{ value: 'colour', label: 'Colour' },
{ value: 'endAction', label: 'End action' },
{ value: 'timerType', label: 'Timer type' },
{ value: 'timeWarning', label: 'Time warning' },
{ value: 'timeDanger', label: 'Time danger' },
];
type SelectableField = {
value: keyof OntimeEvent | string; // string for custom fields
label: string;
};
function makeFieldList(customFields: CustomFields): SelectableField[] {
return [
...staticSelectProperties,
...Object.entries(customFields).map(([key, { label }]) => ({ value: key, label: `Custom: ${label}` })),
];
}
@@ -1,5 +1,14 @@
import type { AutomationFilter, AutomationOutput, FilterRule, RuntimeStore, TimerLifeCycle } from 'ontime-types'; import {
isHTTPOutput,
isOSCOutput,
type AutomationFilter,
type AutomationOutput,
type FilterRule,
type RuntimeStore,
type TimerLifeCycle,
} from 'ontime-types';
import { getState, type RuntimeState } from '../../stores/runtimeState.js';
import { emitOSC } from './clients/osc.client.js'; import { emitOSC } from './clients/osc.client.js';
import { emitHTTP } from './clients/http.client.js'; import { emitHTTP } from './clients/http.client.js';
import { getAutomations, getBlueprints } from './automation.dao.js'; import { getAutomations, getBlueprints } from './automation.dao.js';
@@ -7,7 +16,7 @@ import { getAutomations, getBlueprints } from './automation.dao.js';
/** /**
* Exposes a method for triggering actions based on a TimerLifeCycle event * Exposes a method for triggering actions based on a TimerLifeCycle event
*/ */
export function triggerAction(event: TimerLifeCycle, state: Partial<RuntimeStore>) { export function triggerAutomations(event: TimerLifeCycle, state: RuntimeState) {
const automations = getAutomations(); const automations = getAutomations();
const triggerAutomations = automations.filter((automation) => automation.trigger === event); const triggerAutomations = automations.filter((automation) => automation.trigger === event);
if (triggerAutomations.length === 0) { if (triggerAutomations.length === 0) {
@@ -31,11 +40,8 @@ export function triggerAction(event: TimerLifeCycle, state: Partial<RuntimeStore
}); });
} }
export function testOutput(payload: AutomationOutput, state: Partial<RuntimeStore>) { export function testOutput(payload: AutomationOutput) {
const success = send([payload], state); send([payload]);
if (!success) {
throw new Error('Failed to send output');
}
} }
/** /**
@@ -60,6 +66,7 @@ export function testConditions(
const { field, operator, value } = filter; const { field, operator, value } = filter;
const fieldValue = state[field]; const fieldValue = state[field];
// TODO: if value is empty string, the user could be meaning to check if the value does not exist
switch (operator) { switch (operator) {
case 'equals': case 'equals':
return fieldValue === value; return fieldValue === value;
@@ -83,17 +90,14 @@ export function testConditions(
* Handles preparing and sending of the data * Handles preparing and sending of the data
* Returns a boolean indicating whether a message was sent * Returns a boolean indicating whether a message was sent
*/ */
function send(output: AutomationOutput[], _state: Partial<RuntimeStore>): boolean { function send(output: AutomationOutput[], state?: RuntimeState) {
const stateSnapshot = state ?? getState();
output.forEach((payload) => { output.forEach((payload) => {
if (payload.type === 'osc') { if (isOSCOutput(payload)) {
emitOSC(); emitOSC();
return true;
} }
if (payload.type === 'http') { if (isHTTPOutput(payload)) {
emitHTTP(); emitHTTP(payload, stateSnapshot);
return true;
} }
return false;
}); });
return true;
} }
@@ -1,4 +1,11 @@
import { AutomationBlueprint, AutomationFilter, AutomationOutput, timerLifecycleValues } from 'ontime-types'; import {
AutomationBlueprint,
AutomationFilter,
AutomationOutput,
HTTPOutput,
OSCOutput,
timerLifecycleValues,
} from 'ontime-types';
import { Request, Response, NextFunction } from 'express'; import { Request, Response, NextFunction } from 'express';
import { body, param, validationResult } from 'express-validator'; import { body, param, validationResult } from 'express-validator';
@@ -130,26 +137,9 @@ function validateOutput(output: Array<unknown>): output is AutomationOutput[] {
assert.isString(type); assert.isString(type);
if (type === 'osc') { if (type === 'osc') {
assert.hasKeys(payload, ['targetIP', 'targetPort', 'address', 'args']); validateOSCOutput(payload);
const { targetIP, targetPort, address, args } = payload;
assert.isString(targetIP);
assert.isNumber(targetPort);
assert.isString(address);
if (typeof args !== 'string' && typeof args !== 'number') {
throw new Error('Invalid automation');
}
} else if (type === 'http') { } else if (type === 'http') {
assert.hasKeys(payload, ['targetIP', 'address']); validateHttpOutput(payload);
const { targetIP, address } = payload;
assert.isString(targetIP);
assert.isString(address);
} else if (type === 'companion') {
assert.hasKeys(payload, ['targetIP', 'address', 'page', 'bank']);
const { targetIP, address, page, bank } = payload;
assert.isString(targetIP);
assert.isString(address);
assert.isNumber(page);
assert.isNumber(bank);
} else { } else {
throw new Error('Invalid automation'); throw new Error('Invalid automation');
} }
@@ -157,6 +147,25 @@ function validateOutput(output: Array<unknown>): output is AutomationOutput[] {
return true; return true;
} }
function validateOSCOutput(payload: object): payload is OSCOutput {
assert.hasKeys(payload, ['targetIP', 'targetPort', 'address', 'args']);
const { targetIP, targetPort, address, args } = payload;
assert.isString(targetIP);
assert.isNumber(targetPort);
assert.isString(address);
if (typeof args !== 'string' && typeof args !== 'number') {
throw new Error('Invalid automation');
}
return true;
}
function validateHttpOutput(payload: object): payload is HTTPOutput {
assert.hasKeys(payload, ['url']);
const { url } = payload;
assert.isString(url);
return true;
}
export const validateTestPayload = [ export const validateTestPayload = [
body('type').exists().isIn(['osc', 'http']), body('type').exists().isIn(['osc', 'http']),
@@ -164,10 +173,10 @@ export const validateTestPayload = [
body('targetIP').if(body('type').equals('osc')).isIP(), body('targetIP').if(body('type').equals('osc')).isIP(),
body('targetPort').if(body('type').equals('osc')).isPort(), body('targetPort').if(body('type').equals('osc')).isPort(),
body('address').if(body('type').equals('osc')).isString().trim(), body('address').if(body('type').equals('osc')).isString().trim(),
body('message').if(body('type').equals('osc')).isString().trim(), body('args').if(body('type').equals('osc')).isString().trim(),
// validation for HTTP message // validation for HTTP message
body('url').if(body('type').equals('http')).isString().trim(), body('url').if(body('type').equals('http')).isURL({ require_tld: false }).trim(),
(req: Request, res: Response, next: NextFunction) => { (req: Request, res: Response, next: NextFunction) => {
const errors = validationResult(req); const errors = validationResult(req);
@@ -1,18 +1,44 @@
import { HTTPOutput, LogOrigin } from 'ontime-types';
import { logger } from '../../../classes/Logger.js';
import type { RuntimeState } from '../../../stores/runtimeState.js';
import { parseTemplateNested } from '../automation.utils.js';
/** /**
* Expose possibility to send a message using HTTP protocol * Expose possibility to send a message using HTTP protocol
*/ */
export function emitHTTP() { export function emitHTTP(output: HTTPOutput, state: RuntimeState) {
console.log('HTTP emit not implemented'); const url = preparePayload(output, state);
const payload = preparePayload(); emit(url);
emit(payload);
} }
/** Parses the state and prepares payload to be emitted */ /** Parses the state and prepares payload to be emitted */
function preparePayload() { function preparePayload(output: HTTPOutput, state: RuntimeState): string {
return; const parsedUrl = parseTemplateNested(output.url, state);
return parsedUrl;
} }
/** Emits message over transport */ /** Emits message over transport */
function emit(_payload) { async function emit(url: string) {
return; logger.info(LogOrigin.Rx, `Sending HTTP: ${url}`);
try {
const response = await fetch(url);
if (!response.ok) {
if (response.status >= 500 && response.status < 600) {
logger.warning(LogOrigin.Tx, `HTTP Integration: Server refused message ${response.status}`);
} else if (response.status >= 400) {
logger.warning(LogOrigin.Tx, `HTTP Integration: Failed sending message ${response.status}`);
} else {
logger.warning(LogOrigin.Tx, `HTTP Integration: Failed sending message ${response.status}`);
}
}
} catch (error) {
if (!(error instanceof Error)) {
logger.warning(LogOrigin.Tx, `HTTP Integration: Failed sending message ${error}`);
return;
}
logger.warning(LogOrigin.Tx, `HTTP Integration: ${error.name} ${error.message}`);
}
} }
+1 -1
View File
@@ -41,7 +41,7 @@ export const eventStore = {
} }
}, },
poll() { poll() {
return store; return store as RuntimeStore;
}, },
broadcast() { broadcast() {
socket.sendAsJson({ socket.sendAsJson({
+2
View File
@@ -105,5 +105,7 @@ export {
isPlayableEvent, isPlayableEvent,
isOntimeCycle, isOntimeCycle,
isKeyOfType, isKeyOfType,
isOSCOutput,
isHTTPOutput,
} from './utils/guards.js'; } from './utils/guards.js';
export type { MaybeNumber, MaybeString } from './utils/utils.type.js'; export type { MaybeNumber, MaybeString } from './utils/utils.type.js';
+9
View File
@@ -1,3 +1,4 @@
import type { AutomationOutput, HTTPOutput, OSCOutput } from '../definitions/core/Automation.type.js';
import type { OntimeBlock, OntimeDelay, OntimeEvent, PlayableEvent } from '../definitions/core/OntimeEvent.type.js'; import type { OntimeBlock, OntimeDelay, OntimeEvent, PlayableEvent } from '../definitions/core/OntimeEvent.type.js';
import { SupportedEvent } from '../definitions/core/OntimeEvent.type.js'; import { SupportedEvent } from '../definitions/core/OntimeEvent.type.js';
import type { OntimeRundownEntry } from '../definitions/core/Rundown.type.js'; import type { OntimeRundownEntry } from '../definitions/core/Rundown.type.js';
@@ -32,3 +33,11 @@ export function isOntimeCycle(maybeCycle: unknown): maybeCycle is TimerLifeCycle
if (typeof maybeCycle !== 'string') return false; if (typeof maybeCycle !== 'string') return false;
return Object.values(TimerLifeCycle).includes(maybeCycle as TimerLifeCycle); return Object.values(TimerLifeCycle).includes(maybeCycle as TimerLifeCycle);
} }
export function isOSCOutput(output: AutomationOutput): output is OSCOutput {
return output.type === 'osc';
}
export function isHTTPOutput(output: AutomationOutput): output is HTTPOutput {
return output.type === 'http';
}