AdventCalendar.pm untested

filter: Statementstmt 0.0% 0 / 182 Branchbran 0.0% 0 / 28 Conditioncond 0.0% 0 / 17 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 260 SCAR 52.0
CC
13
Cov
0%
build
42.0
BUILD
20.0
read_articles
20.0
CRAP 182.0
1 package WWW::AdventCalendar 1.113;
2 # ABSTRACT: a calendar for a month of articles (on the web)
3  
4 use Moose;
5  
6 use MooseX::StrictConstructor;
7  
8 use autodie;
9 use Calendar::Simple 2; # the default start_day has changed
10 use Color::Palette 0.100002; # optimized_for, as_strict_css_hash
11 use Color::Palette::Schema;
12 use DateTime::Format::W3CDTF;
13 use DateTime;
14 use DateTime;
15 use Email::Simple;
16 use File::Basename;
17 use File::Copy qw(copy);
18 use File::Path 2.07 qw(remove_tree);
19 use File::ShareDir;
20 use Gravatar::URL ();
21 use HTML::Mason::Interp;
22 use Moose::Util::TypeConstraints;
23 use Path::Class ();
24 use WWW::AdventCalendar::Article;
25 use XML::Atom::SimpleFeed;
26  
27 use namespace::autoclean;
28  
29 #pod =head1 DESCRIPTION
30 #pod
31 #pod This is a library for producing Advent calendar websites. In other words, it
32 #pod makes four things:
33 #pod
34 #pod =for :list
35 #pod * a page saying "first door opens in X days" the calendar starts
36 #pod * a calendar page on and after the calendar starts
37 #pod * a page for each day in the month with an article
38 #pod * an Atom feed
39 #pod
40 #pod This library was originally written just for RJBS's Perl Advent Calendar, so it
41 #pod assumed you'd always be publishing from Dec 1 to Dec 24 or so. It has recently
42 #pod been retooled to work across arbitrary ranges, as long as they're within one
43 #pod month. This feature isn't well tested. Neither is the rest of the code, to be
44 #pod perfectly honest, though...
45 #pod
46 #pod =head1 OVERVIEW
47 #pod
48 #pod To build an Advent calendar:
49 #pod
50 #pod =for :list
51 #pod 1. create an advent.ini configuration file
52 #pod 2. write articles and put them in a directory
53 #pod 3. schedule F<advcal> to run nightly
54 #pod
55 #pod F<advent.ini> is easy to produce. Here's the one used for the original RJBS
56 #pod Advent Calendar:
57 #pod
58 #pod title = RJBS Advent Calendar
59 #pod year = 2009
60 #pod uri = http://advent.rjbs.manxome.org/
61 #pod editor = Ricardo Signes
62 #pod category = Perl
63 #pod category = RJBS
64 #pod
65 #pod article_dir = rjbs/articles
66 #pod share_dir = share
67 #pod
68 #pod These should all be self-explanatory. Only C<category> can be provided more
69 #pod than once, and is used for the category listing in the Atom feed.
70 #pod
71 #pod These settings all correspond to L<calendar attributes/ATTRIBUTES> described
72 #pod below. A few settings below are not given above.
73 #pod
74 #pod Articles are easy, too. They're just files in the C<article_dir>. They begin
75 #pod with an email-like set of headers, followed by a body written in Pod. For
76 #pod example, here's the beginning of the first article in the original calendar:
77 #pod
78 #pod Title: Built in Our Workshop, Delivered in Your Package
79 #pod Topic: Sub::Exporter
80 #pod
81 #pod =head1 Exporting
82 #pod
83 #pod In Perl, we organize our subroutines (and other stuff) into namespaces called
84 #pod packages. This makes it easy to avoid having to think of unique names for
85 #pod
86 #pod The two headers seen above, title and topic, are the only headers required,
87 #pod and correspond to those attributes in the L<WWW::AdventCalendar::Article>
88 #pod object created from the article file.
89 #pod
90 #pod Finally, running L<advcal> is easy, too. Here is its usage:
91 #pod
92 #pod advcal [-aot] [long options...]
93 #pod -c --config the ini file to read for configuration
94 #pod -a --article-dir the root of articles
95 #pod --share-dir the root of shared files
96 #pod -o --output-dir output directory
97 #pod --today the day we treat as "today"; default to today
98 #pod
99 #pod -y --year-links place year links at the bottom of the page
100 #pod
101 #pod Options given on the command line override those loaded form configuration. By
102 #pod running this program every day, we cause the calendar to be rebuilt, adding any
103 #pod new articles that have become available.
104 #pod
105 #pod =head1 ATTRIBUTES
106 #pod
107 #pod =for :list
108 #pod = title
109 #pod The title of the calendar, to be used in headers, the feed, and so on.
110 #pod = tagline
111 #pod A tagline for the calendar, used in some templates. Optional.
112 #pod = uri
113 #pod The base URI of the calendar, including trailing slash.
114 #pod = editor
115 #pod The name of the calendar's editor, used in the feed.
116 #pod = default_author
117 #pod The name of the calendar's default author, used for articles that provide none.
118 #pod = year
119 #pod The calendar year. Optional, if you provide C<start_date> and C<end_date>.
120 #pod = start_date
121 #pod The start of the article-containing period. Defaults to Dec 1 of the year.
122 #pod = end_date
123 #pod The end of the article-containing period. Defaults to Dec 24 of the year.
124 #pod = categories
125 #pod An arrayref of category names for use in the feed.
126 #pod = article_dir
127 #pod The directory in which articles can be found, with names like
128 #pod F<YYYY-MM-DD.html>.
129 #pod = share_dir
130 #pod The directory for templates, stylesheets, and other static content.
131 #pod = output_dir
132 #pod The directory into which output files will be written.
133 #pod = today
134 #pod The date to treat as "today" when deciding how much of the calendar to publish.
135 #pod
136 #pod =cut
137  
138 has title => (is => 'ro', required => 1);
139 has uri => (is => 'ro', required => 1);
140 has editor => (is => 'ro', required => 1);
141 has tagline => (is => 'ro', predicate => 'has_tagline');
142 has categories => (is => 'ro', default => sub { [ qw() ] });
143  
144 has article_dir => (is => 'rw', required => 1);
145 has share_dir => (is => 'rw', required => 1);
146 has output_dir => (is => 'rw', required => 1);
147 has year_links => (is => 'rw', required => 1, default => 0);
148  
149 has default_author => (
150   is => 'ro',
151   isa => 'Maybe[Str]', # should be using UndefTolerant instead!
152 # -- rjbs, 2011-11-08
153 );
154  
155 has year => (
156   is => 'ro',
157   lazy => 1,
158   default => sub {
159     my ($self) = @_;
160     return $self->start_date->year if $self->_has_start_date;
161     return $self->end_date->year if $self->_has_end_date;
162  
163     return (localtime)[5] + 1900;
164   },
165 );
166  
167 class_type('DateTime', { class => 'DateTime' });
168 coerce  'DateTime', from 'Str', via \&_parse_isodate;
169  
170 has start_date => (
171   is => 'ro',
172   isa => 'DateTime',
173   lazy => 1,
174   coerce => 1,
175   default => sub { DateTime->new(year => $_[0]->year, month => 12, day => 1) },
176   predicate => '_has_start_date',
177 );
178  
179 has end_date => (
180   is => 'ro',
181   isa => 'DateTime',
182   lazy => 1,
183   coerce => 1,
184   default => sub { DateTime->new(year => $_[0]->year, month => 12, day => 24) },
185   predicate => '_has_end_date',
186 );
187  
188 has today => (is => 'rw');
189  
190 class_type('Color::Palette', { class => 'Color::Palette' });
191  
192 has color_palette => (
193   is => 'ro',
194   isa => 'Color::Palette',
195   required => 1,
196 );
197  
198 has css_hrefs => (
199   traits => [ 'Array' ],
200   handles => { css_hrefs => 'elements' },
201   default => sub { [] },
202 );
203  
204 sub _masonize {
205   my ($self, $comp, $args) = @_;
206  
207   my $str = '';
208  
209   my $interp = HTML::Mason::Interp->new(
210     comp_root => [
211       [ user => $self->share_dir->subdir('templates')->absolute->stringify ],
212       [ stock => Path::Class::dir(
213           File::ShareDir::dist_dir('WWW-AdventCalendar') )
214           ->subdir('templates')->absolute->stringify
215       ],
216     ],
217     out_method => \$str,
218     allow_globals => [ '$calendar' ],
219   );
220  
221   $interp->set_global('$calendar', $self);
222  
223   $interp->exec($comp,
224     year_links => $self->year_links,
225     %$args
226   );
227  
228   return $str;
229 }
230  
231 sub _parse_isodate {
232   my ($date, $time_from) = @_;
233  
234   my ($y, $m, $d) = $date =~ /\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/;
235   die "can't parse date: $date\n" unless $y and $m and $d;
236  
237   $time_from ||= [ (0) x 10 ];
238  
239   return DateTime->new(
240     year => $y,
241     month => $m,
242     day => $d,
243     hour => $time_from->[2],
244     minute => $time_from->[1],
245     second => $time_from->[0],
246     time_zone => 'local',
247   );
248 }
249  
250 sub BUILD {
251   my ($self) = @_;
252  
253   $self->today(
254     $self->today
255     ? _parse_isodate($self->today, [localtime])
256     : DateTime->now(time_zone => 'local')
257   );
258  
259   confess "start_date, end_date, and year do not all agree"
260     unless $self->year == $self->start_date->year
261     and $self->year == $self->end_date->year;
262  
263   confess "range from start_date to end_date must not cross a month boundary"
264     if $self->start_date->month != $self->end_date->month;
265  
266   for (map { "$_\_dir" } qw(article output share)) {
267     $self->$_( Path::Class::Dir->new($self->$_) );
268   }
269 }
270  
271 #pod =method build
272 #pod
273 #pod $calendar->build;
274 #pod
275 #pod This method does all the work: it reads in the articles, decides how many to
276 #pod show, writes out the rendered pages, the index, and the atom feed.
277 #pod
278 #pod =cut
279  
280 my $SCHEMA = Color::Palette::Schema->new({
281   required_colors => [ qw(
282 bodyBG
283 bodyFG
284 blotterBG
285 blotterBorder
286 contentBG
287 contentBorder
288
289 feedLinkFG
290
291 headerFG
292
293 linkFG
294
295 linkDisabledFG
296
297 linkHoverFG
298 linkHoverBG
299
300 quoteBorder
301
302 sectionBorder
303
304 taglineBG
305 taglineFG
306 taglineBorder
307
308 titleFG
309
310 calendarHeaderCellBorder
311 calendarHeaderCellBG
312
313 calendarIgnoredDayBG
314
315 calendarPastDayBG
316 calendarPastDayFG
317
318 calendarPastDayHoverBG
319 calendarPastDayHoverFG
320
321 calendarTodayBG
322 calendarTodayFG
323
324 calendarTodayHoverBG
325 calendarTodayHoverFG
326
327 calendarFutureDayBG
328 calendarFutureDayFG
329
330 calendarMissingDayFG
331 calendarMissingDayBG
332
333 codeBG
334 codeFG
335
336 codeNumbersBG
337 codeNumbersFG
338 codeNumbersBorder
339 ) ],
340 });
341  
342 sub build {
343   my ($self) = @_;
344  
345   $self->output_dir->rmtree;
346   $self->output_dir->mkpath;
347  
348   my $share = $self->share_dir;
349   copy "$_" => $self->output_dir
350     for grep { ! $_->is_dir } $self->share_dir->subdir('static')->children;
351  
352   my $opt_palette = $self->color_palette->optimized_for($SCHEMA);
353  
354   $self->output_dir->file("style.css")->openw->print(
355     $self->_masonize('/style.css', {
356       color => $opt_palette->as_strict_css_hash,
357     }),
358   );
359  
360   my $feed = XML::Atom::SimpleFeed->new(
361     title => $self->title,
362     id => $self->uri,
363     link => {
364       rel => 'self',
365       href => $self->uri . 'atom.xml',
366     },
367     updated => $self->_w3cdtf($self->today),
368     author => $self->editor,
369   );
370  
371   my %month;
372   for (
373     1 .. DateTime->last_day_of_month(
374       year => $self->year,
375       month => $self->start_date->month
376     )->day
377   ) {
378     $month{$_} = DateTime->new(
379       year => $self->year,
380       month => $self->start_date->month,
381       day => $_,
382       time_zone => 'local',
383     );
384   }
385  
386   if ($self->start_date > $self->today) {
387     my $dur = $self->start_date->subtract_datetime_absolute( $self->today );
388     my $days = int($dur->delta_seconds / 86_400 + 1);
389     my $str = $days != 1 ? "$days days" : "1 day";
390  
391     $self->output_dir->file("index.html")->openw->print(
392       $self->_masonize('/patience.mhtml', {
393         days => $str,
394         year => $self->year,
395       }),
396     );
397  
398     $feed->add_entry(
399       title => $self->title . " is Coming",
400       link => $self->uri,
401       id => $self->uri,
402       summary => "The first door opens in $str...\n",
403       updated => $self->_w3cdtf($self->today),
404  
405       (map {; category => $_ } @{ $self->categories }),
406     );
407  
408     $feed->print( $self->output_dir->file('atom.xml')->openw );
409  
410     return;
411   }
412  
413   my $article = $self->read_articles;
414  
415   {
416     my $d = $month{1};
417     while (
418       $d->ymd le (sort { $a cmp $b } ($self->end_date->ymd, $self->today->ymd))[0]
419     ) {
420       warn "no article written for " . $d->ymd . "!\n"
421         if $d >= $self->start_date && ! $article->{ $d->ymd };
422  
423       $d = $d + DateTime::Duration->new(days => 1 );
424     }
425   }
426  
427   $self->output_dir->file('index.html')->openw->print(
428     $self->_masonize('/calendar.mhtml', {
429       today => $self->today,
430       year => $self->year,
431       month => \%month,
432       calendar => scalar calendar(12, $self->year, 0),
433       articles => $article,
434     }),
435   );
436  
437   my @dates = sort keys %$article;
438   for my $i (0 .. $#dates) {
439     my $date = $dates[ $i ];
440  
441     my $output;
442  
443     print "processing article for $date...\n";
444     my $txt = $self->_masonize('/article.mhtml', {
445       article => $article->{ $date },
446       date => $date,
447       next => ($i < $#dates ? $article->{ $dates[ $i + 1 ] } : undef),
448       prev => ($i > 0 ? $article->{ $dates[ $i - 1 ] } : undef),
449       year => $self->year,
450     });
451  
452     my $bytes = Encode::encode('utf-8', $txt);
453     $self->output_dir->file("$date.html")->openw->print($bytes);
454   }
455  
456   for my $date (reverse @dates){
457     my $article = $article->{ $date };
458  
459     $feed->add_entry(
460       title => HTML::Entities::encode_entities($article->title),
461       link => $self->uri . "$date.html",
462       id => $article->atom_id,
463       summary => $article->body_html,
464       updated => $self->_w3cdtf($article->date),
465       (map {; category => $_ } @{ $self->categories }),
466  
467       author => { name => $article->author_name },
468     );
469   }
470  
471   $feed->print( $self->output_dir->file('atom.xml')->openw );
472 }
473  
474 sub _w3cdtf {
475   my ($self, $datetime) = @_;
476   DateTime::Format::W3CDTF->new->format_datetime($datetime);
477 }
478  
479 #pod =method read_articles
480 #pod
481 #pod my $article = $calendar->read_articles;
482 #pod
483 #pod This method reads in all the articles for the calendar and returns a hashref.
484 #pod The keys are dates (in the format C<YYYY-MM-DD>) and the values are
485 #pod L<WWW::AdventCalendar::Article> objects.
486 #pod
487 #pod =cut
488  
489 sub read_articles {
490   my ($self) = @_;
491  
492   my %article;
493  
494   for my $file (grep { ! $_->is_dir } $self->article_dir->children) {
495     my ($name, $path) = fileparse($file);
496     $name =~ s{\..+\z}{}; # remove extension
497  
498     open my $fh, '<:encoding(utf-8)', $file;
499     my $content = do { local $/; <$fh> };
500     my $document = Email::Simple->new($content);
501     my $isodate = $name;
502  
503     die "no title set in $file\n" unless $document->header('title');
504  
505     my $article = WWW::AdventCalendar::Article->new(
506       body => scalar $document->body,
507       date => scalar _parse_isodate($isodate),
508       title => scalar $document->header('title'),
509       topic => scalar $document->header('topic'),
510       author => scalar $document->header('author')
511              // scalar $self->default_author,
512       calendar => $self,
513     );
514  
515     next unless $article->date < $self->today;
516  
517     die "already have an article for " . $article->date->ymd
518       if $article{ $article->date->ymd };
519  
520     $article{ $article->date->ymd } = $article;
521   }
522  
523   return \%article;
524 }
525  
526 1;
527  
528 __END__
529
530 =pod
531
532 =encoding UTF-8
533
534 =head1 NAME
535
536 WWW::AdventCalendar - a calendar for a month of articles (on the web)
537
538 =head1 VERSION
539
540 version 1.113
541
542 =head1 DESCRIPTION
543
544 This is a library for producing Advent calendar websites. In other words, it
545 makes four things:
546
547 =over 4
548
549 =item *
550
551 a page saying "first door opens in X days" the calendar starts
552
553 =item *
554
555 a calendar page on and after the calendar starts
556
557 =item *
558
559 a page for each day in the month with an article
560
561 =item *
562
563 an Atom feed
564
565 =back
566
567 This library was originally written just for RJBS's Perl Advent Calendar, so it
568 assumed you'd always be publishing from Dec 1 to Dec 24 or so. It has recently
569 been retooled to work across arbitrary ranges, as long as they're within one
570 month. This feature isn't well tested. Neither is the rest of the code, to be
571 perfectly honest, though...
572
573 =head1 OVERVIEW
574
575 To build an Advent calendar:
576
577 =over 4
578
579 =item 1
580
581 create an advent.ini configuration file
582
583 =item 2
584
585 write articles and put them in a directory
586
587 =item 3
588
589 schedule F<advcal> to run nightly
590
591 =back
592
593 F<advent.ini> is easy to produce. Here's the one used for the original RJBS
594 Advent Calendar:
595
596 title = RJBS Advent Calendar
597 year = 2009
598 uri = http://advent.rjbs.manxome.org/
599 editor = Ricardo Signes
600 category = Perl
601 category = RJBS
602
603 article_dir = rjbs/articles
604 share_dir = share
605
606 These should all be self-explanatory. Only C<category> can be provided more
607 than once, and is used for the category listing in the Atom feed.
608
609 These settings all correspond to L<calendar attributes/ATTRIBUTES> described
610 below. A few settings below are not given above.
611
612 Articles are easy, too. They're just files in the C<article_dir>. They begin
613 with an email-like set of headers, followed by a body written in Pod. For
614 example, here's the beginning of the first article in the original calendar:
615
616 Title: Built in Our Workshop, Delivered in Your Package
617 Topic: Sub::Exporter
618
619 =head1 Exporting
620
621 In Perl, we organize our subroutines (and other stuff) into namespaces called
622 packages. This makes it easy to avoid having to think of unique names for
623
624 The two headers seen above, title and topic, are the only headers required,
625 and correspond to those attributes in the L<WWW::AdventCalendar::Article>
626 object created from the article file.
627
628 Finally, running L<advcal> is easy, too. Here is its usage:
629
630 advcal [-aot] [long options...]
631 -c --config the ini file to read for configuration
632 -a --article-dir the root of articles
633 --share-dir the root of shared files
634 -o --output-dir output directory
635 --today the day we treat as "today"; default to today
636
637 -y --year-links place year links at the bottom of the page
638
639 Options given on the command line override those loaded form configuration. By
640 running this program every day, we cause the calendar to be rebuilt, adding any
641 new articles that have become available.
642
643 =head1 PERL VERSION
644
645 This module should work on any version of perl still receiving updates from
646 the Perl 5 Porters. This means it should work on any version of perl released
647 in the last two to three years. (That is, if the most recently released
648 version is v5.40, then this module should work on both v5.40 and v5.38.)
649
650 Although it may work on older versions of perl, no guarantee is made that the
651 minimum required version will not be increased. The version may be increased
652 for any reason, and there is no promise that patches will be accepted to lower
653 the minimum required perl.
654
655 =head1 METHODS
656
657 =head2 build
658
659 $calendar->build;
660
661 This method does all the work: it reads in the articles, decides how many to
662 show, writes out the rendered pages, the index, and the atom feed.
663
664 =head2 read_articles
665
666 my $article = $calendar->read_articles;
667
668 This method reads in all the articles for the calendar and returns a hashref.
669 The keys are dates (in the format C<YYYY-MM-DD>) and the values are
670 L<WWW::AdventCalendar::Article> objects.
671
672 =head1 ATTRIBUTES
673
674 =over 4
675
676 =item title
677
678 The title of the calendar, to be used in headers, the feed, and so on.
679
680 =item tagline
681
682 A tagline for the calendar, used in some templates. Optional.
683
684 =item uri
685
686 The base URI of the calendar, including trailing slash.
687
688 =item editor
689
690 The name of the calendar's editor, used in the feed.
691
692 =item default_author
693
694 The name of the calendar's default author, used for articles that provide none.
695
696 =item year
697
698 The calendar year. Optional, if you provide C<start_date> and C<end_date>.
699
700 =item start_date
701
702 The start of the article-containing period. Defaults to Dec 1 of the year.
703
704 =item end_date
705
706 The end of the article-containing period. Defaults to Dec 24 of the year.
707
708 =item categories
709
710 An arrayref of category names for use in the feed.
711
712 =item article_dir
713
714 The directory in which articles can be found, with names like
715 F<YYYY-MM-DD.html>.
716
717 =item share_dir
718
719 The directory for templates, stylesheets, and other static content.
720
721 =item output_dir
722
723 The directory into which output files will be written.
724
725 =item today
726
727 The date to treat as "today" when deciding how much of the calendar to publish.
728
729 =back
730
731 =head1 AUTHOR
732
733 Ricardo SIGNES <cpan@semiotic.systems>
734
735 =head1 CONTRIBUTORS
736
737 =for stopwords Len Jaffe Ricardo Signes Shoichi Kaji
738
739 =over 4
740
741 =item *
742
743 Len Jaffe <lenjaffe@jaffesystems.com>
744
745 =item *
746
747 Ricardo Signes <rjbs@semiotic.systems>
748
749 =item *
750
751 Shoichi Kaji <skaji@cpan.org>
752
753 =back
754
755 =head1 COPYRIGHT AND LICENSE
756
757 This software is copyright (c) 2022 by Ricardo SIGNES.
758
759 This is free software; you can redistribute it and/or modify it under
760 the same terms as the Perl 5 programming language system itself.
761
762 =cut