1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
|
package Net::GitHub::V3::Query;
our $VERSION = '1.05';
our $AUTHORITY = 'cpan:FAYLAND';
use URI;
use JSON::MaybeXS;
use MIME::Base64;
use LWP::UserAgent;
use HTTP::Request;
use Carp qw/croak/;
use URI::Escape;
use Types::Standard qw(Int Str Bool InstanceOf Object HashRef);
use Cache::LRU;
use Scalar::Util qw(looks_like_number);
use Net::GitHub::V3::ResultSet;
use Moo::Role;
# configurable args
# Authentication
has 'login' => ( is => 'rw', isa => Str, predicate => 'has_login' );
has 'pass' => ( is => 'rw', isa => Str, predicate => 'has_pass' );
has 'otp' => ( is => 'rw', isa => Str, predicate => 'has_otp' );
has 'access_token' => ( is => 'rw', isa => Str, predicate => 'has_access_token' );
# return raw unparsed JSON
has 'raw_string' => (is => 'rw', isa => Bool, default => 0);
has 'raw_response' => (is => 'rw', isa => Bool, default => 0);
has 'api_url' => (is => 'ro', default => 'https://api.github.com');
has 'api_throttle' => ( is => 'rw', isa => Bool, default => 1 );
has 'upload_url' => (is => 'ro', default => 'https://uploads.github.com');
# pagination
has 'next_url' => ( is => 'rw', isa => Str, predicate => 'has_next_page', clearer => 'clear_next_url' );
has 'last_url' => ( is => 'rw', isa => Str, predicate => 'has_last_page', clearer => 'clear_last_url' );
has 'first_url' => ( is => 'rw', isa => Str, predicate => 'has_first_page', clearer => 'clear_first_url' );
has 'prev_url' => ( is => 'rw', isa => Str, predicate => 'has_prev_page', clearer => 'clear_prev_url' );
has 'per_page' => ( is => 'rw', isa => Str, default => 100 );
has 'total_pages' => ( is => 'rw', isa => Str, default => 0 );
# deprecation
has 'deprecation_url' => ( is => 'rw', isa => Str );
has 'alternate_url' => ( is => 'rw', isa => Str );
# Error handle
has 'RaiseError' => ( is => 'rw', isa => Bool, default => 1 );
# Rate limits
# has 'rate_limit' => ( is => 'rw', isa => Int, default => sub { shift->update_rate_limit('rate_limit') } );
# has 'rate_limit_remaining' => ( is => 'rw', isa => Int, default => sub { shift->update_rate_limit('rate_limit_remaining') } );
# has 'rate_limit_reset' => ( is => 'rw', isa => Str, default => sub { shift->update_rate_limit('rate_limit_reset') } );
has 'rate_limit' => ( is => 'rw', isa => Int, default => sub { 0 } );
has 'rate_limit_remaining' => ( is => 'rw', isa => Int, default => sub { 0 } );
has 'rate_limit_reset' => ( is => 'rw', isa => Str, default => sub { 0 } );
# optional
has 'u' => (is => 'rw', isa => Str);
has 'repo' => (is => 'rw', isa => Str);
# accept version
has 'accept_version' => (is => 'rw', isa => Str, default => '');
has 'is_main_module' => (is => 'ro', isa => Bool, default => 0);
sub update_rate_limit {
my ( $self, $what ) = @_;
# If someone calls rate_limit before an API query happens, force these fields to update before giving back a response.
# Per github: Accessing this endpoint does not count against your REST API rate limit.
# https://developer.github.com/v3/rate_limit/
my $content = $self->query('/rate_limit');
return $self->{$what};
}
sub set_default_user_repo {
my ($self, $user, $repo) = @_;
$self->u($user);
$self->repo($repo);
# need apply to all sub modules
if ($self->is_main_module) {
if ($self->is_repos_init) {
$self->repos->u($user); $self->repos->repo($repo);
}
if ($self->is_issue_init) {
$self->issue->u($user); $self->issue->repo($repo);
}
if ($self->is_pull_request_init) {
$self->pull_request->u($user); $self->pull_request->repo($repo);
}
if ($self->is_git_data_init) {
$self->git_data->u($user); $self->git_data->repo($repo);
}
}
return $self;
}
sub args_to_pass {
my $self = shift;
my $ret;
foreach my $col ('login', 'pass', 'otp', 'access_token', 'raw_string', 'raw_response', 'api_url', 'api_throttle', 'u', 'repo', 'next_url', 'last_url', 'first_url', 'prev_url', 'per_page', 'ua') {
my $v = $self->$col;
$ret->{$col} = $v if defined $v;
}
return $ret;
}
has 'ua' => (
isa => InstanceOf['LWP::UserAgent'],
is => 'ro',
lazy => 1,
default => sub {
LWP::UserAgent->new(
agent => "perl-net-github/$VERSION",
cookie_jar => {},
keep_alive => 4,
timeout => 60,
);
},
);
has 'json' => (
is => 'ro',
isa => Object, # InstanceOf['JSON::MaybeXS'],
lazy => 1,
default => sub {
return JSON::MaybeXS->new( utf8 => 1 );
}
);
has 'cache' => (
isa => InstanceOf['Cache::LRU'],
is => 'rw',
lazy => 1,
default => sub {
Cache::LRU->new(
size => 200
);
}
);
# per-page pagination
has 'result_sets' => (
isa => HashRef,
is => 'ro',
default => sub { {} },
);
sub next {
my $self = shift;
my ($url) = @_;
my $result_set;
$result_set = $self->result_sets->{$url} or do {
$result_set = Net::GitHub::V3::ResultSet->new( url => $url );
$self->result_sets->{$url} = $result_set;
};
my $results = $result_set->results;
my $cursor = $result_set->cursor;
if ( $cursor > $#$results ) {
return if $result_set->done;
my $next_url = $result_set->next_url || $result_set->url;
my $new_result = $self->query($next_url);
$result_set->results(ref $new_result eq 'ARRAY' ?
$new_result :
[$new_result]
);
$result_set->cursor(0);
if ($self->has_next_page) {
$result_set->next_url($self->next_url);
}
else {
$result_set->done(1);
}
}
my $result = $result_set->results->[$result_set->cursor];
$result_set->cursor($result_set->cursor + 1);
return $result;
}
sub close {
my $self = shift;
my ($url) = @_;
delete $self->result_sets->{$url};
return;
}
sub query {
my $self = shift;
# fix ARGV, not sure if it's the good idea
my @args = @_;
if (@args == 1) {
unshift @args, 'GET'; # method by default
} elsif (@args > 1 and not (grep { $args[0] eq $_ } ('GET', 'POST', 'PUT', 'PATCH', 'HEAD', 'DELETE')) ) {
unshift @args, 'POST'; # if POST content
}
my $request_method = shift @args;
my $url = shift @args;
my $data = shift @args;
my $ua = $self->ua;
## always go with login:pass or access_token (for private repos)
if ($self->has_access_token) {
$ua->default_header('Authorization', "token " . $self->access_token);
} elsif ($self->has_login and $self->has_pass) {
my $auth_basic = $self->login . ':' . $self->pass;
$ua->default_header('Authorization', 'Basic ' . encode_base64($auth_basic));
if ($self->has_otp) {
$ua->default_header('X-GitHub-OTP', $self->otp);
}
}
$url = $self->api_url . $url unless $url =~ /^https\:/;
if ($request_method eq 'GET') {
if ($url !~ /per_page=\d/) {
## auto add per_page in url for GET no matter it supports or not
my $uri = URI->new($url);
my %query_form = $uri->query_form;
$query_form{per_page} ||= $self->per_page;
$uri->query_form(%query_form);
$url = $uri->as_string;
}
if ($data and ref $data eq 'HASH') {
my $uri = URI->new($url);
my %query_form = $uri->query_form;
$uri->query_form(%$data);
$url = $uri->as_string;
}
}
print STDERR ">>> $request_method $url\n" if $ENV{NG_DEBUG};
my $req = HTTP::Request->new( $request_method, $url );
$req->accept_decodable;
if ($request_method ne 'GET' and $data) {
my $json = $self->json->encode($data);
print STDERR ">>> $json\n" if $ENV{NG_DEBUG} and $ENV{NG_DEBUG} > 1;
$req->content($json);
}
$req->header( 'Content-Length' => length $req->content );
# if preview API, specify a custom media type to Accept header
# https://developer.github.com/v3/media/
$req->header( 'Accept' => sprintf("application/vnd.github.%s.param+json", $self->accept_version) )
if $self->accept_version;
my $res = $self->_make_request($req);
# get the rate limit information from the http response headers
$self->rate_limit( $res->header('x-ratelimit-limit') );
$self->rate_limit_remaining( $res->header('x-ratelimit-remaining') );
$self->rate_limit_reset( $res->header('x-ratelimit-reset') );
# Slow down if we're approaching the rate limit
# By the way GitHub mistakes days for minutes in their documentation --
# the rate limit is per minute, not per day.
if ( $self->api_throttle ) {
sleep 2 if (($self->rate_limit_remaining || 0)
< ($self->rate_limit || 60) / 2);
}
print STDERR "<<< " . $res->decoded_content . "\n" if $ENV{NG_DEBUG} and $ENV{NG_DEBUG} > 1;
return $res if $self->raw_response;
return $res->decoded_content if $self->raw_string;
if ($res->header('Content-Type') and $res->header('Content-Type') =~ 'application/json') {
my $json = $res->decoded_content;
$data = eval { $self->json->decode($json) };
unless ($data) {
# We tolerate bad JSON for errors,
# otherwise we just rethrow the JSON parsing problem.
die unless $res->is_error;
$data = { message => $res->message };
}
} else {
$data = { message => $res->message };
}
if ( $self->RaiseError ) {
# check for 'Client Errors'
if (not $res->is_success and ref $data eq 'HASH' and exists $data->{message}) {
my $message = $data->{message};
# Include any additional error information that was returned by the API
if (exists $data->{errors}) {
$message .= ': '.join(' - ',
map { $_->{message} }
grep { exists $_->{message} }
@{ $data->{errors} });
}
croak $message;
}
}
$self->_clear_pagination;
if ($res->header('link')) {
my @rel_strs = split ',', $res->header('link');
$self->_extract_link_url(\@rel_strs);
}
## be smarter
if (wantarray) {
return @$data if ref $data eq 'ARRAY';
return %$data if ref $data eq 'HASH';
}
return $data;
}
sub set_next_page {
my ($self, $page) = @_;
if( ! looks_like_number($page) ){
croak "Trying to set_next_page to $page, and not a number\n";
}
if( $page > $self->total_page && $page > 0 ){
return 0;
}
my $temp_url = $self->next_url;
$temp_url =~ s/([&?])page=[0-9]+([&?]*)/$1page=$page$2/;
$self->next_url( $temp_url );
return 1;
}
sub next_page {
my $self = shift;
return $self->query($self->next_url);
}
sub prev_page {
my $self = shift;
return $self->query($self->prev_url);
}
sub first_page {
my $self = shift;
return $self->query($self->first_url);
}
sub last_page {
my $self = shift;
return $self->query($self->last_url);
}
sub _clear_pagination {
my $self = shift;
foreach my $page (qw/first last prev next/) {
my $clearer = 'clear_' . $page . '_url';
$self->$clearer;
}
return 1;
}
sub iterate {
my ( $self, $method, $args, $callback ) = @_;
die "This is a method class" unless ref $self;
die "Need a method name as second argument" unless defined $method && $self->can($method);
die "Missing a callback function as third argument" unless ref $callback eq 'CODE';
my @list_args; # 3rd argument
if ( ref $args eq 'ARRAY' ) {
@list_args = @$args;
} elsif ( ref $args eq 'HASH' ) {
# used for v2 api which are passing a hash of named parameters instead of a list
@list_args = $args;
} else {
@list_args = $args; # can be undefined [need to preserve it instead of an empty list]
}
my $chunk = $self->can($method)->( $self, $args );
my $continue = 1;
while ( ref $chunk eq 'ARRAY' && scalar @$chunk ) {
# process a chunk
foreach my $item ( @$chunk ) {
$continue = $callback->( $item );
last unless $continue; # user has requested to stop iterating
}
last unless $continue; # user has requested to stop iterating
# get the next chunk
last unless $self->has_next_page;
$chunk = $self->next_page;
}
$self->_clear_pagination;
return;
}
sub _extract_link_url {
my ($self, $raw_strs) = @_;
foreach my $str (@$raw_strs) {
my ($link_url, $rel) = split ';', $str;
$link_url =~ s/^\s*//;
$link_url =~ s/^<//;
$link_url =~ s/>$//;
if( $rel =~ m/rel="(next|last|first|prev|deprecation|alternate)"/ ){
$rel = $1;
}
elsif( $rel=~ m/rel="(.*?)"/ ){
warn "Unexpected link rel='$1' in '$str'";
next;
}
else {
warn "Unable to process link rel in '$str'";
next;
}
if( $rel eq 'deprecation' ){
warn "Deprecation warning: $link_url\n";
}
my $url_attr = $rel . "_url";
$self->$url_attr($link_url);
# Grab, and expose, some additional header information
if( $rel eq "last" ){
$link_url =~ /[\&?]page=([0-9]*)[\&?]*/;
$self->total_pages( $1 );
}
}
return 1;
}
sub _make_request {
my($self, $req) = @_;
my $cached_res = $self->_get_shared_cache($req->uri);
if ($cached_res) {
$req->header("If-None-Match" => $cached_res->header("ETag"));
my $res = $self->ua->request($req);
if ($res->code == 304) {
return $cached_res;
}
$self->_set_shared_cache($req->uri, $res);
return $res;
} else {
my $res = $self->ua->request($req);
$self->_set_shared_cache( $req->uri, $res);
return $res;
}
}
sub _get_shared_cache {
my ($self, $uri) = @_;
return $self->cache->get($uri);
}
sub _set_shared_cache {
my($self, $uri, $response) = @_;
$self->cache->set($uri, $response);
}
## build methods on fly
sub __build_methods {
my $package = shift;
my %methods = @_;
foreach my $m (keys %methods) {
my $v = $methods{$m};
my $url = $v->{url};
my $method = $v->{method} || 'GET';
my $args = $v->{args} || 0; # args for ->query
my $check_status = $v->{check_status};
my $is_u_repo = $v->{is_u_repo}; # need auto shift u/repo
my $preview_version = $v->{preview};
my $paginate = $v->{paginate};
my $version = $v->{v} || $v->{version} || 1; # version for the accessor
# count how much %s inside u
my $n = 0; while ($url =~ /\%s/g) { $n++ }
no strict 'refs';
no warnings 'once';
*{"${package}::${m}"} = sub {
my $self = shift;
my ( $u, @qargs );
if ( $version == 2 ) {
my $opts = {};
if ( ref $_[0] ) {
my ( $_opts, $_qargs ) = @_;
$opts = $_opts;
if ( my $ref = ref $_qargs ) {
@qargs = @$_qargs if $ref eq 'ARRAY';
@qargs = $_qargs if $ref eq 'HASH';
}
} else { # backward compatibility
my $u = $url;
while ( $u =~ s{:([a-z_]+)}{} ) {
my $k = $1;
#next if defined $opts->{$k};
$opts->{$k} = shift;
die "$k value is not a scalar value $opts->{$k}" if ref $opts->{$k};
}
@qargs = $args ? splice(@_, 0, $args) : ();
}
# we can now use named :parameter in the url itself
$u = "$url";
{
no warnings;
$u =~ s{:([a-z_]+)}{$opts->{$1}}g;
}
} else {
## if is_u_repo, both ($user, $repo, @args) or (@args) should be supported
if ( ($is_u_repo or index($url, '/repos/%s/%s') > -1) and @_ < $n + $args) {
unshift @_, ($self->u, $self->repo);
}
# make url, replace %s with real args
my @uargs = splice(@_, 0, $n);
$u = sprintf($url, @uargs);
# args for json data POST
@qargs = $args ? splice(@_, 0, $args) : ();
}
# if preview API, set preview version
$self->accept_version($preview_version) if $preview_version;
if ($check_status) { # need check Response Status
my $old_raw_response = $self->raw_response;
$self->raw_response(1); # need check header
my $res = $self->query($method, $u, @qargs);
$self->raw_response($old_raw_response);
return index($res->header('Status'), $check_status) > -1 ? 1 : 0;
} else {
return $self->query($method, $u, @qargs);
}
};
if ($paginate) {
# Add methods next... and close...
# Make method names singular (next_comments to next_comment)
$m =~ s/s$//;
my $m_name = ref $paginate ? $paginate->{name} : $m;
*{"${package}::next_${m_name}"} = sub {
my $self = shift;
# count how much %s inside u
my $n = 0; while ($url =~ /\%s/g) { $n++ }
## if is_u_repo, both ($user, $repo, @args) or (@args) should be supported
if ( ($is_u_repo or index($url, '/repos/%s/%s') > -1) and @_ < $n + $args) {
unshift @_, ($self->u, $self->repo);
}
# make url, replace %s with real args
my @uargs = map { defined $_ ? $_ : '' } splice(@_, 0, $n);
my $u = sprintf($url, @uargs);
# if preview API, set preview version
$self->accept_version($preview_version) if $preview_version;
return $self->next($u);
};
*{"${package}::close_${m_name}"} = sub {
my $self = shift;
# count how much %s inside u
my $n = 0; while ($url =~ /\%s/g) { $n++ }
## if is_u_repo, both ($user, $repo, @args) or (@args) should be supported
if ( ($is_u_repo or index($url, '/repos/%s/%s') > -1) and @_ < $n + $args) {
unshift @_, ($self->u, $self->repo);
}
# make url, replace %s with real args
my @uargs = splice(@_, 0, $n);
my $u = sprintf($url, @uargs);
# if preview API, set preview version
$self->accept_version($preview_version) if $preview_version;
$self->close($u);
};
}
}
}
no Moo::Role;
1;
__END__
=head1 NAME
Net::GitHub::V3::Query - Base Query role for Net::GitHub::V3
=head1 SYNOPSIS
package Net::GitHub::V3::XXX;
use Moo;
with 'Net::GitHub::V3::Query';
=head1 DESCRIPTION
set Authentication and call API
=head2 ATTRIBUTES
=over 4
=item login
=item pass
=item access_token
Either set access_token from OAuth or login:pass for Basic Authentication
L<http://developer.github.com/>
=item raw_string
=item raw_response
=item api_throttle
API throttling is enabled by default, set api_throttle to 0 to disable it.
=item rate_limit
The maximum number of queries allowed per hour. 60 for anonymous users and
5,000 for authenticated users.
=item rate_limit_remaining
The number of requests remaining in the current rate limit window.
=item rate_limit_reset
The time the current rate limit resets in UTC epoch seconds.
=item update_rate_limit
Query the /rate_limit API (for free) to update the cached values for rate_limit, rate_limit_remaining, rate_limit_reset
=item last_page
Denotes the index of the last page in the pagination
=item RaiseError
=back
=head2 METHODS
=over 4
=item query
Refer L<Net::GitHub::V3>
=item next_page
Calls C<query> with C<next_url>. See L<Net::GitHub::V3>
=item prev_page
Calls C<query> with C<prev_url>. See L<Net::GitHub::V3>
=item first_page
Calls C<query> with C<first_url>. See L<Net::GitHub::V3>
=item last_page
Calls C<query> with C<last_url>. See L<Net::GitHub::V3>
=item set_next_page
Adjusts next_url to be a new url in the pagination space
I.E. you are jumping to a new index in the pagination
=item iterate($method_name, $arguments, $callback)
This provides an helper to iterate over APIs call using pagination,
using the combo: has_next_page, next_page... for you.
The arguments can be either a scalar if the function is using
a single argument, an ArrayRef when the function is using multiple
arguments. You can also use one HashRef for functions supporting named
parameters.
The callback function is called with a single item.
The return value of the callback function can be used to stop the
iteration when returning a 'false' value.
In common cases, you want to return a true value: '1'.
Sample usage:
$gh->org->iterate( 'repos', 'OrganizationName', sub {
my $item = shift;
print "Repo Name is $item->{name}"
return 1; # if you want to continue iterating
return; # use a false value when you want to interrupt the iteration
} );
=item result_sets
For internal use by the item-per-item pagination: This is a store of
the state(s) for the pagination. Each entry maps the initial URL of a
GitHub query to a L<Net::GitHub::V3::ResultSet> object.
=item next($url)
Returns the next item for the query which started at $url, or undef if
there are no more items.
=item close($url)
Terminates the item-per-item pagination for the query which started at
$url.
=back
=head3 NG_DEBUG
export NG_DEBUG=1 to view the request URL
NG_DEBUG > 1 to view request/response string
=head1 AUTHOR & COPYRIGHT & LICENSE
Refer L<Net::GitHub>
|