forked from legoandmars/nightscout-chrome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
822 lines (787 loc) · 30.3 KB
/
background.js
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
var secondVal = 10;
var addToUrl = '/api/v1/entries.json?count=';
var urgentLowValue;
var lowValue;
var highValue;
var urgentHighValue;
var refreshGraphFunc;
//default variables
var defaultSite = '';
var defaultUrgentLowValue = 55;
var defaultLowValue = 80;
var defaultHighValue = 180;
var defaultUrgentHighValue = 260;
var snoozeMinutesDefault = 30;
//array of ALL storage --important
var storageArray = [{
siteUrl: defaultSite
}, {
bsTable: "dne"
}, {
dataAmount: 7
}, {
alarmValues: [
[defaultUrgentLowValue, true],
[defaultLowValue, true],
[defaultHighValue, true],
[defaultUrgentHighValue, true]
]
},
{
lastAlarmName: "dne"
}, {
snoozeUnix: "dne"
}, {
snoozeMinutes: snoozeMinutesDefault
}, {
unitValue: "mgdl"
}, {
tempBsTable: "dne"
}, {
gottenProfileAlarms: false
}, {
lastProfileUrl: ""
}, {
colors:false
},{
gottenColors:false
}
];
var storageInc = 0; //used for looping through storage
function saveStorageData(callbackFunction){
chrome.storage.local.get(storageArray[storageInc], function(data){
chrome.storage.local.getBytesInUse(Object.keys(data), function(bytes){
//console.log(bytes+"BYTES")
if(bytes==0){
//does not exist. make sure to set default.
chrome.storage.local.set(storageArray[storageInc], function(){
console.log("SET "+Object.keys(storageArray[storageInc])+" TO "+Object.values(storageArray[storageInc]));
storageInc++;
if(storageInc < storageArray.length){
//do it again.
saveStorageData(callbackFunction)
}else{
if(callbackFunction){
//go back to loaddefaultvariables function.
callbackFunction();
}
}
});
}else{
//add 1 anyways.. we still need to go up
storageInc++;
if(storageInc < storageArray.length){
//do it again.
saveStorageData(callbackFunction)
}else{
if(callbackFunction){
//go back to loaddefaultvariables function.
callbackFunction();
}
}
}
});
});
}
function loadDefaultVariables(){
saveStorageData(function(){
console.log("Extension done with initial load!");
webRequest();
})
}
chrome.runtime.onInstalled.addListener(function() {
//note: please clean this code up >_>
loadDefaultVariables();
});
//get data from nightscout!
//https://test.herokuapp.com/api/v1/entries <- link stuff
function forceRefreshGraph() {
if (refreshGraphFunc) {
refreshGraphFunc();
}
}
function setGraphFunction(callbackFunction) {
refreshGraphFunc = callbackFunction;
}
function notifClear(id) {
setTimeout(function() {
chrome.notifications.clear(id, function() {
//console.log("wow it cleared!");
})
}, 10000);
}
function clearById(id) {
chrome.notifications.clear(id, function() {
console.log("cleared succesfully!");
})
}
function unitToProperString(unitType) {
//yes i made a function for one if/else statement, deal with it
if (unitType == "mgdl") {
return "mg/dL";
} else if (unitType == "mmol") {
return "mmol/L";
}
}
function saveNotifID(notifID) {
chrome.storage.local.set({
lastAlarmName: notifID
}, function() {
console.log("Notification Sent!");
//notification has been sent. do nothing.
});
}
//notification functions
function notificationFunction(bgValue, dateValue, valueText, unitType) {
var tempColor;
if (valueText != "Low" && valueText != "High") return;
//chrome.browserAction.setBadgeBackgroundColor({color:tempColor});
chrome.storage.local.get(['lastAlarmName'], function(lastAlarmRaw) {
var lastAlarmString = Object.values(lastAlarmRaw)[0];
//audioNotification()
//now, see if it's snoozed.
chrome.storage.local.get(['snoozeUnix'], function(snoozeUnixRaw) {
var snoozeUnixString = Object.values(snoozeUnixRaw)[0];
//now we can see if the snooze has been within x (default 30?? minutes)
chrome.storage.local.get(['snoozeMinutes'], function(snoozeMinutesRaw) {
var snoozeMinutesVal = Number(Object.values(snoozeMinutesRaw)[0]);
if (snoozeMinutesVal == 0) {
//just for old users who don't have old variables.
snoozeMinutesVal = 30;
}
var snoozeVal;
if (snoozeUnixString != "dne") {
var snoozeUnixTemp = Math.round((new Date()).getTime() / 1000);
//compare
var snoozeDiff = -(Number(snoozeUnixString) - Number(snoozeUnixTemp)); //yes i double negated this. got a problem with it?
console.log("SNOOZED FOR " + (snoozeMinutesVal - (snoozeDiff / 60)).toString() + " MORE MINUTES!");
if (snoozeDiff > snoozeMinutesVal * 60) {
//reset difference
snoozeVal = false;
stopSnooze();
}
//console.log("SNOOZE DIFFERENCE IS "+snoozeDiff);
} else {
//no alarm - set to dne
snoozeVal = false;
}
if (snoozeVal == false) {
if (dateValue.toString() != lastAlarmString) {
//now double check that it hasn't been snoozed recently
//console.log(dateValue.toString())
//console.log(lastAlarmString);
//indeed a new data point!
var urgentLowValueTemp = urgentLowValue[0];
var urgentHighValueTemp = urgentHighValue[0];
//var unitAddition = unitToProperString(unitType); this is for adding mg/dL or mmol/L properly
if (unitType == "mmol") {
urgentLowValueTemp = mgdlToMMOL(urgentLowValueTemp);
urgentHighValueTemp = mgdlToMMOL(urgentHighValueTemp);
//it's mmol, so we have to convert the lowvalues.
} //else is mgdl
//do mmol conversion stuff...
if (valueText == "High") {
if (highValue[1] == true) {
//is high and notifs are enabled.
if (Number(bgValue) >= urgentHighValueTemp) {
//is an urgent high. adjust accordingly, check notification permissions.
if (urgentHighValue[1] == false) {
valueText = ""
} else {
valueText = "Urgent High"
}
}
} else {
valueText = ""
}
} else if (valueText == "Low") {
if (lowValue[1] == true) {
//is low and notifs are enabled.
if (Number(bgValue) <= urgentLowValueTemp) {
//is an urgent low. adjust accordingly, check notification permissions.
if (urgentLowValue[1] == false) {
valueText = ""
} else {
valueText = "Urgent Low"
}
}
} else {
valueText = ""
}
}
var notifID = 'nightscout-alert';
//double check that notifs were indeed enabled.
if (valueText == "") {
//notifications are disabled. whoops.
clearNotifications(notifID);
} else {
chrome.notifications.create(
notifID, {
type: 'basic',
iconUrl: 'images/nightscout128.png',
title: valueText + " Glucose Alert",
message: "Your blood sugar is " + bgValue,
priority: 1,
buttons: [{
title: "Dismiss",
},
{
title: "Snooze (" + snoozeMinutesVal + "m)"
}
]
},
function() {
setTimeout(clearNotifications, 10000);
});
}
} else {
//don't clear - we still want the notification visible from last time!
console.log("sorry man, notification hasn't changed...")
}
}
});
});
});
}
chrome.notifications.onButtonClicked.addListener(function(notifId, btnIdx) {
if (btnIdx == 0) {
clearNotifications();
//alert("YEET");
} else if (btnIdx == 1) {
var snoozeUnixTemp = Math.round((new Date()).getTime() / 1000);
chrome.storage.local.set({
snoozeUnix: snoozeUnixTemp
}, function() {
console.log("SNOOZED! SEND SNOOZE NOTIF~!");
});
//alert("SNOOZE");
//make a snooze thing!
}
});
function stopSnooze() {
chrome.storage.local.set({
snoozeUnix: "dne"
}, function() {
console.log("ALARM DATA HAS BEEN RESET!");
});
}
function checkBSvariables(callbackFunc) {
chrome.storage.local.get(['alarmValues'], function(result) {
var alarmValues = Object.values(result)
//console.log(alarmValues);
//console.log("ARE ALARM VALUES");
if (alarmValues) {
var urgentLowData = alarmValues[0][0];
var lowData = alarmValues[0][1];
var highData = alarmValues[0][2];
var urgentHighData = alarmValues[0][3];
//check if any are changed.
if (urgentLowData != urgentLowValue || lowData != lowValue || highData != highValue || urgentHighData != urgentHighValue) {
urgentLowValue = urgentLowData;
lowValue = lowData;
highValue = highData;
urgentHighValue = urgentHighData;
//console.log("Alarm data has been changed!");
//getData();
//saveFunc("pushNotifications");
if (callbackFunc) {
callbackFunc();
}
}
}
});
}
function clearNotifications(lastAlarmRaw) {
chrome.notifications.clear("nightscout-alert", function() {
//console.log("cleared notification, boss");
//now, set last to nothing.
//chrome.storage.local.set({lastAlarmName: "dne"}, function() {
// console.log('Last Alarm Variable created!');
//});
});
}
function bsAlerts(bloodSugarVal, dateValue, unitType) {
var lowValueTemp = lowValue[0];
var highValueTemp = highValue[0];
if (unitType == "mmol") {
lowValueTemp = mgdlToMMOL(lowValueTemp);
highValueTemp = mgdlToMMOL(highValueTemp);
//it's mmol, so we have to convert the lowvalues.
}
if (Number(bloodSugarVal) <= Number(lowValueTemp)) {
notificationFunction(bloodSugarVal, dateValue, "Low", unitType);
} else if (Number(bloodSugarVal) >= Number(highValueTemp)) {
notificationFunction(bloodSugarVal, dateValue, "High", unitType);
} else {
//not high, not low. let's clear notifications anyways.
chrome.storage.local.get(['lastAlarmName'], function(lastAlarmRaw) {
chrome.browserAction.setBadgeBackgroundColor({
color: "gray"
});
var lastAlarmString = Object.values(lastAlarmRaw)[0];
if (lastAlarmString != dateValue) {
//if they're different, clear notifications!
clearNotifications(lastAlarmString);
}
});
}
}
function mgdlToMMOL(mgdlVal) {
var mmolMult = 18.016;
var tempMmol = mgdlVal / mmolMult;
//make sure to round to one decimal place!
var tempMmolFinal = Math.round(tempMmol * 10) / 10;
if (tempMmolFinal % 1 == 0) {
tempMmolFinal = tempMmolFinal + ".0";
}
return (tempMmolFinal);
}
function arrowValues(direction) {
var exportString = "";
switch (direction) {
case "NONE":
exportString = ""
break;
case "DOUBLEUP":
exportString = "↑"
break;
case "SINGLEUP":
exportString = "↑"
break;
case "FORTYFIVEUP":
exportString = "↗"
break;
case "FLAT":
exportString = "→"
break;
case "FORTYFIVEDOWN":
exportString = "↘"
break;
case "SINGLEDOWN":
exportString = "↓"
break;
case "DOUBLEDOWN":
exportString = "↓"
break;
case "NOT COMPUTABLE":
exportString = ""
break;
case "RATE OUT OF RANGE":
exportString = ""
break;
}
return exportString;
}
function bsColors(bgValue, unitType, fullData) {
var lowValueTemp = lowValue[0];
var highValueTemp = highValue[0];
var directionValue = fullData["direction"];
var deltaValue = fullData["delta"];
if (unitType == "mmol") {
lowValueTemp = mgdlToMMOL(lowValueTemp);
highValueTemp = mgdlToMMOL(highValueTemp);
//console.log("COLORS YEET");
//it's mmol, so we have to convert the lowvalues.
}
var newNum = "NaN";
if(deltaValue){
newNum = Math.round(Number(deltaValue));
if (newNum >= 0) {
newNum = "+" + newNum;
}
}
//get arrow value, too.
var customColor = "gray";
if (Number(bgValue) <= lowValueTemp) {
customColor = "red";
} else if (Number(bgValue) >= highValueTemp) {
customColor = "#c6a400";
}
chrome.browserAction.setBadgeBackgroundColor({
color: customColor
});
var bgValueString = bgValue;
if(directionValue){
//double check it's not mmol above ten.
if(unitType == "mmol"){
if(Number(bgValue) < 10){
bgValueString = bgValue.toString() + arrowValues(directionValue.toUpperCase());
}else{
//no luck. mmol above ten is ba d.
}
}else{
bgValueString = bgValue.toString() + arrowValues(directionValue.toUpperCase());
}
}
chrome.browserAction.setBadgeText({
text: bgValueString.toString()
});
//chrome.browserAction.setBadgeBackgroundColor({color:"gray"})
chrome.browserAction.setTitle({
title: "Blood Glucose: " + bgValue.toString()+unitToProperString(unitType)+"\n"+"Delta: "+newNum+" ("+arrowValues(directionValue.toUpperCase())+")"
});
}
function saveFunc(responseData, callbackFunc) {
//console.log("SAVE FUNC ENABLED!");
//before saving, check BG vals.
//var convertedString = JSON.stringify(responseData);
chrome.storage.local.get(['tempBsTable'], function(result) {
//data needs to be updated!
//console.log("Updating data!");
/* if(responseData.toString() == "pushNotifications"){
//only push notifications!
var tempTest = Object.values(result);
var tempTabl = returnCurrentBG(tempTest,true,true);
tempBG = tempTabl[0];
tempDate = tempTabl[1];
if(tempBG != false){
//bsAlerts(tempBG,tempDate);
} else if here */
//but first, double check unit type.
chrome.storage.local.get(['unitValue'], function(unitResult) {
var unitType = Object.values(unitResult)[0];
if (Object.values(result) == responseData) {
//it's the same.
var tempTest = Object.values(result);
var tempTabl = returnCurrentBG(tempTest, true, true, unitType);
tempBG = tempTabl[0];
var currentPointData = tempTabl[2];
if (tempBG != false) {
checkBSvariables(function() {
//bsAlerts(tempBG,tempDate,true);
//change bg vals.
console.log("Current blood sugar is: " + tempBG);
bsColors(tempBG, unitType,currentPointData);
});
}
//console.log("No change in data.")
//still, double check!
} else {
console.log("Saving Data!");
chrome.storage.local.set({
tempBsTable: responseData
}, function() {
//web request AGAIN, this time with the full dataTable.
webRequest(function(dataReturned){
chrome.storage.local.set({bsTable: dataReturned},function(){
//parse
//now that it's been saved, double check that you callback.
if (callbackFunc) {
callbackFunc()
}
//run more after-save code here.
forceRefreshGraph();
//console.log('Value succesfully set.');
//do low, high alerts too!
var currentDATA = returnCurrentBG(responseData, false, true, unitType);
currentBG = currentDATA[0];
//mmol and mgdl have a few problems - for now, notification data is stored in mgdl, so make sure to convert them to mmol when you get into the function!
currentDate = currentDATA[1];
var currentPointData = currentDATA[2];
if (currentBG != false) {
//currentBG = 70;
//console.log(currentBG);
//set icon
//note: add custom alert vars.
//not only does this control low/high alerts, but also the colors of the program.
//get alarmValues
checkBSvariables(function() {
//now that variables are set, do alerts and colors.
bsAlerts(currentBG, currentDate, unitType);
bsColors(currentBG, unitType,currentPointData);
});
}
});
},true);
});
//console.log(result);
}
});
});
}
function returnCurrentBG(data, notif, returnDate, unitType) {
var parsed;
if (!unitType) {
//no unit type, assume mgdl!
unitType = "mgdl";
}
if (notif == true) {
//actually fixing errors: small brain
//just using a try catch statement: galaxy brain
try {
parsed = JSON.parse(data[0]);
} catch (err) {
console.log("aaaand the json parse crashed!");
return [false,false];
}
} else {
parsed = JSON.parse(data);
}
for (i = 0; i < parsed.length; i++) {
var firstValue = false;
if (i == 0) {
firstValue = true;
}
var indivString = parsed[i];
var sgv = indivString["sgv"];
var dateStr = indivString["date"];
if (firstValue == true) {
//first bg value, meaning we need to C O N V E R T!
if (unitType == "mmol") {
//mmol, convert!
sgv = mgdlToMMOL(sgv);
//console.log("MMOL VERSION IS " + sgv);
} else if (unitType == "mgdl") {
//mgdl, make sure to change to number
sgv = Number(sgv);
}
if (returnDate == false) {
return [sgv, indivString];
} else if (returnDate == true) {
return [sgv, Number(dateStr), indivString];
} else {
return [sgv, indivString];
}
}
}
};
function parseData(response, callbackFunc) {
if (callbackFunc) {
saveFunc(response, callbackFunc);
} else {
saveFunc(response);
}
}
function manipulateURL(urlObj,count) {
var siteUrlBase = Object.values(urlObj)[0];
//check if it starts with https/http and manipulate accordingly
if (siteUrlBase.startsWith("https://") || siteUrlBase.startsWith("http://")) {
//it starts with https/http, we should be good.
} else {
//no http, add to string.
siteUrlBase = "http://" + siteUrlBase;
}
//make sure it ends in a big ol slash
if (siteUrlBase.endsWith("/")) {
//we're fine. we have a slash.
} else {
//no slash, add one.
siteUrlBase = siteUrlBase + "/";
}
siteUrlBase = siteUrlBase + 'api/v1/entries.json?count='+count;
//console.log("URL IS "+siteUrlBase);
//return url with correct values.
return siteUrlBase;
}
function manipulateProfileURL(urlObj) {
var siteUrlBase = Object.values(urlObj)[0];
//console.log(siteUrlBase);
//check if it starts with https/http and manipulate accordingly
if (siteUrlBase.startsWith("https://") || siteUrlBase.startsWith("http://")) {
//it starts with https/http, we should be good.
} else {
//no http, add to string.
siteUrlBase = "http://" + siteUrlBase;
}
//make sure it ends in a big ol slash
if (siteUrlBase.endsWith("/")) {
//we're fine. we have a slash.
} else {
//no slash, add one.
siteUrlBase = siteUrlBase + "/";
}
siteUrlBase = siteUrlBase + 'api/v1/status.json';
//console.log("URL IS "+siteUrlBase);
//return url with correct values.
return siteUrlBase;
}
function webError() {
console.log("ERROR! SITE DOES NOT EXIST!");
}
function alarmProfileFunction2(alarmTempArray,callbackFunc){
chrome.storage.local.get(['gottenProfileAlarms'], function(gottenResult){
var gottenValue = Object.values(gottenResult)[0];
if(gottenValue == false){
console.log("Pulling alarm data from the Nightscout site!");
chrome.storage.local.set({alarmValues: alarmTempArray}, function(){
//set old profile url too!
console.log("GETTING ALARM VALUES FROM NIGHTSCOUT!");
chrome.storage.local.set({gottenProfileAlarms: true}, function(){
if (callbackFunc) {
callbackFunc();
}
});
});
}else{
//console.log("SORRY, WE'VE GOTTEN IT.");
if (callbackFunc) {
callbackFunc();
}
}
});
}
function alarmProfileFunction(alarmTempArray,callbackFunc){
//get to see if changed from default site stuff yet;
//NOTE: IF PROFILE URL SAVED VALUE IS DIFFERENT, RESET THE VALUESS OF gottenProfileAlarms!
// this will ALSO handle profile url stuff.
chrome.storage.local.get(['lastProfileUrl'], function(lastProfileURLResult){
var profileUrlValue = Object.values(lastProfileURLResult)[0];
chrome.storage.local.get(['siteUrl'], function(siteUrlResult){
var siteUrlValue = Object.values(siteUrlResult)[0];
if(profileUrlValue == siteUrlValue){
alarmProfileFunction2(alarmTempArray,callbackFunc);
//nothing has changed. the url is still the same.
}else{
//it has changed. set the new profile url, and set gottenProfileAlarms to false.
chrome.storage.local.set({gottenProfileAlarms: false}, function(){
chrome.storage.local.set({gottenColors: false}, function(){
//it has been set to false.
chrome.storage.local.set({lastProfileUrl: siteUrlValue}, function(){
//new profile url set.
alarmProfileFunction2(alarmTempArray,callbackFunc);
});
});
});
}
});
});
}
function colorProfileFunction(colorValue,callbackFunc){
//!!!
chrome.storage.local.get(['gottenColors'], function(gottenResult){
var gottenValue = Object.values(gottenResult)[0];
if(gottenValue == false){
console.log("Pulling color data from the Nightscout site!");
chrome.storage.local.set({colors: colorValue}, function(){
//set old profile stuff too!
chrome.storage.local.set({gottenColors: true}, function(){
if (callbackFunc) {
callbackFunc();
}
});
});
}else{
//console.log("SORRY, WE'VE GOTTEN IT.");
if (callbackFunc) {
callbackFunc();
}
}
});
}
function profileWebRequest(profileURL, callbackFunctionWeb) {
var defaultUnit = "mgdl";
var unit;
var xhr = new XMLHttpRequest();
xhr.open("GET", profileURL, true);
xhr.onload = function(e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
//we got the data, boys!
var webData = JSON.parse(xhr.responseText);
//console.log("WE GOT SOME PROFILE DATA:");
var dataLength = Object.values(webData).length;
var settingsArray = webData["settings"];
var settingsArrayLength = Object.values(settingsArray).length;
//certain values we need
var thresholds = settingsArray["thresholds"];
var unitValueSetting = settingsArray["units"];
var userTheme = settingsArray["theme"];
var urgLowArray = [thresholds["bgLow"],settingsArray["alarmUrgentLow"]];
var lowArray = [thresholds["bgTargetBottom"],settingsArray["alarmLow"]];
var urgHighArray = [thresholds["bgHigh"],settingsArray["alarmUrgentHigh"]];
var highArray = [thresholds["bgTargetTop"],settingsArray["alarmHigh"]];
//var urgLowArray = [thresholds["bgLow"],true];
//var lowArray = [thresholds["bgTargetBottom"],true];
//var urgHighArray = [thresholds["bgHigh"],true];
//var highArray = [thresholds["bgTargetTop"],true];
//these are ONLY when you want the alarms to be true by default.
var alarmArray = [urgLowArray,lowArray,highArray,urgHighArray];
//console.log(alarmArray);
//we got the default profile, now parse.
if (unitValueSetting.toLowerCase() == "md/dl") {
//nightscout devs... why is it saved as md/dl... EXPLAIN THIS....
unitValueSetting = "mgdl";
}else if (unitValueSetting == "mmol"){
//nothing
}else{
unitValueSetting = "mgdl";
}
/*alarmValues: [
[defaultUrgentLowValue, true],
[defaultLowValue, true],
[defaultHighValue, true],
[defaultUrgentHighValue, true]
]*/
//unit is stored in "mgdl" or "mmol". save this and return.
//check if unit has changed.
chrome.storage.local.get(['unitValue'], function(unitResult) {
var unitType = Object.values(unitResult)[0];
if(unitType==unitValueSetting){
//it's the same.
alarmProfileFunction(alarmArray,callbackFunctionWeb)
}else{
//change it.
chrome.storage.local.set({unitValue: unitValueSetting}, function(){
//set unit. do callback now yay!
console.log("SAVED UNIT AS " + unitValueSetting);
alarmProfileFunction(alarmArray,function(){
colorProfileFunction(userTheme,callbackFunctionWeb);
});
});
}
});
} else {
webError();
}
}
};
xhr.onerror = function(e) {
//console.error(xhr.statusText);
webError();
};
xhr.send(null);
}
function webRequest(callbackFunc,fullChart) {
//we need a couple of variables. first of all, get the site URL.
chrome.storage.local.get(['siteUrl'], function(siteData) {
var siteUrlBase
if(fullChart == true){
siteUrlBase = manipulateURL(siteData,289);
}else{
siteUrlBase = manipulateURL(siteData,1);
}
//now, we need to see how much data we're supposed to load.
//yes... the data has data.
var xhr = new XMLHttpRequest();
xhr.open("GET", siteUrlBase, true);
xhr.onload = function(e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
//console.log(xhr.responseText);
//everything is done. now, get the profile data and set to mgdl/mmol.
if(fullChart == true){
//since it's the full chart, just return the data ASAP!;
if(callbackFunc){
callbackFunc(xhr.responseText);
}
}else{
var profileURLBase = manipulateProfileURL(siteData);
profileWebRequest(profileURLBase, function() {
//console.log("PARSING DATA!");
parseData(xhr.responseText, callbackFunc);
});
}
// we are done. find a way to callback after all the data, too.
} else {
webError();
}
}
};
xhr.onerror = function(e) {
//console.error(xhr.statusText);
webError();
};
xhr.send(null);
});
}
setInterval(webRequest, secondVal * 1000);