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