event cucle (#76)

* install sass
* refact: integration settings
- OSC in its own HTTP endpoint
- OSC settings have own object in db
* refact: simplify event cycle
* refact: restructure external triggers http
* refact: restructure external triggers osc+socket
* refact: restructure data updates
* feat: osc integration class
* IO improvements
- timer uses osc integration
- create trigger handler to manage external triggers
* refact: refract state machine update
* Integration: simple HTTP Client
* Integration: http options in datamodel
* Integration: call http send on life cycle
* feat/62-logging: fix issue #71
This commit is contained in:
Carlos Valente
2021-12-22 18:17:48 +01:00
committed by GitHub
parent 2b2bafa8c6
commit ac0d5832b6
53 changed files with 2041 additions and 1948 deletions
+8 -4
View File
@@ -23,13 +23,17 @@ dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
ontime.code-workspace
TODO.md
# working stuff
_SS/
.vscode/launch.json
.eslintrc.json
db backup.json
server/src/data/db.json
server/src/models/db.json
TODO.md
# vscode stuff
.vscode/*
ontime.code-workspace
# webstorm stuff
.idea/*
+5
View File
@@ -0,0 +1,5 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
+1 -1
View File
@@ -1,6 +1,6 @@
import { lazy, Suspense, useCallback, useEffect } from 'react';
import { Route, Switch } from 'react-router-dom';
import './App.css';
import './App.scss';
import { QueryClient, QueryClientProvider } from 'react-query';
import SocketProvider from 'app/context/socketContext';
import withSocket from 'features/viewers/ViewWrapper';
+1
View File
@@ -2,6 +2,7 @@ export const NODE_PORT = 4001;
export const EVENT_TABLE = 'event';
export const EVENTS_TABLE = 'events';
export const APP_TABLE = 'appinfo';
export const OSC_SETTINGS = 'oscSettings';
const calculateServer = () => {
return window.location.origin.replace(window.location.port, `${NODE_PORT}/`);
+79 -5
View File
@@ -3,13 +3,77 @@ import { ontimeURL } from './apiConstants';
export const ontimePlaceholderInfo = {
networkInterfaces: [],
version: '',
serverPort: 4001,
oscInPort: '',
oscOutPort: '',
oscOutIP: '',
settings: {
version: '',
serverPort: 4001,
},
};
export const oscPlaceholderSettings = {
port: '',
portOut: '',
targetIP: '',
enabled: true,
};
export const httpPlaceholder = {
onLoad: {
url: '',
enabled: false,
},
onStart: {
url: '',
enabled: false,
},
onUpdate: {
url: '',
enabled: false,
},
onPause: {
url: '',
enabled: false,
},
onStop: {
url: '',
enabled: false,
},
onFinish: {
url: '',
enabled: false,
},
};
export const ontimeVars = [
{
name: '$timer',
description: 'Current running timer',
},
{
name: '$title',
description: 'Current title',
},
{
name: '$presenter',
description: 'Current presenter',
},
{
name: '$subtitle',
description: 'Current subtitle',
},
{
name: '$next-title',
description: 'Next title',
},
{
name: '$next-presenter',
description: 'Next presenter',
},
{
name: '$next-subtitle',
description: 'Next subtitle',
},
];
export const getInfo = async () => {
const res = await axios.get(ontimeURL + '/info');
return res.data;
@@ -20,6 +84,16 @@ export const postInfo = async (data) => {
return res;
};
export const getOSC = async () => {
const res = await axios.get(ontimeURL + '/osc');
return res.data;
};
export const postOSC = async (data) => {
const res = await axios.post(ontimeURL + '/osc', data);
return res;
};
export const downloadEvents = async () => {
await axios({
url: ontimeURL + '/db',
+34 -12
View File
@@ -1,4 +1,5 @@
import { memo } from 'react';
import PropTypes from 'prop-types';
import style from './PlaybackControl.module.scss';
import StartIconBtn from 'common/components/buttons/StartIconBtn';
import PauseIconBtn from 'common/components/buttons/PauseIconBtn';
@@ -10,70 +11,77 @@ import ReloadIconButton from 'common/components/buttons/ReloadIconBtn';
const areEqual = (prevProps, nextProps) => {
return (
prevProps.playback === nextProps.playback &&
prevProps.selectedId === nextProps.selectedId
prevProps.playback === nextProps.playback
&& prevProps.selectedId === nextProps.selectedId
&& prevProps.noEvents === nextProps.noEvents
);
};
const Playback = ({ playback, selectedId, playbackControl }) => {
const Playback = (props) => {
const { playback, selectedId, playbackControl, noEvents } = props;
const isRolling = playback === 'roll';
return (
<div className={style.playbackContainer}>
<StartIconBtn
active={playback === 'start'}
clickhandler={() => playbackControl('start')}
disabled={!selectedId || isRolling}
disabled={!selectedId || isRolling || noEvents}
/>
<PauseIconBtn
active={playback === 'pause'}
clickhandler={() => playbackControl('pause')}
disabled={!selectedId || isRolling}
disabled={!selectedId || isRolling || noEvents || playback !== 'start'}
/>
<RollIconBtn
active={playback === 'roll'}
disabled={playback === 'roll'}
disabled={playback === 'roll' || noEvents}
clickhandler={() => playbackControl('roll')}
/>
</div>
);
};
const Transport = ({ playback, selectedId, playbackControl }) => {
const Transport = (props) => {
const { playback, selectedId, playbackControl, noEvents } = props;
const isRolling = playback === 'roll';
return (
<div className={style.playbackContainer}>
<PrevIconBtn
clickhandler={() => playbackControl('previous')}
disabled={playback === 'roll'}
disabled={isRolling || noEvents}
/>
<NextIconBtn
clickhandler={() => playbackControl('next')}
disabled={playback === 'roll'}
disabled={isRolling || noEvents}
/>
<ReloadIconButton
clickhandler={() => playbackControl('reload')}
disabled={!selectedId || isRolling}
disabled={selectedId == null || isRolling || noEvents}
/>
<UnloadIconBtn
clickhandler={() => playbackControl('unload')}
disabled={!selectedId && !isRolling}
disabled={(selectedId == null && !isRolling) || noEvents}
/>
</div>
);
};
const PlaybackButtons = (props) => {
const { playback, selectedId } = props;
const { playback, selectedId, noEvents } = props;
return (
<>
<Playback
playback={playback}
selectedId={selectedId}
noEvents={noEvents}
playbackControl={props.playbackControl}
/>
<Transport
playback={playback}
selectedId={selectedId}
noEvents={noEvents}
playbackControl={props.playbackControl}
/>
</>
@@ -81,3 +89,17 @@ const PlaybackButtons = (props) => {
};
export default memo(PlaybackButtons, areEqual);
PlaybackButtons.propTypes = {
playback: PropTypes.string,
selectedId: PropTypes.string,
playbackControl: PropTypes.func.isRequired,
noEvents: PropTypes.bool.isRequired,
};
Transport.propTypes = {
playback: PropTypes.string,
selectedId: PropTypes.string,
playbackControl: PropTypes.func.isRequired,
noEvents: PropTypes.bool.isRequired,
};
@@ -15,6 +15,7 @@ export default function PlaybackControl() {
secondary: null,
});
const [selectedId, setSelectedId] = useState(null);
const [numEvents, setNumEvents] = useState(0);
const resetTimer = () => {
setTimer({
@@ -32,6 +33,7 @@ export default function PlaybackControl() {
socket.emit('get-timer');
socket.emit('get-playstate');
socket.emit('get-selected-id');
socket.emit('get-numevents');
// Handle playstate
socket.on('playstate', (data) => {
@@ -48,11 +50,16 @@ export default function PlaybackControl() {
setSelectedId(data);
});
socket.on('numevents', (data) => {
setNumEvents(data);
});
// Clear listener
return () => {
socket.off('playstate');
socket.off('timer');
socket.off('selected-id');
socket.off('numevents');
};
}, [socket]);
@@ -93,11 +100,13 @@ export default function PlaybackControl() {
<PlaybackTimer
timer={timer}
playback={playback}
selectedId={selectedId}
handleIncrement={(amount) => socket.emit('increment-timer', amount)}
/>
<PlaybackButtons
playback={playback}
selectedId={selectedId}
noEvents={numEvents < 1}
playbackControl={playbackControl}
/>
</div>
+20 -10
View File
@@ -4,24 +4,27 @@ import {stringFromMillis} from 'common/utils/dateConfig';
import {Tooltip} from '@chakra-ui/react';
import {Button} from '@chakra-ui/button';
import {memo} from 'react';
import PropTypes from "prop-types";
const areEqual = (prevProps, nextProps) => {
return (
prevProps.timer.running === nextProps.timer.running &&
prevProps.timer.expectedFinish === nextProps.timer.expectedFinish &&
prevProps.timer.startedAt === nextProps.timer.startedAt &&
prevProps.playback === nextProps.playback &&
prevProps.timer.secondary === nextProps.timer.secondary
prevProps.timer.running === nextProps.timer.running
&& prevProps.timer.expectedFinish === nextProps.timer.expectedFinish
&& prevProps.timer.startedAt === nextProps.timer.startedAt
&& prevProps.playback === nextProps.playback
&& prevProps.timer.secondary === nextProps.timer.secondary
&& prevProps.selectedId === nextProps.selectedId
);
};
const PlaybackTimer = (props) => {
const {timer, playback, handleIncrement} = props;
const {timer, playback, handleIncrement, selectedId} = props;
const started = stringFromMillis(timer.startedAt, true);
const finish = stringFromMillis(timer.expectedFinish, true);
const isNegative = timer.running < 0;
const isRolling = playback === 'roll';
const isWaiting = timer.secondary > 0 && timer.running == null;
const disableButtons = (selectedId == null || isRolling);
const incrementProps = {
size: 'sm',
@@ -70,28 +73,28 @@ const PlaybackTimer = (props) => {
<div className={style.btn}>
<Button
{...incrementProps}
disabled={isRolling}
disabled={disableButtons}
onClick={() => handleIncrement(-1)}
>
-1
</Button>
<Button
{...incrementProps}
disabled={isRolling}
disabled={disableButtons}
onClick={() => handleIncrement(1)}
>
+1
</Button>
<Button
{...incrementProps}
disabled={isRolling}
disabled={disableButtons}
onClick={() => handleIncrement(-5)}
>
-5
</Button>
<Button
{...incrementProps}
disabled={isRolling}
disabled={disableButtons}
onClick={() => handleIncrement(5)}
>
+5
@@ -103,3 +106,10 @@ const PlaybackTimer = (props) => {
};
export default memo(PlaybackTimer, areEqual);
PlaybackTimer.propTypes = {
timer: PropTypes.object.isRequired,
playback: PropTypes.string,
handleIncrement: PropTypes.func.isRequired,
selectedId: PropTypes.string,
};
+1 -1
View File
@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import { useSocket } from 'app/context/socketContext';
import style from './Info.module.css';
import style from './Info.module.scss';
import InfoTitle from './InfoTitle';
import InfoLogger from './InfoLogger';
import InfoNif from './InfoNif';
@@ -84,14 +84,15 @@
margin: 0 0.5em;
}
ul > li {
font-size: 0.9em;
color: #fff;
}
.log {
overflow-y: scroll;
height: 30vh;
ul > li {
font-size: 0.9em;
color: #fff;
}
}
.info {
+1 -1
View File
@@ -1,7 +1,7 @@
import { Icon } from '@chakra-ui/react';
import { useState } from 'react';
import { FiChevronUp } from 'react-icons/fi';
import style from './Info.module.css';
import style from './Info.module.scss';
export default function InfoLogger(props) {
const [collapsed, setCollapsed] = useState(false);
+1 -1
View File
@@ -4,7 +4,7 @@ import { FiChevronUp } from 'react-icons/fi';
import { APP_TABLE } from 'app/api/apiConstants';
import { getInfo, ontimePlaceholderInfo } from 'app/api/ontimeApi';
import { useFetch } from 'app/hooks/useFetch';
import style from './Info.module.css';
import style from './Info.module.scss';
export default function InfoNif() {
const { data, status } = useFetch(APP_TABLE, getInfo, {
+1 -1
View File
@@ -1,7 +1,7 @@
import { Icon } from '@chakra-ui/react';
import { useState } from 'react';
import { FiChevronUp } from 'react-icons/fi';
import style from './Info.module.css';
import style from './Info.module.scss';
export default function InfoTitle(props) {
const [collapsed, setCollapsed] = useState(false);
+15 -5
View File
@@ -1,4 +1,4 @@
import { IconButton } from '@chakra-ui/button';
import { Button, IconButton } from '@chakra-ui/button';
import { FiPlus, FiMinus } from 'react-icons/fi';
import { ModalBody } from '@chakra-ui/modal';
import { Input } from '@chakra-ui/react';
@@ -6,7 +6,7 @@ import { fetchEvent } from 'app/api/eventApi';
import { useState } from 'react';
import { useFetch } from 'app/hooks/useFetch';
import { EVENT_TABLE } from 'app/api/apiConstants';
import style from './Modals.module.css';
import style from './Modals.module.scss';
export default function AliasesModal() {
const { data, status, isError } = useFetch(EVENT_TABLE, fetchEvent);
@@ -31,10 +31,10 @@ export default function AliasesModal() {
<p className={style.notes}>
Configure easy to use URL Aliases
<br />
!!! Feature is not yet implemented !!!
Feature is not yet implemented
</p>
<span> Default URLs </span>
<span>Default URLs</span>
<div className={style.highNotes}>
<p className={style.flexNote}>
@@ -83,7 +83,7 @@ export default function AliasesModal() {
</p>
</div>
<span> Manage custom aliases</span>
<span>Manage custom aliases</span>
<div className={style.modalInline}>
<Input
size='sm'
@@ -145,6 +145,16 @@ export default function AliasesModal() {
disabled
/>
</div>
<div className={style.submitContainer}>
<Button
colorScheme='blue'
type='submit'
isLoading={submitting}
disabled={true}
>
Save
</Button>
</div>
</ModalBody>
</form>
</>
+36 -39
View File
@@ -1,26 +1,21 @@
import { ModalBody } from '@chakra-ui/modal';
import { FormLabel, FormControl, Input, Button } from '@chakra-ui/react';
import { getInfo, ontimePlaceholderInfo, postInfo } from 'app/api/ontimeApi';
import { getOSC, oscPlaceholderSettings, postOSC } from 'app/api/ontimeApi';
import { useEffect, useState } from 'react';
import { useFetch } from 'app/hooks/useFetch';
import { APP_TABLE } from 'app/api/apiConstants';
import { OSC_SETTINGS } from 'app/api/apiConstants';
import { showErrorToast } from 'common/helpers/toastManager';
import style from './Modals.module.css';
import style from './Modals.module.scss';
export default function AppSettingsModal() {
const { data, status } = useFetch(APP_TABLE, getInfo);
const [formData, setFormData] = useState(ontimePlaceholderInfo);
const { data, status } = useFetch(OSC_SETTINGS, getOSC);
const [formData, setFormData] = useState(oscPlaceholderSettings);
const [changed, setChanged] = useState(false);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (data == null) return;
setFormData({
oscInPort: data.oscInPort,
oscOutPort: data.oscOutPort,
oscOutIP: data.oscOutIP,
});
setFormData({ ...data });
}, [data]);
const submitHandler = async (event) => {
@@ -30,15 +25,15 @@ export default function AppSettingsModal() {
let e = { status: false, message: '' };
// Validate fields
if (f.oscInPort < 1024 || f.oscInPort > 65535) {
if (f.port < 1024 || f.port > 65535) {
// Port in incorrect range
e.status = true;
e.message += 'OSC IN Port in incorrect range (1024 - 65535)';
} else if (f.oscOutPort < 1024 || f.oscOutPort > 65535) {
} else if (f.portOut < 1024 || f.portOut > 65535) {
// Port in incorrect range
e.status = true;
e.message += 'OSC OUT Port in incorrect range (1024 - 65535)';
} else if (f.oscInPort === f.oscOutPort) {
} else if (f.port === f.portOut) {
// Cant use the same port
e.status = true;
e.message += 'OSC IN and OUT Ports cant be the same';
@@ -51,7 +46,7 @@ export default function AppSettingsModal() {
}
// Post here
postInfo(formData);
postOSC(formData);
setChanged(false);
setSubmitting(false);
@@ -66,7 +61,7 @@ export default function AppSettingsModal() {
<p className={style.notes}>
Options related to the application
<br />
!!! Changes take effect after app restart !!!
🔥 Changes take effect after app restart 🔥
</p>
<FormControl id='serverPort'>
@@ -85,8 +80,8 @@ export default function AppSettingsModal() {
/>
<span className={style.notes}>(Read Only Value)</span>
</FormControl>
<FormControl id='oscInPort'>
<FormLabel htmlFor='oscInPort'>
<FormControl id='port'>
<FormLabel htmlFor='port'>
OSC In Port
<span className={style.notes}>
<br />
@@ -95,18 +90,18 @@ export default function AppSettingsModal() {
</FormLabel>
<Input
size='sm'
name='oscInPort'
name='port'
placeholder='8888'
autoComplete='off'
type='number'
value={formData.oscInPort}
value={formData.port}
min='1024'
max='65535'
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
oscInPort: parseInt(event.target.value),
port: parseInt(event.target.value),
});
}}
isDisabled={submitting}
@@ -114,8 +109,8 @@ export default function AppSettingsModal() {
/>
</FormControl>
<div className={style.modalInline}>
<FormControl id='oscOutIP' width='auto'>
<FormLabel htmlFor='oscOutIP'>
<FormControl id='targetIP' width='auto'>
<FormLabel htmlFor='targetIP'>
OSC Out Target IP
<span className={style.notes}>
<br />
@@ -124,23 +119,23 @@ export default function AppSettingsModal() {
</FormLabel>
<Input
size='sm'
name='oscOutIP'
name='targetIP'
placeholder='127.0.0.1'
autoComplete='off'
value={formData.oscOutIP}
value={formData.targetIP}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
oscOutIP: event.target.value,
targetIP: event.target.value,
});
}}
isDisabled={submitting}
style={{ width: '12em', textAlign: 'right' }}
/>
</FormControl>
<FormControl id='oscOutPort' width='auto'>
<FormLabel htmlFor='oscOutPort'>
<FormControl id='portOut' width='auto'>
<FormLabel htmlFor='portOut'>
OSC Out Port
<span className={style.notes}>
<br />
@@ -149,18 +144,18 @@ export default function AppSettingsModal() {
</FormLabel>
<Input
size='sm'
name='oscOutPort'
name='portOut'
placeholder='9999'
autoComplete='off'
type='number'
value={formData.oscOutPort}
value={formData.portOut}
min='1024'
max='65535'
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
oscOutPort: parseInt(event.target.value),
portOut: parseInt(event.target.value),
});
}}
isDisabled={submitting}
@@ -170,14 +165,16 @@ export default function AppSettingsModal() {
</div>
</>
)}
<Button
colorScheme='blue'
type='submit'
isLoading={submitting}
disabled={!changed}
>
Save
</Button>
<div className={style.submitContainer}>
<Button
colorScheme='blue'
type='submit'
isLoading={submitting}
disabled={!changed}
>
Save
</Button>
</div>
</ModalBody>
</form>
</>
@@ -10,7 +10,7 @@ import { fetchEvent, postEvent } from 'app/api/eventApi';
import { useEffect, useState } from 'react';
import { useFetch } from 'app/hooks/useFetch';
import { EVENT_TABLE } from 'app/api/apiConstants';
import style from './Modals.module.css';
import style from './Modals.module.scss';
export default function SettingsModal() {
const { data, status } = useFetch(EVENT_TABLE, fetchEvent);
@@ -122,6 +122,7 @@ export default function SettingsModal() {
name='backstageInfo'
placeholder='Information to be shown on backstage screens'
autoComplete='off'
resize={false}
value={formData.backstageInfo}
onChange={(event) => {
setChanged(true);
@@ -160,14 +161,16 @@ export default function SettingsModal() {
</FormControl>
</>
)}
<Button
colorScheme='blue'
type='submit'
isLoading={submitting}
disabled={!changed}
>
Save
</Button>
<div className={style.submitContainer}>
<Button
colorScheme='blue'
type='submit'
isLoading={submitting}
disabled={!changed}
>
Save
</Button>
</div>
</ModalBody>
</form>
</>
@@ -0,0 +1,335 @@
import { ModalBody } from '@chakra-ui/modal';
import {
FormLabel,
FormControl,
Input,
Button,
Switch,
} from '@chakra-ui/react';
import {
getInfo,
httpPlaceholder,
ontimeVars,
postInfo,
} from 'app/api/ontimeApi';
import { useEffect, useState } from 'react';
import { useFetch } from 'app/hooks/useFetch';
import { APP_TABLE } from 'app/api/apiConstants';
import { showErrorToast } from 'common/helpers/toastManager';
import style from './Modals.module.scss';
export default function IntegrationSettingsModal() {
const { data, status } = useFetch(APP_TABLE, getInfo);
const [formData, setFormData] = useState(httpPlaceholder);
const [changed, setChanged] = useState(false);
const [submitting, setSubmitting] = useState(false);
const ready = status === 'success';
const integrationInputProps = {
size: 'sm',
autoComplete: 'off',
isDisabled: submitting || !ready,
};
useEffect(() => {
if (data == null) return;
setFormData({
onLoad: data?.onLoad,
onStart: data?.onStart,
onUpdate: data?.onUpdate,
onPause: data?.onPause,
onStop: data?.onStop,
});
}, [data]);
const submitHandler = async (event) => {
event.preventDefault();
const f = formData;
let e = { status: false, message: '' };
// set fields with error
if (e.status) {
showErrorToast('Invalid Input', e.message);
return;
}
// Post here
postInfo(f);
setChanged(false);
setSubmitting(false);
};
return (
<>
<form onSubmit={submitHandler}>
<ModalBody
className={ready ? style.modalBody : style.modalBodyDisabled}
>
<>
<p className={style.notes}>
Integrate with third party over an HTTP API
<br />
🔥 Changes take effect after app restart 🔥
</p>
<div className={style.highNotes}>
<p>
Add HTTP messages that ontime will send during the app lifecycle
</p>
<p>
You can use the variables below to pass data directly from
ontime eg:
<span className={style.emNote}>
http://127.0.0.1:8088/API/?setHeadline=<b>$title</b>
&setSub=<b>$presenter</b>
</span>
</p>
<table>
{ontimeVars.map((v) => (
<tr>
<td className={style.noteItem}>{v.name}</td>
<td>{v.description}</td>
</tr>
))}
</table>
</div>
<>
<FormLabel>
On Load
<span className={style.notes}>When a new event loads</span>
</FormLabel>
<FormControl id='onLoad' className={style.modalInline}>
<Input
{...integrationInputProps}
name='onLoadURL'
value={formData?.onLoad?.url}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onLoad: {
...formData.onLoad,
url: event.target.value,
},
});
}}
/>
<Switch
colorScheme='green'
id='onLoadEnable'
value={formData?.onLoad?.enabled}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onLoad: {
...formData.onLoad,
enabled: event.target.value,
},
});
}}
/>
</FormControl>
<FormLabel>
On Start
<span className={style.notes}>
When an timer starts / resumes
</span>
</FormLabel>
<FormControl id='onStart' className={style.modalInline}>
<Input
{...integrationInputProps}
name='onStartURL'
value={formData?.onStart?.url}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onStart: {
...formData.onStart,
url: event.target.value,
},
});
}}
/>
<Switch
colorScheme='green'
id='onStartEnable'
value={formData?.onStart?.enabled}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onStart: {
...formData.onStart,
enabled: event.target.value,
},
});
}}
/>
</FormControl>
<FormLabel>
On Update
<span className={style.notes}>At every clock tick</span>
</FormLabel>
<FormControl id='onUpdate' className={style.modalInline}>
<Input
{...integrationInputProps}
name='onUpdateURL'
value={formData?.onUpdate?.url}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onUpdate: {
...formData.onUpdate,
url: event.target.value,
},
});
}}
/>
<Switch
colorScheme='green'
id='onUpdateEnable'
value={formData?.onUpdate?.enabled}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onUpdate: {
...formData.onUpdate,
enabled: event.target.value,
},
});
}}
/>
</FormControl>
<FormLabel>
On Pause
<span className={style.notes}>When a timer pauses</span>
</FormLabel>
<FormControl id='onPause' className={style.modalInline}>
<Input
{...integrationInputProps}
name='onPauseURL'
value={formData?.onPause?.url}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onPause: {
...formData.onPause,
url: event.target.value,
},
});
}}
/>
<Switch
colorScheme='green'
id='onPauseEnable'
value={formData?.onPause?.enabled}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onPause: {
...formData.onPause,
enabled: event.target.value,
},
});
}}
/>
</FormControl>
<FormLabel>
On Stop
<span className={style.notes}>When an event is unloaded</span>
</FormLabel>
<FormControl id='onStop' className={style.modalInline}>
<Input
{...integrationInputProps}
name='onStopURL'
value={formData?.onStop?.url}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onStop: {
...formData.onStop,
url: event.target.value,
},
});
}}
/>
<Switch
colorScheme='green'
id='onStopEnable'
value={formData?.onStop?.enabled}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onStop: {
...formData.onStop,
enabled: event.target.value,
},
});
}}
/>
</FormControl>
<FormLabel>
On Finish
<span className={style.notes}>When an event is finished</span>
</FormLabel>
<FormControl id='onFinish' className={style.modalInline}>
<Input
{...integrationInputProps}
name='onFinishURL'
value={formData?.onFinish?.url}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onStop: {
...formData.onFinish,
url: event.target.value,
},
});
}}
/>
<Switch
colorScheme='green'
id='onFinishEnable'
value={formData?.onFinish?.enabled}
onChange={(event) => {
setChanged(true);
setFormData({
...formData,
onStop: {
...formData.onStop,
enabled: event.target.value,
},
});
}}
/>
</FormControl>
</>
</>
<div className={style.submitContainer}>
<Button
colorScheme='blue'
type='submit'
isLoading={submitting}
disabled={!changed || !ready}
>
Save
</Button>
</div>
</ModalBody>
</form>
</>
);
}
+9 -3
View File
@@ -10,6 +10,7 @@ import { Tab, TabList, TabPanel, TabPanels, Tabs } from '@chakra-ui/tabs';
import EventSettingsModal from './EventSettingsModal';
import AppSettingsModal from './AppSettingsModal';
import AliasesModal from './AliasesModal';
import IntegrationSettingsModal from './IntegrationSettingsModal';
export default function ModalManager(props) {
const { isOpen, onClose } = props;
@@ -19,6 +20,7 @@ export default function ModalManager(props) {
onClose={onClose}
closeOnOverlayClick={false}
motionPreset={'slideInBottom'}
size='lg'
>
<ModalOverlay />
<ModalContent>
@@ -27,9 +29,10 @@ export default function ModalManager(props) {
<Tabs size='sm' isLazy>
<TabList>
<Tab>Event Settings</Tab>
<Tab>Application Settings</Tab>
<Tab>URL Aliases</Tab>
<Tab style={{ fontSize: '0.9em' }}>Event Data</Tab>
<Tab style={{ fontSize: '0.9em' }}>Application Settings</Tab>
<Tab style={{ fontSize: '0.9em' }}>URL Aliases</Tab>
{/*<Tab style={{ fontSize: '0.9em' }}>Integration</Tab>*/}
</TabList>
<TabPanels>
<TabPanel>
@@ -41,6 +44,9 @@ export default function ModalManager(props) {
<TabPanel>
<AliasesModal />
</TabPanel>
{/*<TabPanel>*/}
{/* <IntegrationSettingsModal />*/}
{/*</TabPanel>*/}
</TabPanels>
</Tabs>
</ModalContent>
@@ -1,60 +0,0 @@
.modalBody {
font-weight: 400;
}
.modalBody > * {
margin-top: 0.5em;
}
.modalBody > button {
margin-top: 1em;
}
.notes {
font-weight: 400;
color: #2b6cb0;
}
p.notes {
text-align: center;
border-color: #2b6cb055;
border-width: 0 2px;
font-size: 0.9em;
margin-bottom: 1em;
}
span.notes {
font-size: 0.8em;
padding-left: 0.4em;
}
.modalInline {
display: flex;
gap: 2em;
}
.highNotes {
background-color: #2b6cb022;
margin: 1em 0;
padding: 0.3em;
}
.flexNote {
font-size: 0.9em;
padding-bottom: 0.3em;
}
a::after {
content: ' \2197';
color: #ff7597;
}
a:hover {
color: #ff7597;
}
.separator {
border: 1px solid #2b6cb055;
width: 50%;
margin: 0.5em auto;
}
@@ -0,0 +1,99 @@
@use '../../styles/variables' as *;
//////////////////////////////////// main
.modalBody,
.modalBodyDisabled {
font-weight: 400;
.notes {
font-weight: 400;
color: $light-bg;
}
.separator {
border: 1px solid $light-bg-transparent;
width: 50%;
margin: 0.5em auto;
}
.modalInline {
display: flex;
gap: 2em;
align-items: center;
}
.submitContainer {
display: flex;
flex-direction: row-reverse;
button {
margin-top: 1em;
}
}
}
.modalBody > *,
.modalBodyDisabled > * {
margin-top: 0.5em;
}
//////////////////////////////////// notes
p {
&.notes {
text-align: center;
border-color: $light-bg-transparent;
border-width: 0 2px;
font-size: 0.9em;
margin-bottom: 1em;
}
}
span {
&.notes {
font-size: 0.8em;
padding-left: 0.4em;
}
}
.highNotes {
background-color: $light-text;
margin: 1em 0;
padding: 0.3em;
font-size: 0.9em;
table {
background-color: $light-text;
width: 100%;
margin-top: 0.3em;
}
.noteItem {
user-select: text;
font-weight: 700;
padding-right: 2em;
}
.flexNote {
user-select: text;
padding-bottom: 0.3em;
}
.emNote {
user-select: text;
display: block;
background-color: #fffc;
}
}
// Define style for a link
a {
&::after {
content: ' \2197';
color: $accent;
}
&:hover {
color: $accent;
}
}
@@ -21,10 +21,10 @@ export default function StageManager(props) {
useEffect(() => {
if (backstageEvents == null) return;
setFilteredEvents(getEventsWithDelay(backstageEvents));
const f = getEventsWithDelay(backstageEvents)
console.log('hhh', getEventsWithDelay(backstageEvents))
}, [backstageEvents]);
setFilteredEvents(f);
}, [backstageEvents]);
// Format messages
@@ -3,7 +3,11 @@ import useFitText from "use-fit-text";
import NavLogo from "../../../common/components/nav/NavLogo";
import {useEffect, useState} from "react";
import {formatDisplay} from "../../../common/utils/dateConfig";
import {formatEventList, trimEventlist} from "../../../common/utils/eventsManager";
import {
formatEventList,
getEventsWithDelay,
trimEventlist
} from "../../../common/utils/eventsManager";
export default function StudioClock(props) {
const {title, time, backstageEvents, selectedId, nextId, onAir} = props;
@@ -25,11 +29,11 @@ export default function StudioClock(props) {
useEffect(() => {
if (backstageEvents == null) return;
const events = backstageEvents.filter((e) => e.type === 'event');
let e = trimEventlist(events, selectedId, MAX_TITLES);
e = formatEventList(e, selectedId, nextId);
setSchedule(e);
const delayed = getEventsWithDelay(backstageEvents);
const events = delayed.filter((e) => e.type === 'event');
const trimmed = trimEventlist(events, selectedId, MAX_TITLES);
const formatted = formatEventList(trimmed, selectedId, nextId);
setSchedule(formatted);
}, [backstageEvents, selectedId, nextId]);
+3 -12
View File
@@ -1,26 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import './index.scss';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
// 1. import Chakra components
import { ChakraProvider, extendTheme } from '@chakra-ui/react';
// 2. Extend the theme to include custom colors, fonts, etc
const colors = {
// not yet
};
import { ChakraProvider } from '@chakra-ui/react';
// Load Open Sans typeface
require('typeface-open-sans');
const theme = extendTheme({ colors });
ReactDOM.render(
<React.StrictMode>
<ChakraProvider resetCSS theme={theme}>
<ChakraProvider resetCSS>
<BrowserRouter>
<App />
</BrowserRouter>
@@ -1,3 +1,5 @@
@use './styles/main';
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
+11
View File
@@ -0,0 +1,11 @@
//////////////////////////////////// general app style
// no decoration on lists
ul {
list-style-type: none;
}
// no resizing on text areas
textarea {
resize: none !important;
}
+4
View File
@@ -0,0 +1,4 @@
$light-bg: #2b6cb0;
$light-bg-transparent: #2b6cb055;
$light-text: #2b6cb022;
$accent: #ff7597;
+3 -6
View File
@@ -17,18 +17,15 @@ let loaded = 'Nothing loaded';
let isQuitting = false;
const nodePath =
env != 'prod'
env !== 'prod'
? path.join('file://', __dirname, 'src/app.js')
: path.join('file://', __dirname, '../', 'extraResources', 'src/app.js');
(async () => {
try {
const { startServer, startOSCServer, startOSCClient } = await import(
const { startServer, startOSCServer } = await import(
nodePath
);
// Start OSC Client (Feedback)
await startOSCClient();
// Start express server
loaded = await startServer();
@@ -140,7 +137,7 @@ app.whenReady().then(() => {
setTimeout(() => {
// Load page served by node
const reactApp =
env == 'prod'
env === 'prod'
? 'http://localhost:4001/editor'
: 'http://localhost:3000/editor';
+12 -3
View File
@@ -33,6 +33,9 @@
"dist-mac": "electron-builder --publish=never --x64 --mac",
"dist-all": "electron-builder -mw"
},
"jest": {
"testPathIgnorePatterns": ["dist"]
},
"build": {
"productName": "ontime",
"appId": "no.lightdev.ontime",
@@ -64,7 +67,9 @@
},
"files": [
"**/*",
"assets/"
"assets/",
"!**/{yarn.lock,yarn-error.log}",
"!**/{test,tests,__test__,__tests__,mock,mocks,__mock__,__mocks__}"
],
"directories": {
"buildResources": "./assets/"
@@ -74,14 +79,18 @@
"from": "../client/build",
"to": "extraResources/client/build",
"filter": [
"**/*"
"**/*",
"!**/{yarn.lock,yarn-error.log}",
"!**/{test,tests,__test__,__tests__,mock,mocks,__mock__,__mocks__}"
]
},
{
"from": "src",
"to": "extraResources/src",
"filter": [
"**/*"
"**/*",
"!**/{yarn.lock,yarn-error.log}",
"!**/{test,tests,__test__,__tests__,mock,mocks,__mock__,__mocks__}"
]
}
]
+17 -26
View File
@@ -22,7 +22,6 @@ const adapter = new JSONFile(file);
export const db = new Low(adapter);
// dependencies
import { Client } from 'node-osc';
import express from 'express';
import http from 'http';
import cors from 'cors';
@@ -48,8 +47,8 @@ if (db.data == null || !isValid) {
// get data
// there is also the case of the db being corrupt
// try to parse the data
export const data = await parseJson(db.data);
// try to parse the data, make sure that all fields exist (enforce)
export const data = await parseJson(db.data, true);
db.data = data;
await db.write();
@@ -113,17 +112,17 @@ app.use((err, req, res, next) => {
* ----------------
*
* Configuration of services comes from app general config
* It can be overriden here by the settings in the db
* It can also be overriden on call
* It can be overridden here by the settings in the db
* It can also be overridden on call
*
*/
const s = data.settings;
const oscIP = s.oscOutIP || config.osc.ipOut;
const oscOutPort = s.oscOutPort || config.osc.portOut;
const oscInPort = s.oscInPort || config.osc.port;
const osc = data.osc;
const oscIP = osc?.targetIP || config.osc.targetIP;
const oscOutPort = osc?.portOut || config.osc.portOut;
const oscInPort = osc?.port || config.osc.port;
const serverPort = s.serverPort || config.server.port;
const serverPort = data.settings.serverPort || config.server.port;
// Start OSC server
import { initiateOSC, shutdownOSCServer } from './controllers/OscController.js';
@@ -140,17 +139,6 @@ export const startOSCServer = async (overrideConfig = null) => {
initiateOSC(oscSettings);
};
// Start OSC Client
let oscClient = null;
export const startOSCClient = async (overrideConfig = null) => {
// Setup default port
const port = overrideConfig?.port || oscOutPort;
console.log('initialise OSC Client on port: ', port);
oscClient = new Client(oscIP, oscOutPort);
};
// create HTTP server
const server = http.createServer(app);
@@ -168,8 +156,14 @@ export const startServer = async (overrideConfig = null) => {
const returnMessage = `HTTP Server is listening on port ${port}`;
server.listen(port, '0.0.0.0', () => console.log(returnMessage));
// OSC Config
const oscConfig = {
ip: oscIP,
port: overrideConfig?.port || oscOutPort
}
// init timer
global.timer = new EventTimer(server, oscClient, config);
global.timer = new EventTimer(server, config.timer, oscConfig, data.http);
global.timer.setupWithEventList(data.events);
return returnMessage;
@@ -178,7 +172,7 @@ export const startServer = async (overrideConfig = null) => {
export const shutdown = async () => {
console.log('Node service shutdown');
user.event('NODE', 'shutdown', 'requesting node shutfown').send();
user.event('NODE', 'shutdown', 'requesting node shutdown').send();
// shutdown express server
server.close();
@@ -186,9 +180,6 @@ export const shutdown = async () => {
// shutdown OSC Server
shutdownOSCServer();
// shutdown OSC Client
oscClient.close();
// shutdown timer
global.timer.shutdown();
};
+429 -212
View File
@@ -1,6 +1,9 @@
import { Timer } from './Timer.js';
import { Server } from 'socket.io';
import {DAYMS, getSelectionByRoll} from './classUtils.js';
import {Timer} from './Timer.js';
import {Server} from 'socket.io';
import {DAY_TO_MS, getSelectionByRoll, replacePlaceholder, updateRoll} from './classUtils.js';
import {OSCIntegration} from './integrations/Osc.js';
import {HTTPIntegration} from "./integrations/Http.js";
import {cleanURL} from "../utils/url.js";
/*
* EventTimer adds functions specific to APP
@@ -11,11 +14,35 @@ import {DAYMS, getSelectionByRoll} from './classUtils.js';
*/
export class EventTimer extends Timer {
// Keep track of Timer lifecycle
// idle: before it is initialised
// load: when a new event is loaded
// update: every update call cycle (1 x second)
// stop: when the timer is stopped
// finish: when a timer finishes
cycleState = {
idle: 'idle',
onLoad: 'onLoad',
armed: 'armed',
onStart: 'onStart',
onUpdate: 'onUpdate',
onPause: 'onPause',
onStop: 'onStop',
onFinish: 'onFinish',
};
ontimeCycle = 'idle';
prevCycle = null;
lastUpdate = null;
// Socket IO Object
io = null;
// OSC Client
oscClient = null;
// OSC Object
osc = null;
// HTTP Client Object
http = null;
_numClients = 0;
_interval = null;
@@ -62,10 +89,21 @@ export class EventTimer extends Timer {
_eventlist = null;
onAir = false;
constructor(httpServer, oscClient, config) {
/**
* Instantiates an event timer object
* @param httpServer
* @param timerConfig
* @param [oscConfig]
* @param [httpConfig]
*/
constructor(httpServer, timerConfig, oscConfig, httpConfig) {
// call super constructor
super();
// initialise class variables
this.numEvents = 0;
// initialise socketIO server
this.io = new Server(httpServer, {
cors: {
@@ -76,135 +114,47 @@ export class EventTimer extends Timer {
},
});
// Todo: extract
// initialise osc object
if (oscConfig != null) {
console.log('initialise OSC Client on port: ', oscConfig?.port);
this.osc = new OSCIntegration();
this.osc.init(oscConfig);
}
// Todo: extract
// initialise http object
if (httpConfig != null) {
this.http = new HTTPIntegration();
this.http.init(httpConfig);
this.httpMessages = httpConfig.messages;
}
// set recurrent emits
this._interval = setInterval(
() => this.broadcastTimer(),
config.timer.refresh
() => this.runCycle(),
timerConfig?.refresh || 1000
);
// listen to new connections
this._listenToConnections();
// set oscClient
this.updateOSCClient(oscClient);
}
/**
* @description Updates the osc client used in the object
* @param {object} oscClient
*/
updateOSCClient(oscClient) {
this.oscClient = oscClient;
}
/**
* @description Sends osc value from predefined messages
* @param {string} event - message to be sent
*/
sendOSC(event) {
if (this.oscClient == null) return;
const add = '/ontime';
const play = 'play';
const pause = 'pause';
const stop = 'stop';
const prev = 'prev';
const next = 'next';
const reload = 'reload';
const finished = 'finished';
const time = this.timeTag;
const overtime = this.current > 0 ? 0 : 1;
const title = this.titles?.titleNow || '';
const presenter = this.titles?.presenterNow || '';
switch (event) {
case 'time':
// Send Timetag Message
this.oscClient.send(add + '/time', time, (err) => {
if (err) console.error(err);
});
break;
case 'finished':
// Runs when timer reaches 0
this.oscClient.send(add, finished, (err) => {
if (err) console.error(err);
});
break;
case 'overtime':
// Whether timer is negative
this.oscClient.send(add + '/overtime', overtime, (err) => {
if (err) console.error(err);
});
break;
case 'titles':
// Send Title of current event
this.oscClient.send(add + '/title', title, (err) => {
if (err) console.error(err);
});
// Send presenter data on current event
this.oscClient.send(add + '/presenter', presenter, (err) => {
if (err) console.error(err);
});
break;
case 'play':
// Play Message
this.oscClient.send(add, play, (err) => {
if (err) console.error(err);
});
break;
case 'pause':
// Pause Message
this.oscClient.send(add, pause, (err) => {
if (err) console.error(err);
});
break;
case 'stop':
// Stop Message
this.oscClient.send(add, stop, (err) => {
if (err) console.error(err);
});
break;
case 'prev':
this.oscClient.send(add, prev, (err) => {
if (err) console.error(err);
});
break;
case 'next':
this.oscClient.send(add, next, (err) => {
if (err) console.error(err);
});
break;
case 'reload':
this.oscClient.send(add, reload, (err) => {
if (err) console.error(err);
});
break;
default:
break;
}
}
/**
* @description Shutdown process
*/
shutdown() {
console.log('Closing socket server');
console.log('Shutting down integrations')
console.log('... Closing socket server');
this.io.close();
console.log('... Closing osc server');
this.osc.shutdown();
}
// send current timer
broadcastTimer() {
// through websockets
this.io.emit('timer', this.getTimes());
// through OSC, only if running
if (this.state === 'start' || this.state === 'roll') {
this.sendOSC('time');
this.sendOSC('overtime');
this.sendOSC('titles');
}
}
// broadcast state
@@ -230,11 +180,239 @@ export class EventTimer extends Timer {
this.io.emit(address, payload);
}
/**
* @description Interface for triggering playback actions
* @param {string} action - state to be triggered
* @returns {boolean} Whether action was called
*/
trigger(action) {
// Todo: reply should come from status change
let reply = true;
switch (action) {
case 'start':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.start();
this.runCycle();
break;
case 'pause':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.pause();
this.runCycle();
break;
case 'stop':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.stop();
this.runCycle();
break;
case 'roll':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.roll();
this.runCycle();
break;
case 'previous':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.previous();
this.runCycle();
break;
case 'next':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.next();
this.runCycle();
break;
case 'unload':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.unload();
this.runCycle();
break;
case 'reload':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.reload();
this.runCycle();
break;
case 'onAir':
// Call action
this.setonAir(true);
break;
case 'offAir':
// Call action and force update
this.setonAir(false);
break;
default:
// Error, disable flag
console.log('ERROR: Unhandled action triggered')
reply = false;
break;
}
return reply;
}
/**
* @description State machine checks what actions need to
* happen at every app cycle
*/
runCycle() {
const h = this.httpMessages?.messages;
let httpMessage = null;
switch (this.ontimeCycle) {
case "idle":
break;
case "armed":
// if we come from roll, see if we can start
if (this.state === 'roll') {
this.update();
}
break;
case "onLoad":
// broadcast change
this.broadcastState();
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onLoad?.url !== '') {
httpMessage = h?.onLoad?.url;
}
}
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
break;
case "onStart":
// broadcast current state
this.broadcastState();
// send OSC if there is something running
// _finish at is only set when an event is loaded
if (this._finishAt > 0) {
this.osc.send(this.osc.implemented.play);
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onStart?.url !== '') {
httpMessage = h?.onStart?.url;
}
}
// update lifecycle: onUpdate
this.ontimeCycle = this.cycleState.onUpdate;
break;
case "onUpdate":
// call update
this.update();
// broadcast current state
this.broadcastTimer();
// through OSC, only if running
if (this.state === 'start' || this.state === 'roll') {
if (this.current != null && this.secondaryTimer == null) {
this.osc.send(this.osc.implemented.time, this.timeTag);
this.osc.send(this.osc.implemented.overtime, this.current > 0 ? 0 : 1);
this.osc.send(this.osc.implemented.title, this.titles?.titleNow || '');
}
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onUpdate?.url !== '') {
httpMessage = h?.onUpdate?.url;
}
}
break;
case "onPause":
// broadcast current state
this.broadcastState();
// send OSC
this.osc.send(this.osc.implemented.pause);
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onPause?.url !== '') {
httpMessage = h?.onPause?.url;
}
}
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
break;
case "onStop":
// broadcast change
this.broadcastState();
// send OSC if something was actually stopped
if (this.prevCycle === this.cycleState.onUpdate) {
this.osc.send(this.osc.implemented.stop);
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onStop?.url !== '') {
httpMessage = h?.onStop?.url;
}
}
// update lifecycle: idle
this.ontimeCycle = this.cycleState.idle;
break;
case "onFinish":
console.log('onFinish')
// broadcast change
this.broadcastState(false);
// finished an event
this.osc.send(this.osc.implemented.finished);
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onFinish?.url !== '') {
httpMessage = h?.onFinish?.url;
}
}
// update lifecycle: onUpdate
this.ontimeCycle = this.cycleState.onUpdate;
break;
default:
console.log(`ERROR: Unhandled cycle: ${this.ontimeCycle}`)
}
// send http message if any
if (httpMessage != null) {
const v = {
'$timer': this.timeTag,
'$title': this.titles.titleNow,
'$presenter': this.titles.presenterNow,
'$subtitle': this.titles.subtitleNow,
'$next-title': this.titles.titleNext,
'$next-presenter': this.titles.presenterNext,
'$next-subtitle': this.titles.subtitleNext,
}
const m = cleanURL(replacePlaceholder(httpMessage, v));
this.http.send(m);
}
// update
this.update();
// reset cycle
this.prevCycle = this.ontimeCycle;
}
update() {
// if there is nothing selected, update clock
const now = this._getCurrentTime();
// if there is nothing selected, update only clock
if (this.selectedEventId == null && this.state !== 'roll') {
// if we are not updating, send the timers
if (this.ontimeCycle !== this.cycleState.onUpdate) {
this.clock = now;
this.broadcastThis('timer', {
clock: now,
@@ -244,81 +422,59 @@ export class EventTimer extends Timer {
expectedFinish: this._getExpectedFinish(),
startedAt: this._startedAt,
});
return;
}
// only implement roll here
if (this.state !== 'roll') {
super.update();
} else {
// update timer as usual
this.clock = now;
if (this.selectedEventId && this.current > 0) {
// something is running, update
this.current = this._finishAt - now;
} else if (this.secondaryTimer > 0) {
// waiting to start, update secondary
this.secondaryTimer = this._secondaryTarget - now;
// Have we skipped onStart?
if (this.state === 'start' || this.state === 'roll') {
if (this.ontimeCycle === this.cycleState.armed) {
// update lifecycle: onStart
this.ontimeCycle = this.cycleState.onStart;
this.runCycle();
}
}
// update default functions
super.update();
if (this._finishedFlag) {
// update lifecycle: onFinish and call cycle
this.ontimeCycle = this.cycleState.onFinish;
this._finishedFlag = false;
this.runCycle();
}
// only implement roll here, rest implemented in super
if (this.state === 'roll') {
const u = {
selectedEventId: this.selectedEventId,
current: this.current,
// safeguard on midnight rollover
_finishAt: this._finishAt >= this._startedAt ? this._finishAt : this._finishAt + DAY_TO_MS,
clock: this.clock,
secondaryTimer: this.secondaryTimer,
_secondaryTarget: this._secondaryTarget,
}
// look for event if none is loaded
const currentRunning = this.current <= 0 && this.current !== null;
const secondaryRunning =
this.secondaryTimer <= 0 && this.secondaryTimer !== null;
const {updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished} = updateRoll(u);
if (currentRunning) {
// finished an event
this.sendOSC('finished');
this._finishedFlag = true;
this.current = updatedTimer;
this.secondaryTimer = updatedSecondaryTimer;
if (isFinished) {
// update lifecycle: onFinish
this.ontimeCycle = this.cycleState.onFinish;
this.runCycle();
}
if (currentRunning || secondaryRunning) {
// look for events
if (doRollLoad) {
this.rollLoad();
// broadcast state without recalculating timer
this.broadcastState(false);
}
}
// if event is finished
if (
this.current <= 0 &&
(this.state === 'start' || this.state === 'roll') &&
!this._finishedFlag
) {
if (this._finishedAt === null) {
this._finishedAt = now;
}
this.sendOSC('finished');
this._finishedFlag = true;
}
}
_setterManager(action, payload) {
switch (action) {
/*******************************************/
// playstate
case 'set-playstate':
// check state is defined
if (payload === 'start') this.start();
else if (payload === 'pause') this.pause();
else if (payload === 'stop') this.stop();
else if (payload === 'previous') this.previous();
else if (payload === 'next') this.next();
else if (payload === 'reload') this.reload();
else if (payload === 'unload') this.unload();
else if (payload === 'roll') this.roll();
// TODO: Cleanup
// here tdo this.broadcastState;
// remove broadcast from functions
this.broadcastThis('playstate', this.state);
this.broadcastThis('selected-id', this.selectedEventId);
this.broadcastThis('titles', this.titles);
break;
/*******************************************/
// Presenter message
case 'set-presenter-text':
@@ -423,7 +579,7 @@ export class EventTimer extends Timer {
/*******************************************/
// playstate
socket.on('set-playstate', (data) => {
this._setterManager('set-playstate', data);
this.trigger(data);
});
socket.on('get-playstate', () => {
@@ -453,6 +609,10 @@ export class EventTimer extends Timer {
socket.emit('selected-id', this.selectedEventId);
});
socket.on('get-numevents', () => {
socket.emit('numevents', this.numEvents);
});
socket.on('get-next-id', () => {
socket.emit('next-id', this.nextEventId);
});
@@ -539,8 +699,11 @@ export class EventTimer extends Timer {
this._eventlist = [];
this.numEvents = 0;
// broadcast change
this.broadcastState();
// update lifecycle: onStop
this.ontimeCycle = this.cycleState.onStop;
// update clients
this.broadcastThis('numevents', this.numEvents);
}
setupWithEventList(eventlist) {
@@ -559,6 +722,12 @@ export class EventTimer extends Timer {
// load first event
this.loadEvent(0);
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
updateEventList(eventlist) {
@@ -601,7 +770,11 @@ export class EventTimer extends Timer {
this.loadEvent(eventIndex, type);
}
this.broadcastState();
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
updateSingleEvent(id, entry) {
@@ -640,7 +813,11 @@ export class EventTimer extends Timer {
console.log(error);
}
this.broadcastState();
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
deleteId(eventId) {
@@ -670,37 +847,53 @@ export class EventTimer extends Timer {
this._loadTitlesNow();
}
this.broadcastState();
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
/**
* @description loads an event with a given Id
* @param eventId - ID of event in eventlist
*/
loadEventById(eventId) {
const eventIndex = this._eventlist.findIndex((e) => e.id === eventId);
if (eventIndex === -1) return;
this.pause();
this.loadEvent(eventIndex, 'load', true);
// run cycle
this.runCycle();
}
/**
* @description loads an event with a given index
* @param eventIndex - Index of event in eventlist
*/
loadEventByIndex(eventIndex) {
if (eventIndex === -1 || eventIndex > this.numEvents) return;
this.pause();
this.loadEvent(eventIndex, 'load', true);
// run cycle
this.runCycle();
}
// Loads a given event
// load timers
// load selectedEventIndex
// load titles
loadEvent(eventIndex, type = 'load', broadcastChange = 'false') {
loadEvent(eventIndex, type = 'load') {
const e = this._eventlist[eventIndex];
if (e == null) return;
const start = e.timeStart == null || e.timeStart === '' ? 0 : e.timeStart;
let end = e.timeEnd == null || e.timeEnd === '' ? 0 : e.timeEnd;
// in case the end is earlier than start, we assume is the day after
if (end < start) end += DAYMS;
if (end < start) end += DAY_TO_MS;
// time stuff changes on wheter we keep the running clock
// time stuff changes on whether we keep the running clock
if (type === 'load') {
this._resetTimers();
@@ -724,9 +917,8 @@ export class EventTimer extends Timer {
// look for event after
this._loadTitlesNext();
if (broadcastChange)
// broadcast current state
this.broadcastState();
// update lifecycle: onLoad
this.ontimeCycle = this.cycleState.onLoad;
}
_loadTitlesNow() {
@@ -980,54 +1172,55 @@ export class EventTimer extends Timer {
}
start() {
// do we need to change
if (this.state === 'start') return;
// if there is nothing selected, no nothing
if (this.selectedEventId == null) return;
// call super
super.start();
// broadcast current state
this.broadcastState();
// send OSC
this.sendOSC('play');
// update lifecycle: onStart
this.ontimeCycle = this.cycleState.onStart;
}
pause() {
// do we need to change
if (this.state === 'pause') return;
// if there is nothing selected, no nothing
if (this.selectedEventId == null) return;
// call super
super.pause();
// broadcast current state
this.broadcastState();
// send OSC
this.sendOSC('pause');
// update lifecycle: onPause
this.ontimeCycle = this.cycleState.onPause;
}
stop() {
// do we need to change
if (this.state === 'stop') return;
// call super
super.stop();
// broadcast current state
this.broadcastState();
// send OSC
this.sendOSC('stop');
// update lifecycle: onPause
this.ontimeCycle = this.cycleState.onStop;
}
increment(amount) {
// call super
super.increment(amount);
// broadcast current state
this.broadcastState();
// run cycle
this.runCycle();
}
rollLoad() {
const now = this._getCurrentTime();
let prevLoaded = this.selectedEventId;
// maybe roll has already been loaded
if (this.secondaryTimer === null) {
@@ -1103,18 +1296,31 @@ export class EventTimer extends Timer {
if (publicIndex !== null) {
this._loadThisTitles(this._eventlist[publicIndex], 'now-public');
}
if (prevLoaded !== this.selectedEventId) {
// update lifecycle: onLoad
this.ontimeCycle = this.cycleState.onLoad;
// ensure we go through onLoad cycle
this.runCycle();
}
}
roll() {
// do we need to change
if (this.state === 'roll') return;
if (this.numEvents === 0 || this.numEvents == null) return;
// set state
this.state = 'roll';
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
// load into event
this.rollLoad();
// broadcast change
this.broadcastState();
}
@@ -1122,6 +1328,9 @@ export class EventTimer extends Timer {
// check that we have events to run
if (this.numEvents < 1) return;
// maybe this is the first event?
if (this.selectedEventIndex === 0) return;
// if there is no event running, go to first
if (this.selectedEventIndex == null) {
this.loadEvent(0);
@@ -1129,7 +1338,7 @@ export class EventTimer extends Timer {
}
// send OSC
this.sendOSC('prev');
this.osc.send(this.osc.implemented.previous);
// change playstate
this.pause();
@@ -1145,6 +1354,9 @@ export class EventTimer extends Timer {
// check that we have events to run
if (this.numEvents < 1) return;
// maybe this is the last event?
if (this.selectedEventIndex === this.numEvents - 1) return;
// if there is no event running, go to first
if (this.selectedEventIndex == null) {
this.loadEvent(0);
@@ -1152,7 +1364,7 @@ export class EventTimer extends Timer {
}
// send OSC
this.sendOSC('next');
this.osc.send(this.osc.implemented.next);
// change playstate
this.pause();
@@ -1173,16 +1385,21 @@ export class EventTimer extends Timer {
// reset selected
this._resetSelection();
// broadcast state
this.broadcastState();
// reset playstate
this.stop();
}
reload() {
// reset playstate
if (this.numEvents === 0 || this.numEvents == null) return;
// change playstate
this.pause();
// send OSC
this.sendOSC('reload');
this.osc.send(this.osc.implemented.reload);
// reload data
this.loadEvent(this.selectedEventIndex);
+46 -11
View File
@@ -24,11 +24,35 @@ export class Timer {
constructor() {}
// call setup separately
setupWithSeconds(seconds, autoStart = false) {
// aux
const now = this._getCurrentTime();
this.clock = now;
// populate targets
this.duration = seconds * 1000;
this._finishAt = now + seconds * 1000;
// start counting
this._startedAt = now;
if (autoStart) {
this.state = 'start';
} else {
this._pausedAt = now;
this._pausedInterval = 0;
}
this._pausedTotal = 0;
this.update();
}
// update()
update() {
// get current time
const now = this._getCurrentTime();
this.clock = now;
let checkFinish = false;
// check playstate
switch (this.state) {
@@ -40,6 +64,8 @@ export class Timer {
this.current =
this._startedAt + this.duration + this._pausedTotal - now;
// enable flag
checkFinish = true;
break;
case 'pause':
// update paused time
@@ -48,28 +74,37 @@ export class Timer {
if (this._startedAt != null) {
// update current timer
this.current =
this._startedAt +
this.duration +
this._pausedTotal +
this._pausedInterval -
now;
this._startedAt
+ this.duration
+ this._pausedTotal
+ this._pausedInterval
- now;
}
// enable flag
checkFinish = true;
break;
case 'stop':
// nothing here yet
break;
default:
console.error('Timer: no playstate on update call', this.state);
break;
}
if (checkFinish) {
// is event finished?
const isTimeOver = this.current <= 0;
const isUpdating = (this.state !== 'pause');
if (isTimeOver && isUpdating && this._finishedAt == null) {
if (this._finishedAt === null) this._finishedAt = now;
this._finishedFlag = true;
}
}
}
// helpers
static toSeconds(millis) {
if (millis == null) return null;
return Math.ceil(millis * 0.001);
}
// get current time in epoc
@@ -148,7 +183,7 @@ export class Timer {
// do we need to change
if (this.state === 'start') return;
else if (this._startedAt == null) {
// it hasnt started yet
// it hasn't started yet
const now = this._getCurrentTime();
// set start time as now
this._startedAt = now;
+187 -28
View File
@@ -1,22 +1,29 @@
import {DAYMS, getSelectionByRoll, normaliseEndTime, sortArrayByProperty} from '../classUtils.js';
import {
DAY_TO_MS,
getSelectionByRoll,
replacePlaceholder,
normaliseEndTime,
sortArrayByProperty,
updateRoll
} from '../classUtils.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 },
{timeStart: 1},
{timeStart: 5},
{timeStart: 3},
{timeStart: 2},
{timeStart: 4},
];
const arr1Expected = [
{ timeStart: 1 },
{ timeStart: 2 },
{ timeStart: 3 },
{ timeStart: 4 },
{ timeStart: 5 },
{timeStart: 1},
{timeStart: 2},
{timeStart: 3},
{timeStart: 4},
{timeStart: 5},
];
const sorted = sortArrayByProperty(arr1, 'timeStart');
@@ -25,21 +32,21 @@ describe('sort simple arrays of objects', () => {
it('sort array 1-5 with null', () => {
const arr1 = [
{ timeStart: 1 },
{ timeStart: 5 },
{ timeStart: 3 },
{ timeStart: 2 },
{ timeStart: 4 },
{ timeStart: null },
{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 },
{timeStart: null},
{timeStart: 1},
{timeStart: 2},
{timeStart: 3},
{timeStart: 4},
{timeStart: 5},
];
const sorted = sortArrayByProperty(arr1, 'timeStart');
@@ -244,7 +251,6 @@ describe('test that roll loads selection in right order', () => {
});
// test getSelectionByRoll()
describe('test that roll behaviour with overlapping times', () => {
const eventlist = [
{
@@ -384,6 +390,68 @@ describe('test that roll behaviour with overlapping times', () => {
});
});
// test replacePlaceholder()
describe('test that it replaces data correctly', () => {
const values = {
$timer: "timer",
$title: "title",
$presenter: "presenter",
$subtitle: "subtitle",
"$next-title": "next title",
"$next-presenter": "next presenter",
"$next-subtitle": "next subtitle"
};
it('replaces timer', () => {
const test = '___1232132 $timer';
const expected = '___1232132 timer';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces title', () => {
const test = '___1232132 $title';
const expected = '___1232132 title';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces presenter', () => {
const test = '___1232132 $presenter';
const expected = '___1232132 presenter';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces subtitle', () => {
const test = '___1232132 $subtitle';
const expected = '___1232132 subtitle';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces next next title', () => {
const test = '___1232132 $next-title';
const expected = '___1232132 next title';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces next presenter', () => {
const test = '___1232132 $next-presenter';
const expected = '___1232132 next presenter';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces next subtitle', () => {
const test = '___1232132 $next-subtitle';
const expected = '___1232132 next subtitle';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
});
// test getSelectionByRoll() on issue #58
describe('test that roll behaviour multi day event edge cases', () => {
@@ -407,8 +475,8 @@ describe('test that roll behaviour multi day event edge cases', () => {
timers: {
_startedAt: eventlist[0].timeStart,
_finishAt: eventlist[0].timeEnd,
current: eventlist[0].timeEnd + DAYMS - now,
duration: DAYMS - eventlist[0].timeStart + eventlist[0].timeEnd,
current: eventlist[0].timeEnd + DAY_TO_MS - now,
duration: DAY_TO_MS - eventlist[0].timeStart + eventlist[0].timeEnd,
},
timeToNext: null,
};
@@ -454,10 +522,10 @@ test('test typical scenarios', () => {
expect(normaliseEndTime(t1.start, t1.end)).toBe(t1_expected);
const t2 = {
start: 10+DAYMS,
start: 10 + DAY_TO_MS,
end: 20,
}
const t2_expected = 20+DAYMS;
const t2_expected = 20 + DAY_TO_MS;
expect(normaliseEndTime(t2.start, t2.end)).toBe(t2_expected);
@@ -470,3 +538,94 @@ test('test typical scenarios', () => {
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: timers._finishAt - timers.clock,
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);
});
});
@@ -0,0 +1,137 @@
import {EventTimer} from "../EventTimer";
import http from 'http';
import express from "express";
// Create server
const app = express();
const server = http.createServer(app);
// necessary config
const timerConfig = {refresh: 1000};
beforeEach(async () => {
server.listen(0, '0.0.0.0');
});
afterEach(async () => {
await server.close();
});
test('object instantiates correctly', async () => {
const t = new EventTimer(server, timerConfig);
// it contains everything from Timer
expect(t.clock).toBeNull();
expect(t.duration).toBeNull();
expect(t.current).toBeNull();
expect(t.timeTag).toBeNull();
expect(t.secondaryTimer).toBeNull();
expect(t._secondaryTarget).toBeNull();
expect(t._finishAt).toBeNull();
expect(t._finishedAt).toBeNull();
expect(t._finishedFlag).toBeFalsy();
expect(t._startedAt).toBeNull();
expect(t._pausedAt).toBeNull();
expect(t._pausedInterval).toBeNull();
expect(t._pausedTotal).toBeNull();
expect(t.state).toBe('stop');
// and its own properties
expect(t.ontimeCycle).toBe('idle');
expect(t.prevCycle).toBeNull();
expect(t.lastUpdate).toBeNull();
expect(t.io).not.toBeNull();
expect(t.osc).toBeNull();
expect(t.http).toBeNull();
expect(t._numClients).toBe(0);
expect(t._interval).not.toBeNull();
expect(t.presenter).toStrictEqual({text: '', visible: false});
expect(t.public).toStrictEqual({text: '', visible: false});
expect(t.lower).toStrictEqual({text: '', visible: false});
expect(t.lower).toStrictEqual({text: '', visible: false});
const expectTitlesPublic = {
titleNow: null,
subtitleNow: null,
presenterNow: null,
titleNext: null,
subtitleNext: null,
presenterNext: null,
};
const expectTitles = {
...expectTitlesPublic,
noteNow: null,
noteNext: null,
};
expect(t.titlesPublic).toStrictEqual(expectTitlesPublic);
expect(t.titles).toStrictEqual(expectTitles);
expect(t.selectedEventIndex).toBeNull();
expect(t.selectedEventId).toBeNull();
expect(t.nextEventId).toBeNull();
expect(t.selectedPublicEventId).toBeNull();
expect(t.nextPublicEventId).toBeNull();
expect(t.numEvents).toBe(0);
expect(t._eventlist).toBeNull();
expect(t.onAir).toBeFalsy();
});
describe('test triggers behaviour', () => {
const t = new EventTimer(server, timerConfig);
it('ignores bad commands', () => {
const success = t.trigger('test');
expect(success).toBeFalsy();
})
it('does not allow triggering events with an empty list', () => {
expect(t.numEvents).toBe(0);
expect(t.trigger('start')).toBeFalsy();
expect(t.trigger('pause')).toBeFalsy();
expect(t.trigger('stop')).toBeFalsy();
expect(t.trigger('roll')).toBeFalsy();
expect(t.trigger('previous')).toBeFalsy();
expect(t.trigger('next')).toBeFalsy();
expect(t.trigger('reload')).toBeFalsy();
expect(t.onAir).toBeFalsy();
expect(t.trigger('onAir')).toBeTruthy();
expect(t.onAir).toBeTruthy();
expect(t.trigger('offAir')).toBeTruthy();
expect(t.onAir).toBeFalsy();
});
it('...and is consistent by calling the class methods', () => {
expect(t.numEvents).toBe(0);
expect(t.state).toBe('stop');
t.start();
expect(t.state).toBe('stop');
t.pause();
expect(t.state).toBe('stop');
t.stop();
expect(t.state).toBe('stop');
t.roll();
expect(t.state).toBe('stop');
t.previous();
expect(t.state).toBe('stop');
t.next();
expect(t.state).toBe('stop');
t.reload();
expect(t.state).toBe('stop');
});
})
+81 -6
View File
@@ -1,13 +1,17 @@
export const DAYMS = 86400000;
/**
* Utility variable: 24 hour in milliseconds .
* @type {number}
*/
export const DAY_TO_MS = 86400000;
/**
* @description handle events that span over midnight
* @param {num} start - When does the event start
* @param {num} end - When does the event end
* @returns {num} normalised time
* @param {number} start - When does the event start
* @param {number} end - When does the event end
* @returns {number} normalised time
*/
export const normaliseEndTime = (start, end) => (end < start ? end + DAYMS : end);
export const normaliseEndTime = (start, end) => (end < start ? end + DAY_TO_MS : end);
/**
* @description Sorts an array of objects by given property
@@ -22,6 +26,21 @@ export const sortArrayByProperty = (arr, property) => {
});
};
/**
* @description Replaces placeholder variables in string with given data
* @param {string} str - string to analyse
* @param {object} values - map of variables: values to use
* @returns {string} finished string
*/
export const replacePlaceholder = (str, values) => {
for (let [k, v] of Object.entries(values)) {
str = str.replace(k, v);
console.log(k, v);
}
return str;
};
/**
* @description Used in roll mode, returns selection variables from array
* @param {array} arr - event list
@@ -130,3 +149,59 @@ export const getSelectionByRoll = (arr, now) => {
};
};
/**
* @description Implements update functions for roll mode
* @param {object} currentTimers
* @param {object} currentTimers.selectedEventId - Id of currently selected event
* @param {object} currentTimers.current - Running timer
* @param {object} currentTimers._finishAt - Expected finish time
* @param {object} currentTimers.clock - time now
* @param {object} currentTimers.secondaryTimer - secondary timer
* @param {object} currentTimers._secondaryTarget - finish time of secondary timer
* @returns {object} object with selection variables
*/
export const updateRoll = (currentTimers) => {
const {selectedEventId,current,_finishAt,clock,secondaryTimer,_secondaryTarget} = currentTimers;
// timers
let updatedTimer = current;
let updatedSecondaryTimer = secondaryTimer;
// whether rollLoad should be called
let doRollLoad = false;
// whether runCycle should be called
let isFinished = false;
if (selectedEventId && current >= 0) {
// if we have something selected and a timer, we are running
// this is true because roll never goes into negative times
// update timer
updatedTimer = _finishAt - clock;
if (updatedTimer < 0) {
isFinished = true;
}
console.log(updatedTimer, isFinished, _finishAt)
} else if (secondaryTimer >= 0) {
// if secondaryTimer is running we are in waiting to roll
// update secondary
updatedSecondaryTimer = _secondaryTarget - clock;
}
// if nothing is running, we need to find out if
// a) we just finished an event (finished was set to true)
// b) we need to look for events
// this could be caused by a secondary timer or event finished
const secondaryRunning =
updatedSecondaryTimer <= 0 && updatedSecondaryTimer != null;
if (isFinished || secondaryRunning) {
// look for events
doRollLoad = true;
}
return {updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished};
}
+52
View File
@@ -0,0 +1,52 @@
/** Class contains logic towards outgoing HTTP communications. */
import * as http from 'http';
export class HTTPIntegration {
constructor() {
// nothing to do here
}
/**
* @description Initializes oscClient
* @param {object} httpConfig - Http configurations options
*/
init(httpConfig) {
}
/**
* @description Sends http get request from predefined messages
* @param {string} path - complete http path
*/
async send(path) {
if (path == null) {
console.log('HTTP ERROR: Message undefined');
return;
}
const options = new URL(path);
let str = '';
const req = http.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', function (chunk) {
str += chunk;
});
res.on('end', function () {
console.log(str);
});
})
req.on('error', error => {
console.error(error)
})
req.end()
}
shutdown() { /* Nothing to shutdown */ }
}
+107
View File
@@ -0,0 +1,107 @@
/** Class contains logic towards outgoing OSC communications. */
import {Client, Message} from 'node-osc';
export class OSCIntegration {
ADDRESS = '/ontime';
constructor() {
// OSC Client
this.oscClient = null;
}
/**
* @description Returns list of implemented messages
* @returns {object} implemented messages
*/
get implemented() {
return {
play: 'play',
pause: 'pause',
stop: 'stop',
previous: 'prev',
next: 'next',
reload: 'reload',
finished: 'finished',
time: 'time',
overtime: 'overtime',
title: 'title',
presenter:'presenter',
}
}
/**
* @description Initializes oscClient
* @param {object} oscConfig - oscClient configuration options
* @param {string} oscConfig.ip - oscClient object
* @param {number} oscConfig.port - OSC Destination Port
*/
init(oscConfig) {
const {ip, port} = oscConfig;
try {
this.oscClient = new Client(ip, port);
console.log(`Initialised OSC Client at ${ip}:${port}`);
} catch (error) {
this.oscClient = null;
console.log(`Failed initialising OSC Client: ${error}`);
}
}
/**
* @description Sends osc from predefined messages
* @param {string} messageType - message to be sent
* @param {string} [payload] - optional payload required in some message types
*/
async send(messageType, payload) {
if (this.oscClient == null) {
console.log('OSC ERROR: Client not initialised');
return;
}
if (messageType == null) {
console.log('OSC ERROR: Message undefined');
return;
}
// only specify special cases
switch (payload) {
case 'overtime':
// Whether timer is negative
this.oscClient.send(`${this.ADDRESS}/overtime`, payload, (err) => {
if (err) console.error(err);
});
break;
case 'title':
if (payload != null && payload !== "") {
// Send Title of current event
this.oscClient.send(`${this.ADDRESS}/title`, payload, (err) => {
if (err) console.error(err);
});
}
break;
case 'presenter':
if (payload != null && payload !== "") {
// Send presenter data on current event
this.oscClient.send(`${this.ADDRESS}/presenter`, payload, (err) => {
if (err) console.error(err);
});
}
break;
default:
// catch all for messages, allows to add new messages
// but should be used with the integrations definition
const message = new Message(`${this.ADDRESS}/${messageType}`)
if (payload != null) message.append(payload)
this.oscClient.send(message, (err) => {
if (err) console.error(err);
});
break;
}
}
shutdown() {
// Shutdown client object
this.oscClient.close();
this.oscClient = null;
}
}
+7 -1
View File
@@ -11,7 +11,13 @@ export const config = {
},
osc: {
port: 8888,
ipOut: '127.0.0.1',
portOut: 9999,
targetIP: '127.0.0.1',
enabled: true,
},
http: {
user: '',
pwd: '',
enabled: true,
},
};
+7 -7
View File
@@ -47,32 +47,32 @@ export const initiateOSC = (config) => {
case 'start':
case 'play':
console.log('calling play');
global.timer.start();
global.timer.trigger('start');
break;
case 'pause':
console.log('calling pause');
global.timer.pause();
global.timer.trigger('pause');
break;
case 'prev':
console.log('calling prev');
global.timer.previous();
global.timer.trigger('previous');
break;
case 'next':
console.log('calling next');
global.timer.next();
global.timer.trigger('next');
break;
case 'unload':
case 'stop':
console.log('calling unload');
global.timer.unload();
global.timer.trigger('unload');
break;
case 'reload':
console.log('calling reload');
global.timer.reload();
global.timer.trigger('reload');
break;
case 'roll':
console.log('calling roll');
global.timer.roll();
global.timer.trigger('roll');
break;
case 'delay':
console.log('calling delay with', args);
+9 -17
View File
@@ -9,14 +9,6 @@ import {
block as blockDef,
} from '../models/eventsDefinition.js';
function _getEventsCount() {
return Array.from(data.events).length;
}
function _pushNew(entry) {
return data.events.push(entry).write();
}
async function _insertAt(entry, index) {
// get events
let events = data.events;
@@ -26,7 +18,7 @@ async function _insertAt(entry, index) {
// Remove order field from object
delete entry.order;
// Insert at beggining
// Insert at beginning
if (order === 0) {
events.unshift(entry);
}
@@ -47,7 +39,7 @@ async function _insertAt(entry, index) {
}
async function _removeById(eventId) {
data.events = Array.from(data.events).filter((e) => e.id != eventId);
data.events = Array.from(data.events).filter((e) => e.id !== eventId);
await db.write();
}
@@ -122,7 +114,7 @@ export const eventsPost = async (req, res) => {
const index = newEvent.order || 0;
// add new event in place
_insertAt(newEvent, index);
await _insertAt(newEvent, index);
// update timers
_updateTimers();
@@ -160,7 +152,7 @@ export const eventsPut = async (req, res) => {
const e = data.events[eventIndex];
data.events[eventIndex] = { ...e, ...req.body };
data.events[eventIndex].revision++;
db.write();
await db.write();
// update timer
_updateTimersSingle(eventId, req.body);
@@ -176,7 +168,7 @@ export const eventsPut = async (req, res) => {
// Returns -
export const eventsPatch = async (req, res) => {
// Code is the same as put, call that
eventsPut(req, res);
await eventsPut(req, res);
};
export const eventsReorder = async (req, res) => {
@@ -207,7 +199,7 @@ export const eventsReorder = async (req, res) => {
// save events
data.events = events;
db.write();
await db.write();
// TODO: would it be more efficient to reorder at timer?
// update timer
@@ -273,7 +265,7 @@ export const eventsApplyDelay = async (req, res) => {
// update events
data.events = events;
db.write();
await db.write();
// update timer
_updateTimers();
@@ -297,7 +289,7 @@ export const eventsDelete = async (req, res) => {
try {
// remove new event
_removeById(req.params.eventId);
await _removeById(req.params.eventId);
// update timer
_deleteTimerId(req.params.eventId);
@@ -316,7 +308,7 @@ export const eventsDeleteAll = async (req, res) => {
try {
// set with nothing
data.events = [];
db.write();
await db.write();
// update timer object
global.timer.clearEventList();
+33 -6
View File
@@ -95,9 +95,13 @@ const getNetworkInterfaces = () => {
export const getInfo = async (req, res) => {
const version = data.settings.version;
const serverPort = data.settings.serverPort;
const oscInPort = data.settings.oscInPort;
const oscOutPort = data.settings.oscOutPort;
const oscOutIP = data.settings.oscOutIP;
const osc = {
port: data.osc.port,
portOut: data.osc.portOut,
targetIP: data.osc.targetIP,
enabled: data.osc.enabled,
};
// get nif and inject localhost
const ni = getNetworkInterfaces();
@@ -108,9 +112,7 @@ export const getInfo = async (req, res) => {
networkInterfaces: ni,
version,
serverPort,
oscInPort,
oscOutPort,
oscOutIP,
osc,
});
};
@@ -132,6 +134,31 @@ export const postInfo = async (req, res) => {
}
};
// Create controller for POST request to '/ontime/osc'
// Returns -
export const getOSC = async (req, res) => {
// send object with network information
res.status(200).send(data.osc);
};
// Create controller for POST request to '/ontime/osc'
// Returns ACK message
export const postOSC = async (req, res) => {
if (!req.body) {
res.status(400).send('No object found in request');
return;
}
// TODO: validate data
try {
data.osc = { ...data.osc, ...req.body };
await db.write();
res.sendStatus(200);
} catch (error) {
res.status(400).send(error);
console.log(error);
}
};
// Create controller for POST request to '/ontime/db'
// Returns -
export const dbUpload = async (req, res) => {
+10 -21
View File
@@ -8,79 +8,68 @@ export const pbGet = async (req, res) => {
// Turns onAir flag to true
export const onAir = async (req, res) => {
console.log('Setting onAir to true');
global.timer.setonAir(true);
res.sendStatus(200);
global.timer.trigger('onAir') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/onAir'
// Turns onAir flag to true
export const offAir = async (req, res) => {
console.log('Setting onAir to false');
global.timer.setonAir(false);
res.sendStatus(200);
global.timer.trigger('offAir') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/start'
// Starts timer object
export const pbStart = async (req, res) => {
console.log('Calling start');
global.timer.start();
res.sendStatus(200);
global.timer.trigger('start') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/pause'
// Pauses timer object
export const pbPause = async (req, res) => {
console.log('Calling pause');
global.timer.pause();
res.sendStatus(200);
global.timer.trigger('pause') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/stop'
// Stops timer object
export const pbStop = async (req, res) => {
console.log('Calling stop');
global.timer.stop();
res.sendStatus(200);
global.timer.trigger('stop') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/roll'
// Sets timer object to roll mode
export const pbRoll = async (req, res) => {
console.log('Calling roll');
global.timer.roll();
res.sendStatus(501);
global.timer.trigger('roll') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/previous'
// Sets timer object to roll mode
export const pbPrevious = async (req, res) => {
console.log('Calling previous');
global.timer.previous();
res.sendStatus(200);
global.timer.trigger('previous') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/next'
// Sets timer object to roll mode
export const pbNext = async (req, res) => {
console.log('Calling next');
global.timer.next();
res.sendStatus(200);
global.timer.trigger('next') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/unload'
// Unloads any events
export const pbUnload = async (req, res) => {
console.log('Calling unload');
global.timer.unload();
res.sendStatus(200);
global.timer.trigger('unload') ? res.sendStatus(200) : res.sendStatus(400);
};
// Create controller for GET request to '/playback/reload'
// Reloads current event
export const pbReload = async (req, res) => {
console.log('Calling reload');
global.timer.reload();
res.sendStatus(200);
global.timer.trigger('reload') ? res.sendStatus(200) : res.sendStatus(400);
};
+38 -5
View File
@@ -11,10 +11,43 @@ export const dbModelv1 = {
app: 'ontime',
version: 1,
serverPort: 4001,
oscInPort: 8888,
oscOutPort: 9999,
oscOutIP: '127.0.0.1',
oscEnabled: false,
lock: false,
lock: null,
},
osc: {
port: 8888,
portOut: 9999,
targetIP: '127.0.0.1',
enabled: true,
},
http: {
user: null,
pwd: null,
messages: {
onLoad: {
url: '',
enabled: false,
},
onStart: {
url: '',
enabled: false,
},
onUpdate: {
url: '',
enabled: false,
},
onPause: {
url: '',
enabled: false,
},
onStop: {
url: '',
enabled: false,
},
onFinish: {
url: '',
enabled: false,
},
},
enabled: true,
},
};
+1 -9
View File
@@ -15,15 +15,7 @@
"socket.io": "^4.3.1",
"universal-analytics": "^0.4.23"
},
"devDependencies": {
"eslint": "^7.26.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.23.2",
"eslint-plugin-react-hooks": "^4.2.0",
"eslint-plugin-simple-import-sort": "^7.0.0"
},
"devDependencies": {},
"scripts": {
"nodestart": "nodemon app.js",
"start": "node app.js"
+9 -1
View File
@@ -8,6 +8,8 @@ import {
getInfo,
postInfo,
dbPathToUpload,
getOSC,
postOSC,
} from '../controllers/ontimeController.js';
// create route between controller and '/ontime/db' endpoint
@@ -17,10 +19,16 @@ router.get('/db', dbDownload);
router.post('/db', uploadFile, dbUpload);
// create route between controller and '/ontime/info' endpoint
router.get('/info', uploadFile, getInfo);
router.get('/info', getInfo);
// create route between controller and '/ontime/info' endpoint
router.post('/info', postInfo);
// create route between controller and '/ontime/osc' endpoint
router.get('/osc', getOSC);
// create route between controller and '/ontime/osc' endpoint
router.post('/osc', postOSC);
// create route between controller and '/ontime/dbpath' endpoint
router.post('/dbpath', dbPathToUpload);
+9 -22
View File
@@ -6,7 +6,6 @@ import {
validateEventv1,
} from '../parser.js';
import { dbModelv1 as dbModel } from '../../models/dataModel.js';
import { describe } from 'jest-circus';
describe('test json parser with valid def', () => {
const testData = {
@@ -133,6 +132,7 @@ describe('test json parser with valid def', () => {
revision: 0,
id: '4b31',
};
expect(first).toStrictEqual(expected);
});
it('loaded event settings', () => {
@@ -192,7 +192,7 @@ describe('test parser edge cases', () => {
const parseResponse = await parseJsonv1(testData);
expect(console.log).toHaveBeenCalledWith(
'ERROR: ID colision on import, skipping'
'ERROR: ID collision on import, skipping'
);
expect(parseResponse?.events.length).toBe(1);
});
@@ -267,11 +267,7 @@ describe('test corrupt data', () => {
app: 'ontime',
version: 1,
serverPort: 4001,
oscInPort: 8888,
oscOutPort: 9999,
oscOutIP: '127.0.0.1',
oscEnabled: false,
lock: false,
lock: null,
},
};
@@ -293,11 +289,7 @@ describe('test corrupt data', () => {
app: 'ontime',
version: 1,
serverPort: 4001,
oscInPort: 8888,
oscOutPort: 9999,
oscOutIP: '127.0.0.1',
oscEnabled: false,
lock: false,
lock: null,
},
};
@@ -313,11 +305,7 @@ describe('test corrupt data', () => {
app: 'ontime',
version: 1,
serverPort: 4001,
oscInPort: 8888,
oscOutPort: 9999,
oscOutIP: '127.0.0.1',
oscEnabled: false,
lock: false,
lock: null,
},
};
@@ -430,7 +418,6 @@ describe('test makeString function', () => {
expect(converted).toBe(expected);
val = { doing: 'testing' };
expected = 'testing';
converted = makeString(val, 'fallback');
expect(converted).toBe('fallback');
});
@@ -477,8 +464,8 @@ describe('test parseExcel function', () => {
const expectedParsedEvents = [
{
timeStart: 28800000,
timeEnd: 32410000,
timeStart: 25200000,
timeEnd: 28810000,
title: 'Guest Welcome',
presenter: 'Carlos',
subtitle: 'Getting things started',
@@ -487,8 +474,8 @@ describe('test parseExcel function', () => {
type: 'event',
},
{
timeStart: 32400000,
timeEnd: 34200000,
timeStart: 28800000,
timeEnd: 30600000,
title: 'A song from the hearth',
presenter: 'Still Carlos',
subtitle: 'Derailing early',
+3 -1
View File
@@ -1,4 +1,3 @@
import { describe } from 'jest-circus';
import { excelDateStringToMillis, stringFromMillis } from '../time.js';
describe('test string to milis function', () => {
@@ -60,12 +59,15 @@ describe('test string to milis function', () => {
describe('test excel date parser', () => {
it('parses the given dates correctly', () => {
const d0 = '1899-12-30T00:00:00.000Z';
const d1 = '1899-12-30T08:00:00.000Z';
const d2 = '1899-12-30T08:30:00.000Z';
const d0Millis = 0;
const d1Millis = 28800000;
const d2Millis = 30600000;
expect(excelDateStringToMillis(d0)).toBe(d0Millis);
expect(excelDateStringToMillis(d1)).toBe(d1Millis);
expect(excelDateStringToMillis(d2)).toBe(d2Millis);
});
+36
View File
@@ -0,0 +1,36 @@
// test cleanURL()
import {cleanURL} from "../url";
describe('url is correctly formatted', () => {
it('has no leading spaces', () => {
const test = ' http://testing';
const expected = 'http://testing';
expect(cleanURL(test)).toBe(expected);
});
it('has no trailing spaces', () => {
const test = 'http://testing ';
const expected = 'http://testing';
expect(cleanURL(test)).toBe(expected);
});
it('doesnt contain spaces', () => {
const test = 'http://t e s t i n g';
const expected = 'http://t%20e%20s%20t%20i%20n%20g';
expect(cleanURL(test)).toBe(expected);
});
it('only contains allowed characters', () => {
const test = 'http://<>[]{}|\^';
const expected = 'http://';
expect(cleanURL(test)).toBe(expected);
});
it('begins with http://', () => {
const test = 'ontime.com';
const expected = 'http://ontime.com';
expect(cleanURL(test)).toBe(expected);
});
});
+66 -19
View File
@@ -16,7 +16,7 @@ export const ALLOWED_TYPES = ['JSON', 'EXCEL'];
/**
* @description Middleware function that checks file type and calls relevant parser
* @argument {string} file - reference to file
* @param {string} file - reference to file
* @return {object} - parse result message
*/
export const fileHandler = async (file) => {
@@ -82,7 +82,7 @@ export const fileHandler = async (file) => {
/**
* @description Excel array parser
* @argument {array} excelData - array with excel sheet
* @param {array} excelData - array with excel sheet
* @returns {object} - parsed object
*/
export const parseExcelv1 = async (excelData) => {
@@ -196,11 +196,12 @@ export const parseExcelv1 = async (excelData) => {
/**
* @description JSON parser function for v1 of data system
* @argument {object} jsonData - json data JSON object to be parsed
* @param {object} jsonData - json data JSON object to be parsed
* @param {boolean} [enforce=false] - flag, tells to create an object anyway
* @returns {object} - parsed object
*/
export const parseJsonv1 = async (jsonData) => {
export const parseJsonv1 = async (jsonData, enforce=false) => {
if (!jsonData || typeof jsonData !== 'object') {
console.log('ERROR: Invalid JSON format');
return -1;
@@ -213,9 +214,9 @@ export const parseJsonv1 = async (jsonData) => {
let events = [];
let ids = [];
for (const e of jsonData.events) {
// doublecheck unique ids
// double check unique ids
if (ids.indexOf(e?.id) !== -1) {
console.log('ERROR: ID colision on import, skipping');
console.log('ERROR: ID collision on import, skipping');
continue;
}
@@ -243,13 +244,17 @@ export const parseJsonv1 = async (jsonData) => {
// write to db
returnData.events = events;
console.log(`Uploaded file with ${numEntries} entries`);
} else if (enforce) {
returnData.events = [];
console.log(`Created events object in db`);
}
if ('event' in jsonData) {
console.log('Found event data, importing...');
const e = jsonData.event;
// filter known properties
const event = {
// filter known properties and write to db
returnData.event = {
...dbModelv1.event,
title: e.title || dbModelv1.event.title,
url: e.url || dbModelv1.event.url,
@@ -257,9 +262,9 @@ export const parseJsonv1 = async (jsonData) => {
backstageInfo: e.backstageInfo || dbModelv1.event.backstageInfo,
endMessage: e.endMessage || dbModelv1.event.endMessage,
};
// write to db
returnData.event = event;
} else if (enforce) {
returnData.event = dbModelv1.event;
console.log(`Created event object in db`);
}
// Settings handled partially
@@ -271,11 +276,9 @@ export const parseJsonv1 = async (jsonData) => {
if (s.app == null || s.version == null) {
console.log('ERROR: unknown app version, skipping');
} else {
let settings = {};
if (s.oscInPort) settings.oscInPort = s.oscInPort;
if (s.oscOutPort) settings.oscOutPort = s.oscOutPort;
if (s.oscOutIP) settings.oscOutIP = s.oscOutIP;
let settings = {
lock: s.lock || null,
};
// write to db
returnData.settings = {
@@ -283,6 +286,49 @@ export const parseJsonv1 = async (jsonData) => {
...settings,
};
}
} else if (enforce) {
returnData.settings = dbModelv1.settings;
console.log(`Created settings object in db`);
}
// Import OSC settings if any
if ('osc' in jsonData) {
console.log('Found OSC definition, importing...');
const s = jsonData.osc;
let osc = {};
if (s.port) osc.port = s.port;
if (s.portOut) osc.portOut = s.portOut;
if (s.targetIP) osc.targetIP = s.targetIP;
if (s.enabled) osc.enabled = s.enabled;
// write to db
returnData.osc = {
...dbModelv1.osc,
...osc,
};
} else if (enforce) {
returnData.osc = dbModelv1.osc;
console.log(`Created osc object in db`);
}
// Import HTTP settings if any
if ('http' in jsonData) {
console.log('Found HTTP definition, importing...');
const h = jsonData.osc;
let http = {};
if (h.user) http.user = h.user;
if (h.pwd) http.pwd = h.pwd;
// write to db
returnData.http = {
...dbModelv1.http,
...http,
};
} else if (enforce) {
returnData.http = dbModelv1.http;
console.log(`Created http object in db`);
}
return returnData;
@@ -292,7 +338,7 @@ export const parseJsonv1 = async (jsonData) => {
* @description Ensures variable is string, it skips object types
* @param {any} val - variable to convert
* @param {string} [fallback=''] - fallback value
* @returns {string} - value as string or fallback if not possibe
* @returns {string} - value as string or fallback if not possible
*/
export const makeString = (val, fallback = '') => {
if (typeof val === 'string') return val;
@@ -348,7 +394,7 @@ export const validateEventv1 = (eventArgs) => {
/**
* @description Delete file from system
* @argument {string} file - reference to file
* @param {string} file - reference to file
*/
const deleteFile = async (file) => {
// delete a file
@@ -361,7 +407,8 @@ const deleteFile = async (file) => {
/**
* @description Delete file from system
* @argument {string} file - reference to file
* @param {string} file - reference to file
* @returns {boolean} - whether file is valid JSON
*/
export const validateFile = (file) => {
try {
+1 -2
View File
@@ -40,9 +40,8 @@ export const stringFromMillis = (
*/
export const excelDateStringToMillis = (excelDate) => {
const date = new Date(excelDate);
if (date instanceof Date && !isNaN(date)) {
const h = date.getHours();
const h = date.getUTCHours();
const m = date.getMinutes();
const s = date.getSeconds();
+21
View File
@@ -0,0 +1,21 @@
/**
* @description Cleans given url
* @param {string} url - URL to be checked
* @returns {string} Sanitized url
*/
export const cleanURL = (url) => {
// trim whitespaces
let r = url.trim();
// clear any whitespaces
r = r.split(' ').join('%20');
// contain only allowed characters
r = r.replace(/([^\x00-\x7F]|[@\s<>\[\]{}|\\^])+/g, '')
// starts with http://
if (!r.startsWith('http://')) r = `http://${r}`
return r;
}
+9 -1367
View File
File diff suppressed because it is too large Load Diff
+5
View File
@@ -1356,6 +1356,11 @@ configstore@^5.0.1:
write-file-atomic "^3.0.0"
xdg-basedir "^4.0.0"
confusing-browser-globals@^1.0.10:
version "1.0.11"
resolved "https://registry.yarnpkg.com/confusing-browser-globals/-/confusing-browser-globals-1.0.11.tgz#ae40e9b57cdd3915408a2805ebd3a5585608dc81"
integrity sha512-JsPKdmh8ZkmnHxDk55FZ1TqVLvEQTvoByJZRN9jzI0UjxK/QgAmsphz7PGtqgPieQZ/CQcHWXCR7ATDNhGe+YA==
convert-source-map@^1.4.0, convert-source-map@^1.6.0, convert-source-map@^1.7.0:
version "1.8.0"
resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.8.0.tgz#f3373c32d21b4d780dd8004514684fb791ca4369"