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
|
package VUser::Google::ApiProtocol::V2_0;
use warnings;
use strict;
use XML::Simple;
use LWP::UserAgent qw(:strict);
use HTTP::Request qw(:strict);
use Encode;
use Carp;
use Data::Dumper;
use Moose;
extends 'VUser::Google::ApiProtocol';
our $VERSION = '0.5.1';
has 'google_host' => (is => 'ro',
default => 'www.google.com'
);
has 'google_token_url' => (is => 'ro',
default => 'https://www.google.com/accounts/ClientLogin'
);
has 'max_token_age' => (is => 'ro',
default => 86400
);
# base url to the Google REST API
has 'google_baseurl' => (is => 'ro',
default => 'https://www.google.com/a/feeds/'
);
has 'google_apps_schema' => (is => 'ro',
default => 'http://schemas.google.com/apps/2006'
);
has 'success_code' => (is => 'ro',
default => 'Success(2000)'
);
has 'failure_code' => (is => 'ro',
default => 'Failure(2001)'
);
has 'max_name_length' => (is => 'ro', default => '40');
has 'max_username_length' => (is => 'ro', default => '30');
override 'Login' => sub {
my $self = shift;
#print STDERR "LOGIN: debug=".$self->debug."\n";
$self->dprint("Relogin called");
return 1 if $self->IsAuthenticated() and not $self->refresh_token();
my $retval = 0;
my $stats = $self->stats();
$stats->{logins}++;
## Clear last results
$self->_set_reply_headers('');
$self->_set_reply_content('');
$self->_set_result({});
## Create an LWP object to make the HTTP POST request
my $lwp = LWP::UserAgent->new;
if (defined $lwp) {
$lwp->agent($self->useragent);
$lwp->from($self->admin.'@'.$self->domain);
# Submit the request with values for
# accountType, Email and Passwd variables
my $response = $lwp->post($self->google_token_url,
['accountType' => 'HOSTED',
'Email' => $self->admin.'@'.$self->domain,
'Passwd' => $self->password,
'service' => 'apps'
]
);
# save the reply page
$self->_set_reply_headers($response->headers->as_string);
$self->_set_reply_content($response->content);
if ($response->is_success) {
# Extract the authentication token from the response
foreach my $line (split(/\n/, $response->content)) {
$self->dprint("RECV'd: $line");
if ($line =~ m/^Auth=(.+)$/) {
$self->_set_authtoken($1);
$self->_set_authtime(time());
$self->dprint("Token found: %s", $self->authtoken);
# Clear refresh
$self->refresh_token(0);
$retval = 1;
last;
}
}
}
else {
$self->dprint("Error in login: %s", $response->status_line);
$self->_set_result({reason => "Error in login: ".$response->status_line});
}
}
else {
$self->dprint("Error getting LWP object: $!");
$self->_set_result({reason => "Error getting LWP object: $!"});
}
$self->_set_stats($stats);
return $retval;
};
override 'IsAuthenticated' => sub {
#get object reference
my $self = shift();
my $token_age = time - $self->authtime();
if( $self->refresh_token() or ( $token_age > $self->max_token_age() ) ) {
$self->dprint("Refresh token: %s; time-auth: %d; max_age: %d",
$self->refresh_token, $token_age, $self->max_token_age);
return 0;
}
#we are still okay!
return 1;
};
override 'Request' => sub {
my $self = shift;
my $retval = 0;
$self->dprint( "*** REQUEST ***" );
# relogin if needed
$self->Login;
# clear last results
$self->_set_reply_headers('');
$self->_set_reply_content('');
$self->_set_result({});
if (@_ != 2 and @_ != 3) {
$self->_set_result({reason => 'Invalid number of arguments to Request()'});
return 0;
}
# get paramters
my ($method, $url, $body) = @_;
$self->dprint("Method: $method; URL: $url");
$self->dprint("Body: $body") if $body;
## Keep some stats
my $stats = $self->stats;
$stats->{requests}++;
$stats->{rtime} = time;
## Check if we are authenticated to google
if (not $self->IsAuthenticated()) {
$self->dprint("Error autheticating");
$self->_set_stats($stats);
return 0;
}
## Properly encode the body
$body = encode('UTF-8', $body);
## Create an LWP object to make the HTTP POST request
my $ua = LWP::UserAgent->new;
if (not defined $ua) {
$self->dprint("Cannot create LWP::UserAgent: $!");
$self->_set_result({reason => "Cannotcreate LWP::UserAgent in Request: $!"});
$self->_set_stats($stats);
return 0;
}
#and create the request object where are we connecting to
# v2.0 uses a diffent url based what's being done.
# The API methods will construct the URL becuase action specific
# information, such as domain and user, is embedded with it.
# v2.0 use different methods depending on the action
# It's up to the API methods to know which method to use
my $req = HTTP::Request->new($method => $url);
if (not defined $req) {
$self->dprint("Cannot create HTTP::Request object: $!");
$self->_set_result({reason => "Cannot create HTTP::Request object in Request(): $!"});
$self->_set_stats($stats);
return $retval;
}
# Set some user agent variables
$ua->agent($self->useragent);
$ua->from('<'.$self->admin.'@'.$self->domain.'>');
# Submit the request
$req->header('Accept' => 'application/atom+xml');
$req->header('Content-Type' => 'application/atom+xml');
if ($body) {
$req->header('Content-Length' => length($body) );
}
$req->header('Connection' => 'Keep-Alive');
$req->header('Host' => $self->google_host);
$req->header('Authorization' => 'GoogleLogin auth='.$self->authtoken);
# Assign the data to the request
# Perhaps if $method eq 'GET' or 'DELETE' would be better
if ($body) {
$req->content($body);
}
## Execute the request
my $response = $ua->request($req);
$self->dprint(Data::Dumper::Dumper($response));
# Save reply page
$self->_set_reply_headers($response->headers->as_string);
$self->_set_reply_content($response->content);
# Check result
if ($response->is_success) {
$stats->{success}++;
$self->dprint("Success in post:");
my $xml = decode('UTF-8', $response->content);
$self->dprint($xml);
if ($xml) {
## Parse the XML using XML::Simple
my $simple = XML::Simple->new(ForceArray => 1);
$self->_set_result($simple->XMLin($xml));
$self->dprint(Dumper($self->{result}));
}
else {
$self->_set_result({});
}
$self->dprint("Google API success!");
$retval = 1;
}
else {
# OK. Funky issue. When trying to get a user that doesn't exist,
# Google throws a 400 error instead of returning a error document.
# Google has fun. If there is a problem with the request,
# google triggers a 400 error which then fails on ->is_success.
# So, we need to check the content anyway to see if there is a
# reason for the failure.
$self->dprint("Google API failure!");
my $xml = decode('UTF-8', $response->content);
$self->dprint($xml);
if ($xml) {
my $simple = XML::Simple->new(ForceArray => 1);
$self->_set_result($simple->XMLin($xml));
$self->dprint('Error result: %s', Dumper($self->result));
}
if (defined ($self->result()->{error}[0]{reason})) {
my $error = sprintf("Google API failure: %s - %s",
$self->result()->{error}[0]{errorCode},
$self->result()->{error}[0]{reason}
);
$self->dprint($error);
my $res = $self->result;
$res->{reason} = $error;
$self->_set_result($res);
}
else {
$self->dprint("Error in post: %s", $response->status_line);
my $res = $self->result;
$res->{reason} = "Error in post: ".$response->status_line;
$self->_set_result($res);
}
}
return $retval;
};
no Moose;
__PACKAGE__->meta->make_immutable;
1;
__END__
=head1 NAME
VUser::Google::ApiProtocol::V2_0 - Implements version 2.0 of the Google APIs.
=head1 SYSNOPSIS
use VUser::Google::ApiProtocol::V2_0;
## Create a new connection
my $google = VUser::Google::ApiProtocol::V2_0->new(
domain => 'your.google-apps-domain.com',
admin => 'admin_user',
password => 'admin_user password',
);
## Login to the Google Apps API
# Login() uses the credentials provided in new()
$google->Login();
## Create a new request
# Create the URL to send to API request to.
# See the API docs for the valid URLs
my $url = "https://apps-apis.google.com/a/feeds/emailsettings/2.0/"
$url .= "your.google-apps-domain.com/username/label";
# Create XML message to send to Google
# See the API docs for the valid XML to send
my $xml = '<?xml version="1.0" encoding="utf-8"?>...';
# NB: The method (POST here) may be different depending on API call
my $success = $google->Request('POST', $url, $xml);
# Get the parsed response
if ($success) {
# $result is the XML reply parsed by XML::Simple
my $result = $google->get_result;
}
else {
# $result is the error message from google
# parsed by XML::Simple with the addition of a
# 'reason' key which contains the error.
my $result = $google->get_result;
die "Error: $result->{reason}";
}
=head1 DESCRIPTION
Implements version 2.0 of the Google API. See L<VUser::Google::ApiProtocol>
for a list of members and methods.
=head1 SEE ALSO
L<VUser::Google::ApiProtocol>, L<XML::Simple>
=head1 AUTHOR
Randy Smith <perlstalker@vuser.org>
Adapted from code from Johan Reinalda <johan@reinalda.net>
=head1 LICENSE
Copyright (C) 2006 by Johan Reinalda, johan at reinalda dot net
Copyright (C) 2009 by Randy Smith, perlstalker at vuser dot org
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.
If you make useful modification, kindly consider emailing then to me for inclusion in a future version of this module.
=cut
|