| 1 | package Plagger::Plugin::Publish::iCal; | ||
| 2 | use strict; | ||
| 3 | use base qw( Plagger::Plugin ); | ||
| 4 | |||
| 5 | use File::Spec; | ||
| 6 | use Data::ICal; | ||
| 7 | use Data::ICal::Entry::Event; | ||
| 8 | use DateTime::Duration; | ||
| 9 | use DateTime::Format::ICal; | ||
| 10 | use Plagger::Util; | ||
| 11 | |||
| 12 | sub register { | ||
| 13 | my($self, $context) = @_; | ||
| 14 | $context->register_hook( | ||
| 15 | $self, | ||
| 16 | 'publish.feed' => \&publish_feed, | ||
| 17 | 'plugin.init ' => \&plugin_init, | ||
| 18 | ); | ||
| 19 | } | ||
| 20 | |||
| 21 | sub plugin_init { | ||
| 22 | my($self, $context) = @_; | ||
| 23 | |||
| 24 | my $dir = $self->conf->{dir}; | ||
| 25 | unless (-e $dir && -d _) { | ||
| 26 | mkdir $dir, 0755 or $context->error("Failed to mkdir $dir: $!"); | ||
| 27 | } | ||
| 28 | } | ||
| 29 | |||
| 30 | sub publish_feed { | ||
| 31 | my($self, $context, $args) = @_; | ||
| 32 | |||
| 33 | my $feed = $args->{feed}; | ||
| 34 | my $ical = Data::ICal->new; | ||
| 35 | $ical->add_properties( | ||
| 36 | 'X-WR-CALNAME' => $feed->title, | ||
| 37 | ); | ||
| 38 | |||
| 39 | for my $entry ($feed->entries) { | ||
| 40 | my $date = $entry->date; | ||
| 41 | my $event = Data::ICal::Entry::Event->new; | ||
| 42 | |||
| 43 | my $tz = $date->time_zone; | ||
| 44 | |||
| 45 | my $dt = [ $date->format('ICal'), {} ]; | ||
| 46 | $dt->[0] =~ s/^TZID=(.*?):// | ||
| 47 | and $dt->[1]->{TZID} = $1; | ||
| 48 | |||
| 49 | if ($date->hms eq '00:00:00') { | ||
| 50 | $dt->[1]->{VALUE} = 'DATE'; | ||
| 51 | } | ||
| 52 | |||
| 53 | $event->add_properties( | ||
| 54 | summary => $entry->title, | ||
| 55 | description => $entry->summary ? $entry->summary->plaintext : '', | ||
| 56 | dtstart => $dt, | ||
| 57 | dtend => $dt, | ||
| 58 | ); | ||
| 59 | $ical->add_entry($event); | ||
| 60 | } | ||
| 61 | |||
| 62 | my $file = Plagger::Util::filename_for($feed, $self->conf->{filename} || '%i.ics'); | ||
| 63 | my $path = File::Spec->catfile($self->conf->{dir}, $file); | ||
| 64 | |||
| 65 | my $data = $ical->as_string; | ||
| 66 | utf8::decode($data) unless utf8::is_utf8($data); | ||
| 67 | |||
| 68 | open my $output, ">:utf8", $path or $context->error("$path: $!"); | ||
| 69 | print $output $data; | ||
| 70 | close $output; | ||
| 71 | |||
| 72 | $context->log(info => "Wrote iCalendar file to $path"); | ||
| 73 | } | ||
| 74 | |||
| 75 | 1; | ||
| 76 | __END__ |