AdventCalendar.pm untested

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