mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-14 03:43:50 +00:00
refactor: use strict typing
This commit is contained in:
committed by
Carlos Valente
parent
4ed38340e0
commit
178640bfc4
@@ -1,11 +1,11 @@
|
||||
import { timerConfig } from '../setup/config.js';
|
||||
import * as runtimeState from '../stores/runtimeState.js';
|
||||
import type { UpdateResult } from '../stores/runtimeState.js';
|
||||
import { timerConfig } from '../config/config.js';
|
||||
|
||||
type UpdateCallbackFn = (updateResult: UpdateResult) => void;
|
||||
|
||||
/**
|
||||
* Service manages Ontime's main timer
|
||||
* Manages Ontime's main timer
|
||||
*/
|
||||
export class EventTimer {
|
||||
private readonly _interval: NodeJS.Timeout;
|
||||
@@ -43,6 +43,14 @@ export class EventTimer {
|
||||
}
|
||||
|
||||
const state = runtimeState.getState();
|
||||
|
||||
// eslint-disable-next-line no-unused-labels -- dev code path
|
||||
DEV: {
|
||||
if (state.timer.current === null) {
|
||||
throw new Error('EventTimer.start: invalid state received');
|
||||
}
|
||||
}
|
||||
|
||||
const endTime = state.timer.current - timerConfig.triggerAhead;
|
||||
this.endCallback = setTimeout(() => this.update(), endTime);
|
||||
return true;
|
||||
|
||||
@@ -45,8 +45,6 @@ export async function getShowWelcomeDialog(): Promise<boolean> {
|
||||
}
|
||||
|
||||
export async function setShowWelcomeDialog(show: boolean): Promise<boolean> {
|
||||
if (isTest) return;
|
||||
|
||||
config.data.showWelcomeDialog = show;
|
||||
await config.write();
|
||||
return show;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { SimpleDirection, SimplePlayback, SimpleTimerState } from 'ontime-types'
|
||||
|
||||
import { SimpleTimer } from '../../classes/simple-timer/SimpleTimer.js';
|
||||
import { eventStore } from '../../stores/EventStore.js';
|
||||
import { timerConfig } from '../../config/config.js';
|
||||
import { timerConfig } from '../../setup/config.js';
|
||||
|
||||
type EmitFn = (state: SimpleTimerState) => void;
|
||||
type GetTimeFn = () => number;
|
||||
@@ -77,7 +77,8 @@ function broadcastReturn(_target: any, _propertyKey: string, descriptor: Propert
|
||||
|
||||
descriptor.value = function (...args: any[]) {
|
||||
const result = originalMethod.apply(this, args);
|
||||
this.emit(result);
|
||||
// @ts-expect-error -- we can access private properties from the decorator
|
||||
(this as AuxTimerService).emit(result);
|
||||
return result;
|
||||
};
|
||||
|
||||
|
||||
@@ -31,7 +31,8 @@ export function clear() {
|
||||
* Exposes the internal state of the message service
|
||||
*/
|
||||
export function getState(): MessageState {
|
||||
return storeGet('message');
|
||||
// we know this exists at runtime
|
||||
return storeGet('message') as MessageState;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { RuntimeStore } from 'ontime-types';
|
||||
|
||||
import * as messageService from '../MessageService.js';
|
||||
|
||||
describe('MessageService', () => {
|
||||
let store: Partial<RuntimeStore>;
|
||||
beforeEach(() => {
|
||||
// at runtime, the store is instantiated before the message service
|
||||
const store = {};
|
||||
const storeSetter = (key, value) => (store[key] = value);
|
||||
const storeGetter = (key) => store[key];
|
||||
messageService.init(storeSetter, storeGetter);
|
||||
store = {};
|
||||
messageService.init(
|
||||
(key, value) => (store[key] = value),
|
||||
(key) => store[key],
|
||||
);
|
||||
messageService.clear();
|
||||
});
|
||||
|
||||
|
||||
@@ -42,6 +42,21 @@ import {
|
||||
} from './projectServiceUtils.js';
|
||||
import { getFirstRundown } from '../rundown-service/rundownUtils.js';
|
||||
|
||||
type ProjectState =
|
||||
| {
|
||||
status: 'PENDING';
|
||||
currentProjectName: undefined;
|
||||
}
|
||||
| {
|
||||
status: 'INITIALIZED';
|
||||
currentProjectName: string;
|
||||
};
|
||||
|
||||
let currentProjectState: ProjectState = {
|
||||
status: 'PENDING',
|
||||
currentProjectName: undefined,
|
||||
};
|
||||
|
||||
// init dependencies
|
||||
init();
|
||||
|
||||
@@ -53,11 +68,17 @@ function init() {
|
||||
ensureDirectory(publicDir.corruptDir);
|
||||
}
|
||||
|
||||
export async function getCurrentProject() {
|
||||
const filename = await getLastLoadedProject();
|
||||
const pathToFile = getPathToProject(filename);
|
||||
export async function getCurrentProject(): Promise<{ filename: string; pathToFile: string }> {
|
||||
if (currentProjectState.status === 'PENDING') {
|
||||
const lastLoadedProject = await initialiseProject();
|
||||
currentProjectState = {
|
||||
status: 'INITIALIZED',
|
||||
currentProjectName: lastLoadedProject,
|
||||
};
|
||||
}
|
||||
const pathToFile = getPathToProject(currentProjectState.currentProjectName);
|
||||
|
||||
return { filename, pathToFile };
|
||||
return { filename: currentProjectState.currentProjectName, pathToFile };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -276,6 +297,9 @@ export async function createProject(filename: string, initialData: Partial<Datab
|
||||
// update app state to point to new value
|
||||
setLastLoadedProject(uniqueFileName);
|
||||
|
||||
// update the service state
|
||||
currentProjectState.currentProjectName = uniqueFileName;
|
||||
|
||||
return uniqueFileName;
|
||||
}
|
||||
|
||||
@@ -283,8 +307,7 @@ export async function createProject(filename: string, initialData: Partial<Datab
|
||||
* Deletes a project file
|
||||
*/
|
||||
export async function deleteProjectFile(filename: string) {
|
||||
const isPreviousProject = await isLastLoadedProject(filename);
|
||||
if (isPreviousProject) {
|
||||
if (filename === currentProjectState.currentProjectName) {
|
||||
throw new Error('Cannot delete currently loaded project');
|
||||
}
|
||||
|
||||
|
||||
@@ -26,11 +26,6 @@ vi.mock('../projectServiceUtils.js', () => ({
|
||||
* controller depend on these to send the right responses
|
||||
*/
|
||||
describe('deleteProjectFile', () => {
|
||||
it('throws an error if trying to delete the currently loaded project', async () => {
|
||||
(isLastLoadedProject as Mock).mockResolvedValue(true);
|
||||
await expect(deleteProjectFile('loadedProject')).rejects.toThrow('Cannot delete currently loaded project');
|
||||
});
|
||||
|
||||
it('throws an error if the project file does not exist', async () => {
|
||||
(isLastLoadedProject as Mock).mockResolvedValue(false);
|
||||
(doesProjectExist as Mock).mockReturnValue(null);
|
||||
|
||||
@@ -18,10 +18,10 @@ import { deepEqual } from 'fast-equals';
|
||||
import { logger } from '../../classes/Logger.js';
|
||||
import * as runtimeState from '../../stores/runtimeState.js';
|
||||
import type { RuntimeState } from '../../stores/runtimeState.js';
|
||||
import { timerConfig } from '../../config/config.js';
|
||||
import { eventStore } from '../../stores/EventStore.js';
|
||||
|
||||
import { triggerReportEntry } from '../../api-data/report/report.service.js';
|
||||
import { timerConfig } from '../../setup/config.js';
|
||||
import { triggerAutomations } from '../../api-data/automation/automation.service.js';
|
||||
|
||||
import { EventTimer } from '../EventTimer.js';
|
||||
import { RestorePoint, restoreService } from '../RestoreService.js';
|
||||
@@ -35,11 +35,10 @@ import {
|
||||
getTimedEvents,
|
||||
getRundownData,
|
||||
} from '../rundown-service/rundownUtils.js';
|
||||
import { skippedOutOfEvent } from '../timerUtils.js';
|
||||
import { getEventOrder } from '../rundown-service/rundownCache.js';
|
||||
|
||||
import { getForceUpdate, getShouldClockUpdate, getShouldTimerUpdate } from './rundownService.utils.js';
|
||||
import { skippedOutOfEvent } from '../timerUtils.js';
|
||||
import { triggerAutomations } from '../../api-data/automation/automation.service.js';
|
||||
import { getEventOrder } from '../rundown-service/rundownCache.js';
|
||||
|
||||
type RuntimeStateEventKeys = keyof Pick<RuntimeState, 'eventNext' | 'eventNow' | 'publicEventNow' | 'publicEventNext'>;
|
||||
|
||||
@@ -48,7 +47,7 @@ type RuntimeStateEventKeys = keyof Pick<RuntimeState, 'eventNext' | 'eventNow' |
|
||||
* Coordinating with necessary services
|
||||
*/
|
||||
class RuntimeService {
|
||||
private eventTimer: EventTimer;
|
||||
private readonly eventTimer: EventTimer;
|
||||
private lastIntegrationClockUpdate = -1;
|
||||
private lastIntegrationTimerValue = -1;
|
||||
|
||||
@@ -819,6 +818,7 @@ function broadcastResult(_target: any, _propertyKey: string, descriptor: Propert
|
||||
|
||||
function storeKey(eventKey: RuntimeStateEventKeys) {
|
||||
eventStore.set(eventKey, state[eventKey]);
|
||||
// @ts-expect-error -- not sure how to type this in a sane way
|
||||
RuntimeService.previousState[eventKey] = { ...state[eventKey] };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { millisToSeconds } from 'ontime-utils';
|
||||
|
||||
import { timerConfig } from '../../config/config.js';
|
||||
import { MaybeNumber } from 'ontime-types';
|
||||
|
||||
import { timerConfig } from '../../setup/config.js';
|
||||
|
||||
/**
|
||||
* Checks whether we should update the clock value
|
||||
* - clock has slid
|
||||
|
||||
@@ -17,7 +17,8 @@ import { parseRundowns } from '../../utils/parserFunctions.js';
|
||||
import { getCurrentRundown, getRundownOrThrow } from '../rundown-service/rundownUtils.js';
|
||||
import { getCustomFields } from '../rundown-service/rundownCache.js';
|
||||
|
||||
import { cellRequestFromEvent, type ClientSecret, getA1Notation, validateClientSecret } from './sheetUtils.js';
|
||||
import { cellRequestFromEvent, type ClientSecret, getA1Notation, isClientSecret } from './sheetUtils.js';
|
||||
import { catchCommonImportXlsxError } from './googleApi.utils.js';
|
||||
|
||||
const sheetScope = 'https://www.googleapis.com/auth/spreadsheets';
|
||||
const codesUrl = 'https://oauth2.googleapis.com/device/code';
|
||||
@@ -69,16 +70,12 @@ export function revoke(): ReturnType<typeof hasAuth> {
|
||||
|
||||
/**
|
||||
* Parses and validates a client secret string
|
||||
* @param clientSecret
|
||||
* @returns
|
||||
*/
|
||||
export function handleClientSecret(clientSecret: string): ClientSecret {
|
||||
const clientSecretObject = JSON.parse(clientSecret);
|
||||
|
||||
try {
|
||||
validateClientSecret(clientSecretObject);
|
||||
} catch (error) {
|
||||
throw new Error(`Client secret is invalid: ${error}`);
|
||||
if (!isClientSecret(clientSecretObject)) {
|
||||
throw new Error('Client secret is invalid');
|
||||
}
|
||||
|
||||
return clientSecretObject;
|
||||
@@ -94,21 +91,26 @@ type CodesResponse = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Establishes connection with Google Auth server
|
||||
* and retrieves device codes
|
||||
* @param clientSecret
|
||||
* @returns
|
||||
* Establishes connection with Google Auth server and retrieves device codes
|
||||
*/
|
||||
async function getDeviceCodes(clientSecret: ClientSecret): Promise<CodesResponse> {
|
||||
const deviceCodes: CodesResponse = await got
|
||||
.post(codesUrl, {
|
||||
json: {
|
||||
client_id: clientSecret.installed.client_id,
|
||||
scope: sheetScope,
|
||||
},
|
||||
})
|
||||
.json();
|
||||
const response = await fetch(codesUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
client_id: clientSecret.installed.client_id,
|
||||
scope: sheetScope,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Failed to fetch device codes: ${response.status} ${response.statusText} - ${errorText}`);
|
||||
}
|
||||
|
||||
const deviceCodes: CodesResponse = await response.json();
|
||||
return deviceCodes;
|
||||
}
|
||||
|
||||
@@ -186,6 +188,9 @@ function verifyConnection(
|
||||
}
|
||||
|
||||
export function hasAuth(): { authenticated: AuthenticationStatus; sheetId: string } {
|
||||
if (!currentSheetId) {
|
||||
throw new Error('No sheet ID');
|
||||
}
|
||||
if (cleanupTimeout) {
|
||||
return { authenticated: 'pending', sheetId: currentSheetId };
|
||||
}
|
||||
@@ -196,22 +201,28 @@ async function verifySheet(
|
||||
sheetId = currentSheetId,
|
||||
authClient = currentAuthClient,
|
||||
): Promise<{ worksheetOptions: string[] }> {
|
||||
if (!sheetId || !authClient) {
|
||||
throw new Error('Missing sheet ID or authentication');
|
||||
}
|
||||
|
||||
try {
|
||||
const spreadsheets = await sheets({ version: 'v4', auth: authClient }).spreadsheets.get({
|
||||
spreadsheetId: sheetId,
|
||||
includeGridData: false,
|
||||
});
|
||||
return { worksheetOptions: spreadsheets.data.sheets.map((i) => i.properties.title) };
|
||||
const worksheets = spreadsheets.data.sheets?.forEach((sheet) => {
|
||||
if (sheet.properties?.title) {
|
||||
return sheet.properties.title;
|
||||
}
|
||||
});
|
||||
|
||||
if (!worksheets) {
|
||||
throw new Error('No worksheets found');
|
||||
}
|
||||
return worksheets;
|
||||
} catch (error) {
|
||||
// attempt to catch errors caused by importing xlsx
|
||||
if (
|
||||
error.code === 400 &&
|
||||
Array.isArray(error.errors) &&
|
||||
error.errors[0].reason === 'failedPrecondition' &&
|
||||
error.errors[0].message === 'This operation is not supported for this document'
|
||||
) {
|
||||
throw new Error('Cannot read the linked file as a Google Sheet. It may be an .xlsx file instead.');
|
||||
}
|
||||
catchCommonImportXlsxError(error);
|
||||
const errorMessage = getErrorMessage(error);
|
||||
throw new Error(`Failed to verify sheet: ${errorMessage}`);
|
||||
}
|
||||
@@ -227,6 +238,9 @@ export async function handleInitialConnection(
|
||||
// we know there is an ongoing process if there is a timeout for cleanup
|
||||
// if there is an ongoing process, we return its data
|
||||
if (cleanupTimeout) {
|
||||
if (!currentAuthUrl || !currentAuthCode) {
|
||||
throw new Error('No ongoing connection');
|
||||
}
|
||||
return { verification_url: currentAuthUrl, user_code: currentAuthCode };
|
||||
}
|
||||
|
||||
@@ -255,6 +269,10 @@ export async function getWorksheetOptions(sheetId: string): ReturnType<typeof ve
|
||||
}
|
||||
|
||||
async function verifyWorksheet(sheetId: string, worksheet: string): Promise<{ worksheetId: number; range: string }> {
|
||||
if (!currentAuthClient) {
|
||||
throw new Error('Not authenticated');
|
||||
}
|
||||
|
||||
const spreadsheets = await sheets({ version: 'v4', auth: currentAuthClient }).spreadsheets.get({
|
||||
spreadsheetId: sheetId,
|
||||
});
|
||||
@@ -263,22 +281,33 @@ async function verifyWorksheet(sheetId: string, worksheet: string): Promise<{ wo
|
||||
throw new Error(`Request failed: ${spreadsheets.status} ${spreadsheets.statusText}`);
|
||||
}
|
||||
|
||||
if (!spreadsheets.data.sheets) {
|
||||
throw new Error('No worksheets found');
|
||||
}
|
||||
|
||||
const selectedWorksheet = spreadsheets.data.sheets.find(
|
||||
(n) => n.properties.title.toLowerCase() === worksheet.toLowerCase(),
|
||||
(sheet) => sheet.properties?.title && sheet.properties.title.toLowerCase() === worksheet.toLowerCase(),
|
||||
);
|
||||
|
||||
if (!selectedWorksheet) {
|
||||
throw new Error('Could not find worksheet');
|
||||
}
|
||||
if (!selectedWorksheet.properties || !selectedWorksheet.properties.sheetId) {
|
||||
throw new Error('Got invalid data from worksheet');
|
||||
}
|
||||
|
||||
const endCell = getA1Notation(
|
||||
selectedWorksheet.properties.gridProperties.rowCount,
|
||||
selectedWorksheet.properties.gridProperties.columnCount,
|
||||
selectedWorksheet.properties?.gridProperties?.rowCount ?? -1,
|
||||
selectedWorksheet.properties?.gridProperties?.columnCount ?? -1,
|
||||
);
|
||||
return { worksheetId: selectedWorksheet.properties.sheetId, range: `${worksheet}!A1:${endCell}` };
|
||||
}
|
||||
|
||||
export async function upload(sheetId: string, options: ImportMap) {
|
||||
if (!currentAuthClient) {
|
||||
throw new Error('Not authenticated');
|
||||
}
|
||||
|
||||
const { worksheetId, range } = await verifyWorksheet(sheetId, options.worksheet);
|
||||
|
||||
const readResponse = await sheets({ version: 'v4', auth: currentAuthClient }).spreadsheets.values.get({
|
||||
@@ -288,7 +317,7 @@ export async function upload(sheetId: string, options: ImportMap) {
|
||||
range,
|
||||
});
|
||||
|
||||
if (readResponse.status !== 200) {
|
||||
if (readResponse.status !== 200 || !readResponse.data.values) {
|
||||
throw new Error(`Sheet read failed: ${readResponse.statusText}`);
|
||||
}
|
||||
|
||||
@@ -357,6 +386,10 @@ export async function download(
|
||||
rundown: Rundown;
|
||||
customFields: CustomFields;
|
||||
}> {
|
||||
if (!currentAuthClient) {
|
||||
throw new Error('Not authenticated');
|
||||
}
|
||||
|
||||
const { range } = await verifyWorksheet(sheetId, options.worksheet);
|
||||
|
||||
const googleResponse = await sheets({ version: 'v4', auth: currentAuthClient }).spreadsheets.values.get({
|
||||
@@ -370,6 +403,10 @@ export async function download(
|
||||
throw new Error(`Sheet read failed: ${googleResponse.statusText}`);
|
||||
}
|
||||
|
||||
if (!googleResponse.data.values) {
|
||||
throw new Error('Sheet: No data found in the worksheet');
|
||||
}
|
||||
|
||||
const dataFromSheet = parseExcel(googleResponse.data.values, getCustomFields(), 'Rundown', options);
|
||||
|
||||
const rundownId = dataFromSheet.rundown.id;
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// https://developers.google.com/calendar/api/guides/errors
|
||||
interface GoogleApiError {
|
||||
code: number;
|
||||
message: string;
|
||||
errors?: {
|
||||
message: string;
|
||||
domain: string;
|
||||
reason: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether an error is a Google API error
|
||||
*/
|
||||
function isGoogleApiError(error: any): error is GoogleApiError {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
typeof error.code === 'number' &&
|
||||
Array.isArray(error.errors) &&
|
||||
typeof error.errors[0]?.reason === 'string' &&
|
||||
typeof error.errors[0]?.message === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract utility to handle a common error where a user imports an xlsx file instead of a Google Sheet
|
||||
*/
|
||||
export function catchCommonImportXlsxError(error: any) {
|
||||
if (
|
||||
isGoogleApiError(error) &&
|
||||
error.code === 400 &&
|
||||
Array.isArray(error.errors) &&
|
||||
error.errors[0].reason === 'failedPrecondition' &&
|
||||
error.errors[0].message === 'This operation is not supported for this document'
|
||||
) {
|
||||
throw new Error('Cannot read the linked file as a Google Sheet. It may be an .xlsx file instead.');
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,7 @@ import { isOntimeBlock, isOntimeEvent, OntimeEvent, OntimeEntry } from 'ontime-t
|
||||
import { millisToString } from 'ontime-utils';
|
||||
|
||||
import type { sheets_v4 } from '@googleapis/sheets';
|
||||
import { isObject } from '../../utils/assert.js';
|
||||
|
||||
// we expect client secret file to contain the following keys
|
||||
const requiredClientKeys = [
|
||||
'client_id',
|
||||
'auth_uri',
|
||||
'token_uri',
|
||||
'token_uri',
|
||||
'auth_provider_x509_cert_url',
|
||||
'client_secret',
|
||||
];
|
||||
import { is } from '../../utils/is.js';
|
||||
|
||||
export type ClientSecret = {
|
||||
installed: {
|
||||
@@ -29,19 +19,25 @@ export type ClientSecret = {
|
||||
* @param clientSecret
|
||||
* @throws
|
||||
*/
|
||||
export function validateClientSecret(clientSecret: object): clientSecret is ClientSecret {
|
||||
export function isClientSecret(clientSecret: object): clientSecret is ClientSecret {
|
||||
if (!('installed' in clientSecret)) {
|
||||
throw new Error('Missing "installed" object');
|
||||
return false;
|
||||
}
|
||||
|
||||
const { installed } = clientSecret;
|
||||
isObject(installed);
|
||||
|
||||
if (requiredClientKeys.every((key) => Object.keys(installed).includes(key))) {
|
||||
return;
|
||||
if (!is.object(installed)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw new Error('Missing keys in "installed" object');
|
||||
// we expect client secret file to contain the following keys
|
||||
return is.objectWithKeys(installed, [
|
||||
'client_id',
|
||||
'auth_uri',
|
||||
'token_uri',
|
||||
'token_uri',
|
||||
'auth_provider_x509_cert_url',
|
||||
'client_secret',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user