-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html.bak
1436 lines (1159 loc) · 43 KB
/
index.html.bak
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 name="generator" content="PSPad editor, www.pspad.com">
<title>Unofficial MyRenault dashboard for browsers</title>
<script src="myrenault-public.js?dummy=new"></script>
<script src="endpoints.js?dummy=new"></script>
<script src="errors.js?dummy=new"></script>
<script src="payloads.js?dummy=new"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
// 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
GIGYA_API_KEY = null;
KAMEREON_KEY = null;
JWTextracted = null;
countdownStarted = false;
lastStep = "start";
empty = "";
slash = "\\";
fuelQuantity = {"path" : "", "value" : ""};
fuelAutonomy = {"path" : "", "value" : ""};
totalMileage = {"path" : "", "value" : ""};
gpsLatitude = {"path" : "", "value" : ""};
gpsLongitude = {"path" : "", "value" : ""};
v1_chargeStatus = {"path" : "", "value" : ""};
v1_rangeHvacOn = {"path" : "", "value" : ""};
v1_plugStatus = {"path" : "", "value" : ""};
v1_batteryLevel = {"path" : "", "value" : ""};
v2_batteryLevel = {"path" : "", "value" : ""};
v2_batteryTemperature = {"path" : "", "value" : ""};
v2_batteryAutonomy = {"path" : "", "value" : ""};
v2_batteryCapacity = {"path" : "", "value" : ""};
v2_batteryAvailableEnergy = {"path" : "", "value" : ""};
v2_plugStatus = {"path" : "", "value" : ""};
v2_chargingStatus = {"path" : "", "value" : ""};
v2_chargingRemainingTime = {"path" : "", "value" : ""};
v2_chargingInstantaneousPower = {"path" : "", "value" : ""};
hvacStatus = {"path" : "", "value" : ""};
internalTemperature = {"path" : "", "value" : ""};
HVAC_mode = {"path" : "", "value" : ""};
globalTargetTemperature = {"path" : "", "value" : ""};
HVACschedules = {"path" : "", "value" : ""};
HVACcalendar = {"path" : "", "value" : ""};
chargeMode = {"path" : "", "value" : ""};
chargeSchedules = {"path" : "", "value" : ""};
chargeCalendar = {"path" : "", "value" : ""};
results = [];
// 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 init() {
gigyaurl = data.servers.gigyaProd.target;
GIGYA_API_KEY= newData.servers.gigyaProd.apikey;
kamereonurl = data.servers.wiredProd.target;
KAMEREON_KEY = newData.servers.wiredProd.apikey;
}
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 loadEndpoints() {
CR = document.createElement("BR");
for (var i=0; i<endpointsList.length; i++) {
var endpointUrl= document.createElement("A");
endpointUrl.setAttribute("onclick", "callByClick('" + endpointsList[i].name + "')");
//endpointUrl.setAttribute("HREF", "");
//console.log(endpointUrl);
endpoints.appendChild(endpointUrl);
endpoints.appendChild(CR);
endpointUrl.innerHTML = endpointsList[i].name+ "<br>";
}
};
*/
function callByClick(endp, libVer) {
// Called when clicked on endpoint
endpoint.value = endp;
output.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 += "\nREQ - XHR timeout error.\n";
reject('timeout');
}
xhr.onerror = function (e) {
console.log("REQ - XHR error: ", e , "\n");
log.value += "\nREQ - 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 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 = "";
log.value +="Sending query...\n";
console.log("=== DIRECT 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/v" + libraryVersion + "/cars/" + MY_VIN.value +
"/" +
endpoint.value +
QUESTION_MARK +
"apikey=" + KAMEREON_KEY +
"&country=" + country.value;
console.log("finalQueryUrl ", queryUrl);
console.log("Sending query by REQUEST v." + libraryVersion + "...");
if (endpoint.value.indexOf("actions") >= 0) {
kamereonPost(JWT.value, endpoint.value, actionPayloadSpan.value, libraryVersion, "", "")
} else {
kamereonGet(JWT.value, endpoint.value, libraryVersion)
}
/* const sendQuery = request(queryUrl, true, null, "get");
sendQuery
.then(showResults)
.catch(vehicleError)
return ("query finished.");*/
}
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() {
log.value = "Endpoint: " + endpoint.value + "\n";
cookieValue.value="waiting...";
JWT.value = "waiting...";
personId.value = "waiting...";
accountId.value = "waiting...";
accountId2.value = "waiting...";
init();
login1.innerHTML = "-";
login2.innerHTML = "-";
login3.innerHTML = "-";
login4.innerHTML = "-";
login5.innerHTML = "-";
login6.innerHTML = " logging in...";
loginUrl = gigyaurl + "/accounts.login?loginID=" + username.value + "&password=" + password.value + "&apikey=" + GIGYA_API_KEY;
finalLoginURL = "http://win98.altervista.org/space/exploration/myp.php?pass=miapass&mode=native&url=" + encodeURIComponent(loginUrl);
path1 = "sessionInfo";
path2 = "cookieValue";
/*
const requestsList = request(finalLoginURL, null, null, "get");
requestsList
.then(initialLogin)
.then(getJWTtoken)
.catch(errore)
*/
// VERSIONE CON AXIOS:
return axios.post(
finalLoginURL,
null, // No payload required for login
{
headers: {'apikey': KAMEREON_KEY}
})
.then(response => {
//console.log("POST result for lOGIN:" + (JSON.stringify(response.data, null, 4)));
//output.value = "\nPOST result for lOGIN:\n" + (JSON.stringify(response.data, null, 4));
return (JSON.stringify(response.data));
})
.then(initialLogin)
.then(getJWTtoken)
.catch(
function (error) {
log.value += "\nERROR for lOGIN:\n" + error + "\n";
console.log("ERROR for lOGIN:\n" + error);
login1.innerHTML = "ERR_LOGIN";
console.log(error)
}
);
}
function initialLogin(loginResponse) {
lastStep = "initialLogin";
log.value += "Renault login...\n"
console.log("Renault login RAW:",loginResponse);
loginResult = JSON.parse(loginResponse);
console.log("Renault login parsed:",loginResult);
log.value +="Login response received. Analysing...";
if (loginResult.errorCode === 400002) {
console.log("ERR 002 - Cannot retrieve Renault cookie, missing login data:\n"+ loginResult.errorDetails);
log.value += "ERR 002 - Cannot retrieve Renault cookie, missing login data:\n"+ loginResult.errorDetails + "\n";
login1.innerHTML = "ERR-002";
return "error 002";
}
if (loginResult.errorCode === 403042) {
console.log("ERR 042 - Cannot retrieve Renault cookie, invalid login data:\n"+ loginResult.errorDetails);
log.value += "ERR 042 - Cannot retrieve Renault cookie, invalid login data:\n"+ loginResult.errorDetails + "\n";
login1.innerHTML = "ERR-042";
return "error 042";
}
if (loginResult.errorCode != "0") {
console.log("ERR unknwon - Cannot retrieve Renault cookie, login failed:\n"+ loginResult.errorDetails);
log.value += "ERR unknown - Cannot retrieve Renault cookie, login failed:\n"+ loginResult.errorDetails + "\n";
login1.innerHTML = "ERR-UNK";
return "error unknown";
}
console.log("Credentials accepted, Renault cookie retrieved.");
log.value += "\nCredentials accepted, Renault cookie retrieved.";
login1.innerHTML = "OK";
cookie = loginResult.sessionInfo.cookieValue;
renaultUID = loginResult.UID; // needed for Axios calls?
cookieValue.value = loginResult.sessionInfo.cookieValue;
//console.log("Cookie=", loginResult.sessionInfo.cookieValue);
return(loginResult.sessionInfo.cookieValue)
}
function getJWTtoken(cookie) {
lastStep = "getJWTtoken";
if (cookie.indexOf("error") >= 0) {
console.log("Cannot proceed and ask for JWT due to failed login.");
return cookie;
}
JWTheaders = {
'login_token': cookie,
'apikey': KAMEREON_KEY,
'fields' : 'data.personId,data.gigyaDataCenter',
'expiration': 87000
};
console.log("====JWT");
console.log("Logged in, searching for JWT...");
log.value += "\nLogged in, searching for JWT...\n";
console.log("====JWT");
JWTurl = "https://gigya-it-it.renault.it/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=" + cookie;
finalJWTurl= "http://win98.altervista.org/space/exploration/myp.php?pass=miapass&mode=native&url=" + encodeURIComponent(JWTurl);
//console.log("Processing ", finalJWTurl);
// VERSIONE CON AXIOS:
return axios.post(
finalJWTurl,
null, // No payload required for retrieveing JWT
{
headers: JWTheaders
})
.then(response => {
//console.log("POST result:" + (JSON.stringify(response.data, null, 4)));
//output.value = "\nPOST result:\n" + (JSON.stringify(response.data, null, 4));
//console.log("response.id: "+ response.data.id_token);
return ({ status: "ok", data: response.data.id_token });
})
.then(
response2 => {
//console.log("Pippo", response2);
//console.log("Pippo2", response2.data);
extractJWT(response2.data);
return "Che ne so?";
}
)
.then (
response3 => {
//console.log("Pippo3", response3);
getPersonId();
//extractJWT(response.data);
}
)
.catch(
function (error) {
log.value += "\nERROR for POST while getting JWT:\n" + error + "\n";
console.log("ERROR for POST while getting JWT:\n" + error);
login2.innerHTML = "ERR_POST";
console.log(error)
}
);
/* VERSIONE CON REQUEST():
const JWTrequest = request(finalJWTurl,null ,null , "get");
JWTrequest
.then(extractJWT)
.then(getPersonId)
.catch(JWTerror)
return (cookie);
}
*/
}
function getPersonId(dummy) {
lastStep = "getPersonId";
console.log("====personId");
console.log("Found JWT, searching for Person Id...");
var personUrl = gigyaurl + "/accounts.getAccountInfo?apikey=" + GIGYA_API_KEY + "&login_token=" + cookieValue.value;
var finalPersonurl= "http://win98.altervista.org/space/exploration/myp.php?pass=miapass&mode=native&url=" + encodeURIComponent(personUrl);
personHeaders = {
'login_token': cookie,
'apikey': KAMEREON_KEY,
'expiration': 87000
};
// VERSIONE CON AXIOS:
return axios.post(
finalPersonurl,
null, // No payload required for retrieveing personId
{
headers: personHeaders
})
.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);
return ({ status: "ok", data: response.data.data.personId });
})
.then (response2 => {
//console.log("POST result for Person2:" + (JSON.stringify(response2, null, 4)));
//output.value = "\nPOST result for Person:\n" + (JSON.stringify(response.data, null, 4));
console.log("response2: ", response2);
personId.value = response2.data
login3.innerHTML = "OK";
getAccountId("pippo");
return ({ status: "ok", data: null });
})
.catch(
function (error) {
log.value += "\nERROR for POST while getting personId:\n" + error + "\n";
console.log("ERROR for POST while getting personId:\n" + error);
console.log(error)
login3.innerHTML = "ERR_POST";
}
);
/* VERSIONE CON REQUEST():
const personIdRequest = request(finalPersonurl,null,null, "post");
personIdRequest
.then(extractPersonId)
.then(getAccountId)
.catch(personIdError)
return (cookie);
*/
}
function getAccountId(dummy) {
lastStep = "getAccountId";
log.value += "\n\nFound Person Id, searching for accounts...";
console.log("====accountId");
accountUrl = kamereonurl + "/commerce/v1/persons/" +
personId.value +
"?apikey=" + KAMEREON_KEY +
"&country=" + country.value;
var finalAccounturl= "http://win98.altervista.org/space/exploration/myp.php?pass=miapass&mode=native&url=" + encodeURIComponent(accountUrl);
console.log("URL PER ACCOUNT: " + accountUrl);
accountHeaders = {
'apikey': KAMEREON_KEY,
'x-gigya-id_token' : JWT.value
//'expiration': 87000
};
// VERSIONE CON AXIOS:
return axios.get(
accountUrl,
{
headers: accountHeaders
}
)
.then(response => {
//console.log("POST result for Account:" + (JSON.stringify(response.data, null, 4)));
//output.value = "\nPOST result for Person:\n" + (JSON.stringify(response.data, null, 4));
console.log("response: ", response);
extractAccountId(response.data);
getVINs();
return ({ status: "ok", data: response.data });
})
.catch(
function (error) {
log.value += "\nERROR for POST while getting accountId:\n" + error + "\n";
console.log("ERROR for POST while getting accountId:\n" + error);
login4.innerHTML = "ERR_POST";
console.log(error)
}
);
/* VERSIONE CON REQUEST():
const accountIdRequest = request(accountUrl, true,null, "get");
accountIdRequest
.then(extractAccountId)
.then(getVINs)
.catch(accountIdError)
*/
return (cookie);
}
function getVINs(a) {
lastStep = "getVINs";
console.log("=== VIN");
console.log("Found account, searching for VIN...");
log.value += "\n\nFound account, searching for VIN...";
vehiclesListQueryUrl = kamereonurl + "/commerce/v1/accounts/" +
accountId2.value +
"/vehicles" +
"?apikey=" + KAMEREON_KEY +
"&country=" + country.value;
finalVehiclesListQueryUrl= "http://win98.altervista.org/space/exploration/myp.php?pass=miapass&mode=native&url=" + encodeURIComponent(vehiclesListQueryUrl);
console.log("vehiclesListQueryUrl ", vehiclesListQueryUrl);
accountHeaders = {
'apikey': KAMEREON_KEY,
'x-gigya-id_token' : JWT.value
//'expiration': 87000
};
// 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: ", response);
return ({ status: "ok", data: response.data });
})
.then(response2 => {
//console.log("Extract VIN from:" + (JSON.stringify(response2, null, 4)));
//output.value = "\nPOST result for VIN:\n" + (JSON.stringify(response.data, null, 4));
console.log("response2: ", response2);
extractVIN(response2.data);
return ({ status: "ok", data: response2.data });
})
.catch(
function (error) {
log.value += "\nERROR for POST while getting VIN:\n" + error + "\n";
console.log("ERROR for POST while getting VIN:\n" + error);
console.log(error)
login1.innerHTML = "ERR_POST";}
);
/* VESIONE CON REQUEST():
const sendQuery = request(vehiclesListQueryUrl, true,null, "get");
sendQuery
.then(extractVIN)
.then(getVehicleData)
.catch(vehicleError)
*/
return ("query finished.");
}
////////////////////////////////////////////////
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.replaceAll(slash, empty );
JSONerrorMessage = JSON.parse(cleanedErrorMessage);
console.log(">>>> getVehicleData - Final error:", JSONerrorMessage);
output.value = JSON.stringify(JSONerrorMessage, null, 4);
}
}
/*
function (error) {
log.value += "\nERROR for POST while getting vehicle data:\n" + error + "\n";
console.log("ERROR for POST while getting vehicle data:\n" + error);
console.log(error)
}
*/
);
/* VERSIONE CON REQUEST():
const sendQuery = request(queryUrl, true, actionPayloadSpan.value, "get");
sendQuery
.then(showResults)
.catch(vehicleError)
*/
console.log("QUERY FINISHED");
return ("\n\n ==== Query finished ====");
}
////////////////////////////////////////////////
function extractJWT(JWTresponse) {
lastStep = "extractJWT";
//console.log("JWTresponse:" , JWTresponse);
// var JSONdata = JSON.parse(JWTresponse);
//console.log("Extracted:" , JSONdata);
console.log("JWT response received. Analysing...");
log.value +="JWT response received. Analysing...";
log.value +="\nJWT correctly retrieved.";
console.log("JWT correctly retrieved.");
JWT.value = JWTresponse; //JSONdata.id_token;
login2.innerHTML = "OK";
loginPayloadForReqbin.innerHTML = "<pre>apikey :" + KAMEREON_KEY + "<br>" +
"Content-type : application/vnd.api+json<br>" +
"x-gigya-id_token : " + JWTresponse + "<br></pre>";
return JWTresponse;
}
function extractPersonId(personIdResponse) {
lastStep = "extractPersonId";
console.log("========personId extraction");// , personIdResponse);
console.log("personId response received, analysing...");// , personIdResponse);
log.value += "\npersonId response received, analysing...";
var JSONdata = JSON.parse(personIdResponse);
console.log("personId response:" , JSONdata);
if (JSONdata.errorCode != "0") {
console.log("ERR unknwon - Cannot extract personId from response:\n", JSONdata);
log.value += "ERR unknown - Cannot extract personId from response:\n" + personIdResponse;
login3.innerHTML = "ERR";
return "Error on personId extraction:" + personIdResponse;
}
console.log("personId successfully extracted:" + JSONdata.data.personId);
log.value += "\n\npersonId successfully extracted:\n" + JSONdata.data.personId;
login3.innerHTML = "OK";
personId.value = JSONdata.data.personId;
renaultUID2 = JSONdata.UID;
console.log(">>>>>>>>>>UIDS:", renaultUID, renaultUID2);
}
function extractAccountId(accountIdResponse) {
lastStep = "extractAccountId";
console.log("========accountId extraction", accountIdResponse);
console.log("accountId response received, analysing...");// , personIdResponse);
log.value += "\naccountId response received, analysing...";
var JSONdata = /*JSON.parse(*/accountIdResponse/*)*/;
if (JSONdata.accounts === null) { // No error=0 in case of success!
console.log("ERR unknwon - Cannot extract accountId from response:\n", accountIdResponse);
log.value += "ERR unknown - Cannot extract accountId from response:\n" + accountIdResponse;
login4.innerHTML = "ERR";
return "Error on accountId extraction:" + accountIdResponse;
}
accountId.value = JSONdata.accounts[0].accountId;
accountIdType.value = JSONdata.accounts[0].accountType;
accountId2.value = JSONdata.accounts[1].accountId;
accountId2Type.value = JSONdata.accounts[1].accountType;
login4.innerHTML = "OK";
console.log("accountId successfully extracted:" + JSONdata.accounts[0].accountId + ", " + JSONdata.accounts[1].accountId);
log.value += "\n\naccountId successfully extracted:\n" + JSONdata.accounts[0].accountId + ", " + JSONdata.accounts[1].accountId;
}
function extractVIN(VINResponse) {
lastStep = "extractVIN";
console.log("============ VIN:" , VINResponse);
console.log("VIN response recevied, analysing..."); // , VINResponse);
log.value += "\nVIN response recevied, analysing...";
var JSONdata = /*JSON.parse(*/VINResponse/*)*/;
console.log("VINResponse obj: " , JSONdata);
if (JSONdata.vehicleLinks === null) { // No error=0 in case of success!
console.log("ERR unknwon - Cannot extract VIN from response:\n", JSONdata);
log.value += "ERR unknown - Cannot extract VIN from response:\n" + VINResponse;
login5.innerHTML = "ERR";
login6.innerHTML = "<b>LOGIN FAILED<b>";
return "Error on VIN extraction:" + VINResponse;
}
MY_VIN.value = JSONdata.vehicleLinks[0].vin;
login5.innerHTML = "OK";
loginTime = new Date();
loginString = loginTime.getHours() + ":" + loginTime.getMinutes();
login6.innerHTML = "<b>Successfully logged in at " + loginString + "</b>";
startCountdown();
var testlink = kamereonurl + "/commerce/v1/accounts/" +
accountId.value +
"/kamereon/kca/car-adapter/v1/cars/" + MY_VIN.value +
"/" +
"cockpit" +
"?" +
"apikey=" + KAMEREON_KEY +
"&country=" + country.value;
testUrlReqbin.innerHTML = "<a href='" + testlink + "'>" + testlink + "</a><br>" ;
console.log("VIN successfully extracted:" + JSONdata.vehicleLinks[0].vin);
log.value += "\n\nVIN successfully extracted:\n" + JSONdata.vehicleLinks[0].vin;
}
function showResults(queryResponse) {
lastStep = "showResults";
console.log("queryResponse:", queryResponse);
// document.getElementById("status").innerHTML = queryResponse;
JSONdataFinal = JSON.parse(queryResponse);
console.log("Extracted:" , JSONdataFinal);
output.value = "Results for endpoint " + endpoint.value + ":\n" + (JSON.stringify(JSONdataFinal, null, 4)).replace(MY_VIN.value,"xxxMYVINxxx"); ;
}
function errore(e) {
console.log("Errore in login:" + e);
log.value += "\nErrore in login:" + e;
return ("Errore");
}
function JWTerror(e) {
console.log("Errore JWT: " + e);
log.value += "\nErrore in JWT:" + e;
JWT.value="JWT error";
return ("!!!!!!!!!!!!Errore JWT");
}
function personIdError(e) {
console.log(e);
log.value += "\nErrore in personId:" + e;
personId.value = "!!!!!!!!!!!! Person Id error";
return ("Errore PersonId");
}
function accountIdError(e) {
console.log(e);
accountId.value = "!!!!!!!!!!!! Account ID error";
log.value += "\nErrore in accountId:" + e;
return ("Errore accountId");
}
function vehicleError(e) {
console.log(e);
log.value += "!\nVehicle query error";
return ("Errore PersonId");
}
function startCountdown() {
if (countdownStarted) return;
countdownStarted = true;
var minute = 10;
var sec = 59;
if (myInterval != null) clearInterval(myInterval);
var myInterval=setInterval(function() {
document.getElementById("countdown").innerHTML = minute + " : " + sec;
sec--;
if (sec == 00) {
minute --;
sec = 59;
if (minute == 0) {
clearInterval(myInterval);
login1.innerHTML = "Expired";
login2.innerHTML = "Expired";
login3.innerHTML = "Expired";
login4.innerHTML = "Expired";
login5.innerHTML = "Expired";
login6.innerHTML = "Expired";
alert("New login required!");
countdownStarted = false;
}
}
}, 1000);
}
function kamereonGet(id_token, path, version) {
// https://github.com/joco73/se.cohen.renaultze/blob/a597635a3a6365be6a8e6edb650a4b8f986b877f/lib/api.js#L372
console.log("Sending Axios GET request for '" + path + "' using library version " + version + "...");
log.value = "Sending Axios GET request for '" + path + "' using library version " + version + "...\n";
if (path.indexOf("?") > 0 ) { // in case quetion mark is included in manual input...
QUESTION_MARK = "&";
} else {
QUESTION_MARK = "?";
}
var fullUrl = kamereonurl + '/commerce/v1/accounts/' + accountId.value + "/kamereon/kca/car-adapter/v" + version + "/cars/" + MY_VIN.value + "/" + path +
QUESTION_MARK +
"country=" +
country.value;
return axios.get(
fullUrl, {
headers: {
'x-gigya-id_token': id_token,
'apikey': KAMEREON_KEY
//'expiration': 87000
}
})
.then(response => {
console.log("Axios GET successful.", response);// for '" + path + "' with version " + version + "':" + (JSON.stringify(response.data, null, 4)).replace(MY_VIN.value, "xxx MY VIN xxx"));
output.value = "\nAxios GET successful:\n" + (JSON.stringify(response.data, null, 4)).replace(MY_VIN.value, "xxx MY VIN xxx");
selectedEndpoint = endpointsList[EP_list.selectedIndex]
fo (var i=0; i<selectedEndpoint.response.length; i++) {
paramName = selectedEndpoint.response[i].name;
console.log("Assegno ", response.data[paramName] , " a " , paramName );
results[paramName] = response.data[paramName];
}
return ({ status: "ok", data: response.data });
}).catch((error) => {
if (error.response) {
console.log(error.response);
wholeError = error.response;
errorMessage = wholeError.data.errors[0].errorMessage;
cleanedErrorMessage = errorMessage.replaceAll(slash, empty );
try {
JSONerrorMessage = JSON.parse(cleanedErrorMessage);
} catch {
// Non JSON error response
console.log("Axios POST - Final error for " + path + " :", cleanedErrorMessage);
output.value = cleanedErrorMessage;
return;
}