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