FindEntry.pm

filter: Statementstmt 81.8% 9 / 11 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 86.6% 13 / 15 CC 1 SCAR 0.7
CC
1
Cov
82%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Utils.pm ↑ Summary
1 package Net::CalDAV::FindEntry 0.01;
2 1 ▶use 5.020;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use experimental 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 0 ▶use Net::CalDAVTalk;
Subroutine BEGIN: called CC=1 SCAR=2.6
6 use Net::CalDAV::Utils;
7 use Text::JSCalendar;
8  
9 use Moo 2;
10  
11 =head1 NAME
12  
13 Net::CalDAV::FindEntry - find calendar entries overlapping a timespan
14  
15 =head1 SYNOPSIS
16  
17 use 5.020;
18 my $cal = Net::CalDAV::FindEntry->new(
19 user => 'AzureDiamond',
20 password => 'hunter2',
21 calendar_url => 'https://example.com/calendar/',
22 );
23 if( 0 ) {
24 $cal->ua->verify_SSL(0);
25 }
26 my @relevant_events = $cal->get_events(
27 after => '2026-09-01T09:00:00',
28 before => '2026-09-01T16:00:00',
29 calendar => 'Work'
30 );
31 for ( sort { $a->{start} cmp $b->{start} } @relevant_events) {
32 say(join( "-", $_->{start}, $_->{title} ));
33 }
34  
35 =cut
36  
37 has ['user','password','calendar_url'] => (
38 is => 'ro',
39 required => 1,
40 );
41  
42 has 'calendar' => (
43 is => 'ro',
44 );
45  
46 has 'cal' => (
47 is => 'lazy',
48 default => \&_get_calendar,
49 handles => ['ua', 'logger'],
50 );
51  
52 =head1 METHODS
53  
54 =cut
55  
56 sub _get_calendar($self, %options) {
57 return Net::CalDAVTalk::Extended->new(
58 user => $options{ user } // $self->user,
59 password => $options{ password } // $self->password,
60 url => $options{ calendar_url } // $self->calendar_url,
61 logger => sub { warn "DAV: @_" },
62 );
63 }
64  
65 # We need this filtering to account for events that start before our boundaries
66 # like whole-day events
67 sub event_overlaps( $start, $duration, $after, $before, $str=undef ) {
68 my $starts_before_end = ($start le $before);
69 my $ends_after_start = (dtend( $start, $duration) gt $after);
70 #warn sprintf "%s - %s - %s - %s [%s] [%s] - %s", $after, $start, $before, dtend( $start, $duration ),
71 # $starts_before_end ? 'x' : ' ',
72 # $ends_after_start ? 'x' : ' ',
73 # $str
74 # ;
75 return
76 $starts_before_end && $ends_after_start;
77 }
78  
79 sub overlapping_events( $Events, $after, $before ) {
80 my @relevant_events;
81  
82 # Filter the returned events for overlap
83 EVENT: for my $e ($Events->@*) {
84 my $title;
85 my ($start, $duration);
86  
87 # For recurring events we want all events that somehow overlap with $after and $before
88 if( scalar keys $e->{recurrenceOverrides}->%*) {
89 my @matching = grep { event_overlaps( $_, $e->{recurrenceOverrides}->{$_}->{duration}, $after, $before, "" )
90 } sort { $a cmp $b } keys $e->{recurrenceOverrides}->%*;
91 if( ! @matching ) {
92 next EVENT;
93 };
94 for my $t ( @matching ) {
95 $title //= $e->{recurrenceOverrides}->{$t}->{title};
96 $start //= $t;
97 $duration //= $e->{recurrenceOverrides}->{$t}->{duration};
98 };
99 };
100 $title //= $e->{title};
101 $start //= $e->{start};
102 $duration //= $e->{duration};
103  
104 if( !event_overlaps( $start, $duration, $after, $before, $title )) {
105 #warn "Ignoring '$title'";
106 next EVENT;
107 }
108  
109 push @relevant_events, {
110 start => tslocal( $start ),
111 title => $title,
112 _e => $e,
113 };
114 }
115 return @relevant_events
116 }
117  
118 sub get_events( $self, %args ) {
119  
120 my $before = $args{ before }
121 or croak "Need 'before'";
122 my $after = $args{ after }
123 or croak "Need 'after'";
124 my $calendar = $args{ calendar } // $self->calendar;
125  
126 # To also catch things that start (up to) two days before the current timestamp...
127 my $_after = Text::JSCalendar::_wireDate($after)->add(days => -2)->strftime('%Y-%m-%dT%H:%M:%S');
128  
129 my @Events = $self->cal->GetEventsEx($calendar, after => $_after, before => $before)->@*;
130 my @relevant_events = overlapping_events( \@Events, $after, $before );
131 }
132  
133 package Net::CalDAVTalk::Extended 0.01;
134 use 5.020;
135 use Moo 2;
136 use experimental 'signatures';
137  
138 =head1 NAME
139  
140 Net::CalDAVTalk::Extended - convenience functions and bugfixes for Net::CalDAVTalk
141  
142 =cut
143  
144 extends 'Net::CalDAVTalk';
145 use XML::Spice;
146 use URI::Escape qw(uri_unescape);
147 use Net::CalDAV::Utils;
148  
149 =head1 METHODS
150  
151 =head2 C<< ->GetEventLinksEx >>
152  
153 my $links = $cal->GetEventLinksEx( after => '...', before => '...' );
154  
155 Allows filtering for events within a time range without truncating
156 the C<before> and C<after> values to whole days.
157  
158 =cut
159  
160 sub GetEventLinksEx {
161 my ($Self, $calendarId, %Args) = @_;
162 die "Need a calendarId" unless $calendarId;
163 my @Extra;
164 if ($Args{AlwaysRange} || $Args{after} || $Args{before}) {
165 my $Start = Text::JSCalendar::_wireDate($Args{after} || die);
166 my $End = Text::JSCalendar::_wireDate($Args{before} || die);
167 push @Extra, x('C:time-range', {
168 start => $Start->strftime('%Y%m%dT%H%M%SZ'),
169 end => $End->strftime('%Y%m%dT%H%M%SZ'),
170 });
171 }
172 my $payload = x('C:calendar-query', $Self->NS(),
173 x('D:prop',
174 x('D:getetag'),
175 ),
176 x('C:filter',
177 x('C:comp-filter', { name => 'VCALENDAR' },
178 x('C:comp-filter', { name => 'VEVENT' },
179 @Extra,
180 ),
181 ),
182 ),
183 ),
184 ;
185 my $Response = $Self->Request(
186 'REPORT',
187 "$calendarId/",
188 $payload,
189 Depth => 1,
190 );
191 my (%Links, @Errors);
192 my $NS_A = $Self->ns('A');
193 my $NS_C = $Self->ns('C');
194 my $NS_D = $Self->ns('D');
195 foreach my $Response (@{$Response->{"{$NS_D}response"} || []}) {
196 my $href = uri_unescape($Response->{"{$NS_D}href"}{content} // '');
197 next unless $href;
198 foreach my $Propstat (@{$Response->{"{$NS_D}propstat"} || []}) {
199 my $etag = $Propstat->{"{$NS_D}prop"}{"{$NS_D}getetag"}{content};
200 $Links{$href} = $etag;
201 }
202 }
203 return \%Links;
204 }
205  
206 =head2 C<< ->GetEventsEx >>
207  
208 Like C<< ->GetEvents >> but expands all recurrences to the actual timespan
209 instead of leaving that to the calling client. This requires RFC 4791
210 support by the CalDAV server.
211  
212 =cut
213  
214 # Copied from Net::CalDAVTalk, because we need to create a C:expand element
215 sub GetEventsEx($cal, $calendar, %Args) {
216 my $urls = GetEventLinksEx($cal, $calendar, %Args);
217 my $AnnotNames;
218 my @Annotations;
219  
220 my (@Events, @Errors, %Links);
221 if( $urls->%* ) {
222  
223 my %Args = ( start => $Args{ after } , end => $Args{before} );
224  
225 my $payload =
226 x('C:calendar-multiget', $cal->NS(),
227 x('D:prop',
228 x('C:calendar-data',
229 x('C:expand', \%Args),
230 x('C:limit-recurrence-set', \%Args),
231 ),
232 x('D:getetag'),
233 @Annotations,
234 ),
235 map { x('D:href', $_) } sort keys $urls->%*,
236 );
237 my $Response = $cal->Request(
238 'REPORT',
239 "$calendar/",
240 $payload,
241 Depth => 1,
242 );
243  
244 my $NS_A = $cal->ns('A');
245 my $NS_C = $cal->ns('C');
246 my $NS_D = $cal->ns('D');
247 for my $Response (@{$Response->{"{$NS_D}response"} || []}) {
248 my $href = uri_unescape($Response->{"{$NS_D}href"}{content} // '');
249 next unless $href;
250 foreach my $Propstat (@{$Response->{"{$NS_D}propstat"} || []}) {
251 my $etag = $Propstat->{"{$NS_D}prop"}{"{$NS_D}getetag"}{content};
252 $Links{$href} = $etag;
253 my $Prop = $Propstat->{"{$NS_D}prop"}{"{$NS_C}calendar-data"};
254 my $Data = $Prop->{content};
255 next unless $Data;
256 my $Event;
257 if ($Prop->{'-content-type'} and $Prop->{'-content-type'} =~ m{application/event\+json}) {
258 # JSON event is in API format already
259 $Event = eval { decode_json($Data) };
260 }
261 else {
262 # returns an array, but there should only be one UID per file
263 # Suppress property warnings here as JSCalendar raises otherwise
264 # unsuppressible warnings :-/
265 my $org_warn = $SIG{ __WARN__ };
266 local $SIG{ __WARN__ } = sub {
267 return if $_[0] =~ /DTEND and DURATION/;
268 goto &$org_warn;
269 };
270  
271 ($Event) = eval { $cal->vcalendarToEvents($Data) };
272 }
273 if ($@) {
274 push @Errors, $@;
275 next;
276 }
277 next unless $Event;
278 if ($Args{Full}) {
279 $Event->{_raw} = $Data;
280 }
281 $Event->{href} = $href;
282 $Event->{id} = $cal->shortpath($href);
283 foreach my $key (@$AnnotNames) {
284 my $propns = $NS_C;
285 my $name = $key;
286 if ($key =~ m/(.*):(.*)/) {
287 $name = $2;
288 $propns = $cal->ns($1);
289 }
290 my $AData = $Propstat->{"{$NS_D}prop"}{"{$propns}$name"}{content};
291 next unless $AData;
292 $Event->{annotation}{$name} = $AData;
293 }
294 push @Events, $Event;
295 }
296 }
297 }
298 return wantarray ? (\@Events, \@Errors) : \@Events;
299 }
300  
301 1;
302  
303 =head1 REPOSITORY
304  
305 The public repository of this module is
306 L<https://github.com/Corion/Net-CalDAV-FindEntry>.
307  
308 =head1 SUPPORT
309  
310 The public support forum of this module is L<https://perlmonks.org/>.
311  
312 =head1 BUG TRACKER
313  
314 Please report bugs in this module via the Github bug queue at
315 L<https://github.com/Corion/Net-CalDAV-FindEntry/issues>
316  
317  
318 =head1 AUTHOR
319  
320 Max Maischein C<corion@cpan.org>
321  
322 =head1 LICENSE
323  
324 This module is released under the same terms as Perl itself.
325  
326 =cut
« Utils.pm ↑ Summary