script/jupiter

filter: Statementstmt 94.4% 355 / 376 Branchbran 66.6% 60 / 90 Conditioncond 76.9% 50 / 65 MC/DCmcdc 62.1% 23 / 37 Subroutinesub 94.3% 50 / 53 Podpod n/a totaltotal 86.6% 538 / 621 CC 85 SCAR 20.3
CC
85
Cov
88%
main
30.0
add_data
22.2
entries
7.1
CRAP 7.6
↑ Summary blib/lib/App/jupiter.pm »
1 #! /usr/bin/env perl
2 # Planet Jupiter is a feed aggregator that creates a single HTML file
3 # Copyright (C) 2020–2021 Alex Schroeder <alex@gnu.org>
4  
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 #
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17  
18 package Jupiter;
19  
20 15 ▶use Encode::Locale;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 15 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 15 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 15 binmode(STDOUT, ":utf8");
25 15 binmode(STDERR, ":utf8");
26  
27 =encoding UTF8
28  
29 =head1 NAME
30  
31 jupiter - turn a list of feeds into a HTML page, a river of news
32  
33 =head1 SYNOPSIS
34  
35 To update the feeds from one or more OPML files:
36  
37 B<jupiter update> I<feed.opml> … [I</regex/> …]
38  
39 To generate F<index.html>:
40  
41 B<jupiter html> I<feed.opml>
42  
43 =head1 DESCRIPTION
44  
45 Planet Jupiter is used to pull together the latest updates from a bunch of other
46 sites and display them on a single web page, the "river of news". The sites we
47 get our updates from are defined in an OPML file.
48  
49 A river of news, according to Dave Winer, is a feed aggregator. New items appear
50 at the top and old items disappear at the bottom. When it's gone, it's gone.
51 There is no count of unread items. The goal is to fight the I<fear of missing
52 out> (FOMO).
53  
54 Each item looks similar to every other: headline, link, an extract, maybe a date
55 and an author. Extracts contain but the beginning of the article's text; all
56 markup is removed; no images. The goal is to make the page easy to skim.
57 Scroll down until you find something interesting and follow the link to the
58 original article if you want to read it.
59  
60 =head2 The OPML file
61  
62 You B<need> an OPML file. It's an XML file linking to I<feeds>. Here's an
63 example listing just one feed. In order to add more, add more C<outline>
64 elements with the C<xmlUrl> attribute. The exact order and nesting does not
65 matter. People can I<import> these OPML files into their own feed readers and
66 thus it may make sense to spend a bit more effort in making it presentable.
67  
68 <opml version="2.0">
69 <body>
70 <outline title="Alex Schroeder"
71 xmlUrl="https://alexschroeder.ch/view/index.rss"/>
72 </body>
73 </opml>
74  
75 =head2 Update the feeds in your cache
76  
77 This is how you update the feeds in a file called C<feed.opml>. It downloads all
78 the feeds linked to in the OPML file and stores them in the cache directory.
79  
80 jupiter update feed.opml
81  
82 The directory used to keep a copy of all the feeds in the OPML file has the same
83 name as the OPML file but without the .opml extension. In other words, if your
84 OPML file is called C<feed.opml> then the cache directory is called C<feed>.
85  
86 This operation takes long because it requests an update from all the sites
87 listed in your OPML file. Don't run it too often or you'll annoy the site
88 owners.
89  
90 The OPML file must use the .opml extension. You can update the feeds for
91 multiple OPML files in one go.
92  
93 =head2 Adding just one feed
94  
95 After a while, the list of feeds in your OPML starts getting unwieldy. When you
96 add a new feed, you might not want to fetch all of them. In this case, provide a
97 regular expression surrounded by slashes to the C<update> command:
98  
99 jupiter update feed.opml /example/
100  
101 Assuming a feed with a URL or title that matches the regular expression is
102 listed in your OPML file, only that feed is going to get updated.
103  
104 There is no need to escape slashes in the regular expression: C<//rss/> works
105 just fine. Beware shell escaping, however. Most likely, you need to surround the
106 regular expression with single quotes if it contains spaces:
107  
108 jupiter update feed.opml '/Halberds & Helmets/'
109  
110 Notice how we assume that named entities such as C<&amp;> have already been
111 parsed into the appropriate strings.
112  
113 =head2 Generate the HTML
114  
115 This is how you generate the C<index.html> file based on the feeds of your
116 C<feed.opml>. It assumes that you have already updated all the feeds (see
117 above).
118  
119 jupiter html feed.opml
120  
121 See L</OPTIONS> for ways to change how the HTML is generated.
122  
123 =head2 Generate the RSS feed
124  
125 This happens at the same time as when you generate the HTML. It takes all the
126 entries that are being added to the HTML and puts the into a feed.
127  
128 See L</OPTIONS> for ways to change how the HTML is generated.
129  
130 =head2 Why separate the two steps?
131  
132 The first reason is that tinkering with the templates involves running the
133 program again and again, and you don't want to contact all the sites whenever
134 you update your templates.
135  
136 The other reason is that it allows you to create subsets. For example, you can
137 fetch the feeds for three different OPML files:
138  
139 jupiter update osr.opml indie.opml other.opml
140  
141 And then you can create three different HTML files:
142  
143 jupiter html osr.html osr.opml
144 jupiter html indie.html indie.opml
145 jupiter html rpg.html osr.opml indie.opml other.opml
146  
147 For an example of how it might look, check out the setup for the planets I run.
148 L<https://alexschroeder.ch/cgit/planet/about/>
149  
150 =head2 What about the JSON file?
151  
152 There's a JSON file that gets generated and updated as you run Planet Jupiter.
153 It's name depends on the OPML files used. It records metadata for every feed in
154 the OPML file that isn't stored in the feeds themselves.
155  
156 C<message> is the HTTP status message, or a similar message such as "No entry
157 newer than 90 days." This is set when updating the feeds in your cache.
158  
159 C<message> is the HTTP status code; this code could be the real status code from
160 the server (such as 404 for a "not found" status) or one generated by Jupiter
161 such that it matches the status message (such as 206 for a "partial content"
162 status when there aren't any recent entries in the feed). This is set when
163 updating the feeds in your cache.
164  
165 C<title> is the site's title. When you update the feeds in your cache, it is
166 taken from the OPML file. That's how the feed can have a title even if the
167 download failed. When you generate the HTML, the feeds in the cache are parsed
168 and if a title is provided, it is stored in the JSON file and overrides the
169 title in the OPML file.
170  
171 C<link> is the site's link for humans. When you generate the HTML, the feeds in
172 the cache are parsed and if a link is provided, it is stored in the JSON file.
173 If the OPML element contained a C<htmlURL> attribute, however, that takes
174 precedence. The reasoning is that when a podcast is hosted on a platform which
175 generates a link that you don't like and you know the link to the human-readable
176 blog elsewhere, use the C<htmlURL> attribute in the OPML file to override this.
177  
178 C<last_modified> and C<etag> are two headers used for caching from the HTTP
179 response that cannot be changed by data in the feed.
180  
181 If we run into problems downloading a feed, this setup allows us to still link
182 to the feeds that aren't working, using their correct names, and describing the
183 error we encountered.
184  
185 =head2 Logging
186  
187 Use the C<--log=LEVEL> to set the log level. Valid values for LEVEL are debug,
188 info, warn, error, and fatal.
189  
190 =head1 LICENSE
191  
192 GNU Affero General Public License
193  
194 =head1 INSTALLATION
195  
196 Using C<cpan>:
197  
198 cpan App::jupiter
199  
200 Manual install:
201  
202 perl Makefile.PL
203 make
204 make install
205  
206 =head2 Dependencies
207  
208 To run Jupiter on Debian we need:
209  
210 C<libmodern-perl-perl> for L<Modern::Perl>
211  
212 C<libmojolicious-perl> for L<Mojo::Template>, L<Mojo::UserAgent>, L<Mojo::Log>,
213 L<Mojo::JSON>, and L<Mojo::Util>
214  
215 C<libxml-libxml-perl> for L<XML::LibXML>
216  
217 C<libfile-slurper-perl> for L<File::Slurper>
218  
219 C<libdatetime-perl> for L<DateTime>
220  
221 C<libdatetime-format-mail-perl> for L<DateTime::Format::Mail>
222  
223 C<libdatetime-format-iso8601-perl> for L<DateTime::Format::ISO8601>
224  
225 Unfortunately, L<Mojo::UserAgent::Role::Queued> isn't packaged for Debian.
226 Therefore, let's build it and install it as a Debian package.
227  
228 sudo apt-get install libmodule-build-tiny-perl
229 sudo apt-get install dh-make-perl
230 sudo dh-make-perl --build --cpan Mojo::UserAgent::Role::Queued
231 dpkg --install libmojo-useragent-role-queued-perl_1.15-1_all.deb
232  
233 To generate the C<README.md> from the source file, you need F<pod2markdown>
234 which you get in C<libpod-markdown-perl>.
235  
236 =head1 FILES
237  
238 There are a number of files in the F<share> directory which you can use as
239 starting points.
240  
241 F<template.html> is the HTML template.
242  
243 F<default.css> is a small CSS file used by F<template.html>.
244  
245 F<personalize.js> is a small Javascript file used by F<template.html> used to
246 allow visitors to jump from one article to the next using C<J> and C<K>.
247  
248 F<jupiter.png> is used by F<template.html> as the icon.
249  
250 F<jupiter.svg> is used by F<template.html> as the logo.
251  
252 F<feed.png> is used by F<template.html> as the icon for the feeds in the
253 sidebar.
254  
255 F<feed.rss> is the feed template.
256  
257 =head1 OPTIONS
258  
259 HTML generation uses a template, C<template.html>. It is written for
260 C<Mojo::Template> and you can find it in the F<share> directory of your
261 distribution. The default templates use other files, such as the logo, the feed
262 icon, a CSS file, and a small Javascript snippet to enable navigation using the
263 C<J> and C<K> keys (see above).
264  
265 You can specify a different HTML file to generate:
266  
267 B<jupiter html> I<your.html feed.opml>
268  
269 If you specify two HTML files, the first is the HTML file to generate and the
270 second is the template to use. Both must use the C<.html> extension.
271  
272 B<jupiter html> I<your.html your-template.html feed.opml>
273  
274 Feed generation uses a template, C<feed.rss>. It writes all the entries into a
275 file called C<feed.xml>. Again, the template is written for C<Mojo::Template>.
276  
277 You can specify up to two XML, RSS or ATOM files. They must uses one of these
278 three extensions: C<.xml>, C<.rss>, or C<.atom>. The first is the name of the
279 feed to generate, the second is the template to use:
280  
281 B<jupiter html> I<atom.xml template.xml planet.html template.html feed.opml>
282  
283 In the above case, Planet Jupiter will write a feed called F<atom.xml> based on
284 F<template.xml> and a HTML file called F<planet.html> based on F<template.html>,
285 using the cached entries matching the feeds in F<feed.opml>.
286  
287 =cut
288  
289 15 ▶use DateTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
290 15 ▶use DateTime::Format::Mail;
Subroutine BEGIN: called CC=1 SCAR=0.0
291 15 ▶use DateTime::Format::ISO8601;
Subroutine BEGIN: called CC=1 SCAR=0.0
292 15 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
293 15 ▶use File::Slurper qw(read_binary write_binary read_text write_text);
Subroutine BEGIN: called CC=1 SCAR=0.0
294 15 ▶use List::Util qw(uniq min shuffle);
Subroutine BEGIN: called CC=1 SCAR=0.0
295 15 ▶use Modern::Perl;
Subroutine BEGIN: called CC=1 SCAR=0.0
296 15 ▶use Mojo::Log;
Subroutine BEGIN: called CC=1 SCAR=0.0
297 15 ▶use Mojo::JSON qw(decode_json encode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
298 15 ▶use Mojo::Template;
Subroutine BEGIN: called CC=1 SCAR=0.0
299 15 ▶use Mojo::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
300 15 ▶use Pod::Simple::Text;
Subroutine BEGIN: called CC=1 SCAR=0.0
301 15 ▶use XML::LibXML;
Subroutine BEGIN: called CC=1 SCAR=0.0
302 15 ▶use Mojo::Util qw(slugify trim xml_escape html_unescape);
Subroutine BEGIN: called CC=1 SCAR=0.0
303 15 ▶use File::ShareDir 'dist_file';
Subroutine BEGIN: called CC=1 SCAR=0.0
304  
305 15 ▶use vars qw($log);
Subroutine BEGIN: called CC=1 SCAR=0.0
306 15 our $log = Mojo::Log->new;
307  
308 15 my $xpc = XML::LibXML::XPathContext->new;
309 15 $xpc->registerNs('atom', 'http://www.w3.org/2005/Atom');
310 15 $xpc->registerNs('html', 'http://www.w3.org/1999/xhtml');
311 15 $xpc->registerNs('dc', 'http://purl.org/dc/elements/1.1/');
312 15 $xpc->registerNs('itunes', 'http://www.itunes.com/dtds/podcast-1.0.dtd');
313  
314 15 my $undefined_date = DateTime->from_epoch( epoch => 0 );
315  
316 15 my (%wday, %month, $wday_re, $month_re);
317 15 %wday = qw (lun. Mon mar. Tue mer. Wed jeu. Thu ven. Fri sam. Sat dim. Sun);
318 15 %month = qw (janv. Jan févr. Feb mars Mar avr. Apr mai May juin Jun
319 juil. Jul août Aug sept. Sep oct. Oct nov. Nov déc. Dec);
320 15 ▶$wday_re = join('|', map { quotemeta } keys %wday) unless $wday_re;
Branch: 1 branch
BranchTrueFalseTotal
unless $wday_re 15 0 15
321 15 ▶$month_re = join('|', map { quotemeta } keys %month) unless $month_re;
Branch: 1 branch
BranchTrueFalseTotal
unless $month_re 15 0 15
322  
323 # Our tests don't want to call main
324 15 ▶__PACKAGE__->main unless caller;
Branch: 1 branch
BranchTrueFalseTotal
unless caller 0 15 15
325  
326 0 ▶sub main {
Subroutine main: not called CC=5 SCAR=34.0
327 0 my ($log_level) = grep /^--log=/, @ARGV;
328 0 ▶ $log->level(substr($log_level, 6)) if $log_level;
Branch: 1 branch
BranchTrueFalseTotal
if $log_level 0 0 0
329 0 my ($command) = grep /^[a-z]+$/, @ARGV;
330 0 ▶ $command ||= 'help';
Condition0%0/2
$command ||= "help"
l!l
00
MC/DC0%0/1
$command ||= "help"
$command
Truth table0%0/2
A
A= $command
Aresult
11
00
331 0 ▶ if ($command eq 'update') {
Branch: 2 branches
BranchTrueFalseTotal
if ($command eq 'update') { } 0 0 0
elsif ($command eq 'html') { } 0 0 0
332 0 update_cache(@ARGV);
333 } elsif ($command eq 'html') {
334 0 make_html(@ARGV);
335 } else {
336 0 my $parser = Pod::Simple::Text->new();
337 0 $parser->parse_file($0);
338 }
339 }
340  
341 18 ▶sub update_cache {
Subroutine update_cache: called CC=1 SCAR=0.0
342 18 my ($feeds, $files) = read_opml(@_);
343 18 make_directories($feeds);
344 18 load_feed_metadata($feeds, $files);
345 18 my $ua = Mojo::UserAgent->new->with_roles('+Queued')
346 ->max_redirects(3)
347 ->max_active(5);
348 18 make_promises($ua, $feeds);
349 18 fetch_feeds($feeds);
350 18 save_feed_metadata($feeds, $files);
351 18 cleanup_cache($feeds);
352 }
353  
354 18 ▶sub make_promises {
Subroutine make_promises: called CC=2 SCAR=7.4
355 18 my $ua = shift;
356 18 my $feeds = shift;
357 18 for my $feed (@$feeds) {
358 18 my $url = html_unescape $feed->{url}; # undo xml_escape for the request
359 18 ▶ $ua->on(start => sub {
Subroutine __ANON__: called CC=3 SCAR=11.7
360 18 my ($ua, $tx) = @_;
361 18 ▶ $tx->req->headers->if_none_match($feed->{etag}) if ($feed->{etag});
Branch: 1 branch
BranchTrueFalseTotal
if $feed->{"etag"} 0 18 18
362 18 ▶ $tx->req->headers->if_modified_since($feed->{last_modified}) if ($feed->{last_modified});
Branch: 1 branch
BranchTrueFalseTotal
if $feed->{"last_modified"} 0 18 18
363 18 });
364 $feed->{promise} = $ua->get_p($url)
365 0 ▶ ->catch(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
366 0 $feed->{message} = "@_";
367 0 $feed->{code} = 521;
368 # returning 0 in the case of an error is important
369 0 0; })
370 # sleeping to stop blogger.com from blocking us
371 18 ▶ ->finally(sub { $log->debug($url); sleep 2; });
Subroutine __ANON__: called CC=1 SCAR=0.0
372 }
373 }
374  
375 18 ▶sub fetch_feeds {
Subroutine fetch_feeds: called CC=1 SCAR=0.0
376 18 my $feeds = shift;
377 18 $log->info("Fetching feeds...");
378 18 ▶ Mojo::Promise->all(map { $_->{promise} } @$feeds)->then(sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
379 # all returns the values in the same order!
380 18 ▶ for (my $i = 0; $i < @_; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @_) 18 18 36
381 18 my $feed = $feeds->[$i];
382 18 my $value = $_[$i];
383 18 my $tx = $value->[0];
384 # relies on catch returning 0 above
385 18 ▶ next unless $tx;
Branch: 1 branch
BranchTrueFalseTotal
unless $tx 0 18 18
386 18 $feed->{message} = $tx->result->message;
387 18 $feed->{code} = $tx->result->code;
388 18 $feed->{last_modified} = $tx->result->headers->last_modified;
389 18 $feed->{etag} = $tx->result->headers->etag;
390 # save raw bytes if this is a success
391 18 ▶ eval { write_binary($feed->{cache_file}, $tx->result->body) } if $tx->result->is_success;
Branch: 1 branch
BranchTrueFalseTotal
if $tx->result->is_success 18 0 18
392 18 ▶ warn "Unable to write $feed->{cache_file}: $@\n" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 18 18
393 }
394 0 ▶ })->catch(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
395 0 warn "Something went wrong: @_";
396 18 })->wait;
397 }
398  
399 37 ▶sub load_feed_metadata {
Subroutine load_feed_metadata: called CC=7 SCAR=19.5
400 37 my $feeds = shift;
401 37 my $files = shift;
402 37 for my $file (@$files) {
403 37 my $filename = "$file->{path}/$file->{name}";
404 37 ▶ next unless -r "$filename.json";
Branch: 1 branch
BranchTrueFalseTotal
unless -r "$filename.json" 14 23 37
405 23 my $data = decode_json read_binary("$filename.json");
406 23 for my $feed (@$feeds) {
407 22 my $url = $feed->{url};
408 22 ▶ next unless $url;
Branch: 1 branch
BranchTrueFalseTotal
unless $url 0 22 22
409 # don't overwrite title and htmlUrl from OPML file
410 22 ▶ $feed->{title} = $data->{$url}->{title} if $data->{$url}->{title};
Branch: 1 branch
BranchTrueFalseTotal
if $data->{$url}{"title"} 21 1 22
411 22 ▶ $feed->{link} ||= $data->{$url}->{link};
Condition100%3/3
$feed->{"link"} ||= $data->{$url}{"link"}
l!l&&r!l&&!r
1813
MC/DC100%2/2
$feed->{"link"} ||= $data->{$url}{"link"}
$feed->{"link"} $data->{$url}{"link"}
Truth table100%3/3
A ||= B
A= $feed->{"link"}B= $data->{$url}{"link"}
ABresult
1X1
011
000
412 # all the other metadata is loaded from the JSON file
413 22 $feed->{message} = $data->{$url}->{message};
414 22 $feed->{code} = $data->{$url}->{code};
415 22 $feed->{last_modified} = $data->{$url}->{last_modified};
416 22 $feed->{etag} = $data->{$url}->{etag};
417 23 } grep { $_->{opml_file} eq $file->{file} } @$feeds;
418 }
419 }
420  
421 37 ▶sub save_feed_metadata {
Subroutine save_feed_metadata: called CC=2 SCAR=6.9
422 37 my $feeds = shift;
423 37 my $files = shift;
424 37 for my $file (@$files) {
425 37 my $name = $file->{name};
426 my %messages = map {
427 36 my $feed = $_;
428 36 $feed->{url} => { map { $_ => $feed->{$_} } grep { $feed->{$_} } qw(title link message code last_modified etag) };
429 37 } grep { $_->{opml_file} eq $file->{file} } @$feeds;
430 37 write_binary("$file->{path}/$file->{name}.json", encode_json \%messages);
431 }
432 }
433  
434 18 ▶sub cleanup_cache {
Subroutine cleanup_cache: called CC=3 SCAR=12.3
435 18 my $feeds = shift;
436 18 my %good = map { $_ => 1 } @{cache_files($feeds)};
437 18 my @unused = grep { not $good{$_} } @{existing_files($feeds)};
438 18 ▶ if (@unused) {
Branch: 1 branch
BranchTrueFalseTotal
if (@unused) 0 18 18
439 0 $log->info("Removing unused files from the cache...");
440 0 foreach (@unused) { $log->info($_) }
441 0 unlink @unused;
442 }
443 }
444  
445 18 ▶sub existing_files {
Subroutine existing_files: called CC=4 SCAR=14.6
446 18 my $feeds = shift;
447 18 my @files;
448 18 for my $dir (uniq map { $_->{cache_dir} } @$feeds) {
449 18 ▶ push(@files, <"$dir/*">) if $dir and -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
if $dir and -d $dir 18 0 18
Condition33%1/3
$dir and -d $dir
!ll&&!rl&&r
0018
MC/DC0%0/2
$dir and -d $dir
$dir -d $dir
Truth table33%1/3
A and B
A= $dirB= -d $dir
ABresult
0X0
100
111
450 }
451 18 return \@files;
452 }
453  
454 18 ▶sub cache_files {
Subroutine cache_files: called CC=1 SCAR=0.0
455 18 my $feeds = shift;
456 18 my @files = map { $_->{cache_file} } @$feeds;
457 18 return \@files;
458 }
459  
460 18 ▶sub make_directories {
Subroutine make_directories: called CC=4 SCAR=13.9
461 18 my $feeds = shift;
462 18 for my $dir (uniq map { $_->{cache_dir} } @$feeds) {
463 18 ▶ if ($dir and not -d $dir) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dir and not -d $dir) 14 4 18
Condition66%2/3
$dir and not -d $dir
!ll&&!rl&&r
0414
MC/DC50%1/2
$dir and not -d $dir
$dir not -d $dir
Truth table66%2/3
A and not(B)
A= $dirB= not -d $dir
ABresult
0X0
100
111
464 14 mkdir $dir;
465 }
466 }
467 }
468  
469 19 ▶sub make_html {
Subroutine make_html: called CC=1 SCAR=0.0
470 19 my ($feeds, $files) = read_opml(@_);
471 19 load_feed_metadata($feeds, $files); # load messages and codes for feeds
472 19 my $globals = globals($files);
473 19 my $entries = entries($feeds, 4); # set data for feeds, too
474 19 add_data($feeds, $entries); # extract data from the xml
475 19 save_feed_metadata($feeds, $files); # save title and link for feeds
476 19 $entries = limit($entries, 100);
477 19 write_text(html_file(@_), apply_template(read_text(html_template_file(@_)), $globals, $feeds, $entries));
478 19 write_text(feed_file(@_), apply_template(read_text(feed_template_file(@_)), $globals, $feeds, $entries));
479 }
480  
481 19 ▶sub html_file {
Subroutine html_file: called CC=2 SCAR=7.2
482 19 my ($html) = grep /\.html$/, @_;
483 19 ▶ return $html || 'index.html';
Condition50%1/2
$html || 'index.html'
l!l
190
MC/DC0%0/1
$html || 'index.html'
$html
Truth table50%1/2
A
A= $html
Aresult
11
00
484 }
485  
486 19 ▶sub html_template_file {
Subroutine html_template_file: called CC=3 SCAR=12.0
487 19 my ($html, $template) = grep /\.html$/, @_;
488 19 ▶ $template ||= dist_file('App-jupiter', 'template.html');
Condition33%1/3
$template ||= dist_file("App-jupiter", "template.html")
l!l&&r!l&&!r
0190
MC/DC0%0/2
$template ||= dist_file("App-jupiter", "template.html")
$template dist_file("App-jupiter", "template.html")
Truth table33%1/3
A ||= B
A= $templateB= dist_file("App-jupiter", "template.html")
ABresult
1X1
011
000
489 19 ▶ die "HTML template $template not found\n" unless -r $template;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $template 0 19 19
490 19 return $template;
491 }
492  
493 19 ▶sub feed_file {
Subroutine feed_file: called CC=2 SCAR=8.1
494 19 my ($feed) = grep /\.(xml|rss|atom)$/, @_;
495 19 ▶ return $feed if $feed;
Branch: 1 branch
BranchTrueFalseTotal
if $feed 19 0 19
496 0 return 'feed.xml';
497 }
498  
499 19 ▶sub feed_template_file {
Subroutine feed_template_file: called CC=2 SCAR=7.1
500 19 my ($feed, $template) = grep /\.(xml|rss|atom)$/, @_;
501 19 ▶ return $template if $template;
Branch: 1 branch
BranchTrueFalseTotal
if $template 0 19 19
502 19 return dist_file('App-jupiter', 'feed.rss');
503 }
504  
505 38 ▶sub apply_template {
Subroutine apply_template: called CC=1 SCAR=0.0
506 38 my $mnt = Mojo::Template->new;
507 38 return $mnt->render(@_);
508 }
509  
510 =head1 TEMPLATES
511  
512 The page template is called with three hash references: C<globals>, C<feeds>,
513 and C<entries>. The keys of these three hash references are documented below.
514 The values of these hashes are all I<escaped HTML> except where noted (dates and
515 file names, for example).
516  
517 The technical details of how to write the templates are documented in the man
518 page for L<Mojo::Template>.
519  
520 =head2 Globals
521  
522 There are not many global keys.
523  
524 B<date> is the the publication date of the HTML page, in ISO date format:
525 YYYY-MM-DD.
526  
527 B<files> is the list of OPML files used.
528  
529 =cut
530  
531 19 ▶sub globals {
Subroutine globals: called CC=1 SCAR=0.0
532 19 my $files = shift;
533 19 my @time = gmtime;
534 19 my $today = DateTime->now->ymd;
535 19 return {date => $today, files => $files};
536 }
537  
538 =head2 Writing templates for feeds
539  
540 Feeds have the following keys available:
541  
542 B<title> is the title of the feed.
543  
544 B<url> is the URL of the feed (RSS or Atom). This is not the link to the site!
545  
546 B<link> is the URL of the web page (HTML). This is the link to the site.
547  
548 B<opml_file> is the file name where this feed is listed.
549  
550 B<cache_dir> is the directory where this feed is cached.
551  
552 B<message> is the HTTP status message or other warning or error that we got
553 while fetching the feed.
554  
555 B<code> is the HTTP status code we got while fetching the feed.
556  
557 B<doc> is the L<XML::LibXML::Document>. Could be either Atom or RSS!
558  
559 =cut
560  
561 # Creates list of feeds. Each feed is a hash with keys title, url, opml_file,
562 # cache_dir and cache_file.
563 37 ▶sub read_opml {
Subroutine read_opml: called CC=7 SCAR=19.5
564 37 my (@feeds, @files);
565 37 my @filters = map { decode(locale => substr($_, 1, -1)) } grep /^\/.*\/$/, @_;
566 37 for my $file (grep /\.opml$/, @_) {
567 37 my $doc = XML::LibXML->load_xml(location => $file); # this better have no errors!
568 37 my @nodes = $doc->findnodes('//outline[./@xmlUrl]');
569 37 my ($name, $path) = fileparse($file, '.opml', '.xml');
570 37 for my $node (@nodes) {
571 37 my $title = xml_escape $node->getAttribute('title');
572 37 my $url = xml_escape $node->getAttribute('xmlUrl');
573 37 ▶ next if @filters > 0 and not grep { $url =~ /$_/ or $title =~ /$_/ } @filters;
Branch: 1 branch
BranchTrueFalseTotal
if @filters > 0 and not grep({$url =~ /$_/u or $title =~ /$_/u;} @filters) 1 36 37
Condition83%5/6
@filters > 0 and not grep({$url =~ /$_/u or $title =~ /$_/u;} @filters)
!ll&&!rl&&r
3511
$url =~ /$_/u || $title =~ /$_/u
l!l&&r!l&&!r
101
MC/DC100%2/2
@filters > 0 and not grep({$url =~ /$_/u or $title =~ /$_/u;} @filters)
@filters > 0 not grep({$url =~ /$_/u or $title =~ /$_/u;} @filters)
MC/DC50%1/2
$url =~ /$_/u || $title =~ /$_/u
$url =~ /$_/u $title =~ /$_/u
Truth table100%3/3
A and not(B)
A= @filters > 0B= not grep({$url =~ /$_/u or $title =~ /$_/u;} @filters)
ABresult
0X0
100
111
Truth table66%2/3
A || B
A= $url =~ /$_/uB= $title =~ /$_/u
ABresult
1X1
011
000
574 36 my $link = xml_escape $node->getAttribute('htmlUrl');
575 36 push @feeds, {
576 title => $title, # title in the OPML file
577 url => $url, # feed URL in the OPML file
578 link => $link, # web URL in the OPML file
579 opml_file => $file,
580 cache_dir => "$path/$name",
581 cache_file => "$path/$name/" . slugify($url),
582 };
583 }
584 37 ▶ warn "No feeds found in the OPML file $file\n" unless @nodes;
Branch: 1 branch
BranchTrueFalseTotal
unless @nodes 0 37 37
585 37 push @files, { file => $file, path => $path, name => $name };
586 }
587 37 @feeds = shuffle @feeds;
588 37 return \@feeds, \@files;
589 }
590  
591 19 ▶sub entries {
Subroutine entries: called CC=7 SCAR=19.6
592 19 my $feeds = shift;
593 19 my $limit = shift;
594 19 my $date = DateTime->now(time_zone => 'UTC')->subtract( days => 90 ); # compute once
595 19 my $now = DateTime->now(time_zone => 'UTC');
596 19 my @entries;
597 19 for my $feed (@$feeds) {
598 18 ▶ next unless -r $feed->{cache_file};
Branch: 1 branch
BranchTrueFalseTotal
unless -r $feed->{"cache_file"} 0 18 18
599 18 my $doc = eval { XML::LibXML->load_xml(recover => 2, location => $feed->{cache_file} )};
600 18 ▶ if (not $doc) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($doc) 0 18 18
601 0 $feed->{message} = xml_escape "Parsing error: $@";
602 0 $feed->{code} = 422; # unprocessable
603 0 next;
604 }
605 18 $feed->{doc} = $doc;
606 18 my @nodes = $xpc->findnodes("/rss/channel/item | /atom:feed/atom:entry", $doc);
607 18 ▶ if (not @nodes) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@nodes) 2 16 18
608 2 $feed->{message} = "Empty feed";
609 2 $feed->{code} = 204; # no content
610 2 next;
611 }
612 # if this is an Atom feed, we need to sort the entries ourselves (older entries at the end)
613 my @candidates = map {
614 16 my $entry = {};
615 40 $entry->{element} = $_;
616 40 $entry->{id} = id($_);
617 40 ▶ $entry->{date} = updated($_) || $undefined_date;
Condition66%2/3
updated($_) || $undefined_date
l!l&&r!l&&!r
3550
MC/DC0%0/2
updated($_) || $undefined_date
updated($_) $undefined_date
Truth table66%2/3
A || B
A= updated($_)B= $undefined_date
ABresult
1X1
011
000
618 40 $entry;
619 } @nodes;
620 16 @candidates = grep { DateTime->compare($_->{date}, $now) <= 0 } @candidates;
621 16 @candidates = unique(sort { DateTime->compare( $b->{date}, $a->{date} ) } @candidates);
622 16 @candidates = @candidates[0 .. min($#candidates, $limit - 1)];
623 # now that we have limited the candidates, let's add more metadata from the feed
624 16 for my $entry (@candidates) {
625 30 $entry->{feed} = $feed;
626 # these two are already escaped
627 30 $entry->{blog_title} = $feed->{title};
628 30 $entry->{blog_url} = $feed->{url};
629 }
630 16 add_age_warning($feed, \@candidates, $date);
631 16 push @entries, @candidates;
632 }
633 19 return \@entries;
634 }
635  
636 16 ▶sub add_age_warning {
Subroutine add_age_warning: called CC=5 SCAR=16.1
637 16 my $feed = shift;
638 16 my $entries = shift;
639 16 my $date = shift;
640 # feed modification date is smaller than the date given
641 16 my ($node) = $xpc->findnodes("/rss/channel | /atom:feed", $feed->{doc});
642 16 my $feed_date = updated($node);
643 16 ▶ if ($feed_date and DateTime->compare($feed_date, $date) == -1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($feed_date and 'DateTime'->compare($feed_date, $date) == -1) { } 11 5 16
Condition100%3/3
$feed_date and "DateTime"->compare($feed_date, $date) == -1
!ll&&!rl&&r
4111
MC/DC100%2/2
$feed_date and "DateTime"->compare($feed_date, $date) == -1
$feed_date "DateTime"->compare($feed_date, $date) == -1
Truth table100%3/3
A and B
A= $feed_dateB= "DateTime"->compare($feed_date, $date) == -1
ABresult
0X0
100
111
644 11 $feed->{message} = "No feed updates in 90 days";
645 11 $feed->{code} = 206; # partial content
646 11 return;
647 } else {
648 # or no entry found with a modification date equal or bigger than the date given
649 5 for my $entry (@$entries) {
650 11 ▶ return if DateTime->compare($entry->{date}, $date) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if "DateTime"->compare($entry->{"date"}, $date) >= 0 1 10 11
651 }
652 4 $feed->{message} = "No entry newer than 90 days";
653 4 $feed->{code} = 206; # partial content
654 }
655 }
656  
657 113 ▶sub updated {
Subroutine updated: called CC=5 SCAR=16.1
658 113 my $node = shift;
659 113 ▶ return unless $node;
Branch: 1 branch
BranchTrueFalseTotal
unless $node 0 113 113
660 113 ▶ my @nodes = $xpc->findnodes('pubDate | atom:published | atom:updated', $node) or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@nodes) = $xpc->findnodes("pubDate | atom:published | atom:updated", $node) or return 106 7 113
661 106 my $date = $nodes[0]->textContent;
662 106 my $dt = eval { DateTime::Format::Mail->parse_datetime($date) }
663 75 || eval { DateTime::Format::ISO8601->parse_datetime($date) }
664 106 ▶ || eval { DateTime::Format::Mail->parse_datetime(french($date)) };
Condition100%6/6
eval { do { 'DateTime::Format::Mail'->parse_datetime($date) } } || eval { do { 'DateTime::Format::ISO8601'->parse_datetime($date) } } || eval { do { 'DateTime::Format::Mail'->parse_datetime(french($date)) } }
l!l&&r!l&&!r
47572
eval { do { "DateTime::Format::Mail"->parse_datetime($date) } } or eval { do { "DateTime::Format::ISO8601"->parse_datetime($date) } }
l!l&&r!l&&!r
311659
MC/DC100%3/3
eval { do { 'DateTime::Format::Mail'->parse_datetime($date) } } || eval { do { 'DateTime::Format::ISO8601'->parse_datetime($date) } } || eval { do { 'DateTime::Format::Mail'->parse_datetime(french($date)) } }
eval { do { "DateTime::Format::Mail"->parse_datetime($date) } } eval { do { "DateTime::Format::ISO8601"->parse_datetime($date) } } eval { do { 'DateTime::Format::Mail'->parse_datetime(french($date)) } }
Truth table100%4/4
A or B || C
A= eval { do { "DateTime::Format::Mail"->parse_datetime($date) } }B= eval { do { "DateTime::Format::ISO8601"->parse_datetime($date) } }C= eval { do { 'DateTime::Format::Mail'->parse_datetime(french($date)) } }
ABCresult
1XX1
01X1
0011
0000
665 106 return $dt;
666 }
667  
668 60 ▶sub french {
Subroutine french: called CC=1 SCAR=0.0
669 60 my $date = shift;
670 60 $date =~ s/^($wday_re)/$wday{$1}/;
671 60 $date =~ s/\b($month_re)/$month{$1}/;
672 60 return $date;
673 }
674  
675 40 ▶sub id {
Subroutine id: called CC=5 SCAR=16.1
676 40 my $node = shift;
677 40 ▶ return unless $node;
Branch: 1 branch
BranchTrueFalseTotal
unless $node 0 40 40
678 40 my $id = $xpc->findvalue('guid | atom:id', $node); # id is mandatory for Atom
679 40 ▶ $id ||= $node->findvalue('link'); # one of the following three is mandatory for RSS
Condition100%3/3
$id ||= $node->findvalue("link")
l!l&&r!l&&!r
12424
MC/DC100%2/2
$id ||= $node->findvalue("link")
$id $node->findvalue("link")
Truth table100%3/3
A ||= B
A= $idB= $node->findvalue("link")
ABresult
1X1
011
000
680 40 ▶ $id ||= $node->findvalue('title');
Condition100%3/3
$id ||= $node->findvalue("title")
l!l&&r!l&&!r
161113
MC/DC100%2/2
$id ||= $node->findvalue("title")
$id $node->findvalue("title")
Truth table100%3/3
A ||= B
A= $idB= $node->findvalue("title")
ABresult
1X1
011
000
681 40 ▶ $id ||= $node->findvalue('description');
Condition100%3/3
$id ||= $node->findvalue("description")
l!l&&r!l&&!r
27211
MC/DC100%2/2
$id ||= $node->findvalue("description")
$id $node->findvalue("description")
Truth table100%3/3
A ||= B
A= $idB= $node->findvalue("description")
ABresult
1X1
011
000
682 40 return $id;
683 }
684  
685 35 ▶sub unique {
Subroutine unique: called CC=3 SCAR=11.0
686 35 my %seen;
687 my @unique;
688 35 for my $node (@_) {
689 69 ▶ next if $seen{$node->{id}};
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$node->{"id"}} 8 61 69
690 61 $seen{$node->{id}} = 1;
691 61 push(@unique, $node);
692 }
693 35 return @unique;
694 }
695  
696 19 ▶sub limit {
Subroutine limit: called CC=1 SCAR=0.0
697 19 my $entries = shift;
698 19 my $limit = shift;
699 # we want the most recent entries overall
700 19 @$entries = sort { DateTime->compare( $b->{date}, $a->{date} ) } unique(@$entries);
701 19 return [@$entries[0 .. min($#$entries, $limit - 1)]];
702 }
703  
704 =head2 Writing templates for entries
705  
706 Entries have the following keys available:
707  
708 B<title> is the title of the post.
709  
710 B<link> is the URL to the post on the web (probably a HTML page).
711  
712 B<blog_title> is the title of the site.
713  
714 B<blog_link> is the URL for the site on the web (probably a HTML page).
715  
716 B<blog_url> is the URL for the site's feed (RSS or Atom).
717  
718 B<authors> are the authors (or the Dublin Core contributor), a list of strings.
719  
720 B<date> is the publication date, as a DateTime object.
721  
722 B<day> is the publication date, in ISO date format: YYYY-MM-DD, for the UTC
723 timezone. The UTC timezone is picked so that the day doesn't jump back and forth
724 when sorting entries by date.
725  
726 B<content> is the full post content, as string or encoded HTML.
727  
728 B<excerpt> is the post content, limited to 500 characters, with paragraph
729 separators instead of HTML elements, as HTML. It is not encoded because the idea
730 is that it only gets added to the HTML and not to the feed, and the HTML it
731 contains is very controlled (only the pilcrow sign inside a span to indicate
732 paragraph breaks).
733  
734 B<categories> are the categories, a list of strings.
735  
736 B<element> is for internal use only. It contains the L<XML::LibXML::Element>
737 object. This could be RSS or Atom!
738  
739 B<feed> is for internal use only. It's a reference to the feed this entry
740 belongs to.
741  
742 =cut
743  
744 19 ▶sub add_data {
Subroutine add_data: called CC=22 SCAR=31.0
745 19 my $feeds = shift;
746 19 my $entries = shift;
747 # A note on the use of xml_escape: whenever we get data from the feed itself,
748 # it needs to be escaped if it gets printed into the HTML. For example: the
749 # feed contains a feed title of "Foo &amp; Bar". findvalue returns "Foo &
750 # Bar". When the template inserts the title, however, we want "Foo &amp; Bar",
751 # not "Foo & Bar". Thus: any text we get from the feed needs to be escaped
752 # if there's a chance we're going to print it again.
753 19 for my $feed (@$feeds) {
754 18 ▶ next unless $feed->{doc};
Branch: 1 branch
BranchTrueFalseTotal
unless $feed->{"doc"} 0 18 18
755 # title and url in the feed overrides title and xmlUrl set in the OPML (XML already escaped)
756 18 ▶ $feed->{title} = xml_escape($xpc->findvalue('/rss/channel/title | /atom:feed/atom:title', $feed->{doc})) || $feed->{title} || "";
Condition40%2/5
xml_escape($xpc->findvalue('/rss/channel/title | /atom:feed/atom:title', $feed->{'doc'})) || $feed->{'title'} || ''
l!l
180
xml_escape($xpc->findvalue("/rss/channel/title | /atom:feed/atom:title", $feed->{"doc"})) or $feed->{"title"}
l!l&&r!l&&!r
1800
MC/DC0%0/2
xml_escape($xpc->findvalue('/rss/channel/title | /atom:feed/atom:title', $feed->{'doc'})) || $feed->{'title'} || ''
xml_escape($xpc->findvalue("/rss/channel/title | /atom:feed/atom:title", $feed->{"doc"})) $feed->{"title"}
Truth table33%1/3
A or B
A= xml_escape($xpc->findvalue("/rss/channel/title | /atom:feed/atom:title", $feed->{"doc"}))B= $feed->{"title"}
ABresult
1X1
011
000
757 18 ▶ $feed->{url} = xml_escape($xpc->findvalue('/atom:feed/atom:link[@rel="self"]/@href', $feed->{doc})) || $feed->{url} || "";
Condition60%3/5
xml_escape($xpc->findvalue('/atom:feed/atom:link[@rel="self"]/@href', $feed->{'doc'})) || $feed->{'url'} || ''
l!l
180
xml_escape($xpc->findvalue("/atom:feed/atom:link[\@rel=\"self\"]/\@href", $feed->{"doc"})) or $feed->{"url"}
l!l&&r!l&&!r
2160
MC/DC0%0/2
xml_escape($xpc->findvalue('/atom:feed/atom:link[@rel="self"]/@href', $feed->{'doc'})) || $feed->{'url'} || ''
xml_escape($xpc->findvalue("/atom:feed/atom:link[\@rel=\"self\"]/\@href", $feed->{"doc"})) $feed->{"url"}
Truth table66%2/3
A or B
A= xml_escape($xpc->findvalue("/atom:feed/atom:link[\@rel=\"self\"]/\@href", $feed->{"doc"}))B= $feed->{"url"}
ABresult
1X1
011
000
758 # link in the feed does not override htmlUrl in the OPML (XML already escaped)
759 18 ▶ $feed->{link} = $feed->{link} || xml_escape($xpc->findvalue('/rss/channel/link | /atom:feed/atom:link[@rel="alternate"][@type="text/html"]/@href', $feed->{doc})) || "";
Condition100%5/5
$feed->{'link'} || xml_escape($xpc->findvalue('/rss/channel/link | /atom:feed/atom:link[@rel="alternate"][@type="text/html"]/@href', $feed->{'doc'})) || ''
l!l
135
$feed->{"link"} or xml_escape($xpc->findvalue("/rss/channel/link | /atom:feed/atom:link[\@rel=\"alternate\"][\@type=\"text/html\"]/\@href", $feed->{"doc"}))
l!l&&r!l&&!r
585
MC/DC100%2/2
$feed->{'link'} || xml_escape($xpc->findvalue('/rss/channel/link | /atom:feed/atom:link[@rel="alternate"][@type="text/html"]/@href', $feed->{'doc'})) || ''
$feed->{"link"} xml_escape($xpc->findvalue("/rss/channel/link | /atom:feed/atom:link[\@rel=\"alternate\"][\@type=\"text/html\"]/\@href", $feed->{"doc"}))
Truth table100%3/3
A or B
A= $feed->{"link"}B= xml_escape($xpc->findvalue("/rss/channel/link | /atom:feed/atom:link[\@rel=\"alternate\"][\@type=\"text/html\"]/\@href", $feed->{"doc"}))
ABresult
1X1
011
000
760 # if they just pasted a domain "foo" then "//foo" is a valid URL
761 18 ▶ $feed->{link} = "//" . $feed->{link} unless $feed->{link} =~ /\/\//;
Branch: 1 branch
BranchTrueFalseTotal
unless $feed->{"link"} =~ m[//]u 5 13 18
762 }
763 19 for my $entry (@$entries) {
764 # copy from the feed (XML is already escaped)
765 30 $entry->{blog_link} = $entry->{feed}->{link};
766 30 $entry->{blog_title} = $entry->{feed}->{title};
767 30 $entry->{blog_url} = $entry->{feed}->{url};
768 # parse the elements
769 30 my $element = $entry->{element};
770 30 ▶ $entry->{title} = xml_escape $xpc->findvalue('title | atom:title', $element) || "Untitled";
Condition100%2/2
$xpc->findvalue('title | atom:title', $element) || 'Untitled'
l!l
273
MC/DC100%1/1
$xpc->findvalue('title | atom:title', $element) || 'Untitled'
$xpc->findvalue('title | atom:title', $element)
Truth table100%2/2
A
A= $xpc->findvalue('title | atom:title', $element)
Aresult
11
00
771 30 my @links = map { xml_escape $_->to_literal } map { $xpc->findnodes($_, $element) }
772 # sorted by preferences!
773 qw(link atom:link[@rel="alternate"][@type="text/html"]/@href atom:link/@href);
774 30 ▶ $entry->{link} = shift(@links) || "";
Condition100%2/2
shift @links || ''
l!l
1218
MC/DC100%1/1
shift @links || ''
shift @links
Truth table100%2/2
A
A= shift @links
Aresult
11
00
775 30 my @authors = map { without_email(xml_escape strip_html($_->to_literal)) } $xpc->findnodes(
776 'author | atom:author/atom:name | atom:contributor/atom:name | dc:creator | dc:contributor', $element);
777 30 ▶ @authors = map { without_email(xml_escape strip_html($_->to_literal)) } $xpc->findnodes(
Branch: 1 branch
BranchTrueFalseTotal
unless @authors 25 5 30
778 '/atom:feed/atom:author/atom:name | '
779 . '/atom:feed/atom:contributor/atom:name | '
780 . '/rss/channel/dc:creator | '
781 . '/rss/channel/dc:contributor | '
782 . '/rss/channel/webMaster ', $element) unless @authors;
783 30 ▶ $entry->{authors} = @authors ? \@authors : undef; # key must exist in the hash
Branch: 1 branch
BranchTrueFalseTotal
@authors ? : 15 15 30
784 30 ▶ if (DateTime->compare($entry->{date}, $undefined_date) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ('DateTime'->compare($entry->{'date'}, $undefined_date) == 0) { } 5 25 30
785 5 $entry->{day} = "(no date found)";
786 } else {
787 25 $entry->{day} = $entry->{date}->clone->set_time_zone('UTC')->ymd; # operate on a clone
788 }
789 30 my @categories = map { xml_escape strip_html($_->to_literal) } $xpc->findnodes('category | atom:category/@term', $element);
790 30 ▶ $entry->{categories} = @categories ? \@categories : undef; # key must exist in the hash
Branch: 1 branch
BranchTrueFalseTotal
@categories ? : 6 24 30
791 30 $entry->{excerpt} = '';
792 30 $entry->{content} = '';
793 30 my @nodes = $xpc->findnodes('description[text()!=""] | atom:content[text()!=""]', $element);
794 30 ▶ @nodes = $xpc->findnodes('summary[text()!=""] | atom:summary[text()!=""] | itunes:summary[text()!=""]', $element) unless @nodes;
Branch: 1 branch
BranchTrueFalseTotal
unless @nodes 10 20 30
795 30 my $content = shift(@nodes);
796 # The default is that the content is either plain text or escaped HTML,
797 # which is what we want for RSS. For Atom feeds, type="xhtml" means that the
798 # content is XHTML, so it needs to be escaped.
799 30 ▶ if ($content) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content) 23 7 30
800 23 ▶ my $is_xhtml = $content->hasAttribute("type") && $content->getAttribute("type") eq "xhtml";
Condition100%3/3
$content->hasAttribute('type') && $content->getAttribute('type') eq 'xhtml'
!ll&&!rl&&r
1652
MC/DC100%2/2
$content->hasAttribute('type') && $content->getAttribute('type') eq 'xhtml'
$content->hasAttribute('type') $content->getAttribute('type') eq 'xhtml'
Truth table100%3/3
A && B
A= $content->hasAttribute('type')B= $content->getAttribute('type') eq 'xhtml'
ABresult
0X0
100
111
801 23 $entry->{excerpt} = excerpt($content->to_literal);
802 23 for my $child ($content->childNodes()) {
803 27 my $c = $child->toString();
804 27 ▶ $c = xml_escape $c if $is_xhtml;
Branch: 1 branch
BranchTrueFalseTotal
if $is_xhtml 6 21 27
805 27 $entry->{content} .= $c;
806 }
807 }
808 }
809 }
810  
811 23 ▶sub excerpt {
Subroutine excerpt: called CC=5 SCAR=16.1
812 23 my $content = shift;
813 23 ▶ return '(no excerpt)' unless $content;
Branch: 1 branch
BranchTrueFalseTotal
unless $content 0 23 23
814 23 my $doc = eval { XML::LibXML->load_html(recover => 2, string => $content) };
815 23 my $separator = "¶";
816 23 for my $node ($doc->findnodes('//style | //script | //time | //*[contains(@class, "post-header")] | //*[contains(@class, "post-share-buttons")] | //*[contains(@class, "post-footer")] | //*[contains(@class, "comments")]'),
817 ){
818 1 $node->parentNode->removeChild($node);
819 }
820 23 for my $node ($doc->findnodes('//p | //br | //blockquote | //li | //td | //th | //div | //h1 | //h2 | //h3 | //h4 | //h5 | //h6')) {
821 2 $node->appendTextNode($separator);
822 }
823 23 my $text = strip_html($doc->textContent());
824 23 $text =~ s/( +|----+)/ /g;
825 # collapse whitespace and trim
826 23 $text =~ s/\s+/ /g;
827 23 $text = trim $text;
828 # replace paragraph repeats with their surrounding spaces
829 23 $text =~ s/ ?¶( ?¶)* ?/¶/g;
830 23 $text =~ s/^¶//;
831 23 $text =~ s/¶$//;
832 23 my $len = length($text);
833 23 $text = substr($text, 0, 500);
834 23 ▶ $text .= "…" if $len > 500;
Branch: 1 branch
BranchTrueFalseTotal
if $len > 500 0 23 23
835 23 $text = xml_escape $text;
836 23 $text =~ s/¶/<span class="paragraph">¶ <\/span>/g;
837 23 return $text;
838 }
839  
840 # When there's a value that's supposed to be text but isn't, then we can try to
841 # turn it to HTML and from there to text... This is an ugly hack and I wish it
842 # wasn't necessary.
843 47 ▶sub strip_html {
Subroutine strip_html: called CC=3 SCAR=11.2
844 47 my $str = shift;
845 47 ▶ return '' unless $str;
Branch: 1 branch
BranchTrueFalseTotal
unless $str 0 47 47
846 47 my $doc = eval { XML::LibXML->load_html(string => $str) };
847 47 ▶ return $str unless $doc;
Branch: 1 branch
BranchTrueFalseTotal
unless $doc 0 47 47
848 47 return $doc->textContent();
849 }
850  
851 # Strip RSS 2.0 emails
852 18 ▶sub without_email {
Subroutine without_email: called CC=1 SCAR=0.0
853 18 my $str = shift;
854 18 $str =~ s/\S+@\S+ \(([^\)]+)\)/$1/;
855 18 return $str;
856 }
857  
858 =head1 SEE ALSO
859  
860 OPML 2.0, L<http://dev.opml.org/spec2.html>
861  
862 RSS 2.0, L<https://cyber.harvard.edu/rss/rss.html>
863  
864 Atom Syndication, L<https://tools.ietf.org/html/rfc4287>
865  
866 River of News,
867 L<http://scripting.com/2014/06/02/whatIsARiverOfNewsAggregator.html>
868  
869 =cut
870  
871 15 1;
↑ Summary blib/lib/App/jupiter.pm »