-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathNews Widget.js
More file actions
2554 lines (2279 loc) · 111 KB
/
News Widget.js
File metadata and controls
2554 lines (2279 loc) · 111 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: blue; icon-glyph: file-alt;
/********************************************
* *
* NEWS WIDGET (WORDPRESS AND RSS) *
* *
* v1.2.2 - made by @saudumm *
* https://twitter.com/saudumm *
* *
********************************************
Feel free to contact me on Twitter or
GitHub, if you have any questions or issues.
GitHub Repo:
https://github.com/Saudumm/scriptable-News-Widget
********************************************
* *
* INSTRUCTIONS / MANUAL / CHANGELOG *
* For instructions on how to set up the *
* widget and the latest changes to *
* the script please check the *
* GitHub Repo *
* *
* DOWNLOAD UPDATES *
* To update News Widget or download *
* the latest version of the script *
* check out "News Widget Update.js" *
* in my GitHub Repo *
* Just add "News Widget Update.js" to *
* Scriptable and run it to download the *
* latest version of News Widget! *
* *
********************************************
WIDGET PARAMETERS: you can long press on the
widget on your homescreen and edit
parameters
Please run Settings Wizard, configure
everything to your liking and then set the
name of the Settings File as a
Widget Parameter.
*/
/* ============ CONFIG START ============ */
/*******************************************/
/* */
/* CONFIG FILE */
/* */
/* You can store your preferred settings */
/* in a config file in the Scriptables */
/* directory in your Files App. This */
/* config file can then be loaded and */
/* used to overwrite the various */
/* settings below, so you don't have to */
/* constantly change them when the widget */
/* code is updated. You can even use */
/* different config files as widget */
/* parameter to create different */
/* widget styles! */
/* */
/* Check the GitHub Repo for more info */
/* and an example file */
/* */
/*******************************************/
// set to "none" if you don't want to use a
// settings file or if you want to use a
// settings file via widget parameter
var SETTINGS_FILE = "none";
/*******************************************/
/* */
/* CHECK FOR SCRIPT UDPATE */
/* */
/*******************************************/
// Check for script updates and get notified
// as soon as a new version is released
// true = check for script updates
// false = don't check for updates
var CHECK_FOR_SCRIPT_UPDATE = true;
/*******************************************/
/* */
/* STANDARD WIDGET CONFIG */
/* */
/* Everything in this section can be */
/* overwritten with Widget Parameters */
/* */
/*******************************************/
// Add Addresses (URLs/Links) of the
// website(s) and/or the RSS Feed(s) you want
// to fetch posts from.
// Format of a new line has to be:
//
// ["Link to site/feed", "Name of site"],
//
// Please note, the more sites you add, the
// longer the widgets needs to load all data.
// It's possible that the widget on your
// homescreen won't load anything or takes a
// very long time if you add too many links.
var PARAM_LINKS =
[
["https://venturebeat.com", "VENTUREBEAT"],
["http://rss.cnn.com/rss/edition.rss", "CNN"],
["https://news.google.com/rss", "GOOGLE NEWS"],
["https://stadt-bremerhaven.de", "CASCHYS BLOG"],
["https://insidexbox.de", "INSIDEXBOX"],
];
// Name of the website/feed to display in the
// widget (at the top).
// If only one site is configured (in the
// code or parameters), the name of the site
// is used.
var PARAM_WIDGET_TITLE = "News Widget";
// Note: custom background image files have
// to be in the Scriptable (iCloud) Files
// folder (same as the script .js file).
// Change to the filename of a custom
// background image (CASE SENSITIVE!) or set
// to "none" if you don't want a custom image
var PARAM_BG_IMAGE_NAME = "none";
// Blur the background image (custom or the
// news image in small widgets).
// "true" = blur the background image
// "false" = no blur
var PARAM_BG_IMAGE_BLUR = "true";
// "true" = gradient over the bg image
// "false" = no gradient
var PARAM_BG_IMAGE_GRADIENT = "true";
// Note: combining
// PARAM_SHOW_NEWS_IMAGES = true + small
// widget will ignore CONF_BG_GRADIENT_COLOR
// values in small config widgets.
// "true" = display images next to headlines
// "false" = no images next to posts
var PARAM_SHOW_NEWS_IMAGES = "true";
/*******************************************/
/* */
/* CONFIGURE LOOK AND FEEL */
/* */
/* NOTE ON DYNAMIC COLORS: */
/* the first value is used in iOS light */
/* mode, second value will be used in */
/* dark mode */
/* */
/* Values are hexadecimal color values */
/* Visit sites like */
/* https://htmlcolorcodes.com */
/* to find hex values for colors */
/* */
/*******************************************/
// Configure if you want a maximum of four or
// five News displayed in the LARGE Widget.
// Please only set 4 or 5. Other values will
// default to 4. If you have exactly
// four websites configured in PARAM_LINKS,
// this Setting will always default to 4.
var CONF_LARGE_WIDGET_MAX_NEWS = 4;
// Configure how posts should be displayed
// in the widget.
// Set to "websites" if you want to
// prioritize seeing news from all your
// configured websites. This will more
// closely resemble the iOS News Widget.
// Set to "date" if you want to
// prioritize just sorting by date. This will
// more closely resemble a timeline or feed
// of all configured websites combined.
var CONF_DISPLAY_NEWS = "websites";
// Configure your preferred region to format
// how date and time values will be displayed
// "default" = uses your system region
// Use locales shortcodes like "en-US",
// "en-GB", "ko", "fr-CA" or "de-DE"
// For a list of possible iOS locales, see:
// https://gist.github.com/jacobbubu/1836273
var CONF_DATE_TIME_LOCALE = "default";
// Configure which time format to use
// true = 12h time format
// false = 24h time format
var CONF_12_HOUR = false;
// Set the background color of your widget
var CONF_BG_COLOR =
Color.dynamic(
new Color("#fefefe"),
new Color("#2c2c2e")
);
// Configure to use a color gradient instead
// of the single background color (above)
// true = use a color gradient
// - (colors configured below)
// false = use a single color
// - (color configured above)
var CONF_BG_GRADIENT = false;
// gradient color from the top of the widget
var CONF_BG_GRADIENT_COLOR_TOP =
Color.dynamic(
new Color("#fefefe"),
new Color("#000000")
);
// gradient color to the bottom of the widget
var CONF_BG_GRADIENT_COLOR_BTM =
Color.dynamic(
new Color("#cccccc"),
new Color("#2c2c2e")
);
// gradient color image overlay from the top
// of the widget
// used if a background image is displayed
// and PARAM_BG_IMAGE_GRADIENT = "true"
var CONF_BG_GRADIENT_OVERLAY_TOP =
Color.dynamic(
new Color("#fefefe", 0.3),
new Color("#2c2c2e", 0.3)
);
// gradient color image overlay to the bottom
// of the widget
// used if a background image is displayed
// and PARAM_BG_IMAGE_GRADIENT = "true"
var CONF_BG_GRADIENT_OVERLAY_BTM =
Color.dynamic(
new Color("#fefefe", 1.0),
new Color("#2c2c2e", 1.0)
);
/*******************************************/
/* */
/* TEXT FONTS AND SIZES */
/* */
/* NOTE ON FONTS: */
/* Use "System" if you want to use the */
/* system font (SF Pro), "Rounded" */
/* for a rounded system font, */
/* "Monospaced" for a monosopaced system */
/* font and choose your font weight. */
/* */
/* Font weight options are: */
/* ultralight, thin, light, regular, */
/* medium, semibold, bold, heavy, black */
/* */
/* */
/* Refer to http://iosfonts.com if you */
/* want to use other fonts and replace */
/* System withyour chosen font name */
/* (e.g. Copperplate or Copperplate-Bold) */
/* */
/*******************************************/
// Set the font, size and text color of the
// widget title at the top of the widget
var CONF_FONT_WIDGET_TITLE = "System";
var CONF_FONT_WEIGHT_WIDGET_TITLE = "heavy";
var CONF_FONT_SIZE_WIDGET_TITLE = 16;
var CONF_FONT_COLOR_WIDGET_TITLE =
Color.dynamic(
new Color("#000000"),
new Color("#fefefe")
);
// Set the font, size and text color of the
// date and time line(s) in the widget
var CONF_FONT_DATE = "System";
var CONF_FONT_WEIGHT_DATE = "heavy";
var CONF_FONT_SIZE_DATE = 12;
var CONF_FONT_COLOR_DATE =
Color.dynamic(
new Color("#8a8a8d"),
new Color("#9f9fa4")
);
// Set the font, size and text color of the
// news headlines in the widget
var CONF_FONT_HEADLINE = "System";
var CONF_FONT_WEIGHT_HEADLINE = "semibold";
var CONF_FONT_SIZE_HEADLINE = 13;
var CONF_FONT_COLOR_HEADLINE =
Color.dynamic(
new Color("#000000"),
new Color("#fefefe")
);
/* ============= CONFIG END ============= */
/*******************************************/
/* */
/* DO NOT CHANGE ANYTHING BELOW! */
/* (or do so at your own risk) */
/* */
/*******************************************/
const ONLINE = await isOnline();
// check for updates
var UPDATE_AVAILABLE = false;
if (ONLINE && CHECK_FOR_SCRIPT_UPDATE === true) {UPDATE_AVAILABLE = await checkForUpdate("v1.2.2");}
// define default size of widget
var WIDGET_SIZE = (config.runsInWidget ? config.widgetFamily : "large");
// process widget parameters
await checkWidgetParameter();
// load settings if a file is configured
if (SETTINGS_FILE != "none") {await loadSettingsFromFile(SETTINGS_FILE);}
// set the number of posts depending on WIDGET_SIZE
var WIDGET_NEWS_COUNT = (WIDGET_SIZE == "small") ? 1 : (WIDGET_SIZE == "medium") ? 2 : 5;
if (CONF_LARGE_WIDGET_MAX_NEWS < 4 || CONF_LARGE_WIDGET_MAX_NEWS > 5) {CONF_LARGE_WIDGET_MAX_NEWS = 4;}
// check directories
await checkFileDirs();
await cleanUpCache();
if (config.runsInApp) {
let welcomeAlert = await new Alert();
welcomeAlert.title = "News Widget";
welcomeAlert.message = "Welcome and THANK YOU for using News Widget!\nDo you want to run the Settings Wizard or Preview the Widget?";
welcomeAlert.addAction("Run Settings Wizard");
welcomeAlert.addAction("Preview Widget");
welcomeAlert.addCancelAction("Cancel");
switch (await welcomeAlert.presentSheet()) {
case 0: await settingsWizard(); return;
case 1: break;
case -1: return;
}
}
// create widget
const widget = await createWidget();
// show widget if run in app
if (!config.runsInWidget) {
switch (WIDGET_SIZE) {
case "small": await widget.presentSmall(); break;
case "medium": await widget.presentMedium(); break;
case "large": await widget.presentLarge(); break;
}
}
// set widget and end script
Script.setWidget(widget);
Script.complete();
/* ============== FUNCTIONS ============== */
// create the widget
async function createWidget() {
const fontWidgetTitle = await loadFont(CONF_FONT_WIDGET_TITLE, CONF_FONT_WEIGHT_WIDGET_TITLE, CONF_FONT_SIZE_WIDGET_TITLE);
const fontDate = await loadFont(CONF_FONT_DATE, CONF_FONT_WEIGHT_DATE, CONF_FONT_SIZE_DATE);
const fontHeadline = await loadFont(CONF_FONT_HEADLINE, CONF_FONT_WEIGHT_HEADLINE, CONF_FONT_SIZE_HEADLINE);
const singleSiteMode = (PARAM_LINKS.length == 1 ? true : false);
const list = new ListWidget();
const widgetNewsData = await getData();
// Display the title of the widget
const titleStack = list.addStack();
titleStack.layoutHorizontally();
const widgetTitle = titleStack.addText(PARAM_WIDGET_TITLE);
widgetTitle.font = fontWidgetTitle;
widgetTitle.textColor = CONF_FONT_COLOR_WIDGET_TITLE;
widgetTitle.lineLimit = 1;
widgetTitle.minimumScaleFactor = 0.5;
if (!ONLINE) {
titleStack.addSpacer();
const sym = SFSymbol.named("icloud.slash");
sym.applyFont(fontWidgetTitle);
const symbolOffline = titleStack.addImage(sym.image);
symbolOffline.rightAlignImage();
symbolOffline.tintColor = CONF_FONT_COLOR_WIDGET_TITLE;
symbolOffline.imageSize = new Size(19, 19)
}
if (widgetNewsData) {
if (WIDGET_SIZE == "large" && CONF_LARGE_WIDGET_MAX_NEWS == 4) {WIDGET_NEWS_COUNT = 4;}
if (WIDGET_NEWS_COUNT >= widgetNewsData.aNewsHeadlines.length) {WIDGET_NEWS_COUNT = widgetNewsData.aNewsHeadlines.length;}
if (WIDGET_SIZE == "medium" && WIDGET_NEWS_COUNT == 2) {list.addSpacer(3);} else if (WIDGET_SIZE == "large" && WIDGET_NEWS_COUNT == 5) {list.addSpacer(10);} else {list.addSpacer();}
if (WIDGET_NEWS_COUNT == 1 || widgetNewsData.aNewsHeadlines.length == 1) {
// use default padding
list.useDefaultPadding();
// load widget background image (if PARAM_SHOW_NEWS_IMAGES = true or PARAM_BG_IMAGE_NAME is set)
if (PARAM_SHOW_NEWS_IMAGES == "true" && PARAM_BG_IMAGE_NAME == "none") {
if (widgetNewsData.aNewsIMGPaths[0] != "none") {
list.backgroundImage = await loadLocalImage(widgetNewsData.aNewsIMGPaths[0]+(PARAM_BG_IMAGE_BLUR == "true" ? "-bg-blur" : "-bg"));
// draw gradient over background image for better legibility
CONF_BG_GRADIENT = true;
CONF_BG_GRADIENT_COLOR_TOP = CONF_BG_GRADIENT_OVERLAY_TOP;
CONF_BG_GRADIENT_COLOR_BTM = CONF_BG_GRADIENT_OVERLAY_BTM;
}
}
const postStack = list.addStack();
postStack.layoutVertically();
if (config.widgetFamily === "medium" || config.widgetFamily === "large") {
const labelDateTime = postStack.addText((singleSiteMode ? "" : widgetNewsData.aNewsSiteNames[0]+" - ")+widgetNewsData.aNewsDateTimes[0]);
labelDateTime.font = fontDate;
labelDateTime.textColor = CONF_FONT_COLOR_DATE;
labelDateTime.lineLimit = 1;
labelDateTime.minimumScaleFactor = 0.5;
} else {
if (!singleSiteMode) {
const labelWidgetTitle = postStack.addText(widgetNewsData.aNewsSiteNames[0]);
labelWidgetTitle.font = fontDate;
labelWidgetTitle.textColor = CONF_FONT_COLOR_DATE;;
labelWidgetTitle.lineLimit = 1;
labelWidgetTitle.minimumScaleFactor = 0.5;
}
const labelDateTime = postStack.addText(widgetNewsData.aNewsDateTimes[0]);
labelDateTime.font = fontDate;
labelDateTime.textColor = CONF_FONT_COLOR_DATE;
labelDateTime.lineLimit = 1;
labelDateTime.minimumScaleFactor = 0.5;
}
const labelHeadline = postStack.addText(widgetNewsData.aNewsHeadlines[0]);
labelHeadline.font = fontHeadline;
labelHeadline.textColor = CONF_FONT_COLOR_HEADLINE;
labelHeadline.lineLimit = 3;
list.url = widgetNewsData.aNewsURLs[0];
} else {
list.setPadding(16, 16, 16, 16);
const aStackRow = await new Array(WIDGET_NEWS_COUNT);
const aStackCol = await new Array(WIDGET_NEWS_COUNT);
const aLblNewsDateTime = await new Array(WIDGET_NEWS_COUNT);
const aLblNewsHeadline = await new Array(WIDGET_NEWS_COUNT);
const aLblNewsImage = await new Array(WIDGET_NEWS_COUNT);
let i;
for (i = 0; i < WIDGET_NEWS_COUNT; i++) {
aStackRow[i] = list.addStack();
aStackRow[i].layoutHorizontally();
aStackRow[i].url = widgetNewsData.aNewsURLs[i];
aStackCol[i] = aStackRow[i].addStack();
aStackCol[i].layoutVertically();
aLblNewsDateTime[i] = aStackCol[i].addText((singleSiteMode ? "" : widgetNewsData.aNewsSiteNames[i]+" - ")+widgetNewsData.aNewsDateTimes[i]);
aLblNewsDateTime[i].font = fontDate;
aLblNewsDateTime[i].textColor = CONF_FONT_COLOR_DATE;
aLblNewsDateTime[i].lineLimit = 1;
aLblNewsDateTime[i].minimumScaleFactor = 0.5;
aLblNewsHeadline[i] = aStackCol[i].addText(widgetNewsData.aNewsHeadlines[i]);
aLblNewsHeadline[i].font = fontHeadline;
aLblNewsHeadline[i].textColor = CONF_FONT_COLOR_HEADLINE;
aLblNewsHeadline[i].lineLimit = 2;
if (PARAM_SHOW_NEWS_IMAGES == "true") {
aStackRow[i].addSpacer();
aLblNewsImage[i] = aStackRow[i].addImage(await loadLocalImage(widgetNewsData.aNewsIMGPaths[i]));
if (WIDGET_SIZE == "large" && WIDGET_NEWS_COUNT == 4) {
aLblNewsImage[i].imageSize = new Size(63,63);
aLblNewsHeadline[i].lineLimit = 3;
} else {
aLblNewsImage[i].imageSize = new Size(45.66,45.66);
}
aLblNewsImage[i].cornerRadius = 8;
if (widgetNewsData.aNewsIMGPaths[i] === "none") {aLblNewsImage[i].tintColor = CONF_FONT_COLOR_HEADLINE; aLblNewsImage[i].imageOpacity = 0.5;}
aLblNewsImage[i].rightAlignImage();
}
if (i < WIDGET_NEWS_COUNT-1) {list.addSpacer();}
}
}
} else {
widgetTitle.textColor = Color.white();
list.addSpacer();
const sadFace = list.addText(":(");
sadFace.font = Font.regularSystemFont((WIDGET_SIZE === "large") ? 190 : 60);
sadFace.textColor = Color.white();
sadFace.lineLimit = 1;
sadFace.minimumScaleFactor = 0.1;
list.addSpacer();
const errMsg = list.addText("Couldn't load data");
errMsg.font = Font.regularSystemFont(12);
errMsg.textColor = Color.white();
CONF_BG_COLOR = new Color("#1f67b1");
CONF_BG_GRADIENT = false;
PARAM_BG_IMAGE_NAME = "none";
}
if (UPDATE_AVAILABLE) {
list.addSpacer(4);
list.setPadding(16, 16, 0, 16);
const updateMsg = list.addText("Script Update available on GitHub");
updateMsg.font = Font.lightSystemFont(9);
updateMsg.textColor = Color.white();
updateMsg.lineLimit = 1;
updateMsg.minimumScaleFactor = 0.2;
updateMsg.centerAlignText()
updateMsg.url = "https://github.com/Saudumm/scriptable-News-Widget"
}
// widget background (image, single color or gradient)
if (PARAM_BG_IMAGE_NAME != "none") {
const customBGImage = await loadBGImage(PARAM_BG_IMAGE_NAME, PARAM_BG_IMAGE_BLUR);
if (customBGImage != "not found") {
list.backgroundImage = customBGImage;
if (PARAM_BG_IMAGE_GRADIENT == "true") {
// draw gradient over background image for better legibility
const gradient = new LinearGradient();
gradient.locations = [0, 1];
gradient.colors = [CONF_BG_GRADIENT_OVERLAY_TOP, CONF_BG_GRADIENT_OVERLAY_BTM];
list.backgroundGradient = gradient;
}
} else {
list.backgroundColor = CONF_BG_COLOR;
}
} else if (CONF_BG_GRADIENT == true) {
const gradient = new LinearGradient();
gradient.locations = [0, 1];
gradient.colors = [CONF_BG_GRADIENT_COLOR_TOP, CONF_BG_GRADIENT_COLOR_BTM];
list.backgroundGradient = gradient;
} else {
list.backgroundColor = CONF_BG_COLOR;
}
return list;
}
// get data from all websites and extract necessary data
async function getData() {
try {
const localFM = FileManager.local();
const aData = await new Array();
for (iLink = 0; iLink < PARAM_LINKS.length; iLink++) {
// add https:// to the link if it's missing
if (PARAM_LINKS[iLink][0].substring(0, 7) != "http://" && PARAM_LINKS[iLink][0].substring(0, 8) != "https://") {
PARAM_LINKS[iLink][0] = "https://"+PARAM_LINKS[iLink][0]
}
// remove last / from link
if (PARAM_LINKS[iLink][0].slice(-1) == "/") {PARAM_LINKS[iLink][0] = PARAM_LINKS[iLink][0].slice(0, -1);}
const whatToLoad = await _whatShouldILoad(PARAM_LINKS[iLink][0], PARAM_LINKS[iLink][1])
if (whatToLoad.loadFormat == "WP-JSON") {
// WordPress JSON
try {
let loadedJSON
if (ONLINE) {
loadedJSON = await new Request(PARAM_LINKS[iLink][0]+"/wp-json/wp/v2/posts?per_page=5").loadJSON();
// Save data to file
await localFM.writeString(whatToLoad.loadFilePath, JSON.stringify(loadedJSON));
} else {
loadedJSON = await JSON.parse(localFM.readString(whatToLoad.loadFilePath));
}
// Define how many news should be processed
let calcLoadPosts = 5;
let maxPostsForWidgetSize = (WIDGET_SIZE == "small") ? 1 : (WIDGET_SIZE == "medium") ? 2 : 5
if (WIDGET_SIZE == "large" && CONF_LARGE_WIDGET_MAX_NEWS == 4) {maxPostsForWidgetSize = 4;}
if (CONF_DISPLAY_NEWS == "websites") {
calcLoadPosts = await Math.round(maxPostsForWidgetSize / PARAM_LINKS.length / 1);
calcLoadPosts = (calcLoadPosts <= 1) ? 1 : calcLoadPosts;
} else if (CONF_DISPLAY_NEWS == "date") {
calcLoadPosts = maxPostsForWidgetSize
}
const loadPosts = (loadedJSON.length >= calcLoadPosts) ? calcLoadPosts : loadedJSON.length
let iPost;
for (iPost = 0; iPost < loadPosts; iPost++) {
let postDate = loadedJSON[iPost].date_gmt;
if (postDate === undefined) {postDate = loadedJSON[iPost].date;} else {(postDate.slice(-1) == "Z") ? postDate : postDate += "Z";}
const postDateSort = await new Date(postDate).toLocaleString(["fr-CA"], {year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit"});
const postTitle = await _formatPostTitle(loadedJSON[iPost].title.rendered);
const postURL = loadedJSON[iPost].guid.rendered;
const postIMGURL = await _getMediaURL(PARAM_LINKS[iLink][0], loadedJSON[iPost].featured_media, loadedJSON[iPost].id, PARAM_LINKS[iLink][1]);
await aData.push([postDateSort, postDate+"|||"+postTitle+"|||"+postURL+"|||"+postIMGURL+"|||"+PARAM_LINKS[iLink][1]]);
}
} catch(err) {
log("try processing WP-JSON: "+err);
}
} else if (whatToLoad.loadFormat == "RSS") {
// RSS Feeds
try {
let loadRSSFeed = null;
if (ONLINE) {
loadRSSFeed = await new Request(PARAM_LINKS[iLink][0]).loadString();
// Save data to file
await localFM.writeString(whatToLoad.loadFilePath, loadRSSFeed);
} else {
loadRSSFeed = await localFM.readString(whatToLoad.loadFilePath);
}
const aRSSItems = await new Array();
let itemValue = null;
let currentItem = null;
let searchForImage = true;
let xmlParser = new XMLParser(loadRSSFeed);
// start of element
xmlParser.didStartElement = (name, elementContent) => {
itemValue = "";
if (name == "entry" || name == "item") {
currentItem = {};
searchForImage = true;
}
// possible image values in element name
if ((name.substring(0, 6) == "media:" || name == "enclosure") && searchForImage) {
if (elementContent.url !== null && elementContent.url !== undefined && currentItem !== null && currentItem !== undefined) {
let imgLink = elementContent.url.match(/"?(http(?!.*http)s?\:\/\/.*?\.)(jpe?g|png|bmp|webp)"?/i);
if (imgLink && imgLink.length == 3) {
imgLink = imgLink[1]+imgLink[2];
currentItem["image"] = imgLink;
searchForImage = false;
}
}
}
}
// end of element
xmlParser.didEndElement = name => {
const hasItem = currentItem != null;
// possible url location
if (hasItem && name == "id") {currentItem["id"] = itemValue;}
// possible url location
if (hasItem && name == "link") {currentItem["link"] = itemValue;}
// title value
if (hasItem && name == "title") {currentItem["title"] = itemValue;}
// published date
if (hasItem && (name == "published" || name == "pubDate" || name == "updated")) {currentItem["published"] = itemValue;}
// possible image link location
if (hasItem && name == "image" && searchForImage) {
let imgLink = itemValue.match(/"?(http(?!.*http)s?\:\/\/.*?\.)(jpe?g|png|bmp|webp)"?/i);
if (imgLink && imgLink.length == 3) {
imgLink = imgLink[1]+imgLink[2];
currentItem["image"] = imgLink;
searchForImage = false;
}
}
// possible image link location
if (hasItem && name == "thumb" && searchForImage) {
let imgLink = itemValue.match(/"?(http(?!.*http)s?\:\/\/.*?\.)(jpe?g|png|bmp|webp)"?/i);
if (imgLink && imgLink.length == 3) {
imgLink = imgLink[1]+imgLink[2];
currentItem["image"] = imgLink;
searchForImage = false;
}
}
// possible image link location
if (hasItem && name.includes("content")) {
let imgLink = itemValue.match(/src="(https?\:\/\/.*?\.)(jpe?g|png|bmp|webp).*?"/i);
if (imgLink && imgLink.length == 3) {
imgLink = imgLink[1]+imgLink[2];
currentItem["image"] = imgLink;
searchForImage = false;
} else {
imgLink = itemValue.match(/src="(.*?\.)(jpe?g|png|bmp|webp).*?"/i);
if (imgLink && imgLink.length == 3) {
let urlFromParam = PARAM_LINKS[iLink][0].match(/(https?\:\/\/.*?)\//i);
if (urlFromParam && urlFromParam.length == 2) {
imgLink = urlFromParam[1]+imgLink[1]+imgLink[2];
imgLink = imgLink.match(/(https?\:\/\/.*?\.)(jpe?g|png|bmp|webp).*?/i);
if (imgLink && imgLink.length == 3) {
imgLink = imgLink[1]+imgLink[2];
currentItem["image"] = imgLink;
searchForImage = false;
}
}
}
}
}
// possible image link location
if (hasItem && name == "description") {
let imgLink = itemValue.match(/src="(https?\:\/\/.*?\.)(jpe?g|png|bmp|webp).*?"/i);
if (imgLink && imgLink.length == 3) {
imgLink = imgLink[1]+imgLink[2];
currentItem["image"] = imgLink;
searchForImage = false;
} else {
imgLink = itemValue.match(/src="(.*?\.)(jpe?g|png|bmp|webp).*?"/i);
if (imgLink && imgLink.length == 3) {
let urlFromParam = PARAM_LINKS[iLink][0].match(/(https?\:\/\/.*?)\//i);
if (urlFromParam && urlFromParam.length == 2) {
imgLink = urlFromParam[1]+imgLink[1]+imgLink[2];
imgLink = imgLink.match(/(https?\:\/\/.*?\.)(jpe?g|png|bmp|webp).*?/i);
if (imgLink && imgLink.length == 3) {
imgLink = imgLink[1]+imgLink[2];
currentItem["image"] = imgLink;
searchForImage = false;
}
}
}
}
}
// end of item/entry block
if (name == "entry" || name == "item") {
aRSSItems.push(currentItem);
currentItem = null;
}
}
// found characters between element start and end
xmlParser.foundCharacters = str => {itemValue += str;}
// end of document
xmlParser.didEndDocument = () => {}
// parse xml string
await xmlParser.parse();
//const loadPosts = (aRSSItems.length >= 5) ? 5 : aRSSItems.length
const aRSSData = await new Array();
for (iRSS = 0; iRSS < aRSSItems.length; iRSS++) {
let rssDate = "none";
let rssDateSort = "none";
let rssTitle = "none";
let rssURL = "none";
let rssIMGURL = "none";
if (aRSSItems[iRSS].published !== null) {
rssDate = aRSSItems[iRSS].published;
rssDateSort = await new Date(rssDate).toLocaleString(["fr-CA"], {year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit"});
}
if (aRSSItems[iRSS].title) {rssTitle = aRSSItems[iRSS].title;}
if (aRSSItems[iRSS].id) {
rssURL = aRSSItems[iRSS].id;
} else if (aRSSItems[iRSS].link) {
rssURL = aRSSItems[iRSS].link;
}
if (aRSSItems[iRSS].image) {
// double check if link is image link
const rssIMGRegEx = await aRSSItems[iRSS].image.match(/"?(http(?!.*http)s?\:\/\/.*?\.)(jpe?g|png|bmp|webp)"?/i);
if (rssIMGRegEx && rssIMGRegEx.length == 3) {
rssIMGURL = rssIMGRegEx[1]+rssIMGRegEx[2];
}
}
if (rssDateSort !== "Invalid Date") {
await aRSSData.push([rssDateSort, rssDate+"|||"+rssTitle+"|||"+rssURL+"|||"+rssIMGURL+"|||"+PARAM_LINKS[iLink][1]]);
}
}
if (aRSSData && aRSSData.length >= 1) {
// sort all post according to date
aRSSData.sort(function sortFunction(a, b) {
if (a[0] === b[0]) {
return 0;
} else {
return (a[0] < b[0]) ? -1 : 1;
}
})
// reverse sorting - new to old date
aRSSData.reverse()
// Define how many news should be processed
let calcLoadPosts = 5;
let maxPostsForWidgetSize = (WIDGET_SIZE == "small") ? 1 : (WIDGET_SIZE == "medium") ? 2 : 5
if (WIDGET_SIZE == "large" && CONF_LARGE_WIDGET_MAX_NEWS == 4) {maxPostsForWidgetSize = 4;}
if (CONF_DISPLAY_NEWS == "websites") {
calcLoadPosts = await Math.round(maxPostsForWidgetSize / PARAM_LINKS.length / 1);
calcLoadPosts = (calcLoadPosts <= 1) ? 1 : calcLoadPosts;
} else if (CONF_DISPLAY_NEWS == "date") {
calcLoadPosts = maxPostsForWidgetSize
}
const loadPosts = (aRSSData.length >= calcLoadPosts) ? calcLoadPosts : aRSSData.length
let iRSSNews;
for (iRSSNews = 0; iRSSNews < loadPosts; iRSSNews++) {
await aData.push([aRSSData[iRSSNews][0], aRSSData[iRSSNews][1]]);
}
}
} catch(err) {
log("try processing RSS feed: "+err);
}
}
}
if (aData.length >= 1) {
// sort all post according to date
aData.sort(function sortFunction(a, b) {
if (a[0] === b[0]) {
return 0;
} else {
return (a[0] < b[0]) ? -1 : 1;
}
})
// reverse sorting - new to old date
aData.reverse()
const POSTS_TO_LOAD = (aData.length >= 5) ? 5 : aData.length;
const aDateTimes = await new Array(POSTS_TO_LOAD);
const aHeadlines = await new Array(POSTS_TO_LOAD);
const aURLs = await new Array(POSTS_TO_LOAD);
const aIMGURLs = await new Array(POSTS_TO_LOAD);
const aIMGPaths = await new Array(POSTS_TO_LOAD);
const aSiteNames = await new Array(POSTS_TO_LOAD);
const aFileNames = await new Array(POSTS_TO_LOAD);
for (iNewPost = 0; iNewPost < POSTS_TO_LOAD; iNewPost++) {
const aStrSplit = aData[iNewPost][1].split("|||")
if (aStrSplit[0] != "none" && aStrSplit[0] != "undefined" && aStrSplit[0] != undefined) {
aDateTimes[iNewPost] = await new Date(aStrSplit[0]);
} else {
aDateTimes[iNewPost] = await Date.now();
}
aDateTimes[iNewPost] = await _formatDateTimeString(aDateTimes[iNewPost]);
aHeadlines[iNewPost] = aStrSplit[1];
aHeadlines[iNewPost] = await _formatPostTitle(aHeadlines[iNewPost]);
aURLs[iNewPost] = aStrSplit[2];
aSiteNames[iNewPost] = aStrSplit[4];
if (PARAM_SHOW_NEWS_IMAGES == "true") {
aIMGURLs[iNewPost] = aStrSplit[3];
if (aIMGURLs[iNewPost] != "none") {
const fileID = await _hashCode(aIMGURLs[iNewPost])
aFileNames[iNewPost] = await getFileName(aSiteNames[iNewPost], fileID);
const addBGImage = (iNewPost == 0 ? true : false);
aIMGURLs[iNewPost] = await encodeURI(aIMGURLs[iNewPost]);
aIMGURLs[iNewPost] = await aIMGURLs[iNewPost].replaceAll("%25", "%"); // hack for some image URLs with %
aIMGPaths[iNewPost] = await _downloadPostImage(aFileNames[iNewPost], aIMGURLs[iNewPost], addBGImage);
} else {
aIMGPaths[iNewPost] = "none";
}
}
}
return {
aNewsDateTimes: aDateTimes,
aNewsHeadlines: aHeadlines,
aNewsURLs: aURLs,
aNewsIMGPaths: aIMGPaths,
aNewsSiteNames: aSiteNames
};
} else {
return null;
}
} catch(err) {
logError("try getData: "+err);
return null;
}
// define what sould be loaded depending on link and online status
async function _whatShouldILoad(link, strSiteName) {
let loadFormat = "none";
let loadFilePath = "none";
const localFM = FileManager.local();
const docDir = localFM.documentsDirectory();
const backupFilename = await getFileName(strSiteName, "0");
const pathBackupJSON = localFM.joinPath(docDir+"/saudumm-news-widget-data", backupFilename+".json");
const pathBackupXML = localFM.joinPath(docDir+"/saudumm-news-widget-data", backupFilename+".xml");
if (ONLINE) {
if (await isJSON(link+"/wp-json/wp/v2/posts?per_page=1")) {
loadFormat = "WP-JSON";
loadFilePath = pathBackupJSON;
} else {
loadFormat = "RSS";
loadFilePath = pathBackupXML;
}
} else {
if (localFM.fileExists(pathBackupJSON)) {
loadFormat = "WP-JSON";
loadFilePath = pathBackupJSON;
} else if (localFM.fileExists(pathBackupXML)) {
loadFormat = "RSS";
loadFilePath = pathBackupXML;
}
}
return {
loadFormat: loadFormat,
loadFilePath: loadFilePath
};
// check if the url leads to a json file
async function isJSON(strURL) {
try {
const testJSON = await new Request(strURL).loadJSON();
if (testJSON.reason == "Not Found") {return false;}
} catch(err) {
return false;
}
return true;
}
}
// format the date and time string to a locale date/time
function _formatDateTimeString(strDateTime) {
return new Date(strDateTime).toLocaleString((CONF_DATE_TIME_LOCALE == "default" ? [] : [CONF_DATE_TIME_LOCALE]), {year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hour12: (CONF_12_HOUR ? true : false)})
}
// format the post title and replace all html entities with characters
function _formatPostTitle(strHeadline) {
strHeadline = strHeadline.trim().replaceAll(""", '"')
.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">")
.replaceAll("'", "'").replaceAll(""", '"').replaceAll("&", "&")
.replaceAll("'", "'").replaceAll("<", "<").replaceAll(">", ">")
.replaceAll("Œ", "Œ").replaceAll("œ", "œ").replaceAll("Š", "Š")
.replaceAll("š", "š").replaceAll("Ÿ", "Ÿ").replaceAll("ˆ", "ˆ")
.replaceAll("˜", "˜").replaceAll("–", "–").replaceAll("—", "—")
.replaceAll("‘", "‘").replaceAll("’", "’").replaceAll("‚", "‚")
.replaceAll("“", "“").replaceAll("”", "”").replaceAll("„", "„")
.replaceAll("†", "†").replaceAll("‡", "‡").replaceAll("…", "…")
.replaceAll("‰", "‰").replaceAll("‹", "‹").replaceAll("›", "›")
.replaceAll("€", "€").replaceAll("<![CDATA[", "").replaceAll("]]>", "");
return strHeadline;
}
// get the featuredMedia image URL
async function _getMediaURL(strURL, strFeatMediaID, strPostID, strSiteName) {
const localFM = FileManager.local();
const docDir = localFM.documentsDirectory();
const backupFilename = await getFileName(strSiteName, strPostID);
const pathBackupMedia = localFM.joinPath(docDir+"/saudumm-news-widget-data", backupFilename+"-media.json");
const pathBackupPosts = localFM.joinPath(docDir+"/saudumm-news-widget-data", backupFilename+"-posts.json");
let featuredMediaJSONURL = strURL+"/wp-json/wp/v2/media/"+strFeatMediaID;
let loadedMediaJSON
if (ONLINE) {
loadedMediaJSON = await new Request(featuredMediaJSONURL).loadJSON();
// Save data to file
await localFM.writeString(pathBackupMedia, JSON.stringify(loadedMediaJSON));
} else {
loadedMediaJSON = await JSON.parse(localFM.readString(pathBackupMedia));
}
let mediaURL = loadedMediaJSON.source_url;
if (mediaURL === undefined || mediaURL == "undefined") {
// search for other images
featuredMediaJSONURL = strURL+"/wp-json/wp/v2/posts/"+strPostID;
if (ONLINE) {
loadedMediaJSON = await new Request(featuredMediaJSONURL).loadJSON();
// Save data to file
await localFM.writeString(pathBackupPosts, JSON.stringify(loadedMediaJSON));
} else {
loadedMediaJSON = await JSON.parse(localFM.readString(pathBackupPosts));
}
mediaURL = loadedMediaJSON.jetpack_featured_media_url;
if (mediaURL === undefined || mediaURL == "undefined") {
return "none";
} else {
mediaURL = mediaURL.match(/(http?s.*\.)(jpe?g|png|bmp|webp)/i)
mediaURL = mediaURL[1]+""+mediaURL[2];
return await encodeURI(mediaURL);
}
} else {
mediaURL = await mediaURL.match(/(http?s.*\.)(jpe?g|png|bmp|webp)/i)
mediaURL = mediaURL[1]+""+mediaURL[2];
return await encodeURI(mediaURL);
}