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