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