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