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