From 576d9058a4afb2a179f8c6a338f9b6c08108822b Mon Sep 17 00:00:00 2001 From: Pliable Pixels Date: Tue, 14 May 2019 13:33:00 -0400 Subject: initial support for tokens #817 --- www/js/app.js | 174 ++++++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 122 insertions(+), 52 deletions(-) (limited to 'www/js/app.js') diff --git a/www/js/app.js b/www/js/app.js index c5428465..f64ea1da 100755 --- a/www/js/app.js +++ b/www/js/app.js @@ -1040,20 +1040,12 @@ angular.module('zmApp', [ 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) { + // 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 = ''; @@ -1064,6 +1056,75 @@ angular.module('zmApp', [ } + + // lets first try tokens and stored tokens + if (ld.isTokenSupported) { + NVR.log ("Detected token login supported"); + var now = moment.utc(); + var diff_access = moment.utc(ld.accessTokenExpires).diff(now, 'minutes'); + var diff_refresh = moment.utc(ld.refreshTokenExpires).diff(now, 'minutes'); + + // first see if we can work with access token + if (moment.utc(ld.accessTokenExpires).isAfter(now) && diff_access >=30) { + NVR.log ("Access token still has "+diff_access+" minutes left, using it"); + $rootScope.authSession = '&token='+ld.accessToken; + d.resolve("Login success via access token"); + $rootScope.$broadcast('auth-success', '' ); + return d.promise; + } + // then see if we have at least 30 mins left for refresh token + else if (moment.utc(ld.refreshTokenExpires).isAfter(now) && diff_refresh >=30) { + NVR.log ("Refresh token still has "+diff_refresh+" minutes left, using it"); + var loginAPI = loginData.apiurl + '/host/login.json?token='+ld.refreshToken; + $http.get($loginAPI) + .then (function (succ) { + succ = succ.data; + if (succ.access_token) { + $rootScope.authSession = '&token='+succ.access_token; + NVR.log ("New access token retrieved:"+succ.access_token); + ld.accessToken = succ.access_token; + ld.accessTokenExpires = moment.utc().add(succ.access_token_expires,'seconds'); + NVR.log ("Current time is: UTC "+moment.utc().format("YYYY-MM-DD hh:mm:ss")); + NVR.log ("New access token expires on: UTC "+ld.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss")); + NVR.log ("New access token expires on:"+ld.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss")); + ld.isTokenSupported = true; + NVR.setLogin(ld); + d.resolve("Login success via refresh token"); + $rootScope.$broadcast('auth-success', '' ); + return d.promise; + } + else { + NVR.log ('ERROR:Trying to refresh with refresh token:'+JSON.stringify(succ)); + return proceedWithFreshLogin(); + + } + }, + function (err) { + NVR.log ('access token login HTTP failed with: '+JSON.stringify(err)); + return proceedWithFreshLogin(); + }); + } // valid refresh + + } // is token supported + NVR.log ("Token login not being used"); + // coming here means token reloads fell through + return proceedWithFreshLogin(); + } + + function proceedWithFreshLogin() { + // 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("Doing fresh login to ZM"); + var httpDelay = NVR.getLogin().enableSlowLoading ? zm.largeHttpTimeout : zm.httpTimeout; + + if (!str) str = $translate.instant('kAuthenticating'); if (str) { @@ -1081,9 +1142,11 @@ angular.module('zmApp', [ //first login using new API + $rootScope.authSession = ''; var loginAPI = loginData.apiurl + '/host/login.json'; + $http({ method: 'post', url: loginAPI, @@ -1108,10 +1171,7 @@ angular.module('zmApp', [ .then(function (textsucc) { $ionicLoading.hide(); - var succ; - - try { succ = JSON.parse(textsucc.data); @@ -1141,13 +1201,39 @@ angular.module('zmApp', [ //$rootScope.loggedIntoZm = 1; $rootScope.authSession = ''; - if (succ.credentials) { - $rootScope.authSession = "&" + succ.credentials; - if (succ.append_password == '1') { - $rootScope.authSession = $rootScope.authSession + - loginData.password; + if (succ.refresh_token) { + $rootScope.authSession = '&token='+succ.access_token; + NVR.log ("New refresh token retrieved:"+succ.refresh_token); + ld.isTokenSupported = true; + + ld.accessToken = succ.access_token; + ld.accessTokenExpires = moment.utc().add(succ.access_token_expires, 'seconds'); + ld.refreshToken = succ.refresh_token; + + ld.refreshTokenExpires = moment.utc().add(succ.refresh_token_expires, 'seconds'); + + NVR.log ("Current time is: UTC "+moment.utc().format("YYYY-MM-DD hh:mm:ss")); + NVR.log ("New refresh token expires on: UTC "+ld.refreshTokenExpires.format("YYYY-MM-DD hh:mm:ss")); + NVR.log ("New access token expires on: UTC "+ld.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss")); + NVR.setLogin(ld); + + } + else { + if (succ.credentials) { + NVR.log ("Could not recover token details, trying old auth credentials"); + ld.isTokenSupported = false; + NVR.setLogin(ld); + $rootScope.authSession = "&" + succ.credentials; + if (succ.append_password == '1') { + $rootScope.authSession = $rootScope.authSession + + loginData.password; + } + } + else { + NVR.log ("Neither token nor old cred worked. Seems like an error"); } } + var ldg = NVR.getLogin(); ldg.loginAPISupported = true; @@ -1166,8 +1252,10 @@ angular.module('zmApp', [ } catch (e) { NVR.debug("Login API approach did not work..."); + ld = NVR.getLogin(); ld.loginAPISupported = false; + ld.isTokenSupported = false; NVR.setLogin(ld); loginWebScrape() .then(function (succ) { @@ -1189,42 +1277,24 @@ angular.module('zmApp', [ 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); - - } - + //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); + }); } - ); // post - - + ); // post .then return d.promise; } -- cgit v1.2.3 From 151b26e60a18ccdc4231b2ce52abf864848eaa90 Mon Sep 17 00:00:00 2001 From: Pliable Pixels Date: Tue, 14 May 2019 14:40:12 -0400 Subject: #817 initial interceptor code for expiry (Mobile tbd) --- www/js/app.js | 95 +++++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 59 insertions(+), 36 deletions(-) (limited to 'www/js/app.js') diff --git a/www/js/app.js b/www/js/app.js index f64ea1da..3cdf49da 100755 --- a/www/js/app.js +++ b/www/js/app.js @@ -648,7 +648,7 @@ angular.module('zmApp', [ //console.log ("HERE TIMEOUT"); return { - 'request': function (config) { + request: function (config) { if (!config) return config; if (!config.url) return config; @@ -682,7 +682,25 @@ angular.module('zmApp', [ return config; }, - 'response': function (response) { + responseError: function (rejection) { + if (rejection.status == 401) { + nvr = $injector.get('NVR'); + nvr.log ("******** INTERCEPTOR CAUGHT ERROR, RE-LOGIN NEEDED"); + + return nvr.recreateTokens() + .then (function() { + return $injector.get('$http')(rejection.config); + }) + } + else { + nvr.log ("NOT 401"); + return response; + } + + }, + + response: function (response) { + var cookies = response.headers("Set-Cookie"); if (cookies != null) { @@ -699,6 +717,7 @@ angular.module('zmApp', [ //console.log ("HTTP response"); + if (response.data && typeof(response.data) == 'string' && (response.data.indexOf("
")==0)) {
             console.log ("cake error detected, attempting fix...");
@@ -1037,7 +1056,7 @@ angular.module('zmApp', [
 
       return d.promise;
 
-
+      
 
       function proceedWithLogin() {
 
@@ -1065,7 +1084,7 @@ angular.module('zmApp', [
           var diff_refresh = moment.utc(ld.refreshTokenExpires).diff(now, 'minutes');
 
           // first see if we can work with access token
-          if (moment.utc(ld.accessTokenExpires).isAfter(now) &&  diff_access  >=30) {
+          if (moment.utc(ld.accessTokenExpires).isAfter(now) &&  diff_access  >=5) {
             NVR.log ("Access token still has "+diff_access+" minutes left, using it");
             $rootScope.authSession = '&token='+ld.accessToken;
             d.resolve("Login success via access token");
@@ -1075,8 +1094,8 @@ angular.module('zmApp', [
           // then see if we have at least 30 mins left for refresh token
           else if (moment.utc(ld.refreshTokenExpires).isAfter(now) &&  diff_refresh  >=30) {
             NVR.log ("Refresh token still has "+diff_refresh+" minutes left, using it");
-            var loginAPI = loginData.apiurl + '/host/login.json?token='+ld.refreshToken;
-            $http.get($loginAPI)
+            var loginAPI = ld.apiurl + '/host/login.json?token='+ld.refreshToken;
+            $http.get(loginAPI)
             .then (function (succ) {
               succ = succ.data;
               if (succ.access_token) {
@@ -1116,17 +1135,17 @@ angular.module('zmApp', [
         // 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("Doing fresh login to ZM");
         var httpDelay = NVR.getLogin().enableSlowLoading ? zm.largeHttpTimeout : zm.httpTimeout;
-
+  
        
         if (!str) str = $translate.instant('kAuthenticating');
-
+  
         if (str) {
           $ionicLoading.show({
             template: str,
@@ -1134,19 +1153,19 @@ angular.module('zmApp', [
             duration: httpDelay
           });
         }
-
+  
         //console.log(">>>>>>>>>>>>>> ISRECAPTCHA");
-
+  
         var loginData = NVR.getLogin();
         var currentServerVersion = NVR.getCurrentServerVersion();
-
-
+  
+  
         //first login using new API
         $rootScope.authSession = '';
         var loginAPI = loginData.apiurl + '/host/login.json';
-
-
-
+  
+  
+  
         $http({
             method: 'post',
             url: loginAPI,
@@ -1169,19 +1188,19 @@ angular.module('zmApp', [
           })
           //$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");
@@ -1200,7 +1219,7 @@ angular.module('zmApp', [
                 $ionicLoading.hide();
                 //$rootScope.loggedIntoZm = 1;
                 $rootScope.authSession = '';
-
+  
                 if (succ.refresh_token) {
                   $rootScope.authSession = '&token='+succ.access_token;
                   NVR.log ("New refresh token retrieved:"+succ.refresh_token);
@@ -1216,7 +1235,7 @@ angular.module('zmApp', [
                   NVR.log ("New refresh token expires on: UTC "+ld.refreshTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
                   NVR.log ("New access token expires on: UTC "+ld.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
                   NVR.setLogin(ld);
-
+  
                 }
                 else {
                   if (succ.credentials) {
@@ -1234,22 +1253,22 @@ angular.module('zmApp', [
                   }
                 }
                 
-
+  
                 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...");
                
@@ -1268,11 +1287,11 @@ angular.module('zmApp', [
                       return (d.promise);
                     });
                 return d.promise;
-
+  
               }
-
-
-
+  
+  
+  
             },
             function (err) {
               console.log("******************* API login error " + JSON.stringify(err));
@@ -1292,17 +1311,21 @@ angular.module('zmApp', [
                     d.reject("Login Error");
                     return (d.promise);
                   });
-
+  
             }
           ); // post .then
-
+  
         return d.promise;
       }
 
+
       return d.promise;
 
     }
 
+
+ 
+
     function loginWebScrape() {
       var loginData = NVR.getLogin();
       var d = $q.defer();
-- 
cgit v1.2.3


From eb327c9b7cbca93c7fee43b3a25e47112ba7c595 Mon Sep 17 00:00:00 2001
From: Pliable Pixels 
Date: Wed, 15 May 2019 09:57:02 -0400
Subject: add token support to PTZ and stream control #817

---
 www/js/app.js | 59 +++++++++++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 45 insertions(+), 14 deletions(-)

(limited to 'www/js/app.js')

diff --git a/www/js/app.js b/www/js/app.js
index 3cdf49da..cf95a600 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: 30
 
   })
 
@@ -685,15 +687,17 @@ angular.module('zmApp', [
       responseError: function (rejection) {
         if (rejection.status == 401) {
           nvr = $injector.get('NVR');
-          nvr.log ("******** INTERCEPTOR CAUGHT ERROR, RE-LOGIN NEEDED");
-         
+          nvr.log ("Browser Http intecepted 401, will try reauth");
           return nvr.recreateTokens()
-          .then (function() {
+          .then (function(succ) {
+
+            rejection.config.url = rejection.config.url.replace(/&token=([^&]*)/, $rootScope.authSession);
             return $injector.get('$http')(rejection.config);
-          })
+          }, function (err) {
+            return response;
+          });
         } 
         else {
-          nvr.log ("NOT 401");
           return response;
         }
         
@@ -1084,7 +1088,7 @@ angular.module('zmApp', [
           var diff_refresh = moment.utc(ld.refreshTokenExpires).diff(now, 'minutes');
 
           // first see if we can work with access token
-          if (moment.utc(ld.accessTokenExpires).isAfter(now) &&  diff_access  >=5) {
+          if (moment.utc(ld.accessTokenExpires).isAfter(now) &&  diff_access  >=zm.accessTokenLeewayMin) {
             NVR.log ("Access token still has "+diff_access+" minutes left, using it");
             $rootScope.authSession = '&token='+ld.accessToken;
             d.resolve("Login success via access token");
@@ -1092,7 +1096,7 @@ angular.module('zmApp', [
             return d.promise;
           } 
           // then see if we have at least 30 mins left for refresh token
-          else if (moment.utc(ld.refreshTokenExpires).isAfter(now) &&  diff_refresh  >=30) {
+          else if (moment.utc(ld.refreshTokenExpires).isAfter(now) &&  diff_refresh  >=zm.refreshTokenLeewayMin) {
             NVR.log ("Refresh token still has "+diff_refresh+" minutes left, using it");
             var loginAPI = ld.apiurl + '/host/login.json?token='+ld.refreshToken;
             $http.get(loginAPI)
@@ -1601,6 +1605,10 @@ angular.module('zmApp', [
         NVR.debug(msg);
       };
 
+      $rootScope.recreateTokens = function() {
+        return NVR.recreateTokens();
+      };
+
      
       // DPAD Handler - disabled for now
       // when ready add ionic cordova plugin add https://github.com/pliablepixels/cordova-plugin-android-tv.git
@@ -2436,7 +2444,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;
@@ -2475,7 +2484,7 @@ angular.module('zmApp', [
 
                   // console.log ("HTTP RESPONSE:" + JSON.stringify(succ.data));
                    if (succ.data && (succ.data.indexOf("
") == 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(/
[\s\S]*<\/pre>/,''));
                   }
 
@@ -2506,10 +2515,32 @@ angular.module('zmApp', [
               }
             },
             function (err) {
-              logger.debug("***  Inside native HTTP error: " + JSON.stringify(err));
-
-              d.reject(err);
-              return d.promise;
+              var d = $q.defer();
+              nvr.debug("***  Inside native HTTP error: " + JSON.stringify(err));
+              if (err.status == 401) {
+                nvr.debug ("** Native intercept: Got 401, going to try recreating tokens");
+                return nvr.recreateTokens()
+                .then (function() {
+                          nvr.debug ("** Native, tokens generated, retrying old request");
+                          url = url.replace(/&token=([^&]*)/, nvr.authSession);
+                          cordova.plugin.http.sendRequest(encodeURI(url), options, 
+                          function (succ) {
+                            d.resolve(succ);
+                            return d.promise;
+                          }, 
+                          function (err) {
+                            d.resolve(err);
+                            return d.promise;
+                          });
+                          return d.promise;
+                }, function (err) {d.reject(err); return d.promise;});
+              }
+              else {
+                // not a 401, so pass on rejection
+                d.reject(err);
+                return d.promise;
+              }
+              
             });
           return d.promise;
 
-- 
cgit v1.2.3


From 36725a09b94b37ebfcd17f8909070745482728b0 Mon Sep 17 00:00:00 2001
From: Pliable Pixels 
Date: Wed, 15 May 2019 10:44:45 -0400
Subject: typo #817

---
 www/js/app.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

(limited to 'www/js/app.js')

diff --git a/www/js/app.js b/www/js/app.js
index cf95a600..c8e59138 100755
--- a/www/js/app.js
+++ b/www/js/app.js
@@ -694,11 +694,11 @@ angular.module('zmApp', [
             rejection.config.url = rejection.config.url.replace(/&token=([^&]*)/, $rootScope.authSession);
             return $injector.get('$http')(rejection.config);
           }, function (err) {
-            return response;
+            return err;
           });
         } 
         else {
-          return response;
+          return rejection;
         }
         
       },
-- 
cgit v1.2.3


From 2965a63388508a58ba141e743092661f6ebf6601 Mon Sep 17 00:00:00 2001
From: Pliable Pixels 
Date: Wed, 15 May 2019 14:23:09 -0400
Subject: #817 no need to relogin with timer for tokens

---
 www/js/app.js | 20 +++++++++++++-------
 1 file changed, 13 insertions(+), 7 deletions(-)

(limited to 'www/js/app.js')

diff --git a/www/js/app.js b/www/js/app.js
index c8e59138..9df47f23 100755
--- a/www/js/app.js
+++ b/www/js/app.js
@@ -1480,14 +1480,20 @@ angular.module('zmApp', [
       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");
+      }
+        
 
     }
 
-- 
cgit v1.2.3


From dffe5d2c0b7969a0ce5f7af4a3719b43c0d1320f Mon Sep 17 00:00:00 2001
From: Pliable Pixels 
Date: Wed, 15 May 2019 16:41:13 -0400
Subject: #817 don't update image if authSession is being negotiated

---
 www/js/app.js | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)

(limited to 'www/js/app.js')

diff --git a/www/js/app.js b/www/js/app.js
index 9df47f23..303467be 100755
--- a/www/js/app.js
+++ b/www/js/app.js
@@ -491,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: {
@@ -618,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 
+              }
+          
 
             }
           }
-- 
cgit v1.2.3


From f2f6040847b53222e4ca18334fc0978853c4b345 Mon Sep 17 00:00:00 2001
From: Pliable Pixels 
Date: Thu, 16 May 2019 10:48:21 -0400
Subject: #817 reduce some logs, fix return without promise error

---
 www/js/app.js | 40 +++++++++-------------------------------
 1 file changed, 9 insertions(+), 31 deletions(-)

(limited to 'www/js/app.js')

diff --git a/www/js/app.js b/www/js/app.js
index 303467be..989bd99b 100755
--- a/www/js/app.js
+++ b/www/js/app.js
@@ -654,8 +654,7 @@ 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) {
@@ -667,27 +666,6 @@ 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?
-
-        /*
-        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))
-
-        {
-
-          // these can take time, so lets bump up timeout
-          config.timeout = zm.largeHttpTimeout;
-
-        }*/
 
         return config;
       },
@@ -1112,7 +1090,7 @@ angular.module('zmApp', [
               succ = succ.data;
               if (succ.access_token) {
                 $rootScope.authSession = '&token='+succ.access_token;
-                NVR.log ("New access token retrieved:"+succ.access_token);
+                NVR.log ("New access token retrieved: ..."+succ.access_token.substr(-5));
                 ld.accessToken = succ.access_token;
                 ld.accessTokenExpires = moment.utc().add(succ.access_token_expires,'seconds');
                 NVR.log ("Current time is: UTC "+moment.utc().format("YYYY-MM-DD hh:mm:ss"));
@@ -1135,8 +1113,8 @@ angular.module('zmApp', [
                 return proceedWithFreshLogin();
             });
           } // valid refresh
-
-        } // is token supported
+            return d.promise;
+          } // is token supported
         NVR.log ("Token login not being used");
         // coming here means token reloads fell through
         return proceedWithFreshLogin();
@@ -1225,8 +1203,8 @@ angular.module('zmApp', [
                       });
                   return d.promise;
                 }
-                NVR.debug("API based login returned... ");
-                console.log (JSON.stringify(succ));
+                NVR.debug("API based login returned. ");
+                //console.log (JSON.stringify(succ));
                 NVR.setCurrentServerVersion(succ.version);
                 $ionicLoading.hide();
                 //$rootScope.loggedIntoZm = 1;
@@ -1234,7 +1212,7 @@ angular.module('zmApp', [
   
                 if (succ.refresh_token) {
                   $rootScope.authSession = '&token='+succ.access_token;
-                  NVR.log ("New refresh token retrieved:"+succ.refresh_token);
+                  NVR.log ("New refresh token retrieved: ..."+succ.refresh_token.substr(-5));
                   ld.isTokenSupported = true;
                
                   ld.accessToken = succ.access_token;
@@ -2237,7 +2215,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"};
 
@@ -2281,7 +2259,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();
 
-- 
cgit v1.2.3


From 12c8516a9f8151f22588d4a0fb42530b85265c6f Mon Sep 17 00:00:00 2001
From: Pliable Pixels 
Date: Sat, 18 May 2019 13:29:28 -0400
Subject: #817 various intercept fixes

---
 www/js/app.js | 483 +++++++---------------------------------------------------
 1 file changed, 59 insertions(+), 424 deletions(-)

(limited to 'www/js/app.js')

diff --git a/www/js/app.js b/www/js/app.js
index 989bd99b..dd6a3ce4 100755
--- a/www/js/app.js
+++ b/www/js/app.js
@@ -671,19 +671,29 @@ angular.module('zmApp', [
       },
 
       responseError: function (rejection) {
-        if (rejection.status == 401) {
-          nvr = $injector.get('NVR');
+        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) */
+
+          console.log ("MESSAGE:"+rejection.data.data.message);
+    
           nvr.log ("Browser Http intecepted 401, will try reauth");
-          return nvr.recreateTokens()
+          return nvr.proceedWithLogin({'nobroadcast':true, 'access':false, 'refresh':true})
           .then (function(succ) {
-
+            nvr.log ("Interception proceedWithLogin completed, retrying old request");
+           // console.log ("OLD URL-"+rejection.config.url );
             rejection.config.url = rejection.config.url.replace(/&token=([^&]*)/, $rootScope.authSession);
+          //  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;
         }
         
@@ -998,13 +1008,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());
@@ -1023,7 +1059,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();
@@ -1046,422 +1082,13 @@ angular.module('zmApp', [
 
       return d.promise;
 
-      
-
-      function proceedWithLogin() {
-
-        var d = $q.defer();
-        var ld = NVR.getLogin();
-
-         // 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);
-
-        }
-
-
-        // lets first try tokens and stored tokens
-        if (ld.isTokenSupported) {
-          NVR.log ("Detected token login supported");
-          var now = moment.utc();
-          var diff_access = moment.utc(ld.accessTokenExpires).diff(now, 'minutes');
-          var diff_refresh = moment.utc(ld.refreshTokenExpires).diff(now, 'minutes');
-
-          // first see if we can work with access token
-          if (moment.utc(ld.accessTokenExpires).isAfter(now) &&  diff_access  >=zm.accessTokenLeewayMin) {
-            NVR.log ("Access token still has "+diff_access+" minutes left, using it");
-            $rootScope.authSession = '&token='+ld.accessToken;
-            d.resolve("Login success via access token");
-            $rootScope.$broadcast('auth-success', ''  );
-            return d.promise;
-          } 
-          // then see if we have at least 30 mins left for refresh token
-          else if (moment.utc(ld.refreshTokenExpires).isAfter(now) &&  diff_refresh  >=zm.refreshTokenLeewayMin) {
-            NVR.log ("Refresh token still has "+diff_refresh+" minutes left, using it");
-            var loginAPI = ld.apiurl + '/host/login.json?token='+ld.refreshToken;
-            $http.get(loginAPI)
-            .then (function (succ) {
-              succ = succ.data;
-              if (succ.access_token) {
-                $rootScope.authSession = '&token='+succ.access_token;
-                NVR.log ("New access token retrieved: ..."+succ.access_token.substr(-5));
-                ld.accessToken = succ.access_token;
-                ld.accessTokenExpires = moment.utc().add(succ.access_token_expires,'seconds');
-                NVR.log ("Current time is: UTC "+moment.utc().format("YYYY-MM-DD hh:mm:ss"));
-                NVR.log ("New access token expires on: UTC "+ld.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
-                NVR.log ("New access token expires on:"+ld.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
-                ld.isTokenSupported = true;
-                NVR.setLogin(ld);
-                d.resolve("Login success via refresh token");
-                $rootScope.$broadcast('auth-success', ''  );
-                return d.promise;
-              }
-              else {
-                NVR.log ('ERROR:Trying to refresh with refresh token:'+JSON.stringify(succ));
-                return proceedWithFreshLogin();
-
-              }
-            },
-            function (err) {
-                NVR.log ('access token login HTTP failed with: '+JSON.stringify(err));
-                return proceedWithFreshLogin();
-            });
-          } // valid refresh
-            return d.promise;
-          } // is token supported
-        NVR.log ("Token login not being used");
-        // coming here means token reloads fell through
-        return proceedWithFreshLogin();
-      }
-
-      function proceedWithFreshLogin() {
-        // 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("Doing fresh login to ZM");
-        var httpDelay = NVR.getLogin().enableSlowLoading ? zm.largeHttpTimeout : zm.httpTimeout;
-  
-       
-        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
-        $rootScope.authSession = '';
-        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.refresh_token) {
-                  $rootScope.authSession = '&token='+succ.access_token;
-                  NVR.log ("New refresh token retrieved: ..."+succ.refresh_token.substr(-5));
-                  ld.isTokenSupported = true;
-               
-                  ld.accessToken = succ.access_token;
-                  ld.accessTokenExpires = moment.utc().add(succ.access_token_expires, 'seconds');
-                  ld.refreshToken = succ.refresh_token;
-                
-                  ld.refreshTokenExpires = moment.utc().add(succ.refresh_token_expires, 'seconds');
-              
-                  NVR.log ("Current time is: UTC "+moment.utc().format("YYYY-MM-DD hh:mm:ss"));
-                  NVR.log ("New refresh token expires on: UTC "+ld.refreshTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
-                  NVR.log ("New access token expires on: UTC "+ld.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
-                  NVR.setLogin(ld);
-  
-                }
-                else {
-                  if (succ.credentials) {
-                    NVR.log ("Could not recover token details, trying old auth credentials");
-                    ld.isTokenSupported = false;
-                    NVR.setLogin(ld);
-                    $rootScope.authSession = "&" + succ.credentials;
-                    if (succ.append_password == '1') {
-                      $rootScope.authSession = $rootScope.authSession +
-                        loginData.password;
-                    }
-                  }
-                  else {
-                    NVR.log ("Neither token nor old cred worked. Seems like an error");
-                  }
-                }
-                
-  
-                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;
-                ld.isTokenSupported = 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 (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);
-                  });
-  
-            }
-          ); // post .then
-  
-        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
-            // ZM - Login -- 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
@@ -1597,8 +1224,9 @@ angular.module('zmApp', [
         NVR.debug(msg);
       };
 
-      $rootScope.recreateTokens = function() {
-        return NVR.recreateTokens();
+
+      $rootScope.proceedWithLogin = function(obj) {
+        return NVR.proceedWithLogin(obj);
       };
 
      
@@ -2452,6 +2080,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;
@@ -2507,13 +2137,14 @@ angular.module('zmApp', [
               }
             },
             function (err) {
-              var d = $q.defer();
-              nvr.debug("***  Inside native HTTP error: " + JSON.stringify(err));
-              if (err.status == 401) {
-                nvr.debug ("** Native intercept: Got 401, going to try recreating tokens");
-                return nvr.recreateTokens()
-                .then (function() {
+            
+              nvr.debug("***  Inside native HTTP error" + JSON.stringify(err));
+              if (err.status == 401 && !skipIntercept) {
+                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");
+                          //console.log ("I GOT: "+ JSON.stringify(succ));
                           url = url.replace(/&token=([^&]*)/, nvr.authSession);
                           cordova.plugin.http.sendRequest(encodeURI(url), options, 
                           function (succ) {
@@ -2521,13 +2152,17 @@ angular.module('zmApp', [
                             return d.promise;
                           }, 
                           function (err) {
-                            d.resolve(err);
+                            d.reject(err);
                             return d.promise;
+                   
                           });
                           return d.promise;
                 }, function (err) {d.reject(err); return d.promise;});
               }
               else {
+                if (skipIntercept) {
+                  nvr.debug ("Not intercepting as skipIntercept is true");
+                }
                 // not a 401, so pass on rejection
                 d.reject(err);
                 return d.promise;
-- 
cgit v1.2.3


From 5aee4039af90cc6b5c372076daa1d5ada9596075 Mon Sep 17 00:00:00 2001
From: Pliable Pixels 
Date: Mon, 20 May 2019 10:43:06 -0400
Subject: demote logs

---
 www/js/app.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

(limited to 'www/js/app.js')

diff --git a/www/js/app.js b/www/js/app.js
index dd6a3ce4..140c8cad 100755
--- a/www/js/app.js
+++ b/www/js/app.js
@@ -113,7 +113,7 @@ angular.module('zmApp', [
     versionWithLoginAPI: "1.31.47",
     androidBackupKey: "AEdPqrEAAAAIqF-OaHdwIzZhx2L1WOfAGTagBxm5a1R4wBW_Uw",
     accessTokenLeewayMin: 5,
-    refreshTokenLeewayMin: 30
+    refreshTokenLeewayMin: 10
 
   })
 
-- 
cgit v1.2.3


From 3b38f53d06d41d3fc9246786d8ee25c422406462 Mon Sep 17 00:00:00 2001
From: Pliable Pixels 
Date: Mon, 20 May 2019 11:52:24 -0400
Subject: more logs demotion

---
 www/js/app.js | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

(limited to 'www/js/app.js')

diff --git a/www/js/app.js b/www/js/app.js
index 140c8cad..27a9aff9 100755
--- a/www/js/app.js
+++ b/www/js/app.js
@@ -720,7 +720,7 @@ angular.module('zmApp', [
 
       
         if (response.data && typeof(response.data) == 'string' && (response.data.indexOf("
")==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(/
[\s\S]*<\/pre>/,''));
            // console.log ("FIXED="+JSON.stringify(response.data));
@@ -935,7 +935,8 @@ angular.module('zmApp', [
 
             },
             function (err) {
-              console.log("AUTH HASH ERROR: " + JSON.stringify(conf));
+            
+             NVR.debug("Auth Hash error: " + JSON.stringify(conf));
             });
       }
 
@@ -1278,7 +1279,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) {
@@ -1329,7 +1330,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;
           }
@@ -1877,7 +1878,7 @@ angular.module('zmApp', [
               loadServices();
             }, function (err) {
               
-              console.log("ERR " + JSON.stringify(err));
+            //  console.log("ERR " + JSON.stringify(err));
               $rootScope.lastState = "app.montage";
               loadServices();
             });
-- 
cgit v1.2.3


From 3e6d70bf5c9803bc32c3f9cdacf13ab3ee70af9b Mon Sep 17 00:00:00 2001
From: Pliable Pixels 
Date: Fri, 24 May 2019 16:05:42 -0400
Subject: if you disable APIs in ZM 1.34, this is still not clean. TBD

---
 www/js/app.js | 23 ++++++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)

(limited to 'www/js/app.js')

diff --git a/www/js/app.js b/www/js/app.js
index 27a9aff9..e8bd243e 100755
--- a/www/js/app.js
+++ b/www/js/app.js
@@ -677,7 +677,17 @@ angular.module('zmApp', [
 
          /* rejection.data && rejection.data.data && rejection.data.data.message.indexOf('Token revoked') != -1) */
 
+         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;
+            }
+         }
+          
+
+          
     
           nvr.log ("Browser Http intecepted 401, will try reauth");
           return nvr.proceedWithLogin({'nobroadcast':true, 'access':false, 'refresh':true})
@@ -1160,7 +1170,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();
@@ -2139,8 +2149,15 @@ angular.module('zmApp', [
             },
             function (err) {
             
-              nvr.debug("***  Inside native HTTP error" + JSON.stringify(err));
-              if (err.status == 401 && !skipIntercept) {
+              nvr.debug("***  Inside native HTTP error");
+              if (err.status == 401 && !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) {
-- 
cgit v1.2.3


From e2f5d6477fe22e31d1f09d15570b289fb69b9e6a Mon Sep 17 00:00:00 2001
From: Pliable Pixels 
Date: Sat, 25 May 2019 07:49:56 -0400
Subject: make sure a retry doesn't get retried

---
 www/js/app.js | 13 ++++++++-----
 1 file changed, 8 insertions(+), 5 deletions(-)

(limited to 'www/js/app.js')

diff --git a/www/js/app.js b/www/js/app.js
index e8bd243e..18bead17 100755
--- a/www/js/app.js
+++ b/www/js/app.js
@@ -692,9 +692,10 @@ angular.module('zmApp', [
           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");
+            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) {
@@ -2103,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;
@@ -2150,7 +2152,7 @@ angular.module('zmApp', [
             function (err) {
             
               nvr.debug("***  Inside native HTTP error");
-              if (err.status == 401 && !skipIntercept && nvr.apiValid) {
+              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);
@@ -2161,9 +2163,10 @@ angular.module('zmApp', [
                 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");
+                          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);
@@ -2178,7 +2181,7 @@ angular.module('zmApp', [
                 }, function (err) {d.reject(err); return d.promise;});
               }
               else {
-                if (skipIntercept) {
+                if (options.skipIntercept) {
                   nvr.debug ("Not intercepting as skipIntercept is true");
                 }
                 // not a 401, so pass on rejection
-- 
cgit v1.2.3