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