Compare commits

..

44 Commits

Author SHA1 Message Date
arc-alex b37494109a ifx: use template string not concatination 2023-11-27 23:27:10 +01:00
arc-alex aaa1fb9368 fix: saveClientSecrets type object 2023-11-27 23:24:36 +01:00
arc-alex cb198bc3fe comments 2023-11-26 17:29:12 +01:00
arc-alex 6880f459b6 check keys of client secrets 2023-11-26 17:11:55 +01:00
arc-alex 7b34c8f3b1 push project data 2023-11-26 16:48:34 +01:00
arc-alex c714727801 useEffect 2023-11-26 14:26:05 +01:00
arc-alex 8fc70fa162 cellRequenstFromEvent change 2023-11-26 14:23:12 +01:00
arc-alex 54c4a7f68c add test 2023-11-26 14:16:50 +01:00
arc-alex 9820c71a2d move util functions to separat file for testing 2023-11-25 20:03:30 +01:00
arc-alex 2ff7d0f546 pass lint 2023-11-25 19:56:19 +01:00
arc-alex f29ed1b05a types for getA1Notation function 2023-11-25 19:54:33 +01:00
arc-alex b1de7ffe5b Merge branch 'master' into google-sheets-lite 2023-11-25 19:39:53 +01:00
arc-alex 46d17e0570 extend authServer timeout if opened again 2023-11-24 21:17:30 +01:00
arc-alex 38e3ef7586 dont save login token Between Sessions 2023-11-24 20:07:50 +01:00
arc-alex e8bcbb4291 clean up sheet flow 2023-11-24 17:47:21 +01:00
arc-alex 111df94d6d parseGoogleSheet from db 2023-11-24 16:49:37 +01:00
arc-alex d32d8a547d lint 2023-11-23 18:38:01 +01:00
arc-alex 5bc2c2f241 remove unused 2023-11-23 17:55:22 +01:00
arc-alex 28533464d4 add db test for google sheet 2023-11-23 17:49:08 +01:00
arc-alex 4f1fa2053f sheet settings with feedback 2023-11-23 17:17:13 +01:00
arc-alex b15b4b48a7 add googleSheet to db model 2023-11-23 14:53:22 +01:00
arc-alex ef2fa99673 finde correct range 2023-11-19 20:15:07 +01:00
arc-alex 85ee9de528 lint 2023-11-19 19:39:13 +01:00
arc-alex e52a75db7d test sheet exist and get worksheet id 2023-11-19 19:24:56 +01:00
arc-alex 07ebb5a321 fix merge 2023-11-19 19:24:31 +01:00
arc-alex 071cae4cc6 Merge remote-tracking branch 'org/master' into google-sheets-lite 2023-11-19 18:28:57 +01:00
arc-alex 543e365f82 push to sheet 2023-11-19 17:04:14 +01:00
arc-alex a7c9ce876c get cell location when from parseExcel 2023-11-19 17:03:50 +01:00
arc-alex ae4e2ceafe push function 2023-11-18 21:41:40 +01:00
arc-alex b77db4cbf6 rename to pull 2023-11-18 21:17:44 +01:00
arc-alex fe67e65a95 return auth url on first clik 2023-11-18 21:15:39 +01:00
arc-alex 785695c01c clear rundownState on modal close 2023-11-18 21:01:32 +01:00
arc-alex 65efebe180 Preview Sheet 2023-11-18 20:58:57 +01:00
arc-alex 52a9c85dbc remove duplicate routs 2023-11-18 17:57:13 +01:00
arc-alex 6b2b6dc6dd auth flow 2023-11-18 17:53:08 +01:00
arc-alex 31b46bbb34 handle client secret upload 2023-11-18 17:24:29 +01:00
arc-alex 38cf3a7b63 ensure sheets directory 2023-11-18 17:23:19 +01:00
arc-alex 81cf30daa0 use only sheets portion of google api 2023-11-17 16:15:28 +01:00
Carlos Valente e9683c6cab wip: placeholder sheets modal 2023-11-17 15:21:19 +01:00
arc-alex 370777326d add jsdoc comments 2023-11-15 10:26:04 +01:00
arc-alex 309f622077 update lock file 2023-11-15 10:09:50 +01:00
arc-alex 285b05bd65 comment 2023-11-15 09:06:03 +01:00
arc-alex 05207189cf add google sheet functions 2023-11-15 09:06:03 +01:00
arc-alex d70bb2174a install google apis 2023-11-15 09:06:03 +01:00
114 changed files with 1276 additions and 3086 deletions
+1 -13
View File
@@ -44,8 +44,7 @@ jobs:
- name: Docker Setup Buildx
uses: docker/setup-buildx-action@v2.5.0
- name: Build and push stable release
if: github.event.release.prerelease == false
- name: Build and push Docker images
uses: docker/build-push-action@v4.0.0
with:
context: .
@@ -55,14 +54,3 @@ jobs:
push: true
tags: ${{ secrets.DOCKERHUB_USERNAME }}/ontime:${{ env.RELEASE_VERSION }} , ${{ secrets.DOCKERHUB_USERNAME }}/ontime:latest
- name: Build and push pre-release
if: github.event.release.prerelease == true
uses: docker/build-push-action@v4.0.0
with:
context: .
file: ./Dockerfile
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6
# Push is a shorthand for --output=type=registry
push: true
tags: ${{ secrets.DOCKERHUB_USERNAME }}/ontime:${{ env.RELEASE_VERSION }} , ${{ secrets.DOCKERHUB_USERNAME }}/ontime:nightly
-1
View File
@@ -89,7 +89,6 @@ While it should allow for a generic setup, it might need to be modified to fit y
From the project root, run the following commands
- __Install the project dependencies__ by running `pnpm i`
- __Build packages__ by running `pnpm build:localdocker`
- __Build docker image from__ by running `docker build -t getontime/ontime`
- __Run docker image from compose__ by running `docker-compose up -d`
+1 -1
View File
@@ -4,7 +4,7 @@
## Download the latest releases here
<div style="display: flex; justify-content: space-around">
<a href="https://github.com/cpvalente/ontime/releases/latest/download/ontime-macOS-arm64.dmg"><img alt="Download MacOS" src="https://github.com/cpvalente/ontime/blob/master/.github/aux-images/mac-download.png"/></a>
<a href="https://github.com/cpvalente/ontime/releases/latest/download/ontime-macOS.dmg"><img alt="Download MacOS" src="https://github.com/cpvalente/ontime/blob/master/.github/aux-images/mac-download.png"/></a>
<a href="https://github.com/cpvalente/ontime/releases/latest/download/ontime-win64.exe"><img alt="Download Windows" src="https://github.com/cpvalente/ontime/blob/master/.github/aux-images/win-download.png"/></a>
<a href="https://github.com/cpvalente/ontime/releases/latest/download/ontime-linux.AppImage"><img alt="Download Linux" src="https://github.com/cpvalente/ontime/blob/master/.github/aux-images/linux-download.png"/></a>
<a href="https://hub.docker.com/r/getontime/ontime"><img alt="Get from Dockerhub" src="https://github.com/cpvalente/ontime/blob/master/.github/aux-images/dockerhub.png"/></a>
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "ontime-ui",
"version": "2.28.12",
"version": "2.16.2",
"private": true,
"dependencies": {
"@chakra-ui/react": "^2.7.0",
@@ -40,7 +40,6 @@
"build:local": "cross-env NODE_ENV=local vite build",
"build:electron": "cross-env NODE_ENV=local vite build",
"build:docker": "vite build",
"build:localdocker": "cross-env NODE_ENV=local vite build",
"lint": "eslint . --quiet",
"lint-staged": "eslint",
"test": "vitest",
@@ -5,11 +5,9 @@ export const USERFIELDS = ['userFields'];
export const RUNDOWN = ['rundown'];
export const APP_INFO = ['appinfo'];
export const OSC_SETTINGS = ['oscSettings'];
export const HTTP_SETTINGS = ['httpSettings'];
export const APP_SETTINGS = ['appSettings'];
export const VIEW_SETTINGS = ['viewSettings'];
export const RUNTIME = ['runtimeStore'];
export const SHEET_STATE = ['sheetState'];
const location = window.location;
const socketProtocol = location.protocol === 'https:' ? 'wss' : 'ws';
+40 -70
View File
@@ -3,7 +3,8 @@ import {
Alias,
DatabaseModel,
GetInfo,
HttpSettings,
GoogleSheet,
GoogleSheetState,
OntimeRundown,
OSCSettings,
OscSubscription,
@@ -105,23 +106,6 @@ export async function getOSC(): Promise<OSCSettings> {
return res.data;
}
/**
* @description HTTP request to retrieve http settings
* @return {Promise}
*/
export async function getHTTP(): Promise<HttpSettings> {
const res = await axios.get(`${ontimeURL}/http`);
return res.data;
}
/**
* @description HTTP request to mutate http settings
* @return {Promise}
*/
export async function postHTTP(data: HttpSettings) {
return axios.post(`${ontimeURL}/http`, data);
}
/**
* @description HTTP request to mutate osc settings
* @return {Promise}
@@ -247,74 +231,60 @@ export async function postNew(initialData: Partial<ProjectData>) {
}
/**
* @description STEP 1
* @description sheet Client File
* @return {Promise}
*/
export const uploadSheetClientFile = async (file: File) => {
const formData = new FormData();
formData.append('userFile', file);
const res = await axios
.post(`${ontimeURL}/sheet/clientsecret`, formData, {
await axios
.post(`${ontimeURL}/sheet-clientsecrect`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then((response) => response.data.id);
return res;
};
/**
* @description STEP 1 test
*/
export const getClientSecrect = async () => {
const response = await axios.get(`${ontimeURL}/sheet/clientsecret`);
return response.data;
};
/**
* @description STEP 2
*/
export const getSheetsAuthUrl = async () => {
const response = await axios.get(`${ontimeURL}/sheet/authentication/url`);
return response.data;
const res = await axios.get(`${ontimeURL}/sheet-authurl`);
return res.data;
};
/**
* @description STEP 2 test
*/
export const getAuthentication = async () => {
const response = await axios.get(`${ontimeURL}/sheet/authentication`);
return response.data;
};
/**
* @description STEP 3
* @returns worksheetOptions
*/
export const postId = async (id: string) => {
const response = await axios.post(`${ontimeURL}/sheet/id`, { id });
return response.data;
};
/**
* @description STEP 4
*/
export const postWorksheet = async (id: string, worksheet: string) => {
const response = await axios.post(`${ontimeURL}/sheet/worksheet`, { id, worksheet });
return response.data;
};
/**
* @description STEP 5
*/
export const postPreviewSheet = async (id: string, options: ExcelImportMap) => {
const response = await axios.post(`${ontimeURL}/sheet/pull`, { id, options });
export const postPreviewSheet = async () => {
const response = await axios.post(`${ontimeURL}/sheet-preview`);
return response.data.data;
};
/**
* @description STEP 5
*/
export const postPushSheet = async (id: string, options: ExcelImportMap) => {
const response = await axios.post(`${ontimeURL}/sheet-push`, { id, options });
export const postPushSheet = async () => {
const response = await axios.post(`${ontimeURL}/sheet-push`);
return response.data.data;
};
/**
* @description HTTP request to retrieve google sheets settings
* @return {Promise}
*/
export async function getSheetSettings(): Promise<GoogleSheet> {
const res = await axios.get(`${ontimeURL}/sheet-settings`);
return res.data;
}
/**
* @description HTTP request to mutate google sheets settings
* @return {Promise}
*/
export async function postSheetSettings(data: GoogleSheet): Promise<GoogleSheet> {
const res = await axios.post(`${ontimeURL}/sheet-settings`, data);
return res.data;
}
/**
* @description HTTP request to retrieve google sheets state
* @return {Promise}
*/
export async function getSheetstate(): Promise<GoogleSheetState> {
const res = await axios.get(`${ontimeURL}/sheet-state`);
return res.data;
}
@@ -17,8 +17,9 @@ interface TimeInputProps {
time?: number;
delay?: number;
placeholder: string;
validationHandler: (entry: TimeEntryField, val: number) => boolean;
previousEnd?: number;
tooltip?: string;
warning?: string;
}
function ButtonInitial(name: TimeEntryField) {
@@ -28,15 +29,25 @@ function ButtonInitial(name: TimeEntryField) {
return '';
}
function ButtonTooltip(name: TimeEntryField, tooltip?: string) {
if (name === 'timeStart') return `Start${tooltip ? `: ${tooltip}` : ''}`;
if (name === 'timeEnd') return `End${tooltip ? `: ${tooltip}` : ''}`;
if (name === 'durationOverride') return `Duration${tooltip ? `: ${tooltip}` : ''}`;
function ButtonTooltip(name: TimeEntryField, warning?: string) {
if (name === 'timeStart') return `Start${warning ? `: ${warning}` : ''}`;
if (name === 'timeEnd') return `End${warning ? `: ${warning}` : ''}`;
if (name === 'durationOverride') return `Duration${warning ? `: ${warning}` : ''}`;
return '';
}
export default function TimeInput(props: TimeInputProps) {
const { id, name, submitHandler, time = 0, delay = 0, placeholder, previousEnd = 0 } = props;
const {
id,
name,
submitHandler,
time = 0,
delay = 0,
placeholder,
validationHandler,
previousEnd = 0,
warning,
} = props;
const { emitError } = useEmitLog();
const inputRef = useRef<HTMLInputElement | null>(null);
const [value, setValue] = useState<string>('');
@@ -92,12 +103,15 @@ export default function TimeInput(props: TimeInputProps) {
// check if time is different from before
if (newValMillis === time) return false;
// validate with parent
if (!validationHandler(name, newValMillis)) return false;
// update entry
submitHandler(name, newValMillis);
return true;
},
[name, previousEnd, submitHandler, time],
[name, previousEnd, submitHandler, time, validationHandler],
);
/**
@@ -157,11 +171,11 @@ export default function TimeInput(props: TimeInputProps) {
const isDelayed = delay !== 0;
const inputClasses = cx([style.timeInput, isDelayed ? style.delayed : null]);
const buttonClasses = cx([style.inputButton, isDelayed ? style.delayed : null]);
const buttonClasses = cx([style.inputButton, isDelayed ? style.delayed : null, warning ? style.warn : null]);
const TooltipLabel = useMemo(() => {
return ButtonTooltip(name, '');
}, [name]);
return ButtonTooltip(name, warning);
}, [name, warning]);
const ButtonText = useMemo(() => {
return ButtonInitial(name);
@@ -198,7 +212,6 @@ export default function TimeInput(props: TimeInputProps) {
onKeyDown={onKeyDownHandler}
value={value}
maxLength={8}
autoComplete='off'
/>
</InputGroup>
);
@@ -10,6 +10,10 @@ $icon-color: $ui-white;
$button-bg: $gray-1050;
$button-size: 48px;
.mirror {
transform: rotate(180deg);
}
.buttonContainer {
display: flex;
flex-direction: column;
@@ -12,6 +12,7 @@ import { IoSwapVertical } from '@react-icons/all-files/io5/IoSwapVertical';
import { navigatorConstants } from '../../../viewerConfig';
import useClickOutside from '../../hooks/useClickOutside';
import useFullscreen from '../../hooks/useFullscreen';
import { useKeyDown } from '../../hooks/useKeyDown';
import { useViewOptionsStore } from '../../stores/viewOptions';
import RenameClientModal from './rename-client-modal/RenameClientModal';
@@ -22,19 +23,18 @@ function NavigationMenu() {
const location = useLocation();
const { isFullScreen, toggleFullScreen } = useFullscreen();
const { toggleMirror } = useViewOptionsStore();
const { mirror, toggleMirror } = useViewOptionsStore();
const [showButton, setShowButton] = useState(false);
const [searchParams, setSearchParams] = useSearchParams();
const [showMenu, setShowMenu] = useState(false);
const menuRef = useRef<HTMLDivElement | null>(null);
useClickOutside(menuRef, () => setShowMenu(false));
const { isOpen, onOpen, onClose } = useDisclosure();
const toggleMenu = () => setShowMenu((prev) => !prev);
useKeyDown(toggleMenu, ' ', { isDisabled: searchParams.get('edit') === 'true' || isOpen });
// show on mouse move
useEffect(() => {
let fadeOut: NodeJS.Timeout | null = null;
const setShowMenuTrue = () => {
@@ -63,7 +63,7 @@ function NavigationMenu() {
};
return createPortal(
<div id='navigation-menu-portal' ref={menuRef}>
<div id='navigation-menu-portal' ref={menuRef} className={mirror ? style.mirror : ''}>
<RenameClientModal isOpen={isOpen} onClose={onClose} />
<div className={`${style.buttonContainer} ${!showButton && !showMenu ? style.hidden : ''}`}>
<button onClick={toggleMenu} aria-label='toggle menu' className={style.navButton}>
@@ -1,5 +1,5 @@
import { useSearchParams } from 'react-router-dom';
import { Input, InputGroup, InputLeftElement, Select, Switch } from '@chakra-ui/react';
import { Input, Select, Switch } from '@chakra-ui/react';
import { isStringBoolean } from '../../utils/viewUtils';
@@ -9,22 +9,16 @@ interface EditFormInputProps {
paramField: ParamField;
}
export default function ParamInput(props: EditFormInputProps) {
export default function ParamInput({ paramField }: EditFormInputProps) {
const [searchParams] = useSearchParams();
const { paramField } = props;
const { id, type, defaultValue } = paramField;
const { id, type } = paramField;
if (type === 'option') {
const optionFromParams = searchParams.get(id);
const defaultOptionValue = optionFromParams || defaultValue;
const defaultOptionValue = optionFromParams || undefined;
return (
<Select
placeholder={defaultValue ? undefined : 'Select an option'}
variant='ontime'
name={id}
defaultValue={defaultOptionValue}
>
<Select placeholder='Select an option' variant='ontime' name={id} defaultValue={defaultOptionValue}>
{Object.entries(paramField.values).map(([key, value]) => (
<option key={key} value={key}>
{value}
@@ -35,38 +29,19 @@ export default function ParamInput(props: EditFormInputProps) {
}
if (type === 'boolean') {
const defaultCheckedValue = isStringBoolean(searchParams.get(id)) || defaultValue;
const defaultCheckedValue = isStringBoolean(searchParams.get(id)) ?? false;
// checked value should be 'true', so it can be captured by the form event
return <Switch variant='ontime' name={id} defaultChecked={defaultCheckedValue} value='true' />;
}
if (type === 'number') {
const { prefix, placeholder } = paramField;
const defaultNumberValue = searchParams.get(id) ?? defaultValue;
const defaultNumberValue = searchParams.get(id) ?? '';
return (
<InputGroup variant='ontime-filled'>
{prefix && <InputLeftElement pointerEvents='none'>{prefix}</InputLeftElement>}
<Input
type='number'
step='any'
variant='ontime-filled'
name={id}
defaultValue={defaultNumberValue}
placeholder={placeholder}
/>
</InputGroup>
);
return <Input type='number' step='any' variant='ontime-filled' name={id} defaultValue={defaultNumberValue} />;
}
const defaultStringValue = searchParams.get(id) ?? defaultValue;
const { prefix, placeholder } = paramField;
const defaultStringValue = searchParams.get(id) ?? '';
return (
<InputGroup variant='ontime-filled'>
{prefix && <InputLeftElement pointerEvents='none'>{prefix}</InputLeftElement>}
<Input name={id} defaultValue={defaultStringValue} placeholder={placeholder} />
</InputGroup>
);
return <Input variant='ontime-filled' name={id} defaultValue={defaultStringValue} />;
}
@@ -22,15 +22,9 @@ import style from './ViewParamsEditor.module.scss';
type ViewParamsObj = { [key: string]: string | FormDataEntryValue };
type SavedViewParams = Record<string, ViewParamsObj>;
const getURLSearchParamsFromObj = (paramsObj: ViewParamsObj, paramFields: ParamField[]) => {
const defaultValues = paramFields.map(({ defaultValue }) => String(defaultValue));
return Object.entries(paramsObj).reduce((newSearchParams, [id, value]) => {
const getURLSearchParamsFromObj = (paramsObj: ViewParamsObj) =>
Object.entries(paramsObj).reduce((newSearchParams, [id, value]) => {
if (typeof value === 'string' && value.length) {
if (defaultValues.includes(value)) {
return newSearchParams;
}
newSearchParams.set(id, value);
return newSearchParams;
@@ -38,7 +32,6 @@ const getURLSearchParamsFromObj = (paramsObj: ViewParamsObj, paramFields: ParamF
return newSearchParams;
}, new URLSearchParams());
};
interface EditFormDrawerProps {
paramFields: ParamField[];
@@ -79,30 +72,31 @@ export default function ViewParamsEditor({ paramFields }: EditFormDrawerProps) {
*/
const onCloseWithoutSaving = () => {
const onEditDrawerClose = () => {
onClose();
searchParams.delete('edit');
setSearchParams(searchParams);
};
const resetParams = () => {
const clearParams = () => {
setStoredViewParams({ ...storedViewParams, [pathname]: {} });
setSearchParams();
onClose();
};
const onParamsFormSubmit = (formEvent: FormEvent<HTMLFormElement>) => {
formEvent.preventDefault();
const newParamsObject = Object.fromEntries(new FormData(formEvent.currentTarget));
const newSearchParams = getURLSearchParamsFromObj(newParamsObject, paramFields);
const newSearchParams = getURLSearchParamsFromObj(newParamsObject);
setStoredViewParams({ ...storedViewParams, [pathname]: newParamsObject });
setSearchParams(newSearchParams);
};
return (
<Drawer isOpen={isOpen} placement='right' onClose={onCloseWithoutSaving} size='lg'>
<Drawer isOpen={isOpen} placement='right' onClose={onEditDrawerClose} size='lg'>
<DrawerOverlay />
<DrawerContent>
<DrawerHeader className={style.drawerHeader}>
@@ -125,10 +119,10 @@ export default function ViewParamsEditor({ paramFields }: EditFormDrawerProps) {
</DrawerBody>
<DrawerFooter className={style.drawerFooter}>
<Button variant='ontime-ghosted' onClick={resetParams} type='reset'>
Reset
<Button variant='ontime-ghosted' onClick={clearParams} type='reset'>
Clear
</Button>
<Button variant='ontime-subtle' onClick={onCloseWithoutSaving}>
<Button variant='ontime-subtle' onClick={onEditDrawerClose}>
Cancel
</Button>
<Button variant='ontime-filled' form='edit-params-form' type='submit'>
@@ -1,56 +1,46 @@
import { UserFields } from 'ontime-types';
import { TimeFormat } from 'ontime-types/src/definitions/core/TimeFormat.type';
import { ParamField } from './types';
export const getTimeOption = (timeFormat: TimeFormat): ParamField => ({
export const TIME_FORMAT_OPTION: ParamField = {
id: 'format',
title: '12 / 24 hour timer',
description: 'Whether to show the time in 12 or 24 hour mode. Overrides the global setting from preferences',
type: 'option',
values: { '12': '12 hour AM/PM', '24': '24 hour' },
defaultValue: timeFormat,
});
};
export const getClockOptions = (timeFormat: TimeFormat): ParamField[] => [
getTimeOption(timeFormat),
export const CLOCK_OPTIONS: ParamField[] = [
TIME_FORMAT_OPTION,
{
id: 'key',
title: 'Key Colour',
description: 'Background colour in hexadecimal',
prefix: '#',
type: 'string',
placeholder: '00000000 (default)',
},
{
id: 'text',
title: 'Text Colour',
description: 'Text colour in hexadecimal',
prefix: '#',
type: 'string',
placeholder: 'fffff (default)',
},
{
id: 'textbg',
title: 'Text Background',
description: 'Colour of text background in hexadecimal',
prefix: '#',
type: 'string',
placeholder: '00000000 (default)',
},
{
id: 'font',
title: 'Font',
description: 'Font family, will use the fonts available in the system',
type: 'string',
placeholder: 'Arial Black (default)',
},
{
id: 'size',
title: 'Text Size',
description: 'Scales the current style (0.5 = 50% 1 = 100% 2 = 200%)',
type: 'number',
placeholder: '1 (default)',
},
{
id: 'alignx',
@@ -58,14 +48,12 @@ export const getClockOptions = (timeFormat: TimeFormat): ParamField[] => [
description: 'Moves the horizontally in page to start = left | center | end = right',
type: 'option',
values: { start: 'Start', center: 'Center', end: 'End' },
defaultValue: 'center',
},
{
id: 'offsetx',
title: 'Offset Horizontal',
description: 'Offsets the timer horizontal position by a given amount in pixels',
type: 'number',
placeholder: '0 (default)',
},
{
id: 'aligny',
@@ -73,53 +61,46 @@ export const getClockOptions = (timeFormat: TimeFormat): ParamField[] => [
description: 'Moves the vertically in page to start = left | center | end = right',
type: 'option',
values: { start: 'Start', center: 'Center', end: 'End' },
defaultValue: 'center',
},
{
id: 'offsety',
title: 'Offset Vertical',
description: 'Offsets the timer vertical position by a given amount in pixels',
type: 'number',
placeholder: '0 (default)',
},
];
export const getTimerOptions = (timeFormat: TimeFormat): ParamField[] => [
getTimeOption(timeFormat),
export const TIMER_OPTIONS: ParamField[] = [
TIME_FORMAT_OPTION,
{
id: 'hideClock',
title: 'Hide Time Now',
description: 'Hides the Time Now field',
type: 'boolean',
defaultValue: false,
},
{
id: 'hideCards',
title: 'Hide Cards',
description: 'Hides the Now and Next cards',
type: 'boolean',
defaultValue: false,
},
{
id: 'hideProgress',
title: 'Hide progress bar',
description: 'Hides the progress bar',
type: 'boolean',
defaultValue: false,
},
{
id: 'hideMessage',
title: 'Hide Presenter Message',
description: 'Prevents the screen from displaying messages from the presenter',
type: 'boolean',
defaultValue: false,
},
{
id: 'hideExternal',
title: 'Hide External',
description: 'Prevents the screen from displaying the external field',
type: 'boolean',
defaultValue: false,
},
];
@@ -128,39 +109,31 @@ export const MINIMAL_TIMER_OPTIONS: ParamField[] = [
id: 'key',
title: 'Key Colour',
description: 'Background colour in hexadecimal',
prefix: '#',
type: 'string',
placeholder: '00000000 (default)',
},
{
id: 'text',
title: 'Text Colour',
description: 'Text colour in hexadecimal',
prefix: '#',
type: 'string',
placeholder: 'fffff (default)',
},
{
id: 'textbg',
title: 'Text Background',
description: 'Colour of text background in hexadecimal',
prefix: '#',
type: 'string',
placeholder: '00000000 (default)',
},
{
id: 'font',
title: 'Font',
description: 'Font family, will use the fonts available in the system',
type: 'string',
placeholder: 'Arial Black (default)',
},
{
id: 'size',
title: 'Text Size',
description: 'Scales the current style (0.5 = 50% 1 = 100% 2 = 200%)',
type: 'number',
placeholder: '1 (default)',
},
{
id: 'alignx',
@@ -168,14 +141,12 @@ export const MINIMAL_TIMER_OPTIONS: ParamField[] = [
description: 'Moves the horizontally in page to start = left | center | end = right',
type: 'option',
values: { start: 'Start', center: 'Center', end: 'End' },
defaultValue: 'center',
},
{
id: 'offsetx',
title: 'Offset Horizontal',
description: 'Offsets the timer horizontal position by a given amount in pixels',
type: 'number',
placeholder: '0 (default)',
},
{
id: 'aligny',
@@ -183,162 +154,145 @@ export const MINIMAL_TIMER_OPTIONS: ParamField[] = [
description: 'Moves the vertically in page to start = left | center | end = right',
type: 'option',
values: { start: 'Start', center: 'Center', end: 'End' },
defaultValue: 'center',
},
{
id: 'offsety',
title: 'Offset Vertical',
description: 'Offsets the timer vertical position by a given amount in pixels',
type: 'number',
placeholder: '0 (default)',
},
{
id: 'hideovertime',
title: 'Hide Overtime',
description: 'Whether to suppress overtime styles (red borders and red text)',
type: 'boolean',
defaultValue: false,
},
{
id: 'hidemessages',
title: 'Hide Message Overlay',
description: 'Whether to hide the overlay from showing timer screen messages',
type: 'boolean',
defaultValue: false,
},
{
id: 'hideendmessage',
title: 'Hide End Message',
description: 'Whether to hide end message and continue showing the clock if timer is in overtime',
type: 'boolean',
defaultValue: false,
},
];
export const LOWER_THIRDS_OPTIONS: ParamField[] = [
{
id: 'preset',
title: 'Preset',
description: 'Selects a style preset (0-1)',
type: 'number',
},
{
id: 'size',
title: 'Size',
description: 'Scales the current style (0.5 = 50% 1 = 100% 2 = 200%)',
type: 'number',
placeholder: '1 (default)',
},
{
id: 'transition',
title: 'Transition',
description: 'Transition in time in seconds (default 3)',
description: 'Transition in time in seconds (default 5)',
type: 'number',
placeholder: '3 (default)',
},
{
id: 'text',
title: 'Text Colour',
description: 'Text colour in hexadecimal',
prefix: '#',
type: 'string',
placeholder: 'fffffa (default)',
},
{
id: 'bg',
title: 'Text Background',
description: 'Text background colour in hexadecimal',
prefix: '#',
type: 'string',
placeholder: '00000033 (default)',
},
{
id: 'key',
title: 'Key Colour',
description: 'Screen background colour in hexadecimal',
prefix: '#',
type: 'string',
placeholder: '00000033 (default)',
},
{
id: 'fadeout',
title: 'Fadeout',
description: 'Time (in seconds) the lower third displays before fading out',
type: 'number',
placeholder: '3 (default)',
},
];
export const getBackstageOptions = (timeFormat: TimeFormat): ParamField[] => [
getTimeOption(timeFormat),
export const BACKSTAGE_OPTIONS: ParamField[] = [
TIME_FORMAT_OPTION,
{
id: 'hidePast',
title: 'Hide past events',
description: 'Scheduler will only show upcoming events',
type: 'boolean',
defaultValue: false,
},
{
id: 'stopCycle',
title: 'Stop cycling through event pages',
description: 'Schedule will not auto-cycle through events',
type: 'boolean',
defaultValue: false,
},
{
id: 'eventsPerPage',
title: 'Events per page',
description: 'Sets the number of events on the page, can cause overlow',
type: 'number',
placeholder: '7 (default)',
},
];
export const getPublicOptions = (timeFormat: TimeFormat): ParamField[] => [
getTimeOption(timeFormat),
export const PUBLIC_OPTIONS: ParamField[] = [
TIME_FORMAT_OPTION,
{
id: 'hidePast',
title: 'Hide past events',
description: 'Scheduler will only show upcoming events',
type: 'boolean',
defaultValue: false,
},
{
id: 'stopCycle',
title: 'Stop cycling through event pages',
description: 'Schedule will not auto-cycle through events',
type: 'boolean',
defaultValue: false,
},
{
id: 'eventsPerPage',
title: 'Events per page',
description: 'Sets the number of events on the page, can cause overlow',
type: 'number',
placeholder: '7 (default)',
},
];
export const getStudioClockOptions = (timeFormat: TimeFormat): ParamField[] => [
getTimeOption(timeFormat),
export const STUDIO_CLOCK_OPTIONS: ParamField[] = [
TIME_FORMAT_OPTION,
{
id: 'seconds',
title: 'Show Seconds',
description: 'Shows seconds in clock',
type: 'boolean',
defaultValue: false,
},
];
export const getOperatorOptions = (userFields: UserFields, timeFormat: TimeFormat): ParamField[] => {
export const getOperatorOptions = (userFields: UserFields): ParamField[] => {
return [
getTimeOption(timeFormat),
TIME_FORMAT_OPTION,
{
id: 'showseconds',
title: 'Show seconds',
description: 'Schedule shows hh:mm:ss',
type: 'boolean',
defaultValue: false,
},
{
id: 'hidepast',
title: 'Hide Past Events',
description: 'Whether to events that have passed',
type: 'boolean',
defaultValue: false,
},
{
id: 'main',
@@ -380,12 +334,5 @@ export const getOperatorOptions = (userFields: UserFields, timeFormat: TimeForma
user9: userFields.user9 || 'user9',
},
},
{
id: 'shouldEdit',
title: 'Edit user field',
description: 'Allows editing an events user field by long pressing on it. Needs a selected highlighted field',
type: 'boolean',
defaultValue: false,
},
];
};
@@ -4,13 +4,9 @@ type BaseField = {
description: string;
};
type OptionsField = {
type: 'option';
values: Record<string, string>;
defaultValue?: string;
};
type StringField = { type: 'string'; defaultValue?: string; prefix?: string; placeholder?: string };
type NumberField = { type: 'number'; defaultValue?: number; prefix?: string; placeholder?: string };
type BooleanField = { type: 'boolean'; defaultValue: boolean };
type OptionsField = { type: 'option'; values: Record<string, string> };
type StringField = { type: 'string' };
type BooleanField = { type: 'boolean' };
type NumberField = { type: 'number' };
export type ParamField = BaseField & (StringField | BooleanField | NumberField | OptionsField);
@@ -1,33 +0,0 @@
import { useMutation, useQuery } from '@tanstack/react-query';
import { HttpSettings } from 'ontime-types';
import { queryRefetchIntervalSlow } from '../../ontimeConfig';
import { HTTP_SETTINGS } from '../api/apiConstants';
import { logAxiosError } from '../api/apiUtils';
import { getHTTP, postHTTP } from '../api/ontimeApi';
import { httpPlaceholder } from '../models/Http';
import { ontimeQueryClient } from '../queryClient';
export function useHttpSettings() {
const { data, status, isFetching, isError, refetch } = useQuery({
queryKey: HTTP_SETTINGS,
queryFn: getHTTP,
placeholderData: httpPlaceholder,
retry: 5,
retryDelay: (attempt: number) => attempt * 2500,
refetchInterval: queryRefetchIntervalSlow,
networkMode: 'always',
});
// we need to jump through some hoops because of the type op port
return { data: data! as unknown as HttpSettings, status, isFetching, isError, refetch };
}
export function usePostHttpSettings() {
const { isPending, mutateAsync } = useMutation({
mutationFn: postHTTP,
onError: (error) => logAxiosError('Error saving HTTP settings', error),
onSettled: () => ontimeQueryClient.invalidateQueries({ queryKey: HTTP_SETTINGS }),
});
return { isPending, mutateAsync };
}
@@ -1,4 +1,7 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-nocheck -- working on it
import { useMutation, useQuery } from '@tanstack/react-query';
import { OSCSettings } from 'ontime-types';
import { queryRefetchIntervalSlow } from '../../ontimeConfig';
import { OSC_SETTINGS } from '../api/apiConstants';
@@ -10,10 +13,7 @@ import { ontimeQueryClient } from '../queryClient';
export default function useOscSettings() {
const { data, status, isFetching, isError, refetch } = useQuery({
queryKey: OSC_SETTINGS,
queryFn: async () => {
const oscData = await getOSC();
return { ...oscData, portIn: String(oscData.portIn), portOut: String(oscData.portOut) };
},
queryFn: getOSC,
placeholderData: oscPlaceholderSettings,
retry: 5,
retryDelay: (attempt: number) => attempt * 2500,
@@ -21,7 +21,8 @@ export default function useOscSettings() {
networkMode: 'always',
});
return { data: data ?? oscPlaceholderSettings, status, isFetching, isError, refetch };
// we need to jump through some hoops because of the type op port
return { data: data! as unknown as OSCSettings, status, isFetching, isError, refetch };
}
export function useOscSettingsMutation() {
+2 -2
View File
@@ -75,8 +75,8 @@ export const setPlayback = {
reload: () => {
socketSendJson('reload');
},
addTime: (amount: number) => {
socketSendJson('addtime', amount);
delay: (amount: number) => {
socketSendJson('delay', amount);
},
};
+24 -11
View File
@@ -1,13 +1,26 @@
import { HttpSettings } from 'ontime-types';
export const httpPlaceholder: HttpSettings = {
enabledOut: false,
subscriptions: {
onLoad: [],
onStart: [],
onUpdate: [],
onPause: [],
onStop: [],
onFinish: [],
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,
},
};
@@ -1,4 +1,4 @@
import { isIPAddress, isOnlyNumbers, startsWithHttp } from '../regex';
import { isIPAddress, isOnlyNumbers } from '../regex';
describe('simple tests for regex', () => {
test('isOnlyNumbers', () => {
@@ -24,16 +24,4 @@ describe('simple tests for regex', () => {
expect(isIPAddress.test(t)).toBe(false);
});
});
test('startsWithHttp', () => {
const right = ['http://test'];
const wrong = ['https://test', 'testing', '123.0.1'];
right.forEach((t) => {
expect(startsWithHttp.test(t)).toBe(true);
});
wrong.forEach((t) => {
expect(startsWithHttp.test(t)).toBe(false);
});
});
});
@@ -1,4 +1,4 @@
import { cx, getAccessibleColour } from '../styleUtils';
import { cx } from '../styleUtils';
import style from './styleUtils.module.scss';
@@ -13,24 +13,3 @@ describe('cx()', () => {
expect(merged).toMatchSnapshot();
});
});
describe('getAccessibleColour()', () => {
it('handles named colours', () => {
const colour = 'red';
const { backgroundColor, color } = getAccessibleColour(colour);
expect(backgroundColor).toBe('#FF0000FF');
expect(color).toBe('#fffffa');
});
it('handles hex colours', () => {
const colour = '#0F0';
const { backgroundColor, color } = getAccessibleColour(colour);
expect(backgroundColor).toBe('#00FF00FF');
expect(color).toBe('black');
});
it('handles transparens', () => {
const colour = '#0F08';
const { backgroundColor, color } = getAccessibleColour(colour);
expect(backgroundColor).toBe('#0C940CFF');
expect(color).toBe('#fffffa');
});
});
-1
View File
@@ -1,3 +1,2 @@
export const isOnlyNumbers = /^\d+$/;
export const isIPAddress = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/;
export const startsWithHttp = /^http:\/\//;
+3 -5
View File
@@ -13,15 +13,13 @@ type ColourCombination = {
export const getAccessibleColour = (bgColour?: string): ColourCombination => {
if (bgColour) {
try {
const originalColour = Color(bgColour);
const backgroundColorMix = originalColour.alpha(1).mix(Color('#1a1a1a'), 1 - originalColour.alpha());
const textColor = backgroundColorMix.isLight() ? 'black' : '#fffffa';
return { backgroundColor: backgroundColorMix.hexa(), color: textColor };
const textColor = Color(bgColour).isLight() ? 'black' : '#fffffa';
return { backgroundColor: bgColour, color: textColor };
} catch (_error) {
/* we do not handle errors here */
}
}
return { backgroundColor: '#1a1a1a', color: '#fffffa' };
return { backgroundColor: '#000', color: '#fffffa' };
};
/**
@@ -1 +1,44 @@
export type TimeEntryField = 'timeStart' | 'timeEnd' | 'durationOverride';
/**
* @description Checks which field the value relates to
*/
export const handleTimeEntry = (
field: TimeEntryField,
val: number,
timeStart: number,
timeEnd: number,
): { start: number; end: number; durationOverride: boolean } => {
let start = timeStart;
let end = timeEnd;
let durationOverride = false;
if (field === 'timeStart') {
start = val;
} else if (field === 'timeEnd') {
end = val;
} else {
durationOverride = field === 'durationOverride';
}
return { start, end, durationOverride };
};
/**
* @description Validates time entry
*/
export const validateEntry = (
field: TimeEntryField,
value: number,
timeStart: number,
timeEnd: number,
): { value: boolean; warnings: { start?: string; end?: string; duration?: string } } => {
const validate = { value: true, warnings: { start: '', end: '', duration: '' } };
const { start, end } = handleTimeEntry(field, value, timeStart, timeEnd);
if (end < start) {
validate.warnings.start = 'Start time later than end time';
}
return validate;
};
@@ -86,22 +86,22 @@ export default function PlaybackTimer(props: PlaybackTimerProps) {
)}
<div className={style.btn}>
<Tooltip label='Remove 1 minute' openDelay={tooltipDelayMid} shouldWrapChildren={disableButtons}>
<TapButton onClick={() => setPlayback.addTime(-60)} disabled={disableButtons} aspect='square'>
<TapButton onClick={() => setPlayback.delay(-1)} disabled={disableButtons} aspect='square'>
-1
</TapButton>
</Tooltip>
<Tooltip label='Add 1 minute' openDelay={tooltipDelayMid} shouldWrapChildren={disableButtons}>
<TapButton onClick={() => setPlayback.addTime(60)} disabled={disableButtons} aspect='square'>
<TapButton onClick={() => setPlayback.delay(1)} disabled={disableButtons} aspect='square'>
+1
</TapButton>
</Tooltip>
<Tooltip label='Remove 5 minutes' openDelay={tooltipDelayMid} shouldWrapChildren={disableButtons}>
<TapButton onClick={() => setPlayback.addTime(-5 * 60)} disabled={disableButtons} aspect='square'>
<TapButton onClick={() => setPlayback.delay(-5)} disabled={disableButtons} aspect='square'>
-5
</TapButton>
</Tooltip>
<Tooltip label='Add 5 minutes' openDelay={tooltipDelayMid} shouldWrapChildren={disableButtons}>
<TapButton onClick={() => setPlayback.addTime(+5 * 60)} disabled={disableButtons} aspect='square'>
<TapButton onClick={() => setPlayback.delay(+5)} disabled={disableButtons} aspect='square'>
+5
</TapButton>
</Tooltip>
@@ -5,7 +5,6 @@ import { isOntimeBlock, isOntimeDelay, isOntimeEvent, OntimeRundown, OntimeRundo
import useFollowComponent from '../../common/hooks/useFollowComponent';
import { useLocalStorage } from '../../common/hooks/useLocalStorage';
import { getAccessibleColour } from '../../common/utils/styleUtils';
import BlockRow from './cuesheet-table-elements/BlockRow';
import CuesheetHeader from './cuesheet-table-elements/CuesheetHeader';
@@ -121,8 +120,8 @@ export default function Cuesheet({ data, columns, handleUpdate, selectedId }: Cu
} else if (row.original.colour) {
try {
// the colour is user defined and might be invalid
const accessibleBackgroundColor = Color(getAccessibleColour(row.original.colour).backgroundColor);
rowBgColour = accessibleBackgroundColor.fade(0.75).hexa();
const colour = new Color(row.original.colour).alpha(0.25);
rowBgColour = colour.hsl().string();
} catch (_error) {
/* we do not handle errors here */
}
@@ -19,8 +19,8 @@ function EventRow(props: PropsWithChildren<EventRowProps>) {
const ownRef = useRef<HTMLTableRowElement>(null);
const [isVisible, setIsVisible] = useState(false);
const textColour = getAccessibleColour(colour);
const bgColour = textColour.backgroundColor;
const bgColour = colour;
const textColour = getAccessibleColour(bgColour);
useLayoutEffect(() => {
const observer = new IntersectionObserver(
@@ -55,7 +55,7 @@ function EventRow(props: PropsWithChildren<EventRowProps>) {
style={{ opacity: `${isPast ? pastOpacity : '1'}` }}
ref={selectedRef ?? ownRef}
>
<td className={style.indexColumn} style={{ backgroundColor: bgColour, color: textColour.color }}>
<td className={style.indexColumn} style={{ backgroundColor: bgColour, color: textColour?.color }}>
{eventIndex}
</td>
{isVisible ? children : null}
@@ -73,8 +73,8 @@ export default function EventEditor() {
handleSubmit={handleSubmit}
>
<CopyTag label='Event ID'>{event.id}</CopyTag>
<CopyTag label='OSC trigger by id'>{`/ontime/gotoid "${event.id}"`}</CopyTag>
<CopyTag label='OSC trigger by cue'>{`/ontime/gotocue "${event.cue}"`}</CopyTag>
<CopyTag label='OSC trigger by id'>{`/ontime/gotoid/${event.id}`}</CopyTag>
<CopyTag label='OSC trigger by cue'>{`/ontime/gotocue/${event.cue}`}</CopyTag>
</EventEditorDataRight>
</div>
);
@@ -40,7 +40,6 @@ export default function CountedTextInput(props: CountedTextInputProps) {
onChange={onChange}
onBlur={onBlur}
onKeyDown={onKeyDown}
autoComplete='off'
/>
</div>
);
@@ -1,4 +1,4 @@
import { memo } from 'react';
import { memo, useState } from 'react';
import { Select, Switch } from '@chakra-ui/react';
import { EndAction, OntimeEvent, TimerType } from 'ontime-types';
import { calculateDuration, millisToString } from 'ontime-utils';
@@ -7,6 +7,7 @@ import TimeInput from '../../../common/components/input/time-input/TimeInput';
import { useEventAction } from '../../../common/hooks/useEventAction';
import { millisToDelayString } from '../../../common/utils/dateConfig';
import { cx } from '../../../common/utils/styleUtils';
import { TimeEntryField, validateEntry } from '../../../common/utils/timesManager';
import style from '../EventEditor.module.scss';
@@ -28,6 +29,13 @@ const EventEditorTimes = (props: EventEditorTimesProps) => {
const { eventId, timeStart, timeEnd, duration, delay, isPublic, endAction, timerType } = props;
const { updateEvent } = useEventAction();
const [warning, setWarnings] = useState({ start: '', end: '', duration: '' });
const timerValidationHandler = (entry: TimeEntryField, val: number) => {
const valid = validateEntry(entry, val, timeStart, timeEnd);
setWarnings((prev) => ({ ...prev, ...valid.warnings }));
return valid.value;
};
const handleSubmit = (field: TimeActions, value: number | string | boolean) => {
const newEventData: Partial<OntimeEvent> = { id: eventId };
@@ -79,9 +87,11 @@ const EventEditorTimes = (props: EventEditorTimesProps) => {
id='timeStart'
name='timeStart'
submitHandler={handleSubmit}
validationHandler={timerValidationHandler}
time={timeStart}
delay={delay}
placeholder='Start'
warning={warning.start}
/>
<label className={inputTimeLabels} htmlFor='timeEnd'>
{endLabel}
@@ -90,9 +100,11 @@ const EventEditorTimes = (props: EventEditorTimesProps) => {
id='timeEnd'
name='timeEnd'
submitHandler={handleSubmit}
validationHandler={timerValidationHandler}
time={timeEnd}
delay={delay}
placeholder='End'
warning={warning.end}
/>
<label className={style.inputLabel} htmlFor='durationOverride'>
Duration
@@ -101,8 +113,10 @@ const EventEditorTimes = (props: EventEditorTimesProps) => {
id='durationOverride'
name='durationOverride'
submitHandler={handleSubmit}
validationHandler={timerValidationHandler}
time={duration}
placeholder='Duration'
warning={warning.duration}
/>
</div>
<div className={style.timeSettings}>
@@ -5,7 +5,6 @@
display: flex;
justify-content: space-between;
gap: 1rem;
font-size: $inner-section-text-size;
.title {
white-space: nowrap;
@@ -15,12 +14,12 @@
.selected {
min-width: max-content;
font-size: $inner-section-text-size;
color: $label-gray;
}
}
.description {
font-size: $inner-section-text-size;
color: $label-gray;
white-space: nowrap;
overflow: hidden;
+2 -3
View File
@@ -1,7 +1,6 @@
import { memo, useCallback, useEffect, useState } from 'react';
import { VStack } from '@chakra-ui/react';
import { IoCloud } from '@react-icons/all-files/io5/IoCloud';
import { IoCloudOutline } from '@react-icons/all-files/io5/IoCloudOutline';
import { IoCalendarOutline } from '@react-icons/all-files/io5/IoCalendarOutline';
import { IoColorWand } from '@react-icons/all-files/io5/IoColorWand';
import { IoExtensionPuzzle } from '@react-icons/all-files/io5/IoExtensionPuzzle';
import { IoExtensionPuzzleOutline } from '@react-icons/all-files/io5/IoExtensionPuzzleOutline';
@@ -183,7 +182,7 @@ const MenuBar = (props: MenuBarProps) => {
<TooltipActionBtn
{...buttonStyle}
isDisabled={appMode === AppMode.Run}
icon={isSheetsOpen ? <IoCloud /> : <IoCloudOutline />}
icon={<IoCalendarOutline />}
className={isSheetsOpen ? style.open : ''}
clickHandler={onSheetsOpen}
tooltip='Sheets'
@@ -2,9 +2,8 @@ import { ModalBody, Tab, TabList, TabPanel, TabPanels, Tabs } from '@chakra-ui/r
import ModalWrapper from '../ModalWrapper';
import HttpIntegration from './http/HttpIntegration';
import OscIntegration from './osc/OscIntegration';
import OscSettings from './osc/OscSettings';
import OscIntegration from './OscIntegration';
import OscSettings from './OscSettings';
import styles from '../Modal.module.scss';
@@ -31,7 +30,6 @@ export default function IntegrationModal(props: IntegrationModalProps) {
<TabList>
<Tab>OSC</Tab>
<Tab>OSC Integration</Tab>
<Tab>HTTP Integration</Tab>
</TabList>
<TabPanels>
<TabPanel>
@@ -40,9 +38,6 @@ export default function IntegrationModal(props: IntegrationModalProps) {
<TabPanel>
<OscIntegration />
</TabPanel>
<TabPanel>
<HttpIntegration />
</TabPanel>
</TabPanels>
</Tabs>
</ModalBody>
@@ -3,15 +3,43 @@ import { useForm } from 'react-hook-form';
import type { OscSubscription } from 'ontime-types';
import { TimerLifeCycle } from 'ontime-types';
import useOscSettings, { usePostOscSubscriptions } from '../../../../common/hooks-query/useOscSettings';
import { useEmitLog } from '../../../../common/stores/logger';
import ModalLoader from '../../modal-loader/ModalLoader';
import OntimeModalFooter from '../../OntimeModalFooter';
import { type OntimeCycle, sectionText } from '../integration.utils';
import useOscSettings, { usePostOscSubscriptions } from '../../../common/hooks-query/useOscSettings';
import { useEmitLog } from '../../../common/stores/logger';
import ModalLoader from '../modal-loader/ModalLoader';
import OntimeModalFooter from '../OntimeModalFooter';
import OscSubscriptionRow from './OscSubscriptionRow';
import styles from '../../Modal.module.scss';
import styles from '../Modal.module.scss';
type OntimeCycle = keyof typeof TimerLifeCycle;
const sectionText: { [key in TimerLifeCycle]: { title: string; subtitle: string } } = {
onLoad: {
title: 'On Load',
subtitle: 'Triggers when a timer is loaded',
},
onStart: {
title: 'On Start',
subtitle: 'Triggers when a timer starts',
},
onPause: {
title: 'On Pause',
subtitle: 'Triggers when a running timer is paused',
},
onStop: {
title: 'On Stop',
subtitle: 'Triggers when a running timer is stopped',
},
onUpdate: {
title: 'On Every Second',
subtitle: 'Triggers when a running timer is updated (at least once a second, can be more)',
},
onFinish: {
title: 'On Finish',
subtitle: 'Triggers when a running reaches 0',
},
};
export default function OscIntegration() {
const { data, isFetching } = useOscSettings();
@@ -64,7 +92,6 @@ export default function OscIntegration() {
return <ModalLoader />;
}
const placeholder = 'OSC message';
return (
<form onSubmit={handleSubmit(onSubmit)} className={styles.sectionContainer} id='osc-subscriptions'>
<OscSubscriptionRow
@@ -75,7 +102,6 @@ export default function OscIntegration() {
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<OscSubscriptionRow
cycle={TimerLifeCycle.onStart}
@@ -85,7 +111,6 @@ export default function OscIntegration() {
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<OscSubscriptionRow
cycle={TimerLifeCycle.onPause}
@@ -95,7 +120,6 @@ export default function OscIntegration() {
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<OscSubscriptionRow
cycle={TimerLifeCycle.onStop}
@@ -105,7 +129,6 @@ export default function OscIntegration() {
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<OscSubscriptionRow
cycle={TimerLifeCycle.onUpdate}
@@ -115,7 +138,6 @@ export default function OscIntegration() {
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<OscSubscriptionRow
cycle={TimerLifeCycle.onFinish}
@@ -125,7 +147,6 @@ export default function OscIntegration() {
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<OntimeModalFooter
formId='osc-subscriptions'
@@ -1,15 +1,17 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-nocheck -- working on it
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { FormControl, Input, Switch } from '@chakra-ui/react';
import useOscSettings, { useOscSettingsMutation } from '../../../../common/hooks-query/useOscSettings';
import { PlaceholderSettings } from '../../../../common/models/OscSettings';
import { useEmitLog } from '../../../../common/stores/logger';
import { isIPAddress, isOnlyNumbers } from '../../../../common/utils/regex';
import ModalLoader from '../../modal-loader/ModalLoader';
import OntimeModalFooter from '../../OntimeModalFooter';
import useOscSettings, { useOscSettingsMutation } from '../../../common/hooks-query/useOscSettings';
import { PlaceholderSettings } from '../../../common/models/OscSettings';
import { useEmitLog } from '../../../common/stores/logger';
import { isIPAddress, isOnlyNumbers } from '../../../common/utils/regex';
import ModalLoader from '../modal-loader/ModalLoader';
import OntimeModalFooter from '../OntimeModalFooter';
import styles from '../../Modal.module.scss';
import styles from '../Modal.module.scss';
export default function OscSettings() {
const { data, isFetching } = useOscSettings();
@@ -57,6 +59,7 @@ export default function OscSettings() {
};
const resetForm = () => {
// @ts-expect-error -- we know the types dont match
reset(data);
};
@@ -2,12 +2,12 @@ import { Control, useFieldArray, UseFormRegister } from 'react-hook-form';
import { Button, IconButton, Input, Switch } from '@chakra-ui/react';
import { FiChevronUp } from '@react-icons/all-files/fi/FiChevronUp';
import { IoRemove } from '@react-icons/all-files/io5/IoRemove';
import type { OscSubscription, TimerLifeCycle } from 'ontime-types';
import { OscSubscription, TimerLifeCycle } from 'ontime-types';
import { useEmitLog } from '../../../../common/stores/logger';
import { useEmitLog } from '../../../common/stores/logger';
import collapseStyles from '../../../../common/components/collapse-bar/CollapseBar.module.scss';
import styles from '../../Modal.module.scss';
import collapseStyles from '../../../common/components/collapse-bar/CollapseBar.module.scss';
import styles from '../Modal.module.scss';
interface OscSubscriptionRowProps {
cycle: TimerLifeCycle;
@@ -17,11 +17,10 @@ interface OscSubscriptionRowProps {
setShowSection: (cycle: TimerLifeCycle) => void;
register: UseFormRegister<OscSubscription>;
control: Control<OscSubscription>;
placeholder: string;
}
export default function OscSubscriptionRow(props: OscSubscriptionRowProps) {
const { cycle, title, subtitle, visible, setShowSection, register, control, placeholder } = props;
const { cycle, title, subtitle, visible, setShowSection, register, control } = props;
const { emitError } = useEmitLog();
const { fields, append, remove } = useFieldArray({
name: cycle,
@@ -65,7 +64,7 @@ export default function OscSubscriptionRow(props: OscSubscriptionRowProps) {
colorScheme='red'
/>
<Input
placeholder={placeholder}
placeholder='OSC Message'
size='xs'
variant='ontime-filled-on-light'
autoComplete='off'
@@ -1,152 +0,0 @@
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { Switch } from '@chakra-ui/react';
import type { HttpSettings } from 'ontime-types';
import { TimerLifeCycle } from 'ontime-types';
import { useHttpSettings, usePostHttpSettings } from '../../../../common/hooks-query/useHttpSettings';
import { useEmitLog } from '../../../../common/stores/logger';
import ModalLoader from '../../modal-loader/ModalLoader';
import OntimeModalFooter from '../../OntimeModalFooter';
import { OntimeCycle, sectionText } from '../integration.utils';
import HttpSubscriptionRow from './HttpSubscriptionRow';
import styles from '../../Modal.module.scss';
export default function HttpIntegration() {
const { data, isFetching } = useHttpSettings();
const { mutateAsync } = usePostHttpSettings();
const { emitError } = useEmitLog();
const {
control,
handleSubmit,
register,
reset,
formState: { isSubmitting, isDirty, isValid },
} = useForm<HttpSettings>({
mode: 'onBlur',
defaultValues: data,
values: data,
resetOptions: {
keepDirtyValues: true,
},
});
const [showSection, setShowSection] = useState<OntimeCycle>(TimerLifeCycle.onLoad);
useEffect(() => {
if (data) {
reset(data);
}
}, [data, reset]);
const resetForm = () => {
reset(data);
};
const onSubmit = async (values: HttpSettings) => {
try {
const newSettings: HttpSettings = {
enabledOut: Boolean(values.enabledOut),
subscriptions: {
onLoad: values.subscriptions.onLoad ?? [],
onStart: values.subscriptions.onStart ?? [],
onPause: values.subscriptions.onPause ?? [],
onStop: values.subscriptions.onStop ?? [],
onUpdate: values.subscriptions.onUpdate ?? [],
onFinish: values.subscriptions.onFinish ?? [],
},
};
await mutateAsync(newSettings);
} catch (error) {
emitError(`Error setting HTML: ${error}`);
}
};
if (isFetching) {
return <ModalLoader />;
}
const placeholder = 'http://x.x.x.x:xxxx/api/path';
return (
<form onSubmit={handleSubmit(onSubmit)} className={styles.sectionContainer} id='http-subscriptions'>
<div className={styles.splitSection}>
<div>
<span className={`${styles.sectionTitle} ${styles.main}`}>HTTP Output</span>
<span className={styles.sectionSubtitle}>Ontime data feedback</span>
</div>
<Switch {...register('enabledOut')} variant='ontime-on-light' />
</div>
<HttpSubscriptionRow
cycle={TimerLifeCycle.onLoad}
title={sectionText.onLoad.title}
subtitle={sectionText.onLoad.subtitle}
visible={showSection === TimerLifeCycle.onLoad}
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<HttpSubscriptionRow
cycle={TimerLifeCycle.onStart}
title={sectionText.onStart.title}
subtitle={sectionText.onStart.subtitle}
visible={showSection === TimerLifeCycle.onStart}
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<HttpSubscriptionRow
cycle={TimerLifeCycle.onPause}
title={sectionText.onPause.title}
subtitle={sectionText.onPause.subtitle}
visible={showSection === TimerLifeCycle.onPause}
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<HttpSubscriptionRow
cycle={TimerLifeCycle.onStop}
title={sectionText.onStop.title}
subtitle={sectionText.onStop.subtitle}
visible={showSection === TimerLifeCycle.onStop}
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<HttpSubscriptionRow
cycle={TimerLifeCycle.onUpdate}
title={sectionText.onUpdate.title}
subtitle={sectionText.onUpdate.subtitle}
visible={showSection === TimerLifeCycle.onUpdate}
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<HttpSubscriptionRow
cycle={TimerLifeCycle.onFinish}
title={sectionText.onFinish.title}
subtitle={sectionText.onFinish.subtitle}
visible={showSection === TimerLifeCycle.onFinish}
setShowSection={setShowSection}
register={register}
control={control}
placeholder={placeholder}
/>
<OntimeModalFooter
formId='http-subscriptions'
handleRevert={resetForm}
isDirty={isDirty}
isValid={isValid}
isSubmitting={isSubmitting}
/>
</form>
);
}
@@ -1,95 +0,0 @@
import { Control, useFieldArray, UseFormRegister } from 'react-hook-form';
import { Button, IconButton, Input, Switch } from '@chakra-ui/react';
import { FiChevronUp } from '@react-icons/all-files/fi/FiChevronUp';
import { IoRemove } from '@react-icons/all-files/io5/IoRemove';
import { HttpSettings, TimerLifeCycle } from 'ontime-types';
import { useEmitLog } from '../../../../common/stores/logger';
import { startsWithHttp } from '../../../../common/utils/regex';
import collapseStyles from '../../../../common/components/collapse-bar/CollapseBar.module.scss';
import styles from '../../Modal.module.scss';
interface SubscriptionRowProps {
cycle: TimerLifeCycle;
title: string;
subtitle: string;
visible: boolean;
setShowSection: (cycle: TimerLifeCycle) => void;
register: UseFormRegister<HttpSettings>;
control: Control<HttpSettings>;
placeholder: string;
}
export default function SubscriptionRow(props: SubscriptionRowProps) {
const { cycle, title, subtitle, visible, setShowSection, register, control, placeholder } = props;
const { emitError } = useEmitLog();
const { fields, append, remove } = useFieldArray({
name: `subscriptions.${cycle}`,
control,
});
const hasTooManyOptions = fields.length >= 3;
const headerStyle = `${styles.splitSection} ${visible ? '' : styles.showPointer}`;
const sectionTitle = `${title} ${fields.length ? fields.length : '-'} / 3`;
const handleAddNew = () => {
if (hasTooManyOptions) {
emitError(`Maximum amount of ${cycle} subscriptions reached (3)`);
return;
}
append({
message: '',
enabled: false,
});
};
return (
<>
<div className={headerStyle} onClick={() => setShowSection(cycle)}>
<div>
<span className={`${styles.sectionTitle} ${styles.main}`}>{sectionTitle}</span>
{visible && <span className={styles.sectionSubtitle}>{subtitle}</span>}
</div>
<FiChevronUp className={visible ? collapseStyles.moreCollapsed : collapseStyles.moreExpanded} />
</div>
{visible && (
<>
{fields.map((subscription, index) => (
<div key={subscription.id} className={styles.entryRow}>
<IconButton
icon={<IoRemove />}
onClick={() => remove(index)}
aria-label='delete'
size='xs'
colorScheme='red'
/>
<Input
placeholder={placeholder}
size='xs'
variant='ontime-filled-on-light'
autoComplete='off'
{...register(`subscriptions.${cycle}.${index}.message`, {
pattern: { value: startsWithHttp, message: 'Request address must start with http://' },
})}
/>
<Switch variant='ontime-on-light' {...register(`subscriptions.${cycle}.${index}.enabled`)} />
</div>
))}
<Button
onClick={handleAddNew}
className={styles.shiftRight}
isDisabled={hasTooManyOptions}
size='xs'
colorScheme='blue'
variant='outline'
padding='0 2em'
>
Add new
</Button>
</>
)}
</>
);
}
@@ -1,30 +0,0 @@
import { TimerLifeCycle } from 'ontime-types';
export type OntimeCycle = keyof typeof TimerLifeCycle;
export const sectionText: { [key in TimerLifeCycle]: { title: string; subtitle: string } } = {
onLoad: {
title: 'On Load',
subtitle: 'Triggers when a timer is loaded',
},
onStart: {
title: 'On Start',
subtitle: 'Triggers when a timer starts',
},
onPause: {
title: 'On Pause',
subtitle: 'Triggers when a running timer is paused',
},
onStop: {
title: 'On Stop',
subtitle: 'Triggers when a running timer is stopped',
},
onUpdate: {
title: 'On Every Second',
subtitle: 'Triggers when a running timer is updated (at least once a second, can be more)',
},
onFinish: {
title: 'On Finish',
subtitle: 'Triggers when a running reaches 0',
},
};
@@ -119,7 +119,6 @@ export default function AppSettingsModal() {
<option value='en'>English</option>
<option value='fr'>French</option>
<option value='de'>German</option>
<option value='it'>Italian</option>
<option value='no'>Norwegian</option>
<option value='pt'>Portuguese</option>
<option value='es'>Spanish</option>
@@ -1,11 +1,6 @@
import { ChangeEvent, useEffect, useRef, useState } from 'react';
import { ChangeEvent, useEffect,useRef, useState } from 'react';
import {
Alert,
AlertDescription,
AlertIcon,
AlertTitle,
Button,
HStack,
Input,
Modal,
ModalBody,
@@ -14,33 +9,29 @@ import {
ModalFooter,
ModalHeader,
ModalOverlay,
Select,
} from '@chakra-ui/react';
import { IoArrowDownCircleOutline } from '@react-icons/all-files/io5/IoArrowDownCircleOutline';
import { IoArrowUpCircleOutline } from '@react-icons/all-files/io5/IoArrowUpCircleOutline';
import { IoCheckmarkCircleOutline } from '@react-icons/all-files/io5/IoCheckmarkCircleOutline';
import { IoCloseCircleOutline } from '@react-icons/all-files/io5/IoCloseCircleOutline';
import { useQueryClient } from '@tanstack/react-query';
import { OntimeRundown, ProjectData, UserFields } from 'ontime-types';
import { defaultExcelImportMap, ExcelImportMap } from 'ontime-utils';
import { GoogleSheetState, OntimeRundown, ProjectData, UserFields } from 'ontime-types';
import { PROJECT_DATA, RUNDOWN, USERFIELDS } from '../../../common/api/apiConstants';
import { maybeAxiosError } from '../../../common/api/apiUtils';
import {
getAuthentication,
getClientSecrect,
getSheetsAuthUrl,
getSheetSettings,
getSheetstate,
patchData,
postId,
postPreviewSheet,
postPushSheet,
postWorksheet,
postSheetSettings,
uploadSheetClientFile,
} from '../../../common/api/ontimeApi';
import { projectDataPlaceholder } from '../../../common/models/ProjectData';
import { userFieldsPlaceholder } from '../../../common/models/UserFields';
import { openLink } from '../../../common/utils/linkUtils';
import ModalLink from '../ModalLink';
import PreviewExcel from '../upload-modal/preview/PreviewExcel';
import ExcelFileOptions from '../upload-modal/upload-options/ExcelFileOptions';
import Step from './Step';
interface SheetsModalProps {
onClose: () => void;
@@ -50,37 +41,18 @@ interface SheetsModalProps {
export default function SheetsModal(props: SheetsModalProps) {
const { isOpen, onClose } = props;
const queryClient = useQueryClient();
const fileInputRef = useRef<HTMLInputElement>(null);
const [rundown, setRundown] = useState<OntimeRundown | null>(null);
const [userFields, setUserFields] = useState<UserFields | null>(null);
const [project, setProject] = useState<ProjectData | null>(null);
const [id, setSheetId] = useState('');
const [worksheet, setWorksheet] = useState('');
const [worksheetOptions, setWorksheetOptions] = useState<string[]>([]);
const [sheetState, setSheetState] = useState<GoogleSheetState>({ auth: false, id: false, worksheet: false });
const [direction, setDirection] = useState('none');
const excelFileOptions = useRef<ExcelImportMap>(defaultExcelImportMap);
const queryClient = useQueryClient();
const fileInputRef = useRef<HTMLInputElement>(null);
const [state, setState] = useState({
clientSecret: { complete: false, message: '' },
authenticate: { complete: false, message: '' },
id: { complete: false, message: '' },
worksheet: { complete: false, message: '' },
pullPush: { complete: false, message: '' },
});
useEffect(() => {
if (isOpen) {
setDirection('none');
testClientSecret();
if (state.clientSecret.complete) testAuthentication();
if (state.authenticate.complete) testSheetId();
}
}, [isOpen]);
const sheetid = useRef<HTMLInputElement>(null);
const worksheet = useRef<HTMLInputElement>(null);
const handleClose = () => {
setRundown(null);
@@ -88,162 +60,75 @@ export default function SheetsModal(props: SheetsModalProps) {
setUserFields(null);
onClose();
};
//SETP-1 Upload Client ID
const handleClick = () => {
fileInputRef.current?.click();
};
const handleFile = (event: ChangeEvent<HTMLInputElement>) => {
if (!event.target.files?.length) {
setState({
clientSecret: { complete: false, message: 'Missing file' },
authenticate: { complete: false, message: '' },
id: { complete: false, message: '' },
worksheet: { complete: false, message: '' },
pullPush: { complete: false, message: '' },
});
const handleFile = async (event: ChangeEvent<HTMLInputElement>) => {
const selectedFile = event?.target?.files?.[0];
if (!selectedFile) {
return;
} else {
await uploadSheetClientFile(selectedFile);
_onChange();
}
const selectedFile = event.target.files[0];
uploadSheetClientFile(selectedFile)
.then(() => {
setState({ ...state, clientSecret: { complete: true, message: '' } });
})
.catch((err) => {
const message = maybeAxiosError(err);
setState({
clientSecret: { complete: false, message },
authenticate: { complete: false, message: '' },
id: { complete: false, message: '' },
worksheet: { complete: false, message: '' },
pullPush: { complete: false, message: '' },
});
});
};
const testClientSecret = () => {
getClientSecrect()
.then(() => {
setState({ ...state, clientSecret: { complete: true, message: '' } });
})
.catch((err) => {
const message = maybeAxiosError(err);
setState({
clientSecret: { complete: false, message },
authenticate: { complete: false, message: '' },
id: { complete: false, message: '' },
worksheet: { complete: false, message: '' },
pullPush: { complete: false, message: '' },
});
});
const _onChange = async () => {
setSheetState(await getSheetstate());
};
useEffect(() => {
getSheetSettings().then((data) => {
if (sheetid.current?.value != data.id || worksheet.current?.value != data.worksheet) {
_onChange();
}
if (sheetid.current) {
sheetid.current.value = data.id;
}
if (worksheet.current) {
worksheet.current.value = data.worksheet;
}
});
});
const handelSave = () => {
postSheetSettings({ id: sheetid.current?.value ?? '', worksheet: worksheet.current?.value ?? '' }).then((data) => {
_onChange();
if (sheetid.current) {
sheetid.current.value = data.id;
}
if (worksheet.current) {
worksheet.current.value = data.worksheet;
}
});
};
//SETP-2 Authenticate
const handleAuthenticate = () => {
getSheetsAuthUrl()
.then((data) => {
openLink(data);
window.addEventListener('focus', () => testAuthentication(), { once: true });
})
.catch((err) => {
const message = maybeAxiosError(err);
setState({
...state,
authenticate: { complete: false, message },
id: { complete: false, message: '' },
worksheet: { complete: false, message: '' },
pullPush: { complete: false, message: '' },
});
});
};
const testAuthentication = () => {
getAuthentication()
.then(() => {
setState({ ...state, authenticate: { complete: true, message: '' } });
})
.catch((error) => {
const message = maybeAxiosError(error);
setState({
...state,
authenticate: { complete: false, message },
id: { complete: false, message: '' },
worksheet: { complete: false, message: '' },
pullPush: { complete: false, message: '' },
});
});
};
//SETP-3 set sheet ID
const testSheetId = () => {
postId(id)
.then((data) => {
setState({ ...state, id: { complete: true, message: '' } });
setWorksheetOptions(data.worksheetOptions);
})
.catch((err) => {
const message = maybeAxiosError(err);
setState({
...state,
id: { complete: false, message },
worksheet: { complete: false, message: '' },
pullPush: { complete: false, message: '' },
});
setWorksheetOptions([]);
});
};
//SETP-4 Select Worksheet
const testWorksheet = (value: string) => {
excelFileOptions.current.worksheet = value;
setWorksheet(value);
postWorksheet(id, worksheet)
.then(() => {
setState({ ...state, worksheet: { complete: true, message: '' } });
})
.catch((err) => {
const message = maybeAxiosError(err);
setState({ ...state, worksheet: { complete: false, message }, pullPush: { complete: false, message: '' } });
});
};
//SETP-5 Upload / Download
const updateExcelFileOptions = <T extends keyof ExcelImportMap>(field: T, value: ExcelImportMap[T]) => {
if (excelFileOptions.current[field] !== value) {
excelFileOptions.current = { ...excelFileOptions.current, [field]: value };
}
getSheetsAuthUrl().then((data) => {
if (data != 'bad') {
window.open(data, '_blank', 'noreferrer');
//TODO: can we detect when this window is closed
}
});
};
const handlePullData = () => {
postPreviewSheet(id, excelFileOptions.current)
.then((data) => {
setProject(data.project);
setRundown(data.rundown);
setUserFields(data.userFields);
})
.catch((error) => {
const message = maybeAxiosError(error);
setDirection('none');
setState({ ...state, pullPush: { complete: false, message } });
});
postPreviewSheet().then((data) => {
setProject(data.project);
setRundown(data.rundown);
setUserFields(data.userFields);
});
};
const handlePushData = () => {
postPushSheet(id, excelFileOptions.current)
.then(() => {
setDirection('none');
setState({ ...state, pullPush: { complete: true, message: '' } });
})
.catch((error) => {
const message = maybeAxiosError(error);
setDirection('none');
setState({ ...state, pullPush: { complete: false, message } });
});
postPushSheet().then((data) => {
console.log(data);
});
};
//GET preview
const handleFinalise = async () => {
// this step is currently only used for excel files, after preview
if (rundown && userFields && project) {
let doClose = false;
try {
@@ -257,7 +142,8 @@ export default function SheetsModal(props: SheetsModalProps) {
doClose = true;
} catch (error) {
const message = maybeAxiosError(error);
console.error(message);
console.log(message);
// setErrors(`Failed applying changes ${message}`);
} finally {
if (doClose) {
handleClose();
@@ -279,188 +165,95 @@ export default function SheetsModal(props: SheetsModalProps) {
>
<ModalOverlay />
<ModalContent>
<ModalHeader>Rundown from sheets (experimental)</ModalHeader>
<ModalHeader>Sheets!</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Alert status='info' variant='ontime-on-light-info'>
<AlertIcon />
<div style={{ display: 'flex', flexDirection: 'column' }}>
<AlertTitle>Sync with Google Sheets</AlertTitle>
<AlertDescription>
<ModalLink href='https://ontime.gitbook.io/v2/features/google-sheet'>
For more information, see the docs
</ModalLink>
</AlertDescription>
</div>
</Alert>
{!rundown ? (
direction === 'up' || direction === 'down' ? (
<ExcelFileOptions optionsRef={excelFileOptions} updateOptions={updateExcelFileOptions} />
) : (
<>
<Step
title='1 - Upload OAuth 2.0 Client ID'
completed={state.clientSecret.complete}
disabled={false}
error={state.clientSecret.message}
>
<Input
ref={fileInputRef}
style={{ display: 'none' }}
type='file'
onChange={handleFile}
accept='.json'
data-testid='file-input'
/>
<div style={{ display: 'flex', gap: '1em' }}>
<Button size='sm' variant='ontime-subtle-on-light' onClick={handleClick}>
{state.clientSecret.complete ? 'Reupload Client ID' : 'Upload Client ID'}
</Button>
<Button size='sm' variant='ontime-ghosted-on-light' onClick={testClientSecret}>
Retry Client ID
</Button>
</div>
</Step>
<Step
title='2 - Authenticate with Google'
completed={state.authenticate.complete}
disabled={!state.clientSecret.complete}
error={state.authenticate.message}
>
<div style={{ display: 'flex', gap: '1em' }}>
<Button
size='sm'
variant='ontime-subtle-on-light'
onClick={handleAuthenticate}
isDisabled={!state.clientSecret.complete}
>
Authenticate
</Button>
<Button
size='sm'
variant='ontime-ghosted-on-light'
onClick={testAuthentication}
isDisabled={!state.clientSecret.complete}
>
Retry Connection
</Button>
</div>
</Step>
<Step
title='3 - Add Document ID'
completed={state.id.complete}
disabled={!state.authenticate.complete}
error={state.id.message}
>
<HStack>
<Input
type='text'
size='sm'
variant='ontime-filled-on-light'
isDisabled={!state.authenticate.complete}
value={id}
onChange={(event) => setSheetId(event.target.value)}
/>
<Button
isDisabled={!state.authenticate.complete}
size='sm'
variant='ontime-subtle-on-light'
padding='0 2em'
onClick={testSheetId}
>
Connect
</Button>
</HStack>
</Step>
<Step
title='4 - Select Worksheet to import'
completed={state.worksheet.complete}
disabled={worksheetOptions.length == 0}
>
<Select
size='sm'
isDisabled={worksheetOptions.length == 0}
placeholder='Select a worksheet'
onChange={(event) => testWorksheet(event.target.value)}
value={worksheet}
>
{worksheetOptions.map((value) => (
<option key={value} value={value}>
{value}
</option>
))}
</Select>
</Step>
<Step title='5 - Upload / Download rundown' completed={false} disabled={!state.worksheet.complete}>
<div style={{ display: 'flex', gap: '1em' }}>
<Button
isDisabled={!state.worksheet.complete}
variant='ontime-subtle-on-light'
padding='0 2em'
onClick={() => setDirection('up')}
>
Upload
</Button>
<Button
isDisabled={!state.worksheet.complete}
variant='ontime-subtle-on-light'
padding='0 2em'
onClick={() => setDirection('down')}
>
Download
</Button>
</div>
</Step>
</>
)
) : (
<PreviewExcel
rundown={rundown ?? []}
project={project ?? projectDataPlaceholder}
userFields={userFields ?? userFieldsPlaceholder}
/>
{rundown && (
<>
<PreviewExcel
rundown={rundown ?? []}
project={project ?? projectDataPlaceholder}
userFields={userFields ?? userFieldsPlaceholder}
/>
</>
)}
{!rundown && (
<>
<Input
ref={fileInputRef}
style={{ display: 'none' }}
type='file'
onChange={handleFile}
accept='.json'
data-testid='file-input'
/>
<div>Need to add some help here</div>
<div>
<Button onClick={handleClick}>Upload Client Secrect</Button>
</div>
<Button variant='ontime-filled' padding='0 2em' onClick={handleAuthenticate}>
Authenticate
</Button>
{sheetState.auth ? <div>You are authenticated</div> : <div>You are not authenticated</div>}
<div>
<label htmlFor='sheetid'>Sheet ID </label>
<Input
type='text'
ref={sheetid}
id='sheetid'
width='240px'
size='sm'
textAlign='right'
variant='ontime-filled-on-light'
/>
{sheetState.id ? <IoCheckmarkCircleOutline /> : <IoCloseCircleOutline />}
<br />
<label htmlFor='worksheet'>Worksheet </label>
<Input
type='text'
ref={worksheet}
id='worksheet'
width='240px'
size='sm'
textAlign='right'
variant='ontime-filled-on-light'
/>
{sheetState.worksheet ? <IoCheckmarkCircleOutline /> : <IoCloseCircleOutline />}
</div>
</>
)}
</ModalBody>
<ModalFooter>
{rundown ? (
<div style={{ display: 'flex', gap: '1em' }}>
{!rundown && (
<div>
<Button
onClick={() => {
setRundown(null);
setDirection('none');
}}
variant='ontime-ghost-on-light'
variant='ontime-subtle-on-light'
padding='0 2em'
onClick={handlePullData}
rightIcon={<IoArrowDownCircleOutline />}
>
Go Back
Pull data
</Button>
<Button variant='ontime-filled' padding='0 2em' onClick={handleFinalise}>
Import
<Button
variant='ontime-subtle-on-light'
padding='0 2em'
onClick={handlePushData}
rightIcon={<IoArrowUpCircleOutline />}
>
Push data
</Button>
</div>
) : direction === 'up' ? (
<div style={{ display: 'flex', gap: '1em' }}>
<Button onClick={() => setDirection('none')} variant='ontime-ghost-on-light'>
Go Back
</Button>
<Button variant='ontime-filled' padding='0 2em' onClick={handlePushData}>
Upload
</Button>
</div>
) : direction === 'down' ? (
<div style={{ display: 'flex', gap: '1em' }}>
<Button onClick={() => setDirection('none')} variant='ontime-ghost-on-light'>
Go Back
</Button>
<Button variant='ontime-filled' padding='0 2em' onClick={handlePullData}>
Preview
</Button>
</div>
) : (
<></>
)}
<Button variant='ontime-ghost-on-light'>Reset</Button>
{!rundown && (
<Button variant='ontime-filled' padding='0 2em' onClick={handelSave}>
Save
</Button>
)}
{rundown && (
<Button variant='ontime-filled' padding='0 2em' onClick={handleFinalise}>
Import
</Button>
)}
</ModalFooter>
</ModalContent>
@@ -1,42 +0,0 @@
@use '../../../theme/ontimeColours' as *;
.wrapper {
padding: 0.5rem;
}
.header {
width: 100%;
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 1rem;
padding-bottom: 1rem;
}
.step {
width: 1.25rem;
height: 1.25rem;
font-size: 0.75rem;
display: grid;
place-content: center;
}
.title {
display: inline;
color: $gray-500;
text-transform: uppercase;
cursor: pointer;
}
.check {
color: $green-700;
}
.errorIcon {
color: $red-700;
}
.errorText {
color: $red-700;
font-size: 0.75rem;
}
@@ -1,47 +0,0 @@
import { PropsWithChildren, useEffect, useMemo, useState } from 'react';
import { IoCheckmarkCircle } from '@react-icons/all-files/io5/IoCheckmarkCircle';
import { IoCloseCircle } from '@react-icons/all-files/io5/IoCloseCircle';
import { IoRadioButtonOffOutline } from '@react-icons/all-files/io5/IoRadioButtonOffOutline';
import style from './Step.module.scss';
interface StepProps {
title: string;
disabled: boolean;
completed: boolean;
error?: string;
}
export default function Step(props: PropsWithChildren<StepProps>) {
const { title, disabled, completed, error, children } = props;
const [collapsed, setCollapsed] = useState(disabled);
const handleCollapse = () => setCollapsed((prev) => !prev);
const icon = useMemo(() => {
if (completed) return <IoCheckmarkCircle className={style.step} style={{ color: 'green' }} />;
if (error) return <IoCloseCircle className={style.step} style={{ color: 'red' }} />;
return <IoRadioButtonOffOutline className={style.step} />;
}, [completed, error]);
useEffect(() => {
if (completed) {
setCollapsed(true);
}
}, [completed]);
return (
<div className={style.wrapper}>
<div className={style.header} onClick={handleCollapse}>
{icon}
<span className={style.title}>{title}</span>
</div>
{!collapsed && (
<>
{error && <div className={style.errorText}>{error}</div>}
{children}
</>
)}
</div>
);
}
@@ -11,7 +11,6 @@ import useFollowComponent from '../../common/hooks/useFollowComponent';
import { useOperator } from '../../common/hooks/useSocket';
import useProjectData from '../../common/hooks-query/useProjectData';
import useRundown from '../../common/hooks-query/useRundown';
import useSettings from '../../common/hooks-query/useSettings';
import useUserFields from '../../common/hooks-query/useUserFields';
import { debounce } from '../../common/utils/debounce';
import { isStringBoolean } from '../../common/utils/viewUtils';
@@ -41,7 +40,6 @@ export default function Operator() {
const featureData = useOperator();
const [searchParams] = useSearchParams();
const { data: settings } = useSettings();
const [showEditPrompt, setShowEditPrompt] = useState(false);
const [editEvent, setEditEvent] = useState<PartialEdit | null>(null);
@@ -123,16 +121,13 @@ export default function Operator() {
}
// get fields which the user subscribed to
const shouldEdit = searchParams.get('shouldEdit');
const subscribe = searchParams.get('subscribe') as keyof UserFields | null;
const canEdit = shouldEdit && subscribe;
const main = searchParams.get('main') as keyof TitleFields | null;
const secondary = searchParams.get('secondary') as keyof TitleFields | null;
const subscribedAlias = subscribe ? userFields[subscribe] : '';
const showSeconds = isStringBoolean(searchParams.get('showseconds'));
const operatorOptions = getOperatorOptions(userFields, settings?.timeFormat ?? '24');
const operatorOptions = getOperatorOptions(userFields);
let isPast = Boolean(featureData.selectedEventId);
const hidePast = isStringBoolean(searchParams.get('hidepast'));
@@ -155,7 +150,7 @@ export default function Operator() {
lastId={lastEvent?.id}
/>
{canEdit && (
{subscribe && (
<div className={`${style.editPrompt} ${showEditPrompt ? style.show : undefined}`}>
Press and hold to edit user field
</div>
@@ -196,7 +191,7 @@ export default function Operator() {
showSeconds={showSeconds}
isPast={isPast}
selectedRef={isSelected ? selectedRef : undefined}
onLongPress={canEdit ? handleEdit : () => undefined}
onLongPress={subscribe ? handleEdit : () => undefined}
/>
);
}
@@ -198,9 +198,7 @@ export default function Rundown(props: RundownProps) {
if (index === 0) {
eventIndex = 0;
}
let isFirstEvent = false;
if (entry.type === SupportedEvent.Event) {
isFirstEvent = eventIndex === 0;
eventIndex++;
previousEnd = thisEnd;
thisEnd = entry.timeEnd;
@@ -222,7 +220,6 @@ export default function Rundown(props: RundownProps) {
<RundownEntry
type={entry.type}
isPast={isPast}
isFirstEvent={isFirstEvent}
data={entry}
selected={isSelected}
hasCursor={hasCursor}
@@ -19,7 +19,6 @@ export type EventItemActions = 'set-cursor' | 'event' | 'delay' | 'block' | 'del
interface RundownEntryProps {
type: SupportedEvent;
isPast: boolean;
isFirstEvent: boolean;
data: OntimeRundownEntry;
selected: boolean;
hasCursor: boolean;
@@ -32,19 +31,8 @@ interface RundownEntryProps {
}
export default function RundownEntry(props: RundownEntryProps) {
const {
isPast,
data,
selected,
hasCursor,
next,
previousEnd,
previousEventId,
playback,
isRolling,
disableEdit,
isFirstEvent,
} = props;
const { isPast, data, selected, hasCursor, next, previousEnd, previousEventId, playback, isRolling, disableEdit } =
props;
const { emitError } = useEmitLog();
const { addEvent, updateEvent, deleteEvent, swapEvents } = useEventAction();
@@ -112,7 +100,7 @@ export default function RundownEntry(props: RundownEntryProps) {
}
case 'clone': {
const newEvent = cloneEvent(data as OntimeEvent, data.id);
const rundown = ontimeQueryClient.getQueryData<GetRundownCached>(RUNDOWN)?.rundown ?? [];
const rundown = ontimeQueryClient.getQueryData<GetRundownCached>(RUNDOWN)?.rundown ?? []
newEvent.cue = getCueCandidate(rundown, data.id);
addEvent(newEvent);
break;
@@ -188,7 +176,6 @@ export default function RundownEntry(props: RundownEntryProps) {
isRolling={isRolling}
actionHandler={actionHandler}
disableEdit={disableEdit}
isFirstEvent={isFirstEvent}
/>
);
} else if (data.type === SupportedEvent.Block) {
@@ -10,11 +10,11 @@ $skip-opacity: 0.1;
display: grid;
grid-template-areas:
'binder ... ... ...'
'binder pb-actions times actions'
'binder pb-actions title next-ind'
'binder pb-actions estatus estatus'
'binder ... ... ...';
"binder ... ... ..."
"binder pb-actions times actions"
"binder pb-actions title next"
"binder pb-actions estatus estatus"
"binder ... ... ...";
grid-template-columns: $block-binder-width auto 1fr auto;
grid-template-rows: 0.25rem 2.25rem 2.25rem 2.25rem 0.25rem;
@@ -53,18 +53,8 @@ $skip-opacity: 0.1;
outline: 1px solid $block-cursor-color;
}
/* we stop the eventActions from having opacity to fix issue with dropdown drawing order */
&.past:not(.skip) {
.delayNote,
.statusElements,
.eventTitle,
.eventNote,
.eventTimers,
.eventStatus,
.playbackActions,
.binder {
opacity: 0.4;
}
opacity: 0.6;
}
&.skip {
@@ -170,8 +160,8 @@ $skip-opacity: 0.1;
grid-area: estatus;
display: grid;
grid-template-areas:
'notes status'
'progb progb';
"notes status"
"progb progb";
gap: 2px;
grid-template-rows: auto 0.25rem;
align-items: center;
@@ -190,8 +180,9 @@ $skip-opacity: 0.1;
overflow-y: hidden;
}
.nextTag {
grid-area: next-ind;
grid-area: next;
font-size: 1rem;
color: $orange-500;
letter-spacing: 0.03px;
@@ -199,31 +190,6 @@ $skip-opacity: 0.1;
text-align: right;
}
.indicators {
grid-area: next-ind;
display: flex;
justify-content: flex-end;
align-items: center;
gap: 0.5rem;
.indicator {
background-color: transparent;
margin: 0.4rem;
margin-right: 0;
border-radius: 0.7rem;
width: 0.7rem;
height: 0.7rem;
}
.indicator.delay {
background-color: $ontime-delay;
}
.indicator.nextDay,
.indicator.overlap,
.indicator.spacing {
background-color: $gray-600;
}
}
.eventStatus {
grid-area: status;
display: flex;
@@ -232,6 +198,7 @@ $skip-opacity: 0.1;
gap: 0.5rem;
color: var(--status-color-override, $gray-500);
.statusIcon {
width: 1rem;
height: 1rem;
@@ -50,7 +50,6 @@ interface EventBlockProps {
},
) => void;
disableEdit: boolean;
isFirstEvent: boolean;
}
export default function EventBlock(props: EventBlockProps) {
@@ -77,7 +76,6 @@ export default function EventBlock(props: EventBlockProps) {
isRolling,
actionHandler,
disableEdit,
isFirstEvent,
} = props;
const { selectedEventId, setSelectedEventId, clearSelectedEventId } = useEventIdSwapping();
const moveCursorTo = useAppMode((state) => state.setCursor);
@@ -212,7 +210,6 @@ export default function EventBlock(props: EventBlockProps) {
isRolling={isRolling}
actionHandler={actionHandler}
disableEdit={disableEdit}
isFirstEvent={isFirstEvent}
/>
)}
</div>
@@ -11,11 +11,9 @@ import { IoPlaySkipForward } from '@react-icons/all-files/io5/IoPlaySkipForward'
import { IoStop } from '@react-icons/all-files/io5/IoStop';
import { IoTime } from '@react-icons/all-files/io5/IoTime';
import { EndAction, Playback, TimerType } from 'ontime-types';
import { millisToString } from 'ontime-utils';
import TooltipActionBtn from '../../../common/components/buttons/TooltipActionBtn';
import { useAppMode } from '../../../common/stores/appModeStore';
import { millisToDelayString } from '../../../common/utils/dateConfig';
import { tooltipDelayMid } from '../../../ontimeConfig';
import EditableBlockTitle from '../common/EditableBlockTitle';
import { EventItemActions } from '../RundownEntry';
@@ -55,7 +53,6 @@ interface EventBlockInnerProps {
isRolling: boolean;
actionHandler: (action: EventItemActions, payload?: any) => void;
disableEdit: boolean;
isFirstEvent: boolean;
}
const EventBlockInner = (props: EventBlockInnerProps) => {
@@ -79,7 +76,6 @@ const EventBlockInner = (props: EventBlockInnerProps) => {
isRolling,
actionHandler,
disableEdit,
isFirstEvent,
} = props;
const [renderInner, setRenderInner] = useState(false);
@@ -107,19 +103,6 @@ const EventBlockInner = (props: EventBlockInnerProps) => {
playBtnStyles._hover = {};
}
const delayedStart = Math.max(0, timeStart + delay);
const newTime = millisToString(delayedStart);
const delayTime = delay !== 0 ? millisToDelayString(delay) : null;
const overlap = previousEnd - timeStart;
const overlapTime = !isFirstEvent
? overlap > 0
? `Overlapping ${millisToDelayString(overlap)}`
: overlap < 0
? `Spacing ${millisToDelayString(overlap)}`
: null
: null;
return !renderInner ? null : (
<>
<EventBlockTimers
@@ -131,35 +114,10 @@ const EventBlockInner = (props: EventBlockInnerProps) => {
previousEnd={previousEnd}
/>
<EditableBlockTitle title={title} eventId={eventId} placeholder='Event title' className={style.eventTitle} />
{next ? (
{next && (
<Tooltip label='Next event' {...tooltipProps}>
<span className={style.nextTag}>UP NEXT</span>
</Tooltip>
) : (
<span className={style.indicators}>
{delayTime && (
<Tooltip
label={
<div>
{delayTime} <br />
New Time: {newTime}
</div>
}
>
<div className={`${style.indicator} ${style.delay}`} />
</Tooltip>
)}
{overlapTime && (
<Tooltip label={overlapTime}>
<div className={`${style.indicator} ${overlap > 0 ? style.overlap : style.spacing}`} />
</Tooltip>
)}
{timeStart > timeEnd && (
<Tooltip label='Start time is later than end'>
<div className={`${style.indicator} ${style.nextDay}`} />
</Tooltip>
)}
</span>
)}
<EventBlockPlayback
eventId={eventId}
@@ -1,10 +1,11 @@
import { memo } from 'react';
import { memo, useCallback, useState } from 'react';
import { OntimeEvent } from 'ontime-types';
import { calculateDuration, millisToString } from 'ontime-utils';
import TimeInput from '../../../../common/components/input/time-input/TimeInput';
import { useEventAction } from '../../../../common/hooks/useEventAction';
import { millisToDelayString } from '../../../../common/utils/dateConfig';
import { TimeEntryField, validateEntry } from '../../../../common/utils/timesManager';
import style from '../EventBlock.module.scss';
@@ -23,6 +24,8 @@ const EventBlockTimers = (props: EventBlockTimerProps) => {
const { eventId, timeStart, timeEnd, duration, delay, previousEnd } = props;
const { updateEvent } = useEventAction();
const [warning, setWarnings] = useState({ start: '', end: '', duration: '' });
const handleSubmit = (field: TimeActions, value: number) => {
const newEventData: Partial<OntimeEvent> = { id: eventId };
switch (field) {
@@ -46,6 +49,21 @@ const EventBlockTimers = (props: EventBlockTimerProps) => {
updateEvent(newEventData);
};
/**
* @description Validates a time input against its pair
* @param {string} entry - field to validate: timeStart, timeEnd, durationOverride
* @param {number} val - field value
* @return {boolean}
*/
const handleValidation = useCallback(
(field: TimeEntryField, value: number) => {
const valid = validateEntry(field, value, timeStart, timeEnd);
setWarnings((prev) => ({ ...prev, ...valid.warnings }));
return valid.value;
},
[timeEnd, timeStart],
);
const delayedStart = Math.max(0, timeStart + delay);
const newTime = millisToString(delayedStart);
const delayTime = delay !== 0 ? millisToDelayString(delay) : null;
@@ -55,26 +73,32 @@ const EventBlockTimers = (props: EventBlockTimerProps) => {
<TimeInput
name='timeStart'
submitHandler={handleSubmit}
validationHandler={handleValidation}
time={timeStart}
delay={delay}
placeholder='Start'
previousEnd={previousEnd}
warning={warning.start}
/>
<TimeInput
name='timeEnd'
submitHandler={handleSubmit}
validationHandler={handleValidation}
time={timeEnd}
delay={delay}
placeholder='End'
previousEnd={previousEnd}
warning={warning.end}
/>
<TimeInput
name='durationOverride'
submitHandler={handleSubmit}
validationHandler={handleValidation}
time={duration}
delay={0}
placeholder='Duration'
previousEnd={previousEnd}
warning={warning.duration}
/>
{delayTime && (
<div className={style.delayNote}>
@@ -1,11 +1,10 @@
import { ComponentType, useMemo } from 'react';
import { TimeManagerType } from 'common/models/TimeManager.type';
import { Message, OntimeEvent, ProjectData, Settings, SupportedEvent, TimerMessage, ViewSettings } from 'ontime-types';
import { Message, OntimeEvent, ProjectData, SupportedEvent, TimerMessage, ViewSettings } from 'ontime-types';
import { useStore } from 'zustand';
import useProjectData from '../../common/hooks-query/useProjectData';
import useRundown from '../../common/hooks-query/useRundown';
import useSettings from '../../common/hooks-query/useSettings';
import useViewSettings from '../../common/hooks-query/useViewSettings';
import { runtime } from '../../common/stores/runtime';
import { useViewOptionsStore } from '../../common/stores/viewOptions';
@@ -28,7 +27,6 @@ type WithDataProps = {
nextId: string | null;
general: ProjectData;
viewSettings: ViewSettings;
settings: Settings | undefined;
onAir: boolean;
};
@@ -45,7 +43,6 @@ const withData = <P extends WithDataProps>(Component: ComponentType<P>) => {
const { data: rundownData } = useRundown();
const { data: project } = useProjectData();
const { data: viewSettings } = useViewSettings();
const { data: settings } = useSettings();
const publicEvents = useMemo(() => {
if (Array.isArray(rundownData)) {
@@ -107,7 +104,6 @@ const withData = <P extends WithDataProps>(Component: ComponentType<P>) => {
selectedId={selectedId}
publicSelectedId={publicSelectedId}
viewSettings={viewSettings}
settings={settings}
nextId={nextId}
general={project}
onAir={onAir}
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react';
import QRCode from 'react-qr-code';
import { AnimatePresence, motion } from 'framer-motion';
import { Message, OntimeEvent, ProjectData, Settings, SupportedEvent, ViewSettings } from 'ontime-types';
import { Message, OntimeEvent, ProjectData, SupportedEvent, ViewSettings } from 'ontime-types';
import { formatDisplay } from 'ontime-utils';
import { overrideStylesURL } from '../../../common/api/apiConstants';
@@ -11,7 +11,7 @@ import Schedule from '../../../common/components/schedule/Schedule';
import { ScheduleProvider } from '../../../common/components/schedule/ScheduleContext';
import ScheduleNav from '../../../common/components/schedule/ScheduleNav';
import TitleCard from '../../../common/components/title-card/TitleCard';
import { getBackstageOptions } from '../../../common/components/view-params-editor/constants';
import { BACKSTAGE_OPTIONS } from '../../../common/components/view-params-editor/constants';
import ViewParamsEditor from '../../../common/components/view-params-editor/ViewParamsEditor';
import { useRuntimeStylesheet } from '../../../common/hooks/useRuntimeStylesheet';
import { TimeManagerType } from '../../../common/models/TimeManager.type';
@@ -37,12 +37,10 @@ interface BackstageProps {
selectedId: string | null;
general: ProjectData;
viewSettings: ViewSettings;
settings: Settings | undefined;
}
export default function Backstage(props: BackstageProps) {
const { isMirrored, publ, eventNow, eventNext, time, backstageEvents, selectedId, general, viewSettings, settings } =
props;
const { isMirrored, publ, eventNow, eventNext, time, backstageEvents, selectedId, general, viewSettings } = props;
const { shouldRender } = useRuntimeStylesheet(viewSettings?.overrideStyles && overrideStylesURL);
const { getLocalizedString } = useTranslation();
const [blinkClass, setBlinkClass] = useState(false);
@@ -91,12 +89,11 @@ export default function Backstage(props: BackstageProps) {
}
const totalTime = (time.duration ?? 0) + (time.addedTime ?? 0);
const backstageOptions = getBackstageOptions(settings?.timeFormat ?? '24');
return (
<div className={`backstage ${isMirrored ? 'mirror' : ''}`} data-testid='backstage-view'>
<NavigationMenu />
<ViewParamsEditor paramFields={backstageOptions} />
<ViewParamsEditor paramFields={BACKSTAGE_OPTIONS} />
<div className='project-header'>
{general.title}
<div className='clock-container'>
@@ -140,7 +137,7 @@ export default function Backstage(props: BackstageProps) {
{isNegative ? (
<div className='aux-timers__value'>{expectedFinish}</div>
) : (
<SuperscriptTime time={expectedFinish} className='aux-timers__value' />
<SuperscriptTime time={startedAt} className='aux-timers__value' />
)}
</div>
<div className='timer-gap' />
@@ -1,10 +1,10 @@
import { useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Settings, ViewSettings } from 'ontime-types';
import { ViewSettings } from 'ontime-types';
import { overrideStylesURL } from '../../../common/api/apiConstants';
import NavigationMenu from '../../../common/components/navigation-menu/NavigationMenu';
import { getClockOptions } from '../../../common/components/view-params-editor/constants';
import { CLOCK_OPTIONS } from '../../../common/components/view-params-editor/constants';
import ViewParamsEditor from '../../../common/components/view-params-editor/ViewParamsEditor';
import { useRuntimeStylesheet } from '../../../common/hooks/useRuntimeStylesheet';
import { TimeManagerType } from '../../../common/models/TimeManager.type';
@@ -18,7 +18,6 @@ interface ClockProps {
isMirrored: boolean;
time: TimeManagerType;
viewSettings: ViewSettings;
settings: Settings | undefined;
}
const formatOptions = {
@@ -27,7 +26,7 @@ const formatOptions = {
};
export default function Clock(props: ClockProps) {
const { isMirrored, time, viewSettings, settings } = props;
const { isMirrored, time, viewSettings } = props;
const { shouldRender } = useRuntimeStylesheet(viewSettings?.overrideStyles && overrideStylesURL);
const [searchParams] = useSearchParams();
@@ -125,8 +124,6 @@ export default function Clock(props: ClockProps) {
const clock = formatTime(time.clock, formatOptions);
const clean = clock.replace('/:/g', '');
const clockOptions = getClockOptions(settings?.timeFormat ?? '24');
return (
<div
className={`clock-view ${isMirrored ? 'mirror' : ''}`}
@@ -138,7 +135,7 @@ export default function Clock(props: ClockProps) {
data-testid='clock-view'
>
<NavigationMenu />
<ViewParamsEditor paramFields={clockOptions} />
<ViewParamsEditor paramFields={CLOCK_OPTIONS} />
<SuperscriptTime
time={clock}
className='clock'
@@ -1,11 +1,11 @@
import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { OntimeEvent, OntimeRundownEntry, Playback, Settings, SupportedEvent, ViewSettings } from 'ontime-types';
import { OntimeEvent, OntimeRundownEntry, Playback, SupportedEvent, ViewSettings } from 'ontime-types';
import { formatDisplay } from 'ontime-utils';
import { overrideStylesURL } from '../../../common/api/apiConstants';
import NavigationMenu from '../../../common/components/navigation-menu/NavigationMenu';
import { getTimeOption } from '../../../common/components/view-params-editor/constants';
import { TIME_FORMAT_OPTION } from '../../../common/components/view-params-editor/constants';
import ViewParamsEditor from '../../../common/components/view-params-editor/ViewParamsEditor';
import { useRuntimeStylesheet } from '../../../common/hooks/useRuntimeStylesheet';
import { TimeManagerType } from '../../../common/models/TimeManager.type';
@@ -34,11 +34,10 @@ interface CountdownProps {
time: TimeManagerType;
selectedId: string | null;
viewSettings: ViewSettings;
settings: Settings | undefined;
}
export default function Countdown(props: CountdownProps) {
const { isMirrored, backstageEvents, time, selectedId, viewSettings, settings } = props;
const { isMirrored, backstageEvents, time, selectedId, viewSettings } = props;
const { shouldRender } = useRuntimeStylesheet(viewSettings?.overrideStyles && overrideStylesURL);
const [searchParams] = useSearchParams();
const { getLocalizedString } = useTranslation();
@@ -110,12 +109,10 @@ export default function Countdown(props: CountdownProps) {
isSelected || runningMessage === TimerMessage.waiting,
);
const timeOption = getTimeOption(settings?.timeFormat ?? '24');
return (
<div className={`countdown ${isMirrored ? 'mirror' : ''}`} data-testid='countdown-view'>
<NavigationMenu />
<ViewParamsEditor paramFields={[timeOption]} />
<ViewParamsEditor paramFields={[TIME_FORMAT_OPTION]} />
{follow === null ? (
<CountdownSelect events={backstageEvents} />
) : (
@@ -126,11 +126,10 @@ export default function MinimalTimer(props: MinimalTimerProps) {
const hideEndMessage = searchParams.get('hideendmessage');
userOptions.hideEndMessage = isStringBoolean(hideEndMessage);
const timerIsTimeOfDay = time.timerType === TimerType.Clock;
const showOverlay = pres.text !== '' && pres.visible;
const isPlaying = time.playback !== Playback.Pause;
const isNegative = (time.current ?? 0) < 0 && !timerIsTimeOfDay && time.timerType !== TimerType.CountUp;
const isNegative =
(time.current ?? 0) < 0 && time.timerType !== TimerType.Clock && time.timerType !== TimerType.CountUp;
const showEndMessage = (time.current ?? 0) < 0 && viewSettings.endMessage && !hideEndMessage;
const finished = time.playback === Playback.Play && (time.current ?? 0) < 0 && time.startedAt;
const showFinished = finished && !userOptions?.hideOvertime && (time.timerType !== TimerType.Clock || showEndMessage);
@@ -141,9 +140,13 @@ export default function MinimalTimer(props: MinimalTimerProps) {
const showBlinking = pres.timerBlink;
const showBlackout = pres.timerBlackout;
let timerColor = viewSettings.normalColor;
if (!timerIsTimeOfDay && showProgress && showDanger) timerColor = viewSettings.dangerColor;
if (!timerIsTimeOfDay && showProgress && showWarning) timerColor = viewSettings.warningColor;
const timerColor = userOptions.textColour
? userOptions.textColour
: showProgress && showDanger
? viewSettings.dangerColor
: showProgress && showWarning
? viewSettings.warningColor
: viewSettings.normalColor;
const stageTimer = getTimerByType(time);
let display = formatTimerDisplay(stageTimer);
@@ -1,7 +1,7 @@
import { useEffect } from 'react';
import QRCode from 'react-qr-code';
import { AnimatePresence, motion } from 'framer-motion';
import { Message, OntimeEvent, ProjectData, Settings, ViewSettings } from 'ontime-types';
import { Message, OntimeEvent, ProjectData, ViewSettings } from 'ontime-types';
import { overrideStylesURL } from '../../../common/api/apiConstants';
import NavigationMenu from '../../../common/components/navigation-menu/NavigationMenu';
@@ -9,7 +9,7 @@ import Schedule from '../../../common/components/schedule/Schedule';
import { ScheduleProvider } from '../../../common/components/schedule/ScheduleContext';
import ScheduleNav from '../../../common/components/schedule/ScheduleNav';
import TitleCard from '../../../common/components/title-card/TitleCard';
import { getPublicOptions } from '../../../common/components/view-params-editor/constants';
import { PUBLIC_OPTIONS } from '../../../common/components/view-params-editor/constants';
import ViewParamsEditor from '../../../common/components/view-params-editor/ViewParamsEditor';
import { useRuntimeStylesheet } from '../../../common/hooks/useRuntimeStylesheet';
import { TimeManagerType } from '../../../common/models/TimeManager.type';
@@ -35,22 +35,11 @@ interface BackstageProps {
publicSelectedId: string | null;
general: ProjectData;
viewSettings: ViewSettings;
settings: Settings | undefined;
}
export default function Public(props: BackstageProps) {
const {
isMirrored,
publ,
publicEventNow,
publicEventNext,
time,
events,
publicSelectedId,
general,
viewSettings,
settings,
} = props;
const { isMirrored, publ, publicEventNow, publicEventNext, time, events, publicSelectedId, general, viewSettings } =
props;
const { shouldRender } = useRuntimeStylesheet(viewSettings?.overrideStyles && overrideStylesURL);
const { getLocalizedString } = useTranslation();
@@ -67,12 +56,10 @@ export default function Public(props: BackstageProps) {
const clock = formatTime(time.clock, formatOptions);
const qrSize = Math.max(window.innerWidth / 15, 128);
const publicOptions = getPublicOptions(settings?.timeFormat ?? '24');
return (
<div className={`public-screen ${isMirrored ? 'mirror' : ''}`} data-testid='public-view'>
<NavigationMenu />
<ViewParamsEditor paramFields={publicOptions} />
<ViewParamsEditor paramFields={PUBLIC_OPTIONS} />
<div className='project-header'>
{general.title}
<div className='clock-container'>
@@ -13,7 +13,7 @@ $half-hours: min(1.5vh, 10px);
$size-min: min(2.5vh, 18px);
$half-min: min(1.25vh, 9px);
$red-active: #c53030;
$red-idle: #300000;
$red-idle: #000000;
$cyan-active: #0ff;
$cyan-idle: #0aa;
@@ -109,8 +109,7 @@ $cyan-idle: #0aa;
line-height: 1em;
&--overtime {
color: var(--studio-active, $red-active);
filter: brightness(0.9);
color: darken($red-active, 10%);
}
}
@@ -134,7 +133,7 @@ $cyan-idle: #0aa;
color: var(--studio-active, $red-active);
&--idle {
color: var(--studio-idle, $red-idle);
color: var(--studio-idle, $red-active);
}
}
@@ -1,12 +1,12 @@
import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import type { OntimeEvent, OntimeRundown, Settings, ViewSettings } from 'ontime-types';
import type { OntimeEvent, OntimeRundown, ViewSettings } from 'ontime-types';
import { SupportedEvent } from 'ontime-types';
import { formatDisplay } from 'ontime-utils';
import { overrideStylesURL } from '../../../common/api/apiConstants';
import NavigationMenu from '../../../common/components/navigation-menu/NavigationMenu';
import { getStudioClockOptions } from '../../../common/components/view-params-editor/constants';
import { STUDIO_CLOCK_OPTIONS } from '../../../common/components/view-params-editor/constants';
import ViewParamsEditor from '../../../common/components/view-params-editor/ViewParamsEditor';
import useFitText from '../../../common/hooks/useFitText';
import { useRuntimeStylesheet } from '../../../common/hooks/useRuntimeStylesheet';
@@ -32,11 +32,10 @@ interface StudioClockProps {
nextId: string | null;
onAir: boolean;
viewSettings: ViewSettings;
settings: Settings | undefined;
}
export default function StudioClock(props: StudioClockProps) {
const { isMirrored, eventNext, time, backstageEvents, selectedId, nextId, onAir, viewSettings, settings } = props;
const { isMirrored, eventNext, time, backstageEvents, selectedId, nextId, onAir, viewSettings } = props;
// deferring rendering seems to affect styling (font and useFitText)
useRuntimeStylesheet(viewSettings?.overrideStyles && overrideStylesURL);
@@ -76,12 +75,10 @@ export default function StudioClock(props: StudioClockProps) {
const secondsNow = secondsInMillis(time.clock);
const isNegative = (time.current ?? 0) < 0;
const studioClockOptions = getStudioClockOptions(settings?.timeFormat ?? '24');
return (
<div className={`studio-clock ${isMirrored ? 'mirror' : ''}`} data-testid='studio-view'>
<NavigationMenu />
<ViewParamsEditor paramFields={studioClockOptions} />
<ViewParamsEditor paramFields={STUDIO_CLOCK_OPTIONS} />
<div className='clock-container'>
<div className={`studio-timer ${showSeconds ? 'studio-timer--with-seconds' : ''}`}>{clock}</div>
<div
@@ -1,13 +1,13 @@
import { useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { AnimatePresence, motion } from 'framer-motion';
import { Message, OntimeEvent, Playback, Settings, TimerMessage, TimerType, ViewSettings } from 'ontime-types';
import { Message, OntimeEvent, Playback, TimerMessage, TimerType, ViewSettings } from 'ontime-types';
import { overrideStylesURL } from '../../../common/api/apiConstants';
import MultiPartProgressBar from '../../../common/components/multi-part-progress-bar/MultiPartProgressBar';
import NavigationMenu from '../../../common/components/navigation-menu/NavigationMenu';
import TitleCard from '../../../common/components/title-card/TitleCard';
import { getTimerOptions } from '../../../common/components/view-params-editor/constants';
import { TIMER_OPTIONS } from '../../../common/components/view-params-editor/constants';
import ViewParamsEditor from '../../../common/components/view-params-editor/ViewParamsEditor';
import { useRuntimeStylesheet } from '../../../common/hooks/useRuntimeStylesheet';
import { TimeManagerType } from '../../../common/models/TimeManager.type';
@@ -48,11 +48,10 @@ interface TimerProps {
eventNext: OntimeEvent | null;
time: TimeManagerType;
viewSettings: ViewSettings;
settings: Settings | undefined;
}
export default function Timer(props: TimerProps) {
const { isMirrored, pres, eventNow, eventNext, time, viewSettings, external, settings } = props;
const { isMirrored, pres, eventNow, eventNext, time, viewSettings, external } = props;
const { shouldRender } = useRuntimeStylesheet(viewSettings?.overrideStyles && overrideStylesURL);
const { getLocalizedString } = useTranslation();
const [searchParams] = useSearchParams();
@@ -90,9 +89,8 @@ export default function Timer(props: TimerProps) {
const showOverlay = pres.text !== '' && pres.visible;
const isPlaying = time.playback !== Playback.Pause;
const timerIsTimeOfDay = time.timerType === TimerType.Clock;
const isNegative = (time.current ?? 0) < 0 && !timerIsTimeOfDay && time.timerType !== TimerType.CountUp;
const isNegative =
(time.current ?? 0) < 0 && time.timerType !== TimerType.Clock && time.timerType !== TimerType.CountUp;
const finished = time.playback === Playback.Play && (time.current ?? 0) < 0 && time.startedAt;
const totalTime = (time.duration ?? 0) + (time.addedTime ?? 0);
@@ -106,9 +104,12 @@ export default function Timer(props: TimerProps) {
const showClock = time.timerType !== TimerType.Clock;
const showExternal = external.visible && external.text;
let timerColor = viewSettings.normalColor;
if (!timerIsTimeOfDay && showProgress && showDanger) timerColor = viewSettings.dangerColor;
if (!timerIsTimeOfDay && showProgress && showWarning) timerColor = viewSettings.warningColor;
const timerColor =
showProgress && showDanger
? viewSettings.dangerColor
: showProgress && showWarning
? viewSettings.warningColor
: viewSettings.normalColor;
const stageTimer = getTimerByType(time);
let display = formatTimerDisplay(stageTimer);
@@ -127,12 +128,10 @@ export default function Timer(props: TimerProps) {
const timerContainerClasses = `timer-container ${showBlinking ? (showOverlay ? '' : 'blink') : ''}`;
const timerClasses = `timer ${!isPlaying ? 'timer--paused' : ''} ${showFinished ? 'timer--finished' : ''}`;
const timerOptions = getTimerOptions(settings?.timeFormat ?? '24');
return (
<div className={showFinished ? `${baseClasses} stage-timer--finished` : baseClasses} data-testid='timer-view'>
<NavigationMenu />
<ViewParamsEditor paramFields={timerOptions} />
<ViewParamsEditor paramFields={TIMER_OPTIONS} />
{!userOptions.hideMessage && (
<div className={showOverlay ? 'message-overlay message-overlay--active' : 'message-overlay'}>
<div className={`message ${showBlinking ? 'blink' : ''}`}>{pres.text}</div>
@@ -171,7 +170,7 @@ export default function Timer(props: TimerProps) {
{!userOptions.hideProgress && (
<MultiPartProgressBar
className={isPlaying ? 'progress-container' : 'progress-container progress-container--paused'}
now={timerIsTimeOfDay ? null : time.current}
now={time.current}
complete={totalTime}
normalColor={viewSettings.normalColor}
warning={viewSettings.warningThreshold}
+1 -26
View File
@@ -12,38 +12,13 @@ import './index.scss';
const container = document.getElementById('root');
const root = createRoot(container as Element);
// https://docs.sentry.io/platforms/javascript/configuration/filtering/#decluttering-sentry
const sentryRecommendedIgnore = [
// Random plugins/extensions
'top.GLOBALS',
// See: http://blog.errorception.com/2012/03/tale-of-unfindable-js-error.html
'originalCreateNotification',
'canvas.contentDocument',
'MyApp_RemoveAllHighlights',
'http://tt.epicplay.com',
"Can't find variable: ZiteReader",
'jigsaw is not defined',
'ComboSearch is not defined',
'http://loading.retry.widdit.com/',
'atomicFindClose',
// Facebook borked
'fb_xd_fragment',
// ISP "optimizing" proxy - `Cache-Control: no-transform` seems to
// reduce this. (thanks @acdha)
// See http://stackoverflow.com/questions/4113268
'bmi_SafeAddOnload',
'EBCallBackMessageReceived',
// See http://toolbar.conduit.com/Developer/HtmlAndGadget/Methods/JSInjection.aspx
'conduitPage',
];
Sentry.init({
dsn: 'https://5e4d2c4b57ab409cb98d4c08b2014755@o4504288369836032.ingest.sentry.io/4504288371343360',
integrations: [new BrowserTracing()],
tracesSampleRate: 0.3,
release: ONTIME_VERSION,
enabled: import.meta.env.PROD,
ignoreErrors: [...sentryRecommendedIgnore, 'Unable to preload CSS', 'Failed to fetch dynamically imported module'],
ignoreErrors: ['top.GLOBALS', 'Unable to preload CSS', 'Failed to fetch dynamically imported module'],
denyUrls: [/extensions\//i, /^chrome:\/\//i, /^chrome-extension:\/\//i],
});
@@ -6,7 +6,6 @@ import { langDe } from './languages/de';
import { langEn } from './languages/en';
import { langEs } from './languages/es';
import { langFr } from './languages/fr';
import { langIt } from './languages/it';
import { langNo } from './languages/no';
import { langPt } from './languages/pt';
import { langSv } from './languages/sv';
@@ -15,7 +14,6 @@ const translationsList = {
en: langEn,
es: langEs,
fr: langFr,
it: langIt,
de: langDe,
no: langNo,
pt: langPt,
@@ -1,19 +0,0 @@
import { TranslationObject } from './en';
export const langIt: TranslationObject = {
'common.end_time': 'Ora di Fine',
'common.expected_finish': 'Fine Prevista',
'common.now': 'Adesso',
'common.next': 'Prossimo',
'common.public_message': 'Messaggio pubblico',
'common.start_time': 'Ora di Inizio',
'common.stage_timer': 'Orologio Palco',
'common.started_at': 'Iniziato Alle',
'common.time_now': 'Ora attuale',
'countdown.ended': 'Evento finito alle',
'countdown.running': 'Evento in corso',
'countdown.select_event': 'Seleziona un evento da seguire',
'countdown.to_start': 'Tempo alla partenza',
'countdown.waiting': 'In attesa dell\'inizio dell\'evento',
'countdown.overtime': 'in ritardo',
};
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "ontime",
"version": "2.28.12",
"version": "2.16.2",
"author": "Carlos Valente",
"description": "Time keeping for live events",
"repository": "https://github.com/cpvalente/ontime",
+1 -3
View File
@@ -2,7 +2,7 @@
"name": "ontime-server",
"type": "module",
"main": "src/index.ts",
"version": "2.28.12",
"version": "2.16.2",
"exports": "./src/index.js",
"dependencies": {
"@googleapis/sheets": "^5.0.5",
@@ -13,7 +13,6 @@
"express-session": "^1.17.3",
"express-static-gzip": "^2.1.7",
"express-validator": "^6.14.2",
"got": "^14.0.0",
"google-auth-library": "^9.2.0",
"lowdb": "^5.0.5",
"multer": "^1.4.5-lts.1",
@@ -55,7 +54,6 @@
"build:electron": "pnpm prebuild && esbuild src/app.ts --log-level=error --platform=node --format=cjs --bundle --minify --outfile=dist/index.cjs",
"build:local": "pnpm prebuild && esbuild src/index.ts --log-level=error --platform=node --format=cjs --bundle --minify --outfile=dist/index.cjs",
"build:docker": "pnpm prebuild && esbuild src/index.ts --log-level=error --platform=node --format=cjs --minify --bundle --outfile=dist/docker.cjs",
"build:localdocker": "NODE_ENV=local pnpm prebuild && esbuild src/index.ts --log-level=error --platform=node --format=cjs --minify --bundle --outfile=dist/docker.cjs",
"build:debug": "pnpm prebuild && esbuild src/app.ts --platform=node --format=cjs --bundle --outfile=dist/index.cjs",
"lint": "eslint . --quiet",
"lint-staged": "eslint",
+3 -27
View File
@@ -3,7 +3,7 @@ import { LogOrigin, OSCSettings } from 'ontime-types';
import { Server } from 'node-osc';
import { IAdapter } from './IAdapter.js';
import { dispatchFromAdapter, type ChangeOptions } from '../controllers/integrationController.js';
import { dispatchFromAdapter } from '../controllers/integrationController.js';
import { logger } from '../classes/Logger.js';
export class OscServer implements IAdapter {
@@ -36,36 +36,12 @@ export class OscServer implements IAdapter {
return;
}
let transformedPayload: unknown = args;
// we need to transform the params for the change endpoint
// OSC: ontime/change/{eventID}/{propertyName} value
if (path === 'change') {
if (params.length < 2) {
logger.error(LogOrigin.Rx, 'OSC IN: No params provided for change');
return;
}
if (args === undefined) {
logger.error(LogOrigin.Rx, 'OSC IN: No valid payload provided for change');
return;
}
const eventId = params[0];
const property = params[1];
const value: string | number | boolean = args as string | number | boolean;
transformedPayload = {
eventId,
property,
value,
} satisfies ChangeOptions;
}
try {
const reply = dispatchFromAdapter(
path,
{
payload: transformedPayload,
payload: args,
params,
},
'osc',
);
+1 -2
View File
@@ -17,7 +17,6 @@
import { LogOrigin } from 'ontime-types';
import { WebSocket, WebSocketServer } from 'ws';
import type { Server } from 'http';
import getRandomName from '../utils/getRandomName.js';
import { IAdapter } from './IAdapter.js';
@@ -44,7 +43,7 @@ export class SocketServer implements IAdapter {
this.wss = null;
}
init(server: Server) {
init(server) {
this.wss = new WebSocketServer({ path: '/ws', server });
this.wss.on('connection', (ws) => {
+14 -37
View File
@@ -1,21 +1,14 @@
import { HttpSettings, LogOrigin, OSCSettings } from 'ontime-types';
import { LogOrigin, OSCSettings } from 'ontime-types';
import 'dotenv/config';
import express from 'express';
import expressStaticGzip from 'express-static-gzip';
import http, { type Server } from 'http';
import http from 'http';
import cors from 'cors';
// import utils
import { join, resolve } from 'path';
import {
currentDirectory,
environment,
isProduction,
resolveExternalsDirectory,
resolveStylesDirectory,
resolvedPath,
} from './setup.js';
import { currentDirectory, environment, externalsStartDirectory, isProduction, resolvedPath } from './setup.js';
import { ONTIME_VERSION } from './ONTIME_VERSION.js';
// Import Routes
@@ -36,13 +29,11 @@ import { eventLoader } from './classes/event-loader/EventLoader.js';
import { integrationService } from './services/integration-service/IntegrationService.js';
import { logger } from './classes/Logger.js';
import { oscIntegration } from './services/integration-service/OscIntegration.js';
import { httpIntegration } from './services/integration-service/HttpIntegration.js';
import { populateStyles } from './modules/loadStyles.js';
import { eventStore, getInitialPayload } from './stores/EventStore.js';
import { PlaybackService } from './services/PlaybackService.js';
import { RestorePoint, restoreService } from './services/RestoreService.js';
import { messageService } from './services/message-service/MessageService.js';
import { populateDemo } from './modules/loadDemo.js';
console.log(`Starting Ontime version ${ONTIME_VERSION}`);
@@ -72,11 +63,7 @@ app.use('/ontime', ontimeRouter);
app.use('/playback', playbackRouter);
// serve static - css
app.use('/external/styles', express.static(resolveStylesDirectory));
app.use('/external/', express.static(resolveExternalsDirectory));
app.use('/external', (req, res) => {
res.status(404).send(`${req.originalUrl} not found`);
});
app.use('/external', express.static(externalsStartDirectory));
// serve static - react, in dev/test mode we fetch the React app from module
const reactAppPath = join(currentDirectory, resolvedPath());
@@ -120,8 +107,8 @@ enum OntimeStartOrder {
}
let step = OntimeStartOrder.InitAssets;
let expressServer: Server | null = null;
let oscServer: OscServer | null = null;
let expressServer = null;
let oscServer = null;
const checkStart = (currentState: OntimeStartOrder) => {
if (step !== currentState) {
@@ -138,7 +125,6 @@ export const initAssets = async () => {
checkStart(OntimeStartOrder.InitAssets);
await dbLoadingProcess;
populateStyles();
populateDemo();
};
/**
@@ -179,6 +165,7 @@ export const startServer = async () => {
};
/**
* @description starts OSC server
* @description starts OSC server
* @param overrideConfig
* @return {Promise<void>}
@@ -207,30 +194,20 @@ export const startOSCServer = async (overrideConfig = null) => {
/**
* starts integrations
*/
export const startIntegrations = async (config?: { osc: OSCSettings; http: HttpSettings }) => {
export const startIntegrations = async (config?: { osc: OSCSettings }) => {
checkStart(OntimeStartOrder.InitIO);
const { osc, http } = config ?? DataProvider.getData();
const { osc } = config ?? DataProvider.getData();
if (!osc) {
return 'OSC Invalid configuration';
} else {
const { success, message } = oscIntegration.init(osc);
logger.info(LogOrigin.Tx, message);
if (success) {
integrationService.register(oscIntegration);
}
}
if (!http) {
return 'HTTP Invalid configuration';
} else {
const { success, message } = httpIntegration.init(http);
logger.info(LogOrigin.Tx, message);
if (success) {
integrationService.register(httpIntegration);
}
const { success, message } = oscIntegration.init(osc);
logger.info(LogOrigin.Tx, message);
if (success) {
integrationService.register(oscIntegration);
}
};
@@ -11,6 +11,7 @@ import {
UserFields,
Alias,
Settings,
GoogleSheet,
} from 'ontime-types';
import { data, db } from '../../modules/loadDb.js';
@@ -58,12 +59,17 @@ export class DataProvider {
await this.persist();
}
static getOsc() {
return data.osc;
static getGoogleSheet() {
return data.googleSheet;
}
static getHttp() {
return data.http;
static async setGoogleSheet(newData: GoogleSheet) {
data.googleSheet = { ...newData };
await this.persist();
}
static getOsc() {
return data.osc;
}
static getAliases() {
@@ -98,11 +104,6 @@ export class DataProvider {
await this.persist();
}
static async setHttp(newData) {
data.http = { ...newData };
await this.persist();
}
static getRundown() {
return [...data.rundown];
}
@@ -6,12 +6,13 @@ import { DatabaseModel } from 'ontime-types';
* @param {object} newData
*/
export function safeMerge(existing: DatabaseModel, newData: Partial<DatabaseModel>) {
const { rundown, project, settings, viewSettings, osc, aliases, userFields } = newData || {};
const { rundown, project, settings, googleSheet, viewSettings, osc, aliases, userFields } = newData || {};
return {
...existing,
rundown: rundown ?? existing.rundown,
project: { ...existing.project, ...project },
settings: { ...existing.settings, ...settings },
googleSheet: { ...existing.googleSheet, ...googleSheet },
viewSettings: { ...existing.viewSettings, ...viewSettings },
aliases: aliases ?? existing.aliases,
userFields: {
@@ -1,4 +1,4 @@
import { Alias, DatabaseModel, OntimeRundown, Settings } from 'ontime-types';
import { Alias, DatabaseModel, GoogleSheet, OntimeRundown, Settings } from 'ontime-types';
import { safeMerge } from '../DataProvider.utils.js';
describe('safeMerge', () => {
@@ -21,6 +21,10 @@ describe('safeMerge', () => {
timeFormat: '24',
language: 'en',
},
googleSheet: {
worksheet: '1',
id: '2',
},
viewSettings: {
overrideStyles: false,
endMessage: 'existing endMessage',
@@ -97,6 +101,21 @@ describe('safeMerge', () => {
language: 'pt',
});
});
it('merges the google sheet key', () => {
const newData = {
googleSheet: {
id: '4',
worksheet: '5',
} as GoogleSheet,
};
const mergedData = safeMerge(existing, newData);
expect(mergedData.googleSheet).toEqual({
id: '4',
worksheet: '5',
});
});
it('merges the osc key', () => {
const newData = {
osc: {
-4
View File
@@ -8,9 +8,5 @@ export const config = {
directory: 'styles',
filename: 'override.css',
},
demo: {
directory: 'demo',
filename: ['app.js', 'index.html', 'styles.css'],
},
restoreFile: 'ontime.restore',
};
@@ -1,9 +1,8 @@
import { LogOrigin, OntimeEvent } from 'ontime-types';
import { EventLoader } from '../classes/event-loader/EventLoader.js';
import { editEvent } from '../services/rundown-service/RundownService.js';
import { coerceString, coerceNumber, coerceBoolean, coerceColour } from '../utils/coerceType.js';
import { coerceString, coerceNumber, coerceBoolean } from '../utils/coerceType.js';
import { logger } from '../classes/Logger.js';
import { isKeyOfType, isOntimeEvent } from 'ontime-types/src/utils/guards.js';
const whitelistedPayload = {
title: coerceString,
@@ -17,8 +16,7 @@ const whitelistedPayload = {
isPublic: coerceBoolean,
skip: coerceBoolean,
colour: coerceColour,
colour: coerceString,
user0: coerceString,
user1: coerceString,
user2: coerceString,
@@ -31,12 +29,12 @@ const whitelistedPayload = {
user9: coerceString,
};
export function parse(property: string, value: unknown) {
if (!isKeyOfType(property, whitelistedPayload)) {
throw new Error(`Property ${property} not permitted`);
export function parse(field: string, value: unknown) {
if (!Object.hasOwn(whitelistedPayload, field)) {
throw new Error(`Field ${field} not permitted`);
}
const parserFn = whitelistedPayload[property];
return { parsedProperty: property, parsedPayload: parserFn(value) };
const parserFn = whitelistedPayload[field];
return parserFn(value);
}
/**
@@ -51,10 +49,8 @@ export function updateEvent(
newValue: OntimeEvent[typeof propertyName],
) {
const event = EventLoader.getEventWithId(eventId);
if (event) {
if (!isOntimeEvent(event)) {
throw new Error(`Can only update events`);
}
const propertiesToUpdate = { [propertyName]: newValue };
// Handles the special case for duration
@@ -1,25 +1,25 @@
import { OntimeEvent } from 'ontime-types';
import { messageService } from '../services/message-service/MessageService.js';
import { PlaybackService } from '../services/PlaybackService.js';
import { eventStore } from '../stores/EventStore.js';
import { parse, updateEvent } from './integrationController.config.js';
export type ChangeOptions = {
eventId: string;
property: string;
value: unknown;
};
import { isKeyOfType } from 'ontime-types/src/utils/guards.js';
import { event } from '../models/eventsDefinition.js';
//TODO: re-throwing the error does not add any extra information or value
export function dispatchFromAdapter(
type: string,
args: {
payload: unknown;
params?: Array<string>;
},
_source?: 'osc' | 'ws',
) {
const payload = args.payload;
const typeComponents = type.toLowerCase().split('/');
const mainType = typeComponents[0];
const params = args.params || [];
switch (mainType) {
case 'test-ontime': {
@@ -139,10 +139,11 @@ export function dispatchFromAdapter(
throw new Error(`Event index not recognised or out of range ${eventIndex}`);
}
// Indexes in frontend are 1 based
const success = PlaybackService.startByIndex(eventIndex - 1);
if (!success) {
throw new Error(`Event index not recognised or out of range ${eventIndex}`);
try {
// Indexes in frontend are 1 based
PlaybackService.startByIndex(eventIndex - 1);
} catch (error) {
throw new Error(`Error loading event:: ${error}`);
}
break;
}
@@ -193,8 +194,11 @@ export function dispatchFromAdapter(
if (isNaN(time)) {
throw new Error(`Time not recognised ${payload}`);
}
PlaybackService.addTime(time);
try {
PlaybackService.addTime(time);
} catch (error) {
throw new Error(`Could not add time: ${error}`);
}
break;
}
//deprecated
@@ -204,7 +208,11 @@ export function dispatchFromAdapter(
throw new Error(`Delay time not recognised ${payload}`);
}
PlaybackService.setDelay(delayTime);
try {
PlaybackService.setDelay(delayTime);
} catch (error) {
throw new Error(`Could not add delay: ${error}`);
}
break;
}
case 'gotoindex':
@@ -214,10 +222,11 @@ export function dispatchFromAdapter(
throw new Error(`Event index not recognised or out of range ${eventIndex}`);
}
// Indexes in frontend are 1 based
const success = PlaybackService.loadByIndex(eventIndex - 1);
if (!success) {
throw new Error(`Event index not recognised or out of range ${eventIndex}`);
try {
// Indexes in frontend are 1 based
PlaybackService.loadByIndex(eventIndex - 1);
} catch (error) {
throw new Error(`Event index not recognised or out of range ${error}`);
}
break;
}
@@ -227,9 +236,10 @@ export function dispatchFromAdapter(
throw new Error(`Event ID not recognised: ${payload}`);
}
const success = PlaybackService.loadById(payload.toString().toLowerCase());
if (!success) {
throw new Error(`Event ID not found: ${payload}`);
try {
PlaybackService.loadById(payload.toString().toLowerCase());
} catch (error) {
throw new Error(`OSC IN: error calling goto ${error}`);
}
break;
}
@@ -239,9 +249,10 @@ export function dispatchFromAdapter(
throw new Error(`Event cue not recognised: ${payload}`);
}
const success = PlaybackService.loadByCue(payload);
if (!success) {
throw new Error(`Event cue not found: ${payload}`);
try {
PlaybackService.loadByCue(payload);
} catch (error) {
throw new Error(`OSC IN: error calling goto ${error}`);
}
break;
}
@@ -256,11 +267,21 @@ export function dispatchFromAdapter(
return { topic: 'timer', payload: timer };
}
// WS: {type: 'change', payload: { eventId, property, value } }
// ontime/change/{eventID}/{propertyName}
case 'change': {
const { eventId, property, value } = payload as ChangeOptions;
const { parsedPayload, parsedProperty } = parse(property, value);
return updateEvent(eventId, parsedProperty, parsedPayload);
if (params.length < 2) {
throw new Error('Too few parameters, 3 expected');
}
if (payload === undefined) {
throw new Error('No payload found');
}
const eventID = params[0];
const propertyName = params[1] as keyof OntimeEvent;
if (!isKeyOfType(propertyName, event)) {
throw new Error(`Cannot update unknown event property ${propertyName}`);
}
const parsedPayload = parse(propertyName, payload);
return updateEvent(eventID, propertyName, parsedPayload);
}
default: {
+77 -139
View File
@@ -1,5 +1,4 @@
import { LogOrigin } from 'ontime-types';
import type { Alias, DatabaseModel, GetInfo, HttpSettings, ProjectData } from 'ontime-types';
import { Alias, DatabaseModel, GetInfo, LogOrigin, ProjectData } from 'ontime-types';
import { RequestHandler, Request, Response } from 'express';
import fs from 'fs';
@@ -10,17 +9,15 @@ import { DataProvider } from '../classes/data-provider/DataProvider.js';
import { failEmptyObjects, failIsNotArray } from '../utils/routerUtils.js';
import { PlaybackService } from '../services/PlaybackService.js';
import { eventStore } from '../stores/EventStore.js';
import { isDocker, resolveDbPath, resolveStylesPath } from '../setup.js';
import { isDocker, pathToStartStyles, resolveDbPath } from '../setup.js';
import { oscIntegration } from '../services/integration-service/OscIntegration.js';
import { httpIntegration } from '../services/integration-service/HttpIntegration.js';
import { logger } from '../classes/Logger.js';
import { deleteAllEvents, notifyChanges } from '../services/rundown-service/RundownService.js';
import { deepmerge } from 'ontime-utils';
import { runtimeCacheStore } from '../stores/cachingStore.js';
import { delayedRundownCacheKey } from '../services/rundown-service/delayedRundown.utils.js';
import { integrationService } from '../services/integration-service/IntegrationService.js';
import { sheet } from '../utils/sheetsAuth.js';
import { Sheet } from '../utils/sheetsAuth.js';
// Create controller for GET request to '/ontime/poll'
// Returns data for current state
@@ -119,7 +116,7 @@ export const getInfo = async (req: Request, res: Response<GetInfo>) => {
// get nif and inject localhost
const ni = getNetworkInterfaces();
ni.unshift({ name: 'localhost', address: '127.0.0.1' });
const cssOverride = resolveStylesPath;
const cssOverride = pathToStartStyles;
// send object with network information
res.status(200).send({
@@ -288,42 +285,15 @@ export const getOSC = async (req, res) => {
res.status(200).send(osc);
};
// Create controller for POST request to '/ontime/osc'
// Returns ACK message
export const postOSC = async (req, res) => {
if (failEmptyObjects(req.body, res)) {
return;
}
try {
const oscSettings = req.body;
await DataProvider.setOsc(oscSettings);
integrationService.unregister(oscIntegration);
// TODO: this update could be more granular, checking that relevant data was changed
const { success, message } = oscIntegration.init(oscSettings);
logger.info(LogOrigin.Tx, message);
if (success) {
integrationService.register(oscIntegration);
}
res.send(oscSettings).status(200);
} catch (error) {
res.status(400).send({ message: error.toString() });
}
};
export const postOscSubscriptions = async (req, res) => {
if (failEmptyObjects(req.body, res)) {
return;
}
try {
const subscriptions = req.body;
const oscSubscriptions = req.body;
const oscSettings = DataProvider.getOsc();
oscSettings.subscriptions = subscriptions;
oscSettings.subscriptions = oscSubscriptions;
await DataProvider.setOsc(oscSettings);
// TODO: this update could be more granular, checking that relevant data was changed
@@ -336,33 +306,22 @@ export const postOscSubscriptions = async (req, res) => {
}
};
// Create controller for GET request to '/ontime/http'
export const getHTTP = async (_req, res: Response<HttpSettings>) => {
const http = DataProvider.getHttp();
res.status(200).send(http);
};
// Create controller for POST request to '/ontime/http'
export const postHTTP = async (req, res) => {
// Create controller for POST request to '/ontime/osc'
// Returns ACK message
export const postOSC = async (req, res) => {
if (failEmptyObjects(req.body, res)) {
return;
}
try {
const httpSettings = req.body;
await DataProvider.setHttp(httpSettings);
integrationService.unregister(httpIntegration);
const oscSettings = req.body;
await DataProvider.setOsc(oscSettings);
// TODO: this update could be more granular, checking that relevant data was changed
const { success, message } = httpIntegration.init(httpSettings);
const { message } = oscIntegration.init(oscSettings);
logger.info(LogOrigin.Tx, message);
if (success) {
integrationService.register(httpIntegration);
}
res.send(httpSettings).status(200);
res.send(oscSettings).status(200);
} catch (error) {
res.status(400).send({ message: error.toString() });
}
@@ -458,19 +417,45 @@ export const postNew: RequestHandler = async (req, res) => {
}
};
//SHEET Functions
/**
* @description SETP-1 POST Client Secrect
* downloads and parses an sheet
* @returns parsed result
*/
export async function uploadSheetClientFile(req, res) {
export async function previewSheet(req, res) {
try {
const data = await Sheet.pull();
res.status(200).send(data);
} catch (error) {
res.status(500).send({ message: error.toString() });
}
}
/**
* downloads and parses an sheet
* @returns parsed result
*/
export async function pushSheet(req, res) {
try {
await Sheet.push();
res.status(200).send('ok');
} catch (error) {
res.status(500).send({ message: error.toString() });
}
}
/**
* uploads Client secrets file
* @returns parsed result
*/
export async function uploadGoogleSheetClientFile(req, res) {
if (!req.file.path) {
res.status(400).send({ message: 'File not found' });
return;
}
try {
const client = JSON.parse(fs.readFileSync(req.file.path as string, 'utf-8'));
await sheet.saveClientSecrets(client);
await Sheet.saveClientSecrets(client);
res.status(200).send('OK');
} catch (error) {
res.status(500).send({ message: error.toString() });
@@ -481,98 +466,51 @@ export async function uploadSheetClientFile(req, res) {
}
/**
* @description SETP-1 GET Client Secrect status
* @returns link to sheet auth url
*/
export const getClientSecrect = async (req, res) => {
try {
const clientSecrectExists = await sheet.testClientSecret();
if (clientSecrectExists) {
res.status(200).send();
} else {
res.status(500).send({ message: 'The Client ID does not exist' });
}
} catch (error) {
res.status(500).send({ message: error.toString() });
}
};
/**
* @description SETP-2 GET sheet authentication url
*/
export async function getAuthenticationUrl(req, res) {
try {
const authUrl = await sheet.openAuthServer();
res.status(200).send(authUrl);
} catch (error) {
res.status(500).send({ message: error.toString() });
export async function sheetAuthUrl(req, res) {
const successful = await Sheet.openAuthServer();
if (successful === false) {
res.status(500).send('bad');
} else {
res.status(200).send(successful);
}
}
/**
* @description SETP-2 GET sheet authentication status
* @description Get google sheet Settings
* @method GET
*/
export const getAuthentication = async (req, res) => {
export const getGoogleSheetSettings = async (req, res) => {
const sheet = DataProvider.getGoogleSheet();
res.status(200).send(sheet);
};
/**
* @description Change view Settings
* @method POST
*/
export const postGoogleSheetSettings = async (req, res) => {
if (failEmptyObjects(req.body, res)) {
return;
}
try {
await sheet.testAuthentication();
res.status(200).send();
const newData = {
id: req.body.id,
worksheet: req.body.worksheet,
};
await DataProvider.setGoogleSheet(newData);
res.status(200).send(newData);
} catch (error) {
res.status(500).send({ message: error.toString() });
res.status(400).send({ message: error.toString() });
}
};
/**
* @description SETP-3 POST sheet id
* @returns list of worksheets
* @description Get google sheet state
* @method GET
*/
export const postId = async (req, res) => {
try {
const { id } = req.body;
if (id.lenght < 40) {
res.status(400).send({ message: 'ID is usualy 44 characters long' });
}
const state = await sheet.testSheetId(id);
res.status(200).send(state);
} catch (error) {
res.status(500).send({ message: error.toString() });
}
export const getGoogleSheetState = async (req, res) => {
res.status(200).send(await Sheet.getSheetState());
};
/**
* @description SETP-4 POST worksheet
*/
export const postWorksheet = async (req, res) => {
try {
const { worksheet, id } = req.body;
const state = await sheet.testWorksheet(worksheet, id);
res.status(200).send(state);
} catch (error) {
res.status(500).send({ message: error.toString() });
}
};
/**
* @description STEP-5 POST download undown to sheet
* @returns parsed result
*/
export async function pullSheet(req, res) {
try {
const { id, options } = req.body;
const data = await sheet.pull(id, options);
res.status(200).send(data);
} catch (error) {
res.status(500).send({ message: error.toString() });
}
}
/**
* @description STEP-5 POST upload rundown to sheet
*/
export async function pushSheet(req, res) {
try {
const { id, options } = req.body;
await sheet.push(id, options);
res.status(200).send();
} catch (error) {
res.status(500).send({ message: error.toString() });
}
}
@@ -1,9 +1,5 @@
import { body, check, validationResult } from 'express-validator';
import {
validateHttpSubscriptionObject,
validateOscSubscriptionObject,
validateOscSubscriptionCycle,
} from '../utils/parserFunctions.js';
import { validateOscObject, validateOscSubscriptionEntry } from '../utils/parserFunctions.js';
/**
* @description Validates object for POST /ontime/views
@@ -86,22 +82,7 @@ export const validateOSC = [
body('enabledOut').exists().isBoolean(),
body('subscriptions')
.isObject()
.custom((value) => validateOscSubscriptionObject(value)),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
next();
},
];
/**
* @description Validates object for POST /ontime/http
*/
export const validateHTTP = [
body('enabledOut').exists().isBoolean(),
body('subscriptions')
.isObject()
.custom((value) => validateHttpSubscriptionObject(value)),
.custom((value) => validateOscObject(value)),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
@@ -115,22 +96,22 @@ export const validateHTTP = [
export const validateOscSubscription = [
body('onLoad')
.isArray()
.custom((value) => validateOscSubscriptionCycle(value)),
.custom((value) => validateOscSubscriptionEntry(value)),
body('onStart')
.isArray()
.custom((value) => validateOscSubscriptionCycle(value)),
.custom((value) => validateOscSubscriptionEntry(value)),
body('onPause')
.isArray()
.custom((value) => validateOscSubscriptionCycle(value)),
.custom((value) => validateOscSubscriptionEntry(value)),
body('onStop')
.isArray()
.custom((value) => validateOscSubscriptionCycle(value)),
.custom((value) => validateOscSubscriptionEntry(value)),
body('onUpdate')
.isArray()
.custom((value) => validateOscSubscriptionCycle(value)),
.custom((value) => validateOscSubscriptionEntry(value)),
body('onFinish')
.isArray()
.custom((value) => validateOscSubscriptionCycle(value)),
.custom((value) => validateOscSubscriptionEntry(value)),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
@@ -153,8 +134,11 @@ export const validatePatchProjectFile = [
},
];
export const validateSheetid = [
body('id').exists().isString(),
//TODO: is thise correct
export const validateSheetPreview = [
body('sheetid').isString().optional({ nullable: false }),
body('worksheet').isString().optional({ nullable: false }),
body('options').isObject().optional({ nullable: true }),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
@@ -162,19 +146,9 @@ export const validateSheetid = [
},
];
export const validateWorksheet = [
body('id').exists().isString(),
body('worksheet').exists().isString(),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
next();
},
];
export const validateSheetOptions = [
body('id').exists().isString(),
// body('options').exists().isObject(), TODO:
export const validateGoogleSheetSettings = [
body('id').isString().optional({ nullable: false }),
body('worksheet').isString().optional({ nullable: false }),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
-67
View File
@@ -1,67 +0,0 @@
/*eslint-env browser*/
/**
* This is a very minimal example for a websocket client
* You could use this as a starting point to creating your own interfaces
*/
const mts = 1000; // millis to seconds
const mtm = 1000 * 60; // millis to minutes
const mth = 1000 * 60 * 60; // millis to hours
const leftPad = (number) => {
return Math.floor(number).toString().padStart(2, '0');
};
let reconnectTimeout;
const reconnectInterval = 1000;
let reconnectAttempts = 0;
const connectSocket = () => {
const websocket = new WebSocket(`ws://${window.location.hostname}:${window.location.port}/ws`);
websocket.onopen = () => {
clearTimeout(reconnectTimeout);
reconnectAttempts = 0;
console.info('WebSocket connected');
};
websocket.onclose = () => {
console.warn('WebSocket disconnected');
reconnectTimeout = setTimeout(() => {
console.warn(`WebSocket: attempting reconnect ${reconnectAttempts}`);
if (websocket && websocket.readyState === WebSocket.CLOSED) {
reconnectAttempts += 1;
connectSocket();
}
}, reconnectInterval);
};
websocket.onerror = (error) => {
console.error('WebSocket error:', error);
};
websocket.onmessage = (event) => {
const data = JSON.parse(event.data);
// all objects from ontime are structured with type and payload
const { type, payload } = data;
// we only need to read message type of ontime
if (type === 'ontime') {
// destructure known data from ontime
// see https://cpvalente.gitbook.io/ontime/control-and-feedback/websocket-api
const { timer, playback } = payload;
const timerElement = document.getElementById('timer');
if (playback == 'stop') {
timerElement.innerText = '--:--:--';
} else {
const millis = Math.abs(timer.current);
const isNegative = timer.current < 0;
timerElement.innerText = `${isNegative ? '-' : ''}${leftPad(millis / mth)}:${leftPad(
(millis % mth) / mtm,
)}:${leftPad((millis % mtm) / mts)}`;
}
}
};
};
connectSocket();
-14
View File
@@ -1,14 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>ontime demo</title>
<link href="./styles.css" rel="stylesheet" />
</head>
<body>
<div id="timer"></div>
<script src="./app.js" type="module"></script>
</html>
-16
View File
@@ -1,16 +0,0 @@
body {
overflow: hidden;
margin: 0;
}
div {
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
color: azure;
font-family: monospace;
font-size: 20vw;
background-color: black;
}
+4 -11
View File
@@ -20,6 +20,10 @@ export const dbModel: DatabaseModel = {
timeFormat: '24',
language: 'en',
},
googleSheet: {
worksheet: '',
id: '',
},
viewSettings: {
overrideStyles: false,
normalColor: '#ffffffcc',
@@ -57,15 +61,4 @@ export const dbModel: DatabaseModel = {
onFinish: [],
},
},
http: {
enabledOut: false,
subscriptions: {
onLoad: [],
onStart: [],
onPause: [],
onStop: [],
onUpdate: [],
onFinish: [],
},
},
};
-21
View File
@@ -1,21 +0,0 @@
import { copyFile } from 'fs/promises';
import { pathToStartDemo, resolveDemoDirectory, resolveDemoPath } from '../setup.js';
import { ensureDirectory } from '../utils/fileManagement.js';
/**
* @description ensures directories exist and populates demo folder
*/
export const populateDemo = () => {
ensureDirectory(resolveDemoDirectory);
// even if demo exist we want to use startup demo
try {
Promise.all(
resolveDemoPath.map((to, index) => {
const from = pathToStartDemo[index];
copyFile(from, to);
}),
);
} catch (_) {
/* we do not handle this */
}
};
+8 -3
View File
@@ -4,15 +4,20 @@ import { ensureDirectory } from '../utils/fileManagement.js';
/**
* @description ensures directories exist and populates stylesheet
* @return {string} - path to stylesheet file
*/
export const populateStyles = () => {
const stylesInDisk = resolveStylesPath;
ensureDirectory(resolveStylesDirectory);
// if styles doesn't exist we want to use startup stylesheet
if (!existsSync(resolveStylesPath)) {
// if stylesInDisk doesn't exist we want to use startup stylesheet
if (!existsSync(stylesInDisk)) {
try {
copyFileSync(pathToStartStyles, resolveStylesPath);
copyFileSync(pathToStartStyles, stylesInDisk);
} catch (_) {
/* we do not handle this */
}
}
return stylesInDisk;
};
+24 -33
View File
@@ -6,7 +6,6 @@ import {
getAliases,
getInfo,
getOSC,
getHTTP,
getSettings,
getUserFields,
getViewSettings,
@@ -20,28 +19,25 @@ import {
postUserFields,
postViewSettings,
previewExcel,
postHTTP,
getAuthenticationUrl,
uploadSheetClientFile as uploadClientSecret,
pullSheet,
sheetAuthUrl,
uploadGoogleSheetClientFile,
previewSheet,
pushSheet,
postId,
getAuthentication,
getClientSecrect as getClientSecret,
getGoogleSheetSettings,
postGoogleSheetSettings,
getGoogleSheetState,
} from '../controllers/ontimeController.js';
import {
validateAliases,
validateGoogleSheetSettings,
validateOSC,
validateOscSubscription,
validatePatchProjectFile,
validateSettings,
validateSheetPreview,
validateUserFields,
viewValidator,
validateHTTP,
validateOscSubscription,
validateSheetid,
validateWorksheet,
validateSheetOptions,
} from '../controllers/ontimeController.validate.js';
import { projectSanitiser } from '../controllers/projectController.validate.js';
@@ -98,31 +94,26 @@ router.post('/osc', validateOSC, postOSC);
// create route between controller and '/ontime/osc-subscriptions' endpoint
router.post('/osc-subscriptions', validateOscSubscription, postOscSubscriptions);
// create route between controller and '/ontime/http' endpoint
router.get('/http', getHTTP);
// create route between controller and '/ontime/http' endpoint
router.post('/http', validateHTTP, postHTTP);
// create route between controller and '/ontime/new' endpoint
router.post('/new', projectSanitiser, postNew);
//SETP-1
router.post('/sheet/clientsecret', uploadFile, uploadClientSecret);
router.get('/sheet/clientsecret', uploadFile, getClientSecret);
// create route between controller and '/ontime/sheet-client' endpoint
router.post('/sheet-clientsecrect', uploadFile, uploadGoogleSheetClientFile);
//SETP-2
router.get('/sheet/authentication/url', getAuthenticationUrl);
router.get('/sheet/authentication', getAuthentication);
// create route between controller and '/ontime/sheet-authstatus' endpoint
router.get('/sheet-authurl', sheetAuthUrl);
//STEP-3
router.post('/sheet/id', validateSheetid, postId);
// create route between controller and '/ontime/preview-sheet' endpoint
router.post('/sheet-preview', validateSheetPreview, previewSheet);
//STEP-4
router.post('/sheet/worksheet', validateWorksheet, postId);
// create route between controller and '/ontime/preview-sheet' endpoint
router.post('/sheet-push', pushSheet);
//STEP-5 download and generate preview
router.post('/sheet/pull', validateSheetOptions, pullSheet);
// create route between controller and '/ontime/sheet-settings' endpoint
router.get('/sheet-settings', getGoogleSheetSettings);
//STEP-5 upload
router.post('/sheet-push', validateSheetOptions, pushSheet);
// create route between controller and '/ontime/sheet-settings' endpoint
router.post('/sheet-settings', validateGoogleSheetSettings, postGoogleSheetSettings);
// create route between controller and '/ontime/sheet-state' endpoint
router.get('/sheet-state', getGoogleSheetState);
+7 -24
View File
@@ -5,7 +5,7 @@ import { eventStore } from '../stores/EventStore.js';
import { PlaybackService } from './PlaybackService.js';
import { updateRoll } from './rollUtils.js';
import { integrationService } from './integration-service/IntegrationService.js';
import { getCurrent, getExpectedFinish, skippedOutOfEvent } from './timerUtils.js';
import { getCurrent, getExpectedFinish } from './timerUtils.js';
import { clock } from './Clock.js';
import { logger } from '../classes/Logger.js';
import type { RestorePoint } from './RestoreService.js';
@@ -18,13 +18,10 @@ type initialLoadingData = {
type RestoreCallback = (newState: RestorePoint) => Promise<void>;
export const timeSkipLimit = 3 * 32;
export class TimerService {
private readonly _interval: NodeJS.Timer;
private _updateInterval: number;
private _lastUpdate: number | null;
private _skipThreshold: number;
playback: Playback;
timer: TimerState;
@@ -43,13 +40,11 @@ export class TimerService {
* @param {object} [timerConfig]
* @param {number} [timerConfig.refresh]
* @param {number} [timerConfig.updateInterval]
* @param {number} [timerConfig.skipThreshold]
*/
constructor(timerConfig: { refresh: number; updateInterval: number; skipThreshold: number }) {
constructor(timerConfig: { refresh?: number; updateInterval?: number } = {}) {
this._clear();
this._interval = setInterval(() => this.update(), timerConfig.refresh);
this._updateInterval = timerConfig.updateInterval;
this._skipThreshold = timerConfig.skipThreshold;
this._interval = setInterval(() => this.update(), timerConfig?.refresh ?? 1000);
this._updateInterval = timerConfig?.updateInterval ?? 1000;
}
/**
@@ -344,6 +339,7 @@ export class TimerService {
this.timer.expectedFinish >= this.timer.startedAt
? this.timer.expectedFinish
: this.timer.expectedFinish + dayInMs,
clock: this.timer.clock,
secondaryTimer: this.timer.secondaryTimer,
secondaryTarget: this.secondaryTarget,
@@ -409,19 +405,7 @@ export class TimerService {
let shouldNotify = false;
if (this.playback === Playback.Roll) {
shouldNotify = true;
if (
skippedOutOfEvent(
previousTime,
this.timer.clock,
this.timer.startedAt,
this.timer.expectedFinish,
this._skipThreshold,
)
) {
PlaybackService.roll();
} else {
this.updateRoll();
}
this.updateRoll();
} else if (this.timer.startedAt !== null) {
// we only update timer if a timer has been started
shouldNotify = true;
@@ -521,5 +505,4 @@ export class TimerService {
}
// calculate at 30fps, refresh at 1fps
// we consider a skip at 3 lost updates
export const eventTimer = new TimerService({ refresh: 32, updateInterval: 1000, skipThreshold: 32 * 3 });
export const eventTimer = new TimerService({ refresh: 32, updateInterval: 1000 });
@@ -1,7 +1,7 @@
import { dayInMs } from 'ontime-utils';
import { TimerType } from 'ontime-types';
import { getCurrent, getExpectedFinish, skippedOutOfEvent } from '../timerUtils.js';
import { getCurrent, getExpectedFinish } from '../timerUtils.js';
describe('getExpectedFinish()', () => {
it('is null if we havent started', () => {
@@ -354,106 +354,3 @@ describe('getExpectedFinish() and getCurrentTime() combined', () => {
expect(current).toBe(8);
});
});
describe('skippedOutOfEvent()', () => {
const testSkipLimit = 32;
it('does not consider an event end as a skip', () => {
const startedAt = 1000;
const duration = 1000;
const expectedFinish = startedAt + duration;
const previousTime = expectedFinish - testSkipLimit / 2;
let clock = previousTime;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
clock += testSkipLimit;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
});
it('allows rolling backwards in an event', () => {
const startedAt = 1000;
const duration = 1000;
const expectedFinish = startedAt + duration;
const previousTime = startedAt + testSkipLimit / 2;
let clock = previousTime;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
clock -= testSkipLimit;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
});
it('accounts for crossing midnight', () => {
const startedAt = dayInMs - testSkipLimit;
const expectedFinish = 10;
const previousTime = dayInMs - 1;
let clock = previousTime;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
clock = testSkipLimit - 2;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
});
it('allows rolling backwards in an event across midnight', () => {
const startedAt = dayInMs - testSkipLimit;
const expectedFinish = 10;
const previousTime = startedAt + 1;
let clock = previousTime;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
clock -= testSkipLimit;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
});
it('finds skip forwards out of event', () => {
const startedAt = 1000;
const duration = 1000;
const expectedFinish = startedAt + duration;
const previousTime = expectedFinish - testSkipLimit / 2;
let clock = previousTime;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
clock += testSkipLimit + 1;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(true);
});
it('finds skip backwards out of event', () => {
const startedAt = 1000;
const duration = 1000;
const expectedFinish = startedAt + duration;
const previousTime = startedAt + testSkipLimit / 2;
let clock = previousTime;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
clock -= testSkipLimit + 1;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(true);
});
it('finds skip forwards out of event across midnight', () => {
const startedAt = dayInMs - testSkipLimit;
const expectedFinish = 10;
const previousTime = dayInMs - 3;
let clock = previousTime;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
clock = testSkipLimit - 2;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(true);
});
it('finds skip backwards out of event across midnight', () => {
const startedAt = dayInMs - testSkipLimit;
const expectedFinish = 10;
const previousTime = startedAt + 1;
let clock = previousTime;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(false);
clock -= testSkipLimit + 1;
expect(skippedOutOfEvent(previousTime, clock, startedAt, expectedFinish, testSkipLimit)).toBe(true);
});
});
@@ -1,99 +0,0 @@
import got from 'got';
import { HttpSettings, HttpSubscription, HttpSubscriptionOptions, LogOrigin } from 'ontime-types';
import IIntegration, { TimerLifeCycleKey } from './IIntegration.js';
import { parseTemplateNested } from './integrationUtils.js';
import { dbModel } from '../../models/dataModel.js';
import { logger } from '../../classes/Logger.js';
import { validateHttpSubscriptionObject } from '../../utils/parserFunctions.js';
type Action = TimerLifeCycleKey | string;
/**
* @description Class contains logic towards outgoing HTTP communications
* @class
*/
export class HttpIntegration implements IIntegration<HttpSubscriptionOptions> {
subscriptions: HttpSubscription;
constructor() {
this.subscriptions = dbModel.http.subscriptions;
}
/**
* Initializes httpClient
*/
init(config: HttpSettings) {
const { subscriptions, enabledOut } = config;
if (!enabledOut) {
return {
success: false,
message: 'HTTP output disabled',
};
}
this.initSubscriptions(subscriptions);
try {
return {
success: true,
message: `HTTP integration client ready`,
};
} catch (error) {
return {
success: false,
message: `Failed initialising HTTP integration: ${error}`,
};
}
}
initSubscriptions(subscriptionOptions: HttpSubscription) {
if (validateHttpSubscriptionObject(subscriptionOptions)) {
this.subscriptions = { ...subscriptionOptions };
}
}
dispatch(action: Action, state?: object) {
if (!action) {
return {
success: false,
message: 'HTTP called with no action',
};
}
// check subscriptions for action
const eventSubscriptions = this.subscriptions?.[action] || [];
eventSubscriptions.forEach((sub) => {
const { enabled, message } = sub;
if (enabled && message) {
const parsedMessage = parseTemplateNested(message, state || {});
try {
const parsedUrl = new URL(parsedMessage);
this.emit(parsedUrl);
} catch (err) {
logger.error(LogOrigin.Tx, `HTTP Integration: ${err}`);
return {
success: false,
message: `${err}`,
};
}
}
});
}
async emit(path: URL) {
try {
await got.get(path, {
retry: { limit: 0 },
});
} catch (err) {
logger.error(LogOrigin.Tx, `HTTP integration: ${err}`);
}
}
shutdown() {}
}
export const httpIntegration = new HttpIntegration();
@@ -1,9 +1,9 @@
import { TimerLifeCycle, Subscription } from 'ontime-types';
import { TimerLifeCycle, OscSubscription } from 'ontime-types';
export type TimerLifeCycleKey = keyof typeof TimerLifeCycle;
export default interface IIntegration<T> {
subscriptions: Subscription<T>;
export default interface IIntegration {
subscriptions: OscSubscription;
init: (config: unknown) => OperationReturn;
dispatch: (action: TimerLifeCycleKey, state?: object) => OperationReturn;
emit: (...args: unknown[]) => unknown;
@@ -2,17 +2,17 @@ import IIntegration, { TimerLifeCycleKey } from './IIntegration.js';
import { eventStore } from '../../stores/EventStore.js';
class IntegrationService {
private integrations: IIntegration<unknown>[];
private integrations: IIntegration[];
constructor() {
this.integrations = [];
}
register(integrationService: IIntegration<unknown>) {
register(integrationService: IIntegration) {
this.integrations.push(integrationService);
}
unregister(integrationService: IIntegration<unknown>) {
unregister(integrationService: IIntegration) {
this.integrations = this.integrations.filter((int) => int !== integrationService);
}
@@ -1,11 +1,11 @@
import { ArgumentType, Client, Message } from 'node-osc';
import { OSCSettings, OscSubscription, OscSubscriptionOptions } from 'ontime-types';
import { OSCSettings, OscSubscription } from 'ontime-types';
import IIntegration, { TimerLifeCycleKey } from './IIntegration.js';
import { parseTemplateNested } from './integrationUtils.js';
import { isObject } from '../../utils/varUtils.js';
import { dbModel } from '../../models/dataModel.js';
import { validateOscSubscriptionObject } from '../../utils/parserFunctions.js';
import { validateOscObject } from '../../utils/parserFunctions.js';
type Action = TimerLifeCycleKey | string;
@@ -13,7 +13,7 @@ type Action = TimerLifeCycleKey | string;
* @description Class contains logic towards outgoing OSC communications
* @class
*/
export class OscIntegration implements IIntegration<OscSubscriptionOptions> {
export class OscIntegration implements IIntegration {
protected oscClient: null | Client;
subscriptions: OscSubscription;
@@ -26,15 +26,7 @@ export class OscIntegration implements IIntegration<OscSubscriptionOptions> {
* Initializes oscClient
*/
init(config: OSCSettings) {
const { targetIP, portOut, subscriptions, enabledOut } = config;
if (!enabledOut) {
this.oscClient?.close();
return {
success: false,
message: 'OSC output disabled',
};
}
const { targetIP, portOut, subscriptions } = config;
this.initSubscriptions(subscriptions);
@@ -66,7 +58,7 @@ export class OscIntegration implements IIntegration<OscSubscriptionOptions> {
}
initSubscriptions(subscriptionOptions: OscSubscription) {
if (validateOscSubscriptionObject(subscriptionOptions)) {
if (validateOscObject(subscriptionOptions)) {
this.subscriptions = { ...subscriptionOptions };
}
}
-17
View File
@@ -64,20 +64,3 @@ export function getCurrent(
}
return startedAt + duration + addedTime + pausedTime - clock;
}
export function skippedOutOfEvent(
previousTime: number,
clock: number,
startedAt: number,
expectedFinish: number,
skipLimit: number,
): boolean {
const hasPassedMidnight = previousTime > dayInMs - skipLimit && clock < skipLimit;
const adjustedClock = hasPassedMidnight ? clock + dayInMs : clock;
const timeDifference = previousTime - adjustedClock;
const hasSkipped = Math.abs(timeDifference) > skipLimit;
const adjustedExpectedFinish = expectedFinish >= startedAt ? expectedFinish : expectedFinish + dayInMs;
return hasSkipped && (adjustedClock > adjustedExpectedFinish || adjustedClock < startedAt);
}
+1 -17
View File
@@ -68,8 +68,7 @@ export const currentDirectory = dirname(__dirname);
const testDbStartDirectory = isTest ? '../' : getAppDataPath();
export const externalsStartDirectory = isProduction ? getAppDataPath() : join(currentDirectory, 'external');
//TODO: we only need one when they are all in the same folder
export const resolveExternalsDirectory = join(isProduction ? getAppDataPath() : currentDirectory, 'external');
// path to public db
export const resolveDbDirectory = join(
testDbStartDirectory,
@@ -81,26 +80,11 @@ export const pathToStartDb = isTest
? join(currentDirectory, '../', config.database.testdb, config.database.filename)
: join(currentDirectory, '/preloaded-db/', config.database.filename);
//TODO: move all static files to the external directory
// path to public styles
export const resolveStylesDirectory = join(externalsStartDirectory, config.styles.directory);
export const resolveStylesPath = join(resolveStylesDirectory, config.styles.filename);
export const pathToStartStyles = join(currentDirectory, '/external/styles/', config.styles.filename);
// path to public demo
export const resolveDemoDirectory = join(
externalsStartDirectory,
isProduction ? '/external/' : '', //move to external folde in production
config.demo.directory,
);
export const resolveDemoPath = config.demo.filename.map((file) => {
return join(resolveDemoDirectory, file);
});
export const pathToStartDemo = config.demo.filename.map((file) => {
return join(currentDirectory, '/external/demo/', file);
});
// path to restore file
export const resolveRestoreFile = join(getAppDataPath(), config.restoreFile);
@@ -1,21 +0,0 @@
import { coerceColour } from '../coerceType.js';
describe('parses a colour string that is', () => {
it('valid hex', () => {
const color = coerceColour('#000');
expect(color).toBe('#000');
});
it('valid name', () => {
const color = coerceColour('darkgoldenrod');
expect(color).toBe('darkgoldenrod');
});
it('invalid hex', () => {
expect(() => coerceColour('#not a hex color')).toThrowError(Error('Invalid hex colour received'));
});
it('invalid name', () => {
expect(() => coerceColour('bad name')).toThrowError(Error('Invalid colour name received'));
});
it('not a string', () => {
expect(() => coerceColour(5)).toThrowError(Error('Invalid colour value received'));
});
});
@@ -1,5 +1,5 @@
import { millisToString } from 'ontime-utils';
import { getA1Notation, cellRequestFromEvent, cellRequenstFromProjectData } from '../sheetUtils.js';
import { getA1Notation, cellRequenstFromEvent, cellRequenstFromProjectData } from '../googleSheetUtils.js';
import { EndAction, OntimeRundownEntry, ProjectData, SupportedEvent, TimerType } from 'ontime-types';
describe('getA1Notation()', () => {
@@ -75,7 +75,7 @@ describe('cellRequenstFromEvent()', () => {
revision: { row: 1, col: 38 },
id: { row: 1, col: 39 },
};
const result = cellRequestFromEvent(event, 1, 1234, metadata);
const result = cellRequenstFromEvent(event, 1, 1234, metadata);
expect(result.updateCells.rows[0].values[5].userEnteredValue.stringValue).toStrictEqual(event.note);
});
@@ -136,7 +136,7 @@ describe('cellRequenstFromEvent()', () => {
revision: { row: 1, col: 38 },
id: { row: 1, col: 39 },
};
const result = cellRequestFromEvent(event, 1, 1234, metadata).updateCells.rows[0].values[10].userEnteredValue
const result = cellRequenstFromEvent(event, 1, 1234, metadata).updateCells.rows[0].values[10].userEnteredValue
.stringValue;
expect(result).toStrictEqual(millisToString(event.duration));
});
@@ -198,7 +198,7 @@ describe('cellRequenstFromEvent()', () => {
revision: { row: 1, col: 38 },
id: { row: 1, col: 39 },
};
const result = cellRequestFromEvent(event, 1, 1234, metadata);
const result = cellRequenstFromEvent(event, 1, 1234, metadata);
expect(result.updateCells.rows[0].values[11].userEnteredValue.stringValue).toStrictEqual('x');
expect(result.updateCells.rows[0].values[12].userEnteredValue.stringValue).toStrictEqual('');
});
@@ -238,7 +238,7 @@ describe('cellRequenstFromEvent()', () => {
subtitle: { row: 1, col: 10 },
user0: { row: 1, col: 16 },
};
const result = cellRequestFromEvent(event, 1, 1234, metadata);
const result = cellRequenstFromEvent(event, 1, 1234, metadata);
expect(result.updateCells.rows[0].values[0].userEnteredValue.stringValue).toStrictEqual(event.cue);
expect(result.updateCells.rows[0].values[6].userEnteredValue.stringValue).toStrictEqual(event.title);
expect(result.updateCells.rows[0].values[10].userEnteredValue.stringValue).toStrictEqual(event.subtitle);
@@ -279,7 +279,7 @@ describe('cellRequenstFromEvent()', () => {
subtitle: { row: 1, col: 10 },
user0: { row: 1, col: 16 },
};
const result = cellRequestFromEvent(event, 1, 1234, metadata);
const result = cellRequenstFromEvent(event, 1, 1234, metadata);
expect(result.updateCells.rows[0].values[0].userEnteredValue.stringValue).toStrictEqual(event.cue);
expect(result.updateCells.rows[0].values[1].userEnteredValue.stringValue).toStrictEqual(event.title);
expect(result.updateCells.rows[0].values[5].userEnteredValue.stringValue).toStrictEqual(event.subtitle);
@@ -320,9 +320,9 @@ describe('cellRequenstFromEvent()', () => {
subtitle: { row: 1, col: 10 },
user0: { row: 10, col: 16 },
};
const result1 = cellRequestFromEvent(event, 1, 1234, metadata);
const result1 = cellRequenstFromEvent(event, 1, 1234, metadata);
expect(result1.updateCells.start.sheetId).toStrictEqual(1234);
const result2 = cellRequestFromEvent(event, 10, 1234, metadata);
const result2 = cellRequenstFromEvent(event, 10, 1234, metadata);
expect(result2.updateCells.start.rowIndex).toStrictEqual(21);
expect(result2.updateCells.start.columnIndex).toStrictEqual(5);
expect(result2.updateCells.fields).toStrictEqual('userEnteredValue');
@@ -0,0 +1,91 @@
import { validateOscObject } from '../parserFunctions.ts';
test('validateOscSubscription()', () => {
it('should return true when given a valid OscSubscription', () => {
const validSubscription = {
onLoad: [{ id: '1', message: 'test', enabled: true }],
onStart: [{ id: '2', message: 'test', enabled: false }],
onPause: [{ id: '3', message: 'test', enabled: true }],
onStop: [{ id: '4', message: 'test', enabled: false }],
onUpdate: [{ id: '5', message: 'test', enabled: true }],
onFinish: [{ id: '6', message: 'test', enabled: false }],
};
const result = validateOscObject(validSubscription);
expect(result).toBe(true);
});
it('should return false when given undefined', () => {
const result = validateOscObject(undefined);
expect(result).toBe(false);
});
it('should return false when given null', () => {
const result = validateOscObject(null);
expect(result).toBe(false);
});
it('should return false when given an empty object', () => {
const result = validateOscObject({});
expect(result).toBe(false);
});
it('should return false when given an empty array', () => {
const result = validateOscObject([]);
expect(result).toBe(false);
});
it('should return false when given an object that is not an OscSubscription', () => {
const invalidObject = { foo: 'bar' };
const result = validateOscObject(invalidObject);
expect(result).toBe(false);
});
it('should return false when given an OscSubscription with a missing property', () => {
const invalidSubscription = {
onLoad: [{ id: '1', message: 'test', enabled: true }],
onStart: [{ id: '2', message: 'test', enabled: false }],
onPause: [{ id: '3', message: 'test', enabled: true }],
// Missing onStop
onUpdate: [{ id: '5', message: 'test', enabled: true }],
onFinish: [{ id: '6', message: 'test', enabled: false }],
};
const result = validateOscObject(invalidSubscription);
expect(result).toBe(false);
});
it('should return false when given an OscSubscription with an invalid property value', () => {
const invalidSubscription = {
onLoad: [{ id: '1', message: 'test', enabled: true }],
onStart: [{ id: '2', message: 'test', enabled: false }],
onPause: [{ id: '3', message: 'test', enabled: true }],
onStop: [{ id: '4', message: 'test', enabled: false }],
onUpdate: [{ id: '5', message: 'test', enabled: true }],
onFinish: [{ id: '6', message: 'test', enabled: 'not a boolean' }],
};
const result = validateOscObject(invalidSubscription);
expect(result).toBe(false);
});
it('should return true if the message field is empty', () => {
const invalidSubscription = {
onLoad: [{ id: '1', message: 'test', enabled: true }],
onStart: [{ id: '2', message: '', enabled: false }],
onPause: [{ id: '3', message: '', enabled: true }],
onStop: [{ id: '4', message: 'test', enabled: false }],
onUpdate: [{ id: '5', message: 'test', enabled: true }],
onFinish: [{ id: '6', message: 'test', enabled: 'not a boolean' }],
};
const result = validateOscObject(invalidSubscription);
expect(result).toBe(true);
});
});
@@ -1,162 +0,0 @@
import { HttpSubscription, OscSubscription } from 'ontime-types';
import {
validateOscSubscriptionObject,
validateOscSubscriptionCycle,
validateHttpSubscriptionCycle,
validateHttpSubscriptionObject,
} from '../parserFunctions.js';
describe('validateOscSubscriptionCycle()', () => {
it('should return false when given an OscSubscription with an invalid property value', () => {
const invalidEntry = [{ message: 'test', enabled: 'not a boolean' }];
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
const result = validateOscSubscriptionCycle(invalidEntry);
expect(result).toBe(false);
});
});
describe('validateOscSubscriptionObject()', () => {
it('should return true when given a valid OscSubscription', () => {
const validSubscription: OscSubscription = {
onLoad: [{ message: 'test', enabled: true }],
onStart: [{ message: 'test', enabled: false }],
onPause: [{ message: 'test', enabled: true }],
onStop: [{ message: 'test', enabled: false }],
onUpdate: [{ message: 'test', enabled: true }],
onFinish: [{ message: 'test', enabled: false }],
};
const result = validateOscSubscriptionObject(validSubscription);
expect(result).toBe(true);
});
it('should return false when given undefined', () => {
const result = validateOscSubscriptionObject(undefined);
expect(result).toBe(false);
});
it('should return false when given null', () => {
const result = validateOscSubscriptionObject(null);
expect(result).toBe(false);
});
it('should return false when given an empty object', () => {
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
const result = validateOscSubscriptionObject({});
expect(result).toBe(false);
});
it('should return false when given an empty array', () => {
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
const result = validateOscSubscriptionObject([]);
expect(result).toBe(false);
});
it('should return false when given an object that is not an OscSubscription', () => {
const invalidObject = { foo: 'bar' };
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
const result = validateOscSubscriptionObject(invalidObject);
expect(result).toBe(false);
});
it('should return false when given an OscSubscription with a missing property', () => {
const invalidSubscription = {
onLoad: [{ message: 'test', enabled: true }],
onStart: [{ message: 'test', enabled: false }],
onPause: [{ message: 'test', enabled: true }],
// Missing onStop
onUpdate: [{ message: 'test', enabled: true }],
onFinish: [{ message: 'test', enabled: false }],
};
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
const result = validateOscSubscriptionObject(invalidSubscription);
expect(result).toBe(false);
});
});
describe('validateHttpSubscriptionCycle()', () => {
it('should return false when given an HttpSubscription with an invalid property value', () => {
const invalidBoolean = [{ message: 'http://', enabled: 'not a boolean' }];
const invalidHttp = [{ message: 'test', enabled: true }];
const noFtp = [{ message: 'ftp://test', enabled: true }];
const noEmpty = [{ message: '', enabled: true }];
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
expect(validateHttpSubscriptionCycle(invalidBoolean)).toBe(false);
expect(validateHttpSubscriptionCycle(invalidHttp)).toBe(false);
expect(validateHttpSubscriptionCycle(noFtp)).toBe(false);
expect(validateHttpSubscriptionCycle(noEmpty)).toBe(false);
});
it('should return true when given an HttpSubscription matches definition', () => {
const validHttp = [{ message: 'http://', enabled: true }];
const invalidHttps = [{ message: 'https://', enabled: true }];
expect(validateHttpSubscriptionCycle(validHttp)).toBe(true);
expect(validateHttpSubscriptionCycle(invalidHttps)).toBe(false);
});
});
describe('validateHttpSubscriptionObject()', () => {
it('should return true when given a valid HttpSubscription', () => {
const validSubscription: HttpSubscription = {
onLoad: [{ message: 'http://', enabled: true }],
onStart: [{ message: 'http://', enabled: false }],
onPause: [{ message: 'http://', enabled: true }],
onStop: [{ message: 'http://', enabled: false }],
onUpdate: [{ message: 'http://', enabled: true }],
onFinish: [{ message: 'http://', enabled: false }],
};
const result = validateHttpSubscriptionObject(validSubscription);
expect(result).toBe(true);
});
it('should return false when given undefined', () => {
const result = validateHttpSubscriptionObject(undefined);
expect(result).toBe(false);
});
it('should return false when given null', () => {
const result = validateHttpSubscriptionObject(null);
expect(result).toBe(false);
});
it('should return false when given an empty object', () => {
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
const result = validateOscSubscriptionObject({});
expect(result).toBe(false);
});
it('should return false when given an empty array', () => {
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
const result = validateHttpSubscriptionObject([]);
expect(result).toBe(false);
});
it('should return false when given an object that is not an HttpSubscription', () => {
const invalidObject = { foo: 'bar' };
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
const result = validateHttpSubscriptionObject(invalidObject);
expect(result).toBe(false);
});
it('should return false when given an HttpSubscription with a missing property', () => {
const invalidSubscription = {
onLoad: [{ message: 'http://', enabled: true }],
onStart: [{ message: 'http://', enabled: false }],
onPause: [{ message: 'http://', enabled: true }],
// Missing onStop
onUpdate: [{ message: 'http://', enabled: true }],
onFinish: [{ message: 'http://', enabled: false }],
};
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
const result = validateHttpSubscriptionObject(invalidSubscription);
expect(result).toBe(false);
});
});
+2 -196
View File
@@ -1,8 +1,5 @@
import { isColourHex } from 'ontime-utils';
//TODO: write tests
/**
* @description Converts a value to a string if possible, throws otherwise
* @description Converts a value to a number if possible, throws otherwise
* @param {unknown} value - Value to be converted to a string.
* @returns {string} - The converted value as a string.
* @throws {Error} Throws an error if the value is null or undefined.
@@ -14,9 +11,8 @@ export function coerceString(value: unknown): string {
return String(value);
}
//TODO: write tests
/**
* @description Converts a value to a boolean if possible, throws otherwise
* @description Converts a value to a number if possible, throws otherwise
* @param {unknown} value - Value to be converted to a boolean.
* @returns {boolean} - The converted value as a boolean.
* @throws {Error} Throws an error if the value is null or undefined.
@@ -25,26 +21,9 @@ export function coerceBoolean(value: unknown): boolean {
if (value == null) {
throw new Error('Invalid value received');
}
if (typeof value === 'string') {
const lowerCaseValue = value.toLocaleLowerCase();
switch (lowerCaseValue) {
case 'true':
case '1':
case 'yes':
return true;
case 'false':
case '0':
case 'no':
case '':
return false;
default:
throw new Error('Invalid value received');
}
}
return Boolean(value);
}
//TODO: write tests
/**
* @description Converts a value to a number if possible, throws otherwise
* @param {unknown} value - Value to be converted to a number.
@@ -61,176 +40,3 @@ export function coerceNumber(value: unknown): number {
}
return parsedValue;
}
/**
* @description Converts a value to a colour if possible, throws otherwise
* @param {unknown} value - Value to be converted to a colour.
* @returns {string} - The converted value as a string.
* @throws {Error} Throws an error if the value is null or undefined.
*/
export function coerceColour(value: unknown): string {
if (typeof value !== 'string') {
throw new Error('Invalid colour value received');
}
const lowerCaseValue = value.toLocaleLowerCase();
if (lowerCaseValue.startsWith('#')) {
if (!isColourHex(lowerCaseValue)) {
throw new Error('Invalid hex colour received');
}
} else if (!(lowerCaseValue in cssColours)) {
throw new Error('Invalid colour name received');
}
return lowerCaseValue;
}
//https://developer.mozilla.org/en-US/docs/Web/CSS/named-color
const cssColours = {
aliceblue: '#f0f8ff',
antiquewhite: '#faebd7',
aqua: '#00ffff',
aquamarine: '#7fffd4',
azure: '#f0ffff',
beige: '#f5f5dc',
bisque: '#ffe4c4',
black: '#000000',
blanchedalmond: '#ffebcd',
blue: '#0000ff',
blueviolet: '#8a2be2',
brown: '#a52a2a',
burlywood: '#deb887',
cadetblue: '#5f9ea0',
chartreuse: '#7fff00',
chocolate: '#d2691e',
coral: '#ff7f50',
cornflowerblue: '#6495ed',
cornsilk: '#fff8dc',
crimson: '#dc143c',
cyan: '#00ffff',
darkblue: '#00008b',
darkcyan: '#008b8b',
darkgoldenrod: '#b8860b',
darkgray: '#a9a9a9',
darkgreen: '#006400',
darkgrey: '#a9a9a9',
darkkhaki: '#bdb76b',
darkmagenta: '#8b008b',
darkolivegreen: '#556b2f',
darkorange: '#ff8c00',
darkorchid: '#9932cc',
darkred: '#8b0000',
darksalmon: '#e9967a',
darkseagreen: '#8fbc8f',
darkslateblue: '#483d8b',
darkslategray: '#2f4f4f',
darkslategrey: '#2f4f4f',
darkturquoise: '#00ced1',
darkviolet: '#9400d3',
deeppink: '#ff1493',
deepskyblue: '#00bfff',
dimgray: '#696969',
dimgrey: '#696969',
dodgerblue: '#1e90ff',
firebrick: '#b22222',
floralwhite: '#fffaf0',
forestgreen: '#228b22',
fuchsia: '#ff00ff',
gainsboro: '#dcdcdc',
ghostwhite: '#f8f8ff',
goldenrod: '#daa520',
gold: '#ffd700',
gray: '#808080',
green: '#008000',
greenyellow: '#adff2f',
grey: '#808080',
honeydew: '#f0fff0',
hotpink: '#ff69b4',
indianred: '#cd5c5c',
indigo: '#4b0082',
ivory: '#fffff0',
khaki: '#f0e68c',
lavenderblush: '#fff0f5',
lavender: '#e6e6fa',
lawngreen: '#7cfc00',
lemonchiffon: '#fffacd',
lightblue: '#add8e6',
lightcoral: '#f08080',
lightcyan: '#e0ffff',
lightgoldenrodyellow: '#fafad2',
lightgray: '#d3d3d3',
lightgreen: '#90ee90',
lightgrey: '#d3d3d3',
lightpink: '#ffb6c1',
lightsalmon: '#ffa07a',
lightseagreen: '#20b2aa',
lightskyblue: '#87cefa',
lightslategray: '#778899',
lightslategrey: '#778899',
lightsteelblue: '#b0c4de',
lightyellow: '#ffffe0',
lime: '#00ff00',
limegreen: '#32cd32',
linen: '#faf0e6',
magenta: '#ff00ff',
maroon: '#800000',
mediumaquamarine: '#66cdaa',
mediumblue: '#0000cd',
mediumorchid: '#ba55d3',
mediumpurple: '#9370db',
mediumseagreen: '#3cb371',
mediumslateblue: '#7b68ee',
mediumspringgreen: '#00fa9a',
mediumturquoise: '#48d1cc',
mediumvioletred: '#c71585',
midnightblue: '#191970',
mintcream: '#f5fffa',
mistyrose: '#ffe4e1',
moccasin: '#ffe4b5',
navajowhite: '#ffdead',
navy: '#000080',
oldlace: '#fdf5e6',
olive: '#808000',
olivedrab: '#6b8e23',
orange: '#ffa500',
orangered: '#ff4500',
orchid: '#da70d6',
palegoldenrod: '#eee8aa',
palegreen: '#98fb98',
paleturquoise: '#afeeee',
palevioletred: '#db7093',
papayawhip: '#ffefd5',
peachpuff: '#ffdab9',
peru: '#cd853f',
pink: '#ffc0cb',
plum: '#dda0dd',
powderblue: '#b0e0e6',
purple: '#800080',
rebeccapurple: '#663399',
red: '#ff0000',
rosybrown: '#bc8f8f',
royalblue: '#4169e1',
saddlebrown: '#8b4513',
salmon: '#fa8072',
sandybrown: '#f4a460',
seagreen: '#2e8b57',
seashell: '#fff5ee',
sienna: '#a0522d',
silver: '#c0c0c0',
skyblue: '#87ceeb',
slateblue: '#6a5acd',
slategray: '#708090',
slategrey: '#708090',
snow: '#fffafa',
springgreen: '#00ff7f',
steelblue: '#4682b4',
tan: '#d2b48c',
teal: '#008080',
thistle: '#d8bfd8',
tomato: '#ff6347',
turquoise: '#40e0d0',
violet: '#ee82ee',
wheat: '#f5deb3',
white: '#ffffff',
whitesmoke: '#f5f5f5',
yellow: '#ffff00',
yellowgreen: '#9acd3',
} as const;
@@ -36,13 +36,13 @@ export function getA1Notation(row: number, column: number): string {
* @param {any} metadata - object with all the cell positions of the title of each attribute
* @returns {sheets_v4.Schema} - list of update requests
*/
export function cellRequestFromEvent(
export function cellRequenstFromEvent(
event: OntimeRundownEntry,
index: number,
worksheetId: number,
metadata,
): sheets_v4.Schema$Request {
const returnRows: sheets_v4.Schema$CellData[] = [];
const r: sheets_v4.Schema$CellData[] = [];
const tmp = Object.entries(metadata)
.filter(([_, value]) => value !== undefined)
.sort(([_a, a], [_b, b]) => a['col'] - b['col']) as [string, { col: number; row: number }][];
@@ -50,7 +50,7 @@ export function cellRequestFromEvent(
const titleCol = tmp[0][1].col;
for (const [index, e] of tmp.entries()) {
if (index !== 0) {
if (index != 0) {
const prevCol = tmp[index - 1][1].col;
const thisCol = e[1].col;
const diff = thisCol - prevCol;
@@ -64,25 +64,25 @@ export function cellRequestFromEvent(
tmp.forEach(([key, _]) => {
if (isOntimeEvent(event)) {
if (key === 'blank') {
returnRows.push({});
r.push({});
} else if (key === 'colour') {
returnRows.push({
r.push({
userEnteredValue: { stringValue: event.colour },
});
} else if (typeof event[key] === 'number') {
returnRows.push({
r.push({
userEnteredValue: { stringValue: millisToString(event[key], true) },
});
} else if (typeof event[key] === 'string') {
returnRows.push({
r.push({
userEnteredValue: { stringValue: event[key] },
});
} else if (typeof event[key] === 'boolean') {
returnRows.push({
r.push({
userEnteredValue: { stringValue: event[key] ? 'x' : '' },
});
} else {
returnRows.push({});
r.push({});
}
}
});
@@ -96,7 +96,7 @@ export function cellRequestFromEvent(
fields: 'userEnteredValue',
rows: [
{
values: returnRows,
values: r,
},
],
},
@@ -115,7 +115,7 @@ export function cellRequenstFromProjectData(
worksheetId: number,
metadata,
): sheets_v4.Schema$Request {
const returnRows: sheets_v4.Schema$RowData[] = [];
const r: sheets_v4.Schema$RowData[] = [];
const tmp = Object.entries(metadata)
.filter(([_, value]) => value !== undefined)
.sort(([_a, a], [_b, b]) => a['col'] - b['col']) as [string, { col: number; row: number }][];
@@ -139,9 +139,9 @@ export function cellRequenstFromProjectData(
}
tmp.forEach(([key, _]) => {
if (key == 'blank') {
returnRows.push({});
r.push({});
} else {
returnRows.push({
r.push({
values: [
{
userEnteredValue: { stringValue: projectData[key] },
@@ -159,7 +159,7 @@ export function cellRequenstFromProjectData(
columnIndex: minCol,
},
fields: 'userEnteredValue',
rows: returnRows,
rows: r,
},
};
}
+37 -39
View File
@@ -29,14 +29,13 @@ import {
parseAliases,
parseProject,
parseOsc,
parseHttp,
parseRundown,
parseSettings,
parseUserFields,
parseViewSettings,
parseGoogleSheet,
} from './parserFunctions.js';
import { parseExcelDate } from './time.js';
import { coerceBoolean } from './coerceType.js';
export const EXCEL_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
export const JSON_MIME = 'application/json';
@@ -51,9 +50,6 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
const projectMetadata = {};
const rundownMetadata = {};
const importMap: ExcelImportMap = { ...defaultExcelImportMap, ...options };
for (const [key, value] of Object.entries(importMap)) {
importMap[key] = value.toLocaleLowerCase();
}
const projectData: Partial<ProjectData> = {
title: '',
description: '',
@@ -125,123 +121,123 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
const handlers = {
[importMap.projectName]: (row: number, col: number) => {
projectTitleNext = true;
projectMetadata['title'] = { row, col };
projectMetadata['title'] = { row: row, col: col };
},
[importMap.projectDescription]: (row: number, col: number) => {
projectDescriptionNext = true;
projectMetadata['description'] = { row, col };
projectMetadata['description'] = { row: row, col: col };
},
[importMap.publicUrl]: (row: number, col: number) => {
publicUrlNext = true;
projectMetadata['publicUrl'] = { row, col };
projectMetadata['publicUrl'] = { row: row, col: col };
},
[importMap.publicInfo]: (row: number, col: number) => {
publicInfoNext = true;
projectMetadata['publicInfo'] = { row, col };
projectMetadata['publicInfo'] = { row: row, col: col };
},
[importMap.backstageUrl]: (row: number, col: number) => {
backstageUrlNext = true;
projectMetadata['backstageUrl'] = { row, col };
projectMetadata['backstageUrl'] = { row: row, col: col };
},
[importMap.backstageInfo]: (row: number, col: number) => {
backstageInfoNext = true;
projectMetadata['backstageInfo'] = { row, col };
projectMetadata['backstageInfo'] = { row: row, col: col };
},
[importMap.timeStart]: (row: number, col: number) => {
timeStartIndex = col;
rundownMetadata['timeStart'] = { row, col };
rundownMetadata['timeStart'] = { row: row, col: col };
},
[importMap.timeEnd]: (row: number, col: number) => {
timeEndIndex = col;
rundownMetadata['timeEnd'] = { row, col };
rundownMetadata['timeEnd'] = { row: row, col: col };
},
[importMap.duration]: (row: number, col: number) => {
durationIndex = col;
rundownMetadata['duration'] = { row, col };
rundownMetadata['duration'] = { row: row, col: col };
},
[importMap.cue]: (row: number, col: number) => {
cueIndex = col;
rundownMetadata['cue'] = { row, col };
rundownMetadata['cue'] = { row: row, col: col };
},
[importMap.title]: (row: number, col: number) => {
titleIndex = col;
rundownMetadata['title'] = { row, col };
rundownMetadata['title'] = { row: row, col: col };
},
[importMap.presenter]: (row: number, col: number) => {
presenterIndex = col;
rundownMetadata['presenter'] = { row, col };
rundownMetadata['presenter'] = { row: row, col: col };
},
[importMap.subtitle]: (row: number, col: number) => {
subtitleIndex = col;
rundownMetadata['subtitle'] = { row, col };
rundownMetadata['subtitle'] = { row: row, col: col };
},
[importMap.isPublic]: (row: number, col: number) => {
isPublicIndex = col;
rundownMetadata['isPublic'] = { row, col };
rundownMetadata['isPublic'] = { row: row, col: col };
},
[importMap.skip]: (row: number, col: number) => {
skipIndex = col;
rundownMetadata['skip'] = { row, col };
rundownMetadata['skip'] = { row: row, col: col };
},
[importMap.note]: (row: number, col: number) => {
notesIndex = col;
rundownMetadata['note'] = { row, col };
rundownMetadata['note'] = { row: row, col: col };
},
[importMap.colour]: (row: number, col: number) => {
colourIndex = col;
rundownMetadata['colour'] = { row, col };
rundownMetadata['colour'] = { row: row, col: col };
},
[importMap.endAction]: (row: number, col: number) => {
endActionIndex = col;
rundownMetadata['endAction'] = { row, col };
rundownMetadata['endAction'] = { row: row, col: col };
},
[importMap.timerType]: (row: number, col: number) => {
timerTypeIndex = col;
rundownMetadata['timerType'] = { row, col };
rundownMetadata['timerType'] = { row: row, col: col };
},
[importMap.user0]: (row: number, col: number) => {
user0Index = col;
rundownMetadata['user0'] = { row, col };
rundownMetadata['user0'] = { row: row, col: col };
},
[importMap.user1]: (row: number, col: number) => {
user1Index = col;
rundownMetadata['user1'] = { row, col };
rundownMetadata['user1'] = { row: row, col: col };
},
[importMap.user2]: (row: number, col: number) => {
user2Index = col;
rundownMetadata['user2'] = { row, col };
rundownMetadata['user2'] = { row: row, col: col };
},
[importMap.user3]: (row: number, col: number) => {
user3Index = col;
rundownMetadata['user3'] = { row, col };
rundownMetadata['user3'] = { row: row, col: col };
},
[importMap.user4]: (row: number, col: number) => {
user4Index = col;
rundownMetadata['user4'] = { row, col };
rundownMetadata['user4'] = { row: row, col: col };
},
[importMap.user5]: (row: number, col: number) => {
user5Index = col;
rundownMetadata['user5'] = { row, col };
rundownMetadata['user5'] = { row: row, col: col };
},
[importMap.user6]: (row: number, col: number) => {
user6Index = col;
rundownMetadata['user6'] = { row, col };
rundownMetadata['user6'] = { row: row, col: col };
},
[importMap.user7]: (row: number, col: number) => {
user7Index = col;
rundownMetadata['user7'] = { row, col };
rundownMetadata['user7'] = { row: row, col: col };
},
[importMap.user8]: (row: number, col: number) => {
user8Index = col;
rundownMetadata['user8'] = { row, col };
rundownMetadata['user8'] = { row: row, col: col };
},
[importMap.user9]: (row: number, col: number) => {
user9Index = col;
rundownMetadata['user9'] = { row, col };
rundownMetadata['user9'] = { row: row, col: col };
},
} as const;
@@ -280,9 +276,9 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
} else if (j === subtitleIndex) {
event.subtitle = makeString(column, '');
} else if (j === isPublicIndex) {
event.isPublic = column == 'x' ? true : coerceBoolean(column);
event.isPublic = Boolean(column);
} else if (j === skipIndex) {
event.skip = column == 'x' ? true : coerceBoolean(column);
event.skip = Boolean(column);
} else if (j === notesIndex) {
event.note = makeString(column, '');
} else if (j === endActionIndex) {
@@ -339,8 +335,8 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
version: '2.0.0',
},
userFields: customUserFields,
projectMetadata,
rundownMetadata,
projectMetadata: projectMetadata,
rundownMetadata: rundownMetadata,
};
};
@@ -372,7 +368,9 @@ export const parseJson = async (jsonData): Promise<DatabaseModel | null> => {
// Import OSC settings if any
returnData.osc = parseOsc(jsonData) ?? dbModel.osc;
// Import HTTP settings if any
returnData.http = parseHttp(jsonData) ?? dbModel.http;
// returnData.http = parseHttp(jsonData, enforce);
// Import GoogleSheet settings if any
returnData.googleSheet = parseGoogleSheet(jsonData, true);
return returnData as DatabaseModel;
};
+41 -67
View File
@@ -1,18 +1,16 @@
import { generateId } from 'ontime-utils';
import {
Alias,
GoogleSheet,
OntimeRundown,
HttpSettings,
OSCSettings,
OscSubscription,
OscSubscriptionOptions,
ProjectData,
Settings,
TimerLifeCycle,
UserFields,
ViewSettings,
OscSubscription,
HttpSubscription,
OscSubscriptionOptions,
HttpSubscriptionOptions,
} from 'ontime-types';
import { block as blockDef, delay as delayDef } from '../models/eventsDefinition.js';
@@ -162,12 +160,12 @@ export const parseViewSettings = (data): ViewSettings => {
};
/**
* Parses and validates OSC subscription cycle options
* Parses and validates subscription entry
* @param data
*/
export const validateOscSubscriptionCycle = (data: OscSubscriptionOptions[]): boolean => {
for (const subscriptionOption of data) {
if (typeof subscriptionOption.message !== 'string' || typeof subscriptionOption.enabled !== 'boolean') {
export const validateOscSubscriptionEntry = (data: OscSubscriptionOptions): boolean => {
for (const subscription in data) {
if (typeof data[subscription].message !== 'string' || typeof data[subscription].enabled !== 'boolean') {
return false;
}
}
@@ -175,23 +173,22 @@ export const validateOscSubscriptionCycle = (data: OscSubscriptionOptions[]): bo
};
/**
* Parses and validates OSC subscription object
* Parses and validates subscription object
* @param data
*/
export const validateOscSubscriptionObject = (data: OscSubscription): boolean => {
export const validateOscObject = (data: OscSubscription): boolean => {
if (!data) {
return false;
}
const timerKeys = Object.keys(TimerLifeCycle);
for (const key of timerKeys) {
// must contains all keys and be an array
if (!(key in data) || !Array.isArray(data[key])) {
return false;
}
const isValid = validateOscSubscriptionCycle(data[key]);
if (!isValid) {
return false;
for (const subscription of data[key]) {
if (typeof subscription.message !== 'string' || typeof subscription.enabled !== 'boolean') {
return false;
}
}
}
return true;
@@ -204,9 +201,8 @@ export const parseOsc = (data: { osc?: Partial<OSCSettings> }): OSCSettings => {
if ('osc' in data) {
console.log('Found OSC definition, importing...');
// TODO: this can be improved by only merging known keys
const loadedConfig = data.osc || {};
const validatedSubscriptions = validateOscSubscriptionObject(loadedConfig.subscriptions)
const validatedSubscriptions = validateOscObject(loadedConfig.subscriptions)
? loadedConfig.subscriptions
: dbModel.osc.subscriptions;
@@ -221,63 +217,20 @@ export const parseOsc = (data: { osc?: Partial<OSCSettings> }): OSCSettings => {
}
};
/**
* Parses and validates HTTP subscription cycle options
* @param data
*/
export const validateHttpSubscriptionCycle = (data: HttpSubscriptionOptions[]): boolean => {
for (const subscriptionOption of data) {
const isHttp = subscriptionOption.message?.startsWith('http://');
if (typeof subscriptionOption.message !== 'string' || !isHttp || typeof subscriptionOption.enabled !== 'boolean') {
return false;
}
}
return true;
};
/**
* Parses and validates HTTP subscription object
* @param data
*/
export const validateHttpSubscriptionObject = (data: HttpSubscription): boolean => {
if (!data) {
return false;
}
const timerKeys = Object.keys(TimerLifeCycle);
// must contains all keys and be an array
for (const key of timerKeys) {
if (!(key in data) || !Array.isArray(data[key])) {
return false;
}
const isValid = validateHttpSubscriptionCycle(data[key]);
if (!isValid) {
return false;
}
}
return true;
};
/**
* Parse Http portion of an entry
* @param {object} data - data object
* @param {boolean} enforce - whether to create a definition if one is missing
* @returns {object} - event object data
*/
export const parseHttp = (data: { http?: Partial<HttpSettings> }): HttpSettings => {
export const parseHttp = (data, enforce) => {
const newHttp = {};
if ('http' in data) {
console.log('Found HTTP definition, importing...');
// TODO: this can be improved by only merging known keys
const loadedConfig = data?.http || {};
const validatedSubscriptions = validateHttpSubscriptionObject(loadedConfig.subscriptions)
? loadedConfig.subscriptions
: dbModel.http.subscriptions;
return {
enabledOut: loadedConfig.enabledOut ?? dbModel.http.enabledOut,
subscriptions: validatedSubscriptions,
};
} else if (enforce) {
/* Not yet */
}
return newHttp;
};
/**
@@ -331,4 +284,25 @@ export const parseUserFields = (data): UserFields => {
}
}
return { ...newUserFields };
};
};
/**
* Parse Google Sheet portion of an entry
* @param {object} data - data object
* @param {boolean} enforce - whether to create a definition if one is missing
* @returns {object} - event object data
*/
export const parseGoogleSheet = (data, enforce) => {
const newSheet: GoogleSheet = {
id: '',
worksheet: '',
};
if ('googleSheet' in data) {
console.log('Found Google Sheet definition, importing...');
newSheet.id ??= data.googleSheet?.id;
newSheet.worksheet ??= data.googleSheet?.worksheet;
return newSheet;
} else if (enforce) {
return newSheet;
}
};
+260 -263
View File
@@ -1,120 +1,282 @@
import { sheets, sheets_v4 } from '@googleapis/sheets';
import { writeFile } from 'fs/promises';
import { readFileSync } from 'fs';
import { OAuth2Client } from 'google-auth-library';
import { readFile, writeFile } from 'fs/promises';
import { sheets, sheets_v4 } from '@googleapis/sheets';
import http from 'http';
import { DatabaseModel, LogOrigin } from 'ontime-types';
import { join } from 'path';
import { URL } from 'url';
import { logger } from '../classes/Logger.js';
import { DataProvider } from '../classes/data-provider/DataProvider.js';
import { getAppDataPath } from '../setup.js';
import { ensureDirectory } from './fileManagement.js';
import { cellRequestFromEvent, cellRequenstFromProjectData, getA1Notation } from './sheetUtils.js';
import { DatabaseModel, LogOrigin } from 'ontime-types';
import { parseExcel } from './parser.js';
import { parseProject, parseRundown, parseUserFields } from './parserFunctions.js';
import { ExcelImportMap } from 'ontime-utils';
import { ensureDirectory } from './fileManagement.js';
import { DataProvider } from '../classes/data-provider/DataProvider.js';
import { GoogleSheetState } from 'ontime-types';
import { cellRequenstFromEvent, cellRequenstFromProjectData, getA1Notation } from './googleSheetUtils.js';
type ResponseOK = {
data: Partial<DatabaseModel>;
};
class Sheet {
class sheet {
private static client: null | OAuth2Client = null;
private readonly scope = 'https://www.googleapis.com/auth/spreadsheets';
private readonly sheetsFolder: string;
private readonly clientSecretFile: string;
private static clientSecret = null;
private readonly sheetsFolder = `${getAppDataPath()}/sheets`;
private readonly client_secret = `${this.sheetsFolder}/client_secret.json`;
private static authUrl: null | string = null;
private authServerTimeout;
private worksheetId: number = 0;
private sheetId: string = '';
private range: string = '';
private readonly requiredClientKeys = [
'client_id',
'project_id',
'auth_uri',
'token_uri',
'auth_provider_x509_cert_url',
'client_secret',
'redirect_uris',
];
constructor() {
const appDataPath = getAppDataPath();
if (appDataPath === '') {
throw new Error('Sheet: Could not resolve sheet folser');
public async getSheetState(): Promise<GoogleSheetState> {
const ret: GoogleSheetState = {
auth: false,
id: false,
worksheet: false,
};
this.sheetId = '';
this.worksheetId = 0;
if (!sheet.client) {
return ret;
}
this.sheetsFolder = join(appDataPath, 'sheets');
this.clientSecretFile = join(this.sheetsFolder, 'client_secret.json');
ensureDirectory(this.sheetsFolder);
try {
const secrets = JSON.parse(readFileSync(this.clientSecretFile, 'utf-8'));
const isKeyMissing = this.requiredClientKeys.some((key) => !(key in secrets['installed']));
if (!isKeyMissing) {
Sheet.clientSecret = secrets;
ret.auth = await this.refreshToken();
if (ret.auth) {
const settings = DataProvider.getGoogleSheet();
const x = await this.exist(settings.id, settings.worksheet);
if (x === true) {
ret.id = true;
this.sheetId = settings.id;
} else if (x !== false) {
ret.id = true;
ret.worksheet = true;
this.sheetId = settings.id;
this.worksheetId = x.worksheetId;
this.range = x.range;
}
}
} catch (_) {
/* empty - it is ok thet there is no clientSecret */
} catch (err) {
logger.error(LogOrigin.Server, `Google Sheet: Faild to refresh token ${err}`);
}
return ret;
}
/**
* test existence of sheet and worksheet
* @param {string} sheetId - https://docs.google.com/spreadsheets/d/[[spreadsheetId]]/edit#gid=0
* @param {string} worksheet - the name of the worksheet containing ontime data
* @returns {Promise<false | {worksheetId: number, range: string}>} - false if not found | true if sheetId existes | id of worksheet and rage of worksheet
* @throws
*/
private async exist(
sheetId: string,
worksheet: string,
): Promise<false | true | { worksheetId: number; range: string }> {
const spreadsheets = await sheets({ version: 'v4', auth: sheet.client }).spreadsheets.get({
spreadsheetId: sheetId,
});
if (spreadsheets.status === 200) {
const w = spreadsheets.data.sheets.find((p) => p.properties.title == worksheet);
if (w !== undefined) {
const endCell = getA1Notation(w.properties.gridProperties.rowCount, w.properties.gridProperties.columnCount);
return { worksheetId: w.properties.sheetId, range: `${worksheet}!A1:${endCell}` };
} else {
return true;
}
}
return false;
}
/**
* push sheet
* @throws
*/
public async push() {
const { auth, id, worksheet } = await this.getSheetState();
if (!auth && !id && !worksheet) {
throw new Error(`Sheet not authorized or incorrect ID or worksheet`);
}
const rq = await sheets({ version: 'v4', auth: sheet.client }).spreadsheets.values.get({
spreadsheetId: this.sheetId,
valueRenderOption: 'FORMATTED_VALUE',
majorDimension: 'ROWS',
range: this.range,
});
if (rq.status === 200) {
const { rundownMetadata, projectMetadata } = parseExcel(rq.data.values);
const rundown = DataProvider.getRundown();
const projectData = DataProvider.getProjectData();
const titleRow = Object.values(rundownMetadata)[0]['row'];
const updateRundown = Array<sheets_v4.Schema$Request>();
// we can't delete the last unflozzen row so we create an empty one
updateRundown.push({
insertDimension: {
inheritFromBefore: false,
range: {
dimension: 'ROWS',
startIndex: titleRow + 1,
endIndex: titleRow + 2,
sheetId: this.worksheetId,
},
},
});
//and delete the rest
updateRundown.push({
deleteDimension: { range: { dimension: 'ROWS', startIndex: titleRow + 2, sheetId: this.worksheetId } },
});
// insert the lenght of the rundown
updateRundown.push({
insertDimension: {
inheritFromBefore: false,
range: {
dimension: 'ROWS',
startIndex: titleRow + 1,
endIndex: titleRow + rundown.length,
sheetId: this.worksheetId,
},
},
});
//update the corresponding row with event data
rundown.forEach((entry, index) =>
updateRundown.push(cellRequenstFromEvent(entry, index, this.worksheetId, rundownMetadata)),
);
//update project data
updateRundown.push(cellRequenstFromProjectData(projectData, this.worksheetId, projectMetadata));
const writeResponds = await sheets({ version: 'v4', auth: sheet.client }).spreadsheets.batchUpdate({
spreadsheetId: this.sheetId,
requestBody: {
includeSpreadsheetInResponse: false,
responseRanges: [this.range],
requests: updateRundown,
},
});
if (writeResponds.status == 200) {
logger.info(LogOrigin.Server, `Sheet write: ${writeResponds.statusText}`);
} else {
throw new Error(`Sheet write faild: ${writeResponds.statusText}`);
}
} else {
throw new Error(`Sheet read faild: ${rq.statusText}`);
}
}
/**
* @description SETP 1 - saves secrets object to appdata path as client_secret.json
* pull sheet
* @returns {Promise<Partial<ResponseOK>>}
* @throws
*/
public async pull(): Promise<Partial<ResponseOK>> {
const { auth, id, worksheet } = await this.getSheetState();
if (!auth && !id && !worksheet) {
throw new Error(`Sheet not authorized or incorrect ID or worksheet`);
}
const res: Partial<ResponseOK> = {};
const rq = await sheets({ version: 'v4', auth: sheet.client }).spreadsheets.values.get({
spreadsheetId: this.sheetId,
valueRenderOption: 'FORMATTED_VALUE',
majorDimension: 'ROWS',
range: this.range,
});
if (rq.status === 200) {
res.data = {};
const dataFromSheet = parseExcel(rq.data.values);
res.data.rundown = parseRundown(dataFromSheet);
if (res.data.rundown.length < 1) {
throw new Error(`Could not find data to import in the worksheet`);
}
res.data.project = parseProject(dataFromSheet);
res.data.userFields = parseUserFields(dataFromSheet);
return res;
} else {
throw new Error(`Sheet read faild: ${rq.statusText}`);
}
}
/**
* saves secrets object to appdata path as client_secret.json
* @param {object} secrets
* @throws
*/
public async saveClientSecrets(secrets: object) {
Sheet.client = null;
Sheet.authUrl = null;
Sheet.clientSecret = null;
const isKeyMissing = this.requiredClientKeys.some((key) => !(key in secrets['installed']));
if (isKeyMissing) {
throw new Error('Client file is missing some keys');
sheet.client = null;
sheet.authUrl = null;
ensureDirectory(this.sheetsFolder);
if (
'client_id' in secrets ||
!('project_id' in secrets) ||
!('auth_uri' in secrets) ||
!('token_uri' in secrets) ||
!('auth_provider_x509_cert_url' in secrets) ||
!('client_secret' in secrets) ||
!('redirect_uris' in secrets)
) {
throw new Error('Sheet slient secret is missing some keys');
}
await writeFile(this.clientSecretFile, JSON.stringify(secrets), 'utf-8').catch((err) => {
throw new Error(`Unable to save client file to disk ${err}`);
});
Sheet.clientSecret = secrets;
await writeFile(this.client_secret, JSON.stringify(secrets), 'utf-8');
}
/**
* @description SETP 1 - test that the saved object is pressent
* refresh the client token
* @returns {Promise<boolean>}
*/
testClientSecret() {
return Sheet.clientSecret !== null;
async refreshToken(): Promise<boolean> {
if (!sheet.client?.credentials?.refresh_token) return false;
try {
const response = await sheet.client.refreshAccessToken();
if (response?.credentials) {
return true;
}
} catch (_) {
logger.info(LogOrigin.Server, 'Sheets token expired');
}
return false;
}
private authServerTimeout;
/**
* @description SETP 2 - create server to interact with th OAuth2 request
* @returns {Promise<string | null>} - returns url path serve on success
* create local Auth Server
* @returns {Promise<string | false>} - returns url to serve on success
* @throws
*/
async openAuthServer(): Promise<string | null> {
public async openAuthServer(): Promise<string | false> {
//TODO: this only works on local networks
// if the server is allready running retun it
if (Sheet.authUrl) {
if (sheet.authUrl) {
clearTimeout(this.authServerTimeout);
this.authServerTimeout = setTimeout(
() => {
Sheet.authUrl = null;
sheet.authUrl = null;
server.unref;
},
2 * 60 * 1000,
);
return Sheet.authUrl;
return sheet.authUrl;
}
// Check that Secret is valid
const keyFile = Sheet.clientSecret;
const creadFile = await readFile(this.client_secret, 'utf-8').catch((err) =>
logger.error(LogOrigin.Server, `${err}`),
);
if (!creadFile) {
return false;
}
const keyFile = JSON.parse(creadFile);
const keys = keyFile.installed || keyFile.web;
if (!keys.redirect_uris || keys.redirect_uris.length === 0) {
throw new Error('Sheet: Missing redirect URI');
logger.error(LogOrigin.Server, `${invalidRedirectUri}`);
return false;
}
// create an oAuth client to authorize the API call
const redirectUri = new URL(keys.redirect_uris[0]);
if (redirectUri.hostname !== 'localhost') {
throw new Error('Sheet: Invalid redirect URI');
throw new Error(invalidRedirectUri);
}
// create an oAuth client to authorize the API call
@@ -123,7 +285,6 @@ class Sheet {
clientSecret: keys.client_secret,
});
// start the server that will recive the codes
const server = http.createServer(async (req, res) => {
try {
const serverUrl = new URL(req.url, 'http://localhost:3000');
@@ -144,11 +305,11 @@ class Sheet {
}
const code = searchParams.get('code');
const { tokens } = await client.getToken({
code,
code: code,
redirect_uri: redirectUri.toString(),
});
client.credentials = tokens;
Sheet.client = client;
sheet.client = client;
res.end('Authentication successful! Please close this tab and return to OnTime.');
logger.info(LogOrigin.Server, `Sheet: Authentication successful`);
} catch (e) {
@@ -165,7 +326,7 @@ class Sheet {
listenPort = Number(redirectUri.port);
}
//TODO: the server might not start correctly
server.listen(listenPort);
server.listen(listenPort, () => {});
const address = server.address();
if (typeof address !== 'string') {
redirectUri.port = String(address.port);
@@ -176,205 +337,41 @@ class Sheet {
access_type: 'offline',
scope: this.scope,
});
Sheet.authUrl = authorizeUrl;
sheet.authUrl = authorizeUrl;
this.authServerTimeout = setTimeout(
() => {
Sheet.authUrl = null;
server.unref();
sheet.authUrl = null;
server.unref;
},
2 * 60 * 1000,
);
return authorizeUrl;
}
/**
* @description SETP 2 - test that the reciveed OAuth2 is still valid
* @throws
*/
async testAuthentication() {
if (Sheet.client) {
const ref = await Sheet.client.refreshAccessToken();
if (ref.credentials.expiry_date > 10000) {
return true;
} else {
throw new Error('Unable to use access token');
}
} else {
throw new Error('Unable to authenticate');
}
}
/**
* @description SETP 3 - test the given sheet id
* @throws
*/
async testSheetId(id: string) {
const spreadsheets = await sheets({ version: 'v4', auth: Sheet.client }).spreadsheets.get({
spreadsheetId: id,
includeGridData: false,
});
if (spreadsheets.status != 200) {
throw new Error(spreadsheets.statusText);
}
return { worksheetOptions: spreadsheets.data.sheets.map((i) => i.properties.title) };
}
/**
* @description SETP 4 - test the given worksheet
* @throws
*/
async testWorksheet(id: string, worksheet: string) {
const spreadsheets = await sheets({ version: 'v4', auth: Sheet.client }).spreadsheets.get({
spreadsheetId: id,
includeGridData: false,
});
if (spreadsheets.status != 200) {
throw new Error(spreadsheets.statusText);
}
const worksheetExist = spreadsheets.data.sheets.find((i) => i.properties.title === worksheet);
if (!worksheetExist) {
throw new Error('Unable to find worksheet');
}
}
/**
* test existence of sheet and worksheet
* @param {string} sheetId - https://docs.google.com/spreadsheets/d/[[spreadsheetId]]/edit#gid=0
* @param {string} worksheet - the name of the worksheet containing ontime data
* @returns {Promise<{worksheetId: number, range: string}>} - id of worksheet and rage of worksheet
* @throws
*/
private async exist(sheetId: string, worksheet: string): Promise<{ worksheetId: number; range: string }> {
const spreadsheets = await sheets({ version: 'v4', auth: Sheet.client }).spreadsheets.get({
spreadsheetId: sheetId,
});
if (spreadsheets.status === 200) {
const ourWorksheetData = spreadsheets.data.sheets.find((n) => n.properties.title == worksheet);
if (ourWorksheetData !== undefined) {
const endCell = getA1Notation(
ourWorksheetData.properties.gridProperties.rowCount,
ourWorksheetData.properties.gridProperties.columnCount,
);
return { worksheetId: ourWorksheetData.properties.sheetId, range: `${worksheet}!A1:${endCell}` };
}
} else {
throw new Error('Uable to open spreadsheets');
}
}
/**
* @description SETP 5 - Upload the rundown to sheet
* @param {string} id - id of the sheet https://docs.google.com/spreadsheets/d/[[spreadsheetId]]/edit#gid=0
* @param {ExcelImportMap} options
* @throws
*/
public async push(id: string, options: ExcelImportMap) {
const { worksheetId, range } = await this.exist(id, options.worksheet);
const readResponse = await sheets({ version: 'v4', auth: Sheet.client }).spreadsheets.values.get({
spreadsheetId: id,
valueRenderOption: 'FORMATTED_VALUE',
majorDimension: 'ROWS',
range: range,
});
if (readResponse.status === 200) {
const { rundownMetadata, projectMetadata } = parseExcel(readResponse.data.values, options);
const rundown = DataProvider.getRundown();
const projectData = DataProvider.getProjectData();
const titleRow = Object.values(rundownMetadata)[0]['row'];
const updateRundown = Array<sheets_v4.Schema$Request>();
// we can't delete the last unflozzen row so we create an empty one
updateRundown.push({
insertDimension: {
inheritFromBefore: false,
range: {
dimension: 'ROWS',
startIndex: titleRow + 1,
endIndex: titleRow + 2,
sheetId: worksheetId,
},
},
});
//and delete the rest
updateRundown.push({
deleteDimension: { range: { dimension: 'ROWS', startIndex: titleRow + 2, sheetId: worksheetId } },
});
// insert the lenght of the rundown
updateRundown.push({
insertDimension: {
inheritFromBefore: false,
range: {
dimension: 'ROWS',
startIndex: titleRow + 1,
endIndex: titleRow + rundown.length,
sheetId: worksheetId,
},
},
});
//update the corresponding row with event data
rundown.forEach((entry, index) =>
updateRundown.push(cellRequestFromEvent(entry, index, worksheetId, rundownMetadata)),
);
//update project data
updateRundown.push(cellRequenstFromProjectData(projectData, worksheetId, projectMetadata));
const writeResponse = await sheets({ version: 'v4', auth: Sheet.client }).spreadsheets.batchUpdate({
spreadsheetId: id,
requestBody: {
includeSpreadsheetInResponse: false,
responseRanges: [range],
requests: updateRundown,
},
});
if (writeResponse.status === 200) {
logger.info(LogOrigin.Server, `Sheet: write: ${writeResponse.statusText}`);
} else {
throw new Error(`Sheet: write failed: ${writeResponse.statusText}`);
}
} else {
throw new Error(`Sheet: read failed: ${readResponse.statusText}`);
}
}
/**
* @description STEP 5 - Downpload the rundown from sheet
* @param {string} id - id of the sheet https://docs.google.com/spreadsheets/d/[[spreadsheetId]]/edit#gid=0
* @param {ExcelImportMap} options
* @returns {Promise<Partial<ResponseOK>>}
* @throws
*/
public async pull(id: string, options: ExcelImportMap): Promise<Partial<ResponseOK>> {
const { range } = await this.exist(id, options.worksheet);
const res: Partial<ResponseOK> = {};
const googleResponse = await sheets({ version: 'v4', auth: Sheet.client }).spreadsheets.values.get({
spreadsheetId: id,
valueRenderOption: 'FORMATTED_VALUE',
majorDimension: 'ROWS',
range,
});
if (googleResponse.status === 200) {
res.data = {};
const dataFromSheet = parseExcel(googleResponse.data.values, options);
res.data.rundown = parseRundown(dataFromSheet);
if (res.data.rundown.length < 1) {
throw new Error(`Sheet: Could not find data to import in the worksheet`);
}
res.data.project = parseProject(dataFromSheet);
res.data.userFields = parseUserFields(dataFromSheet);
return res;
} else {
throw new Error(`Sheet: read failed: ${googleResponse.statusText}`);
}
}
}
export const sheet = new Sheet();
// Copyright 2020 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//TODO: add modification notifications as requrirde by the license
const invalidRedirectUri = `The provided keyfile does not define a valid
redirect URI. There must be at least one redirect URI defined, and this sample
assumes it redirects to 'http://localhost:3000/oauth2callback'. Please edit
your keyfile, and add a 'redirect_uris' section. For example:
"redirect_uris": [
"http://localhost:3000/oauth2callback"
]
`;
export const Sheet = new sheet();
-11
View File
@@ -259,17 +259,6 @@
"targetIP": "127.0.0.1",
"enabled": true
},
"http": {
"enabledOut": false,
"subscriptions": {
"onLoad": [],
"onStart": [],
"onPause": [],
"onStop": [],
"onUpdate": [],
"onFinish": []
}
},
"aliases": [
{
"enabled": true,
+7 -18
View File
@@ -29,8 +29,8 @@
"user9": "",
"type": "event",
"revision": 0,
"cue": "1",
"id": "aa42f"
"id": "aa42f",
"cue": "1"
},
{
"title": "title 2",
@@ -57,8 +57,8 @@
"user9": "",
"type": "event",
"revision": 0,
"cue": "2",
"id": "d71bc"
"id": "d71bc",
"cue": "2"
},
{
"title": "title 3",
@@ -85,8 +85,8 @@
"user9": "",
"type": "event",
"revision": 0,
"cue": "3",
"id": "da5b4"
"id": "da5b4",
"cue": "3"
}
],
"project": {
@@ -99,7 +99,7 @@
},
"settings": {
"app": "ontime",
"version": "2.24.8",
"version": "2.0.0",
"serverPort": 4001,
"editorKey": null,
"operatorKey": null,
@@ -148,16 +148,5 @@
"onUpdate": [],
"onFinish": []
}
},
"http": {
"enabledOut": true,
"subscriptions": {
"onLoad": [],
"onStart": [],
"onPause": [],
"onStop": [],
"onUpdate": [],
"onFinish": []
}
}
}
-11
View File
@@ -468,16 +468,5 @@
],
"onFinish": []
}
},
"http": {
"enabledOut": true,
"subscriptions": {
"onLoad": [],
"onStart": [],
"onPause": [],
"onStop": [],
"onUpdate": [],
"onFinish": []
}
}
}

Some files were not shown because too many files have changed in this diff Show More