Skip to content

Instantly share code, notes, and snippets.

@yusukebe
Created December 15, 2012 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yusukebe/4290677 to your computer and use it in GitHub Desktop.
Save yusukebe/4290677 to your computer and use it in GitHub Desktop.
Run a facebook post like a Web Application.
package facebook;
use Plack::Request;
use Plack::Response;
use Plack::Runner;
use Plack::App::URLMap;
use URI::Escape;
use LWP::Simple;
use JSON;
use HTML::Entities;
use Encode;
my $id;
use overload "/" => sub { $id = $_[1]; $_[0] }, fallback => 1;
sub import {
my $pkg = caller;
*{"$pkg\::com"} = *{"$pkg\::posts"} = sub() { bless {}, __PACKAGE__ };
}
my $app_id = $ENV{RUNFB_APP_ID};
my $app_secret = $ENV{RUNFB_APP_SECRET};
my $app_redirect = sub {
my $req = Plack::Request->new(shift);
my $uri = uri_escape_utf8( $req->base . 'callback' );
my $redirect_url = "http://www.facebook.com/dialog/oauth?"
. "client_id=$app_id&redirect_uri=$uri&scope=read_stream";
my $res = Plack::Response->new(302);
$res->redirect($redirect_url);
return $res->finalize;
};
my $app_callback = sub {
my $req = Plack::Request->new(shift);
my $code = $req->param('code');
my $uri = uri_escape_utf8( $req->base );
my $token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=$app_id&redirect_uri=$uri&client_secret=$app_secret&code=$code";
my $access_token = get($token_url);
my $json = get("https://graph.facebook.com/$id?$access_token");
my $data = decode_json($json);
my $message = $data->{message};
my $result;
{
local *STDOUT;
open STDOUT, '>', \$result;
eval $message;
}
my $res = Plack::Response->new(200);
$res->content_type('text/html');
$res->body(encode_utf8($result));
return $res->finalize;
};
END {
my $urlmap = Plack::App::URLMap->new;
$urlmap->map( '/' => $app_redirect );
$urlmap->map( '/callback' => $app_callback );
my $app = $urlmap->to_app;
my $runner = Plack::Runner->new;
$runner->parse_options(@ARGV);
$runner->run($app);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment