Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions apps/client/src/common/api/sync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import axios from 'axios';
import { SyncClientList, SyncHostConnectionRequest } from 'ontime-types';

import { apiEntryUrl } from './constants';

const syncPath = `${apiEntryUrl}/sync`;

/**
* HTTP request to retrieve application info
*/
export async function getSyncList(): Promise<SyncClientList> {
const res = await axios.get(`${syncPath}/list`);
return res.data;
}

export async function connectToHost(settings: SyncHostConnectionRequest) {
await axios.post(`${syncPath}/connect`, settings);
}
68 changes: 34 additions & 34 deletions apps/client/src/common/hooks-query/useAppVersion.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
import { useQuery } from '@tanstack/react-query';
import { dayInMs } from 'ontime-utils';

import { version } from '../../../../../package.json';
import { isLocalhost } from '../../externals';
import { APP_VERSION } from '../api/constants';
import { getLatestVersion, HasUpdate } from '../api/external';

const placeholder: HasUpdate & { hasUpdates: boolean } = { url: '', version: '', hasUpdates: false };

export default function useAppVersion() {
const {
data: fetchData,
status,
isFetching,
isError,
refetch,
} = useQuery({
queryKey: APP_VERSION,
queryFn: getLatestVersion,
placeholderData: (previousData, _previousQuery) => previousData,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: false,
staleTime: dayInMs,
enabled: isLocalhost,
});

const hasUpdates = fetchData?.version && !fetchData.version.includes(version);

const data = fetchData ? { ...fetchData, hasUpdates } : placeholder;

return { data, placeholder, status, isFetching, isError, refetch };
}
import { useQuery } from '@tanstack/react-query';
import { dayInMs } from 'ontime-utils';
import { version } from '../../../../../package.json';
import { isLocalhost } from '../../externals';
import { APP_VERSION } from '../api/constants';
import { getLatestVersion, HasUpdate } from '../api/external';
const placeholder: HasUpdate & { hasUpdates: boolean } = { url: '', version: '', hasUpdates: false };
export default function useAppVersion() {
const {
data: fetchData,
status,
isFetching,
isError,
refetch,
} = useQuery({
queryKey: APP_VERSION,
queryFn: getLatestVersion,
placeholderData: (previousData, _previousQuery) => previousData,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: false,
staleTime: dayInMs,
enabled: isLocalhost,
});
const hasUpdates = fetchData?.version && !fetchData.version.includes(version);
const data = fetchData ? { ...fetchData, hasUpdates } : placeholder;
return { data, placeholder, status, isFetching, isError, refetch };
}
13 changes: 13 additions & 0 deletions apps/client/src/common/hooks-query/useSync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useQuery } from '@tanstack/react-query';

import { getSyncList } from '../api/sync';

export function useSync() {
const { data, status, isError, refetch, isLoading } = useQuery({
queryKey: ['sync-client-list'],
queryFn: getSyncList,
placeholderData: (previousData, _previousQuery) => previousData,
});

return { list: data ?? [], status, isError, refetch, isLoading };
}
2 changes: 1 addition & 1 deletion apps/client/src/common/utils/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export const connectSocket = () => {
ontimeQueryClient.invalidateQueries({ queryKey: APP_SETTINGS });
break;
default: {
target satisfies never;
target satisfies never | RefetchKey.RestorePoint;
break;
}
}
Expand Down
2 changes: 2 additions & 0 deletions apps/client/src/features/app-settings/AppSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import NetworkLogPanel from './panel/network-panel/NetworkLogPanel';
import ProjectPanel from './panel/project-panel/ProjectPanel';
import SettingsPanel from './panel/settings-panel/SettingsPanel';
import ShutdownPanel from './panel/shutdown-panel/ShutdownPanel';
import Sync from './panel/sync-panel/SyncPanel';
import PanelContent from './panel-content/PanelContent';
import PanelList from './panel-list/PanelList';
import useAppSettingsNavigation from './useAppSettingsNavigation';
Expand All @@ -33,6 +34,7 @@ export default function AppSettings() {
{panel === 'network' && <NetworkLogPanel location={location} />}
{panel === 'about' && <AboutPanel />}
{panel === 'shutdown' && <ShutdownPanel />}
{panel === 'sync' && <Sync />}
</PanelContent>
</ErrorBoundary>
</div>
Expand Down
180 changes: 180 additions & 0 deletions apps/client/src/features/app-settings/panel/sync-panel/SyncPanel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { useForm } from 'react-hook-form';
import { SyncHostConnectionRequest, SyncRoll } from 'ontime-types';

import { connectToHost } from '../../../../common/api/sync';
import { maybeAxiosError } from '../../../../common/api/utils';
import Button from '../../../../common/components/buttons/Button';
import Input from '../../../../common/components/input/input/Input';
import Select from '../../../../common/components/select/Select';
import { useSync } from '../../../../common/hooks-query/useSync';
import { preventEscape } from '../../../../common/utils/keyEvent';
import * as Panel from '../../panel-utils/PanelUtils';

export default function Sync() {
const { list, refetch, isLoading } = useSync();
const {
handleSubmit,
register,
reset,
setError,
watch,
setValue,
formState: { isSubmitting, isDirty, isValid, errors },
} = useForm<SyncHostConnectionRequest>({
mode: 'onChange',
defaultValues: { host: 'http://127.0.0.1:4003', roll: SyncRoll.Listener },
resetOptions: {
keepDirtyValues: true,
},
});

const onSubmit = async (formData: SyncHostConnectionRequest) => {
try {
await connectToHost(formData);
} catch (error) {
const message = maybeAxiosError(error);
setError('root', { message });
} finally {
await refetch();
}
};

const submitError = '';
const disableSubmit = isSubmitting || !isValid;

const onReset = () => {
reset();
};

return (
<>
<Panel.Header>Machine Synchronization</Panel.Header>

{list.length === 0 && (
<Panel.Section
as='form'
onSubmit={handleSubmit(onSubmit)}
onKeyDown={(event) => preventEscape(event, onReset)}
id='sync-settings'
>
<Panel.Card>
<Panel.SubHeader>
Connect to a host
<Panel.InlineElements>
<Button disabled={!isDirty || isSubmitting} variant='ghosted' onClick={onReset}>
Reset
</Button>
<Button
type='submit'
form='sync-settings'
name='sync-settings-submit'
loading={isSubmitting}
disabled={disableSubmit}
variant='primary'
>
Connect
</Button>
</Panel.InlineElements>
</Panel.SubHeader>
{submitError && <Panel.Error>{submitError}</Panel.Error>}
<Panel.Divider />
<Panel.Section>
<Panel.Loader isLoading={isLoading} />
<Panel.ListGroup>
<Panel.ListItem>
<Panel.Field title='Host' description='URL of the host ' error={errors.host?.message} />
<Input
id='host'
type='text'
style={{ width: '275px' }}
{...register('host', {
required: { value: true, message: 'Required field' },
})}
/>
</Panel.ListItem>
<Panel.ListItem>
<Panel.Field
title='Roll'
description='Select whether to push or pull the project from the host'
error={errors.roll?.message}
/>
<Select
value={watch('roll')}
onValueChange={(value: SyncRoll | null) => {
if (value === null) return;
setValue('roll', value, { shouldDirty: true });
}}
options={[
{ value: SyncRoll.Controller, label: 'Controller' },
{ value: SyncRoll.Listener, label: 'Listener' },
]}
/>
</Panel.ListItem>
</Panel.ListGroup>
</Panel.Section>
</Panel.Card>
</Panel.Section>
)}
{list.length > 0 && (
<Panel.Section>
<Panel.Card>
<Panel.SubHeader>
Connect to a host
<Panel.InlineElements>
<Button disabled={!isDirty || isSubmitting} variant='ghosted' onClick={onReset}>
Reset
</Button>
<Button
type='submit'
form='sync-settings'
name='sync-settings-submit'
loading={isSubmitting}
disabled={disableSubmit}
variant='primary'
>
Connect
</Button>
</Panel.InlineElements>
</Panel.SubHeader>
<Panel.Description>Description</Panel.Description>
<Panel.Table>
<thead>
<tr>
<td>Client Name</td>
<td>Roll</td>
<td>Action</td>
<td>Host</td>
</tr>
</thead>
<tbody>
{list.map(({ id, name, roll, host }) => {
const isController = roll === SyncRoll.Controller;
const hostName = list.find(({ id }) => id === host)?.name;
return (
<tr key={id}>
<td> {name}</td>
<td> {roll}</td>
<Panel.InlineElements relation='inner' as='td'>
<Button
size='small'
disabled={isController}
variant='primary'
onClick={() => {
console.log('click');
}}
>
Promote To Controller
</Button>
</Panel.InlineElements>
<td> {hostName}</td>
</tr>
);
})}
</tbody>
</Panel.Table>
</Panel.Card>
</Panel.Section>
)}
</>
);
}
2 changes: 2 additions & 0 deletions apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
"dev": "cross-env NODE_ENV=development tsx watch ./src/index.ts",
"dev:electron": "pnpm dev",
"dev:inspect": "cross-env NODE_ENV=development tsx watch --inspect ./src/index.ts",
"dev:synchost": "cross-env NODE_ENV=development HOST_SYNC=true PORT=4003 ONTIME_DATA=../../ontime-db tsx watch ./src/index.ts",


"lint": "eslint . --quiet",
"typecheck": "tsc --noEmit",
Expand Down
17 changes: 13 additions & 4 deletions apps/server/src/adapters/WebsocketAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { logger } from '../classes/Logger.js';
import { dispatchFromAdapter } from '../api-integration/integration.controller.js';
import { generateId } from 'ontime-utils';
import { authenticateSocket } from '../middleware/authenticate.js';
import { syncService } from '../api-data/sync/sync.service.js';

type ClientId = string;
let instance: SocketServer | null = null;
Expand Down Expand Up @@ -115,10 +116,17 @@ class SocketServer implements IAdapter {
case MessageTag.ClientSet: {
const previousData = this.getOrCreateClient(clientId);
const updatedClient = { ...previousData, ...payload };
this.clients.set(clientId, updatedClient);
if (this.shouldShowWelcome && updatedClient.path?.toLowerCase().includes('editor')) {
this.shouldShowWelcome = false;
sendPacket(MessageTag.Dialog, { dialog: 'welcome' });
if (updatedClient.type === 'sync') {
ws.removeAllListeners('message');
ws.removeAllListeners('close');
syncService.handleIncomingWsConnection(ws, clientId, updatedClient);
this.clients.delete(clientId);
} else {
this.clients.set(clientId, updatedClient);
if (this.shouldShowWelcome && updatedClient.path?.toLowerCase().includes('editor')) {
this.shouldShowWelcome = false;
sendPacket(MessageTag.Dialog, { dialog: 'welcome' });
}
}
this.sendClientList();
break;
Expand Down Expand Up @@ -246,5 +254,6 @@ export const socket = new SocketServer();
* Utility function to notify clients that the REST data is stale
*/
export function sendRefetch(target: RefetchKey, revision: MaybeNumber = null) {
syncService.handleRefetch(target);
socket.sendAsJson(MessageTag.Refetch, { target, revision });
}
2 changes: 2 additions & 0 deletions apps/server/src/api-data/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { router as sessionRouter } from './session/session.router.js';
import { router as viewSettingsRouter } from './view-settings/viewSettings.router.js';
import { router as reportRouter } from './report/report.router.js';
import { router as assetsRouter } from './assets/assets.router.js';
import { router as syncRouter } from './sync/sync.router.js';

export const appRouter = express.Router();

Expand All @@ -29,6 +30,7 @@ appRouter.use('/session', sessionRouter);
appRouter.use('/view-settings', viewSettingsRouter);
appRouter.use('/report', reportRouter);
appRouter.use('/assets', assetsRouter);
appRouter.use('/sync', syncRouter);

// we don't want to redirect to react index when using api routes
appRouter.all('/*splat', (_req, res) => {
Expand Down
15 changes: 2 additions & 13 deletions apps/server/src/api-data/rundown/rundown.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
initRundown,
reorderEntry,
swapEvents,
loadRundown,
ungroupEntries,
} from './rundown.service.js';
import {
Expand Down Expand Up @@ -62,19 +63,7 @@ router.get('/current', async (_req: Request, res: Response<Rundown>) => {
*/
router.post('/:id/load', paramsWithId, async (req: Request, res: Response<ProjectRundownsList | ErrorResponse>) => {
try {
// maybe the rundown is already loaded
if (req.params.id === getCurrentRundown().id) {
const projectRundowns = getDataProvider().getProjectRundowns();
res.status(200).json({ loaded: getCurrentRundown().id, rundowns: normalisedToRundownArray(projectRundowns) });
return;
}

const dataProvider = getDataProvider();
const rundown = dataProvider.getRundown(req.params.id);
const customField = dataProvider.getCustomFields();
await initRundown(rundown, customField);

const projectRundowns = getDataProvider().getProjectRundowns();
const projectRundowns = await loadRundown(req.params.id);
res.status(200).json({ loaded: getCurrentRundown().id, rundowns: normalisedToRundownArray(projectRundowns) });
} catch (error) {
const message = getErrorMessage(error);
Expand Down
Loading
Loading