forked from rphl/corona-widget
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathincidence.js
1266 lines (1188 loc) · 62.8 KB
/
incidence.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
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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: red; icon-glyph: briefcase-medical;
/**
* Licence: Robert Koch-Institut (RKI), dl-de/by-2-0
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* AUTHOR: https://github.com/rphl - https://github.com/rphl/corona-widget/
* ISSUES: https://github.com/rphl/corona-widget/issues
*
*/
// ============= ============= ============= ============= =================
// ÄNDERUNGEN HIER, WERDEN BEI AKTIVEN AUTOUPDATE ÜBERSCHRIEBEN
// ZUR KONFIGURATION SIEHE README!
// https://github.com/rphl/corona-widget#erweiterte-konfiguration
//
// ============= ============= ============= ============= =================
let CFG = {
theme: '', // '' = Automatic Ligh/Darkmode based on iOS. light = only lightmode is used, dark = only darkmode is used
showDataInRow: false, // show "vaccine", "hospitalization", or false (statictics) values based on RKI reports. MEDIUMWIDGET IS REQUIRED!
showDataInBlocks: 'hospitalization', // show "vaccine", "hospitalization", or false disabled based on RKI reports (State/Country). Vaccine only in MEDIUMWIDGET. Hospitalization only in SMALLWIDGET.
openUrl: false, //"https://experience.arcgis.com/experience/478220a4c454480e823b17327b2bf1d4", // open RKI dashboard on tap, set false to disable
graphShowValues: 'i', // 'i' = incidence OR 'c' = cases
graphShowDays: 21, // show days in graph
csvRvalueFields: ['Schätzer_7_Tage_R_Wert', 'Punktschätzer des 7-Tage-R Wertes', 'Schไtzer_7_Tage_R_Wert', 'Punktschไtzer des 7-Tage-R Wertes', 'PS_7_Tage_R_Wert'], // try to find possible field (column) with rvalue, because rki is changing columnsnames and encoding randomly on each update
scriptRefreshInterval: 5400, // refresh after 1,5 hours (in seconds)
scriptSelfUpdate: false, // script updates itself,
disableLiveIncidence: false, // show old, static incidance. update ONLY ONCE A DAY on intial RKI import
debugIncidenceCalc: false // show all calculated incidencevalues on console
}
// ============= ============= ============= ============= =================
// HALT, STOP !!!
// NACHFOLGENDE ZEILEN NUR AUF EIGENE GEFAHR ÄNDERN !!!
// ============= ============= ============= ============= =================
const ENV = {
themes: {
light: {
mainBackgroundImageURL: '',
mainBackgroundColor: '#f0f0f0',
stackBackgroundColor: '#99999920',
stackBackgroundColorSmall: '#99999915',
stackBackgroundColorSmallTop: '#99999900',
areaIconBackgroundColor: '#99999930',
titleTextColor: '#222222',
titleRowTextColor: '#222222',
titleRowTextColor2: '#222222',
smallNameTextColor: '#777777',
dateTextColor: '#777777',
dateTextColor2: '#777777',
graphTextColor: '#888888',
incidenceColorsLila: '#93079f',
incidenceColorsPink: '#D90183',
incidenceColorsDarkdarkred: '#941100',
incidenceColorsDarkred: '#c01a00',
incidenceColorsRed: '#f92206',
incidenceColorsOrange: '#faa31b',
incidenceColorsYellow: '#ffd800',
incidenceColorsGreen: '#00cc00',
incidenceColorsGray: '#d0d0d0'
},
dark: {
mainBackgroundImageURL: '',
mainBackgroundColor: '#9999999',
stackBackgroundColor: '#99999920',
stackBackgroundColorSmall: '#99999910',
stackBackgroundColorSmallTop: '#99999900',
areaIconBackgroundColor: '#99999930',
titleTextColor: '#f0f0f0',
titleRowTextColor: '#f0f0f0',
titleRowTextColor2: '#f0f0f0',
smallNameTextColor: '#888888',
dateTextColor: '#777777',
dateTextColor2: '#777777',
graphTextColor: '#888888',
incidenceColorsLila: '#93079f',
incidenceColorsPink: '#D90183',
incidenceColorsDarkdarkred: '#941100',
incidenceColorsDarkred: '#c01a00',
incidenceColorsRed: '#f92206',
incidenceColorsOrange: '#faa31b',
incidenceColorsYellow: '#ffd800',
incidenceColorsGreen: '#00cc00',
incidenceColorsGray: '#d0d0d0'
}
},
incidenceColors: {
lila: { limit: 1000, color: 'incidenceColorsLila' },
pink: { limit: 500, color: 'incidenceColorsPink' },
darkdarkred: { limit: 250, color: 'incidenceColorsDarkdarkred' },
darkred: { limit: 100, color: 'incidenceColorsDarkred' },
red: { limit: 50, color: 'incidenceColorsRed' },
orange: { limit: 35, color: 'incidenceColorsOrange' },
yellow: { limit: 25, color: 'incidenceColorsYellow' },
green: { limit: 1, color: 'incidenceColorsGreen' },
gray: { limit: 0, color: 'incidenceColorsGray' }
},
hospitalizedIncidenceLimits: {
green: { limit: 0, color: 'incidenceColorsGreen' },
yellow: { limit: 3, color: 'incidenceColorsYellow' },
orange: { limit: 6, color: 'incidenceColorsOrange' },
red: { limit: 9, color: 'incidenceColorsDarkdarkred' },
},
statesAbbr: {
'8': 'BW',
'9': 'BY',
'11': 'BE',
'12': 'BB',
'4': 'HB',
'2': 'HH',
'6': 'HE',
'13': 'MV',
'3': 'NI',
'5': 'NRW',
'7': 'RP',
'10': 'SL',
'14': 'SN',
'15': 'ST',
'1': 'SH',
'16': 'TH'
},
vaccineSatesAbbr: {
'8' : 'Baden-Württemberg',
'9' : 'Bayern',
'11' : 'Berlin',
'12' : 'Brandenburg',
'4' : 'Bremen',
'2' : 'Hamburg',
'6' : 'Hessen',
'13' : 'Mecklenburg-Vorpommern',
'3' : 'Niedersachsen',
'5' : 'Nordrhein-Westfalen',
'7' : 'Rheinland-Pfalz',
'10' : 'Saarland',
'14' : 'Sachsen',
'15' : 'Sachsen-Anhalt',
'1' : 'Schleswig-Holstein',
'16' : 'Thüringen'
},
areaIBZ: {
'40': 'KS',// Kreisfreie Stadt
'41': 'SK', // Stadtkreis
'42': 'K', // Kreis
'46': 'K', // Sonderverband offiziel Kreis
'43': 'LK', // Landkreis
'45': 'LK', // Sonderverband offiziel Landkreis
null: 'BZ',
'': 'BZ'
},
fonts: {
xlarge: Font.boldSystemFont(26),
large: Font.mediumSystemFont(20),
medium: Font.mediumSystemFont(14),
normal: Font.mediumSystemFont(12),
small: Font.boldSystemFont(11),
small2: Font.boldSystemFont(10),
xsmall: Font.boldSystemFont(9)
},
status: {
nogps: 555,
offline: 418,
notfound: 404,
error: 500,
ok: 200,
fromcache: 418
},
isMediumWidget: config.widgetFamily === 'medium',
isSameState: false,
cache: {},
staticCoordinates: [],
script: {
selfUpdate: CFG.scriptSelfUpdate,
filename: this.module.filename.replace(/^.*[\\\/]/, ''),
updateStatus: ''
}
}
class Theme {
static getCurrentTheme () {
let theme = 'auto';
if (CFG.theme === 'light' || CFG.theme === 'dark') {
theme = CFG.theme
}
return theme
}
static getColor(colorName, useDefault = false) {
let theme = Theme.getCurrentTheme();
if (theme === 'auto' && useDefault) {
theme = 'light';
}
if (theme === 'light' || theme === 'dark') {
return new Color(ENV.themes[theme][colorName])
}
return false // no color preferred
}
static setColor(object, propertyName, colorName, useDefault = false) {
if (CFG.theme === 'light' || CFG.theme === 'dark' || useDefault) {
let theme = Theme.getCurrentTheme();
object[propertyName] = new Color(ENV.themes[theme][colorName])
}
}
}
class IncidenceWidget {
constructor(coordinates = []) {
this.loadConfig();
if (args.widgetParameter) ENV.staticCoordinates = Parse.input(args.widgetParameter)
ENV.staticCoordinates = [...ENV.staticCoordinates, ...coordinates]
if (typeof ENV.staticCoordinates[1] !== 'undefined' && Object.keys(ENV.staticCoordinates[1]).length >= 3) ENV.isMediumWidget = true
Helper.log("Current Theme:", Theme.getCurrentTheme())
this.selfUpdate()
}
async init() {
this.widget = await this.createWidget()
this.widget.setPadding(0, 0, 0, 0)
if (Theme.getCurrentTheme() === 'light' || Theme.getCurrentTheme() === 'dark') {
const backgroundImageUrl = ENV.themes[Theme.getCurrentTheme()]['mainBackgroundImageURL']
if (backgroundImageUrl !== '') {
const i = await new Request(backgroundImageUrl);
const img = await i.loadImage();
this.widget.backgroundImage = img
}
}
Theme.setColor(this.widget, 'backgroundColor', 'mainBackgroundColor')
if (!config.runsInWidget) {
(ENV.isMediumWidget) ? await this.widget.presentMedium() : await this.widget.presentSmall()
}
Script.setWidget(this.widget)
Script.complete()
}
async createWidget() {
const list = new ListWidget()
const statusPos0 = await Data.load(0)
const statusPos1 = (ENV.isMediumWidget && typeof ENV.staticCoordinates[1] !== 'undefined') ? await Data.load(1) : false
// UI ===============
let topBar = new UI(list).stack('h', [4, 8, 4, 4])
topBar.text("🦠", Font.mediumSystemFont(22))
topBar.space(3)
if (statusPos0 === ENV.status.error || statusPos1 === ENV.status.error) {
topBar.space()
list.addSpacer()
let statusError = new UI(list).stack('v', [4, 6, 4, 6])
statusError.text('⚡️', ENV.fonts.medium)
statusError.text('Standortdaten konnten nicht geladen werden. \nKein Cache verfügbar. \n\nBitte später nochmal versuchen.', ENV.fonts.small, Theme.getColor('titleTextColor'))
list.addSpacer(4)
list.refreshAfterDate = new Date(Date.now() + ((CFG.scriptRefreshInterval / 2) * 1000))
return list
}
Helper.calcIncidence('s0')
Helper.calcIncidence(ENV.cache['s0'].meta.BL_ID)
Helper.calcIncidence('d')
ENV.isSameState = false;
if (statusPos0 === statusPos1) {
ENV.isSameState = (ENV.cache['s0'].meta.BL_ID === ENV.cache['s1'].meta.BL_ID)
}
if (statusPos1) Helper.calcIncidence('s1')
if (statusPos1 && !ENV.isSameState) Helper.calcIncidence(ENV.cache['s1'].meta.BL_ID)
let topRStack = new UI(topBar).stack('v', [0,0,0,0])
topRStack.text(Format.number(ENV.cache.d.meta.r, 2, 'n/v') + 'ᴿ', ENV.fonts.medium, Theme.getColor('titleTextColor'))
let updatedDate = Format.dateStr(ENV.cache.d.getDay().date);
let updatedTime = ('' + new Date().getHours()).padStart(2, '0') + ':' + ('' + new Date().getMinutes()).padStart(2, '0')
topRStack.text(updatedDate + ' ' +updatedTime, ENV.fonts.xsmall, Theme.getColor('dateTextColor', true))
topBar.space()
UIComp.statusBlock(topBar, statusPos0)
topBar.space(4)
if (ENV.isMediumWidget && !ENV.isSameState && statusPos1) {
topBar.space()
UIComp.smallIncidenceRow(topBar, 'd', 'stackBackgroundColorSmallTop')
}
UIComp.incidenceVaccineRows(list)
list.addSpacer(3)
let stateBar = new UI(list).stack('h', [0, 0, 0, 0])
stateBar.space(6)
let leftCacheID = ENV.cache['s0'].meta.BL_ID
if (ENV.isMediumWidget) { UIComp.smallIncidenceRow(stateBar, leftCacheID) } else { UIComp.smallIncidenceBlock(stateBar, leftCacheID) }
stateBar.space(4)
// DEFAULT IS GER... else STATE
let rightCacheID = (ENV.isMediumWidget && !ENV.isSameState && statusPos1) ? ENV.cache['s1'].meta.BL_ID : 'd'
if (ENV.isMediumWidget) { UIComp.smallIncidenceRow(stateBar, rightCacheID) } else { UIComp.smallIncidenceBlock(stateBar, rightCacheID) }
stateBar.space(6)
list.addSpacer(5)
// UI ===============
if (CFG.openUrl) list.url = CFG.openUrl
list.refreshAfterDate = new Date(Date.now() + (CFG.scriptRefreshInterval * 1000))
return list
}
async selfUpdate() {
if (!ENV.script.selfUpdate) return
Helper.log('script selfUpdate', 'running')
let url = 'https://raw.githubusercontent.com/rphl/corona-widget/master/incidence.js';
let request = new Request(url)
let filenameBak = ENV.script.filename.replace('.js', '.bak.js')
try {
let script = await request.loadString()
if (script !== '') {
if (cfm.fm.fileExists(filenameBak)) await cfm.fm.remove(filenameBak)
cfm.copy(ENV.script.filename, filenameBak)
script = script.replace("scriptSelfUpdate: false", "scriptSelfUpdate: true")
cfm.save(script, ENV.script.filename)
ENV.script.updateStatus = 'updated'
Helper.log('script selfUpdate', ENV.script.updateStatus);
}
} catch (e) {
console.warn(e)
if (cfm.fm.fileExists(filenameBak)) {
// await cfm.fm.copy(filenameBak, ENV.script.filename)
// await cfm.fm.remove(filenameBak)
ENV.script.updateStatus = 'loading failed, rollback?'
Helper.log('script selfUpdate', ENV.script.updateStatus);
}
}
}
async loadConfig () {
let path = cfm.fm.joinPath(cfm.configPath, 'config.json');
if (cfm.fm.fileExists(path)) {
Helper.log('Loading config.json (defaults will be overwritten)')
const cfg = await cfm.read('config')
if (typeof cfg.data.themes !== 'undefined' && typeof cfg.data.themes.dark !== 'undefined') {
ENV.themes.dark = Object.assign(ENV.themes.dark, cfg.data.themes.dark)
}
Object.keys(ENV.themes).forEach(theme => {
if (typeof cfg.data.themes !== 'undefined' && typeof cfg.data.themes[theme] !== 'undefined') {
Helper.log('Loading custom theme from config.json: ' + theme)
ENV.themes[theme] = Object.assign(ENV.themes[theme], cfg.data.themes[theme])
}
})
if (cfg.status === ENV.status.ok) CFG = Object.assign(CFG, cfg.data)
}
}
}
class UIComp {
static incidenceVaccineRows(view) {
let b = new UI(view).stack('v', [4, 6, 4, 6])
let bb = new UI(b).stack('v', false, Theme.getColor('stackBackgroundColor', true), 10)
let padding = [4, 6, 4, 4]
if (ENV.isMediumWidget) {
padding = [2, 8, 2, 8]
}
let bb2 = new UI(bb).stack('h', padding, Theme.getColor('stackBackgroundColor', true), 10)
UIComp.incidenceRow(bb2, 's0')
let bb3 = new UI(bb).stack('h', padding)
if (ENV.isMediumWidget && CFG.showDataInRow === false && typeof ENV.cache.s1 === 'undefined' && typeof ENV.cache.vaccine !== 'undefined') {
UIComp.statisticsRow(bb3, 's0')
} else if (ENV.isMediumWidget && CFG.showDataInRow === 'vaccine' && typeof ENV.cache.s1 === 'undefined' && typeof ENV.cache.vaccine !== 'undefined') {
UIComp.vaccineRow(bb3, 's0')
} else if (ENV.isMediumWidget && CFG.showDataInRow === 'hospitalization' && typeof ENV.cache.s1 === 'undefined' && typeof ENV.cache.hospitalization !== 'undefined') {
UIComp.hospitalizationRow(bb3, 's0')
} else if (ENV.isMediumWidget && typeof ENV.cache.s1 !== 'undefined') {
UIComp.incidenceRow(bb3, 's1')
} else if (!ENV.isMediumWidget) {
bb3.space()
UIComp.areaIcon(bb3, ENV.cache['s0'].meta.IBZ)
bb3.space(3)
let areaName = ENV.cache['s0'].meta.GEN
if (typeof ENV.staticCoordinates[0] !== 'undefined' && ENV.staticCoordinates[0].name !== false) {
areaName = ENV.staticCoordinates[0].name
}
bb3.text(areaName.toUpperCase(), ENV.fonts.medium, Theme.getColor('titleRowTextColor'), 1, 0.9)
bb3.space(8) // center title if small widget
bb3.space()
}
}
static incidenceRow(view, cacheID) {
let b = new UI(view).stack('h', [2,0,0,0])
let ib = new UI(b).stack('h', [0,0,0,0], false, false, false, [72, 26])
ib.elem.centerAlignContent()
let incidence = ENV.cache[cacheID].getDay().incidence
let incidenceFormatted = Format.number(incidence, 1, 'n/v', 100)
let incidenceParts = incidenceFormatted.split(",")
let incidenceFontsize = (incidence >= 1000) ? 19 : 26;
ib.text(incidenceParts[0], Font.boldMonospacedSystemFont(incidenceFontsize), UI.getIncidenceColor(incidence), 1, 1)
if (typeof incidenceParts[1] !== "undefined") {
ib.text(',' + incidenceParts[1], Font.boldMonospacedSystemFont(18), UI.getIncidenceColor(incidence), 1, 1)
}
let trendArrow = UI.getTrendArrow(ENV.cache[cacheID].getAvg(0), ENV.cache[cacheID].getAvg(1))
let trendColor = (trendArrow === '↑') ? Theme.getColor(ENV.incidenceColors.red.color, true) : (trendArrow === '↓') ? Theme.getColor(ENV.incidenceColors.green.color, true) : Theme.getColor(ENV.incidenceColors.gray.color, true)
ib.text(trendArrow, Font.boldRoundedSystemFont(18), trendColor, 1, 0.9)
if (ENV.isMediumWidget) {
b.space(5)
UIComp.areaIcon(b, ENV.cache[cacheID].meta.IBZ)
b.space(3)
let areaName = ENV.cache[cacheID].meta.GEN
let cacheIndex = parseInt(cacheID.replace('s', ''))
if (typeof ENV.staticCoordinates[cacheIndex] !== 'undefined' && ENV.staticCoordinates[cacheIndex].name !== false) {
areaName = ENV.staticCoordinates[cacheIndex].name
}
b.text(areaName.toUpperCase(), ENV.fonts.medium, Theme.getColor('titleRowTextColor'), 1, 1)
}
b.space()
let b2 = new UI(b).stack('v', [2, 0, 0, 0], false, false, false, [58, 30])
let graphImg
if (CFG.graphShowValues === 'i') {
graphImg = UI.generateIcidenceGraph(ENV.cache[cacheID], 58, 16, false).getImage()
} else {
graphImg = UI.generateGraph(ENV.cache[cacheID], 58, 16, false).getImage()
}
b2.image(graphImg)
let bb2 = new UI(b2).stack('h')
bb2.space()
bb2.text('+' + Format.number(ENV.cache[cacheID].getDay().cases), ENV.fonts.xsmall, Theme.getColor('graphTextColor', true), 1, 1)
bb2.space(0)
}
static statisticsRow(view, cacheID) {
const data = ENV.cache[cacheID];
let b = new UI(view).stack('h', [4,0,4,0])
b.elem.centerAlignContent()
b.space()
b.text("Diff. ", ENV.fonts.medium, Theme.getColor('titleRowTextColor'), 1, 0.9)
const dayLastWeek = Format.dateStr(data.getDay(7).date, false);
b.text(` ${dayLastWeek} `, ENV.fonts.xsmall, Theme.getColor('dateTextColor2', true), 1, 0.9)
let diffDay = 0
if (data.getDay(0).cases > 0) {
diffDay = (data.getDay(0).incidence / data.getDay(7).incidence * 100) - 100;
if (diffDay > 0) {
b.text("+", ENV.fonts.medium, Theme.getColor(ENV.incidenceColors.red.color, true), 1, 0.9)
} else if (diffDay < 0) {
b.text("-", ENV.fonts.medium, Theme.getColor(ENV.incidenceColors.green.color, true), 1, 0.9)
}
}
b.text( Format.number(Math.abs(diffDay), 2), ENV.fonts.medium, Theme.getColor('titleRowTextColor'), 1, 0.9)
b.text( '% ', ENV.fonts.medium, Theme.getColor('titleRowTextColor'), 1, 0.9)
b.text(` WOCHE Ø `, ENV.fonts.xsmall, Theme.getColor('dateTextColor2', true), 1, 0.9)
const diffWeek = (data.getAvg(0) / data.getAvg(1) * 100) - 100;
if (diffWeek > 0) {
b.text("+", ENV.fonts.medium, Theme.getColor(ENV.incidenceColors.red.color, true), 1, 0.9)
} else if (diffWeek < 0) {
b.text("-", ENV.fonts.medium, Theme.getColor(ENV.incidenceColors.green.color, true), 1, 0.9)
}
b.text( Format.number(Math.abs(diffWeek), 2) + '%', ENV.fonts.medium, Theme.getColor('titleRowTextColor'), 1, 0.9)
b.space()
view.space()
}
static vaccineRow (view, cacheID) {
// state data
const blId = ENV.cache[cacheID].meta.BL_ID.toString().padStart(2, '0');
let stateData = ENV.cache.vaccine.data.data.filter(state => {
return state.rs === blId
});
stateData = stateData.pop();
let b = new UI(view).stack('h', [4,0,4,0])
b.elem.centerAlignContent()
b.space()
b.text("💉", ENV.fonts.normal, false, 1, 0.9)
let name = (typeof ENV.cache[cacheID].meta.BL_ID !== 'undefined') ? ENV.statesAbbr[ENV.cache[cacheID].meta.BL_ID] : cacheID
// b.text(name + "", ENV.fonts.medium, Theme.getColor('titleRowTextColor2'), 1, 0.9)
b.text(" ② ", ENV.fonts.normal, Theme.getColor('dateTextColor2', true), 1, 0.9)
b.text(Format.number(stateData.fullyVaccinated.quote, 1) + '%', ENV.fonts.normal, Theme.getColor('titleRowTextColor2'), 1, 1)
b.text(' ③ ', ENV.fonts.normal, Theme.getColor('dateTextColor2', true), 1, 0.9)
b.text(Format.number(stateData.boosterVaccinated.quote, 1) + '%', ENV.fonts.normal, Theme.getColor('titleRowTextColor2'), 1, 1)
b.space(4)
// country data
let countryData = ENV.cache.vaccine.data.data.filter(state => {
return state.name === "Deutschland"
});
countryData = countryData.pop();
b.text("[ D:", ENV.fonts.normal, Theme.getColor('dateTextColor2'), 1, 0.9)
b.text(" ② ", ENV.fonts.normal, Theme.getColor('dateTextColor2', true), 1, 0.9)
b.text(Format.number(countryData.fullyVaccinated.quote, 2) + '%', ENV.fonts.normal, Theme.getColor('dateTextColor2'), 1, 0.9)
b.text(" ]", ENV.fonts.normal, Theme.getColor('dateTextColor2'), 1, 0.9)
b.space(4)
let dateTS = new Date(ENV.cache.vaccine.data.lastUpdate).getTime()
let date = Format.dateStr(dateTS)
date = date.replace('.2021', '');
b.text('('+ date +')', ENV.fonts.xsmall, Theme.getColor('dateTextColor2', true), 1, 1)
b.space()
view.space()
}
static hospitalizationRow (view, cacheID) {
const stateId = ENV.cache[cacheID].meta.BL_ID;
const stateName = ENV.statesAbbr[stateId]
let b = new UI(view).stack('h', [4,0,4,0])
b.elem.centerAlignContent()
b.space()
const stateHospitalizationData = ENV.cache.hospitalization.data[parseInt(stateId)];
const stateHospitalizedIncidence = stateHospitalizationData.hospitalization['7daysIncidence'];
const stateHospitalized = stateHospitalizationData.hospitalization['7daysCases'];
const stateHospitalizedStatus = UI.getHospitalizationStatus(stateHospitalizedIncidence);
b.text('🏥 ' + stateName + ' ', ENV.fonts.medium, Theme.getColor('titleRowTextColor'), 1, 0.9)
b.image(stateHospitalizedStatus, 0.9)
b.text(' '+stateHospitalizedIncidence, ENV.fonts.medium, Theme.getColor('titleRowTextColor'), 1, 0.9)
b.text(' (' + stateHospitalized + ')', ENV.fonts.small, Theme.getColor('dateTextColor2', true), 1, 0.9)
b.space(4)
const hospitalizationData = ENV.cache.hospitalization.data[0];
const hospitalizedIncidence = hospitalizationData.hospitalization['7daysIncidence'];
const hospitalized = hospitalizationData.hospitalization['7daysCases'];
const hospitalizedStatus = UI.getHospitalizationStatus(hospitalizedIncidence);
b.text("/ D: ", ENV.fonts.medium, Theme.getColor('titleRowTextColor'), 1, 0.9)
b.image(hospitalizedStatus, 0.9)
b.text(' '+hospitalizedIncidence, ENV.fonts.medium, Theme.getColor('titleRowTextColor'), 1, 0.9)
b.text(' (' + hospitalized + ')', ENV.fonts.small, Theme.getColor('dateTextColor2', true), 1, 0.9)
b.space()
view.space()
}
static smallIncidenceBlock(view, cacheID, options = {}) {
let b = new UI(view).stack('v', false, Theme.getColor('stackBackgroundColorSmall', true), 12)
let b2 = new UI(b).stack('h', [4, 0, 0, 5])
b2.space()
let incidence = ENV.cache[cacheID].getDay().incidence
b2.text(Format.number(incidence, 1, 'n/v', 100), ENV.fonts.small2, UI.getIncidenceColor(incidence), 1, 1)
let trendArrow = UI.getTrendArrow(ENV.cache[cacheID].getAvg(0), ENV.cache[cacheID].getAvg(1))
let trendColor = (trendArrow === '↑') ? Theme.getColor(ENV.incidenceColors.red.color, true) : (trendArrow === '↓') ? Theme.getColor(ENV.incidenceColors.green.color, true) : Theme.getColor(ENV.incidenceColors.gray.color, true)
b2.text(trendArrow, ENV.fonts.small2, trendColor, 1, 1)
let name = (typeof ENV.cache[cacheID].meta.BL_ID !== 'undefined') ? ENV.statesAbbr[ENV.cache[cacheID].meta.BL_ID] : cacheID
b2.text(name.toUpperCase(), ENV.fonts.small2, Theme.getColor('smallNameTextColor', true), 1, 1)
let b3 = new UI(b).stack('h', [0, 0, 0, 5])
b3.space()
//let chartdata = [{ incidence: 0, value: 0 }, { incidence: 10, value: 10 }, { incidence: 20, value: 20 }, { incidence: 30, value: 30 }, { incidence: 40, value: 40 }, { incidence: 50, value: 50 }, { incidence: 70, value: 70 }, { incidence: 100, value: 100 }, { incidence: 60, value: 60 }, { incidence: 70, value: 70 }, { incidence: 39, value: 39 }, { incidence: 20, value: 25 }, { incidence: 10, value: 20 }, { incidence: 30, value: 30 }, { incidence: 0, value: 0 }, { incidence: 10, value: 10 }, { incidence: 20, value: 20 }, { incidence: 30, value: 30 }, { incidence: 60, value: 60 }, { incidence: 70, value: 70 }, { incidence: 39, value: 39 }, { incidence: 40, value: 40 }, { incidence: 50, value: 50 }, { incidence: 70, value: 70 }, { incidence: 100, value: 100 }, { incidence: 60, value: 60 }, { incidence: 70, value: 70 }, { incidence: 40, value: 40 }]
let graphImg
if (CFG.graphShowValues === 'i') {
graphImg = UI.generateIcidenceGraph(ENV.cache[cacheID], 58, 8, false).getImage()
} else {
graphImg = UI.generateGraph(ENV.cache[cacheID], 58, 8, false).getImage()
}
b3.image(graphImg, 0.9)
let b4 = new UI(b).stack('h', [0, 0, 1, 5])
b4.space()
if (CFG.showDataInBlocks === 'hospitalization' && ENV.cache.hospitalization) {
UIComp.hospitalizationIcon(b4, cacheID, 8, 8);
}
b4.text(' +' + Format.number(ENV.cache[cacheID].getDay().cases), ENV.fonts.xsmall, Theme.getColor('graphTextColor', true), 1, 0.9)
b.space(2)
}
static smallIncidenceRow(view, cacheID, bgColor = 'stackBackgroundColorSmall') {
let r = new UI(view).stack('h', false, Theme.getColor(bgColor, true), 12)
let b = new UI(r).stack('v')
let bb2 = new UI(b).stack('h', [2, 0, 0, 6])
bb2.space()
let incidence = ENV.cache[cacheID].getDay().incidence
bb2.text(Format.number(incidence, 1, 'n/v', 100), ENV.fonts.normal, UI.getIncidenceColor(incidence), 1 ,1)
let trendArrow = UI.getTrendArrow(ENV.cache[cacheID].getAvg(0), ENV.cache[cacheID].getAvg(1))
let trendColor = (trendArrow === '↑') ? Theme.getColor(ENV.incidenceColors.red.color, true) : (trendArrow === '↓') ? Theme.getColor(ENV.incidenceColors.green.color, true) : Theme.getColor(ENV.incidenceColors.gray.color, true)
bb2.text(trendArrow, ENV.fonts.normal, trendColor)
bb2.space(2)
let name = (typeof ENV.cache[cacheID].meta.BL_ID !== 'undefined') ? ENV.statesAbbr[ENV.cache[cacheID].meta.BL_ID] : cacheID
bb2.text(name.toUpperCase(), ENV.fonts.normal, Theme.getColor('smallNameTextColor', true))
let b3 = new UI(b).stack('h', [0, 0, 2, 6])
b3.space()
if (CFG.showDataInBlocks === 'vaccine' && ENV.cache.vaccine) {
UIComp.vaccineInfo(b3, cacheID);
} else if (CFG.showDataInBlocks === 'hospitalization' && ENV.cache.hospitalization) {
UIComp.hospitalizationInfo(b3, cacheID);
}
let b2 = new UI(r).stack('v', false, false, false, false, [60, 30])
let b2b2 = new UI(b2).stack('h', [0, 0, 0, 6])
b2b2.space()
let graphImg
if (CFG.graphShowValues == 'i') {
graphImg = UI.generateIcidenceGraph(ENV.cache[cacheID], 58, 10, false).getImage()
} else {
graphImg = UI.generateGraph(ENV.cache[cacheID], 58, 10, false).getImage()
}
b2b2.image(graphImg, 0.9)
let b2b3 = new UI(b2).stack('h', [0, 0, 0, 0])
b2b3.space()
b2b3.text('+' + Format.number(ENV.cache[cacheID].getDay().cases), ENV.fonts.xsmall, Theme.getColor('graphTextColor', true), 1, 0.9)
r.space(6)
}
static vaccineInfo(view, cacheID) {
// state data
let vaccineData = ENV.cache.vaccine.data.data.filter(state => {
if (cacheID !== 'd') {
const blId = ENV.cache[cacheID].meta.BL_ID.toString().padStart(2, '0');
return state.rs === blId
} else {
return state.name === "Deutschland"
}
});
vaccineData = vaccineData.pop();
let b3Text = ' ';
b3Text = '💉² ' + Format.number(vaccineData.fullyVaccinated.quote, 2, 'n/v') +'%'
view.text(b3Text, ENV.fonts.xsmall, Theme.getColor('graphTextColor', true), 1, 0.9)
}
static hospitalizationInfo(view, cacheID) {
let b3Text = ' ';
let stateId = 0;
if (cacheID !== 'd') {
stateId = ENV.cache[cacheID].meta.BL_ID;
}
const stateHospitalizationData = ENV.cache.hospitalization.data[parseInt(stateId)];
const stateHospitalizedIncidence = stateHospitalizationData.hospitalization['7daysIncidence'];
const stateHospitalizedStatus = UI.getHospitalizationStatus(stateHospitalizedIncidence);
b3Text += stateHospitalizedIncidence + ' ';
view.text(b3Text, ENV.fonts.xsmall, Theme.getColor('graphTextColor', true), 1, 0.9)
view.image(stateHospitalizedStatus, 0.9)
}
static hospitalizationIcon(view, cacheID, width, height) {
let stateId = 0;
if (cacheID !== 'd') {
stateId = ENV.cache[cacheID].meta.BL_ID;
}
const stateHospitalizationData = ENV.cache.hospitalization.data[parseInt(stateId)];
const stateHospitalizedIncidence = stateHospitalizationData.hospitalization['7daysIncidence'];
const stateHospitalizedStatus = UI.getHospitalizationStatus(stateHospitalizedIncidence, width, height);
view.image(stateHospitalizedStatus, 0.9)
}
static areaIcon(view, ibzID) {
let b = new UI(view).stack('h', [1, 3, 1, 3], Theme.getColor('areaIconBackgroundColor', true), 2, 2)
b.text(ENV.areaIBZ[ibzID], ENV.fonts.xsmall, Theme.getColor('titleRowTextColor'), 1, 1)
}
static statusBlock(view, status) {
let icon
let iconText
switch (status) {
case ENV.status.offline:
icon = '⚡️'
iconText = 'Offline'
break;
case ENV.status.nogps:
icon = '📡'
iconText = 'GPS?'
break;
}
if (icon && iconText) {
let topStatusStack = new UI(view).stack('v')
topStatusStack.text(icon, ENV.fonts.small)
}
}
}
class UI {
constructor(view) {
if (view instanceof UI) {
this.view = this.elem = view.elem
} else {
this.view = this.elem = view
}
}
static generateGraph(data, width, height, alignLeft = true) {
let graphData = data.data.slice(Math.max(data.data.length - CFG.graphShowDays, 1));
let context = new DrawContext()
context.size = new Size(width, height)
context.opaque = false
context.respectScreenScale = true
let max = Math.max.apply(Math, graphData.map(function (o) { return o.cases; }))
max = (max <= 0) ? 10 : max;
let w = Math.max(2, Math.round((width - (graphData.length * 2)) / graphData.length))
let xOffset = (!alignLeft) ? (width - (graphData.length * (w + 1))) : 0
for (let i = 0; i < CFG.graphShowDays; i++) {
let item = graphData[i]
let value = parseFloat(item.cases)
if (value === -1 && i == 0) value = 10;
let h = Math.max(2, (Math.abs(value) / max) * height)
let x = xOffset + (w + 1) * i
let rect = new Rect(x, height - h, w, h)
context.setFillColor(UI.getIncidenceColor((item.cases >= 1) ? item.incidence : 0))
context.fillRect(rect)
}
return context
}
static generateIcidenceGraph(data, width, height, alignLeft = true) {
let graphData = data.data.slice(Math.max(data.data.length - CFG.graphShowDays, 1));
let context = new DrawContext()
context.size = new Size(width, height)
context.opaque = false
context.respectScreenScale = true
let max = Math.max.apply(Math, graphData.map(function (o) { return o.incidence; }))
let min = Math.min.apply(Math, graphData.map(function (o) { return o.incidence; })) / 1.2
max = (max <= 0) ? 10 : max - min;
let w = Math.max(2, Math.round((width - (graphData.length * 2)) / graphData.length))
let xOffset = (!alignLeft) ? (width - (graphData.length * (w + 1))) : 0
for (let i = 0; i < CFG.graphShowDays; i++) {
let item = graphData[i]
let value = parseFloat(item.incidence) - min
if (value === -1 && i == 0) value = 10;
let h = Math.max(2,(Math.abs(value) / max) * (height - 1))
let x = xOffset + (w + 1) * i
let rect = new Rect(x, height - h - 1, w, h)
context.setFillColor(UI.getIncidenceColor((item.cases >= 0) ? item.incidence : 0))
context.fillRect(rect)
}
return context
}
stack(type = 'h', padding = false, borderBgColor = false, radius = false, borderWidth = false, size = false) {
this.elem = this.view.addStack()
if (radius) this.elem.cornerRadius = radius
if (borderWidth !== false) {
this.elem.borderWidth = borderWidth
this.elem.borderColor = borderBgColor
} else if (borderBgColor) {
this.elem.backgroundColor = borderBgColor
}
if (padding) this.elem.setPadding(...padding)
if (size) this.elem.size = new Size(size[0], size[1])
if (type === 'h') { this.elem.layoutHorizontally() } else { this.elem.layoutVertically() }
this.elem.centerAlignContent()
return this
}
text(text, font = false, color = false, maxLines = 0, minScale = 0.9) {
let t = this.elem.addText(text)
if (color) t.textColor = (typeof color === 'string') ? new Color(color) : color
t.font = (font) ? font : ENV.fonts.normal
t.lineLimit = (maxLines > 0 && minScale < 1) ? maxLines + 1 : maxLines
t.minimumScaleFactor = minScale
return this
}
image(image, imageOpacity = 1.0) {
let i = this.elem.addImage(image)
i.resizable = false
i.imageOpacity = imageOpacity
}
space(size) {
this.elem.addSpacer(size)
return this
}
static getTrendUpArrow(now, prev) {
if (now < 0 && prev < 0) {
now = Math.abs(now)
prev = Math.abs(prev)
}
return (now < prev) ? '↗' : (now > prev) ? '↑' : '→'
}
static getTrendArrow(value1, value2) {
return (value1 < value2) ? '↓' : (value1 > value2) ? '↑' : '→'
}
static getTrendColor(value1, value2, altColorUp = null, altColorDown = null) {
let colorUp = (altColorUp) ? new Color(altColorUp) : Theme.getColor(ENV.incidenceColors.red.color, true)
let colorDown = (altColorDown) ? new Color(altColorDown) : Theme.getColor(ENV.incidenceColors.green.color, true)
return (value1 < value2) ? colorDown : (value1 > value2) ? colorUp : Theme.getColor(ENV.incidenceColors.gray.color, true)
}
static getIncidenceColor(incidence) {
let color = Theme.getColor(ENV.incidenceColors.green.color, true)
if (incidence >= ENV.incidenceColors.lila.limit) {
color = Theme.getColor(ENV.incidenceColors.lila.color, true)
} else if (incidence >= ENV.incidenceColors.pink.limit) {
color = Theme.getColor(ENV.incidenceColors.pink.color, true)
} else if (incidence >= ENV.incidenceColors.darkdarkred.limit) {
color = Theme.getColor(ENV.incidenceColors.darkdarkred.color, true)
} else if (incidence >= ENV.incidenceColors.darkred.limit) {
color = Theme.getColor(ENV.incidenceColors.darkred.color, true)
} else if (incidence >= ENV.incidenceColors.red.limit) {
color = Theme.getColor(ENV.incidenceColors.red.color, true)
} else if (incidence >= ENV.incidenceColors.orange.limit) {
color = Theme.getColor(ENV.incidenceColors.orange.color, true)
} else if (incidence >= ENV.incidenceColors.yellow.limit) {
color = Theme.getColor(ENV.incidenceColors.yellow.color, true)
}
return color
}
static getHospitalizationStatus(hospitalizedIncidence, width = 10, height = 10) {
let context = new DrawContext()
context.size = new Size(width, height)
context.opaque = false
context.respectScreenScale = true
if (hospitalizedIncidence >= ENV.hospitalizedIncidenceLimits.red.limit) {
context.setFillColor(Theme.getColor(ENV.hospitalizedIncidenceLimits.red.color, true))
} else if (hospitalizedIncidence >= ENV.hospitalizedIncidenceLimits.orange.limit) {
context.setFillColor(Theme.getColor(ENV.hospitalizedIncidenceLimits.orange.color, true))
} else if (hospitalizedIncidence >= ENV.hospitalizedIncidenceLimits.yellow.limit) {
context.setFillColor(Theme.getColor(ENV.hospitalizedIncidenceLimits.yellow.color, true))
} else {
context.setFillColor(Theme.getColor(ENV.hospitalizedIncidenceLimits.green.color, true))
}
let rect = new Rect(0, 0, width, height)
context.fillEllipse(rect)
return context.getImage()
}
}
class DataResponse {
constructor(data, status = ENV.status.ok) {
this.data = data
this.status = status
}
}
class CustomFilemanager {
constructor() {
try {
this.fm = FileManager.iCloud()
this.fm.documentsDirectory()
} catch (e) {
this.fm = FileManager.local()
}
this.configDirectory = 'coronaWidgetNext'
this.configPath = this.fm.joinPath(this.fm.documentsDirectory(), '/' + this.configDirectory)
if (!this.fm.isDirectory(this.configPath)) this.fm.createDirectory(this.configPath)
}
async copy(oldFilename, newFilename) {
let oldPath = this.fm.joinPath(this.configPath, oldFilename);
let newPath = this.fm.joinPath(this.configPath, newFilename);
this.fm.copy(oldPath, newPath)
}
async save(data, filename = '') {
let path
let dataStr
if (filename === '') {
path = this.fm.joinPath(this.configPath, 'coronaWidget_' + data.dataId + '.json');
dataStr = JSON.stringify(data);
} else {
path = this.fm.joinPath(this.fm.documentsDirectory(), filename);
dataStr = data;
}
this.fm.writeString(path, dataStr);
}
async read(filename) {
let path = this.fm.joinPath(this.configPath, filename + '.json');
let type = 'json'
if (filename.includes('.')) {
path = this.fm.joinPath(this.fm.documentsDirectory(), filename);
type = 'string'
}
if (this.fm.isFileStoredIniCloud(path) && !this.fm.isFileDownloaded(path)) await this.fm.downloadFileFromiCloud(path);
if (this.fm.fileExists(path)) {
try {
let resStr = await this.fm.readString(path)
let res = (type === 'json') ? JSON.parse(resStr) : resStr
return new DataResponse(res);
} catch (e) {
console.error(e)
return new DataResponse('', ENV.status.error);
}
}
return new DataResponse('', ENV.status.notfound);
}
}
class Data {
constructor(dataId, data = {}, meta = {}) {
this.dataId = dataId
this.data = data
this.meta = meta
}
getDay (dayOffset = 0) {
return (typeof this.data[this.data.length - 1 - dayOffset] !== 'undefined') ? this.data[this.data.length - 1 - dayOffset] : false;
}
getAvg (weekOffset = 0, ignoreToday = false) {
let casesData = [...this.data].reverse()
let skipToday = (ignoreToday) ? 1 : 0;
const offsetDays = 7
const weekData = casesData.slice((offsetDays * weekOffset) + skipToday, (offsetDays * weekOffset) + 7 + skipToday)
const avg = weekData.reduce((a, b) => a + b.incidence, 0) / offsetDays
return avg
}
static completeHistory (data) {
const completeDataObj = {}
for(let i = 0; i <= CFG.graphShowDays + 8; i++) {
let lastDate = new Date()
let prevDate = lastDate.setDate(lastDate.getDate() - i);
completeDataObj[Format.dateStr(prevDate)] = { cases: 0, date: prevDate }
}
data.map((value) => {
let curDate = Format.dateStr(value.date)
completeDataObj[curDate].cases = value.cases
})
let completeData = Object.values(completeDataObj)
completeData.sort((a, b) => { return a.date - b.date; })
return completeData.reverse();
}
static async tryLoadFromCache(cacheID, useStaticCoordsIndex) {
const dataResponse = await cfm.read(cfm.configDirectory + '/coronaWidget_config.json')
if (dataResponse.status !== ENV.status.ok) return ENV.status.error
const cacheIDs = JSON.parse(dataResponse.data)
if (typeof cacheIDs[cacheID] === 'undefined') return ENV.status.error
const dataIds = cacheIDs[cacheID]
if (typeof dataIds['dataIndex' + useStaticCoordsIndex] !== 'undefined') {
const areaData = await cfm.read('coronaWidget_' + dataIds['dataIndex' + useStaticCoordsIndex])
if (!areaData.data.data) return ENV.status.error
const area = new Data(dataIds['dataIndex' + useStaticCoordsIndex], areaData.data.data, areaData.data.meta)
ENV.cache['s' + useStaticCoordsIndex] = area
const stateData = await cfm.read('coronaWidget_' + areaData.data.meta.BL_ID)
if (!stateData.data.data) return ENV.status.error
const state = new Data(areaData.data.meta.BL_ID, stateData.data.data, stateData.data.meta)
ENV.cache[areaData.data.meta.BL_ID] = state
const dData = await cfm.read('coronaWidget_d')
if (!dData.data.data) return ENV.status.error
const d = new Data('d', dData.data.data, dData.data.meta)
ENV.cache.d = d
const vaccineData = await cfm.read('coronaWidget_vaccine')
if (!vaccineData.data.data) return ENV.status.error
const vaccine = new Data('vaccine', vaccineData.data.data, vaccineData.data.meta)
ENV.cache.vaccine = vaccine
const hospitalizationData = await cfm.read('coronaWidget_hospitalization')
if (!hospitalizationData.data.data) return ENV.status.error
const hospitalization = new Data('hospitalization', hospitalizationData.data.data, hospitalizationData.data.meta)
ENV.cache.hospitalization = hospitalization
return ENV.status.ok
}
return ENV.status.error
}
static async load(useStaticCoordsIndex = false) {
if (typeof ENV.cache['s' + useStaticCoordsIndex] !== 'undefined') return true
let configId = btoa('cID' + JSON.stringify(ENV.staticCoordinates).replace(/[^a-zA-Z ]/g, ""))
const location = await Helper.getLocation(useStaticCoordsIndex)
if (!location) {
const status = await Data.tryLoadFromCache(configId, useStaticCoordsIndex)
return (status === ENV.status.ok) ? ENV.status.nogps : ENV.status.error
}
const locationData = await rkiRequest.locationData(location)
if (!locationData) {
const status = await Data.tryLoadFromCache(configId, useStaticCoordsIndex)
return (status === ENV.status.ok) ? ENV.status.fromcache : ENV.status.error
}
let areaCases = await rkiRequest.areaCases(locationData.RS)
if (!areaCases) {
const status = await Data.tryLoadFromCache(configId, useStaticCoordsIndex)
return (status === ENV.status.ok) ? ENV.status.fromcache : ENV.status.error
}
await Data.geoCache(configId, useStaticCoordsIndex, locationData.RS)
let areaData = new Data(locationData.RS)
areaData.data = areaCases
areaData.meta = locationData
await cfm.save(areaData)
ENV.cache['s' + useStaticCoordsIndex] = areaData
// STATE DATA
if (typeof ENV.cache[locationData.BL_ID] === 'undefined') {
let stateCases = await rkiRequest.stateCases(locationData.BL_ID)
if (!stateCases) {
const status = await Data.tryLoadFromCache(configId, useStaticCoordsIndex)
return (status === ENV.status.ok) ? ENV.status.fromcache : ENV.status.error
}
let stateData = new Data(locationData.BL_ID)
stateData.data = stateCases
stateData.meta = {
BL_ID: locationData.BL_ID,
BL: locationData.BL,
EWZ: locationData.EWZ_BL
}
await cfm.save(stateData)
ENV.cache[locationData.BL_ID] = stateData
}
// GER DATA
if (typeof ENV.cache.d === 'undefined') {
let dCases = await rkiRequest.dCases()
if (!dCases) {
const status = await Data.tryLoadFromCache(configId, useStaticCoordsIndex)
return (status === ENV.status.ok) ? ENV.status.fromcache : ENV.status.error
}
let dData = new Data('d')
dData.data = dCases
dData.meta = {
r: await rkiRequest.rvalue(),
EWZ: 83.02 * 1000000 // @TODO real number?
}
await cfm.save(dData)
ENV.cache.d = dData
}
// VACCINE DATA
if (typeof ENV.cache.vaccine === 'undefined') {