forked from Zefau/ioBroker.jarvis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jarvis.js
519 lines (423 loc) · 15.4 KB
/
jarvis.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
'use strict';
const adapterName = require('./io-package.json').common.name;
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const _crypto = require('crypto');
const _got = require('got');
const _fs = require('fs');
const _path = require('path');
const { v4: _uuid } = require('uuid');
const _platform = require('platform');
/*
* internal libraries
*/
const Library = require('./lib/library.js');
const ioWebSocket = require('./lib/websocket.io.min.js');
/*
* variables initiation
*/
let adapter;
let library;
let socket;
let unloaded;
let notification = '';
let NotificationTimer = null;
let NOTIFICATIONS = [];
let SETTINGS = {};
let CLIENTS = {};
let BACKUPS = {
'styles': {},
'settings': {},
'layout': {},
'widgets': {},
'devices': {}
};
const BACKUP_STATES = [
{ 'state': 'devices' },
{ 'state': 'layout' },
{ 'state': 'widgets' },
{ 'state': 'settings',},
{ 'state': 'css', 'id': 'styles' }
];
/*
* allSettled polyfill
* @see https://medium.com/trabe/using-promise-allsettled-now-e1767d43e480
*/
if (!Promise.allSettled) {
Promise.allSettled = promises =>
Promise.all(
promises.map((promise, i) =>
promise
.then(value => ({
status: "fulfilled",
value,
}))
.catch(reason => ({
status: "rejected",
reason,
}))
)
);
}
/*
* ADAPTER
*
*/
function startAdapter(options) {
options = options || {};
adapter = new utils.Adapter({ ...options, 'name': adapterName });
/*
* ADAPTER READY
*
*/
adapter.on('ready', function() {
unloaded = false;
library = new Library(adapter);
// Check Node.js Version
let version = parseInt(process.version.substr(1, process.version.indexOf('.')-1));
if (version <= 6) {
return library.terminate('This Adapter is not compatible with your Node.js Version ' + process.version + ' (must be >= Node.js v7).', true);
}
// create backup object
BACKUP_STATES.forEach(s => {
s.id = s.id || s.state;
const file = _path.join(__dirname, '..', '..', 'iobroker-data', 'jarvis', adapter.instance.toString(), '_BACKUP_' + s.id.toUpperCase() + '.json');
_fs.readFile(file, (err, contents) => {
// create dir
const dir = _path.dirname(file);
if (!_fs.existsSync(dir)){
_fs.mkdirSync(dir, { 'recursive': true });
}
// trigger initial backup
if (err) {
adapter.log.info('No Backup found for ' + s.id + ', thus backing up initially.');
adapter.getState(s.state, (err, state) => !err && state && state.val && backup(s, state.val));
}
// load recent backups
else if (contents) {
adapter.log.info('Found Backups for ' + s.id + '.');
try {
BACKUPS[s.id] = JSON.parse(contents);
}
catch(err) {
adapter.log.error('Error loading recent backups (' + s.id + '): ' + err.message);
}
}
});
});
// detect and write web port to config
let configPromises = [];
const defaultSocketPort = 8400 + adapter.instance;
configPromises.push(new Promise(resolve => {
adapter.getForeignObject('system.adapter.web.0', (err, obj) => {
adapter.log.debug('Web Configuration: ' + JSON.stringify(obj.native));
const config = {
'user': (obj && obj.native && obj.native.defaultUser) || null,
'webPort': (obj && obj.native && obj.native.port) || 8082,
'socketSecure': obj && obj.native && obj.native.secure !== undefined ? obj.native.secure : false
}
const certificates = {
'certPublic': obj && obj.native && obj.native.certPublic !== undefined ? obj.native.certPublic : '',
'certPrivate': obj && obj.native && obj.native.certPrivate !== undefined ? obj.native.certPrivate : '',
'certChained': obj && obj.native && obj.native.certChained !== undefined ? obj.native.certChained : '',
}
// write config to jarvis
if (
(adapter.config.certPublic !== certificates.certPublic || adapter.config.certPrivate !== certificates.certPrivate || adapter.config.certChained !== certificates.certChained) ||
(adapter.config.autoDetect === true && (adapter.config.webPort !== config.webPort || adapter.config.socketPort !== defaultSocketPort || adapter.config.socketSecure !== config.socketSecure))
) {
adapter.getForeignObject('system.adapter.' + adapter.namespace, (err, obj) => {
if (err || !obj || !obj.native) {
return library.terminate('Error system.adapter.' + adapter.namespace + ' not found!');
}
adapter.log.debug('Remember certificates...');
obj.native = {
...obj.native,
...certificates
}
if (adapter.config.autoDetect === true) {
adapter.log.debug('Write default config to jarvis...');
obj.native = {
...obj.native,
...config,
'socketPort': defaultSocketPort
}
}
adapter.setForeignObject(obj._id, obj);
});
}
resolve(config);
});
}));
// get certificates
if (adapter.config.certPublic && adapter.config.certPrivate) {
configPromises.push(new Promise(resolve => {
adapter.getCertificates(adapter.config.certPublic, adapter.config.certPrivate, adapter.config.certChained, (err, certificates, leConfig) => {
resolve(certificates);
});
}));
}
// open web socket
Promise.all(configPromises)
.then(res => {
const certificates = adapter.config.socketSecure && res[1] ? res[1] : null;
const port = adapter.config.autoDetect === true ? defaultSocketPort : (adapter.config.socketPort || defaultSocketPort);
// open socket
socket = new ioWebSocket(adapter, { ...adapter.config, ...res[0], port, certificates });
// listen for new clients
socket.on('CLIENT_NEW', client => {
CLIENTS[client.id] = CLIENTS[client.id] || {
'path': 'jarvis.' + adapter.instance + '.clients.' + client.id,
'unreadNotifications': []
}
});
// listen for client list
socket.on('CLIENT_LIST', clients => {
adapter.setState('clients.connected', JSON.stringify(clients), true);
});
})
.catch(error => adapter.log.error(error.message || error));
// all ok
library.set(Library.CONNECTION, true);
// write settings to states
adapter.getState('settings', (err, state) => {
if (!err && state && state.val) {
SETTINGS = JSON.parse(state.val) || {};
// random token
SETTINGS.token = SETTINGS.token || _crypto.randomBytes(16).toString('hex');
// usage data option
SETTINGS.sendUsageData = adapter.config.sendUsageData !== undefined ? adapter.config.sendUsageData : true;
adapter.setState('settings', JSON.stringify(SETTINGS), true);
writeSettingsToStates(SETTINGS, () => adapter.subscribeStates('settings*'));
}
});
// initially load notifications
adapter.getState('notifications', (err, state) => {
NOTIFICATIONS = (state && state.val && JSON.parse(state.val)) || [];
});
// initially load available clients
adapter.getDevices((err, clients) => { // [{"type":"device","common":{"name":"::ffff:192.168.178.50"},"native":{},"from":"system.adapter.jarvis.0","user":"system.user.admin","ts":1621149128890,"_id":"jarvis.0.clients.ffff192-168-178-50","acl":{"object":1636,"owner":"system.user.admin","ownerGroup":"system.group.administrator"}}]
clients.forEach(client => {
const clientId = client._id.substr(client._id.lastIndexOf('.')+1);
adapter.getState(client._id + '.newNotifications', (err, state) => {
CLIENTS[clientId] = {
'path': client._id,
'unreadNotifications': []
}
});
});
});
});
/*
* STATE CHANGE
*
*/
adapter.on('stateChange', function(id, state) {
// SKIP ON INVALID STATE
if (id.startsWith('jarvis.' + adapter.instance) === false || state === undefined || state === null || state.val === undefined || state.val === null) {
return;
}
// CLIENT CONNECTION STATE
if (id.startsWith('jarvis.') && id.indexOf('.clients.') > -1 && id.endsWith('.connected') && state && state.val === true) {
const [ , , , clientId,] = id.split('.');
// push unread notifications
if (CLIENTS[clientId].unreadNotifications && CLIENTS[clientId].unreadNotifications.length > 0 && socket.sockets[clientId]) {
socket.sockets[clientId].emit('notification', CLIENTS[clientId].unreadNotifications);
CLIENTS[clientId].unreadNotifications = [];
}
}
// PARSE USER AGENT
if (id.startsWith('jarvis.') && id.indexOf('.clients.') > -1 && id.endsWith('.userAgent') && state && state.val) {
const [ , , , clientId,] = id.split('.');
const platform = _platform.parse(state.val);
adapter.setState(id.substr(0, id.lastIndexOf('.')) + '.userBrowser', JSON.stringify(platform), true);
}
// NOTIFICATIONS
if (id.indexOf('.notifications') > -1) {
NOTIFICATIONS = (state && state.val && JSON.parse(state.val)) || [];
}
// SETTINGS
if (id.substr(-9) === '.settings') {
writeSettingsToStates(JSON.parse(state.val) || {});
}
// SKIP ON ACK
if (state.ack === true) {
return;
}
// ADD NOTIFICATION
if (id.indexOf('.addNotification') > -1 && state && state.val) {
adapter.setState('addNotification', '', true);
try {
// parse notification
notification = state.val.indexOf('{') > -1 && state.val.indexOf('}') > -1 ? JSON.parse(state.val) : { 'title': state.val };
if (Array.isArray(notification) && notification.length === 1) {
notification = notification[0];
}
else if (Array.isArray(notification) && notification.length > 1) {
notification = notification[0];
adapter.log.warn('Only single notification allowed for newly added notifications. Took first one and dropped the rest.');
}
// add further information
notification.id = _uuid();
notification.ts = notification.ts || Date.now();
if (notification.devices) {
notification.devices = Array.isArray(notification.devices) ? notification.devices : [ notification.devices ];
}
// add to list of all notifications
if (notification.state !== 'delete') {
NOTIFICATIONS.push(notification);
adapter.setState('notifications', JSON.stringify(processNotifications(NOTIFICATIONS)), true);
}
// emit notification to clients (or add to list of unread notifications if client is not reachable)
for (let clientId in CLIENTS) {
// either emit to all devices or only to specific ones
if (!notification.devices || notification.devices.includes(clientId)) {
// get connection state
adapter.getState(CLIENTS[clientId].path + '.connected', (err, state) => {
// is connected
if (!err && state && state.val === true && socket.sockets[clientId]) {
socket.sockets[clientId].emit('notification', notification);
}
// not connected, thus, save for later
else {
CLIENTS[clientId].unreadNotifications.push(notification);
}
});
}
}
}
catch(err) {
adapter.log.error(err.message);
}
}
// SETTING
if (id.indexOf('.settings.') > -1) {
const setting = id.substr(id.lastIndexOf('.settings.')+10);
// update settings
SETTINGS[setting] = state && state.val && state.val.toString().indexOf('{') > -1 && state.val.toString().indexOf('}') > -1 ? JSON.parse(state.val) : state.val;
adapter.setState('settings', JSON.stringify(SETTINGS), true);
// update adapter config
if (adapter.config[setting] !== undefined) {
adapter.getForeignObject('system.adapter.' + adapter.namespace, (err, obj) => {
if (err || !obj || !obj.native) {
return library.terminate('Error system.adapter.' + adapter.namespace + ' not found!');
}
obj.native[setting] = state.val;
adapter.setForeignObject(obj._id, obj);
});
}
}
// BACKUP
const foundIndex = BACKUP_STATES.findIndex(s => s.state === id.substr(id.lastIndexOf('.')+1));
if (foundIndex > -1) {
backup(BACKUP_STATES[foundIndex], state.val);
}
});
/*
* MESSAGE
*
*/
adapter.on('message', function(msg) {
adapter.log.debug('Got message: ' + JSON.stringify(msg));
// get backups
if (msg.command === '_backups' && msg.message) {
adapter.log.debug('Get List of Backups for ' + msg.message.id);
library.msg(msg.from, msg.command, BACKUPS[msg.message.id], msg.callback);
}
// restore
else if (msg.command === '_restore' && msg.message && msg.message.id && msg.message.state && msg.message.date) {
adapter.log.debug('Restore ' + msg.message.id);
restore(msg.message.id, msg.message.state, msg.message.date);
}
});
/*
* ADAPTER UNLOAD
*
*/
adapter.on('unload', function(callback) {
try {
adapter.log.info('Adapter stopped und unloaded.');
unloaded = true;
library.resetStates();
callback();
}
catch(e) {
callback();
}
});
return adapter;
}
/**
*
*
*/
function processNotifications(notifications) {
// max entries
const maxEntries = SETTINGS.maxNotifications || 1000;
notifications = notifications.slice(-(maxEntries + 1));
// purge old notifications
//notifications = notifications.map(notification => );
return notifications;
}
/**
*
*
*/
function restore(id, state, date) {
adapter.log.info('Restore ' + id + ' from ' + date + '..');
adapter.setState(state, BACKUPS[id][date], true);
}
/**
*
*
*/
function backup(s, data) {
s.id = s.id || s.state;
// add to backup
const date = new Date();
const key = date.getFullYear() + '-' + ('0' + (date.getMonth()+1)).substr(-2) + '-' + ('0' + date.getDate()).substr(-2) + '_' + ('0' + date.getHours()).substr(-2) + '-' + ('0' + date.getMinutes()).substr(-2) + '-' + ('0' + date.getSeconds()).substr(-2);
BACKUPS[s.id][key] = data;
// delete old entries
adapter.config.keepBackupEntries = (adapter.config.keepBackupEntries || 25)-1;
const entries = Object.keys(BACKUPS[s.id]);
if (entries.length > adapter.config.keepBackupEntries) {
entries.reverse().forEach((key, i) => {
if (i > adapter.config.keepBackupEntries) {
delete BACKUPS[s.id][key];
}
});
}
// save backup
adapter.log.info('Backup ' + s.id + '..');
const file = _path.join(__dirname, '..', '..', 'iobroker-data', 'jarvis', adapter.instance.toString(), '_BACKUP_' + s.id.toUpperCase() + '.json');
_fs.writeFile(file, JSON.stringify(BACKUPS[s.id], null, 3), err => err && adapter.log.error(err));
}
/**
*
*
*/
function writeSettingsToStates(s, cb = null) {
let promises = [];
for (let setting in s) {
const val = typeof s[setting] === 'object' ? JSON.stringify(s[setting]) : s[setting];
promises.push(new Promise((resolve, reject) => {
library.set({
'node': 'settings.' + setting,
'description': 'Modify setting ' + setting,
'role': 'config',
'type': typeof val,
'write': true,
'read': true
}, val, { 'callback': (err, res) => err ? reject(err) : resolve(res) });
}));
}
Promise.allSettled(promises).then(res => cb && cb());
}
/*
* COMPACT MODE
* If started as allInOne/compact mode => return function to create instance
*
*/
if (module && module.parent)
module.exports = startAdapter;
else
startAdapter(); // or start the instance directly