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

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