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