├── .gitignore
├── LICENSE
├── News Widget Clear Cache.js
├── News Widget Update.js
├── News Widget.js
├── README.md
├── example-links.txt
├── images
├── settings-wizard.jpg
├── update-example.jpg
├── widget-config-old.jpg
├── widget-config.jpg
└── widgets.jpg
├── screenshots
├── screenshot1.jpg
├── screenshot2.jpg
├── screenshot3.jpg
└── screenshot4.jpg
└── version.txt
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | .DS_Store
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/News Widget Clear Cache.js:
--------------------------------------------------------------------------------
1 | // Variables used by Scriptable.
2 | // These must be at the very top of the file. Do not edit.
3 | // icon-color: red; icon-glyph: trash-alt;
4 | /********************************************
5 | * *
6 | * DELETE NEWS WIDGET CACHE *
7 | * *
8 | * v1.1.3 - made by @saudumm *
9 | * https://twitter.com/saudumm *
10 | * *
11 | *******************************************/
12 |
13 | // GitHub Repo:
14 | // https://github.com/Saudumm/scriptable-News-Widget
15 |
16 | let fm = FileManager.local();
17 | let docDir = fm.documentsDirectory();
18 | let alertMsg = "No files to delete";
19 |
20 | if (await fm.fileExists(docDir+"/saudumm-news-widget-data")) {
21 | try {
22 | await fm.remove(docDir+"/saudumm-news-widget-data");
23 | alertMsg = "All cache files deleted!";
24 | } catch(err) {
25 | alertMsg = "Error while deleting cache files\n\n"+err;
26 | }
27 | }
28 |
29 | let alert = new Alert();
30 | alert.message = "\n"+alertMsg;
31 | alert.title = "Clear News Widget Cache";
32 | alert.addAction("OK");
33 | alert.presentAlert();
34 |
--------------------------------------------------------------------------------
/News Widget Update.js:
--------------------------------------------------------------------------------
1 | // Variables used by Scriptable.
2 | // These must be at the very top of the file. Do not edit.
3 | // icon-color: deep-gray; icon-glyph: sync-alt;
4 | /********************************************
5 | * *
6 | * UPDATE OR INSTALL NEWS WIDGET *
7 | * *
8 | * v1.0.1 - made by @saudumm *
9 | * https://twitter.com/saudumm *
10 | * *
11 | *******************************************/
12 |
13 | // GitHub Repo:
14 | // https://github.com/Saudumm/scriptable-News-Widget
15 |
16 | let fm
17 | try {fm = FileManager.iCloud()} catch (err) {fm = FileManager.local()}
18 | try {fm.documentsDirectory()} catch(e) {fm = FileManager.local()}
19 |
20 | const docDir = fm.documentsDirectory()
21 | const path = fm.joinPath(docDir, "News Widget.js")
22 | const pathAlt = fm.joinPath(docDir, "News-Widget.js")
23 | const pathBackup = fm.joinPath(docDir, "News Widget Backup.js")
24 | const pathBackup2 = fm.joinPath(docDir, "News Widget Backup2.js")
25 |
26 | let alertMsg = "No Message"
27 |
28 | try {
29 | const latestVersion = await new Request("https://raw.githubusercontent.com/Saudumm/scriptable-News-Widget/main/News%20Widget.js").loadString();
30 |
31 | if (fm.fileExists(pathBackup2)) {await fm.remove(pathBackup2);}
32 |
33 | if (fm.fileExists(pathBackup)) {await fm.move(pathBackup, pathBackup2);}
34 |
35 | if (fm.fileExists(pathAlt)) {
36 | await fm.move(pathAlt, pathBackup);
37 | } else if (fm.fileExists(path)) {
38 | await fm.move(path, pathBackup);
39 | }
40 |
41 | if (fm.fileExists(path) || await fm.fileExists(pathAlt)) {
42 | await fm.remove(path);
43 | await fm.remove(pathAlt);
44 | }
45 |
46 | await fm.writeString(path, latestVersion);
47 |
48 | if (fm.fileExists(pathBackup2)) {await fm.remove(pathBackup2);}
49 |
50 | alertMsg = "News Widget successfully updated!\n\nOld Script has been saved as\n'News Widget Backup'"
51 | } catch(err) {
52 | alertMsg = "Error while updateing News Widget\n\n"+err+"\n\nPlease Check 'News Widget' \nor\n'News Widget Backup'"
53 | }
54 |
55 | let alert = new Alert();
56 | alert.message = "\n"+alertMsg;
57 | alert.title = "News Widget Update";
58 | alert.addAction("OK");
59 | alert.presentAlert();
60 |
--------------------------------------------------------------------------------
/News Widget.js:
--------------------------------------------------------------------------------
1 | // Variables used by Scriptable.
2 | // These must be at the very top of the file. Do not edit.
3 | // icon-color: blue; icon-glyph: file-alt;
4 | /********************************************
5 | * *
6 | * NEWS WIDGET (WORDPRESS AND RSS) *
7 | * *
8 | * v1.2.2 - made by @saudumm *
9 | * https://twitter.com/saudumm *
10 | * *
11 | ********************************************
12 |
13 | Feel free to contact me on Twitter or
14 | GitHub, if you have any questions or issues.
15 |
16 | GitHub Repo:
17 | https://github.com/Saudumm/scriptable-News-Widget
18 |
19 | ********************************************
20 | * *
21 | * INSTRUCTIONS / MANUAL / CHANGELOG *
22 | * For instructions on how to set up the *
23 | * widget and the latest changes to *
24 | * the script please check the *
25 | * GitHub Repo *
26 | * *
27 | * DOWNLOAD UPDATES *
28 | * To update News Widget or download *
29 | * the latest version of the script *
30 | * check out "News Widget Update.js" *
31 | * in my GitHub Repo *
32 | * Just add "News Widget Update.js" to *
33 | * Scriptable and run it to download the *
34 | * latest version of News Widget! *
35 | * *
36 | ********************************************
37 |
38 | WIDGET PARAMETERS: you can long press on the
39 | widget on your homescreen and edit
40 | parameters
41 |
42 | Please run Settings Wizard, configure
43 | everything to your liking and then set the
44 | name of the Settings File as a
45 | Widget Parameter.
46 | */
47 |
48 | /* ============ CONFIG START ============ */
49 |
50 | /*******************************************/
51 | /* */
52 | /* CONFIG FILE */
53 | /* */
54 | /* You can store your preferred settings */
55 | /* in a config file in the Scriptables */
56 | /* directory in your Files App. This */
57 | /* config file can then be loaded and */
58 | /* used to overwrite the various */
59 | /* settings below, so you don't have to */
60 | /* constantly change them when the widget */
61 | /* code is updated. You can even use */
62 | /* different config files as widget */
63 | /* parameter to create different */
64 | /* widget styles! */
65 | /* */
66 | /* Check the GitHub Repo for more info */
67 | /* and an example file */
68 | /* */
69 | /*******************************************/
70 |
71 | // set to "none" if you don't want to use a
72 | // settings file or if you want to use a
73 | // settings file via widget parameter
74 | var SETTINGS_FILE = "none";
75 |
76 | /*******************************************/
77 | /* */
78 | /* CHECK FOR SCRIPT UDPATE */
79 | /* */
80 | /*******************************************/
81 |
82 | // Check for script updates and get notified
83 | // as soon as a new version is released
84 | // true = check for script updates
85 | // false = don't check for updates
86 | var CHECK_FOR_SCRIPT_UPDATE = true;
87 |
88 | /*******************************************/
89 | /* */
90 | /* STANDARD WIDGET CONFIG */
91 | /* */
92 | /* Everything in this section can be */
93 | /* overwritten with Widget Parameters */
94 | /* */
95 | /*******************************************/
96 |
97 | // Add Addresses (URLs/Links) of the
98 | // website(s) and/or the RSS Feed(s) you want
99 | // to fetch posts from.
100 | // Format of a new line has to be:
101 | //
102 | // ["Link to site/feed", "Name of site"],
103 | //
104 | // Please note, the more sites you add, the
105 | // longer the widgets needs to load all data.
106 | // It's possible that the widget on your
107 | // homescreen won't load anything or takes a
108 | // very long time if you add too many links.
109 | var PARAM_LINKS =
110 | [
111 | ["https://venturebeat.com", "VENTUREBEAT"],
112 | ["http://rss.cnn.com/rss/edition.rss", "CNN"],
113 | ["https://news.google.com/rss", "GOOGLE NEWS"],
114 | ["https://stadt-bremerhaven.de", "CASCHYS BLOG"],
115 | ["https://insidexbox.de", "INSIDEXBOX"],
116 | ];
117 |
118 | // Name of the website/feed to display in the
119 | // widget (at the top).
120 | // If only one site is configured (in the
121 | // code or parameters), the name of the site
122 | // is used.
123 | var PARAM_WIDGET_TITLE = "News Widget";
124 |
125 | // Note: custom background image files have
126 | // to be in the Scriptable (iCloud) Files
127 | // folder (same as the script .js file).
128 | // Change to the filename of a custom
129 | // background image (CASE SENSITIVE!) or set
130 | // to "none" if you don't want a custom image
131 | var PARAM_BG_IMAGE_NAME = "none";
132 |
133 | // Blur the background image (custom or the
134 | // news image in small widgets).
135 | // "true" = blur the background image
136 | // "false" = no blur
137 | var PARAM_BG_IMAGE_BLUR = "true";
138 |
139 | // "true" = gradient over the bg image
140 | // "false" = no gradient
141 | var PARAM_BG_IMAGE_GRADIENT = "true";
142 |
143 | // Note: combining
144 | // PARAM_SHOW_NEWS_IMAGES = true + small
145 | // widget will ignore CONF_BG_GRADIENT_COLOR
146 | // values in small config widgets.
147 | // "true" = display images next to headlines
148 | // "false" = no images next to posts
149 | var PARAM_SHOW_NEWS_IMAGES = "true";
150 |
151 | /*******************************************/
152 | /* */
153 | /* CONFIGURE LOOK AND FEEL */
154 | /* */
155 | /* NOTE ON DYNAMIC COLORS: */
156 | /* the first value is used in iOS light */
157 | /* mode, second value will be used in */
158 | /* dark mode */
159 | /* */
160 | /* Values are hexadecimal color values */
161 | /* Visit sites like */
162 | /* https://htmlcolorcodes.com */
163 | /* to find hex values for colors */
164 | /* */
165 | /*******************************************/
166 |
167 | // Configure if you want a maximum of four or
168 | // five News displayed in the LARGE Widget.
169 | // Please only set 4 or 5. Other values will
170 | // default to 4. If you have exactly
171 | // four websites configured in PARAM_LINKS,
172 | // this Setting will always default to 4.
173 | var CONF_LARGE_WIDGET_MAX_NEWS = 4;
174 |
175 | // Configure how posts should be displayed
176 | // in the widget.
177 | // Set to "websites" if you want to
178 | // prioritize seeing news from all your
179 | // configured websites. This will more
180 | // closely resemble the iOS News Widget.
181 | // Set to "date" if you want to
182 | // prioritize just sorting by date. This will
183 | // more closely resemble a timeline or feed
184 | // of all configured websites combined.
185 | var CONF_DISPLAY_NEWS = "websites";
186 |
187 | // Configure your preferred region to format
188 | // how date and time values will be displayed
189 | // "default" = uses your system region
190 | // Use locales shortcodes like "en-US",
191 | // "en-GB", "ko", "fr-CA" or "de-DE"
192 | // For a list of possible iOS locales, see:
193 | // https://gist.github.com/jacobbubu/1836273
194 | var CONF_DATE_TIME_LOCALE = "default";
195 |
196 | // Configure which time format to use
197 | // true = 12h time format
198 | // false = 24h time format
199 | var CONF_12_HOUR = false;
200 |
201 | // Set the background color of your widget
202 | var CONF_BG_COLOR =
203 | Color.dynamic(
204 | new Color("#fefefe"),
205 | new Color("#2c2c2e")
206 | );
207 |
208 | // Configure to use a color gradient instead
209 | // of the single background color (above)
210 | // true = use a color gradient
211 | // - (colors configured below)
212 | // false = use a single color
213 | // - (color configured above)
214 | var CONF_BG_GRADIENT = false;
215 |
216 | // gradient color from the top of the widget
217 | var CONF_BG_GRADIENT_COLOR_TOP =
218 | Color.dynamic(
219 | new Color("#fefefe"),
220 | new Color("#000000")
221 | );
222 | // gradient color to the bottom of the widget
223 | var CONF_BG_GRADIENT_COLOR_BTM =
224 | Color.dynamic(
225 | new Color("#cccccc"),
226 | new Color("#2c2c2e")
227 | );
228 |
229 | // gradient color image overlay from the top
230 | // of the widget
231 | // used if a background image is displayed
232 | // and PARAM_BG_IMAGE_GRADIENT = "true"
233 | var CONF_BG_GRADIENT_OVERLAY_TOP =
234 | Color.dynamic(
235 | new Color("#fefefe", 0.3),
236 | new Color("#2c2c2e", 0.3)
237 | );
238 | // gradient color image overlay to the bottom
239 | // of the widget
240 | // used if a background image is displayed
241 | // and PARAM_BG_IMAGE_GRADIENT = "true"
242 | var CONF_BG_GRADIENT_OVERLAY_BTM =
243 | Color.dynamic(
244 | new Color("#fefefe", 1.0),
245 | new Color("#2c2c2e", 1.0)
246 | );
247 |
248 | /*******************************************/
249 | /* */
250 | /* TEXT FONTS AND SIZES */
251 | /* */
252 | /* NOTE ON FONTS: */
253 | /* Use "System" if you want to use the */
254 | /* system font (SF Pro), "Rounded" */
255 | /* for a rounded system font, */
256 | /* "Monospaced" for a monosopaced system */
257 | /* font and choose your font weight. */
258 | /* */
259 | /* Font weight options are: */
260 | /* ultralight, thin, light, regular, */
261 | /* medium, semibold, bold, heavy, black */
262 | /* */
263 | /* */
264 | /* Refer to http://iosfonts.com if you */
265 | /* want to use other fonts and replace */
266 | /* System withyour chosen font name */
267 | /* (e.g. Copperplate or Copperplate-Bold) */
268 | /* */
269 | /*******************************************/
270 |
271 | // Set the font, size and text color of the
272 | // widget title at the top of the widget
273 | var CONF_FONT_WIDGET_TITLE = "System";
274 | var CONF_FONT_WEIGHT_WIDGET_TITLE = "heavy";
275 | var CONF_FONT_SIZE_WIDGET_TITLE = 16;
276 | var CONF_FONT_COLOR_WIDGET_TITLE =
277 | Color.dynamic(
278 | new Color("#000000"),
279 | new Color("#fefefe")
280 | );
281 |
282 | // Set the font, size and text color of the
283 | // date and time line(s) in the widget
284 | var CONF_FONT_DATE = "System";
285 | var CONF_FONT_WEIGHT_DATE = "heavy";
286 | var CONF_FONT_SIZE_DATE = 12;
287 | var CONF_FONT_COLOR_DATE =
288 | Color.dynamic(
289 | new Color("#8a8a8d"),
290 | new Color("#9f9fa4")
291 | );
292 |
293 | // Set the font, size and text color of the
294 | // news headlines in the widget
295 | var CONF_FONT_HEADLINE = "System";
296 | var CONF_FONT_WEIGHT_HEADLINE = "semibold";
297 | var CONF_FONT_SIZE_HEADLINE = 13;
298 | var CONF_FONT_COLOR_HEADLINE =
299 | Color.dynamic(
300 | new Color("#000000"),
301 | new Color("#fefefe")
302 | );
303 |
304 | /* ============= CONFIG END ============= */
305 |
306 | /*******************************************/
307 | /* */
308 | /* DO NOT CHANGE ANYTHING BELOW! */
309 | /* (or do so at your own risk) */
310 | /* */
311 | /*******************************************/
312 |
313 | const ONLINE = await isOnline();
314 |
315 | // check for updates
316 | var UPDATE_AVAILABLE = false;
317 | if (ONLINE && CHECK_FOR_SCRIPT_UPDATE === true) {UPDATE_AVAILABLE = await checkForUpdate("v1.2.2");}
318 |
319 | // define default size of widget
320 | var WIDGET_SIZE = (config.runsInWidget ? config.widgetFamily : "large");
321 |
322 | // process widget parameters
323 | await checkWidgetParameter();
324 |
325 | // load settings if a file is configured
326 | if (SETTINGS_FILE != "none") {await loadSettingsFromFile(SETTINGS_FILE);}
327 |
328 | // set the number of posts depending on WIDGET_SIZE
329 | var WIDGET_NEWS_COUNT = (WIDGET_SIZE == "small") ? 1 : (WIDGET_SIZE == "medium") ? 2 : 5;
330 | if (CONF_LARGE_WIDGET_MAX_NEWS < 4 || CONF_LARGE_WIDGET_MAX_NEWS > 5) {CONF_LARGE_WIDGET_MAX_NEWS = 4;}
331 |
332 | // check directories
333 | await checkFileDirs();
334 |
335 | await cleanUpCache();
336 |
337 | if (config.runsInApp) {
338 | let welcomeAlert = await new Alert();
339 | welcomeAlert.title = "News Widget";
340 | welcomeAlert.message = "Welcome and THANK YOU for using News Widget!\nDo you want to run the Settings Wizard or Preview the Widget?";
341 | welcomeAlert.addAction("Run Settings Wizard");
342 | welcomeAlert.addAction("Preview Widget");
343 | welcomeAlert.addCancelAction("Cancel");
344 |
345 | switch (await welcomeAlert.presentSheet()) {
346 | case 0: await settingsWizard(); return;
347 | case 1: break;
348 | case -1: return;
349 | }
350 | }
351 |
352 | // create widget
353 | const widget = await createWidget();
354 |
355 | // show widget if run in app
356 | if (!config.runsInWidget) {
357 | switch (WIDGET_SIZE) {
358 | case "small": await widget.presentSmall(); break;
359 | case "medium": await widget.presentMedium(); break;
360 | case "large": await widget.presentLarge(); break;
361 | }
362 | }
363 |
364 | // set widget and end script
365 | Script.setWidget(widget);
366 | Script.complete();
367 |
368 |
369 | /* ============== FUNCTIONS ============== */
370 |
371 | // create the widget
372 | async function createWidget() {
373 | const fontWidgetTitle = await loadFont(CONF_FONT_WIDGET_TITLE, CONF_FONT_WEIGHT_WIDGET_TITLE, CONF_FONT_SIZE_WIDGET_TITLE);
374 | const fontDate = await loadFont(CONF_FONT_DATE, CONF_FONT_WEIGHT_DATE, CONF_FONT_SIZE_DATE);
375 | const fontHeadline = await loadFont(CONF_FONT_HEADLINE, CONF_FONT_WEIGHT_HEADLINE, CONF_FONT_SIZE_HEADLINE);
376 |
377 | const singleSiteMode = (PARAM_LINKS.length == 1 ? true : false);
378 |
379 | const list = new ListWidget();
380 |
381 | const widgetNewsData = await getData();
382 |
383 | // Display the title of the widget
384 | const titleStack = list.addStack();
385 | titleStack.layoutHorizontally();
386 |
387 | const widgetTitle = titleStack.addText(PARAM_WIDGET_TITLE);
388 | widgetTitle.font = fontWidgetTitle;
389 | widgetTitle.textColor = CONF_FONT_COLOR_WIDGET_TITLE;
390 | widgetTitle.lineLimit = 1;
391 | widgetTitle.minimumScaleFactor = 0.5;
392 |
393 | if (!ONLINE) {
394 | titleStack.addSpacer();
395 | const sym = SFSymbol.named("icloud.slash");
396 | sym.applyFont(fontWidgetTitle);
397 | const symbolOffline = titleStack.addImage(sym.image);
398 | symbolOffline.rightAlignImage();
399 | symbolOffline.tintColor = CONF_FONT_COLOR_WIDGET_TITLE;
400 | symbolOffline.imageSize = new Size(19, 19)
401 | }
402 |
403 | if (widgetNewsData) {
404 | if (WIDGET_SIZE == "large" && CONF_LARGE_WIDGET_MAX_NEWS == 4) {WIDGET_NEWS_COUNT = 4;}
405 | if (WIDGET_NEWS_COUNT >= widgetNewsData.aNewsHeadlines.length) {WIDGET_NEWS_COUNT = widgetNewsData.aNewsHeadlines.length;}
406 | 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();}
407 |
408 | if (WIDGET_NEWS_COUNT == 1 || widgetNewsData.aNewsHeadlines.length == 1) {
409 | // use default padding
410 | list.useDefaultPadding();
411 | // load widget background image (if PARAM_SHOW_NEWS_IMAGES = true or PARAM_BG_IMAGE_NAME is set)
412 | if (PARAM_SHOW_NEWS_IMAGES == "true" && PARAM_BG_IMAGE_NAME == "none") {
413 | if (widgetNewsData.aNewsIMGPaths[0] != "none") {
414 | list.backgroundImage = await loadLocalImage(widgetNewsData.aNewsIMGPaths[0]+(PARAM_BG_IMAGE_BLUR == "true" ? "-bg-blur" : "-bg"));
415 | // draw gradient over background image for better legibility
416 | CONF_BG_GRADIENT = true;
417 | CONF_BG_GRADIENT_COLOR_TOP = CONF_BG_GRADIENT_OVERLAY_TOP;
418 | CONF_BG_GRADIENT_COLOR_BTM = CONF_BG_GRADIENT_OVERLAY_BTM;
419 | }
420 | }
421 |
422 | const postStack = list.addStack();
423 | postStack.layoutVertically();
424 |
425 | if (config.widgetFamily === "medium" || config.widgetFamily === "large") {
426 | const labelDateTime = postStack.addText((singleSiteMode ? "" : widgetNewsData.aNewsSiteNames[0]+" - ")+widgetNewsData.aNewsDateTimes[0]);
427 | labelDateTime.font = fontDate;
428 | labelDateTime.textColor = CONF_FONT_COLOR_DATE;
429 | labelDateTime.lineLimit = 1;
430 | labelDateTime.minimumScaleFactor = 0.5;
431 | } else {
432 | if (!singleSiteMode) {
433 | const labelWidgetTitle = postStack.addText(widgetNewsData.aNewsSiteNames[0]);
434 | labelWidgetTitle.font = fontDate;
435 | labelWidgetTitle.textColor = CONF_FONT_COLOR_DATE;;
436 | labelWidgetTitle.lineLimit = 1;
437 | labelWidgetTitle.minimumScaleFactor = 0.5;
438 | }
439 |
440 | const labelDateTime = postStack.addText(widgetNewsData.aNewsDateTimes[0]);
441 | labelDateTime.font = fontDate;
442 | labelDateTime.textColor = CONF_FONT_COLOR_DATE;
443 | labelDateTime.lineLimit = 1;
444 | labelDateTime.minimumScaleFactor = 0.5;
445 | }
446 |
447 | const labelHeadline = postStack.addText(widgetNewsData.aNewsHeadlines[0]);
448 | labelHeadline.font = fontHeadline;
449 | labelHeadline.textColor = CONF_FONT_COLOR_HEADLINE;
450 | labelHeadline.lineLimit = 3;
451 |
452 | list.url = widgetNewsData.aNewsURLs[0];
453 | } else {
454 | list.setPadding(16, 16, 16, 16);
455 |
456 | const aStackRow = await new Array(WIDGET_NEWS_COUNT);
457 | const aStackCol = await new Array(WIDGET_NEWS_COUNT);
458 | const aLblNewsDateTime = await new Array(WIDGET_NEWS_COUNT);
459 | const aLblNewsHeadline = await new Array(WIDGET_NEWS_COUNT);
460 | const aLblNewsImage = await new Array(WIDGET_NEWS_COUNT);
461 |
462 | let i;
463 | for (i = 0; i < WIDGET_NEWS_COUNT; i++) {
464 | aStackRow[i] = list.addStack();
465 | aStackRow[i].layoutHorizontally();
466 | aStackRow[i].url = widgetNewsData.aNewsURLs[i];
467 |
468 | aStackCol[i] = aStackRow[i].addStack();
469 | aStackCol[i].layoutVertically();
470 |
471 | aLblNewsDateTime[i] = aStackCol[i].addText((singleSiteMode ? "" : widgetNewsData.aNewsSiteNames[i]+" - ")+widgetNewsData.aNewsDateTimes[i]);
472 | aLblNewsDateTime[i].font = fontDate;
473 | aLblNewsDateTime[i].textColor = CONF_FONT_COLOR_DATE;
474 | aLblNewsDateTime[i].lineLimit = 1;
475 | aLblNewsDateTime[i].minimumScaleFactor = 0.5;
476 |
477 | aLblNewsHeadline[i] = aStackCol[i].addText(widgetNewsData.aNewsHeadlines[i]);
478 | aLblNewsHeadline[i].font = fontHeadline;
479 | aLblNewsHeadline[i].textColor = CONF_FONT_COLOR_HEADLINE;
480 | aLblNewsHeadline[i].lineLimit = 2;
481 |
482 | if (PARAM_SHOW_NEWS_IMAGES == "true") {
483 | aStackRow[i].addSpacer();
484 | aLblNewsImage[i] = aStackRow[i].addImage(await loadLocalImage(widgetNewsData.aNewsIMGPaths[i]));
485 | if (WIDGET_SIZE == "large" && WIDGET_NEWS_COUNT == 4) {
486 | aLblNewsImage[i].imageSize = new Size(63,63);
487 | aLblNewsHeadline[i].lineLimit = 3;
488 | } else {
489 | aLblNewsImage[i].imageSize = new Size(45.66,45.66);
490 | }
491 | aLblNewsImage[i].cornerRadius = 8;
492 | if (widgetNewsData.aNewsIMGPaths[i] === "none") {aLblNewsImage[i].tintColor = CONF_FONT_COLOR_HEADLINE; aLblNewsImage[i].imageOpacity = 0.5;}
493 | aLblNewsImage[i].rightAlignImage();
494 | }
495 | if (i < WIDGET_NEWS_COUNT-1) {list.addSpacer();}
496 | }
497 | }
498 | } else {
499 | widgetTitle.textColor = Color.white();
500 | list.addSpacer();
501 | const sadFace = list.addText(":(");
502 | sadFace.font = Font.regularSystemFont((WIDGET_SIZE === "large") ? 190 : 60);
503 | sadFace.textColor = Color.white();
504 | sadFace.lineLimit = 1;
505 | sadFace.minimumScaleFactor = 0.1;
506 |
507 | list.addSpacer();
508 |
509 | const errMsg = list.addText("Couldn't load data");
510 | errMsg.font = Font.regularSystemFont(12);
511 | errMsg.textColor = Color.white();
512 |
513 | CONF_BG_COLOR = new Color("#1f67b1");
514 | CONF_BG_GRADIENT = false;
515 | PARAM_BG_IMAGE_NAME = "none";
516 | }
517 |
518 | if (UPDATE_AVAILABLE) {
519 | list.addSpacer(4);
520 | list.setPadding(16, 16, 0, 16);
521 | const updateMsg = list.addText("Script Update available on GitHub");
522 | updateMsg.font = Font.lightSystemFont(9);
523 | updateMsg.textColor = Color.white();
524 | updateMsg.lineLimit = 1;
525 | updateMsg.minimumScaleFactor = 0.2;
526 | updateMsg.centerAlignText()
527 | updateMsg.url = "https://github.com/Saudumm/scriptable-News-Widget"
528 | }
529 |
530 | // widget background (image, single color or gradient)
531 | if (PARAM_BG_IMAGE_NAME != "none") {
532 | const customBGImage = await loadBGImage(PARAM_BG_IMAGE_NAME, PARAM_BG_IMAGE_BLUR);
533 | if (customBGImage != "not found") {
534 | list.backgroundImage = customBGImage;
535 | if (PARAM_BG_IMAGE_GRADIENT == "true") {
536 | // draw gradient over background image for better legibility
537 | const gradient = new LinearGradient();
538 | gradient.locations = [0, 1];
539 | gradient.colors = [CONF_BG_GRADIENT_OVERLAY_TOP, CONF_BG_GRADIENT_OVERLAY_BTM];
540 | list.backgroundGradient = gradient;
541 | }
542 | } else {
543 | list.backgroundColor = CONF_BG_COLOR;
544 | }
545 | } else if (CONF_BG_GRADIENT == true) {
546 | const gradient = new LinearGradient();
547 | gradient.locations = [0, 1];
548 | gradient.colors = [CONF_BG_GRADIENT_COLOR_TOP, CONF_BG_GRADIENT_COLOR_BTM];
549 | list.backgroundGradient = gradient;
550 | } else {
551 | list.backgroundColor = CONF_BG_COLOR;
552 | }
553 | return list;
554 | }
555 |
556 | // get data from all websites and extract necessary data
557 | async function getData() {
558 | try {
559 | const localFM = FileManager.local();
560 |
561 | const aData = await new Array();
562 |
563 | for (iLink = 0; iLink < PARAM_LINKS.length; iLink++) {
564 | // add https:// to the link if it's missing
565 | if (PARAM_LINKS[iLink][0].substring(0, 7) != "http://" && PARAM_LINKS[iLink][0].substring(0, 8) != "https://") {
566 | PARAM_LINKS[iLink][0] = "https://"+PARAM_LINKS[iLink][0]
567 | }
568 | // remove last / from link
569 | if (PARAM_LINKS[iLink][0].slice(-1) == "/") {PARAM_LINKS[iLink][0] = PARAM_LINKS[iLink][0].slice(0, -1);}
570 |
571 | const whatToLoad = await _whatShouldILoad(PARAM_LINKS[iLink][0], PARAM_LINKS[iLink][1])
572 |
573 | if (whatToLoad.loadFormat == "WP-JSON") {
574 | // WordPress JSON
575 | try {
576 | let loadedJSON
577 | if (ONLINE) {
578 | loadedJSON = await new Request(PARAM_LINKS[iLink][0]+"/wp-json/wp/v2/posts?per_page=5").loadJSON();
579 | // Save data to file
580 | await localFM.writeString(whatToLoad.loadFilePath, JSON.stringify(loadedJSON));
581 | } else {
582 | loadedJSON = await JSON.parse(localFM.readString(whatToLoad.loadFilePath));
583 | }
584 |
585 | // Define how many news should be processed
586 | let calcLoadPosts = 5;
587 | let maxPostsForWidgetSize = (WIDGET_SIZE == "small") ? 1 : (WIDGET_SIZE == "medium") ? 2 : 5
588 | if (WIDGET_SIZE == "large" && CONF_LARGE_WIDGET_MAX_NEWS == 4) {maxPostsForWidgetSize = 4;}
589 | if (CONF_DISPLAY_NEWS == "websites") {
590 | calcLoadPosts = await Math.round(maxPostsForWidgetSize / PARAM_LINKS.length / 1);
591 | calcLoadPosts = (calcLoadPosts <= 1) ? 1 : calcLoadPosts;
592 | } else if (CONF_DISPLAY_NEWS == "date") {
593 | calcLoadPosts = maxPostsForWidgetSize
594 | }
595 |
596 |
597 | const loadPosts = (loadedJSON.length >= calcLoadPosts) ? calcLoadPosts : loadedJSON.length
598 | let iPost;
599 | for (iPost = 0; iPost < loadPosts; iPost++) {
600 | let postDate = loadedJSON[iPost].date_gmt;
601 | if (postDate === undefined) {postDate = loadedJSON[iPost].date;} else {(postDate.slice(-1) == "Z") ? postDate : postDate += "Z";}
602 | const postDateSort = await new Date(postDate).toLocaleString(["fr-CA"], {year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit"});
603 | const postTitle = await _formatPostTitle(loadedJSON[iPost].title.rendered);
604 | const postURL = loadedJSON[iPost].guid.rendered;
605 | const postIMGURL = await _getMediaURL(PARAM_LINKS[iLink][0], loadedJSON[iPost].featured_media, loadedJSON[iPost].id, PARAM_LINKS[iLink][1]);
606 |
607 | await aData.push([postDateSort, postDate+"|||"+postTitle+"|||"+postURL+"|||"+postIMGURL+"|||"+PARAM_LINKS[iLink][1]]);
608 | }
609 | } catch(err) {
610 | log("try processing WP-JSON: "+err);
611 | }
612 | } else if (whatToLoad.loadFormat == "RSS") {
613 | // RSS Feeds
614 | try {
615 | let loadRSSFeed = null;
616 | if (ONLINE) {
617 | loadRSSFeed = await new Request(PARAM_LINKS[iLink][0]).loadString();
618 | // Save data to file
619 | await localFM.writeString(whatToLoad.loadFilePath, loadRSSFeed);
620 | } else {
621 | loadRSSFeed = await localFM.readString(whatToLoad.loadFilePath);
622 | }
623 |
624 | const aRSSItems = await new Array();
625 | let itemValue = null;
626 | let currentItem = null;
627 | let searchForImage = true;
628 | let xmlParser = new XMLParser(loadRSSFeed);
629 | // start of element
630 | xmlParser.didStartElement = (name, elementContent) => {
631 | itemValue = "";
632 | if (name == "entry" || name == "item") {
633 | currentItem = {};
634 | searchForImage = true;
635 | }
636 |
637 | // possible image values in element name
638 | if ((name.substring(0, 6) == "media:" || name == "enclosure") && searchForImage) {
639 | if (elementContent.url !== null && elementContent.url !== undefined && currentItem !== null && currentItem !== undefined) {
640 | let imgLink = elementContent.url.match(/"?(http(?!.*http)s?\:\/\/.*?\.)(jpe?g|png|bmp|webp)"?/i);
641 | if (imgLink && imgLink.length == 3) {
642 | imgLink = imgLink[1]+imgLink[2];
643 | currentItem["image"] = imgLink;
644 | searchForImage = false;
645 | }
646 | }
647 | }
648 | }
649 | // end of element
650 | xmlParser.didEndElement = name => {
651 | const hasItem = currentItem != null;
652 |
653 | // possible url location
654 | if (hasItem && name == "id") {currentItem["id"] = itemValue;}
655 |
656 | // possible url location
657 | if (hasItem && name == "link") {currentItem["link"] = itemValue;}
658 |
659 | // title value
660 | if (hasItem && name == "title") {currentItem["title"] = itemValue;}
661 |
662 | // published date
663 | if (hasItem && (name == "published" || name == "pubDate" || name == "updated")) {currentItem["published"] = itemValue;}
664 |
665 | // possible image link location
666 | if (hasItem && name == "image" && searchForImage) {
667 | let imgLink = itemValue.match(/"?(http(?!.*http)s?\:\/\/.*?\.)(jpe?g|png|bmp|webp)"?/i);
668 | if (imgLink && imgLink.length == 3) {
669 | imgLink = imgLink[1]+imgLink[2];
670 | currentItem["image"] = imgLink;
671 | searchForImage = false;
672 | }
673 | }
674 |
675 | // possible image link location
676 | if (hasItem && name == "thumb" && searchForImage) {
677 | let imgLink = itemValue.match(/"?(http(?!.*http)s?\:\/\/.*?\.)(jpe?g|png|bmp|webp)"?/i);
678 | if (imgLink && imgLink.length == 3) {
679 | imgLink = imgLink[1]+imgLink[2];
680 | currentItem["image"] = imgLink;
681 | searchForImage = false;
682 | }
683 | }
684 |
685 | // possible image link location
686 | if (hasItem && name.includes("content")) {
687 | let imgLink = itemValue.match(/src="(https?\:\/\/.*?\.)(jpe?g|png|bmp|webp).*?"/i);
688 | if (imgLink && imgLink.length == 3) {
689 | imgLink = imgLink[1]+imgLink[2];
690 | currentItem["image"] = imgLink;
691 | searchForImage = false;
692 | } else {
693 | imgLink = itemValue.match(/src="(.*?\.)(jpe?g|png|bmp|webp).*?"/i);
694 | if (imgLink && imgLink.length == 3) {
695 | let urlFromParam = PARAM_LINKS[iLink][0].match(/(https?\:\/\/.*?)\//i);
696 | if (urlFromParam && urlFromParam.length == 2) {
697 | imgLink = urlFromParam[1]+imgLink[1]+imgLink[2];
698 | imgLink = imgLink.match(/(https?\:\/\/.*?\.)(jpe?g|png|bmp|webp).*?/i);
699 | if (imgLink && imgLink.length == 3) {
700 | imgLink = imgLink[1]+imgLink[2];
701 | currentItem["image"] = imgLink;
702 | searchForImage = false;
703 | }
704 | }
705 | }
706 | }
707 | }
708 |
709 | // possible image link location
710 | if (hasItem && name == "description") {
711 | let imgLink = itemValue.match(/src="(https?\:\/\/.*?\.)(jpe?g|png|bmp|webp).*?"/i);
712 | if (imgLink && imgLink.length == 3) {
713 | imgLink = imgLink[1]+imgLink[2];
714 | currentItem["image"] = imgLink;
715 | searchForImage = false;
716 | } else {
717 | imgLink = itemValue.match(/src="(.*?\.)(jpe?g|png|bmp|webp).*?"/i);
718 | if (imgLink && imgLink.length == 3) {
719 | let urlFromParam = PARAM_LINKS[iLink][0].match(/(https?\:\/\/.*?)\//i);
720 | if (urlFromParam && urlFromParam.length == 2) {
721 | imgLink = urlFromParam[1]+imgLink[1]+imgLink[2];
722 | imgLink = imgLink.match(/(https?\:\/\/.*?\.)(jpe?g|png|bmp|webp).*?/i);
723 | if (imgLink && imgLink.length == 3) {
724 | imgLink = imgLink[1]+imgLink[2];
725 | currentItem["image"] = imgLink;
726 | searchForImage = false;
727 | }
728 | }
729 | }
730 | }
731 | }
732 |
733 | // end of item/entry block
734 | if (name == "entry" || name == "item") {
735 | aRSSItems.push(currentItem);
736 | currentItem = null;
737 | }
738 | }
739 | // found characters between element start and end
740 | xmlParser.foundCharacters = str => {itemValue += str;}
741 | // end of document
742 | xmlParser.didEndDocument = () => {}
743 | // parse xml string
744 | await xmlParser.parse();
745 |
746 | //const loadPosts = (aRSSItems.length >= 5) ? 5 : aRSSItems.length
747 |
748 | const aRSSData = await new Array();
749 |
750 | for (iRSS = 0; iRSS < aRSSItems.length; iRSS++) {
751 | let rssDate = "none";
752 | let rssDateSort = "none";
753 | let rssTitle = "none";
754 | let rssURL = "none";
755 | let rssIMGURL = "none";
756 |
757 | if (aRSSItems[iRSS].published !== null) {
758 | rssDate = aRSSItems[iRSS].published;
759 | rssDateSort = await new Date(rssDate).toLocaleString(["fr-CA"], {year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit"});
760 | }
761 |
762 | if (aRSSItems[iRSS].title) {rssTitle = aRSSItems[iRSS].title;}
763 |
764 | if (aRSSItems[iRSS].id) {
765 | rssURL = aRSSItems[iRSS].id;
766 | } else if (aRSSItems[iRSS].link) {
767 | rssURL = aRSSItems[iRSS].link;
768 | }
769 |
770 | if (aRSSItems[iRSS].image) {
771 | // double check if link is image link
772 | const rssIMGRegEx = await aRSSItems[iRSS].image.match(/"?(http(?!.*http)s?\:\/\/.*?\.)(jpe?g|png|bmp|webp)"?/i);
773 | if (rssIMGRegEx && rssIMGRegEx.length == 3) {
774 | rssIMGURL = rssIMGRegEx[1]+rssIMGRegEx[2];
775 | }
776 | }
777 |
778 | if (rssDateSort !== "Invalid Date") {
779 | await aRSSData.push([rssDateSort, rssDate+"|||"+rssTitle+"|||"+rssURL+"|||"+rssIMGURL+"|||"+PARAM_LINKS[iLink][1]]);
780 | }
781 | }
782 |
783 | if (aRSSData && aRSSData.length >= 1) {
784 |
785 | // sort all post according to date
786 | aRSSData.sort(function sortFunction(a, b) {
787 | if (a[0] === b[0]) {
788 | return 0;
789 | } else {
790 | return (a[0] < b[0]) ? -1 : 1;
791 | }
792 | })
793 | // reverse sorting - new to old date
794 | aRSSData.reverse()
795 |
796 | // Define how many news should be processed
797 | let calcLoadPosts = 5;
798 | let maxPostsForWidgetSize = (WIDGET_SIZE == "small") ? 1 : (WIDGET_SIZE == "medium") ? 2 : 5
799 | if (WIDGET_SIZE == "large" && CONF_LARGE_WIDGET_MAX_NEWS == 4) {maxPostsForWidgetSize = 4;}
800 | if (CONF_DISPLAY_NEWS == "websites") {
801 | calcLoadPosts = await Math.round(maxPostsForWidgetSize / PARAM_LINKS.length / 1);
802 | calcLoadPosts = (calcLoadPosts <= 1) ? 1 : calcLoadPosts;
803 | } else if (CONF_DISPLAY_NEWS == "date") {
804 | calcLoadPosts = maxPostsForWidgetSize
805 | }
806 |
807 | const loadPosts = (aRSSData.length >= calcLoadPosts) ? calcLoadPosts : aRSSData.length
808 |
809 | let iRSSNews;
810 | for (iRSSNews = 0; iRSSNews < loadPosts; iRSSNews++) {
811 | await aData.push([aRSSData[iRSSNews][0], aRSSData[iRSSNews][1]]);
812 | }
813 | }
814 | } catch(err) {
815 | log("try processing RSS feed: "+err);
816 | }
817 | }
818 | }
819 |
820 | if (aData.length >= 1) {
821 | // sort all post according to date
822 | aData.sort(function sortFunction(a, b) {
823 | if (a[0] === b[0]) {
824 | return 0;
825 | } else {
826 | return (a[0] < b[0]) ? -1 : 1;
827 | }
828 | })
829 | // reverse sorting - new to old date
830 | aData.reverse()
831 |
832 | const POSTS_TO_LOAD = (aData.length >= 5) ? 5 : aData.length;
833 |
834 | const aDateTimes = await new Array(POSTS_TO_LOAD);
835 | const aHeadlines = await new Array(POSTS_TO_LOAD);
836 | const aURLs = await new Array(POSTS_TO_LOAD);
837 | const aIMGURLs = await new Array(POSTS_TO_LOAD);
838 | const aIMGPaths = await new Array(POSTS_TO_LOAD);
839 | const aSiteNames = await new Array(POSTS_TO_LOAD);
840 | const aFileNames = await new Array(POSTS_TO_LOAD);
841 |
842 | for (iNewPost = 0; iNewPost < POSTS_TO_LOAD; iNewPost++) {
843 | const aStrSplit = aData[iNewPost][1].split("|||")
844 |
845 | if (aStrSplit[0] != "none" && aStrSplit[0] != "undefined" && aStrSplit[0] != undefined) {
846 | aDateTimes[iNewPost] = await new Date(aStrSplit[0]);
847 | } else {
848 | aDateTimes[iNewPost] = await Date.now();
849 | }
850 | aDateTimes[iNewPost] = await _formatDateTimeString(aDateTimes[iNewPost]);
851 |
852 | aHeadlines[iNewPost] = aStrSplit[1];
853 | aHeadlines[iNewPost] = await _formatPostTitle(aHeadlines[iNewPost]);
854 |
855 | aURLs[iNewPost] = aStrSplit[2];
856 |
857 | aSiteNames[iNewPost] = aStrSplit[4];
858 |
859 | if (PARAM_SHOW_NEWS_IMAGES == "true") {
860 | aIMGURLs[iNewPost] = aStrSplit[3];
861 | if (aIMGURLs[iNewPost] != "none") {
862 | const fileID = await _hashCode(aIMGURLs[iNewPost])
863 |
864 | aFileNames[iNewPost] = await getFileName(aSiteNames[iNewPost], fileID);
865 |
866 | const addBGImage = (iNewPost == 0 ? true : false);
867 | aIMGURLs[iNewPost] = await encodeURI(aIMGURLs[iNewPost]);
868 | aIMGURLs[iNewPost] = await aIMGURLs[iNewPost].replaceAll("%25", "%"); // hack for some image URLs with %
869 |
870 | aIMGPaths[iNewPost] = await _downloadPostImage(aFileNames[iNewPost], aIMGURLs[iNewPost], addBGImage);
871 | } else {
872 | aIMGPaths[iNewPost] = "none";
873 | }
874 | }
875 | }
876 |
877 | return {
878 | aNewsDateTimes: aDateTimes,
879 | aNewsHeadlines: aHeadlines,
880 | aNewsURLs: aURLs,
881 | aNewsIMGPaths: aIMGPaths,
882 | aNewsSiteNames: aSiteNames
883 | };
884 | } else {
885 | return null;
886 | }
887 | } catch(err) {
888 | logError("try getData: "+err);
889 | return null;
890 | }
891 |
892 | // define what sould be loaded depending on link and online status
893 | async function _whatShouldILoad(link, strSiteName) {
894 | let loadFormat = "none";
895 | let loadFilePath = "none";
896 |
897 | const localFM = FileManager.local();
898 | const docDir = localFM.documentsDirectory();
899 | const backupFilename = await getFileName(strSiteName, "0");
900 | const pathBackupJSON = localFM.joinPath(docDir+"/saudumm-news-widget-data", backupFilename+".json");
901 | const pathBackupXML = localFM.joinPath(docDir+"/saudumm-news-widget-data", backupFilename+".xml");
902 |
903 | if (ONLINE) {
904 | if (await isJSON(link+"/wp-json/wp/v2/posts?per_page=1")) {
905 | loadFormat = "WP-JSON";
906 | loadFilePath = pathBackupJSON;
907 | } else {
908 | loadFormat = "RSS";
909 | loadFilePath = pathBackupXML;
910 | }
911 | } else {
912 | if (localFM.fileExists(pathBackupJSON)) {
913 | loadFormat = "WP-JSON";
914 | loadFilePath = pathBackupJSON;
915 | } else if (localFM.fileExists(pathBackupXML)) {
916 | loadFormat = "RSS";
917 | loadFilePath = pathBackupXML;
918 | }
919 | }
920 |
921 | return {
922 | loadFormat: loadFormat,
923 | loadFilePath: loadFilePath
924 | };
925 |
926 | // check if the url leads to a json file
927 | async function isJSON(strURL) {
928 | try {
929 | const testJSON = await new Request(strURL).loadJSON();
930 | if (testJSON.reason == "Not Found") {return false;}
931 | } catch(err) {
932 | return false;
933 | }
934 | return true;
935 | }
936 | }
937 |
938 | // format the date and time string to a locale date/time
939 | function _formatDateTimeString(strDateTime) {
940 | 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)})
941 | }
942 |
943 | // format the post title and replace all html entities with characters
944 | function _formatPostTitle(strHeadline) {
945 | strHeadline = strHeadline.trim().replaceAll(""", '"')
946 | .replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">")
947 | .replaceAll("'", "'").replaceAll(""", '"').replaceAll("&", "&")
948 | .replaceAll("'", "'").replaceAll("<", "<").replaceAll(">", ">")
949 | .replaceAll("Œ", "Œ").replaceAll("œ", "œ").replaceAll("Š", "Š")
950 | .replaceAll("š", "š").replaceAll("Ÿ", "Ÿ").replaceAll("ˆ", "ˆ")
951 | .replaceAll("˜", "˜").replaceAll("–", "–").replaceAll("—", "—")
952 | .replaceAll("‘", "‘").replaceAll("’", "’").replaceAll("‚", "‚")
953 | .replaceAll("“", "“").replaceAll("”", "”").replaceAll("„", "„")
954 | .replaceAll("†", "†").replaceAll("‡", "‡").replaceAll("…", "…")
955 | .replaceAll("‰", "‰").replaceAll("‹", "‹").replaceAll("›", "›")
956 | .replaceAll("€", "€").replaceAll("", "");
957 | return strHeadline;
958 | }
959 |
960 | // get the featuredMedia image URL
961 | async function _getMediaURL(strURL, strFeatMediaID, strPostID, strSiteName) {
962 | const localFM = FileManager.local();
963 | const docDir = localFM.documentsDirectory();
964 | const backupFilename = await getFileName(strSiteName, strPostID);
965 | const pathBackupMedia = localFM.joinPath(docDir+"/saudumm-news-widget-data", backupFilename+"-media.json");
966 | const pathBackupPosts = localFM.joinPath(docDir+"/saudumm-news-widget-data", backupFilename+"-posts.json");
967 |
968 | let featuredMediaJSONURL = strURL+"/wp-json/wp/v2/media/"+strFeatMediaID;
969 | let loadedMediaJSON
970 | if (ONLINE) {
971 | loadedMediaJSON = await new Request(featuredMediaJSONURL).loadJSON();
972 | // Save data to file
973 | await localFM.writeString(pathBackupMedia, JSON.stringify(loadedMediaJSON));
974 | } else {
975 | loadedMediaJSON = await JSON.parse(localFM.readString(pathBackupMedia));
976 | }
977 | let mediaURL = loadedMediaJSON.source_url;
978 | if (mediaURL === undefined || mediaURL == "undefined") {
979 | // search for other images
980 | featuredMediaJSONURL = strURL+"/wp-json/wp/v2/posts/"+strPostID;
981 | if (ONLINE) {
982 | loadedMediaJSON = await new Request(featuredMediaJSONURL).loadJSON();
983 | // Save data to file
984 | await localFM.writeString(pathBackupPosts, JSON.stringify(loadedMediaJSON));
985 | } else {
986 | loadedMediaJSON = await JSON.parse(localFM.readString(pathBackupPosts));
987 | }
988 | mediaURL = loadedMediaJSON.jetpack_featured_media_url;
989 | if (mediaURL === undefined || mediaURL == "undefined") {
990 | return "none";
991 | } else {
992 | mediaURL = mediaURL.match(/(http?s.*\.)(jpe?g|png|bmp|webp)/i)
993 | mediaURL = mediaURL[1]+""+mediaURL[2];
994 | return await encodeURI(mediaURL);
995 | }
996 | } else {
997 | mediaURL = await mediaURL.match(/(http?s.*\.)(jpe?g|png|bmp|webp)/i)
998 | mediaURL = mediaURL[1]+""+mediaURL[2];
999 | return await encodeURI(mediaURL);
1000 | }
1001 | return "none";
1002 | }
1003 |
1004 | // create a hash from a string
1005 | function _hashCode(str) {
1006 | var hash = 0;
1007 | if (str.length == 0) return hash;
1008 | for (cHash = 0; cHash < str.length; cHash++) {
1009 | char = str.charCodeAt(cHash);
1010 | hash = ((hash<<5)-hash)+char;
1011 | hash = hash & hash; // Convert to 32bit integer
1012 | }
1013 | hash = Math.abs(hash);
1014 | return hash;
1015 | }
1016 |
1017 | // download the post image (if it doesn't already exist)
1018 | async function _downloadPostImage(strFileName, strURL, boolAddBGImage) {
1019 | const localFM = FileManager.local();
1020 | var imgPath = localFM.documentsDirectory();
1021 | imgPath = localFM.joinPath(imgPath+"/saudumm-news-widget-data/image-cache", strFileName);
1022 | var tempPath = localFM.temporaryDirectory()
1023 | tempPath = localFM.joinPath(tempPath, strFileName);
1024 |
1025 | // check if file already exists
1026 | if (!boolAddBGImage && localFM.fileExists(imgPath)) {
1027 | return imgPath;
1028 | } else if (!boolAddBGImage && !localFM.fileExists(imgPath)) {
1029 | if (ONLINE) {
1030 | // download image
1031 | let loadedImage = await new Request(strURL).load();
1032 | // write image and read again (it's smaller that way???)
1033 | await localFM.write(tempPath, loadedImage);
1034 | loadedImage = await localFM.readImage(tempPath);
1035 |
1036 | // resize, crop and store image
1037 | loadedImage = await resizeImage(loadedImage, 200);
1038 | loadedImage = await cropImageToSquare(loadedImage);
1039 | await localFM.writeImage(imgPath, loadedImage);
1040 |
1041 | await localFM.remove(tempPath);
1042 | return imgPath;
1043 | } else {
1044 | return "none";
1045 | }
1046 | }
1047 |
1048 | if (boolAddBGImage) {
1049 | const imgPathBG = imgPath+"-bg"
1050 | const imgPathBGBlur = imgPath+"-bg-blur"
1051 |
1052 | if (localFM.fileExists(imgPath) && localFM.fileExists(imgPathBG) && localFM.fileExists(imgPathBGBlur)) {
1053 | return imgPath;
1054 | } else {
1055 | if (ONLINE) {
1056 | // download image
1057 | let loadedImage = await new Request(strURL).load();
1058 | // write image and read again (it's smaller that way???)
1059 | await localFM.write(tempPath, loadedImage);
1060 | loadedImage = await localFM.readImage(tempPath);
1061 |
1062 | if (await Math.min(loadedImage.size.height, loadedImage.size.width) > 500) {
1063 | loadedImage = await resizeImage(loadedImage, 500);
1064 | }
1065 |
1066 | // resize, crop and store image
1067 | if(!localFM.fileExists(imgPath)) {
1068 | let loadedSmallImage = await resizeImage(loadedImage, 200);
1069 | loadedSmallImage = await cropImageToSquare(loadedSmallImage);
1070 | await localFM.writeImage(imgPath, loadedSmallImage);
1071 | }
1072 |
1073 | // store original image
1074 | if (!localFM.fileExists(imgPathBG)) {
1075 | await localFM.writeImage(imgPathBG, loadedImage);
1076 | }
1077 |
1078 | // store blurred resized original image
1079 | if (!localFM.fileExists(imgPathBGBlur)) {
1080 | let loadedImageBlur = await blurImage(loadedImage)
1081 | await localFM.writeImage(imgPathBGBlur, loadedImageBlur);
1082 | }
1083 |
1084 | await localFM.remove(tempPath);
1085 | return imgPath;
1086 | } else {
1087 | return "none";
1088 | }
1089 | }
1090 | }
1091 | return "none";
1092 | }
1093 | }
1094 |
1095 | // load all settings from a file
1096 | async function loadSettingsFromFile(strFileName) {
1097 | try {
1098 | let fmSettings;
1099 | try {fmSettings = FileManager.iCloud()} catch (e) {fmSettings = FileManager.local()}
1100 | try {fmSettings.documentsDirectory()} catch(e) {fmSettings = FileManager.local()}
1101 |
1102 | let filePath = fmSettings.documentsDirectory();
1103 | filePath = fmSettings.joinPath(filePath, "News-Widget-Settings");
1104 | filePath = fmSettings.joinPath(filePath, strFileName);
1105 |
1106 | if (fmSettings.fileExists(filePath) && fmSettings.isFileStoredIniCloud(filePath)) {
1107 | await fmSettings.downloadFileFromiCloud(filePath);
1108 |
1109 | const jsonConfig = await JSON.parse(fmSettings.readString(filePath));
1110 |
1111 | if (jsonConfig.CHECK_FOR_SCRIPT_UPDATE !== undefined) {CHECK_FOR_SCRIPT_UPDATE = jsonConfig.CHECK_FOR_SCRIPT_UPDATE;}
1112 | if (jsonConfig.PARAM_LINKS !== undefined) {PARAM_LINKS = jsonConfig.PARAM_LINKS;}
1113 | if (jsonConfig.PARAM_WIDGET_TITLE !== undefined) {PARAM_WIDGET_TITLE = jsonConfig.PARAM_WIDGET_TITLE;}
1114 | if (jsonConfig.PARAM_BG_IMAGE_NAME !== undefined) {PARAM_BG_IMAGE_NAME = jsonConfig.PARAM_BG_IMAGE_NAME;}
1115 | if (jsonConfig.PARAM_BG_IMAGE_BLUR !== undefined) {PARAM_BG_IMAGE_BLUR = jsonConfig.PARAM_BG_IMAGE_BLUR;}
1116 | if (jsonConfig.PARAM_BG_IMAGE_GRADIENT !== undefined) {PARAM_BG_IMAGE_GRADIENT = jsonConfig.PARAM_BG_IMAGE_GRADIENT;}
1117 | if (jsonConfig.PARAM_SHOW_NEWS_IMAGES !== undefined) {PARAM_SHOW_NEWS_IMAGES = jsonConfig.PARAM_SHOW_NEWS_IMAGES;}
1118 | if (jsonConfig.CONF_LARGE_WIDGET_MAX_NEWS !== undefined) {CONF_LARGE_WIDGET_MAX_NEWS = jsonConfig.CONF_LARGE_WIDGET_MAX_NEWS;}
1119 | if (jsonConfig.CONF_POSTS_PER_LINK !== undefined) {CONF_POSTS_PER_LINK = jsonConfig.CONF_POSTS_PER_LINK;}
1120 | if (jsonConfig.CONF_DATE_TIME_LOCALE !== undefined) {CONF_DATE_TIME_LOCALE = jsonConfig.CONF_DATE_TIME_LOCALE;}
1121 | if (jsonConfig.CONF_12_HOUR !== undefined) {CONF_12_HOUR = jsonConfig.CONF_12_HOUR;}
1122 |
1123 | if (jsonConfig.CONF_BG_COLOR.lightMode !== undefined && jsonConfig.CONF_BG_COLOR.darkMode !== undefined) {
1124 | CONF_BG_COLOR = Color.dynamic(new Color(jsonConfig.CONF_BG_COLOR.lightMode), new Color(jsonConfig.CONF_BG_COLOR.darkMode));
1125 | }
1126 |
1127 | if (jsonConfig.CONF_BG_GRADIENT !== undefined) {CONF_BG_GRADIENT = jsonConfig.CONF_BG_GRADIENT;}
1128 | if (jsonConfig.CONF_BG_GRADIENT_COLOR_TOP.lightMode !== undefined && jsonConfig.CONF_BG_GRADIENT_COLOR_TOP.darkMode !== undefined) {
1129 | CONF_BG_GRADIENT_COLOR_TOP = Color.dynamic(new Color(jsonConfig.CONF_BG_GRADIENT_COLOR_TOP.lightMode), new Color(jsonConfig.CONF_BG_GRADIENT_COLOR_TOP.darkMode));
1130 | }
1131 | if (jsonConfig.CONF_BG_GRADIENT_COLOR_BTM.lightMode !== undefined && jsonConfig.CONF_BG_GRADIENT_COLOR_BTM.darkMode !== undefined) {
1132 | CONF_BG_GRADIENT_COLOR_BTM = Color.dynamic(new Color(jsonConfig.CONF_BG_GRADIENT_COLOR_BTM.lightMode), new Color(jsonConfig.CONF_BG_GRADIENT_COLOR_BTM.darkMode));
1133 | }
1134 |
1135 | if (jsonConfig.CONF_BG_GRADIENT_OVERLAY_TOP.lightMode !== undefined && jsonConfig.CONF_BG_GRADIENT_OVERLAY_TOP.darkMode !== undefined) {
1136 | if (jsonConfig.CONF_BG_GRADIENT_OVERLAY_TOP.lightModeAlpha !== undefined && jsonConfig.CONF_BG_GRADIENT_OVERLAY_TOP.darkModeAlpha !== undefined) {
1137 | CONF_BG_GRADIENT_OVERLAY_TOP = Color.dynamic(new Color(jsonConfig.CONF_BG_GRADIENT_OVERLAY_TOP.lightMode, jsonConfig.CONF_BG_GRADIENT_OVERLAY_TOP.lightModeAlpha),
1138 | new Color(jsonConfig.CONF_BG_GRADIENT_OVERLAY_TOP.darkMode, jsonConfig.CONF_BG_GRADIENT_OVERLAY_TOP.darkModeAlpha));}
1139 | }
1140 | if (jsonConfig.CONF_BG_GRADIENT_OVERLAY_BTM.lightMode !== undefined && jsonConfig.CONF_BG_GRADIENT_OVERLAY_BTM.darkMode !== undefined) {
1141 | if (jsonConfig.CONF_BG_GRADIENT_OVERLAY_BTM.lightModeAlpha !== undefined && jsonConfig.CONF_BG_GRADIENT_OVERLAY_BTM.darkModeAlpha !== undefined) {
1142 | CONF_BG_GRADIENT_OVERLAY_BTM = Color.dynamic(new Color(jsonConfig.CONF_BG_GRADIENT_OVERLAY_BTM.lightMode, jsonConfig.CONF_BG_GRADIENT_OVERLAY_BTM.lightModeAlpha),
1143 | new Color(jsonConfig.CONF_BG_GRADIENT_OVERLAY_BTM.darkMode, jsonConfig.CONF_BG_GRADIENT_OVERLAY_BTM.darkModeAlpha));}
1144 | }
1145 |
1146 | if (jsonConfig.CONF_FONT_WIDGET_TITLE !== undefined) {CONF_FONT_WIDGET_TITLE = jsonConfig.CONF_FONT_WIDGET_TITLE;}
1147 | if (jsonConfig.CONF_FONT_WEIGHT_WIDGET_TITLE !== undefined) {CONF_FONT_WEIGHT_WIDGET_TITLE = jsonConfig.CONF_FONT_WEIGHT_WIDGET_TITLE;}
1148 | if (jsonConfig.CONF_FONT_SIZE_WIDGET_TITLE !== undefined) {CONF_FONT_SIZE_WIDGET_TITLE = jsonConfig.CONF_FONT_SIZE_WIDGET_TITLE;}
1149 | if (jsonConfig.CONF_FONT_COLOR_WIDGET_TITLE.lightMode !== undefined && jsonConfig.CONF_FONT_COLOR_WIDGET_TITLE.darkMode !== undefined) {
1150 | CONF_FONT_COLOR_WIDGET_TITLE = Color.dynamic(new Color(jsonConfig.CONF_FONT_COLOR_WIDGET_TITLE.lightMode), new Color(jsonConfig.CONF_FONT_COLOR_WIDGET_TITLE.darkMode));
1151 | }
1152 |
1153 | if (jsonConfig.CONF_FONT_DATE !== undefined) {CONF_FONT_DATE = jsonConfig.CONF_FONT_DATE;}
1154 | if (jsonConfig.CONF_FONT_WEIGHT_DATE !== undefined) {CONF_FONT_WEIGHT_DATE = jsonConfig.CONF_FONT_WEIGHT_DATE;}
1155 | if (jsonConfig.CONF_FONT_SIZE_DATE !== undefined) {CONF_FONT_SIZE_DATE = jsonConfig.CONF_FONT_SIZE_DATE;}
1156 | if (jsonConfig.CONF_FONT_COLOR_DATE.lightMode !== undefined && jsonConfig.CONF_FONT_COLOR_DATE.darkMode !== undefined) {
1157 | CONF_FONT_COLOR_DATE = Color.dynamic(new Color(jsonConfig.CONF_FONT_COLOR_DATE.lightMode), new Color(jsonConfig.CONF_FONT_COLOR_DATE.darkMode));
1158 | }
1159 |
1160 | if (jsonConfig.CONF_FONT_HEADLINE !== undefined) {CONF_FONT_HEADLINE = jsonConfig.CONF_FONT_HEADLINE;}
1161 | if (jsonConfig.CONF_FONT_WEIGHT_HEADLINE !== undefined) {CONF_FONT_WEIGHT_HEADLINE = jsonConfig.CONF_FONT_WEIGHT_HEADLINE;}
1162 | if (jsonConfig.CONF_FONT_SIZE_HEADLINE !== undefined) {CONF_FONT_SIZE_HEADLINE = jsonConfig.CONF_FONT_SIZE_HEADLINE;}
1163 | if (jsonConfig.CONF_FONT_COLOR_HEADLINE.lightMode !== undefined && jsonConfig.CONF_FONT_COLOR_HEADLINE.darkMode !== undefined) {
1164 | CONF_FONT_COLOR_HEADLINE = Color.dynamic(new Color(jsonConfig.CONF_FONT_COLOR_HEADLINE.lightMode), new Color(jsonConfig.CONF_FONT_COLOR_HEADLINE.darkMode));
1165 | }
1166 | } else {
1167 | return null;
1168 | }
1169 | } catch(err) {
1170 | log("try loadSettingsFromFile: "+err);
1171 | return null;
1172 | }
1173 | }
1174 |
1175 | // set the filename of the post image (site name + image id)
1176 | async function getFileName(strSiteName, strID) {
1177 | const strWidgetTitle = await PARAM_WIDGET_TITLE.replace(/[^a-zA-Z1-9]+/g, "").toLowerCase();
1178 | strSiteName = await strSiteName.replace(/[^a-zA-Z1-9]+/g, "").toLowerCase();
1179 | return strWidgetTitle+"-"+strSiteName+"-"+strID;
1180 | }
1181 |
1182 | // load post image from file path
1183 | async function loadLocalImage(imgPath) {
1184 | const localFM = FileManager.local();
1185 |
1186 | if (localFM.fileExists(imgPath)) {
1187 | return await localFM.readImage(imgPath);
1188 | } else {
1189 | const fontSym = await loadFont(CONF_FONT_HEADLINE, "regular", 60);
1190 | const sym = SFSymbol.named("square.slash");
1191 | sym.applyFont(fontSym);
1192 | return sym.image;
1193 | }
1194 | }
1195 |
1196 | // search for and load a local (or iCloud) background image
1197 | async function loadBGImage(imageName, optBlur) {
1198 | const localFM = FileManager.local();
1199 | let iCloudFM;
1200 | try {iCloudFM = FileManager.iCloud();} catch(err) {log("try loadBGImage iCloudFM: "+err); return "not found";}
1201 |
1202 | const docDir = localFM.documentsDirectory();
1203 | const iCloudDocDir = iCloudFM.documentsDirectory();
1204 | const bgIMGiCloudDocPath = iCloudFM.joinPath(iCloudDocDir, imageName);
1205 | const bgIMGiCloudWPPath = iCloudFM.joinPath(iCloudDocDir+"/wallpaper", imageName);
1206 | const bgIMGWPCachePath = localFM.joinPath(docDir+"/saudumm-news-widget-data/wallpaper-cache", imageName);
1207 |
1208 | if (optBlur == "true" && localFM.fileExists(bgIMGWPCachePath+"-blur")) {
1209 | return await localFM.readImage(bgIMGWPCachePath+"-blur");
1210 | } else {
1211 | if (optBlur == "true") {
1212 | if (iCloudFM.fileExists(bgIMGiCloudDocPath)) {
1213 | if (iCloudFM.isFileStoredIniCloud(bgIMGiCloudDocPath)) {await iCloudFM.downloadFileFromiCloud(bgIMGiCloudDocPath);}
1214 | let imgToBlur = await iCloudFM.readImage(bgIMGiCloudDocPath);
1215 | imgToBlur = await resizeImage(imgToBlur, 300)
1216 | imgToBlur = await blurImage(imgToBlur);
1217 | await localFM.writeImage(bgIMGWPCachePath+"-blur", imgToBlur);
1218 | return imgToBlur;
1219 | } else if (iCloudFM.fileExists(bgIMGiCloudWPPath)) {
1220 | if (iCloudFM.isFileStoredIniCloud(bgIMGiCloudWPPath)) {await iCloudFM.downloadFileFromiCloud(bgIMGiCloudWPPath);}
1221 | let imgToBlur = await iCloudFM.readImage(bgIMGiCloudWPPath);
1222 | imgToBlur = await resizeImage(imgToBlur, 300)
1223 | imgToBlur = await blurImage(imgToBlur);
1224 | await localFM.writeImage(bgIMGWPCachePath+"-blur", imgToBlur);
1225 | return imgToBlur;
1226 | } else {
1227 | return "not found";
1228 | }
1229 | } else {
1230 | if (iCloudFM.fileExists(bgIMGiCloudDocPath)) {
1231 | return await iCloudFM.readImage(bgIMGiCloudDocPath);
1232 | } else if (iCloudFM.fileExists(bgIMGiCloudWPPath)) {
1233 | return await iCloudFM.readImage(bgIMGiCloudWPPath);
1234 | } else {
1235 | return "not found";
1236 | }
1237 | }
1238 | }
1239 | }
1240 |
1241 | // check if all folders are available and create them if needed
1242 | function checkFileDirs() {
1243 | // Create new FileManager and set data dir
1244 | const localFM = FileManager.local();
1245 | const docDir = localFM.documentsDirectory();
1246 | const imgCacheDir = localFM.joinPath(docDir, "saudumm-news-widget-data/image-cache");
1247 | const imgCacheDirWP = localFM.joinPath(docDir, "saudumm-news-widget-data/wallpaper-cache");
1248 |
1249 | if (!localFM.fileExists(imgCacheDir)) {localFM.createDirectory(imgCacheDir, true);}
1250 | if (!localFM.fileExists(imgCacheDirWP)) {localFM.createDirectory(imgCacheDirWP, true);}
1251 |
1252 | let fmSettings;
1253 | try {fmSettings = FileManager.iCloud()} catch (e) {fmSettings = FileManager.local()}
1254 | try {fmSettings.documentsDirectory()} catch(e) {fmSettings = FileManager.local()}
1255 | let filePathSettings = fmSettings.documentsDirectory();
1256 | filePathSettings = fmSettings.joinPath(filePathSettings, "News-Widget-Settings");
1257 | if (!fmSettings.fileExists(filePathSettings)) {fmSettings.createDirectory(filePathSettings, true);}
1258 |
1259 | return;
1260 | }
1261 |
1262 | // cleanup post image files (if older than 7 days)
1263 | function cleanUpCache() {
1264 | const localFM = FileManager.local();
1265 | const docDir = localFM.documentsDirectory();
1266 | const widgetDir = localFM.joinPath(docDir, "saudumm-news-widget-data");
1267 | const content = localFM.listContents(widgetDir);
1268 |
1269 | if (content && content.length >= 1) {
1270 | for (i = 0; i < content.length; i++) {
1271 | if (!localFM.isDirectory(localFM.joinPath(widgetDir, content[i]))) {
1272 | const filePath = localFM.joinPath(widgetDir, content[i]);
1273 | const fileDate = localFM.creationDate(filePath);
1274 | const dateDiffHours = Math.round((Date.now()-fileDate)/1000/60/60/1);
1275 | // delete cache files older than 24 hours
1276 | if (Math.abs(dateDiffHours) > 24) {localFM.remove(filePath);}
1277 | } else if (localFM.isDirectory(localFM.joinPath(widgetDir, content[i]))) {
1278 | const subDir = localFM.joinPath(widgetDir, content[i]);
1279 | const contentSub = localFM.listContents(subDir);
1280 | for (c = 0; c < contentSub.length; c++) {
1281 | const filePath = localFM.joinPath(subDir, contentSub[c]);
1282 | const fileDate = localFM.creationDate(filePath);
1283 | const dateDiffHours = Math.round((Date.now()-fileDate)/1000/60/60/1);
1284 | if (content[i] == "image-cache") {
1285 | // delete image cache files older than 24 hours
1286 | if (Math.abs(dateDiffHours) > 24) {localFM.remove(filePath);}
1287 | }
1288 | else if (content[i] == "wallpaper-cache") {
1289 | // delete wallpaper cache files older than 2 days
1290 | if (Math.abs(dateDiffHours) > 48) {localFM.remove(filePath);}
1291 | }
1292 | }
1293 | }
1294 | }
1295 | }
1296 | return;
1297 | }
1298 |
1299 | // get the chosen font for widget texts
1300 | function loadFont(fontName, fontThickness, fontSize) {
1301 | let font = Font.boldSystemFont(fontSize);
1302 | if (fontName == "System" || fontName == "Rounded" || fontName == "Monospaced") {
1303 | switch (fontThickness) {
1304 | case "ultralight":
1305 | font = (fontName == "Rounded") ? Font.ultraLightRoundedSystemFont(fontSize) : (fontName == "Monospaced") ? Font.ultraLightMonospacedSystemFont(fontSize) : Font.ultraLightSystemFont(fontSize); break;
1306 | case "thin":
1307 | font = (fontName == "Rounded") ? Font.thinRoundedSystemFont(fontSize) : (fontName == "Monospaced") ? Font.thinMonospacedSystemFont(fontSize) : Font.thinSystemFont(fontSize); break;
1308 | case "light":
1309 | font = (fontName == "Rounded") ? Font.lightRoundedSystemFont(fontSize) : (fontName == "Monospaced") ? Font.lightMonospacedSystemFont(fontSize) : Font.lightSystemFont(fontSize); break;
1310 | case "regular":
1311 | font = (fontName == "Rounded") ? Font.regularRoundedSystemFont(fontSize) : (fontName == "Monospaced") ? Font.regularMonospacedSystemFont(fontSize) : Font.regularSystemFont(fontSize); break;
1312 | case "medium":
1313 | font = (fontName == "Rounded") ? Font.mediumRoundedSystemFont(fontSize) : (fontName == "Monospaced") ? Font.mediumMonospacedSystemFont(fontSize) : Font.mediumSystemFont(fontSize); break;
1314 | case "semibold":
1315 | font = (fontName == "Rounded") ? Font.semiboldRoundedSystemFont(fontSize) : (fontName == "Monospaced") ? Font.semiboldMonospacedSystemFont(fontSize) : Font.semiboldSystemFont(fontSize); break;
1316 | case "bold":
1317 | font = (fontName == "Rounded") ? Font.boldRoundedSystemFont(fontSize) : (fontName == "Monospaced") ? Font.boldMonospacedSystemFont(fontSize) : Font.boldSystemFont(fontSize); break;
1318 | case "heavy":
1319 | font = (fontName == "Rounded") ? Font.heavyRoundedSystemFont(fontSize) : (fontName == "Monospaced") ? Font.heavyMonospacedSystemFont(fontSize) : Font.heavySystemFont(fontSize); break;
1320 | case "black":
1321 | font = (fontName == "Rounded") ? Font.blackRoundedSystemFont(fontSize) : (fontName == "Monospaced") ? Font.blackMonospacedSystemFont(fontSize) : Font.blackSystemFont(fontSize); break;
1322 | }
1323 | } else {
1324 | font = new Font(fontName, fontSize);
1325 | }
1326 | return font;
1327 | }
1328 |
1329 | // check if there's a connection to the interwebz
1330 | async function isOnline() {
1331 | const view = new WebView();
1332 | const connection = await view.evaluateJavaScript("navigator.onLine");
1333 | return connection;
1334 | }
1335 |
1336 | // check if there's a script update available on GitHub
1337 | async function checkForUpdate(currentVersion) {
1338 | if (ONLINE) {
1339 | try {
1340 | const latestVersion = await new Request("https://raw.githubusercontent.com/Saudumm/scriptable-News-Widget/main/version.txt").loadString();
1341 | return (currentVersion.replace(/[^1-9]+/g, "") < latestVersion.replace(/[^1-9]+/g, "")) ? true : false;
1342 | } catch(err) {
1343 | log("try checkForUpdate: "+err);
1344 | return false;
1345 | }
1346 | }
1347 | }
1348 |
1349 | // check and process widget parameters
1350 | function checkWidgetParameter() {
1351 | if (args.widgetParameter) {
1352 | const aWidgetParameter = args.widgetParameter.split("|");
1353 | switch (aWidgetParameter.length) {
1354 | case 8: CONF_FONT_WIDGET_TITLE = CONF_FONT_DATE = CONF_FONT_HEADLINE = aWidgetParameter[7];
1355 | case 7: PARAM_BG_IMAGE_GRADIENT = aWidgetParameter[6];
1356 | case 6: PARAM_BG_IMAGE_BLUR = aWidgetParameter[5];
1357 | case 5: PARAM_BG_IMAGE_NAME = aWidgetParameter[4];
1358 | case 4: PARAM_SHOW_NEWS_IMAGES = aWidgetParameter[3];
1359 | case 3: PARAM_WIDGET_TITLE = aWidgetParameter[2];
1360 | case 2:
1361 | if (aWidgetParameter[1].substring(0, 4) == "http") {
1362 | PARAM_LINKS = [[aWidgetParameter[1], ""]];
1363 | } else {
1364 | SETTINGS_FILE = aWidgetParameter[1];
1365 | }
1366 | case 1:
1367 | if (aWidgetParameter[0] == "small" || aWidgetParameter[0] == "medium" || aWidgetParameter[0] == "large") {
1368 | WIDGET_SIZE = aWidgetParameter[0];
1369 | } else {
1370 | SETTINGS_FILE = aWidgetParameter[0]
1371 | }
1372 | }
1373 | }
1374 | }
1375 |
1376 | // blurs an image
1377 | async function blurImage(img) {
1378 | /*
1379 | * A big THANK YOU to Mario Klingemann for the Blur Code and Max Zeryck for the WebView Code
1380 | * code taken and modified from: https://github.com/mzeryck/Widget-Blur
1381 | * Follow @mzeryck on Twitter: https://twitter.com/mzeryck
1382 | */
1383 |
1384 | // defines the blur strength in relation to the image resolution
1385 | const blurStrength = await Math.floor((img.size.height*img.size.width)/18000/1);
1386 | if (blurStrength == 0) {blurStrength = 1;}
1387 |
1388 | const js = `
1389 | /*
1390 | StackBlur - a fast almost Gaussian Blur For Canvas
1391 | Version: 0.5
1392 | Author: Mario Klingemann
1393 | Contact: mario@quasimondo.com
1394 | Website: http://quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
1395 | Twitter: @quasimondo
1396 | In case you find this class useful - especially in commercial projects -
1397 | I am not totally unhappy for a small donation to my PayPal account
1398 | mario@quasimondo.de
1399 | Or support me on flattr:
1400 | https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript
1401 | Copyright (c) 2010 Mario Klingemann
1402 | Permission is hereby granted, free of charge, to any person
1403 | obtaining a copy of this software and associated documentation
1404 | files (the "Software"), to deal in the Software without
1405 | restriction, including without limitation the rights to use,
1406 | copy, modify, merge, publish, distribute, sublicense, and/or sell
1407 | copies of the Software, and to permit persons to whom the
1408 | Software is furnished to do so, subject to the following
1409 | conditions:
1410 | The above copyright notice and this permission notice shall be
1411 | included in all copies or substantial portions of the Software.
1412 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1413 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
1414 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1415 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
1416 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
1417 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
1418 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1419 | OTHER DEALINGS IN THE SOFTWARE.
1420 | */
1421 | var mul_table = [512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,
1422 | 454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,
1423 | 482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,
1424 | 437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,
1425 | 497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,
1426 | 320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,
1427 | 446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,
1428 | 329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,
1429 | 505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,
1430 | 399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,
1431 | 324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,
1432 | 268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,
1433 | 451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,
1434 | 385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,
1435 | 332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,
1436 | 289,287,285,282,280,278,275,273,271,269,267,265,263,261,259];
1437 |
1438 | var shg_table = [ 9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17,
1439 | 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19,
1440 | 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20,
1441 | 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21,
1442 | 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
1443 | 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22,
1444 | 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
1445 | 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23,
1446 | 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
1447 | 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
1448 | 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
1449 | 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
1450 | 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
1451 | 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
1452 | 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
1453 | 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 ];
1454 |
1455 | function stackBlurCanvasRGB(id, top_x, top_y, width, height, radius) {
1456 | if (isNaN(radius) || radius < 1) {return;}
1457 | radius |= 0;
1458 |
1459 | var canvas = document.getElementById(id);
1460 | var context = canvas.getContext("2d");
1461 | var imageData;
1462 |
1463 | try {
1464 | imageData = context.getImageData(top_x, top_y, width, height);
1465 | } catch(e) {
1466 | alert("Cannot access image");
1467 | throw new Error("unable to access image data: " + e);
1468 | }
1469 |
1470 | var pixels = imageData.data;
1471 |
1472 | var x, y, i, p, yp, yi, yw, r_sum, g_sum, b_sum,
1473 | r_out_sum, g_out_sum, b_out_sum,
1474 | r_in_sum, g_in_sum, b_in_sum,
1475 | pr, pg, pb, rbs;
1476 |
1477 | var div = radius + radius + 1;
1478 | var w4 = width << 2;
1479 | var widthMinus1 = width - 1;
1480 | var heightMinus1 = height - 1;
1481 | var radiusPlus1 = radius + 1;
1482 | var sumFactor = radiusPlus1 * (radiusPlus1 + 1) / 2 / 1;
1483 |
1484 | var stackStart = new BlurStack();
1485 | var stack = stackStart;
1486 | for (i = 1; i < div; i++) {
1487 | stack = stack.next = new BlurStack();
1488 | if (i == radiusPlus1) var stackEnd = stack;
1489 | }
1490 | stack.next = stackStart;
1491 | var stackIn = null;
1492 | var stackOut = null;
1493 |
1494 | yw = yi = 0;
1495 |
1496 | var mul_sum = mul_table[radius];
1497 | var shg_sum = shg_table[radius];
1498 |
1499 | for (y = 0; y < height; y++) {
1500 | r_in_sum = g_in_sum = b_in_sum = r_sum = g_sum = b_sum = 0;
1501 |
1502 | r_out_sum = radiusPlus1 * (pr = pixels[yi]);
1503 | g_out_sum = radiusPlus1 * (pg = pixels[yi+1]);
1504 | b_out_sum = radiusPlus1 * (pb = pixels[yi+2]);
1505 |
1506 | r_sum += sumFactor * pr;
1507 | g_sum += sumFactor * pg;
1508 | b_sum += sumFactor * pb;
1509 |
1510 | stack = stackStart;
1511 |
1512 | for (i = 0; i < radiusPlus1; i++) {
1513 | stack.r = pr;
1514 | stack.g = pg;
1515 | stack.b = pb;
1516 | stack = stack.next;
1517 | }
1518 |
1519 | for (i = 1; i < radiusPlus1; i++) {
1520 | p = yi + ((widthMinus1 < i ? widthMinus1 : i) << 2);
1521 | r_sum += (stack.r = (pr = pixels[p])) * (rbs = radiusPlus1 - i);
1522 | g_sum += (stack.g = (pg = pixels[p+1])) * rbs;
1523 | b_sum += (stack.b = (pb = pixels[p+2])) * rbs;
1524 |
1525 | r_in_sum += pr;
1526 | g_in_sum += pg;
1527 | b_in_sum += pb;
1528 |
1529 | stack = stack.next;
1530 | }
1531 |
1532 |
1533 | stackIn = stackStart;
1534 | stackOut = stackEnd;
1535 | for (x = 0; x < width; x++) {
1536 | pixels[yi] = (r_sum * mul_sum) >> shg_sum;
1537 | pixels[yi+1] = (g_sum * mul_sum) >> shg_sum;
1538 | pixels[yi+2] = (b_sum * mul_sum) >> shg_sum;
1539 |
1540 | r_sum -= r_out_sum;
1541 | g_sum -= g_out_sum;
1542 | b_sum -= b_out_sum;
1543 |
1544 | r_out_sum -= stackIn.r;
1545 | g_out_sum -= stackIn.g;
1546 | b_out_sum -= stackIn.b;
1547 |
1548 | p = (yw + ((p = x + radius + 1) < widthMinus1 ? p : widthMinus1)) << 2;
1549 |
1550 | r_in_sum += (stackIn.r = pixels[p]);
1551 | g_in_sum += (stackIn.g = pixels[p+1]);
1552 | b_in_sum += (stackIn.b = pixels[p+2]);
1553 |
1554 | r_sum += r_in_sum;
1555 | g_sum += g_in_sum;
1556 | b_sum += b_in_sum;
1557 |
1558 | stackIn = stackIn.next;
1559 |
1560 | r_out_sum += (pr = stackOut.r);
1561 | g_out_sum += (pg = stackOut.g);
1562 | b_out_sum += (pb = stackOut.b);
1563 |
1564 | r_in_sum -= pr;
1565 | g_in_sum -= pg;
1566 | b_in_sum -= pb;
1567 |
1568 | stackOut = stackOut.next;
1569 | yi += 4;
1570 | }
1571 | yw += width;
1572 | }
1573 |
1574 | for (x = 0; x < width; x++) {
1575 | g_in_sum = b_in_sum = r_in_sum = g_sum = b_sum = r_sum = 0;
1576 |
1577 | yi = x << 2;
1578 | r_out_sum = radiusPlus1 * (pr = pixels[yi]);
1579 | g_out_sum = radiusPlus1 * (pg = pixels[yi+1]);
1580 | b_out_sum = radiusPlus1 * (pb = pixels[yi+2]);
1581 |
1582 | r_sum += sumFactor * pr;
1583 | g_sum += sumFactor * pg;
1584 | b_sum += sumFactor * pb;
1585 |
1586 | stack = stackStart;
1587 |
1588 | for (i = 0; i < radiusPlus1; i++) {
1589 | stack.r = pr;
1590 | stack.g = pg;
1591 | stack.b = pb;
1592 | stack = stack.next;
1593 | }
1594 |
1595 | yp = width;
1596 |
1597 | for (i = 1; i <= radius; i++) {
1598 | yi = (yp + x) << 2;
1599 |
1600 | r_sum += (stack.r = (pr = pixels[yi])) * (rbs = radiusPlus1 - i);
1601 | g_sum += (stack.g = (pg = pixels[yi+1])) * rbs;
1602 | b_sum += (stack.b = (pb = pixels[yi+2])) * rbs;
1603 |
1604 | r_in_sum += pr;
1605 | g_in_sum += pg;
1606 | b_in_sum += pb;
1607 |
1608 | stack = stack.next;
1609 |
1610 | if (i < heightMinus1) {yp += width;}
1611 | }
1612 |
1613 | yi = x;
1614 | stackIn = stackStart;
1615 | stackOut = stackEnd;
1616 | for (y = 0; y < height; y++) {
1617 | p = yi << 2;
1618 | pixels[p] = (r_sum * mul_sum) >> shg_sum;
1619 | pixels[p+1] = (g_sum * mul_sum) >> shg_sum;
1620 | pixels[p+2] = (b_sum * mul_sum) >> shg_sum;
1621 |
1622 | r_sum -= r_out_sum;
1623 | g_sum -= g_out_sum;
1624 | b_sum -= b_out_sum;
1625 |
1626 | r_out_sum -= stackIn.r;
1627 | g_out_sum -= stackIn.g;
1628 | b_out_sum -= stackIn.b;
1629 |
1630 | p = (x + (((p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1) * width)) << 2;
1631 |
1632 | r_sum += (r_in_sum += (stackIn.r = pixels[p]));
1633 | g_sum += (g_in_sum += (stackIn.g = pixels[p+1]));
1634 | b_sum += (b_in_sum += (stackIn.b = pixels[p+2]));
1635 |
1636 | stackIn = stackIn.next;
1637 |
1638 | r_out_sum += (pr = stackOut.r);
1639 | g_out_sum += (pg = stackOut.g);
1640 | b_out_sum += (pb = stackOut.b);
1641 |
1642 | r_in_sum -= pr;
1643 | g_in_sum -= pg;
1644 | b_in_sum -= pb;
1645 |
1646 | stackOut = stackOut.next;
1647 |
1648 | yi += width;
1649 | }
1650 | }
1651 |
1652 | context.putImageData(imageData, top_x, top_y);
1653 | }
1654 |
1655 | function BlurStack() {
1656 | this.r = 0;
1657 | this.g = 0;
1658 | this.b = 0;
1659 | this.a = 0;
1660 | this.next = null;
1661 | }
1662 |
1663 | // Set up the canvas
1664 | const img = document.getElementById("blurImg");
1665 | const canvas = document.getElementById("mainCanvas");
1666 | const w = img.width;
1667 | const h = img.height;
1668 | canvas.style.width = w + "px";
1669 | canvas.style.height = h + "px";
1670 | canvas.width = w;
1671 | canvas.height = h;
1672 | const context = canvas.getContext("2d");
1673 | context.clearRect(0, 0, w, h);
1674 | context.drawImage(img, 0, 0, w, h);
1675 |
1676 | // Get the image data from the context
1677 | var imageData = context.getImageData(0,0,w,h);
1678 | // Draw over the old image
1679 | context.putImageData(imageData,0,0);
1680 | // Blur the image
1681 | stackBlurCanvasRGB("mainCanvas", 0, 0, w, h, ${blurStrength});
1682 | // Return a base64 representation
1683 | canvas.toDataURL();
1684 | `;
1685 |
1686 | // Convert the images and create the HTML
1687 | let blurImgData = await Data.fromPNG(img).toBase64String();
1688 | let html = `
`;
1689 |
1690 | // Make the web view and get its return value
1691 | let view = await new WebView();
1692 | await view.loadHTML(html);
1693 | let returnValue = await view.evaluateJavaScript(js);
1694 |
1695 | // Remove the data type from the string and convert to data
1696 | let imageDataString = await returnValue.slice(22);
1697 | let imageData = await Data.fromBase64String(imageDataString);
1698 |
1699 | // Convert to image before returning
1700 | let imageFromData = await Image.fromData(imageData);
1701 | return imageFromData;
1702 | }
1703 |
1704 | // resize the background image
1705 | async function resizeImage(img, maxShortSide) {
1706 | let imgHeight = await img.size.height;
1707 | let imgWidth = await img.size.width;
1708 | let imgShortSide = await Math.min(imgHeight, imgWidth);
1709 | let resizeFactor = await Math.round(imgShortSide/maxShortSide/1);
1710 |
1711 | const js = `
1712 | // Set up the canvas
1713 | const img = document.getElementById("resImg");
1714 | const canvas = document.getElementById("mainCanvas");
1715 | const w = img.width;
1716 | const h = img.height;
1717 | const maxW = Math.round(w / ${resizeFactor} / 1);
1718 | const maxH = Math.round(h / ${resizeFactor} / 1);
1719 | canvas.style.width = w + "px";
1720 | canvas.style.height = h + "px";
1721 | canvas.width = maxW;
1722 | canvas.height = maxH;
1723 | const context = canvas.getContext("2d");
1724 | context.clearRect(0, 0, w, h);
1725 | context.drawImage(img, 0, 0, maxW, maxH);
1726 |
1727 | // Get the image data from the context
1728 | var imageData = context.getImageData(0,0,w,h);
1729 | // Draw over the old image
1730 | context.putImageData(imageData,0,0);
1731 | // Return a base64 representation
1732 | canvas.toDataURL();
1733 | `;
1734 |
1735 | // Convert the images and create the HTML
1736 | let resImgData = await Data.fromPNG(img).toBase64String();
1737 | let html = `
`;
1738 |
1739 | // Make the web view and get its return value
1740 | let view = await new WebView();
1741 | await view.loadHTML(html);
1742 | let returnValue = await view.evaluateJavaScript(js);
1743 |
1744 | // Remove the data type from the string and convert to data
1745 | let imageDataString = await returnValue.slice(22);
1746 | let imageData = await Data.fromBase64String(imageDataString);
1747 |
1748 | // Convert to image before returning
1749 | let imageFromData = await Image.fromData(imageData);
1750 |
1751 | return imageFromData;
1752 | }
1753 |
1754 | // crop an image to a square
1755 | async function cropImageToSquare(img) {
1756 | const imgHeight = await img.size.height;
1757 | const imgWidth = await img.size.width;
1758 |
1759 | let imgShortSide = await Math.min(imgHeight, imgWidth);
1760 | let imgLongSide = await Math.max(imgHeight, imgWidth);
1761 |
1762 | if (imgShortSide != imgLongSide) {
1763 | let imgCropTotal = await (imgLongSide - imgShortSide);
1764 | let imgCropSide = await Math.floor(imgCropTotal / 2 / 1);
1765 |
1766 | let rect;
1767 | switch (imgShortSide) {
1768 | case imgHeight: rect = await new Rect(imgCropSide, 0, imgShortSide, imgShortSide); break;
1769 | case imgWidth: rect = await new Rect(0, imgCropSide, imgShortSide, imgShortSide); break;
1770 | }
1771 |
1772 | let draw = await new DrawContext();
1773 | draw.size = await new Size(rect.width, rect.height);
1774 |
1775 | await draw.drawImageAtPoint(img, new Point(-rect.x, -rect.y));
1776 | img = await draw.getImage();
1777 | }
1778 | return img;
1779 | }
1780 |
1781 | // settings wizard
1782 | async function settingsWizard() {
1783 | try {
1784 | let fm;
1785 | try {fm = FileManager.iCloud()} catch (err) {fm = FileManager.local()}
1786 | try {fm.documentsDirectory()} catch(err) {fm = FileManager.local()}
1787 | let filePath = fm.documentsDirectory();
1788 | filePath = fm.joinPath(filePath, "News-Widget-Settings")
1789 |
1790 | let settingsFileName = "widget-settings.txt";
1791 | let jsonData;
1792 |
1793 | const alAddEdit = await _createNewAlert("Welcome to News Widget Settings Wizard\nDo you want to create a new Settings File or edit an exisiting file?");
1794 | alAddEdit.addAction("Create New File");
1795 | alAddEdit.addAction("Edit Existing File");
1796 | alAddEdit.addAction("Delete Existing File");
1797 | alAddEdit.addCancelAction("Cancel");
1798 |
1799 | switch (await alAddEdit.presentSheet()) {
1800 | case 0: jsonData = await _getStandardSettings(); break;
1801 | case 1:
1802 | const settingsContent = fm.listContents(filePath)
1803 | settingsContent.sort();
1804 | const alLoad = await _createNewAlert("Select which Settings File you want to edit:");
1805 | if (settingsContent && settingsContent.length > 0) {
1806 | for (let iLoad = 0; iLoad < settingsContent.length; iLoad++) {alLoad.addAction(settingsContent[iLoad]);}
1807 | alLoad.addCancelAction("Cancel");
1808 | const answerLoad = await alLoad.presentSheet();
1809 | if (answerLoad > -1) {
1810 | settingsFileName = settingsContent[answerLoad]
1811 | const filePathLoad = fm.joinPath(filePath, settingsFileName);
1812 | if (fm.fileExists(filePathLoad)) {
1813 | if (fm.isFileStoredIniCloud(filePathLoad)) {await fm.downloadFileFromiCloud(filePathLoad);}
1814 | jsonData = await JSON.parse(fm.readString(filePathLoad));
1815 | }
1816 | }
1817 | }
1818 | break;
1819 | case 2:
1820 | const settingsContentDel = fm.listContents(filePath)
1821 | const alDel = await _createNewAlert("Select which Settings File you want to delete:");
1822 | if (settingsContentDel && settingsContentDel.length > 0) {
1823 | for (let iDel = 0; iDel < settingsContentDel.length; iDel++) {alDel.addAction(settingsContentDel[iDel]);}
1824 | alDel.addCancelAction("Cancel");
1825 | const answerDel = await alDel.presentSheet();
1826 | if (answerDel > -1) {
1827 | const settingsFileNameDel = settingsContentDel[answerDel]
1828 | const filePathDel = fm.joinPath(filePath, settingsFileNameDel);
1829 | if (fm.fileExists(filePathDel)) {
1830 | if (fm.isFileStoredIniCloud(filePathDel)) {await fm.downloadFileFromiCloud(filePathDel);}
1831 | const alDelConfirm = await _createNewAlert("Are you sure you want to delete "+settingsFileNameDel+"?");
1832 | alDelConfirm.addAction("Yes");
1833 | alDelConfirm.addAction("No");
1834 | switch (await alDelConfirm.presentSheet()) {
1835 | case 0:
1836 | fm.remove(filePathDel);
1837 | const alDelOK = await _createNewAlert("File "+settingsFileNameDel+" deleted!");
1838 | alDelOK.addAction("OK");
1839 | await alDelOK.presentSheet();
1840 | break;
1841 | case 1: return await settingsWizard();
1842 | }
1843 | }
1844 | }
1845 | }
1846 | return await settingsWizard();
1847 | case -1: return null;
1848 | }
1849 |
1850 | if (jsonData !== undefined) {
1851 | await createTable();
1852 | } else {
1853 | const alErr = await _createNewAlert("Couldn't load Settings Data. Please try again.");
1854 | alErr.addAction("OK");
1855 | await alErr.presentSheet();
1856 | return;
1857 | }
1858 |
1859 | async function createTable() {
1860 | const jsonKeys = Object.keys(jsonData);
1861 | const translate = _translateSettings();
1862 |
1863 | const tblSettings = new UITable();
1864 | tblSettings.showSeparators = true
1865 | await _reCreateRows();
1866 | await tblSettings.present(true);
1867 | return;
1868 |
1869 | // Create or recreate all Rows
1870 | async function _reCreateRows() {
1871 | const rowTitle = new UITableRow();
1872 | rowTitle.addText("Tap on the Settings to edit their values!\n\nTap \"SAVE\" when you're done").centerAligned();
1873 | rowTitle.height = 90;
1874 | tblSettings.addRow(rowTitle);
1875 |
1876 | const rowSave = new UITableRow();
1877 | rowSave.addText("SAVE").centerAligned();
1878 | rowSave.backgroundColor = Color.blue();
1879 | rowSave.height = 50;
1880 | rowSave.dismissOnSelect = false;
1881 | rowSave.onSelect = async () => {
1882 | let isWritten = await _saveSettings();
1883 | if (isWritten == true) {
1884 | let alDone = await _createNewAlert("Settings File successfully saved!\nYou can now close the Settings Wizard (Top Left) and configure\n\n"+settingsFileName+"\n\nas a Widget Parameter or in the News Widget Code.");
1885 | alDone.addAction("OK");
1886 | await alDone.presentAlert();
1887 | return;
1888 | } else {
1889 | let alDone = await _createNewAlert("No Settings File saved.");
1890 | alDone.addAction("OK");
1891 | await alDone.presentAlert();
1892 | return;
1893 | }
1894 | }
1895 | tblSettings.addRow(rowSave);
1896 |
1897 | let rowSpacer = new UITableRow();
1898 | rowSpacer.height = 30;
1899 | tblSettings.addRow(rowSpacer);
1900 |
1901 | let rowBGColor = Color.dynamic(new Color("#e3e3e1"),new Color("#1c1c1e"));
1902 |
1903 | for (let i = 0; i < jsonKeys.length; i++) {
1904 | let rowSetting = new UITableRow()
1905 | rowSetting.height = 70;
1906 | rowSetting.dismissOnSelect = false;
1907 |
1908 | let rowTitleTXT = translate[jsonKeys[i]];
1909 |
1910 | // color every second row
1911 | if (i%2 != 0) {rowSetting.backgroundColor = rowBGColor;}
1912 |
1913 | let rowTXT;
1914 | switch (jsonKeys[i].toString()) {
1915 | case "CHECK_FOR_SCRIPT_UPDATE":
1916 | case "CONF_LARGE_WIDGET_MAX_NEWS":
1917 | case "CONF_12_HOUR":
1918 | case "CONF_BG_GRADIENT":
1919 | case "CONF_FONT_SIZE_WIDGET_TITLE":
1920 | case "CONF_FONT_SIZE_DATE":
1921 | case "CONF_FONT_SIZE_HEADLINE":
1922 | rowTXT = jsonKeys[i].toString() + " = " + jsonData[jsonKeys[i]].toString(); break;
1923 | case "PARAM_WIDGET_TITLE":
1924 | case "PARAM_BG_IMAGE_NAME":
1925 | case "PARAM_BG_IMAGE_BLUR":
1926 | case "PARAM_BG_IMAGE_GRADIENT":
1927 | case "PARAM_SHOW_NEWS_IMAGES":
1928 | case "CONF_DISPLAY_NEWS":
1929 | case "CONF_DATE_TIME_LOCALE":
1930 | case "CONF_FONT_WIDGET_TITLE":
1931 | case "CONF_FONT_WEIGHT_WIDGET_TITLE":
1932 | case "CONF_FONT_DATE":
1933 | case "CONF_FONT_WEIGHT_DATE":
1934 | case "CONF_FONT_HEADLINE":
1935 | case "CONF_FONT_WEIGHT_HEADLINE":
1936 | rowTXT = jsonKeys[i].toString() + " = \"" + jsonData[jsonKeys[i]].toString() + "\"";
1937 | break;
1938 | case "PARAM_LINKS":
1939 | if (jsonData[jsonKeys[i]].length >= 1) {
1940 | let strWebsite = "";
1941 | for (let cArr = 0; cArr < jsonData[jsonKeys[i]].length; cArr++) {
1942 | strWebsite += "[\""+jsonData[jsonKeys[i]][cArr][0]+"\", \""+jsonData[jsonKeys[i]][cArr][1]+"\"],\n";
1943 | }
1944 | rowTXT = strWebsite.slice(0, -2);
1945 | rowSetting.height = 70+(15*jsonData[jsonKeys[i]].length);
1946 | }
1947 | break;
1948 | case "CONF_BG_COLOR":
1949 | case "CONF_BG_GRADIENT_COLOR_TOP":
1950 | case "CONF_BG_GRADIENT_COLOR_BTM":
1951 | case "CONF_BG_GRADIENT_OVERLAY_TOP":
1952 | case "CONF_BG_GRADIENT_OVERLAY_BTM":
1953 | case "CONF_FONT_COLOR_WIDGET_TITLE":
1954 | case "CONF_FONT_COLOR_DATE":
1955 | case "CONF_FONT_COLOR_HEADLINE":
1956 | if (typeof jsonData[jsonKeys[i]] === "object") {
1957 | let height = 75;
1958 | let strWebsite = jsonKeys[i].toString() + ":\n";
1959 | if (jsonData[jsonKeys[i]].lightMode !== undefined) {strWebsite += "lightMode = \""+jsonData[jsonKeys[i]].lightMode+"\"\n"; height += 15;}
1960 | if (jsonData[jsonKeys[i]].lightModeAlpha !== undefined) {strWebsite += "lightModeAlpha = "+jsonData[jsonKeys[i]].lightModeAlpha+"\n"; height += 15;}
1961 | if (jsonData[jsonKeys[i]].darkMode !== undefined) {strWebsite += "darkMode = \""+jsonData[jsonKeys[i]].darkMode+"\"\n"; height += 15;}
1962 | if (jsonData[jsonKeys[i]].darkModeAlpha !== undefined) {strWebsite += "darkModeAlpha = "+jsonData[jsonKeys[i]].darkModeAlpha+"\n"; height += 15;}
1963 | rowSetting.height = height;
1964 | rowTXT = strWebsite.slice(0, -1);
1965 | }
1966 | break;
1967 | default: rowTXT = jsonData[jsonKeys[i]].toString(); break;
1968 | }
1969 | rowSetting.addText(rowTitleTXT, rowTXT)
1970 | rowSetting.onSelect = async (number) => {
1971 | await _showMessage(number);
1972 | await tblSettings.removeAllRows();
1973 | await _reCreateRows();
1974 | await tblSettings.reload();
1975 | }
1976 | tblSettings.addRow(rowSetting);
1977 | }
1978 | }
1979 | }
1980 |
1981 | /* === Settings Wizard internal functions === */
1982 | async function _saveSettings() {
1983 | let alertSave = await _createNewAlert("Enter the Filename of your Settings File including the Extension (.txt)");
1984 | alertSave.addTextField("filename.txt", settingsFileName);
1985 | alertSave.addAction("Save");
1986 | alertSave.addCancelAction("Cancel");
1987 | switch (await alertSave.presentAlert()) {
1988 | case 0:
1989 | if (alertSave.textFieldValue(0).length > 0 && alertSave.textFieldValue(0).slice(-4) == ".txt") {
1990 | settingsFileName = alertSave.textFieldValue(0);
1991 | settingsFileName = settingsFileName.replaceAll(/[\?\|&;\$%@"<>\(\)\+,]/g, "");
1992 | let filePathWrite = fm.joinPath(filePath, settingsFileName);
1993 | if (fm.fileExists(filePathWrite)) {
1994 | let alertOverwrite = await _createNewAlert("The File \""+settingsFileName+"\" already exists.\nDo you want to overwrite the File?");
1995 | alertOverwrite.addAction("No");
1996 | alertOverwrite.addAction("Yes");
1997 | switch (await alertOverwrite.presentAlert()) {
1998 | case 0: return false;
1999 | case 1: await fm.writeString(filePathWrite, JSON.stringify(jsonData)); return true;
2000 | }
2001 | } else {
2002 | await fm.writeString(filePathWrite, JSON.stringify(jsonData));
2003 | return true;
2004 | }
2005 | }
2006 | break;
2007 | case -1: return false;
2008 | }
2009 | }
2010 |
2011 | async function _showMessage(rowID) {
2012 | let al = await _createNewAlert("");
2013 | switch (rowID) {
2014 | case 3: // CHECK_FOR_SCRIPT_UPDATE
2015 | al.message = "Do you want to automatically search for Script Updates to News Widget?\n(Default: Yes)"
2016 | al.addAction("Yes");
2017 | al.addAction("No");
2018 | al.addCancelAction("Cancel");
2019 | switch (await al.presentSheet()) {
2020 | case 0: jsonData["CHECK_FOR_SCRIPT_UPDATE"] = true; break;
2021 | case 1: jsonData["CHECK_FOR_SCRIPT_UPDATE"] = false; break;
2022 | case -1: return;
2023 | }
2024 | break;
2025 | case 4: // PARAM_LINKS
2026 | await _editParamLinks()
2027 | break;
2028 | case 5: // PARAM_WIDGET_TITLE
2029 | al.message = "Enter the Title of the Widget\nThe Title is displayed at the top of the Widget\n(Default: News Widget)";
2030 | al.addTextField("example: News Widget", jsonData["PARAM_WIDGET_TITLE"].toString());
2031 | al.addAction("OK");
2032 | al.addCancelAction("Cancel");
2033 | switch (await al.presentAlert()) {
2034 | case 0:
2035 | if (al.textFieldValue(0).length > 0) {jsonData["PARAM_WIDGET_TITLE"] = al.textFieldValue(0);}
2036 | break;
2037 | case -1: return;
2038 | }
2039 | break;
2040 | case 6: // PARAM_BG_IMAGE_NAME
2041 | al.message = "Enter the Filename of the image you want to use as a Widget Background\n(Default: none)";
2042 | al.addTextField("example: image.jpg", jsonData["PARAM_BG_IMAGE_NAME"].toString());
2043 | al.addAction("OK");
2044 | al.addCancelAction("Cancel");
2045 | switch (await al.presentAlert()) {
2046 | case 0:
2047 | if (al.textFieldValue(0).length > 0) {jsonData["PARAM_BG_IMAGE_NAME"] = al.textFieldValue(0);} else {jsonData["PARAM_BG_IMAGE_NAME"] = "none"}
2048 | break;
2049 | case -1: return;
2050 | }
2051 | break;
2052 | case 7: // PARAM_BG_IMAGE_BLUR
2053 | al.message = "Do you want Widget Background Images to be blurred?\n(Default: Yes)"
2054 | al.addAction("Yes");
2055 | al.addAction("No");
2056 | al.addCancelAction("Cancel");
2057 | switch (await al.presentSheet()) {
2058 | case 0: jsonData["PARAM_BG_IMAGE_BLUR"] = "true"; break;
2059 | case 1: jsonData["PARAM_BG_IMAGE_BLUR"] = "false"; break;
2060 | case -1: return;
2061 | }
2062 | break;
2063 | case 8: // PARAM_BG_IMAGE_GRADIENT
2064 | al.message = "Do you want to display a Color Gradient over the Background Image?\nThis can improve legibility of text\n(Default: Yes)"
2065 | al.addAction("Yes");
2066 | al.addAction("No");
2067 | al.addCancelAction("Cancel");
2068 | switch (await al.presentSheet()) {
2069 | case 0: jsonData["PARAM_BG_IMAGE_GRADIENT"] = "true"; break;
2070 | case 1: jsonData["PARAM_BG_IMAGE_GRADIENT"] = "false"; break;
2071 | case -1: return;
2072 | }
2073 | break;
2074 | case 9: // PARAM_SHOW_NEWS_IMAGES
2075 | al.message = "Do you want to display Images next to the News?\n(Default: Yes)"
2076 | al.addAction("Yes");
2077 | al.addAction("No");
2078 | al.addCancelAction("Cancel");
2079 | switch (await al.presentSheet()) {
2080 | case 0: jsonData["PARAM_SHOW_NEWS_IMAGES"] = "true"; break;
2081 | case 1: jsonData["PARAM_SHOW_NEWS_IMAGES"] = "false"; break;
2082 | case -1: return;
2083 | }
2084 | break;
2085 | case 10: // CONF_LARGE_WIDGET_MAX_NEWS
2086 | al.message = "Do you want to display a max. number of 4 (like iOS News Widget) or 5 News in a Large Widget?\n\n(Default: Max. 5 News)"
2087 | al.addAction("Max. 4 News");
2088 | al.addAction("Max. 5 News");
2089 | al.addCancelAction("Cancel");
2090 | switch (await al.presentSheet()) {
2091 | case 0: jsonData["CONF_LARGE_WIDGET_MAX_NEWS"] = 4; break;
2092 | case 1: jsonData["CONF_LARGE_WIDGET_MAX_NEWS"] = 5; break;
2093 | case -1: return;
2094 | }
2095 | break;
2096 | case 11: // CONF_DISPLAY_NEWS
2097 | al.message = "Do you want to prioritize seeing News from all Websites (like iOS News Widget) or prioritize sorting all News by Date?\n(Default: Prioritize Websites)"
2098 | al.addAction("Prioritize Websites");
2099 | al.addAction("Prioritize Date");
2100 | al.addCancelAction("Cancel");
2101 | switch (await al.presentSheet()) {
2102 | case 0: jsonData["CONF_DISPLAY_NEWS"] = "websites"; break;
2103 | case 1: jsonData["CONF_DISPLAY_NEWS"] = "date"; break;
2104 | case -1: return;
2105 | }
2106 | break;
2107 | case 12: // CONF_DATE_TIME_LOCALE
2108 | al.message = "Enter the Region you want to use for the Date and Time\n(e.g. en-US, de-DE, ko)\n(Default: default)";
2109 | al.addTextField("example: en-US", jsonData["CONF_DATE_TIME_LOCALE"].toString());
2110 | al.addAction("OK");
2111 | al.addCancelAction("Cancel");
2112 | switch (await al.presentAlert()) {
2113 | case 0:
2114 | if (al.textFieldValue(0).length > 0) {jsonData["CONF_DATE_TIME_LOCALE"] = al.textFieldValue(0);} else {jsonData["PARAM_BG_IMAGE_NAME"] = "default"}
2115 | break;
2116 | case -1: return;
2117 | }
2118 | break;
2119 | case 13: // CONF_12_HOUR
2120 | al.message = "Do you want to display the TIME\nin 12 or 24 hour format?\n(Default: 24 Hour)"
2121 | al.addAction("12 Hour");
2122 | al.addAction("24 Hour");
2123 | al.addCancelAction("Cancel");
2124 | switch (await al.presentSheet()) {
2125 | case 0: jsonData["CONF_12_HOUR"] = true; break;
2126 | case 1: jsonData["CONF_12_HOUR"] = false; break;
2127 | case -1: return;
2128 | }
2129 | break;
2130 | case 14: // CONF_BG_COLOR
2131 | al.message = "Enter the Widget Background Color (HEX)\n(Default Light Mode: #fefefe)\n(Default Dark Mode: #2c2c2e)\n\nFirst Value is used in iOS Light Mode\nSecond Value is used in iOS Dark Mode";
2132 | al.addTextField("example: #fefefe", jsonData["CONF_BG_COLOR"].lightMode.toString());
2133 | al.addTextField("example: #2c2c2e", jsonData["CONF_BG_COLOR"].darkMode.toString());
2134 | al.addAction("OK");
2135 | al.addCancelAction("Cancel");
2136 | let wBGColorLight, wBGColorDark;
2137 | switch (await al.presentAlert()) {
2138 | case 0:
2139 | if (al.textFieldValue(0).length == 6 || al.textFieldValue(0).length == 7) {
2140 | wBGColorLight = (al.textFieldValue(0).substring(0,1) == "#") ? al.textFieldValue(0) : "#"+al.textFieldValue(0)
2141 | if (/^#([0-9A-F]{3}){1,2}$/i.test(wBGColorLight)) {jsonData["CONF_BG_COLOR"].lightMode = wBGColorLight;}
2142 | }
2143 | if (al.textFieldValue(1).length == 6 || al.textFieldValue(1).length == 7) {
2144 | wBGColorDark = (al.textFieldValue(1).substring(0,1) == "#") ? al.textFieldValue(1) : "#"+al.textFieldValue(1)
2145 | if (/^#([0-9A-F]{3}){1,2}$/i.test(wBGColorDark)) {jsonData["CONF_BG_COLOR"].darkMode = wBGColorDark;}
2146 | }
2147 | break;
2148 | case -1: return;
2149 | }
2150 | break;
2151 | case 15: // CONF_BG_GRADIENT
2152 | al.message = "Do you want to use a Widget Background Color Gradient instead of a Solid Color? (Only active if no Background Image is displayed)\n(Default: No)"
2153 | al.addAction("Yes");
2154 | al.addAction("No");
2155 | al.addCancelAction("Cancel");
2156 | switch (await al.presentSheet()) {
2157 | case 0: jsonData["CONF_BG_GRADIENT"] = true; break;
2158 | case 1: jsonData["CONF_BG_GRADIENT"] = false; break;
2159 | case -1: return;
2160 | }
2161 | break;
2162 | case 16: // CONF_BG_GRADIENT_COLOR_TOP
2163 | al.message = "Enter the Widget Background Gradient Top Color (HEX)\n(Default Light Mode: #fefefe)\n(Default Dark Mode: #000000)\n\nFirst Value is used in iOS Light Mode\nSecond Value is used in iOS Dark Mode";
2164 | al.addTextField("example: #fefefe", jsonData["CONF_BG_GRADIENT_COLOR_TOP"].lightMode.toString());
2165 | al.addTextField("example: #000000", jsonData["CONF_BG_GRADIENT_COLOR_TOP"].darkMode.toString());
2166 | al.addAction("OK");
2167 | al.addCancelAction("Cancel");
2168 | let wBGGTopColorLight, wBGGTopColorDark;
2169 | switch (await al.presentAlert()) {
2170 | case 0:
2171 | if (al.textFieldValue(0).length == 6 || al.textFieldValue(0).length == 7) {
2172 | wBGGTopColorLight = (al.textFieldValue(0).substring(0,1) == "#") ? al.textFieldValue(0) : "#"+al.textFieldValue(0)
2173 | if (/^#([0-9A-F]{3}){1,2}$/i.test(wBGGTopColorLight)) {jsonData["CONF_BG_GRADIENT_COLOR_TOP"].lightMode = wBGGTopColorLight;}
2174 | }
2175 | if (al.textFieldValue(1).length == 6 || al.textFieldValue(1).length == 7) {
2176 | wBGGTopColorDark = (al.textFieldValue(1).substring(0,1) == "#") ? al.textFieldValue(1) : "#"+al.textFieldValue(1)
2177 | if (/^#([0-9A-F]{3}){1,2}$/i.test(wBGGTopColorDark)) {jsonData["CONF_BG_GRADIENT_COLOR_TOP"].darkMode = wBGGTopColorDark;}
2178 | }
2179 | break;
2180 | case -1: return;
2181 | }
2182 | break;
2183 | case 17: // CONF_BG_GRADIENT_COLOR_BTM
2184 | al.message = "Enter the Widget Background Gradient Bottom Color (HEX)\n(Default Light Mode:#cccccc)\n(Default Dark Mode: #2c2c2e)\n\nFirst Value is used in iOS Light Mode\nSecond Value is used in iOS Dark Mode";
2185 | al.addTextField("example: #cccccc", jsonData["CONF_BG_GRADIENT_COLOR_BTM"].lightMode.toString());
2186 | al.addTextField("example: #2c2c2e", jsonData["CONF_BG_GRADIENT_COLOR_BTM"].darkMode.toString());
2187 | al.addAction("OK");
2188 | al.addCancelAction("Cancel");
2189 | let wBGGBtmColorLight, wBGGBtmColorDark;
2190 | switch (await al.presentAlert()) {
2191 | case 0:
2192 | if (al.textFieldValue(0).length == 6 || al.textFieldValue(0).length == 7) {
2193 | wBGGBtmColorLight = (al.textFieldValue(0).substring(0,1) == "#") ? al.textFieldValue(0) : "#"+al.textFieldValue(0)
2194 | if (/^#([0-9A-F]{3}){1,2}$/i.test(wBGGBtmColorLight)) {jsonData["CONF_BG_GRADIENT_COLOR_BTM"].lightMode = wBGGBtmColorLight;}
2195 | }
2196 | if (al.textFieldValue(1).length == 6 || al.textFieldValue(1).length == 7) {
2197 | wBGGBtmColorDark = (al.textFieldValue(1).substring(0,1) == "#") ? al.textFieldValue(1) : "#"+al.textFieldValue(1)
2198 | if (/^#([0-9A-F]{3}){1,2}$/i.test(wBGGBtmColorDark)) {jsonData["CONF_BG_GRADIENT_COLOR_BTM"].darkMode = wBGGBtmColorDark;}
2199 | }
2200 | break;
2201 | case -1: return;
2202 | }
2203 | break;
2204 | case 18: // CONF_BG_GRADIENT_OVERLAY_TOP
2205 | al.message = "Enter the BG Image Overlay Gradient Top Color (HEX)\n(Default Light Mode: #fefefe, 0.3)\n(Default Dark Mode: #2c2c2e, 0.3)\n\n1st Value is Color in iOS Light Mode\n2nd Value is Alpha in Light Mode\n3rd Value is Color in iOS Dark Mode\n4th Value is Alpha value in Dark Mode";
2206 | al.addTextField("example: #fefefe", jsonData["CONF_BG_GRADIENT_OVERLAY_TOP"].lightMode.toString());
2207 | al.addTextField("example: 0.3", jsonData["CONF_BG_GRADIENT_OVERLAY_TOP"].lightModeAlpha.toString());
2208 | al.addTextField("example: #2c2c2e", jsonData["CONF_BG_GRADIENT_OVERLAY_TOP"].darkMode.toString());
2209 | al.addTextField("example: 0.3", jsonData["CONF_BG_GRADIENT_OVERLAY_TOP"].darkModeAlpha.toString());
2210 | al.addAction("OK");
2211 | al.addCancelAction("Cancel");
2212 | let wBGGOTopColorLight, wBGGOTopColorDark;
2213 | switch (await al.presentAlert()) {
2214 | case 0:
2215 | if (al.textFieldValue(0).length == 6 || al.textFieldValue(0).length == 7) {
2216 | wBGGOTopColorLight = (al.textFieldValue(0).substring(0,1) == "#") ? al.textFieldValue(0) : "#"+al.textFieldValue(0)
2217 | if (/^#([0-9A-F]{3}){1,2}$/i.test(wBGGOTopColorLight)) {jsonData["CONF_BG_GRADIENT_OVERLAY_TOP"].lightMode = wBGGOTopColorLight;}
2218 | }
2219 | if (al.textFieldValue(1).length > 0 && parseFloat(al.textFieldValue(1)).toString() != "NaN") {jsonData["CONF_BG_GRADIENT_OVERLAY_TOP"].lightModeAlpha = parseFloat(al.textFieldValue(1));}
2220 |
2221 | if (al.textFieldValue(2).length == 6 || al.textFieldValue(2).length == 7) {
2222 | wBGGOTopColorDark = (al.textFieldValue(2).substring(0,1) == "#") ? al.textFieldValue(2) : "#"+al.textFieldValue(2)
2223 | if (/^#([0-9A-F]{3}){1,2}$/i.test(wBGGOTopColorDark)) {jsonData["CONF_BG_GRADIENT_OVERLAY_TOP"].darkMode = wBGGOTopColorDark;}
2224 | }
2225 | if (al.textFieldValue(3).length > 0 && parseFloat(al.textFieldValue(3)).toString() != "NaN") {jsonData["CONF_BG_GRADIENT_OVERLAY_TOP"].darkModeAlpha = parseFloat(al.textFieldValue(3));}
2226 | break;
2227 | case -1: return;
2228 | }
2229 | break;
2230 | case 19: // CONF_BG_GRADIENT_OVERLAY_BTM
2231 | al.message = "Enter the BG Image Overlay Gradient Bottom Color (HEX)\n(Default Light Mode: #fefefe, 1)\n(Default Dark Mode: #2c2c2e, 1)\n\n1st Value is Color in iOS Light Mode\n2nd Value is Alpha in Light Mode\n3rd Value is Color in iOS Dark Mode\n4th Value is Alpha value in Dark Mode";
2232 | al.addTextField("example: #fefefe", jsonData["CONF_BG_GRADIENT_OVERLAY_BTM"].lightMode.toString());
2233 | al.addTextField("example: 1", jsonData["CONF_BG_GRADIENT_OVERLAY_BTM"].lightModeAlpha.toString());
2234 | al.addTextField("example: #2c2c2e", jsonData["CONF_BG_GRADIENT_OVERLAY_BTM"].darkMode.toString());
2235 | al.addTextField("example: 1", jsonData["CONF_BG_GRADIENT_OVERLAY_BTM"].darkModeAlpha.toString());
2236 | al.addAction("OK");
2237 | al.addCancelAction("Cancel");
2238 | let wBGGOBtmColorLight, wBGGOBtmColorDark;
2239 | switch (await al.presentAlert()) {
2240 | case 0:
2241 | if (al.textFieldValue(0).length == 6 || al.textFieldValue(0).length == 7) {
2242 | wBGGOBtmColorLight = (al.textFieldValue(0).substring(0,1) == "#") ? al.textFieldValue(0) : "#"+al.textFieldValue(0)
2243 | if (/^#([0-9A-F]{3}){1,2}$/i.test(wBGGOBtmColorLight)) {jsonData["CONF_BG_GRADIENT_OVERLAY_BTM"].lightMode = wBGGOBtmColorLight;}
2244 | }
2245 | if (al.textFieldValue(1).length > 0 && parseFloat(al.textFieldValue(1)).toString() != "NaN") {jsonData["CONF_BG_GRADIENT_OVERLAY_BTM"].lightModeAlpha = parseFloat(al.textFieldValue(1));}
2246 |
2247 | if (al.textFieldValue(2).length == 6 || al.textFieldValue(2).length == 7) {
2248 | wBGGOBtmColorDark = (al.textFieldValue(2).substring(0,1) == "#") ? al.textFieldValue(2) : "#"+al.textFieldValue(2)
2249 | if (/^#([0-9A-F]{3}){1,2}$/i.test(wBGGOBtmColorDark)) {jsonData["CONF_BG_GRADIENT_OVERLAY_BTM"].darkMode = wBGGOBtmColorDark;}
2250 | }
2251 | if (al.textFieldValue(3).length > 0 && parseFloat(al.textFieldValue(3)).toString() != "NaN") {jsonData["CONF_BG_GRADIENT_OVERLAY_BTM"].darkModeAlpha = parseFloat(al.textFieldValue(3));}
2252 | break;
2253 | case -1: return;
2254 | }
2255 | break;
2256 | case 20: // CONF_FONT_WIDGET_TITLE
2257 | case 24: // CONF_FONT_DATE
2258 | case 28: // CONF_FONT_HEADLINE
2259 | let selTextFont = (rowID == 20) ? "Widget Title\n(Default: System)" : (rowID == 24) ? "Date and Time\n(Default: System)" : "Headline\n(Default: System)";
2260 | let selKeyFont = (rowID == 20) ? "CONF_FONT_WIDGET_TITLE" : (rowID == 24) ? "CONF_FONT_DATE" : "CONF_FONT_HEADLINE";
2261 | al.message = "Enter your Font Weight for the "+selTextFont;
2262 | al.addTextField("example: MarkerFelt-Thin", jsonData[selKeyFont].toString());
2263 | al.addAction("OK");
2264 | al.addCancelAction("Cancel");
2265 | switch (await al.presentAlert()) {
2266 | case 0:
2267 | if (al.textFieldValue(0).length > 0) {jsonData[selKeyFont] = al.textFieldValue(0);}
2268 | break;
2269 | case -1: return;
2270 | }
2271 | break;
2272 | case 21: // CONF_FONT_WEIGHT_WIDGET_TITLE
2273 | case 25: // CONF_FONT_WEIGHT_DATE
2274 | case 29: // CONF_FONT_WEIGHT_HEADLINE
2275 | let selTextWeight = (rowID == 21) ? "Widget Title\n(Default: heavy)" : (rowID == 25) ? "Date and Time\n(Default: heavy)" : "Headline\n(Default: semibold)";
2276 | let selKeyWeight = (rowID == 21) ? "CONF_FONT_WEIGHT_WIDGET_TITLE" : (rowID == 25) ? "CONF_FONT_WEIGHT_DATE" : "CONF_FONT_WEIGHT_HEADLINE";
2277 | al.message = "Select your Font Weight for the "+selTextWeight;
2278 | al.addAction("ultralight");
2279 | al.addAction("thin");
2280 | al.addAction("light");
2281 | al.addAction("regular");
2282 | al.addAction("medium");
2283 | al.addAction("semibold");
2284 | al.addAction("bold");
2285 | al.addAction("heavy");
2286 | al.addAction("black");
2287 | al.addCancelAction("Cancel");
2288 | switch (await al.presentSheet()) {
2289 | case 0: jsonData[selKeyWeight] = "ultralight"; break;
2290 | case 1: jsonData[selKeyWeight] = "thin"; break;
2291 | case 2: jsonData[selKeyWeight] = "light"; break;
2292 | case 3: jsonData[selKeyWeight] = "regular"; break;
2293 | case 4: jsonData[selKeyWeight] = "medium"; break;
2294 | case 5: jsonData[selKeyWeight] = "semibold"; break;
2295 | case 6: jsonData[selKeyWeight] = "bold"; break;
2296 | case 7: jsonData[selKeyWeight] = "heavy"; break;
2297 | case 8: jsonData[selKeyWeight] = "black"; break;
2298 | case -1: return;
2299 | }
2300 | break;
2301 | case 22: // CONF_FONT_SIZE_WIDGET_TITLE
2302 | case 26: // CONF_FONT_SIZE_DATE
2303 | case 30: // CONF_FONT_SIZE_HEADLINE
2304 | let selTextSize = (rowID == 22) ? "Widget Title\n(Default: 16)" : (rowID == 26) ? "Date and Time\n(Default: 12)" : "Headline\n(Default: 13)";
2305 | let selKeySize = (rowID == 22) ? "CONF_FONT_SIZE_WIDGET_TITLE" : (rowID == 26) ? "CONF_FONT_SIZE_DATE" : "CONF_FONT_SIZE_HEADLINE";
2306 | al.message = "Enter your Font Weight for the "+selTextSize;
2307 | al.addTextField("example: 12", jsonData[selKeySize].toString());
2308 | al.addAction("OK");
2309 | al.addCancelAction("Cancel");
2310 | switch (await al.presentAlert()) {
2311 | case 0:
2312 | if (al.textFieldValue(0).length > 0 && parseFloat(al.textFieldValue(0)).toString() != "NaN") {jsonData[selKeySize] = parseFloat(al.textFieldValue(0));}
2313 | break;
2314 | case -1: return;
2315 | }
2316 | break;
2317 | case 23: // CONF_FONT_COLOR_WIDGET_TITLE
2318 | case 27: // CONF_FONT_COLOR_DATE
2319 | case 31: // CONF_FONT_COLOR_HEADLINE
2320 | let selTextColor = (rowID == 23) ? "Widget Title\n(Default Light Mode: #000000)\n(Default Dark Mode: #fefefe)" : (rowID == 27) ? "News Date and Time\n(Default Light Mode: #8a8a8d)\n(Default Dark Mode: #9f9fa4)" : "News Headline\n(Default Light Mode: #000000)\n(Default Dark Mode: #fefefe)";
2321 | let selKeyColor = (rowID == 23) ? "CONF_FONT_COLOR_WIDGET_TITLE" : (rowID == 27) ? "CONF_FONT_COLOR_DATE" : "CONF_FONT_COLOR_HEADLINE";
2322 | al.message = "Enter the Font Color (HEX) for the "+selTextColor+"\n\nFirst Value is used in iOS Light Mode\nSecond Value is used in iOS Dark Mode";
2323 | al.addTextField("example: #8a8a8d", jsonData[selKeyColor].lightMode.toString());
2324 | al.addTextField("example: #9f9fa4", jsonData[selKeyColor].darkMode.toString());
2325 | al.addAction("OK");
2326 | al.addCancelAction("Cancel");
2327 | let fontColorLight, fontColorDark;
2328 | switch (await al.presentAlert()) {
2329 | case 0:
2330 | if (al.textFieldValue(0).length == 6 || al.textFieldValue(0).length == 7) {
2331 | fontColorLight = (al.textFieldValue(0).substring(0,1) == "#") ? al.textFieldValue(0) : "#"+al.textFieldValue(0);
2332 | if (/^#([0-9A-F]{3}){1,2}$/i.test(fontColorLight)) {jsonData[selKeyColor].lightMode = fontColorLight;}
2333 | }
2334 | if (al.textFieldValue(1).length == 6 || al.textFieldValue(1).length == 7) {
2335 | fontColorDark = (al.textFieldValue(1).substring(0,1) == "#") ? al.textFieldValue(1) : "#"+al.textFieldValue(1);
2336 | if (/^#([0-9A-F]{3}){1,2}$/i.test(fontColorDark)) {jsonData[selKeyColor].darkMode = fontColorDark;}
2337 | }
2338 | break;
2339 | case -1: return;
2340 | }
2341 | break;
2342 | }
2343 | }
2344 |
2345 | // edit websites
2346 | async function _editParamLinks() {
2347 | var tableParamLinks = new UITable();
2348 | tableParamLinks.showSeparators = true
2349 | await _reCreateRowsParamLinks();
2350 | await tableParamLinks.present(false);
2351 | return;
2352 |
2353 | async function _reCreateRowsParamLinks() {
2354 | const rowLinkTitle = new UITableRow();
2355 | rowLinkTitle.addText("Tap on the Links to edit or remove!\n\nTap on Close (Top Left)\nwhen you're done").centerAligned();
2356 | rowLinkTitle.height = 115;
2357 | rowLinkTitle.backgroundColor = Color.dynamic(new Color("#fefefe"), new Color("#000000"));
2358 | tableParamLinks.addRow(rowLinkTitle);
2359 |
2360 | let rowLinkSpacer = new UITableRow();
2361 | rowLinkSpacer.height = 30;
2362 | rowLinkSpacer.backgroundColor = Color.dynamic(new Color("#fefefe"), new Color("#000000"));
2363 | tableParamLinks.addRow(rowLinkSpacer);
2364 |
2365 | let rowLinkBGColor = Color.dynamic(new Color("#e3e3e1"), new Color("#000000"));
2366 |
2367 | for (let iLink = 0; iLink < jsonData["PARAM_LINKS"].length; iLink++) {
2368 | let rowLink = new UITableRow();
2369 | rowLink.height = 70;
2370 | rowLink.dismissOnSelect = false;
2371 |
2372 | // color every second row
2373 | if (iLink%2 != 0) {rowLink.backgroundColor = rowLinkBGColor;}
2374 |
2375 | rowLink.addText(jsonData.PARAM_LINKS[iLink][1].toString(), jsonData.PARAM_LINKS[iLink][0].toString());
2376 | rowLink.onSelect = async (number) => {
2377 | await _showLinkEdit(number-2);
2378 | await tableParamLinks.removeAllRows();
2379 | await _reCreateRowsParamLinks();
2380 | await tableParamLinks.reload();
2381 | }
2382 | tableParamLinks.addRow(rowLink);
2383 | }
2384 |
2385 | const rowAddLink = new UITableRow();
2386 | rowAddLink.addText("Add another Website").centerAligned();
2387 | rowAddLink.backgroundColor = Color.blue();
2388 | rowAddLink.height = 50;
2389 | rowAddLink.dismissOnSelect = false;
2390 | rowAddLink.onSelect = async () => {
2391 | let alAddLink = await _createNewAlert("Enter the Link and Name of a Website or RSS Feed:");
2392 | alAddLink.addTextField("Website URL (https://...)", "");
2393 | alAddLink.addTextField("Website Name", "");
2394 | alAddLink.addAction("Add");
2395 | alAddLink.addCancelAction("Cancel");
2396 |
2397 | switch (await alAddLink.presentAlert()) {
2398 | case 0:
2399 | if (alAddLink.textFieldValue(0).length > 0 && alAddLink.textFieldValue(1).length > 0) {jsonData.PARAM_LINKS.push([alAddLink.textFieldValue(0), alAddLink.textFieldValue(1)]);}
2400 | break;
2401 | }
2402 | await tableParamLinks.removeAllRows();
2403 | await _reCreateRowsParamLinks();
2404 | await tableParamLinks.reload();
2405 | }
2406 | tableParamLinks.addRow(rowAddLink);
2407 | }
2408 |
2409 | async function _showLinkEdit(linkID) {
2410 | let websiteURL = jsonData.PARAM_LINKS[linkID][0];
2411 | let websiteName = jsonData.PARAM_LINKS[linkID][1];
2412 | let alertEditLink = await _createNewAlert("Enter the Link and Name of a Website or RSS Feed:");
2413 | alertEditLink.addTextField("Website URL", websiteURL);
2414 | alertEditLink.addTextField("Website Name", websiteName);
2415 | alertEditLink.addAction("OK");
2416 | alertEditLink.addDestructiveAction("Remove");
2417 | alertEditLink.addCancelAction("Cancel");
2418 |
2419 | switch (await alertEditLink.presentAlert()) {
2420 | case 0:
2421 | if (alertEditLink.textFieldValue(0).length > 0) {jsonData.PARAM_LINKS[linkID][0] = alertEditLink.textFieldValue(0);}
2422 | if (alertEditLink.textFieldValue(1).length > 0) {jsonData.PARAM_LINKS[linkID][1] = alertEditLink.textFieldValue(1);}
2423 | break;
2424 | case 1:
2425 | let alertWantToDelete = await _createNewAlert("Are you sure you want to remove this Website?");
2426 | alertWantToDelete.addAction("No");
2427 | alertWantToDelete.addAction("Yes");
2428 | switch (await alertWantToDelete.presentAlert()) {
2429 | case 0: break;
2430 | case 1: jsonData.PARAM_LINKS.splice(linkID, 1); break;
2431 | }
2432 | break;
2433 | case -1: return;
2434 | }
2435 | return;
2436 | }
2437 | }
2438 |
2439 | // create a new alert (saving on lines and file size)
2440 | async function _createNewAlert(message) {
2441 | let newAlert = await new Alert();
2442 | newAlert.title = "News Widget Settings Wizard";
2443 | newAlert.message = message;
2444 | return newAlert;
2445 | }
2446 |
2447 | // translate the settings var name to a string
2448 | function _translateSettings() {
2449 | return {
2450 | "CHECK_FOR_SCRIPT_UPDATE": "Check For News Widget Script Updates:",
2451 | "PARAM_LINKS": "Configure Websites:",
2452 | "PARAM_WIDGET_TITLE": "Widget Title:",
2453 | "PARAM_BG_IMAGE_NAME": "Widget Background Image:",
2454 | "PARAM_BG_IMAGE_BLUR": "Blur Background Image:",
2455 | "PARAM_BG_IMAGE_GRADIENT": "Background Image Color Gradient Overlay:",
2456 | "PARAM_SHOW_NEWS_IMAGES": "Show Images Next to News:",
2457 | "CONF_LARGE_WIDGET_MAX_NEWS": "Max News in Large Widget:",
2458 | "CONF_DISPLAY_NEWS": "Prioritize News In Widget by:",
2459 | "CONF_DATE_TIME_LOCALE": "Region Settings for Date and Time:",
2460 | "CONF_12_HOUR": "12 Hour Time Format:",
2461 | "CONF_BG_COLOR": "Widget Background Color:",
2462 | "CONF_BG_GRADIENT": "Color Gradient as Widget Background:",
2463 | "CONF_BG_GRADIENT_COLOR_TOP": "Top Color of Background Gradient:",
2464 | "CONF_BG_GRADIENT_COLOR_BTM": "Bottom Color of Background Gradient:",
2465 | "CONF_BG_GRADIENT_OVERLAY_TOP": "Top Color of Image Gradient Overlay:",
2466 | "CONF_BG_GRADIENT_OVERLAY_BTM": "Bottom Color of Image Gradient Overlay:",
2467 | "CONF_FONT_WIDGET_TITLE": "Font of Widget Title:",
2468 | "CONF_FONT_WEIGHT_WIDGET_TITLE": "Font Weight of Widget Title:",
2469 | "CONF_FONT_SIZE_WIDGET_TITLE": "Font Size of Widget Title:",
2470 | "CONF_FONT_COLOR_WIDGET_TITLE": "Font Color of Widget Title:",
2471 | "CONF_FONT_DATE": "Font of News Date+Time:",
2472 | "CONF_FONT_WEIGHT_DATE": "Font Weight of News Date+Time:",
2473 | "CONF_FONT_SIZE_DATE": "Font Size of News Date+Time:",
2474 | "CONF_FONT_COLOR_DATE": "Font Color of News Date+Time:",
2475 | "CONF_FONT_HEADLINE": "Font of News Headlines:",
2476 | "CONF_FONT_WEIGHT_HEADLINE": "Font Weight of News Headlines:",
2477 | "CONF_FONT_SIZE_HEADLINE": "Font Size of News Headlines:",
2478 | "CONF_FONT_COLOR_HEADLINE": "Font Color of News Headlines:"
2479 | };
2480 | }
2481 |
2482 | // load standard settings
2483 | function _getStandardSettings() {
2484 | const jsonData = `
2485 | {
2486 | "CHECK_FOR_SCRIPT_UPDATE": true,
2487 | "PARAM_LINKS": [
2488 | ["https://venturebeat.com", "VENTUREBEAT"],
2489 | ["http://rss.cnn.com/rss/edition.rss", "CNN"]
2490 | ],
2491 | "PARAM_WIDGET_TITLE": "News Widget",
2492 | "PARAM_BG_IMAGE_NAME": "none",
2493 | "PARAM_BG_IMAGE_BLUR": "true",
2494 | "PARAM_BG_IMAGE_GRADIENT": "true",
2495 | "PARAM_SHOW_NEWS_IMAGES": "true",
2496 | "CONF_LARGE_WIDGET_MAX_NEWS": 4,
2497 | "CONF_DISPLAY_NEWS": "websites",
2498 | "CONF_DATE_TIME_LOCALE": "default",
2499 | "CONF_12_HOUR": false,
2500 | "CONF_BG_COLOR": {
2501 | "lightMode": "#fefefe",
2502 | "darkMode": "#2c2c2e"
2503 | },
2504 | "CONF_BG_GRADIENT": false,
2505 | "CONF_BG_GRADIENT_COLOR_TOP": {
2506 | "lightMode": "#fefefe",
2507 | "darkMode": "#000000"
2508 | },
2509 | "CONF_BG_GRADIENT_COLOR_BTM": {
2510 | "lightMode": "#cccccc",
2511 | "darkMode": "#2c2c2e"
2512 | },
2513 | "CONF_BG_GRADIENT_OVERLAY_TOP": {
2514 | "lightMode": "#fefefe",
2515 | "lightModeAlpha": 0.3,
2516 | "darkMode": "#2c2c2e",
2517 | "darkModeAlpha": 0.3
2518 | },
2519 | "CONF_BG_GRADIENT_OVERLAY_BTM": {
2520 | "lightMode": "#fefefe",
2521 | "lightModeAlpha": 1.0,
2522 | "darkMode": "#2c2c2e",
2523 | "darkModeAlpha": 1.0
2524 | },
2525 | "CONF_FONT_WIDGET_TITLE": "System",
2526 | "CONF_FONT_WEIGHT_WIDGET_TITLE": "heavy",
2527 | "CONF_FONT_SIZE_WIDGET_TITLE": 16,
2528 | "CONF_FONT_COLOR_WIDGET_TITLE": {
2529 | "lightMode": "#000000",
2530 | "darkMode" : "#fefefe"
2531 | },
2532 | "CONF_FONT_DATE" : "System",
2533 | "CONF_FONT_WEIGHT_DATE": "heavy",
2534 | "CONF_FONT_SIZE_DATE": 12,
2535 | "CONF_FONT_COLOR_DATE": {
2536 | "lightMode": "#8a8a8d",
2537 | "darkMode" : "#9f9fa4"
2538 | },
2539 | "CONF_FONT_HEADLINE": "System",
2540 | "CONF_FONT_WEIGHT_HEADLINE": "semibold",
2541 | "CONF_FONT_SIZE_HEADLINE": 13,
2542 | "CONF_FONT_COLOR_HEADLINE": {
2543 | "lightMode": "#000000",
2544 | "darkMode" : "#fefefe"
2545 | }
2546 | }`
2547 | return JSON.parse(jsonData);
2548 | }
2549 | } catch(err) {
2550 | log("try settingsWizard: "+err);
2551 | }
2552 | }
2553 |
2554 | /* ============ END OF SCRIPT ============ */
2555 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # iOS News Widget for Scriptable
2 |
3 | iOS Scriptable News Widget (for websites using WordPress and RSS feeds)
4 | Tap on a news in the widget to open it directly in your browser.
5 |
6 | 
7 |
8 | # List of contents
9 |
10 | - [Requirements](#requirements)
11 | - [Support](#support)
12 | - [Notes and known bugs](#notes-and-bugs)
13 | - [Changelog](#changelog)
14 | - [Setup](#setup)
15 | - [Widget Parameters](#widget-parameters)
16 | - [Widget Settings](#widget-settings)
17 | - [News Widget Clear Cache.js](#clear-cache)
18 | - [Update News Widget](#widget-update)
19 | - [Links](#links)
20 | - [Thanks](#thanks)
21 |
22 | ---
23 |
24 | __If you'd like to support my work with a coffee 😊: https://ko-fi.com/saudumm__
25 |
26 | ---
27 |
28 |
29 | # Requirements:
30 |
31 | - iOS14
32 | - Latest version of [Scriptable for iOS](https://apps.apple.com/de/app/scriptable/id1405459188)
33 |
34 |
35 | # Support
36 |
37 | I just started learning JavaScript, so there will be bugs.
38 | If there are any issues or questions, feel free to open an issue here on GitHub or contact me via Twitter: [@saudumm](https://www.twitter.com/saudumm)
39 | __Please mention the URL of the website or RSS feed, so I can help you faster.__
40 |
41 |
42 | # Notes and known bugs
43 |
44 | - Most WordPress websites, RSS and Atom feeds should work, but it's possible that not everything will work. Please feel free to contact me, if there are any problems.
45 |
46 |
47 | # Changelog
48 |
49 | - v1.2.2
50 | - fix for feeds containing webp images
51 | - v1.2.1
52 | - small fix for RSS feeds without a published date
53 | - v1.2.0
54 | - added offline mode
55 | - if you lose your internet connection, the widget won't go blank (if all necessary data is cached)
56 | - the widget will show a small cloud icon on the top right, if offline mode is temporarily active
57 | - added settings files (see [Settings](#settings) for more info)
58 | - added Settings Wizard (run script directly in Scriptable to use the Settings Wizard)
59 | - removed links files in favor of settings files
60 | - added blank image symbol if a news image isn't available
61 | - standard design now resembles the official news widget more closely
62 | - added setting CONF_LARGE_WIDGET_MAX_NEWS
63 | - configure how much news you want to see max. in a large widget
64 | - added setting CONF_DISPLAY_NEWS
65 | - "websites" prioritizes showing at least one news per link
66 | - "date" just sorts everything by date
67 | - v1.1.4
68 | - fixed incorrect display of date and time
69 | - added new font config options "Rounded" and "Monospaced"
70 | - added date/time region config setting
71 | - additional fixes for fetching images from RSS feeds
72 | - changed chaches from cache dir to documents dir
73 | - v1.1.3
74 | - Added instructions for Script Updates and Widget Setup
75 | - v1.1.2
76 | - Fix for fetching images from RSS feeds
77 | - v1.1.1
78 | - Fix for links that don't start with http:// or https://
79 | - v1.1.0
80 | - Multi URL support in the code or via text files
81 | - better RSS support
82 | - support for Atom feeds
83 | - more customization options
84 | - v1.0.2
85 | - Support for iOS light and dark mode
86 | - v1.0.1
87 | - Small bugfix loading images in RSS feed
88 | - v1.0.0
89 | - Initial Upload
90 |
91 |
92 | # Setup:
93 |
94 | First, you should add the __News-Widget.js__ Script to Scriptable. Either copy the content of the __News-Widget.js__ file and paste it into a new script in Scriptables or download the file and add it to your iCloud Drive Scriptables folder in iCloud Drive (Files App)
95 | You can also add the Widget directly via the Scriptable Gallery: https://scriptable.app/gallery/news-widget
96 |
97 | 1. Enter "Wiggle Mode" on your homescreen and tap on the __+__ symbol
98 | 2. Search for and/or tap on Scriptable
99 | 3. Choose one of three sizes and tap __+ Add Widget__
100 | 4. Tap on the new widget while still in "Wiggle Mode" or long press on the widget and tap "Edit Widget"
101 | 5. Click on __Choose__ next to __Script__
102 | 6. Choose __News Widget__ from the list
103 | 7. Edit your parameters for the widget (see Widget Parameters below)
104 | 8. Tap anywhere outside of the config window and you're done! The widget should now load.
105 |
106 | 
107 |
108 |
109 | ## Widget Parameters
110 |
111 | In v1.2.0, i've added settings files, so you don't have to configure your widget with a thousand different parameters.
112 | Just run the Settings Wizard, create a settings file and add it via Widget Parameters. See Settings Wizard for more information.
113 |
114 | 
115 |
116 | - Example:
117 | - widget-settings.txt
118 | - small|widget-settings.txt
119 |
120 | Of course, the old Parameters still work:
121 | - Example:
122 | - small|https://www.stadt-bremerhaven.de|Caschys Blog|true|background.jpg|false|true|MarkerFelt-Thin
123 | - Parameter order has to be:
124 | - Widget size (small, large, medium)
125 | - Site url (url of the WordPress Website or RSS feed URL)
126 | - Site name (name of the website, displayed at the top of the widget)
127 | - Show post images (use true if you want to display the images of the posts or set to false if not)
128 | - Background image (name of an image file. The file has to be stored in the scriptables folder in iCloud Drive (Files App))
129 | - Blur background image (use true if you want the background image to be blurry. Use false if not)
130 | - Background image gradient (use true to create a color gradient over the background image (for better readbility), use false to turn off the gradient)
131 | - Font Name (refer to http://iosfonts.com for available font names)
132 | - Parameters have to be separated by |
133 | - You don't have to set all parameters, the following examples will work just fine:
134 | - small|https://www.stadt-bremerhaven.de|Caschys Blog
135 | - large|https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml|NY Times RSS|true|background.jpg
136 | - Parameters that are not set will be set by the standard widget config in the source code
137 | - You can change more things like background color, font color and more in the source code. Look at the comments in the code for explanations
138 |
139 |
140 | ## Widget Settings
141 |
142 | 
143 |
144 | To start Settings Wizard, just run News Widget in the Scriptable App.
145 |
146 | You can create, edit or delete settings files.
147 | To edit a specific setting, just tap on it, edit it to your liking and once you're done, tap on "SAVE" at the top of the list, set a filename (ending in .txt) and you're done! You can now set this file as a Parameter for your Widget.
148 |
149 | I've tried to make this as simple as possible, but feel free to contact me, if there are any questions or problems.
150 |
151 | Here are all Settings that you can edit, there are also explanations for everything in the code:
152 |
153 | ### CHECK_FOR_SCRIPT_UPDATE
154 | Check for script updates and get notified as soon as a new version is released
155 | - true = check for script updates
156 | - false = don't check for updates
157 |
158 | ### PARAM_LINKS
159 | Add Addresses (URLs/Links) of the website(s) and/or the RSS Feed(s) you want to fetch posts from.
160 | Format of a new line has to be: ["Link to site/feed", "Name of site"],
161 | 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.
162 |
163 | ### PARAM_WIDGET_TITLE
164 | 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.
165 |
166 | ### PARAM_BG_IMAGE_NAME
167 | Note: custom background image files have to be in the Scriptable (iCloud) Files folder (same as the script .js file).
168 | Change to the filename of a custom background image (CASE SENSITIVE!) or set to "none" if you don't want a custom image
169 |
170 | ### PARAM_BG_IMAGE_BLUR
171 | Blur the background image (custom or the news image in small widgets).
172 | - "true" = blur the background image
173 | - "false" = no blur
174 |
175 | ### PARAM_BG_IMAGE_GRADIENT
176 | - "true" = gradient over the background image
177 | - "false" = no gradient
178 |
179 | ### PARAM_SHOW_NEWS_IMAGES
180 | Note: combining PARAM_SHOW_NEWS_IMAGES = true + small widget will ignore CONF_BG_GRADIENT_COLOR values in small config widgets.
181 | - "true" = display images next to headlines
182 | - "false" = no images next to posts
183 |
184 | ### CONF_LARGE_WIDGET_MAX_NEWS
185 | Configure if you want a maximum of four or five News displayed in the LARGE Widget.
186 | 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.
187 |
188 | ### CONF_DISPLAY_NEWS
189 | Configure how posts should be displayed in the widget.
190 | - Set to "websites" if you want to prioritize seeing news from all your configured websites. This will more closely resemble the iOS News Widget.
191 | - 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.
192 |
193 | ### CONF_DATE_TIME_LOCALE
194 | Configure your preferred region to format how date and time values will be displayed
195 | - "default" = uses your system region
196 | - Use locales shortcodes like "en-US", "en-GB", "ko", "fr-CA" or "de-DE"
197 | For a list of possible iOS locales, see: https://gist.github.com/jacobbubu/1836273
198 |
199 | ### CONF_12_HOUR
200 | Configure which time format to use
201 | - true = 12h time format
202 | - false = 24h time format
203 |
204 | ### CONF_BG_COLOR
205 | Set the background color of your widget
206 |
207 | ### CONF_BG_GRADIENT
208 | Configure to use a color Gradient instead of the single background color (above)
209 | - true = use a color gradient (colors configured below)
210 | - false = use a single color (color configured above)
211 |
212 | ### CONF_BG_GRADIENT_COLOR_TOP
213 | Gradient color from the top of the widget
214 |
215 | ### CONF_BG_GRADIENT_COLOR_BTM
216 | Gradient color to the bottom of the widget
217 |
218 | ### CONF_BG_GRADIENT_OVERLAY_TOP
219 | Gradient color image overlay from the top of the widget
220 | - used if a background image is displayed and PARAM_BG_IMAGE_GRADIENT = "true"
221 |
222 | ### CONF_BG_GRADIENT_OVERLAY_BTM
223 | Gradient Color Image Overlay to the bottom of the Widget
224 | - used if a background image is displayed and PARAM_BG_IMAGE_GRADIENT = "true"
225 |
226 | ### CONF_FONT_WIDGET_TITLE, CONF_FONT_WEIGHT_WIDGET_TITLE, CONF_FONT_SIZE_WIDGET_TITLE, CONF_FONT_COLOR_WIDGET_TITLE
227 | Set the font, size and text color of the widget title at the top of the widget
228 |
229 | ### CONF_FONT_DATE, CONF_FONT_WEIGHT_DATE, CONF_FONT_SIZE_DATE, CONF_FONT_COLOR_DATE
230 | Set the font, size and text color of the date and time line(s) in the widget
231 |
232 | ### CONF_FONT_HEADLINE, CONF_FONT_WEIGHT_HEADLINE, CONF_FONT_SIZE_HEADLINE, CONF_FONT_COLOR_HEADLINE
233 | Set the font, size and text color of the news headlines in the widget
234 |
235 | ---
236 |
237 |
238 | ## News Widget Clear Cache.js
239 |
240 | __News-Widget__ stores images and other data on your iPhone for faster loading and to save mobile data. You can't access those files directly. If there are problems or you want to delete all the cache files, just add __News-Widget-Clear-Cache.js__ to Scriptables and run the script in the app. It'll delete all cache files from News-Widget. Because the files are in a cache folder, iOS can delete thos files automatically, if there's not enough free space on your phone.
241 |
242 |
243 | # Update News Widget
244 |
245 | To install or update News Widget hassle-free, please add __News Widget Update.js__ from this Repo to your Scriptable App and run the script in Scriptable. It'll save a backup of your existing News Widget Code and download the latest version of News Widget to your Scriptable App.
246 |
247 | 
248 |
249 |
250 | # Links
251 |
252 | You can configure one or multiple Links to WordPress website and/or RSS feeds (at the same time!) directly in the script code (section STANDARD WIDGET CONFIG) or via Settings Files, if you want to set up different News Widgets.
253 |
254 | In case you're not sure if a website is using WordPress, just add _/wp-json/wp/v2/posts_ at the end of the url (https://stadt-bremerhaven.de/wp-json/wp/v2/posts). If you see a lot of text in your browser, the site should work.
255 | If not, you can search for an RSS feed (if the site has one) and use the link of the RSS feed.
256 |
257 | Here are a few links to help you get started:
258 |
259 | ## WordPress
260 |
261 | ### Gaming:
262 |
263 | - PlayStation Blog: http://blog.playstation.com
264 | - PlayStation Blog Germany: http://blog.de.playstation.com
265 | - Xbox Wire US: https://news.xbox.com/en-us
266 | - Xbox Wire Germany: https://news.xbox.com/de-de
267 | - InsideXbox (German): https://insidexbox.de
268 | - Dualshockers: https://www.dualshockers.com
269 | - Twinfinite: https://twinfinite.net
270 |
271 | ### Tech:
272 |
273 | - Caschys Blog (German): https://stadt-bremerhaven.de
274 | - Tarnkappe.info (German): https://tarnkappe.info
275 | - 9to5Mac: https://9to5mac.com
276 | - 9to5Google: https://9to5google.com
277 | - TechCrunch: https://techcrunch.com
278 | - VentureBeat: https://venturebeat.com
279 | - Wired: https://wired.com
280 |
281 | ## RSS Feeds
282 |
283 | ### News:
284 | - New York Times (World News): https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml
285 | - (more feeds can be found here: http://rss.nytimes.com)
286 | - CNBC Top News: https://www.cnbc.com/id/100003114/device/rss/rss.html
287 | - CNN (World News): http://rss.cnn.com/rss/edition_world.rss
288 | - more feeds: https://edition.cnn.com/services/rss/
289 | - ABC News World: https://abcnews.go.com/abcnews/internationalheadlines
290 |
291 | ### Gaming:
292 | - PC Gamer: https://www.pcgamer.com/rss/
293 | - IGN: http://feeds.feedburner.com/ign/all
294 | - Eurogamer: https://www.eurogamer.net/?format=rss
295 | - more feeds: https://www.eurogamer.net/rss/eurogamer_frontpage_feed.rss
296 | - Digital Foundry: https://www.eurogamer.net/?format=rss&topic=digital_foundry
297 |
298 | ### Tech:
299 | - MacStories: https://www.macstories.net/feed
300 | - WindowsCentral: http://feeds.windowscentral.com/wmexperts
301 | - Tom's Hardware: https://www.tomshardware.com/feeds/all
302 | - Heise (German): https://https://www.heise.de/rss/heise.rdf
303 |
304 |
305 | ## Thanks
306 |
307 | A big THANK YOU to [Mario Klingemann](http://quasimondo.com/StackBlurForCanvas/StackBlurDemo.html) for the blur code and [Max Zeryck](https://github.com/mzeryck) for the WebView code.
308 |
309 | Also a big THANK YOU to Simon B. Støvring [@simonbs](https://www.twitter.com/simonbs) for his awesome Scriptable App!
310 |
--------------------------------------------------------------------------------
/example-links.txt:
--------------------------------------------------------------------------------
1 | https://stadt-bremerhaven.de|Caschys Blog
2 | https://www.polygon.com/rss/index.xml|Polygon RSS
3 | https://insidexbox.de|InsideXbox.de
--------------------------------------------------------------------------------
/images/settings-wizard.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Saudumm/scriptable-News-Widget/1a36020f1143b5975fceabca7b40ea4d026e0e41/images/settings-wizard.jpg
--------------------------------------------------------------------------------
/images/update-example.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Saudumm/scriptable-News-Widget/1a36020f1143b5975fceabca7b40ea4d026e0e41/images/update-example.jpg
--------------------------------------------------------------------------------
/images/widget-config-old.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Saudumm/scriptable-News-Widget/1a36020f1143b5975fceabca7b40ea4d026e0e41/images/widget-config-old.jpg
--------------------------------------------------------------------------------
/images/widget-config.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Saudumm/scriptable-News-Widget/1a36020f1143b5975fceabca7b40ea4d026e0e41/images/widget-config.jpg
--------------------------------------------------------------------------------
/images/widgets.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Saudumm/scriptable-News-Widget/1a36020f1143b5975fceabca7b40ea4d026e0e41/images/widgets.jpg
--------------------------------------------------------------------------------
/screenshots/screenshot1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Saudumm/scriptable-News-Widget/1a36020f1143b5975fceabca7b40ea4d026e0e41/screenshots/screenshot1.jpg
--------------------------------------------------------------------------------
/screenshots/screenshot2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Saudumm/scriptable-News-Widget/1a36020f1143b5975fceabca7b40ea4d026e0e41/screenshots/screenshot2.jpg
--------------------------------------------------------------------------------
/screenshots/screenshot3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Saudumm/scriptable-News-Widget/1a36020f1143b5975fceabca7b40ea4d026e0e41/screenshots/screenshot3.jpg
--------------------------------------------------------------------------------
/screenshots/screenshot4.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Saudumm/scriptable-News-Widget/1a36020f1143b5975fceabca7b40ea4d026e0e41/screenshots/screenshot4.jpg
--------------------------------------------------------------------------------
/version.txt:
--------------------------------------------------------------------------------
1 | v1.2.2
2 |
--------------------------------------------------------------------------------