Skip to content

Instantly share code, notes, and snippets.

@mtsukamoto
Created January 7, 2013 09:04
Show Gist options
  • Save mtsukamoto/4473514 to your computer and use it in GitHub Desktop.
Save mtsukamoto/4473514 to your computer and use it in GitHub Desktop.
WWW::OpenPNE3::API::Client - OpenPNE3 smartphone api client
package WWW::OpenPNE3::API::Client;
use utf8;
use strict;
use warnings;
use Carp;
use base 'WWW::Mechanize';
use Encode;
use JSON -support_by_pp;
use URI;
our $VERSION = '0.0.1';
sub new {
my $class = shift;
my %args = @_;
my $openpne = exists($args{'openpne'}) ? delete($args{'openpne'}) : undef;
my $self = $class->SUPER::new(%args);
bless $self, $class;
$self->env_proxy;
$self->_param($openpne) if (defined($openpne));
return $self;
}
sub _param {
my $self = shift;
$self->{'_param'} ||= {};
return $self->{'_param'} if (not @_);
return $self->{'_param'}->{$_[0]} if (@_ == 1 && ref($_[0]) ne 'HASH');
if (@_ == 1) {
$self->{'_param'} = shift;
} else {
while (@_) {
my ($key, $value) = splice(@_, 0, 2);
$self->{'_param'}->{$key} = $value;
}
}
return $self;
}
sub site { my $self = shift; return $self->_param('site', @_); }
sub account { my $self = shift; return $self->_param('account', @_); }
sub password { my $self = shift; return $self->_param('password', @_); }
sub api_base { my $self = shift; return $self->_param('api_base', @_); }
sub api_key { my $self = shift; return $self->_param('api_key', @_); }
sub _api_url {
my $self = shift;
my $url = shift || return;
my $site_base = $self->site;
my $api_base = $self->api_base;
$api_base = URI->new_abs($api_base, $site_base) if ($api_base && $site_base);
$url = $api_base ? URI->new_abs($url, $api_base) : URI->new($url);
return $url;
}
sub login {
my $self = shift;
my $url = URI->new($self->site);
my $account = $self->account;
my $password = $self->password;
# start page
my $res = $self->get($url);
croak(decode_utf8($res->status_line). "\n") if (not $res->is_success);
# login
$self->current_form()->find_input(undef, 'text')->value($account);
$self->current_form()->find_input(undef, 'password')->value($password);
$res = $self->submit_form();
croak(decode_utf8($res->status_line). "\n") if (not $res->is_success);
croak($self->pne_error. "\n") if ($self->is_error);
# extract api information
my $content = $res->content;
croak("Can't find 'apiKey' and 'apiBase'") unless ($content =~ /var openpne = ({.*?});/);
my $json = $1;
my $openpne = JSON::from_json($json);
$self->api_key($openpne->{'apiKey'});
$self->api_base($openpne->{'apiBase'});
return 1;
}
sub fetch_api {
my $self = shift;
my $url = shift;
my %args = @_;
$args{'apiKey'} = $self->api_key;
my $uri = $self->_api_url($url);
my $res = $self->post($uri, \%args);
croak(decode_utf8($res->status_line). "\n") if (not $res->is_success);
croak($self->status_line. "\n") if ($self->is_error);
my $json = $res->content;
my $result = JSON::from_json($json);
if ($result->{'status'} eq 'error') {
$self->status_line($result->{'status'} . ':' . $result->{'message'});
croak($self->status_line. "\n");
}
return $result;
}
sub is_error {
my $self = shift;
my $response = $self->response || return undef;
if ($response->is_error) {
$self->status_line($response->status_line);
return 1;
}
if ($self->is_html) {
my $error = undef;
$error = $1 if ($self->content =~ /<input\b[^<>]*\bname="([^"]*error[^"]*)"\b[^<>]*>/i);
$error = $1 if ($self->content =~ /<div\b[^<>]*\bid="([^"]*error[^"]*)"\b[^<>]*>/i);
if ($error) {
$self->status_line($error);
return 1;
}
}
return;
}
sub status_line {
my $self = shift;
$self->{'_status_line'} = shift if (@_);
return $self->{'_status_line'};
}
1;
__END__
=head1 NAME
WWW::OpenPNE3::API::Client - OpenPNE3 smartphone api client
=head1 VERSION
This document describes WWW::OpenPNE3::API::Client version 0.0.1
=head1 SYNOPSIS
use strict;
use warnings;
use utf8;
use Encode;
use WWW::OpenPNE3::API::Client;
my $pne = WWW::OpenPNE3::API::Client->new(
'openpne' => {
'site' => 'http://openpne3.example.com/',
'account' => 'myname',
'password' => 'mypassword',
}
);
$pne->login();
my $result = eval { $pne->fetch_api('community/search.json'); };
foreach my $data (@{$result->{'data'}}) {
my @data = map { $data->{$_} } qw(id name category public_flag member_count);
my $line = Encode::encode_utf8(sprintf("[%05d] %s (%s/%s/%d members)\n", @data));
print $line;
}
=head1 DESCRIPTION
This module is client library for OpenPNE3 smartphone api
specified in "OpenPNE Smartphone API Document",
at <http://houou.github.com/api.php/>
=head1 INTERFACE
=over
=item new
Constructor.
Most of arguments are passed to WWW::Mechanize->new, the base class constructor.
Additionally, you can pass site pecification with 'openpne' key, see SYNOPSIS.
=item site
Set/get openpne site url.
=item account
Set/get openpne account.
=item password
Set/get openpne password.
=item api_base
Get openpne api base url.
api_base is set automatically in login().
Althogh, you can specify immediatory with this method.
note: login() overwrites api_base, so do it after login() succeeded.
=item api_key
Get openpne api key.
api_key is set automatically in login().
Althogh, you can specify immediatory with this method.
note: login() overwrites api_key, so do it after login() succeeded.
=item login
Login to openpne at specified with site(),
with authorization parameters specified with account() and password().
=item fetch_api
Fetch API result.
First argument is api url, like 'community/search.json' or
'http://openpne3.example.com/api.php/community/search.json',
necessary.
Additionary, you can pass api parameters like below.
my $result = eval { $pne->fetch_api('community/search.json', 'keyword' => 'openpne'); };
For more information about api parametes, see "OpenPNE Smartphone API Document".
=item is_error
Returns true when latest fetch failed, like $mech->res->is_error().
This method can care login error (it returns 200, and contents with error message).
=item status_line
Returns status line when latest fetch failed, like $mech->res->status_line().
This method can care login or api error (these return 200, and contents with error message).
=back
=head1 DEPENDENCIES
=over
=item * WWW::Mechanize
=item * Encode
=item * JSON
=back
=head1 AUTHOR
Makio Tsukamoto C<tsukamoto@gmail.com>
=head1 LICENCE AND COPYRIGHT
Copyright (c) 2013, Makio Tsukamoto C<tsukamoto@gmail.com>. All rights reserved.
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic>.
=head1 DISCLAIMER OF WARRANTY
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment