summaryrefslogtreecommitdiff
path: root/www
diff options
context:
space:
mode:
Diffstat (limited to 'www')
-rw-r--r--www/index.html2
-rw-r--r--www/js/BookmarkCtrl.js2
-rw-r--r--www/js/DevOptionsCtrl.js2
-rw-r--r--www/js/EventCtrl.js40
-rw-r--r--www/js/EventDateTimeFilterCtrl.js2
-rw-r--r--www/js/EventModalCtrl.js12
-rw-r--r--www/js/EventsGraphsCtrl.js2
-rw-r--r--www/js/FirstUseCtrl.js2
-rw-r--r--www/js/LogCtrl.js2
-rw-r--r--www/js/LoginCtrl.js109
-rw-r--r--www/js/MenuController.js20
-rw-r--r--www/js/MomentCtrl.js6
-rw-r--r--www/js/MonitorCtrl.js6
-rw-r--r--www/js/MonitorModalCtrl.js68
-rw-r--r--www/js/MontageCtrl.js26
-rw-r--r--www/js/MontageHistoryCtrl.js64
-rw-r--r--www/js/NVR.js1168
-rw-r--r--www/js/StateCtrl.js14
-rw-r--r--www/js/TimelineCtrl.js26
-rw-r--r--www/js/TimelineModalCtrl.js2
-rw-r--r--www/js/WizardCtrl.js17
-rwxr-xr-xwww/js/app.js544
-rw-r--r--www/templates/timeline.html1
23 files changed, 1156 insertions, 981 deletions
diff --git a/www/index.html b/www/index.html
index d7f0e9bf..e07749a0 100644
--- a/www/index.html
+++ b/www/index.html
@@ -147,7 +147,7 @@
window.ionic.Platform.ready(function () {
- console.log("******* PLATFORM READY ****");
+ // console.log("******* PLATFORM READY ****");
angular.bootstrap(document, ['zmApp']);
});
diff --git a/www/js/BookmarkCtrl.js b/www/js/BookmarkCtrl.js
index 57de1ccd..b36fae69 100644
--- a/www/js/BookmarkCtrl.js
+++ b/www/js/BookmarkCtrl.js
@@ -95,7 +95,7 @@ angular.module('zmApp.controllers').controller('zmApp.BookmarkCtrl', ['$scope',
disableAnimate: true,
expire: 300
});
- console.log("GOIN WITH " + JSON.stringify(item.params));
+ //console.log("GOIN WITH " + JSON.stringify(item.params));
$state.go(item.state, item.params);
};
diff --git a/www/js/DevOptionsCtrl.js b/www/js/DevOptionsCtrl.js
index 57aceff4..55aa0e5b 100644
--- a/www/js/DevOptionsCtrl.js
+++ b/www/js/DevOptionsCtrl.js
@@ -63,7 +63,7 @@ angular.module('zmApp.controllers').controller('zmApp.DevOptionsCtrl', ['$scope'
//console.log("**VIEW ** DevOptions Ctrl Entered");
$scope.loginData = NVR.getLogin();
- console.log("DEV LOGS=" + $scope.loginData.enableLogs);
+ //console.log("DEV LOGS=" + $scope.loginData.enableLogs);
$scope.isMultiPort = false;
diff --git a/www/js/EventCtrl.js b/www/js/EventCtrl.js
index e06309aa..c1311ebd 100644
--- a/www/js/EventCtrl.js
+++ b/www/js/EventCtrl.js
@@ -317,7 +317,7 @@ angular.module('zmApp.controllers')
function getEventObject(eid) {
- var apiurl = NVR.getLogin().apiurl + '/events/' + eid + '.json';
+ var apiurl = NVR.getLogin().apiurl + '/events/' + eid + '.json?'+$rootScope.authSession;
$http.get(apiurl)
.then(function (data) {},
@@ -456,7 +456,7 @@ angular.module('zmApp.controllers')
pageLoaded = true;
//$scope.viewTitle.title = data.pagination.count;
- console.log(JSON.stringify(data.pagination));
+ // console.log(JSON.stringify(data.pagination));
if (data.pagination && data.pagination.pageCount)
maxEventsPage = data.pagination.pageCount;
@@ -919,7 +919,7 @@ angular.module('zmApp.controllers')
function onError(error) {
$ionicLoading.hide();
- console.log("Error: " + error);
+ NVR.debug("Error: " + error);
}
}
@@ -1222,7 +1222,7 @@ angular.module('zmApp.controllers')
function prepareImages(e) {
var d = $q.defer();
var imglist = [];
- var myurl = loginData.apiurl + '/events/' + e.Event.Id + ".json";
+ var myurl = loginData.apiurl + '/events/' + e.Event.Id + ".json?"+$rootScope.authSession;
$http.get(myurl)
.then(function (succ) {
var data = succ.data;
@@ -1656,7 +1656,7 @@ angular.module('zmApp.controllers')
NVR.debug("Archiving request for EID=" + eid);
var loginData = NVR.getLogin();
- var apiArchive = loginData.apiurl + "/events/" + eid + ".json";
+ var apiArchive = loginData.apiurl + "/events/" + eid + ".json?"+$rootScope.authSession;
var setArchiveBit = ($scope.events[ndx].Event.Archived == '0') ? "1" : "0";
NVR.debug("Calling archive with:" + apiArchive + " and Archive=" + setArchiveBit);
@@ -1743,7 +1743,7 @@ angular.module('zmApp.controllers')
//$scope.eventList.showDelete = false;
//curl -XDELETE http://server/zm/api/events/1.json
var loginData = NVR.getLogin();
- var apiDelete = loginData.apiurl + "/events/" + id + ".json";
+ var apiDelete = loginData.apiurl + "/events/" + id + ".json?"+$rootScope.authSession;
NVR.debug("DeleteEvent: ID=" + id + " item=" + itemid);
NVR.log("Delete event " + apiDelete);
@@ -1877,18 +1877,18 @@ angular.module('zmApp.controllers')
var af = "/AlarmFrames >=:" + (ld.enableAlarmCount ? ld.minAlarmCount : 0);
if (ld.objectDetectionFilter) {
- af = af + '/Notes REGEXP:"detected:"';
+ af = af + '/Notes REGEXP:detected:';
}
- var apiurl = ld.apiurl + "/events/consoleEvents/1 hour" + af + ".json";
+ var apiurl = ld.apiurl + "/events/consoleEvents/1 hour" + af + ".json?"+$rootScope.authSession;
//NVR.debug("consoleEvents API:" + apiurl);
$http.get(apiurl)
.then(function (data) {
data = data.data;
- // NVR.debug(JSON.stringify(data));
+ // NVR.debug(JSON.stringify(data));
$scope.hours = [];
var p = data.results;
for (var key in data.results) {
@@ -1919,7 +1919,7 @@ angular.module('zmApp.controllers')
}
});
- apiurl = ld.apiurl + "/events/consoleEvents/1 day" + af + ".json";
+ apiurl = ld.apiurl + "/events/consoleEvents/1 day" + af + ".json?"+$rootScope.authSession;
//NVR.debug("consoleEvents API:" + apiurl);
$http.get(apiurl)
.then(function (data) {
@@ -1952,7 +1952,7 @@ angular.module('zmApp.controllers')
}
});
- apiurl = ld.apiurl + "/events/consoleEvents/1 week" + af + ".json";
+ apiurl = ld.apiurl + "/events/consoleEvents/1 week" + af + ".json?"+$rootScope.authSession;
//NVR.debug("consoleEvents API:" + apiurl);
$http.get(apiurl)
.then(function (data) {
@@ -1986,7 +1986,7 @@ angular.module('zmApp.controllers')
}
});
- apiurl = ld.apiurl + "/events/consoleEvents/1 month" + af + ".json";
+ apiurl = ld.apiurl + "/events/consoleEvents/1 month" + af + ".json?"+$rootScope.authSession;
//NVR.debug("consoleEvents API:" + apiurl);
$http.get(apiurl)
.then(function (data) {
@@ -2163,7 +2163,7 @@ angular.module('zmApp.controllers')
$scope.alarm_images = [];
event.Event.height = (eventsListDetailsHeight + eventsListScrubHeight);
$ionicScrollDelegate.resize();
- var myurl = loginData.apiurl + '/events/' + event.Event.Id + ".json";
+ var myurl = loginData.apiurl + '/events/' + event.Event.Id + ".json?"+$rootScope.authSession;
NVR.log("API for event details" + myurl);
$http.get(myurl)
.then(function (data) {
@@ -2274,7 +2274,7 @@ angular.module('zmApp.controllers')
var i;
- var myurl_frames = loginData.apiurl + '/events/' + event.Event.Id + ".json";
+ var myurl_frames = loginData.apiurl + '/events/' + event.Event.Id + ".json?"+$rootScope.authSession;
NVR.log("API for event details" + myurl_frames);
$http.get(myurl_frames)
.then(function (data) {
@@ -2320,7 +2320,7 @@ angular.module('zmApp.controllers')
videoURL += NVR.insertBasicAuthToken();
- console.log("************** VIDEO IS " + videoURL);
+ // console.log("************** VIDEO IS " + videoURL);
event.Event.video.config = {
autoPlay: true,
sources: [{
@@ -2334,7 +2334,7 @@ angular.module('zmApp.controllers')
};
- var myurl2 = loginData.apiurl + '/events/' + event.Event.Id + ".json";
+ var myurl2 = loginData.apiurl + '/events/' + event.Event.Id + ".json?"+$rootScope.authSession;
NVR.log("API for event details" + myurl2);
$http.get(myurl2)
.then(function (data) {
@@ -2751,13 +2751,13 @@ angular.module('zmApp.controllers')
// the events API does not return an error for anything
// except greater page limits than reported
- console.log("***** LOADING MORE INFINITE SCROLL ****");
+ //console.log("***** LOADING MORE INFINITE SCROLL ****");
if ((currEventsPage >= maxEventsPage) && (pageLoaded)) {
moreEvents = false;
NVR.debug("No more - We have a total of " + maxEventsPage + " and are at page=" + currEventsPage);
- console.log("*** At Page " + currEventsPage + " of " + maxEventsPage + ", not proceeding");
+ // console.log("*** At Page " + currEventsPage + " of " + maxEventsPage + ", not proceeding");
$ionicLoading.hide();
return;
}
@@ -2776,7 +2776,7 @@ angular.module('zmApp.controllers')
if ($scope.search.text != "") {
var toastStr = $translate.instant('kPleaseWait') +'...'+ currEventsPage;
- console.log ("SHOW " + toastStr );
+ // console.log ("SHOW " + toastStr );
$ionicLoading.show({
maxwidth: 100,
noBackdrop:true,
@@ -3017,7 +3017,7 @@ angular.module('zmApp.controllers')
var ld = NVR.getLogin();
- console.log("Toggling " + ld.enableAlarmCount);
+ // console.log("Toggling " + ld.enableAlarmCount);
ld.enableAlarmCount = !ld.enableAlarmCount;
NVR.setLogin(ld);
$scope.loginData = NVR.getLogin();
diff --git a/www/js/EventDateTimeFilterCtrl.js b/www/js/EventDateTimeFilterCtrl.js
index 51ebe91f..0e5f9988 100644
--- a/www/js/EventDateTimeFilterCtrl.js
+++ b/www/js/EventDateTimeFilterCtrl.js
@@ -124,7 +124,7 @@ angular.module('zmApp.controllers')
disableBack: true
});
- console.log (" >>>>>>>> BACK VIEW = "+$ionicHistory.backTitle());
+ //console.log (" >>>>>>>> BACK VIEW = "+$ionicHistory.backTitle());
if ($ionicHistory.backTitle() == 'Timeline') {
$ionicHistory.nextViewOptions({
diff --git a/www/js/EventModalCtrl.js b/www/js/EventModalCtrl.js
index 096fc52f..eb7e5524 100644
--- a/www/js/EventModalCtrl.js
+++ b/www/js/EventModalCtrl.js
@@ -591,7 +591,7 @@ angular.module('zmApp.controllers').controller('EventModalCtrl', ['$scope', '$ro
// console.log ("STEP 0 progress is " + $scope.currentProgress.progress);
$scope.slides = [];
- var apiurl = $scope.loginData.apiurl + "/events/" + $scope.eventId + ".json";
+ var apiurl = $scope.loginData.apiurl + "/events/" + $scope.eventId + ".json?"+$rootScope.authSession;
NVR.debug("prepared to get frame details using " + apiurl);
$http.get(apiurl)
.then(function (success) {
@@ -1392,20 +1392,18 @@ angular.module('zmApp.controllers').controller('EventModalCtrl', ['$scope', '$ro
var d = $q.defer();
// now get event details to show alarm frames
var loginData = NVR.getLogin();
- var myurl = loginData.apiurl + '/events/' + eid + ".json";
-
var nextEvent = loginData.apiurl + "/events/index" +
"/StartTime >: " + currentEvent.Event.StartTime +
($scope.followSameMonitor == '1' ? "/MonitorId =: " + currentEvent.Monitor.Id : "") +
"/AlarmFrames >=: " + (loginData.enableAlarmCount ? loginData.minAlarmCount : 0) +
- ".json?sort=StartTime&direction=asc&limit=1";
+ ".json?sort=StartTime&direction=asc&limit=1"+$rootScope.authSession;
var prevEvent = loginData.apiurl + "/events/index" +
"/StartTime <: " + currentEvent.Event.StartTime +
($scope.followSameMonitor == '1' ? "/MonitorId =: " + currentEvent.Monitor.Id : "") +
"/AlarmFrames >=: " + (loginData.enableAlarmCount ? loginData.minAlarmCount : 0) +
- ".json?sort=StartTime&direction=desc&limit=1";
+ ".json?sort=StartTime&direction=desc&limit=1"+$rootScope.authSession;
NVR.debug("Neighbor next URL=" + nextEvent);
@@ -1485,7 +1483,7 @@ angular.module('zmApp.controllers').controller('EventModalCtrl', ['$scope', '$ro
//$scope.eventList.showDelete = false;
//curl -XDELETE http://server/zm/api/events/1.json
var loginData = NVR.getLogin();
- var apiDelete = loginData.apiurl + "/events/" + id + ".json";
+ var apiDelete = loginData.apiurl + "/events/" + id + ".json?"+$rootScope.authSession;
NVR.debug("DeleteEvent: ID=" + id);
NVR.log("Delete event " + apiDelete);
@@ -1949,7 +1947,7 @@ angular.module('zmApp.controllers').controller('EventModalCtrl', ['$scope', '$ro
// Lets get the detailed event API
var loginData = NVR.getLogin();
- var myurl = loginData.apiurl + '/events/' + eid + ".json";
+ var myurl = loginData.apiurl + '/events/' + eid + ".json?"+$rootScope.authSession;
NVR.log("*** Constructed API for detailed events: " + myurl);
$scope.humanizeTime = "...";
$scope.mName = "...";
diff --git a/www/js/EventsGraphsCtrl.js b/www/js/EventsGraphsCtrl.js
index f870f029..dd8fe279 100644
--- a/www/js/EventsGraphsCtrl.js
+++ b/www/js/EventsGraphsCtrl.js
@@ -186,7 +186,7 @@ angular.module('zmApp.controllers').controller('zmApp.EventsGraphsCtrl', ['$ioni
}
var url = loginData.apiurl +
"/events/index/MonitorId:" + monitors[j].Monitor.Id + dateString +
- ".json?page=1";
+ ".json?page=1"+$rootScope.authSession;
// console.log("Monitor event URL:" + url);
NVR.log("EventGraph: composed url is " + url);
$http.get(url /*,{timeout:15000}*/ )
diff --git a/www/js/FirstUseCtrl.js b/www/js/FirstUseCtrl.js
index 02d7c177..c6f55ef4 100644
--- a/www/js/FirstUseCtrl.js
+++ b/www/js/FirstUseCtrl.js
@@ -21,7 +21,7 @@ angular.module('zmApp.controllers').controller('zmApp.FirstUseCtrl', ['$scope',
cordova.plugin.http.setSSLCertMode('nocheck', function () {
NVR.debug('--> First use -> SSL is permissive, will allow any certs for now. You can change it later.');
}, function () {
- console.log('-->First Use -> Error setting SSL permissive');
+ NVR.log('-->First Use -> Error setting SSL permissive');
});
if ($rootScope.platformOS == 'android') {
diff --git a/www/js/LogCtrl.js b/www/js/LogCtrl.js
index 19203d43..d2b30e3e 100644
--- a/www/js/LogCtrl.js
+++ b/www/js/LogCtrl.js
@@ -146,7 +146,7 @@ angular.module('zmApp.controllers').controller('zmApp.LogCtrl', ['$scope', '$roo
function loadZMlogs() {
var ld = NVR.getLogin();
- var lapi = ld.apiurl + "/logs.json?sort=TimeKey&direction=desc&page=" + $scope.zmPage;
+ var lapi = ld.apiurl + "/logs.json?sort=TimeKey&direction=desc&page=" + $scope.zmPage+$rootScope.authSession;
$http.get(lapi)
.then(function (success) {
$ionicLoading.hide();
diff --git a/www/js/LoginCtrl.js b/www/js/LoginCtrl.js
index 36eac47d..9e369f02 100644
--- a/www/js/LoginCtrl.js
+++ b/www/js/LoginCtrl.js
@@ -610,9 +610,8 @@ function mobilePinConfig () {
// don't do it for WSS - lets mandate that
}*/
- var apiurl = $scope.loginData.apiurl + '/host/getVersion.json';
- var portalurl = $scope.loginData.url + '/index.php';
-
+ var apiurl = $scope.loginData.apiurl + '/host/getVersion.json?'+$rootScope.authSession;
+
// Check if isUseAuth is set make sure u/p have a dummy value
if ($scope.loginData.isUseAuth) {
if (!$scope.loginData.username) $scope.loginData.username = "x";
@@ -654,6 +653,7 @@ function mobilePinConfig () {
$rootScope.authSession = '';
+ //console.log ("***** CLEARING AUTHSESSION IN SAVEITEMS");
if ($rootScope.platformOS != 'desktop') {
@@ -669,7 +669,7 @@ function mobilePinConfig () {
cordova.plugin.http.setSSLCertMode('nocheck', function () {
NVR.debug('--> SSL is permissive, will allow any certs. Use at your own risk.');
}, function () {
- console.log('-->Error setting SSL permissive');
+ NVR.log('-->Error setting SSL permissive');
});
if ($rootScope.platformOS == 'android') {
@@ -769,7 +769,7 @@ function mobilePinConfig () {
if ($scope.loginData.serverName != NVR.getLogin().serverName) {
NVR.debug(">>> Server information has changed, likely a fallback took over!");
$scope.loginData = NVR.getLogin();
- apiurl = $scope.loginData.apiurl + '/host/getVersion.json';
+ apiurl = $scope.loginData.apiurl + '/host/getVersion.json?'+$rootScope.authSession;
portalurl = $scope.loginData.url + '/index.php';
}
@@ -785,85 +785,32 @@ function mobilePinConfig () {
var loginStatus = $translate.instant('kExploreEnjoy') + " " + $rootScope.appName + "!";
EventServer.refresh();
- // now grab and report PATH_ZMS
- NVR.getPathZms()
+ NVR.debug("refreshing API version...");
+ NVR.getAPIversion()
.then(function (data) {
- var ld = NVR.getLogin();
- var zm_cgi = data.toLowerCase();
-
- var user_cgi = (ld.streamingurl).toLowerCase();
- NVR.log("ZM relative cgi-path: " + zm_cgi + ", you entered: " + user_cgi);
-
- $http.get(ld.streamingurl + "/zms")
- .then(function (data) {
- data = data.data;
- NVR.debug("Urk! cgi-path returned success, but it should not have come here");
- loginStatus = $translate.instant('kLoginStatusNoCgi');
-
- NVR.debug("refreshing API version...");
- NVR.getAPIversion()
- .then(function (data) {
- var refresh = NVR.getMonitors(1);
- $rootScope.apiVersion = data;
- },
- function (error) {
- var refresh = NVR.getMonitors(1);
- $rootScope.apiVersion = "0.0.0";
- NVR.debug("Error, failed API version, setting to " + $rootScope.apiVersion);
- });
-
- if (showalert) {
- $rootScope.zmPopup = SecuredPopups.show('alert', {
- title: $translate.instant('kLoginValidatedTitle'),
- template: loginStatus,
- okText: $translate.instant('kButtonOk'),
- cancelText: $translate.instant('kButtonCancel'),
- }).then(function (res) {
-
- $ionicSideMenuDelegate.toggleLeft();
- NVR.debug("Force reloading monitors...");
-
- });
- }
- },
- function (error, status) {
- // If its 5xx, then the cgi-bin path is valid
- // if its 4xx then the cgi-bin path is not valid
-
- if (status < 500) {
- loginStatus = $translate.instant('kLoginStatusNoCgiAlt');
- }
-
- if (showalert) {
- $rootScope.zmPopup = SecuredPopups.show('alert', {
- title: $translate.instant('kLoginValidatedTitle'),
- template: loginStatus,
- okText: $translate.instant('kButtonOk'),
- cancelText: $translate.instant('kButtonCancel'),
- }).then(function (res) {
-
- $ionicSideMenuDelegate.toggleLeft();
- NVR.debug("Force reloading monitors...");
-
- });
- } else // make sure CGI error is always shown
- {
- NVR.displayBanner((status < 500) ? 'error' : 'info', [loginStatus]);
- }
- NVR.debug("refreshing API version...");
- NVR.getAPIversion()
- .then(function (data) {
- var refresh = NVR.getMonitors(1);
- $rootScope.apiVersion = data;
- },
- function (error) {
- var refresh = NVR.getMonitors(1);
- $rootScope.apiVersion = "0.0.0";
- NVR.debug("Error, failed API version, setting to " + $rootScope.apiVersion);
- });
+ var refresh = NVR.getMonitors(1);
+ $rootScope.apiVersion = data;
+ // console.log ("ALERT="+showalert);
+ if (showalert) {
+ $rootScope.zmPopup = SecuredPopups.show('alert', {
+ title: $translate.instant('kLoginValidatedTitle'),
+ template: loginStatus,
+ okText: $translate.instant('kButtonOk'),
+ cancelText: $translate.instant('kButtonCancel'),
+ }).then(function (res) {
+
+ $ionicSideMenuDelegate.toggleLeft();
+ NVR.debug("Force reloading monitors...");
});
- });
+ }
+
+ },
+ function (error) {
+ var refresh = NVR.getMonitors(1);
+ $rootScope.apiVersion = "0.0.0";
+ NVR.debug("Error, failed API version, setting to " + $rootScope.apiVersion);
+ });
},
function (error) {
diff --git a/www/js/MenuController.js b/www/js/MenuController.js
index a7e2e640..e81e9e82 100644
--- a/www/js/MenuController.js
+++ b/www/js/MenuController.js
@@ -50,7 +50,7 @@ angular.module('zmApp.controllers').controller('MenuController', ['$scope', '$io
$rootScope.alarmCount = 0;
$rootScope.isAlarm = false;
$rootScope.authSession = '';
-
+ //console.log ("******************* AUTHSESSION RESET!!!!!!");
@@ -99,7 +99,7 @@ angular.module('zmApp.controllers').controller('MenuController', ['$scope', '$io
cordova.plugin.http.setSSLCertMode('nocheck', function () {
NVR.debug('--> SSL is permissive, will allow any certs. Use at your own risk.');
}, function () {
- console.log('-->Error setting SSL permissive');
+ NVR.log('-->Error setting SSL permissive');
});
if ($rootScope.platformOS == 'android') {
@@ -134,7 +134,8 @@ angular.module('zmApp.controllers').controller('MenuController', ['$scope', '$io
}
- var apiurl = loginData.apiurl + '/host/getVersion.json';
+
+
//var portalurl = loginData.url + '/index.php';
zmAutoLogin.doLogin("<button class='button button-clear' style='line-height: normal; min-height: 0; min-width: 0; color:#fff;' ng-click='$root.cancelAuth()'><i class='ion-close-circled'></i>&nbsp;" + $translate.instant('kAuthenticating') + "...</button>")
@@ -149,6 +150,11 @@ angular.module('zmApp.controllers').controller('MenuController', ['$scope', '$io
// possible image digits changed between servers
NVR.getKeyConfigParams(0);
$rootScope.runMode = NVR.getBandwidth();
+ //console.log ("HERE");
+ var apiurl = loginData.apiurl + '/host/getVersion.json?'+$rootScope.authSession;
+
+ //console.log ("****** MENU CONTROLLER:"+apiurl);
+
NVR.log("Validating APIs at " + apiurl);
$http.get(apiurl)
.then(function (data) {
@@ -185,7 +191,7 @@ angular.module('zmApp.controllers').controller('MenuController', ['$scope', '$io
disableBack: true
});
- console.log("+++ state go after getMonitors force");
+ //console.log("+++ state go after getMonitors force");
$state.go('app.refresh', {
"view": $state.current.name
});
@@ -197,7 +203,7 @@ angular.module('zmApp.controllers').controller('MenuController', ['$scope', '$io
function (error) {
var refresh = NVR.getMonitors(1)
.then(function () {
- console.log("+++ state go after API version error: " + error);
+ //console.log("+++ state go after API version error: " + error);
$rootScope.apiVersion = "0.0.0";
NVR.debug("Error, failed API version, setting to " + $rootScope.apiVersion);
@@ -238,7 +244,7 @@ angular.module('zmApp.controllers').controller('MenuController', ['$scope', '$io
disableBack: true
});
- console.log("+++ state go after 5xx");
+ //console.log("+++ state go after 5xx");
$state.go('app.refresh', {
"view": $state.current.name
});
@@ -254,7 +260,7 @@ angular.module('zmApp.controllers').controller('MenuController', ['$scope', '$io
$ionicHistory.nextViewOptions({
disableBack: true
});
- console.log("+++ state go after API version force");
+ //console.log("+++ state go after API version force");
$state.go('app.refresh', {
"view": $state.current.name
});
diff --git a/www/js/MomentCtrl.js b/www/js/MomentCtrl.js
index b749837a..79454c33 100644
--- a/www/js/MomentCtrl.js
+++ b/www/js/MomentCtrl.js
@@ -324,7 +324,7 @@ angular.module('zmApp.controllers').controller('zmApp.MomentCtrl', ['$scope', '$
var ld = NVR.getLogin();
ld.montageReviewCollapse = $scope.expand;
- console.log(">>>>>>>>> SAVING EXPAND AS:" + $scope.expand);
+ // console.log(">>>>>>>>> SAVING EXPAND AS:" + $scope.expand);
NVR.setLogin(ld);
};
@@ -749,7 +749,7 @@ angular.module('zmApp.controllers').controller('zmApp.MomentCtrl', ['$scope', '$
var ld = NVR.getLogin();
// in API, always sort by StartTime so all monitors are represented
- var myurl = ld.apiurl + "/events/index/AlarmFrames >=:1" + excludeMonitorsFilter + "/StartTime >=:" + timeFrom + "/StartTime <=:" + timeTo + ".json?sort=" + "StartTime" + "&direction=desc";
+ var myurl = ld.apiurl + "/events/index/AlarmFrames >=:1" + excludeMonitorsFilter + "/StartTime >=:" + timeFrom + "/StartTime <=:" + timeTo + ".json?sort=" + "StartTime" + "&direction=desc"+$rootScope.authSession;
NVR.debug("Retrieving " + myurl);
@@ -848,7 +848,7 @@ angular.module('zmApp.controllers').controller('zmApp.MomentCtrl', ['$scope', '$
$scope.expand = ld.montageReviewCollapse;
- console.log(">>>>>>>>> RESTORING EXPAND AS:" + $scope.expand);
+ //console.log(">>>>>>>>> RESTORING EXPAND AS:" + $scope.expand);
$scope.loadingStatus = $translate.instant('kLoading');
diff --git a/www/js/MonitorCtrl.js b/www/js/MonitorCtrl.js
index 89efe4cd..0b6b9985 100644
--- a/www/js/MonitorCtrl.js
+++ b/www/js/MonitorCtrl.js
@@ -140,8 +140,8 @@ angular.module('zmApp.controllers')
NVR.debug("MonitorCtrl:changeConfig selection:" + $scope.monfunc.myenabled +
$scope.monfunc.myfunc);
var loginData = NVR.getLogin();
- var apiRestart = loginData.apiurl + "/states/change/restart.json";
- var apiMon = loginData.apiurl + "/monitors/" + item + ".json";
+ var apiRestart = loginData.apiurl + "/states/change/restart.json?"+$rootScope.authSession;
+ var apiMon = loginData.apiurl + "/monitors/" + item + ".json?"+$rootScope.authSession;
NVR.debug("MonitorCtrl: URLs for changeConfig save:" + apiMon);
@@ -476,7 +476,7 @@ angular.module('zmApp.controllers')
$scope.monitors[j].Monitor.isRunning = "...";
$scope.monitors[j].Monitor.color = zm.monitorCheckingColor;
$scope.monitors[j].Monitor.char = "ion-help-circled";
- apiMonCheck = $scope.loginData.apiurl + "/monitors/daemonStatus/id:" + $scope.monitors[j].Monitor.Id + "/daemon:zmc.json";
+ apiMonCheck = $scope.loginData.apiurl + "/monitors/daemonStatus/id:" + $scope.monitors[j].Monitor.Id + "/daemon:zmc.json?"+$rootScope.authSession;
NVR.debug("MonitorCtrl:monitorStateCheck: " + apiMonCheck);
diff --git a/www/js/MonitorModalCtrl.js b/www/js/MonitorModalCtrl.js
index 1279c013..d6411753 100644
--- a/www/js/MonitorModalCtrl.js
+++ b/www/js/MonitorModalCtrl.js
@@ -33,24 +33,6 @@ angular.module('zmApp.controllers').controller('MonitorModalCtrl', ['$scope', '$
NVR.debug("MonitorModalCtrl called from " + $ionicHistory.currentStateName());
- //no need to recompute auth in modal
- /*$rootScope.validMonitorId = $scope.monitors[0].Monitor.Id;
- NVR.getAuthKey($rootScope.validMonitorId, $scope.monitors[0].Monitor.connKey)
- .then(function (success) {
- $ionicLoading.hide();
- $rootScope.authSession = success;
- NVR.log("Modal: Stream authentication construction: " + $rootScope.authSession);
-
- },
- function (error) {
-
- $ionicLoading.hide();
- NVR.debug("ModalCtrl: Error details of stream auth:" + error);
- //$rootScope.authSession="";
- NVR.log("Modal: Error returned Stream authentication construction. Retaining old value of: " + $rootScope.authSession);
- });
-*/
-
$interval.cancel(intervalModalHandle);
$interval.cancel(cycleHandle);
@@ -100,7 +82,7 @@ angular.module('zmApp.controllers').controller('MonitorModalCtrl', ['$scope', '$
$timeout(function () {
var keyCode = evt.keyCode;
- console.log(keyCode + " PRESSED");
+ //console.log(keyCode + " PRESSED");
if (keyCode == keyCodes.ESC) {
@@ -437,7 +419,7 @@ angular.module('zmApp.controllers').controller('MonitorModalCtrl', ['$scope', '$
];
//console.log ("Inside Modal timer...");
var apiurl = NVR.getLogin().apiurl;
- var alarmurl = apiurl + "/monitors/alarm/id:" + $scope.monitorId + "/command:status.json";
+ var alarmurl = apiurl + "/monitors/alarm/id:" + $scope.monitorId + "/command:status.json?"+$rootScope.authSession;
NVR.log("Invoking " + alarmurl);
$http.get(alarmurl)
@@ -811,6 +793,11 @@ angular.module('zmApp.controllers').controller('MonitorModalCtrl', ['$scope', '$
};
}
+ if ($rootScope.authSession.indexOf("&token=")!=-1) {
+ ptzData.token=$rootScope.authSession.match(/&token=([^&]*)/)[1];
+ }
+
+
//console.log("Command value " + cmd + " with MID=" + monitorId);
//console.log("PTZDATA is " + JSON.stringify(ptzData));
$ionicLoading.hide();
@@ -842,7 +829,7 @@ angular.module('zmApp.controllers').controller('MonitorModalCtrl', ['$scope', '$
str.push(encodeURIComponent(p) + "=" +
encodeURIComponent(obj[p]));
var foo = str.join("&");
- //console.log("****RETURNING " + foo);
+ //console.log("****PTZ RETURNING " + foo);
return foo;
},
@@ -1072,7 +1059,7 @@ angular.module('zmApp.controllers').controller('MonitorModalCtrl', ['$scope', '$
function triggerAlarm(mid, mode) {
var apiurl = NVR.getLogin().apiurl;
var c = mode == 'on' ? 'on' : 'off';
- var alarmurl = apiurl + "/monitors/alarm/id:" + mid + "/command:" + c + ".json";
+ var alarmurl = apiurl + "/monitors/alarm/id:" + mid + "/command:" + c + ".json?"+$rootScope.authSession;
NVR.log("Invoking " + alarmurl);
var status = mode ? $translate.instant('kForcingAlarm') : $translate.instant('kCancellingAlarm');
@@ -1429,8 +1416,22 @@ angular.module('zmApp.controllers').controller('MonitorModalCtrl', ['$scope', '$
var CMD_QUERY = 99;
*/
- var myauthtoken = $rootScope.authSession.replace("&auth=", "");
- //&auth=
+ // var myauthtoken='';
+
+ var data_payload = {
+ view: "request",
+ request: "stream",
+ connkey: connkey,
+ command: cmd
+ };
+
+ if ($rootScope.authSession.indexOf("&auth=")!=-1) {
+ data_payload.auth=$rootScope.authSession.match(/&auth=([^&]*)/)[1];
+ }
+ else if ($rootScope.authSession.indexOf("&token=")!=-1) {
+ data_payload.token=$rootScope.authSession.match(/&token=([^&]*)/)[1];
+ }
+
var req = $http({
method: 'POST',
/*timeout: 15000,*/
@@ -1445,25 +1446,18 @@ angular.module('zmApp.controllers').controller('MonitorModalCtrl', ['$scope', '$
str.push(encodeURIComponent(p) + "=" +
encodeURIComponent(obj[p]));
var foo = str.join("&");
- //console.log("****RETURNING " + foo);
+ //console.log("****CONTROL RETURNING " + foo);
return foo;
},
- data: {
- view: "request",
- request: "stream",
- connkey: connkey,
- command: cmd,
- auth: myauthtoken,
-
- }
+ data: data_payload
});
req.then(function (resp) {
resp = resp.data;
if (resp.result == "Ok" && ndx != -1) {
var ld = NVR.getLogin();
- var apiurl = ld.apiurl + "/events/" + resp.status.event + ".json";
+ var apiurl = ld.apiurl + "/events/" + resp.status.event + ".json?"+$rootScope.authSession;
//console.log ("API " + apiurl);
$http.get(apiurl)
.then(function (data) {
@@ -1558,7 +1552,7 @@ angular.module('zmApp.controllers').controller('MonitorModalCtrl', ['$scope', '$
NVR.debug("configurePTZ: called with mid=" + mid);
var ld = NVR.getLogin();
- var url = ld.apiurl + "/monitors/" + mid + ".json";
+ var url = ld.apiurl + "/monitors/" + mid + ".json?"+$rootScope.authSession;
$http.get(url)
.then(function (data) {
data = data.data;
@@ -1572,7 +1566,7 @@ angular.module('zmApp.controllers').controller('MonitorModalCtrl', ['$scope', '$
if ($scope.isControllable == '1') {
var apiurl = NVR.getLogin().apiurl;
- var myurl = apiurl + "/controls/" + $scope.controlid + ".json";
+ var myurl = apiurl + "/controls/" + $scope.controlid + ".json?"+$rootScope.authSession;
NVR.debug("configurePTZ : getting controllable data " + myurl);
$http.get(myurl)
@@ -1758,7 +1752,7 @@ angular.module('zmApp.controllers').controller('MonitorModalCtrl', ['$scope', '$
function getZones() {
//https://server/zm/api/zones/forMonitor/7.json
- var api = NVR.getLogin().apiurl + "/zones/forMonitor/" + $scope.monitorId + ".json";
+ var api = NVR.getLogin().apiurl + "/zones/forMonitor/" + $scope.monitorId + ".json?"+$rootScope.authSession;
NVR.debug("Getting zones using:" + api);
originalZones = [];
$http.get(api)
diff --git a/www/js/MontageCtrl.js b/www/js/MontageCtrl.js
index a8b5b49d..4834d9e7 100644
--- a/www/js/MontageCtrl.js
+++ b/www/js/MontageCtrl.js
@@ -631,15 +631,16 @@ angular.module('zmApp.controllers')
apiurl += '/\'' + interval + '\' HOUR_SECOND';
}*/
- apiurl += '.json?sort=StartTime&direction=desc&limit=1';
+ apiurl += '.json?sort=StartTime&direction=desc&limit=1'+$rootScope.authSession;
- NVR.debug ("Getting event count using:"+apiurl);
+ NVR.debug ("Getting event count");
$http.get(apiurl)
.then (function (data) {
- console.log ("EVENTS GOT: "+JSON.stringify(data));
+ // console.log ("EVENTS GOT: "+JSON.stringify(data));
var res = data.data;
var mid = monitor.Monitor.Id;
- if (res.events.length == 0) res = undefined;
+ if (!res || !res.events) res = undefined;
+ else if (res.events.length == 0) res = undefined;
monitor.Monitor.lastEvent = res;
@@ -656,7 +657,16 @@ angular.module('zmApp.controllers')
if (monitor.Monitor.lastEvent && showMontageSidebars) {
- monitor.Monitor.showSidebar = true;
+
+ if (ld.objectDetectionFilter) {
+ if (monitor.Monitor.lastEvent.object) {
+ monitor.Monitor.showSidebar = true;
+ }
+ }
+ else {
+ monitor.Monitor.showSidebar = true;
+ }
+
}
},
@@ -721,7 +731,7 @@ angular.module('zmApp.controllers')
var apiurl = NVR.getLogin().apiurl;
//console.log ("ALARM CALLED WITH " +JSON.stringify(monitor));
- var alarmurl = apiurl + "/monitors/alarm/id:" + monitor.Monitor.Id + "/command:status.json";
+ var alarmurl = apiurl + "/monitors/alarm/id:" + monitor.Monitor.Id + "/command:status.json?"+$rootScope.authSession;
// console.log("Alarm Check: Invoking " + alarmurl);
$http.get(alarmurl)
@@ -1916,7 +1926,7 @@ angular.module('zmApp.controllers')
var ld = NVR.getLogin();
var url = ld.apiurl;
var eid = monitor.Monitor.lastEvent.events[0].Event.Id;
- url += '/events/'+monitor.Monitor.lastEvent.events[0].Event.Id+'.json';
+ url += '/events/'+monitor.Monitor.lastEvent.events[0].Event.Id+'.json?'+$rootScope.authSession;
var mid = monitor.Monitor.Id;
ld.lastEventCheckTimes[mid] = (new moment()).tz(NVR.getTimeZoneNow()).format('YYYY-MM-DD HH:mm:ss');
@@ -2442,7 +2452,7 @@ angular.module('zmApp.controllers')
}
$scope.squeezeMonitors = function () {
- console.log ("squeezing");
+ NVR.debug ("squeezing");
pckry.once('layoutComplete', resizeComplete);
$timeout(function () {
pckry.layout();
diff --git a/www/js/MontageHistoryCtrl.js b/www/js/MontageHistoryCtrl.js
index 6f6687e4..50061d0d 100644
--- a/www/js/MontageHistoryCtrl.js
+++ b/www/js/MontageHistoryCtrl.js
@@ -264,7 +264,7 @@ angular.module('zmApp.controllers').controller('zmApp.MontageHistoryCtrl', ['$sc
function getNextSetHistory() {
// grab events that start on or after the time
- apiurl = ld.apiurl + "/events/index/StartTime >=:" + TimeObjectFrom + "/AlarmFrames >=:" + (ld.enableAlarmCount ? ld.minAlarmCount : 0) + ".json?sort=StartTime&direction=asc";
+ apiurl = ld.apiurl + "/events/index/StartTime >=:" + TimeObjectFrom + "/AlarmFrames >=:" + (ld.enableAlarmCount ? ld.minAlarmCount : 0) + ".json?sort=StartTime&direction=asc"+$rootScope.authSession;
NVR.log("Grabbing history using: " + apiurl);
// make sure there are no more than 5 active streams (noevent is ok)
$scope.currentLimit = $scope.monLimit;
@@ -277,7 +277,7 @@ angular.module('zmApp.controllers').controller('zmApp.MontageHistoryCtrl', ['$sc
var data = succ.data;
var ld = NVR.getLogin();
NVR.debug("Got " + data.events.length + "new history events...");
- console.log (JSON.stringify(data));
+ //console.log (JSON.stringify(data));
var eid, mid, stime;
for (i = 0; i < data.events.length; i++) {
mid = data.events[i].Event.MonitorId;
@@ -357,7 +357,7 @@ angular.module('zmApp.controllers').controller('zmApp.MontageHistoryCtrl', ['$sc
for (i = 0; i < $scope.MontageMonitors.length; i++) {
//console.log("Fair chance check for " + $scope.MontageMonitors[i].Monitor.Name);
if ($scope.MontageMonitors[i].Monitor.eventUrl == 'img/noimage.png') {
- var indivGrab = ld.apiurl + "/events/index/MonitorId:" + $scope.MontageMonitors[i].Monitor.Id + "/StartTime >=:" + TimeObjectFrom + "/AlarmFrames >=:" + (ld.enableAlarmCount ? ld.minAlarmCount : 0) + ".json";
+ var indivGrab = ld.apiurl + "/events/index/MonitorId:" + $scope.MontageMonitors[i].Monitor.Id + "/StartTime >=:" + TimeObjectFrom + "/AlarmFrames >=:" + (ld.enableAlarmCount ? ld.minAlarmCount : 0) + ".json?"+$rootScope.authSession;
NVR.debug("Monitor " + $scope.MontageMonitors[i].Monitor.Id + ":" + $scope.MontageMonitors[i].Monitor.Name + " does not have events, trying " + indivGrab);
var p = getExpandedEvents(i, indivGrab);
promises.push(p);
@@ -531,7 +531,21 @@ angular.module('zmApp.controllers').controller('zmApp.MontageHistoryCtrl', ['$sc
function subControlStream(cmd, connkey) {
var loginData = NVR.getLogin();
- var myauthtoken = $rootScope.authSession.replace("&auth=", "");
+
+ var data_payload = {
+ view: "request",
+ request: "stream",
+ connkey: connkey,
+ command: cmd
+ };
+
+ if ($rootScope.authSession.indexOf("&auth=")!=-1) {
+ data_payload.auth=$rootScope.authSession.match(/&auth=([^&]*)/)[1];
+ }
+ else if ($rootScope.authSession.indexOf("&token=")!=-1) {
+ data_payload.token=$rootScope.authSession.match(/&token=([^&]*)/)[1];
+ }
+
//&auth=
var req = qHttp({
method: 'POST',
@@ -544,17 +558,10 @@ angular.module('zmApp.controllers').controller('zmApp.MontageHistoryCtrl', ['$sc
var str = [];
for (var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
var foo = str.join("&");
- //console.log("****SUB RETURNING " + foo);
+ //console.log("****HISTORY CONTROL RETURNING " + foo);
return foo;
},
- data: {
- view: "request",
- request: "stream",
- connkey: connkey,
- command: cmd,
- auth: myauthtoken, // user: loginData.username,
- // pass: loginData.password
- }
+ data: data_payload
});
req.then(function (succ) {
NVR.debug("subControl success:" + JSON.stringify(succ));
@@ -614,32 +621,11 @@ angular.module('zmApp.controllers').controller('zmApp.MontageHistoryCtrl', ['$sc
url:cmdUrl
});
- /* var req = qHttp({
- method: 'POST',
- url: loginData.url + '/index.php?view=console',
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- transformRequest: function (obj) {
- var str = [];
- for (var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
- var foo = str.join("&");
- if (extras) foo = foo + extras;
- return foo;
- },
- data: {
- view: "request",
- request: "stream",
- connkey: connkey,
- command: cmd,
- auth: myauthtoken, // user: loginData.username,
- // pass: loginData.password
- }
- });*/
+
req.then(function (succ) {
var resp = succ.data;
- console.log ("zms response: " + JSON.stringify(resp));
+ //console.log ("zms response: " + JSON.stringify(resp));
// move progress bar if event id is the same
if (resp.result == "Ok" && ndx != -1 && (resp.status && resp.status.event == $scope.MontageMonitors[ndx].Monitor.eid)) {
@@ -655,7 +641,7 @@ angular.module('zmApp.controllers').controller('zmApp.MontageHistoryCtrl', ['$sc
// $scope.MontageMonitors[ndx].Monitor.sliderProgress.progress = 0;
NVR.debug("Fetching details, as event changed for " + $scope.MontageMonitors[ndx].Monitor.Name + " from " + $scope.MontageMonitors[ndx].Monitor.eid + " to " + resp.status.event);
var ld = NVR.getLogin();
- var apiurl = ld.apiurl + "/events/" + resp.status.event + ".json";
+ var apiurl = ld.apiurl + "/events/" + resp.status.event + ".json?"+$rootScope.authSession;
//console.log ("API " + apiurl);
qHttp({
method: 'get',
@@ -998,7 +984,7 @@ angular.module('zmApp.controllers').controller('zmApp.MontageHistoryCtrl', ['$sc
var d = $q.defer();
// now get event details to show alarm frames
var loginData = NVR.getLogin();
- var myurl = loginData.apiurl + '/events/' + eid + ".json";
+ var myurl = loginData.apiurl + '/events/' + eid + ".json?"+$rootScope.authSession;
//console.log (">> 1: getting: "+myurl);
var r = {
@@ -1021,7 +1007,7 @@ angular.module('zmApp.controllers').controller('zmApp.MontageHistoryCtrl', ['$sc
else {
r.eid = target;
// now get time of that event
- myurl = loginData.apiurl+'/events/'+target + '.json';
+ myurl = loginData.apiurl+'/events/'+target + '.json?'+$rootScope.authSession;
$http.get (myurl)
.then (function (succ) {
r.stime = succ.data.event.Event.StartTime;
diff --git a/www/js/NVR.js b/www/js/NVR.js
index 87c76e80..1b5b9da8 100644
--- a/www/js/NVR.js
+++ b/www/js/NVR.js
@@ -192,11 +192,14 @@ angular.module('zmApp.controllers')
'montageReviewCollapse': true,
'objectDetectionFilter': false,
'enableEventRefresh': true,
- 'lastEventCheckTimes':{},
+ 'lastEventCheckTimes': {},
'enableMontageOverlays': true,
- 'showMontageSidebars': false
-
-
+ 'showMontageSidebars': false,
+ 'isTokenSupported': false,
+ 'accessTokenExpires': '',
+ 'refreshTokenExpires': '',
+ 'accessToken': '',
+ 'refreshToken': ''
};
@@ -227,7 +230,7 @@ angular.module('zmApp.controllers')
cordova.plugin.http.setSSLCertMode('nocheck', function () {
debug('--> SSL is permissive, will allow any certs. Use at your own risk.');
}, function () {
- console.log('-->Error setting SSL permissive');
+ NVR.log('-->Error setting SSL permissive');
});
if ($rootScope.platformOS == 'android') {
@@ -311,10 +314,15 @@ angular.module('zmApp.controllers')
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 () {
@@ -332,7 +340,7 @@ angular.module('zmApp.controllers')
if (configParams.ZM_MIN_STREAMING_PORT == -1 || forceReload) {
log("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';
+ var myurl = apiurl + '/configs/viewByName/ZM_MIN_STREAMING_PORT.json?' + $rootScope.authSession;
$http.get(myurl)
.then(function (data) {
data = data.data;
@@ -370,6 +378,314 @@ angular.module('zmApp.controllers')
}
+ 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 = $translate.instant('kAuthenticating');
+
+ if (str) {
+ $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;
+
+ 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) {
+ 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 {
+ log ("Neither token nor old cred worked. Seems like an error");
+ }
+ }
+
+
+
+ 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(ld);
+ 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) {
+ NVR.log("API based login not supported, need to use web scraping..."+JSON.stringify(err));
+ // 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();
+ debug("Logging in using old web-scrape method");
+
+ $ionicLoading.show({
+ template: $translate.instant('kAuthenticatingWebScrape'),
+ 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) {
@@ -382,6 +698,12 @@ angular.module('zmApp.controllers')
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)) {
myurl = loginData.apiurl + '/host/getCredentials.json';
@@ -391,7 +713,7 @@ angular.module('zmApp.controllers')
debug("Credentials API returned: " + JSON.stringify(s));
if (!s.data || !s.data.credentials) {
- $rootScope.authSession = "undefined";
+ $rootScope.authSession = "";
d.resolve($rootScope.authSession);
debug("getCredentials() API Succeded, but did NOT return credentials key: " + JSON.stringify(s));
return d.promise;
@@ -408,7 +730,9 @@ angular.module('zmApp.controllers')
},
function (e) {
- $rootScope.authSession = "undefined";
+
+ //console.log ("***** CLEARING AUTHSESSION IN GETCREDENTIALS");
+ $rootScope.authSession = "";
d.resolve($rootScope.authSession);
debug("AuthHash API Error: " + JSON.stringify(e));
return d.promise;
@@ -483,10 +807,15 @@ angular.module('zmApp.controllers')
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>");
}
// make sure password is removed
@@ -510,11 +839,10 @@ angular.module('zmApp.controllers')
try {
positions = JSON.parse(positionsStr);
+ } catch (e) {
+ debug("error parsing positions");
}
- catch (e) {
- debug ("error parsing positions");
- }
-
+
for (var m = 0; m < monitors.length; m++) {
var positionFound = false;
for (var p = 0; p < positions.length; p++) {
@@ -607,464 +935,489 @@ angular.module('zmApp.controllers')
}
function _checkInitSanity(loginData) {
- // old version hacks for new variables
-
- // always true Oct 27 2016
- loginData.persistMontageOrder = true;
- loginData.enableh264 = true;
-
- if (typeof loginData.isUseBasicAuth === 'undefined') {
- loginData.isUseBasicAuth = false;
- loginData.basicAuthUser = '';
- loginData.basicAuthPassword = '';
- $rootScope.basicAuthHeader = '';
- $rootScope.basicAuthToken = '';
- }
+ // old version hacks for new variables
+
+ // always true Oct 27 2016
+ loginData.persistMontageOrder = true;
+ loginData.enableh264 = true;
+
+ if (typeof loginData.isUseBasicAuth === 'undefined') {
+ loginData.isUseBasicAuth = false;
+ loginData.basicAuthUser = '';
+ loginData.basicAuthPassword = '';
+ $rootScope.basicAuthHeader = '';
+ $rootScope.basicAuthToken = '';
+ }
- if (loginData.url.indexOf('@') != -1) {
- log(">> " + loginData.url);
- log(">>User/Password detected in URL, changing to new auth handling...");
- loginData.isUseBasicAuth = true;
+ if (loginData.url.indexOf('@') != -1) {
+ log(">> " + loginData.url);
+ log(">>User/Password detected in URL, changing to new auth handling...");
+ loginData.isUseBasicAuth = true;
- var components = URI.parse(loginData.url);
- loginData.url = components.scheme + "://" + components.host;
- if (components.port) loginData.url = loginData.url + ":" + components.port;
- if (components.path) loginData.url = loginData.url + components.path;
+ var components = URI.parse(loginData.url);
+ loginData.url = components.scheme + "://" + components.host;
+ if (components.port) loginData.url = loginData.url + ":" + components.port;
+ if (components.path) loginData.url = loginData.url + components.path;
- components = URI.parse(loginData.streamingurl);
- loginData.streamingurl = components.scheme + "://" + components.host;
- if (components.port) loginData.streamingurl = loginData.streamingurl + ":" + components.port;
- if (components.path) loginData.streamingurl = loginData.streamingurl + components.path;
+ components = URI.parse(loginData.streamingurl);
+ loginData.streamingurl = components.scheme + "://" + components.host;
+ if (components.port) loginData.streamingurl = loginData.streamingurl + ":" + components.port;
+ if (components.path) loginData.streamingurl = loginData.streamingurl + components.path;
- components = URI.parse(loginData.apiurl);
- loginData.apiurl = components.scheme + "://" + components.host;
- if (components.port) loginData.apiurl = loginData.apiurl + ":" + components.port;
- if (components.path) loginData.apiurl = loginData.apiurl + components.path;
+ components = URI.parse(loginData.apiurl);
+ loginData.apiurl = components.scheme + "://" + components.host;
+ if (components.port) loginData.apiurl = loginData.apiurl + ":" + components.port;
+ if (components.path) loginData.apiurl = loginData.apiurl + components.path;
- $rootScope.basicAuthToken = btoa(components.userinfo);
- $rootScope.basicAuthHeader = 'Basic ' + $rootScope.basicAuthToken;
- //console.log (">>>> SET BASIC AUTH TO " + $rootScope.basicAuthHeader);
+ $rootScope.basicAuthToken = btoa(components.userinfo);
+ $rootScope.basicAuthHeader = 'Basic ' + $rootScope.basicAuthToken;
+ //console.log (">>>> SET BASIC AUTH TO " + $rootScope.basicAuthHeader);
- var up = components.userinfo.split(':');
- loginData.basicAuthPassword = up[1];
- loginData.basicAuthUser = up[0];
- //console.log ("SETTING "+loginData.basicAuthUser+" "+loginData.basicAuthPassword);
+ var up = components.userinfo.split(':');
+ loginData.basicAuthPassword = up[1];
+ loginData.basicAuthUser = up[0];
+ //console.log ("SETTING "+loginData.basicAuthUser+" "+loginData.basicAuthPassword);
- }
+ }
- if (loginData.isUseBasicAuth) {
- $rootScope.basicAuthToken = btoa(loginData.basicAuthUser + ':' + loginData.basicAuthPassword);
- $rootScope.basicAuthHeader = 'Basic ' + $rootScope.basicAuthToken;
- debug("Basic authentication detected, constructing Authorization Header");
+ if (loginData.isUseBasicAuth) {
+ $rootScope.basicAuthToken = btoa(loginData.basicAuthUser + ':' + loginData.basicAuthPassword);
+ $rootScope.basicAuthHeader = 'Basic ' + $rootScope.basicAuthToken;
+ debug("Basic authentication detected, constructing Authorization Header");
- // console.log ("BASIC AUTH SET TO:"+$rootScope.basicAuthHeader);
+ // console.log ("BASIC AUTH SET TO:"+$rootScope.basicAuthHeader);
- }
+ }
- if (typeof loginData.enableAlarmCount === 'undefined') {
- debug("enableAlarmCount does not exist, setting to true");
- loginData.enableAlarmCount = true;
- }
+ if (typeof loginData.enableAlarmCount === 'undefined') {
+ debug("enableAlarmCount does not exist, setting to true");
+ loginData.enableAlarmCount = true;
+ }
- if (typeof loginData.onTapScreen == 'undefined') {
- loginData.onTapScreen = $translate.instant('kTapMontage');
- }
+ if (typeof loginData.onTapScreen == 'undefined') {
+ loginData.onTapScreen = $translate.instant('kTapMontage');
+ }
- if (loginData.onTapScreen != $translate.instant('kTapMontage') &&
- loginData.onTapScreen != $translate.instant('kTapEvents') &&
- loginData.onTapScreen != $translate.instant('kTapLiveMonitor')) {
- log("Invalid onTap setting found, resetting. I got " + loginData.onTapScreen);
- loginData.onTapScreen = $translate.instant('kMontage');
- }
+ if (loginData.onTapScreen != $translate.instant('kTapMontage') &&
+ loginData.onTapScreen != $translate.instant('kTapEvents') &&
+ loginData.onTapScreen != $translate.instant('kTapLiveMonitor')) {
+ log("Invalid onTap setting found, resetting. I got " + loginData.onTapScreen);
+ loginData.onTapScreen = $translate.instant('kMontage');
+ }
- if (typeof loginData.minAlarmCount === 'undefined') {
- debug("minAlarmCount does not exist, setting to true");
- loginData.minAlarmCount = 1;
- }
+ if (typeof loginData.minAlarmCount === 'undefined') {
+ debug("minAlarmCount does not exist, setting to true");
+ loginData.minAlarmCount = 1;
+ }
- if (typeof loginData.montageSize == 'undefined') {
- debug("montageSize does not exist, setting to 2 (2 per col)");
- loginData.montageSize = 2;
- }
+ if (typeof loginData.montageSize == 'undefined') {
+ debug("montageSize does not exist, setting to 2 (2 per col)");
+ loginData.montageSize = 2;
+ }
- if (typeof loginData.useNphZms == 'undefined') {
- debug("useNphZms does not exist. Setting to true");
- loginData.useNphZms = true;
- }
+ if (typeof loginData.useNphZms == 'undefined') {
+ debug("useNphZms does not exist. Setting to true");
+ loginData.useNphZms = true;
+ }
- if (typeof loginData.useNphZmsForEvents == 'undefined') {
- debug("useNphZmsForEvents does not exist. Setting to true");
- loginData.useNphZmsForEvents = true;
- }
+ if (typeof loginData.useNphZmsForEvents == 'undefined') {
+ debug("useNphZmsForEvents does not exist. Setting to true");
+ loginData.useNphZmsForEvents = true;
+ }
- if (typeof loginData.forceImageModePath == 'undefined') {
- debug("forceImageModePath does not exist. Setting to false");
- loginData.forceImageModePath = false;
- }
+ if (typeof loginData.forceImageModePath == 'undefined') {
+ debug("forceImageModePath does not exist. Setting to false");
+ loginData.forceImageModePath = false;
+ }
- if (typeof loginData.reachability == 'undefined') {
- debug("reachability does not exist. Setting to true");
- loginData.reachability = true;
- }
+ if (typeof loginData.reachability == 'undefined') {
+ debug("reachability does not exist. Setting to true");
+ loginData.reachability = true;
+ }
- // force it - this may not be the problem
- loginData.reachability = true;
+ // force it - this may not be the problem
+ loginData.reachability = true;
- // and now, force enable it
- loginData.useNphZms = true;
- loginData.useNphZmsForEvents = true;
+ // and now, force enable it
+ loginData.useNphZms = true;
+ loginData.useNphZmsForEvents = true;
- if (typeof loginData.packMontage == 'undefined') {
- debug("packMontage does not exist. Setting to false");
- loginData.packMontage = false;
- }
+ if (typeof loginData.packMontage == 'undefined') {
+ debug("packMontage does not exist. Setting to false");
+ loginData.packMontage = false;
+ }
- if (typeof loginData.forceNetworkStop == 'undefined') {
- debug("forceNetwork does not exist. Setting to false");
- loginData.forceNetworkStop = false;
- }
+ if (typeof loginData.forceNetworkStop == 'undefined') {
+ debug("forceNetwork does not exist. Setting to false");
+ loginData.forceNetworkStop = false;
+ }
- if (typeof loginData.enableLogs == 'undefined') {
- debug("enableLogs does not exist. Setting to true");
- loginData.enableLogs = true;
- }
+ if (typeof loginData.enableLogs == 'undefined') {
+ debug("enableLogs does not exist. Setting to true");
+ loginData.enableLogs = true;
+ }
- if (typeof loginData.defaultPushSound == 'undefined') {
- debug("defaultPushSound does not exist. Setting to false");
- loginData.defaultPushSound = false;
- }
+ if (typeof loginData.defaultPushSound == 'undefined') {
+ debug("defaultPushSound does not exist. Setting to false");
+ loginData.defaultPushSound = false;
+ }
- //console.log("INIT SIMUL=" + loginData.disableSimulStreaming);
- //console.log("INIT PLATFORM IS=" + $rootScope.platformOS);
- if (typeof loginData.disableSimulStreaming == 'undefined') {
+ //console.log("INIT SIMUL=" + loginData.disableSimulStreaming);
+ //console.log("INIT PLATFORM IS=" + $rootScope.platformOS);
+ if (typeof loginData.disableSimulStreaming == 'undefined') {
- loginData.disableSimulStreaming = false;
- //console.log("INIT DISABLING SIMUL:" + loginData.disableSimulStreaming);
- }
+ loginData.disableSimulStreaming = false;
+ //console.log("INIT DISABLING SIMUL:" + loginData.disableSimulStreaming);
+ }
- if (typeof loginData.exitOnSleep == 'undefined') {
- debug("exitOnSleep does not exist. Setting to false");
- loginData.exitOnSleep = false;
- }
+ if (typeof loginData.exitOnSleep == 'undefined') {
+ debug("exitOnSleep does not exist. Setting to false");
+ loginData.exitOnSleep = false;
+ }
- if (typeof loginData.enableBlog == 'undefined') {
- debug("enableBlog does not exist. Setting to true");
- loginData.enableBlog = true;
+ if (typeof loginData.enableBlog == 'undefined') {
+ debug("enableBlog does not exist. Setting to true");
+ loginData.enableBlog = true;
- }
+ }
- if (typeof loginData.packeryPositionsArray == 'undefined') {
- debug("packeryPositionsArray does not exist. Setting to empty");
- loginData.packeryPositionsArray = {};
+ if (typeof loginData.packeryPositionsArray == 'undefined') {
+ debug("packeryPositionsArray does not exist. Setting to empty");
+ loginData.packeryPositionsArray = {};
- }
+ }
- if (typeof loginData.packeryPositions == 'undefined') {
- debug("packeryPositions does not exist. Setting to empty");
- loginData.packeryPositions = "";
+ if (typeof loginData.packeryPositions == 'undefined') {
+ debug("packeryPositions does not exist. Setting to empty");
+ loginData.packeryPositions = "";
- }
+ }
- if (typeof loginData.EHpackeryPositions == 'undefined') {
- debug("EHpackeryPositions does not exist. Setting to empty");
- loginData.EHpackeryPositions = "";
+ if (typeof loginData.EHpackeryPositions == 'undefined') {
+ //debug("EHpackeryPositions does not exist. Setting to empty");
+ loginData.EHpackeryPositions = "";
- }
+ }
- if (typeof loginData.packerySizes == 'undefined') {
- debug("packerySizes does not exist. Setting to empty");
- loginData.packerySizes = "";
+ if (typeof loginData.packerySizes == 'undefined') {
+ //debug("packerySizes does not exist. Setting to empty");
+ loginData.packerySizes = "";
- }
+ }
- if (typeof loginData.use24hr == 'undefined') {
- debug("use24hr does not exist. Setting to false");
- loginData.use24hr = false;
+ if (typeof loginData.use24hr == 'undefined') {
+ //debug("use24hr does not exist. Setting to false");
+ loginData.use24hr = false;
- }
+ }
- if (typeof timelineModalGraphType == 'undefined') {
- debug("timeline graph type not set. Setting to all");
- loginData.timelineModalGraphType = $translate.instant('kGraphAll');
- //console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + loginData.timelineModalGraphType);
- }
+ if (typeof timelineModalGraphType == 'undefined') {
+ //debug("timeline graph type not set. Setting to all");
+ loginData.timelineModalGraphType = $translate.instant('kGraphAll');
+ //console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + loginData.timelineModalGraphType);
+ }
- if (typeof loginData.resumeDelay == 'undefined') {
- debug("resumeDelay does not exist. Setting to 0");
- loginData.resumeDelay = 0;
+ if (typeof loginData.resumeDelay == 'undefined') {
+ //debug("resumeDelay does not exist. Setting to 0");
+ loginData.resumeDelay = 0;
- }
- // override resumeDelay - it was developed on a wrong assumption
- loginData.resumeDelay = 0;
+ }
+ // override resumeDelay - it was developed on a wrong assumption
+ loginData.resumeDelay = 0;
- if (typeof loginData.montageHistoryQuality == 'undefined') {
- debug("montageHistoryQuality does not exist. Setting to 50");
- loginData.montageHistoryQuality = "50";
+ if (typeof loginData.montageHistoryQuality == 'undefined') {
+ debug("montageHistoryQuality does not exist. Setting to 50");
+ loginData.montageHistoryQuality = "50";
- }
+ }
- if (typeof loginData.vibrateOnPush == 'undefined') {
- debug("vibrate on push not found, setting to true");
- loginData.vibrateOnPush = true;
+ if (typeof loginData.vibrateOnPush == 'undefined') {
+ debug("vibrate on push not found, setting to true");
+ loginData.vibrateOnPush = true;
- }
+ }
- if (typeof loginData.isFullScreen == 'undefined') {
+ if (typeof loginData.isFullScreen == 'undefined') {
- loginData.isFullScreen = false;
+ loginData.isFullScreen = false;
- }
+ }
- if (typeof loginData.reloadInMontage == 'undefined') {
+ if (typeof loginData.reloadInMontage == 'undefined') {
- loginData.reloadInMontage = false;
+ loginData.reloadInMontage = false;
- }
+ }
- if (typeof loginData.soundOnPush == 'undefined') {
- debug("sound on push not found, setting to true");
- loginData.soundOnPush = true;
+ if (typeof loginData.soundOnPush == 'undefined') {
+ debug("sound on push not found, setting to true");
+ loginData.soundOnPush = true;
- }
+ }
- if (typeof loginData.cycleMonitors == 'undefined') {
+ if (typeof loginData.cycleMonitors == 'undefined') {
- loginData.cycleMonitors = false;
+ loginData.cycleMonitors = false;
- }
+ }
- if (typeof loginData.cycleMonitorsInterval == 'undefined') {
+ if (typeof loginData.cycleMonitorsInterval == 'undefined') {
- loginData.cycleMonitorsInterval = 10;
+ loginData.cycleMonitorsInterval = 10;
- }
+ }
- if (typeof loginData.cycleMontage == 'undefined') {
+ if (typeof loginData.cycleMontage == 'undefined') {
- loginData.cycleMontage = false;
+ loginData.cycleMontage = false;
- }
+ }
- if (typeof loginData.cycleMontageInterval == 'undefined') {
+ if (typeof loginData.cycleMontageInterval == 'undefined') {
- loginData.cycleMontageInterval = 10;
+ loginData.cycleMontageInterval = 10;
- }
+ }
- if (typeof loginData.enableLowBandwidth == 'undefined') {
+ if (typeof loginData.enableLowBandwidth == 'undefined') {
- loginData.enableLowBandwidth = false;
+ loginData.enableLowBandwidth = false;
- }
- // wtf is wrong with this ternary?
- //$rootScope.runMode = (loginData.enableLowBandwith==true)? "low": "normal";
+ }
+
- if (typeof loginData.autoSwitchBandwidth == 'undefined') {
+ if (typeof loginData.autoSwitchBandwidth == 'undefined') {
- loginData.autoSwitchBandwidth = false;
+ loginData.autoSwitchBandwidth = false;
- }
+ }
- $rootScope.runMode = getBandwidth();
- log("Setting NVR init bandwidth to: " + $rootScope.runMode);
+ $rootScope.runMode = getBandwidth();
+ log("Setting NVR init bandwidth to: " + $rootScope.runMode);
- if (typeof loginData.refreshSecLowBW == 'undefined') {
+ if (typeof loginData.refreshSecLowBW == 'undefined') {
- loginData.refreshSecLowBW = 8;
+ loginData.refreshSecLowBW = 8;
- }
+ }
- if (typeof loginData.disableAlarmCheckMontage == 'undefined') {
+ if (typeof loginData.disableAlarmCheckMontage == 'undefined') {
- loginData.disableAlarmCheckMontage = false;
+ loginData.disableAlarmCheckMontage = false;
- }
+ }
- if (typeof loginData.useLocalTimeZone == 'undefined') {
+ if (typeof loginData.useLocalTimeZone == 'undefined') {
- loginData.useLocalTimeZone = true;
+ loginData.useLocalTimeZone = true;
- }
+ }
- if (typeof loginData.fastLogin == 'undefined') {
+ if (typeof loginData.fastLogin == 'undefined') {
- loginData.fastLogin = true;
+ loginData.fastLogin = true;
- }
+ }
- if (typeof loginData.currentMontageProfile == 'undefined') {
+ if (typeof loginData.currentMontageProfile == 'undefined') {
- loginData.currentMontageProfile = '';
+ loginData.currentMontageProfile = '';
- }
+ }
- if (typeof loginData.followTimeLine == 'undefined') {
+ if (typeof loginData.followTimeLine == 'undefined') {
- loginData.followTimeLine = false;
+ loginData.followTimeLine = false;
- }
+ }
- if (typeof loginData.timelineScale == 'undefined') {
+ if (typeof loginData.timelineScale == 'undefined') {
- loginData.timelineScale = -1;
+ loginData.timelineScale = -1;
- }
+ }
- if (typeof loginData.showMontageSubMenu == 'undefined') {
+ if (typeof loginData.showMontageSubMenu == 'undefined') {
- loginData.showMontageSubMenu = false;
+ loginData.showMontageSubMenu = false;
- }
+ }
- if (typeof loginData.monSingleImageQuality == 'undefined') {
+ if (typeof loginData.monSingleImageQuality == 'undefined') {
- loginData.monSingleImageQuality = 100;
+ loginData.monSingleImageQuality = 100;
- }
+ }
- if (typeof loginData.hideArchived == 'undefined') {
+ if (typeof loginData.hideArchived == 'undefined') {
- loginData.hideArchived = false;
+ loginData.hideArchived = false;
- }
+ }
- if (typeof loginData.videoPlaybackSpeed == 'undefined') {
+ if (typeof loginData.videoPlaybackSpeed == 'undefined') {
- loginData.videoPlaybackSpeed = 1;
+ loginData.videoPlaybackSpeed = 1;
- }
+ }
- if (typeof loginData.enableThumbs == 'undefined') {
+ if (typeof loginData.enableThumbs == 'undefined') {
- loginData.enableThumbs = true;
+ loginData.enableThumbs = true;
- }
+ }
- if (typeof loginData.enableSlowLoading == 'undefined') {
+ if (typeof loginData.enableSlowLoading == 'undefined') {
- loginData.enableSlowLoading = false;
+ loginData.enableSlowLoading = false;
- }
+ }
- if (typeof loginData.enableStrictSSL == 'undefined') {
+ if (typeof loginData.enableStrictSSL == 'undefined') {
- loginData.enableStrictSSL = false;
+ loginData.enableStrictSSL = false;
- }
+ }
- if (typeof loginData.momentGridSize == 'undefined') {
+ if (typeof loginData.momentGridSize == 'undefined') {
- loginData.momentGridSize = 40;
+ loginData.momentGridSize = 40;
- }
+ }
- if (typeof loginData.enableMomentSubMenu == 'undefined') {
+ if (typeof loginData.enableMomentSubMenu == 'undefined') {
- loginData.enableMomentSubMenu = true;
+ loginData.enableMomentSubMenu = true;
- }
+ }
- if (typeof loginData.momentMonitorFilter == 'undefined') {
+ if (typeof loginData.momentMonitorFilter == 'undefined') {
- loginData.momentMonitorFilter = JSON.stringify([]);
+ loginData.momentMonitorFilter = JSON.stringify([]);
- }
+ }
- if (typeof loginData.momentArrangeBy == 'undefined') {
+ if (typeof loginData.momentArrangeBy == 'undefined') {
- loginData.momentArrangeBy = "StartTime";
+ loginData.momentArrangeBy = "StartTime";
- }
+ }
- if (typeof loginData.insertBasicAuthToken == 'undefined') {
+ if (typeof loginData.insertBasicAuthToken == 'undefined') {
- loginData.insertBasicAuthToken = false;
+ loginData.insertBasicAuthToken = false;
- }
+ }
- if (typeof loginData.showLiveForInProgressEvents == 'undefined') {
+ if (typeof loginData.showLiveForInProgressEvents == 'undefined') {
- loginData.showLiveForInProgressEvents = true;
+ loginData.showLiveForInProgressEvents = true;
- }
+ }
- if (typeof loginData.loginAPISupported == 'undefined') {
+ if (typeof loginData.loginAPISupported == 'undefined') {
- loginData.loginAPISupported = false;
+ loginData.loginAPISupported = false;
- }
+ }
- if (typeof loginData.montageResizeSteps == 'undefined') {
+ if (typeof loginData.montageResizeSteps == 'undefined') {
- loginData.montageResizeSteps = 5;
+ loginData.montageResizeSteps = 5;
- }
+ }
- if (typeof loginData.saveToCloud == 'undefined') {
+ if (typeof loginData.saveToCloud == 'undefined') {
- loginData.saveToCloud = true;
+ loginData.saveToCloud = true;
- }
+ }
- if (typeof loginData.montageReviewCollapse == 'undefined') {
+ if (typeof loginData.montageReviewCollapse == 'undefined') {
- loginData.montageReviewCollapse = true;
+ loginData.montageReviewCollapse = true;
- }
+ }
- if (typeof loginData.objectDetectionFilter == 'undefined') {
+ if (typeof loginData.objectDetectionFilter == 'undefined') {
- loginData.objectDetectionFilter = false;
+ loginData.objectDetectionFilter = false;
- }
+ }
- if (typeof loginData.enableEventRefresh == 'undefined') {
+ if (typeof loginData.enableEventRefresh == 'undefined') {
- loginData.enableEventRefresh = true;
+ loginData.enableEventRefresh = true;
- }
+ }
-
-
- if (typeof loginData.lastEventCheckTimes == 'undefined') {
- loginData.lastEventCheckTimes = {};
- }
+ if (typeof loginData.lastEventCheckTimes == 'undefined') {
+ loginData.lastEventCheckTimes = {};
- if (typeof loginData.enableMontageOverlays == 'undefined') {
- loginData.enableMontageOverlays = true;
+ }
- }
- if (typeof loginData.showMontageSidebars == 'undefined') {
- loginData.showMontageSidebars = false;
+ if (typeof loginData.enableMontageOverlays == 'undefined') {
+ loginData.enableMontageOverlays = true;
- }
+ }
+
+ if (typeof loginData.showMontageSidebars == 'undefined') {
+ loginData.showMontageSidebars = false;
+
+ }
- loginData.canSwipeMonitors = true;
- loginData.forceImageModePath = false;
- loginData.enableBlog = true;
+ if (typeof loginData.isTokenSupported == 'undefined') {
+ loginData.isTokenSupported = false;
+
+ }
+
+ if (typeof loginData.accessTokenExpires == 'undefined') {
+ loginData.accessTokenExpires = '';
+
+ }
+
+ if (typeof loginData.refreshTokenExpires == 'undefined') {
+ loginData.refreshTokenExpires = '';
+
+ }
+
+ if (typeof loginData.refreshToken == 'undefined') {
+ loginData.refreshToken = '';
+
+ }
+
+ if (typeof loginData.accessToken == 'undefined') {
+ loginData.accessToken = '';
+
+ }
+
+
+ loginData.canSwipeMonitors = true;
+ loginData.forceImageModePath = false;
+ loginData.enableBlog = true;
}
@@ -1496,7 +1849,7 @@ angular.module('zmApp.controllers')
},
checkInitSanity: function (l) {
- _checkInitSanity(l);
+ _checkInitSanity(l);
},
init: function () {
@@ -1830,12 +2183,12 @@ angular.module('zmApp.controllers')
getAPIversion: function () {
var d = $q.defer();
- var apiurl = loginData.apiurl + '/host/getVersion.json';
+ var apiurl = loginData.apiurl + '/host/getVersion.json?' + $rootScope.authSession;
debug("getAPIversion called with " + apiurl);
$http.get(apiurl)
.then(function (success) {
if (success.data.version) {
- console.log("API VERSION RETURNED: " + JSON.stringify(success));
+ //console.log("API VERSION RETURNED: " + JSON.stringify(success));
$rootScope.apiValid = true;
if (versionCompare(success.data.version, '1.32.0') != -1) {
@@ -1848,12 +2201,7 @@ angular.module('zmApp.controllers')
setCurrentServerVersion(success.data.version);
debug("getAPI version succeeded with " + success.data.version);
d.resolve(success.data.version);
- } else {
- debug("Setting APIValid to false as API version was not retrieved");
- $rootScope.apiValid = false;
- setCurrentServerVersion("");
- d.reject("-1.-1.-1");
- }
+ }
return (d.promise);
},
@@ -1942,7 +2290,7 @@ angular.module('zmApp.controllers')
getAuthHashLogin: function () {
- return $http.get(loginData.apiurl + '/configs/viewByName/ZM_AUTH_HASH_LOGINS.json');
+ return $http.get(loginData.apiurl + '/configs/viewByName/ZM_AUTH_HASH_LOGINS.json?' + $rootScope.authSession);
},
@@ -1952,7 +2300,7 @@ angular.module('zmApp.controllers')
if (forceReload == 1 || configParams.ZM_EVENT_IMAGE_DIGITS == '-1') {
var apiurl = loginData.apiurl;
- var myurl = apiurl + '/configs/viewByName/ZM_EVENT_IMAGE_DIGITS.json';
+ var myurl = apiurl + '/configs/viewByName/ZM_EVENT_IMAGE_DIGITS.json?' + $rootScope.authSession;
//debug("Config URL for digits is:" + myurl);
$http.get(myurl)
.then(function (data) {
@@ -1989,7 +2337,7 @@ angular.module('zmApp.controllers')
var apiurl = loginData.apiurl;
- var myurl = apiurl + '/configs/viewByName/ZM_PATH_ZMS.json';
+ var myurl = apiurl + '/configs/viewByName/ZM_PATH_ZMS.json?' + $rootScope.authSession;
debug("Config URL for ZMS PATH is:" + myurl);
$http.get(myurl)
.then(function (data) {
@@ -2109,49 +2457,7 @@ angular.module('zmApp.controllers')
);
},
- /*killStream: function (ck) {
- debug ("Killing connKey: "+ck);
- var myauthtoken = $rootScope.authSession.replace("&auth=", "");
- var req = $http(
- {
- method: 'POST',
-
- url: loginData.url + '/index.php',
- headers:
- {
- 'Content-Type': 'application/x-www-form-urlencoded',
- ,
- },
- transformRequest: function(obj)
- {
- var str = [];
- for (var p in obj)
- str.push(encodeURIComponent(p) + "=" +
- encodeURIComponent(obj[p]));
- var foo = str.join("&");
- //console.log("****RETURNING " + foo);
- return foo;
- },
-
- data:
- {
- view: "request",
- request: "stream",
- connkey: ck,
- command: 3,
- auth: myauthtoken,
-
- }
- })
- .then (function (succ) {
- console.log ("STOP/KILL OK WITH: " + JSON.stringify(succ));
- },
- function (err) {
- console.log ("KILL ERROR WITH: " + JSON.stringify(err));
- });
-
-
- },*/
+
getMultiServersCached: function () {
return multiservers;
@@ -2159,7 +2465,7 @@ angular.module('zmApp.controllers')
// use non cached for daemon status
getMultiServers: function () {
- return $http.get(loginData.apiurl + '/servers.json');
+ return $http.get(loginData.apiurl + '/servers.json?' + $rootScope.authSession);
},
@@ -2204,7 +2510,7 @@ angular.module('zmApp.controllers')
log((forceReload == 1) ? "getMonitors:Force reloading all monitors" : "getMonitors:Loading all monitors");
var apiurl = loginData.apiurl;
var myurl = apiurl + "/monitors";
- myurl += "/index/Type !=:WebSite.json";
+ myurl += "/index/Type !=:WebSite.json?" + $rootScope.authSession;
getZmsMultiPortSupport()
.then(function (zmsPort) {
@@ -2220,7 +2526,7 @@ angular.module('zmApp.controllers')
if (data.monitors) monitors = data.monitors;
- if ($rootScope.authSession == 'undefined') {
+ if ($rootScope.authSession == '') {
log("Now that we have monitors, lets get AuthKey...");
getAuthKey(monitors[0].Monitor.Id, (Math.floor((Math.random() * 999999) + 1)).toString());
}
@@ -2234,12 +2540,12 @@ angular.module('zmApp.controllers')
debug("Inside getMonitors, will also regen connkeys");
debug("Now trying to get multi-server data, if present");
- $http.get(apiurl + "/servers.json")
+ $http.get(apiurl + "/servers.json?" + $rootScope.authSession)
.then(function (data) {
data = data.data;
// We found a server list API, so lets make sure
// we get the hostname as it will be needed for playback
- log("multi server list loaded:" + JSON.stringify(data));
+ log("multi server list loaded");
multiservers = data.servers;
var multiserver_scheme = "http://";
@@ -2309,8 +2615,8 @@ angular.module('zmApp.controllers')
debug("recording server reported is " + JSON.stringify(m));
- debug("portal parsed is " + JSON.stringify(p));
- debug("streaming url parsed is " + JSON.stringify(s));
+ //debug("portal parsed is " + JSON.stringify(p));
+ //debug("streaming url parsed is " + JSON.stringify(s));
debug("multi-port is:" + zmsPort);
var st = "";
@@ -2350,7 +2656,7 @@ angular.module('zmApp.controllers')
var sport = parseInt(zmsPort) + parseInt(monitors[i].Monitor.Id);
st = st + ':' + sport;
}
-
+
}
baseurl = st;
@@ -2500,9 +2806,141 @@ angular.module('zmApp.controllers')
},
+ proceedWithLogin: function (obj) {
+
+ var noBroadcast = false;
+ var tryAccess = true;
+ var tryRefresh = true;
+
+ if (obj) {
+ noBroadcast = obj.nobroadcast;
+ tryAccess = obj.access;
+ tryRefresh = obj.refresh;
+
+ }
+
+ var d = $q.defer();
+
+ // This is a good time to check if auth is used :-p
+ if (!loginData.isUseAuth) {
+ log("Auth is disabled, setting authSession to empty");
+ $rootScope.apiValid = true;
+ $rootScope.authSession = '';
+ d.resolve("Login Success");
+
+ if (!noBroadcast) $rootScope.$broadcast('auth-success', 'no auth');
+ return (d.promise);
+
+ }
+
+
+ // lets first try tokens and stored tokens
+ if (loginData.isTokenSupported)
+ {
+ log ("Detected token login supported");
+ var now = moment.utc();
+ var diff_access = moment.utc(loginData.accessTokenExpires).diff(now, 'minutes');
+ var diff_refresh = moment.utc(loginData.refreshTokenExpires).diff(now, 'minutes');
+
+ // first see if we can work with access token
+ if (moment.utc(loginData.accessTokenExpires).isAfter(now) && diff_access >=zm.accessTokenLeewayMin && tryAccess) {
+ log ("Access token still has "+diff_access+" minutes left, using it");
+ // console.log ("**************** TOKEN SET="+loginData.accessToken);
+ $rootScope.authSession = '&token='+loginData.accessToken;
+ d.resolve("Login success via access token");
+ if (!noBroadcast) $rootScope.$broadcast('auth-success', '' );
+ return d.promise;
+ }
+ // then see if we have at least 30 mins left for refresh token
+ else if (moment.utc(loginData.refreshTokenExpires).isAfter(now) && diff_refresh >=zm.refreshTokenLeewayMin && tryRefresh) {
+ log ("Refresh token still has "+diff_refresh+" minutes left, using it");
+ var loginAPI = loginData.apiurl + '/host/login.json?token='+loginData.refreshToken;
+ $http({
+ method:'GET',
+ url: loginAPI,
+ skipIntercept:true,
+ })
+ .then (function (succ) {
+ succ = succ.data;
+ if (succ.access_token) {
+
+ // console.log ("**************** TOKEN SET="+succ.access_token);
+ $rootScope.authSession = '&token='+succ.access_token;
+ log ("New access token retrieved: ..."+succ.access_token.substr(-5));
+ loginData.accessToken = succ.access_token;
+ loginData.accessTokenExpires = moment.utc().add(succ.access_token_expires,'seconds');
+ log ("Current time is: UTC "+moment.utc().format("YYYY-MM-DD hh:mm:ss"));
+ log ("New access token expires on: UTC "+loginData.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
+ log ("New access token expires on:"+loginData.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
+ loginData.isTokenSupported = true;
+ setLogin(loginData);
+ d.resolve("Login success via refresh token");
+ if (!noBroadcast) $rootScope.$broadcast('auth-success', '' );
+ return d.promise;
+ }
+ else {
+ log ('ERROR:Trying to refresh with refresh token:'+JSON.stringify(succ));
+ return proceedWithFreshLogin(noBroadcast)
+ .then (function (succ) {
+ d.resolve(succ);
+ return (d.promise);
+ },
+ function(err) {
+ d.resolve(err);
+ return (d.promise);
+ });
+
+ }
+ },
+ function (err) {
+ log ('access token login HTTP failed with: '+JSON.stringify(err));
+ return proceedWithFreshLogin(noBroadcast)
+ .then (function (succ) {
+ d.resolve(succ);
+ return (d.promise);
+ },
+ function(err) {
+ d.resolve(err);
+ return (d.promise);});
+ });
+ } // valid refresh
+ else {
+ log ('both access and refresh tokens are expired, using a fresh login');
+ return proceedWithFreshLogin(noBroadcast)
+ .then (function (succ) {
+ d.resolve(succ);
+ return (d.promise);
+ },
+ function(err) {
+ d.resolve(err);
+ return (d.promise);
+ });
+ }
+
+ } // is token supported
+ else {
+ log ("Token login not being used");
+ // coming here means token reloads fell through
+ return proceedWithFreshLogin(noBroadcast)
+ .then (function (succ) {
+ d.resolve(succ);
+ return (d.promise);
+ },
+ function(err) {
+ d.resolve(err);
+ return (d.promise);
+ });
+ }
+ return (d.promise);
+
+ },
+
+
+
+
zmPrivacyProcessed: function () {
var apiurl = loginData.apiurl;
- var myurl = apiurl + '/configs/viewByName/ZM_SHOW_PRIVACY.json';
+ var myurl = apiurl + '/configs/viewByName/ZM_SHOW_PRIVACY.json?' + $rootScope.authSession;
var d = $q.defer();
$http({
@@ -2603,6 +3041,7 @@ angular.module('zmApp.controllers')
}
return d.promise;
},
+
// returns if this mid is hidden or not
isNotHidden: function (mid) {
@@ -2641,7 +3080,7 @@ angular.module('zmApp.controllers')
if (!tz || isForce) {
log("First invocation of TimeZone, asking server");
- var apiurl = loginData.apiurl + '/host/getTimeZone.json';
+ var apiurl = loginData.apiurl + '/host/getTimeZone.json?' + $rootScope.authSession;
$http.get(apiurl)
.then(function (success) {
tz = success.data.tz;
@@ -2700,11 +3139,11 @@ angular.module('zmApp.controllers')
//https:///zm/api/events/index/Notes%20REGEXP:detected%3A.json
if (loginData.objectDetectionFilter && !noObjectFilter) {
- myurl = myurl + '/Notes%20REGEXP:detected%3A';
+ myurl = myurl + '/Notes REGEXP:detected:';
}
- myurl = myurl + ".json";
+ myurl = myurl + ".json?" + $rootScope.authSession;
//console.log (">>>>>Constructed URL " + myurl);
$ionicLoading.show({
@@ -2787,12 +3226,13 @@ angular.module('zmApp.controllers')
myurl = myurl + "/AlarmFrames >=:" + (loginData.enableAlarmCount ? loginData.minAlarmCount : 0);
+ // don't know why but adding page messes up Notes
//https:///zm/api/events/index/Notes%20REGEXP: detected%3A.json
if (loginData.objectDetectionFilter && !noObjectFilter) {
myurl = myurl + '/Notes REGEXP:detected:';
}
- myurl = myurl + ".json?&sort=StartTime&direction=desc&page=" + pageId;
+ myurl = myurl + ".json?&sort=StartTime&direction=desc&page=" + pageId + $rootScope.authSession;
debug("getEvents:" + myurl);
@@ -2807,6 +3247,8 @@ angular.module('zmApp.controllers')
data = data.data;
if (loadingStr != 'none') $ionicLoading.hide();
//myevents = data.events;
+
+
myevents = data;
@@ -3056,8 +3498,14 @@ angular.module('zmApp.controllers')
},
logout: function () {
+ var d = $q.defer();
// always resolves
+ if (!loginData.isUseAuth || loginData.isTokenSupported) {
+ log("No need for logout!");
+ d.resolve(true);
+ return d.promise;
+ }
$ionicLoading.show({
template: $translate.instant('kCleaningUp'),
@@ -3065,9 +3513,9 @@ angular.module('zmApp.controllers')
});
- var d = $q.defer();
+
log(loginData.url + "=>Logging out of any existing ZM sessions...");
- $rootScope.authSession = "undefined";
+ $rootScope.authSession = "";
// console.log("CURRENT SERVER: " + loginData.currentServerVersion);
diff --git a/www/js/StateCtrl.js b/www/js/StateCtrl.js
index 0871c5ee..058fcb53 100644
--- a/www/js/StateCtrl.js
+++ b/www/js/StateCtrl.js
@@ -24,11 +24,11 @@ angular.module('zmApp.controllers').controller('zmApp.StateCtrl', ['$ionicPopup'
var loginData = NVR.getLogin();
- var apiRun = loginData.apiurl + "/host/daemonCheck.json";
- var apiLoad = loginData.apiurl + "/host/getLoad.json";
- var apiStorage = loginData.apiurl + "/storage.json";
- var apiServer = loginData.apiurl + "/servers.json";
- var apiCurrentState = loginData.apiurl + "/States.json";
+ var apiRun = loginData.apiurl + "/host/daemonCheck.json?"+$rootScope.authSession;
+ var apiLoad = loginData.apiurl + "/host/getLoad.json?"+$rootScope.authSession;
+ var apiStorage = loginData.apiurl + "/storage.json?"+$rootScope.authSession;
+ var apiServer = loginData.apiurl + "/servers.json?"+$rootScope.authSession;
+ var apiCurrentState = loginData.apiurl + "/States.json?"+$rootScope.authSession;
var apiExec = loginData.apiurl + "/states/change/";
@@ -120,7 +120,7 @@ $scope.toggleServer = function() {
$scope.$on('$ionicView.afterEnter', function () {
// console.log("**VIEW ** Montage Ctrl Entered");
- console.log("STATE SHORTCUT: " + JSON.stringify($stateParams));
+ // console.log("STATE SHORTCUT: " + JSON.stringify($stateParams));
$stateParams.shortcut && $stateParams.shortcut.fn &&
$scope[$stateParams.shortcut.fn]($stateParams.shortcut.fnargs); // jshint ignore:line
@@ -355,7 +355,7 @@ $scope.toggleServer = function() {
$scope.customState = "";
NVR.debug("StateCtrl/controlZM: POST Control command is " + apiExec + str + ".json");
inProgress = 1;
- $http.post(apiExec + str + ".json")
+ $http.post(apiExec + str + ".json?"+$rootScope.authSession)
.then(
function (success) {
NVR.debug("StateCtrl/controlZM: returned success with:"+JSON.stringify(success));
diff --git a/www/js/TimelineCtrl.js b/www/js/TimelineCtrl.js
index 78006f37..d2cc82ea 100644
--- a/www/js/TimelineCtrl.js
+++ b/www/js/TimelineCtrl.js
@@ -344,7 +344,8 @@ angular.module('zmApp.controllers').controller('zmApp.TimelineCtrl', ['$ionicPla
url: '',
eid: $translate.instant('kMonNone'),
time: $translate.instant('kMonNone'),
- monName: $translate.instant('kMonNone')
+ monName: $translate.instant('kMonNone'),
+ notes: ''
};
$scope.newEvents = '';
@@ -383,7 +384,7 @@ angular.module('zmApp.controllers').controller('zmApp.TimelineCtrl', ['$ionicPla
$timeout(function () {
var keyCode = evt.keyCode;
- console.log(keyCode + " PRESSED");
+ //console.log(keyCode + " PRESSED");
if (keyCode == keyCodes.UP) {
@@ -744,9 +745,13 @@ angular.module('zmApp.controllers').controller('zmApp.TimelineCtrl', ['$ionicPla
//
var completedEvents = ld.apiurl + '/events/index/EndTime >=:' + from;
// we can add alarmCount as this is really for completed events
- //completedEvents = completedEvents + "/AlarmFrames >=:" + (ld.enableAlarmCount ? ld.minAlarmCount : 0);
+ completedEvents = completedEvents + "/AlarmFrames >=:" + (ld.enableAlarmCount ? ld.minAlarmCount : 0);
- completedEvents = completedEvents + ".json";
+ if (ld.objectDetectionFilter) {
+ completedEvents = completedEvents + '/Notes REGEXP:"detected:"';
+ }
+
+ completedEvents = completedEvents + ".json?"+$rootScope.authSession;
// now get currently ongoing events
// as it turns out various events get stored withn null and never recover
@@ -755,7 +760,7 @@ angular.module('zmApp.controllers').controller('zmApp.TimelineCtrl', ['$ionicPla
var st = moment(lastTimeForEvent).tz(NVR.getTimeZoneNow());
st = st.subtract(10, 'minutes').locale('en').format("YYYY-MM-DD HH:mm:ss");
- var ongoingEvents = ld.apiurl + '/events/index/StartTime >=:' + st + '/EndTime =:.json';
+ var ongoingEvents = ld.apiurl + '/events/index/StartTime >=:' + st + '/EndTime =:.json?'+$rootScope.authSession;
//NVR.debug("Getting incremental events using: " + completedEvents);
NVR.debug("Completed events API:" + completedEvents);
@@ -1161,6 +1166,7 @@ angular.module('zmApp.controllers').controller('zmApp.TimelineCtrl', ['$ionicPla
for (var j = 0; j < data.length; j++) {
var myevents = data[j].events;
+
// console.log ("****************DATA ="+JSON.stringify(data[j]));
// console.log ("**********************************");
if (graphIndex > count) {
@@ -1175,6 +1181,11 @@ angular.module('zmApp.controllers').controller('zmApp.TimelineCtrl', ['$ionicPla
var idfound = true;
var ld = NVR.getLogin();
+ // skip non detections here because we can't query to DB due to page attribute
+ if (ld.objectDetectionFilter && myevents[i].Event.Notes.indexOf('detected:') == -1) {
+ continue;
+ }
+
if (ld.persistMontageOrder) {
idfound = false;
@@ -1358,7 +1369,7 @@ angular.module('zmApp.controllers').controller('zmApp.TimelineCtrl', ['$ionicPla
}
$scope.thumbnailClicked = function(event) {
- console.log ("Thumb tapped");
+ //console.log ("Thumb tapped");
if (!$scope.currentThumbEvent) {
// will this ever be? Don't think so
NVR.debug ("No thumb rendered");
@@ -1509,7 +1520,8 @@ angular.module('zmApp.controllers').controller('zmApp.TimelineCtrl', ['$ionicPla
url: stream,
eid: event.Event.Id,
time: prettifyTimeSec(event.Event.StartTime),
- monName: event.Event.MonitorName
+ monName: event.Event.MonitorName,
+ notes: event.Event.Notes
};
});
diff --git a/www/js/TimelineModalCtrl.js b/www/js/TimelineModalCtrl.js
index 0b7fb5cb..59210aa5 100644
--- a/www/js/TimelineModalCtrl.js
+++ b/www/js/TimelineModalCtrl.js
@@ -179,7 +179,7 @@ angular.module('zmApp.controllers').controller('TimelineModalCtrl', ['$scope', '
var eid = $scope.event.Event.Id;
//eid = 22302;
var ld = NVR.getLogin();
- var apiurl = ld.apiurl + "/events/" + eid + ".json";
+ var apiurl = ld.apiurl + "/events/" + eid + ".json?"+$rootScope.authSession;
NVR.log("Getting " + apiurl);
$http.get(apiurl)
.then(function (success) {
diff --git a/www/js/WizardCtrl.js b/www/js/WizardCtrl.js
index c1a2ca57..86c4cbe9 100644
--- a/www/js/WizardCtrl.js
+++ b/www/js/WizardCtrl.js
@@ -83,7 +83,7 @@ angular.module('zmApp.controllers').controller('zmApp.WizardCtrl', ['$scope', '$
function getFirstMonitor() {
var d = $q.defer();
- $http.get($scope.wizard.apiURL + "/monitors.json")
+ $http.get($scope.wizard.apiURL + "/monitors.json?"+$rootScope.authSession)
.then(function (success) {
// console.log("getfirst monitor success: " + JSON.stringify(success));
if (success.data.monitors.length > 0) {
@@ -202,7 +202,7 @@ angular.module('zmApp.controllers').controller('zmApp.WizardCtrl', ['$scope', '$
var urls = [a1, a2, a3, a4, a5];
// can't use getPathZms as loginData is not inited yet
- $http.get($scope.wizard.apiURL + "/configs/viewByName/ZM_PATH_ZMS.json")
+ $http.get($scope.wizard.apiURL + "/configs/viewByName/ZM_PATH_ZMS.json?"+$rootScope.authSession)
//NVR.getPathZms() // what does ZM have stored in PATH_ZMS?
.then(function (data) {
// remove zms or nph-zms
@@ -229,7 +229,7 @@ angular.module('zmApp.controllers').controller('zmApp.WizardCtrl', ['$scope', '$
getFirstMonitor()
.then(function (success) {
$ionicLoading.hide();
- var tail = "/nph-zms?mode=single&monitor=" + success;
+ var tail = "/nph-zms?mode=single&monitor=" + success;//+ $rootScope.authSession;
if ($scope.wizard.useauth && $scope.wizard.usezmauth) {
var ck = Math.floor(Math.random() * (50000 - 10000 + 1)) + 10000;
@@ -321,7 +321,7 @@ angular.module('zmApp.controllers').controller('zmApp.WizardCtrl', ['$scope', '$
// lets try both /zm/api and /api. What else is there?
var apilist = [api1, api2, api3];
- findFirstReachableUrl(apilist, '/host/getVersion.json')
+ findFirstReachableUrl(apilist, '/host/getVersion.json?'+$rootScope.authSession)
.then(function (success) {
NVR.log("Valid API response found with:" + success);
$scope.wizard.apiURL = success;
@@ -470,7 +470,7 @@ angular.module('zmApp.controllers').controller('zmApp.WizardCtrl', ['$scope', '$
data = data.data;
$ionicLoading.hide();
- console.log ("GOT "+data);
+ // console.log ("GOT "+data);
if (data.indexOf(zm.loginScreenString1) >=0 ||
data.indexOf(zm.loginScreenString2) >=0 ) {
@@ -578,7 +578,7 @@ angular.module('zmApp.controllers').controller('zmApp.WizardCtrl', ['$scope', '$
return d.promise;
}
NVR.debug("API based login returned... ");
- console.log (JSON.stringify(succ));
+ // console.log (JSON.stringify(succ));
$ionicLoading.hide();
//$rootScope.loggedIntoZm = 1;
$rootScope.authSession = '';
@@ -635,13 +635,13 @@ angular.module('zmApp.controllers').controller('zmApp.WizardCtrl', ['$scope', '$
},
function (err) {
- console.log("******************* API login error " + JSON.stringify(err));
+ NVR.debug("******************* API login error " + JSON.stringify(err));
$ionicLoading.hide();
if (1) {
//if (err && err.data && 'success' in err.data) {
- console.log("API based login not supported, need to use web scraping...");
+ NVR.log("API based login not supported, need to use web scraping...");
loginWebScrape(u,zmu,zmp)
.then(function (succ) {
@@ -678,6 +678,7 @@ angular.module('zmApp.controllers').controller('zmApp.WizardCtrl', ['$scope', '$
function validateData() {
+ //console.log ("***** CLEARING AUTHSESSION IN VALIDATEDATA");
$rootScope.authSession = '';
$rootScope.zmCookie = '';
diff --git a/www/js/app.js b/www/js/app.js
index c5428465..18bead17 100755
--- a/www/js/app.js
+++ b/www/js/app.js
@@ -111,7 +111,9 @@ angular.module('zmApp', [
zmVersionCheckNag: 60 * 24, // in hrs
waitTimeTillResume: 5, // in sec, for ES error
versionWithLoginAPI: "1.31.47",
- androidBackupKey: "AEdPqrEAAAAIqF-OaHdwIzZhx2L1WOfAGTagBxm5a1R4wBW_Uw"
+ androidBackupKey: "AEdPqrEAAAAIqF-OaHdwIzZhx2L1WOfAGTagBxm5a1R4wBW_Uw",
+ accessTokenLeewayMin: 5,
+ refreshTokenLeewayMin: 10
})
@@ -489,8 +491,8 @@ angular.module('zmApp', [
// This directive is adapted from https://github.com/paveisistemas/ionic-image-lazy-load
// I've removed lazyLoad and only made it show a spinner when an image is loading
//--------------------------------------------------------------------------------------------
- .directive('imageSpinnerSrc', ['$document', '$compile', 'imageLoadingDataShare', '$timeout', '$parse',
- function ($document, $compile, imageLoadingDataShare, $timeout, $parse) {
+ .directive('imageSpinnerSrc', ['$document', '$compile', 'imageLoadingDataShare', '$timeout', '$parse', 'NVR', '$rootScope',
+ function ($document, $compile, imageLoadingDataShare, $timeout, $parse, NVR, $rootScope) {
return {
restrict: 'A',
scope: {
@@ -616,7 +618,15 @@ angular.module('zmApp', [
bgImg.src = $attributes.imageSpinnerSrc;
} else {
- $element[0].src = $attributes.imageSpinnerSrc; // set src attribute on element (it will load image)
+
+ var ld = NVR.getLogin();
+ if (ld.isUseAuth && $rootScope.authSession=='' ) {
+ NVR.log ("waiting for authSession to have a value...");
+
+ } else {
+ $element[0].src = $attributes.imageSpinnerSrc; // set src
+ }
+
}
}
@@ -644,11 +654,10 @@ angular.module('zmApp', [
//------------------------------------------------------------------
.factory('timeoutHttpIntercept', ['$rootScope', '$q', 'zm', '$injector', function ($rootScope, $q, zm, $injector) {
$rootScope.zmCookie = "";
- //console.log ("HHHHHHHHHHHHHH**************************");
- //console.log ("HERE TIMEOUT");
+
return {
- 'request': function (config) {
+ request: function (config) {
if (!config) return config;
if (!config.url) return config;
@@ -657,32 +666,52 @@ angular.module('zmApp', [
config.headers.Authorization = $rootScope.basicAuthHeader;
}
- // handle basic auth properly
- if (config.url.indexOf("@") > -1) {
- NVR.debug(">>>>>>>>>> ERROR!!!!! url has a basic auth u:p!" + config.url);
-
- }
-
- // I don't think we need this - do we?
+ return config;
+ },
- /*
- if ((config.url.indexOf("/api/states/change/") > -1) ||
- (config.url.indexOf("getDiskPercent.json") > -1) ||
- (config.url.indexOf("daemonCheck.json") > -1) ||
- (config.url.indexOf("getLoad.json") > -1))
+ responseError: function (rejection) {
+ nvr = $injector.get('NVR');
+// console.log (JSON.stringify(rejection));
+ if (rejection.status == 401 && !rejection.config.skipIntercept) {
- {
+ /* rejection.data && rejection.data.data && rejection.data.data.message.indexOf('Token revoked') != -1) */
- // these can take time, so lets bump up timeout
- config.timeout = zm.largeHttpTimeout;
+ if (rejection && rejection.data && rejection.data.data) {
- }*/
+ console.log ("MESSAGE:"+rejection.data.data.message);
+ if (rejection.data.data.message.indexOf('API Disabled') != -1) {
+ $rootScope.apiValid = false;
+ return rejection;
+ }
+ }
+
- return config;
+
+
+ nvr.log ("Browser Http intecepted 401, will try reauth");
+ return nvr.proceedWithLogin({'nobroadcast':true, 'access':false, 'refresh':true})
+ .then (function(succ) {
+ nvr.log ("Interception proceedWithLogin completed, retrying old request with skipIntercept = true");
+ // console.log ("OLD URL-"+rejection.config.url );
+ rejection.config.url = rejection.config.url.replace(/&token=([^&]*)/, $rootScope.authSession);
+ rejection.config.skipIntercept = true;
+ // console.log ("NEW URL-"+rejection.config.url );
+ return $injector.get('$http')(rejection.config);
+ }, function (err) {
+ nvr.log ("Interception proceedWithLogin failed, NOT retrying old request");
+ return err;
+ });
+ }
+ else {
+ if (rejection.config.skipIntercept) nvr.log ("Not intercepting as skipIntercept true");
+ return rejection;
+ }
+
},
- 'response': function (response) {
+ response: function (response) {
+
var cookies = response.headers("Set-Cookie");
if (cookies != null) {
@@ -699,9 +728,10 @@ angular.module('zmApp', [
//console.log ("HTTP response");
+
if (response.data && typeof(response.data) == 'string' && (response.data.indexOf("<pre class=\"cake-error\">")==0)) {
- console.log ("cake error detected, attempting fix...");
+ NVR.debug ("cake error detected, attempting fix...");
//console.log ("BAD = "+ JSON.stringify(response.data));
response.data = JSON.parse(response.data.replace(/<pre class=\"cake-error\">[\s\S]*<\/pre>/,''));
// console.log ("FIXED="+JSON.stringify(response.data));
@@ -916,7 +946,8 @@ angular.module('zmApp', [
},
function (err) {
- console.log("AUTH HASH ERROR: " + JSON.stringify(conf));
+
+ NVR.debug("Auth Hash error: " + JSON.stringify(conf));
});
}
@@ -989,13 +1020,39 @@ angular.module('zmApp', [
return d.promise;
}
+
+ NVR.isReCaptcha()
+ .then(function (result) {
+ if (result == true) {
+ $ionicLoading.hide();
+
+ NVR.displayBanner('error', ['reCaptcha must be disabled', ], "", 8000);
+ var alertPopup = $ionicPopup.alert({
+ title: 'reCaptcha enabled',
+ template: $translate.instant('kRecaptcha'),
+ okText: $translate.instant('kButtonOk'),
+ cancelText: $translate.instant('kButtonCancel'),
+ });
+
+ // close it after 5 seconds
+ $timeout(function () {
+
+ alertPopup.close();
+ }, 5000);
+
+ d.reject("Error-disable recaptcha");
+ return (d.promise);
+ }
+
+ });
+
NVR.debug("Resetting zmCookie...");
$rootScope.zmCookie = '';
// first try to login, if it works, good
// else try to do reachability
//console.log(">>>>>>>>>>>> CALLING DO LOGIN");
- proceedWithLogin()
+ NVR.proceedWithLogin()
.then(function (success) {
//NVR.debug("Storing login time as " + moment().toString());
@@ -1014,7 +1071,7 @@ angular.module('zmApp', [
NVR.debug(">>>>>>>>>>>> Failed first login, trying reachability");
NVR.getReachableConfig(true)
.then(function (data) {
- proceedWithLogin()
+ NVR.proceedWithLogin()
.then(function (success) {
d.resolve(success);
$ionicLoading.hide();
@@ -1037,360 +1094,31 @@ angular.module('zmApp', [
return d.promise;
-
-
- function proceedWithLogin() {
- // 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();
- var ld = NVR.getLogin();
- NVR.log("zmAutologin called");
- var httpDelay = NVR.getLogin().enableSlowLoading ? zm.largeHttpTimeout : zm.httpTimeout;
-
- // This is a good time to check if auth is used :-p
- if (!ld.isUseAuth) {
- NVR.log("Auth is disabled, setting authSession to empty");
- $rootScope.apiValid = true;
- $rootScope.authSession = '';
- d.resolve("Login Success");
-
- $rootScope.$broadcast('auth-success', 'no auth');
- return (d.promise);
-
- }
-
- if (!str) str = $translate.instant('kAuthenticating');
-
- if (str) {
- $ionicLoading.show({
- template: str,
- noBackdrop: true,
- duration: httpDelay
- });
- }
-
- //console.log(">>>>>>>>>>>>>> ISRECAPTCHA");
-
- var loginData = NVR.getLogin();
- var currentServerVersion = NVR.getCurrentServerVersion();
-
-
- //first login using new API
- var loginAPI = loginData.apiurl + '/host/login.json';
-
-
- $http({
- method: 'post',
- url: loginAPI,
- timeout: httpDelay,
- 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) {
- NVR.debug("API login returned fake success, going back to webscrape");
- ld = NVR.getLogin();
- ld.loginAPISupported = false;
- NVR.setLogin(ld);
-
- loginWebScrape()
- .then(function (succ) {
- d.resolve("Login Success");
- return d.promise;
- },
- function (err) {
- $ionicLoading.hide();
- d.reject("Login Error");
- return (d.promise);
- });
- return d.promise;
- }
- NVR.debug("API based login returned... ");
- console.log (JSON.stringify(succ));
- NVR.setCurrentServerVersion(succ.version);
- $ionicLoading.hide();
- //$rootScope.loggedIntoZm = 1;
- $rootScope.authSession = '';
-
- if (succ.credentials) {
- $rootScope.authSession = "&" + succ.credentials;
- if (succ.append_password == '1') {
- $rootScope.authSession = $rootScope.authSession +
- loginData.password;
- }
- }
-
- var ldg = NVR.getLogin();
- ldg.loginAPISupported = true;
- NVR.setLogin(ldg);
-
- NVR.log("Stream authentication construction: " +
- $rootScope.authSession);
-
- NVR.log("zmAutologin successfully logged into Zoneminder via API");
-
-
-
- d.resolve("Login Success");
- $rootScope.$broadcast('auth-success', succ);
- return d.promise;
-
- } catch (e) {
- NVR.debug("Login API approach did not work...");
- ld = NVR.getLogin();
- ld.loginAPISupported = false;
- NVR.setLogin(ld);
- loginWebScrape()
- .then(function (succ) {
- 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 (1) {
- //if (err && err.data && 'success' in err.data) {
- console.log("API based login not supported, need to use web scraping...");
- // login using old web scraping
- var ld = NVR.getLogin();
- ld.loginAPISupported = false;
- NVR.setLogin(ld);
- loginWebScrape()
- .then(function (succ) {
- d.resolve("Login Success");
- return d.promise;
- },
- function (err) {
- d.reject("Login Error");
- return (d.promise);
- });
-
-
- } else {
- // $rootScope.loggedIntoZm = -1;
- //console.log("**** ZM Login FAILED");
- NVR.log("zmAutologin Error via API: some meta foo", "error");
- $rootScope.$broadcast('auth-error', "I'm confused why");
-
- d.reject("Login Error");
- return (d.promise);
-
- }
-
-
- }
- ); // post
-
-
-
- return d.promise;
- }
-
- return d.promise;
+
}
- function loginWebScrape() {
- var loginData = NVR.getLogin();
- var d = $q.defer();
- NVR.debug("Logging in using old web-scrape method");
-
- $ionicLoading.show({
- template: $translate.instant('kAuthenticatingWebScrape'),
- noBackdrop: true,
- duration: httpDelay
- });
-
-
- NVR.isReCaptcha()
- .then(function (result) {
- if (result == true) {
- $ionicLoading.hide();
- NVR.displayBanner('error', ['reCaptcha must be disabled', ], "", 8000);
- $ionicLoading.hide();
- var alertPopup = $ionicPopup.alert({
- title: 'reCaptcha enabled',
- template: $translate.instant('kRecaptcha'),
- okText: $translate.instant('kButtonOk'),
- cancelText: $translate.instant('kButtonCancel'),
- });
-
- // close it after 5 seconds
- $timeout(function () {
-
- alertPopup.close();
- }, 5000);
-
- d.reject("Error-disable recaptcha");
- return (d.promise);
- }
-
- });
-
- var httpDelay = NVR.getLogin().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',
- 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 ||
- data.indexOf(zm.loginScreenString2) >=0 ) {
- //eventServer.start();
- //$rootScope.loggedIntoZm = 1;
-
- NVR.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");
- NVR.log("zmAutologin Error: Bad Credentials ", "error");
- $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
- $rootScope.authSession = '';
- var ld = NVR.getLogin();
- NVR.getAuthKey($rootScope.validMonitorId)
- .then(function (success) {
-
- //console.log(success);
- $rootScope.authSession = success;
- NVR.log("Stream authentication construction: " +
- $rootScope.authSession);
- d.resolve("Login Success");
- $rootScope.$broadcast('auth-success', data);
- return d.promise;
-
- },
- function (error) {
- //console.log(error);
-
- NVR.log("Modal: Error returned Stream authentication construction. Retaining old value of: " + $rootScope.authSession);
- NVR.debug("Error was: " + JSON.stringify(error));
- d.resolve("Login Success");
- $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
-
- NVR.log("zmAutologin Error " + JSON.stringify(error) + " and status " + status);
- // bad urls etc come here
- //$rootScope.loggedIntoZm = -1;
- $rootScope.$broadcast('auth-error', error);
- d.reject("Login Error");
- return d.promise;
- });
- return d.promise;
- }
+
function start() {
var ld = NVR.getLogin();
// lets keep this timer irrespective of auth or no auth
//$rootScope.loggedIntoZm = 0;
- $interval.cancel(zmAutoLoginHandle);
- //doLogin();
- zmAutoLoginHandle = $interval(function () {
- _doLogin("");
- }, zm.loginInterval); // Auto login every 5 minutes
- // PHP timeout is around 10 minutes
- // should be ok?
+ if (!ld.isTokenSupported) {
+ $interval.cancel(zmAutoLoginHandle);
+ //doLogin();
+ zmAutoLoginHandle = $interval(function () {
+ _doLogin("");
+
+ }, zm.loginInterval); // Auto login every 5 minutes
+ // PHP timeout is around 10 minutes
+ // should be ok?
+ } else {
+ NVR.log ("Disabling login timer, as we are using tokens");
+ }
+
}
@@ -1443,7 +1171,7 @@ angular.module('zmApp', [
$rootScope.dpadId = 0;
$rootScope.textScaleFactor = 1.0;
$rootScope.isLoggedIn = false;
- $rootScope.apiValid = false;
+ $rootScope.apiValid = true;
$rootScope.db = null;
$rootScope.runMode = NVR.getBandwidth();
@@ -1508,6 +1236,11 @@ angular.module('zmApp', [
NVR.debug(msg);
};
+
+ $rootScope.proceedWithLogin = function(obj) {
+ return NVR.proceedWithLogin(obj);
+ };
+
// DPAD Handler - disabled for now
// when ready add ionic cordova plugin add https://github.com/pliablepixels/cordova-plugin-android-tv.git
@@ -1557,7 +1290,7 @@ angular.module('zmApp', [
$rootScope.dpadId = 0;
$rootScope.dpadState = $state.current.name.replace('app.', "");
}
- console.log("dpad State is: " + $rootScope.dpadState);
+ //console.log("dpad State is: " + $rootScope.dpadState);
handled = true;
} else if (keyCode == keyCodes.SELECT) { // select
if ($rootScope.dpadId > 0) {
@@ -1608,7 +1341,7 @@ angular.module('zmApp', [
nextel[0].scrollIntoView();
$rootScope.dpadId = nextId;
}
- console.log("dpadID=" + $rootScope.dpadId + " with state=" + $rootScope.dpadState);
+ // console.log("dpadID=" + $rootScope.dpadId + " with state=" + $rootScope.dpadState);
}
handled = true;
}
@@ -2122,7 +1855,7 @@ angular.module('zmApp', [
localforage.getItem('last-desktop-state')
.then(function (succ) {
- console.log("FOUND STATE" + JSON.stringify(succ) + ":" + succ);
+ //console.log("FOUND STATE" + JSON.stringify(succ) + ":" + succ);
if (succ == null) succ = {name:"app.montage"};
@@ -2156,7 +1889,7 @@ angular.module('zmApp', [
loadServices();
}, function (err) {
- console.log("ERR " + JSON.stringify(err));
+ // console.log("ERR " + JSON.stringify(err));
$rootScope.lastState = "app.montage";
loadServices();
});
@@ -2166,7 +1899,7 @@ angular.module('zmApp', [
NVR.log("Language file loaded, continuing with rest");
NVR.init();
zmCheckUpdates.start();
- NVR.log("Setting up POST LOGIN timer");
+ // NVR.log("Setting up POST LOGIN timer");
zmAutoLogin.start();
setupPauseAndResume();
@@ -2343,7 +2076,8 @@ angular.module('zmApp', [
$provide.decorator('$http', ['$delegate', '$q', '$injector', function ($delegate, $q, $injector) {
// create function which overrides $http function
var $http = $delegate;
- var logger = $injector.get("$rootScope");
+ var nvr = $injector.get("$rootScope");
+
var wrapper = function () {
var url;
@@ -2358,6 +2092,8 @@ angular.module('zmApp', [
var d = $q.defer();
+ var skipIntercept = arguments[0].skipIntercept || false;
+
var dataPayload = {};
if (arguments[0].data !== undefined) {
dataPayload = arguments[0].data;
@@ -2368,7 +2104,8 @@ angular.module('zmApp', [
data: dataPayload,
headers: arguments[0].headers,
// timeout: arguments[0].timeout,
- responseType: arguments[0].responseType
+ responseType: arguments[0].responseType,
+ skipIntercept:skipIntercept
};
if (arguments[0].timeout) options.timeout = arguments[0].timeout;
@@ -2382,7 +2119,7 @@ angular.module('zmApp', [
// console.log ("HTTP RESPONSE:" + JSON.stringify(succ.data));
if (succ.data && (succ.data.indexOf("<pre class=\"cake-error\">") == 0) ) {
- logger.debug ("**** Native: cake-error in message, trying fix...");
+ nvr.debug ("**** Native: cake-error in message, trying fix...");
succ.data = JSON.parse(succ.data.replace(/<pre class=\"cake-error\">[\s\S]*<\/pre>/,''));
}
@@ -2413,10 +2150,45 @@ angular.module('zmApp', [
}
},
function (err) {
- logger.debug("*** Inside native HTTP error: " + JSON.stringify(err));
-
- d.reject(err);
- return d.promise;
+
+ nvr.debug("*** Inside native HTTP error");
+ if (err.status == 401 && !options.skipIntercept && nvr.apiValid) {
+ if (err.error && err.error.indexOf("API is disabled for user") != -1) {
+ nvr.apiValid = false;
+ nvr.debug ("Setting API to "+nvr.apiValid);
+ d.reject(err);
+ return d.promise;
+
+ }
+ nvr.debug ("** Native intercept: Got 401, going to try logging in");
+ return nvr.proceedWithLogin({'nobroadcast':true, 'access':false, 'refresh':true})
+ .then (function(succ) {
+ nvr.debug ("** Native, tokens generated, retrying old request with skipIntercept = true");
+ //console.log ("I GOT: "+ JSON.stringify(succ));
+ url = url.replace(/&token=([^&]*)/, nvr.authSession);
+ options.skipIntercept = true;
+ cordova.plugin.http.sendRequest(encodeURI(url), options,
+ function (succ) {
+ d.resolve(succ);
+ return d.promise;
+ },
+ function (err) {
+ d.reject(err);
+ return d.promise;
+
+ });
+ return d.promise;
+ }, function (err) {d.reject(err); return d.promise;});
+ }
+ else {
+ if (options.skipIntercept) {
+ nvr.debug ("Not intercepting as skipIntercept is true");
+ }
+ // not a 401, so pass on rejection
+ d.reject(err);
+ return d.promise;
+ }
+
});
return d.promise;
diff --git a/www/templates/timeline.html b/www/templates/timeline.html
index e3fa40a5..0a0d399f 100644
--- a/www/templates/timeline.html
+++ b/www/templates/timeline.html
@@ -58,6 +58,7 @@
<img ng-src="{{thumbData.url}}" fallback-src="img/noimage.png" width="400px" on-tap="thumbnailClicked($event)"/>
</figure>
+ <p>{{thumbData.notes}}</p>
</div>