GeoIP2/WebService/Client.pm

filter: Statementstmt 97.4% 151 / 155 Branchbran 100% 14 / 14 Conditioncond 73.6% 14 / 19 MC/DCmcdc 50.0% 5 / 10 Subroutinesub 94.8% 37 / 39 Podpod 75.0% 3 / 4 totaltotal 92.9% 224 / 241 CC 15 SCAR 7.1
CC
15
Cov
95%
_handle_4xx_status
5.0
__ANON__
4.0
BUILD
3.0
CRAP 2.0
« GeoIP2/Database/Reader.pm ↑ Summary GeoIP2.pm »
1 package GeoIP2::WebService::Client;
2 1 $GeoIP2::WebService::Client::VERSION = '0.050000';
3 1 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use Data::Validate::IP 0.19 qw( is_public_ipv4 is_public_ipv6 );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use GeoIP2::Error::Generic;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use GeoIP2::Error::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use GeoIP2::Error::IPAddressNotFound;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use GeoIP2::Error::WebService;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use GeoIP2::Model::City;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use GeoIP2::Model::Country;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use GeoIP2::Model::Insights;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 use GeoIP2::Types
17 1 ▶ qw( JSONObject MaxMindID MaxMindLicenseKey Str URIObject UserAgentObject );
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use MIME::Base64 qw( encode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use LWP::Protocol::https;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 1 ▶use Params::Validate qw( validate );
Subroutine BEGIN: called CC=1 SCAR=0.0
23 1 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
24 1 ▶use Sub::Quote qw( quote_sub );
Subroutine BEGIN: called CC=1 SCAR=0.0
25 1 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 1 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 1 with 'GeoIP2::Role::HasLocales';
31  
32 1 has user_id => (
33 is => 'ro',
34 isa => MaxMindID,
35 required => 1,
36 );
37  
38 1 has license_key => (
39 is => 'ro',
40 isa => MaxMindLicenseKey,
41 required => 1,
42 );
43  
44 1 has host => (
45 is => 'ro',
46 isa => Str,
47 default => quote_sub(q{ 'geoip.maxmind.com' }),
48 );
49  
50 1 has ua => (
51 is => 'ro',
52 isa => UserAgentObject,
53 builder => '_build_ua',
54 );
55  
56 1 has _base_uri => (
57 is => 'ro',
58 isa => URIObject,
59 lazy => 1,
60 builder => '_build_base_uri',
61 );
62  
63 1 has _json => (
64 is => 'ro',
65 isa => JSONObject,
66 init_arg => undef,
67 default => quote_sub(q{ JSON->new()->utf8() }),
68 );
69  
70 sub BUILD {
71 14 ▶ my $self = shift;
Subroutine BUILD: called CC=3 SCAR=11.1
Pod undocumented
72  
73 14 local $@;
74 14 ▶ my $self_version = eval { 'v' . $self->VERSION() } || 'v?';
Condition50%1/2
eval { || 'v?'
l!l
140
MC/DC0%0/1
eval { do { 'v' . $self->VERSION } } || 'v?'
eval { do { 'v' . $self->VERSION } }
Truth table50%1/2
A
A= eval { do { 'v' . $self->VERSION } }
Aresult
11
00
75  
76 14 my $ua = $self->ua();
77 14 ▶ my $ua_version = eval { 'v' . $ua->VERSION() } || 'v?';
Condition50%1/2
eval { || 'v?'
l!l
140
MC/DC0%0/1
eval { do { 'v' . $ua->VERSION } } || 'v?'
eval { do { 'v' . $ua->VERSION } }
Truth table50%1/2
A
A= eval { do { 'v' . $ua->VERSION } }
Aresult
11
00
78  
79 14 my $agent
80 = blessed($self)
81 . " $self_version" . ' ('
82 . blessed($ua) . q{ }
83 . $ua_version . q{ / }
84 . "Perl $^V)";
85  
86 14 $ua->agent($agent);
87 }
88  
89 sub country {
90 20 ▶ my $self = shift;
Subroutine country: called CC=1 SCAR=0.0
Pod documented
91  
92 20 return $self->_response_for(
93 'country',
94 'GeoIP2::Model::Country',
95 @_,
96 );
97 }
98  
99 sub city {
100 0 ▶ my $self = shift;
Subroutine city: not called CC=1 SCAR=6.9
Pod documented
101  
102 0 return $self->_response_for(
103 'city',
104 'GeoIP2::Model::City',
105 @_,
106 );
107 }
108  
109 sub insights {
110 0 ▶ my $self = shift;
Subroutine insights: not called CC=1 SCAR=6.9
Pod documented
111  
112 0 return $self->_response_for(
113 'insights',
114 'GeoIP2::Model::Insights',
115 @_,
116 );
117 }
118  
119 my %spec = (
120 ip => {
121 callbacks => {
122 'is a public IP address or me' => sub {
123 20 ▶ return defined $_[0]
Subroutine __ANON__: called CC=4 SCAR=13.9
Condition88%8/9
defined $_[0] && ($_[0] eq 'me' || is_public_ipv4($_[0]) || is_public_ipv6($_[0]))
!ll&&!rl&&r
0614
$_[0] eq "me" or is_public_ipv4($_[0]) or is_public_ipv6($_[0])
l!l&&r!l&&!r
1316
$_[0] eq "me" or is_public_ipv4($_[0])
l!l&&r!l&&!r
1127
MC/DC75%3/4
defined $_[0] && ($_[0] eq 'me' || is_public_ipv4($_[0]) || is_public_ipv6($_[0]))
defined $_[0] $_[0] eq "me" is_public_ipv4($_[0]) is_public_ipv6($_[0])
Truth table80%4/5
A && B or C or D
A= defined $_[0]B= $_[0] eq "me"C= is_public_ipv4($_[0])D= is_public_ipv6($_[0])
ABCDresult
0XXX0
10000
11XX1
101X1
10011
124 && ( $_[0] eq 'me'
125 || is_public_ipv4( $_[0] )
126 || is_public_ipv6( $_[0] ) );
127 }
128 },
129 },
130 1 );
131  
132 sub _response_for {
133 20 ▶ my $self = shift;
Subroutine _response_for: called CC=2 SCAR=6.9
134 20 my $path = shift;
135 20 my $model_class = shift;
136  
137 20 my %p = validate( @_, \%spec );
138  
139 14 my $uri = $self->_base_uri()->clone();
140 14 $uri->path_segments( $uri->path_segments(), $path, $p{ip} );
141  
142 14 my $request = HTTP::Request->new(
143 'GET', $uri,
144 HTTP::Headers->new( Accept => 'application/json' ),
145 );
146  
147 14 $request->authorization_basic( $self->user_id(), $self->license_key() );
148  
149 14 my $response = $self->ua()->request($request);
150  
151 14 ▶ if ( $response->code() == 200 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->code == 200) { } 6 8 14
152 6 my $body = $self->_handle_success( $response, $uri );
153 return $model_class->new(
154 5 %{$body},
155 locales => $self->locales(),
156 );
157 }
158 else {
159 # all other error codes throw an exception
160 8 $self->_handle_error_status( $response, $uri, $p{ip} );
161 }
162 }
163  
164 sub _handle_success {
165 6 ▶ my $self = shift;
Subroutine _handle_success: called CC=1 SCAR=0.0
166 6 my $response = shift;
167 6 my $uri = shift;
168  
169 6 my $body;
170 try {
171 6 ▶ $body = $self->_json()->decode( $response->decoded_content() );
Subroutine __ANON__: called CC=1 SCAR=0.0
172 }
173 catch {
174 1 ▶ GeoIP2::Error::Generic->throw(
Subroutine __ANON__: called CC=1 SCAR=0.0
175 message =>
176 "Received a 200 response for $uri but could not decode the response as JSON: $_",
177 );
178 6 };
179  
180 5 return $body;
181 }
182  
183 sub _handle_error_status {
184 8 ▶ my $self = shift;
Subroutine _handle_error_status: called CC=3 SCAR=11.0
185 8 my $response = shift;
186 8 my $uri = shift;
187 8 my $ip = shift;
188  
189 8 my $status = $response->code();
190  
191 8 ▶ if ( $status =~ /^4/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($status =~ /^4/) { } 6 2 8
elsif ($status =~ /^5/) { } 1 1 2
192 6 $self->_handle_4xx_status( $response, $status, $uri, $ip );
193 }
194 elsif ( $status =~ /^5/ ) {
195 1 $self->_handle_5xx_status( $response, $status, $uri );
196 }
197 else {
198 1 $self->_handle_non_200_status( $response, $status, $uri );
199 }
200 }
201  
202 sub _handle_4xx_status {
203 6 ▶ my $self = shift;
Subroutine _handle_4xx_status: called CC=5 SCAR=16.1
204 6 my $response = shift;
205 6 my $status = shift;
206 6 my $uri = shift;
207 6 my $ip = shift;
208  
209 6 ▶ if ( $status == 404 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status == 404) 1 5 6
210 1 GeoIP2::Error::IPAddressNotFound->throw(
211 message => "No record found for IP address $ip",
212 ip_address => $ip,
213 );
214 }
215  
216 5 my $content = $response->decoded_content();
217  
218 5 my $body = {};
219  
220 5 ▶ if ( defined $content && length $content ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $content and length $content) { } 4 1 5
Condition66%2/3
defined $content and length $content
!ll&&!rl&&r
014
MC/DC50%1/2
defined $content and length $content
defined $content length $content
Truth table66%2/3
A and B
A= defined $contentB= length $content
ABresult
0X0
100
111
221 4 ▶ if ( $response->content_type() =~ /json/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->content_type =~ /json/) { } 3 1 4
222 try {
223 3 ▶ $body = $self->_json()->decode($content);
Subroutine __ANON__: called CC=3 SCAR=11.1
224 GeoIP2::Error::Generic->throw( message =>
225 'Response contains JSON but it does not specify code or error keys'
226 2 ▶ ) unless $body->{code} && $body->{error};
Branch: 1 branch
BranchTrueFalseTotal
unless $body->{"code"} and $body->{"error"} 1 1 2
Condition66%2/3
$body->{"code"} and $body->{"error"}
!ll&&!rl&&r
101
MC/DC50%1/2
$body->{"code"} and $body->{"error"}
$body->{"code"} $body->{"error"}
Truth table66%2/3
A and B
A= $body->{"code"}B= $body->{"error"}
ABresult
0X0
100
111
227 }
228 catch {
229 2 ▶ GeoIP2::Error::HTTP->throw(
Subroutine __ANON__: called CC=1 SCAR=0.0
230 message =>
231 "Received a $status error for $uri but it did not include the expected JSON body: $_",
232 http_status => $status,
233 uri => $uri,
234 );
235 3 };
236 }
237 else {
238 1 GeoIP2::Error::HTTP->throw(
239 message =>
240 "Received a $status error for $uri with the following body: $content",
241 http_status => $status,
242 uri => $uri,
243 );
244 }
245 }
246 else {
247 1 GeoIP2::Error::HTTP->throw(
248 message => "Received a $status error for $uri with no body",
249 http_status => $status,
250 uri => $uri,
251 );
252 }
253  
254 GeoIP2::Error::WebService->throw(
255 message => delete $body->{error},
256 1 %{$body},
257 http_status => $status,
258 uri => $uri,
259 );
260 }
261  
262 sub _handle_5xx_status {
263 1 ▶ my $self = shift;
Subroutine _handle_5xx_status: called CC=1 SCAR=0.0
264 1 my $response = shift;
265 1 my $status = shift;
266 1 my $uri = shift;
267  
268 1 GeoIP2::Error::HTTP->throw(
269 message => "Received a server error ($status) for $uri",
270 http_status => $status,
271 uri => $uri,
272 );
273 }
274  
275 sub _handle_non_200_status {
276 1 ▶ my $self = shift;
Subroutine _handle_non_200_status: called CC=1 SCAR=0.0
277 1 my $response = shift;
278 1 my $status = shift;
279 1 my $uri = shift;
280  
281 1 GeoIP2::Error::HTTP->throw(
282 message =>
283 "Received a very surprising HTTP status ($status) for $uri",
284 http_status => $status,
285 uri => $uri,
286 );
287 }
288  
289 sub _build_base_uri {
290 12 ▶ my $self = shift;
Subroutine _build_base_uri: called CC=1 SCAR=0.0
291  
292 12 return URI->new( 'https://' . $self->host() . '/geoip/v2.1' );
293 }
294  
295 sub _build_ua {
296 2 ▶ my $self = shift;
Subroutine _build_ua: called CC=1 SCAR=0.0
297  
298 2 return LWP::UserAgent->new();
299 }
300  
301 1 1;
302  
303 # ABSTRACT: Perl API for the GeoIP2 Precision web services
304  
305 __END__
306  
307 =pod
308  
309 =head1 NAME
310  
311 GeoIP2::WebService::Client - Perl API for the GeoIP2 Precision web services
312  
313 =head1 VERSION
314  
315 version 0.050000
316  
317 =head1 SYNOPSIS
318  
319 use 5.008;
320  
321 use GeoIP2::WebService::Client;
322  
323 # This creates a Client object that can be reused across requests.
324 # Replace "42" with your user id and "abcdef123456" with your license
325 # key.
326 my $client = GeoIP2::WebService::Client->new(
327 user_id => 42,
328 license_key => 'abcdef123456',
329 );
330  
331 # Replace "insights" with the method corresponding to the web service
332 # that you are using, e.g., "country", "city".
333 my $insights = $client->insights( ip => '24.24.24.24' );
334  
335 my $country = $insights->country();
336 say $country->iso_code();
337  
338 =head1 DESCRIPTION
339  
340 This class provides a client API for all the GeoIP2 Precision web service end
341 points. The end points are Country, City, and Insights. Each end point returns
342 a different set of data about an IP address, with Country returning the least
343 data and Insights the most.
344  
345 Each web service end point is represented by a different model class, and
346 these model classes in turn contain multiple Record classes. The record
347 classes have attributes which contain data about the IP address.
348  
349 If the web service does not return a particular piece of data for an IP
350 address, the associated attribute is not populated.
351  
352 The web service may not return any information for an entire record, in which
353 case all of the attributes for that record class will be empty.
354  
355 =head1 SSL
356  
357 Requests to the GeoIP2 web service are always made with SSL.
358  
359 =head1 USAGE
360  
361 The basic API for this class is the same for all of the web service end
362 points. First you create a web service object with your MaxMind C<user_id> and
363 C<license_key>, then you call the method corresponding to a specific end
364 point, passing it the IP address you want to look up.
365  
366 If the request succeeds, the method call will return a model class for the end
367 point you called. This model in turn contains multiple record classes, each of
368 which represents part of the data returned by the web service.
369  
370 If the request fails, the client class throws an exception.
371  
372 =head1 CONSTRUCTOR
373  
374 This class has a single constructor method:
375  
376 =head2 GeoIP2::WebService::Client->new()
377  
378 This method creates a new client object. It accepts the following arguments:
379  
380 =over 4
381  
382 =item * user_id
383  
384 Your MaxMind User ID. Go to L<https://www.maxmind.com/en/my_license_key> to see
385 your MaxMind User ID and license key.
386  
387 This argument is required.
388  
389 =item * license_key
390  
391 Your MaxMind license key. Go to L<https://www.maxmind.com/en/my_license_key> to
392 see your MaxMind User ID and license key.
393  
394 This argument is required.
395  
396 =item * locales
397  
398 This is an array reference where each value is a string indicating a locale.
399 This argument will be passed onto record classes to use when their C<name()>
400 methods are called.
401  
402 The order of the locales is significant. When a record class has multiple
403 names (country, city, etc.), its C<name()> method will look at each element of
404 this array ref and return the first locale for which it has a name.
405  
406 Note that the only locale which is always present in the GeoIP2 data in "en".
407 If you do not include this locale, the C<name()> method may end up returning
408 C<undef> even when the record in question has an English name.
409  
410 Currently, the valid list of locale codes is:
411  
412 =over 8
413  
414 =item * de - German
415  
416 =item * en - English
417  
418 English names may still include accented characters if that is the accepted
419 spelling in English. In other words, English does not mean ASCII.
420  
421 =item * es - Spanish
422  
423 =item * fr - French
424  
425 =item * ja - Japanese
426  
427 =item * pt-BR - Brazilian Portuguese
428  
429 =item * ru - Russian
430  
431 =item * zh-CN - simplified Chinese
432  
433 =back
434  
435 Passing any other locale code will result in an error.
436  
437 The default value for this argument is C<['en']>.
438  
439 =item * host
440  
441 The hostname to make a request against. This defaults to
442 "geoip.maxmind.com". In most cases, you should not need to set this
443 explicitly.
444  
445 =item * ua
446  
447 This argument allows you to your own L<LWP::UserAgent> object. This is useful
448 if you cannot use a vanilla LWP object, for example if you need to set proxy
449 parameters.
450  
451 This can actually be any object which supports C<agent()> and C<request()>
452 methods. This method will be called with an L<HTTP::Request> object as its
453 only argument. This method must return an L<HTTP::Response> object.
454  
455 =back
456  
457 =head1 REQUEST METHODS
458  
459 All of the request methods accept a single argument:
460  
461 =over 4
462  
463 =item * ip
464  
465 This must be a valid IPv4 or IPv6 address, or the string "me". This is the
466 address that you want to look up using the GeoIP2 web service.
467  
468 If you pass the string "me" then the web service returns data on the client
469 system's IP address. Note that this is the IP address that the web service
470 sees. If you are using a proxy, the web service will not see the client
471 system's actual IP address.
472  
473 =back
474  
475 =head2 $client->country()
476  
477 This method calls the GeoIP2 Precision: Country end point. It returns a
478 L<GeoIP2::Model::Country> object.
479  
480 =head2 $client->city()
481  
482 This method calls the GeoIP2 Precision: City end point. It returns a
483 L<GeoIP2::Model::City> object.
484  
485 =head2 $client->insights()
486  
487 This method calls the GeoIP2 Precision: Insights end point. It returns a
488 L<GeoIP2::Model::Insights> object.
489  
490 =head1 User-Agent HEADER
491  
492 This module will set the User-Agent header to include the package name and
493 version of this module (or a subclass if you use one), the package name and
494 version of the user agent object, and the version of Perl.
495  
496 This is set in order to help us support individual users, as well to determine
497 support policies for dependencies and Perl itself.
498  
499 =head1 EXCEPTIONS
500  
501 For details on the possible errors returned by the web service itself, see
502 L<http://dev.maxmind.com/geoip/geoip2/web-services> for the GeoIP2 web service
503 docs.
504  
505 If the web service returns an explicit error document, this is thrown as a
506 L<GeoIP2::Error::WebService> exception object. If some other sort of error
507 occurs, this is thrown as a L<GeoIP2::Error::HTTP> object. The difference is
508 that the web service error includes an error message and error code delivered
509 by the web service. The latter is thrown when some sort of unanticipated error
510 occurs, such as the web service returning a 500 or an invalid error document.
511  
512 If the web service returns any status code besides 200, 4xx, or 5xx, this also
513 becomes a L<GeoIP2::Error::HTTP> object.
514  
515 Finally, if the web service returns a 200 but the body is invalid, the client
516 throws a L<GeoIP2::Error::Generic> object.
517  
518 All of these error classes have an C<< $error->message() >> method and
519 overload stringification to show that message. This means that if you don't
520 explicitly catch errors they will ultimately be sent to C<STDERR> with some
521 sort of (hopefully) useful error message.
522  
523 =head1 WHAT DATA IS RETURNED?
524  
525 While many of the end points return the same basic records, the attributes
526 which can be populated vary between end points. In addition, while an end
527 point may offer a particular piece of data, MaxMind does not always have every
528 piece of data for any given IP address.
529  
530 Because of these factors, it is possible for any end point to return a record
531 where some or all of the attributes are unpopulated.
532  
533 See L<http://dev.maxmind.com/geoip/geoip2/web-services> for details on what data each end
534 point I<may> return.
535  
536 The only piece of data which is always returned is the C<ip_address> key in
537 the C<GeoIP2::Record::Traits> record.
538  
539 Every record class attribute has a corresponding predicate method so you can
540 check to see if the attribute is set.
541  
542 =head1 AUTHORS
543  
544 =over 4
545  
546 =item *
547  
548 Dave Rolsky <drolsky@maxmind.com>
549  
550 =item *
551  
552 Greg Oschwald <goschwald@maxmind.com>
553  
554 =item *
555  
556 Olaf Alders <oalders@maxmind.com>
557  
558 =back
559  
560 =head1 COPYRIGHT AND LICENSE
561  
562 This software is copyright (c) 2014 by MaxMind, Inc..
563  
564 This is free software; you can redistribute it and/or modify it under
565 the same terms as the Perl 5 programming language system itself.
566  
567 =cut
« GeoIP2/Database/Reader.pm ↑ Summary GeoIP2.pm »