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