source: lib/BarnOwl/Module/Twitter.pm @ 4ae10de

release-1.7release-1.8release-1.9
Last change on this file since 4ae10de was 4ae10de, checked in by Nelson Elhage <nelhage@mit.edu>, 12 years ago
Fix behavior when live-upgraded from a non-timer Twitter.par
  • Property mode set to 100644
File size: 9.9 KB
Line 
1use warnings;
2use strict;
3
4=head1 NAME
5
6BarnOwl::Module::Twitter
7
8=head1 DESCRIPTION
9
10Post outgoing zephyrs from -c $USER -i status -O TWITTER to Twitter
11
12=cut
13
14package BarnOwl::Module::Twitter;
15
16our $VERSION = 0.2;
17
18use Net::Twitter;
19use JSON;
20use List::Util qw(first);
21
22use BarnOwl;
23use BarnOwl::Hooks;
24use BarnOwl::Module::Twitter::Handle;
25
26our @twitter_handles = ();
27our $default_handle = undef;
28my $class    = $ENV{USER};
29my $instance = "status";
30my $opcode   = "twitter";
31my $use_reply_to = 0;
32my $next_service_to_poll = 0;
33
34my $desc = <<'END_DESC';
35BarnOwl::Module::Twitter will watch for authentic zephyrs to
36-c $twitter:class -i $twitter:instance -O $twitter:opcode
37from your sender and mirror them to Twitter.
38
39A value of '*' in any of these fields acts a wildcard, accepting
40messages with any value of that field.
41END_DESC
42BarnOwl::new_variable_string(
43    'twitter:class',
44    {
45        default     => $class,
46        summary     => 'Class to watch for Twitter messages',
47        description => $desc
48    }
49);
50BarnOwl::new_variable_string(
51    'twitter:instance',
52    {
53        default => $instance,
54        summary => 'Instance on twitter:class to watch for Twitter messages.',
55        description => $desc
56    }
57);
58BarnOwl::new_variable_string(
59    'twitter:opcode',
60    {
61        default => $opcode,
62        summary => 'Opcode for zephyrs that will be sent as twitter updates',
63        description => $desc
64    }
65);
66
67BarnOwl::new_variable_bool(
68    'twitter:poll',
69    {
70        default => 1,
71        summary => 'Poll Twitter for incoming messages',
72        description => "If set, will poll Twitter every minute for normal updates,\n"
73        . 'and every two minutes for direct message'
74     }
75 );
76
77sub fail {
78    my $msg = shift;
79    undef @twitter_handles;
80    BarnOwl::admin_message('Twitter Error', $msg);
81    die("Twitter Error: $msg\n");
82}
83
84my $conffile = BarnOwl::get_config_dir() . "/twitter";
85open(my $fh, "<", "$conffile") || fail("Unable to read $conffile");
86my $raw_cfg = do {local $/; <$fh>};
87close($fh);
88eval {
89    $raw_cfg = from_json($raw_cfg);
90};
91if($@) {
92    fail("Unable to parse $conffile: $@");
93}
94
95$raw_cfg = [$raw_cfg] unless UNIVERSAL::isa $raw_cfg, "ARRAY";
96
97# Perform some sanity checking on the configuration.
98{
99    my %nicks;
100    my $default = 0;
101
102    for my $cfg (@$raw_cfg) {
103        if(! exists $cfg->{user}) {
104            fail("Account has no username set.");
105        }
106        my $user = $cfg->{user};
107        if(! exists $cfg->{password}) {
108            fail("Account $user has no password set.");
109        }
110        if(@$raw_cfg > 1&&
111           !exists($cfg->{account_nickname}) ) {
112            fail("Account $user has no account_nickname set.");
113        }
114        if($cfg->{account_nickname}) {
115            if($nicks{$cfg->{account_nickname}}++) {
116                fail("Nickname " . $cfg->{account_nickname} . " specified more than once.");
117            }
118        }
119        if($cfg->{default} || $cfg->{default_sender}) {
120            if($default++) {
121                fail("Multiple accounts marked as 'default'.");
122            }
123        }
124    }
125}
126
127# If there is only a single account, make publish_tweets default to
128# true.
129if (scalar @$raw_cfg == 1 && !exists($raw_cfg->[0]{publish_tweets})) {
130    $raw_cfg->[0]{publish_tweets} = 1;
131}
132
133for my $cfg (@$raw_cfg) {
134    my $twitter_args = { username   => $cfg->{user},
135                        password   => $cfg->{password},
136                        source     => 'barnowl', 
137                    };
138    if (defined $cfg->{service}) {
139        my $service = $cfg->{service};
140        $twitter_args->{apiurl} = $service;
141        my $apihost = $service;
142        $apihost =~ s/^\s*http:\/\///;
143        $apihost =~ s/\/.*$//;
144        $apihost .= ':80' unless $apihost =~ /:\d+$/;
145        $twitter_args->{apihost} = $cfg->{apihost} || $apihost;
146        my $apirealm = "Laconica API";
147        $twitter_args->{apirealm} = $cfg->{apirealm} || $apirealm;
148    } else {
149        $cfg->{service} = 'http://twitter.com';
150    }
151
152    my $twitter_handle;
153    eval {
154         $twitter_handle = BarnOwl::Module::Twitter::Handle->new($cfg, %$twitter_args);
155    };
156    if ($@) {
157        BarnOwl::error($@);
158        next;
159    }
160    push @twitter_handles, $twitter_handle;
161}
162
163$default_handle = first {$_->{cfg}->{default}} @twitter_handles;
164if (!$default_handle && @twitter_handles) {
165    $default_handle = $twitter_handles[0];
166}
167
168sub match {
169    my $val = shift;
170    my $pat = shift;
171    return $pat eq "*" || ($val eq $pat);
172}
173
174sub handle_message {
175    my $m = shift;
176    ($class, $instance, $opcode) = map{BarnOwl::getvar("twitter:$_")} qw(class instance opcode);
177    if($m->type eq 'zephyr'
178       && $m->sender eq BarnOwl::zephyr_getsender()
179       && match($m->class, $class)
180       && match($m->instance, $instance)
181       && match($m->opcode, $opcode)
182       && $m->auth eq 'YES') {
183        for my $handle (@twitter_handles) {
184            $handle->twitter($m->body) if $handle->{cfg}->{publish_tweets};
185        }
186    }
187}
188
189sub poll_messages {
190    # If we are reloaded into a barnowl with the old
191    # BarnOwl::Module::Twitter loaded, it still has a main loop hook
192    # that will call this function every second. If we just delete it,
193    # it will get the old version, which will call poll on each of our
194    # handles every second. However, they no longer include the time
195    # check, and so we will poll a handle every second until
196    # ratelimited.
197
198    # So we include an empty function here.
199}
200
201sub find_account {
202    my $name = shift;
203    my $handle = first {$_->{cfg}->{account_nickname} eq $name} @twitter_handles;
204    if ($handle) {
205        return $handle;
206    } else {
207        die("No such Twitter account: $name\n");
208    }
209}
210
211sub find_account_default {
212    my $name = shift;
213    if(defined($name)) {
214        return find_account($name);
215    } else {
216        return $default_handle;
217    }
218}
219
220sub twitter {
221    my $account = shift;
222
223    my $sent = 0;
224    if (defined $account) {
225        my $handle = find_account($account);
226        $handle->twitter(@_);
227    } 
228    else {
229        # broadcast
230        for my $handle (@twitter_handles) {
231            $handle->twitter(@_) if $handle->{cfg}->{publish_tweets};
232        }
233    }
234}
235
236BarnOwl::new_command(twitter => \&cmd_twitter, {
237    summary     => 'Update Twitter from BarnOwl',
238    usage       => 'twitter [ACCOUNT] [MESSAGE]',
239    description => 'Update Twitter on ACCOUNT. If MESSAGE is provided, use it as your status.'
240    . "\nIf no ACCOUNT is provided, update all services which have publishing enabled."
241    . "\nOtherwise, prompt for a status message to use."
242   });
243
244BarnOwl::new_command('twitter-direct' => \&cmd_twitter_direct, {
245    summary     => 'Send a Twitter direct message',
246    usage       => 'twitter-direct USER [ACCOUNT]',
247    description => 'Send a Twitter Direct Message to USER on ACCOUNT (defaults to default_sender,'
248    . "\nor first service if no default is provided)"
249   });
250
251BarnOwl::new_command( 'twitter-atreply' => sub { cmd_twitter_atreply(@_); },
252    {
253    summary     => 'Send a Twitter @ message',
254    usage       => 'twitter-atreply USER [ACCOUNT]',
255    description => 'Send a Twitter @reply Message to USER on ACCOUNT (defaults to default_sender,' 
256    . "\nor first service if no default is provided)"
257    }
258);
259
260BarnOwl::new_command( 'twitter-retweet' => sub { cmd_twitter_retweet(@_) },
261    {
262    summary     => 'Retweet the current Twitter message',
263    usage       => 'twitter-retweet [ACCOUNT]',
264    description => <<END_DESCRIPTION
265Retweet the current Twitter message using ACCOUNT (defaults to the
266account that received the tweet).
267END_DESCRIPTION
268    }
269);
270
271BarnOwl::new_command( 'twitter-follow' => sub { cmd_twitter_follow(@_); },
272    {
273    summary     => 'Follow a user on Twitter',
274    usage       => 'twitter-follow USER [ACCOUNT]',
275    description => 'Follow USER on Twitter ACCOUNT (defaults to default_sender, or first service'
276    . "\nif no default is provided)"
277    }
278);
279
280BarnOwl::new_command( 'twitter-unfollow' => sub { cmd_twitter_unfollow(@_); },
281    {
282    summary     => 'Stop following a user on Twitter',
283    usage       => 'twitter-unfollow USER [ACCOUNT]',
284    description => 'Stop following USER on Twitter ACCOUNT (defaults to default_sender, or first'
285    . "\nservice if no default is provided)"
286    }
287);
288
289sub cmd_twitter {
290    my $cmd = shift;
291    my $account = shift;
292    if (defined $account) {
293        if(@_) {
294            my $status = join(" ", @_);
295            twitter($account, $status);
296            return;
297        }
298    }
299    BarnOwl::start_edit_win("What's happening?" . (defined $account ? " ($account)" : ""), sub{twitter($account, shift)});
300}
301
302sub cmd_twitter_direct {
303    my $cmd = shift;
304    my $user = shift;
305    die("Usage: $cmd USER\n") unless $user;
306    my $account = find_account_default(shift);
307    BarnOwl::start_edit_win("$cmd $user " . ($account->nickname||""),
308                            sub { $account->twitter_direct($user, shift) });
309}
310
311sub cmd_twitter_atreply {
312    my $cmd  = shift;
313    my $user = shift || die("Usage: $cmd USER [In-Reply-To ID]\n");
314    my $id   = shift;
315    my $account = find_account_default(shift);
316
317    BarnOwl::start_edit_win("Reply to \@" . $user . ($account->nickname ? (" on " . $account->nickname) : ""),
318                            sub { $account->twitter_atreply($user, $id, shift) });
319}
320
321sub cmd_twitter_retweet {
322    my $cmd = shift;
323    my $account = shift;
324    my $m = BarnOwl::getcurmsg();
325    if(!$m || $m->type ne 'Twitter') {
326        die("$cmd must be used with a Twitter message selected.\n");
327    }
328
329    $account = $m->account unless defined($account);
330    find_account($account)->twitter_retweet($m);
331}
332
333sub cmd_twitter_follow {
334    my $cmd = shift;
335    my $user = shift;
336    die("Usage: $cmd USER\n") unless $user;
337    my $account = shift;
338    find_account_default($account)->twitter_follow($user);
339}
340
341sub cmd_twitter_unfollow {
342    my $cmd = shift;
343    my $user = shift;
344    die("Usage: $cmd USER\n") unless $user;
345    my $account = shift;
346    find_account_default($account)->twitter_unfollow($user);
347}
348
349BarnOwl::filter(qw{twitter type ^twitter$});
350
3511;
Note: See TracBrowser for help on using the repository browser.