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