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