API.pm

filter: Statementstmt 92.5% 25 / 27 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 9 / 9 Podpod n/a totaltotal 94.4% 34 / 36 CC 1 SCAR 0.3
CC
1
Cov
93%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« API/Video.pm ↑ Summary
1 #########################################################################
2 # ex: set ts=8 sw=4 et
3 #########################################################################
4 package WWW::Facebook::API;
5  
6 33 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 33 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 33 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 33 ▶use version; our $VERSION = qv('0.4.18');
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 33 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 33 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 33 ▶use Digest::MD5 qw(md5_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 33 ▶use Encode qw(encode_utf8 is_utf8);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 0 ▶use CGI;
Subroutine BEGIN: called CC=1 SCAR=2.6
17 use CGI::Util qw(escape);
18  
19 use WWW::Facebook::API::Exception;
20  
21 our @namespaces = qw(
22 Admin Application Auth
23 Canvas Comments Connect
24 Data Events FBML
25 Feed FQL Friends
26 Groups Intl Links
27 LiveMessage Message Notes
28 Notifications Pages Permissions
29 Photos Profile SMS
30 Status Stream Users
31 Video
32 );
33  
34 for (@namespaces) {
35 my $package = __PACKAGE__ . "::$_";
36 my $name = "\L$_";
37 ## no critic
38 my $namespace = eval qq(
39 use $package;
40  
41 sub $name {
42 my \$self = shift;
43 unless ( \$self->{'_$name'} ) {
44 \$self->{'_$name'} = $package->new( base => \$self );
45 }
46 return \$self->{'_$name'};
47 }
48  
49 package $package;
50 sub base { return shift->{'base'}; };
51 sub new {
52 my ( \$class, \%args ) = \@_;
53 my \$self = bless \\\%args, \$class;
54  
55 delete \$self->{\$_} for grep { !/base/xms } keys %{\$self};
56 \$self->\$_ for keys %{\$self};
57  
58 return \$self;
59 };
60 1;
61  
62 );
63 croak "Cannot create namespace $name: $@\n" if not $namespace;
64 }
65  
66 our %attributes = (
67 parse => 1,
68 format => 'JSON',
69 debug => 0,
70 throw_errors => 1,
71 api_version => '1.0',
72 apps_uri => 'http://apps.facebook.com/',
73 server_uri => 'http://api.facebook.com/restserver.php',
74 ( map { $_ => q{} }
75 qw(
76 api_key secret desktop
77 last_call_success last_error skipcookie
78 popup next session_key
79 session_expires session_uid callback
80 app_path ua query
81 config app_id call_as_apikey
82 )
83 ),
84 );
85  
86 for ( keys %attributes ) {
87 ## no critic
88 my $attribute = eval qq(
89 sub $_ {
90 my \$self = shift;
91 return \$self->{$_} = shift if defined \$_[0];
92 return \$self->{$_} if defined \$self->{$_};
93 return \$self->{$_} = '$attributes{$_}';
94 }
95 1;
96 );
97 croak "Cannot create attribute $_: $@\n" if not $attribute;
98 }
99  
100 sub _set_from_outside {
101 my $self = shift;
102  
103 my $app_path = '_' . ( $self->{'app_path'} || $self->app_path );
104 $app_path =~ tr/a-z/A-Z/;
105 $app_path =~ tr/A-Za-z0-9_/_/c;
106  
107 my %ENV_VARS = qw(
108 WFA_API_KEY api_key
109 WFA_SECRET secret
110 WFA_DESKTOP desktop
111 WFA_SESSION_KEY session_key
112 );
113  
114 $self->_set_from_file( $app_path, %ENV_VARS ) if $self->{'config'};
115 $self->_set_from_env( $app_path, %ENV_VARS );
116  
117 return;
118 }
119  
120 sub _set_from_file {
121 my $self = shift;
122 my $app_path = shift;
123 my %ENV_VARS = @_;
124  
125 open my $config, '<', $self->{'config'} ## no critic
126 or croak "Cannot open $self->{'config'}";
127  
128 while (<$config>) {
129 carp "Config line: $_" if $self->{'debug'};
130 chomp;
131 my ( $key, $val ) = split m/=/xms, $_, 2;
132 next if !$key;
133 carp "Key/Val pair: $key -> $val" if $self->{'debug'};
134 for ( $key, $val ) {
135 s/\A\s+//xms;
136 s/\s+\Z//xms;
137 }
138 $ENV{$key} ||= $val;
139 }
140  
141 close $config or croak "Cannot close $self->{'config'}";
142  
143 return;
144 }
145  
146 sub _set_from_env {
147 my $self = shift;
148 my $app_path = shift;
149 my %ENV_VARS = @_;
150  
151 for ( keys %ENV_VARS ) {
152 if ( exists $ENV{ $_ . $app_path } ) {
153 $self->{ $ENV_VARS{$_} } ||= $ENV{ $_ . $app_path };
154 }
155 elsif ( exists $ENV{$_} ) {
156 $self->{ $ENV_VARS{$_} } ||= $ENV{$_};
157 }
158 }
159  
160 return;
161 }
162  
163 sub new {
164 my ( $self, %args ) = @_;
165 my $class = ref $self || $self;
166 $self = bless \%args, $class;
167 $self->_set_from_outside(); # set api_key etc. if needed
168  
169 $self->{'ua'} ||=
170 LWP::UserAgent->new( agent => "Perl-WWW-Facebook-API/$VERSION" );
171 my $is_attribute = join q{|}, keys %attributes;
172 delete $self->{$_} for grep { !/^ $is_attribute $/xms } keys %{$self};
173  
174 # set up default namespaces
175 $self->$_($self) for map {"\L$_"} @namespaces;
176  
177 # set up default attributes
178 $self->$_ for keys %attributes;
179  
180 return $self;
181 }
182  
183 sub log_string {
184 my ( $self, $params, $response ) = @_;
185 my $string = "\nparams = \n";
186  
187 $string .= "\t$_:$params->{$_}\n" for sort keys %{$params};
188 $string .= "response =\n$response\n";
189  
190 return $string;
191 }
192  
193 sub call_success {
194 my $self = shift;
195 $self->last_call_success(shift) if @_;
196 $self->last_error(shift) if @_;
197 return [ $self->last_call_success, $self->last_error ];
198 }
199  
200 sub call {
201 my ( $self, $method, %args ) = @_;
202 my ( $response, $params, $sig, $raw_data, $filename );
203 $self->call_success(1);
204  
205 if ( $self->call_as_apikey ) {
206 $args{'call_as_apikey'} = $self->call_as_apikey;
207 }
208  
209 ( $params, $raw_data, $filename ) =
210 $self->_format_and_check_params( $method, %args );
211 $sig = $self->generate_sig(
212 params => $params,
213 secret => delete $params->{'secret'},
214 );
215  
216 $response = $self->_post_request( $params, $sig, $raw_data, $filename );
217  
218 carp $self->log_string( $params, $response ) if $self->debug;
219 if ( $self->_has_error_response($response) ) {
220 if ( $self->throw_errors ) {
221 warn WWW::Facebook::API::Exception->new(
222 $method, $params, $response
223 );
224 }
225 }
226  
227 return $self->_reformat_response( $params, $response );
228 }
229  
230 sub generate_sig {
231 my ( $self, %args ) = @_;
232 my %params = %{ $args{'params'} };
233 return md5_hex( ( map {"$_=$params{$_}"} sort keys %params ),
234 $args{'secret'} );
235 }
236  
237 sub verify_sig {
238 my ( $self, %args ) = @_;
239 return $args{'sig'} eq $self->generate_sig(
240 params => $args{'params'},
241 secret => $args{'secret'} || $self->secret,
242 );
243 }
244  
245 sub session {
246 my ( $self, %args ) = @_;
247 $self->{"session_$_"} = $args{$_} for keys %args;
248 return;
249 }
250  
251 sub redirect {
252 my $self = shift;
253 my $url = shift;
254 $self->query(shift);
255  
256 if ( $self->canvas->in_fb_canvas ) {
257 return qq{<fb:redirect url="$url" />};
258 }
259 elsif ($url =~ m{^https?://([^/]*\.)?facebook\.com(:\d+)?}ixms
260 && $self->session_uid )
261 {
262 return join q{},
263 map {"$_\n"}
264 '<script type="text/javascript">'
265 . qq{top.location.href = "$url"}
266 . '</script>';
267 }
268  
269 print CGI->new->redirect(
270 $self->get_app_url( next => $self->get_login_url ) );
271 return 1;
272 }
273  
274 sub require_add { return shift->require( 'add', @_ ); }
275 sub require_frame { return shift->require( 'frame', @_ ); }
276 sub require_login { return shift->require( 'login', @_ ); }
277  
278 sub require { ## no critic
279 my $self = shift;
280 my $what = shift;
281 $self->query(shift);
282  
283 if ( $what eq 'login' ) {
284 unshift @_, qw( canvas ) if $self->canvas->in_frame;
285 }
286 if ( $what eq 'frame' ) {
287 return if $self->canvas->in_frame;
288 unshift @_, qw( canvas );
289 $what = 'login';
290 }
291  
292 my $user = $self->canvas->get_fb_params->{'user'};
293 if ( $what eq 'add' ) {
294 if ( !$self->canvas->get_fb_params->{'added'} ) {
295 $user = undef;
296 }
297 }
298 return if $user;
299  
300 return $self->redirect( $self->get_url( $what, @_ ) );
301 }
302  
303 sub get_facebook_url { return shift->get_url( 'facebook', @_ ); }
304 sub get_add_url { return shift->get_url( 'add', @_ ); }
305 sub get_infinite_session_url { return shift->get_url('infinite_session'); }
306 sub get_login_url { return shift->get_url( 'login', @_ ); }
307 sub get_app_url { return shift->get_url( 'app', @_ ); }
308  
309 sub get_url {
310 my $self = shift;
311 my $type = shift;
312  
313 if ( $type eq 'facebook' ) {
314 my $site = shift || 'www';
315 return "http://$site.facebook.com";
316 }
317  
318 if ( $type eq 'app' ) {
319 return $self->apps_uri . $self->app_path . q{/};
320 }
321  
322 if ( $type eq 'custom' ) {
323 return (shift) . $self->_add_url_params(@_);
324 }
325  
326 return $self->get_url('facebook')
327 . (
328 $type eq 'add' ? '/add.php'
329 : $type eq 'infinite_session' ? '/code_gen.php'
330 : $type eq 'login' ? '/login.php'
331 : q{}
332 ) . $self->_add_url_params(@_);
333 }
334  
335 sub unescape_string {
336 my $self = shift;
337 my $string = shift;
338 $string =~ s/(?<!\\)(\\.)/qq("$1")/xmsgee;
339 return $string;
340 }
341  
342 sub _add_url_params {
343 my $self = shift;
344 my $params = q{?api_key=} . $self->api_key . q{&v=1.0};
345 if (@_) {
346 if ( @_ % 2 ) {
347  
348 # Odd number of elelemts, so didn't pass in canvas => 1
349 $params .= q{&canvas} if grep { $_ eq 'canvas' } @_; ## no critic
350 @_ = grep { $_ ne 'canvas' } @_;
351 }
352 my %params = @_;
353 $params .= q{&canvas} if delete $params{'canvas'};
354  
355 for ( sort keys %params ) {
356 next if not defined $params{$_};
357 $params{$_} = escape( $params{$_} ) if $_ eq 'next';
358 $params .= "&$_=$params{$_}";
359 }
360 }
361 return $params;
362 }
363  
364 sub _parser {
365 my $parser = JSON::Any->new;
366  
367 $parser->handler->allow_nonref;
368 return $parser;
369 }
370  
371 sub _parse {
372 my ( $self, $response ) = @_;
373  
374 # Some shortcuts
375 return q{} if $response =~ /\A"?"?\Z/xms;
376 return 1 if $response =~ /\A"?true"?\Z/xms;
377 return 0 if $response =~ /\A"?false"?\Z/xms;
378  
379 my $parser;
380 eval { $parser = _parser(); 1; } or do {
381  
382 # Only load JSON::Any if we haven't already. Lets the developers
383 # pick their choice of JSON modules (JSON::DWIW, for example)
384 ## no critic
385 eval q{use JSON::Any};
386 croak "Unable to load JSON module for parsing:$@\n" if $@;
387 $parser = _parser();
388 };
389 carp 'JSON::Any is parsing with ' . $parser->handlerType if $self->debug;
390  
391 return $parser->decode($response);
392 }
393  
394 sub _check_values_of {
395 my ( $self, $params ) = @_;
396  
397 if ( $self->desktop ) {
398 $params->{'call_id'} = time if $self->desktop;
399 }
400  
401 if ( $params->{'method'} !~ m/^auth/xms ) {
402 $params->{'session_key'} ||= $self->session_key;
403 if ( !$params->{'callback'} && $self->callback ) {
404 $params->{'callback'} = $self->callback;
405 }
406 }
407  
408 $params->{'method'} = "facebook.$params->{'method'}";
409 $params->{'v'} ||= $self->api_version;
410  
411 $params->{$_} ||= $self->$_ for qw(api_key format);
412 return;
413 }
414  
415 sub _format_and_check_params {
416 my ( $self, $method, %args ) = @_;
417  
418 my $params = delete $args{'params'} || {};
419 $params->{$_} = $args{$_} for keys %args;
420 $params->{'secret'} ||= $self->secret;
421 $params->{'method'} ||= $method;
422  
423 $self->_check_values_of($params);
424  
425 # reformat arrays and add each param to digest
426 for ( keys %{$params} ) {
427 if ( ref $params->{$_} eq 'ARRAY' ) {
428 $params->{$_} = join q{,}, @{ $params->{$_} };
429 }
430  
431 if ( is_utf8( $params->{$_} ) ) {
432 $params->{$_} = encode_utf8( $params->{$_} );
433 }
434 }
435  
436 croak '_format_and_check_params must be called in list context!'
437 if !wantarray;
438  
439 return ( $params, delete $params->{'data'}, delete $params->{'filename'} );
440 }
441  
442 sub _has_error_response {
443 my $self = shift;
444 my $response = shift;
445  
446 # The different type of error responses
447 my $json = q{ \{ "error_code" \D+ (\d+) .* "error_msg" [^"]+ "([^"]+)" };
448 my $xml = q{ <error_code> (\d+) .* <error_msg> ([^<]+)};
449  
450 for ( $json, $xml ) {
451 if ( $response =~ m/$_/xms ) {
452 $self->call_success( 0, "$1: $2" );
453 return 1;
454 }
455 }
456  
457 return;
458 }
459  
460 sub _reformat_response {
461 my ( $self, $params, $response ) = @_;
462  
463 # get actual response when web app
464 if ( $params->{'callback'} ) {
465 $response =~ s/^$params->{'callback'} [^(]* [(](.+) [)];$/$1/xms;
466 }
467 undef $params;
468  
469 # ... and unescape it if it's not going to be parsed
470 if ( !$self->desktop && !$self->parse ) {
471 $response = $self->unescape_string($response);
472 }
473  
474 if ( $self->parse && $self->format eq 'XML' ) {
475 $self->parse(0);
476 carp q{format is XML: setting parse to 0} if $self->debug;
477 }
478 return $response if !$self->parse;
479  
480 $response = $self->_parse($response);
481 return if $self->_is_empty_response($response);
482 return $response;
483 }
484  
485 sub _is_empty_response {
486 my ( $self, $response ) = @_;
487  
488 return 1 if ref $response eq 'HASH' && !keys %{$response};
489 return 1 if ref $response eq 'ARRAY' && @{$response} == 0;
490 return;
491 }
492  
493 sub _post_request {
494 my ( $self, $params, $sig, $raw_data, $filename ) = @_;
495  
496 my $post_params = [ map { $_ => $params->{$_} } sort keys %{$params} ];
497 push @{$post_params}, 'sig' => $sig;
498  
499 if ($raw_data) {
500 push @{$post_params}, data => [
501 undef, ( $filename || 'filename'),
502 'Content-Type' => 'application/octet-stream',
503 'Content' => $raw_data,
504 ];
505 }
506 return $self->ua->post(
507 $self->server_uri,
508 'Content_type' => 'form-data',
509 'Content' => $post_params,
510 )->content;
511 }
512  
513 1; # Magic true value required at end of module
514 __END__
« API/Video.pm ↑ Summary