-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
331 lines (279 loc) · 8.5 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
import { InstanceBase, runEntrypoint, InstanceStatus } from '@companion-module/base'
import { configFields } from './src/config.js'
import { upgradeScripts } from './src/upgrade.js'
import { FIELDS } from './src/fields.js'
import { initActions } from './src/actions.js'
import got from 'got'
import JimpRaw from 'jimp'
// Webpack makes a mess..
const Jimp = JimpRaw.default || JimpRaw
class SwitchingManager extends InstanceBase {
configUpdated(config) {
this.config = config
initActions(this)
//this.initActions()
this.initFeedbacks()
}
init(config) {
this.config = config
this.updateStatus(InstanceStatus.Ok)
initActions(this)
//this.initActions()
this.initFeedbacks()
}
// Return config fields for web config
getConfigFields() {
return configFields
}
// When module gets deleted
async destroy() {
// Stop any running feedback timers
for (const timer of Object.values(this.feedbackTimers)) {
clearInterval(timer)
}
}
/**
* Send POST command to switching manager.
* Try to re-authenticate in case of authentication token has expired.
* @param {*} url
* @param {*} options
* @param {*} authenticate
*/
async sendCommand(url, options, reAuthenticate){
try {
await got.post(url, options)
this.updateStatus(InstanceStatus.Ok)
} catch (e) {
//this.log('error', `HTTP POST Exception ` + JSON.stringify(e))
if(e.response) {
if(e.response.statusCode == 401 && reAuthenticate) {
this.log('warn', `HTTP POST Request failed (${e.message})`)
this.log('warn', `Try to get new authentication token`)
// Generate new authentication token.
await this.authenticate()
// Use new authentication token.
if(InstanceStatus.Ok) {
options.headers['Authorization'] = 'Bearer ' + this.config.bearer
await this.sendCommand(url, options, false)
}
}
else {
this.log('error', `HTTP POST Request failed (${e.message})`)
this.updateStatus(InstanceStatus.UnknownError, e.response.statusCode)
}
}
else {
this.log('error', `HTTP POST Message ` + JSON.stringify(e.message))
this.updateStatus(InstanceStatus.UnknownError, JSON.stringify(e.message))
}
}
}
/**
* Send authentication request to switching manager.
* Save response bearer token in config.
*/
async authenticate(){
var crypto = await import('node:crypto')
let url = this.config.url + '/Users/authenticate'
let json = {}
json["username"] = this.config.username
json["password"] = crypto.createHash('md5').update(this.config.password).digest("hex");
json["baseNumber"] = 0
json["apiKey"] = "string"
let headers = {}
headers['Content-Type'] = 'application/json'
let https = {}
https['rejectUnauthorized'] = this.config.rejectUnauthorized
// All in one options object.
const options = {
https,
headers,
json,
}
try {
const response = await got.post(url, options)
const token = JSON.parse(response.body).token
this.log('info', 'Received new token')
this.log('info', token)
this.config.bearer = token
this.saveConfig(this.config)
this.updateStatus(InstanceStatus.Ok)
} catch (e) {
this.log('error', `Authenticate HTTP POST Request failed (${e.message})`)
this.updateStatus(InstanceStatus.UnknownError, e.code)
}
}
async prepareQuery(uri, action, includeBody) {
let url = this.config.url + uri
let body = {}
const options = {
https: {
rejectUnauthorized: this.config.rejectUnauthorized,
},
headers,
}
if (typeof body === 'string') {
body = body.replace(/\\n/g, '\n')
options.body = body
} else if (body) {
options.json = body
}
return {
url,
options,
}
}
initActionsOrg() {
const urlLabel = this.config.prefix ? 'URI' : 'URL'
this.setActionDefinitions({
post: {
name: 'POST',
options: [FIELDS.Url(urlLabel), FIELDS.Body, FIELDS.Header, FIELDS.ContentType],
callback: async (action, context) => {
const { url, options } = await this.prepareQuery(context, action, true)
try {
await got.post(url, options)
this.updateStatus(InstanceStatus.Ok)
} catch (e) {
this.log('error', `HTTP POST Request failed (${e.message})`)
this.updateStatus(InstanceStatus.UnknownError, e.code)
}
},
},
get: {
name: 'GET',
options: [
FIELDS.Url(urlLabel),
FIELDS.Header,
{
type: 'custom-variable',
label: 'JSON Response Data Variable',
id: 'jsonResultDataVariable',
},
{
type: 'checkbox',
label: 'JSON Stringify Result',
id: 'result_stringify',
default: true,
},
],
callback: async (action, context) => {
const { url, options } = await this.prepareQuery(context, action, false)
try {
const response = await got.get(url, options)
// store json result data into retrieved dedicated custom variable
const jsonResultDataVariable = action.options.jsonResultDataVariable
if (jsonResultDataVariable) {
this.log('debug', `Writing result to ${jsonResultDataVariable}`)
let resultData = response.body
if (!action.options.result_stringify) {
try {
resultData = JSON.parse(resultData)
} catch (error) {
//error stringifying
}
}
this.setCustomVariableValue(jsonResultDataVariable, resultData)
}
this.updateStatus(InstanceStatus.Ok)
} catch (e) {
this.log('error', `HTTP GET Request failed (${e.message})`)
this.updateStatus(InstanceStatus.UnknownError, e.code)
}
},
},
put: {
name: 'PUT',
options: [FIELDS.Url(urlLabel), FIELDS.Body, FIELDS.Header, FIELDS.ContentType],
callback: async (action, context) => {
const { url, options } = await this.prepareQuery(context, action, true)
try {
await got.put(url, options)
this.updateStatus(InstanceStatus.Ok)
} catch (e) {
this.log('error', `HTTP PUT Request failed (${e.message})`)
this.updateStatus(InstanceStatus.UnknownError, e.code)
}
},
},
patch: {
name: 'PATCH',
options: [FIELDS.Url(urlLabel), FIELDS.Body, FIELDS.Header, FIELDS.ContentType],
callback: async (action, context) => {
const { url, options } = await this.prepareQuery(context, action, true)
try {
await got.patch(url, options)
this.updateStatus(InstanceStatus.Ok)
} catch (e) {
this.log('error', `HTTP PATCH Request failed (${e.message})`)
this.updateStatus(InstanceStatus.UnknownError, e.code)
}
},
},
delete: {
name: 'DELETE',
options: [FIELDS.Url(urlLabel), FIELDS.Body, FIELDS.Header],
callback: async (action, context) => {
const { url, options } = await this.prepareQuery(context, action, true)
try {
await got.delete(url, options)
this.updateStatus(InstanceStatus.Ok)
} catch (e) {
this.log('error', `HTTP DELETE Request failed (${e.message})`)
this.updateStatus(InstanceStatus.UnknownError, e.code)
}
},
},
})
}
feedbackTimers = {}
initFeedbacks() {
const urlLabel = this.config.prefix ? 'URI' : 'URL'
this.setFeedbackDefinitions({
imageFromUrl: {
type: 'advanced',
name: 'Image from URL',
options: [FIELDS.Url(urlLabel), FIELDS.Header, FIELDS.PollInterval],
subscribe: (feedback) => {
// Ensure existing timer is cleared
if (this.feedbackTimers[feedback.id]) {
clearInterval(this.feedbackTimers[feedback.id])
delete this.feedbackTimers[feedback.id]
}
// Start new timer if needed
if (feedback.options.interval) {
this.feedbackTimers[feedback.id] = setInterval(() => {
this.checkFeedbacksById(feedback.id)
}, feedback.options.interval)
}
},
unsubscribe: (feedback) => {
// Ensure timer is cleared
if (this.feedbackTimers[feedback.id]) {
clearInterval(this.feedbackTimers[feedback.id])
delete this.feedbackTimers[feedback.id]
}
},
callback: async (feedback, context) => {
try {
const { url, options } = await this.prepareQuery(context, feedback, false)
const res = await got.get(url, options)
// Scale image to a sensible size
const img = await Jimp.read(res.rawBody)
const png64 = await img
.scaleToFit(feedback.image?.width ?? 72, feedback.image?.height ?? 72)
.getBase64Async('image/png')
return {
png64,
}
} catch (e) {
// Image failed to load so log it and output nothing
this.log('error', `Failed to fetch image: ${e}`)
return {}
}
},
},
})
}
}
runEntrypoint(SwitchingManager, upgradeScripts)