-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
2203 lines (1835 loc) · 71.9 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="Cache-Control" content="no-store" />
<meta name="generator" content="PSPad editor, www.pspad.com">
<title>Unofficial MyRenault dashboard for browsers</title>
<!--<script src="myrenault-public.js?t=<?=time()?> type="text/javascript""></script>-->
<script>
var scr = document.createElement("script");
scr.src = "myrenault-public.js" + "?ts=" + new Date().getTime();
document.getElementsByTagName("head")[0].appendChild(scr);
</script>
<script src="endpoints.js?t=<?=time()?>" type="text/javascript"></script>
<script src="errors.js?t=<?=time()?>" type="text/javascript"></script>
<script src="payloads.js?t=<?=time()?>" type="text/javascript"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
// 2.9.0 - 2023-05-23
// Updated kamereon api key
// Fixed bug of infinite loop for notifications monitoring
// Added list of available temperatures (to do: missing externalTemperature)
// 2.8.1 - 2022-06-18
// Fixed some payloads
// Improved notification management
// 2.8.0 - 2022-04-29
// Added support for notifications
// Added SendNavigation payload
// 2.7.1 - 2022-04-06
// Fixed bug of bad error managment in manageOutput()
// Added error management in showVehicleData()
// Fixed bug of bad descriptions for charging status
// Fixed bug of bad processing of char\ges/chargestatus
// Added management of chargingStatus besides chargeStatus
// 2.7.0 - 2022-03-28
// Implemented CSV(TSV) output for /charges
// Fixed bug of improper displaying of results partially filled by Renault servers
// Added workaround for Renault bug of missing chargeSummaries field if no charges have been recorded
// 2.6.0 - 2022-03-21
// Implemented CSV(TSV) output for /charge-history
// 2.5.0 - 2022-03-16
// Updated api key to VAX7XYKGfa92yMvXculCkEFyfZbuM7Ss
// Improved error management
// Fixed bug of API keys not read from file at startup and not copied to textareas for editing
// Added buttons to start/stop HVAC
// Added button to refresh location status
// Added /res-state endpoint (although I don't know what it is for)
// Added "engine stop" (although it does not work on Renault)
// Added multiple VINs support and vechile data
// 2.4.0 Removed use of myp.php generic proxy, now using specific PHPO login performed by gigya-login.php
// 2.3.0 Cleaned up code for login process
// 2.2.4 Fixed bug of hardcoded gigya server
// 2.2.3 Improved error management during login process
// 2.2.2 Fixed for Firefox support; improved interface.
// 2.2.1 Added plugStatus and chargingStatus texts
// 2.2.0 Added automatic initial query of all endpoints
// 2.1.0 Added "getAllData()" function (to be optimized). Removed dead/useless code.
// 2.0.0 New interface, more user friendly, with preloaded payloads, meaningful endpoints names, login process status,...
// 1.6.1 Added further payloads
// 1.6.0 Implemented predefined payloads for actions
// 1.5.0 New Axios method implemented for login and query (to be cleaned up)
// 1.4.0 Added plenty of debug error messages during login; cleaned up page and code; added textareas for endpoint and payload for manual testing
// 1.3.0 Addes some test buttons and functions for actions; implemented Axios for actions
// 1.1.1 Fixed bug of post/get; actions not working yet.
// 1.1.0 Added actions support
// 1.0.2 Reordered enpoints, enhanced output
// 1.0.1 Oscurato VIN in output
// 1.0.0 Prima versione pubblica
/*var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'myrenault-public.js?' + new Date().getMilliseconds();
*/
/*var scr = document.createElement("script");
scr.src = "myrenault-public.js" + "?ts=" + new Date().getTime();
document.getElementsByTagName("head")[0].appendChild(scr);
*/
//console.log("---------------",newData);
localRun = null;
GIGYA_API_KEY = null;
KAMEREON_KEY = null;
DEFAULT_VIN = 1;
JWTextracted = null;
countdownStarted = false;
lastStep = "start";
empty = "";
slash = "\\";
results = [];
endpointResponseTemplate = endpointsList.filter(vals=>vals.name === "battery-status")[0].response;// Find element named "battery-status"
allowedPlugValues = endpointResponseTemplate.filter(vals=>vals.name === "plugStatus")[0].values; // Find element named "plugStatus"
allowedChargingValues = endpointResponseTemplate.filter(vals=>vals.name === "chargingStatus")[0].values; // Find element named "chargingStatus"
notificationId = "[empty]";
notifRetry = 0;
notifInterval = null;
NOTIF_INT = 3000;
NOTIF_MAX = 5;
CommandCompleted = false;
// To get data from an item undefinely nested inside an object:
// https://stackoverflow.com/posts/43849204/timeline
const resolvePath = (object, path, defaultValue) => path
.split('.')
.reduce((o, p) => o ? o[p] : defaultValue, object)
function readRunningMode() {
if (window.location.protocol === "file:") {
console.log("Running as local file!");
localRun = true;
} else {
localRun = false;
}
}
function init() {
gigyaurl = newData.servers.gigyaProd.target;
GIGYA_API_KEY= newData.servers.gigyaProd.apikey;
gapikey.value = GIGYA_API_KEY;
kamereonurl = newData.servers.wiredProd.target;
console.log("Writing to GUI:", newData.servers.wiredProd.apikey);
kapikey.value = newData.servers.wiredProd.apikey; // Read from file, write to interface, which is editable by user
// GIGYA_PHP_LOGIN = gigyaPhpLogin.value;
}
function createJSrefreshLinks() {
// To prevent caching of old .js files, creates links to JS with fake parameters: click on the link to force refresh of scripts
timestamp = (new Date()).getTime();
console.log(timestamp);
link1 = "myrenault-public.js?dummy=" + timestamp;
link2 = "endpoints.js?dummy=" + timestamp;
link3 = "errors.js?dummy=" + timestamp;
link4 = "payloads.js?dummy=" + timestamp;
links.innerHTML = "" +
"<a href='"+ link1 + "'>myrenault</a><br>" +
"<a href='"+ link2 + "'>endpoints</a><br>" +
"<a href='"+ link3 + "'>errors</a><br>" +
"<a href='"+ link4 + "'>payloads</a><br>";
}
function fillPayload() {
console.log("Funziona o no?");
actionPayloadSpan.value = JSON.stringify(samplePayloads[payloadsList.selectedIndex].pldContents, null, 4);
actionEndpoint.value = "actions/" + samplePayloads[payloadsList.selectedIndex].associatedAction;
payloadTested.innerHTML = samplePayloads[payloadsList.selectedIndex].testedOk;
}
function loadPayloads() {
var lst = payloadsList;
for (var i=0; i<samplePayloads.length; i++) {
opt = document.createElement("option");
opt.setAttribute("value", samplePayloads[i].pldName);
opt.text = samplePayloads[i].pldName;
lst.appendChild(opt);
}
}
function fillEndPoint() {
endpoint.value = endpointsList[EP_list.selectedIndex].url;
endpointDescription.innerHTML = endpointsList[EP_list.selectedIndex].description;
actionPayloadSpan.value = JSON.stringify(endpointsList[EP_list.selectedIndex].payload,null,4);
}
function loadEndpoints() {
var lst = EP_list;
for (var i=0; i < endpointsList.length; i++) {
opt = document.createElement("option");
opt.setAttribute("value", endpointsList[i].name);
opt.text = endpointsList[i].name;
lst.appendChild(opt);
}
}
function callByClick(endp, libVer) {
// Called when clicked on endpoint
endpoint.value = endp;
output.value = "";
outputNotifications.value = "";
log.value = "";
//startCountdown();
justQuery(libVer);
}
function request(url, setMyHeader, payload, requestType) {
//console.log("REQ - Processing " , url , "...");
console.log("REQ - payload ricevuto: '" , payload , "'");
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.timeout = 2000;
xhr.onreadystatechange = function(e) {
if (xhr.readyState === 4) {
// Response received
if (xhr.status === 200) {
// Positive response received
resolve(xhr.response);
} else {
console.log("REQ - Error at step ' " + lastStep + "' for URL " + url + ": " , xhr.status);
log.value += "\n\nREQ - Error at step ' " + lastStep + "' for URL " + url + ":\n\nERROR " + xhr.status;
if (errors[xhr.status] != null) {
console.log(errors[xhr.status]);
log.value += "\nREQ - " + errors[xhr.status].message + "\n" + errors[xhr.status].description;
} else {
log.value += "\nREQ - Sorry, no further info on this error.\n";
}
reject(xhr.status)
}
} else {
// Prcessing....
// console.log("Ongoing,Status=", xhr.readyState);
}
}
xhr.ontimeout = function () {
console.log("REQ - XHR timeout error.\n");
log.value += "REQ - XHR timeout error.\n";
reject('timeout');
}
xhr.onerror = function (e) {
console.log("REQ - XHR error: ", e , "\n");
log.value += "REQ - XHR error: ", e , "\n";
reject('error');
}
if (requestType == "get") {
xhr.open('get', url , true)
} else {
xhr.open('post', url , true)
}
if (setMyHeader === true) {
xhr.setRequestHeader("x-gigya-id_token",JWT.value);
xhr.setRequestHeader("apikey",KAMEREON_KEY);
xhr.setRequestHeader("Content-type","application/vnd.api+json");
console.log("REQ - With header, type: ", requestType);
} else {
console.log("REQ - Without header, type: ", requestType);
}
if ((payload != null) && (payload.length > 0)) {
xhr.send(payload);
console.log("REQ - With payload, type: ", requestType);
} else {
xhr.send();
console.log("REQ - Without payload, type: ", requestType);
}
} // Promise function end
) // Promise end
}
function getAllData() {
kamereonGet(JWT.value, "cockpit", 1);
kamereonGet(JWT.value, "location", 1);
kamereonGet(JWT.value, "battery-status", 1);
kamereonGet(JWT.value, "battery-status", 2);
kamereonGet(JWT.value, "hvac-status", 1);
kamereonGet(JWT.value, "hvac-settings", 1);
kamereonGet(JWT.value, "hvac-schdule", 1);
kamereonGet(JWT.value, "charge-mode", 1);
kamereonGet(JWT.value, "charging-settings", 1);
kamereonGet(JWT.value, "charge-schedule", 1);
console.log(results);
}
function justQuery(libraryVersion) {
if (login5.innerHTML !== "OK") alert("Not logged in!");
lastStep = "justQuery v." + libraryVersion;
log.value += "Endpoint '" + endpoint.value + "', library version: " + libraryVersion + ":\n";
output.value = "";
outputNotifications.value = "";
log.value += "Sending query...\n";
console.log("=== DIRECT QUERY");
if (endpoint.value.indexOf("actions") >= 0) {
console.log("Final POST result: " , kamereonPost(JWT.value, endpoint.value, actionPayloadSpan.value, libraryVersion, "", ""));
} else {
console.log("Final GET result: " , kamereonGet(JWT.value, endpoint.value, libraryVersion));
}
}
function sendManualUrl() {
lastStep = "sendManualUrl";
log.value = "Manual url:\n";
log.value += manualUrl.value + "\n";
console.log("=== sendManualUrl");
queryUrl = manualUrl.value;
console.log("finalQueryUrl ", queryUrl);
const sendQuery = request(queryUrl, true, actionPayloadSpan.value, "get");
sendQuery
.then(showResults)
.catch(vehicleError)
return ("query finished.");
}
function main() {
GIGYA_PHP_LOGIN = gigyaPhpLogin.value;
output.value = "";
outputNotifications.value = "";
log.value = "Logging in...\n";
cookieValue.value="waiting...";
JWT.value = "waiting...";
personId.value = "waiting...";
accountId.value = "waiting...";
accountId2.value = "waiting...";
console.log("Loading apikey:" , kapikey.value);
KAMEREON_KEY = kapikey.value; // get final value from interface
// init(); // Called at page first loading
login1.innerHTML = "-";
login2.innerHTML = "-";
login3.innerHTML = "-";
login4.innerHTML = "-";
login5.innerHTML = "-";
login6.innerHTML = " logging in...";
/// debug
// if (!localRun) {
// Running on the web, no PHP/CORS required ---> invece sì...
/* onlineLoginHeader = {
'ApiKey' : GIGYA_API_KEY,
'loginId' : username.value,
'password' : password.value,
'include' : 'data',
'sessionExpiration' : 60
};
onlineLoginURL = gigyaurl + "/accounts.login";
return axios.post(
onlineLoginURL,
null,
{
headers: onlineLoginHeader
})
.then(response => {
if (response.data != "") {
return { status: "ok", data: "Login ok" };
} else {
console.log("ERROR: Invalid login response.");
log.value += "\nERROR: Invalid login response.\n";
return { status: "err", data: "Invalid login response" };
}
})
.catch(
function (error) {
log.value += "\nERROR online001 for POST while logging in, please see console for details:" + JSON.stringify(error,null,4);
console.log("ERROR online001 for POST while logging in:\n", error);
login2.innerHTML = "ERR_OLOG1";
console.log("POST ERROR OLOG001:" , error)
return { status : "error", data: "POST ERROR OLOG001:" + error };
}
);
*/
// } else {
// local login
console.log("Logging in from local PC");
return axios.get(
GIGYA_PHP_LOGIN + '?gigyakey=' + GIGYA_API_KEY + '&gigyasite=' + gigyaurl + '&username=' + username.value + '&password=' + password.value + '&kamereon=' + KAMEREON_KEY,
null, // No payload required for login
{ headers: null }
)
.then(response => {
console.log("POST result for my login:", response);
// output.value = "\nPOST result for lOGIN:\n" + (JSON.stringify(response.data, null, 4));
debugCheck = response;
//////////////////////////
if (checkRenaultLoginResult(response).status != "ok") return -1; // Only if check is successful the function calls next functions to retrieve JWT, Person, Account, VIN
//////////////////////////
cookieValue.value = response.data.loginData.cookie;
JWT.value = response.data.loginData.JWT;
personId.value = response.data.loginData.personId;
getAccountId();
})
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
log.value += "\nERROR MAIN (RESPONSE) for POST while logging to Gigya:\n" + error.response.data.error + ", " + error.response.data.error_description + "\n";
console.log("ERROR MAIN (RESPONSE) for POST while logging to Gigya:\n" , error);
login4.innerHTML = "ERR_MAINresponse";
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
log.value += "\nERROR MAIN (REQUEST) for POST while logging to Gigya:\n" + error.request+ "\n";
console.log("ERROR MAIN (REQUEST) for POST while logging to Gigya:\n" , error);
login4.innerHTML = "ERR_MAINrequest";
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
log.value += "\nERROR MAIN (CONFIG) for POST while logging to Gigya:\n" + error.message+ "\n";
console.log("ERROR MAIN (CONFIG) for POST while logging to Gigya:\n" , error);
login4.innerHTML = "ERR_MAINconfig";
}
console.log(error.config);
});
//}
}
function checkRenaultLoginResult(loginResponse) {
lastStep = "checkRenaultLoginResult";
log.value += "Checking Renault login results...\n";
console.log("Checking Renault login results...",loginResponse);
if( (typeof loginResponse.data === "object") && (loginResponse.data !== null) ) {
// already object--> created by my PHP page
if (loginResponse.data.loginData !== null) return {status : "ok", data : "Login ok, cookie received"};
} else {
// convert to objject for processing
loginResponse.data = JSON.stringify(loginResponse.data);
}
try {
if (loginResponse.data.errorCode === 400002) {
console.log("ERR 002 - Cannot retrieve Renault cookie, missing login data:\n", loginResponse);
log.value += "ERR 002 - Cannot retrieve Renault cookie, missing login data:\n"+ loginResponse.data.errorDetails + "\n";
login1.innerHTML = "ERR-002";
return {status : "error 002", data : loginResponse};
}
if (loginResponse.data.errorCode === 403042) {
console.log("ERR 042 - Cannot retrieve Renault cookie, invalid login data:\n", loginResponse);
log.value += "ERR 042 - Cannot retrieve Renault cookie, invalid login data:\n"+ loginResponse.data.errorDetails + "\n";
login1.innerHTML = "ERR-042";
return {status : "error 042", data : loginResponse};
}
if (loginResponse.data.errorCode === 403120) {
console.log("ERR 120 - ", loginResponse.data.errorDetails);
log.value += "ERR 120 - " + loginResponse.data.errorDetails + "\n";
login1.innerHTML = "ERR-120";
return {status : "error 120", data : loginResponse};
}
if (loginResponse.data.errorCode != "0") {
console.log("ERR unknown - Cannot retrieve Renault cookie, login failed:\n", loginResponse);
if( (typeof loginResponse.data === "object") && (loginResponse.data !== null) ) {
toPrint = JSON.stringify(loginResponse.data,null,4);
fullError = "ERR unknown - Cannot retrieve Renault cookie, login failed:\n"+ toPrint + "\n"
} else {
toPrint = loginResponse.data;
fullError = "ERR possible wrong password - Cannot retrieve Renault cookie, login failed:\n"+ toPrint + "\n"
}
log.value += fullError;
login1.innerHTML = "ERR-UNK";
return {status : "error unknown", data : loginResponse};
}
console.log("Credentials accepted, Renault cookie retrieved: ", loginResponse.data.sessionInfo.cookieValue);
log.value += "Credentials accepted, Renault cookie retrieved.\n";
login1.innerHTML = "OK";
cookie = loginResponse.data.sessionInfo.cookieValue;
cookieValue.value = loginResponse.data.sessionInfo.cookieValue;
renaultUID = loginResponse.data.UID; // needed for Axios calls?
return {status : "ok", data : "Login ok, cookie received"};
} catch (error) {
console.log("ERR 112 - Cannot retrieve Renault cookie, error during login:\n", error,loginResponse);
log.value += "ERR 112 - Cannot retrieve Renault cookie, error during login:\n";
return {status : "error 112", data : loginResponse};
}
}
function getJWTtoken() {
lastStep = "getJWTtoken";
if (cookieValue.value.indexOf("error") >= 0) {
console.log("Cannot proceed and ask for JWT due to failed Renault login: ", error);
log.value += "Cannot proceed and ask for JWT due to failed Renault login: " + error + "\n";
return { status: "error", data: "Cannot proceed and ask for JWT due to failed Renault login: " + cookieValue.value} ;
}
JWTheaders = {
'login_token': cookieValue.value,
'apikey': KAMEREON_KEY,
'fields' : 'data.personId,data.gigyaDataCenter',
'expiration': 87000
};
console.log("====JWT");
console.log("Logged in, searching for JWT...");
log.value += "Logged in, searching for JWT...\n";
JWTurl = gigyaurl + "/accounts.getJWT?fields=data.personId%2Cdata.gigyaDataCenter&expiration=600&APIKey=" + GIGYA_API_KEY +
"&sdk=js_latest&authMode=cookie&pageURL=https%3A%2F%2Fmyr.renault.it%2F&sdkBuild=12426&format=json&login_token=" + cookieValue.value;
if (PROXY_STRING !== "") {
finalJWTurl = PROXY_STRING + encodeURIComponent(JWTurl);
} else {
finalJWTurl = JWTurl;
}
// VERSIONE CON AXIOS:
return axios.post(
finalJWTurl,
null, // No payload required for retrieving JWT
{
headers: JWTheaders
})
.then(response => {
//output.value = "\nPOST result:\n" + (JSON.stringify(response.data, null, 4));
//console.log("response.id: "+ response.data.id_token);
debugCheck = response;
if (checkJWT(response.data).status.toUpperCase() === "OK") {; // Not async, just extract JWT string from response, hence not blocking.
//////////////////////
getPersonId(); // Async function: can proceed to next step (getAccountId) only after receiving response.
//////////////////////
return { status: "ok", data: "Retrieving person id..." };
} else {
console.log("ERROR: Invalid JWT response.");
log.value += "\nERROR: Invalid JWT response.\n";
return { status: "err", data: "Invalid JWT response" };
}
})
.catch(
function (error) {
log.value += "\nERROR 001 for POST while getting JWT, please see console for details.\n";
console.log("ERROR 001 for POST while getting JWT:\n", error);
login2.innerHTML = "ERR_POST1";
console.log("POST ERROR 001:" , error)
return { status : "error", data: "POST ERROR 001b:" + error };
}
);
}
function getPersonId() {
lastStep = "getPersonId";
console.log("====personId");
console.log("Found JWT, searching for Person Id...");
log.value += "Found JWT, searching for Person Id...\n";
var personUrl = gigyaurl + "/accounts.getAccountInfo?apikey=" + GIGYA_API_KEY + "&login_token=" + cookieValue.value;
// var finalPersonurl= PROXY_STRING + encodeURIComponent(personUrl);
if (PROXY_STRING !== "") {
finalPersonurl = PROXY_STRING + encodeURIComponent(personUrl);
} else {
finalPersonurl = personUrl;
}
personHeaders = {
'login_token': cookieValue.value,
'apikey': KAMEREON_KEY,
'expiration': 87000
};
// VERSIONE CON AXIOS:
return axios.post(
finalPersonurl,
null, // No payload required for retrieveing personId
{
headers: null
})
.then(response => {
//console.log("POST result for Person:" + (JSON.stringify(response.data, null, 4)));
//output.value = "\nPOST result for Person:\n" + (JSON.stringify(response.data, null, 4));
console.log("response.id: "+ response.data.data.personId);
personIdResult = checkPersonId(response);
if (personIdResult.status.toUpperCase() == "OK") {
/////////////////////////////////
getAccountId(); // After receiving personId, proceed with getAccountId
/////////////////////////////////
return { status: "ok", data: "Retrieving account id...." };
} else {
console.log("Account id error 114:" , personIdResult);
log.value += "\nAccount id error 114\n";
}
})
.catch(
function (error) {
log.value += "\nERROR 002 for POST while getting personId:\n" + error + "\n";
console.log("ERROR 002 for POST while getting personId:\n" , error);
login3.innerHTML = "ERR_POST2";
return( {status: "error", data : "ERROR 002b:" + JSON.stringify(error, null, 4) } );
}
);
}
function getAccountId() {
lastStep = "getAccountId";
log.value += "Found Person Id, searching for accounts...\n";
console.log("====accountId");
accountUrl = kamereonurl + "/commerce/v1/persons/" +
personId.value +
"?apikey=" + KAMEREON_KEY +
"&country=" + country.value;
console.log("URL PER ACCOUNT: " + accountUrl);
accountHeaders = {
'apikey': KAMEREON_KEY,
'x-gigya-id_token' : JWT.value
};
// VERSIONE CON AXIOS:
return axios.get(
accountUrl,
{
headers: accountHeaders
}
)
.then(response => {
console.log("Account response received, processing...");
accountIdExtractionResut = extractAccountId(response.data); // Not blocking, just extracting string from response.
console.log("Account response processed:", accountIdExtractionResut);
///////////////////////////////
getVINs(accountIdExtractionResut); //After retrieving accountId, proceed wirh getVin
///////////////////////////////
return {status: "ok", data : "Account retrieved, retrieving VIN..."};
})
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
log.value += "\nERROR 002b (RESPONSE) for POST while getting accountId:\n" + error.response.data.error + ", " + error.response.data.error_description + "\n";
console.log("ERROR 002b (RESPONSE) for POST while getting accountId:\n" , error);
login4.innerHTML = "ERR_POST2";
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
log.value += "\nERROR 002c (REQUEST) for POST while getting accountId:\n" + error.request+ "\n";
console.log("ERROR 002c (REQUEST) for POST while getting accountId:\n" , error);
login4.innerHTML = "ERR_POST2c";
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
log.value += "\nERROR 002d (CONFIG) for POST while getting accountId:\n" + error.message+ "\n";
console.log("ERROR 002d (CONFIG) for POST while getting accountId:\n" , error);
login4.innerHTML = "ERR_POST2c";
}
console.log(error.config);
});
}
function getVINs(accountIdResult) {
lastStep = "getVINs";
console.log("=== VIN");
if (accountIdResult.status.toUpperCase().indexOf("OK") === false) {
log.value += "\nERROR 004: accountId not found, cannot extract VIN, please see console for details.";
console.log("ERROR 004: accountId not found, cannot extract VIN: ", accountIdResult);
login1.innerHTML = "ERR_EXTR_ACC";
return ({ status: "ERROR 004", data: accountIdResult });
} else {
// go on
}
console.log("Found account, searching for VIN...");
log.value += "Found account, searching for VIN...\n";
vehiclesListQueryUrl = kamereonurl + "/commerce/v1/accounts/" +
accountId2.value +
"/vehicles" +
"?apikey=" + KAMEREON_KEY +
"&country=" + country.value;
console.log("vehiclesListQueryUrl ", vehiclesListQueryUrl);
accountHeaders = {
'apikey': KAMEREON_KEY,
'x-gigya-id_token' : JWT.value
};
// VERSIONE CON AXIOS:
return axios.get(
vehiclesListQueryUrl,
{
headers: accountHeaders
}
)
.then(response => {
console.log("POST result for VIN:" + (JSON.stringify(response.data, null, 4)));
output.value = "\nPOST result for VIN:\n" + (JSON.stringify(response.data, null, 4));
//console.log("response VIN: ", response);
checkVIN(response.data);
})
.catch(
function (error) {
log.value += "\nERROR 003 for POST while getting VIN:\n" + error + "\n";
console.log("ERROR 003 for POST while getting VIN:\n" + error);
console.log("POST ERROR 003:" ,error)
login1.innerHTML = "ERR_POST";
return ({ status: "POST ERROR 003 (VIN)", data: response.data });
}
);
}
////////////////////////////////////////////////
function getVehicleData() {
lastStep = "getVehicleData";
log.value +="\n\nLOGIN SUCCESSFUL.\nSending query...\n";
console.log("=== QUERY");
if ((endpoint.value).indexOf("?") >0 ) { // in case quetion mark is included in manual input...
QUESTION_MARK = "&";
} else {
QUESTION_MARK = "?";
}
queryUrl = kamereonurl + "/commerce/v1/accounts/" +
accountId.value +
"/kamereon/kca/car-adapter/v1/cars/" + MY_VIN.value +
"/" +
endpoint.value +
QUESTION_MARK +
"apikey=" + KAMEREON_KEY +
"&country=" + country.value;
console.log("finalQueryUrl ", queryUrl);
queryHeaders = {
'apikey': KAMEREON_KEY,
'x-gigya-id_token' : JWT.value,
'Content-type' : 'application/vnd.api+json'
//'expiration': 87000
};
actionPayload = actionPayloadSpan.value;
// VERSIONE CON AXIOS:
return axios.post(
queryUrl,
actionPayload,
{
headers: queryHeaders
})
.then(response => {
console.log("Axios POST result for vehicle data:" + (JSON.stringify(response.data, null, 4)));
output.value = "\nAxios POST result for vechile data:\n" + (JSON.stringify(response.data, null, 4));
console.log("response: ", response);
return ({ status: "OK", data: response });
})
.catch((error) => {
if (error.response) {
console.log(error.response);
wholeError = error.response;
errorMessage = wholeError.data.errors[0].errorMessage;
cleanedErrorMessage = errorMessage.split(slash).join(empty);
JSONerrorMessage = JSON.parse(cleanedErrorMessage);
console.log(">>>> getVehicleData - Final error:", JSONerrorMessage);
output.value = JSON.stringify(JSONerrorMessage, null, 4);
console.log("QUERY FINISHED");
return ({ status: "VIN ERROR", data: response });
}
}
);
}
////////////////////////////////////////////////
function checkJWT(JWTresponse) {
lastStep = "checkJWT";
//console.log("JWTresponse:" , JWTresponse);
// var JSONdata = JSON.parse(JWTresponse);
//console.log("Extracted:" , JSONdata);
console.log("JWT response received. Analysing...", JWTresponse);
log.value +="JWT response received. Analysing...\n";
try {
JWT.value = JWTresponse.id_token;
login2.innerHTML = "OK";
loginPayloadForReqbin.innerHTML = "<pre>apikey :" + KAMEREON_KEY + "<br>" +
"Content-type : application/vnd.api+json<br>" +
"x-gigya-id_token : " + JWTresponse.id_token + "<br></pre>";
return {status: "OK", data : JWTresponse};
} catch (error) {
return {status: "error in JWT check", data : JWTresponse};
}
}
function checkPersonId(personIdResponse) {
lastStep = "checkPersonId";
console.log("========personId extraction");
console.log("personId response received, analysing..." , personIdResponse);
log.value += "personId response received, analysing...\n";
try {
if (personIdResponse.data.errorCode != "0") {
console.log("ERR unknwon - Cannot extract personId from response:\n", personIdResponse);
log.value += "ERR unknown - Cannot extract personId from response:\n" + personIdResponse;
login3.innerHTML = "ERR";
return {status: "error" , data : personIdResponse};
}
console.log("personId successfully extracted: " + personIdResponse.data.data.personId);
log.value += "personId successfully extracted.\n";
login3.innerHTML = "OK";
personId.value = personIdResponse.data.data.personId;
return {status : "OK", data : personIdResponse};
} catch (error) {
console.log("Error extracting personid" , personIdResponse);
log.value += "\nError extracting personid.\n";
return {status: "error", data : personIdResponse};
}
}
function extractAccountId(accountIdResponse) {
lastStep = "extractAccountId";
console.log("========accountId extraction", accountIdResponse);
console.log("accountId response received, analysing...");// , personIdResponse);
log.value += "accountId response received, analysing...\n";
//var JSONdata = accountIdResponse;
if (accountIdResponse.accounts === null) {
console.log("ERR unknwon - No accounts found in response:\n", accountIdResponse);
log.value += "ERR unknown - No accounts found in response:\n" + JSON.stringify(accountIdResponse, null, 4);
login4.innerHTML = "JSON_ERR";
return ({ status: "error", data: accountIdResponse });
}
try {
accountId.value = accountIdResponse.accounts[0].accountId;
accountIdType.value = accountIdResponse.accounts[0].accountType;
accountId2.value = accountIdResponse.accounts[1].accountId;
accountId2Type.value = accountIdResponse.accounts[1].accountType;
login4.innerHTML = "OK";
console.log("accountId successfully extracted", accountId.value, accountId2.value);
log.value += "accountId successfully extracted.\n";
return ({ status: "OK", data: accountIdResponse });
} catch (error) {
console.log("\nJSON ERROR - Cannot extract accountId from response:\n", accountIdResponse);
log.value += "\nJSON ERROR - Cannot extract accountId from response:\n" + JSON.stringify(accountIdResponse, null, 4);
login4.innerHTML = "JSON_ERR2";
return ({ status: "error in accountId extraction", data: accountIdResponse });
}
}
function showVehicleData(index) {
data = globalVehicles[index];
try {
data = globalVehicles[index];
try {
details = data.vehicleDetails;
} catch (err) {
details = "n/a";
}
try {
brand = data.brand;
} catch (err) {
brand = "n/a";
}
try {
model = details.model.label;
} catch (err) {
model = "n/a";
}
try {
regNum = details.registrationNumber;
} catch (err) {
regNum = "n/a";
}
try {
regDate = details.registrationDate;
} catch (err) {
regDate = "n/a";
}
try {
engType = details.engineType;
} catch (err) {
engType = "n/a";
}
try {
engRatio = details.engineRatio;
} catch (err) {
engRatio = "n/a";
}
try {
batLabel = details.battery.label;
} catch (err) {
batLabel = "n/a";
}
try {
owner = data.linkType;
} catch (err) {
owner = "n/a";
}
vehicleDetails.innerHTML = brand + " " + model + ', ' + regNum + " (" + regDate + ") , engine type: " + engType +
", engine ratio: " + engRatio + ', Battery: ' + batLabel + ", Ownership:" + owner;
} catch (err) {
data = "no data available";
vehicleDetails.innerHTML = data;
}
}
function checkVIN(VINResponse) {
lastStep = "checkVIN";
console.log("============ VIN:" , VINResponse);
console.log("VIN response recevied, analysing..."); // , VINResponse);
log.value += "VIN response recevied, analysing...\n";
if (VINResponse.vehicleLinks === null) { // No error=0 in case of success!
console.log("ERR unknwon - Cannot extract VIN from response, no vehicles array:\n", VINResponse);
log.value += "\nERR unknown - Cannot extract VIN from response, no vehicles array, please see console for dertails.\n";
login5.innerHTML = "ERR";
login6.innerHTML = "<b>LOGIN FAILED<b>";
return ({ status: "error in VIN extraction, no vehicles array", data: VINResponse });