Compare commits

..

40 Commits

Author SHA1 Message Date
arc-alex 1164975c91 missing retryCount in httpPlaceholder 2023-12-08 17:14:03 +01:00
arc-alex f133aebfe8 Revert "split url and searchParams allow for post option"
This reverts commit 54ab8d4ffe.
2023-12-06 21:24:09 +01:00
arc-alex 2a1b5d4de8 Revert "add options to post"
This reverts commit 0523a68ef4.
2023-12-06 21:12:52 +01:00
arc-alex 47232095bb Revert "fix test"
This reverts commit 927e88370f.
2023-12-06 21:12:07 +01:00
arc-alex 927e88370f fix test 2023-12-06 20:32:38 +01:00
arc-alex d0191ebc26 add retry count 2023-12-05 21:28:37 +01:00
arc-alex 0523a68ef4 add options to post 2023-12-05 17:55:51 +01:00
arc-alex 54ab8d4ffe split url and searchParams allow for post option 2023-12-05 17:46:44 +01:00
arc-alex 7f095f0f06 allow https 2023-12-04 17:05:07 +01:00
arc-alex 2a3c7f28ff try GOT 2023-12-04 17:03:46 +01:00
arc-alex 23bfc0787f cleanup 2023-12-04 14:11:19 +01:00
Carlos Valente 8169ea724c cleanup 2023-12-01 13:13:15 +01:00
Carlos Valente efcd6494be refactor: validation 2023-12-01 13:08:05 +01:00
Carlos Valente f720c56345 refactor: subscription types and form register 2023-11-30 22:28:55 +01:00
arc-alex 52a61777ed register/unregister http 2023-11-29 11:29:04 +01:00
arc-alex dfd38c91f6 Merge remote-tracking branch 'org/master' into feat/http-integration 2023-11-29 11:17:13 +01:00
arc-alex e5f6e5afb9 disable HTTP integration if enabledOut==false 2023-11-23 14:27:00 +01:00
Carlos Valente 04f7b342c9 wip: temporary fix to get form to work 2023-11-22 22:41:12 +01:00
Carlos Valente cdca5eaad3 wip: prepare endpoints 2023-11-22 22:30:31 +01:00
Carlos Valente f39c8b46bb Merge remote-tracking branch 'origin/master' into feat/http-integration 2023-11-22 21:40:13 +01:00
arc-alex c30b0cbf0a fix httpPlaceholder 2023-11-19 21:28:29 +01:00
arc-alex 95bb9b4366 lint 2023-11-19 21:08:32 +01:00
arc-alex 2dd872eb2d fix merge 2023-11-19 21:05:52 +01:00
arc-alex c0f9521f86 Merge branch 'master' into feat/http-integration 2023-11-19 21:05:31 +01:00
arc-alex 5577fc0505 lint 2023-11-09 10:55:03 +01:00
arc-alex b77d74a37e import not needed yet 2023-11-08 12:35:18 +01:00
arc-alex 42c92329a0 test for http protocol 2023-11-08 12:20:37 +01:00
arc-alex b9dbda072d add todo in UI 2023-11-08 12:07:34 +01:00
arc-alex a670913320 simplify retun path 2023-11-08 10:48:09 +01:00
arc-alex de93827e40 reuse agent and test url compatibility 2023-11-05 21:26:25 +01:00
arc-alex 2b2c092d99 Revert "addtime endpoint"
This reverts commit 4c039220dc.
2023-11-05 17:06:27 +01:00
arc-alex 858aee83ac remove log 2023-11-05 13:06:17 +01:00
arc-alex 1e930851ca add http subscription to integration modal 2023-11-04 20:37:22 +01:00
arc-alex 477fbbe666 make subscription part of modal generic 2023-11-04 20:36:19 +01:00
arc-alex 4c38207a15 add necessary endpoint for http subscription 2023-11-04 20:34:08 +01:00
arc-alex 2b87f72acb unify osc and http validateSubscriptionEntry 2023-11-04 20:32:30 +01:00
arc-alex 563ea92a3b catch error from HTTP integration emit 2023-11-04 20:30:26 +01:00
arc-alex 7a5bc76a9e add http integration 2023-11-03 23:28:18 +01:00
arc-alex 89c7f8707b create universal Subscription 2023-11-03 23:25:20 +01:00
arc-alex 4c039220dc addtime endpoint 2023-11-03 16:15:42 +01:00
87 changed files with 464 additions and 3181 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.17",
"version": "2.21.3",
"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",
@@ -9,7 +9,6 @@ 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';
-73
View File
@@ -245,76 +245,3 @@ export async function getLatestVersion(): Promise<HasUpdate> {
export async function postNew(initialData: Partial<ProjectData>) {
return axios.post(`${ontimeURL}/new`, initialData);
}
/**
* @description STEP 1
*/
export const uploadSheetClientFile = async (file: File) => {
const formData = new FormData();
formData.append('userFile', file);
const res = await axios
.post(`${ontimeURL}/sheet/clientsecret`, 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;
};
/**
* @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 });
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 });
return response.data.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);
@@ -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;
@@ -22,7 +22,7 @@ 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);
@@ -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}>
@@ -380,12 +380,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,
},
];
};
@@ -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);
},
};
+1
View File
@@ -2,6 +2,7 @@ import { HttpSettings } from 'ontime-types';
export const httpPlaceholder: HttpSettings = {
enabledOut: false,
retryCount: 0,
subscriptions: {
onLoad: [],
onStart: [],
@@ -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,4 @@
export const isOnlyNumbers = /^\d+$/;
export const isIPAddress = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/;
export const startsWithHttp = /^http:\/\//;
export const startsWithHttpOrS = /^https?:\/\//;
+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}
@@ -5,7 +5,6 @@ import ErrorBoundary from '../../common/components/error-boundary/ErrorBoundary'
import MenuBar from '../menu/MenuBar';
import AboutModal from '../modals/about-modal/AboutModal';
import QuickStart from '../modals/quick-start/QuickStart';
import SheetsModal from '../modals/sheets-modal/SheetsModal';
import UploadModal from '../modals/upload-modal/UploadModal';
import styles from './Editor.module.scss';
@@ -29,7 +28,6 @@ export default function Editor() {
} = useDisclosure();
const { isOpen: isAboutModalOpen, onOpen: onAboutModalOpen, onClose: onAboutModalClose } = useDisclosure();
const { isOpen: isQuickStartOpen, onOpen: onQuickStartOpen, onClose: onQuickStartClose } = useDisclosure();
const { isOpen: isSheetsOpen, onOpen: onSheetsOpen, onClose: onSheetsClose } = useDisclosure();
// Set window title
useEffect(() => {
@@ -44,7 +42,6 @@ export default function Editor() {
<IntegrationModal onClose={onIntegrationModalClose} isOpen={isIntegrationModalOpen} />
<AboutModal onClose={onAboutModalClose} isOpen={isAboutModalOpen} />
<SettingsModal isOpen={isSettingsOpen} onClose={onSettingsClose} />
<SheetsModal onClose={onSheetsClose} isOpen={isSheetsOpen} />
</ErrorBoundary>
<div className={styles.mainContainer} data-testid='event-editor'>
<div id='settings' className={styles.settings}>
@@ -61,8 +58,6 @@ export default function Editor() {
onAboutOpen={onAboutModalOpen}
isQuickStartOpen={isQuickStartOpen}
onQuickStartOpen={onQuickStartOpen}
isSheetsOpen={isSheetsOpen}
onSheetsOpen={onSheetsOpen}
/>
</ErrorBoundary>
</div>
@@ -1,12 +1,13 @@
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, dayInMs, millisToString } from 'ontime-utils';
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 { cx } from '../../../common/utils/styleUtils';
import { TimeEntryField, validateEntry } from '../../../common/utils/timesManager';
import style from '../EventEditor.module.scss';
@@ -28,13 +29,21 @@ 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 };
switch (field) {
case 'durationOverride': {
// duration defines timeEnd
newEventData.duration = value as number;
newEventData.timeEnd = timeStart + ((value as number) % dayInMs);
newEventData.timeEnd = timeStart + (value as number);
break;
}
case 'timeStart': {
@@ -78,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}
@@ -89,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
@@ -100,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}>
-16
View File
@@ -1,7 +1,5 @@
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 { 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';
@@ -33,8 +31,6 @@ interface MenuBarProps {
onAboutOpen: () => void;
isQuickStartOpen: boolean;
onQuickStartOpen: () => void;
isSheetsOpen: boolean;
onSheetsOpen: () => void;
}
const buttonStyle = {
@@ -62,8 +58,6 @@ const MenuBar = (props: MenuBarProps) => {
onAboutOpen,
isQuickStartOpen,
onQuickStartOpen,
isSheetsOpen,
onSheetsOpen,
} = props;
const { isElectron, sendToElectron } = useElectronEvent();
@@ -180,16 +174,6 @@ const MenuBar = (props: MenuBarProps) => {
/>
<div className={style.gap} />
<TooltipActionBtn
{...buttonStyle}
isDisabled={appMode === AppMode.Run}
icon={isSheetsOpen ? <IoCloud /> : <IoCloudOutline />}
className={isSheetsOpen ? style.open : ''}
clickHandler={onSheetsOpen}
tooltip='Sheets'
aria-label='Sheets'
size='sm'
/>
<TooltipActionBtn
{...buttonStyle}
isDisabled={appMode === AppMode.Run}
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { Switch } from '@chakra-ui/react';
import { Input, Switch } from '@chakra-ui/react';
import type { HttpSettings } from 'ontime-types';
import { TimerLifeCycle } from 'ontime-types';
@@ -49,6 +49,7 @@ export default function HttpIntegration() {
try {
const newSettings: HttpSettings = {
enabledOut: Boolean(values.enabledOut),
retryCount: 0,
subscriptions: {
onLoad: values.subscriptions.onLoad ?? [],
onStart: values.subscriptions.onStart ?? [],
@@ -79,6 +80,13 @@ export default function HttpIntegration() {
</div>
<Switch {...register('enabledOut')} variant='ontime-on-light' />
</div>
<div className={styles.splitSection}>
<div>
<span className={`${styles.sectionTitle} ${styles.main}`}>Retry count</span>
<span className={styles.sectionSubtitle}>How many times should the connection be retried</span>
</div>
<Input size='xs' variant='ontime-filled-on-light' autoComplete='off' {...register('retryCount')} />
</div>
<HttpSubscriptionRow
cycle={TimerLifeCycle.onLoad}
@@ -5,7 +5,7 @@ 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 { startsWithHttpOrS } from '../../../../common/utils/regex';
import collapseStyles from '../../../../common/components/collapse-bar/CollapseBar.module.scss';
import styles from '../../Modal.module.scss';
@@ -71,7 +71,7 @@ export default function SubscriptionRow(props: SubscriptionRowProps) {
variant='ontime-filled-on-light'
autoComplete='off'
{...register(`subscriptions.${cycle}.${index}.message`, {
pattern: { value: startsWithHttp, message: 'Request address must start with http://' },
pattern: { value: startsWithHttpOrS, message: 'Request address must start with http://' },
})}
/>
<Switch variant='ontime-on-light' {...register(`subscriptions.${cycle}.${index}.enabled`)} />
@@ -1,3 +1,5 @@
// 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';
@@ -57,6 +59,7 @@ export default function OscSettings() {
};
const resetForm = () => {
// @ts-expect-error -- we know the types dont match
reset(data);
};
@@ -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,469 +0,0 @@
import { ChangeEvent, useEffect, useRef, useState } from 'react';
import {
Alert,
AlertDescription,
AlertIcon,
AlertTitle,
Button,
HStack,
Input,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
Select,
} from '@chakra-ui/react';
import { useQueryClient } from '@tanstack/react-query';
import { OntimeRundown, ProjectData, UserFields } from 'ontime-types';
import { defaultExcelImportMap, ExcelImportMap } from 'ontime-utils';
import { PROJECT_DATA, RUNDOWN, USERFIELDS } from '../../../common/api/apiConstants';
import { maybeAxiosError } from '../../../common/api/apiUtils';
import {
getAuthentication,
getClientSecrect,
getSheetsAuthUrl,
patchData,
postId,
postPreviewSheet,
postPushSheet,
postWorksheet,
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;
isOpen: boolean;
}
export default function SheetsModal(props: SheetsModalProps) {
const { isOpen, onClose } = props;
const queryClient = useQueryClient();
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 [direction, setDirection] = useState('none');
const excelFileOptions = useRef<ExcelImportMap>(defaultExcelImportMap);
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 handleClose = () => {
setRundown(null);
setProject(null);
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: '' },
});
return;
}
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: '' },
});
});
};
//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 };
}
};
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 } });
});
};
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 } });
});
};
//GET preview
const handleFinalise = async () => {
if (rundown && userFields && project) {
let doClose = false;
try {
await patchData({ rundown, userFields, project });
queryClient.setQueryData(RUNDOWN, rundown);
queryClient.setQueryData(USERFIELDS, userFields);
queryClient.setQueryData(PROJECT_DATA, project);
await queryClient.invalidateQueries({
queryKey: [...RUNDOWN, ...USERFIELDS, ...PROJECT_DATA],
});
doClose = true;
} catch (error) {
const message = maybeAxiosError(error);
console.error(message);
} finally {
if (doClose) {
handleClose();
}
}
}
};
return (
<Modal
onClose={handleClose}
isOpen={isOpen}
closeOnOverlayClick={false}
motionPreset='slideInBottom'
size='xl'
scrollBehavior='inside'
preserveScrollBarGap
variant='ontime-upload'
>
<ModalOverlay />
<ModalContent>
<ModalHeader>Rundown from sheets (experimental)</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}
/>
)}
</ModalBody>
<ModalFooter>
{rundown ? (
<div style={{ display: 'flex', gap: '1em' }}>
<Button
onClick={() => {
setRundown(null);
setDirection('none');
}}
variant='ontime-ghost-on-light'
>
Go Back
</Button>
<Button variant='ontime-filled' padding='0 2em' onClick={handleFinalise}>
Import
</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>
) : (
<></>
)}
</ModalFooter>
</ModalContent>
</Modal>
);
}
@@ -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>
);
}
@@ -123,10 +123,7 @@ 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] : '';
@@ -155,7 +152,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 +193,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, dayInMs, millisToString } from 'ontime-utils';
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,13 +24,15 @@ 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) {
case 'durationOverride': {
// duration defines timeEnd
newEventData.duration = value;
newEventData.timeEnd = timeStart + ((value as number) % dayInMs);
newEventData.timeEnd = timeStart + value;
break;
}
case 'timeStart': {
@@ -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}>
@@ -140,7 +140,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' />
@@ -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 && showWarning) timerColor = viewSettings.warningColor;
if (!timerIsTimeOfDay && showProgress && showDanger) timerColor = viewSettings.dangerColor;
const timerColor = userOptions.textColour
? userOptions.textColour
: showProgress && showDanger
? viewSettings.dangerColor
: showProgress && showWarning
? viewSettings.warningColor
: viewSettings.normalColor;
const stageTimer = getTimerByType(time);
let display = formatTimerDisplay(stageTimer);
@@ -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);
}
}
@@ -90,9 +90,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 +105,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 && showWarning) timerColor = viewSettings.warningColor;
if (!timerIsTimeOfDay && showProgress && showDanger) timerColor = viewSettings.dangerColor;
const timerColor =
showProgress && showDanger
? viewSettings.dangerColor
: showProgress && showWarning
? viewSettings.warningColor
: viewSettings.normalColor;
const stageTimer = getTimerByType(time);
let display = formatTimerDisplay(stageTimer);
@@ -171,7 +173,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.17",
"version": "2.21.3",
"author": "Carlos Valente",
"description": "Time keeping for live events",
"repository": "https://github.com/cpvalente/ontime",
+1 -4
View File
@@ -2,10 +2,9 @@
"name": "ontime-server",
"type": "module",
"main": "src/index.ts",
"version": "2.28.17",
"version": "2.21.3",
"exports": "./src/index.js",
"dependencies": {
"@googleapis/sheets": "^5.0.5",
"body-parser": "^1.20.0",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
@@ -14,7 +13,6 @@
"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",
"node-osc": "^9.0.2",
@@ -55,7 +53,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",
+2 -15
View File
@@ -8,14 +8,7 @@ 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
@@ -42,7 +35,6 @@ 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 +64,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());
@@ -138,7 +126,6 @@ export const initAssets = async () => {
checkStart(OntimeStartOrder.InitAssets);
await dbLoadingProcess;
populateStyles();
populateDemo();
};
/**
@@ -97,6 +97,7 @@ describe('safeMerge', () => {
language: 'pt',
});
});
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
@@ -2,6 +2,8 @@ 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';
import { isKeyOfType } from 'ontime-types/src/utils/guards.js';
import { event } from '../models/eventsDefinition.js';
export type ChangeOptions = {
eventId: string;
@@ -139,10 +141,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 +196,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 +210,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 +224,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 +238,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 +251,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;
}
@@ -259,8 +272,11 @@ export function dispatchFromAdapter(
// WS: {type: 'change', payload: { eventId, property, value } }
case 'change': {
const { eventId, property, value } = payload as ChangeOptions;
const { parsedPayload, parsedProperty } = parse(property, value);
return updateEvent(eventId, parsedProperty, parsedPayload);
if (!isKeyOfType(property, event)) {
throw new Error(`Cannot update unknown event property ${property}`);
}
const parsedPayload = parse(property, value);
return updateEvent(eventId, property, parsedPayload);
}
default: {
+2 -123
View File
@@ -10,7 +10,7 @@ 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';
@@ -20,8 +20,6 @@ import { runtimeCacheStore } from '../stores/cachingStore.js';
import { delayedRundownCacheKey } from '../services/rundown-service/delayedRundown.utils.js';
import { integrationService } from '../services/integration-service/IntegrationService.js';
import { sheet } from '../utils/sheetsAuth.js';
// Create controller for GET request to '/ontime/poll'
// Returns data for current state
export const poll = async (req, res) => {
@@ -119,7 +117,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({
@@ -457,122 +455,3 @@ export const postNew: RequestHandler = async (req, res) => {
res.status(400).send({ message: error.toString() });
}
};
//SHEET Functions
/**
* @description SETP-1 POST Client Secrect
* @returns parsed result
*/
export async function uploadSheetClientFile(req, res) {
if (!req.file.path) {
res.status(400).send({ message: 'File not found' });
return;
}
try {
const client = JSON.parse(fs.readFileSync(req.file.path as string, 'utf-8'));
await sheet.saveClientSecrets(client);
res.status(200).send('OK');
} catch (error) {
res.status(500).send({ message: error.toString() });
}
fs.unlink(req.file.path, (err) => {
if (err) logger.error(LogOrigin.Server, err.message);
});
}
/**
* @description SETP-1 GET Client Secrect status
*/
export const getClientSecrect = async (req, res) => {
try {
const clientSecrectExists = await sheet.testClientSecret();
if (clientSecrectExists) {
res.status(200).send();
} else {
res.status(500).send({ message: 'The Client ID does not exist' });
}
} catch (error) {
res.status(500).send({ message: error.toString() });
}
};
/**
* @description SETP-2 GET sheet authentication url
*/
export async function getAuthenticationUrl(req, res) {
try {
const authUrl = await sheet.openAuthServer();
res.status(200).send(authUrl);
} catch (error) {
res.status(500).send({ message: error.toString() });
}
}
/**
* @description SETP-2 GET sheet authentication status
*/
export const getAuthentication = async (req, res) => {
try {
await sheet.testAuthentication();
res.status(200).send();
} catch (error) {
res.status(500).send({ message: error.toString() });
}
};
/**
* @description SETP-3 POST sheet id
* @returns list of worksheets
*/
export const postId = async (req, res) => {
try {
const { id } = req.body;
if (id.lenght < 40) {
res.status(400).send({ message: 'ID is usualy 44 characters long' });
}
const state = await sheet.testSheetId(id);
res.status(200).send(state);
} catch (error) {
res.status(500).send({ message: error.toString() });
}
};
/**
* @description SETP-4 POST worksheet
*/
export const postWorksheet = async (req, res) => {
try {
const { worksheet, id } = req.body;
const state = await sheet.testWorksheet(worksheet, id);
res.status(200).send(state);
} catch (error) {
res.status(500).send({ message: error.toString() });
}
};
/**
* @description STEP-5 POST download undown to sheet
* @returns parsed result
*/
export async function pullSheet(req, res) {
try {
const { id, options } = req.body;
const data = await sheet.pull(id, options);
res.status(200).send(data);
} catch (error) {
res.status(500).send({ message: error.toString() });
}
}
/**
* @description STEP-5 POST upload rundown to sheet
*/
export async function pushSheet(req, res) {
try {
const { id, options } = req.body;
await sheet.push(id, options);
res.status(200).send();
} catch (error) {
res.status(500).send({ message: error.toString() });
}
}
@@ -152,32 +152,3 @@ export const validatePatchProjectFile = [
next();
},
];
export const validateSheetid = [
body('id').exists().isString(),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
next();
},
];
export const validateWorksheet = [
body('id').exists().isString(),
body('worksheet').exists().isString(),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
next();
},
];
export const validateSheetOptions = [
body('id').exists().isString(),
// body('options').exists().isObject(), TODO:
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() });
next();
},
];
-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;
}
+1
View File
@@ -59,6 +59,7 @@ export const dbModel: DatabaseModel = {
},
http: {
enabledOut: false,
retryCount: 0,
subscriptions: {
onLoad: [],
onStart: [],
-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;
};
-30
View File
@@ -21,13 +21,6 @@ import {
postViewSettings,
previewExcel,
postHTTP,
getAuthenticationUrl,
uploadSheetClientFile as uploadClientSecret,
pullSheet,
pushSheet,
postId,
getAuthentication,
getClientSecrect as getClientSecret,
} from '../controllers/ontimeController.js';
import {
@@ -39,9 +32,6 @@ import {
viewValidator,
validateHTTP,
validateOscSubscription,
validateSheetid,
validateWorksheet,
validateSheetOptions,
} from '../controllers/ontimeController.validate.js';
import { projectSanitiser } from '../controllers/projectController.validate.js';
@@ -106,23 +96,3 @@ router.post('/http', validateHTTP, postHTTP);
// create route between controller and '/ontime/new' endpoint
router.post('/new', projectSanitiser, postNew);
//SETP-1
router.post('/sheet/clientsecret', uploadFile, uploadClientSecret);
router.get('/sheet/clientsecret', uploadFile, getClientSecret);
//SETP-2
router.get('/sheet/authentication/url', getAuthenticationUrl);
router.get('/sheet/authentication', getAuthentication);
//STEP-3
router.post('/sheet/id', validateSheetid, postId);
//STEP-4
router.post('/sheet/worksheet', validateWorksheet, postId);
//STEP-5 download and generate preview
router.post('/sheet/pull', validateSheetOptions, pullSheet);
//STEP-5 upload
router.post('/sheet-push', validateSheetOptions, pushSheet);
+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 });
@@ -528,76 +528,6 @@ describe('test that roll behaviour multi day event edge cases', () => {
});
});
// test getRollTimers() on issue #757
describe('it handles timeEnd over day', () => {
it('ignores events with timeEnd larger than a day', () => {
const testRundown = [
{
title: 'Setup',
subtitle: '',
presenter: '',
note: 'BMA, Nebelfluid, Shooter, Akkus, UHF11, Getränke, Kaffee, Strom, ELA, Text für Holger',
endAction: 'play-next',
timerType: 'count-down',
timeStart: 66600000,
timeEnd: 68400000,
duration: 1800000,
isPublic: false,
skip: false,
colour: '#2fa9e5',
user0: '',
user1: '',
user2: '',
user3: '',
user4: '',
user5: '',
user6: '',
user7: '',
user8: '',
user9: '',
type: 'event',
revision: 0,
cue: 'PRE',
id: 'b2f8d',
},
{
title: 'Künstliche Intelligenz',
subtitle: ' -> Vorstellung Maske',
presenter: 'Engel und Teufel',
note: 'Melli Kleben! Sofa',
endAction: 'play-next',
timerType: 'count-down',
timeStart: 86100000,
// timeEnd: 1020000, <--- this would have been equivalent
timeEnd: 87420000,
duration: 1320000,
isPublic: true,
skip: false,
colour: '#a8ec31',
user0: 'UHF1 Melli (Korsett)',
user1: 'UHF2 Reinhold (unter Flügel)',
user2: 'UHF3 Oli (Sport-Unterhose Rechts)',
user3: '',
user4: '',
user5: '',
user6: '',
user7: '',
user8: '',
user9: '',
type: 'event',
revision: 0,
cue: '16',
id: '8b970',
},
];
const timeNow = 64488675; // 17:55-something
const timers = getRollTimers(testRundown as OntimeEvent[], timeNow);
expect(timers.currentEvent).toBeNull();
});
});
// test normaliseEndTime() on issue #58
test('test typical scenarios', () => {
const t1 = {
@@ -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);
});
});
@@ -15,8 +15,11 @@ type Action = TimerLifeCycleKey | string;
* @class
*/
export class HttpIntegration implements IIntegration<HttpSubscriptionOptions> {
// protected httpAgent: null | http.Agent;
subscriptions: HttpSubscription;
private retryCount = 0;
constructor() {
// this.httpAgent = null;
this.subscriptions = dbModel.http.subscriptions;
}
@@ -24,9 +27,12 @@ export class HttpIntegration implements IIntegration<HttpSubscriptionOptions> {
* Initializes httpClient
*/
init(config: HttpSettings) {
const { subscriptions, enabledOut } = config;
const { subscriptions, enabledOut, retryCount } = config;
this.retryCount = retryCount;
if (!enabledOut) {
// this.httpAgent?.destroy();
return {
success: false,
message: 'HTTP output disabled',
@@ -36,6 +42,9 @@ export class HttpIntegration implements IIntegration<HttpSubscriptionOptions> {
this.initSubscriptions(subscriptions);
try {
// this allows re-calling the init function during runtime
// this.httpAgent?.destroy();
// this.httpAgent = new http.Agent({ keepAlive: true, timeout: 2000 });
return {
success: true,
message: `HTTP integration client ready`,
@@ -55,6 +64,13 @@ export class HttpIntegration implements IIntegration<HttpSubscriptionOptions> {
}
dispatch(action: Action, state?: object) {
// if (!this.httpAgent) {
// return {
// success: false,
// message: 'Client not initialised',
// };
// }
if (!action) {
return {
success: false,
@@ -70,7 +86,14 @@ export class HttpIntegration implements IIntegration<HttpSubscriptionOptions> {
if (enabled && message) {
const parsedMessage = parseTemplateNested(message, state || {});
try {
const parsedUrl = new URL(parsedMessage);
const parsedUrl = new globalThis.URL(parsedMessage);
// if (parsedUrl.protocol != 'http:') {
// logger.error(LogOrigin.Tx, `HTTP Integration: Only HTTP allowed, got ${parsedUrl.protocol}`);
// return {
// success: false,
// message: `Only HTTP allowed, got ${parsedUrl.protocol}`,
// };
// }
this.emit(parsedUrl);
} catch (err) {
logger.error(LogOrigin.Tx, `HTTP Integration: ${err}`);
@@ -83,17 +106,32 @@ export class HttpIntegration implements IIntegration<HttpSubscriptionOptions> {
});
}
async emit(path: URL) {
async emit(path: globalThis.URL) {
try {
await got.get(path, {
retry: { limit: 0 },
retry: { limit: this.retryCount },
});
} catch (err) {
logger.error(LogOrigin.Tx, `HTTP integration: ${err}`);
}
// http
// .get(path, { agent: this.httpAgent }, (res) => {
// if (res.statusCode !== 200) {
// logger.error(LogOrigin.Tx, `HTTP Error: ${res.statusCode}`);
// }
// res.resume();
// })
// .on('error', (err) => {
// logger.error(LogOrigin.Tx, `HTTP integration: ${err}`);
// });
}
shutdown() {}
shutdown() {
// if (this.httpAgent) {
// this.httpAgent?.destroy();
// this.httpAgent = null;
// }
}
}
export const httpIntegration = new HttpIntegration();
+1 -2
View File
@@ -79,8 +79,7 @@ export const getRollTimers = (rundown: OntimeEvent[], timeNow: number) => {
const normalEnd = normaliseEndTime(event.timeStart, event.timeEnd);
const hasNotEnded = normalEnd > timeNow;
// TODO: we will likely want a better solution than the modulus here
const isFromDayBefore = normalEnd > dayInMs && timeNow < event.timeEnd % dayInMs;
const isFromDayBefore = normalEnd > dayInMs && timeNow < event.timeEnd;
const hasStarted = isFromDayBefore || timeNow >= event.timeStart;
if (normalEnd <= timeNow) {
-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'));
});
});
@@ -93,10 +93,10 @@ describe('validateHttpSubscriptionCycle()', () => {
});
it('should return true when given an HttpSubscription matches definition', () => {
const validHttp = [{ message: 'http://', enabled: true }];
const invalidHttps = [{ message: 'https://', enabled: true }];
const validHttps = [{ message: 'https://', enabled: true }];
expect(validateHttpSubscriptionCycle(validHttp)).toBe(true);
expect(validateHttpSubscriptionCycle(invalidHttps)).toBe(false);
expect(validateHttpSubscriptionCycle(validHttps)).toBe(true);
});
});
@@ -1,433 +0,0 @@
import { millisToString } from 'ontime-utils';
import { getA1Notation, cellRequestFromEvent, cellRequenstFromProjectData } from '../sheetUtils.js';
import { EndAction, OntimeRundownEntry, ProjectData, SupportedEvent, TimerType } from 'ontime-types';
describe('getA1Notation()', () => {
test('A1', () => {
expect(getA1Notation(0, 0)).toStrictEqual('A1');
});
test('E3', () => {
expect(getA1Notation(2, 4)).toStrictEqual('E3');
});
test('AA100', () => {
expect(getA1Notation(99, 26)).toStrictEqual('AA100');
});
test('can not be negative', () => {
expect(() => getA1Notation(-1, 1)).toThrowError('Index can not be less than 0');
});
});
describe('cellRequenstFromEvent()', () => {
test('string to string', () => {
const event: OntimeRundownEntry = {
type: SupportedEvent.Event,
cue: '1',
title: 'Fancy',
subtitle: 'Wow',
presenter: 'Mr. Presenter',
note: 'Blue button on the right',
timeStart: 46800000,
timeEnd: 57600000,
endAction: EndAction.None,
timerType: TimerType.CountDown,
duration: 10800000,
isPublic: false,
skip: false,
colour: 'red',
user0: '',
user1: '',
user2: '',
user3: '',
user4: '',
user5: '',
user6: '',
user7: '',
user8: '',
user9: '',
revision: 0,
id: '1358',
};
const metadata = {
type: { row: 1, col: 14 },
cue: { row: 1, col: 15 },
title: { row: 1, col: 16 },
subtitle: { row: 1, col: 17 },
presenter: { row: 1, col: 18 },
note: { row: 1, col: 19 },
timeStart: { row: 1, col: 20 },
timeEnd: { row: 1, col: 21 },
endAction: { row: 1, col: 22 },
timerType: { row: 1, col: 23 },
duration: { row: 1, col: 24 },
isPublic: { row: 1, col: 25 },
skip: { row: 1, col: 26 },
colour: { row: 1, col: 27 },
user0: { row: 1, col: 28 },
user1: { row: 1, col: 29 },
user2: { row: 1, col: 30 },
user3: { row: 1, col: 31 },
user4: { row: 1, col: 32 },
user5: { row: 1, col: 33 },
user6: { row: 1, col: 34 },
user7: { row: 1, col: 35 },
user8: { row: 1, col: 36 },
user9: { row: 1, col: 37 },
revision: { row: 1, col: 38 },
id: { row: 1, col: 39 },
};
const result = cellRequestFromEvent(event, 1, 1234, metadata);
expect(result.updateCells.rows[0].values[5].userEnteredValue.stringValue).toStrictEqual(event.note);
});
test('numer to timer', () => {
const event: OntimeRundownEntry = {
type: SupportedEvent.Event,
cue: '1',
title: 'Fancy',
subtitle: 'Wow',
presenter: 'Mr. Presenter',
note: 'Blue button on the right',
timeStart: 46800000,
timeEnd: 57600000,
endAction: EndAction.None,
timerType: TimerType.CountDown,
duration: 10800000,
isPublic: false,
skip: false,
colour: 'red',
user0: '',
user1: '',
user2: '',
user3: '',
user4: '',
user5: '',
user6: '',
user7: '',
user8: '',
user9: '',
revision: 0,
id: '1358',
};
const metadata = {
type: { row: 1, col: 14 },
cue: { row: 1, col: 15 },
title: { row: 1, col: 16 },
subtitle: { row: 1, col: 17 },
presenter: { row: 1, col: 18 },
note: { row: 1, col: 19 },
timeStart: { row: 1, col: 20 },
timeEnd: { row: 1, col: 21 },
endAction: { row: 1, col: 22 },
timerType: { row: 1, col: 23 },
duration: { row: 1, col: 24 },
isPublic: { row: 1, col: 25 },
skip: { row: 1, col: 26 },
colour: { row: 1, col: 27 },
user0: { row: 1, col: 28 },
user1: { row: 1, col: 29 },
user2: { row: 1, col: 30 },
user3: { row: 1, col: 31 },
user4: { row: 1, col: 32 },
user5: { row: 1, col: 33 },
user6: { row: 1, col: 34 },
user7: { row: 1, col: 35 },
user8: { row: 1, col: 36 },
user9: { row: 1, col: 37 },
revision: { row: 1, col: 38 },
id: { row: 1, col: 39 },
};
const result = cellRequestFromEvent(event, 1, 1234, metadata).updateCells.rows[0].values[10].userEnteredValue
.stringValue;
expect(result).toStrictEqual(millisToString(event.duration));
});
test('boolean to x', () => {
const event: OntimeRundownEntry = {
type: SupportedEvent.Event,
cue: '1',
title: 'Fancy',
subtitle: 'Wow',
presenter: 'Mr. Presenter',
note: 'Blue button on the right',
timeStart: 46800000,
timeEnd: 57600000,
endAction: EndAction.None,
timerType: TimerType.CountDown,
duration: 10800000,
isPublic: true,
skip: false,
colour: 'red',
user0: 'u',
user1: 'u',
user2: 'u',
user3: 'u',
user4: 'u',
user5: 'u',
user6: 'u',
user7: 'u',
user8: 'u',
user9: 'u',
revision: 0,
id: '1358',
};
const metadata = {
type: { row: 1, col: 14 },
cue: { row: 1, col: 15 },
title: { row: 1, col: 16 },
subtitle: { row: 1, col: 17 },
presenter: { row: 1, col: 18 },
note: { row: 1, col: 19 },
timeStart: { row: 1, col: 20 },
timeEnd: { row: 1, col: 21 },
endAction: { row: 1, col: 22 },
timerType: { row: 1, col: 23 },
duration: { row: 1, col: 24 },
isPublic: { row: 1, col: 25 },
skip: { row: 1, col: 26 },
colour: { row: 1, col: 27 },
user0: { row: 1, col: 28 },
user1: { row: 1, col: 29 },
user2: { row: 1, col: 30 },
user3: { row: 1, col: 31 },
user4: { row: 1, col: 32 },
user5: { row: 1, col: 33 },
user6: { row: 1, col: 34 },
user7: { row: 1, col: 35 },
user8: { row: 1, col: 36 },
user9: { row: 1, col: 37 },
revision: { row: 1, col: 38 },
id: { row: 1, col: 39 },
};
const result = cellRequestFromEvent(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('');
});
test('spacing in metadata', () => {
const event: OntimeRundownEntry = {
type: SupportedEvent.Event,
cue: '1',
title: 'Fancy',
subtitle: 'Wow',
presenter: 'Mr. Presenter',
note: 'Blue button on the right',
timeStart: 46800000,
timeEnd: 57600000,
endAction: EndAction.None,
timerType: TimerType.CountDown,
duration: 10800000,
isPublic: true,
skip: false,
colour: 'red',
user0: 'u',
user1: 'u',
user2: 'u',
user3: 'u',
user4: 'u',
user5: 'u',
user6: 'u',
user7: 'u',
user8: 'u',
user9: 'u',
revision: 0,
id: '1358',
};
const metadata = {
cue: { row: 1, col: 0 },
title: { row: 1, col: 6 },
subtitle: { row: 1, col: 10 },
user0: { row: 1, col: 16 },
};
const result = cellRequestFromEvent(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);
});
test('metadata offset from zero', () => {
const event: OntimeRundownEntry = {
type: SupportedEvent.Event,
cue: '1',
title: 'Fancy',
subtitle: 'Wow',
presenter: 'Mr. Presenter',
note: 'Blue button on the right',
timeStart: 46800000,
timeEnd: 57600000,
endAction: EndAction.None,
timerType: TimerType.CountDown,
duration: 10800000,
isPublic: true,
skip: false,
colour: 'red',
user0: 'u',
user1: 'u',
user2: 'u',
user3: 'u',
user4: 'u',
user5: 'u',
user6: 'u',
user7: 'u',
user8: 'u',
user9: 'u',
revision: 0,
id: '1358',
};
const metadata = {
cue: { row: 1, col: 5 },
title: { row: 1, col: 6 },
subtitle: { row: 1, col: 10 },
user0: { row: 1, col: 16 },
};
const result = cellRequestFromEvent(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);
});
test('sheet setup', () => {
const event: OntimeRundownEntry = {
type: SupportedEvent.Event,
cue: '1',
title: 'Fancy',
subtitle: 'Wow',
presenter: 'Mr. Presenter',
note: 'Blue button on the right',
timeStart: 46800000,
timeEnd: 57600000,
endAction: EndAction.None,
timerType: TimerType.CountDown,
duration: 10800000,
isPublic: true,
skip: false,
colour: 'red',
user0: 'u',
user1: 'u',
user2: 'u',
user3: 'u',
user4: 'u',
user5: 'u',
user6: 'u',
user7: 'u',
user8: 'u',
user9: 'u',
revision: 0,
id: '1358',
};
const metadata = {
cue: { row: 10, col: 5 },
title: { row: 10, col: 6 },
subtitle: { row: 1, col: 10 },
user0: { row: 10, col: 16 },
};
const result1 = cellRequestFromEvent(event, 1, 1234, metadata);
expect(result1.updateCells.start.sheetId).toStrictEqual(1234);
const result2 = cellRequestFromEvent(event, 10, 1234, metadata);
expect(result2.updateCells.start.rowIndex).toStrictEqual(21);
expect(result2.updateCells.start.columnIndex).toStrictEqual(5);
expect(result2.updateCells.fields).toStrictEqual('userEnteredValue');
});
});
describe('cellRequenstFromProjectData()', () => {
test('string to string', () => {
const projectData: ProjectData = {
title: 'Title',
description: 'Description',
publicUrl: 'Public Url',
backstageUrl: 'Backstage Url',
publicInfo: 'Public Info',
backstageInfo: 'Backstage Info',
};
const metadata = {
title: { row: 0, col: 1 },
description: { row: 1, col: 1 },
publicUrl: { row: 2, col: 1 },
backstageUrl: { row: 3, col: 1 },
publicInfo: { row: 4, col: 1 },
backstageInfo: { row: 5, col: 1 },
};
const result = cellRequenstFromProjectData(projectData, 1234, metadata);
expect(result.updateCells.rows[0].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.title);
expect(result.updateCells.rows[1].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.description);
expect(result.updateCells.rows[2].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.publicUrl);
expect(result.updateCells.rows[3].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.backstageUrl);
expect(result.updateCells.rows[4].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.publicInfo);
expect(result.updateCells.rows[5].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.backstageInfo);
});
test('metadata offset from zero', () => {
const projectData: ProjectData = {
title: 'Title',
description: 'Description',
publicUrl: 'Public Url',
backstageUrl: 'Backstage Url',
publicInfo: 'Public Info',
backstageInfo: 'Backstage Info',
};
const metadata = {
title: { row: 5, col: 10 },
description: { row: 6, col: 10 },
publicUrl: { row: 7, col: 10 },
backstageUrl: { row: 9, col: 10 },
publicInfo: { row: 10, col: 10 },
backstageInfo: { row: 11, col: 10 },
};
const result = cellRequenstFromProjectData(projectData, 1234, metadata);
expect(result.updateCells.rows[0].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.title);
expect(result.updateCells.rows[1].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.description);
expect(result.updateCells.rows[2].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.publicUrl);
expect(result.updateCells.rows[4].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.backstageUrl);
expect(result.updateCells.rows[5].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.publicInfo);
expect(result.updateCells.rows[6].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.backstageInfo);
});
test('spacing in metadata', () => {
const projectData: ProjectData = {
title: 'Title',
description: 'Description',
publicUrl: 'Public Url',
backstageUrl: 'Backstage Url',
publicInfo: 'Public Info',
backstageInfo: 'Backstage Info',
};
const metadata = {
title: { row: 0, col: 1 },
description: { row: 1, col: 1 },
publicUrl: { row: 2, col: 1 },
backstageUrl: { row: 9, col: 1 },
publicInfo: { row: 15, col: 1 },
backstageInfo: { row: 50, col: 1 },
};
const result = cellRequenstFromProjectData(projectData, 1234, metadata);
expect(result.updateCells.rows[0].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.title);
expect(result.updateCells.rows[1].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.description);
expect(result.updateCells.rows[2].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.publicUrl);
expect(result.updateCells.rows[9].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.backstageUrl);
expect(result.updateCells.rows[15].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.publicInfo);
expect(result.updateCells.rows[50].values[0].userEnteredValue.stringValue).toStrictEqual(projectData.backstageInfo);
});
test('sheet setup', () => {
const projectData: ProjectData = {
title: 'Title',
description: 'Description',
publicUrl: 'Public Url',
backstageUrl: 'Backstage Url',
publicInfo: 'Public Info',
backstageInfo: 'Backstage Info',
};
const metadata = {
title: { row: 0, col: 10 },
description: { row: 1, col: 10 },
publicUrl: { row: 2, col: 10 },
backstageUrl: { row: 3, col: 10 },
publicInfo: { row: 4, col: 10 },
backstageInfo: { row: 5, col: 10 },
};
const result = cellRequenstFromProjectData(projectData, 1234, metadata);
expect(result.updateCells.start.rowIndex).toStrictEqual(0);
expect(result.updateCells.start.columnIndex).toStrictEqual(11);
expect(result.updateCells.fields).toStrictEqual('userEnteredValue');
});
});
+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;
+122 -218
View File
@@ -36,7 +36,6 @@ import {
parseViewSettings,
} 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';
@@ -48,12 +47,7 @@ export const JSON_MIME = 'application/json';
* @returns {object} - parsed object
*/
export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImportMap>) => {
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: '',
@@ -109,228 +103,140 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
let user8Index: number | null = null;
let user9Index: number | null = null;
excelData.forEach((row, rowIndex) => {
if (row.length === 0) {
return;
}
// these fields contain the data to its right
let projectTitleNext = false;
let projectDescriptionNext = false;
let publicUrlNext = false;
let publicInfoNext = false;
let backstageUrlNext = false;
let backstageInfoNext = false;
excelData
.filter((e) => e.length > 0)
.forEach((row) => {
// these fields contain the data to its right
let projectTitleNext = false;
let projectDescriptionNext = false;
let publicUrlNext = false;
let publicInfoNext = false;
let backstageUrlNext = false;
let backstageInfoNext = false;
const event: Partial<OntimeEvent> = {};
const handlers = {
[importMap.projectName]: (row: number, col: number) => {
projectTitleNext = true;
projectMetadata['title'] = { row, col };
},
[importMap.projectDescription]: (row: number, col: number) => {
projectDescriptionNext = true;
projectMetadata['description'] = { row, col };
},
[importMap.publicUrl]: (row: number, col: number) => {
publicUrlNext = true;
projectMetadata['publicUrl'] = { row, col };
},
[importMap.publicInfo]: (row: number, col: number) => {
publicInfoNext = true;
projectMetadata['publicInfo'] = { row, col };
},
[importMap.backstageUrl]: (row: number, col: number) => {
backstageUrlNext = true;
projectMetadata['backstageUrl'] = { row, col };
},
[importMap.backstageInfo]: (row: number, col: number) => {
backstageInfoNext = true;
projectMetadata['backstageInfo'] = { row, col };
},
const event: Partial<OntimeEvent> = {};
const handlers = {
[importMap.projectName]: () => (projectTitleNext = true),
[importMap.projectDescription]: () => (projectDescriptionNext = true),
[importMap.publicUrl]: () => (publicUrlNext = true),
[importMap.publicInfo]: () => (publicInfoNext = true),
[importMap.backstageUrl]: () => (backstageUrlNext = true),
[importMap.backstageInfo]: () => (backstageInfoNext = true),
[importMap.timeStart]: (row: number, col: number) => {
timeStartIndex = col;
rundownMetadata['timeStart'] = { row, col };
},
[importMap.timeEnd]: (row: number, col: number) => {
timeEndIndex = col;
rundownMetadata['timeEnd'] = { row, col };
},
[importMap.duration]: (row: number, col: number) => {
durationIndex = col;
rundownMetadata['duration'] = { row, col };
},
[importMap.timeStart]: (index: number) => (timeStartIndex = index),
[importMap.timeEnd]: (index: number) => (timeEndIndex = index),
[importMap.duration]: (index: number) => (durationIndex = index),
[importMap.cue]: (row: number, col: number) => {
cueIndex = col;
rundownMetadata['cue'] = { row, col };
},
[importMap.title]: (row: number, col: number) => {
titleIndex = col;
rundownMetadata['title'] = { row, col };
},
[importMap.presenter]: (row: number, col: number) => {
presenterIndex = col;
rundownMetadata['presenter'] = { row, col };
},
[importMap.subtitle]: (row: number, col: number) => {
subtitleIndex = col;
rundownMetadata['subtitle'] = { row, col };
},
[importMap.isPublic]: (row: number, col: number) => {
isPublicIndex = col;
rundownMetadata['isPublic'] = { row, col };
},
[importMap.skip]: (row: number, col: number) => {
skipIndex = col;
rundownMetadata['skip'] = { row, col };
},
[importMap.note]: (row: number, col: number) => {
notesIndex = col;
rundownMetadata['note'] = { row, col };
},
[importMap.colour]: (row: number, col: number) => {
colourIndex = col;
rundownMetadata['colour'] = { row, col };
},
[importMap.cue]: (index: number) => (cueIndex = index),
[importMap.title]: (index: number) => (titleIndex = index),
[importMap.presenter]: (index: number) => (presenterIndex = index),
[importMap.subtitle]: (index: number) => (subtitleIndex = index),
[importMap.isPublic]: (index: number) => (isPublicIndex = index),
[importMap.skip]: (index: number) => (skipIndex = index),
[importMap.note]: (index: number) => (notesIndex = index),
[importMap.colour]: (index: number) => (colourIndex = index),
[importMap.endAction]: (row: number, col: number) => {
endActionIndex = col;
rundownMetadata['endAction'] = { row, col };
},
[importMap.timerType]: (row: number, col: number) => {
timerTypeIndex = col;
rundownMetadata['timerType'] = { row, col };
},
[importMap.endAction]: (index: number) => (endActionIndex = index),
[importMap.timerType]: (index: number) => (timerTypeIndex = index),
[importMap.user0]: (row: number, col: number) => {
user0Index = col;
rundownMetadata['user0'] = { row, col };
},
[importMap.user1]: (row: number, col: number) => {
user1Index = col;
rundownMetadata['user1'] = { row, col };
},
[importMap.user2]: (row: number, col: number) => {
user2Index = col;
rundownMetadata['user2'] = { row, col };
},
[importMap.user3]: (row: number, col: number) => {
user3Index = col;
rundownMetadata['user3'] = { row, col };
},
[importMap.user4]: (row: number, col: number) => {
user4Index = col;
rundownMetadata['user4'] = { row, col };
},
[importMap.user5]: (row: number, col: number) => {
user5Index = col;
rundownMetadata['user5'] = { row, col };
},
[importMap.user6]: (row: number, col: number) => {
user6Index = col;
rundownMetadata['user6'] = { row, col };
},
[importMap.user7]: (row: number, col: number) => {
user7Index = col;
rundownMetadata['user7'] = { row, col };
},
[importMap.user8]: (row: number, col: number) => {
user8Index = col;
rundownMetadata['user8'] = { row, col };
},
[importMap.user9]: (row: number, col: number) => {
user9Index = col;
rundownMetadata['user9'] = { row, col };
},
} as const;
[importMap.user0]: (index: number) => (user0Index = index),
[importMap.user1]: (index: number) => (user1Index = index),
[importMap.user2]: (index: number) => (user2Index = index),
[importMap.user3]: (index: number) => (user3Index = index),
[importMap.user4]: (index: number) => (user4Index = index),
[importMap.user5]: (index: number) => (user5Index = index),
[importMap.user6]: (index: number) => (user6Index = index),
[importMap.user7]: (index: number) => (user7Index = index),
[importMap.user8]: (index: number) => (user8Index = index),
[importMap.user9]: (index: number) => (user9Index = index),
} as const;
row.forEach((column, j) => {
// 1. we check if we have set a flag for a known field
if (projectTitleNext) {
projectData.title = makeString(column, '');
projectTitleNext = false;
} else if (projectDescriptionNext) {
projectData.description = makeString(column, '');
projectDescriptionNext = false;
} else if (publicUrlNext) {
projectData.publicUrl = makeString(column, '');
publicUrlNext = false;
} else if (publicInfoNext) {
projectData.publicInfo = makeString(column, '');
publicInfoNext = false;
} else if (backstageUrlNext) {
projectData.backstageUrl = makeString(column, '');
backstageUrlNext = false;
} else if (backstageInfoNext) {
projectData.backstageInfo = makeString(column, '');
backstageInfoNext = false;
} else if (j === timeStartIndex) {
event.timeStart = parseExcelDate(column);
} else if (j === timeEndIndex) {
event.timeEnd = parseExcelDate(column);
} else if (j === durationIndex) {
event.duration = parseExcelDate(column);
} else if (j === titleIndex) {
event.title = makeString(column, '');
} else if (j === cueIndex) {
event.cue = makeString(column, '');
} else if (j === presenterIndex) {
event.presenter = makeString(column, '');
} else if (j === subtitleIndex) {
event.subtitle = makeString(column, '');
} else if (j === isPublicIndex) {
event.isPublic = column == 'x' ? true : coerceBoolean(column);
} else if (j === skipIndex) {
event.skip = column == 'x' ? true : coerceBoolean(column);
} else if (j === notesIndex) {
event.note = makeString(column, '');
} else if (j === endActionIndex) {
event.endAction = validateEndAction(column);
} else if (j === timerTypeIndex) {
event.timerType = validateTimerType(column);
} else if (j === colourIndex) {
event.colour = makeString(column, '');
} else if (j === user0Index) {
event.user0 = makeString(column, '');
} else if (j === user1Index) {
event.user1 = makeString(column, '');
} else if (j === user2Index) {
event.user2 = makeString(column, '');
} else if (j === user3Index) {
event.user3 = makeString(column, '');
} else if (j === user4Index) {
event.user4 = makeString(column, '');
} else if (j === user5Index) {
event.user5 = makeString(column, '');
} else if (j === user6Index) {
event.user6 = makeString(column, '');
} else if (j === user7Index) {
event.user7 = makeString(column, '');
} else if (j === user8Index) {
event.user8 = makeString(column, '');
} else if (j === user9Index) {
event.user9 = makeString(column, '');
} else {
// 2. if there is no flag, lets see if we know the field type
if (typeof column === 'string') {
const col = column.toLowerCase();
row.forEach((column, j) => {
// 1. we check if we have set a flag for a known field
if (projectTitleNext) {
projectData.title = makeString(column, '');
projectTitleNext = false;
} else if (projectDescriptionNext) {
projectData.description = makeString(column, '');
projectDescriptionNext = false;
} else if (publicUrlNext) {
projectData.publicUrl = makeString(column, '');
publicUrlNext = false;
} else if (publicInfoNext) {
projectData.publicInfo = makeString(column, '');
publicInfoNext = false;
} else if (backstageUrlNext) {
projectData.backstageUrl = makeString(column, '');
backstageUrlNext = false;
} else if (backstageInfoNext) {
projectData.backstageInfo = makeString(column, '');
backstageInfoNext = false;
} else if (j === timeStartIndex) {
event.timeStart = parseExcelDate(column);
} else if (j === timeEndIndex) {
event.timeEnd = parseExcelDate(column);
} else if (j === durationIndex) {
event.duration = parseExcelDate(column);
} else if (j === titleIndex) {
event.title = makeString(column, '');
} else if (j === cueIndex) {
event.cue = makeString(column, '');
} else if (j === presenterIndex) {
event.presenter = makeString(column, '');
} else if (j === subtitleIndex) {
event.subtitle = makeString(column, '');
} else if (j === isPublicIndex) {
event.isPublic = Boolean(column);
} else if (j === skipIndex) {
event.skip = Boolean(column);
} else if (j === notesIndex) {
event.note = makeString(column, '');
} else if (j === endActionIndex) {
event.endAction = validateEndAction(column);
} else if (j === timerTypeIndex) {
event.timerType = validateTimerType(column);
} else if (j === colourIndex) {
event.colour = makeString(column, '');
} else if (j === user0Index) {
event.user0 = makeString(column, '');
} else if (j === user1Index) {
event.user1 = makeString(column, '');
} else if (j === user2Index) {
event.user2 = makeString(column, '');
} else if (j === user3Index) {
event.user3 = makeString(column, '');
} else if (j === user4Index) {
event.user4 = makeString(column, '');
} else if (j === user5Index) {
event.user5 = makeString(column, '');
} else if (j === user6Index) {
event.user6 = makeString(column, '');
} else if (j === user7Index) {
event.user7 = makeString(column, '');
} else if (j === user8Index) {
event.user8 = makeString(column, '');
} else if (j === user9Index) {
event.user9 = makeString(column, '');
} else {
// 2. if there is no flag, lets see if we know the field type
if (typeof column === 'string') {
const col = column.toLowerCase();
if (handlers[col]) {
handlers[col](rowIndex, j);
if (handlers[col]) {
handlers[col](j);
}
// else. we don't know how to handle this column
// just ignore it
}
// else. we don't know how to handle this column
// just ignore it
}
});
if (Object.keys(event).length > 0) {
// if any data was found, push to array
rundown.push({ ...event, type: SupportedEvent.Event } as OntimeEvent);
}
});
if (Object.keys(event).length > 0) {
// if any data was found, push to array
rundown.push({ ...event, type: SupportedEvent.Event } as OntimeEvent);
}
});
return {
rundown,
project: projectData,
@@ -339,8 +245,6 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
version: '2.0.0',
},
userFields: customUserFields,
projectMetadata,
rundownMetadata,
};
};
+6 -2
View File
@@ -227,7 +227,8 @@ export const parseOsc = (data: { osc?: Partial<OSCSettings> }): OSCSettings => {
*/
export const validateHttpSubscriptionCycle = (data: HttpSubscriptionOptions[]): boolean => {
for (const subscriptionOption of data) {
const isHttp = subscriptionOption.message?.startsWith('http://');
const isHttp =
subscriptionOption.message?.startsWith('http://') || subscriptionOption.message?.startsWith('https://');
if (typeof subscriptionOption.message !== 'string' || !isHttp || typeof subscriptionOption.enabled !== 'boolean') {
return false;
}
@@ -273,8 +274,11 @@ export const parseHttp = (data: { http?: Partial<HttpSettings> }): HttpSettings
? loadedConfig.subscriptions
: dbModel.http.subscriptions;
const retryCount = Math.max(0, loadedConfig.retryCount ?? dbModel.http.retryCount);
return {
enabledOut: loadedConfig.enabledOut ?? dbModel.http.enabledOut,
retryCount: retryCount,
subscriptions: validatedSubscriptions,
};
}
@@ -331,4 +335,4 @@ export const parseUserFields = (data): UserFields => {
}
}
return { ...newUserFields };
};
};
-165
View File
@@ -1,165 +0,0 @@
import { sheets_v4 } from '@googleapis/sheets';
import { millisToString } from 'ontime-utils';
import { OntimeRundownEntry, ProjectData, isOntimeEvent } from 'ontime-types';
/**
*
* @param {number} row - The row number of the cell reference. Row 1 is row number 0.
* @param {number} column - The column number of the cell reference. A is column number 0.
* @returns {string} - Returns a cell reference as a string using A1 Notation
* @author https://www.labnol.org/convert-column-a1-notation-210601
* @example
*
* getA1Notation(2, 4) returns "E3"
* getA1Notation(99, 26) returns "AA100"
*
*/
export function getA1Notation(row: number, column: number): string {
if (row < 0 || column < 0) {
throw new Error('Index can not be less than 0');
}
const a1Notation = [`${row + 1}`];
const totalAlphabets = 'Z'.charCodeAt(0) - 'A'.charCodeAt(0) + 1;
let block = column;
while (block >= 0) {
a1Notation.unshift(String.fromCharCode((block % totalAlphabets) + 'A'.charCodeAt(0)));
block = Math.floor(block / totalAlphabets) - 1;
}
return a1Notation.join('');
}
/**
* @description - creates updateCells request from ontime event
* @param {OntimeRundownEntry} event
* @param {number} index - index of the event
* @param {number} worksheetId
* @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(
event: OntimeRundownEntry,
index: number,
worksheetId: number,
metadata,
): sheets_v4.Schema$Request {
const returnRows: 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 }][];
const titleCol = tmp[0][1].col;
for (const [index, e] of tmp.entries()) {
if (index !== 0) {
const prevCol = tmp[index - 1][1].col;
const thisCol = e[1].col;
const diff = thisCol - prevCol;
if (diff > 1) {
const fillArr = new Array<(typeof tmp)[0]>(1).fill(['blank', { row: e[1].row, col: prevCol + 1 }]);
tmp.splice(index, 0, ...fillArr);
}
}
}
tmp.forEach(([key, _]) => {
if (isOntimeEvent(event)) {
if (key === 'blank') {
returnRows.push({});
} else if (key === 'colour') {
returnRows.push({
userEnteredValue: { stringValue: event.colour },
});
} else if (typeof event[key] === 'number') {
returnRows.push({
userEnteredValue: { stringValue: millisToString(event[key], true) },
});
} else if (typeof event[key] === 'string') {
returnRows.push({
userEnteredValue: { stringValue: event[key] },
});
} else if (typeof event[key] === 'boolean') {
returnRows.push({
userEnteredValue: { stringValue: event[key] ? 'x' : '' },
});
} else {
returnRows.push({});
}
}
});
return {
updateCells: {
start: {
sheetId: worksheetId,
rowIndex: index + tmp[0][1]['row'] + 1,
columnIndex: titleCol,
},
fields: 'userEnteredValue',
rows: [
{
values: returnRows,
},
],
},
};
}
/**
* @description - creates updateCells request from ontime event
* @param {ProjectData} projectData
* @param {number} worksheetId
* @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 cellRequenstFromProjectData(
projectData: ProjectData,
worksheetId: number,
metadata,
): sheets_v4.Schema$Request {
const returnRows: 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 }][];
const minRow = Object.values(metadata).reduce(
(accumulator: number, val) => Math.min(accumulator, val['row']),
Number.MAX_VALUE,
) as number;
const minCol = tmp[0][1].col + 1;
for (const [index, e] of tmp.entries()) {
if (index != 0) {
const prevRow = tmp[index - 1][1].row;
const thisRow = e[1].row;
const diff = thisRow - prevRow;
if (diff > 1) {
const fillArr = new Array<(typeof tmp)[0]>(1).fill(['blank', { row: prevRow + 1, col: e[1].col }]);
tmp.splice(index, 0, ...fillArr);
}
}
}
tmp.forEach(([key, _]) => {
if (key == 'blank') {
returnRows.push({});
} else {
returnRows.push({
values: [
{
userEnteredValue: { stringValue: projectData[key] },
},
],
});
}
});
return {
updateCells: {
start: {
sheetId: worksheetId,
rowIndex: minRow,
columnIndex: minCol,
},
fields: 'userEnteredValue',
rows: returnRows,
},
};
}
-380
View File
@@ -1,380 +0,0 @@
import { sheets, sheets_v4 } from '@googleapis/sheets';
import { writeFile } from 'fs/promises';
import { readFileSync } from 'fs';
import { OAuth2Client } from 'google-auth-library';
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 { parseExcel } from './parser.js';
import { parseProject, parseRundown, parseUserFields } from './parserFunctions.js';
import { ExcelImportMap } from 'ontime-utils';
type ResponseOK = {
data: Partial<DatabaseModel>;
};
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 static authUrl: null | string = null;
private authServerTimeout;
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');
}
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;
}
} catch (_) {
/* empty - it is ok thet there is no clientSecret */
}
}
/**
* @description SETP 1 - 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');
}
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;
}
/**
* @description SETP 1 - test that the saved object is pressent
*/
testClientSecret() {
return Sheet.clientSecret !== null;
}
/**
* @description SETP 2 - create server to interact with th OAuth2 request
* @returns {Promise<string | null>} - returns url path serve on success
* @throws
*/
async openAuthServer(): Promise<string | null> {
//TODO: this only works on local networks
// if the server is allready running retun it
if (Sheet.authUrl) {
clearTimeout(this.authServerTimeout);
this.authServerTimeout = setTimeout(
() => {
Sheet.authUrl = null;
server.unref;
},
2 * 60 * 1000,
);
return Sheet.authUrl;
}
// Check that Secret is valid
const keyFile = Sheet.clientSecret;
const keys = keyFile.installed || keyFile.web;
if (!keys.redirect_uris || keys.redirect_uris.length === 0) {
throw new Error('Sheet: Missing redirect URI');
}
const redirectUri = new URL(keys.redirect_uris[0]);
if (redirectUri.hostname !== 'localhost') {
throw new Error('Sheet: Invalid redirect URI');
}
// create an oAuth client to authorize the API call
const client = new OAuth2Client({
clientId: keys.client_id,
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');
if (serverUrl.pathname !== redirectUri.pathname) {
res.end('Invalid callback URL');
return;
}
const searchParams = serverUrl.searchParams;
if (searchParams.has('error')) {
res.end('Authorization rejected.');
logger.info(LogOrigin.Server, `Sheet: ${searchParams.get('error')}`);
return;
}
if (!searchParams.has('code')) {
res.end('No authentication code provided.');
logger.info(LogOrigin.Server, `Sheet: Cannot read authentication code`);
return;
}
const code = searchParams.get('code');
const { tokens } = await client.getToken({
code,
redirect_uri: redirectUri.toString(),
});
client.credentials = tokens;
Sheet.client = client;
res.end('Authentication successful! Please close this tab and return to OnTime.');
logger.info(LogOrigin.Server, `Sheet: Authentication successful`);
} catch (e) {
logger.error(LogOrigin.Server, `Sheet: ${e}`);
} finally {
server.close();
}
});
let listenPort = 3000;
if (keyFile.installed) {
// Use emphemeral port if not a web client
listenPort = 0;
} else if (redirectUri.port !== '') {
listenPort = Number(redirectUri.port);
}
//TODO: the server might not start correctly
server.listen(listenPort);
const address = server.address();
if (typeof address !== 'string') {
redirectUri.port = String(address.port);
}
// open the browser to the authorize url to start the workflow
const authorizeUrl = client.generateAuthUrl({
redirect_uri: redirectUri.toString(),
access_type: 'offline',
scope: this.scope,
});
Sheet.authUrl = authorizeUrl;
this.authServerTimeout = setTimeout(
() => {
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();
+7 -7
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,
+1 -1
View File
@@ -3,7 +3,7 @@ version: "3"
services:
ontime:
container_name: ontime
image: getontime/ontime:latest
image: getontime/ontime:beta_v2
ports:
- "4001:4001/tcp"
- "8888:8888/udp"
+2 -4
View File
@@ -1,9 +1,9 @@
{
"name": "ontime",
"version": "2.28.17",
"version": "2.21.3",
"description": "Time keeping for live events",
"keywords": [
"lightdev",
"lighdev",
"ontime",
"timer",
"rundown"
@@ -30,8 +30,6 @@
"build": "turbo run build",
"build:local": "turbo run build:local",
"build:electron": "turbo run build:electron",
"build:docker": "turbo run build:docker",
"build:localdocker": "turbo run build:localdocker",
"dist-win": "turbo run dist-win",
"dist-mac": "turbo run dist-mac",
"dist-linux": "turbo run dist-linux",
@@ -5,5 +5,6 @@ export type HttpSubscription = Subscription<HttpSubscriptionOptions>;
export interface HttpSettings {
enabledOut: boolean;
retryCount: number;
subscriptions: HttpSubscription;
}
-1
View File
@@ -15,7 +15,6 @@ export { formatDisplay } from './src/date-utils/formatDisplay.js';
export { formatFromMillis } from './src/date-utils/formatFromMillis.js';
export { isTimeString } from './src/date-utils/isTimeString.js';
export { millisToString } from './src/date-utils/millisToString.js';
export { isColourHex } from './src/regex-utils/isColourHex.js';
// time utils
export { dayInMs, mts } from './src/timeConstants.js';
+1 -2
View File
@@ -28,6 +28,5 @@
"prettier": "^3.0.3",
"typescript": "^5.2.2",
"vitest": "^0.30.1"
},
"sideEffects": false
}
}
@@ -1,45 +0,0 @@
import { isColourHex } from './isColourHex';
describe('test isColourHex() function', () => {
it('it validates colour hex strings', () => {
const ts = ['#FFF', '#FFFF', '#FFFFFF', '#FFFFFFFF'];
for (const s of ts) {
expect(isColourHex(s)).toBe(true);
}
});
it('it validates colour hex strings', () => {
const ts = ['#F90', '#1234', '#56789A', '#BCDEF012'];
for (const s of ts) {
expect(isColourHex(s)).toBe(true);
}
});
it('it validates colour hex strings', () => {
const ts = ['#f90', '#1234', '#56789a', '#bcdef012'];
for (const s of ts) {
expect(isColourHex(s)).toBe(true);
}
});
it('it fails digits bigger than F', () => {
const ts = ['#FFG'];
for (const s of ts) {
expect(isColourHex(s)).toBe(false);
}
});
it('it fails incorect amout of digits', () => {
const ts = ['#F', '#FF', '#FFFFF', '#FFFFFFF', '#FFFFFFFFF'];
for (const s of ts) {
expect(isColourHex(s)).toBe(false);
}
});
it('it fails missing #', () => {
const ts = ['FFF', 'FFFF', 'FFFFFF', 'FFFFFFFF'];
for (const s of ts) {
expect(isColourHex(s)).toBe(false);
}
});
});
@@ -1,10 +0,0 @@
/**
* @description Validates a colour hex string
* @param {string} text - colour hex string "#FFF" | "#FFFF" | "#FFFFFF" | "#FFFFFFFF"
* @returns {boolean} string represents time
*/
export const isColourHex = (text: string): boolean => {
const regexS = /^#((?:[a-f\d]{1}){3,4})$/i;
const regexD = /^#((?:[a-f\d]{2}){3,4})$/i;
return regexS.test(text) || regexD.test(text);
};
@@ -93,17 +93,6 @@ describe('validateTimes()', () => {
expect(timeEnd).toBe(10);
expect(duration).toBe(10);
});
it('ensures values dont overflow dayMs', () => {
const start = 86100000;
const endOverDay = 87420000;
const durationNormal = 1320000;
const { timeStart, timeEnd, duration } = validateTimes(start, endOverDay, durationNormal);
expect(timeStart).toBe(start);
expect(timeEnd).toBe(1020000);
expect(duration).toBe(durationNormal);
});
});
describe('calculateDuration()', () => {
@@ -52,9 +52,9 @@ function convertToInteger(value: unknown): number {
* @param _duration
*/
export function validateTimes(_start?: unknown, _end?: unknown, _duration?: unknown) {
const timeStart = convertToInteger(_start) % dayInMs;
const timeEnd = convertToInteger(_end) % dayInMs;
const duration = convertToInteger(_duration) % dayInMs;
const timeStart = convertToInteger(_start);
const timeEnd = convertToInteger(_end);
const duration = convertToInteger(_duration);
if (_start != null && _end != null) {
// Case 1. if we have start and end, duration must be derived
+7 -160
View File
@@ -249,9 +249,6 @@ importers:
apps/server:
dependencies:
'@googleapis/sheets':
specifier: ^5.0.5
version: 5.0.5
body-parser:
specifier: ^1.20.0
version: 1.20.1
@@ -273,9 +270,6 @@ importers:
express-validator:
specifier: ^6.14.2
version: 6.14.2
google-auth-library:
specifier: ^9.2.0
version: 9.2.0
got:
specifier: ^14.0.0
version: 14.0.0
@@ -2234,16 +2228,6 @@ packages:
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
dev: true
/@googleapis/sheets@5.0.5:
resolution: {integrity: sha512-XMoONmgAJm2jYeTYHX4054VcEkElxlgqmnHvt0wAurzEHoGJLdUHhTAJXGPLgSs4WVMPtgU8HLrmk7/U+Qlw7A==}
engines: {node: '>=12.0.0'}
dependencies:
googleapis-common: 7.0.1
transitivePeerDependencies:
- encoding
- supports-color
dev: false
/@humanwhocodes/config-array@0.11.13:
resolution: {integrity: sha512-JSBDMiDKSzQVngfRjOdFXgFfklaXI4K9nLF49Auh21lmBWRLIK3+xTErTWD4KU54pb6coM6ESE7Awz/FNU3zgQ==}
engines: {node: '>=10.10.0'}
@@ -3551,15 +3535,6 @@ packages:
- supports-color
dev: true
/agent-base@7.1.0:
resolution: {integrity: sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==}
engines: {node: '>= 14'}
dependencies:
debug: 4.3.4
transitivePeerDependencies:
- supports-color
dev: false
/ajv-keywords@3.5.2(ajv@6.12.6):
resolution: {integrity: sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==}
peerDependencies:
@@ -3812,16 +3787,13 @@ packages:
/base64-js@1.5.1:
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
requiresBuild: true
dev: true
/big-integer@1.6.51:
resolution: {integrity: sha512-GPEid2Y9QU1Exl1rpO9B2IPJGHPSupF5GnVIP0blYvNOMer2bTvSWs1jGOUg04hTmu67nmLsQ9TBo1puaotBHg==}
engines: {node: '>=0.6'}
dev: true
/bignumber.js@9.1.2:
resolution: {integrity: sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug==}
dev: false
/binary-extensions@2.2.0:
resolution: {integrity: sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==}
engines: {node: '>=8'}
@@ -3924,10 +3896,6 @@ packages:
resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==}
dev: true
/buffer-equal-constant-time@1.0.1:
resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==}
dev: false
/buffer-equal@1.0.0:
resolution: {integrity: sha512-tcBWO2Dl4e7Asr9hTGcpVrCe+F7DubpmqWCTbj4FHLmjqO2hIaC383acQubWtRJhdceqs5uBHs6Es+Sk//RKiQ==}
engines: {node: '>=0.4.0'}
@@ -4457,6 +4425,7 @@ packages:
optional: true
dependencies:
ms: 2.1.2
dev: true
/decimal.js@10.4.3:
resolution: {integrity: sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==}
@@ -4685,12 +4654,6 @@ packages:
resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
dev: true
/ecdsa-sig-formatter@1.0.11:
resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==}
dependencies:
safe-buffer: 5.2.1
dev: false
/ee-first@1.1.1:
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
dev: false
@@ -5337,10 +5300,6 @@ packages:
- supports-color
dev: false
/extend@3.0.2:
resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}
dev: false
/extract-zip@2.0.1:
resolution: {integrity: sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==}
engines: {node: '>= 10.17.0'}
@@ -5603,30 +5562,6 @@ packages:
resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==}
dev: true
/gaxios@6.1.1:
resolution: {integrity: sha512-bw8smrX+XlAoo9o1JAksBwX+hi/RG15J+NTSxmNPIclKC3ZVK6C2afwY8OSdRvOK0+ZLecUJYtj2MmjOt3Dm0w==}
engines: {node: '>=14'}
dependencies:
extend: 3.0.2
https-proxy-agent: 7.0.2
is-stream: 2.0.1
node-fetch: 2.7.0
transitivePeerDependencies:
- encoding
- supports-color
dev: false
/gcp-metadata@6.1.0:
resolution: {integrity: sha512-Jh/AIwwgaxan+7ZUUmRLCjtchyDiqh4KjBJ5tW3plBZb5iL/BPcso8A5DlzeD9qlw0duCamnNdpFjxwaT0KyKg==}
engines: {node: '>=14'}
dependencies:
gaxios: 6.1.1
json-bigint: 1.0.0
transitivePeerDependencies:
- encoding
- supports-color
dev: false
/gensync@1.0.0-beta.2:
resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}
engines: {node: '>=6.9.0'}
@@ -5758,36 +5693,6 @@ packages:
resolution: {integrity: sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==}
dev: true
/google-auth-library@9.2.0:
resolution: {integrity: sha512-1oV3p0JhNEhVbj26eF3FAJcv9MXXQt4S0wcvKZaDbl4oHq5V3UJoSbsGZGQNcjoCdhW4kDSwOs11wLlHog3fgQ==}
engines: {node: '>=14'}
dependencies:
base64-js: 1.5.1
ecdsa-sig-formatter: 1.0.11
gaxios: 6.1.1
gcp-metadata: 6.1.0
gtoken: 7.0.1
jws: 4.0.0
transitivePeerDependencies:
- encoding
- supports-color
dev: false
/googleapis-common@7.0.1:
resolution: {integrity: sha512-mgt5zsd7zj5t5QXvDanjWguMdHAcJmmDrF9RkInCecNsyV7S7YtGqm5v2IWONNID88osb7zmx5FtrAP12JfD0w==}
engines: {node: '>=14.0.0'}
dependencies:
extend: 3.0.2
gaxios: 6.1.1
google-auth-library: 9.2.0
qs: 6.11.0
url-template: 2.0.8
uuid: 9.0.1
transitivePeerDependencies:
- encoding
- supports-color
dev: false
/gopd@1.0.1:
resolution: {integrity: sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==}
dependencies:
@@ -5840,17 +5745,6 @@ packages:
resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==}
dev: true
/gtoken@7.0.1:
resolution: {integrity: sha512-KcFVtoP1CVFtQu0aSk3AyAt2og66PFhZAlkUOuWKwzMLoulHXG5W5wE5xAnHb+yl3/wEFoqGW7/cDGMU8igDZQ==}
engines: {node: '>=14.0.0'}
dependencies:
gaxios: 6.1.1
jws: 4.0.0
transitivePeerDependencies:
- encoding
- supports-color
dev: false
/has-bigints@1.0.2:
resolution: {integrity: sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==}
dev: true
@@ -5963,16 +5857,6 @@ packages:
- supports-color
dev: true
/https-proxy-agent@7.0.2:
resolution: {integrity: sha512-NmLNjm6ucYwtcUmL7JQC1ZQ57LmHP4lT15FQ8D61nak1rO6DH+fz5qNK2Ap5UN4ZapYICE3/0KodcLYSPsPbaA==}
engines: {node: '>= 14'}
dependencies:
agent-base: 7.1.0
debug: 4.3.4
transitivePeerDependencies:
- supports-color
dev: false
/human-signals@2.1.0:
resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==}
engines: {node: '>=10.17.0'}
@@ -6251,6 +6135,7 @@ packages:
/is-stream@2.0.1:
resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}
engines: {node: '>=8'}
dev: true
/is-stream@3.0.0:
resolution: {integrity: sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==}
@@ -6455,12 +6340,6 @@ packages:
hasBin: true
dev: true
/json-bigint@1.0.0:
resolution: {integrity: sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==}
dependencies:
bignumber.js: 9.1.2
dev: false
/json-buffer@3.0.1:
resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==}
@@ -6513,21 +6392,6 @@ packages:
object.assign: 4.1.4
dev: true
/jwa@2.0.0:
resolution: {integrity: sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==}
dependencies:
buffer-equal-constant-time: 1.0.1
ecdsa-sig-formatter: 1.0.11
safe-buffer: 5.2.1
dev: false
/jws@4.0.0:
resolution: {integrity: sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==}
dependencies:
jwa: 2.0.0
safe-buffer: 5.2.1
dev: false
/keyv@4.5.2:
resolution: {integrity: sha512-5MHbFaKn8cNSmVW7BYnijeAVlE4cYA/SVkifVgrh7yotnfhKmjuXpDKjrABLnT0SfHWV21P8ow07OGfRrNDg8g==}
dependencies:
@@ -6880,6 +6744,7 @@ packages:
/ms@2.1.2:
resolution: {integrity: sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==}
dev: true
/ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
@@ -6936,18 +6801,6 @@ packages:
whatwg-url: 5.0.0
dev: true
/node-fetch@2.7.0:
resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}
engines: {node: 4.x || >=6.0.0}
peerDependencies:
encoding: ^0.1.0
peerDependenciesMeta:
encoding:
optional: true
dependencies:
whatwg-url: 5.0.0
dev: false
/node-osc@9.0.2:
resolution: {integrity: sha512-q+VQL7DMWRL5+yvzRlWVig8BD9raotLs6onHU4e8MaFgxmYuIwcXhsvQeyUZFiKP6y/qGUXU6K0T99gVmISwmA==}
engines: {node: ^18.17.0 || >=20.5.0}
@@ -8350,6 +8203,7 @@ packages:
/tr46@0.0.3:
resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==}
dev: true
/tr46@3.0.0:
resolution: {integrity: sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==}
@@ -8653,10 +8507,6 @@ packages:
requires-port: 1.0.0
dev: true
/url-template@2.0.8:
resolution: {integrity: sha512-XdVKMF4SJ0nP/O7XIPB0JwAEuT9lDIYnNsK8yGVe43y0AWoKeJNdv3ZNWh7ksJ6KqQFjOO6ox/VEitLnaVNufw==}
dev: false
/use-callback-ref@1.3.0(@types/react@18.0.26)(react@18.2.0):
resolution: {integrity: sha512-3FT9PRuRdbB9HfXhEq35u4oZkvpJ5kuYbpqhCfmiZyReuRgpnhDlbr2ZEnnuS0RrJAPn6l23xjFg9kpDM+Ms7w==}
engines: {node: '>=10'}
@@ -8709,11 +8559,6 @@ packages:
engines: {node: '>= 0.4.0'}
dev: false
/uuid@9.0.1:
resolution: {integrity: sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==}
hasBin: true
dev: false
/v8-compile-cache-lib@3.0.1:
resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==}
dev: true
@@ -9066,6 +8911,7 @@ packages:
/webidl-conversions@3.0.1:
resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
dev: true
/webidl-conversions@7.0.0:
resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==}
@@ -9111,6 +8957,7 @@ packages:
dependencies:
tr46: 0.0.3
webidl-conversions: 3.0.1
dev: true
/which-boxed-primitive@1.0.2:
resolution: {integrity: sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==}
-1
View File
@@ -26,7 +26,6 @@
"build:local": {},
"build:electron": {},
"build:docker": {},
"build:localdocker": {},
"e2e": {
"dependsOn": ["^build"]
},