| 1 | package Web::API; | ||
| 2 | |||
| 3 | use 5.010001; | ||
| 4 | use Mouse::Role; | ||
| 5 | use experimental 'smartmatch'; | ||
| 6 | |||
| 7 | # ABSTRACT: A Simple base module to implement almost every RESTful API with just a few lines of configuration | ||
| 8 | |||
| 9 | our $VERSION = '2.4.1'; # VERSION | ||
| 10 | |||
| 11 | use LWP::UserAgent; | ||
| 12 | use HTTP::Cookies 6.04; | ||
| 13 | use Data::Printer colored => 1; | ||
| 14 | use XML::Simple; | ||
| 15 | use URI::Escape::XS qw/uri_escape uri_unescape/; | ||
| 16 | use JSON; | ||
| 17 | use URI; | ||
| 18 | use URI::QueryParam; | ||
| 19 | use Carp; | ||
| 20 | use Net::OAuth; | ||
| 21 | use Data::Random qw(rand_chars); | ||
| 22 | use Time::HiRes 'sleep'; | ||
| 23 | |||
| 24 | $Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0A; | ||
| 25 | |||
| 26 | our $AUTOLOAD; | ||
| 27 | |||
| 28 | our %CONTENT_TYPE = ( | ||
| 29 | json => 'application/json', | ||
| 30 | js => 'application/json', | ||
| 31 | xml => 'text/xml', | ||
| 32 | ); | ||
| 33 | |||
| 34 | |||
| 35 | requires 'commands'; | ||
| 36 | |||
| 37 | |||
| 38 | has 'base_url' => ( | ||
| 39 | is => 'rw', | ||
| 40 | isa => 'Str', | ||
| 41 | ); | ||
| 42 | |||
| 43 | |||
| 44 | has 'api_key' => ( | ||
| 45 | is => 'rw', | ||
| 46 | isa => 'Str', | ||
| 47 | ); | ||
| 48 | |||
| 49 | |||
| 50 | has 'user' => ( | ||
| 51 | is => 'rw', | ||
| 52 | isa => 'Str', | ||
| 53 | ); | ||
| 54 | |||
| 55 | |||
| 56 | has 'api_key_field' => ( | ||
| 57 | is => 'rw', | ||
| 58 | isa => 'Str', | ||
| 59 | default => sub { 'key' }, | ||
| 60 | ); | ||
| 61 | |||
| 62 | |||
| 63 | has 'api_version' => ( | ||
| 64 | is => 'rw', | ||
| 65 | isa => 'Int', | ||
| 66 | default => sub { 1 }, | ||
| 67 | ); | ||
| 68 | |||
| 69 | |||
| 70 | has 'mapping' => (is => 'rw'); | ||
| 71 | |||
| 72 | |||
| 73 | has 'wrapper' => ( | ||
| 74 | is => 'rw', | ||
| 75 | clearer => 'clear_wrapper', | ||
| 76 | ); | ||
| 77 | |||
| 78 | |||
| 79 | has 'header' => ( | ||
| 80 | is => 'rw', | ||
| 81 | lazy => 1, | ||
| 82 | default => sub { {} }, | ||
| 83 | ); | ||
| 84 | |||
| 85 | |||
| 86 | has 'auth_type' => ( | ||
| 87 | is => 'rw', | ||
| 88 | isa => 'Str', | ||
| 89 | default => sub { 'none' }, | ||
| 90 | ); | ||
| 91 | |||
| 92 | |||
| 93 | has 'auth_header' => ( | ||
| 94 | is => 'rw', | ||
| 95 | isa => 'Str', | ||
| 96 | default => sub { 'Authorization' }, | ||
| 97 | ); | ||
| 98 | |||
| 99 | |||
| 100 | has 'default_method' => ( | ||
| 101 | is => 'rw', | ||
| 102 | isa => 'Str', | ||
| 103 | default => sub { 'GET' }, | ||
| 104 | ); | ||
| 105 | |||
| 106 | |||
| 107 | has 'extension' => ( | ||
| 108 | is => 'rw', | ||
| 109 | isa => 'Str', | ||
| 110 | default => sub { '' }, | ||
| 111 | ); | ||
| 112 | |||
| 113 | |||
| 114 | has 'user_agent' => ( | ||
| 115 | is => 'rw', | ||
| 116 | isa => 'Str', | ||
| 117 | default => sub { __PACKAGE__ . ' ' . $Web::API::VERSION }, | ||
| 118 | ); | ||
| 119 | |||
| 120 | |||
| 121 | has 'timeout' => ( | ||
| 122 | is => 'rw', | ||
| 123 | isa => 'Int', | ||
| 124 | default => sub { 30 }, | ||
| 125 | lazy => 1, | ||
| 126 | ); | ||
| 127 | |||
| 128 | |||
| 129 | has 'strict_ssl' => ( | ||
| 130 | is => 'rw', | ||
| 131 | isa => 'Bool', | ||
| 132 | default => sub { 1 }, | ||
| 133 | lazy => 1, | ||
| 134 | ); | ||
| 135 | |||
| 136 | |||
| 137 | has 'agent' => ( | ||
| 138 | is => 'rw', | ||
| 139 | isa => 'LWP::UserAgent', | ||
| 140 | lazy => 1, | ||
| 141 | required => 1, | ||
| 142 | builder => '_build_agent', | ||
| 143 | ); | ||
| 144 | |||
| 145 | |||
| 146 | has 'retry_http_codes' => ( | ||
| 147 | is => 'rw', | ||
| 148 | isa => 'ArrayRef[Int]', | ||
| 149 | ); | ||
| 150 | |||
| 151 | |||
| 152 | has 'retry_errors' => ( | ||
| 153 | is => 'rw', | ||
| 154 | isa => 'ArrayRef[RegexpRef]', | ||
| 155 | ); | ||
| 156 | |||
| 157 | |||
| 158 | has 'retry_times' => ( | ||
| 159 | is => 'rw', | ||
| 160 | isa => 'Int', | ||
| 161 | lazy => 1, | ||
| 162 | default => sub { 3 }, | ||
| 163 | ); | ||
| 164 | |||
| 165 | |||
| 166 | has 'retry_delay' => ( | ||
| 167 | is => 'rw', | ||
| 168 | isa => 'Num', | ||
| 169 | lazy => 1, | ||
| 170 | default => sub { 1.0 }, | ||
| 171 | ); | ||
| 172 | |||
| 173 | |||
| 174 | has 'content_type' => ( | ||
| 175 | is => 'rw', | ||
| 176 | isa => 'Str', | ||
| 177 | default => sub { 'text/plain' }, | ||
| 178 | ); | ||
| 179 | |||
| 180 | |||
| 181 | has 'incoming_content_type' => ( | ||
| 182 | is => 'rw', | ||
| 183 | isa => 'Str', | ||
| 184 | ); | ||
| 185 | |||
| 186 | |||
| 187 | has 'outgoing_content_type' => ( | ||
| 188 | is => 'rw', | ||
| 189 | isa => 'Str', | ||
| 190 | ); | ||
| 191 | |||
| 192 | |||
| 193 | has 'debug' => ( | ||
| 194 | is => 'rw', | ||
| 195 | isa => 'Bool', | ||
| 196 | default => sub { 0 }, | ||
| 197 | lazy => 1, | ||
| 198 | ); | ||
| 199 | |||
| 200 | |||
| 201 | has 'cookies' => ( | ||
| 202 | is => 'rw', | ||
| 203 | isa => 'HTTP::Cookies', | ||
| 204 | default => sub { HTTP::Cookies->new }, | ||
| 205 | ); | ||
| 206 | |||
| 207 | |||
| 208 | has 'consumer_secret' => ( | ||
| 209 | is => 'rw', | ||
| 210 | isa => 'Str', | ||
| 211 | ); | ||
| 212 | |||
| 213 | |||
| 214 | has 'access_token' => ( | ||
| 215 | is => 'rw', | ||
| 216 | isa => 'Str', | ||
| 217 | ); | ||
| 218 | |||
| 219 | |||
| 220 | has 'access_secret' => ( | ||
| 221 | is => 'rw', | ||
| 222 | isa => 'Str', | ||
| 223 | ); | ||
| 224 | |||
| 225 | |||
| 226 | has 'signature_method' => ( | ||
| 227 | is => 'rw', | ||
| 228 | isa => 'Str', | ||
| 229 | default => sub { 'HMAC-SHA1' }, | ||
| 230 | lazy => 1, | ||
| 231 | ); | ||
| 232 | |||
| 233 | |||
| 234 | has 'encoder' => ( | ||
| 235 | is => 'rw', | ||
| 236 | isa => 'CodeRef', | ||
| 237 | predicate => 'has_encoder', | ||
| 238 | ); | ||
| 239 | |||
| 240 | |||
| 241 | has 'decoder' => ( | ||
| 242 | is => 'rw', | ||
| 243 | isa => 'CodeRef', | ||
| 244 | predicate => 'has_decoder', | ||
| 245 | ); | ||
| 246 | |||
| 247 | |||
| 248 | has 'oauth_post_body' => ( | ||
| 249 | is => 'rw', | ||
| 250 | isa => 'Bool', | ||
| 251 | default => sub { 1 }, | ||
| 252 | lazy => 1, | ||
| 253 | ); | ||
| 254 | |||
| 255 | |||
| 256 | has 'error_keys' => ( | ||
| 257 | is => 'rw', | ||
| 258 | isa => 'ArrayRef[Str]', | ||
| 259 | ); | ||
| 260 | |||
| 261 | has 'json' => ( | ||
| 262 | is => 'rw', | ||
| 263 | isa => 'JSON', | ||
| 264 | default => sub { | ||
| 265 | my $js = JSON->new; | ||
| 266 | $js->utf8; | ||
| 267 | $js->allow_blessed; | ||
| 268 | $js->convert_blessed; | ||
| 269 | $js->allow_nonref; | ||
| 270 | $js; | ||
| 271 | }, | ||
| 272 | ); | ||
| 273 | |||
| 274 | has 'xml' => ( | ||
| 275 | is => 'rw', | ||
| 276 | isa => 'XML::Simple', | ||
| 277 | lazy => 1, | ||
| 278 | default => sub { | ||
| 279 | XML::Simple->new( | ||
| 280 | ContentKey => '-content', | ||
| 281 | NoAttr => 1, | ||
| 282 | KeepRoot => 1, | ||
| 283 | KeyAttr => {}, | ||
| 284 | ); | ||
| 285 | }, | ||
| 286 | ); | ||
| 287 | |||
| 288 | has '_decoded_response' => ( | ||
| 289 | is => 'rw', | ||
| 290 | isa => 'Ref', | ||
| 291 | clearer => 'clear_decoded_response', | ||
| 292 | ); | ||
| 293 | |||
| 294 | has '_response' => ( | ||
| 295 | is => 'rw', | ||
| 296 | isa => 'HTTP::Response', | ||
| 297 | clearer => 'clear_response', | ||
| 298 | ); | ||
| 299 | |||
| 300 | sub _build_agent { | ||
| 301 | my ($self) = @_; | ||
| 302 | |||
| 303 | return LWP::UserAgent->new( | ||
| 304 | agent => $self->user_agent, | ||
| 305 | cookie_jar => $self->cookies, | ||
| 306 | timeout => $self->timeout, | ||
| 307 | keep_alive => 1, | ||
| 308 | ssl_opts => { verify_hostname => $self->strict_ssl }, | ||
| 309 | ); | ||
| 310 | } | ||
| 311 | |||
| 312 | |||
| 313 | sub nonce { | ||
| 314 | return join('', rand_chars(size => 16, set => 'alphanumeric')); | ||
| 315 | } | ||
| 316 | |||
| 317 | |||
| 318 | sub log { ## no critic (ProhibitBuiltinHomonyms) | ||
| 319 | my ($self, $msg) = @_; | ||
| 320 | print STDERR caller() . ': ' . $msg . $/; | ||
| 321 | return; | ||
| 322 | } | ||
| 323 | |||
| 324 | |||
| 325 | sub decode { | ||
| 326 | my ($self, $content, $content_type) = @_; | ||
| 327 | |||
| 328 | $self->log("decoding response from '$content_type'") if $self->debug; | ||
| 329 | |||
| 330 | my $data; | ||
| 331 | eval { | ||
| 332 | if ($self->has_decoder) { | ||
| 333 | $self->log('running custom decoder') if $self->debug; | ||
| 334 | $data = $self->decoder->($content, $content_type); | ||
| 335 | } | ||
| 336 | else { | ||
| 337 | given ($content_type) { | ||
| 338 | when (/plain/) { | ||
| 339 | chomp $content; | ||
| 340 | $data = { text => $content }; | ||
| 341 | } | ||
| 342 | when (/urlencoded/) { | ||
| 343 | foreach (split(/&/, $content)) { | ||
| 344 | my ($key, $value) = split(/=/, $_); | ||
| 345 | $data->{ uri_unescape($key) } = uri_unescape($value); | ||
| 346 | } | ||
| 347 | } | ||
| 348 | when (/json/) { $data = $self->json->decode($content); } | ||
| 349 | when (/(xml|html)/) { | ||
| 350 | $data = $self->xml->XMLin($content, NoAttr => 0); | ||
| 351 | } | ||
| 352 | } | ||
| 353 | } | ||
| 354 | }; | ||
| 355 | |||
| 356 | die("couldn't decode payload using $content_type: $@\n" . np($content)) | ||
| 357 | if ($@ || ref \$content ne 'SCALAR'); | ||
| 358 | |||
| 359 | $self->_decoded_response($data); | ||
| 360 | |||
| 361 | return $data; | ||
| 362 | } | ||
| 363 | |||
| 364 | |||
| 365 | sub encode { | ||
| 366 | my ($self, $options, $content_type) = @_; | ||
| 367 | |||
| 368 | $self->log("encoding response to '$content_type'") if $self->debug; | ||
| 369 | |||
| 370 | my $payload; | ||
| 371 | eval { | ||
| 372 | # custom encoder should only be run if called by Web::API otherwise we | ||
| 373 | # end up calling it twice | ||
| 374 | if ($self->has_encoder and caller(1) eq 'Web::API') { | ||
| 375 | $self->log('running custom encoder') if $self->debug; | ||
| 376 | $payload = $self->encoder->($options, $content_type); | ||
| 377 | } | ||
| 378 | else { | ||
| 379 | given ($content_type) { | ||
| 380 | when (/plain/) { $payload = $options; } | ||
| 381 | when (/urlencoded/) { | ||
| 382 | $payload .= | ||
| 383 | uri_escape($_) . '=' . uri_escape($options->{$_}) . '&' | ||
| 384 | foreach (keys %$options); | ||
| 385 | chop($payload); | ||
| 386 | } | ||
| 387 | when (/json/) { $payload = $self->json->encode($options); } | ||
| 388 | when (/xml/) { $payload = $self->xml->XMLout($options); } | ||
| 389 | } | ||
| 390 | } | ||
| 391 | }; | ||
| 392 | die("couldn't encode payload using $content_type: $@\n" . np(%$options)) | ||
| 393 | if ($@ || ref \$payload ne 'SCALAR'); | ||
| 394 | |||
| 395 | return $payload; | ||
| 396 | } | ||
| 397 | |||
| 398 | |||
| 399 | sub talk { | ||
| 400 | my ($self, $command, $uri, $options, $query_keys, $content_type) = @_; | ||
| 401 | |||
| 402 | my $method = uc($command->{method} || $self->default_method); | ||
| 403 | my $oauth_req; | ||
| 404 | |||
| 405 | # handle different auth_types | ||
| 406 | given (lc $self->auth_type) { | ||
| 407 | when ('basic') { $uri->userinfo($self->user . ':' . $self->api_key); } | ||
| 408 | when ('header') { | ||
| 409 | $self->header->{ $self->auth_header } = | ||
| 410 | "Token token=" . $self->api_key; | ||
| 411 | } | ||
| 412 | when ('hash_key') { | ||
| 413 | my $api_key_field = $self->api_key_field; | ||
| 414 | if ($self->mapping and not $command->{no_mapping}) { | ||
| 415 | $self->log("mapping api_key_field: " . $self->api_key_field) | ||
| 416 | if $self->debug; | ||
| 417 | $api_key_field = $self->mapping->{$api_key_field} | ||
| 418 | if $self->mapping->{$api_key_field}; | ||
| 419 | } | ||
| 420 | $options->{$api_key_field} = $self->api_key; | ||
| 421 | } | ||
| 422 | when ('get_params') { | ||
| 423 | $uri->query_form( | ||
| 424 | $self->mapping->{user} || 'user' => $self->user, | ||
| 425 | $self->mapping->{api_key} || 'api_key' => $self->api_key, | ||
| 426 | ); | ||
| 427 | } | ||
| 428 | when (/^oauth/) { | ||
| 429 | my %opts = ( | ||
| 430 | consumer_key => $self->api_key, | ||
| 431 | consumer_secret => $self->consumer_secret, | ||
| 432 | request_url => $uri, | ||
| 433 | request_method => $method, | ||
| 434 | signature_method => $self->signature_method, | ||
| 435 | timestamp => time, | ||
| 436 | nonce => $self->nonce, | ||
| 437 | token => $self->access_token, | ||
| 438 | token_secret => $self->access_secret, | ||
| 439 | ); | ||
| 440 | |||
| 441 | if ( | ||
| 442 | $options | ||
| 443 | and (($self->oauth_post_body and $method eq 'POST') | ||
| 444 | or $method ne 'POST')) | ||
| 445 | { | ||
| 446 | $opts{extra_params} = { %$options, %{ $query_keys || {} } }; | ||
| 447 | } | ||
| 448 | |||
| 449 | $oauth_req = Net::OAuth->request("protected resource")->new(%opts); | ||
| 450 | $oauth_req->sign; | ||
| 451 | } | ||
| 452 | default { | ||
| 453 | $self->log( | ||
| 454 | "WARNING: auth_type " . $self->auth_type . " not supported yet") | ||
| 455 | unless (lc($self->auth_type) eq 'none'); | ||
| 456 | } | ||
| 457 | } | ||
| 458 | |||
| 459 | # encode payload | ||
| 460 | my $payload; | ||
| 461 | if (keys %$options) { | ||
| 462 | if ($method =~ m/^(GET|HEAD|DELETE)$/) { | ||
| 463 | |||
| 464 | # TODO: check whether $option is a flat hashref | ||
| 465 | |||
| 466 | unless ($self->auth_type eq 'oauth_params') { | ||
| 467 | $uri->query_param_append($_ => $options->{$_}) | ||
| 468 | for (keys %$options); | ||
| 469 | } | ||
| 470 | } | ||
| 471 | else { | ||
| 472 | $payload = $self->encode($options, $content_type->{out}); | ||
| 473 | $self->log("send payload: $payload") if $self->debug; | ||
| 474 | } | ||
| 475 | } | ||
| 476 | |||
| 477 | # append query keys to URI | ||
| 478 | $uri->query_param_append($_ => $query_keys->{$_}) for keys %$query_keys; | ||
| 479 | |||
| 480 | $uri = $oauth_req->to_url if ($self->auth_type eq 'oauth_params'); | ||
| 481 | |||
| 482 | # build headers | ||
| 483 | my %header = %{ $self->header }; | ||
| 484 | if (exists $command->{headers} and ref $command->{headers} eq 'HASH') { | ||
| 485 | %header = (%header, %{ $command->{headers} }); | ||
| 486 | } | ||
| 487 | my $headers = HTTP::Headers->new("Accept" => $content_type->{in}, %header); | ||
| 488 | |||
| 489 | if ($self->debug) { | ||
| 490 | $self->log("uri: $method $uri"); | ||
| 491 | $self->log("extra headers: " . np(%header)) if (%header); | ||
| 492 | $self->log("OAuth headers: " . $oauth_req->to_authorization_header) | ||
| 493 | if ($self->auth_type eq 'oauth_header'); | ||
| 494 | } | ||
| 495 | |||
| 496 | # build request | ||
| 497 | my $request = HTTP::Request->new($method, $uri, $headers); | ||
| 498 | unless ($method =~ m/^(GET|HEAD|DELETE)$/) { | ||
| 499 | $request->header("Content-type" => $content_type->{out}); | ||
| 500 | $request->content($payload); | ||
| 501 | } | ||
| 502 | |||
| 503 | # oauth POST | ||
| 504 | if ( $options | ||
| 505 | and ($method eq 'POST') | ||
| 506 | and ($self->auth_type =~ m/^oauth/) | ||
| 507 | and $self->oauth_post_body) | ||
| 508 | { | ||
| 509 | $request->content($oauth_req->to_post_body); | ||
| 510 | } | ||
| 511 | |||
| 512 | # oauth_header | ||
| 513 | $request->header(Authorization => $oauth_req->to_authorization_header) | ||
| 514 | if ($self->auth_type eq 'oauth_header'); | ||
| 515 | |||
| 516 | # add session cookies | ||
| 517 | $self->agent->cookie_jar($self->cookies); | ||
| 518 | |||
| 519 | # do the actual work | ||
| 520 | return $self->request($request); | ||
| 521 | } | ||
| 522 | |||
| 523 | |||
| 524 | sub map_options { | ||
| 525 | my ($self, $options, $command) = @_; | ||
| 526 | |||
| 527 | my %opts; | ||
| 528 | |||
| 529 | # first include default attributes | ||
| 530 | %opts = %{ $command->{default_attributes} } | ||
| 531 | if exists $command->{default_attributes}; | ||
| 532 | |||
| 533 | # then map everything in $options, overwriting default_attributes if necessary | ||
| 534 | if ($self->mapping and not $command->{no_mapping}) { | ||
| 535 | $self->log("mapping hash:\n" . np(%{ $self->mapping })) if $self->debug; | ||
| 536 | |||
| 537 | # do the key and value mapping of options hash and overwrite defaults | ||
| 538 | foreach my $key (keys %$options) { | ||
| 539 | my ($newkey, $newvalue); | ||
| 540 | $newkey = $self->mapping->{$key} if ($self->mapping->{$key}); | ||
| 541 | $newvalue = $self->mapping->{ $options->{$key} } | ||
| 542 | if ($options->{$key} and $self->mapping->{ $options->{$key} }); | ||
| 543 | |||
| 544 | $opts{ $newkey || $key } = $newvalue || $options->{$key}; | ||
| 545 | } | ||
| 546 | |||
| 547 | # and write everything back to $options | ||
| 548 | $options = \%opts; | ||
| 549 | } | ||
| 550 | else { | ||
| 551 | $options = { %opts, %$options }; | ||
| 552 | } | ||
| 553 | |||
| 554 | return $options; | ||
| 555 | } | ||
| 556 | |||
| 557 | |||
| 558 | sub check_mandatory { | ||
| 559 | my ($self, $options, $mandatory) = @_; | ||
| 560 | |||
| 561 | $self->log("mandatory keys:\n" . np(@$mandatory)) | ||
| 562 | if $self->debug; | ||
| 563 | |||
| 564 | my @missing_attrs; | ||
| 565 | foreach my $attr (@$mandatory) { | ||
| 566 | push(@missing_attrs, $attr) | ||
| 567 | unless $self->key_exists($attr, $options); | ||
| 568 | } | ||
| 569 | |||
| 570 | die 'mandatory attributes for this command missing: ' | ||
| 571 | . join(', ', @missing_attrs) | ||
| 572 | . $/ | ||
| 573 | if @missing_attrs; | ||
| 574 | |||
| 575 | return; | ||
| 576 | } | ||
| 577 | |||
| 578 | |||
| 579 | sub key_exists { | ||
| 580 | my ($self, $path, $hash) = @_; | ||
| 581 | |||
| 582 | my @bits = split /\./, $path; | ||
| 583 | my $node = $hash; | ||
| 584 | |||
| 585 | return $node | ||
| 586 | if @bits == grep { | ||
| 587 | ref $node eq "HASH" | ||
| 588 | && exists $node->{$_} | ||
| 589 | && ($node = $node->{$_} // {}) | ||
| 590 | } @bits; | ||
| 591 | |||
| 592 | return; | ||
| 593 | } | ||
| 594 | |||
| 595 | |||
| 596 | sub wrap { | ||
| 597 | my ($options, $wrapper, $content_type) = @_; | ||
| 598 | |||
| 599 | if (ref $wrapper eq 'ARRAY') { | ||
| 600 | |||
| 601 | # XML needs wrapping into extra array ref layer to make XML::Simple | ||
| 602 | # behave correctly | ||
| 603 | if ($content_type =~ m/xml/) { | ||
| 604 | $options = { $_ => [$options] } for (reverse @$wrapper); | ||
| 605 | } | ||
| 606 | else { | ||
| 607 | $options = { $_ => $options } for (reverse @$wrapper); | ||
| 608 | } | ||
| 609 | } | ||
| 610 | elsif (defined $wrapper) { | ||
| 611 | $options = { $wrapper => $options }; | ||
| 612 | } | ||
| 613 | |||
| 614 | return $options; | ||
| 615 | } | ||
| 616 | |||
| 617 | |||
| 618 | sub request { | ||
| 619 | my ($self, $request) = @_; | ||
| 620 | |||
| 621 | my $response; | ||
| 622 | my $error; | ||
| 623 | |||
| 624 | if ( ($self->retry_http_codes and scalar(@{ $self->retry_http_codes })) | ||
| 625 | or ($self->retry_errors and scalar(@{ $self->retry_errors }))) | ||
| 626 | { | ||
| 627 | my $times = $self->retry_times; | ||
| 628 | my $n = 0; | ||
| 629 | |||
| 630 | while ($times-- > 0) { | ||
| 631 | $n++; | ||
| 632 | $self->log("try: $n/" | ||
| 633 | . $self->retry_times | ||
| 634 | . ' delay: ' | ||
| 635 | . $self->retry_delay . 's') | ||
| 636 | if $self->debug; | ||
| 637 | |||
| 638 | $response = eval { $self->agent->request($request) }; | ||
| 639 | $error = $@; | ||
| 640 | |||
| 641 | # if the user agent died there was a connection issue, definitely retry those | ||
| 642 | unless ($error) { | ||
| 643 | $self->_response($response); | ||
| 644 | |||
| 645 | $self->log("recv payload: " . $response->decoded_content) | ||
| 646 | if $self->debug; | ||
| 647 | |||
| 648 | return $response | ||
| 649 | unless $self->needs_retry($response, | ||
| 650 | $request->header('Accept')); | ||
| 651 | } | ||
| 652 | |||
| 653 | sleep $self->retry_delay if $times; # Do not sleep in last time | ||
| 654 | } | ||
| 655 | } | ||
| 656 | else { | ||
| 657 | $response = eval { $self->agent->request($request) }; | ||
| 658 | $error = $@; | ||
| 659 | |||
| 660 | $self->log("recv payload: " . $response->decoded_content) | ||
| 661 | if $response and $self->debug; | ||
| 662 | } | ||
| 663 | |||
| 664 | $self->_response($response); | ||
| 665 | |||
| 666 | die $error if $error; | ||
| 667 | |||
| 668 | return $response; | ||
| 669 | } | ||
| 670 | |||
| 671 | |||
| 672 | sub needs_retry { | ||
| 673 | my ($self, $response, $content_type) = @_; | ||
| 674 | |||
| 675 | $self->log("response code was: " . $response->code) | ||
| 676 | if $self->debug; | ||
| 677 | |||
| 678 | return 1 if $response->code ~~ $self->retry_http_codes; | ||
| 679 | |||
| 680 | if ( $self->retry_errors | ||
| 681 | and scalar(@{ $self->retry_errors }) | ||
| 682 | and $self->error_keys | ||
| 683 | and scalar(@{ $self->error_keys })) | ||
| 684 | { | ||
| 685 | # we need to decode the response content to be able to find a custom | ||
| 686 | # error field | ||
| 687 | my $content = $self->decode($response->decoded_content, | ||
| 688 | ($response->header('Content-Type') || $content_type)); | ||
| 689 | |||
| 690 | my $error = $self->find_error($content); | ||
| 691 | |||
| 692 | return unless $error; | ||
| 693 | |||
| 694 | return 1 if map { $error =~ $_ } @{ $self->retry_errors }; | ||
| 695 | } | ||
| 696 | |||
| 697 | return; | ||
| 698 | } | ||
| 699 | |||
| 700 | |||
| 701 | sub find_error { | ||
| 702 | my ($self, $content) = @_; | ||
| 703 | |||
| 704 | for (@{ $self->error_keys || [] }) { | ||
| 705 | $self->log("checking for error at ($_)") if $self->debug; | ||
| 706 | |||
| 707 | my $node = $self->key_exists($_, $content); | ||
| 708 | |||
| 709 | if ($node) { | ||
| 710 | $self->log("found error: '$node' at ($_)") if $self->debug; | ||
| 711 | return $node; | ||
| 712 | } | ||
| 713 | } | ||
| 714 | |||
| 715 | return; | ||
| 716 | } | ||
| 717 | |||
| 718 | |||
| 719 | sub format_response { | ||
| 720 | my ($self, $response, $ct, $error) = @_; | ||
| 721 | |||
| 722 | my $answer; | ||
| 723 | |||
| 724 | if ($response) { | ||
| 725 | |||
| 726 | # collect response headers | ||
| 727 | my $response_headers; | ||
| 728 | $response_headers->{$_} = $response->header($_) | ||
| 729 | foreach ($response->header_field_names); | ||
| 730 | |||
| 731 | # decode content if necessary | ||
| 732 | unless ($self->_decoded_response) { | ||
| 733 | if ( defined $response->decoded_content | ||
| 734 | and length($response->decoded_content) > 0 | ||
| 735 | and $response->decoded_content =~ m/\S/) | ||
| 736 | { | ||
| 737 | $self->_decoded_response( | ||
| 738 | eval { | ||
| 739 | $self->decode($response->decoded_content, | ||
| 740 | ($response_headers->{'Content-Type'} || $ct)); | ||
| 741 | }); | ||
| 742 | $error ||= $@; | ||
| 743 | } | ||
| 744 | } | ||
| 745 | |||
| 746 | # search for and expose errors | ||
| 747 | $error ||= $self->find_error($self->_decoded_response); | ||
| 748 | |||
| 749 | $answer = { | ||
| 750 | header => $response_headers, | ||
| 751 | code => $response->code, | ||
| 752 | content => $self->_decoded_response, | ||
| 753 | raw => $response->content, | ||
| 754 | cookies => $self->cookies->get_cookies($self->base_url), | ||
| 755 | }; | ||
| 756 | |||
| 757 | unless ($response->is_success || $response->is_redirect) { | ||
| 758 | $error ||= $response->status_line; | ||
| 759 | } | ||
| 760 | } | ||
| 761 | |||
| 762 | if ($error) { | ||
| 763 | chomp($error); | ||
| 764 | $self->log("ERROR: $error"); | ||
| 765 | $answer->{error} = $error; | ||
| 766 | } | ||
| 767 | |||
| 768 | return $answer; | ||
| 769 | } | ||
| 770 | |||
| 771 | |||
| 772 | sub build_uri { | ||
| 773 | my ($self, $command, $options, $path) = @_; | ||
| 774 | |||
| 775 | my $uri = URI->new($self->base_url); | ||
| 776 | my $p = $uri->path; | ||
| 777 | |||
| 778 | if ($path) { | ||
| 779 | $p .= '/' . $path; | ||
| 780 | |||
| 781 | # parse all mandatory ID keys from URI path | ||
| 782 | # format: /path/with/some/:id/and/:another_id/fun.js | ||
| 783 | my @mandatory = ($path =~ m/:(\w+)/g); | ||
| 784 | |||
| 785 | # and replace placeholders | ||
| 786 | foreach my $key (@mandatory) { | ||
| 787 | die "required {$key} option missing\n" | ||
| 788 | unless (exists $options->{$key}); | ||
| 789 | |||
| 790 | my $encoded_option = uri_escape(delete $options->{$key}); | ||
| 791 | $p =~ s/:$key/$encoded_option/gex; | ||
| 792 | } | ||
| 793 | } | ||
| 794 | else { | ||
| 795 | $p .= "/$command"; | ||
| 796 | } | ||
| 797 | |||
| 798 | $p .= '.' . $self->extension if ($self->extension); | ||
| 799 | $uri->path($p); | ||
| 800 | |||
| 801 | return $uri; | ||
| 802 | } | ||
| 803 | |||
| 804 | |||
| 805 | sub build_content_type { | ||
| 806 | my ($self, $command) = @_; | ||
| 807 | |||
| 808 | return { | ||
| 809 | in => $command->{incoming_content_type} | ||
| 810 | || $command->{content_type} | ||
| 811 | || $CONTENT_TYPE{ $self->extension } | ||
| 812 | || $self->incoming_content_type | ||
| 813 | || $self->content_type, | ||
| 814 | out => $command->{outgoing_content_type} | ||
| 815 | || $command->{content_type} | ||
| 816 | || $self->outgoing_content_type | ||
| 817 | || $self->content_type, | ||
| 818 | }; | ||
| 819 | } | ||
| 820 | |||
| 821 | |||
| 822 | sub DESTROY { } | ||
| 823 | |||
| 824 | |||
| 825 | sub AUTOLOAD { | ||
| 826 | my ($self, %options) = @_; | ||
| 827 | |||
| 828 | $self->clear_decoded_response; | ||
| 829 | $self->clear_response; | ||
| 830 | |||
| 831 | # sanity checks | ||
| 832 | die "Attribute (base_url) is required\n" unless $self->base_url; | ||
| 833 | if ($self->auth_type =~ m/^oauth_/) { | ||
| 834 | for (qw(consumer_secret access_token access_secret)) { | ||
| 835 | die "Attribute ($_) is required\n" unless $self->$_; | ||
| 836 | } | ||
| 837 | } | ||
| 838 | |||
| 839 | my ($command) = $AUTOLOAD =~ /([^:]+)$/; | ||
| 840 | |||
| 841 | my $ct; | ||
| 842 | my $response = eval { | ||
| 843 | die "unknown command: $command\n" | ||
| 844 | unless (exists $self->commands->{$command}); | ||
| 845 | |||
| 846 | my $options = \%options; | ||
| 847 | |||
| 848 | # construct URI | ||
| 849 | my $uri = | ||
| 850 | $self->build_uri($command, $options, | ||
| 851 | $self->commands->{$command}->{path}); | ||
| 852 | |||
| 853 | # first select the right content types for encoding/decoding | ||
| 854 | $ct = $self->build_content_type($self->commands->{$command}); | ||
| 855 | |||
| 856 | # then map options if necessary | ||
| 857 | $options = | ||
| 858 | $self->map_options($options, $self->commands->{$command}, $ct->{in}) | ||
| 859 | if (((keys %$options) and ($ct->{out} =~ m/(xml|json|urlencoded)/)) | ||
| 860 | or (exists $self->commands->{$command}->{default_attributes}) | ||
| 861 | or (exists $self->commands->{$command}->{mandatory})); | ||
| 862 | |||
| 863 | # then check existence of mandatory attributes | ||
| 864 | $self->check_mandatory($options, | ||
| 865 | $self->commands->{$command}->{mandatory}) | ||
| 866 | if exists $self->commands->{$command}->{mandatory}; | ||
| 867 | |||
| 868 | # then extract query keys from options to prevent them being wrapped | ||
| 869 | # in the next step | ||
| 870 | my $query_keys; | ||
| 871 | foreach my $key (keys %$options) { | ||
| 872 | $query_keys->{$key} = delete $options->{$key} | ||
| 873 | if $key ~~ $self->commands->{$command}->{query_keys}; | ||
| 874 | } | ||
| 875 | |||
| 876 | # finally wrap all options in wrapper key(s) if requested | ||
| 877 | my $method = | ||
| 878 | uc($self->commands->{$command}->{method} || $self->default_method); | ||
| 879 | $options = | ||
| 880 | wrap($options, | ||
| 881 | $self->commands->{$command}->{wrapper} || $self->wrapper, | ||
| 882 | $ct->{in}) | ||
| 883 | unless ($method =~ m/^(GET|HEAD|DELETE)$/); | ||
| 884 | |||
| 885 | $self->log("options:\n" . np(%$options)) if $self->debug; | ||
| 886 | |||
| 887 | # do the talking | ||
| 888 | return $self->talk($self->commands->{$command}, | ||
| 889 | $uri, $options, $query_keys, $ct); | ||
| 890 | }; | ||
| 891 | |||
| 892 | return $self->format_response($self->_response, $ct->{in}, $@); | ||
| 893 | } | ||
| 894 | |||
| 895 | |||
| 896 | 1; # End of Web::API | ||
| 897 | |||
| 898 | __END__ |