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