Repository navigation
Expand file tree
/
Copy pathweather-cal-code.js
More file actions
1985 lines (1564 loc) · 68.4 KB
/
Copy pathweather-cal-code.js
File metadata and controls
1985 lines (1564 loc) · 68.4 KB
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 is the Weather Cal code script.
Don't delete it or change its name.
To update, run a Weather Cal widget script.
In the popup, tap "Update code".
It will update to the newest version.
~
*/
// Warn the user if this script is added to a widget.
if (config.runsInWidget) {
let infoWidget = new ListWidget()
infoWidget.addText('"Weather-cal-code" 不作为小部件使用. 请使用"Weather Cal"脚本设置为小部件')
Script.setWidget(infoWidget)
Script.complete()
}
// Set up the widget.
module.exports.runSetup = async (name, iCloudInUse, codeFilename, gitHubUrl) => {
return await setup(name, iCloudInUse, codeFilename, gitHubUrl)
}
// Return the widget.
module.exports.createWidget = async (settings, name, iCloudInUse) => {
return await makeWidget(settings, name, iCloudInUse)
}
async function setup(name, iCloudInUse, codeFilename, gitHubUrl) {
const fm = iCloudInUse ? FileManager.iCloud() : FileManager.local()
const widgetUrl = "https://raw.githubusercontent.com/KerwinKwong/Weather-Cal/main/Weather-Cal/weather-cal.js"
// If no setup file exists, this is the initial Weather Cal setup.
const setupPath = fm.joinPath(fm.libraryDirectory(), "weather-cal-setup")
if (!fm.fileExists(setupPath)) { return await initialSetup() }
// If a settings file exists for this widget, we're editing settings.
const widgetpath = fm.joinPath(fm.libraryDirectory(), "weather-cal-" + name)
if (fm.fileExists(widgetpath)) { return await editSettings() }
// Otherwise, we're setting up this particular widget.
await generateAlert("Weather Cal已设置,但是您需要为此小部件选择背景。",["Continue"])
return await setWidgetBackground()
// Run the initial setup.
async function initialSetup() {
// Welcome the user and make sure they like the script name.
let message = "欢迎使用Weather Cal。在开始之前,请确保脚本具有所需的名称。"
let options = ['我喜欢"' + name + '"这个名字', "我要更改"]
let shouldExit = await generateAlert(message,options)
if (shouldExit) return
// Welcome the user and check for permissions.
message = "接下来,需要检查您是否已授予Scriptable应用程序权限。 这可能需要几秒钟。"
options = ["检查权限"]
await generateAlert(message,options)
let errors = []
try { await Location.current() } catch { 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没有权限" + issues + "。 如果未在“设置”中启用某些功能,则可能无法使用。"
options = ["仍然继续设置", "退出设置"]
} else {
message = "您的权限已启用。"
options = ["继续设置"]
}
shouldExit = await generateAlert(message,options)
if (shouldExit) return
// Set up the weather integration.
message = "要在小部件上显示天气,您需要一个OpenWeather API密钥。"
options = ["我已有一个密钥", "我需要一个密钥", "我不想显示天气信息"]
const weather = await generateAlert(message,options)
// Show a web view to claim the API key.
if (weather == 1) {
message = "在下一个窗口中,注册OpenWeather。 找到API密钥,将其复制,然后关闭Web视图。 然后将提示您粘贴密钥。"
options = ["继续"]
let weather = await generateAlert(message,options)
let 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) {
const response = await getWeatherKey(true)
if (!response) return
}
// Set up background image.
await setWidgetBackground()
// Record setup completion.
writePreference("weather-cal-setup", "true")
message = "您的小部件已准备就绪! 现在,您可以查看预览。 您可以在脚本代码中调整更多设置。 准备好后,将Scriptable小部件添加到主屏幕,然后选择此Weather-cal脚本。"
options = ["显示预览"]
await generateAlert(message,options)
// Return and show the preview.
return true
}
// Edit the widget settings.
async function editSettings() {
let message = "编辑您的小部件设置。"
let options = ["显示预览", "更改背景", "重置API", "更新代码", "重置widget", "退出设置"]
const response = await generateAlert(message,options)
// Return true to show the widget preview.
if (response == 0) return true
// Set the background and show a preview.
if (response == 1) {
await setWidgetBackground()
return true
}
// Set the API key.
if (response == 2) {
await getWeatherKey()
return
}
if (response == 3) {
// Prompt the user for updates.
message = "您想更新Weather Cal代码吗? 您的小部件将不受影响。"
options = ["更新", "退出"]
const updateResponse = await generateAlert(message,options)
// Exit if the user didn't want to update.
if (updateResponse) return
// Try updating the code.
const success = await downloadCode(codeFilename, gitHubUrl)
message = success ? "代码更新已完成。" : "更新失败,请稍后再试。"
options = ["OK"]
await generateAlert(message,options)
return
}
if (response == 4) {
const alert = new Alert()
alert.message = "您确定要完全重置此小部件吗?"
alert.addDestructiveAction("重置")
alert.addAction("取消")
const cancelReset = await alert.present()
if (cancelReset === 0) {
const success = await downloadCode(name, widgetUrl)
message = success ? "脚本已被重置。 关闭脚本,然后重新打开以使更改生效。" : "重置失败"
options = ["OK"]
await generateAlert(message,options)
}
return
}
// If response was Exit, just return.
return
}
// Get the weather key, optionally determining if it's the first run.
async function getWeatherKey(firstRun = false) {
// Prompt for the key.
const apiKey = await promptForText("在下面的输入框中粘贴您的API密钥。", "82c29fdbgd6aebbb595d402f8a65fabf")
let message, options
if (!apiKey || apiKey == "" || apiKey == null) {
message = "没有输入API密钥。 尝试再次复制密钥,然后重新运行此脚本。"
options = ["退出"]
await generateAlert(message,options)
return false
}
// Save the key.
writePreference("weather-cal-api-key", apiKey)
// Test to see if the key works.
const req = new Request("https://api.openweathermap.org/data/2.5/onecall?lat=37.332280&lon=-122.010980&appid=" + apiKey)
let val = {}
try { val = await req.loadJSON() } catch { val.current = false }
// Warn the user if it didn't work.
if (!val.current) {
message = firstRun ? "新的OpenWeather API密钥可能需要几个小时才能激活。 您的小部件一旦启用,将开始显示天气信息。" : "您输入的密钥," + apiKey + ", 没用。 如果是新密钥,则可能需要几个小时才能激活。"
options = [firstRun ? "继续" : "OK"]
await generateAlert(message,options)
// Otherwise, confirm that it was saved.
} else if (val.current && !firstRun) {
message = "新密钥可用并被保存。"
options = ["OK"]
await generateAlert(message,options)
}
// If we made it this far, we did it.
return true
}
// Set the background of the widget.
async function setWidgetBackground() {
// Prompt for the widget background.
let message = "您希望小部件使用哪种背景?"
let options = ["纯色背景", "自动渐变", "自定义渐变", "选择图片"]
let backgroundType = await generateAlert(message,options)
let background = {}
if (backgroundType == 0) {
background.type = "color"
background.color = await promptForText("输入所需背景颜色的十六进制值。","#007030")
} else if (backgroundType == 1) {
background.type = "auto"
} else if (backgroundType == 2) {
background.type = "gradient"
background.initialColor = await promptForText("输入第一个渐变颜色的十六进制值。","#007030")
background.finalColor = await promptForText("输入第二个渐变颜色的十六进制值。","#007030")
} else if (backgroundType == 3) {
background.type = "image"
// Create the Weather Cal directory if it doesn't already exist.
const dirPath = fm.joinPath(fm.documentsDirectory(), "Weather Cal")
if (!fm.fileExists(dirPath) || !fm.isDirectory(dirPath)) {
fm.createDirectory(dirPath)
}
// Determine if a dupe already exists.
const dupePath = fm.joinPath(dirPath, name + " 2.jpg")
const dupeAlreadyExists = fm.fileExists(dupePath)
// Get the image and write it to disk.
const img = await Photos.fromLibrary()
const path = fm.joinPath(dirPath, name + ".jpg")
fm.writeImage(path, img)
// If we just created a dupe, alert the user.
if (!dupeAlreadyExists && fm.fileExists(dupePath)) {
message = "Weather Cal检测到重复的图像。 请打开“文件”应用,“Scriptable”>“Weather-cal”,并确保文件名为" + name + ".jpg 是正确的。"
options = ["OK"]
const response = generateAlert(message,options)
}
}
writePreference("weather-cal-" + name, background)
return true
}
// Download a Scriptable script.
async function downloadCode(filename, url) {
const pathToCode = fm.joinPath(fm.documentsDirectory(), filename + ".js")
const req = new Request(url)
try {
const codeString = await req.loadString()
fm.writeString(pathToCode, codeString)
return true
} catch {
return false
}
}
// Generate an alert with the provided array of options.
async function generateAlert(message,options) {
const alert = new Alert()
alert.message = message
for (const option of options) {
alert.addAction(option)
}
const response = await alert.presentAlert()
return response
}
// Prompt for a single text field value.
async function promptForText(message,placeholder) {
const alert = new Alert()
alert.message = message
alert.addTextField(placeholder)
alert.addAction("OK")
await alert.present()
return alert.textFieldValue(0)
}
// Write the value of a preference to disk.
function writePreference(filename, value) {
const path = fm.joinPath(fm.libraryDirectory(), filename)
if (typeof value === "string") {
fm.writeString(path, value)
} else {
fm.writeString(path, JSON.stringify(value))
}
}
}
async function makeWidget(settings, name, iCloudInUse) {
// All widget items must be documented here.
function provideFunction(name) {
const functions = {
battery() { return battery },
center() { return center },
column() { return column },
covid() { return covid },
current() { return current },
date() { return date },
events() { return events },
forecast() { return forecast },
future() { return future },
greeting() { return greeting },
left() { return left },
reminders() { return reminders },
right() { return right },
row() { return row },
space() { return space },
sunrise() { return sunrise },
sunset() { return sunset },
text() { return text },
}
return functions[name]()
}
// Get often-used values from the settings object.
let locale = settings.widget.locale
const padding = settings.widget.padding
const tintIcons = settings.widget.tintIcons
const localizedText = settings.localization
const textFormat = settings.font
// Create the other shared variables.
var data = {}
const currentDate = new Date()
const files = iCloudInUse ? FileManager.iCloud() : FileManager.local()
// Make sure we have a locale value.
if (!locale || locale == "" || locale == null) { locale = Device.locale() }
// Set up the widget with padding.
const widget = new ListWidget()
const horizontalPad = padding < 10 ? 10 - padding : 10
const verticalPad = padding < 15 ? 15 - padding : 15
widget.setPadding(horizontalPad, verticalPad, horizontalPad, verticalPad)
widget.spacing = 0
/*
* BACKGROUND DISPLAY
* ==================
*/
// Read the background information from disk.
const backgroundPath = files.joinPath(files.libraryDirectory(), "weather-cal-" + name)
const backgroundRaw = files.readString(backgroundPath)
const background = JSON.parse(backgroundRaw)
if (background.type == "color") {
widget.backgroundColor = new Color(background.color)
} else if (background.type == "auto") {
const gradient = new LinearGradient()
const gradientSettings = await setupGradient()
gradient.colors = gradientSettings.color()
gradient.locations = gradientSettings.position()
widget.backgroundGradient = gradient
} else if (background.type == "gradient") {
const gradient = new LinearGradient()
const initialColor = new Color(background.initialColor)
const finalColor = new Color(background.finalColor)
gradient.colors = [initialColor, finalColor]
gradient.locations = [0, 1]
widget.backgroundGradient = gradient
} else if (background.type == "image") {
// Determine if our image exists.
const dirPath = files.joinPath(files.documentsDirectory(), "Weather Cal")
const path = files.joinPath(dirPath, name + ".jpg")
const exists = files.fileExists(path)
// If it exists, load from file.
if (exists) {
if (iCloudInUse) { await files.downloadFileFromiCloud(path) }
widget.backgroundImage = files.readImage(path)
// If it's missing when running in the widget, use a gray background.
} else if (!exists && config.runsInWidget) {
widget.backgroundColor = Color.gray()
// But if we're running in app, prompt the user for the image.
} else {
const img = await Photos.fromLibrary()
widget.backgroundImage = img
files.writeImage(path, img)
}
}
/*
* CONSTRUCTION
* ============
*/
// Set up the layout variables.
var currentRow = {}
var currentColumn = {}
// Set up the initial alignment.
var currentAlignment = alignLeft
// Set up the global ASCII variables.
var foundASCII, usingASCII
var currentColumns = []
var rowNeedsSetup = false
// Process the layout.
for (line of settings.layout.split(/\r?\n/)) {
await processLine(line)
}
// Finish the widget and return.
return widget
/*
* CONSTRUCTION FUNCTIONS
* Processing the layout input.
* ============================
*/
async function processLine(lineInput) {
// Trim the input.
const line = lineInput.trim()
// If it's blank, return.
if (line == '') { return }
// If we have a row, we're not using ASCII.
if (!foundASCII && line.includes('row')) {
foundASCII = true
usingASCII = false
// If we have a row of dashes, we're using ASCII.
} else if (!foundASCII && line[0] == '-' && line[line.length-1] == '-') {
foundASCII = true
usingASCII = true
}
if (usingASCII) { await processASCIILine(line) }
else { await processRegularLine(line) }
}
// Process a single line of regular layout.
async function processRegularLine(lineInput) {
let line = lineInput
// If it's using the old style, remove the comma.
if (line[line.length-1] == ',') {
line = line.slice(0, -1)
}
// If there are no parentheses, run the function.
let item = line.split('(')
if (!item[1]) {
const func = provideFunction(item[0])
await func(currentColumn)
return
}
// Otherwise, pass the parameter.
const param = item[1].slice(0, -1)
const func = provideFunction(item[0])(parseInt(param) || param)
await func(currentColumn)
}
// Processes a single line of ASCII.
async function processASCIILine(lineInput) {
const line = lineInput.replace(/\.+/g,'')
// If it's a line, enumerate previous columns (if any) and set up the new row.
if (line[0] == '-' && line[line.length-1] == '-') {
if (currentColumns.length > 0) { await enumerateColumns() }
rowNeedsSetup = true
return
}
// If it's the first content row, finish the row setup.
if (rowNeedsSetup) {
row(currentColumn)
rowNeedsSetup = false
}
// If there's a number, this is a setup row.
const setupRow = line.match(/\d+/)
// Otherwise, it has columns.
const items = line.split('|')
// Iterate through each item.
for (var i=1; i < items.length-1; i++) {
// If the current column doesn't exist, make it.
if (!currentColumns[i]) { currentColumns[i] = { items: [] } }
// Now we have a column to add the items to.
const column = currentColumns[i].items
// Get the current item and its trimmed version.
const item = items[i]
const trim = item.trim()
// If it's not a function, figure out spacing.
if (!provideFunction(trim)) {
// If it's a setup row, whether or not we find the number, we keep going.
if (setupRow) {
const value = parseInt(trim, 10)
if (value) { currentColumns[i].width = value }
continue
}
// If it's blank and we haven't already added a space, add one.
const prevItem = column[column.length-1]
if (trim == '' && (!prevItem || (prevItem && !prevItem.startsWith("space")))) {
column.push("space")
}
// Either way, we're done.
continue
}
// Determine the alignment.
const index = item.indexOf(trim)
const length = item.slice(index,item.length).length
let align
if (index > 0 && length > trim.length) { align = "center" }
else if (index > 0) { align = "right" }
else { align = "left" }
// Add the items to the column.
column.push(align)
column.push(trim)
}
}
// Runs the function names in each column.
async function enumerateColumns() {
if (currentColumns.length > 0) {
for (col of currentColumns) {
// If it's null, go to the next one.
if (!col) { continue }
// If there's a width, use the width function.
if (col.width) {
column(col.width)(currentColumn)
// Otherwise, create the column normally.
} else {
column(currentColumn)
}
for (item of col.items) {
const func = provideFunction(item)
await func(currentColumn)
}
}
currentColumns = []
}
}
/*
* LAYOUT FUNCTIONS
* These functions manage spacing and alignment.
* =============================================
*/
// Makes a new row on the widget.
function row(input = null) {
function makeRow() {
currentRow = widget.addStack()
currentRow.layoutHorizontally()
currentRow.setPadding(0, 0, 0, 0)
currentColumn.spacing = 0
// If input was given, make a row of that size.
if (input > 0) { currentRow.size = new Size(0,input) }
}
// If there's no input or it's a number, it's being called in the layout declaration.
if (!input || typeof input == "number") { return makeRow }
// Otherwise, it's being called in the generator.
else { makeRow() }
}
// Makes a new column on the widget.
function column(input = null) {
function makeColumn() {
currentColumn = currentRow.addStack()
currentColumn.layoutVertically()
currentColumn.setPadding(0, 0, 0, 0)
currentColumn.spacing = 0
// If input was given, make a column of that size.
if (input > 0) { currentColumn.size = new Size(input,0) }
}
// If there's no input or it's a number, it's being called in the layout declaration.
if (!input || typeof input == "number" || typeof input == "string" ) {
return makeColumn
}
// Otherwise, it's being called in the generator.
else { makeColumn() }
}
// Create an aligned stack to add content to.
function align(column) {
// Add the containing stack to the column.
let alignmentStack = column.addStack()
alignmentStack.layoutHorizontally()
// Get the correct stack from the alignment function.
let returnStack = currentAlignment(alignmentStack)
returnStack.layoutVertically()
return returnStack
}
// Create a right-aligned stack.
function alignRight(alignmentStack) {
alignmentStack.addSpacer()
let returnStack = alignmentStack.addStack()
return returnStack
}
// Create a left-aligned stack.
function alignLeft(alignmentStack) {
let returnStack = alignmentStack.addStack()
alignmentStack.addSpacer()
return returnStack
}
// Create a center-aligned stack.
function alignCenter(alignmentStack) {
alignmentStack.addSpacer()
let returnStack = alignmentStack.addStack()
alignmentStack.addSpacer()
return returnStack
}
// This function adds a space, with an optional amount.
function space(input = null) {
// This function adds a spacer with the input width.
function spacer(column) {
// If the input is null or zero, add a flexible spacer.
if (!input || input == 0) { column.addSpacer() }
// Otherwise, add a space with the specified length.
else { column.addSpacer(input) }
}
// If there's no input or it's a number, it's being called in the column declaration.
if (!input || typeof input == "number") { return spacer }
// Otherwise, it's being called in the column generator.
else { input.addSpacer() }
}
// Change the current alignment to right.
function right(x) { currentAlignment = alignRight }
// Change the current alignment to left.
function left(x) { currentAlignment = alignLeft }
// Change the current alignment to center.
function center(x) { currentAlignment = alignCenter }
/*
* SETUP FUNCTIONS
* These functions prepare data needed for items.
* ==============================================
*/
// Set up the data.events object.
async function setupEvents() {
data.events = {}
const eventSettings = settings.events
const calendars = eventSettings.selectCalendars
const numberOfEvents = eventSettings.numberOfEvents
// Function to determine if an event should be shown.
function shouldShowEvent(event) {
// If events are filtered and the calendar isn't in the selected calendars, return false.
if (calendars.length && !calendars.includes(event.calendar.title)) { return false }
// Hack to remove canceled Office 365 events.
if (event.title.startsWith("Canceled:")) { return false }
// If it's an all-day event, only show if the setting is active.
if (event.isAllDay) { return eventSettings.showAllDay }
// Otherwise, return the event if it's in the future or recently started.
const minutesAfter = eventSettings.minutesAfter * 60000 || 0
return (event.startDate.getTime() + minutesAfter > currentDate.getTime())
}
// Determine which events to show, and how many.
const todayEvents = await CalendarEvent.today([])
let shownEvents = 0
let futureEvents = []
for (const event of todayEvents) {
if (shownEvents == numberOfEvents) { break }
if (shouldShowEvent(event)) {
futureEvents.push(event)
shownEvents++
}
}
// If there's room and we need to, show tomorrow's events.
let multipleTomorrowEvents = false
let showTomorrow = eventSettings.showTomorrow
// Determine if we're specifying an hour to show.
if (typeof showTomorrow == "number") {
showTomorrow = (currentDate.getHours() > showTomorrow)
}
if (showTomorrow && shownEvents < numberOfEvents) {
const tomorrowEvents = await CalendarEvent.tomorrow([])
for (const event of tomorrowEvents) {
if (shownEvents == numberOfEvents) { break }
if (shouldShowEvent(event)) {
// Add the tomorrow label prior to the first tomorrow event.
if (!multipleTomorrowEvents) {
// The tomorrow label is pretending to be an event.
futureEvents.push({ title: localizedText.tomorrowLabel.toUpperCase(), isLabel: true })
multipleTomorrowEvents = true
}
// Show the tomorrow event and increment the counter.
futureEvents.push(event)
shownEvents++
}
}
}
// Store the future events, and whether or not any events are displayed.
data.events.futureEvents = futureEvents
data.events.eventsAreVisible = (futureEvents.length > 0) && (eventSettings.numberOfEvents > 0)
}
// Set up the data.reminders object.
async function setupReminders() {
data.reminders = {}
const reminderSettings = settings.reminders
const lists = reminderSettings.selectLists
const numberOfReminders = reminderSettings.numberOfReminders
const showWithoutDueDate = reminderSettings.showWithoutDueDate
const showOverdue = reminderSettings.showOverdue
// Function to determine if an event should be shown.
function shouldShowReminder(reminder) {
// If reminders are filtered and the list isn't in the selected lists, return false.
if (lists.length && !lists.includes(reminder.calendar.title)) { return false }
// If there's no due date, use the setting.
if (!reminder.dueDate) { return showWithoutDueDate }
// If it's overdue, use the setting.
if (reminder.isOverdue) { return showOverdue }
// If we only want today and overdue, use the setting.
if (reminderSettings.todayOnly) {
return sameDay(reminder.dueDate, currentDate)
}
// Otherwise, return true.
return true
}
// Determine which reminders to show.
let reminders = await Reminder.allIncomplete()
reminders = reminders.filter(shouldShowReminder).slice(0,numberOfReminders)
// Sort in order of due date.
reminders.sort(function(a, b) {
// Due dates are always picked first.
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
})
// Store the data.
data.reminders.all = reminders
}
// Set up the gradient for the widget background.
async function setupGradient() {
// Requirements: sunrise
if (!data.sun) { await setupSunrise() }
let gradient = {
dawn: {
color() { return [new Color("142C52"), new Color("1B416F"), new Color("62668B")] },
position() { return [0, 0.5, 1] },
},
sunrise: {
color() { return [new Color("274875"), new Color("766f8d"), new Color("f0b35e")] },
position() { return [0, 0.8, 1.5] },
},
midday: {
color() { return [new Color("3a8cc1"), new Color("90c0df")] },
position() { return [0, 1] },
},
noon: {
color() { return [new Color("b2d0e1"), new Color("80B5DB"), new Color("3a8cc1")] },
position() { return [-0.2, 0.2, 1.5] },
},
sunset: {
color() { return [new Color("32327A"), new Color("662E55"), new Color("7C2F43")] },
position() { return [0.1, 0.9, 1.2] },
},
twilight: {
color() { return [new Color("021033"), new Color("16296b"), new Color("414791")] },
position() { return [0, 0.5, 1] },
},
night: {
color() { return [new Color("16296b"), new Color("021033"), new Color("021033"), new Color("113245")] },
position() { return [-0.5, 0.2, 0.5, 1] },
},
}
const sunrise = data.sun.sunrise
const sunset = data.sun.sunset
// Use sunrise or sunset if we're within 30min of it.
if (closeTo(sunrise)<=15) { return gradient.sunrise }
if (closeTo(sunset)<=15) { return gradient.sunset }
// In the 30min before/after, use dawn/twilight.
if (closeTo(sunrise)<=45 && currentDate.getTime() < sunrise) { return gradient.dawn }
if (closeTo(sunset)<=45 && currentDate.getTime() > sunset) { return gradient.twilight }
// Otherwise, if it's night, return night.
if (isNight(currentDate)) { return gradient.night }
// If it's around noon, the sun is high in the sky.
if (currentDate.getHours() == 12) { return gradient.noon }
// Otherwise, return the "typical" theme.
return gradient.midday
}
// Set up the location data object.
async function setupLocation() {
// Get the cached location info if it exists.
const locationPath = files.joinPath(files.libraryDirectory(), "weather-cal-location")
const locationExists = files.fileExists(locationPath)
let cachedLocation
if (locationExists) {
cachedLocation = JSON.parse(files.readString(locationPath))
}
// If it's been more than an hour, ask iOS for location.
let location, geocode
const timeToCache = 60 * 60 * 1000
const locationDate = locationExists ? files.modificationDate(locationPath).getTime() : -(timeToCache+1)
const locationDataOld = (currentDate.getTime() - locationDate) > timeToCache
if (locationDataOld) {
try {
location = await Location.current()
geocode = location ? await Location.reverseGeocode(location.latitude, location.longitude, locale) : false
} catch {}
}
// Store the possible location values in the data object.
data.location = {}
if (location) {
data.location.latitude = location.latitude
data.location.longitude = location.longitude
} else {
data.location.latitude = cachedLocation.latitude
data.location.longitude = cachedLocation.longitude
}
if (geocode) {
data.location.locality = (geocode[0].locality || geocode[0].postalAddress.city) || geocode[0].administrativeArea
} else {
data.location.locality = cachedLocation.locality
}
// If we have old location data, save it to disk.
if (locationDataOld) {
files.writeString(locationPath, JSON.stringify(data.location))
}
}
// Set up the sun data object.
async function setupSunrise() {
// Requirements: location
if (!data.location) { await setupLocation() }
async function getSunData(date) {
const req = "https://api.sunrise-sunset.org/json?lat=" + data.location.latitude + "&lng=" + data.location.longitude + "&formatted=0&date=" + date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate()
const sunData = await new Request(req).loadJSON()
return sunData
}
// Set up the sunrise/sunset cache.
const sunCachePath = files.joinPath(files.libraryDirectory(), "weather-cal-sunrise")
const sunCacheExists = files.fileExists(sunCachePath)
const sunCacheDate = sunCacheExists ? files.modificationDate(sunCachePath) : 0
let sunDataRaw
// If cache exists and was created today, use cached data.
if (sunCacheExists && sameDay(currentDate, sunCacheDate)) {
const sunCache = files.readString(sunCachePath)
sunDataRaw = JSON.parse(sunCache)
}
// Otherwise, get the data from the server.
else {
sunDataRaw = await getSunData(currentDate)
// Calculate tomorrow's date and get tomorrow's data.
let tomorrowDate = new Date()
tomorrowDate.setDate(currentDate.getDate() + 1)
const tomorrowData = await getSunData(tomorrowDate)
sunDataRaw.results.tomorrow = tomorrowData.results.sunrise