-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathServer.js
1597 lines (1420 loc) · 62.2 KB
/
Server.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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Server.js
// Homematic Virtual Interface Core
//
// Created by Thomas Kluge on 20.11.16.
// Copyright � 2016 kSquare.de. All rights reserved.
//
/* eslint-disable handle-callback-err */
'use strict'
const path = require('path')
const os = require('os')
const HomematicLogicalLayer = require(path.join(__dirname, 'HomematicLogicLayer.js')).HomematicLogicalLayer
const Config = require(path.join(__dirname, 'Config.js')).Config
const ConfigServer = require(path.join(__dirname, 'ConfigurationServer.js')).ConfigurationServer
const Plugin = require(path.join(__dirname, 'VirtualDevicePlugin.js')).VirtualDevicePlugin
const crypto = require('crypto')
const httpHeaders = require('http-headers')
const dgram = require('dgram')
const RegaRequest = require(path.join(__dirname, 'HomematicReqaRequest.js'))
var appRoot = path.join(__dirname, '..')
appRoot = path.normalize(appRoot)
const logger = require(path.join(__dirname, '/logger.js')).logger('Homematic Virtual Interface.Server')
const HomematicChannel = require(path.join(__dirname, '/HomematicChannel.js')).HomematicChannel
const HomematicDevice = require(path.join(__dirname, '/HomematicDevice.js')).HomematicDevice
const fs = require('fs')
const url = require('url')
var Server = function () {
logger.debug('Starting up')
this.cleanLog()
this.configuration = Config
}
Server.prototype.init = function () {
var that = this
this.configuration.load()
if (this.configuration.getValue('enable_debug') === true) {
require(path.join(__dirname, '/logger.js')).setDebugEnabled(true)
}
logger.info('core version %s', this.getVersion(undefined))
logger.info('running on %s with node version %s', process.platform, process.version)
logger.info('current system user is %s', this.currentUser())
logger.info('hello from the flight deck. my path is %s', appRoot)
logger.info('starting point was %s', path.dirname(require.main.filename))
this.configuratedPlugins = []
this.configServer = new ConfigServer(this.configuration)
this.homematicChannel = HomematicChannel
this.homematicDevice = HomematicDevice
// this.updateResult
this.myPathHandler = ['', 'index', 'settings', 'install', 'device', 'plugins', 'security', 'assets']
this.npmCommand = this.configuration.getValueWithDefault('npm_command', 'npm')
this.npmUpdate = this.configuration.getValueWithDefault('npm_update_command', 'i')
this.serviceLauncher = this.configuration.getValueWithDefault('serviceLauncher', '/etc/init.d/hvl_service')
this.serviceEnableCommand = this.configuration.getValueWithDefault('serviceEnableCommand', 'sudo chmod +x /etc/init.d/hvl_service;sudo update-rc.d hvl_service defaults;')
this.serviceDisableCommand = this.configuration.getValueWithDefault('serviceDisableCommand', 'sudo rm /etc/init.d/hvl_service;sudo update-rc.d hvl_service remove')
this.backupCommand = this.configuration.getValueWithDefault('backupCommand', 'tar -C %config% --exclude=logs/* -czvf /tmp/hvl_backup.tar.gz .')
this.localization = require(path.join(__dirname, '/Localization.js'))(path.join(__dirname, '/Localizable.strings'))
this.hm_layer = new HomematicLogicalLayer(this.configuration)
this.hm_layer.init()
this.hm_layer.hvlserver = this
this.ccuAlive = false
this.initSSDPBroadcaster()
if (this.configuration.getValueWithDefault('enable_ccu_ssdp', false) === true) {
logger.info('addind CCU to SSDP Service')
this.addSSDPService({
"owner": "core",
"st": "upnp:rootdevice",
"payload": {
"EXT": "",
"LOCATION": "http://" + this.configuration.getValue('ccu_ip') + "/upnp/basic_dev.cgi",
"SERVER": "HomeMatic",
"ST": "upnp:rootdevice",
"USN": "uuid:upnp-BasicDevice-1_0-3014F711A061A7D5698CEA1B::upnp:rootdevice"
}
})
}
this.ccuPing()
/* systemd stuff */
this.systemdPath = '/etc/systemd/system/'
this.systemdFile = 'hvl.service'
if (this.configuration.getValueWithDefault('ssdp_ccu', 0) === 1) {
this.startAnnouncingCCU()
}
this.cachedPluginList = []
this.reloadPlugins()
// Scan the www directory for .htm or html files an add them to myPathHandler
fs.readdirSync(path.join(__dirname, '..', 'www')).forEach(file => {
if (file.endsWith('.htm') || (file.endsWith('.html'))) {
that.myPathHandler.push(file)
}
})
this.configServer.on('config_server_http_event', function (dispatched_request) {
var handled = false
if (dispatched_request.request_paths.length > 0) {
let pluginpart = dispatched_request.request_paths[1]
that.configuratedPlugins.forEach(function (plugin) {
if (pluginpart === plugin.name) {
try {
logger.debug('WebRequest for Plugin %s', pluginpart)
plugin.handleConfigurationRequest(dispatched_request)
handled = true
} catch (err) {
logger.error('Handle Configuration Request Error %s', err.stack)
}
}
})
}
if (handled === false) {
logger.debug('request %s not handled by a plugin try mine', dispatched_request.request_paths[1])
// request not handled by a plugin try core
var isMy = that.myPathHandler.indexOf(dispatched_request.request_paths[1].toLowerCase())
if (isMy > -1) {
logger.debug('%s is mine', dispatched_request.request_paths[1])
if (dispatched_request.request_paths[1].endsWith('.htm') || dispatched_request.request_paths[1].endsWith('.html')) {
// this is a static html file -> send it
dispatched_request.dispatchFile(null, dispatched_request.request.url)
} else {
that.handleConfigurationRequest(dispatched_request)
}
} else {
// check .htm / html Files
// Redirect to index there is no one to handle that request
logger.debug('nobody to handle redirect')
dispatched_request.redirectTo('/')
}
}
})
setTimeout(function () {
that.cleanLog()
}, 3600000)
process.on('unhandledRejection', (reason, p) => {
logger.error('Unhandled Rejection at: Promise %s reason: %s', JSON.stringify(p), reason.stack)
})
}
Server.prototype.ccuPing = function () {
var that = this
logger.debug('Pinging CCU')
this.hm_layer.ccuPing(function (result) {
if (result === true) {
logger.info('CCU is alive')
that.ccuAlive = true
} else {
that.ccuAlive = false
logger.warn('No rega response')
setTimeout(function () {
that.ccuPing()
}, 2000)
}
})
}
Server.prototype.addSSDPService = function (options) {
logger.info('Add UPnP Service %s', options.st)
if (typeof options.payload === 'object') {
// Build payloadString
var mPayload = 'HTTP/1.1 200 OK\r\n\HOST: 239.255.255.250:1900r\n'
Object.keys(options.payload).forEach(key => {
let pv = options.payload[key]
mPayload = mPayload + key.toUpperCase() + ':' + pv + '\r\n'
})
mPayload = mPayload + '\r\n'
options.payload = mPayload
}
this.ssdpServices.push(options)
}
Server.prototype.removeSSDPServiceByOwner = function (owner) {
for (var i = 0; i < this.ssdpServices.length; i++) {
var obj = this.ssdpServices[i]
if (obj.owner === owner) {
logger.info('remove %s from UPnP', obj.st)
this.ssdpServices.splice(i, 1)
i--
}
}
}
Server.prototype.initSSDPBroadcaster = function () {
var that = this
this.ssdpServices = []
this.ssdp = dgram.createSocket('udp4')
this.ssdp.bind(1900, undefined, function () {
that.ssdp.addMembership('239.255.255.250')
that.ssdp.on('message', function (msg, rinfo) {
var msgString = msg.toString()
if (msgString.substr(0, 10) === 'M-SEARCH *') {
var headers = httpHeaders(msg)
if ((headers.man === '"ssdp:discover"') || (headers.man === 'ssdp:discover')) {
that.ssdpServices.forEach(function (options) {
if ((headers.st === options.st) || (headers.st === 'ssdp:all')) {
var responseBuffer = new Buffer(options.payload)
logger.debug('SSDP discovery returning message for %s (%s)', options.owner, options.st)
setTimeout(function () {
that.ssdp.send(responseBuffer, 0, responseBuffer.length, rinfo.port, rinfo.address)
}, Math.random(10) * 100)
}
})
}
}
})
that.ssdp.on('error', function (error) {
logger.error('SSDP Broadcaster Error : %s', error)
})
})
}
Server.prototype.startAnnouncingCCU = function () {
// Start announcing ccu
this.addSSDPService({
'owner': 'core',
'st': 'upnp:rootdeviceUSN:uuid:upnp-BasicDevice-1_0-::upnp:rootdevice',
'payload': 'HTTP/1.1 200 OK\r\nHOST: 239.255.255.250:1900\r\nNT: urn:schemas-upnp-org:device:Basic:1\r\nExt: \r\nNTS: ssdp:alive\r\nCACHE-CONTROL: max-age=1800\r\nSERVER:HomeMatic\r\nST: upnp:rootdeviceUSN:uuid:upnp-BasicDevice-1_0-::upnp:rootdevice\r\nLOCATION: http://' + this.hm_layer.ccuIP + '/upnp/basic_dev.cgi\r\n\r\n'
})
}
Server.prototype.getCoreRootFolder = function () {
return appRoot
}
Server.prototype.reloadPlugins = function () {
logger.info('Reload .. shutdown all plugins')
this.configuratedPlugins.forEach(function (plugin) {
plugin.platform.shutdown()
})
this.activePlugins = []
this.ssdpServices = []
this.configuratedPlugins = []
this.plugins = this._loadPlugins()
// this.buildpackagefile()
}
Server.prototype.cleanLog = function () {
var LoggerQuery = require(path.join(__dirname, '/logger.js')).LoggerQuery
new LoggerQuery('').clean(5)
}
Server.prototype.shutdown = function () {
this.getBridge().shutdown()
this.getConfigurationServer().shutdown()
this.configuratedPlugins.forEach(function (plugin) {
if (plugin.platform) {
plugin.platform.shutdown()
}
})
this.configuratedPlugins = []
logger.info('remove all UPnP advertizements')
if (this.ssdp && this.ssdp._bindState) this.ssdp.close()
logger.info('Shutdown completed, bon voyage')
}
Server.prototype.getBridge = function () {
return this.hm_layer
}
Server.prototype.getConfigurationServer = function () {
return this.configServer
}
Server.prototype.dependenciesInitialized = function (dependencies) {
var result = true
var that = this
if (dependencies) {
// uuuuh this is just dirty stuff .. �\_(. .)_/�
if (typeof dependencies === 'string') {
dependencies = dependencies.split(',')
}
dependencies.forEach(function (dplugin) {
that.configuratedPlugins.forEach(function (plugin) {
if ((plugin.name === dplugin) && (plugin.initialized === false)) {
result = false
}
})
})
}
return result
}
Server.prototype.addDefaultIndexAttributes = function (attributes) {
attributes['haz_update'] = (this.updateResult === -1) ? '(1)' : ''
return attributes
}
Server.prototype.handleConfigurationRequest = function (dispatched_request) {
/* eslint-disable no-new */
var requesturl = dispatched_request.request.url
var that = this
var cfg_handled = false
this.localization.setLanguage(dispatched_request)
var parsed = new url.URL(requesturl, 'http://localhost')
if ((parsed.pathname === '/') || (parsed.pathname === '/index.html')) {
// this.updateResult = this.checkUpdate()
var pluginString = ''
var pluginSettings = ''
var plugin_settings_template = dispatched_request.getTemplate(null, 'plugin_item_ws.html', null)
var plugin_no_settings_template = dispatched_request.getTemplate(null, 'plugin_item_wos.html', null)
this.configuratedPlugins.forEach(function (plugin) {
pluginString = pluginString + '<li><a href="' + plugin.name + '/">' + plugin.name + '</a></li>'
// var hazSettings = (typeof(plugin.platform.showSettings) === 'function')
var hazSettings = true
var pversion = that.getVersion(plugin)
pluginSettings = pluginSettings + dispatched_request.fillTemplate((hazSettings === true) ? plugin_settings_template : plugin_no_settings_template, {
'plugin.name': plugin.name,
'plugin.version': pversion
})
})
var cs = 0
var csd = ''
var zeroMessage = ''
var ipccu = this.localization.localize('unknow CCU ip')
var bridge = this.getBridge()
if (bridge !== undefined) {
cs = bridge.listConsumer().length
bridge.listConsumer().forEach(function (consumer) {
csd = csd + consumer.description() + ' | '
})
ipccu = 'CCU IP: ' + bridge.ccuIP + ((this.ccuAlive === true) ? ' alive ' : ' no response')
if (cs === 0) {
zeroMessage = this.localization.localize('It seems that your ccu does not know anything about the Homematic-Virtual-Layer. If you are sure about the CCU-IP, and the correct settings in your CCU InterfacesList.xml, a CCU reboot may help.')
/* eslint-disable no-useless-escape */
if ((bridge.ccuIP !== undefined) && (bridge.ccuInterfaceFound === false)) {
let installMessage = this.localization.localize('If its the first run you have to setup your ccu click <a href=\"/settings/?addInterface\">here to add HVL</a>')
zeroMessage = zeroMessage + ' ' + installMessage
}
}
}
var sysversion = this.getVersion(undefined)
csd = csd + this.localization.localize('Last Message ') + bridge.lastMessage
dispatched_request.dispatchFile(null, 'index.html', this.addDefaultIndexAttributes({
'message': '',
'plugins': pluginString,
'pluginSettings': pluginSettings,
'consumer': cs,
'consumer.detail': csd,
'consumer.zeromessage': zeroMessage,
'system.version': sysversion,
'system.ipccu': ipccu
}))
cfg_handled = true
} else {
if (dispatched_request.request_paths[1] === 'index') {
if (parsed.searchParams.get('installmode') !== null) {
this.hm_layer.publishAllDevices(function () {
dispatched_request.dispatchFile(null, 'action.html', that.addDefaultIndexAttributes({
'message': that.localization.localize('all devices published')
}))
})
cfg_handled = true
}
if (parsed.searchParams.get('checkupdate') !== null) {
var npmName = 'homematic-virtual-interface'
// var systemPath = appRoot // lib/homematic-virtual-layer/node_modules
if (this.isNPM(npmName, appRoot)) {
var message = 'You are using the npm version. Updates are shown at the main page.'
var link = '#'
} else {
var update = this.checkUpdate()
message = 'You are up to date'
link = '#'
if (update === -1) {
message = that.localization.localize('There is an update available.')
link = '/index/?doupdate'
}
}
dispatched_request.dispatchFile(null, 'update.html', this.addDefaultIndexAttributes({
'message': message,
'link': link
}))
cfg_handled = true
}
if (parsed.searchParams.get('doupdate') !== null) {
update = this.doUpdate()
dispatched_request.dispatchFile(null, 'update.html', this.addDefaultIndexAttributes({
'message': update,
'link': '#'
}))
cfg_handled = true
}
if (parsed.searchParams.get('cleanup') !== null) {
this.hm_layer.cleanUp()
update = that.localization.localize('All connections removed. Please restart your CCU.')
dispatched_request.dispatchFile(null, 'index.html', this.addDefaultIndexAttributes({
'message': update,
'link': '#'
}))
cfg_handled = true
}
if (parsed.searchParams.get('showlog') !== null) {
var LoggerQuery = require(path.join(__dirname, '/logger.js')).LoggerQuery
new LoggerQuery('').queryAll(function (err, result) {
var str = ''
result.some(function (msg) {
str = str + msg.time + '[' + msg.module + '] [' + msg.level + '] - ' + msg.msg + '\n'
})
dispatched_request.dispatchFile(null, 'log.html', {
'logData': str
})
})
cfg_handled = true
}
if (parsed.searchParams.get('enabledebug') !== null) {
this.configuration.setValue('enable_debug', true)
setTimeout(function () {
that.restart()
}, 2000)
dispatched_request.dispatchFile(null, 'restart.html', this.addDefaultIndexAttributes({
'message': 'Rebooting',
'link': '#'
}))
cfg_handled = true
}
if (parsed.searchParams.get('disabledebug') !== null) {
this.configuration.setValue('enable_debug', false)
setTimeout(function () {
that.restart()
}, 2000)
dispatched_request.dispatchFile(null, 'restart.html', this.addDefaultIndexAttributes({
'message': 'Rebooting',
'link': '#'
}))
cfg_handled = true
}
if (parsed.searchParams.get('daemon') !== null) {
if (this.isRaspberryMatic()) {
dispatched_request.dispatchFile(null, 'daemon.html', this.addDefaultIndexAttributes({
'message': that.localization.localize('Not available on RaspberryMatic'),
'link': '#'
}))
} else
if (process.platform === 'linux') {
if (this.hazDaemon()) {
dispatched_request.dispatchFile(null, 'daemon.html', this.addDefaultIndexAttributes({
'message': that.localization.localize('Disable HVL launch at boot'),
'link': '/index/?disabledaemon'
}))
} else {
dispatched_request.dispatchFile(null, 'daemon.html', this.addDefaultIndexAttributes({
'message': that.localization.localize('Enable HVL launch at boot'),
'link': '/index/?enabledaemon'
}))
}
} else {
dispatched_request.dispatchFile(null, 'daemon.html', this.addDefaultIndexAttributes({
'message': that.localization.localize('This is not supported on your os'),
'link': '#'
}))
}
cfg_handled = true
}
if (parsed.searchParams.get('enabledaemon') !== null) {
let msg = this.enableDaemon() ? 'Added as service' : 'Cannot add hvl as a service'
dispatched_request.dispatchFile(null, 'message.html', this.addDefaultIndexAttributes({
'message': that.localization.localize(msg),
'link': '#'
}))
cfg_handled = true
}
if (parsed.searchParams.get('disabledaemon') !== null) {
let msg = this.disableDaemon() ? 'removed service' : 'unable to remove the service'
dispatched_request.dispatchFile(null, 'message.html', this.addDefaultIndexAttributes({
'message': that.localization.localize(msg),
'link': '#'
}))
cfg_handled = true
}
if (parsed.searchParams.get('logvirtualchannels') !== null) {
this.hm_layer.logVirtualChannels()
}
if (parsed.searchParams.get('backup') !== null) {
this.createHVLBackup()
dispatched_request.dispatchFile('/tmp', 'hvl_backup.tar.gz', null)
cfg_handled = true
}
if (parsed.searchParams.get('restart') !== null) {
setTimeout(function () {
that.restart()
}, 2000)
dispatched_request.dispatchFile(null, 'restart.html', this.addDefaultIndexAttributes({
'message': 'Rebooting',
'link': '#'
}))
cfg_handled = true
}
if (parsed.searchParams.get('getcorps') !== null) {
this.hm_layer.getcorpsedCCUDevices(function (list) {
var devList = ''
var template = dispatched_request.getTemplate(null, 'list_corps_item.html', null)
list.some(function (device) {
logger.debug(JSON.stringify(device))
devList = devList + dispatched_request.fillTemplate(template, {
'device_address': device.address,
'rega_id': device.regaid
})
})
dispatched_request.dispatchFile(null, 'corpsed_devices.html', that.addDefaultIndexAttributes({
'list': devList
}))
})
cfg_handled = true
}
if (parsed.searchParams.get('removecorps') !== null) {
logger.debug('remove unhandled devices')
let regaid = parsed.searchParams.get('regaid')
if (regaid !== undefined) {
logger.debug('trying to remove %s', regaid)
this.hm_layer.removeCorpses([{
'regaid': regaid
}], function () {
dispatched_request.redirectTo('/index/?getcorps')
})
}
cfg_handled = true
}
}
if (dispatched_request.request_paths[1] === 'settings') {
var result = {}
if (parsed.searchParams.get('plugin') !== null) {
that.configuratedPlugins.forEach(function (plugin) {
if (plugin.name === parsed.searchParams.get('plugin')) {
result['plugin.name'] = plugin.name
var ret = that.handlePluginSettingsRequest(dispatched_request, plugin)
if (ret) {
result['editor'] = ret
} else {
cfg_handled = true
}
}
})
}
if (parsed.searchParams.get('ccu') !== null) {
let ccuip = parsed.searchParams.get('ccu')
logger.info('set ccu ip to %s ...', ccuip)
this.configuration.setValue('ccu_ip', ccuip)
setTimeout(function () {
that.restart()
}, 2000)
dispatched_request.dispatchFile(null, 'restart.html', this.addDefaultIndexAttributes({
'message': 'Rebooting',
'link': '#'
}))
cfg_handled = true
}
if (parsed.searchParams.get('rebootCCU') !== null) {
let script = "system.Exec('reboot');"
new RegaRequest(this.hm_layer, script, function (result) {
})
update = that.localization.localize('Your ccu reboots now.. Time to get a coffee...')
dispatched_request.dispatchFile(null, 'restart_ccu.html', that.addDefaultIndexAttributes({
'message': update,
'link': '#'
}))
cfg_handled = true
}
if (parsed.searchParams.get('addInterfaceScript') !== null) {
var script = this.prepareScriptFile('ccu_rcscript.txt')
dispatched_request.dispatchMessage(script)
cfg_handled = true
}
if (parsed.searchParams.get('addInterfaceInstaller') !== null) {
script = this.prepareScriptFile('ccu_installer.txt')
dispatched_request.dispatchMessage(script)
cfg_handled = true
}
if (parsed.searchParams.get('addInterface') !== null) {
logger.info('try to add HVL as Service ...')
script = 'string stdin;string stdout;string cmd;cmd="sh -c \'wget myProt://myIp:myPort/settings/?addInterfaceInstaller --no-check-certificate -O/tmp/i.sh\'";system.Exec(cmd,&stdin,&stdout);system.Exec("sh -c \'chmod +x /tmp/i.sh;/tmp/i.sh\'",&stdin,&stdout);WriteLine(stdout);'
script = this.prepareScript(script)
logger.info(script)
new RegaRequest(this.hm_layer, script, function (result) {
logger.info('HVL Add Result %s', result)
})
update = '<a href=\'/settings/?rebootCCU\'>' + that.localization.localize('Please reboot your ccu') + '</a>'
dispatched_request.dispatchFile(null, 'restart_ccu.html', that.addDefaultIndexAttributes({
'message': update,
'link': '#'
}))
cfg_handled = true
}
dispatched_request.dispatchFile(null, 'plugin_settings.html', this.addDefaultIndexAttributes(result))
cfg_handled = true
}
if (dispatched_request.request_paths[1] === 'install') {
if (parsed.searchParams.get('plugin') !== null) {
var plugin = parsed.searchParams.get('plugin')
try {
this.installPlugin(plugin, function (error) {
dispatched_request.dispatchMessage('{"result":' + (error) ? 'true' : 'false' + '}')
})
} catch (e) {
logger.error(e.stack)
}
}
cfg_handled = true
}
if (dispatched_request.request_paths[1] === 'plugins') {
if ((parsed.searchParams.get('do')) && (parsed.searchParams.get('plugin'))) {
var plgtp = parsed.searchParams.get('plugin')
switch (parsed.searchParams.get('do')) {
case 'activate':
that.activatePlugin(plgtp)
dispatched_request.dispatchMessage('{"result":"true"}')
break
case 'deactivate':
that.deactivatePlugin(plgtp)
dispatched_request.dispatchMessage('{"result":"true"}')
break
case 'refresh':
that.refreshPluginList()
dispatched_request.dispatchMessage('{"result":"true"}')
break
case 'update':
var updateList = []
if (plgtp !== 'all') {
logger.info('Updating %s', plgtp)
var pobj = that.pluginWithType(plgtp)
if (pobj) {
pobj.npm = plgtp
updateList.push(pobj)
that.doNPMUpdate(updateList)
that.reloadPlugins()
} else {
logger.error('Update Object for %s not found', plgtp)
}
dispatched_request.dispatchMessage('{"result":"true"}')
} else {
logger.info('Updating all plugins')
this.fetchPluginList(function (error, lresult) {
logger.debug('Plugin list %s', lresult)
lresult.some(function (pluginObject) {
if (pluginObject.installed) {
updateList.push(pluginObject)
}
})
that.doNPMUpdate(updateList)
that.reloadPlugins()
dispatched_request.dispatchMessage('{"result":"true"}')
})
}
break
case 'version':
that.fetch_npmVersion(plgtp, function (centralVersion) {
if ((centralVersion !== undefined) && (centralVersion.version !== undefined)) {
logger.debug('Get Version for %s result %s', plgtp, JSON.stringify(centralVersion))
dispatched_request.dispatchMessage('{"result":' + JSON.stringify(centralVersion) + '}')
} else {
logger.warn('Error Get Version for %s', plgtp)
dispatched_request.dispatchMessage('{}')
}
})
break
}
cfg_handled = true
} else {
// generate a List
var plugin_template = dispatched_request.getTemplate(null, 'plugin_item.html', null)
result = ''
this.fetchPluginList(function (error, lresult) {
if (error == null) {
that.cachedPluginList = lresult
lresult.some(function (pluginObject) {
var description = that.localization.getLocalizedStringFromModuleJSON(pluginObject.description)
result = result + dispatched_request.fillTemplate(plugin_template, {
'plugin.type': pluginObject.name,
'plugin.installed': (pluginObject.installed) ? '[X]' : '[ ]',
'plugin.active': (pluginObject.active) ? '[X]' : '[ ]',
'plugin.description': description || '',
'plugin.installbutton': (pluginObject.installed) ? 'disabled="disabled"' : '',
'plugin.activatebutton': ((pluginObject.active) || (!pluginObject.installed)) ? 'disabled="disabled"' : '',
'plugin.version': (pluginObject.version) || 'unknow version',
'plugin.removebutton': (pluginObject.active) ? '' : 'disabled="disabled"',
'plugin.npm': pluginObject.npm
})
})
} else {
logger.error('Fetch Error %s', error)
}
dispatched_request.dispatchFile(null, 'plugins.html', that.addDefaultIndexAttributes({
'plugins': result
}))
})
cfg_handled = true
}
}
if (dispatched_request.request_paths[1] === 'assets') {
logger.debug('WebUI asset request')
dispatched_request.dispatchFile(null, dispatched_request.request.url)
cfg_handled = true
}
if (dispatched_request.request_paths[1] === 'security') {
logger.debug('security handler request')
if (dispatched_request.post !== undefined) {
var operation = dispatched_request.post['op']
if (operation === 'save') {
logger.info('Saving Settings -> Restart')
var https = dispatched_request.post['settings_https']
var auth = dispatched_request.post['settings_auth']
var pwd = dispatched_request.post['settings_pwd']
this.configuration.setValue('use_https', (https === 'true'))
this.configuration.setValue('use_http_auth', (auth === 'true'))
if ((pwd !== undefined) && (pwd !== '')) {
var md5 = crypto.createHash('md5').update(pwd).digest('hex')
this.configuration.setValue('http_auth_pwd', md5)
}
}
}
https = this.configuration.getValueWithDefault('use_https', false)
auth = this.configuration.getValueWithDefault('use_http_auth', false)
pwd = this.configuration.getValueWithDefault('http_auth_pwd', undefined)
var settings_text_template = dispatched_request.getTemplate(null, 'settings_text.html', null)
var settings_option_template = dispatched_request.getTemplate(null, 'settings_option.html', null)
result = ''
result = result + dispatched_request.fillTemplate(settings_option_template, {
'control.name': 'settings_https',
'control.value': (https) ? 'checked=\'checked\'' : '',
'control.label': that.localization.localize('Use https'),
'control.description': ''
})
result = result + dispatched_request.fillTemplate(settings_option_template, {
'control.name': 'settings_auth',
'control.value': (auth) ? 'checked=\'checked\'' : '',
'control.label': that.localization.localize('Use HTTP Auth'),
'control.description': ''
})
result = result + dispatched_request.fillTemplate(settings_text_template, {
'control.name': 'settings_pwd',
'control.value': '',
'control.label': that.localization.localize('Admin Password'),
'control.description': 'Username : admin',
'control.type': 'password'
})
dispatched_request.dispatchFile(null, 'security.html', this.addDefaultIndexAttributes({
'content': result
}))
cfg_handled = true
}
if (dispatched_request.request_paths[1] === 'device') {
if (parsed.searchParams.get('do') !== null) {
switch (parsed.searchParams.get('do')) {
case 'remove':
if (parsed.searchParams.get('adr') !== null) {
this.hm_layer.deleteDeviceWithAdress(parsed.searchParams.get('adr'))
}
dispatched_request.dispatchFile(null, 'service.html', this.addDefaultIndexAttributes({
'message': 'Will try to remove Device',
'link': '#'
}))
break
case 'restore':
if (parsed.searchParams.get('adr') !== null) {
var adr = parsed.searchParams.get('adr')
var deletedDevices = this.configuration.getPersistValueWithDefault('deletedDevices', [])
var index = deletedDevices.indexOf(adr)
if (index > -1) {
deletedDevices.splice(index, 1)
}
this.configuration.setPersistValue('deletedDevices', deletedDevices)
}
dispatched_request.dispatchFile(null, 'service.html', this.addDefaultIndexAttributes({
'message': 'Will try to restore Device',
'link': '#'
}))
break
}
} else {
// Generate List
deletedDevices = this.configuration.getPersistValueWithDefault('deletedDevices', [])
var template = dispatched_request.getTemplate(null, 'removed_device_item.html', null)
result = ''
deletedDevices.some(function (device) {
result = result + dispatched_request.fillTemplate(template, {
'device.adress': device
})
})
dispatched_request.dispatchFile(null, 'removed_devices.html', this.addDefaultIndexAttributes({
'devices': result
}))
}
cfg_handled = true
}
if (cfg_handled === false) {
dispatched_request.dispatchMessage('404 Not found')
}
}
}
Server.prototype.createHVLBackup = function () {
require('child_process').execSync('rm -f /tmp/hvl_backup.tar.gz')
let bCmd = this.backupCommand.replace(/%config%/gi, this.configuration.storagePath())
logger.debug('Backup with command %s', bCmd)
require('child_process').execSync(bCmd)
}
Server.prototype.prepareScriptFile = function (file) {
let scriptFile = path.join(__dirname, file)
var script = this.configuration.loadFile(scriptFile)
return this.prepareScript(script)
}
Server.prototype.prepareScript = function (script) {
let myIP = this.configuration.getMyIp()
let myPort = this.configuration.getValueWithDefault('web_http_port', 8182)
let myProt = (this.configuration.getValueWithDefault('use_https', false) === true) ? 'https' : 'http'
let myIfPort = this.configuration.getValueWithDefault('local_rpc_port', 7000)
if (script) {
script = script.replace(/myIP/gi, myIP)
script = script.replace(/myPort/, myPort)
script = script.replace(/myProt/, myProt)
script = script.replace(/myIfPort/, myIfPort)
}
return script
}
Server.prototype.handlePluginSettingsRequest = function (dispatched_request, plugin) {
var fields = (typeof plugin.platform.showSettings === 'function') ? plugin.platform.showSettings(dispatched_request) : []
var dplist = this.configuration.getValueForPluginWithDefault(plugin.name, 'dependencies', '')
fields.push({
'control': 'text',
'name': 'dependencies',
'label': this.localization.localize('Dependencies'),
'value': dplist || '',
'description': this.localization.localize('Plugins that need to launch befrore this. (, separated)')
})
if (dispatched_request.post !== undefined) {
var newSettings = {}
// var operation = dispatched_request.post['op']
fields.some(function (field) {
newSettings[field.name] = dispatched_request.post[field.name]
})
if (typeof plugin.platform.saveSettings === 'function') {
plugin.platform.saveSettings(newSettings)
}
dispatched_request.redirectTo('/')
return undefined
} else {
var settings_text_template = dispatched_request.getTemplate(null, 'settings_text.html', null)
var settings_option_template = dispatched_request.getTemplate(null, 'settings_option.html', null)
var result = ''
fields.some(function (field) {
switch (field.control) {
case 'text':
case 'password':
result = result + dispatched_request.fillTemplate(settings_text_template, {
'plugin.name': plugin.name,
'control.name': field.name,
'control.value': (field.value) ? field.value : '',
'control.label': field.label,
'control.description': (field.description) ? field.description : '',
'control.size': (field.size) ? field.size : '25',
'control.type': (field.control === 'password') ? 'password' : 'text'
})
break
case 'option':
result = result + dispatched_request.fillTemplate(settings_option_template, {
'plugin.name': plugin.name,
'control.name': field.name,
'control.value': (field.value) ? 'checked=\'checked\'' : '',
'control.label': field.label,
'control.description': (field.description) ? field.description : '',
'control.size': (field.size) ? field.size : '25'
})
break
}
})
}
return result
}
Server.prototype.pluginWithName = function (name) {
var result
this.configuratedPlugins.some(function (plugin) {
if (name === plugin.name) {
result = plugin
}
})
return result
}
Server.prototype.pluginWithType = function (type) {
var result
this.configuratedPlugins.some(function (plugin) {
if (type === plugin.pluginType) {
result = plugin
}
})
return result
}
Server.prototype.isPluginConfigured = function (type) {
var result = false
var configuredPlugins = this.configuration.getValue('plugins')
if ((configuredPlugins !== undefined) && (configuredPlugins instanceof Array)) {
configuredPlugins.forEach(function (pdef) {
if (pdef['type'] === type) {
result = true
}
})
}
return result
}
Server.prototype.hazDaemon = function () {
/* migrated to systemd */
if (process.platform === 'linux') {
// check enabled systemd services
let buff = require('child_process').execSync('systemctl list-unit-files | grep enabled')
let result = buff.toString("utf8")