-
Notifications
You must be signed in to change notification settings - Fork 316
/
weather-cal-code.js
2532 lines (2168 loc) · 99.7 KB
/
weather-cal-code.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: deep-purple; icon-glyph: calendar;
/*
This script contains the logic that allows Weather Cal to work. Please do not modify this file. You can add customizations in the widget script.
Documentation is available at github.com/mzeryck/Weather-Cal
*/
const weatherCal = {
// Initialize shared properties.
initialize(name, iCloudInUse) {
this.name = name
this.fm = iCloudInUse ? FileManager.iCloud() : FileManager.local()
this.bgPath = this.fm.joinPath(this.fm.libraryDirectory(), "weather-cal-" + this.name)
this.prefPath = this.fm.joinPath(this.fm.libraryDirectory(), "weather-cal-preferences-" + name)
this.widgetUrl = "https://raw.githubusercontent.com/mzeryck/Weather-Cal/main/weather-cal.js"
this.now = new Date()
this.data = {}
this.initialized = true
},
// Determine what to do when Weather Cal is run.
async runSetup(name, iCloudInUse, codeFilename, gitHubUrl) {
if (!this.initialized) this.initialize(name, iCloudInUse)
const backgroundSettingExists = this.fm.fileExists(this.bgPath)
if (!this.fm.fileExists(this.fm.joinPath(this.fm.libraryDirectory(), "weather-cal-setup"))) return await this.initialSetup(backgroundSettingExists)
if (backgroundSettingExists) return await this.editSettings(codeFilename, gitHubUrl)
await this.generateAlert("Weather Cal is set up, but you need to choose a background for this widget.",["Continue"])
return await this.setWidgetBackground()
},
// Run the initial setup.
async initialSetup(imported = false) {
let message, options
if (!imported) {
message = "Welcome to Weather Cal. Make sure your script has the name you want before you begin."
options = ['I like the name "' + this.name + '"', "Let me go change it"]
if (await this.generateAlert(message,options)) return
}
message = (imported ? "Welcome to Weather Cal. We" : "Next, we") + " need to check if you've given permissions to the Scriptable app. This might take a few seconds."
await this.generateAlert(message,["Check permissions"])
let errors = []
if (!(await this.setupLocation())) { errors.push("location") }
try { await CalendarEvent.today() } catch { errors.push("calendar") }
try { await Reminder.all() } catch { errors.push("reminders") }
let issues
if (errors.length > 0) { issues = errors[0] }
if (errors.length == 2) { issues += " and " + errors[1] }
if (errors.length == 3) { issues += ", " + errors[1] + ", and " + errors[2] }
if (issues) {
message = "Scriptable does not have permission for " + issues + ". Some features may not work without enabling them in the Settings app."
options = ["Continue setup anyway", "Exit setup"]
} else {
message = "Your permissions are enabled."
options = ["Continue setup"]
}
if (await this.generateAlert(message,options)) return
message = "To display the weather on your widget, you need an OpenWeather API key."
options = ["I already have a key", "I need to get a key", "I don't want to show weather info"]
const weather = await this.generateAlert(message,options)
// Show a web view to claim the API key.
if (weather == 1) {
message = "On the next screen, sign up for OpenWeather. Find the API key, copy it, and close the web view. You will then be prompted to paste in the key."
await this.generateAlert(message,["Continue"])
const webView = new WebView()
webView.loadURL("https://openweathermap.org/home/sign_up")
await webView.present()
}
// We need the API key if we're showing weather.
if (weather < 2 && !(await this.getWeatherKey(true))) { return }
if (!imported) { await this.setWidgetBackground() }
this.writePreference("weather-cal-setup", "true")
message = "Your widget is ready! You'll now see a preview. Re-run this script to edit the default preferences, including localization. When you're ready, add a Scriptable widget to the home screen and select this script."
await this.generateAlert(message,["Show preview"])
return this.previewValue()
},
// Edit the widget settings.
async editSettings(codeFilename, gitHubUrl) {
const menu = {
preview: "Show widget preview",
background: "Change background",
preferences: "Edit preferences",
update: "Update code",
share: "Export widget",
other: "Other settings",
exit: "Exit settings menu",
}
const menuOptions = [menu.preview, menu.background, menu.preferences, menu.update, menu.share, menu.other, menu.exit]
const response = menuOptions[await this.generateAlert("Widget Setup",menuOptions)]
if (response == menu.preview) { return this.previewValue() }
if (response == menu.background) { return await this.setWidgetBackground() }
if (response == menu.preferences) { return await this.editPreferences() }
if (response == menu.update) {
if (await this.generateAlert("Would you like to update the Weather Cal code? Your widgets will not be affected.",["Update", "Exit"])) return
const success = await this.downloadCode(codeFilename, gitHubUrl)
return await this.generateAlert(success ? "The update is now complete." : "The update failed. Please try again later.")
}
if (response == menu.share) {
const layout = this.fm.readString(this.fm.joinPath(this.fm.documentsDirectory(), this.name + ".js")).split('`')[1]
const prefs = JSON.stringify(await this.getSettings())
const bg = this.fm.readString(this.bgPath)
const widgetExport = `async function importWidget() {
function makeAlert(message,options = ["OK"]) {
const a = new Alert()
a.message = message
for (const option of options) { a.addAction(option) }
return a
}
let fm = FileManager.local()
fm = fm.isFileStoredIniCloud(module.filename) ? FileManager.iCloud() : fm
const path = fm.joinPath(fm.documentsDirectory(), "Weather Cal code.js")
const wc = fm.fileExists(path) ? fm.readString(path) : false
const version = wc ? parseInt(wc.slice(wc.lastIndexOf("//") + 2).trim()) : false
if (wc && (!version || version < 4)) { return await makeAlert("Please update Weather Cal before importing a widget.").present() }
if ((await makeAlert("Do you want your widget to be named " + Script.name() + "?",["Yes, looks good","No, let me change it"]).present()) == 1) { return }
fm.writeString(fm.joinPath(fm.libraryDirectory(), "weather-cal-preferences-" + Script.name()), '${prefs}')
fm.writeString(fm.joinPath(fm.libraryDirectory(), "weather-cal-" + Script.name()), '${bg}')
let code = await new Request('${this.widgetUrl}').loadString()
let arr = code.split('\`')
arr[1] = \`${layout}\`
alert = makeAlert("Close this script and re-run it to finish setup.")
fm.writeString(module.filename, arr.join('\`'))
await alert.present()
}
await importWidget()
Script.complete()`
const shouldUseQuickLook = await this.generateAlert("Your export is ready.",["Save to Files", "Display as text to copy"])
if (shouldUseQuickLook) {
QuickLook.present('/*\n\n\n\nTap the Share icon in the top right.\nThen tap "Copy" to copy all of this code.\nNow you can paste into a new script.\n\n\n\n*/\n' + widgetExport)
} else {
DocumentPicker.exportString(widgetExport, this.name + " export.js")
}
return
}
if (response == menu.other) {
const otherOptions = ["Re-enter API key", "Completely reset widget", "Exit"]
const otherResponse = await this.generateAlert("Other settings",otherOptions)
// Set the API key.
if (otherResponse == 0) { await this.getWeatherKey() }
// Reset the widget.
else if (otherResponse == 1) {
const alert = new Alert()
alert.message = "Are you sure you want to completely reset this widget?"
alert.addDestructiveAction("Reset")
alert.addAction("Cancel")
if ((await alert.present()) == 0) {
for (item of this.fm.listContents(this.fm.libraryDirectory())) {
if (item.startsWith("weather-cal-") && item != "weather-cal-api-key" && item != "weather-cal-setup") {
this.fm.remove(this.fm.joinPath(this.fm.libraryDirectory(), item))
}
}
const success = await this.downloadCode(this.name, this.widgetUrl)
const message = success ? "This script has been reset. Close the script and reopen it for the change to take effect." : "The reset failed."
await this.generateAlert(message)
}
}
}
return
},
// Get the weather key, optionally determining if it's the first run.
async getWeatherKey(firstRun = false) {
const returnVal = await this.promptForText("Paste your API key in the box below.",[""],["82c29fdbgd6aebbb595d402f8a65fabf"])
const apiKey = returnVal.textFieldValue(0)
if (!apiKey || apiKey == "" || apiKey == null) { return await this.generateAlert("No API key was entered. Try copying the key again and re-running this script.",["Exit"]) }
this.writePreference("weather-cal-api-key", apiKey)
const apiResponse = await this.getWeatherApiPath(apiKey)
if (apiResponse && apiResponse.current) {
await this.generateAlert("The API key worked and was saved.",[firstRun ? "Continue" : "OK"])
} else if (firstRun) {
await this.generateAlert("New OpenWeather API keys may take a few hours to activate. Your widget will start displaying weather information once it's active.",["Continue"])
} else {
return await this.generateAlert("The key you entered, " + apiKey + ", didn't work. If it's a new key, it may take a few hours to activate.")
}
return true
},
// Get the API path, or the test response if a new API key is provided.
async getWeatherApiPath(newApiKey) {
const apiParameter = "?appid=" + (newApiKey || this.fm.readString(this.fm.joinPath(this.fm.libraryDirectory(), "weather-cal-api-key")).replace(/\"/g,""))
const apiPathPreference = this.fm.joinPath(this.fm.libraryDirectory(), "weather-cal-api-path")
if (!newApiKey && this.fm.fileExists(apiPathPreference)) {
return this.fm.readString(apiPathPreference).replace(/\"/g,"") + apiParameter
}
async function checkApiKey(path) {
const req = new Request(path + apiParameter + "&lat=37.332280&lon=-122.010980")
let response
try { response = await req.loadJSON() } catch { }
return response
}
let apiPath = "https://api.openweathermap.org/data/3.0/onecall"
let apiResponse = await checkApiKey(apiPath)
if (apiResponse && apiResponse.cod) {
apiPath = "https://api.openweathermap.org/data/2.5/onecall"
apiResponse = await checkApiKey(apiPath)
}
if (apiResponse && !apiResponse.cod) {
this.writePreference("weather-cal-api-path", apiPath)
}
return newApiKey ? apiResponse : apiPath + apiParameter
},
// Set the background of the widget.
async setWidgetBackground() {
const options = ["Solid color", "Automatic gradient", "Custom gradient", "Image from Photos"]
const backgroundType = await this.generateAlert("What type of background would you like for your widget?",options)
const background = this.fm.fileExists(this.bgPath) ? JSON.parse(this.fm.readString(this.bgPath)) : {}
if (backgroundType == 0) {
background.type = "color"
const returnVal = await this.promptForText("Background Color",[background.color,background.dark],["Default color","Dark mode color (optional)"],"Enter the hex value of the background color you want. You can optionally choose a different background color for dark mode.")
background.color = returnVal.textFieldValue(0)
background.dark = returnVal.textFieldValue(1)
} else if (backgroundType == 1) {
background.type = "auto"
} else if (backgroundType == 2) {
background.type = "gradient"
const returnVal = await this.promptForText("Gradient Colors",[background.initialColor,background.finalColor,background.initialDark,background.finalDark],["Top default color","Bottom default color","Top dark mode color","Bottom dark mode color"],"Enter the hex values of the colors for your gradient. You can optionally choose different background colors for dark mode.")
background.initialColor = returnVal.textFieldValue(0)
background.finalColor = returnVal.textFieldValue(1)
background.initialDark = returnVal.textFieldValue(2)
background.finalDark = returnVal.textFieldValue(3)
} else if (backgroundType == 3) {
background.type = "image"
const directoryPath = this.fm.joinPath(this.fm.documentsDirectory(), "Weather Cal")
if (!this.fm.fileExists(directoryPath) || !this.fm.isDirectory(directoryPath)) { this.fm.createDirectory(directoryPath) }
this.fm.writeImage(this.fm.joinPath(directoryPath, this.name + ".jpg"), await Photos.fromLibrary())
background.dark = !(await this.generateAlert("Would you like to use a different image in dark mode?",["Yes","No"]))
if (background.dark) this.fm.writeImage(this.fm.joinPath(directoryPath, this.name + " (Dark).jpg"), await Photos.fromLibrary())
}
this.writePreference(null, background, this.bgPath)
return this.previewValue()
},
// Load or reload a table full of preferences.
async loadPrefsTable(table,category) {
table.removeAllRows()
for (settingName in category) {
if (settingName == "name") continue
const row = new UITableRow()
row.dismissOnSelect = false
row.height = 55
const setting = category[settingName]
let valText
if (Array.isArray(setting.val)) {
valText = setting.val.map(a => a.title).join(", ")
} else if (setting.type == "fonts") {
const item = setting.val
const size = item.size.length ? `size ${item.size}` : ""
const font = item.font.length ? ` ${item.font}` : ""
const color = item.color.length ? ` (${item.color}${item.dark.length ? "/" + item.dark : ""})` : ""
const caps = item.caps.length && item.caps != this.enum.caps.none ? ` - ${item.caps}` : ""
valText = size + font + color + caps
} else if (typeof setting.val == "object") {
for (subItem in setting.val) {
const setupText = subItem + ": " + setting.val[subItem]
valText = (valText ? valText + ", " : "") + setupText
}
} else {
valText = setting.val + ""
}
const cell = row.addText(setting.name,valText)
cell.subtitleColor = Color.gray()
// If there's no type, it's just text.
if (!setting.type) {
row.onSelect = async () => {
const returnVal = await this.promptForText(setting.name,[setting.val],[],setting.description)
setting.val = returnVal.textFieldValue(0).trim()
await this.loadPrefsTable(table,category)
}
} else if (setting.type == "enum") {
row.onSelect = async () => {
const returnVal = await this.generateAlert(setting.name,setting.options,setting.description)
setting.val = setting.options[returnVal]
await this.loadPrefsTable(table,category)
}
} else if (setting.type == "bool") {
row.onSelect = async () => {
const returnVal = await this.generateAlert(setting.name,["true","false"],setting.description)
setting.val = !returnVal
await this.loadPrefsTable(table,category)
}
} else if (setting.type == "fonts") {
row.onSelect = async () => {
const keys = ["size","color","dark","font"]
const values = []
for (key of keys) values.push(setting.val[key])
const options = ["Capitalization","Save and Close"]
const prompt = await this.generatePrompt(setting.name,setting.description,options,values,keys)
const returnVal = await prompt.present()
if (returnVal) {
for (let i=0; i < keys.length; i++) {
setting.val[keys[i]] = prompt.textFieldValue(i).trim()
}
} else {
const capOptions = [this.enum.caps.upper,this.enum.caps.lower,this.enum.caps.title,this.enum.caps.none]
setting.val["caps"] = capOptions[await this.generateAlert("Capitalization",capOptions)]
}
await this.loadPrefsTable(table,category)
}
} else if (setting.type == "multival") {
row.onSelect = async () => {
// We need an ordered set.
const map = new Map(Object.entries(setting.val))
const keys = Array.from(map.keys())
const returnVal = await this.promptForText(setting.name,Array.from(map.values()),keys,setting.description)
for (let i=0; i < keys.length; i++) {
setting.val[keys[i]] = returnVal.textFieldValue(i).trim()
}
await this.loadPrefsTable(table,category)
}
} else if (setting.type == "multiselect") {
row.onSelect = async () => {
// We need to pass sets to the function.
const options = new Set(setting.options)
const selected = new Set(setting.val.map ? setting.val.map(a => a.identifier) : [])
const multiTable = new UITable()
await this.loadMultiTable(multiTable, options, selected)
await multiTable.present()
setting.val = [...options].filter(option => [...selected].includes(option.identifier))
await this.loadPrefsTable(table,category)
}
}
table.addRow(row)
}
table.reload()
},
// Load or reload a table with multi-select rows.
async loadMultiTable(table,options,selected) {
table.removeAllRows()
for (const item of options) {
const row = new UITableRow()
row.dismissOnSelect = false
row.height = 55
const isSelected = selected.has(item.identifier)
row.backgroundColor = isSelected ? Color.dynamic(new Color("d8d8de"), new Color("2c2c2c")) : Color.dynamic(Color.white(), new Color("151517"))
if (item.color) {
const colorCell = row.addText(isSelected ? "\u25CF" : "\u25CB")
colorCell.titleColor = item.color
colorCell.widthWeight = 1
}
const titleCell = row.addText(item.title)
titleCell.widthWeight = 15
row.onSelect = async () => {
if (isSelected) { selected.delete(item.identifier) }
else { selected.add(item.identifier) }
await this.loadMultiTable(table,options,selected)
}
table.addRow(row)
}
table.reload()
},
// Get the current settings for the widget or for editing.
async getSettings(forEditing = false) {
let settingsFromFile
if (this.fm.fileExists(this.prefPath)) { settingsFromFile = JSON.parse(this.fm.readString(this.prefPath)) }
const settingsObject = await this.defaultSettings()
for (category in settingsObject) {
for (item in settingsObject[category]) {
// If the setting exists, use it. Otherwise, the default is used.
let value = (settingsFromFile && settingsFromFile[category]) ? settingsFromFile[category][item] : undefined
if (value == undefined) { value = settingsObject[category][item].val }
// Format the object correctly depending on where it will be used.
if (forEditing) { settingsObject[category][item].val = value }
else { settingsObject[category][item] = value }
}
}
return settingsObject
},
// Edit preferences of the widget.
async editPreferences() {
const settingsObject = await this.getSettings(true)
const table = new UITable()
table.showSeparators = true
for (categoryKey in settingsObject) {
const row = new UITableRow()
row.dismissOnSelect = false
const category = settingsObject[categoryKey]
row.addText(category.name)
row.onSelect = async () => {
const subTable = new UITable()
subTable.showSeparators = true
await this.loadPrefsTable(subTable,category)
await subTable.present()
}
table.addRow(row)
}
await table.present()
for (categoryKey in settingsObject) {
for (item in settingsObject[categoryKey]) {
if (item == "name") continue
settingsObject[categoryKey][item] = settingsObject[categoryKey][item].val
}
}
this.writePreference(null, settingsObject, this.prefPath)
},
// Return the size of the widget preview.
previewValue() {
if (this.fm.fileExists(this.prefPath)) {
const settingsObject = JSON.parse(this.fm.readString(this.prefPath))
return settingsObject.widget.preview
} else { return "large" }
},
// Download a Scriptable script.
async downloadCode(filename, url) {
try {
const codeString = await new Request(url).loadString()
if (codeString.indexOf("// Variables used by Scriptable.") < 0) {
return false
} else {
this.fm.writeString(this.fm.joinPath(this.fm.documentsDirectory(), filename + ".js"), codeString)
return true
}
} catch {
return false
}
},
// Generate an alert with the provided array of options.
async generateAlert(title,options,message) {
return await this.generatePrompt(title,message,options)
},
// Default prompt for text field values.
async promptForText(title,values,keys,message) {
return await this.generatePrompt(title,message,null,values,keys)
},
// Generic implementation of an alert.
async generatePrompt(title,message,options,textvals,placeholders) {
const alert = new Alert()
alert.title = title
if (message) alert.message = message
const buttons = options || ["OK"]
for (button of buttons) { alert.addAction(button) }
if (!textvals) { return await alert.presentAlert() }
for (i=0; i < textvals.length; i++) {
alert.addTextField(placeholders && placeholders[i] ? placeholders[i] : null,(textvals[i] || "") + "")
}
if (!options) await alert.present()
return alert
},
// Write the value of a preference to disk.
writePreference(name, value, inputPath = null) {
const preference = typeof value == "string" ? value : JSON.stringify(value)
this.fm.writeString(inputPath || this.fm.joinPath(this.fm.libraryDirectory(), name), preference)
},
/*
* Widget spacing, background, and construction
* -------------------------------------------- */
// Create and return the widget.
async createWidget(layout, name, iCloudInUse, custom) {
if (!this.initialized) this.initialize(name, iCloudInUse)
// Determine if we're using the old or new setup.
if (typeof layout == "object") {
this.settings = layout
} else {
this.settings = await this.getSettings()
this.settings.layout = layout
}
// Shared values.
this.locale = this.settings.widget.locale
this.padding = parseInt(this.settings.widget.padding)
this.localization = this.settings.localization
this.format = this.settings.font
this.custom = custom
this.darkMode = !(Color.dynamic(Color.white(),Color.black()).red)
if (!this.locale || this.locale == "" || this.locale == null) { this.locale = Device.locale() }
// Widget setup.
this.widget = new ListWidget()
this.widget.spacing = 0
const verticalPad = this.padding < 10 ? 10 - this.padding : 10
const horizontalPad = this.padding < 15 ? 15 - this.padding : 15
const widgetPad = this.settings.widget.widgetPadding || {}
const topPad = (widgetPad.top && widgetPad.top.length) ? parseInt(widgetPad.top) : verticalPad
const leftPad = (widgetPad.left && widgetPad.left.length) ? parseInt(widgetPad.left) : horizontalPad
const bottomPad = (widgetPad.bottom && widgetPad.bottom.length) ? parseInt(widgetPad.bottom) : verticalPad
const rightPad = (widgetPad.right && widgetPad.right.length) ? parseInt(widgetPad.right) : horizontalPad
this.widget.setPadding(topPad, leftPad, bottomPad, rightPad)
// Background setup.
const background = JSON.parse(this.fm.readString(this.bgPath))
if (custom && custom.background) {
await custom.background(this.widget)
} else if (background.type == "color") {
this.widget.backgroundColor = this.provideColor(background)
} else if (background.type == "auto") {
const gradient = new LinearGradient()
const gradientSettings = await this.setupGradient()
gradient.colors = gradientSettings.color()
gradient.locations = gradientSettings.position()
this.widget.backgroundGradient = gradient
} else if (background.type == "gradient") {
const gradient = new LinearGradient()
const initialColor = this.provideColor({ color: background.initialColor, dark: background.initialDark })
const finalColor = this.provideColor({ color: background.finalColor, dark: background.finalDark })
gradient.colors = [initialColor, finalColor]
gradient.locations = [0, 1]
this.widget.backgroundGradient = gradient
} else if (background.type == "image") {
const extension = (this.darkMode && background.dark && !this.settings.widget.instantDark ? " (Dark)" : "") + ".jpg"
const imagePath = this.fm.joinPath(this.fm.joinPath(this.fm.documentsDirectory(), "Weather Cal"), name + extension)
if (this.fm.fileExists(imagePath)) {
if (this.fm.isFileStoredIniCloud(imagePath)) { await this.fm.downloadFileFromiCloud(imagePath) }
this.widget.backgroundImage = this.fm.readImage(imagePath)
} else if (config.runsInWidget) {
this.widget.backgroundColor = Color.gray()
} else {
this.generateAlert("Please choose a background image in the settings menu.")
}
}
// Construct the widget.
this.currentRow = {}
this.currentColumn = {}
this.left()
this.usingASCII = undefined
this.currentColumns = []
this.rowNeedsSetup = false
for (rawLine of this.settings.layout.split(/\r?\n/)) {
const line = rawLine.trim()
if (line == '') { continue }
if (this.usingASCII == undefined) {
if (line.includes("row")) { this.usingASCII = false }
if (line[0] == "-" && line[line.length-1] == "-") { this.usingASCII = true }
}
this.usingASCII ? await this.processASCIILine(line) : await this.executeItem(line)
}
return this.widget
},
// Execute an item in the layout generator.
async executeItem(item) {
const itemArray = item.replace(/[.,]$/,"").split('(')
const functionName = itemArray[0]
const parameter = itemArray[1] ? itemArray[1].slice(0, -1) : null
if (this.custom && this.custom[functionName]) { return await this.custom[functionName](this.currentColumn, parameter) }
if (this[functionName]) { return await this[functionName](this.currentColumn, parameter) }
console.error("The " + functionName + " item in your layout is unavailable. Check for misspellings or other formatting issues. If you have any custom items, ensure they are set up correctly.")
},
// Processes a single line of ASCII.
async processASCIILine(line) {
// If it's a line, enumerate previous columns (if any) and set up the new row.
if (line[0] == "-" && line[line.length-1] == "-") {
if (this.currentColumns.length > 0) {
for (col of this.currentColumns) {
if (!col) { continue }
this.column(this.currentColumn,col.width)
for (item of col.items) { await this.executeItem(item) }
}
this.currentColumns = []
}
return this.rowNeedsSetup = true
}
if (this.rowNeedsSetup) {
this.row(this.currentColumn)
this.rowNeedsSetup = false
}
const items = line.split('|')
for (var i=1; i < items.length-1; i++) {
if (!this.currentColumns[i]) { this.currentColumns[i] = { items: [] } }
const column = this.currentColumns[i].items
const rawItem = items[i]
const trimmedItem = rawItem.trim().split("(")[0]
// If it's not a widget item, it's a column width or a space.
if (!(this[trimmedItem] || (this.custom && this.custom[trimmedItem]))) {
if (rawItem.match(/\s+\d+\s+/)) {
const value = parseInt(trimmedItem)
if (value) { this.currentColumns[i].width = value }
continue
}
const prevItem = column[column.length-1]
if (trimmedItem == "" && (!prevItem || !prevItem.startsWith("space"))) {
column.push("space")
continue
}
}
const leading = rawItem.startsWith(" ")
const trailing = rawItem.endsWith(" ")
column.push((leading && trailing) ? "center" : (trailing ? "left" : "right"))
column.push(rawItem.trim())
}
},
// Makes a new row on the widget.
row(input, parameter) {
this.currentRow = this.widget.addStack()
this.currentRow.layoutHorizontally()
this.currentRow.setPadding(0, 0, 0, 0)
this.currentColumn.spacing = 0
if (parameter) this.currentRow.size = new Size(0,parseInt(parameter))
},
// Makes a new column on the widget.
column(input, parameter) {
this.currentColumn = this.currentRow.addStack()
this.currentColumn.layoutVertically()
this.currentColumn.setPadding(0, 0, 0, 0)
this.currentColumn.spacing = 0
if (parameter) this.currentColumn.size = new Size(parseInt(parameter),0)
},
// Adds a space, with an optional amount.
space(input, parameter) {
if (parameter) input.addSpacer(parseInt(parameter))
else input.addSpacer()
},
// Create an aligned stack to add content to.
align(column) {
const alignmentStack = column.addStack()
alignmentStack.layoutHorizontally()
const returnStack = this.currentAlignment(alignmentStack)
returnStack.layoutVertically()
return returnStack
},
// Set the current alignment.
setAlignment(left = false, right = false) {
function alignment(alignmentStack) {
if (right) alignmentStack.addSpacer()
const returnStack = alignmentStack.addStack()
if (left) alignmentStack.addSpacer()
return returnStack
}
this.currentAlignment = alignment
},
// Change the current alignment to right, left, or center.
right() { this.setAlignment(false, true) },
left() { this.setAlignment(true, false) },
center() { this.setAlignment(true, true) },
/*
* Data setup functions
* -------------------------------------------- */
// Set up the event data object.
async setupEvents() {
const eventSettings = this.settings.events
let calSetting = eventSettings.selectCalendars
let calendars
// Old, manually-entered comma lists.
if (typeof calSetting == "string") {
calSetting = calSetting.trim()
calendars = calSetting.length > 0 ? calSetting.split(",") : []
} else {
calendars = calSetting
}
let numberOfDays = parseInt(eventSettings.numberOfDays)
numberOfDays = isNaN(numberOfDays) ? 1 : numberOfDays
// Complex due to support for old boolean values.
let showFutureAt = parseInt(eventSettings.showTomorrow)
showFutureAt = isNaN(showFutureAt) ? (eventSettings.showTomorrow ? 0 : 24) : showFutureAt
const endDate = new Date()
endDate.setDate(this.now.getDate() + numberOfDays)
const events = await CalendarEvent.between(this.now, endDate)
this.data.events = events.filter((event, index, array) => {
if (!(index == array.findIndex(t => t.identifier == event.identifier && t.startDate.getTime() == event.startDate.getTime()))) { return false }
const diff = this.dateDiff(this.now, event.startDate)
if (diff < 0 || diff > numberOfDays) { return false }
if (diff > 0 && this.now.getHours() < showFutureAt) { return false }
if (calendars.length && !(calendars.some(a => a.identifier == event.calendar.identifier) || calendars.includes(event.calendar.title))) { return false }
if (event.title.startsWith("Canceled:")) { return false }
if (event.isAllDay) { return eventSettings.showAllDay }
// If they leave it blank, set minutes after to the duration of the event
const minutesAfter = parseInt(eventSettings.minutesAfter) >= 0 ? parseInt(eventSettings.minutesAfter) * 60000 : event.endDate - event.startDate
return (event.startDate.getTime() + minutesAfter > this.now.getTime())
}).slice(0,parseInt(eventSettings.numberOfEvents))
},
// Set up the reminders data object.
async setupReminders() {
const reminderSettings = this.settings.reminders
let listSetting = reminderSettings.selectLists
let lists
// Old, manually-entered comma lists.
if (typeof listSetting == "string") {
listSetting = listSetting.trim()
lists = listSetting.length > 0 ? listSetting.split(",") : []
} else {
lists = listSetting
}
const reminders = await Reminder.allIncomplete()
reminders.sort(function(a, b) {
// Non-null due dates are prioritized.
if (!a.dueDate && b.dueDate) return 1
if (a.dueDate && !b.dueDate) return -1
if (!a.dueDate && !b.dueDate) return 0
// Otherwise, earlier due dates go first.
const aTime = a.dueDate.getTime()
const bTime = b.dueDate.getTime()
if (aTime > bTime) return 1
if (aTime < bTime) return -1
return 0
})
this.data.reminders = reminders.filter((reminder) => {
if (lists.length && !(lists.some(a => a.identifier == reminder.calendar.identifier) || lists.includes(reminder.calendar.title))) { return false }
if (!reminder.dueDate) { return reminderSettings.showWithoutDueDate }
if (reminder.isOverdue) { return reminderSettings.showOverdue }
if (reminderSettings.todayOnly) { return this.dateDiff(reminder.dueDate, this.now) == 0 }
return true
}).slice(0,parseInt(reminderSettings.numberOfReminders))
},
// Set up the gradient for the widget background.
async setupGradient() {
if (!this.data.sun) { await this.setupSunrise() }
if (this.isNight(this.now)) {
return {
color() { return [new Color("16296b"), new Color("021033"), new Color("021033"), new Color("113245")] },
position() { return [-0.5, 0.2, 0.5, 1] },
}
}
return {
color() { return [new Color("3a8cc1"), new Color("90c0df")] },
position() { return [0, 1] },
}
},
// Set up the location data object.
async setupLocation() {
const locationPath = this.fm.joinPath(this.fm.libraryDirectory(), "weather-cal-location")
const locationCache = this.getCache(locationPath, this.settings ? parseInt(this.settings.widget.updateLocation) : null)
let location
if (!locationCache || locationCache.cacheExpired) {
try { location = await Location.current() }
catch { location = locationCache || { cacheExpired: true } }
try {
const geocode = await Location.reverseGeocode(location.latitude, location.longitude, this.locale)
location.locality = (geocode[0].locality || geocode[0].postalAddress.city) || geocode[0].administrativeArea
} catch {
location.locality = locationCache ? locationCache.locality : null
}
// If (and only if) we have new data, write it to disk.
if (!location.cacheExpired) this.fm.writeString(locationPath, JSON.stringify(location))
}
this.data.location = location || locationCache
if (!this.data.location.latitude) return false
return true
},
// Set up the sun data object.
async setupSunrise() {
if (!this.data.location) { await this.setupLocation() }
const sunPath = this.fm.joinPath(this.fm.libraryDirectory(), "weather-cal-cache")
let sunData = this.getCache(sunPath, 60, 1440)
const forcedLocale = this.settings.weather.locale || ""
let locale = forcedLocale.length ? forcedLocale : this.locale
const safeLocales = this.getOpenWeatherLocaleCodes()
if (!forcedLocale.length && !safeLocales.includes(locale)) {
const languages = [locale, ...locale.split("_"), ...locale.split("-"), Device.locale(), ...Device.locale().split("_"), ...Device.locale().split("-")]
for (item of languages) {
if (safeLocales.includes(item)) {
locale = item
break
}
}
}
if (!sunData || sunData.cacheExpired) {
try {
const apiPath = await this.getWeatherApiPath()
const sunReq = apiPath + "&lat=" + this.data.location.latitude + "&lon=" + this.data.location.longitude + "&exclude=minutely,alerts&units=" + this.settings.widget.units + "&lang=" + locale
sunData = await new Request(sunReq).loadJSON()
if (sunData.cod) { sunData = null }
if (sunData) { this.fm.writeString(sunPath, JSON.stringify(sunData)) }
} catch {}
}
this.data.sun = {}
this.data.sun.sunrise = sunData ? sunData.daily[0].sunrise*1000 : null
this.data.sun.sunset = sunData ? sunData.daily[0].sunset*1000 : null
this.data.sun.tomorrow = sunData ? sunData.daily[1].sunrise*1000 : null
},
// Set up the weather data object.
async setupWeather() {
if (!this.data.location) { await this.setupLocation() }
const weatherPath = this.fm.joinPath(this.fm.libraryDirectory(), "weather-cal-cache")
let weatherData = this.getCache(weatherPath, 1, 60)
const forcedLocale = this.settings.weather.locale || ""
let locale = forcedLocale.length ? forcedLocale : this.locale
const safeLocales = this.getOpenWeatherLocaleCodes()
if (!forcedLocale.length && !safeLocales.includes(locale)) {
const languages = [locale, ...locale.split("_"), ...locale.split("-"), Device.locale(), ...Device.locale().split("_"), ...Device.locale().split("-")]
for (item of languages) {
if (safeLocales.includes(item)) {
locale = item
break
}
}
}
if (!weatherData || weatherData.cacheExpired) {
try {
const apiPath = await this.getWeatherApiPath()
const weatherReq = apiPath + "&lat=" + this.data.location.latitude + "&lon=" + this.data.location.longitude + "&exclude=minutely,alerts&units=" + this.settings.widget.units + "&lang=" + locale
weatherData = await new Request(weatherReq).loadJSON()
if (weatherData.cod) { weatherData = null }
if (weatherData) { this.fm.writeString(weatherPath, JSON.stringify(weatherData)) }
} catch {}
}
// English continues using the "main" weather description.
const english = (locale.split("_")[0] == "en")
this.data.weather = {}
this.data.weather.currentTemp = weatherData ? weatherData.current.temp : null
this.data.weather.currentCondition = weatherData ? weatherData.current.weather[0].id : 100
this.data.weather.currentDescription = weatherData ? (english ? weatherData.current.weather[0].main : weatherData.current.weather[0].description) : "--"
this.data.weather.todayHigh = weatherData ? weatherData.daily[0].temp.max : null
this.data.weather.todayLow = weatherData ? weatherData.daily[0].temp.min : null
this.data.weather.forecast = []
this.data.weather.hourly = []
for (let i=0; i <= 7; i++) {
this.data.weather.forecast[i] = weatherData ? ({High: weatherData.daily[i].temp.max, Low: weatherData.daily[i].temp.min, Condition: weatherData.daily[i].weather[0].id}) : { High: null, Low: null, Condition: 100 }
this.data.weather.hourly[i] = weatherData ? ({Temp: weatherData.hourly[i].temp, Condition: weatherData.hourly[i].weather[0].id}) : { Temp: null, Condition: 100 }
}
this.data.weather.tomorrowRain = weatherData ? weatherData.daily[1].pop * 100 : null
this.data.weather.nextHourRain = weatherData ? weatherData.hourly[1].pop * 100 : null
},
// Set up the COVID data object.
async setupCovid() {
const covidPath = this.fm.joinPath(this.fm.libraryDirectory(), "weather-cal-covid")
let covidData = this.getCache(covidPath, 15, 1440)
if (!covidData || covidData.cacheExpired) {
try {
covidData = await new Request("https://coronavirus-19-api.herokuapp.com/countries/" + encodeURIComponent(this.settings.covid.country.trim())).loadJSON()
this.fm.writeString(covidPath, JSON.stringify(covidData))
} catch {}
}
this.data.covid = covidData || {}
},
// Set up the news.
async setupNews() {
const newsPath = this.fm.joinPath(this.fm.libraryDirectory(), this.settings.news.url)
let newsData = this.getCache(newsPath, 1, 1440)
if (!newsData || newsData.cacheExpired) {
try {
let rawData = await new Request(this.settings.news.url).loadString()
const isRss = rawData.includes("<rss")
rawData = getTag(rawData, isRss ? "item" : "entry", parseInt(this.settings.news.numberOfItems))
if (!rawData || rawData.length == 0) { throw 0 }
newsData = []
for (item of rawData) {
const listing = {}
listing.title = scrubString(getTag(item, "title")[0])
listing.link = scrubString(getTag(item, "link")[0])
listing.date = new Date(getTag(item, isRss ? "pubDate" : "published")[0])
newsData.push(listing)
}
this.fm.writeString(newsPath, JSON.stringify(newsData))
} catch {}
}