Browse code

retry on auth error

louis.jonget authored on16/03/2023 14:09:28
Showing2 changed files
... ...
@@ -373,13 +373,22 @@ static void inbox_received_callback(DictionaryIterator *iter, void *context) {
373 373
     */
374 374
 
375 375
     //APP_LOG(APP_LOG_LEVEL_DEBUG, "to display : %s ",s_msg);
376
-
377
-    text_layer_set_text(s_upperleft_text_layer, s_altitude);
378
-    text_layer_set_text(s_upperright_text_layer, s_distance);
379
-    text_layer_set_text(s_main_text_layer, s_speed);
380
-    text_layer_set_text(s_lowerleft_text_layer, s_avg_speed);
381
-    text_layer_set_text(s_lowerright_text_layer, s_max_speed);
382
-    text_layer_set_text(s_lower_text_layer, s_duration);
376
+    if(strcmp(s_status, "L200")==0){
377
+      text_layer_set_text(s_upperleft_text_layer, s_altitude);
378
+      text_layer_set_text(s_upperright_text_layer, s_distance);
379
+      text_layer_set_text(s_main_text_layer, s_speed);
380
+      text_layer_set_text(s_lowerleft_text_layer, s_avg_speed);
381
+      text_layer_set_text(s_lowerright_text_layer, s_max_speed);
382
+      text_layer_set_text(s_lower_text_layer, s_duration);
383
+    }else if(strcmp(s_status, "S200")==0){
384
+      text_layer_set_text(s_lower_text_layer, "upload OK");
385
+      vibes_short_pulse();
386
+    }else if(strcmp(s_status, "S401")==0){
387
+      text_layer_set_text(s_lower_text_layer, "auth err, retrying");
388
+    }else{
389
+      text_layer_set_text(s_lower_text_layer, s_status);
390
+      vibes_double_pulse();
391
+    }
383 392
   }else{
384 393
     //APP_LOG(APP_LOG_LEVEL_DEBUG, "not status message... ");
385 394
   }
... ...
@@ -181,9 +181,9 @@ function splitFloatNumber(num) {
181 181
 // Build GPX headers
182 182
 //
183 183
 function GPXHeadersBuilder(timestamp, name, type) {
184
-    var headers = '<?xml version="1.0" encoding="UTF-8"?><gpx creator="Pebble" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" xmlns="http://www.topografix.com/GPX/1/1"><metadata><time>' + timestamp + '</time></metadata><trk><name>' + name + '</name><type>' + type + '</type><trkseg>';
185
-    localStorage.setItem("GPX", headers);
186
-    return true;
184
+  var headers = '<?xml version="1.0" encoding="UTF-8"?><gpx creator="Pebble" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" xmlns="http://www.topografix.com/GPX/1/1"><metadata><time>' + timestamp + '</time></metadata><trk><name>' + name + '</name><type>' + type + '</type><trkseg>';
185
+  localStorage.setItem("GPX", headers);
186
+  return true;
187 187
 }
188 188
 
189 189
 // Build GPX track point
... ...
@@ -198,11 +198,11 @@ function GPXtrkptBuilder(lat, lon, ele, timestamp) {
198 198
 // Build GPX footer
199 199
 //
200 200
 function GPXfooterBuilder() {
201
-    var GPX = localStorage.getItem("GPX");
202
-    var footer = '</trkseg></trk></gpx>';
203
-    var ret = localStorage.setItem("GPX", GPX + footer);
204
-    //console.log("GPX closed : " + GPX + footer);
205
-    return ret;
201
+  var GPX = localStorage.getItem("GPX");
202
+  var footer = '</trkseg></trk></gpx>';
203
+  var ret = localStorage.setItem("GPX", GPX + footer);
204
+  console.log("GPX closed : " + localStorage.getItem("GPX"));
205
+  return ret;
206 206
 }
207 207
 
208 208
 //------------------------------------------
... ...
@@ -279,44 +279,58 @@ function SendToStrava() {
279 279
     }
280 280
 
281 281
 
282
-    var bearer = JSON.parse(tokens).access_token;
283
-    params = {
284
-        url: "https://www.strava.com/api/v3/uploads",
285
-        method: "POST",
286
-        data: { description: "desc", data_type: "gpx" },
287
-        files: { file: gpxfile },
288
-        authorization: "Bearer " + bearer,
289
-        callback: function(e) {
290
-            var message = "";
291
-            if (console.log(e.status + " - " + e.txt), 201 == e.status) {
292
-                message = "Your activity has been created";
293
-                localStorage.setItem("strava_uploaded", true);
294
-            } else if (400 == e.status) {
295
-                message = "An error has occurred. If you've already uploaded the current activity, please delete it in Strava.";
296
-            } else if (401 == e.status) {
297
-                message = "Error - Unauthorized. Please check your credentials in the settings."
298
-            } else {
299
-                try {
300
-                    response_json = JSON.parse(e.txt)
301
-                    response_json.error ? (console.log("error:" + response_json.error), message = response_json.error) : response_json.status && (console.log("status:" + response_json.status))
302
-                } catch (e) {
303
-                    console.log("Error log, " + e)
304
-                }
305
-            }
306
-            message && Pebble.showSimpleNotificationOnPebble("Ventoo SE - Strava", message)
282
+  var bearer = JSON.parse(tokens).access_token;
283
+  params = {
284
+    url: "https://www.strava.com/api/v3/uploads",
285
+    method: "POST",
286
+    data: { description: "desc", data_type: "gpx" },
287
+    files: { file: gpxfile },
288
+    authorization: "Bearer " + bearer,
289
+    callback: function (e) {
290
+      var message = "";
291
+      if (console.log(e.status + " - " + e.txt), 201 == e.status) {
292
+        message = "S200";
293
+        localStorage.setItem("strava_uploaded", true);
294
+      } else if (400 == e.status) {
295
+        message = "S400";
296
+      } else if (401 == e.status) {
297
+        //token expired, retrying
298
+        message = "S401"
299
+        SendToStrava()
300
+      } else {
301
+        try {
302
+          response_json = JSON.parse(e.txt)
303
+          response_json.error ? (console.log("error:" + response_json.error), message = response_json.error) : response_json.status && (console.log("status:" + response_json.status))
304
+        } catch (err) {
305
+          console.log("Error log, " + err)
307 306
         }
307
+        message = "S500";
308
+      }
309
+      //message && Pebble.showSimpleNotificationOnPebble("Ventoo SE - Strava", message)
310
+      
311
+      // Build message
312
+      var dict = {
313
+        'status': message
314
+      };
315
+      // Send the message
316
+      Pebble.sendAppMessage(dict, function () {
317
+        console.log('Message sent successfully: ' + JSON.stringify(dict));
318
+      }, function (e) {
319
+        console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
320
+      });
308 321
     }
309
-    var XHR = new XMLHttpRequest;
310
-    var n = this;
311
-    //console.log(params.url);
312
-    XHR.open(params.method, params.url, !0);
313
-    var body = "";
314
-    var boundary = Math.random().toString().substring(2);
315
-    XHR.setRequestHeader("content-type", "multipart/form-data; charset=utf-8; boundary=" + boundary)
316
-    XHR.setRequestHeader("Authorization", params.authorization);
317
-    for (var i in params.data) body += "--" + boundary + '\r\nContent-Disposition: form-data; name="' + i + '"\r\n\r\n' + params.data[i] + "\r\n";
318
-    for (var i in params.files) body += "--" + boundary + '\r\nContent-Disposition: form-data; name="' + i + '" ; filename=test.gpx\r\n\r\n' + params.files[i] + "\r\n";
319
-    body += "--" + boundary + "--\r\n"
322
+  }
323
+  var XHR = new XMLHttpRequest;
324
+  var n = this;
325
+  //console.log(params.url);
326
+  XHR.open(params.method, params.url, !0);
327
+  var body = "";
328
+  var boundary = Math.random().toString().substring(2);
329
+  XHR.setRequestHeader("content-type", "multipart/form-data; charset=utf-8; boundary=" + boundary)
330
+  XHR.setRequestHeader("Authorization", params.authorization);
331
+  for (var i in params.data) body += "--" + boundary + '\r\nContent-Disposition: form-data; name="' + i + '"\r\n\r\n' + params.data[i] + "\r\n";
332
+  for (var i in params.files) body += "--" + boundary + '\r\nContent-Disposition: form-data; name="' + i + '" ; filename=test.gpx\r\n\r\n' + params.files[i] + "\r\n";
333
+  body += "--" + boundary + "--\r\n"
320 334
 
321 335
     XHR.onreadystatechange = function() {
322 336
         try {
... ...
@@ -357,8 +371,8 @@ function PostToWeb() {
357 371
         }
358 372
     };
359 373
 
360
-    //send GPX in body
361
-    xhr.send(GPX);
374
+  //send GPX in body
375
+  xhr.send(GPX);
362 376
 
363 377
 }
364 378
 
... ...
@@ -487,18 +501,18 @@ function locationSuccess(new_pos) {
487 501
 
488 502
 
489 503
 
490
-        // Build message
491
-        message = "OK";
492
-        var dict = {
493
-            'accuracy': accuracyString,
494
-            'distance': distanceString,
495
-            'avg_speed': avgSpeedString,
496
-            'duration': durationString,
497
-            'altitude': altitudeString,
498
-            'speed': speedString,
499
-            'max_speed': maxSpeedString,
500
-            'status': message
501
-        };
504
+    // Build message
505
+    message = "L200";
506
+    var dict = {
507
+      'accuracy': accuracyString,
508
+      'distance': distanceString,
509
+      'avg_speed': avgSpeedString,
510
+      'duration': durationString,
511
+      'altitude': altitudeString,
512
+      'speed': speedString,
513
+      'max_speed': maxSpeedString,
514
+      'status': message
515
+    };
502 516
 
503 517
         // Send the message
504 518
         Pebble.sendAppMessage(dict, function() {
... ...
@@ -558,16 +572,16 @@ function init() {
558 572
 
559 573
     if ((se && !su) || (ce && !cu)) {
560 574
 
561
-        var GPX = localStorage.getItem("GPX");
562
-        console.log("last 6 char of GPX are " + GPX.substring(GPX.length - 6, GPX.length))
563
-        if (GPX.substring(GPX.length - 6, GPX.length) !== "</gpx>") {
564
-            console.log("WARNING - NO GPX FOOTER ")
565
-                /*var footer = '</trkseg></trk></gpx>';
566
-                localStorage.setItem("GPX", GPX + footer);*/
567
-            GPXfooterBuilder();
568
-            GPX = localStorage.getItem("GPX");
569
-            console.log("GPX FOOTER is now : " + GPX.substring(GPX.length - 6, GPX.length))
570
-        }
575
+    var GPX = localStorage.getItem("GPX");
576
+    console.log("last 6 char of GPX are " + GPX.substring(GPX.length - 6, GPX.length))
577
+    if (GPX.substring(GPX.length - 6, GPX.length) !== "</gpx>") {
578
+        console.log("WARNING - NO GPX FOOTER ")
579
+            /*var footer = '</trkseg></trk></gpx>';
580
+            localStorage.setItem("GPX", GPX + footer);*/
581
+        GPXfooterBuilder();
582
+        GPX = localStorage.getItem("GPX");
583
+        console.log("GPX FOOTER is now : " + GPX.substring(GPX.length - 6, GPX.length))
584
+    }
571 585
 
572 586
         if (se) {
573 587
             console.log("GPX upload needed to Strava")
... ...
@@ -603,48 +617,37 @@ Pebble.addEventListener('ready', function(e) {
603 617
 });
604 618
 
605 619
 // Get AppMessage events
606
-Pebble.addEventListener('appmessage', function(e) {
607
-    // Get the dictionary from the message
608
-    var dict = e.payload;
609
-    //console.log(dict[0].toString());
610
-    switch (dict[0]) {
611
-        case 'startstop':
612
-            if (!locationInterval == false) {
613
-                console.log("Stopping the track");
614
-                clearInterval(locationInterval);
615
-                locationInterval = false;
616
-                clearInterval(instantLocationInterval);
617
-                instantLocationInterval = false;
618
-                firstlocationInterval = setInterval(function() {
619
-                    navigator.geolocation.getCurrentPosition(null, locationError, firstlocationOptions);
620
-                }, 1000);
621
-            } else {
622
-                console.log("Starting the track");
623
-                start_get_coordinate();
624
-            }
625
-            break;
626
-        case 'send':
627
-            if (locate_me) {
628
-                var prev_pos = getLocation(false);
629
-                instantLocationUpdate(prev_pos);
630
-            }
631
-
632
-            init();
633
-
634
-            /*
635
-            // Send the message
636
-            var dict = {
637
-              'status': "EXIT"
638
-            };
639
-            Pebble.sendAppMessage(dict, function () {
640
-              console.log('Message sent successfully: ' + JSON.stringify(dict));
641
-            }, function (e) {
642
-              console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
643
-            });
644
-            */
645
-            break;
646
-        default:
647
-            console.log('Sorry. I don\'t understand your request :' + dict[0]);
648
-    }
620
+Pebble.addEventListener('appmessage', function (e) {
621
+  // Get the dictionary from the message
622
+  var dict = e.payload;
623
+  //console.log(dict[0].toString());
624
+  switch (dict[0]) {
625
+    case 'startstop':
626
+      if (!locationInterval == false) {
627
+        console.log("Stopping the track");
628
+        clearInterval(locationInterval);
629
+        locationInterval = false;
630
+        clearInterval(instantLocationInterval);
631
+        instantLocationInterval = false;
632
+        /*firstlocationInterval = setInterval(function () {
633
+          navigator.geolocation.getCurrentPosition(null, locationError, firstlocationOptions);
634
+        }, 1000);*/
635
+      } else {
636
+        console.log("Starting the track");
637
+        start_get_coordinate();
638
+      }
639
+      break;
640
+    case 'send':
641
+      if (locate_me) {
642
+        var prev_pos = getLocation(false);
643
+        instantLocationUpdate(prev_pos);
644
+      }
645
+      
646
+      init();
647
+
648
+      break;
649
+    default:
650
+      console.log('Sorry. I don\'t understand your request :' + dict[0]);
651
+  }
649 652
 
650 653
 });
651 654
\ No newline at end of file