0c433cd687527540918a1eaa86f1bfc8dbc61ebd
[twirssi-net-twitter-lite.git] / twirssi.pl
1 use strict;
2 use Irssi;
3 use Irssi::Irc;
4 use HTTP::Date;
5 use HTML::Entities;
6 use File::Temp;
7 use LWP::Simple;
8 use Data::Dumper;
9 use Encode;
10 use POSIX qw/:sys_wait_h/;
11 use Net::Twitter qw/3.05/;
12 $Data::Dumper::Indent = 1;
13
14 use vars qw($VERSION %IRSSI);
15
16 $VERSION = "2.4.1beta";
17 %IRSSI   = (
18     authors     => 'Dan Boger',
19     contact     => 'zigdon@gmail.com',
20     name        => 'twirssi',
21     description => 'Send twitter updates using /tweet.  '
22       . 'Can optionally set your bitlbee /away message to same',
23     license => 'GNU GPL v2',
24     url     => 'http://twirssi.com',
25     changed => 'Fri Jan 22 14:40:48 PST 2010',
26 );
27
28 my $window;
29 my $twit;
30 my %twits;
31 my %oauth;
32 my $user;
33 my $defservice;
34 my $poll;
35 my $last_poll;
36 my $last_friends_poll = 0;
37 my %nicks;
38 my %friends;
39 my %tweet_cache;
40 my %id_map;
41 my $failwhale  = 0;
42 my $first_call = 1;
43 my $child_pid;
44 my %fix_replies_index;
45
46 my %irssi_to_mirc_colors = (
47     '%k' => '01',
48     '%r' => '05',
49     '%g' => '03',
50     '%y' => '07',
51     '%b' => '02',
52     '%m' => '06',
53     '%c' => '10',
54     '%w' => '15',
55     '%K' => '14',
56     '%R' => '04',
57     '%G' => '09',
58     '%Y' => '08',
59     '%B' => '12',
60     '%M' => '13',
61     '%C' => '11',
62     '%W' => '00',
63 );
64
65 sub cmd_direct {
66     my ( $data, $server, $win ) = @_;
67
68     return unless &logged_in($twit);
69
70     my ( $target, $text ) = split ' ', $data, 2;
71     unless ( $target and $text ) {
72         &notice("Usage: /dm <nick> <message>");
73         return;
74     }
75
76     &cmd_direct_as( "$user $data", $server, $win );
77 }
78
79 sub cmd_direct_as {
80     my ( $data, $server, $win ) = @_;
81
82     return unless &logged_in($twit);
83
84     my ( $username, $target, $text ) = split ' ', $data, 3;
85     unless ( $username and $target and $text ) {
86         &notice("Usage: /dm_as <username> <nick> <message>");
87         return;
88     }
89
90     return unless $username = &valid_username($username);
91
92     eval {
93         if ( $twits{$username}
94             ->new_direct_message( { user => $target, text => $text } ) )
95         {
96             &notice("DM sent to $target: $text");
97             $nicks{$target} = time;
98         } else {
99             my $error;
100             eval {
101                 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
102                 $error = $error->{error};
103             };
104             die $error if $error;
105             &notice("DM to $target failed");
106         }
107     };
108
109     if ($@) {
110         &notice("DM caused an error: $@");
111         return;
112     }
113 }
114
115 sub cmd_retweet {
116     my ( $data, $server, $win ) = @_;
117
118     return unless &logged_in($twit);
119
120     $data =~ s/^\s+|\s+$//;
121     unless ($data) {
122         &notice("Usage: /retweet <nick[:num]> [comment]");
123         return;
124     }
125
126     my ( $id, $data ) = split ' ', $data, 2;
127
128     &cmd_retweet_as( "$user $id $data", $server, $win );
129 }
130
131 sub cmd_retweet_as {
132     my ( $data, $server, $win ) = @_;
133
134     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
135         &notice("twirssi_track_replies is required in order to reteet.");
136         return;
137     }
138
139     return unless &logged_in($twit);
140
141     $data =~ s/^\s+|\s+$//;
142     my ( $username, $id, $data ) = split ' ', $data, 3;
143
144     unless ($username) {
145         &notice("Usage: /retweet_as <username> <nick[:num]> [comment]");
146         return;
147     }
148
149     return unless $username = &valid_username($username);
150
151     my $nick;
152     $id =~ s/[^\w\d\-:]+//g;
153     ( $nick, $id ) = split /:/, $id;
154     unless ( exists $id_map{ lc $nick } ) {
155         &notice("Can't find a tweet from $nick to retweet!");
156         return;
157     }
158
159     $id = $id_map{__indexes}{$nick} unless $id;
160     unless ( $id_map{ lc $nick }[$id] ) {
161         &notice("Can't find a tweet numbered $id from $nick to retweet!");
162         return;
163     }
164
165     unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
166         &notice("The text of this tweet isn't saved, sorry!");
167         return;
168     }
169
170 # Irssi::settings_add_str( "twirssi", "twirssi_retweet_format", 'RT $n: $t ${-- $c$}' );
171     my $text = Irssi::settings_get_str("twirssi_retweet_format");
172     $text =~ s/\$n/\@$nick/g;
173     if ($data) {
174         $text =~ s/\${|\$}//g;
175         $text =~ s/\$c/$data/;
176     } else {
177         $text =~ s/\${.*?\$}//;
178     }
179     $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
180
181     my $modified = $data;
182     $data = &shorten($text);
183
184     return if $modified and &too_long($data);
185
186     my $success = 1;
187     eval {
188         if ($modified)
189         {
190             $success = $twits{$username}->update(
191                 {
192                     status => $data,
193
194                     # in_reply_to_status_id => $id_map{ lc $nick }[$id]
195                 }
196             );
197         } else {
198             $success =
199               $twits{$username}->retweet( { id => $id_map{ lc $nick }[$id] } );
200             $success = $success->{id} if ref $success;
201         }
202         &notice("Update failed") unless $success;
203     };
204     return unless $success;
205
206     if ($@) {
207         &notice("Update caused an error: $@.  Aborted");
208         return;
209     }
210
211     foreach ( $data =~ /@([-\w]+)/ ) {
212         $nicks{$1} = time;
213     }
214
215     &notice("Retweet sent");
216 }
217
218 sub cmd_tweet {
219     my ( $data, $server, $win ) = @_;
220
221     return unless &logged_in($twit);
222
223     $data =~ s/^\s+|\s+$//;
224     unless ($data) {
225         &notice("Usage: /tweet <update>");
226         return;
227     }
228
229     &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
230 }
231
232 sub cmd_tweet_as {
233     my ( $data, $server, $win ) = @_;
234
235     return unless &logged_in($twit);
236
237     $data =~ s/^\s+|\s+$//;
238     $data =~ s/\s\s+/ /g;
239     my ( $username, $data ) = split ' ', $data, 2;
240
241     unless ( $username and $data ) {
242         &notice("Usage: /tweet_as <username> <update>");
243         return;
244     }
245
246     return unless $username = &valid_username($username);
247
248     $data = &shorten($data);
249
250     return if &too_long($data);
251
252     my $success = 1;
253     eval {
254         unless ( $twits{$username}->update($data) )
255         {
256             &notice("Update failed");
257             $success = 0;
258         }
259     };
260     return unless $success;
261
262     if ($@) {
263         &notice("Update caused an error: $@.  Aborted.");
264         return;
265     }
266
267     foreach ( $data =~ /@([-\w]+)/ ) {
268         $nicks{$1} = time;
269     }
270
271     my $away = &update_away($data);
272
273     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
274 }
275
276 sub cmd_reply {
277     my ( $data, $server, $win ) = @_;
278
279     return unless &logged_in($twit);
280
281     $data =~ s/^\s+|\s+$//;
282     unless ($data) {
283         &notice("Usage: /reply <nick[:num]> <update>");
284         return;
285     }
286
287     my ( $id, $data ) = split ' ', $data, 2;
288     unless ( $id and $data ) {
289         &notice("Usage: /reply <nick[:num]> <update>");
290         return;
291     }
292
293     &cmd_reply_as( "$user $id $data", $server, $win );
294 }
295
296 sub cmd_reply_as {
297     my ( $data, $server, $win ) = @_;
298
299     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
300         &notice("twirssi_track_replies is required in order to reply to "
301               . "specific tweets.  Either enable it, or just use /tweet "
302               . "\@username <text>." );
303         return;
304     }
305
306     return unless &logged_in($twit);
307
308     $data =~ s/^\s+|\s+$//;
309     my ( $username, $id, $data ) = split ' ', $data, 3;
310
311     unless ( $username and $data ) {
312         &notice("Usage: /reply_as <username> <nick[:num]> <update>");
313         return;
314     }
315
316     return unless $username = &valid_username($username);
317
318     my $nick;
319     $id =~ s/[^\w\d\-:]+//g;
320     ( $nick, $id ) = split /:/, $id;
321     unless ( exists $id_map{ lc $nick } ) {
322         &notice("Can't find a tweet from $nick to reply to!");
323         return;
324     }
325
326     $id = $id_map{__indexes}{$nick} unless $id;
327     unless ( $id_map{ lc $nick }[$id] ) {
328         &notice("Can't find a tweet numbered $id from $nick to reply to!");
329         return;
330     }
331
332     if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
333
334         # remove any @nick at the beginning of the reply, as we'll add it anyway
335         $data =~ s/^\s*\@?$nick\s*//;
336         $data = "\@$nick " . $data;
337     }
338
339     $data = &shorten($data);
340
341     return if &too_long($data);
342
343     my $success = 1;
344     eval {
345         unless (
346             $twits{$username}->update(
347                 {
348                     status                => $data,
349                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
350                 }
351             )
352           )
353         {
354             &notice("Update failed");
355             $success = 0;
356         }
357     };
358     return unless $success;
359
360     if ($@) {
361         &notice("Update caused an error: $@.  Aborted");
362         return;
363     }
364
365     foreach ( $data =~ /@([-\w]+)/ ) {
366         $nicks{$1} = time;
367     }
368
369     my $away = &update_away($data);
370
371     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
372 }
373
374 sub gen_cmd {
375     my ( $usage_str, $api_name, $post_ref ) = @_;
376
377     return sub {
378         my ( $data, $server, $win ) = @_;
379
380         return unless &logged_in($twit);
381
382         $data =~ s/^\s+|\s+$//;
383         unless ($data) {
384             &notice("Usage: $usage_str");
385             return;
386         }
387
388         my $success = 1;
389         eval {
390             unless ( $twit->$api_name($data) )
391             {
392                 &notice("$api_name failed");
393                 $success = 0;
394             }
395         };
396         return unless $success;
397
398         if ($@) {
399             &notice("$api_name caused an error.  Aborted.");
400             return;
401         }
402
403         &$post_ref($data) if $post_ref;
404       }
405 }
406
407 sub cmd_switch {
408     my ( $data, $server, $win ) = @_;
409
410     $data =~ s/^\s+|\s+$//g;
411     $data = &normalize_username($data);
412     if ( exists $twits{$data} ) {
413         &notice("Switching to $data");
414         $twit = $twits{$data};
415         if ( $data =~ /(.*)\@(.*)/ ) {
416             $user       = $1;
417             $defservice = $2;
418         } else {
419             &notice("Couldn't figure out what service '$data' is on");
420         }
421     } else {
422         &notice("Unknown user $data");
423     }
424 }
425
426 sub cmd_logout {
427     my ( $data, $server, $win ) = @_;
428
429     $data =~ s/^\s+|\s+$//g;
430     $data = $user unless $data;
431     return unless $data = &valid_username($data);
432
433     &notice("Logging out $data...");
434     eval {
435         $twits{$data}->end_session();
436     };
437     delete $twits{$data};
438     undef $twit;
439     if ( keys %twits ) {
440         &cmd_switch( ( keys %twits )[0], $server, $win );
441     } else {
442         Irssi::timeout_remove($poll) if $poll;
443         undef $poll;
444     }
445 }
446
447 sub cmd_login {
448     my ( $data, $server, $win ) = @_;
449     my $pass;
450     print "logging in: $data" if &debug;
451     if ($data) {
452         print "manual data login" if &debug;
453         ( $user, $pass ) = split ' ', $data, 2;
454         unless (Irssi::settings_get_bool("twirssi_use_oauth") or $pass) {
455             &notice("usage: /twitter_login <username>[\@<service>] <password>");
456             return;
457         }
458     } elsif ( Irssi::settings_get_bool("twirssi_use_oauth") and
459               my $autouser = Irssi::settings_get_str("twitter_usernames") ) {
460         print "oauth autouser login" if &debug;
461         foreach my $user (split /,/, $autouser) {
462             &cmd_login($user);
463         }
464         return;
465     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
466         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
467     {
468         print "autouser login" if &debug;
469         my @user = split /\s*,\s*/, $autouser;
470         my @pass = split /\s*,\s*/, $autopass;
471
472         # if a password ends with a '\', it was meant to escape the comma, and
473         # it should be concatinated with the next one
474         my @unescaped;
475         while (@pass) {
476             my $p = shift @pass;
477             while ( $p =~ /\\$/ and @pass ) {
478                 $p .= "," . shift @pass;
479             }
480             push @unescaped, $p;
481         }
482
483         if ( @user != @unescaped ) {
484             &notice("Number of usernames doesn't match "
485                   . "the number of passwords - auto-login failed" );
486         } else {
487             my ( $u, $p );
488             while ( @user and @unescaped ) {
489                 $u = shift @user;
490                 $p = shift @unescaped;
491                 &cmd_login("$u $p");
492             }
493             return;
494         }
495     } else {
496         &notice("/twitter_login requires either a username/password "
497               . "or twitter_usernames and twitter_passwords to be set. "
498               . "Note that if twirssi_use_oauth is true, passwords are "
499               . "not required");
500         return;
501     }
502
503     %friends = %nicks = ();
504
505     my $service;
506     if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
507         ( $user, $service ) = ( $1, $2 );
508     } else {
509         $service = Irssi::settings_get_str("twirssi_default_service");
510     }
511     $defservice = $service = ucfirst lc $service;
512
513     if ( $service eq 'Twitter' and
514          Irssi::settings_get_bool("twirssi_use_oauth") ) {
515         print "Attempting OAuth for $user\@$service" if &debug;
516         eval {
517             $twit = Net::Twitter->new(
518                 $service eq 'Identica' ? ( identica => 1 ) : (),
519                 traits       => [ 'API::REST', 'OAuth' ],
520                 consumer_key => 'BZVAvBma4GxdiRwXIvbnw',
521                 consumer_secret => '0T5kahwLyb34vciGZsgkA9lsjtGCQ05vxVE2APXM',
522                 source          => "twirssi",
523                 ssl => Irssi::settings_get_bool("twirssi_avoid_ssl") ? 0 : 1,
524             );
525         };
526
527         if ( $twit ) {
528             if (open( OAUTH, Irssi::settings_get_str("twirssi_oauth_store") ) ) {
529                 while (<OAUTH>) {
530                     chomp;
531                     next unless m/$user\@$service (\S+) (\S+)/i;
532                     print "Trying cached oauth creds for $user\@$service" if &debug;
533                     $twit->access_token($1);
534                     $twit->access_token_secret($2);
535                     last;
536                 }
537                 close OAUTH;
538             }
539
540             unless ( $twit->authorized ) {
541                 my $url;
542                 eval {
543                     $url = $twit->get_authorization_url;
544                 };
545
546                 if ($@) {
547                     &notice("ERROR: Failed to get OAuth authorization_url.  Try again later.");
548                     return;
549                 }
550
551                 &notice("Twirssi not autorized to access $service for $user.");
552                 &notice("Please authorize at the following url, then enter the pin ");
553                 &notice("supplied with /twirssi_oauth $user\@$service <pin>");
554                 &notice($url);
555
556                 $oauth{pending}{"$user\@$service"} = $twit;
557                 return;
558             }
559         }
560     } else { 
561         $twit = Net::Twitter->new(
562             $service eq 'Identica' ? ( identica => 1 ) : (),
563             username => $user,
564             password => $pass,
565             source   => "twirssi",
566             ssl      => Irssi::settings_get_bool("twirssi_avoid_ssl") ? 0 : 1,
567         );
568     }
569
570     unless ($twit) {
571         &notice("Failed to create object!  Aborting.");
572         return;
573     }
574
575     return &verify_twitter_object($server, $win, $user, $service, $twit);
576 }
577
578 sub cmd_oauth {
579     my ($data, $server, $win) = @_;
580     my ( $key, $pin ) = split ' ', $data;
581     my ($user, $service);
582     $key = &normalize_username($key);
583     if ( $key =~ /^(.*)@(Twitter|Identica)$/ ) {
584         ( $user, $service ) = ( $1, $2 );
585     }
586     $pin =~ s/\D//g;
587     print "Applying pin to $key" if &debug;
588
589     unless ( exists $oauth{pending}{$key} ) {
590         &notice("There isn't a pending oauth request for $key. "
591               . "Try /twitter_login first" );
592         return;
593     }
594
595     my $twit = $oauth{pending}{$key};
596     my ( $access_token, $access_token_secret );
597     eval {
598         ( $access_token, $access_token_secret ) =
599           $twit->request_access_token( verifier => $pin );
600     };
601
602     if ($@) {
603         &notice("Invalid pin, try again.");
604         return;
605     }
606
607     delete $oauth{pending}{$key};
608
609     my $store_file = Irssi::settings_get_str("twirssi_oauth_store");
610     if ($store_file) {
611         my @store;
612         if ( open( OAUTH, $store_file ) ) {
613             while (<OAUTH>) {
614                 chomp;
615                 next if /$key/i;
616                 push @store, $_;
617             }
618             close OAUTH;
619
620         }
621
622         push @store, "$key $access_token $access_token_secret";
623
624         if ( open( OAUTH, ">$store_file.new" ) ) {
625             print OAUTH "$_\n" foreach @store;
626             close OAUTH;
627             rename "$store_file.new", $store_file
628               or &notice("Failed to rename $store_file.new: $!");
629         } else {
630             &notice("Failed to write $store_file.new: $!");
631         }
632     } else {
633         &notice("No persistant storage set for OAuth.  "
634               . "Please /set twirssi_oauth_store to a writable filename." );
635     }
636
637     return &verify_twitter_object($server, $win, $user, $service, $twit);
638 }
639
640 sub verify_twitter_object {
641     my ($server, $win, $user, $service, $twit) = @_;
642
643     if ( my $timeout = Irssi::settings_get_int("twitter_timeout")
644         and $twit->can('ua') )
645     {
646         $twit->ua->timeout($timeout);
647         &notice("Twitter timeout set to $timeout");
648     }
649
650     unless ( $twit->verify_credentials() ) {
651         &notice("Login as $user\@$service failed");
652
653         if ( not Irssi::settings_get_bool("twirssi_avoid_ssl") ) {
654             &notice(
655                 "It's possible you're missing one of the modules required for "
656                   . "SSL logins.  Try setting twirssi_avoid_ssl to on.  See "
657                   . "http://cpansearch.perl.org/src/GAAS/libwww-perl-5.831/README.SSL "
658                   . "for the detailed requirements." );
659         }
660
661         $twit = undef;
662         if ( keys %twits ) {
663             &cmd_switch( ( keys %twits )[0], $server, $win );
664         }
665         return;
666     }
667
668     my $rate_limit = $twit->rate_limit_status();
669     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
670         &notice(
671             "Rate limit exceeded, try again after $rate_limit->{reset_time}" );
672         $twit = undef;
673         return;
674     }
675
676     print "saving object for $user\@$service" if &debug;
677     $twits{"$user\@$service"} = $twit;
678     Irssi::timeout_remove($poll) if $poll;
679     $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
680     &notice("Logged in as $user\@$service, loading friends list...");
681     &load_friends();
682     &notice( "loaded friends: ", scalar keys %friends );
683     if ( Irssi::settings_get_bool("twirssi_first_run") ) {
684         Irssi::settings_set_bool( "twirssi_first_run", 0 );
685     }
686     %nicks = %friends;
687     $nicks{$user} = 0;
688     return 1;
689 }
690
691 sub cmd_add_follow {
692     my ( $data, $server, $win ) = @_;
693
694     unless ($data) {
695         &notice("Usage: /twitter_add_follow_extra <username>");
696         return;
697     }
698
699     $data =~ s/^\s+|\s+$//;
700     $data =~ s/^\@//;
701     $data = lc $data;
702
703     if ( exists $id_map{__fixreplies}{"$user\@$defservice"}{$data} ) {
704         &notice("Already following all replies by \@$data");
705         return;
706     }
707
708     $id_map{__fixreplies}{"$user\@$defservice"}{$data} = 1;
709     &notice("Will now follow all replies by \@$data");
710 }
711
712 sub cmd_del_follow {
713     my ( $data, $server, $win ) = @_;
714
715     unless ($data) {
716         &notice("Usage: /twitter_del_follow_extra <username>");
717         return;
718     }
719
720     $data =~ s/^\s+|\s+$//;
721     $data =~ s/^\@//;
722     $data = lc $data;
723
724     unless ( exists $id_map{__fixreplies}{"$user\@$defservice"}{$data} ) {
725         &notice("Wasn't following all replies by \@$data");
726         return;
727     }
728
729     delete $id_map{__fixreplies}{"$user\@$defservice"}{$data};
730     &notice("Will no longer follow all replies by \@$data");
731 }
732
733 sub cmd_list_follow {
734     my ( $data, $server, $win ) = @_;
735
736     my $found = 0;
737     foreach my $suser ( sort keys %{ $id_map{__fixreplies} } ) {
738         my $frusers;
739         foreach my $fruser ( sort keys %{ $id_map{__fixreplies}{$suser} } ) {
740             $frusers = $frusers ? "$frusers, $fruser" : $fruser;
741         }
742         if ($frusers) {
743             $found = 1;
744             &notice("Following all replies as \@$suser: $frusers");
745         }
746     }
747
748     unless ($found) {
749         &notice("Not following all replies by anyone");
750     }
751 }
752
753 sub cmd_add_search {
754     my ( $data, $server, $win ) = @_;
755
756     unless ( $twit and $twit->can('search') ) {
757         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
758               . "doesn't support searches." );
759         return;
760     }
761
762     $data =~ s/^\s+|\s+$//;
763     $data = lc $data;
764
765     unless ($data) {
766         &notice("Usage: /twitter_subscribe <topic>");
767         return;
768     }
769
770     if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
771         &notice("Already had a subscription for '$data'");
772         return;
773     }
774
775     $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
776     &notice("Added subscription for '$data'");
777 }
778
779 sub cmd_del_search {
780     my ( $data, $server, $win ) = @_;
781
782     unless ( $twit and $twit->can('search') ) {
783         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
784               . "doesn't support searches." );
785         return;
786     }
787     $data =~ s/^\s+|\s+$//;
788     $data = lc $data;
789
790     unless ($data) {
791         &notice("Usage: /twitter_unsubscribe <topic>");
792         return;
793     }
794
795     unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
796         &notice("No subscription found for '$data'");
797         return;
798     }
799
800     delete $id_map{__searches}{"$user\@$defservice"}{$data};
801     &notice("Removed subscription for '$data'");
802 }
803
804 sub cmd_list_search {
805     my ( $data, $server, $win ) = @_;
806
807     my $found = 0;
808     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
809         my $topics;
810         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
811             $topics = $topics ? "$topics, $topic" : $topic;
812         }
813         if ($topics) {
814             $found = 1;
815             &notice("Search subscriptions for \@$suser: $topics");
816         }
817     }
818
819     unless ($found) {
820         &notice("No search subscriptions set up");
821     }
822 }
823
824 sub cmd_upgrade {
825     my ( $data, $server, $win ) = @_;
826
827     my $loc = Irssi::settings_get_str("twirssi_location");
828     unless ( -w $loc ) {
829         &notice("$loc isn't writable, can't upgrade."
830               . "  Perhaps you need to /set twirssi_location?" );
831         return;
832     }
833
834     my $md5;
835     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
836         eval { use Digest::MD5; };
837
838         if ($@) {
839             &notice("Failed to load Digest::MD5."
840                   . "  Try '/twirssi_upgrade nomd5' to skip MD5 verification" );
841             return;
842         }
843
844         $md5 = get("http://twirssi.com/md5sum");
845         chomp $md5;
846         $md5 =~ s/ .*//;
847         unless ($md5) {
848             &notice("Failed to download md5sum from peeron!  Aborting.");
849             return;
850         }
851
852         unless ( open( CUR, $loc ) ) {
853             &notice("Failed to read $loc."
854                   . "  Check that /set twirssi_location is set to the correct location."
855             );
856             return;
857         }
858
859         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
860         close CUR;
861
862         if ( $cur_md5 eq $md5 ) {
863             &notice("Current twirssi seems to be up to date.");
864             return;
865         }
866     }
867
868     my $URL =
869       Irssi::settings_get_bool("twirssi_upgrade_beta")
870       ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
871       : "http://twirssi.com/twirssi.pl";
872     &notice("Downloading twirssi from $URL");
873     LWP::Simple::getstore( $URL, "$loc.upgrade" );
874
875     unless ( -s "$loc.upgrade" ) {
876         &notice("Failed to save $loc.upgrade."
877               . "  Check that /set twirssi_location is set to the correct location."
878         );
879         return;
880     }
881
882     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
883         unless ( open( NEW, "$loc.upgrade" ) ) {
884             &notice("Failed to read $loc.upgrade."
885                   . "  Check that /set twirssi_location is set to the correct location."
886             );
887             return;
888         }
889
890         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
891         close NEW;
892
893         if ( $new_md5 ne $md5 ) {
894             &notice("MD5 verification failed. expected $md5, got $new_md5");
895             return;
896         }
897     }
898
899     rename $loc, "$loc.backup"
900       or &notice("Failed to back up $loc: $!.  Aborting")
901       and return;
902     rename "$loc.upgrade", $loc
903       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
904       and return;
905
906     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
907     if ( -e "$dir/autorun/$file" ) {
908         &notice("Updating $dir/autorun/$file");
909         unlink "$dir/autorun/$file"
910           or &notice("Failed to remove old $file from autorun: $!");
911         symlink "../$file", "$dir/autorun/$file"
912           or &notice("Failed to create symlink in autorun directory: $!");
913     }
914
915     &notice("Download complete.  Reload twirssi with /script load $file");
916 }
917
918 sub load_friends {
919     my $fh     = shift;
920     my $cursor = -1;
921     my $page   = 1;
922     my %new_friends;
923     eval {
924         while ( $page < 11 and $cursor ne "0" )
925         {
926             print $fh "type:debug Loading friends page $page...\n"
927               if ( $fh and &debug );
928             my $friends;
929             if ( ref $twit =~ /^Net::Twitter/ ) {
930                 $friends = $twit->friends( { cursor => $cursor } );
931                 last unless $friends;
932                 $cursor  = $friends->{next_cursor};
933                 $friends = $friends->{users};
934             } else {
935                 $friends = $twit->friends( { page => $page } );
936                 last unless $friends;
937             }
938             $new_friends{ $_->{screen_name} } = time foreach @$friends;
939             $page++;
940         }
941     };
942
943     if ($@) {
944         print $fh "type:debug Error during friends list update.  Aborted.\n";
945         return;
946     }
947
948     my ( $added, $removed ) = ( 0, 0 );
949     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
950     foreach ( keys %new_friends ) {
951         next if exists $friends{$_};
952         $friends{$_} = time;
953         $added++;
954     }
955
956     print $fh "type:debug Scanning for removed friends...\n"
957       if ( $fh and &debug );
958     foreach ( keys %friends ) {
959         next if exists $new_friends{$_};
960         delete $friends{$_};
961         $removed++;
962     }
963
964     return ( $added, $removed );
965 }
966
967 sub get_updates {
968     print scalar localtime, " - get_updates starting" if &debug;
969
970     $window =
971       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
972     unless ($window) {
973         Irssi::active_win()
974           ->print( "Can't find a window named '"
975               . Irssi::settings_get_str('twitter_window')
976               . "'.  Create it or change the value of twitter_window" );
977     }
978
979     return unless &logged_in($twit);
980
981     my ( $fh, $filename ) = File::Temp::tempfile();
982     binmode( $fh, ":utf8" );
983     $child_pid = fork();
984
985     if ($child_pid) {    # parent
986         Irssi::timeout_add_once( 5000, 'monitor_child',
987             [ "$filename.done", 0 ] );
988         Irssi::pidwait_add($child_pid);
989     } elsif ( defined $child_pid ) {    # child
990         close STDIN;
991         close STDOUT;
992         close STDERR;
993
994         my $new_poll = time;
995
996         my $error = 0;
997         my %context_cache;
998         foreach ( keys %twits ) {
999             $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
1000
1001             if ( $id_map{__fixreplies}{$_} ) {
1002                 my @frusers = sort keys %{ $id_map{__fixreplies}{$_} };
1003
1004                 $error++
1005                   unless &get_timeline( $fh, $frusers[ $fix_replies_index{$_} ],
1006                     $_, $twits{$_}, \%context_cache );
1007
1008                 $fix_replies_index{$_}++;
1009                 $fix_replies_index{$_} = 0
1010                   if $fix_replies_index{$_} >= @frusers;
1011                 print $fh "id:$fix_replies_index{$_} ",
1012                   "account:$_ type:fix_replies_index\n";
1013             }
1014         }
1015
1016         print $fh "__friends__\n";
1017         if (
1018             time - $last_friends_poll >
1019             Irssi::settings_get_int('twitter_friends_poll') )
1020         {
1021             print $fh "__updated ", time, "\n";
1022             my ( $added, $removed ) = &load_friends($fh);
1023             if ( $added + $removed ) {
1024                 print $fh "type:debug %R***%n Friends list updated: ",
1025                   join( ", ",
1026                     sprintf( "%d added",   $added ),
1027                     sprintf( "%d removed", $removed ) ),
1028                   "\n";
1029             }
1030         }
1031
1032         foreach ( sort keys %friends ) {
1033             print $fh "$_ $friends{$_}\n";
1034         }
1035
1036         if ($error) {
1037             print $fh "type:debug Update encountered errors.  Aborted\n";
1038             print $fh "-- $last_poll";
1039         } else {
1040             print $fh "-- $new_poll";
1041         }
1042         close $fh;
1043         rename $filename, "$filename.done";
1044         exit;
1045     } else {
1046         &ccrap("Failed to fork for updating: $!");
1047     }
1048     print scalar localtime, " - get_updates ends" if &debug;
1049 }
1050
1051 sub do_updates {
1052     my ( $fh, $username, $obj, $cache ) = @_;
1053
1054     eval {
1055         my $rate_limit = $obj->rate_limit_status();
1056         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
1057             &notice("Rate limit exceeded for $username");
1058             return undef;
1059         }
1060     };
1061
1062     print scalar localtime, " - Polling for updates for $username" if &debug;
1063     my $tweets;
1064     my $new_poll_id = 0;
1065     eval {
1066         if ( $id_map{__last_id}{$username}{timeline} )
1067         {
1068             $tweets = $obj->home_timeline( { count => 100 } );
1069         } else {
1070             $tweets = $obj->home_timeline();
1071         }
1072     };
1073
1074     if ($@) {
1075         print $fh "type:debug Error during home_timeline call: Aborted.\n";
1076         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
1077         return undef;
1078     }
1079
1080     unless ( ref $tweets ) {
1081         if ( $obj->can("get_error") ) {
1082             my $error = "Unknown error";
1083             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
1084             unless ($@) { $error = $obj->get_error() }
1085             print $fh
1086               "type:debug API Error during home_timeline call: Aborted\n";
1087             print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
1088
1089         } else {
1090             print $fh
1091               "type:debug API Error during home_timeline call. Aborted.\n";
1092         }
1093         return undef;
1094     }
1095
1096     foreach my $t ( reverse @$tweets ) {
1097         my $text = &get_text( $t, $obj );
1098         my $reply = "tweet";
1099         if (    Irssi::settings_get_bool("show_reply_context")
1100             and $t->{in_reply_to_screen_name} ne $username
1101             and $t->{in_reply_to_screen_name}
1102             and not exists $friends{ $t->{in_reply_to_screen_name} } )
1103         {
1104             $nicks{ $t->{in_reply_to_screen_name} } = time;
1105             my $context;
1106             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
1107                 eval {
1108                     $cache->{ $t->{in_reply_to_status_id} } =
1109                       $obj->show_status( $t->{in_reply_to_status_id} );
1110                 };
1111
1112             }
1113             $context = $cache->{ $t->{in_reply_to_status_id} };
1114
1115             if ($context) {
1116                 my $ctext = &get_text( $context, $obj );
1117                 printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
1118                   $context->{id}, $username,
1119                   $context->{user}{screen_name}, $ctext;
1120                 $reply = "reply";
1121             }
1122         }
1123         next
1124           if $t->{user}{screen_name} eq $username
1125               and not Irssi::settings_get_bool("show_own_tweets");
1126         printf $fh "id:%s account:%s nick:%s type:%s %s\n",
1127           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
1128         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1129     }
1130     printf $fh "id:%s account:%s type:last_id timeline\n",
1131       $new_poll_id, $username;
1132
1133     print scalar localtime, " - Polling for replies since ",
1134       $id_map{__last_id}{$username}{reply}
1135       if &debug;
1136     $new_poll_id = 0;
1137     eval {
1138         if ( $id_map{__last_id}{$username}{reply} )
1139         {
1140             $tweets = $obj->replies(
1141                 { since_id => $id_map{__last_id}{$username}{reply} } )
1142               || [];
1143         } else {
1144             $tweets = $obj->replies() || [];
1145         }
1146     };
1147
1148     if ($@) {
1149         print $fh "type:debug Error during replies call.  Aborted.\n";
1150         return undef;
1151     }
1152
1153     foreach my $t ( reverse @$tweets ) {
1154         next
1155           if exists $friends{ $t->{user}{screen_name} };
1156
1157         my $text = &get_text( $t, $obj );
1158         printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
1159           $t->{id}, $username, $t->{user}{screen_name}, $text;
1160         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1161     }
1162     printf $fh "id:%s account:%s type:last_id reply\n", $new_poll_id, $username;
1163
1164     print scalar localtime, " - Polling for DMs" if &debug;
1165     $new_poll_id = 0;
1166     eval {
1167         if ( $id_map{__last_id}{$username}{dm} )
1168         {
1169             $tweets = $obj->direct_messages(
1170                 { since_id => $id_map{__last_id}{$username}{dm} } )
1171               || [];
1172         } else {
1173             $tweets = $obj->direct_messages() || [];
1174         }
1175     };
1176
1177     if ($@) {
1178         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
1179         return undef;
1180     }
1181
1182     foreach my $t ( reverse @$tweets ) {
1183         my $text = decode_entities( $t->{text} );
1184         $text =~ s/[\n\r]/ /g;
1185         printf $fh "id:%s account:%s nick:%s type:dm %s\n",
1186           $t->{id}, $username, $t->{sender_screen_name}, $text;
1187         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1188     }
1189     printf $fh "id:%s account:%s type:last_id dm\n", $new_poll_id, $username;
1190
1191     print scalar localtime, " - Polling for subscriptions" if &debug;
1192     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
1193         my $search;
1194         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
1195             print $fh "type:debug searching for $topic since ",
1196               "$id_map{__searches}{$username}{$topic}\n";
1197             eval {
1198                 $search = $obj->search(
1199                     {
1200                         q        => $topic,
1201                         since_id => $id_map{__searches}{$username}{$topic}
1202                     }
1203                 );
1204             };
1205
1206             if ($@) {
1207                 print $fh
1208                   "type:debug Error during search($topic) call.  Aborted.\n";
1209                 return undef;
1210             }
1211
1212             unless ( $search->{max_id} ) {
1213                 print $fh "type:debug Invalid search results when searching",
1214                   " for $topic. Aborted.\n";
1215                 return undef;
1216             }
1217
1218             $id_map{__searches}{$username}{$topic} = $search->{max_id};
1219             printf $fh "id:%s account:%s type:searchid topic:%s\n",
1220               $search->{max_id}, $username, $topic;
1221
1222             foreach my $t ( reverse @{ $search->{results} } ) {
1223                 my $text = &get_text( $t, $obj );
1224                 printf $fh "id:%s account:%s nick:%s type:search topic:%s %s\n",
1225                   $t->{id}, $username, $t->{from_user}, $topic, $text;
1226                 $new_poll_id = $t->{id}
1227                   if not $new_poll_id
1228                       or $t->{id} < $new_poll_id;
1229             }
1230         }
1231     }
1232
1233     print scalar localtime, " - Done" if &debug;
1234
1235     return 1;
1236 }
1237
1238 sub get_timeline {
1239     my ( $fh, $target, $username, $obj, $cache ) = @_;
1240     my $tweets;
1241     my $last_id = $id_map{__last_id}{$username}{$target};
1242
1243     print $fh "type:debug get_timeline("
1244       . "$fix_replies_index{$username}=$target > $last_id) started."
1245       . "  username = $username\n";
1246     eval {
1247         $tweets = $obj->user_timeline(
1248             {
1249                 id => $target,
1250                 ( $last_id ? ( since_id => $last_id ) : () ),
1251             }
1252         );
1253     };
1254
1255     if ($@) {
1256         print $fh
1257           "type:debug Error during user_timeline($target) call: Aborted.\n";
1258         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
1259         return undef;
1260     }
1261
1262     unless ($tweets) {
1263         print $fh
1264           "type:debug user_timeline($target) call returned undef!  Aborted\n";
1265         return 1;
1266     }
1267
1268     foreach my $t ( reverse @$tweets ) {
1269         my $text = &get_text( $t, $obj );
1270         my $reply = "tweet";
1271         if (    Irssi::settings_get_bool("show_reply_context")
1272             and $t->{in_reply_to_screen_name} ne $username
1273             and $t->{in_reply_to_screen_name}
1274             and not exists $friends{ $t->{in_reply_to_screen_name} } )
1275         {
1276             $nicks{ $t->{in_reply_to_screen_name} } = time;
1277             my $context;
1278             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
1279                 eval {
1280                     $cache->{ $t->{in_reply_to_status_id} } =
1281                       $obj->show_status( $t->{in_reply_to_status_id} );
1282                 };
1283
1284             }
1285             $context = $cache->{ $t->{in_reply_to_status_id} };
1286
1287             if ($context) {
1288                 my $ctext = &get_text( $context, $obj );
1289                 printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
1290                   $context->{id}, $username,
1291                   $context->{user}{screen_name}, $ctext;
1292                 $reply = "reply";
1293             }
1294         }
1295         printf $fh "id:%s account:%s nick:%s type:%s %s\n",
1296           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
1297         $last_id = $t->{id} if $last_id < $t->{id};
1298     }
1299     printf $fh "id:%s account:%s type:last_id_fixreplies %s\n",
1300       $last_id, $username, $target;
1301
1302     return 1;
1303 }
1304
1305 sub monitor_child {
1306     my ($data)   = @_;
1307     my $filename = $data->[0];
1308     my $attempt  = $data->[1];
1309
1310     print scalar localtime, " - checking child log at $filename ($attempt)"
1311       if &debug;
1312     my ($new_last_poll);
1313
1314     # reap any random leftover processes - work around a bug in irssi on gentoo
1315     waitpid( -1, WNOHANG );
1316
1317     # first time we run we don't want to print out *everything*, so we just
1318     # pretend
1319
1320     if ( open FILE, $filename ) {
1321         binmode FILE, ":utf8";
1322         my @lines;
1323         my %new_cache;
1324         while (<FILE>) {
1325             last if /^__friends__/;
1326             unless (/\n$/) {    # skip partial lines
1327                                 # print "Skipping partial line: $_" if &debug;
1328                 next;
1329             }
1330             chomp;
1331             my $hilight = 0;
1332             my %meta;
1333
1334             foreach my $key (qw/id account nick type topic/) {
1335                 if (s/^$key:(\S+)\s*//) {
1336                     $meta{$key} = $1;
1337                 }
1338             }
1339
1340             if ( $meta{type} and $meta{type} eq 'fix_replies_index' ) {
1341                 $fix_replies_index{ $meta{account} } = $meta{id};
1342                 print "fix_replies_index for $meta{account} set to $meta{id}"
1343                   if &debug;
1344                 next;
1345             }
1346
1347             if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1348                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1349                     next;
1350                 }
1351
1352                 $new_cache{ $meta{id} } = time;
1353
1354                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1355                     next;
1356                 }
1357             }
1358
1359             my $account = "";
1360             $meta{account} =~ s/\@(\w+)$//;
1361             $meta{service} = $1;
1362             if (
1363                 lc $meta{service} eq
1364                 lc Irssi::settings_get_str("twirssi_default_service") )
1365             {
1366                 $account = "$meta{account}: "
1367                   if lc "$meta{account}\@$meta{service}" ne lc
1368                       "$user\@$defservice";
1369             } else {
1370                 $account = "$meta{account}\@$meta{service}: ";
1371             }
1372
1373             my $marker = "";
1374             if (    $meta{type} ne 'dm'
1375                 and Irssi::settings_get_bool("twirssi_track_replies")
1376                 and $meta{nick}
1377                 and $meta{id} )
1378             {
1379                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1380                 $id_map{ lc $meta{nick} }[$marker]           = $meta{id};
1381                 $id_map{__indexes}{ $meta{nick} }            = $marker;
1382                 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1383                 $marker                                      = ":$marker";
1384             }
1385
1386             my $hilight_color =
1387               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1388             my $nick = "\@$meta{account}";
1389             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1390                 and Irssi::settings_get_bool("twirssi_hilights") )
1391             {
1392                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1393                 $hilight = MSGLEVEL_HILIGHT;
1394             }
1395
1396             if ( $meta{type} =~ /tweet|reply/ ) {
1397                 push @lines,
1398                   [
1399                     ( MSGLEVEL_PUBLIC | $hilight ),
1400                     $meta{type}, $account, $meta{nick}, $marker, $_
1401                   ];
1402             } elsif ( $meta{type} eq 'search' ) {
1403                 push @lines,
1404                   [
1405                     ( MSGLEVEL_PUBLIC | $hilight ),
1406                     $meta{type}, $account, $meta{topic},
1407                     $meta{nick}, $marker,  $_
1408                   ];
1409                 if (
1410                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1411                     and $meta{id} >
1412                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1413                 {
1414                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1415                       $meta{id};
1416                 }
1417             } elsif ( $meta{type} eq 'dm' ) {
1418                 push @lines,
1419                   [
1420                     ( MSGLEVEL_MSGS | $hilight ),
1421                     $meta{type}, $account, $meta{nick}, $_
1422                   ];
1423             } elsif ( $meta{type} eq 'searchid' ) {
1424                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1425                 if (
1426                     not
1427                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1428                     or $meta{id} >=
1429                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1430                 {
1431                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1432                       $meta{id};
1433                 } elsif (&debug) {
1434                     print "Search '$meta{topic}' returned invalid id $meta{id}";
1435                 }
1436             } elsif ( $meta{type} eq 'last_id' ) {
1437                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1438                   $meta{id}
1439                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1440                       $meta{id};
1441             } elsif ( $meta{type} eq 'last_id_fixreplies' ) {
1442                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1443                   $meta{id}
1444                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1445                       $meta{id};
1446             } elsif ( $meta{type} eq 'error' ) {
1447                 push @lines, [ MSGLEVEL_MSGS, $_ ];
1448             } elsif ( $meta{type} eq 'debug' ) {
1449                 print "$_" if &debug,;
1450             } else {
1451                 print "Unknown line type $meta{type}: $_" if &debug,;
1452             }
1453         }
1454
1455         %friends = ();
1456         while (<FILE>) {
1457             if (/^__updated (\d+)$/) {
1458                 $last_friends_poll = $1;
1459                 print "Friend list updated" if &debug;
1460                 next;
1461             }
1462
1463             if (/^-- (\d+)$/) {
1464                 $new_last_poll = $1;
1465                 if ( $new_last_poll >= $last_poll ) {
1466                     last;
1467                 } else {
1468                     print "Impossible!  ",
1469                       "new_last_poll=$new_last_poll < last_poll=$last_poll!"
1470                       if &debug;
1471                     undef $new_last_poll;
1472                     next;
1473                 }
1474             }
1475             my ( $f, $t ) = split ' ', $_;
1476             $nicks{$f} = $friends{$f} = $t;
1477         }
1478
1479         if ($new_last_poll) {
1480             print "new last_poll    = $new_last_poll" if &debug;
1481             print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1482             if ($first_call) {
1483                 print "First call, not printing updates" if &debug;
1484             } else {
1485                 foreach my $line (@lines) {
1486                     $window->printformat(
1487                         $line->[0],
1488                         "twirssi_" . $line->[1],
1489                         @$line[ 2 .. $#$line - 1 ],
1490                         &hilight( $line->[-1] )
1491                     );
1492                 }
1493             }
1494
1495             close FILE;
1496             unlink $filename
1497               or warn "Failed to remove $filename: $!"
1498               unless &debug;
1499
1500             # commit the pending cache lines to the actual cache, now that
1501             # we've printed our output
1502             %tweet_cache = ( %tweet_cache, %new_cache );
1503
1504             # keep enough cached tweets, to make sure we don't show duplicates.
1505             foreach ( keys %tweet_cache ) {
1506                 next if $tweet_cache{$_} >= $last_poll - 3600;
1507                 delete $tweet_cache{$_};
1508             }
1509             $last_poll = $new_last_poll;
1510
1511             # make sure the pid is removed from the waitpid list
1512             Irssi::pidwait_remove($child_pid);
1513
1514             # and that we don't leave any zombies behind, somehow
1515             wait();
1516
1517             # save id_map hash
1518             if ( keys %id_map
1519                 and my $file =
1520                 Irssi::settings_get_str("twirssi_replies_store") )
1521             {
1522                 if ( open JSON, ">$file" ) {
1523                     print JSON JSON::Any->objToJson( \%id_map );
1524                     close JSON;
1525                 } else {
1526                     &ccrap("Failed to write replies to $file: $!");
1527                 }
1528             }
1529             $failwhale  = 0;
1530             $first_call = 0;
1531             return;
1532         }
1533     }
1534
1535     close FILE;
1536
1537     if ( $attempt < 24 ) {
1538         Irssi::timeout_add_once( 5000, 'monitor_child',
1539             [ $filename, $attempt + 1 ] );
1540     } else {
1541         print "Giving up on polling $filename" if &debug;
1542         Irssi::pidwait_remove($child_pid);
1543         wait();
1544         unlink $filename unless &debug;
1545
1546         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1547
1548         my $since;
1549         my @time = localtime($last_poll);
1550         if ( time - $last_poll < 24 * 60 * 60 ) {
1551             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1552         } else {
1553             $since = scalar localtime($last_poll);
1554         }
1555
1556         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1557             foreach my $whale (
1558                 q{     v  v        v},
1559                 q{     |  |  v     |  v},
1560                 q{     | .-, |     |  |},
1561                 q{  .--./ /  |  _.---.| },
1562                 q{   '-. (__..-"       \\},
1563                 q{      \\          a    |},
1564                 q{       ',.__.   ,__.-'/},
1565                 q{         '--/_.'----'`}
1566               )
1567             {
1568                 &ccrap($whale);
1569             }
1570             $failwhale = 1;
1571         }
1572
1573         if ( time - $last_poll < 600 ) {
1574             &ccrap("Haven't been able to get updated tweets since $since");
1575         }
1576     }
1577 }
1578
1579 sub debug {
1580     return Irssi::settings_get_bool("twirssi_debug");
1581 }
1582
1583 sub notice {
1584     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1585 }
1586
1587 sub ccrap {
1588     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1589 }
1590
1591 sub update_away {
1592     my $data = shift;
1593
1594     if (    Irssi::settings_get_bool("tweet_to_away")
1595         and $data !~ /\@\w/
1596         and $data !~ /^[dD] / )
1597     {
1598         my $server =
1599           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1600         if ($server) {
1601             $server->send_raw("away :$data");
1602             return 1;
1603         } else {
1604             &ccrap( "Can't find bitlbee server.",
1605                 "Update bitlbee_server or disable tweet_to_away" );
1606             return 0;
1607         }
1608     }
1609
1610     return 0;
1611 }
1612
1613 sub too_long {
1614     my $data    = shift;
1615     my $noalert = shift;
1616
1617     if ( length $data > 140 ) {
1618         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1619           unless $noalert;
1620         return 1;
1621     }
1622
1623     return 0;
1624 }
1625
1626 sub valid_username {
1627     my $username = shift;
1628
1629     $username = &normalize_username($username);
1630
1631     unless ( exists $twits{$username} ) {
1632         &notice("Unknown username $username");
1633         return undef;
1634     }
1635
1636     return $username;
1637 }
1638
1639 sub logged_in {
1640     my $obj = shift;
1641     unless ($obj) {
1642         &notice("Not logged in!  Use /twitter_login username pass!");
1643         return 0;
1644     }
1645
1646     return 1;
1647 }
1648
1649 sub sig_complete {
1650     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1651
1652     if (
1653         $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1654         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1655             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1656       )
1657     {    # /twitter_reply gets a nick:num
1658         $word =~ s/^@//;
1659         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1660           sort { $nicks{$b} <=> $nicks{$a} }
1661           grep /^\Q$word/i,
1662           keys %{ $id_map{__indexes} };
1663     }
1664
1665     if ( $linestart =~
1666 /^\/(twitter_unfriend|twitter_add_follow_extra|twitter_del_follow_extra)\s*$/
1667       )
1668     {    # /twitter_unfriend gets a nick
1669         $word =~ s/^@//;
1670         push @$complist, grep /^\Q$word/i,
1671           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1672     }
1673
1674     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1675     # arg to dm)
1676     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1677         my $prefix = $word =~ s/^@//;
1678         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1679         push @$complist, grep /^\Q$word/i,
1680           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1681         @$complist = map { "\@$_" } @$complist if $prefix;
1682     }
1683 }
1684
1685 sub event_send_text {
1686     my ( $line, $server, $win ) = @_;
1687     my $awin = Irssi::active_win();
1688
1689     # if the window where we got our text was the twitter window, and the user
1690     # wants to be lazy, tweet away!
1691     if ( ( $awin->get_active_name() eq $window->{name} )
1692         and Irssi::settings_get_bool("tweet_window_input") )
1693     {
1694         &cmd_tweet( $line, $server, $win );
1695     }
1696 }
1697
1698 sub get_poll_time {
1699     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1700     return $poll if $poll >= 60;
1701     return 60;
1702 }
1703
1704 sub hilight {
1705     my $text = shift;
1706
1707     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1708         my $c = Irssi::settings_get_str("twirssi_nick_color");
1709         $c = $irssi_to_mirc_colors{$c};
1710         $text =~ s/(^|\W)\@(\w+)/$1\cC$c\@$2\cO/g if $c;
1711     }
1712     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1713         my $c = Irssi::settings_get_str("twirssi_topic_color");
1714         $c = $irssi_to_mirc_colors{$c};
1715         $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1716     }
1717     $text =~ s/[\n\r]/ /g;
1718
1719     return $text;
1720 }
1721
1722 sub shorten {
1723     my $data = shift;
1724
1725     my $provider = Irssi::settings_get_str("short_url_provider");
1726     if (
1727         (
1728             Irssi::settings_get_bool("twirssi_always_shorten")
1729             or &too_long( $data, 1 )
1730         )
1731         and $provider
1732       )
1733     {
1734         my @args;
1735         if ( $provider eq 'Bitly' ) {
1736             @args[ 1, 2 ] = split ',',
1737               Irssi::settings_get_str("short_url_args"), 2;
1738             unless ( @args == 3 ) {
1739                 &ccrap(
1740                     "WWW::Shorten::Bitly requires a username and API key.",
1741                     "Set short_url_args to username,API_key or change your",
1742                     "short_url_provider."
1743                 );
1744                 return decode "utf8", $data;
1745             }
1746         }
1747
1748         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1749             eval {
1750                 $args[0] = $url;
1751                 my $short = makeashorterlink(@args);
1752                 if ($short) {
1753                     $data =~ s/\Q$url/$short/g;
1754                 } else {
1755                     &notice("Failed to shorten $url!");
1756                 }
1757             };
1758         }
1759     }
1760
1761     return decode "utf8", $data;
1762 }
1763
1764 sub normalize_username {
1765     my $user = shift;
1766
1767     my ( $username, $service ) = split /\@/, $user, 2;
1768     if ($service) {
1769         $service = ucfirst lc $service;
1770     } else {
1771         $service =
1772           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1773         unless ( exists $twits{"$username\@$service"} ) {
1774             $service = undef;
1775             foreach my $t ( sort keys %twits ) {
1776                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1777                 $service = $1;
1778                 last;
1779             }
1780
1781             unless ($service) {
1782                 &notice("Can't find a logged in user '$user'");
1783             }
1784         }
1785     }
1786
1787     return "$username\@$service";
1788 }
1789
1790 sub get_text {
1791     my $tweet  = shift;
1792     my $object = shift;
1793     my $text   = decode_entities( $tweet->{text} );
1794     if ( $tweet->{truncated} ) {
1795         if ( exists $tweet->{retweeted_status} ) {
1796             $text = "RT \@$tweet->{retweeted_status}{user}{screen_name}: "
1797               . "$tweet->{retweeted_status}{text}";
1798         } elsif ( $object->isa('Net::Twitter') ) {
1799             $text .= " -- http://twitter.com/$tweet->{user}{screen_name}"
1800               . "/status/$tweet->{id}";
1801         }
1802     }
1803
1804     $text =~ s/[\n\r]/ /g;
1805
1806     return $text;
1807 }
1808
1809 Irssi::signal_add( "send text", "event_send_text" );
1810
1811 Irssi::theme_register(
1812     [
1813         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1814         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1815         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1816         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1817         'twirssi_error',  'ERROR: $0',
1818     ]
1819 );
1820
1821 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1822 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
1823 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
1824 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
1825 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
1826 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
1827 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
1828 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1829 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
1830 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
1831 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1832     'RT $n: "$t" ${-- $c$}' );
1833 Irssi::settings_add_str( "twirssi", "twirssi_location",
1834     "$ENV{HOME}/.irssi/scripts/twirssi.pl" );
1835 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1836     "$ENV{HOME}/.irssi/scripts/twirssi.json" );
1837 Irssi::settings_add_str( "twirssi", "twirssi_oauth_store",
1838     "$ENV{HOME}/.irssi/scripts/twirssi.oauth" );
1839
1840 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1841 Irssi::settings_add_int( "twirssi", "twitter_timeout",      30 );
1842
1843 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1844 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1845 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1846 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1847 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1848 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1849 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1850 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1851 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1852 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1853 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1854 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1855 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1856 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl",         0 );
1857 Irssi::settings_add_bool( "twirssi", "twirssi_use_oauth",         1 );
1858
1859 $last_poll = time - &get_poll_time;
1860 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1861 if ( !$window ) {
1862     Irssi::active_win()
1863       ->print( "Couldn't find a window named '"
1864           . Irssi::settings_get_str('twitter_window')
1865           . "', trying to create it." );
1866     $window =
1867       Irssi::Windowitem::window_create(
1868         Irssi::settings_get_str('twitter_window'), 1 );
1869     $window->set_name( Irssi::settings_get_str('twitter_window') );
1870 }
1871
1872 if ($window) {
1873     Irssi::command_bind( "dm",                         "cmd_direct" );
1874     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1875     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1876     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1877     Irssi::command_bind( "retweet",                    "cmd_retweet" );
1878     Irssi::command_bind( "retweet_as",                 "cmd_retweet_as" );
1879     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1880     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1881     Irssi::command_bind( "twitter_login",              "cmd_login" );
1882     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1883     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1884     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1885     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1886     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1887     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1888     Irssi::command_bind( "twirssi_oauth",              "cmd_oauth" );
1889     Irssi::command_bind( "twitter_updates",            "get_updates" );
1890     Irssi::command_bind( "twitter_add_follow_extra",   "cmd_add_follow" );
1891     Irssi::command_bind( "twitter_del_follow_extra",   "cmd_del_follow" );
1892     Irssi::command_bind( "twitter_list_follow_extra",  "cmd_list_follow" );
1893     Irssi::command_bind( "bitlbee_away",               "update_away" );
1894     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1895         Irssi::command_bind( "reply",    "cmd_reply" );
1896         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1897     }
1898     Irssi::command_bind(
1899         "twirssi_dump",
1900         sub {
1901             print "twits: ", join ", ",
1902               map { "u: $_->{username}\@" . ref($_) } values %twits;
1903             print "selected: $user\@$defservice";
1904             print "friends: ", join ", ", sort keys %friends;
1905             print "nicks: ",   join ", ", sort keys %nicks;
1906             print "searches: ", Dumper \%{ $id_map{__searches} };
1907             print "last poll: $last_poll";
1908             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1909                 print DUMP Dumper \%tweet_cache;
1910                 close DUMP;
1911                 print "cache written out to /tmp/twirssi.cache.txt";
1912             }
1913         }
1914     );
1915     Irssi::command_bind(
1916         "twirssi_version",
1917         sub {
1918             &notice(
1919                 "Twirssi v$VERSION; "
1920                   . (
1921                     $Net::Twitter::VERSION
1922                     ? "Net::Twitter v$Net::Twitter::VERSION. "
1923                     : ""
1924                   )
1925                   . (
1926                     $Net::Identica::VERSION
1927                     ? "Net::Identica v$Net::Identica::VERSION. "
1928                     : ""
1929                   )
1930                   . "JSON in use: "
1931                   . JSON::Any::handler()
1932                   . ".  See details at http://twirssi.com/"
1933             );
1934         }
1935     );
1936     Irssi::command_bind(
1937         "twitter_follow",
1938         &gen_cmd(
1939             "/twitter_follow <username>",
1940             "create_friend",
1941             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1942         )
1943     );
1944     Irssi::command_bind(
1945         "twitter_unfollow",
1946         &gen_cmd(
1947             "/twitter_unfriend <username>",
1948             "destroy_friend",
1949             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1950         )
1951     );
1952     Irssi::command_bind(
1953         "twitter_device_updates",
1954         &gen_cmd(
1955             "/twitter_device_updates none|im|sms",
1956             "update_delivery_device",
1957             sub { &notice("Device updated to $_[0]"); }
1958         )
1959     );
1960     Irssi::command_bind(
1961         "twitter_block",
1962         &gen_cmd(
1963             "/twitter_block <username>",
1964             "create_block",
1965             sub { &notice("Blocked $_[0]"); }
1966         )
1967     );
1968     Irssi::command_bind(
1969         "twitter_unblock",
1970         &gen_cmd(
1971             "/twitter_unblock <username>",
1972             "destroy_block",
1973             sub { &notice("Unblock $_[0]"); }
1974         )
1975     );
1976     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1977
1978     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N");
1979     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1980     &notice(
1981         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1982
1983     my $file = Irssi::settings_get_str("twirssi_replies_store");
1984     if ( $file and -r $file ) {
1985         if ( open( JSON, $file ) ) {
1986             local $/;
1987             my $json = <JSON>;
1988             close JSON;
1989             eval {
1990                 my $ref = JSON::Any->jsonToObj($json);
1991                 %id_map = %$ref;
1992                 my $num = keys %{ $id_map{__indexes} };
1993                 &notice( sprintf "Loaded old replies from %d contact%s.",
1994                     $num, ( $num == 1 ? "" : "s" ) );
1995                 &cmd_list_search;
1996                 &cmd_list_follow;
1997             };
1998         } else {
1999             &notice("Failed to load old replies from $file: $!");
2000         }
2001     }
2002
2003     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
2004         &notice("Loading WWW::Shorten::$provider...");
2005         eval "use WWW::Shorten::$provider;";
2006
2007         if ($@) {
2008             &notice(
2009                 "Failed to load WWW::Shorten::$provider - either clear",
2010                 "short_url_provider or install the CPAN module"
2011             );
2012         }
2013     }
2014
2015     if ( my $autouser = Irssi::settings_get_str("twitter_usernames") ) {
2016         &cmd_login();
2017         &get_updates;
2018     }
2019
2020 } else {
2021     Irssi::active_win()
2022       ->print( "Create a window named "
2023           . Irssi::settings_get_str('twitter_window')
2024           . " or change the value of twitter_window.  Then, reload twirssi." );
2025 }
2026
2027 # vim: set sts=4 expandtab: