/
customvariables.js
428 lines (388 loc) · 16.4 KB
/
customvariables.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
'use strict';
const _ = require('lodash');
const safeEval = require('safe-eval');
const axios = require('axios');
const {
isMainThread
} = require('worker_threads');
const mathjs = require('mathjs');
const Message = require('./message');
import { permission } from './permissions';
const commons = require('./commons');
class CustomVariables {
constructor () {
this.timeouts = {};
if (isMainThread) {
this.addMenuAndListenersToPanel();
this.checkIfCacheOrRefresh();
global.db.engine.index('custom.variables.history', [{ index: 'cvarId' }]);
}
}
async getURL(req: Request, res: Response) {
try {
const variable = (await global.db.engine.find('custom.variables'))
.find(variable => {
return _.get(variable, 'urls', []).find(url => url.id === req.params.id)
});
if (variable) {
if (_.get(variable.urls.find(url => url.id === req.params.id), 'access.GET', false)) {
return res.status(200).send({ value: await this.getValueOf(variable.variableName) });
} else {
return res.status(403).send({ error: 'This endpoint is not enabled for GET', code: 403 });
}
} else {
return res.status(404).send({ error: 'Variable not found', code: 404 });
}
} catch (e) {
res.status(500).send({ error: 'Internal Server Error', code: 500 });
throw e;
}
}
async postURL(req: Request, res: Response) {
try {
const variable = (await global.db.engine.find('custom.variables'))
.find(variable => {
return _.get(variable, 'urls', []).find(url => url.id === req.params.id)
});
if (variable) {
if (_.get(variable.urls.find(url => url.id === req.params.id), 'access.POST', false)) {
const value = await this.setValueOf(variable.variableName, req.body.value, {});
if (value.isOk) {
return res.status(200).send({ oldValue: variable.currentValue, value: value.updated.setValue });
} else {
return res.status(400).send({ error: 'This value is not applicable for this endpoint', code: 400 });
}
} else {
return res.status(403).send({ error: 'This endpoint is not enabled for POST', code: 403 });
}
} else {
return res.status(404).send({ error: 'Variable not found', code: 404 });
}
} catch (e) {
res.status(500).send({ error: 'Internal Server Error', code: 500 });
throw e;
}
}
async addMenuAndListenersToPanel () {
clearTimeout(this.timeouts[`${this.constructor.name}.addMenuAndListenersToPanel`]);
if (_.isNil(global.panel)) {
this.timeouts[`${this.constructor.name}.addMenuAndListenersToPanel`] = setTimeout(() => this.addMenuAndListenersToPanel(), 1000);
} else {
global.panel.addMenu({ category: 'registry', name: 'custom-variables', id: 'registry.customVariables/list' });
this.sockets();
}
}
sockets () {
const io = global.panel.io.of('/registry/customVariables');
io.on('connection', (socket) => {
socket.on('list.variables', async (cb) => {
let variables = await global.db.engine.find('custom.variables');
cb(null, variables);
});
socket.on('run.script', async (_id, cb) => {
let item;
try {
item = await global.db.engine.findOne('custom.variables', { _id: String(_id) });
item = await global.db.engine.update('custom.variables', { _id: String(_id) }, { currentValue: await this.runScript(item.evalValue, { _current: item.currentValue }), runAt: Date.now() });
} catch (e) {
cb(e.stack, null);
}
cb(null, item);
});
socket.on('test.script', async (opts, cb) => {
let returnedValue;
try {
returnedValue = await this.runScript(opts.evalValue, { _current: opts.currentValue, sender: { username: 'testuser', userId: '0' }});
} catch (e) {
cb(e.stack, null);
}
cb(null, returnedValue);
});
socket.on('isUnique', async ({ variable, id }, cb) => {
cb(null, (await global.db.engine.find('custom.variables', { variableName: String(variable) })).filter(o => String(o._id) !== id).length === 0);
});
socket.on('delete', async (id, cb) => {
await global.db.engine.remove('custom.variables', { _id: String(id) });
await global.db.engine.remove('custom.variables.watch', { variableId: String(id) }); // force unwatch
this.updateWidgetAndTitle();
cb();
});
socket.on('load', async (id, cb) => {
const variable = await global.db.engine.findOne('custom.variables', { _id: String(id) });
const history = await global.db.engine.find('custom.variables.history', { cvarId: String(id) });
cb({variable, history});
});
socket.on('save', async (data, cb) => {
var _id;
try {
if (!_.isNil(data._id)) {
_id = String(data._id); delete (data._id);
await global.db.engine.update('custom.variables', { _id }, data);
this.updateWidgetAndTitle(data.variableName);
} else {
delete (data._id);
let item = await global.db.engine.insert('custom.variables', data);
_id = String(item._id);
this.updateWidgetAndTitle(data.variableName);
}
cb(null, _id);
} catch (e) {
cb(e.stack, _id);
}
});
});
}
async runScript (script, opts) {
let sender = !_.isNil(opts.sender) ? opts.sender : null;
let param = !_.isNil(opts.param) ? opts.param : null;
if (typeof sender === 'string') {
sender = {
username: sender,
userId: await global.users.getIdByName(sender)
};
}
// we need to check +1 variables, as they are part of commentary
const containUsers = !_.isNil(script.match(/users/g)) && script.match(/users/g).length > 1;
const containRandom = !_.isNil(script.replace(/Math\.random|_\.random/g, '').match(/random/g));
const containOnline = !_.isNil(script.match(/online/g));
let users = [];
if (containUsers || containRandom) {
users = await global.users.getAll();
}
let onlineViewers = [];
let onlineSubscribers = [];
let onlineFollowers = [];
if (containOnline) {
onlineViewers = await global.db.engine.find('users.online');
for (let viewer of onlineViewers) {
let user = await global.db.engine.find('users', { username: viewer.username, is: { subscriber: true } });
if (!_.isEmpty(user)) {onlineSubscribers.push(user.username)};
}
for (let viewer of onlineViewers) {
let user = await global.db.engine.find('users', { username: viewer.username, is: { follower: true } });
if (!_.isEmpty(user)) {onlineFollowers.push(user.username)};
}
}
let randomVar = {
online: {
viewer: _.sample(_.map(onlineViewers, 'username')),
follower: _.sample(_.map(onlineFollowers, 'username')),
subscriber: _.sample(_.map(onlineSubscribers, 'username'))
},
viewer: _.sample(_.map(users, 'username')),
follower: _.sample(_.map(_.filter(users, (o) => _.get(o, 'is.follower', false)), 'username')),
subscriber: _.sample(_.map(_.filter(users, (o) => _.get(o, 'is.subscriber', false)), 'username'))
};
// get custom variables
const customVariablesDb = await global.db.engine.find('custom.variables');
const customVariables = {};
for (const cvar of customVariablesDb) {
customVariables[cvar.variableName] = cvar.currentValue;
}
// update globals and replace theirs values
script = (await new Message(script).global({ escape: '\'' }));
let toEval = `(async function evaluation () { ${script} })()`;
let context = {
url: async (url, opts) => {
if (typeof opts === 'undefined') {
opts = {
url,
method: 'GET',
headers: undefined,
data: undefined,
};
} else {
opts.url = url;
}
if (!['GET', 'POST', 'PUT', 'DELETE'].includes(opts.method.toUpperCase())) {
throw Error('only GET, POST, PUT, DELETE methods are supported');
}
if (opts.url.trim().length === 0) {
throw Error('url was not properly specified');
}
const request = await axios(opts);
return { data: request.data, status: request.status, statusText: request.statusText };
},
_: _,
users: users,
random: randomVar,
stream: {
uptime: commons.getTime((await global.cache.when()).online, false),
currentViewers: _.get((await global.db.engine.findOne('api.current', {
key: 'viewers'
})), 'value', 0),
currentSubscribers: _.get((await global.db.engine.findOne('api.current', {
key: 'subscribers'
})), 'value', 0),
currentBits: _.get((await global.db.engine.findOne('api.current', {
key: 'bits'
})), 'value', 0),
currentTips: _.get((await global.db.engine.findOne('api.current', {
key: 'tips'
})), 'value', 0),
currency: global.currency.symbol(global.currency.mainCurrency),
chatMessages: (await global.cache.isOnline()) ? global.linesParsed - global.api.chatMessagesAtStart : 0,
currentFollowers: _.get((await global.db.engine.findOne('api.current', {
key: 'followers'
})), 'value', 0),
currentViews: _.get((await global.db.engine.findOne('api.current', {
key: 'views'
})), 'value', 0),
maxViewers: _.get((await global.db.engine.findOne('api.max', {
key: 'viewers'
})), 'value', 0),
newChatters: _.get((await global.db.engine.findOne('api.new', {
key: 'chatters'
})), 'value', 0),
game: _.get((await global.db.engine.findOne('api.current', {
key: 'game'
})), 'value', null),
status: _.get((await global.db.engine.findOne('api.current', {
key: 'title'
})), 'value', null),
currentHosts: _.get((await global.db.engine.findOne('api.current', {
key: 'hosts'
})), 'value', 0),
currentWatched: global.api._stream.watchedTime
},
sender,
param: param,
_current: opts._current,
user: async (username) => {
const _user = await global.users.getByName(username);
const userObj = {
username,
id: await global.users.getIdByName(username, false),
is: {
online: (await global.db.engine.find('users.online', { username })).length > 0,
follower: _.get(_user, 'is.follower', false),
vip: _.get(_user, 'is.vip', false),
subscriber: _.get(_user, 'is.subscriber', false),
mod: await commons.isModerator(username)
}
};
return userObj;
},
...customVariables,
};
return (safeEval(toEval, context));
}
async isVariableSet (variableName) {
let item = await global.db.engine.findOne('custom.variables', { variableName });
return !_.isEmpty(item) ? String(item._id) : null;
}
async isVariableSetById (_id) {
let item = await global.db.engine.findOne('custom.variables', { _id });
return !_.isEmpty(item) ? String(item.variableName) : null;
}
async getValueOf (variableName, opts) {
if (!variableName.startsWith('$_')) {variableName = `$_${variableName}`};
let item = await global.db.engine.findOne('custom.variables', { variableName });
if (_.isEmpty(item)) {return ''}; // return empty if variable doesn't exist
if (item.type === 'eval' && Number(item.runEvery) === 0) {
item.currentValue = await this.runScript(item.evalValue, {
_current: item.currentValue,
...opts
});
await global.db.engine.update('custom.variables', { variableName }, { currentValue: item.currentValue, runAt: Date.now() });
}
return item.currentValue;
}
/* Sets value of variable with proper checks
*
* @return object
* { updated, isOK }
*/
async setValueOf (variableName, currentValue, opts) {
let item = await global.db.engine.findOne('custom.variables', { variableName });
let isOk = true;
let isEval = false;
let oldValue = null;
opts.sender = _.isNil(opts.sender) ? null : opts.sender;
opts.readOnlyBypass = _.isNil(opts.readOnlyBypass) ? false : opts.readOnlyBypass;
// add simple text variable, if not existing
if (_.isEmpty(item)) {
item = await global.db.engine.insert('custom.variables', { variableName, currentValue, type: 'text', responseType: 0, permission: permission.MODERATORS });
} else {
// set item permission to owner if missing
item.permission = typeof item.permission === 'undefined' ? permission.CASTERS : item.permission;
if (typeof opts.sender === 'string') {
opts.sender = {
username: opts.sender,
userId: await global.users.getIdByName(opts.sender)
};
}
const permissionsAreValid = _.isNil(opts.sender) || (await global.permissions.check(opts.sender.userId, item.permission)).access;
if ((item.readOnly && !opts.readOnlyBypass) || !permissionsAreValid) {
isOk = false;
} else {
oldValue = item.currentValue;
if (item.type === 'number') {
if (['+', '-'].includes(currentValue)) {
currentValue = mathjs.eval(`${item.currentValue} ${currentValue} 1`);
} else {
const isNumber = _.isFinite(Number(currentValue));
isOk = isNumber;
currentValue = isNumber ? Number(currentValue) : item.currentValue;
}
} else if (item.type === 'options') {
// check if is in usableOptions
let isUsableOption = item.usableOptions.split(',').map((o) => o.trim()).includes(currentValue);
isOk = isUsableOption;
currentValue = isUsableOption ? currentValue : item.currentValue;
} else if (item.type === 'eval') {
opts.param = currentValue;
item.currentValue = await this.getValueOf(variableName, opts);
isEval = true;
}
// do update only on non-eval variables
if (item.type !== 'eval' && isOk) {item = await global.db.engine.update('custom.variables', { variableName }, { currentValue })};
}
}
item.setValue = item.currentValue;
if (isOk) {
this.updateWidgetAndTitle(variableName);
if (!isEval) {
this.addChangeToHistory({ sender: _.get(opts, 'sender.username', null), item, oldValue });
item.currentValue = ''; // be silent if parsed correctly
}
}
return { updated: item, isOk, isEval };
}
async addChangeToHistory(opts) {
await global.db.engine.insert('custom.variables.history', { cvarId: String(opts.item._id), sender: opts.sender, oldValue: opts.oldValue, currentValue: opts.item.currentValue, timestamp: String(new Date())});
}
async checkIfCacheOrRefresh () {
clearTimeout(this.timeouts[`${this.constructor.name}.checkIfCacheOrRefresh`]);
let items = await global.db.engine.find('custom.variables', { type: 'eval' });
for (let item of items) {
try {
item.runAt = _.isNil(item.runAt) ? 0 : item.runAt;
const shouldRun = item.runEvery > 0 && Date.now() - new Date(item.runAt).getTime() >= item.runEvery;
if (shouldRun) {
let newValue = await this.runScript(item.evalValue, { _current: item.currentValue });
await global.db.engine.update('custom.variables', { _id: String(item._id) }, { runAt: Date.now(), currentValue: newValue });
await this.updateWidgetAndTitle(item.variableName);
}
} catch (e) {} // silence errors
}
this.timeouts[`${this.constructor.name}.checkIfCacheOrRefresh`] = setTimeout(() => this.checkIfCacheOrRefresh(), 1000);
}
async updateWidgetAndTitle (variable) {
if (!isMainThread) {
global.workers.sendToMaster({ type: 'widget_custom_variables', emit: 'refresh' });
} else if (!_.isNil(global.widgets.custom_variables.socket)) {global.widgets.custom_variables.socket.emit('refresh')}; // send update to widget
if (!_.isNil(variable)) {
const regexp = new RegExp(`\\${variable}`, 'ig');
let title = await global.cache.rawStatus();
if (title.match(regexp)) {
if (!isMainThread) {
global.workers.sendToMaster({ type: 'call', ns: 'api', fnc: 'setTitleAndGame', args: [null] });
} else {
global.api.setTitleAndGame(null);
}
}
}
}
}
module.exports = CustomVariables;