GeoIP2/WebService/Client.pm

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