App-WatchLater

 view release on metacpan or  search on metacpan

lib/App/WatchLater/YouTube.pm  view on Meta::CPAN

  return $1 if m{^($regex)$};
  die "'$_' is not a valid video ID";
}

=head2 new

    my $api = App::WatchLater::YouTube->new(%opts)

This constructor returns a new API object. Attributes include:

=over 4

=item *

C<http> - an instance of HTTP::Tiny. If none is provided, a default new instance
is used.

=item *

C<api_key> - an API key.

=item *

C<access_token> - an OAuth2 access token.

=back

At least one of C<api_key> and C<access_token> must be provided. If both are
provided, C<access_token> is used for authorization.

=cut

use Carp;
use HTTP::Tiny;
use JSON;

BEGIN {
  my ($ok, $why) = HTTP::Tiny->can_ssl;
  croak $why unless $ok;
}

sub new {
  my ($class, %opts) = @_;

  my $http  = $opts{http} // HTTP::Tiny->new;
  my $key   = $opts{api_key};
  my $token = $opts{access_token};

  defined $key || defined $token
    or croak "no API key or access token, aborting";

  bless {
    http  => $http,
    key   => $key,
    token => $token,
  } => $class;
}

=head2 request

    my $body = $api->request($method, $endpoint, %params);

Send a request to the specified API endpoint using the given HTTP method. Query
parameters may be specified in C<%params>. Croaks if the request fails.

=cut

sub request {
  my ($self, $method, $endpoint, %params) = @_;
  my $url = 'https://www.googleapis.com/youtube/v3' . $endpoint;

  my %headers;

  if (defined $self->{token}) {
    $headers{Authorization} = 'Bearer ' . $self->{token};
  } else {
    $params{key} ||= $self->{key};
  }

  my $query = $self->{http}->www_form_urlencode(\%params);
  my $response = $self->{http}->request($method, "$url?$query", {
    headers => \%headers,
  });
  croak "$response->{status} $response->{reason}" unless $response->{success};
  $response->{content};
}

=head2 get_video

    my \%snippet = $api->get_video($video_id);

Retrieves a YouTube video resource, including the snippet, for the video given
by C<$video_id>. Croaks if no such video is found.

=cut

sub get_video {
  my ($self, $video_id) = @_;
  my $json = $self->request(
    'GET', '/videos',
    id   => $video_id,
    part => 'snippet',
  );
  my $obj = decode_json($json);
  my $item = $obj->{items}[0] or croak "no video with id $video_id";
  $item->{snippet};
}

=head1 AUTHOR

Aaron L. Zeng, C<< <me at bcc32.com> >>

=head1 BUGS

Please report any bugs or feature requests to C<bug-app-watchlater at rt.cpan.org>, or through
the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=App-WatchLater>.  I will be notified, and then you'll
automatically be notified of progress on your bug as I make changes.




=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc App::WatchLater::YouTube


You can also look for information at:



( run in 1.385 second using v1.01-cache-2.11-cpan-524268b4103 )