mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-12 19:03:47 +00:00
V3 (#657)
* refactor: cleanup routes * style: smaller base font * chore: upgrade dependencies * chore: lock node version to electron * refactor: pass HTTP to integration controller (#652) * refactor: deprecate onair control * refactor: remove playback router * Several project files user folder (#617) * chore: automated screenshots (#667) * feat: app settings (#658) * refactor: remove deprecated event data (#674) * Studio clock (#663) --------- Co-authored-by: Carlos Valente <carlosvalente@pm.me> * Feat: reorder events with alt+ctrl + arrow up/down (#645) * Warning and danger per event (#677) --------- Co-authored-by: Fabian Posenau <fabian@fphome.de> * refactor: stabilise actionHandler (#683) Co-authored-by: Fabian Posenau <fabian@fphome.de> * improvement: hide seconds (#675) * wip: overview (#688) * fix: focus cursor (#695) * refactor: update lower third (#665) * Refactor/time formatting (#696) --------- Co-authored-by: Carlos Valente <34649812+cpvalente@users.noreply.github.com> Co-authored-by: Carlos Valente <carlosvalente@pm.me> * feat: multiple selection (#703) --------- Co-authored-by: asharonbaltazar <asharonbaltazar@outlook.com> Co-authored-by: Alex <ac@omnivox.dk> * fix: test - go to `Edit mode` befor tying to click `Event options` button (#708) * refactor: runtime service (#715) * fix: issue with loosing cursor position on message (#719) * remove info panel (#721) * Event editor continue (#722) * update API - part (#709) --------- Co-authored-by: Carlos Valente <34649812+cpvalente@users.noreply.github.com> Co-authored-by: Carlos Valente <carlosvalente@pm.me> * refactor: update timers (#729) * feat: many timers (#706) --------- Co-authored-by: arc-alex <ac@omnivox.dk> * refactor: excel cleanup (#734) * refactor: allow import of blocks and skip import (#735) * Project manager (#697) * refactor: UI for linking events (#763) * upgraded pipeline actions (#777) * Over under (#771) * custom fields (#744) --------- Co-authored-by: Carlos Valente <carlosvalente@pm.me> * Sheets settings (#774) --------- Co-authored-by: arc-alex <ac@omnivox.dk> * style: tweaks to lower thirds (#785) * refactor: delays account for gaps (#784) * refactor: partial state updates (#780) * feat: generate crash report (#787) * Sheet use limited input device auth flow (#782) --------- Co-authored-by: cv <34649812+cpvalente@users.noreply.github.com> Co-authored-by: Carlos Valente <carlosvalente@pm.me> * Custom fields views (#789) * refactor: deprecate presenter and subtitle (#795) * refactor: organise API around resources (#798) --------- Co-authored-by: Bianca Procopio <biancahprocopio@gmail.com> * Time to end (#804) * Skip fixes (#805) * fix: onair derives from playback * Param nav (#822) --------- Co-authored-by: Alex Christoffer Rasmussen <ac@omnivox.dk> * refactor: download files from interface (#831) * Quick options (#814) * End pause (#832) * chore: bump node version in docker (#834) * refactor: follow in run mode (#840) * fix: uncaught error in http integration (#837) * Apply project (#843) Co-authored-by: Matteo Gheza <matteo.gheza07@gmail.com> Co-authored-by: Ary <arylmoraesn@gmail.com> Co-authored-by: Alex Christoffer Rasmussen <ac@omnivox.dk> Co-authored-by: Fabian Posenau <19673098+kellhogs@users.noreply.github.com> Co-authored-by: Fabian Posenau <fabian@fphome.de> Co-authored-by: Alex Rohleder <alexrohleder96@gmail.com> Co-authored-by: asharonbaltazar <asharonbaltazar@outlook.com> Co-authored-by: Bianca Procopio <biancahprocopio@gmail.com> Co-authored-by: Fabian Posenau <fabianpos99+github@gmail.com>
This commit is contained in:
@@ -1,54 +0,0 @@
|
||||
import { insertAtIndex, reorderArray } from '../arrayUtils.js';
|
||||
|
||||
describe('insertAtIndex', () => {
|
||||
it('should insert an item at the beginning of the array', () => {
|
||||
const array = [2, 3, 4];
|
||||
const result = insertAtIndex(0, 1, array);
|
||||
expect(result).toEqual([1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it('should insert an item at the end of the array', () => {
|
||||
const array = [1, 2, 3];
|
||||
const result = insertAtIndex(3, 4, array);
|
||||
expect(result).toEqual([1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it('should insert an item in the middle of the array', () => {
|
||||
const array = [1, 2, 4];
|
||||
const result = insertAtIndex(2, 3, array);
|
||||
expect(result).toEqual([1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it('should return a new array and not modify the original array', () => {
|
||||
const array = [1, 2, 3];
|
||||
const result = insertAtIndex(1, 5, array);
|
||||
expect(result).toEqual([1, 5, 2, 3]);
|
||||
expect(array).toEqual([1, 2, 3]); // Original array should remain unchanged
|
||||
});
|
||||
});
|
||||
|
||||
describe('reorderArray', () => {
|
||||
it('should reorder an item in the array', () => {
|
||||
const array = ['a', 'b', 'c', 'd'];
|
||||
const result = reorderArray(array, 1, 3);
|
||||
expect(result).toEqual(['a', 'c', 'd', 'b']);
|
||||
});
|
||||
|
||||
it('should return the original array if fromIndex and toIndex are the same', () => {
|
||||
const array = ['a', 'b', 'c'];
|
||||
const result = reorderArray(array, 1, 1);
|
||||
expect(result).toEqual(array);
|
||||
});
|
||||
|
||||
it('should handle reordering to the beginning of the array', () => {
|
||||
const array = ['a', 'b', 'c'];
|
||||
const result = reorderArray(array, 2, 0);
|
||||
expect(result).toEqual(['c', 'a', 'b']);
|
||||
});
|
||||
|
||||
it('should handle reordering to the end of the array', () => {
|
||||
const array = ['a', 'b', 'c'];
|
||||
const result = reorderArray(array, 0, 2);
|
||||
expect(result).toEqual(['b', 'c', 'a']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ensureJsonExtension } from '../fileManagement.js';
|
||||
|
||||
describe('ensureJsonExtension', () => {
|
||||
it('should add .json to a filename without an extension', () => {
|
||||
const filename = 'testfile';
|
||||
const result = ensureJsonExtension(filename);
|
||||
expect(result).toBe('testfile.json');
|
||||
});
|
||||
|
||||
it('should not add .json to a filename that already has .json', () => {
|
||||
const filename = 'testfile.json';
|
||||
const result = ensureJsonExtension(filename);
|
||||
expect(result).toBe('testfile.json');
|
||||
});
|
||||
|
||||
it('should add .json to a filename with a different extension', () => {
|
||||
const filename = 'testfile.txt';
|
||||
const result = ensureJsonExtension(filename);
|
||||
expect(result).toBe('testfile.txt.json');
|
||||
});
|
||||
|
||||
it('should handle filenames with multiple dots', () => {
|
||||
const filename = 'my.test.file';
|
||||
const result = ensureJsonExtension(filename);
|
||||
expect(result).toBe('my.test.file.json');
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,162 +1,73 @@
|
||||
import { HttpSubscription, OscSubscription } from 'ontime-types';
|
||||
import {
|
||||
validateOscSubscriptionObject,
|
||||
validateOscSubscriptionCycle,
|
||||
validateHttpSubscriptionCycle,
|
||||
validateHttpSubscriptionObject,
|
||||
} from '../parserFunctions.js';
|
||||
import { sanitiseHttpSubscriptions, sanitiseOscSubscriptions } from '../parserFunctions.js';
|
||||
|
||||
describe('validateOscSubscriptionCycle()', () => {
|
||||
it('should return false when given an OscSubscription with an invalid property value', () => {
|
||||
const invalidEntry = [{ message: 'test', enabled: 'not a boolean' }];
|
||||
describe('sanitiseOscSubscriptions()', () => {
|
||||
it('returns an empty array if not an array', () => {
|
||||
expect(sanitiseOscSubscriptions(undefined)).toEqual([]);
|
||||
// @ts-expect-error -- data is external, we check bad types
|
||||
expect(sanitiseOscSubscriptions({})).toEqual([]);
|
||||
expect(sanitiseOscSubscriptions(null)).toEqual([]);
|
||||
});
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionCycle(invalidEntry);
|
||||
expect(result).toBe(false);
|
||||
it('returns an array of valid entries', () => {
|
||||
const oscSubscriptions: OscSubscription[] = [
|
||||
{ id: '1', cycle: 'onLoad', address: '/test', payload: 'test', enabled: true },
|
||||
{ id: '2', cycle: 'onStart', address: '/test', payload: 'test', enabled: false },
|
||||
{ id: '3', cycle: 'onPause', address: '/test', payload: 'test', enabled: true },
|
||||
{ id: '4', cycle: 'onStop', address: '/test', payload: 'test', enabled: false },
|
||||
{ id: '5', cycle: 'onUpdate', address: '/test', payload: 'test', enabled: true },
|
||||
{ id: '6', cycle: 'onFinish', address: '/test', payload: 'test', enabled: false },
|
||||
];
|
||||
const sanitationResult = sanitiseOscSubscriptions(oscSubscriptions);
|
||||
expect(sanitationResult).toStrictEqual(oscSubscriptions);
|
||||
});
|
||||
|
||||
it('filters invalid entries', () => {
|
||||
const oscSubscriptions = [
|
||||
{ id: '1', cycle: 'onLoad', address: 4, payload: 'test', enabled: true },
|
||||
{ cycle: 'onLoad', payload: 'test', enabled: true },
|
||||
{ id: '2', cycle: 'unknown', payload: 'test', enabled: false },
|
||||
{ id: '3', payload: 'test', enabled: true },
|
||||
{ id: '4', cycle: 'onStop', enabled: false },
|
||||
{ id: '5', cycle: 'onUpdate', payload: 'test' },
|
||||
{ id: '6', cycle: 'onFinish', payload: 'test', enabled: 'true' },
|
||||
];
|
||||
const sanitationResult = sanitiseOscSubscriptions(oscSubscriptions as OscSubscription[]);
|
||||
expect(sanitationResult.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateOscSubscriptionObject()', () => {
|
||||
it('should return true when given a valid OscSubscription', () => {
|
||||
const validSubscription: OscSubscription = {
|
||||
onLoad: [{ message: 'test', enabled: true }],
|
||||
onStart: [{ message: 'test', enabled: false }],
|
||||
onPause: [{ message: 'test', enabled: true }],
|
||||
onStop: [{ message: 'test', enabled: false }],
|
||||
onUpdate: [{ message: 'test', enabled: true }],
|
||||
onFinish: [{ message: 'test', enabled: false }],
|
||||
};
|
||||
|
||||
const result = validateOscSubscriptionObject(validSubscription);
|
||||
expect(result).toBe(true);
|
||||
describe('sanitiseHttpSubscriptions()', () => {
|
||||
it('returns an empty array if not an array', () => {
|
||||
expect(sanitiseHttpSubscriptions(undefined)).toEqual([]);
|
||||
// @ts-expect-error -- data is external, we check bad types
|
||||
expect(sanitiseHttpSubscriptions({})).toEqual([]);
|
||||
expect(sanitiseHttpSubscriptions(null)).toEqual([]);
|
||||
});
|
||||
|
||||
it('should return false when given undefined', () => {
|
||||
const result = validateOscSubscriptionObject(undefined);
|
||||
expect(result).toBe(false);
|
||||
it('returns an array of valid entries', () => {
|
||||
const httpSubscription: HttpSubscription[] = [
|
||||
{ id: '1', cycle: 'onLoad', message: 'http://test', enabled: true },
|
||||
{ id: '2', cycle: 'onStart', message: 'http://test', enabled: false },
|
||||
{ id: '3', cycle: 'onPause', message: 'http://test', enabled: true },
|
||||
{ id: '4', cycle: 'onStop', message: 'http://test', enabled: false },
|
||||
{ id: '5', cycle: 'onUpdate', message: 'http://test', enabled: true },
|
||||
{ id: '6', cycle: 'onFinish', message: 'http://test', enabled: false },
|
||||
];
|
||||
const sanitationResult = sanitiseHttpSubscriptions(httpSubscription);
|
||||
expect(sanitationResult).toStrictEqual(httpSubscription);
|
||||
});
|
||||
|
||||
it('should return false when given null', () => {
|
||||
const result = validateOscSubscriptionObject(null);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an empty object', () => {
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionObject({});
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an empty array', () => {
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionObject([]);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an object that is not an OscSubscription', () => {
|
||||
const invalidObject = { foo: 'bar' };
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionObject(invalidObject);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an OscSubscription with a missing property', () => {
|
||||
const invalidSubscription = {
|
||||
onLoad: [{ message: 'test', enabled: true }],
|
||||
onStart: [{ message: 'test', enabled: false }],
|
||||
onPause: [{ message: 'test', enabled: true }],
|
||||
// Missing onStop
|
||||
onUpdate: [{ message: 'test', enabled: true }],
|
||||
onFinish: [{ message: 'test', enabled: false }],
|
||||
};
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionObject(invalidSubscription);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateHttpSubscriptionCycle()', () => {
|
||||
it('should return false when given an HttpSubscription with an invalid property value', () => {
|
||||
const invalidBoolean = [{ message: 'http://', enabled: 'not a boolean' }];
|
||||
const invalidHttp = [{ message: 'test', enabled: true }];
|
||||
const noFtp = [{ message: 'ftp://test', enabled: true }];
|
||||
const noEmpty = [{ message: '', enabled: true }];
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
expect(validateHttpSubscriptionCycle(invalidBoolean)).toBe(false);
|
||||
|
||||
expect(validateHttpSubscriptionCycle(invalidHttp)).toBe(false);
|
||||
expect(validateHttpSubscriptionCycle(noFtp)).toBe(false);
|
||||
expect(validateHttpSubscriptionCycle(noEmpty)).toBe(false);
|
||||
});
|
||||
it('should return true when given an HttpSubscription matches definition', () => {
|
||||
const validHttp = [{ message: 'http://', enabled: true }];
|
||||
const invalidHttps = [{ message: 'https://', enabled: true }];
|
||||
|
||||
expect(validateHttpSubscriptionCycle(validHttp)).toBe(true);
|
||||
expect(validateHttpSubscriptionCycle(invalidHttps)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateHttpSubscriptionObject()', () => {
|
||||
it('should return true when given a valid HttpSubscription', () => {
|
||||
const validSubscription: HttpSubscription = {
|
||||
onLoad: [{ message: 'http://', enabled: true }],
|
||||
onStart: [{ message: 'http://', enabled: false }],
|
||||
onPause: [{ message: 'http://', enabled: true }],
|
||||
onStop: [{ message: 'http://', enabled: false }],
|
||||
onUpdate: [{ message: 'http://', enabled: true }],
|
||||
onFinish: [{ message: 'http://', enabled: false }],
|
||||
};
|
||||
|
||||
const result = validateHttpSubscriptionObject(validSubscription);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when given undefined', () => {
|
||||
const result = validateHttpSubscriptionObject(undefined);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given null', () => {
|
||||
const result = validateHttpSubscriptionObject(null);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an empty object', () => {
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateOscSubscriptionObject({});
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an empty array', () => {
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateHttpSubscriptionObject([]);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an object that is not an HttpSubscription', () => {
|
||||
const invalidObject = { foo: 'bar' };
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateHttpSubscriptionObject(invalidObject);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when given an HttpSubscription with a missing property', () => {
|
||||
const invalidSubscription = {
|
||||
onLoad: [{ message: 'http://', enabled: true }],
|
||||
onStart: [{ message: 'http://', enabled: false }],
|
||||
onPause: [{ message: 'http://', enabled: true }],
|
||||
// Missing onStop
|
||||
onUpdate: [{ message: 'http://', enabled: true }],
|
||||
onFinish: [{ message: 'http://', enabled: false }],
|
||||
};
|
||||
|
||||
// @ts-expect-error -- since this comes from the client, we check things that typescript would have caught
|
||||
const result = validateHttpSubscriptionObject(invalidSubscription);
|
||||
expect(result).toBe(false);
|
||||
it('filters invalid entries', () => {
|
||||
const httpSubscription = [
|
||||
{ cycle: 'onLoad', message: 'http://test', enabled: true },
|
||||
{ id: '2', cycle: 'unknown', message: 'http://test', enabled: false },
|
||||
{ id: '3', message: 'http://test', enabled: true },
|
||||
{ id: '4', cycle: 'onStop', enabled: false },
|
||||
{ id: '5', cycle: 'onUpdate', message: 'http://test' },
|
||||
{ id: '6', cycle: 'onFinish', message: 'ftp://test', enabled: 'true' },
|
||||
];
|
||||
const sanitationResult = sanitiseHttpSubscriptions(httpSubscription as HttpSubscription[]);
|
||||
expect(sanitationResult.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -37,7 +37,7 @@ describe('parseExcelDate', () => {
|
||||
});
|
||||
|
||||
describe('parses a time string that passes validation', () => {
|
||||
const validFields = ['10:00:00', '10:00'];
|
||||
const validFields = ['10:00:00', '10:00', '10:00AM', '10:00am', '10:00PM', '10:00pm'];
|
||||
validFields.forEach((field) => {
|
||||
it(`handles ${field}`, () => {
|
||||
const millis = parseExcelDate(field);
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
* Inserts an item in an array at a given index
|
||||
* @param index
|
||||
* @param item
|
||||
* @param array
|
||||
*/
|
||||
export function insertAtIndex<T>(index: number, item: T, array: T[]): T[] {
|
||||
const modifiedArray = [...array];
|
||||
|
||||
// Insert at beginning
|
||||
if (index === 0) {
|
||||
modifiedArray.unshift(item);
|
||||
}
|
||||
|
||||
// insert at end
|
||||
else if (index >= modifiedArray.length) {
|
||||
modifiedArray.push(item);
|
||||
}
|
||||
|
||||
// insert in the middle
|
||||
else {
|
||||
modifiedArray.splice(index, 0, item);
|
||||
}
|
||||
|
||||
return modifiedArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes array element at a given index
|
||||
* @param index
|
||||
* @param array
|
||||
*/
|
||||
export function deleteAtIndex<T>(index: number, array: T[]) {
|
||||
return array.filter((_, i) => i !== index);
|
||||
}
|
||||
|
||||
export function reorderArray<T>(array: T[], fromIndex: number, toIndex: number) {
|
||||
if (fromIndex === toIndex) {
|
||||
return array; // No change needed, return the original array
|
||||
}
|
||||
|
||||
const modifiedArray = [...array];
|
||||
|
||||
// delete in from
|
||||
const [reorderedItem] = modifiedArray.splice(fromIndex, 1);
|
||||
|
||||
// reinsert item at to
|
||||
modifiedArray.splice(toIndex, 0, reorderedItem);
|
||||
return modifiedArray;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export function isString(value: unknown): asserts value is string {
|
||||
if (typeof value !== 'string') {
|
||||
throw new Error(`Unexpected payload type: ${String(value)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function isDefined<T>(value: T | undefined): asserts value is T {
|
||||
if (value === undefined) {
|
||||
throw new Error('Payload not found');
|
||||
}
|
||||
}
|
||||
|
||||
export function isNumber(value: unknown): asserts value is number {
|
||||
if (typeof value !== 'number') {
|
||||
throw new Error(`Unexpected payload type: ${String(value)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function isObject(value: unknown): asserts value is object {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
throw new Error(`Unexpected payload type: ${String(value)}`);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import { existsSync, mkdirSync } from 'fs';
|
||||
import { readdir } from 'fs/promises';
|
||||
import { parse } from 'path';
|
||||
|
||||
/**
|
||||
* @description Creates a directory if it doesn't exist
|
||||
* @param {string} directory - directory that should exist or will be created
|
||||
*/
|
||||
export function ensureDirectory(directory) {
|
||||
export function ensureDirectory(directory: string): void {
|
||||
if (!existsSync(directory)) {
|
||||
try {
|
||||
mkdirSync(directory, { recursive: true });
|
||||
@@ -13,3 +15,27 @@ export function ensureDirectory(directory) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that a filename ends with .json extension
|
||||
*/
|
||||
export function ensureJsonExtension(filename: string): string {
|
||||
if (!filename) return filename;
|
||||
|
||||
return filename.includes('.json') ? filename : `${filename}.json`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists all files in a directory
|
||||
*/
|
||||
export async function getFilesFromFolder(folderPath: string): Promise<string[]> {
|
||||
return await readdir(folderPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Takes a filename and removes the extension
|
||||
* @param {string} filename - filename with extension
|
||||
*/
|
||||
export const removeFileExtension = (filename: string): string => {
|
||||
return parse(filename).name;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { writeFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { ONTIME_VERSION } from '../ONTIME_VERSION.js';
|
||||
import { get } from '../services/rundown-service/rundownCache.js';
|
||||
import { getState } from '../stores/runtimeState.js';
|
||||
import { resolveCrashReportDirectory } from '../setup/index.js';
|
||||
|
||||
/**
|
||||
* Writes a file to the crash report location
|
||||
* @param fileName
|
||||
* @param content
|
||||
*/
|
||||
function writeToFile(fileName: string, content: object) {
|
||||
const path = join(resolveCrashReportDirectory, fileName);
|
||||
try {
|
||||
const textContent = JSON.stringify(content, null, 2);
|
||||
writeFileSync(path, textContent);
|
||||
} catch (e_rror) {
|
||||
/** We do not handle the error here */
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Generates a crash report
|
||||
* @param error
|
||||
*/
|
||||
export function generateCrashReport(maybeError: unknown) {
|
||||
const timeNow = new Date().toISOString();
|
||||
const runtimeState = getState();
|
||||
const rundownState = get();
|
||||
const error =
|
||||
maybeError instanceof Error
|
||||
? {
|
||||
message: maybeError.message,
|
||||
stack: maybeError.stack || 'No stack trace available',
|
||||
}
|
||||
: String(maybeError);
|
||||
|
||||
const crashReport = {
|
||||
time: timeNow,
|
||||
version: ONTIME_VERSION,
|
||||
error,
|
||||
runtimeState,
|
||||
rundownState,
|
||||
};
|
||||
|
||||
writeToFile(`crash-log-${timeNow}.log`, crashReport);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { existsSync } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
/**
|
||||
* Generates a unique file name within the specified directory.
|
||||
* If a file with the same name already exists, appends a counter to the filename.
|
||||
*/
|
||||
export const generateUniqueFileName = (directory: string, filename: string): string => {
|
||||
const baseName = path.basename(filename, path.extname(filename));
|
||||
const extension = path.extname(filename);
|
||||
|
||||
let counter = 0;
|
||||
let uniqueFilename = filename;
|
||||
|
||||
while (fileExists(uniqueFilename)) {
|
||||
counter++;
|
||||
// Append counter to filename if the file exists.
|
||||
uniqueFilename = `${baseName} (${counter})${extension}`;
|
||||
}
|
||||
|
||||
return uniqueFilename;
|
||||
|
||||
function fileExists(name: string) {
|
||||
return existsSync(path.join(directory, name));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import { networkInterfaces } from 'os';
|
||||
|
||||
/**
|
||||
* @description Gets information on IPV4 non-internal interfaces
|
||||
* @returns {array} - Array of objects {name: ip}
|
||||
*/
|
||||
export function getNetworkInterfaces(): { name: string; address: string }[] {
|
||||
const nets = networkInterfaces();
|
||||
const results: { name: string; address: string }[] = [];
|
||||
|
||||
for (const name of Object.keys(nets)) {
|
||||
for (const net of nets[name]) {
|
||||
// Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
|
||||
if (net.family === 'IPv4' && !net.internal) {
|
||||
results.push({
|
||||
name,
|
||||
address: net.address,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
+200
-314
@@ -1,38 +1,36 @@
|
||||
import {
|
||||
defaultImportMap,
|
||||
generateId,
|
||||
isExcelImportMap,
|
||||
type ExcelImportMap,
|
||||
defaultExcelImportMap,
|
||||
type ImportMap,
|
||||
isKnownTimerType,
|
||||
validateEndAction,
|
||||
validateLinkStart,
|
||||
validateTimerType,
|
||||
type ExcelImportOptions,
|
||||
validateTimes,
|
||||
} from 'ontime-utils';
|
||||
import {
|
||||
CustomFields,
|
||||
DatabaseModel,
|
||||
EventCustomFields,
|
||||
OntimeBlock,
|
||||
OntimeEvent,
|
||||
OntimeRundown,
|
||||
SupportedEvent,
|
||||
ProjectData,
|
||||
UserFields,
|
||||
EndAction,
|
||||
TimerType,
|
||||
TimeStrategy,
|
||||
} from 'ontime-types';
|
||||
|
||||
import fs from 'fs';
|
||||
import xlsx from 'node-xlsx';
|
||||
|
||||
import { event as eventDef } from '../models/eventsDefinition.js';
|
||||
import { dbModel } from '../models/dataModel.js';
|
||||
import { deleteFile, makeString } from './parserUtils.js';
|
||||
import { makeString } from './parserUtils.js';
|
||||
import {
|
||||
parseAliases,
|
||||
parseProject,
|
||||
parseOsc,
|
||||
parseCustomFields,
|
||||
parseHttp,
|
||||
parseOsc,
|
||||
parseProject,
|
||||
parseRundown,
|
||||
parseSettings,
|
||||
parseUserFields,
|
||||
parseUrlPresets,
|
||||
parseViewSettings,
|
||||
} from './parserFunctions.js';
|
||||
import { parseExcelDate } from './time.js';
|
||||
@@ -41,46 +39,51 @@ import { coerceBoolean } from './coerceType.js';
|
||||
export const EXCEL_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||||
export const JSON_MIME = 'application/json';
|
||||
|
||||
type ExcelData = Pick<DatabaseModel, 'rundown' | 'customFields'> & {
|
||||
rundownMetadata: Record<string, { row: number; col: number }>;
|
||||
};
|
||||
|
||||
export function getCustomFieldData(importMap: ImportMap): {
|
||||
customFields: CustomFields;
|
||||
customFieldImportKeys: Record<keyof CustomFields, string>;
|
||||
} {
|
||||
const customFields = {};
|
||||
const customFieldImportKeys = {};
|
||||
for (const ontimeLabel in importMap.custom) {
|
||||
const ontimeKey = ontimeLabel.toLowerCase();
|
||||
const importLabel = importMap.custom[ontimeLabel].toLowerCase();
|
||||
customFields[ontimeKey] = {
|
||||
type: 'string',
|
||||
colour: '',
|
||||
label: ontimeLabel,
|
||||
};
|
||||
customFieldImportKeys[importLabel] = ontimeKey;
|
||||
}
|
||||
return { customFields, customFieldImportKeys };
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Excel array parser
|
||||
* @param {array} excelData - array with excel sheet
|
||||
* @param {ExcelImportOptions} options - an object that contains the import map
|
||||
* @param {ImportOptions} options - an object that contains the import map
|
||||
* @returns {object} - parsed object
|
||||
*/
|
||||
export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImportMap>) => {
|
||||
const projectMetadata = {};
|
||||
export const parseExcel = (excelData: unknown[][], options?: Partial<ImportMap>): ExcelData => {
|
||||
const rundownMetadata = {};
|
||||
const importMap: ExcelImportMap = { ...defaultExcelImportMap, ...options };
|
||||
const importMap: ImportMap = { ...defaultImportMap, ...options };
|
||||
|
||||
for (const [key, value] of Object.entries(importMap)) {
|
||||
importMap[key] = value.toLocaleLowerCase();
|
||||
if (typeof value === 'string') {
|
||||
importMap[key] = value.toLocaleLowerCase();
|
||||
}
|
||||
}
|
||||
const projectData: Partial<ProjectData> = {
|
||||
title: '',
|
||||
description: '',
|
||||
publicUrl: '',
|
||||
publicInfo: '',
|
||||
backstageUrl: '',
|
||||
backstageInfo: '',
|
||||
};
|
||||
const customUserFields: Partial<UserFields> = {
|
||||
user0: importMap.user0,
|
||||
user1: importMap.user1,
|
||||
user2: importMap.user2,
|
||||
user3: importMap.user3,
|
||||
user4: importMap.user4,
|
||||
user5: importMap.user5,
|
||||
user6: importMap.user6,
|
||||
user7: importMap.user7,
|
||||
user8: importMap.user8,
|
||||
user9: importMap.user9,
|
||||
};
|
||||
|
||||
const { customFields, customFieldImportKeys } = getCustomFieldData(importMap);
|
||||
const rundown: OntimeRundown = [];
|
||||
|
||||
// title stuff: strings
|
||||
let titleIndex: number | null = null;
|
||||
let cueIndex: number | null = null;
|
||||
let presenterIndex: number | null = null;
|
||||
let subtitleIndex: number | null = null;
|
||||
let notesIndex: number | null = null;
|
||||
let colourIndex: number | null = null;
|
||||
|
||||
@@ -92,62 +95,23 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
|
||||
let timeStartIndex: number | null = null;
|
||||
let timeEndIndex: number | null = null;
|
||||
let durationIndex: number | null = null;
|
||||
let timeWarningIndex: number | null = null;
|
||||
let timeDangerIndex: number | null = null;
|
||||
|
||||
// options: enum properties
|
||||
let endActionIndex: number | null = null;
|
||||
let timerTypeIndex: number | null = null;
|
||||
|
||||
// user fields: strings
|
||||
let user0Index: number | null = null;
|
||||
let user1Index: number | null = null;
|
||||
let user2Index: number | null = null;
|
||||
let user3Index: number | null = null;
|
||||
let user4Index: number | null = null;
|
||||
let user5Index: number | null = null;
|
||||
let user6Index: number | null = null;
|
||||
let user7Index: number | null = null;
|
||||
let user8Index: number | null = null;
|
||||
let user9Index: number | null = null;
|
||||
// record of column index and the name of the field
|
||||
const customFieldIndexes: Record<number, string> = {};
|
||||
|
||||
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;
|
||||
|
||||
const event: Partial<OntimeEvent> = {};
|
||||
// TODO: extract generating handlers from importMap
|
||||
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 };
|
||||
},
|
||||
|
||||
[importMap.timeStart]: (row: number, col: number) => {
|
||||
timeStartIndex = col;
|
||||
rundownMetadata['timeStart'] = { row, col };
|
||||
@@ -169,14 +133,6 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
|
||||
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 };
|
||||
@@ -193,7 +149,6 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
|
||||
colourIndex = col;
|
||||
rundownMetadata['colour'] = { row, col };
|
||||
},
|
||||
|
||||
[importMap.endAction]: (row: number, col: number) => {
|
||||
endActionIndex = col;
|
||||
rundownMetadata['endAction'] = { row, col };
|
||||
@@ -202,83 +157,46 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
|
||||
timerTypeIndex = col;
|
||||
rundownMetadata['timerType'] = { row, col };
|
||||
},
|
||||
|
||||
[importMap.user0]: (row: number, col: number) => {
|
||||
user0Index = col;
|
||||
rundownMetadata['user0'] = { row, col };
|
||||
[importMap.timeWarning]: (row: number, col: number) => {
|
||||
timeWarningIndex = col;
|
||||
rundownMetadata['timeWarningIndex'] = { row, col };
|
||||
},
|
||||
[importMap.user1]: (row: number, col: number) => {
|
||||
user1Index = col;
|
||||
rundownMetadata['user1'] = { row, col };
|
||||
[importMap.timeDanger]: (row: number, col: number) => {
|
||||
timeDangerIndex = col;
|
||||
rundownMetadata['timeDangerIndex'] = { 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 };
|
||||
custom: (row: number, col: number, columnText: string) => {
|
||||
customFieldIndexes[col] = columnText;
|
||||
rundownMetadata[`custom-${columnText}`] = { row, col };
|
||||
},
|
||||
} as const;
|
||||
|
||||
row.forEach((column, j) => {
|
||||
const event: any = {};
|
||||
const eventCustomFields: EventCustomFields = {};
|
||||
|
||||
for (let j = 0; j < row.length; j++) {
|
||||
const column = row[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;
|
||||
if (j === timerTypeIndex) {
|
||||
if (column === 'block') {
|
||||
event.type = SupportedEvent.Block;
|
||||
} else if (column === '' || isKnownTimerType(column)) {
|
||||
event.type = SupportedEvent.Event;
|
||||
event.timerType = validateTimerType(column);
|
||||
} else {
|
||||
// if it is not a block or a known type, we dont import it
|
||||
return;
|
||||
}
|
||||
} else if (j === titleIndex) {
|
||||
event.title = makeString(column, '');
|
||||
} 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) {
|
||||
@@ -287,59 +205,60 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
|
||||
event.note = makeString(column, '');
|
||||
} else if (j === endActionIndex) {
|
||||
event.endAction = validateEndAction(column);
|
||||
} else if (j === timerTypeIndex) {
|
||||
event.timerType = validateTimerType(column);
|
||||
} else if (j === timeWarningIndex) {
|
||||
event.timeWarning = parseExcelDate(column);
|
||||
} else if (j === timeDangerIndex) {
|
||||
event.timeDanger = parseExcelDate(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 if (j in customFieldIndexes) {
|
||||
const importKey = customFieldIndexes[j];
|
||||
const ontimeKey = customFieldImportKeys[importKey];
|
||||
eventCustomFields[ontimeKey] = { value: 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);
|
||||
// we cant deal with empty content
|
||||
if (column.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const columnText = column.toLowerCase();
|
||||
|
||||
// check if it is an ontime column
|
||||
if (handlers[columnText]) {
|
||||
handlers[columnText](rowIndex, j, undefined);
|
||||
}
|
||||
|
||||
// check if it is a custom field
|
||||
if (columnText in customFieldImportKeys) {
|
||||
handlers.custom(rowIndex, j, columnText);
|
||||
}
|
||||
|
||||
// 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 any data was found in row, push to array
|
||||
const keysFound = Object.keys(event).length + Object.keys(eventCustomFields).length;
|
||||
if (keysFound > 0) {
|
||||
// if it is a Block type drop all other filed
|
||||
if (event.type === SupportedEvent.Block) {
|
||||
rundown.push({ type: event.type, id: event.id, title: event.title } as OntimeBlock);
|
||||
} else {
|
||||
if (timerTypeIndex === null) {
|
||||
event.timerType = TimerType.CountDown;
|
||||
event.type = SupportedEvent.Event;
|
||||
}
|
||||
rundown.push({ ...event, custom: { ...eventCustomFields } });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
rundown,
|
||||
project: projectData,
|
||||
settings: {
|
||||
app: 'ontime',
|
||||
version: '2.0.0',
|
||||
},
|
||||
userFields: customUserFields,
|
||||
projectMetadata,
|
||||
customFields,
|
||||
rundownMetadata,
|
||||
};
|
||||
};
|
||||
@@ -349,140 +268,107 @@ export const parseExcel = (excelData: unknown[][], options?: Partial<ExcelImport
|
||||
* @param {object} jsonData - project file to be parsed
|
||||
* @returns {object} - parsed object
|
||||
*/
|
||||
export const parseJson = async (jsonData): Promise<DatabaseModel | null> => {
|
||||
export const parseJson = async (jsonData: Partial<DatabaseModel>): Promise<DatabaseModel | null> => {
|
||||
if (!jsonData || typeof jsonData !== 'object') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// object containing the parsed data
|
||||
const returnData: Partial<DatabaseModel> = {};
|
||||
let settings;
|
||||
|
||||
// parse Events
|
||||
returnData.rundown = parseRundown(jsonData);
|
||||
// parse Event
|
||||
returnData.project = parseProject(jsonData) ?? dbModel.project;
|
||||
// Settings handled partially
|
||||
returnData.settings = parseSettings(jsonData) ?? dbModel.settings;
|
||||
// View settings handled partially
|
||||
returnData.viewSettings = parseViewSettings(jsonData) ?? dbModel.viewSettings;
|
||||
// Import Aliases if any
|
||||
returnData.aliases = parseAliases(jsonData);
|
||||
// Import user fields if any
|
||||
returnData.userFields = parseUserFields(jsonData);
|
||||
// Import OSC settings if any
|
||||
returnData.osc = parseOsc(jsonData) ?? dbModel.osc;
|
||||
// Import HTTP settings if any
|
||||
returnData.http = parseHttp(jsonData) ?? dbModel.http;
|
||||
// check settings first to make sure we can parse it
|
||||
try {
|
||||
settings = parseSettings(jsonData);
|
||||
} catch (error) {
|
||||
// if we cant parse, return an empty project
|
||||
console.log('ERROR: unable to parse settings, missing app or version');
|
||||
return dbModel;
|
||||
}
|
||||
|
||||
return returnData as DatabaseModel;
|
||||
const returnData: DatabaseModel = {
|
||||
rundown: parseRundown(jsonData),
|
||||
project: parseProject(jsonData),
|
||||
settings,
|
||||
viewSettings: parseViewSettings(jsonData),
|
||||
urlPresets: parseUrlPresets(jsonData),
|
||||
customFields: parseCustomFields(jsonData),
|
||||
osc: parseOsc(jsonData),
|
||||
http: parseHttp(jsonData),
|
||||
};
|
||||
|
||||
return returnData;
|
||||
};
|
||||
|
||||
/**
|
||||
* Function infers strategy for a patch with only partial timer data
|
||||
* @param end
|
||||
* @param duration
|
||||
* @param fallback
|
||||
* @returns
|
||||
*/
|
||||
function inferStrategy(end: unknown, duration: unknown, fallback: TimeStrategy): TimeStrategy {
|
||||
if (end && !duration) {
|
||||
return TimeStrategy.LockEnd;
|
||||
}
|
||||
|
||||
if (!end && duration) {
|
||||
return TimeStrategy.LockDuration;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function createPatch(originalEvent: OntimeEvent, patchEvent: Partial<OntimeEvent>): OntimeEvent {
|
||||
if (Object.keys(patchEvent).length === 0) {
|
||||
return originalEvent;
|
||||
}
|
||||
|
||||
const { timeStart, timeEnd, duration, timeStrategy } = validateTimes(
|
||||
patchEvent?.timeStart ?? originalEvent.timeStart,
|
||||
patchEvent?.timeEnd ?? originalEvent.timeEnd,
|
||||
patchEvent?.duration ?? originalEvent.duration,
|
||||
patchEvent?.timeStrategy ?? inferStrategy(patchEvent?.timeEnd, patchEvent?.duration, originalEvent.timeStrategy),
|
||||
);
|
||||
const maybeLinkStart = patchEvent.linkStart !== undefined ? patchEvent.linkStart : originalEvent.linkStart;
|
||||
|
||||
return {
|
||||
id: originalEvent.id,
|
||||
type: SupportedEvent.Event,
|
||||
title: makeString(patchEvent.title, originalEvent.title),
|
||||
timeStart,
|
||||
timeEnd,
|
||||
duration,
|
||||
timeStrategy,
|
||||
linkStart: validateLinkStart(maybeLinkStart),
|
||||
endAction: validateEndAction(patchEvent.endAction, originalEvent.endAction),
|
||||
timerType: validateTimerType(patchEvent.timerType, originalEvent.timerType),
|
||||
isPublic: typeof patchEvent.isPublic === 'boolean' ? patchEvent.isPublic : originalEvent.isPublic,
|
||||
skip: typeof patchEvent.skip === 'boolean' ? patchEvent.skip : originalEvent.skip,
|
||||
note: makeString(patchEvent.note, originalEvent.note),
|
||||
colour: makeString(patchEvent.colour, originalEvent.colour),
|
||||
// short circuit empty string
|
||||
cue: makeString(patchEvent.cue ?? null, originalEvent.cue),
|
||||
revision: originalEvent.revision,
|
||||
timeWarning: patchEvent.timeWarning ?? originalEvent.timeWarning,
|
||||
timeDanger: patchEvent.timeDanger ?? originalEvent.timeDanger,
|
||||
custom: { ...originalEvent.custom, ...patchEvent.custom },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Enforces formatting for events
|
||||
* @param {object} eventArgs - attributes of event
|
||||
* @param cueFallback
|
||||
* @returns {object|null} - formatted object or null in case is invalid
|
||||
*/
|
||||
|
||||
export const validateEvent = (eventArgs: Partial<OntimeEvent>, cueFallback: string) => {
|
||||
// ensure id is defined and unique
|
||||
const id = eventArgs.id || generateId();
|
||||
|
||||
let event = null;
|
||||
|
||||
// return if object is empty
|
||||
if (Object.keys(eventArgs).length > 0) {
|
||||
// make sure all properties exits
|
||||
// dont load any extra properties than the ones known
|
||||
|
||||
const e = eventArgs;
|
||||
const d = eventDef;
|
||||
|
||||
const { timeStart, timeEnd, duration } = validateTimes(e.timeStart, e.timeEnd, e.duration);
|
||||
|
||||
event = {
|
||||
...d,
|
||||
title: makeString(e.title, d.title),
|
||||
subtitle: makeString(e.subtitle, d.subtitle),
|
||||
presenter: makeString(e.presenter, d.presenter),
|
||||
timeStart,
|
||||
timeEnd,
|
||||
duration,
|
||||
endAction: validateEndAction(e.endAction, EndAction.None),
|
||||
timerType: validateTimerType(e.timerType, TimerType.CountDown),
|
||||
isPublic: typeof e.isPublic === 'boolean' ? e.isPublic : d.isPublic,
|
||||
skip: typeof e.skip === 'boolean' ? e.skip : d.skip,
|
||||
note: makeString(e.note, d.note),
|
||||
user0: makeString(e.user0, d.user0),
|
||||
user1: makeString(e.user1, d.user1),
|
||||
user2: makeString(e.user2, d.user2),
|
||||
user3: makeString(e.user3, d.user3),
|
||||
user4: makeString(e.user4, d.user4),
|
||||
user5: makeString(e.user5, d.user5),
|
||||
user6: makeString(e.user6, d.user6),
|
||||
user7: makeString(e.user7, d.user7),
|
||||
user8: makeString(e.user8, d.user8),
|
||||
user9: makeString(e.user9, d.user9),
|
||||
colour: makeString(e.colour, d.colour),
|
||||
cue: makeString(e.cue, cueFallback),
|
||||
id,
|
||||
type: 'event',
|
||||
};
|
||||
export const createEvent = (eventArgs: Partial<OntimeEvent>, cueFallback: string): OntimeEvent | null => {
|
||||
if (Object.keys(eventArgs).length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const baseEvent = {
|
||||
id: eventArgs?.id ?? generateId(),
|
||||
cue: cueFallback,
|
||||
...eventDef,
|
||||
};
|
||||
const event = createPatch(baseEvent, eventArgs);
|
||||
return event;
|
||||
};
|
||||
|
||||
type ResponseOK = {
|
||||
data: Partial<DatabaseModel>;
|
||||
};
|
||||
|
||||
/**
|
||||
* @description Middleware function that checks file type and calls relevant parser
|
||||
* @param {string} file - reference to file
|
||||
* @param options - import options
|
||||
* @return {object} - parse result message
|
||||
*/
|
||||
export const fileHandler = async (file: string, options: ExcelImportOptions): Promise<Partial<ResponseOK>> => {
|
||||
const res: Partial<ResponseOK> = {};
|
||||
|
||||
// check which file type are we dealing with
|
||||
if (file.endsWith('.xlsx')) {
|
||||
// we need to check that the options are applicable
|
||||
if (!isExcelImportMap(options)) {
|
||||
throw new Error('Got incorrect options to excel import', JSON.parse(options));
|
||||
}
|
||||
|
||||
const excelData = xlsx
|
||||
.parse(file, { cellDates: true })
|
||||
.find(({ name }) => name.toLowerCase() === options.worksheet.toLowerCase());
|
||||
|
||||
if (!excelData?.data) {
|
||||
throw new Error(`Could not find data to import, maybe the worksheet name is incorrect: ${options.worksheet}`);
|
||||
}
|
||||
|
||||
const dataFromExcel = parseExcel(excelData.data, options);
|
||||
// we run the parsed data through an extra step to ensure the objects shape
|
||||
res.data = {};
|
||||
res.data.rundown = parseRundown(dataFromExcel);
|
||||
if (res.data.rundown.length < 1) {
|
||||
throw new Error(`Could not find data to import in the worksheet ${options.worksheet}`);
|
||||
}
|
||||
res.data.project = parseProject(dataFromExcel);
|
||||
res.data.userFields = parseUserFields(dataFromExcel);
|
||||
return res;
|
||||
}
|
||||
|
||||
if (file.endsWith('.json')) {
|
||||
// if json check version
|
||||
const rawdata = fs.readFileSync(file).toString();
|
||||
let uploadedJson = null;
|
||||
|
||||
uploadedJson = JSON.parse(rawdata);
|
||||
res.data = await parseJson(uploadedJson);
|
||||
|
||||
// delete file
|
||||
await deleteFile(file);
|
||||
return res;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,334 +1,265 @@
|
||||
import { generateId } from 'ontime-utils';
|
||||
import {
|
||||
Alias,
|
||||
OntimeRundown,
|
||||
CustomFields,
|
||||
DatabaseModel,
|
||||
HttpSettings,
|
||||
HttpSubscription,
|
||||
OSCSettings,
|
||||
OntimeBlock,
|
||||
OntimeDelay,
|
||||
OntimeEvent,
|
||||
OntimeRundown,
|
||||
OscSubscription,
|
||||
ProjectData,
|
||||
Settings,
|
||||
TimerLifeCycle,
|
||||
UserFields,
|
||||
URLPreset,
|
||||
ViewSettings,
|
||||
OscSubscription,
|
||||
HttpSubscription,
|
||||
OscSubscriptionOptions,
|
||||
HttpSubscriptionOptions,
|
||||
isOntimeBlock,
|
||||
isOntimeCycle,
|
||||
isOntimeDelay,
|
||||
isOntimeEvent,
|
||||
} from 'ontime-types';
|
||||
import { generateId } from 'ontime-utils';
|
||||
|
||||
import { block as blockDef, delay as delayDef } from '../models/eventsDefinition.js';
|
||||
import { dbModel } from '../models/dataModel.js';
|
||||
import { validateEvent } from './parser.js';
|
||||
import { MAX_EVENTS } from '../settings.js';
|
||||
import { block as blockDef, delay as delayDef } from '../models/eventsDefinition.js';
|
||||
import { createEvent } from './parser.js';
|
||||
|
||||
/**
|
||||
* Parse events array of an entry
|
||||
* @param {object} data - data object
|
||||
* @returns {object} - event object data
|
||||
* Parse rundown array of an entry
|
||||
*/
|
||||
export const parseRundown = (data): OntimeRundown => {
|
||||
let newRundown: OntimeRundown = [];
|
||||
if ('rundown' in data) {
|
||||
console.log('Found rundown definition, importing...');
|
||||
const rundown = [];
|
||||
try {
|
||||
let eventIndex = 0;
|
||||
const ids = [];
|
||||
for (const e of data.rundown) {
|
||||
// cap number of events
|
||||
if (rundown.length >= MAX_EVENTS) {
|
||||
console.log(`ERROR: Reached limit number of ${MAX_EVENTS} events`);
|
||||
break;
|
||||
}
|
||||
|
||||
// double check unique ids
|
||||
if (ids.includes(e?.id)) {
|
||||
console.log('ERROR: ID collision on import, skipping');
|
||||
continue;
|
||||
}
|
||||
|
||||
if (e.type === 'event') {
|
||||
eventIndex += 1;
|
||||
const event = validateEvent(e, eventIndex.toString());
|
||||
if (event != null) {
|
||||
rundown.push(event);
|
||||
ids.push(event.id);
|
||||
}
|
||||
} else if (e.type === 'delay') {
|
||||
rundown.push({
|
||||
...delayDef,
|
||||
duration: e.duration,
|
||||
id: e.id || generateId(),
|
||||
});
|
||||
} else if (e.type === 'block') {
|
||||
rundown.push({ ...blockDef, title: e.title, id: e.id || generateId() });
|
||||
} else {
|
||||
console.log('ERROR: undefined event type, skipping');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`Error ${error}`);
|
||||
}
|
||||
// write to db
|
||||
newRundown = rundown;
|
||||
console.log(`Uploaded file with ${newRundown.length} entries`);
|
||||
export const parseRundown = (data: Partial<DatabaseModel>): OntimeRundown => {
|
||||
if (!data.rundown) {
|
||||
return [];
|
||||
}
|
||||
return newRundown;
|
||||
|
||||
console.log('Found rundown, importing...');
|
||||
|
||||
const rundown: OntimeRundown = [];
|
||||
let eventIndex = 0;
|
||||
const ids: string[] = [];
|
||||
|
||||
for (const event of data.rundown) {
|
||||
if (ids.includes(event.id)) {
|
||||
console.log('ERROR: ID collision on import, skipping');
|
||||
continue;
|
||||
}
|
||||
|
||||
const id = event.id || generateId();
|
||||
let newEvent: OntimeEvent | OntimeDelay | OntimeBlock | null;
|
||||
|
||||
if (isOntimeEvent(event)) {
|
||||
newEvent = createEvent(event, eventIndex.toString());
|
||||
// skip if event is invalid
|
||||
if (newEvent == null) {
|
||||
continue;
|
||||
}
|
||||
eventIndex += 1;
|
||||
} else if (isOntimeDelay(event)) {
|
||||
newEvent = { ...delayDef, duration: event.duration, id };
|
||||
} else if (isOntimeBlock(event)) {
|
||||
newEvent = { ...blockDef, title: event.title, id };
|
||||
} else {
|
||||
console.log('ERROR: unknown event type, skipping');
|
||||
continue;
|
||||
}
|
||||
|
||||
if (newEvent) {
|
||||
rundown.push(newEvent);
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Uploaded rundown with ${rundown.length} entries`);
|
||||
return rundown;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse event portion of an entry
|
||||
* @param {object} data - data object
|
||||
* @returns {object} - event object data
|
||||
*/
|
||||
export const parseProject = (data): ProjectData => {
|
||||
let newProjectData: Partial<ProjectData> = {};
|
||||
// we are adding this here to aid transition, should be removed once enough time has past that users have fully migrated
|
||||
// TODO: Remove eventually
|
||||
if ('project' in data || 'eventData' in data) {
|
||||
console.log('Found project data, importing...');
|
||||
const project = data.project ?? data.eventData;
|
||||
|
||||
// filter known properties and write to db
|
||||
newProjectData = {
|
||||
...dbModel.project,
|
||||
title: project.title || dbModel.project.title,
|
||||
description: project.description || dbModel.project.description,
|
||||
publicUrl: project.publicUrl || dbModel.project.publicUrl,
|
||||
publicInfo: project.publicInfo || dbModel.project.publicInfo,
|
||||
backstageUrl: project.backstageUrl || dbModel.project.backstageUrl,
|
||||
backstageInfo: project.backstageInfo || dbModel.project.backstageInfo,
|
||||
};
|
||||
export const parseProject = (data: Partial<DatabaseModel>): ProjectData => {
|
||||
if (!data.project) {
|
||||
return { ...dbModel.project };
|
||||
}
|
||||
return newProjectData as ProjectData;
|
||||
|
||||
console.log('Found project data, importing...');
|
||||
|
||||
return {
|
||||
title: data.project.title ?? dbModel.project.title,
|
||||
description: data.project.description ?? dbModel.project.description,
|
||||
publicUrl: data.project.publicUrl ?? dbModel.project.publicUrl,
|
||||
publicInfo: data.project.publicInfo ?? dbModel.project.publicInfo,
|
||||
backstageUrl: data.project.backstageUrl ?? dbModel.project.backstageUrl,
|
||||
backstageInfo: data.project.backstageInfo ?? dbModel.project.backstageInfo,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse settings portion of an entry
|
||||
* @param {object} data - data object
|
||||
* @returns {object} - event object data
|
||||
*/
|
||||
export const parseSettings = (data): Settings => {
|
||||
let newSettings: Partial<Settings> = {};
|
||||
if ('settings' in data) {
|
||||
console.log('Found settings definition, importing...');
|
||||
const s = data.settings;
|
||||
|
||||
// skip if file definition is missing
|
||||
if (s.app == null || s.version == null) {
|
||||
console.log('ERROR: unknown app version, skipping');
|
||||
} else {
|
||||
const settings = {
|
||||
version: dbModel.settings.version,
|
||||
serverPort: s.serverPort || dbModel.settings.serverPort,
|
||||
editorKey: s.editorKey || null,
|
||||
operatorKey: s.operatorKey || null,
|
||||
timeFormat: s.timeFormat || '24',
|
||||
language: s.language || 'en',
|
||||
};
|
||||
|
||||
// write to db
|
||||
newSettings = {
|
||||
...dbModel.settings,
|
||||
...settings,
|
||||
};
|
||||
}
|
||||
export const parseSettings = (data: Partial<DatabaseModel>): Settings => {
|
||||
if (!data.settings) {
|
||||
return { ...dbModel.settings };
|
||||
}
|
||||
return newSettings as Settings;
|
||||
|
||||
// skip if file definition is missing
|
||||
if (data.settings?.app !== 'ontime' || data.settings?.version == null) {
|
||||
throw new Error('ERROR: unable to parse settings, missing app or version');
|
||||
}
|
||||
|
||||
console.log('Found settings, importing...');
|
||||
|
||||
return {
|
||||
app: dbModel.settings.app,
|
||||
version: dbModel.settings.version,
|
||||
serverPort: data.settings.serverPort ?? dbModel.settings.serverPort,
|
||||
editorKey: data.settings.editorKey ?? null,
|
||||
operatorKey: data.settings.operatorKey ?? null,
|
||||
timeFormat: data.settings.timeFormat ?? '24',
|
||||
language: data.settings.language ?? 'en',
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse settings portion of an entry
|
||||
* @param {object} data - data object
|
||||
* @returns {object} - event object data
|
||||
* Parse view settings portion of an entry
|
||||
*/
|
||||
export const parseViewSettings = (data): ViewSettings => {
|
||||
let newViews: Partial<ViewSettings> = {};
|
||||
if ('viewSettings' in data) {
|
||||
console.log('Found view definition, importing...');
|
||||
const v = data.viewSettings;
|
||||
|
||||
const viewSettings = {
|
||||
overrideStyles: v.overrideStyles ?? dbModel.viewSettings.overrideStyles,
|
||||
normalColor: v.normalColor ?? dbModel.viewSettings.normalColor,
|
||||
warningColor: v.warningColor ?? dbModel.viewSettings.warningColor,
|
||||
warningThreshold: v.warningThreshold ?? dbModel.viewSettings.warningThreshold,
|
||||
dangerColor: v.dangerColor ?? dbModel.viewSettings.dangerColor,
|
||||
dangerThreshold: v.dangerThreshold ?? dbModel.viewSettings.dangerThreshold,
|
||||
endMessage: v.endMessage ?? dbModel.viewSettings.endMessage,
|
||||
};
|
||||
|
||||
newViews = { ...viewSettings };
|
||||
export const parseViewSettings = (data: Partial<DatabaseModel>): ViewSettings => {
|
||||
if (!data.viewSettings) {
|
||||
return { ...dbModel.viewSettings };
|
||||
}
|
||||
return newViews as ViewSettings;
|
||||
|
||||
console.log('Found view settings, importing...');
|
||||
|
||||
return {
|
||||
dangerColor: data.viewSettings.dangerColor ?? dbModel.viewSettings.dangerColor,
|
||||
endMessage: data.viewSettings.endMessage ?? dbModel.viewSettings.endMessage,
|
||||
freezeEnd: data.viewSettings.freezeEnd ?? dbModel.viewSettings.freezeEnd,
|
||||
normalColor: data.viewSettings.normalColor ?? dbModel.viewSettings.normalColor,
|
||||
overrideStyles: data.viewSettings.overrideStyles ?? dbModel.viewSettings.overrideStyles,
|
||||
warningColor: data.viewSettings.warningColor ?? dbModel.viewSettings.warningColor,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses and validates OSC subscription cycle options
|
||||
* @param data
|
||||
* Sanitises an OSC Subscriptions array
|
||||
*/
|
||||
export const validateOscSubscriptionCycle = (data: OscSubscriptionOptions[]): boolean => {
|
||||
for (const subscriptionOption of data) {
|
||||
if (typeof subscriptionOption.message !== 'string' || typeof subscriptionOption.enabled !== 'boolean') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses and validates OSC subscription object
|
||||
* @param data
|
||||
*/
|
||||
export const validateOscSubscriptionObject = (data: OscSubscription): boolean => {
|
||||
if (!data) {
|
||||
return false;
|
||||
export function sanitiseOscSubscriptions(subscriptions?: OscSubscription[]): OscSubscription[] {
|
||||
if (!Array.isArray(subscriptions)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const timerKeys = Object.keys(TimerLifeCycle);
|
||||
for (const key of timerKeys) {
|
||||
// must contains all keys and be an array
|
||||
if (!(key in data) || !Array.isArray(data[key])) {
|
||||
return false;
|
||||
}
|
||||
const isValid = validateOscSubscriptionCycle(data[key]);
|
||||
if (!isValid) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
return subscriptions.filter(
|
||||
({ id, cycle, address, payload, enabled }) =>
|
||||
typeof id === 'string' &&
|
||||
isOntimeCycle(cycle) &&
|
||||
typeof address === 'string' &&
|
||||
typeof payload === 'string' &&
|
||||
typeof enabled === 'boolean',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse osc portion of an entry
|
||||
*/
|
||||
export const parseOsc = (data: { osc?: Partial<OSCSettings> }): OSCSettings => {
|
||||
if ('osc' in data) {
|
||||
console.log('Found OSC definition, importing...');
|
||||
|
||||
// TODO: this can be improved by only merging known keys
|
||||
const loadedConfig = data.osc || {};
|
||||
const validatedSubscriptions = validateOscSubscriptionObject(loadedConfig.subscriptions)
|
||||
? loadedConfig.subscriptions
|
||||
: dbModel.osc.subscriptions;
|
||||
|
||||
return {
|
||||
portIn: loadedConfig.portIn ?? dbModel.osc.portIn,
|
||||
portOut: loadedConfig.portOut ?? dbModel.osc.portOut,
|
||||
targetIP: loadedConfig.targetIP ?? dbModel.osc.targetIP,
|
||||
enabledIn: loadedConfig.enabledIn ?? dbModel.osc.enabledIn,
|
||||
enabledOut: loadedConfig.enabledOut ?? dbModel.osc.enabledOut,
|
||||
subscriptions: validatedSubscriptions,
|
||||
};
|
||||
export const parseOsc = (data: Partial<DatabaseModel>): OSCSettings => {
|
||||
if (!data.osc) {
|
||||
return { ...dbModel.osc };
|
||||
}
|
||||
console.log('Found OSC settings, importing...');
|
||||
|
||||
return {
|
||||
portIn: data.osc.portIn ?? dbModel.osc.portIn,
|
||||
portOut: data.osc.portOut ?? dbModel.osc.portOut,
|
||||
targetIP: data.osc.targetIP ?? dbModel.osc.targetIP,
|
||||
enabledIn: data.osc.enabledIn ?? dbModel.osc.enabledIn,
|
||||
enabledOut: data.osc.enabledOut ?? dbModel.osc.enabledOut,
|
||||
subscriptions: sanitiseOscSubscriptions(data.osc.subscriptions),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses and validates HTTP subscription cycle options
|
||||
* @param data
|
||||
* Sanitises an HTTP Subscriptions array
|
||||
*/
|
||||
export const validateHttpSubscriptionCycle = (data: HttpSubscriptionOptions[]): boolean => {
|
||||
for (const subscriptionOption of data) {
|
||||
const isHttp = subscriptionOption.message?.startsWith('http://');
|
||||
if (typeof subscriptionOption.message !== 'string' || !isHttp || typeof subscriptionOption.enabled !== 'boolean') {
|
||||
return false;
|
||||
}
|
||||
export function sanitiseHttpSubscriptions(subscriptions?: HttpSubscription[]): HttpSubscription[] {
|
||||
if (!Array.isArray(subscriptions)) {
|
||||
return [];
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses and validates HTTP subscription object
|
||||
* @param data
|
||||
*/
|
||||
export const validateHttpSubscriptionObject = (data: HttpSubscription): boolean => {
|
||||
if (!data) {
|
||||
return false;
|
||||
}
|
||||
const timerKeys = Object.keys(TimerLifeCycle);
|
||||
// must contains all keys and be an array
|
||||
for (const key of timerKeys) {
|
||||
if (!(key in data) || !Array.isArray(data[key])) {
|
||||
return false;
|
||||
}
|
||||
const isValid = validateHttpSubscriptionCycle(data[key]);
|
||||
if (!isValid) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
return subscriptions.filter(
|
||||
({ id, cycle, message, enabled }) =>
|
||||
typeof id === 'string' &&
|
||||
isOntimeCycle(cycle) &&
|
||||
typeof message === 'string' &&
|
||||
message.startsWith('http://') &&
|
||||
typeof enabled === 'boolean',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Http portion of an entry
|
||||
* @param {object} data - data object
|
||||
* @param {boolean} enforce - whether to create a definition if one is missing
|
||||
* @returns {object} - event object data
|
||||
*/
|
||||
export const parseHttp = (data: { http?: Partial<HttpSettings> }): HttpSettings => {
|
||||
if ('http' in data) {
|
||||
console.log('Found HTTP definition, importing...');
|
||||
export const parseHttp = (data: Partial<DatabaseModel>): HttpSettings => {
|
||||
if (!data.http) {
|
||||
return { ...dbModel.http };
|
||||
}
|
||||
|
||||
// TODO: this can be improved by only merging known keys
|
||||
const loadedConfig = data?.http || {};
|
||||
const validatedSubscriptions = validateHttpSubscriptionObject(loadedConfig.subscriptions)
|
||||
? loadedConfig.subscriptions
|
||||
: dbModel.http.subscriptions;
|
||||
console.log('Found HTTP settings, importing...');
|
||||
|
||||
return {
|
||||
enabledOut: loadedConfig.enabledOut ?? dbModel.http.enabledOut,
|
||||
subscriptions: validatedSubscriptions,
|
||||
return {
|
||||
enabledOut: data.http.enabledOut ?? dbModel.http.enabledOut,
|
||||
subscriptions: sanitiseHttpSubscriptions(data.http.subscriptions),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse URL preset portion of an entry
|
||||
*/
|
||||
export const parseUrlPresets = (data: Partial<DatabaseModel>): URLPreset[] => {
|
||||
if (!data.urlPresets) {
|
||||
return [];
|
||||
}
|
||||
|
||||
console.log('Found URL presets, importing...');
|
||||
|
||||
const newPresets: URLPreset[] = [];
|
||||
|
||||
for (const preset of data.urlPresets) {
|
||||
const newPreset = {
|
||||
enabled: preset.enabled ?? false,
|
||||
alias: preset.alias ?? '',
|
||||
pathAndParams: preset.pathAndParams ?? '',
|
||||
};
|
||||
newPresets.push(newPreset);
|
||||
}
|
||||
|
||||
console.log(`Uploaded ${newPresets.length} preset(s)`);
|
||||
|
||||
return newPresets;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse customFields entry
|
||||
*/
|
||||
export const parseCustomFields = (data: Partial<DatabaseModel>): CustomFields => {
|
||||
if (typeof data.customFields !== 'object') {
|
||||
return { ...dbModel.customFields };
|
||||
}
|
||||
|
||||
console.log('Found Custom Fields, importing...');
|
||||
|
||||
const newCustomFields: CustomFields = {};
|
||||
|
||||
for (const fieldLabel in data.customFields) {
|
||||
const field = data.customFields[fieldLabel];
|
||||
if (!field.label || !field.type || !field.colour) {
|
||||
console.log('ERROR: missing required field, skipping');
|
||||
continue;
|
||||
}
|
||||
newCustomFields[field.label] = {
|
||||
type: field.type,
|
||||
colour: field.colour,
|
||||
label: field.label,
|
||||
};
|
||||
}
|
||||
|
||||
return newCustomFields;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse aliases portion of an entry
|
||||
* @param {object} data - data object
|
||||
* @returns {object} - event object data
|
||||
*/
|
||||
export const parseAliases = (data): Alias[] => {
|
||||
const newAliases: Alias[] = [];
|
||||
if ('aliases' in data) {
|
||||
console.log('Found Aliases definition, importing...');
|
||||
try {
|
||||
for (const a of data.aliases) {
|
||||
const newAlias = {
|
||||
enabled: a.enabled || false,
|
||||
alias: a.alias || '',
|
||||
pathAndParams: a.pathAndParams || '',
|
||||
};
|
||||
newAliases.push(newAlias);
|
||||
}
|
||||
console.log(`Uploaded ${newAliases?.length || 0} alias(es)`);
|
||||
} catch (error) {
|
||||
console.log(`Error: ${error}`);
|
||||
}
|
||||
}
|
||||
return newAliases;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse userFields entry
|
||||
* @param {object} data - data object
|
||||
* @returns {object} - event object data
|
||||
*/
|
||||
export const parseUserFields = (data): UserFields => {
|
||||
const newUserFields: UserFields = { ...dbModel.userFields };
|
||||
|
||||
if ('userFields' in data) {
|
||||
console.log('Found User Fields definition, importing...');
|
||||
// we will only be importing the fields we know, so look for that
|
||||
try {
|
||||
let fieldsFound = 0;
|
||||
for (const n in newUserFields) {
|
||||
if (n in data.userFields) {
|
||||
fieldsFound++;
|
||||
newUserFields[n] = data.userFields[n];
|
||||
}
|
||||
}
|
||||
console.log(`Uploaded ${fieldsFound} user fields`);
|
||||
} catch (error) {
|
||||
console.log(`Error: ${error}`);
|
||||
}
|
||||
}
|
||||
return { ...newUserFields };
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import fs from 'fs';
|
||||
import { unlink } from 'fs';
|
||||
import { deepmerge } from 'ontime-utils';
|
||||
|
||||
/**
|
||||
@@ -15,31 +15,15 @@ export const makeString = (val: unknown, fallback = ''): string => {
|
||||
|
||||
/**
|
||||
* @description Delete file from system
|
||||
* @param {string} file - reference to file
|
||||
*/
|
||||
export const deleteFile = async (file) => {
|
||||
// delete a file
|
||||
fs.unlink(file, (err) => {
|
||||
if (err) {
|
||||
console.log(err);
|
||||
export const deleteFile = async (filePath: string) => {
|
||||
unlink(filePath, (error) => {
|
||||
if (error) {
|
||||
console.error('Could not delete file:', error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @description Delete file from system
|
||||
* @param {string} file - reference to file
|
||||
* @returns {boolean} - whether file is valid JSON
|
||||
*/
|
||||
export const validateFile = (file) => {
|
||||
try {
|
||||
JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
return true;
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @description Verifies if object is empty
|
||||
* @param {object} obj
|
||||
@@ -82,10 +66,12 @@ export function mergeObject<T extends object>(a: T, b: Partial<T>): T {
|
||||
* @description Removes undefined
|
||||
* @param {object} obj
|
||||
*/
|
||||
export const removeUndefined = (obj: object) => {
|
||||
const patched = {};
|
||||
Object.keys({ ...obj })
|
||||
.filter((key) => typeof obj[key] !== 'undefined')
|
||||
.map((key) => (patched[key] = obj[key]));
|
||||
return patched;
|
||||
export const removeUndefined = <T extends Record<string, unknown>>(obj: T): Partial<T> => {
|
||||
return Object.keys(obj).reduce((patched, key) => {
|
||||
if (typeof obj[key] !== 'undefined') {
|
||||
// @ts-expect-error -- not sure how to type this
|
||||
patched[key] = obj[key];
|
||||
}
|
||||
return patched;
|
||||
}, {} as Partial<T>);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { parse } from 'path';
|
||||
|
||||
/**
|
||||
* @description Takes a filename and removes the extension
|
||||
* @param {string} filename - filename with extension
|
||||
*/
|
||||
export const removeFileExtension = (filename: string): string => {
|
||||
return parse(filename).name;
|
||||
};
|
||||
@@ -1,3 +1,5 @@
|
||||
import { Response } from 'express';
|
||||
|
||||
import { isEmptyObject } from './parserUtils.js';
|
||||
|
||||
/**
|
||||
@@ -5,18 +7,17 @@ import { isEmptyObject } from './parserUtils.js';
|
||||
* @param obj
|
||||
* @param res
|
||||
*/
|
||||
export const failEmptyObjects = (obj, res) => {
|
||||
let failed = false;
|
||||
export const failEmptyObjects = (obj: object, res: Response): boolean => {
|
||||
try {
|
||||
if (isEmptyObject(obj)) {
|
||||
res.status(400).send('No object found in request');
|
||||
failed = true;
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(400).send(error);
|
||||
failed = true;
|
||||
return true;
|
||||
}
|
||||
return failed;
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -24,16 +25,15 @@ export const failEmptyObjects = (obj, res) => {
|
||||
* @param obj
|
||||
* @param res
|
||||
*/
|
||||
export const failIsNotArray = (obj, res) => {
|
||||
let failed = false;
|
||||
export const failIsNotArray = (obj: object, res: Response): boolean => {
|
||||
try {
|
||||
if (!Array.isArray(obj)) {
|
||||
res.status(400).send('No array found in request');
|
||||
failed = true;
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(400).send(error);
|
||||
failed = true;
|
||||
return true;
|
||||
}
|
||||
return failed;
|
||||
return false;
|
||||
};
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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();
|
||||
@@ -8,7 +8,7 @@
|
||||
*/
|
||||
export function throttle<T extends any[], U>(cb: (...args: T) => U, delay: number) {
|
||||
let shouldWait = false;
|
||||
let waitingArgs;
|
||||
let waitingArgs: T | null = null;
|
||||
const timeoutFunc = () => {
|
||||
if (waitingArgs == null) {
|
||||
shouldWait = false;
|
||||
|
||||
@@ -35,22 +35,40 @@ const parse = (valueAsString: string): number => {
|
||||
return Math.abs(parsed);
|
||||
};
|
||||
|
||||
const stripAMPM = (value: string) => {
|
||||
const lowerValue = value.toLowerCase();
|
||||
if (lowerValue.endsWith('am')) {
|
||||
return { sansPostfix: lowerValue.substring(0, lowerValue.length - 2), pastNoon: false };
|
||||
} else if (lowerValue.endsWith('pm')) {
|
||||
return { sansPostfix: lowerValue.substring(0, lowerValue.length - 2), pastNoon: true };
|
||||
} else {
|
||||
return { sansPostfix: lowerValue, pastNoon: false };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @description Parses a time string to millis, copied from client code
|
||||
* @param {string} value - time string
|
||||
* @param {boolean} fillLeft - autofill left = hours / right = seconds
|
||||
* @returns {number} - time string in millis
|
||||
*/
|
||||
export const forgivingStringToMillis = (value: string, fillLeft = true): number => {
|
||||
export const forgivingStringToMillis = (value: string, fillLeft: boolean = true): number => {
|
||||
let millis = 0;
|
||||
|
||||
// check for AM/PM indicators
|
||||
const { sansPostfix, pastNoon } = stripAMPM(value);
|
||||
|
||||
//if past noon indicated add 12 hours
|
||||
if (pastNoon) {
|
||||
millis = mth * 12;
|
||||
}
|
||||
// split string at known separators : , .
|
||||
const separatorRegex = /[\s,:.]+/;
|
||||
const [first, second, third] = value.split(separatorRegex);
|
||||
const [first, second, third] = sansPostfix.split(separatorRegex);
|
||||
|
||||
if (first != null && second != null && third != null) {
|
||||
// if string has three sections, treat as [hours] [minutes] [seconds]
|
||||
millis = parse(first) * mth;
|
||||
millis += parse(first) * mth;
|
||||
millis += parse(second) * mtm;
|
||||
millis += parse(third) * mts;
|
||||
} else if (first != null && second == null && third == null) {
|
||||
@@ -60,23 +78,23 @@ export const forgivingStringToMillis = (value: string, fillLeft = true): number
|
||||
const hours = first.substring(0, 2);
|
||||
const minutes = first.substring(2, 4);
|
||||
const seconds = first.substring(4);
|
||||
millis = parse(hours) * mth;
|
||||
millis += parse(hours) * mth;
|
||||
millis += parse(minutes) * mtm;
|
||||
millis += parse(seconds) * mts;
|
||||
} else {
|
||||
// otherwise lets treat as [minutes]
|
||||
millis = parse(first) * mtm;
|
||||
millis += parse(first) * mtm;
|
||||
}
|
||||
}
|
||||
if (first != null && second != null && third == null) {
|
||||
// if string has two sections
|
||||
if (fillLeft) {
|
||||
// treat as [hours] [minutes]
|
||||
millis = parse(first) * mth;
|
||||
millis += parse(first) * mth;
|
||||
millis += parse(second) * mtm;
|
||||
} else {
|
||||
// treat as [minutes] [seconds]
|
||||
millis = parse(first) * mtm;
|
||||
millis += parse(first) * mtm;
|
||||
millis += parse(second) * mts;
|
||||
}
|
||||
}
|
||||
@@ -87,7 +105,6 @@ export const forgivingStringToMillis = (value: string, fillLeft = true): number
|
||||
* @description Parses an excel date using the correct parser
|
||||
* @param {string} excelDate
|
||||
* @returns {number} - time in milliseconds
|
||||
|
||||
*/
|
||||
export const parseExcelDate = (excelDate: unknown): number => {
|
||||
if (excelDate instanceof Date) {
|
||||
@@ -103,15 +120,3 @@ export const parseExcelDate = (excelDate: unknown): number => {
|
||||
|
||||
return 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* @description Converts milliseconds to seconds -- Copied from client code
|
||||
* @param {number | null} millis - time in seconds
|
||||
* @returns {number} Amount in seconds
|
||||
*/
|
||||
export const millisToSeconds = (millis: number | null): number => {
|
||||
if (millis === null) {
|
||||
return 0;
|
||||
}
|
||||
return millis < 0 ? Math.ceil(millis / mts) : Math.floor(millis / mts);
|
||||
};
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
|
||||
import { EXCEL_MIME, JSON_MIME } from './parser.js';
|
||||
import { ensureDirectory } from './fileManagement.js';
|
||||
import { getAppDataPath } from '../setup.js';
|
||||
|
||||
// Define multer storage object
|
||||
const storage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
// get platform path
|
||||
const appDataPath = getAppDataPath();
|
||||
if (appDataPath === '') {
|
||||
throw new Error('Could not resolve public folder for platform');
|
||||
}
|
||||
// append uploads folder
|
||||
const newDestination = path.join(appDataPath, 'uploads');
|
||||
|
||||
// Create directory if not exist
|
||||
ensureDirectory(newDestination);
|
||||
cb(null, newDestination);
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
cb(null, `${Date.now()}--${file.originalname}`);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* @description Middleware function to filter allowed file types
|
||||
* @argument file - reference to file
|
||||
* @return {boolean} - file allowed
|
||||
*/
|
||||
const filterAllowed = (req, file, cb) => {
|
||||
if (file.mimetype.includes(JSON_MIME) || file.mimetype.includes(EXCEL_MIME)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
console.log('ERROR: Unrecognised file type');
|
||||
cb(null, false);
|
||||
}
|
||||
};
|
||||
|
||||
// Build multer uploader for a single file
|
||||
export const uploadFile = multer({
|
||||
storage: storage,
|
||||
fileFilter: filterAllowed,
|
||||
}).single('userFile');
|
||||
@@ -0,0 +1,58 @@
|
||||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
import { ensureDirectory } from './fileManagement.js';
|
||||
import { getAppDataPath, uploadsFolderPath } from '../setup/index.js';
|
||||
|
||||
function generateNewFileName(filePath: string, callback: (newName: string) => void) {
|
||||
const baseName = path.basename(filePath, path.extname(filePath));
|
||||
const extension = path.extname(filePath);
|
||||
let counter = 1;
|
||||
|
||||
const checkExistence = (newPath: string) => {
|
||||
fs.access(newPath, fs.constants.F_OK, (err) => {
|
||||
if (err) {
|
||||
// File with the new name does not exist, use this name
|
||||
callback(path.basename(newPath));
|
||||
} else {
|
||||
// File exists, increment the counter and try again
|
||||
newPath = path.join(path.dirname(filePath), `${baseName} (${++counter})${extension}`);
|
||||
checkExistence(newPath);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const newPath = path.join(path.dirname(filePath), `${baseName} (${counter})${extension}`);
|
||||
checkExistence(newPath);
|
||||
}
|
||||
|
||||
// Define multer storage object
|
||||
export const storage = multer.diskStorage({
|
||||
destination: function (_req, file, cb) {
|
||||
const appDataPath = getAppDataPath();
|
||||
if (appDataPath === '') {
|
||||
throw new Error('Could not resolve public folder for platform');
|
||||
}
|
||||
|
||||
ensureDirectory(uploadsFolderPath);
|
||||
|
||||
const filePath = path.join(uploadsFolderPath, file.originalname);
|
||||
|
||||
// Check if file already exists
|
||||
fs.access(filePath, fs.constants.F_OK, (err) => {
|
||||
if (err) {
|
||||
// File does not exist, can safely proceed to this destination
|
||||
cb(null, uploadsFolderPath);
|
||||
} else {
|
||||
generateNewFileName(filePath, (newName) => {
|
||||
file.originalname = newName;
|
||||
cb(null, uploadsFolderPath);
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
filename: function (_, file, cb) {
|
||||
cb(null, file.originalname);
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user