-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
617 lines (561 loc) · 16.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
// noinspection JSFileReferences
const {
CreateConvertToBooleanFeedbackUpgradeScript,
InstanceBase,
InstanceStatus,
Regex,
runEntrypoint,
} = require('@companion-module/base')
const http = require('http')
const actions = require('./actions')
const feedbacks = require('./feedbacks')
const presets = require('./presets')
const { get_config_fields } = require('./config')
/**
* Companion instance class for the Epiphan Pearl.
*
* @extends InstanceBase
* @version 2.1.0
* @since 1.0.0
*/
class EpiphanPearl extends InstanceBase {
/**
* Create an instance of a EpiphanPearl module.
*
* @access public
* @since 1.0.0
* @param {EventEmitter} system - the brains of the operation
* @param {string} id - the instance ID
* @param {Object} config - saved user configuration parameters
*/
constructor(internal) {
super(internal)
/**
* Object holding all the state of the pearl
* structure is similar to the api nodes
*/
this.state = {
channels: {},
recorders: {},
}
Object.assign(this, {
...actions,
...feedbacks,
...presets,
//...variables
})
}
// noinspection JSUnusedGlobalSymbols
/**
* Creates the configuration fields for web config.
*
* @access public
* @since 1.0.0
* @returns {Array} the config fields
*/
getConfigFields() {
return get_config_fields()
}
/**
* Clean up the instance before it is destroyed.
*
* @access public
* @since 1.0.0
*/
async destroy() {
clearInterval(this.timer)
this.updateStatus(InstanceStatus.Disconnected)
this.log('debug', 'destroy', this.id)
}
/**
* Main initialization function called once the module
* is OK to start doing things.
*
* @access public
* @since 1.0.0
* @param config the configuration object
*/
async init(config) {
this.updateStatus(InstanceStatus.Connecting)
await this.configUpdated(config)
this.updateSystem()
this.initInterval()
}
// noinspection JSUnusedGlobalSymbols
/**
* Process an updated configuration array.
*
* @access public
* @since 1.0.0
* @param {Object} config - the new configuration
*/
async configUpdated(config) {
if (!config.host || config.host.match(new RegExp(Regex.IP.slice(1, -1))) === null) {
this.log('error', 'invalid IP given in configuration: ' + config.host)
return
}
if (!config.host_port || parseInt(config.host_port) < 1 || parseInt(config.host_port) > 65536) {
this.log('error', 'invalid portnumber given in configuration: ' + config.host_port)
return
}
if (typeof config.pollfreq !== 'number') {
config.pollfreq = 10
this.saveConfig(config)
}
if (this.config === undefined) {
// get config for the first time after init
this.config = config
} else {
let oldconfig = { ...this.config }
this.config = config
if (oldconfig.pollfreq !== this.config.pollfreq) {
// polling frequency has changed, update interval
clearInterval(this.timer)
this.initInterval()
}
}
}
/**
* INTERNAL: handler of status changes
*
* @private
* @since 1.0.0
* @param {Number} level
* @param {?String} message
*/
setStatus(level, message = '') {
this.updateStatus(level, message)
if (level === 'error') {
this.log('error', message)
} else if (level === 'warn') {
this.log('warn', message)
}
}
/**
* INTERNAL: Update current active layout for a channel to the new active layout
*
* @private
* @since 1.0.0
* @param {String|Number} channelId
*/
async updateActiveChannelLayout(channelId) {
channelId = channelId.toString()
const layouts = await this.sendRequest('get', '/api/channels/' + channelId + '/layouts', {})
layouts.forEach((layout) => {
this.state.channels[channelId].layouts[layout.id].active = layout.active
})
this.checkFeedbacks('channelLayout')
}
/**
* INTERNAL: Update all the companion bits when configuration changes
*
* @private
* @since 1.0.0
*/
updateSystem() {
this.setActionDefinitions(this.get_actions())
this.updateFeedbacks()
this.updatePresets()
}
/**
* INTERNAL: Setup and send request
*
* @private
* @since 1.0.0
* @param {String} type - post, get, put
* @param {String} url - Full URL to send request to
* @param {?Object} body - Optional body to send
*/
async sendRequest(type, url, body = {}) {
const apiHost = this.config.host,
apiPort = this.config.host_port,
baseUrl = 'http://' + apiHost + ':' + apiPort
if (url === null || url === '') {
this.setStatus(InstanceStatus.BadConfig, 'No URL given for sendRequest')
this.log('error', 'No URL given for sendRequest')
return false
}
type = type.toUpperCase()
if (['GET', 'POST', 'PUT'].indexOf(type) === -1) {
this.setStatus(InstanceStatus.UnknownError, 'Wrong request type: ' + type)
this.log('error', 'Wrong request type: ' + type)
return false
}
// Check if body is not empty
if (body === undefined) {
body = {}
}
const requestUrl = baseUrl + url
//this.log('debug', 'Starting request to: ' + type + ' ' + baseUrl + url + ' body: ' + JSON.stringify(body))
let response
try {
let options = {
method: type,
timeout: 3000,
headers: {
Authorization: 'Basic ' + Buffer.from(this.config.username + ':' + this.config.password).toString('base64'),
},
}
if (type !== 'GET') {
options.body = JSON.stringify(body)
options.headers['Content-Type'] = 'application/json'
}
response = await fetch(requestUrl, options)
} catch (error) {
if (error.name === 'AbortError') {
this.setStatus(
InstanceStatus.ConnectionFailure,
'Request was aborted: ' + requestUrl + ' reason: ' + error.message
)
this.log('debug', error.message)
throw new Error(error)
}
this.setStatus(InstanceStatus.ConnectionFailure, error.message)
this.log('debug', error.message)
throw new Error(error)
}
if (!response.ok) {
this.setStatus(
InstanceStatus.ConnectionFailure,
'Non-successful response status code: ' + http.STATUS_CODES[response.status] + ' ' + requestUrl
)
this.log('debug', 'Non-successful response status code: ' + http.STATUS_CODES[response.status] + ' ' + requestUrl)
throw new Error('Non-successful response status code: ' + http.STATUS_CODES[response.status])
}
const responseBody = await response.json()
if (responseBody && responseBody.status && responseBody.status !== 'ok') {
this.setStatus(
InstanceStatus.ConnectionFailure,
'Non-successful response from pearl: ' + requestUrl + ' - ' + (body.message ? body.message : 'No error message')
)
this.log(
'debug',
'Non-successful response from pearl: ' + requestUrl + ' - ' + (body.message ? body.message : 'No error message')
)
throw new Error(
'Non-successful response from pearl: ' + requestUrl + ' - ' + (body.message ? body.message : 'No error message')
)
}
let result = responseBody
if (responseBody && responseBody.result) {
result = responseBody.result
}
this.setStatus(InstanceStatus.Ok)
return result
}
/**
* INTERNAL: initialize feedbacks.
*
* @private
* @since 1.0.0
*/
updateFeedbacks() {
this.setFeedbackDefinitions(this.getFeedbacks())
}
/**
* INTERNAL: initialize presets.
*
* @private
* @since [Unreleased]
*/
updatePresets() {
this.setPresetDefinitions(this.getPresets())
}
/**
* INTERNAL: initialize interval data poller.
* Polling data such as channels, recorders, layouts
*
* @private
* @since 1.0.0
*/
initInterval() {
// Run one time first
this.dataPoller()
// Poll data from pearl regulary
this.timer = setInterval(this.dataPoller.bind(this), Math.ceil(this.config.pollfreq * 1000) || 10000)
}
/**
* Part of poller
* INTERNAL: The data poller will actively make requests to update feedbacks and dropdown options.
* Polling data such as channels, recorders, layouts and status
*
* @private
* @since 1.0.0
*/
async dataPoller() {
const state = {
channels: {},
recorders: {},
} // start with a fresh object, during the update some properties will be unavailable, so it is best to not do live updates
// Get all channels and recorders available (in parallel)
let channels, recorders, recorders_status
try {
[channels, recorders, recorders_status] = await Promise.all([
this.sendRequest('get', '/api/channels?publishers=yes&encoders=yes', {}),
this.sendRequest('get', '/api/recorders', {}),
this.sendRequest('get', '/api/recorders/status', {}),
])
} catch (error) {
this.log('error', 'No valid answer from device')
return
}
channels.forEach((channel) => {
state.channels[channel.id] = { ...channel }
state.channels[channel.id].layouts = {}
state.channels[channel.id].publishers = {}
})
recorders.forEach((recorder) => {
state.recorders[recorder.id] = { ...recorder }
})
recorders_status.forEach((recorder) => {
if (state.recorders[recorder.id] === undefined) state.recorders[recorder.id] = {} // just for the event a recorder has been created between call to recorders and recorders/status
state.recorders[recorder.id].status = recorder.status
})
// Get all layouts and publishers for all channels and all recorder states (in parallel)
await Promise.allSettled([
...channels.map(async (channel) => {
const layouts = await this.sendRequest('get', '/api/channels/' + channel.id + '/layouts', {})
layouts.forEach((layout) => {
state.channels[channel.id].layouts[layout.id] = { ...layout }
})
}),
...channels.map(async (channel) => {
const publishers = await this.sendRequest('get', '/api/channels/' + channel.id + '/publishers/type', {})
publishers.forEach((publisher) => {
if (state.channels[channel.id].publishers[publisher.id] === undefined)
state.channels[channel.id].publishers[publisher.id] = {}
state.channels[channel.id].publishers[publisher.id].id = publisher.id
state.channels[channel.id].publishers[publisher.id].type = publisher.type
state.channels[channel.id].publishers[publisher.id].name = publisher.name
})
}),
...channels.map(async (channel) => {
const publishersstatus = await this.sendRequest('get', '/api/channels/' + channel.id + '/publishers/status', {})
publishersstatus.forEach((publisher) => {
if (state.channels[channel.id].publishers[publisher.id] === undefined)
state.channels[channel.id].publishers[publisher.id] = {}
state.channels[channel.id].publishers[publisher.id].status = publisher.status
})
}),
])
// now that we have an updated state object, let's see where we have to react
const channelIds = Object.keys(state.channels)
const recorderIds = Object.keys(state.recorders)
let updateNeeded = false // this is to mark if choices or presets needs to be updated
if (JSON.stringify(channelIds) !== JSON.stringify(Object.keys(this.state.channels))) {
updateNeeded = true
} else if (JSON.stringify(recorderIds) !== JSON.stringify(Object.keys(this.state.recorders))) {
updateNeeded = true
} else if (
channelIds.reduce((acc, curr) => `${acc},${state.channels[curr].name}`, '') !==
channelIds.reduce((acc, curr) => `${acc},${this.state.channels[curr].name}`, '')
) {
updateNeeded = true
} else if (
recorderIds.reduce((acc, curr) => `${acc},${state.recorders[curr].name}`, '') !==
recorderIds.reduce((acc, curr) => `${acc},${this.state.recorders[curr].name}`, '')
) {
updateNeeded = true
} else if (
channelIds.reduce(
(acc, curr) =>
`${acc},${Object.keys(state.channels[curr].publishers).map(
(id) => state.channels[curr].publishers[id].name
)}`,
''
) !==
channelIds.reduce(
(acc, curr) =>
`${acc},${Object.keys(this.state.channels[curr].publishers).map(
(id) => this.state.channels[curr].publishers[id].name
)}`,
''
)
) {
updateNeeded = true
} else if (
channelIds.reduce(
(acc, curr) =>
`${acc},${Object.keys(state.channels[curr].layouts).map((id) => state.channels[curr].layouts[id].name)}`,
''
) !==
channelIds.reduce(
(acc, curr) =>
`${acc},${Object.keys(this.state.channels[curr].layouts).map(
(id) => this.state.channels[curr].layouts[id].name
)}`,
''
)
) {
updateNeeded = true
}
let feedbacksToCheck = [] // this feedbacks need to be updated
if (updateNeeded) {
//console.log('update is needed: new', JSON.stringify(state), '\n old', JSON.stringify(this.state))
feedbacksToCheck = ['channelLayout', 'channelStreaming', 'recorderRecording'] // recheck everything after reconfiguration, could be more fine grained but not worth for such a small amount of feedbacks
} else {
if (
channelIds.reduce(
(acc, curr) =>
`${acc},${Object.keys(state.channels[curr].layouts).map((id) => state.channels[curr].layouts[id].active)}`,
''
) !==
channelIds.reduce(
(acc, curr) =>
`${acc},${Object.keys(this.state.channels[curr].layouts).map(
(id) => this.state.channels[curr].layouts[id].active
)}`,
''
)
) {
feedbacksToCheck.push('channelLayout')
}
if (
channelIds.reduce(
(acc, curr) =>
`${acc},${Object.keys(state.channels[curr].layouts).map((id) => state.channels[curr].layouts[id].active)}`,
''
) !==
channelIds.reduce(
(acc, curr) =>
`${acc},${Object.keys(this.state.channels[curr].layouts).map(
(id) => this.state.channels[curr].layouts[id].active
)}`,
''
)
) {
feedbacksToCheck.push('channelLayout')
}
if (
channelIds.reduce(
(acc, curr) =>
`${acc},${Object.keys(state.channels[curr].publishers).map((id) =>
JSON.stringify(state.channels[curr].publishers[id].status)
)}`,
''
) !==
channelIds.reduce(
(acc, curr) =>
`${acc},${Object.keys(this.state.channels[curr].publishers).map((id) =>
JSON.stringify(this.state.channels[curr].publishers[id].status)
)}`,
''
)
) {
feedbacksToCheck.push('channelStreaming')
}
if (
recorderIds.reduce((acc, curr) => `${acc},${JSON.stringify(state.recorders[curr].status.state)}`, '') !==
recorderIds.reduce((acc, curr) => `${acc},${JSON.stringify(this.state.recorders[curr].status.state)}`, '')
) {
feedbacksToCheck.push('recorderRecording')
}
}
// now finally swap the state object
this.state = { ...state }
//console.log('feedbacks to check', feedbacksToCheck)
if (feedbacksToCheck.length > 0) this.checkFeedbacks(...feedbacksToCheck)
if (updateNeeded) {
this.updateSystem()
this.log('info', 'Pearl configuration has changed, Choices and Presets updated.')
}
}
/**
* Return the id of the first item of dropdown choices array
*
* @param arr {{id: string|number, label: string}[]} the dropdown array
* @returns {string|number}
*/
firstId(arr) {
if (Array.isArray(arr) && arr.length > 0 && (typeof arr[0].id === 'string' || typeof arr[0].id === 'number')) {
return arr[0].id
} else {
return ''
}
}
/**
* Return dropdown choices for recorders
*/
choicesRecorders() {
return Object.keys(this.state.recorders).map((id) => {
return { id, label: this.state.recorders[id].name }
})
}
/**
* Return dropdown choices for channels
*/
choicesChannel() {
return Object.keys(this.state.channels).map((id) => {
return { id, label: this.state.channels[id].name }
})
}
/**
* Return dropdown choices for channel-layout combination
*/
choicesChannelLayout() {
const choices = []
for (const channel of Object.keys(this.state.channels)) {
for (const layout of Object.keys(this.state.channels[channel].layouts)) {
choices.push({
id: `${channel}-${layout}`,
label: `${this.state.channels[channel].name} - ${this.state.channels[channel].layouts[layout].name}`,
})
}
}
return choices
}
/**
* Return dropdown choices for channel-publishers combination
*/
choicesChannelPublishers() {
const choices = []
for (const channel of Object.keys(this.state.channels)) {
if (Object.keys(this.state.channels[channel].publishers).length > 0) {
choices.push({
id: `${channel}-all`,
label: `${this.state.channels[channel].name} - All Streams`,
})
for (const publisher of Object.keys(this.state.channels[channel].publishers)) {
choices.push({
id: `${channel}-${publisher}`,
label: `${this.state.channels[channel].name} - ${this.state.channels[channel].publishers[publisher].name}`,
})
}
}
}
return choices
}
/**
* Part of poller
* INTERNAL: Update the recorder status
*
* @private
* @since 1.0.0
*/
async updateRecorderStatus() {
const recoders = await this.sendRequest('get', '/api/recorders/status', {})
if (!recoders) {
return
}
for (const recorder of recoders) {
this.state.recorders[recorder.id].status = recorder.status
}
this.log('debug', 'Updating RECORDER_STATES and then call checkFeedbacks(recorderRecording)')
this.checkFeedbacks('recorderRecording')
}
}
const upgradeToBooleanFeedbacks = CreateConvertToBooleanFeedbackUpgradeScript({
channelLayout: {
fg: 'color',
bg: 'bgcolor',
},
channelStreaming: {
fg: 'color',
bg: 'bgcolor',
},
recorderRecording: {
fg: 'color',
bg: 'bgcolor',
},
})
runEntrypoint(EpiphanPearl, [upgradeToBooleanFeedbacks])