blib/lib/Mail/JMAPTalk.pm

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