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