blib/lib/Mail/JMAPTalk.pm

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