DAVTalk.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« DAVTalk/XMLParser.pm ↑ Summary
1 package Net::DAVTalk;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use HTTP::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=2.6
9 use Tie::DataUUID qw{$uuid};
10 use XML::Spice;
11 use Net::DAVTalk::XMLParser;
12 use MIME::Base64 qw(encode_base64);
13 use Encode qw(encode_utf8 decode_utf8);
14 use URI;
15 use URI::Escape qw(uri_escape uri_unescape);
16  
17 =head1 NAME
18  
19 Net::DAVTalk - Interface to talk to DAV servers
20  
21 =head1 VERSION
22  
23 Version 0.04
24  
25 =cut
26  
27 our $VERSION = '0.04';
28  
29  
30 =head1 SYNOPSIS
31  
32 Net::DAVTalk is was originally designed as a service module for Net::CalDAVTalk
33 and Net::DAVTalk, abstracting the process of connecting to a DAV server and
34 parsing the XML responses.
35  
36 Example:
37  
38 use Net::DAVTalk;
39 use XML::Spice;
40  
41 my $davtalk = Net::DAVTalk->new(
42 url => "https://dav.example.com/",
43 user => "foo\@example.com",
44 password => "letmein",
45 );
46  
47 $davtalk->Request(
48 'MKCALENDAR',
49 "$calendarId/",
50 x('C:mkcalendar', $Self->NS(),
51 x('D:set',
52 x('D:prop', @Properties),
53 ),
54 ),
55 );
56  
57 $davtalk->Request(
58 'DELETE',
59 "$calendarId/",
60 );
61  
62 =head1 SUBROUTINES/METHODS
63  
64 =head2 $class->new(%Options)
65  
66 Options:
67  
68 url: either full https?:// url, or relative base path on the
69 server to the DAV endpoint
70  
71 host, scheme and port: alternative to using full URL.
72 If URL doesn't start with https?:// then these will be used to
73 construct the endpoint URI.
74  
75 expandurl and wellknown: if these are set, then the wellknown
76 name (caldav and carddav are both defined) will be used to
77 resolve /.well-known/$wellknown to find the current-user-principal
78 URI, and then THAT will be resovlved to find the $wellknown-home-set
79 URI, which will be used as the URL for all further actions on
80 this object.
81  
82 user and password: if these are set, perform basic authentication.
83 user and access_token: if these are set, perform Bearer (OAUTH2)
84 authentication.
85  
86 =cut
87  
88 # General methods
89  
90 sub new {
91 my ($Class, %Params) = @_;
92  
93 unless ($Params{url}) {
94 confess "URL not supplied";
95 }
96  
97 # Assume url points to xyz-home-set, otherwise expand the url
98 if (delete $Params{expandurl}) {
99 # Locating Services for CalDAV and CardDAV (RFC6764)
100 my $PrincipalURL = $Class->GetCurrentUserPrincipal(%Params);
101  
102 my $HomeSet = $Class->GetHomeSet(
103 %Params,
104 url => $PrincipalURL,
105 );
106  
107 $Params{url} = $HomeSet;
108 }
109  
110 my $Self = bless \%Params, ref($Class) || $Class;
111 $Self->SetURL($Params{url});
112 $Self->ns(D => 'DAV:');
113  
114 return $Self;
115 }
116  
117 =head2 $Self->SetURL($url)
118  
119 Change the endpoint URL for an existing connection.
120  
121 =cut
122  
123 sub SetURL {
124 my ($Self, $URL) = @_;
125  
126 if ($URL =~ m{^https?://}) {
127 my ($HTTPS, $Hostname, $Port, $BasePath)
128 = $URL =~ m{^http(s)?://([^/:]+)(?::(\d+))?(.*)?};
129  
130 unless ($Hostname) {
131 confess "Invalid hostname in '$URL'";
132 }
133  
134 $Self->{scheme} = $HTTPS ? 'https' : 'http';
135 $Self->{host} = $Hostname;
136 $Self->{port} = ($Port || ($HTTPS ? 443 : 80));
137 $Self->{basepath} = $BasePath;
138 }
139 else {
140 $Self->{basepath} = $URL;
141 }
142  
143 $Self->{url} = "$Self->{scheme}://$Self->{host}:$Self->{port}$Self->{basepath}";
144  
145 return $Self->{url};
146 }
147  
148 =head2 $Self->fullpath($shortpath)
149  
150 Convert from a relative path to a full path:
151  
152 e.g
153 my $path = $Dav->fullpath('Default');
154 ## /dav/calendars/user/foo/Default
155  
156 NOTE: a you can pass a non-relative full path (leading /)
157 to this function and it will be returned unchanged.
158  
159 =cut
160  
161 sub fullpath {
162 my $Self = shift;
163 my $path = shift;
164 my $basepath = $Self->{basepath};
165 return $path if $path =~ m{^/};
166 return "$basepath/$path";
167 }
168  
169 =head2 $Self->shortpath($fullpath)
170  
171 Convert from a full path to a relative path
172  
173 e.g
174 my $path = $Dav->fullpath('/dav/calendars/user/foo/Default');
175 ## Default
176  
177 NOTE: if the full path is outside the basepath of the object, it
178 will be unchanged.
179  
180 my $path = $Dav->fullpath('/dav/calendars/user/bar/Default');
181 ## /dav/calendars/user/bar/Default
182  
183 =cut
184  
185 sub shortpath {
186 my $Self = shift;
187 my $origpath = shift;
188 my $basepath = $Self->{basepath};
189 my $path = $origpath;
190 $path =~ s{^$basepath/?}{};
191 return ($path eq '' ? $origpath : $path);
192 }
193  
194 =head2 $Self->Request($method, $path, $content, %headers)
195  
196 The whole point of the module! Perform a DAV request against the
197 endpoint, returning the response as a parsed hash.
198  
199 method: http method, i.e. GET, PROPFIND, MKCOL, DELETE, etc
200  
201 path: relative to base url. With a leading slash, relative to
202 server root, i.e. "Default/", "/dav/calendars/user/foo/Default".
203  
204 content: if the method takes a body, raw bytes to send
205  
206 headers: additional headers to add to request, i.e (Depth => 1)
207  
208 =cut
209  
210 sub Request {
211 my ($Self, $Method, $Path, $Content, %Headers) = @_;
212  
213 # setup request {{{
214  
215 $Content = '' unless defined $Content;
216 my $Bytes = encode_utf8($Content);
217  
218 $Self->{ua} ||= HTTP::Tiny->new(
219 agent => "Net-DAVTalk/0.01",
220 );
221  
222 $Headers{'Content-Type'} //= 'application/xml; charset=utf-8';
223  
224 if ($Self->{user}) {
225 $Headers{'Authorization'} = $Self->auth_header();
226 }
227  
228 # XXX - Accept-Encoding for gzip, etc?
229  
230 # }}}
231  
232 # send request {{{
233  
234 my $URI = $Self->request_url($Path);
235  
236 my $Response;
237  
238 my $OldAlarm = alarm 60;
239 eval {
240 local $SIG{ALRM} = sub { die 'timed out' };
241  
242 $Response = $Self->{ua}->request($Method, $URI, {
243 headers => \%Headers,
244 content => $Bytes,
245 });
246 };
247 alarm $OldAlarm;
248  
249 if ($@ and $@ =~ /timed out/) {
250 confess "Error with $Method for $URI (504, Gateway Timeout)";
251 }
252  
253 if ($Response->{status} == 301 or $Response->{status} == 302) {
254 my $location = URI->new_abs($Response->{headers}{location}, $URI);
255 if ($ENV{DEBUGDAV}) {
256 warn "******** REDIRECT $Response->{status} to $location\n";
257 }
258 $OldAlarm = alarm 60;
259 eval {
260 local $SIG{ALRM} = sub { die 'timed out' };
261  
262 $Response = $Self->{ua}->request($Method, $location, {
263 headers => \%Headers,
264 content => $Bytes,
265 });
266 };
267 alarm $OldAlarm;
268  
269 if ($@ and $@ =~ /timed out/) {
270 confess "Error with $Method for $Response->{headers}{location} (504, Gateway Timeout)";
271 }
272 }
273  
274 # one is enough
275  
276 if ($ENV{DEBUGDAV}) {
277 warn "<<<<<<<< " . Data::Dumper::Dumper({method => $Method, uri => $URI, headers => \%Headers, content => $Bytes }) . "\n\n";
278 warn ">>>>>>>> " . Data::Dumper::Dumper($Response) . "\n\n";
279 warn Data::Dumper::Dumper($Self->{ua});
280 }
281  
282 if ($Method eq 'REPORT' && $Response->{status} == 403) {
283 # maybe invalid sync token, need to return that fact
284 my $Encoded = Encode::decode_utf8($Response->{content});
285 my $Xml = xmlToHash($Encoded);
286 if (exists $Xml->{"{DAV:}valid-sync-token"}) {
287 return {
288 error => "valid-sync-token",
289 };
290 }
291 }
292  
293 unless ($Response->{success}) {
294 confess "Error with $Method for $URI ($Response->{status}, $Response->{reason})\n\n$Bytes\n\n$Response->{content}";
295 }
296  
297 my $ResponseContent = $Response->{content} || '';
298  
299 if ((grep { $Method eq $_ } qw{GET DELETE}) or ($Response->{status} != 207) or (not $ResponseContent)) {
300 return { content => $ResponseContent };
301 }
302  
303 # }}}
304  
305 # parse XML response {{{
306 my $Encoded = Encode::decode_utf8($ResponseContent);
307  
308 my $Xml = xmlToHash($Encoded);
309  
310 # Normalise XML
311  
312 if (exists($Xml->{"{DAV:}response"})) {
313 if (ref($Xml->{"{DAV:}response"}) ne 'ARRAY') {
314 $Xml->{"{DAV:}response"} = [ $Xml->{"{DAV:}response"} ];
315 }
316  
317 foreach my $Response (@{$Xml->{"{DAV:}response"}}) {
318 if (exists($Response->{"{DAV:}propstat"})) {
319 unless (ref($Response->{"{DAV:}propstat"}) eq 'ARRAY') {
320 $Response->{"{DAV:}propstat"} = [$Response->{"{DAV:}propstat"}];
321 }
322 }
323 }
324 }
325  
326 return $Xml;
327  
328 # }}}
329 }
330  
331 =head2 $Self->GetCurrentUserPrincipal()
332 =head2 $class->GetCurrentUserPrincipal(%Args)
333  
334 Can be called with the same args as new() as a class method, or
335 on an existing object. Either way it will use the .well-known
336 URI to find the path to the current-user-principal.
337  
338 Returns a string with the path.
339  
340 =cut
341  
342 sub GetCurrentUserPrincipal {
343 my ($Class, %Args) = @_;
344  
345 if (ref $Class) {
346 %Args = %{$Class};
347 $Class = ref $Class;
348 }
349  
350 my $OriginalURL = $Args{url} || '';
351 my $Self = $Class->new(%Args);
352 my $NS_D = $Self->ns('D');
353 my $NS_C = $Self->ns('C');
354 my @BasePath = split '/', $Self->{basepath};
355  
356 @BasePath = ('', ".well-known/$Args{wellknown}") unless @BasePath;
357  
358 PRINCIPAL: while(1) {
359 $Self->SetURL(join '/', @BasePath);
360  
361 my $Response = $Self->Request(
362 'PROPFIND',
363 '',
364 x('D:propfind', $Self->NS(),
365 x('D:prop',
366 x('D:current-user-principal'),
367 ),
368 ),
369 Depth => 0,
370 );
371  
372 foreach my $Response (@{$Response->{"{$NS_D}response"} || []}) {
373 foreach my $Propstat (@{$Response->{"{$NS_D}propstat"} || []}) {
374 if (my $Principal = $Propstat->{"{$NS_D}prop"}{"{$NS_D}current-user-principal"}{"{$NS_D}href"}{content}) {
375 $Self->SetURL(uri_unescape($Principal));
376 return $Self->{url};
377 }
378 }
379 }
380  
381 pop @BasePath;
382 last unless @BasePath;
383 }
384  
385 croak "Error finding current user principal at '$OriginalURL'";
386 }
387  
388 =head2 $Self->GetHomeSet
389 =head2 $class->GetHomeSet(%Args)
390  
391 Can be called with the same args as new() as a class method, or
392 on an existing object. Either way it assumes that the created
393 object has a 'url' parameter pointing at the current user principal
394 URL (see GetCurrentUserPrincipal above)
395  
396 Returns a string with the path to the home set.
397  
398 =cut
399  
400 sub GetHomeSet {
401 my ($Class, %Args) = @_;
402  
403 if (ref $Class) {
404 %Args = %{$Class};
405 $Class = ref $Class;
406 }
407  
408 my $OriginalURL = $Args{url} || '';
409 my $Self = $Class->new(%Args);
410 my $NS_D = $Self->ns('D');
411 my $NS_HS = $Self->ns($Args{homesetns});
412 my $HomeSet = $Args{homeset};
413  
414 my $Response = $Self->Request(
415 'PROPFIND',
416 '',
417 x('D:propfind', $Self->NS(),
418 x('D:prop',
419 x("$Args{homesetns}:$HomeSet"),
420 ),
421 ),
422 Depth => 0,
423 );
424  
425 foreach my $Response (@{$Response->{"{$NS_D}response"} || []}) {
426 foreach my $Propstat (@{$Response->{"{$NS_D}propstat"} || []}) {
427 if (my $Homeset = $Propstat->{"{$NS_D}prop"}{"{$NS_HS}$HomeSet"}{"{$NS_D}href"}{content}) {
428 $Self->SetURL($Homeset);
429 return $Self->{url};
430 }
431 }
432 }
433  
434 croak "Error finding $HomeSet home set at '$OriginalURL'";
435 }
436  
437 =head2 $Self->genuuid()
438  
439 Helper to generate a uuid string. Returns a UUID, e.g.
440  
441 my $uuid = $DAVTalk->genuuid(); # 9b9d68af-ad13-46b8-b7ab-30ab70da14ac
442  
443 =cut
444  
445 sub genuuid {
446 my $Self = shift;
447 return "$uuid";
448 }
449  
450 =head2 $Self->auth_header()
451  
452 Generate the authentication header to use on requests:
453  
454 e.g:
455  
456 $Headers{'Authorization'} = $Self->auth_header();
457  
458 =cut
459  
460 sub auth_header {
461 my $Self = shift;
462  
463 if ($Self->{password}) {
464 return 'Basic ' . encode_base64("$Self->{user}:$Self->{password}", '');
465 }
466  
467 if ($Self->{access_token}) {
468 return "Bearer $Self->{access_token}";
469 }
470  
471 croak "Need a method to authenticate user (password or access_token)";
472 }
473  
474 =head2 $Self->request_url()
475  
476 Generate the authentication header to use on requests:
477  
478 e.g:
479  
480 $Headers{'Authorization'} = $Self->auth_header();
481  
482 =cut
483  
484 sub request_url {
485 my $Self = shift;
486 my $Path = shift;
487  
488 my $URL = $Self->{url};
489  
490 if ($Path) {
491 $Path = join "/", map { uri_escape $_ } split m{/}, $Path, -1;
492 if ($Path =~ m{^/}) {
493 $URL =~ s{(^https?://[^/]+)(.*)}{$1$Path};
494 }
495 else {
496 $URL =~ s{/$}{};
497 $URL .= "/$Path";
498 }
499 }
500  
501 return $URL;
502 }
503  
504 =head2 $Self->NS()
505  
506 Returns a hashref of the 'xmlns:shortname' => 'full namespace' items for use in XML::Spice body generation, e.g.
507  
508 $DAVTalk->Request(
509 'MKCALENDAR',
510 "$calendarId/",
511 x('C:mkcalendar', $Self->NS(),
512 x('D:set',
513 x('D:prop', @Properties),
514 ),
515 ),
516 );
517  
518 # { 'xmlns:C' => 'urn:ietf:params:xml:ns:caldav', 'xmlns:D' => 'DAV:' }
519  
520 =cut
521  
522 sub NS {
523 my $Self = shift;
524  
525 return {
526 map { ( "xmlns:$_" => $Self->ns($_) ) }
527 $Self->ns(),
528 };
529 }
530  
531  
532 =head2 $Self->ns($key, $value)
533  
534 Get or set namespace aliases, e.g
535  
536 $Self->ns(C => 'urn:ietf:params:xml:ns:caldav');
537 my $NS_C = $Self->ns('C'); # urn:ietf:params:xml:ns:caldav
538  
539 =cut
540  
541 sub ns {
542 my $Self = shift;
543  
544 # case: keys
545 return keys %{$Self->{ns}} unless @_;
546  
547 my $key = shift;
548 # case read one
549 return $Self->{ns}{$key} unless @_;
550  
551 # case write
552 my $prev = $Self->{ns}{$key};
553 $Self->{ns}{$key} = shift;
554 return $prev;
555 }
556  
557 =head2 function2
558  
559 =cut
560  
561 =head1 AUTHOR
562  
563 Bron Gondwana, C<< <brong at cpan.org> >>
564  
565 =head1 BUGS
566  
567 Please report any bugs or feature requests to C<bug-net-davtalk at rt.cpan.org>, or through
568 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-DAVTalk>. I will be notified, and then you'll
569 automatically be notified of progress on your bug as I make changes.
570  
571  
572  
573  
574 =head1 SUPPORT
575  
576 You can find documentation for this module with the perldoc command.
577  
578 perldoc Net::DAVTalk
579  
580  
581 You can also look for information at:
582  
583 =over 4
584  
585 =item * RT: CPAN's request tracker (report bugs here)
586  
587 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-DAVTalk>
588  
589 =item * AnnoCPAN: Annotated CPAN documentation
590  
591 L<http://annocpan.org/dist/Net-DAVTalk>
592  
593 =item * CPAN Ratings
594  
595 L<http://cpanratings.perl.org/d/Net-DAVTalk>
596  
597 =item * Search CPAN
598  
599 L<http://search.cpan.org/dist/Net-DAVTalk/>
600  
601 =back
602  
603  
604 =head1 ACKNOWLEDGEMENTS
605  
606  
607 =head1 LICENSE AND COPYRIGHT
608  
609 Copyright 2015 FastMail Pty. Ltd.
610  
611 This program is free software; you can redistribute it and/or modify it
612 under the terms of the the Artistic License (2.0). You may obtain a
613 copy of the full license at:
614  
615 L<http://www.perlfoundation.org/artistic_license_2_0>
616  
617 Any use, modification, and distribution of the Standard or Modified
618 Versions is governed by this Artistic License. By using, modifying or
619 distributing the Package, you accept this license. Do not use, modify,
620 or distribute the Package, if you do not accept this license.
621  
622 If your Modified Version has been derived from a Modified Version made
623 by someone other than you, you are nevertheless required to ensure that
624 your Modified Version complies with the requirements of this license.
625  
626 This license does not grant you the right to use any trademark, service
627 mark, tradename, or logo of the Copyright Holder.
628  
629 This license includes the non-exclusive, worldwide, free-of-charge
630 patent license to make, have made, use, offer to sell, sell, import and
631 otherwise transfer the Package with respect to any patent claims
632 licensable by the Copyright Holder that are necessarily infringed by the
633 Package. If you institute patent litigation (including a cross-claim or
634 counterclaim) against any party alleging that the Package constitutes
635 direct or contributory patent infringement, then this Artistic License
636 to you shall terminate on the date that such litigation is filed.
637  
638 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
639 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
640 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
641 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
642 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
643 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
644 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
645 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
646  
647  
648 =cut
649  
650 1; # End of Net::DAVTalk
« DAVTalk/XMLParser.pm ↑ Summary