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   197925 use Moo;
  5         101070  
  5         37  
5              
6             with 'Role::Multiton::New';
7              
8 5     5   15360 use Email::Send::SMTP::Gmail ();
  5         391055  
  5         156  
9 5     5   8689 use XML::Simple ();
  0            
  0            
10             use DateTime ();
11              
12             our $VERSION = '0.4';
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.82 } );
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             require DateTime::Format::ISO8601;
96             return DateTime::Format::ISO8601->new();
97             },
98             );
99              
100             has signature => ( is => 'rw', lazy => 1, builder => 1 );
101              
102             sub _build_signature {
103             return "\n\n--\n" . $_[0]->app_name . "\n\nNote: Please ensure mail from “" . $_[0]->gmail_user . "” is not being filtered out of your inbox.";
104             }
105              
106             has debug => ( is => 'rw', default => sub { 0 } );
107              
108             has gcal_cache => ( is => 'rw', default => sub { {} }, isa => sub { die "gcal_cache must be a hashref" unless ref( $_[0] ) eq 'HASH' } );
109              
110             # TODO: clear_gcal() ?
111             sub get_gcal {
112             my ( $self, $gcal ) = @_;
113             my $cache = $self->gcal_cache();
114              
115             if ( !exists $cache->{$gcal} ) {
116              
117             my $q_end = $self->base_date->clone;
118             $q_end->add( days => 42 ); # TODO: start-max via object
119              
120             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
121              
122             my $single_event = 1; # ? DO THIS ALL THE TIME?
123             my $addt = $single_event ? '&singleevents=true' : '';
124              
125             # https://developers.google.com/google-apps/calendar/v2/reference#Calendar_feeds
126             my $url = "http://www.google.com/calendar/feeds/$gcal/full?$query_string$addt";
127              
128             my $path = $gcal;
129             $path =~ s{/}{_slash_}g;
130             my $file = $self->workdir . "/$path.xml"; # TODO: make portable via File::Spec
131             my $res = $self->http->mirror( $url, $file );
132             if ( !$res->{success} ) {
133             die "Could not fetch “$url”: $res->{reason}\n";
134             }
135              
136             my $xml = eval { XML::Simple::XMLin( $file, ForceArray => [ 'gd:who', 'link' ] ) };
137             if ($@) {
138             die "Could not parse XML ($file): $@";
139             }
140              
141             my %cal;
142              
143             my $gcal_title = $xml->{title}{content};
144             my $gcal_updated = $xml->{updated};
145             my $gcal_tz = $xml->{'gCal:timezone'}{'value'};
146             my $gcal_updated_date = defined $gcal_updated ? $self->date_format_obj->parse_datetime($gcal_updated)->format_cldr("E MMM d") : undef;
147              
148             for my $entry_key ( sort { $xml->{entry}{$a}{'gd:when'}{'startTime'} cmp $xml->{entry}{$b}{'gd:when'}{'startTime'} } keys %{ $xml->{entry} } ) {
149             my $entry = $xml->{entry}{$entry_key};
150              
151             my $event_dt_obj = $self->date_format_obj->parse_datetime( $entry->{'gd:when'}{'startTime'} );
152              
153             # $event_dt_obj->set_time_zone($gcal_tz);
154              
155             # TODO: factor author in attendees ?
156             # 'author' => {
157             # 'email' => 'steeplechase.public.talks@gmail.com',
158             # 'name' => 'Steeplechase Public Talks Coord'
159             # },
160              
161             my $attendees_ar = $entry->{'gd:who'};
162             my @who;
163             if ( defined $attendees_ar && ref($attendees_ar) eq 'ARRAY' ) {
164             @who = map {
165             my $str = $_->{email};
166             $str && $str !~ m/\@group.calendar.google.com$/ ? $str : ()
167             } @{$attendees_ar};
168             }
169              
170             my $date = $event_dt_obj->format_cldr("E MMM d");
171             push @{ $cal{$date} }, {
172             'title' => $entry->{title}{content},
173             'desc' => $entry->{content}{content},
174              
175             'url' => $entry->{link}[0]{type} eq 'text/html' ? $entry->{link}[0]{href} : $entry->{link}[1]{href},
176             'date' => $date,
177             'year' => $event_dt_obj->format_cldr("YYYY"),
178             'time' => $event_dt_obj->format_cldr("h:mm a"),
179             ( $self->include_event_dt_obj ? ( 'event_dt_obj' => $event_dt_obj ) : () ),
180             'location' => $entry->{'gd:where'}{valueString},
181             'guests' => \@who,
182              
183             'gcal_title' => $gcal_title,
184             'gcal_uri' => $url,
185             'gcal_entry_obj' => $entry,
186             'gcal_updated' => $gcal_updated,
187             'gcal_updated_date' => $gcal_updated_date,
188             };
189             }
190              
191             $cache->{$gcal} = \%cal;
192             }
193              
194             return $cache->{$gcal};
195             }
196              
197             sub send_reminders {
198             my ( $self, $conf ) = @_;
199              
200             my $gcal = $self->get_gcal( $conf->{'gcal'} );
201             my $name = $conf->{'label'} || $conf->{'gcal'};
202              
203             my $target = $self->base_date->clone();
204             $target->add( @{ $conf->{'in_advance'} } );
205             my $target_str = $target->format_cldr("E MMM d");
206              
207             return "0E0" if !exists $gcal->{$target_str} || !@{ $gcal->{$target_str} }; # no events that day
208              
209             my $event_cnt = @{ $gcal->{$target_str} };
210              
211             if ( $conf->{'min_events'} && $event_cnt < $conf->{'min_events'} ) {
212             $self->warning("Not enough events (min $conf->{'min_events'}, actual $event_cnt) for “$name”.");
213             }
214              
215             if ( $conf->{'max_events'} && $event_cnt > $conf->{'max_events'} ) {
216             $self->warning("Too many events (max $conf->{'max_events'}, actual $event_cnt) for “$name”.");
217             }
218              
219             # ? TODO ? warning() if $conf->{'max_events'} < $conf->{'min_events'}
220              
221             my $count = 0;
222             for my $event ( @{ $gcal->{$target_str} } ) {
223             my @guests = $event->{'guests'} ? @{ $event->{'guests'} } : ();
224             @guests = $conf->{'guestcheck'}->( $self, @guests ) if ref( $conf->{'guestcheck'} ) eq 'CODE';
225              
226             if (@guests) {
227             my $guests_cnt = @guests;
228             if ( $conf->{'min_guests'} && @guests < $conf->{'min_guests'} ) {
229             $self->warning("Not enough guests (min $conf->{'min_guests'}, actual $guests_cnt) for “$event->{'title'}”.");
230             }
231              
232             if ( $conf->{'max_guests'} && @guests > $conf->{'max_guests'} ) {
233             $self->warning("Too many guests (max $conf->{'max_guests'}, actual $guests_cnt) for “$event->{'title'}”.");
234             }
235              
236             # ? TODO ? warning() if $conf->{'max_guests'} < $conf->{'min_guests'}
237              
238             my $to = join( ',', @guests );
239             my $subject = ref( $conf->{'subject'} ) eq 'CODE' ? $conf->{'subject'}->( $self, $event ) : $conf->{'subject'}; # || ? TODO, default/warning/both ?
240             my $body = ref( $conf->{'body'} ) eq 'CODE' ? $conf->{'body'}->( $self, $event ) : $conf->{'body'}; # || ? TODO, default/warning/both ?
241              
242             $count++ if $self->send_gmail( $to, $subject, $body );
243             }
244             else {
245             $self->warning("No guests for “$event->{'title'}”.");
246             $count++ if $self->no_guests_is_ok;
247             }
248             }
249              
250             return unless $count == @{ $gcal->{$target_str} };
251             return $count;
252             }
253              
254             sub send_gmail {
255             my ( $self, $to, $subject, $body ) = @_;
256              
257             eval {
258             my $charset = 'UTF-8';
259              
260             # have to verify this still works as new versions come out
261             # Email::Send::SMTP::Gmail -charset 'bugure' header injection:
262             if ( $Email::Send::SMTP::Gmail::VERSION <= $self->essg_hax_ver ) {
263             if ( $self->try_receipts || $self->try_priority ) {
264              
265             # end charset header
266             $charset .= "\n";
267              
268             if ( $self->try_priority ) {
269              
270             # flag as important to help them see it:
271             $charset .= "X-Priority: 1\n";
272             $charset .= "Priority: Urgent\n";
273             $charset .= "Importance: high"; # !! no newline !! (\n is appended to -charset call in Email::Send::SMTP::Gmail)
274             $charset .= "\n" if $self->try_receipts; # so we can continue the hack
275             }
276              
277             if ( $self->try_receipts ) {
278              
279             # at least try to get some response:
280             $charset .= "X-Confirm-Reading-To: " . $self->gmail_user . "\n";
281             $charset .= "Return-Receipt-To: " . $self->gmail_user . "\n";
282             $charset .= "Disposition-Notification-To: " . $self->gmail_user; # !! no newline !! (\n is appended to -charset call in Email::Send::SMTP::Gmail)
283             }
284             }
285             }
286             else {
287             if ( $self->try_receipts || $self->try_priority ) {
288             my $essg_hax_ver = $self->essg_hax_ver;
289             $self->warning("Email::Send::SMTP::Gmail is newer than $essg_hax_ver, skipping header-via-charset hack");
290             }
291             }
292              
293             my $mail = Email::Send::SMTP::Gmail->new(
294             '-smtp' => 'smtp.gmail.com',
295             '-login' => $self->{'gmail_user'},
296             '-pass' => $self->{'gmail_pass'},
297             );
298              
299             $mail->send(
300             '-to' => ( $self->debug ? $self->gmail_user : $to ),
301             '-from' => $self->gmail_user,
302             ( $self->cc_self ? ( '-cc' => $self->gmail_user ) : () ),
303             '-subject' => $subject,
304             '-charset' => $charset,
305             '-verbose' => $self->debug,
306             '-body' => $body . $self->signature,
307             );
308              
309             $@ = $@; # send() is eval()
310              
311             $mail->bye;
312             };
313              
314             if ($@) {
315             $self->warning($@);
316             return;
317             }
318              
319             return 1;
320             }
321              
322             1;
323              
324             __END__