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

Last change on this file since c323405 was c323405, checked in by Edward Z. Yang <ezyang@mit.edu>, 13 years ago
Comment reading support and back-timing. Signed-off-by: Edward Z. Yang <ezyang@mit.edu>
  • Property mode set to 100644
File size: 9.6 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;
19use Date::Parse;
20use POSIX;
21
22use Scalar::Util qw(weaken);
23
24use BarnOwl;
25use BarnOwl::Message::Facebook;
26
27our $app_id = 235537266461636; # for application 'barnowl'
28
29# Unfortunately, Facebook does not offer a comment stream, in the same
30# way we can get a post stream using the news feed.  This makes it a bit
31# difficult to de-duplicate comments we have already seen.  We use a
32# simple heuristic to fix this: we check if the comment's time is dated
33# from before our last update, and don't re-post if it's dated before.
34# Be somewhat forgiving, since it's better to duplicate a post than to
35# drop one.  Furthermore, we must use Facebook's idea of time, since the
36# server BarnOwl is running on may be desynchronized.  So we need to
37# utilize Facebook's idea of time, not ours.  We do this by looking at
38# all of the timestamps we see while processing an update, and take the
39# latest one and increment it by one second.
40#
41# What properties do we get with this setup?
42#
43#   - We get comment updates only for the latest N posts on a news feed.
44#   Any later ones, you have to use Facebook's usual mechanisms (e.g.
45#   email notifications).
46#
47#   - Processing a poll is relatively expensive, since we have to
48#   iterate over N new posts.  It might be worthwhile polling for new
49#   comments less frequently than polling for new posts.
50
51sub fail {
52    my $self = shift;
53    my $msg  = shift;
54    undef $self->{facebook};
55    die("[Facebook] Error: $msg\n");
56}
57
58sub new {
59    my $class = shift;
60    my $cfg = shift;
61
62    my $self = {
63        'cfg'  => $cfg,
64        'facebook' => undef,
65
66        # Initialized with our 'time', but will be synced to Facebook
67        # soon enough.
68        'last_poll' => time - 60 * 60 * 24 * 2,
69        'timer' => undef,
70
71        # Message polling not implemented yet
72        #'last_message_poll' => time,
73        #'message_timer' => undef,
74
75        # yeah yeah, inelegant, I know.  You can try using
76        # $fb->authorize, but at time of writing (1.0300) they didn't support
77        # the response_type parameter.
78        # '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',
79        # minified to fit in most terminal windows.
80        'login_url' => 'http://goo.gl/yA42G',
81
82        'logged_in' => 0
83    };
84
85    bless($self, $class);
86
87    $self->{facebook} = Facebook::Graph->new( app_id => $app_id );
88    $self->facebook_do_auth;
89
90    return $self;
91}
92
93=head2 sleep N
94
95Stop polling Facebook for N seconds.
96
97=cut
98
99sub sleep {
100    my $self  = shift;
101    my $delay = shift;
102
103    # prevent reference cycles
104    my $weak = $self;
105    weaken($weak);
106
107    # Stop any existing timers.
108    if (defined $self->{timer}) {
109        $self->{timer}->stop;
110        $self->{timer} = undef;
111    }
112    if (defined $self->{message_timer}) {
113        # XXX doesn't do anything right now
114        $self->{message_timer}->stop;
115        $self->{message_timer} = undef;
116    }
117
118    $self->{timer} = BarnOwl::Timer->new({
119        name     => "Facebook poll",
120        after    => $delay,
121        interval => 90,
122        cb       => sub { $weak->poll_facebook if $weak }
123       });
124    # XXX implement message polling
125}
126
127sub die_on_error {
128    my $self = shift;
129    my $error = shift;
130
131    die "$error" if $error;
132}
133
134sub poll_facebook {
135    my $self = shift;
136
137    #return unless ( time - $self->{last_poll} ) >= 60;
138    return unless BarnOwl::getvar('facebook:poll') eq 'on';
139    return unless $self->{logged_in};
140
141    #BarnOwl::message("Polling Facebook...");
142
143    # XXX Oh no! This blocks the user interface.  Not good.
144    # Ideally, we should have some worker thread for polling facebook.
145    # But BarnOwl is probably not thread-safe >_<
146
147    my $updates = eval {
148        $self->{facebook}
149             ->query
150             ->from("my_news")
151             # Not using this, because we want to pick up comment
152             # updates. We need to manually de-dup, though.
153             # ->where_since( "@" . $self->{last_poll} )
154             ->limit_results( 200 )
155             ->request()
156             ->as_hashref()
157    };
158    $self->die_on_error($@);
159
160    #warn Dumper($updates);
161
162    my $new_last_poll = $self->{last_poll};
163    for my $post ( reverse @{$updates->{data}} ) {
164        # No app invites, thanks! (XXX make configurable)
165        if ($post->{type} eq 'link' && $post->{application}) {
166            next;
167        }
168
169        # XXX Need to somehow access Facebook's user hiding
170        # mechanism
171
172        # There can be multiple recipients! Strange! Pick the first one.
173        my $name    = $post->{to}{data}[0]{name} || $post->{from}{name};
174        my $name_id = $post->{to}{data}[0]{id} || $post->{from}{id};
175
176        # Only handle post if it's new
177        my $created_time = str2time($post->{created_time});
178        if ($created_time >= $self->{last_poll}) {
179            # XXX indexing is fragile
180            my $msg = BarnOwl::Message->new(
181                type      => 'Facebook',
182                sender    => $post->{from}{name},
183                sender_id => $post->{from}{id},
184                name      => $name,
185                name_id   => $name_id,
186                direction => 'in',
187                body      => $self->format_body($post),
188                postid    => $post->{id},
189                time      => asctime(localtime $created_time),
190                # XXX The intent is to get the 'Comment' link, which also
191                # serves as a canonical link to the post.  The {name}
192                # field should equal 'Comment'.
193                zsig      => $post->{actions}[0]{link},
194               );
195            BarnOwl::queue_message($msg);
196        }
197
198        # This will have funky interleaving of times (they'll all be
199        # sorted linearly), but since we don't expect too many updates between
200        # polls this is pretty acceptable.
201        my $updated_time = str2time($post->{updated_time});
202        if ($updated_time >= $self->{last_poll} && defined $post->{comments}{data}) {
203            for my $comment ( @{$post->{comments}{data}} ) {
204                my $comment_time = str2time($comment->{created_time});
205                if ($comment_time < $self->{last_poll}) {
206                    next;
207                }
208                my $msg = BarnOwl::Message->new(
209                    type      => 'Facebook',
210                    sender    => $comment->{from}{name},
211                    sender_id => $comment->{from}{id},
212                    name      => $name,
213                    name_id   => $name_id,
214                    direction => 'in',
215                    body      => $comment->{message},
216                    postid    => $post->{id},
217                    time      => asctime(localtime $comment_time),
218                   );
219                BarnOwl::queue_message($msg);
220            }
221        }
222        if ($updated_time + 1 > $new_last_poll) {
223            $new_last_poll = $updated_time + 1;
224        }
225    }
226
227    $self->{last_poll} = $new_last_poll;
228}
229
230sub format_body {
231    my $self = shift;
232
233    my $post = shift;
234
235    # XXX implement optional URL minification
236    if ($post->{type} eq 'status') {
237        return $post->{message};
238    } elsif ($post->{type} eq 'link' || $post->{type} eq 'video' || $post->{type} eq 'photo') {
239        return $post->{name}
240          . ($post->{caption} ? " (" . $post->{caption} . ")\n" : "\n")
241          . $post->{link}
242          . ($post->{description} ? "\n\n" . $post->{description} : "")
243          . ($post->{message} ? "\n\n" . $post->{message} : "");
244    } else {
245        return "(unknown post type " . $post->{type} . ")";
246    }
247}
248
249sub facebook {
250    my $self = shift;
251
252    my $msg = shift;
253    my $reply_to = shift;
254
255    if (!defined $self->{facebook} || !$self->{logged_in}) {
256        BarnOwl::admin_message('Facebook', 'You are not currently logged into Facebook.');
257        return;
258    }
259    $self->{facebook}->add_post->set_message( $msg )->publish;
260    $self->poll_facebook;
261}
262
263sub facebook_comment {
264    my $self = shift;
265
266    my $postid = shift;
267    my $msg = shift;
268
269    $self->{facebook}->add_comment( $postid )->set_message( $msg )->publish;
270}
271
272sub facebook_auth {
273    my $self = shift;
274
275    my $url = shift;
276    # http://www.facebook.com/connect/login_success.html#access_token=TOKEN&expires_in=0
277    $url =~ /access_token=([^&]+)/; # XXX Ew regex
278
279    $self->{cfg}->{token} = $1;
280    if ($self->facebook_do_auth) {
281        my $raw_cfg = to_json($self->{cfg});
282        BarnOwl::admin_message('Facebook', "Add this as the contents of your ~/.owl/facebook file:\n$raw_cfg");
283    }
284}
285
286sub facebook_do_auth {
287    my $self = shift;
288    if ( ! defined $self->{cfg}->{token} ) {
289        BarnOwl::admin_message('Facebook', "Login to Facebook at ".$self->{login_url}
290            . "\nand run command ':facebook-auth URL' with the URL you are redirected to.");
291        return 0;
292    }
293    $self->{facebook}->access_token($self->{cfg}->{token});
294    # Do a quick check to see if things are working
295    my $result = eval { $self->{facebook}->fetch('me'); };
296    if ($@) {
297        BarnOwl::admin_message('Facebook', "Failed to authenticate! Login to Facebook at ".$self->{login_url}
298            . "\nand run command ':facebook-auth URL' with the URL you are redirected to.");
299        return 0;
300    } else {
301        my $name = $result->{'name'};
302        BarnOwl::admin_message('Facebook', "Successfully logged in to Facebook as $name!");
303        $self->{logged_in} = 1;
304        $self->sleep(0); # start polling
305        return 1;
306    }
307}
308
3091;
Note: See TracBrowser for help on using the repository browser.