-
-
Notifications
You must be signed in to change notification settings - Fork 265
/
NVR.js
4067 lines (3315 loc) · 147 KB
/
NVR.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
/* jshint -W041 */
/* jshint esversion: 6 */
/* jslint browser: true*/
/* global cordova,StatusBar,angular,console, URI, moment, localforage, CryptoJS, Connection, LZString */
// This is my central data respository and common functions
// that many other controllers use
// It's grown over time. I guess I may have to split this into multiple services in the future
angular.module('zmApp.controllers')
.service('NVR', ['$ionicPlatform', '$http', '$q', '$ionicLoading', '$ionicBackdrop', '$fileLogger', 'zm', '$rootScope', '$ionicContentBanner', '$timeout', '$cordovaPinDialog', '$ionicPopup', '$localstorage', '$state', '$translate', '$cordovaSQLite',
function ($ionicPlatform, $http, $q, $ionicLoading, $ionicBackdrop, $fileLogger,
zm, $rootScope, $ionicContentBanner, $timeout, $cordovaPinDialog,
$ionicPopup, $localstorage, $state, $translate, $cordovaSQLite ) {
var currentServerMultiPortSupported = false;
var tokenExpiryTimer = null;
/*
DO NOT TOUCH zmAppVersion
It is changed by sync_version.sh
*/
var zmAppVersion = "1.7.000";
var isBackground = false;
var justResumed = false;
var timeSinceResumed = -1;
var monitorsLoaded = 0;
var snapshotFrame = 1; // will be 'snapshot'
// if ZM >= 1.31
var monitors = [];
var zmgroups = [];
var multiservers = [];
var migrationComplete = false;
$rootScope.initComplete = false; // will be true when init is fully done to take care of spurious state changes at times
var tz = "";
var isTzSupported = false;
var languages = [{
text: 'English',
value: 'en'
},
{
text: 'العربية',
value: 'ar'
},
{
text: 'Bosnian',
value: 'ba'
},
{
text: '简体中文',
value: 'zh_CN'
},
{
text: '正體中文',
value: 'zh_TW',
},
{
text: 'Deutsch',
value: 'de'
},
{
text: 'Español',
value: 'es'
},
{
text: 'Français',
value: 'fr'
},
{
text: 'Italiano',
value: 'it'
},
{
text: 'Magyar',
value: 'hu'
},
{
text: 'Nederlands',
value: 'nl'
},
{
text: 'Polski',
value: 'pl'
},
{
text: 'Portugese',
value: 'pt'
},
{
text: 'Русский',
value: 'ru'
},
{
text: 'Swedish',
value: 'se'
},
];
var serverGroupList = {};
var defaultLang = 'en';
var isFirstUse = true;
var lastUpdateCheck = null;
var latestBlogPostChecked = null;
var loginData = {
'serverName': '',
'username': '',
'password': '',
'fallbackConfiguration': '',
'url': '', // This is the ZM portal path
'apiurl': '', // This is the API path
'eventServer': '', //experimental Event server address
'maxMontage': "100", //total # of monitors to display in montage
'streamingurl': "",
'maxFPS': "3", // image streaming FPS
'montageQuality': "50", // montage streaming quality in %
'singleImageQuality': "100", // event single streaming quality in %
'monSingleImageQuality': "100", // live view quality
'montageHistoryQuality': "50",
'useSSL': false, // "1" if HTTPS --> not used #589
'keepAwake': true, // don't dim/dim during live view
'isUseAuth': true, // true if user wants ZM auth
'isUseBasicAuth': false,
'basicAuthUser': '',
'basicAuthPassword': '',
'isUseEventServer': false, // true if you configure the websocket event server
'disablePush': false, // true if only websocket mode is desired
'eventServerMonitors': '', // list of monitors to notify from ES
'eventServerInterval': '', // list of intervals for all monitors
'refreshSec': '2', // timer value for frame change in sec
'refreshSecLowBW': 8,
'singleliveFPS':'',
'montageliveFPS':'',
'enableLogs': true,
'enableDebug': true, // if enabled with log messages with "debug"
'usePin': false,
'pinCode': '',
'canSwipeMonitors': true,
'persistMontageOrder': false,
'onTapScreen': "",
'enableh264': true,
'gapless': false,
'montageOrder': '',
'montageHiddenOrder': '',
'montageArraySize': '0',
'showMontageSubMenu': false,
'graphSize': 500,
'enableAlarmCount': true,
'minAlarmCount': 1,
'montageSize': '3',
'useNphZms': true,
'useNphZmsForEvents': true,
'packMontage': false,
'exitOnSleep': false,
'forceNetworkStop': false,
'defaultPushSound': false,
'enableBlog': true,
'use24hr': false,
'packeryPositions': '',
'currentMontageProfile': '',
'packeryPositionsArray': {},
'timelineModalGraphType': 'all',
'resumeDelay': 0,
'language': 'en',
'reachability': true,
'forceImageModePath': false,
'vibrateOnPush': true,
'soundOnPush': true,
'cycleMonitors': false,
'cycleMontage': false,
'cycleMontageInterval': 10, // 10sec
'cycleMonitorsInterval': 10, // 10sec
'enableLowBandwidth': false,
'autoSwitchBandwidth': false,
'disableAlarmCheckMontage': false,
'useLocalTimeZone': true,
'fastLogin': true,
'followTimeLine': false,
'timelineScale': -1,
'hideArchived': false,
'videoPlaybackSpeed': 2,
'enableStrictSSL': false,
'enableSlowLoading': false,
'isFullScreen': false,
'reloadInMontage': false,
'momentGridSize': 40,
'momentMonitorFilter': [],
'enableMomentSubMenu': true,
'momentShowIcons':false,
'momentArrangeBy': 'StartTime',
'showLiveForInProgressEvents': true,
'disableSimulStreaming': false,
'insertBasicAuthToken': false,
'loginAPISupported': false,
'montageResizeSteps': 0.2,
'currentServerVersion': '',
'saveToCloud': true,
'montageReviewCollapse': true,
'objectDetectionFilter': false,
'enableEventRefresh': true,
'lastEventCheckTimes': {},
'enableMontageOverlays': true,
'showMontageSidebars': false,
'isTokenSupported': false,
'accessTokenExpires': '',
'refreshTokenExpires': '',
'accessToken': '',
'refreshToken': '',
'isKiosk': false,
'kioskPassword': '',
'useAPICaching': true,
'pauseStreams': false,
'zmNinjaCustomId':undefined, // filled in init. custom header
'obfuscationScheme': 'lzs', // or 'aes'
'showAnimation': true,
'montageHideFooter': false,
'httpCordovaNoEncode': false,
'currentZMGroupNames': [],
'unsupported': {},
'monitorSpecific': {},
'eventViewThumbs': 'snapshot',
'eventViewThumbsSize': 'small',
'currentZMState': 'unknown' ,
'retrieveFramesForEvents': true,
};
var defaultLoginData = angular.copy(loginData);
var configParams = {
'ZM_EVENT_IMAGE_DIGITS': '-1',
'ZM_PATH_ZMS': '',
'ZM_MIN_STREAMING_PORT': '-1'
};
/**
* Allows/Disallows self signed certs
*
* @returns
*/
function setCordovaHttpOptions() {
/*debug ("Cordova HTTP: Setting JSON serializer");
cordova.plugin.http.setDataSerializer('utf8');*/
if (loginData.isUseBasicAuth) {
debug("Cordova HTTP: configuring basic auth");
cordova.plugin.http.useBasicAuth(loginData.basicAuthUser, loginData.basicAuthPassword);
}
var cid = loginData.zmNinjaCustomId.replace('%APPVER%',zmAppVersion);
debug("Setting cordova header X-ZmNinja to "+cid);
// setup custom header
cordova.plugin.http.setHeader('*', 'X-ZmNinja', cid);
if (!loginData.enableStrictSSL) {
//alert("Enabling insecure SSL");
log(">>>> Disabling strict SSL checking (turn off in Dev Options if you can't connect)");
cordova.plugin.http.setServerTrustMode('nocheck', function () {
debug('--> SSL is permissive, will allow any certs. Use at your own risk.');
}, function () {
NVR.log('-->Error setting SSL permissive');
});
if ($rootScope.platformOS == 'android') {
log(">>> Android: enabling inline image view for self signed certs");
cordova.plugins.certificates.trustUnsecureCerts(true);
}
} else {
log(">>>> Enabling strict SSL checking (turn off in Dev Options if you can't connect)");
}
}
/**
* Checks if a complex object is empty
*
* @param {any} obj
* @returns
*/
function isEmpty(obj) {
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
function clear_unsupported() {
loginData.unsupported = {};
return setLogin(loginData);
}
function set_unsupported(p) {
loginData.unsupported[p] = true;
debug ('Setting '+p+' to unsupported');
setLogin(loginData);
}
function get_unsupported(p) {
return p ? loginData.unsupported[p] : loginData.unsupported;
}
function computeDeviceSize() {
var pixelRatio = window.devicePixelRatio || 1;
$rootScope.pixelRatio = pixelRatio;
$rootScope.devWidth = ((window.innerWidth > 0) ? window.innerWidth : screen.width);
$rootScope.devHeight = ((window.innerHeight > 0) ? window.innerHeight : screen.height);
$rootScope.devWidthIgnorePix = $rootScope.devWidth;
$rootScope.devHeightIgnorePix = $rootScope.devHeight;
//$rootScope.devWidth *= pixelRatio;
//$rootScope.devHeight *= pixelRatio;
$rootScope.videoHeight = $rootScope.devHeight - 20;
debug("resize/orient: " + $rootScope.devWidth + "(w) * " + $rootScope.devHeight+"(h)");
}
function getBandwidth() {
// if mode is not on always return high
if (loginData.enableLowBandwidth == false) {
return "highbw";
}
// if mode is force on, return low
if (loginData.enableLowBandwidth == true && loginData.autoSwitchBandwidth != true) {
return "lowbw";
}
if (loginData.enableLowBandwidth == true && loginData.autoSwitchBandwidth == true && $rootScope.platformOS == 'desktop') {
return "highbw";
}
// else return real state
switch (navigator.connection.type) {
case Connection.WIFI:
return "highbw";
case Connection.ETHERNET:
return "highbw";
default:
return "lowbw";
}
}
//--------------------------------------------------------------------------
// uses fileLogger to write logs to file for later investigation
//--------------------------------------------------------------------------
// separate out a debug so we don't do this if comparison for normal logs
function debug(val) {
if (loginData.enableDebug && loginData.enableLogs) {
if (val !== undefined) {
var regex1 = /"password":".*?"/g;
var regex2 = /&pass=.*?(?=["&]|$)/g;
var regex3 = /&token=([^&]*)/g;
var regex4 = /&auth=([^&]*)/g;
//console.log ("VAL IS " + val);
val = val.replace(regex1, "<password removed>");
val = val.replace(regex2, "<password removed>");
val = val.replace (regex3, "&token=<removed>");
val = val.replace (regex4, "&auth=<removed>");
}
$ionicPlatform.ready(function () {
$fileLogger.debug(val);
});
//console.log (val);
}
}
function object_to_query_string(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" +
encodeURIComponent(obj[p]));
var params = str.join("&");
return params;
}
// custom caching function as native http doesn't cache
function delete_cache(key) {
return localforage.removeItem(key);
}
function delete_all_caches() {
debug('CACHE: Clearing all unsupported flags');
debug('CACHE: Flushing all network API caches...');
return clear_unsupported()
.then ( function() {return localforage.removeItem('cached_monitors');})
.then ( function () {return localforage.removeItem('cached_api_version');})
.then ( function () {return localforage.removeItem('cached_multi_servers');})
.then ( function () {return localforage.removeItem('cached_multi_port');})
.then ( function () {return localforage.removeItem('cached_timezone');})
.then ( function () {return localforage.removeItem('cached_zmgroups');})
.catch ( function (err) {debug ('Error removing all caches: '+JSON.stringify(err)); return ('error');});
}
function cache_or_http(url,key,doCrypt, expiry) {
if (!loginData.useAPICaching) {
debug ('CACHE: Not being used, as it is disabled');
return $http.get(url);
}
// debug ('Inside cache_or_http with key:'+key+' crypt:'+doCrypt+' exp:'+expiry);
var d = $q.defer();
if (!expiry) expiry = 3600;
return localforage.getItem(key)
.then (function (cache_data) {
if (cache_data) {
debug('CACHE: found for key: '+key+' with expiry of:'+cache_data.expiry+'s');
data = cache_data.data;
t = moment(cache_data.time);
diff = moment().diff(t, 'seconds');
if (diff >=cache_data.expiry) {
debug('CACHE: cached value for key:'+key+' has expired as '+diff+' >='+cache_data.expiry);
return localforage.removeItem(key)
.then(function() {
return cache_or_http(url, key, doCrypt, expiry);
})
.catch (function(err) {
debug('CACHE: error deleting key, err:'+JSON.stringify(err)+' but still proceeding with another call to cache_or_http');
return cache_or_http(url, key, doCrypt, expiry);
});
} else {
debug ('CACHE: cached value for key:'+key+' is good as '+diff+' <'+cache_data.expiry);
}
//data = JSON.parse(data);
if (doCrypt) {
debug('CACHE: decryption requested');
data = decrypt(data);
return (data);
} else {
data = JSON.parse(data);
return (data);
}
} else {
debug('CACHE: NOT found for:'+key+ ' reverting to HTTP');
return $http.get(url)
.then ( function (data) {
debug ('HTTP function in cache returned:'+(typeof data));
cache_entry = {
'data': null,
'time': null,
'expiry': expiry
};
debug('CACHE: storing key data in cache now, with expiry of '+expiry);
if (doCrypt) {
debug('CACHE: encrypting request');
cache_entry.data = encrypt(data);
} else {
cache_entry.data = JSON.stringify(data);
}
cache_entry.time = moment().toString();
//debug ('CACHE: Setting key:'+key+' data value to:'+cache_entry.data);
return localforage.setItem(key, cache_entry)
.then (function() { return (data);});
})
.catch ( function(err) {
log('CACHE: error with http get '+JSON.stringify(err));
return (err);
});
} // end if cache data
})
.catch ( function (err) {
//debug ('cache_or_http error:'+JSON.stringify(err));
return (err);
//return $http.get(url);
}) ;
//debug ('returning promise');
//return d.promise;
}
function getZMState() {
var d = $q.defer();
var apiurl = loginData.apiurl+'/states.json?'+$rootScope.authSession;
$http.get(apiurl)
.then (function (data) {
data = data.data;
/*
{"states":[{"State":{"Id":"4","Name":"default","Definition":"2:Mocord:1,3:Mocord:1,4:Mocord:1,5:Monitor:0,6:Monitor:0,7:Modect:1,8:Modect:1","IsActive":"1"}},{"State":{"Id":"5","Name":"test","Definition":"2:None:1,3:None:1,4:None:1,5:Monitor:1,6:Monitor:1,7:Modect:1,8:Modect:1","IsActive":"0"}}]}
*/
var currentState = 'unknown';
for (var i=0; i < data.states.length; i++ ) {
if (data.states[i].State.IsActive == '1') {
currentState = data.states[i].State.Name;
break;
}
}
if (loginData.currentZMState != currentState) {
debug ('ZM State Change: ZM State changed from:'+loginData.currentZMState+' to:'+currentState+' resetting cache...');
delete_all_caches()
.then(function(data) {
loginData.currentZMState = currentState;
loginData.currentMontageProfile = '';
//loginData.packeryPositionsArray = {};
loginData.packeryPositions= undefined;
setLogin(loginData)
.then (function(v) {
d.resolve(data);
//$rootScope.$broadcast('zm-state-change');
proceedWithFreshLogin(true);
return d.promise;
});
});
} else {
debug ('ZM State has not changed, still at '+loginData.currentZMState);
setLogin(loginData)
.then (function (v) {
d.resolve(data);
return d.promise;
});
}
return d.promise;
}, function (err) {
debug('Error parsing State API:'+JSON.stringify(err));
d.resolve(err);
return d.promise;
});
return d.promise;
}
function getZMGroups() {
//{"groups":[{"Group":{"Id":"1","Name":"test","ParentId":null}},{"Group":{"Id":"2","Name":"test2","ParentId":null}}]}
var d = $q.defer();
zmgroups = [];
if (get_unsupported('groups_associations')) {
debug ('Groups Association API is marked as unsupported, not invoking');
d.resolve(true);
return d.promise;
}
var apiurl = loginData.apiurl+'/groups/associations.json?'+$rootScope.authSession;
for (var m=0; m < monitors.length; m++ ) {
if (!monitors[m].Monitor.Group) monitors[m].Monitor.Group=[];
}
cache_or_http(apiurl, 'cached_zmgroups')
.then (function (data) {
data = data.data;
// console.log (JSON.stringify(data));
//debug ('Groups are:'+JSON.stringify(data));
if (data && data.groups) {
zmgroups = [];
for (var i=0; i< data.groups.length; i++) {
zmgroups.push(data.groups[i].Group.Name);
//console.log( "Checking Group "+data.groups[i].Group.Name);
for (var j=0; j < data.groups[i].Monitor.length; j++) {
for (var k = 0; k < monitors.length; k++) {
// console.log(k);
if (monitors[k].Monitor.Id == data.groups[i].Monitor[j].Id) {
monitors[k].Monitor.Group.push({'id':data.groups[i].Group.Id, 'name':data.groups[i].Group.Name});
var parent = data.groups[i].Group.ParentId;
while (parent) {
var parentFound = false;
var x;
for (x = 0; x < data.groups.length; x++) {
if (data.groups[x].Group.Id == parent) {
parentFound = true;
break;
}
}
if (parentFound) {
monitors[k].Monitor.Group.push({'id':data.groups[x].Group.Id, 'name':data.groups[x].Group.Name});
// console.log (data.groups[x].Group.Id+ " is parent of "+data.groups[i].Group.Id);
parent = data.groups[x].Group.ParentId;
}
}
// console.log ('DONE HIERARCHY');
// console.log ('Monitor: '+ monitors[k].Monitor.Name+" belongs to Group:"+data.groups[i].Group.Name);
}
} // monitors
} // groups monitors
} // groups
d.resolve(true);
return (d.promise);
} else {
debug('No groups found');
d.resolve(true);
return (d.promise);
}
}, function (err) {
debug('Error retrieving groups:'+JSON.stringify(err));
set_unsupported('groups_associations');
d.resolve(true);
return (d.promise);
});
return (d.promise);
}
function getZmsMultiPortSupport(forceReload) {
var d = $q.defer();
if (configParams.ZM_MIN_STREAMING_PORT == -1 || forceReload) {
debug("Checking value of ZM_MIN_STREAMING_PORT for the first time");
var apiurl = loginData.apiurl;
var myurl = apiurl + '/configs/viewByName/ZM_MIN_STREAMING_PORT.json?' + $rootScope.authSession;
cache_or_http(myurl,'cached_multi_port', false, 3600*24)
.then(function (data) {
data = data.data;
//console.log ("GOT " + JSON.stringify(data));
if (data.config && data.config.Value) {
configParams.ZM_MIN_STREAMING_PORT = data.config.Value;
setCurrentServerMultiPortSupported(true);
debug("Got min streaming port value of: " + configParams.ZM_MIN_STREAMING_PORT);
} else {
setCurrentServerMultiPortSupported(false);
debug("ZM_MIN_STREAMING_PORT not configured, disabling");
configParams.ZM_MIN_STREAMING_PORT = 0;
}
d.resolve(configParams.ZM_MIN_STREAMING_PORT);
return (d.promise);
},
function (err) {
configParams.ZM_MIN_STREAMING_PORT = 0;
log("ZM_MIN_STREAMING_PORT not supported");
setCurrentServerMultiPortSupported(false);
d.resolve(configParams.ZM_MIN_STREAMING_PORT);
return (d.promise);
});
} else {
log("sending stored ZM_MIN_STREAMING_PORT " +
configParams.ZM_MIN_STREAMING_PORT);
d.resolve(configParams.ZM_MIN_STREAMING_PORT);
return (d.promise);
}
return (d.promise);
}
function proceedWithFreshLogin(noBroadcast) {
// recompute rand anyway so even if you don't have auth
// your stream should not get frozen
$rootScope.rand = Math.floor((Math.random() * 100000) + 1);
$rootScope.modalRand = Math.floor((Math.random() * 100000) + 1);
// console.log ("***** STATENAME IS " + statename);
var d = $q.defer();
log("Doing fresh login to ZM");
var httpDelay = loginData.enableSlowLoading ? zm.largeHttpTimeout : zm.httpTimeout;
str = "<a style='color:white; text-decoration:none' href='#' ng-click='$root.cancelAuth()' <i class='ion-close-circled'></i> " + $translate.instant('kAuthenticating')+"</a>";
$ionicLoading.show({
template: str,
noBackdrop: true,
duration: httpDelay
});
//first login using new API
$rootScope.authSession = '';
var loginAPI = loginData.apiurl + '/host/login.json';
$http({
method: 'post',
url: loginAPI,
timeout: httpDelay,
skipIntercept: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
responseType: 'text',
transformResponse: undefined,
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
user: loginData.username,
pass: loginData.password
}
})
//$http.get(loginAPI)
.then(function (textsucc) {
$ionicLoading.hide();
var succ;
try {
succ = JSON.parse(textsucc.data);
if (!succ.version) {
debug("API login returned fake success, going back to webscrape");
loginData.loginAPISupported = false;
setLogin(loginData);
loginWebScrape()
.then(function () {
d.resolve("Login Success");
return d.promise;
},
function () {
$ionicLoading.hide();
d.reject("Login Error");
return (d.promise);
});
return d.promise;
}
debug("API based login returned. ");
console.log(JSON.stringify(succ));
setCurrentServerVersion(succ.version);
$ionicLoading.hide();
//$rootScope.loggedIntoZm = 1;
//console.log ("***** CLEARING AUTHSESSION IN LINE 466");
$rootScope.authSession = '';
if (succ.refresh_token) {
$rootScope.authSession = '&token='+succ.access_token;
log ("New refresh token retrieved: ..."+succ.refresh_token.substr(-5));
loginData.isTokenSupported = true;
loginData.accessToken = succ.access_token;
loginData.accessTokenExpires = moment.utc().add(succ.access_token_expires, 'seconds');
loginData.refreshToken = succ.refresh_token;
$rootScope.tokenExpires = succ.access_token_expires;
log ('----> Setting token re-login after '+succ.access_token_expires+' seconds');
if (tokenExpiryTimer) $timeout.cancel(tokenExpiryTimer);
//succ.access_token_expires = 30;
tokenExpiryTimer = $timeout ( function () {
$rootScope.$broadcast('token-expiry');
}, succ.access_token_expires * 1000);
loginData.refreshTokenExpires = moment.utc().add(succ.refresh_token_expires, 'seconds');
log("Current time is: UTC "+moment.utc().format("YYYY-MM-DD hh:mm:ss"));
log("New refresh token expires on: UTC "+loginData.refreshTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
log("New access token expires on: UTC "+loginData.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
setLogin(loginData);
} else {
if (succ.credentials != undefined) {
if (succ.credentials != '') {
log("Could not recover token details, trying old auth credentials");
loginData.isTokenSupported = false;
setLogin(loginData);
$rootScope.authSession = "&" + succ.credentials;
if (succ.append_password == '1') {
$rootScope.authSession = $rootScope.authSession +
loginData.password;
}
} else {
// incase auth is turned off, but user said its on.
$rootScope.authSession="&nonauth=none";
debug('Your auth seems to be turned off, but you said yes');
}
} else {
log("Neither token nor old cred worked. Seems like an error");
}
} // end if succ.refresh_token
loginData.loginAPISupported = true;
setLogin(loginData);
log("Stream authentication construction: " +
$rootScope.authSession);
log("Successfully logged into Zoneminder via API");
d.resolve("Login Success");
if (!noBroadcast) $rootScope.$broadcast('auth-success', succ);
return d.promise;
} catch (e) {
debug("Login API approach did not work...");
loginData.loginAPISupported = false;
loginData.isTokenSupported = false;
setLogin(loginData);
loginWebScrape()
.then(function () {
d.resolve("Login Success");
return d.promise;
},
function (err) {
$ionicLoading.hide();
d.reject("Login Error");
return (d.promise);
});
return d.promise;
}
},
function (err) {
//console.log("******************* API login error " + JSON.stringify(err));
$ionicLoading.hide();
//if (err && err.data && 'success' in err.data) {
log("API based login not supported, need to use web scraping...");
// login using old web scraping
loginData.loginAPISupported = false;
setLogin(loginData);
loginWebScrape()
.then(function () {
d.resolve("Login Success");
return d.promise;
},
function (err) {
d.reject("Login Error");
return (d.promise);
});
}
); // post .then
return d.promise;
}
function loginWebScrape(noBroadcast) {
var d = $q.defer();
if ($rootScope.userCancelledAuth) {
debug('NVR loginWebScrape: User cancelled auth, not proceeding');
d.reject(true);
return d.promise;
}
debug("Logging in using old web-scrape method");
$ionicLoading.show({
template: "<a style='color:white; text-decoration:none' href='#' ng-click='$root.cancelAuth()' <i class='ion-close-circled'></i> " + $translate.instant('kAuthenticatingWebScrape')+"</a>",
noBackdrop: true,
duration: httpDelay
});
var httpDelay = loginData.enableSlowLoading ? zm.largeHttpTimeout : zm.httpTimeout;
//NVR.debug ("*** AUTH LOGIN URL IS " + loginData.url);
$http({
method: 'post',
timeout: httpDelay,
//withCredentials: true,
url: loginData.url + '/index.php?view=console',
skipIntercept:true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
},
transformRequest: function (obj) {
var str = [];
for (var p in obj) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
var params = str.join("&");
return params;
},
data: {
username: loginData.username,
password: loginData.password,
action: "login",
view: "console"
}
})
.then(function (data, status, headers) {
// console.log(">>>>>>>>>>>>>> PARALLEL POST SUCCESS");
data = data.data;
$ionicLoading.hide();
// Coming here does not mean success
// it could also be a bad login, but
// ZM returns you to login.php and returns 200 OK
// so we will check if the data has
// <title>ZM - Login</title> -- it it does then its the login page
if (data.indexOf(zm.loginScreenString1) >= 0) {
//eventServer.start();
//$rootScope.loggedIntoZm = 1;
log("zmAutologin successfully logged into Zoneminder");
$rootScope.apiValid = true;
// now go to authKey part, so don't return yet...
} else {
// this means login error
// $rootScope.loggedIntoZm = -1;
//console.log("**** ZM Login FAILED");
log("zmAutologin Error: Bad Credentials ", "error");
if (!noBroadcast) $rootScope.$broadcast('auth-error', "incorrect credentials");
d.reject("Login Error");
return (d.promise);
// no need to go to next code, so return above
}
// Now go ahead and re-get auth key
// if login was a success
// console.log ("***** CLEARING AUTHSESSION IN AUTHKEY");
$rootScope.authSession = '';
getAuthKey($rootScope.validMonitorId)
.then(function (success) {
//console.log(success);
//console.log ("***** SETTING AUTHSESSION IN AUTHKEY"+success);
$rootScope.authSession = success;
log("Stream authentication construction: " +
$rootScope.authSession);
d.resolve("Login Success");
$rootScope.$broadcast('auth-success', data);
return d.promise;
},
function (error) {
//console.log(error);
log("Modal: Error returned Stream authentication construction. Retaining old value of: " + $rootScope.authSession);
debug("Error was: " + JSON.stringify(error));
d.resolve("Login Success");
if (!noBroadcast) $rootScope.$broadcast('auth-success', data);
});
return (d.promise);
},
function (error, status) {
// console.log(">>>>>>>>>>>>>> PARALLEL POST ERROR");
$ionicLoading.hide();
//console.log("**** ZM Login FAILED");
// FIXME: Is this sometimes results in null
log("zmAutologin Error " + JSON.stringify(error) + " and status " + status);
// bad urls etc come here
//$rootScope.loggedIntoZm = -1;
if (!noBroadcast) $rootScope.$broadcast('auth-error', error);
d.reject("Login Error");
return d.promise;
});
return d.promise;
}
function getAuthKey(mid, ck) {
var d = $q.defer();
if (!loginData.isUseAuth) {
$rootScope.authSession = "";
d.resolve($rootScope.authSession);
return d.promise;
}
if ($rootScope.authSession != '' && $rootScope.authSession != 'undefined') {
log("We already have an auth key of:" + $rootScope.authSession);
d.resolve($rootScope.authSession);
return d.promise;
}
if (loginData.currentServerVersion &&
(versionCompare(loginData.currentServerVersion, zm.versionWithLoginAPI) != -1 || loginData.loginAPISupported)
) {
const myurl = loginData.apiurl + '/host/login.json';
debug("Server version " + loginData.currentServerVersion + " > 1.31.41, so using login API:" + myurl);
$http.get(myurl)
.then(function (s) {
debug("Credentials API returned: " + JSON.stringify(s));
if (!s.data || s.data.credentials == undefined) {
$rootScope.authSession = "";
d.resolve($rootScope.authSession);
debug("login() API Succeded, but did NOT return credentials key: " + JSON.stringify(s));
return d.promise;
} else {
if (s.data.credentials != '') {
$rootScope.authSession = "&" + s.data.credentials;
if (s.data.append_password == '1') {
$rootScope.authSession = $rootScope.authSession +
loginData.password;
}
} else {
// incase auth is turned off, but user said
// its on.
$rootScope.authSession="&nonauth=none";
debug ('Your auth seems to be turned off, but you said yes');
}
d.resolve($rootScope.authSession);
return d.promise;
}
},
function (e) {
//console.log ("***** CLEARING AUTHSESSION IN GETCREDENTIALS");
$rootScope.authSession = "";
d.resolve($rootScope.authSession);
debug("AuthHash API Error: " + JSON.stringify(e));