source: perl/modules/Facebook/lib/BarnOwl/Module/Facebook/Handle.pm @ ee98987

Last change on this file since ee98987 was ee98987, checked in by Edward Z. Yang <ezyang@mit.edu>, 11 years ago
Initial commit of Facebook module implementation. This module was inspired by Kevin Riggle's Facebook-hacked-onto-Twitter implementation, but was rewritten to stand alone as its own module and use the new Facebook Graph API. It requires the Facebook::Graph CPAN module. Signed-off-by: Edward Z. Yang <ezyang@mit.edu>
  • Property mode set to 100644
File size: 6.2 KB
Line 
1use warnings;
2use strict;
3
4=head1 NAME
5
6BarnOwl::Module::Facebook::Handle
7
8=head1 DESCRIPTION
9
10Contains everything needed to send and receive messages from Facebook
11
12=cut
13
14package BarnOwl::Module::Facebook::Handle;
15
16use Facebook::Graph;
17use Data::Dumper;
18use JSON;
19
20use Scalar::Util qw(weaken);
21
22use BarnOwl;
23use BarnOwl::Message::Facebook;
24
25our $app_id = 235537266461636; # for application 'barnowl'
26
27sub fail {
28    my $self = shift;
29    my $msg  = shift;
30    undef $self->{facebook};
31    die("[Facebook] Error: $msg\n");
32}
33
34sub new {
35    my $class = shift;
36    my $cfg = shift;
37
38    my $self = {
39        'cfg'  => $cfg,
40        'facebook' => undef,
41        'last_poll' => time - 60 * 60 * 24,
42        'last_message_poll' => time,
43        'timer' => undef,
44        'message_timer' => undef,
45        # yeah yeah, inelegant, I know.  You can try using
46        # $fb->authorize, but at time of writing (1.0300) they didn't support
47        # the response_type parameter.
48        # 'login_url' => 'https://www.facebook.com/dialog/oauth?client_id=235537266461636&scope=read_stream,read_mailbox,publish_stream,offline_access&redirect_uri=http://www.facebook.com/connect/login_success.html&response_type=token',
49        # minified to fit in most terminal windows.
50        'login_url' => 'http://goo.gl/yA42G',
51        'logged_in' => 0
52    };
53
54    bless($self, $class);
55
56    $self->{facebook} = Facebook::Graph->new( app_id => $app_id );
57    $self->facebook_do_auth;
58
59    return $self;
60}
61
62=head2 sleep N
63
64Stop polling Facebook for N seconds.
65
66=cut
67
68sub sleep {
69    my $self  = shift;
70    my $delay = shift;
71
72    # prevent reference cycles
73    my $weak = $self;
74    weaken($weak);
75
76    # Stop any existing timers.
77    if (defined $self->{timer}) {
78        $self->{timer}->stop;
79        $self->{timer} = undef;
80    }
81    if (defined $self->{message_timer}) {
82        # XXX doesn't do anything right now
83        $self->{message_timer}->stop;
84        $self->{message_timer} = undef;
85    }
86
87    $self->{timer} = BarnOwl::Timer->new({
88        name     => "Facebook poll",
89        after    => $delay,
90        interval => 90,
91        cb       => sub { $weak->poll_facebook if $weak }
92       });
93    # XXX implement message polling
94}
95
96sub die_on_error {
97    my $self = shift;
98    my $error = shift;
99
100    die "$error" if $error;
101}
102
103sub poll_facebook {
104    my $self = shift;
105
106    #return unless ( time - $self->{last_poll} ) >= 60;
107    return unless BarnOwl::getvar('facebook:poll') eq 'on';
108    return unless $self->{logged_in};
109
110    #BarnOwl::message("Polling Facebook...");
111
112    # blah blah blah
113
114    my $updates = eval {
115        $self->{facebook}
116             ->query
117             ->from("my_news")
118             # ->include_metadata()
119             # ->select_fields( ??? )
120             ->where_since( "@" . $self->{last_poll} )
121             ->request()
122             ->as_hashref()
123    };
124
125    $self->{last_poll} = time;
126    $self->die_on_error($@);
127
128    #warn Dumper($updates);
129
130    for my $post ( reverse @{$updates->{data}} ) {
131        # no app invites, thanks! (XXX make configurable)
132        if ($post->{type} eq 'link' && $post->{application}) {
133            next;
134        }
135        # XXX need to somehow access Facebook's user hiding mechanism...
136        # indexing is fragile
137        my $msg = BarnOwl::Message->new(
138            type      => 'Facebook',
139            sender    => $post->{from}{name},
140            sender_id => $post->{from}{id},
141            name      => $post->{to}{data}[0]{name} || $post->{from}{name},
142            name_id   => $post->{to}{data}[0]{id} || $post->{from}{id},
143            direction => 'in',
144            body      => $self->format_body($post),
145            postid    => $post->{id},
146            zsig      => $post->{actions}[0]{link},
147           );
148        BarnOwl::queue_message($msg);
149    }
150}
151
152sub format_body {
153    my $self = shift;
154
155    my $post = shift;
156
157    # XXX implement optional URL minification
158    if ($post->{type} eq 'status') {
159        return $post->{message};
160    } elsif ($post->{type} eq 'link' || $post->{type} eq 'video' || $post->{type} eq 'photo') {
161        return $post->{name}
162          . ($post->{caption} ? " (" . $post->{caption} . ")\n" : "\n")
163          . $post->{link}
164          . ($post->{description} ? "\n\n" . $post->{description} : "")
165          . ($post->{message} ? "\n\n" . $post->{message} : "");
166    } else {
167        return "(unknown post type " . $post->{type} . ")";
168    }
169}
170
171sub facebook {
172    my $self = shift;
173
174    my $msg = shift;
175    my $reply_to = shift;
176
177    if (!defined $self->{facebook} || !$self->{logged_in}) {
178        BarnOwl::admin_message('Facebook', 'You are not currently logged into Facebook.');
179        return;
180    }
181    $self->{facebook}->add_post->set_message( $msg )->publish;
182    $self->poll_facebook;
183}
184
185sub facebook_comment {
186    my $self = shift;
187
188    my $postid = shift;
189    my $msg = shift;
190
191    $self->{facebook}->add_comment( $postid )->set_message( $msg )->publish;
192}
193
194sub facebook_auth {
195    my $self = shift;
196
197    my $url = shift;
198    # http://www.facebook.com/connect/login_success.html#access_token=TOKEN&expires_in=0
199    $url =~ /access_token=([^&]+)/; # XXX Ew regex
200
201    $self->{cfg}->{token} = $1;
202    if ($self->facebook_do_auth) {
203        my $raw_cfg = to_json($self->{cfg});
204        BarnOwl::admin_message('Facebook', "Add this as the contents of your ~/.owl/facebook file:\n$raw_cfg");
205    }
206}
207
208sub facebook_do_auth {
209    my $self = shift;
210    if ( ! defined $self->{cfg}->{token} ) {
211        BarnOwl::admin_message('Facebook', "Login to Facebook at ".$self->{login_url}
212            . "\nand run command ':facebook-auth URL' with the URL you are redirected to.");
213        return 0;
214    }
215    $self->{facebook}->access_token($self->{cfg}->{token});
216    # Do a quick check to see if things are working
217    my $result = eval { $self->{facebook}->fetch('me'); };
218    if ($@) {
219        BarnOwl::admin_message('Facebook', "Failed to authenticate! Login to Facebook at ".$self->{login_url}
220            . "\nand run command ':facebook-auth URL' with the URL you are redirected to.");
221        return 0;
222    } else {
223        my $name = $result->{'name'};
224        BarnOwl::admin_message('Facebook', "Successfully logged in to Facebook as $name!");
225        $self->{logged_in} = 1;
226        $self->sleep(0); # start polling
227        return 1;
228    }
229}
230
2311;
Note: See TracBrowser for help on using the repository browser.