-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
api.js
813 lines (703 loc) · 25.9 KB
/
api.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
/**
* ADT Pulse.
*
* A JavaScript library / Node module for ADT Pulse.
*
* @author Kevin Hickey <kevin@kevinmhickey.com>
* @author Jacky Liang
*
* @since 1.0.0
*/
const cheerio = require('cheerio');
const hasInternet = require('internet-available');
const Q = require('q');
const request = require('request');
const _ = require('lodash');
/**
* Browser session cookies.
*
* @since 1.0.0
*/
let jar;
/**
* Track login, login statuses, portal versions.
*
* @since 1.0.0
*/
let authenticated = false;
let lastKnownVersion = '';
let lastKnownSiteId = '';
/**
* ADT Pulse constructor.
*
* @param {object} options - The configuration.
*
* @constructor
*
* @since 1.0.0
*/
function Pulse(options) {
this.username = _.get(options, 'username', '');
this.password = _.get(options, 'password', '');
this.debug = _.get(options, 'debug', false);
}
/**
* ADT Pulse login.
*
* @returns {Q.Promise<object>}
*
* @since 1.0.0
*/
Pulse.prototype.login = function login() {
const deferred = Q.defer();
const that = this;
this.hasInternetWrapper(deferred, () => {
if (authenticated) {
deferred.resolve({
action: 'LOGIN',
success: true,
info: {
version: lastKnownVersion,
siteId: lastKnownSiteId,
},
});
} else {
this.consoleLogger('ADT Pulse: Logging in...', 'log');
// Request a new cookie session.
jar = request.jar();
request.get(
'https://portal.adtpulse.com',
this.generateRequestOptions(),
(error, response, body) => {
const regex = new RegExp(/(\/myhome\/)([0-9.-]+)(\/access\/signin\.jsp)/);
const responsePath = _.get(response, 'request.uri.path');
this.consoleLogger(`ADT Pulse: Response path -> ${responsePath}`, 'log');
this.consoleLogger(`ADT Pulse: Response path matches -> ${regex.test(responsePath)}`, 'log');
if (error || !regex.test(responsePath)) {
authenticated = false;
this.consoleLogger('ADT Pulse: Login failed.', 'error');
deferred.reject({
action: 'LOGIN',
success: false,
info: {
error,
message: this.getErrorMessage(body),
},
});
} else {
authenticated = false;
const version = responsePath.replace(regex, '$2');
// Saves last known version for reuse later.
lastKnownVersion = version;
this.consoleLogger(`ADT Pulse: Web portal version -> ${version}`, 'log');
request.post(
`https://portal.adtpulse.com/myhome/${lastKnownVersion}/access/signin.jsp`,
this.generateRequestOptions({
followAllRedirects: true,
headers: {
Referer: `https://portal.adtpulse.com/myhome/${lastKnownVersion}/access/signin.jsp`,
},
form: {
usernameForm: that.username,
passwordForm: that.password,
},
}),
(postError, postResponse, postBody) => {
const postRegex = new RegExp(/(\/myhome\/)([0-9.-]+)(\/summary\/summary\.jsp)/);
const postResponsePath = _.get(postResponse, 'request.uri.path');
this.consoleLogger(`ADT Pulse: Response path -> ${postResponsePath}`, 'log');
this.consoleLogger(`ADT Pulse: Response path matches -> ${postRegex.test(postResponsePath)}`, 'log');
if (postError || !postRegex.test(postResponsePath)) {
authenticated = false;
this.consoleLogger('ADT Pulse: Login failed.', 'error');
deferred.reject({
action: 'LOGIN',
success: false,
info: {
error: postError,
message: this.getErrorMessage(postBody),
},
});
} else {
authenticated = true;
const $ = cheerio.load(postBody);
const signoutLink = $('#p_signout1').attr('href');
const siteId = (signoutLink !== undefined) ? signoutLink.replace(/(.*)(networkid=)(.*)(&)(.*)/g, '$3') : undefined;
// Saves last known site ID for reuse later.
lastKnownSiteId = siteId;
this.consoleLogger(`ADT Pulse: Site ID -> ${siteId}`, 'log');
this.consoleLogger('ADT Pulse: Login success.', 'log');
deferred.resolve({
action: 'LOGIN',
success: true,
info: {
version: lastKnownVersion,
siteId: lastKnownSiteId,
},
});
}
},
);
}
},
);
}
});
return deferred.promise;
};
/**
* ADT Pulse logout.
*
* @returns {Q.Promise<object>}
*
* @since 1.0.0
*/
Pulse.prototype.logout = function logout() {
const deferred = Q.defer();
this.hasInternetWrapper(deferred, () => {
if (!authenticated) {
deferred.resolve({
action: 'LOGOUT',
success: true,
info: null,
});
} else {
this.consoleLogger('ADT Pulse: Logging out...', 'log');
request.get(
`https://portal.adtpulse.com/myhome/${lastKnownVersion}/access/signout.jsp?networkid=${lastKnownSiteId}&partner=adt`,
this.generateRequestOptions({
headers: {
Referer: `https://portal.adtpulse.com/myhome/${lastKnownVersion}/summary/summary.jsp`,
},
}),
(error, response, body) => {
const regex = new RegExp(/(\/myhome\/)([0-9.-]+)(\/access\/signin\.jsp)(.*)/);
const responsePath = _.get(response, 'request.uri.path');
this.consoleLogger(`ADT Pulse: Response path -> ${responsePath}`, 'log');
this.consoleLogger(`ADT Pulse: Response path matches -> ${regex.test(responsePath)}`, 'log');
if (error || !regex.test(responsePath)) {
authenticated = true;
this.consoleLogger('ADT Pulse: Logout failed.', 'error');
deferred.reject({
action: 'LOGOUT',
success: false,
info: {
error,
message: this.getErrorMessage(body),
},
});
} else {
authenticated = false;
this.consoleLogger('ADT Pulse: Logout success.', 'log');
deferred.resolve({
action: 'LOGOUT',
success: true,
info: null,
});
}
},
);
}
});
return deferred.promise;
};
/**
* ADT Pulse get device information.
*
* @returns {Q.Promise<object>}
*
* @since 1.0.0
*/
Pulse.prototype.getDeviceInformation = function getDeviceInformation() {
const deferred = Q.defer();
this.hasInternetWrapper(deferred, () => {
this.consoleLogger('ADT Pulse: Getting device information...', 'log');
request.get(
`https://portal.adtpulse.com/myhome/${lastKnownVersion}/system/device.jsp?id=1`,
this.generateRequestOptions({
headers: {
Referer: `https://portal.adtpulse.com/myhome/${lastKnownVersion}/system/system.jsp`,
},
}),
(error, response, body) => {
const regex = new RegExp(/(\/myhome\/)([0-9.-]+)(\/system\/device\.jsp)(.*)/);
const responsePath = _.get(response, 'request.uri.path');
this.consoleLogger(`ADT Pulse: Response path -> ${responsePath}`, 'log');
this.consoleLogger(`ADT Pulse: Response path matches -> ${regex.test(responsePath)}`, 'log');
if (error || !regex.test(responsePath)) {
authenticated = false;
this.consoleLogger('ADT Pulse: Get device information failed.', 'error');
deferred.reject({
action: 'GET_DEVICE_INFO',
success: false,
info: {
error,
message: this.getErrorMessage(body),
},
});
} else {
const $ = cheerio.load(body);
const deviceName = $('td.InputFieldDescriptionL:contains("Name")').next().text().trim();
const deviceMake = $('td.InputFieldDescriptionL:contains("Manufacturer")').next().text().trim();
const deviceType = $('td.InputFieldDescriptionL:contains("Type")').next().text().trim();
this.consoleLogger('ADT Pulse: Get device information success.', 'log');
deferred.resolve({
action: 'GET_DEVICE_INFO',
success: true,
info: {
name: deviceName,
make: deviceMake,
type: deviceType,
},
});
}
},
);
});
return deferred.promise;
};
/**
* ADT Pulse get device status.
*
* @returns {Q.Promise<object>}
*
* @since 1.0.0
*/
Pulse.prototype.getDeviceStatus = function getDeviceStatus() {
const deferred = Q.defer();
this.hasInternetWrapper(deferred, () => {
this.consoleLogger('ADT Pulse: Getting device status...', 'log');
request.get(
`https://portal.adtpulse.com/myhome/${lastKnownVersion}/ajax/orb.jsp`,
this.generateRequestOptions({
headers: {
Accept: '*/*',
Referer: `https://portal.adtpulse.com/myhome/${lastKnownVersion}/summary/summary.jsp`,
},
}),
(error, response, body) => {
const regex = new RegExp(/(\/myhome\/)([0-9.-]+)(\/ajax\/orb\.jsp)/);
const responsePath = _.get(response, 'request.uri.path');
this.consoleLogger(`ADT Pulse: Response path -> ${responsePath}`, 'log');
this.consoleLogger(`ADT Pulse: Response path matches -> ${regex.test(responsePath)}`, 'log');
if (error || !regex.test(responsePath) || body.indexOf('<html') > -1) {
authenticated = false;
this.consoleLogger('ADT Pulse: Get device status failed.', 'error');
deferred.reject({
action: 'GET_DEVICE_STATUS',
success: false,
info: {
error,
message: this.getErrorMessage(body),
},
});
} else {
const $ = cheerio.load(body);
const textSummary = $('#divOrbTextSummary span').text();
const theState = textSummary.replace(/([A-Z a-z ]+)(\.[ ]?)([A-Z a-z 0-9]*)(\.?)(.*)/g, '$1');
const theStatus = textSummary.replace(/([A-Z a-z ]+)(\.[ ]?)([A-Z a-z 0-9]*)(\.?)(.*)/g, '$3');
this.consoleLogger('ADT Pulse: Get device status success.', 'log');
/**
* These are the possible states and statuses.
*
* State:
* "Disarmed"
* "Armed Away"
* "Armed Stay"
* "Armed Night"
* "Status Unavailable"
* Status:
* "All Quiet"
* "1 Sensor Open" or "x Sensors Open"
* "Sensor Bypassed" or "Sensors Bypassed"
* "Sensor Tripped" or "Sensors Tripped"
* "Motion"
* "Uncleared Alarm"
* "Carbon Monoxide Alarm"
* "FIRE ALARM"
* "BURGLARY ALARM"
* "Sensor Problem"
* ""
*/
deferred.resolve({
action: 'GET_DEVICE_STATUS',
success: true,
info: {
summary: textSummary,
state: theState,
status: theStatus,
},
});
}
},
);
});
return deferred.promise;
};
/**
* ADT Pulse set device status.
*
* Notes:
* - When Disarming, armState will be set to "disarmed". It will be set to "off" after re-login.
* - When Arming Night, armState will be set to "night+stay". It will be set to "night" after re-login.
* - If alarm occurred, you must Clear Alarm before setting to Armed Away/Stay/Night.
*
* Disarmed:
* - Arm Away (https://portal.adtpulse.com/myhome/quickcontrol/armDisarm.jsp?href=rest/adt/ui/client/security/setArmState&armstate=disarmed&arm=away).
* - Arm Stay (https://portal.adtpulse.com/myhome/quickcontrol/armDisarm.jsp?href=rest/adt/ui/client/security/setArmState&armstate=disarmed&arm=stay).
* - Arm Night (https://portal.adtpulse.com/myhome/quickcontrol/armDisarm.jsp?href=rest/adt/ui/client/security/setArmState&armstate=disarmed&arm=night).
* - Disarm (https://portal.adtpulse.com/myhome/quickcontrol/armDisarm.jsp?href=rest/adt/ui/client/security/setArmState&armstate=disarmed&arm=off).
* - Clear Alarm (https://portal.adtpulse.com/myhome/quickcontrol/armDisarm.jsp?href=rest/adt/ui/client/security/setArmState&armstate=disarmed+with+alarm&arm=off).
* Armed Away:
* - Disarm (https://portal.adtpulse.com/myhome/quickcontrol/armDisarm.jsp?href=rest/adt/ui/client/security/setArmState&armstate=away&arm=off).
* Armed Stay:
* - Disarm (https://portal.adtpulse.com/myhome/quickcontrol/armDisarm.jsp?href=rest/adt/ui/client/security/setArmState&armstate=stay&arm=off).
* Armed Night:
* - Disarm (https://portal.adtpulse.com/myhome/quickcontrol/armDisarm.jsp?href=rest/adt/ui/client/security/setArmState&armstate=night&arm=off).
*
* @param {string} armState - Can be "disarmed", "disarmed+with+alarm", "away", "stay", or "night".
* @param {string} arm - Can be "off", "away", "stay", or "night".
*
* @returns {Q.Promise<object>}
*
* @since 1.0.0
*/
Pulse.prototype.setDeviceStatus = function setDeviceStatus(armState, arm) {
const deferred = Q.defer();
this.hasInternetWrapper(deferred, () => {
const url = `https://portal.adtpulse.com/myhome/${lastKnownVersion}/quickcontrol/armDisarm.jsp`;
const arg = `?href=rest/adt/ui/client/security/setArmState&armstate=${armState}&arm=${arm}`;
this.consoleLogger('ADT Pulse: Setting device status...', 'log');
request.get(
url + arg,
this.generateRequestOptions({
headers: {
Referer: `https://portal.adtpulse.com/myhome/${lastKnownVersion}/summary/summary.jsp`,
},
}),
(error, response, body) => {
const regex = new RegExp(/(\/myhome\/)([0-9.-]+)(\/quickcontrol\/armDisarm\.jsp)(.*)/);
const responsePath = _.get(response, 'request.uri.path');
this.consoleLogger(`ADT Pulse: Response path -> ${responsePath}`, 'log');
this.consoleLogger(`ADT Pulse: Response path matches -> ${regex.test(responsePath)}`, 'log');
if (error || !regex.test(responsePath)) {
authenticated = false;
this.consoleLogger(`ADT Pulse: Set device status to ${arm} failed.`, 'error');
deferred.reject({
action: 'SET_DEVICE_STATUS',
success: false,
info: {
error,
message: this.getErrorMessage(body),
},
});
} else {
const $ = cheerio.load(body);
const onClick = $('#arm_button_1').attr('onclick');
const satCode = (onClick !== undefined) ? onClick.replace(/(.*)(\?sat=)([0-9a-z-]*)(&href=)(.*)/g, '$3') : undefined;
const forceUrl = `https://portal.adtpulse.com/myhome/${lastKnownVersion}/quickcontrol/serv/RunRRACommand`;
const forceArg = `?sat=${satCode}&href=rest/adt/ui/client/security/setForceArm&armstate=forcearm&arm=${arm}`;
// Check if system requires force arming.
if (['away', 'stay', 'night'].includes(arm) && onClick !== undefined && satCode !== undefined) {
this.consoleLogger('ADT Pulse: Some sensors are open or reporting motion. Arming Anyway...', 'warn');
request.get(
forceUrl + forceArg,
this.generateRequestOptions({
headers: {
Accept: '*/*',
Referer: `https://portal.adtpulse.com/myhome/${lastKnownVersion}/quickcontrol/armDisarm.jsp`,
},
}),
(forceError, forceResponse, forceBody) => {
const forceRegex = new RegExp(/(\/myhome\/)([0-9.-]+)(\/quickcontrol\/serv\/RunRRACommand)(.*)/);
const forceResponsePath = _.get(forceResponse, 'request.uri.path');
this.consoleLogger(`ADT Pulse: Response path -> ${forceResponsePath}`, 'log');
this.consoleLogger(`ADT Pulse: Response path matches -> ${forceRegex.test(forceResponsePath)}`, 'log');
if (forceError || !forceRegex.test(forceResponsePath)) {
authenticated = false;
this.consoleLogger(`ADT Pulse: Set device status to ${arm} failed.`, 'error');
deferred.reject({
action: 'SET_DEVICE_STATUS',
success: false,
info: {
error: forceError,
message: this.getErrorMessage(forceBody),
},
});
} else {
this.consoleLogger(`ADT Pulse: Set device status to ${arm} success.`, 'log');
deferred.resolve({
action: 'SET_DEVICE_STATUS',
success: true,
info: {
forceArm: true,
previousArm: armState,
afterArm: arm,
},
});
}
},
);
} else {
this.consoleLogger(`ADT Pulse: Set device status to ${arm} success.`, 'log');
deferred.resolve({
action: 'SET_DEVICE_STATUS',
success: true,
info: {
forceArm: false,
previousArm: armState,
afterArm: arm,
},
});
}
}
},
);
});
return deferred.promise;
};
/**
* ADT Pulse get zone status.
*
* @returns {Q.Promise<object>}
*
* @since 1.0.0
*/
Pulse.prototype.getZoneStatus = function getZoneStatus() {
const deferred = Q.defer();
this.hasInternetWrapper(deferred, () => {
this.consoleLogger('ADT Pulse: Getting zone status...', 'log');
request.get(
`https://portal.adtpulse.com/myhome/${lastKnownVersion}/ajax/orb.jsp`,
this.generateRequestOptions({
headers: {
Accept: '*/*',
Referer: `https://portal.adtpulse.com/myhome/${lastKnownVersion}/summary/summary.jsp`,
},
}),
(error, response, body) => {
const regex = new RegExp(/(\/myhome\/)([0-9.-]+)(\/ajax\/orb\.jsp)/);
const responsePath = _.get(response, 'request.uri.path');
this.consoleLogger(`ADT Pulse: Response path -> ${responsePath}`, 'log');
this.consoleLogger(`ADT Pulse: Response path matches -> ${regex.test(responsePath)}`, 'log');
if (error || !regex.test(responsePath) || body.indexOf('<html') > -1) {
authenticated = false;
this.consoleLogger('ADT Pulse: Get zone status failed.', 'error');
deferred.reject({
action: 'GET_ZONE_STATUS',
success: false,
info: {
error,
message: this.getErrorMessage(body),
},
});
} else {
const $ = cheerio.load(body);
const sensors = $('#orbSensorsList table tr.p_listRow').toArray();
const output = _.map(sensors, (sensor) => {
const theSensor = cheerio.load(sensor);
const theName = theSensor('a.p_deviceNameText').html();
const theZone = theSensor('span.p_grayNormalText').html();
const theState = theSensor('span.devStatIcon canvas').attr('icon');
const theZoneNumber = (theZone) ? theZone.replace(/(Zone )([0-9]{1,2})/, '$2') : 0;
let theTag;
if (typeof theName === 'string' && theState !== 'devStatUnknown') {
const theNameLowercase = theName.toLowerCase();
if (theNameLowercase.match(/^(.*)(door|window|dr|win|slider|nook)(.*)$/g) !== null) {
theTag = 'sensor,doorWindow';
} else if (theNameLowercase.match(/^(.*)(glass)(.*)$/g) !== null) {
theTag = 'sensor,glass';
} else if (theNameLowercase.match(/^(.*)(motion)(.*)$/g) !== null) {
theTag = 'sensor,motion';
} else if (theNameLowercase.match(/^(.*)(gas)(.*)$/g) !== null) {
theTag = 'sensor,co';
} else if (theNameLowercase.match(/^(.*)(smoke|heat)(.*)$/g) !== null) {
theTag = 'sensor,fire';
}
}
/**
* Expected output.
*
* id: sensor-[integer]
* name: device name
* tags: sensor,[doorWindow,motion,glass,co,fire]
* state: devStatOK (device okay)
* devStatOpen (door/window opened)
* devStatMotion (detected motion)
* devStatTamper (glass broken or device tamper)
* devStatAlarm (detected CO/Smoke)
* devStatUnknown (device offline)
*/
return {
id: `sensor-${theZoneNumber}`,
name: theName || '',
tags: theTag || 'sensor',
state: theState || 'devStatUnknown',
};
});
this.consoleLogger('ADT Pulse: Get zone status success.', 'log');
deferred.resolve({
action: 'GET_ZONE_STATUS',
success: true,
info: output,
});
}
},
);
});
return deferred.promise;
};
/**
* ADT Pulse sync protocol.
*
* @returns {Q.Promise<object>}
*
* @since 1.0.0
*/
Pulse.prototype.performPortalSync = function performPortalSync() {
const deferred = Q.defer();
this.hasInternetWrapper(deferred, () => {
this.consoleLogger('ADT Pulse: Performing portal sync...', 'log');
request.get(
`https://portal.adtpulse.com/myhome/${lastKnownVersion}/Ajax/SyncCheckServ?t=${Date.now()}`,
this.generateRequestOptions({
headers: {
Accept: '*/*',
Referer: `https://portal.adtpulse.com/myhome/${lastKnownVersion}/summary/summary.jsp`,
},
}),
(error, response, body) => {
const regex = new RegExp(/(\/myhome\/)([0-9.-]+)(\/Ajax\/SyncCheckServ)(.*)/);
const responsePath = _.get(response, 'request.uri.path');
this.consoleLogger(`ADT Pulse: Response path -> ${responsePath}`, 'log');
this.consoleLogger(`ADT Pulse: Response path matches -> ${regex.test(responsePath)}`, 'log');
if (error || !regex.test(responsePath) || body.indexOf('<html') > -1) {
authenticated = false;
this.consoleLogger('ADT Pulse: Portal sync failed.', 'error');
deferred.reject({
action: 'SYNC',
success: false,
info: {
error,
message: this.getErrorMessage(body),
},
});
} else {
this.consoleLogger('ADT Pulse: Portal sync success.', 'log');
/**
* May return sync codes like this:
* 1-0-0
* 2-0-0
* [integer]-0-0
* [integer]-[integer]-0
*/
deferred.resolve({
action: 'SYNC',
success: true,
info: {
syncCode: body,
},
});
}
},
);
});
return deferred.promise;
};
/**
* Internet available wrapper.
*
* @param {Q.Deferred} deferred - Used for rejecting promises.
* @param {function} runFunction - Run function if internet is available.
*
* @since 1.0.0
*/
Pulse.prototype.hasInternetWrapper = function hasInternetWrapper(deferred, runFunction) {
const settings = {
timeout: 5000,
retries: 3,
domainName: 'portal.adtpulse.com',
port: 53,
};
hasInternet(settings).then(runFunction).catch(() => {
this.consoleLogger('ADT Pulse: Internet connection is offline or "https://portal.adtpulse.com" is unavailable.', 'error');
deferred.reject({
action: 'HOST_UNREACHABLE',
success: false,
info: null,
});
});
};
/**
* Request options generator.
*
* @param {object} additionalOptions - Additional options.
*
* @returns {object}
*
* @since 1.0.0
*/
Pulse.prototype.generateRequestOptions = function generateRequestOptions(additionalOptions = {}) {
const options = {
jar,
headers: {
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
Host: 'portal.adtpulse.com',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
},
ciphers: [
'ECDHE-RSA-AES256-GCM-SHA384',
'ECDHE-RSA-AES128-GCM-SHA256',
].join(':'),
};
// Merge additional options.
return _.merge(options, additionalOptions);
};
/**
* ADT Pulse get error message.
*
* @param {string} responseBody - The response body.
*
* @returns {(null|string)}
*
* @since 1.0.0
*/
Pulse.prototype.getErrorMessage = function getErrorMessage(responseBody) {
// Returns array or null.
let errorMessage = (responseBody) ? responseBody.match(/<div id="warnMsgContents" class="p_signinWarning">(.*?)<\/div>/g) : null;
// Returns string.
errorMessage = (errorMessage) ? errorMessage[0] : '';
// Replace single line break with space.
errorMessage = errorMessage.replace(/<br ?\/?>/ig, ' ');
// Remove all HTML code.
errorMessage = errorMessage.replace(/(<([^>]+)>)/ig, '');
// If empty message, return null.
return (errorMessage) || null;
};
/**
* ADT Pulse console logger.
*
* @param {string} content - The message or content being recorded into the logs.
* @param {string} type - Can be "error", "warn", or "log".
*
* @since 1.0.0
*/
Pulse.prototype.consoleLogger = function consoleLogger(content, type) {
const that = this;
if (that.debug) {
switch (type) {
case 'error':
console.error(content);
break;
case 'warn':
console.warn(content);
break;
case 'log':
console.log(content);
break;
default:
break;
}
}
};
module.exports = Pulse;