Browse code

refactoring xhr for authentication

louis.jonget authored on24/06/2022 15:26:04
Showing1 changed files
... ...
@@ -7,96 +7,118 @@ var messageKeys = require('message_keys');
7 7
 var sid;
8 8
 var status;
9 9
 var retry;
10
-retry=0;
10
+retry = 1;
11 11
 
12
-function authenticate() {
13
-  var response;
14
-  sid="";
15
-  console.log('---- authenticate');
16
-  console.log('-- '+localStorage.getItem('username'));
17
-  //console.log('-- '+localStorage.getItem('password'));
18
-  console.log('-- '+localStorage.getItem('server'));
19
-  if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
20
-    var username=localStorage.getItem('username');
21
-    var password=localStorage.getItem('password');
22
-    var server=localStorage.getItem('server');
23
-    var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
12
+function xhr_to_syno(method, url_path, onload_function, max_retry) {
13
+  status = "";
14
+  if (localStorage.getItem('username') && localStorage.getItem('password') && localStorage.getItem('server')) {
15
+    var username = localStorage.getItem('username');
16
+    var password = localStorage.getItem('password');
17
+    var server = localStorage.getItem('server');
18
+    url = server + url_path;
24 19
     var xhr = new XMLHttpRequest();
25 20
     xhr.timeout = 3000; // time in milliseconds
26 21
 
27
-    xhr.open("GET", url,true);
28
-    
22
+    xhr.open(method, url, true);
23
+
29 24
     xhr.onload = function () {
30 25
       if (xhr.readyState === 4) {
31
-        retry=0;
32
-        console.log('------authentication request returned');
33
-        if(xhr.status == 200) {
34
-          response = JSON.parse(xhr.responseText);
35
-          if (response.success == true){
36
-            sid = response.data.sid;
37
-          }else{
38
-  	    console.log('------Authentication failed : '+ response.toString());
39
-          }
40
-        }else {
41
-          console.log('------Request returned error code ' + xhr.status);
42
-        }
43
-    
44
-        if (sid != ""){
45
-          auth = "";
46
-          message = "Welcome to Syno Cam Switch ! ready & authenticated";
47
-               
48
-          // Build message
49
-          var dict = {
50
-            'auth': message,
51
-          };
52
-        
53
-          // Send the message
54
-          Pebble.sendAppMessage(dict, function(e) {
55
-            console.log('sent');
56
-          }, function() {
57
-            console.log('failed');
58
-          });
59
-         
60
-        }else{
61
-          console.log('------Unexpected error : authentication is OK but no SID retrieved');
26
+        retry = 1;
27
+        console.log('------xhr request returned');
28
+        if (xhr.status == 200) {
29
+          onload_function(xhr);
30
+          return true;
31
+        } else {
32
+          console.log('------xhr request returned error code ' + xhr.status);
33
+          return false;
62 34
         }
63 35
       }
64
-    };
36
+    }
65 37
 
66
-    xhr.ontimeout = function (e){
38
+    xhr.ontimeout = function (e) {
67 39
       retry++;
68
-      if (retry<=1){
69
-        console.log('------Authentication timed out retrying another time ');
70
-        authenticate();
71
-      }else{
72
-        console.log('------Authentication timed out a second time');
40
+      if (retry < max_retry) {
41
+        console.log('------xhr timed out retrying another time ');
42
+        xhr_to_syno(method, url_path, onload_function, max_retry);
43
+      } else {
44
+        console.log('------xhr timed out ' + retry + ' time');
73 45
         //send back "timeout" to watch
74
-        auth="";
75
-        message ="Authentication timed out, verify settings and connectivity";
46
+        message = "Call to server timed out, verify settings and connectivity";
76 47
 
77 48
         // Build message
78 49
         var dict = {
79
-          'auth': message,
50
+          'status': message,
80 51
         };
81 52
 
82 53
         // Send the message
83
-        Pebble.sendAppMessage(dict, function(e) {
54
+        Pebble.sendAppMessage(dict, function (e) {
84 55
           console.log('sent');
85
-        }, function() {
56
+        }, function () {
86 57
           console.log('failed');
87 58
         });
59
+        return false;
60
+      }
61
+    }
62
+
63
+  } else {
64
+    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
65
+  }
66
+
67
+}
68
+
69
+
70
+function authenticate() {
71
+  var response;
72
+  sid = "";
73
+  console.log('---- authenticate');
74
+  if (localStorage.getItem('username') && localStorage.getItem('password') && localStorage.getItem('server')) {
75
+    var username = localStorage.getItem('username');
76
+    var password = localStorage.getItem('password');
77
+    var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
78
+    var method = "GET";
79
+    onload_function = function (xhr) {
80
+      response = JSON.parse(xhr.responseText);
81
+      if (response.success == true) {
82
+        sid = response.data.sid;
83
+        console.log('------Authentication succeeded');
84
+      } else {
85
+        console.log('------Authentication failed : ' + response.toString());
88 86
       }
89 87
     };
90
-      
91
-    xhr.send();
92
-  }else{
88
+    max_retry = 1;
89
+    if (xhr_to_syno(method, url_path, onload_function, max_retry) == true) {
90
+      if (sid != "") {
91
+        auth = "";
92
+        message = "Welcome to Syno Cam Switch ! ready & authenticated";
93
+
94
+        // Build message
95
+        var dict = {
96
+          'auth': message,
97
+        };
98
+
99
+        // Send the message
100
+        Pebble.sendAppMessage(dict, function (e) {
101
+          console.log('sent');
102
+        }, function () {
103
+          console.log('failed');
104
+        });
105
+      } else {
106
+        console.log('------Unexpected error : authentication is OK but no SID retrieved');
107
+      }
108
+    } else {
109
+      console.log('------Unexpected error : authentication is OK but no SID retrieved');
110
+    }
111
+  } else {
93 112
     Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
94 113
   }
114
+
115
+
95 116
 }
96 117
 
118
+
97 119
 function get_status() {
98 120
   var response;
99
-  
121
+
100 122
   if (sid != ""){
101 123
     status = "";
102 124
     console.log('---- get_status');
... ...
@@ -117,7 +139,7 @@ function get_status() {
117 139
           if(xhr.status == 200) {
118 140
             response = JSON.parse(xhr.responseText);
119 141
             if (response.success == true){
120
-              status=response.data.on;   
142
+              status = response.data.on;
121 143
               var message;
122 144
               switch (status) {
123 145
                 case true:
... ...
@@ -128,12 +150,12 @@ function get_status() {
128 150
                   break;
129 151
                 default:
130 152
                   message = "home mode is unknown !";
131
-              }      
153
+              }
132 154
               // Build message
133 155
               var dict = {
134 156
                 'status': message,
135 157
               };
136
-            
158
+
137 159
               // Send the message
138 160
               Pebble.sendAppMessage(dict, function(e) {
139 161
                 console.log('sent');
... ...
@@ -156,12 +178,12 @@ function get_status() {
156 178
           console.log('------Get-Status timed out a second time');
157 179
           //send back "timeout" to watch
158 180
           message ="Get-Status timed out, verify settings and connectivity";
159
-  
181
+
160 182
           // Build message
161 183
           var dict = {
162 184
             'status': message,
163 185
           };
164
-  
186
+
165 187
           // Send the message
166 188
           Pebble.sendAppMessage(dict, function(e) {
167 189
             console.log('sent');
... ...
@@ -173,12 +195,12 @@ function get_status() {
173 195
 
174 196
       xhr.send();
175 197
 
176
-      
198
+
177 199
     }else{
178 200
       Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
179 201
     }
180 202
   }
181
-      
203
+
182 204
 }
183 205
 
184 206
 
... ...
@@ -193,26 +215,26 @@ function switch_home(bool) {
193 215
       var password=localStorage.getItem('password');
194 216
       var server=localStorage.getItem('server');
195 217
       var xhr = new XMLHttpRequest();
196
-      
218
+
197 219
       url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
198
-      
220
+
199 221
       xhr.open("GET", url,false);
200 222
       xhr.send();
201
-  
223
+
202 224
       if(xhr.status == 200) {
203 225
         response = JSON.parse(xhr.responseText);
204 226
         if (response.success == true){
205
-          status=response.data.on;   
227
+          status = response.data.on;
206 228
           console.log('------ status:'+status);
207 229
           var message;
208 230
           var dict;
209 231
           if ( status != bool){
210 232
             console.log('---- switching home mode to '+ bool);
211 233
             url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on="+bool+"&_sid="+sid;
212
-            
234
+
213 235
             xhr.open("GET", url,false);
214 236
             xhr.send();
215
-        
237
+
216 238
             if(xhr.status == 200) {
217 239
               response = JSON.parse(xhr.responseText);
218 240
               if (response.success == true){
... ...
@@ -226,12 +248,12 @@ function switch_home(bool) {
226 248
                     break;
227 249
                   default:
228 250
                     message = "something happened, try again !";
229
-                }      
251
+                }
230 252
                 // Build message
231 253
                 dict = {
232 254
                   'status': message,
233 255
                 };
234
-              
256
+
235 257
                 // Send the message
236 258
                 Pebble.sendAppMessage(dict, function(e) {
237 259
                   console.log('sent');
... ...
@@ -253,18 +275,18 @@ function switch_home(bool) {
253 275
                 break;
254 276
               default:
255 277
                 message = "something happened, try again !";
256
-            }       
278
+            }
257 279
             // Build message
258 280
             dict = {
259 281
               'status': message,
260 282
             };
261
-  
283
+
262 284
             // Send the message
263 285
             Pebble.sendAppMessage(dict, function(e) {
264 286
               console.log('sent');
265 287
             }, function() {
266 288
               console.log('failed');
267
-            }); 
289
+            });
268 290
           }
269 291
         }
270 292
       }else {
... ...
@@ -305,6 +327,5 @@ Pebble.addEventListener('appmessage', function(e) {
305 327
     default:
306 328
       console.log('Sorry. I don\'t understand your request :'+ dict[0]);
307 329
   }
308
-  
309
-});
310 330
 
331
+});