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

release-1.10release-1.9
Last change on this file since 44f585c was 44f585c, checked in by Edward Z. Yang <ezyang@mit.edu>, 13 years ago
Add alternate implementation of keywords. Signed-off-by: Edward Z. Yang <ezyang@mit.edu>
  • Property mode set to 100644
File size: 10.7 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 die_on_error {
147    my $self = shift;
148    my $error = shift;
149
150    die "$error" if $error;
151}
152
153sub poll_facebook {
154    my $self = shift;
155
156    #return unless ( time - $self->{last_poll} ) >= 60;
157    return unless BarnOwl::getvar('facebook:poll') eq 'on';
158    return unless $self->{logged_in};
159
160    #BarnOwl::message("Polling Facebook...");
161
162    # XXX Oh no! This blocks the user interface.  Not good.
163    # Ideally, we should have some worker thread for polling facebook.
164    # But BarnOwl is probably not thread-safe >_<
165
166    my $old_topics = $self->{topics};
167    $self->{topics} = {};
168
169    my $updates = eval {
170        $self->{facebook}
171             ->query
172             ->from("my_news")
173             # Not using this, because we want to pick up comment
174             # updates. We need to manually de-dup, though.
175             # ->where_since( "@" . $self->{last_poll} )
176             ->limit_results( 200 )
177             ->request()
178             ->as_hashref()
179    };
180    $self->die_on_error($@);
181
182    my $new_last_poll = $self->{last_poll};
183    for my $post ( reverse @{$updates->{data}} ) {
184        # No app invites, thanks! (XXX make configurable)
185        if ($post->{type} eq 'link' && $post->{application}) {
186            next;
187        }
188
189        # XXX Need to somehow access Facebook's user hiding
190        # mechanism
191
192        # There can be multiple recipients! Strange! Pick the first one.
193        my $name    = $post->{to}{data}[0]{name} || $post->{from}{name};
194        my $name_id = $post->{to}{data}[0]{id} || $post->{from}{id};
195        my $post_id  = $post->{id};
196
197        # Only handle post if it's new
198        my $created_time = str2time($post->{created_time});
199        if ($created_time >= $self->{last_poll}) {
200            my @keywords = keywords($post->{name} || $post->{message});
201            my $topic = $keywords[0] || 'personal';
202            $self->{topics}->{$post_id} = $topic;
203            # XXX indexing is fragile
204            my $msg = BarnOwl::Message->new(
205                type      => 'Facebook',
206                sender    => $post->{from}{name},
207                sender_id => $post->{from}{id},
208                name      => $name,
209                name_id   => $name_id,
210                direction => 'in',
211                body      => $self->format_body($post),
212                post_id    => $post_id,
213                topic     => $topic,
214                time      => asctime(localtime $created_time),
215                # XXX The intent is to get the 'Comment' link, which also
216                # serves as a canonical link to the post.  The {name}
217                # field should equal 'Comment'.
218                zsig      => $post->{actions}[0]{link},
219               );
220            BarnOwl::queue_message($msg);
221        } else {
222            $self->{topics}->{$post_id} = $old_topics->{$post_id} || 'personal';
223        }
224
225        # This will have funky interleaving of times (they'll all be
226        # sorted linearly), but since we don't expect too many updates between
227        # polls this is pretty acceptable.
228        my $updated_time = str2time($post->{updated_time});
229        if ($updated_time >= $self->{last_poll} && defined $post->{comments}{data}) {
230            for my $comment ( @{$post->{comments}{data}} ) {
231                my $comment_time = str2time($comment->{created_time});
232                if ($comment_time < $self->{last_poll}) {
233                    next;
234                }
235                my $msg = BarnOwl::Message->new(
236                    type      => 'Facebook',
237                    sender    => $comment->{from}{name},
238                    sender_id => $comment->{from}{id},
239                    name      => $name,
240                    name_id   => $name_id,
241                    direction => 'in',
242                    body      => $comment->{message},
243                    post_id    => $post_id,
244                    topic     => $self->get_topic($post_id),
245                    time      => asctime(localtime $comment_time),
246                   );
247                BarnOwl::queue_message($msg);
248            }
249        }
250        if ($updated_time + 1 > $new_last_poll) {
251            $new_last_poll = $updated_time + 1;
252        }
253    }
254    # old_topics gets GC'd
255
256    $self->{last_poll} = $new_last_poll;
257}
258
259sub format_body {
260    my $self = shift;
261
262    my $post = shift;
263
264    # XXX implement optional URL minification
265    if ($post->{type} eq 'status') {
266        return $post->{message};
267    } elsif ($post->{type} eq 'link' || $post->{type} eq 'video' || $post->{type} eq 'photo') {
268        return $post->{name}
269          . ($post->{caption} ? " (" . $post->{caption} . ")\n" : "\n")
270          . $post->{link}
271          . ($post->{description} ? "\n\n" . $post->{description} : "")
272          . ($post->{message} ? "\n\n" . $post->{message} : "");
273    } else {
274        return "(unknown post type " . $post->{type} . ")";
275    }
276}
277
278sub facebook {
279    my $self = shift;
280
281    my $msg = shift;
282    my $reply_to = shift;
283
284    if (!defined $self->{facebook} || !$self->{logged_in}) {
285        BarnOwl::admin_message('Facebook', 'You are not currently logged into Facebook.');
286        return;
287    }
288    $self->{facebook}->add_post->set_message( $msg )->publish;
289    $self->sleep(0);
290}
291
292sub facebook_comment {
293    my $self = shift;
294
295    my $post_id = shift;
296    my $msg = shift;
297
298    $self->{facebook}->add_comment( $post_id )->set_message( $msg )->publish;
299    $self->sleep(0);
300}
301
302sub facebook_auth {
303    my $self = shift;
304
305    my $url = shift;
306    # http://www.facebook.com/connect/login_success.html#access_token=TOKEN&expires_in=0
307    $url =~ /access_token=([^&]+)/; # XXX Ew regex
308
309    $self->{cfg}->{token} = $1;
310    if ($self->facebook_do_auth) {
311        my $raw_cfg = to_json($self->{cfg});
312        BarnOwl::admin_message('Facebook', "Add this as the contents of your ~/.owl/facebook file:\n$raw_cfg");
313    }
314}
315
316sub facebook_do_auth {
317    my $self = shift;
318    if ( ! defined $self->{cfg}->{token} ) {
319        BarnOwl::admin_message('Facebook', "Login to Facebook at ".$self->{login_url}
320            . "\nand run command ':facebook-auth URL' with the URL you are redirected to.");
321        return 0;
322    }
323    $self->{facebook}->access_token($self->{cfg}->{token});
324    # Do a quick check to see if things are working
325    my $result = eval { $self->{facebook}->fetch('me'); };
326    if ($@) {
327        BarnOwl::admin_message('Facebook', "Failed to authenticate! Login to Facebook at ".$self->{login_url}
328            . "\nand run command ':facebook-auth URL' with the URL you are redirected to.");
329        return 0;
330    } else {
331        my $name = $result->{'name'};
332        BarnOwl::admin_message('Facebook', "Successfully logged in to Facebook as $name!");
333        $self->{logged_in} = 1;
334        $self->sleep(0); # start polling
335        return 1;
336    }
337}
338
339sub get_topic {
340    my $self = shift;
341
342    my $post_id = shift;
343
344    return $self->{topics}->{$post_id} || 'personal';
345}
346
3471;
Note: See TracBrowser for help on using the repository browser.