File Coverage

blib/lib/Mail/GcalReminder.pm
Criterion Covered Total %
statement 7 9 77.7
branch n/a
condition n/a
subroutine 3 3 100.0
pod n/a
total 10 12 83.3


line stmt bran cond sub pod time code
1             package Mail::GcalReminder;
2              
3             ## no critic (RequireUseStrict) - Moo does strict
4 5     5   229624 use Moo;
  5         82766  
  5         33  
5              
6             with 'Role::Multiton::New';
7              
8 5     5   13106 use Email::Send::SMTP::Gmail ();
  5         358364  
  5         409  
9 5     5   24389 use iCal::Parser ();
  0            
  0            
10             use DateTime ();
11              
12             our $VERSION = '0.5';
13              
14             has gmail_user => ( is => 'rw', required => 1 );
15              
16             has gmail_pass => ( is => 'rw', required => 1 );
17              
18             has app_name => ( is => 'rw', lazy => 1, builder => 1 );
19              
20             sub _build_app_name { return $_[0]->gmail_user . ' (' . __PACKAGE__ . ')' }
21              
22             has time_zone => (
23             is => 'rw',
24             default => sub { 'UTC' },
25             isa => sub {
26             require DateTime::TimeZone;
27             my $tz;
28             eval { $tz = DateTime::TimeZone->new( name => $_[0] ) };
29             die "DateTime::TimeZone does not recognize the given name" unless $tz;
30             }
31             );
32              
33             has cc_self => ( is => 'rw', default => sub { 1 } );
34              
35             has try_receipts => ( is => 'rw', default => sub { 1 } );
36              
37             has try_priority => ( is => 'rw', default => sub { 1 } );
38              
39             has no_guests_is_ok => ( is => 'rw', default => sub { 1 } );
40              
41             has include_event_dt_obj => ( is => 'rw', default => sub { 0 } );
42              
43             has http => (
44             is => 'rw',
45             'lazy' => 1,
46             'default' => sub {
47             require HTTP::Tiny;
48             return HTTP::Tiny->new();
49             },
50             isa => sub { die "http() must have a mirror method" unless $_[0]->can('mirror') },
51             );
52              
53             has workdir => (
54             is => 'rw',
55             'lazy' => 1,
56             'default' => sub {
57             require File::Temp;
58             return File::Temp->newdir();
59             },
60             isa => sub { die "workdir() must be a directory" unless -d $_[0] },
61             );
62              
63             has base_date => (
64             is => 'rw',
65             'lazy' => 1,
66             'default' => sub {
67             return DateTime->now( time_zone => $_[0]->time_zone );
68             },
69             'isa' => sub { die "only DateTime objects are supported" unless ref( $_[0] ) eq 'DateTime' },
70             );
71              
72             has essg_hax_ver => ( is => 'rw', 'default' => sub { 0.88 } );
73              
74             has warning_code => (
75             is => 'rw',
76             'default' => sub {
77             require Carp;
78             return sub {
79             shift;
80             local $Carp::CarpLevel += 1;
81             goto &Carp::carp;
82             }
83             }
84             );
85              
86             sub warning {
87             my ( $self, @args ) = @_;
88             $self->warning_code->( $self, @args );
89             }
90              
91             has date_format_obj => (
92             is => 'ro',
93             'lazy' => 1,
94             'default' => sub {
95             warn "date_format_obj() is deprecated and will be removed soon, please update your code";
96             require DateTime::Format::ISO8601;
97             return DateTime::Format::ISO8601->new();
98             },
99             );
100              
101             has signature => ( is => 'rw', lazy => 1, builder => 1 );
102              
103             sub _build_signature {
104             return "\n\n--\n" . $_[0]->app_name . "\n\nNote: Please ensure mail from “" . $_[0]->gmail_user . "” is not being filtered out of your inbox.";
105             }
106              
107             has debug => ( is => 'rw', default => sub { 0 } );
108              
109             has gcal_cache => ( is => 'rw', default => sub { {} }, isa => sub { die "gcal_cache must be a hashref" unless ref( $_[0] ) eq 'HASH' } );
110              
111             # TODO: clear_gcal() ?
112             sub get_gcal {
113             my ( $self, $gcal ) = @_;
114             my $cache = $self->gcal_cache();
115              
116             if ( !exists $cache->{$gcal} ) {
117              
118             my $q_end = $self->base_date->clone;
119             $q_end->add( days => 42 ); # TODO: start-max via object
120              
121             my $query_string = 'orderby=starttime&sortorder=a&start-min=' . $self->base_date->format_cldr('yyyy-MM-dd') . '&start-max=' . $q_end->format_cldr('yyyy-MM-dd') . '&max-results=100'; # TODO: max via object
122              
123             my $single_event = 1; # ? DO THIS ALL THE TIME?
124             my $addt = $single_event ? '&singleevents=true' : '';
125              
126             my $url = "http://www.google.com/calendar/ical/$gcal/basic.ics?$query_string$addt";
127             my $path = $gcal;
128             $path =~ s{/}{_slash_}g;
129             my $file = $self->workdir . "/$path.xml"; # TODO: make portable via File::Spec
130             my $res = $self->http->mirror( $url, $file );
131             if ( !$res->{success} ) {
132             die "Could not fetch “$url”: $res->{reason}\n";
133             }
134              
135             my $ics = eval {
136             iCal::Parser->new(
137             start => $self->base_date->format_cldr('yyyyMMdd'),
138             end => $q_end->format_cldr('yyyyMMdd'),
139             no_todos => 1,
140              
141             # TODO 2: best thing to do here ?tz => $self->time_zone,
142             )->parse($file);
143             };
144              
145             if ($@) {
146             die "Could not parse ICS ($file): $@";
147             }
148              
149             my %cal;
150              
151             my $gcal_title = $ics->{cals}[0]{'X-WR-CALNAME'};
152             my $gcal_updated = undef; # set if possible via BUILD_EVENT_LIST
153             my $gcal_updated_date = undef;
154             my $gcal_tz = $ics->{cals}[0]{'X-WR-TIMEZONE'};
155             my $gcal_uri = $gcal;
156             $gcal_uri =~ s{/p.*$}{};
157             my @entries;
158              
159             BUILD_EVENT_LIST:
160             for my $year ( sort { $a <=> $b } keys %{ $ics->{events} } ) {
161             for my $month ( sort { $a <=> $b } keys %{ $ics->{events}{$year} } ) {
162             for my $day ( sort { $a cmp $b } keys %{ $ics->{events}{$year}{$month} } ) {
163             for my $cuid ( sort { $ics->{events}{$year}{$month}{$day}{$a}{DTSTART}->iso8601() cmp $ics->{events}{$year}{$month}{$day}{$b}{DTSTART}->iso8601() } keys %{ $ics->{events}{$year}{$month}{$day} } ) {
164              
165             my $entry = $ics->{events}{$year}{$month}{$day}{$cuid};
166              
167             if ( !defined $gcal_updated || $gcal_updated->epoch() < $entry->{'LAST-MODIFIED'}->epoch() ) {
168             $gcal_updated = $entry->{'LAST-MODIFIED'}; # because ical cals data dies not contain last updated we have to get it from the events, needs set before BUILD_EVENTS_HASH
169             }
170              
171             # TODO 2 ?: $event_dt_obj->set_time_zone($gcal_tz);
172              
173             push @entries, $entry; # processed via BUILD_EVENTS_HASH
174             }
175             }
176             }
177             }
178              
179             if ( defined $gcal_updated ) {
180             $gcal_updated_date = $gcal_updated->format_cldr("E MMM d");
181             $gcal_updated = $gcal_updated->iso8601();
182             }
183              
184             BUILD_EVENTS_HASH:
185             for my $entry (@entries) {
186              
187             # use Devel::Kit::TAP;d($entry->{DTSTART}."");
188             # 'SUMMARY',
189             # 'LOCATION',
190             # 'hours',
191             # 'LAST-MODIFIED',
192             # 'UID',
193             # 'idref',
194             # 'STATUS',
195             # 'TRANSP',
196             # 'DTSTAMP',
197             # 'DTEND',
198             # 'CREATED',
199             # 'ORGANIZER',
200             # 'DESCRIPTION',
201             # 'DTSTART',
202             # 'ATTENDEE'
203              
204             my $event_dt_obj = $entry->{DTSTART};
205              
206             my @who;
207             if ( defined $entry->{ATTENDEE} && ref( $entry->{ATTENDEE} ) eq 'ARRAY' ) {
208             @who = map {
209             my $str = $_->{value};
210             $str =~ s/^mailto\://;
211             $str && $str !~ m/\@group.calendar.google.com$/ ? $str : ()
212             } @{ $entry->{ATTENDEE} };
213             }
214              
215             my $date = $event_dt_obj->format_cldr("E MMM d");
216             push @{ $cal{$date} }, {
217             'title' => $entry->{SUMMARY},
218             'desc' => $entry->{DESCRIPTION},
219             'url' => "https://www.google.com/calendar/embed?src=$gcal_uri", # TODO 1: URL to event, what is it given the data in the iCal?
220             'date' => $date,
221             'year' => $event_dt_obj->format_cldr("YYYY"),
222             'time' => $event_dt_obj->format_cldr("h:mm a"),
223             ( $self->include_event_dt_obj ? ( 'event_dt_obj' => $event_dt_obj ) : () ),
224             'location' => $entry->{'LOCATION'},
225             'guests' => \@who,
226              
227             'gcal_title' => $gcal_title,
228             'gcal_uri' => $url, # "https://www.google.com/calendar/embed?src=$gcal_uri",
229             'gcal_entry_obj' => $entry,
230             'gcal_updated' => $gcal_updated,
231             'gcal_updated_date' => $gcal_updated_date,
232             };
233              
234             }
235              
236             $cache->{$gcal} = \%cal;
237             }
238              
239             return $cache->{$gcal};
240             }
241              
242             sub send_reminders {
243             my ( $self, $conf ) = @_;
244              
245             my $gcal = $self->get_gcal( $conf->{'gcal'} );
246             my $name = $conf->{'label'} || $conf->{'gcal'};
247              
248             my $target = $self->base_date->clone();
249             $target->add( @{ $conf->{'in_advance'} } );
250             my $target_str = $target->format_cldr("E MMM d");
251              
252             return "0E0" if !exists $gcal->{$target_str} || !@{ $gcal->{$target_str} }; # no events that day
253              
254             my $event_cnt = @{ $gcal->{$target_str} };
255              
256             if ( $conf->{'min_events'} && $event_cnt < $conf->{'min_events'} ) {
257             $self->warning("Not enough events (min $conf->{'min_events'}, actual $event_cnt) for “$name”.");
258             }
259              
260             if ( $conf->{'max_events'} && $event_cnt > $conf->{'max_events'} ) {
261             $self->warning("Too many events (max $conf->{'max_events'}, actual $event_cnt) for “$name”.");
262             }
263              
264             # ? TODO ? warning() if $conf->{'max_events'} < $conf->{'min_events'}
265              
266             my $count = 0;
267             for my $event ( @{ $gcal->{$target_str} } ) {
268             my @guests = $event->{'guests'} ? @{ $event->{'guests'} } : ();
269             @guests = $conf->{'guestcheck'}->( $self, @guests ) if ref( $conf->{'guestcheck'} ) eq 'CODE';
270              
271             if (@guests) {
272             my $guests_cnt = @guests;
273             if ( $conf->{'min_guests'} && @guests < $conf->{'min_guests'} ) {
274             $self->warning("Not enough guests (min $conf->{'min_guests'}, actual $guests_cnt) for “$event->{'title'}”.");
275             }
276              
277             if ( $conf->{'max_guests'} && @guests > $conf->{'max_guests'} ) {
278             $self->warning("Too many guests (max $conf->{'max_guests'}, actual $guests_cnt) for “$event->{'title'}”.");
279             }
280              
281             # ? TODO ? warning() if $conf->{'max_guests'} < $conf->{'min_guests'}
282              
283             my $to = join( ',', @guests );
284             my $subject = ref( $conf->{'subject'} ) eq 'CODE' ? $conf->{'subject'}->( $self, $event ) : $conf->{'subject'}; # || ? TODO, default/warning/both ?
285             my $body = ref( $conf->{'body'} ) eq 'CODE' ? $conf->{'body'}->( $self, $event ) : $conf->{'body'}; # || ? TODO, default/warning/both ?
286              
287             $count++ if $self->send_gmail( $to, $subject, $body );
288             }
289             else {
290             $self->warning("No guests for “$event->{'title'}”.");
291             $count++ if $self->no_guests_is_ok;
292             }
293             }
294              
295             return unless $count == @{ $gcal->{$target_str} };
296             return $count;
297             }
298              
299             sub send_gmail {
300             my ( $self, $to, $subject, $body ) = @_;
301              
302             eval {
303             my $charset = 'UTF-8';
304              
305             # have to verify this still works as new versions come out
306             # Email::Send::SMTP::Gmail -charset 'bugure' header injection:
307             if ( $Email::Send::SMTP::Gmail::VERSION <= $self->essg_hax_ver ) {
308             if ( $self->try_receipts || $self->try_priority ) {
309              
310             # end charset header
311             $charset .= "\n";
312              
313             if ( $self->try_priority ) {
314              
315             # flag as important to help them see it:
316             $charset .= "X-Priority: 1\n";
317             $charset .= "Priority: Urgent\n";
318             $charset .= "Importance: high"; # !! no newline !! (\n is appended to -charset call in Email::Send::SMTP::Gmail)
319             $charset .= "\n" if $self->try_receipts; # so we can continue the hack
320             }
321              
322             if ( $self->try_receipts ) {
323              
324             # at least try to get some response:
325             $charset .= "X-Confirm-Reading-To: " . $self->gmail_user . "\n";
326             $charset .= "Return-Receipt-To: " . $self->gmail_user . "\n";
327             $charset .= "Disposition-Notification-To: " . $self->gmail_user; # !! no newline !! (\n is appended to -charset call in Email::Send::SMTP::Gmail)
328             }
329             }
330             }
331             else {
332             if ( $self->try_receipts || $self->try_priority ) {
333             my $essg_hax_ver = $self->essg_hax_ver;
334             $self->warning("Email::Send::SMTP::Gmail is newer than $essg_hax_ver, skipping header-via-charset hack");
335             }
336             }
337              
338             my $mail = Email::Send::SMTP::Gmail->new(
339             '-smtp' => 'smtp.gmail.com',
340             '-login' => $self->{'gmail_user'},
341             '-pass' => $self->{'gmail_pass'},
342             );
343              
344             $mail->send(
345             '-to' => ( $self->debug ? $self->gmail_user : $to ),
346             '-from' => $self->gmail_user,
347             ( $self->cc_self ? ( '-cc' => $self->gmail_user ) : () ),
348             '-subject' => $subject,
349             '-charset' => $charset,
350             '-verbose' => $self->debug,
351             '-body' => $body . $self->signature,
352             );
353              
354             $@ = $@; # send() is eval()
355              
356             $mail->bye;
357             };
358              
359             if ($@) {
360             $self->warning($@);
361             return;
362             }
363              
364             return 1;
365             }
366              
367             1;
368              
369             __END__