blib/lib/Mail/JMAPTalk.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 #!/usr/bin/perl -cw
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 package Mail::JMAPTalk;
7  
8 1 ▶use HTTP::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Convert::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use File::LibMagic;
Subroutine BEGIN: called CC=1 SCAR=2.6
12 use Carp qw(confess);
13 use Data::Dumper;
14  
15 our $VERSION = '0.17';
16  
17 our $CLIENT = "Mail-JMAPTalk";
18 our $AGENT = "$CLIENT/$VERSION";
19  
20 our $JSON = JSON->new->utf8->max_depth(2048);
21  
22 =head1 NAME
23  
24 Mail::JMAPTalk - Basic interface to talk to JMAP Servers
25  
26 =head1 VERSION
27  
28 Version 0.17
29  
30 =head1 SYNOPSIS
31  
32 Mail::JMAPTalk was originally written as a very small wrapper around HTTP::Tiny
33 to talk to a JMAP server and mapping between Perl hashes and JSON on the wire.
34  
35 It doesn't do anything smart with specific JMAP objects.
36  
37 Example:
38  
39 use Mail::JMAPTalk;
40 use JSON;
41  
42 # using basic auth
43 my $jtalk = Mail::JMAPTalk->new(
44 url => "https://jmap.example.com/",
45 user => "foo\@example.com",
46 password => "letmein",
47 );
48  
49 # using non-standard JMAPAuth token establishment
50 my $jtalk = Mail::JMAPTalk->new(
51 url => "https://jmap.example.com/",
52 );
53 $jtalk->Login("foo\@example.com", "letmein");
54  
55 my $res = $jtalk->Call('Mailbox/get');
56 my %byname = map { $_->{name} -> $_->{id} } @{$res->{ids});
57  
58 my $data = $jtalk->Upload($emailbytes, 'message/rfc822');
59 $res = $jtalk->CallMethods([['Email/import', {
60 emails => {
61 "1" => {
62 blobId => $data->{blobId},
63 keywords => { '$seen' => JSON::true },
64 mailboxIds => { $byname{Inbox} => JSON::true },
65 },
66 },
67 }, "R1"], ["Email/get", { ids => ["#1"] }, "R2" ]]);
68 # all properties of the email in $res->[1][1]{list}[0]
69  
70 my $response = $jtalk->Download($res->[1][1]{accountId}, $data->{blobId});
71  
72  
73 =head1 SUBROUTINES/METHODS
74  
75 =head2 $class->new(%Options)
76  
77 Create a new Mail::JMAPTalk object.
78  
79 Takes options for a variety of purposes:
80  
81 Override the UserAgent used for all connections:
82  
83 * ua => HTTP::Tiny->new(...)
84  
85 Host Options:
86  
87 * scheme => 'http' or 'https' (default 'http')
88 * host => hostname (default 'localhost')
89 * port => port number (default 443 for https, otherwise 80)
90  
91 URI Options: (absolute URI, or use options above to set the scope)
92  
93 * authurl => auth endpoint (default '/jmap/auth/')
94 * uploadurl => upload endpoint (default '/jmap/upload/{accountId}/')
95 * downloadurl => download endpoint (default '/jmap/download/{accountId}/{blobId}/{name}')
96 * url => JMAP API endpoint (default '/jmap/')
97  
98 Authentication Options: (basic auth)
99  
100 * user => $username
101 * password => $password
102  
103 Other Options:
104  
105 * SSL_options => a hashref of SSL options to pass down to the default user
106 agent
107  
108 Request Defaults:
109  
110 * using => \@urns (default ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:mail'])
111  
112 =cut
113  
114 sub new {
115 my ($Proto, %Args) = @_;
116 my $Class = ref($Proto) || $Proto;
117  
118 my $Self = bless { %Args }, $Class;
119  
120 $Self->{using} ||= ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:mail'];
121  
122 return $Self;
123 }
124  
125 =head2 my $ua = $Self->ua();
126  
127 =head2 $Self->ua($setua);
128  
129 Get or set the useragent (HTTP::Tiny or compatible) that will be used to make
130 the requests:
131  
132 e.g.
133  
134 my $ua = $Self->ua();
135  
136 $Self->ua(HTTP::Tiny->new(agent => "MyAgent/1.0", timeout => 5));
137  
138 =cut
139  
140 sub ua {
141 my $Self = shift;
142 unless ($Self->{ua}) {
143 $Self->{ua} = HTTP::Tiny->new(agent => $AGENT,
144 SSL_options => $Self->{SSL_options});
145 }
146 return $Self->{ua};
147 }
148  
149 =head2 my $header = $Self->auth_header();
150  
151 Returns the basic-auth value for the 'Authentication' header.
152  
153 =cut
154  
155 sub auth_header {
156 my $Self = shift;
157 return 'Basic ' . encode_base64("$Self->{user}:$Self->{password}", '');
158 }
159  
160 =head2 my $uri = $Self->authuri();
161  
162 Returns the URI for JMAPAuth authentication (non-standard). Default depends
163 on the parameters passed to new. Most simple would be:
164  
165 http://localhost/jmap/auth/
166  
167 =cut
168  
169 sub authuri {
170 my $Self = shift;
171 my $scheme = $Self->{scheme} // 'http';
172 my $host = $Self->{host} // 'localhost';
173 my $port = $Self->{port} // ($scheme eq 'http' ? 80 : 443);
174 my $url = $Self->{authurl} // '/jmap/auth/';
175  
176 return $url if $url =~ m/^http/;
177  
178 return "$scheme://$host:$port$url";
179 }
180  
181 =head2 my $uri = $Self->uploaduri($accountId);
182  
183 Returns the URI for JMAP uploads. Default depends
184 on the parameters passed to new. Most simple would be:
185  
186 http://localhost/jmap/upload/${accountId}/
187  
188 =cut
189  
190 sub uploaduri {
191 my $Self = shift;
192 my $accountId = shift;
193 die "need account" unless $accountId;
194 my $scheme = $Self->{scheme} // 'http';
195 my $host = $Self->{host} // 'localhost';
196 my $port = $Self->{port} // ($scheme eq 'http' ? 80 : 443);
197 my $url = $Self->{uploadurl} // '/jmap/upload/{accountId}/';
198  
199 my %map = (
200 accountId => $accountId,
201 );
202 $url =~ s/\{([a-zA-Z0-9_]+)\}/$map{$1}||''/ges;
203  
204 return $url if $url =~ m/^http/;
205  
206 return "$scheme://$host:$port$url";
207 }
208  
209 =head2 my $uri = $Self->downloaduri($accountId, $blobId, $name);
210  
211 Returns the URI for JMAP downloads. Default depends
212 on the parameters passed to new. Most simple would be:
213  
214 http://localhost/jmap/download/${accountId}/${blobId}/{$name}
215  
216 Where name is utf8 and uri encoded to be safe.
217  
218 =cut
219  
220 sub downloaduri {
221 my $Self = shift;
222 my ($accountId, $blobId, $name) = @_;
223 die "need account and blob" unless ($accountId and $blobId);
224 $name ||= "download";
225 my $scheme = $Self->{scheme} // 'http';
226 my $host = $Self->{host} // 'localhost';
227 my $port = $Self->{port} // ($scheme eq 'http' ? 80 : 443);
228 my $url = $Self->{downloadurl} // '/jmap/download/{accountId}/{blobId}/{name}';
229  
230 # needs to be encoded as bytes for URI encoding
231 utf8::encode($name);
232  
233 my %map = (
234 accountId => $accountId,
235 blobId => $blobId,
236 name => $name =~ s/([^a-zA-Z0-9])/sprintf('%%%02X', ord($1))/egr
237 );
238  
239 $url =~ s/\{([a-zA-Z0-9_]+)\}/$map{$1}||''/ges;
240  
241 return $url if $url =~ m/^http/;
242  
243 return "$scheme://$host:$port$url";
244 }
245  
246 =head2 my $uri = $Self->uri()
247  
248 Returns the URI for JMAP API Calls. Default depends
249 on the parameters passed to new. Most simple would be:
250  
251 http://localhost/jmap/
252  
253 =cut
254  
255 sub uri {
256 my $Self = shift;
257 my $scheme = $Self->{scheme} // 'http';
258 my $host = $Self->{host} // 'localhost';
259 my $port = $Self->{port} // ($scheme eq 'http' ? 80 : 443);
260 my $url = $Self->{url} // '/jmap/';
261  
262 return $url if $url =~ m/^http/;
263  
264 return "$scheme://$host:$port$url";
265 }
266  
267 =head2 my $uri = $Self->JSONPOST($Uri, $Request, %Headers)
268  
269 Makes a POST request to the given URI with the body being the
270 value of $Request (which must be a reference) encoded as JSON,
271 and with the Headers added.
272  
273 Will set Content-Type and Accept headers to 'application/json'
274 unless overridden.
275  
276 Generally you won't call this directly, but through one of the
277 helper methods.
278  
279 This method will die if the response is not successful or does not
280 contain valid json.
281  
282 =cut
283  
284 sub JSONPOST {
285 my ($Self, $Uri, $Request, %Headers) = @_;
286  
287 $Headers{'Content-Type'} //= "application/json";
288 $Headers{'Accept'} //= "application/json";
289  
290 my $Response = $Self->ua->post($Uri, {
291 headers => \%Headers,
292 content => $JSON->encode($Request),
293 });
294  
295 my $jdata;
296 $jdata = eval { $JSON->decode($Response->{content}) } if $Response->{success};
297  
298 if ($ENV{DEBUGJMAP}) {
299 warn "JMAP " . Dumper($Uri, \%Headers, $Request, $Response);
300 }
301  
302 # check your own success on the Response object
303 if (wantarray) {
304 return ($Response, $jdata);
305 }
306  
307 confess "JMAP request for $Self->{user} failed ($Uri): $Response->{status} $Response->{reason}: $Response->{content}"
308 unless $Response->{success};
309  
310 confess "INVALID JSON $Response->{content}" unless $jdata;
311  
312 return $jdata;
313 }
314  
315 =head2 $Self->AuthRequest($Request, %Headers)
316  
317 Makes a JSONPOST request to the authurl.
318  
319 =cut
320  
321 sub AuthRequest {
322 my ($Self, $Request, %Headers) = @_;
323  
324 return $Self->JSONPOST($Self->authuri(), $Request, %Headers);
325 }
326  
327 =head2 $Self->Login($Username, $Password)
328  
329 Uses the non-standard JMAPAuth protocol to login.
330  
331 On success will set the upload, download and api urls as well as
332 a token which is used to authenticate all further requests.
333  
334 On failure will die.
335  
336 =cut
337  
338 sub Login {
339 my ($Self, $Username, $Password) = @_;
340  
341 my $data = $Self->AuthRequest({
342 username => $Username,
343 clientName => $CLIENT,
344 clientVersion => $VERSION,
345 deviceName => $Self->{deviceName} || 'api',
346 });
347  
348 while ($data->{loginId}) {
349 die "Unknown method" unless grep { $_->{type} eq 'password' } @{$data->{methods}};
350 $data = $Self->AuthRequest({
351 loginId => $data->{loginId},
352 type => 'password',
353 password => $Password,
354 });
355 }
356  
357 die "Failed to get a token" unless $data->{accessToken};
358  
359 $Self->{token} = $data->{accessToken};
360 $Self->{url} = $data->{apiUrl};
361 $Self->{uploaduri} = $data->{uploadUrl};
362 $Self->{downloaduri} = $data->{downloadUrl};
363 $Self->{eventSource} = $data->{eventSource};
364  
365 return 1;
366 }
367  
368 =head2 $Self->Request($Request, %Headers)
369  
370 Makes a JSONPOST request to the API url, authenticated with either
371 the basic auth parameters given at creation, or the token obtained
372 via Login.
373  
374 =cut
375  
376 sub Request {
377 my ($Self, $Request, %Headers) = @_;
378  
379 if ($Self->{user}) {
380 $Headers{'Authorization'} = $Self->auth_header();
381 }
382 if ($Self->{token}) {
383 $Headers{'Authorization'} = "Bearer $Self->{token}";
384 }
385  
386 return $Self->JSONPOST($Self->uri(), $Request, %Headers);
387 }
388  
389 =head2 my $using = $Self->DefaultUsing()
390  
391 =head2 $Self->DefaultUsing(\@urns)
392  
393 Returns or replaces the default 'using' value for method calls.
394  
395 =cut
396  
397 sub DefaultUsing {
398 my ($Self, $Using) = @_;
399 return $Self->{using} unless $Using;
400 $Self->{using} = $Using;
401 }
402  
403 =head2 $Self->AddUsing(@urns)
404  
405 Appends any urns given to the default 'using'
406 if they aren't already registered.
407  
408 =cut
409  
410 sub AddUsing {
411 my $Self = shift;
412 foreach my $Using (@_) {
413 next if grep { $_ eq $Using } @{$Self->{using}};
414 push @{$Self->{using}}, $Using;
415 }
416 }
417  
418 =head2 $Self->CallMethods($MethodCalls, $Using, %Headers)
419  
420 Generates a JMAP request from the given method calls,
421 optionally overriding the using and header values.
422  
423 MethodCalls is an array of arrays, each of the sub arrays
424 is a single "Invocation" per RFC8620 as follows:
425  
426 3.2. The Invocation Data Type
427  
428 Method calls and responses are represented by the *Invocation* data
429 type. This is a tuple, represented as a JSON array containing three
430 elements:
431  
432 1. A "String" *name* of the method to call or of the response.
433  
434 2. A "String[*]" object containing named *arguments* for that method
435 or response.
436  
437 3. A "String" *method call id*: an arbitrary string from the client
438 to be echoed back with the responses emitted by that method call
439 (a method may return 1 or more responses, as it may make implicit
440 calls to other methods; all responses initiated by this method
441 call get the same method call id in the response).
442  
443 In perl, this is [string, hashref, string].
444  
445 Example:
446  
447 my $res = $jtalk->CallMethods([
448 ['Email/query', { }, 'R1'],
449 ['Email/get', {
450 '#ids' => {
451 resultOf => 'R1',
452 name => 'Email/query',
453 path => '/ids'
454 },
455 properties => [ 'subject', 'header:x-mood:asText', 'from', 'to' ],
456 }, 'R2'],
457 ]);
458  
459 The response is an arrayref containing the value of methodResponses from the
460 JSON reply defined in JMAP.
461  
462 This method will die if the server returns an error or invalid JSON.
463  
464 =cut
465  
466 sub CallMethods {
467 my ($Self, $MethodCalls, $Using, %Headers) = @_;
468  
469 $Using ||= $Self->{using};
470  
471 my $Request = {
472 using => $Using,
473 methodCalls => $MethodCalls,
474 createdIds => $Self->{CreatedIds} || {},
475 };
476  
477 my $Response = $Self->Request($Request, %Headers);
478  
479 $Self->{CreatedIds} = $Response->{createdIds};
480 $Self->{SessionState} = $Response->{sessionState};
481  
482 return $Response->{methodResponses};
483 }
484  
485 =head2 $Self->Call($Method, $Params, $Using, %Headers)
486  
487 A convenience method to call a single method. This method
488 generates a single invocation with call id 'c1' and will
489 return undef unless the first response from the server has
490 the same method name (i.e. is not an error) and the same
491 call id.
492  
493 The return value is the response section (middle field) of
494 the first methodResponse Invocation object.
495  
496 Example:
497  
498 my $res = $jtalk->Call('Calendar/get', { properties => ['name'] });
499 my %byname = map { $_->{name} => $_->{id} } @{$res->{list}};
500  
501 =cut
502  
503 sub Call {
504 my ($Self, $Method, $Params, @Args) = @_;
505 $Params ||= {};
506 my $Res = $Self->CallMethods([[$Method, $Params, "c1"]], @Args);
507 return undef unless ref $Res;
508 return undef unless ref $Res->[0];
509 return undef unless $Res->[0][0] eq $Method;
510 return undef unless $Res->[0][2] eq 'c1';
511 return $Res->[0]->[1];
512 }
513  
514 sub _get_type {
515 my $data = shift;
516 # XXX - escape file names?
517 my $magic = File::LibMagic->new();
518 my $info = $magic->info_from_string($data);
519 return $info->{mime_type};
520 }
521  
522 =head2 $Self->Upload($Headers?, $data, $mimetype, $accountId)
523  
524 If the first argument is a hash reference, it will be shifted
525 and used as additional headers.
526  
527 Uploads the bytes in $data with either the given mimetype or
528 if the mimetype is not given, the type picked by File::LibMagic.
529  
530 The POST request is authenticated with either the basic auth
531 parameters given at creation, or the token obtained via Login.
532  
533 If called in scalar context, will die unless the request was
534 successful - and returns a hashref with the content returned
535 by the server as defined in RFC8620:
536  
537 A successful request MUST return a single JSON object with the
538 following properties as the response:
539  
540 o accountId: "Id"
541  
542 The id of the account used for the call.
543  
544 o blobId: "Id"
545  
546 The id representing the binary data uploaded. The data for this
547 id is immutable. The id *only* refers to the binary data, not any
548 metadata.
549  
550 o type: "String"
551  
552 The media type of the file (as specified in [RFC6838],
553 Section 4.2) as set in the Content-Type header of the upload HTTP
554 request.
555  
556 o size: "UnsignedInt"
557  
558 The size of the file in octets.
559  
560 If called in array context, returns two values - the first is the raw
561 HTTP::Tiny response hash, and the second is the JSON as above.
562  
563 Example:
564  
565 my ($Response, $data) = $jtalk->Upload($bytes);
566 if ($Response->{success}) {
567 say "Uploaded $data->{size} bytes as $data->{blobId}";
568 ...
569 }
570  
571 =cut
572  
573 sub Upload {
574 my $Self = shift;
575 my %Headers;
576 if (ref($_[0]) eq 'HASH') {
577 %Headers = %{ (shift) };
578 }
579 my ($data, $type, $accountId) = @_;
580  
581 $Headers{'Content-Type'} = $type || _get_type($data);
582 $accountId = $accountId || $Self->{user};
583  
584 if ($Self->{user}) {
585 $Headers{'Authorization'} = $Self->auth_header();
586 }
587 if ($Self->{token}) {
588 $Headers{'Authorization'} = "Bearer $Self->{token}";
589 }
590  
591 my $uri = $Self->uploaduri($accountId);
592  
593 my $Response = $Self->ua->post($uri, {
594 headers => \%Headers,
595 content => $data,
596 });
597  
598 if ($ENV{DEBUGJMAP}) {
599 warn "JMAP UPLOAD " . Dumper($Response);
600 }
601  
602 my $jdata;
603 $jdata = eval { $JSON->decode($Response->{content}) } if $Response->{success};
604  
605 # check your own success on the Response object
606 if (wantarray) {
607 return ($Response, $jdata);
608 }
609  
610 confess "JMAP request for $Self->{user} failed ($uri): $Response->{status} $Response->{reason}: $Response->{content}"
611 unless $Response->{success};
612  
613 confess "INVALID JSON $Response->{content}" unless $jdata;
614  
615 return $jdata;
616 }
617  
618 =head2 $Self->Download($cb?, $Headers?, $accountId, $blobId, $name)
619  
620 Makes a GET request authenticated with either the basic auth parameters
621 given at creation, or the token obtained via Login.
622  
623 If the first argument is a code reference, it will be shifted and used
624 as the data_callback (see HTTP::Tiny).
625  
626 Then - if the first argument is a hash reference, it will be shifted
627 and used as additional headers.
628  
629 Then - the remaining parameters are passed to $Self->downloadurl() to
630 generate the link to download.
631  
632 The response is a HTTP::Tiny Response object.
633  
634 Example:
635  
636 my $res = $jtalk->Download($accountId, $data->{blobId}, "image.gif");
637 if ($res->{success}) {
638 open(FH, ">image.gif");
639 print FH $res->{content};
640 close(FH);
641 }
642  
643 =cut
644  
645 sub Download {
646 my $Self = shift;
647 my $cb;
648 if (ref($_[0]) eq 'CODE') {
649 $cb = shift;
650 }
651 my %Headers;
652 if (ref($_[0]) eq 'HASH') {
653 %Headers = %{ (shift) };
654 }
655 my $uri = $Self->downloaduri(@_);
656  
657 if ($Self->{user}) {
658 $Headers{'Authorization'} = $Self->auth_header();
659 }
660 if ($Self->{token}) {
661 $Headers{'Authorization'} = "Bearer $Self->{token}";
662 }
663  
664 my %getopts = (headers => \%Headers);
665 $getopts{data_callback} = $cb if $cb;
666 my $Response = $Self->ua->get($uri, \%getopts);
667  
668 if ($ENV{DEBUGJMAP}) {
669 warn "JMAP DOWNLOAD @_ " . Dumper($Response);
670 }
671  
672 return $Response;
673 }
674  
675 1;
676 __END__
↑ Summary