5ab53c1bc2f5ba2681dd5ef517c2f4adf4fcc72e
[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.1beta";
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 3.0";
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         return;
704     }
705
706     my $md5;
707     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
708         eval { use Digest::MD5; };
709
710         if ($@) {
711             &notice("Failed to load Digest::MD5."
712                   . "  Try '/twirssi_upgrade nomd5' to skip MD5 verification" );
713             return;
714         }
715
716         $md5 = get("http://twirssi.com/md5sum");
717         chomp $md5;
718         $md5 =~ s/ .*//;
719         unless ($md5) {
720             &notice("Failed to download md5sum from peeron!  Aborting.");
721             return;
722         }
723
724         unless ( open( CUR, $loc ) ) {
725             &notice("Failed to read $loc."
726                   . "  Check that /set twirssi_location is set to the correct location."
727             );
728             return;
729         }
730
731         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
732         close CUR;
733
734         if ( $cur_md5 eq $md5 ) {
735             &notice("Current twirssi seems to be up to date.");
736             return;
737         }
738     }
739
740     my $URL =
741       Irssi::settings_get_bool("twirssi_upgrade_beta")
742       ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
743       : "http://twirssi.com/twirssi.pl";
744     &notice("Downloading twirssi from $URL");
745     LWP::Simple::getstore( $URL, "$loc.upgrade" );
746
747     unless ( -s "$loc.upgrade" ) {
748         &notice("Failed to save $loc.upgrade."
749               . "  Check that /set twirssi_location is set to the correct location."
750         );
751         return;
752     }
753
754     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
755         unless ( open( NEW, "$loc.upgrade" ) ) {
756             &notice("Failed to read $loc.upgrade."
757                   . "  Check that /set twirssi_location is set to the correct location."
758             );
759             return;
760         }
761
762         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
763         close NEW;
764
765         if ( $new_md5 ne $md5 ) {
766             &notice("MD5 verification failed. expected $md5, got $new_md5");
767             return;
768         }
769     }
770
771     rename $loc, "$loc.backup"
772       or &notice("Failed to back up $loc: $!.  Aborting")
773       and return;
774     rename "$loc.upgrade", $loc
775       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
776       and return;
777
778     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
779     if ( -e "$dir/autorun/$file" ) {
780         &notice("Updating $dir/autorun/$file");
781         unlink "$dir/autorun/$file"
782           or &notice("Failed to remove old $file from autorun: $!");
783         symlink "../$file", "$dir/autorun/$file"
784           or &notice("Failed to create symlink in autorun directory: $!");
785     }
786
787     &notice("Download complete.  Reload twirssi with /script load $file");
788 }
789
790 sub load_friends {
791     my $fh     = shift;
792     my $cursor = -1;
793     my $page   = 1;
794     my %new_friends;
795     eval {
796         while ( $page < 11 and $cursor ne "0" )
797         {
798             print $fh "type:debug Loading friends page $page...\n"
799               if ( $fh and &debug );
800             my $friends;
801             if ( ref $twit =~ /^Net::Twitter/ ) {
802                 $friends = $twit->friends( { cursor => $cursor } );
803                 last unless $friends;
804                 $cursor  = $friends->{next_cursor};
805                 $friends = $friends->{users};
806             } else {
807                 $friends = $twit->friends( { page => $page } );
808                 last unless $friends;
809             }
810             $new_friends{ $_->{screen_name} } = time foreach @$friends;
811             $page++;
812         }
813     };
814
815     if ($@) {
816         print $fh "type:debug Error during friends list update.  Aborted.\n";
817         return;
818     }
819
820     my ( $added, $removed ) = ( 0, 0 );
821     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
822     foreach ( keys %new_friends ) {
823         next if exists $friends{$_};
824         $friends{$_} = time;
825         $added++;
826     }
827
828     print $fh "type:debug Scanning for removed friends...\n"
829       if ( $fh and &debug );
830     foreach ( keys %friends ) {
831         next if exists $new_friends{$_};
832         delete $friends{$_};
833         $removed++;
834     }
835
836     return ( $added, $removed );
837 }
838
839 sub get_updates {
840     print scalar localtime, " - get_updates starting" if &debug;
841
842     $window =
843       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
844     unless ($window) {
845         Irssi::active_win()
846           ->print( "Can't find a window named '"
847               . Irssi::settings_get_str('twitter_window')
848               . "'.  Create it or change the value of twitter_window" );
849     }
850
851     return unless &logged_in($twit);
852
853     my ( $fh, $filename ) = File::Temp::tempfile();
854     binmode( $fh, ":utf8" );
855     $child_pid = fork();
856
857     if ($child_pid) {    # parent
858         Irssi::timeout_add_once( 5000, 'monitor_child',
859             [ "$filename.done", 0 ] );
860         Irssi::pidwait_add($child_pid);
861     } elsif ( defined $child_pid ) {    # child
862         close STDIN;
863         close STDOUT;
864         close STDERR;
865
866         my $new_poll = time;
867
868         my $error = 0;
869         my %context_cache;
870         foreach ( keys %twits ) {
871             $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
872
873             if ( $id_map{__fixreplies}{$_} ) {
874                 my @frusers = sort keys %{ $id_map{__fixreplies}{$_} };
875
876                 $error++
877                   unless &get_timeline( $fh, $frusers[ $fix_replies_index{$_} ],
878                     $_, $twits{$_}, \%context_cache );
879
880                 $fix_replies_index{$_}++;
881                 $fix_replies_index{$_} = 0
882                   if $fix_replies_index{$_} >= @frusers;
883                 print $fh "id:$fix_replies_index{$_} ",
884                   "account:$_ type:fix_replies_index\n";
885             }
886         }
887
888         print $fh "__friends__\n";
889         if (
890             time - $last_friends_poll >
891             Irssi::settings_get_int('twitter_friends_poll') )
892         {
893             print $fh "__updated ", time, "\n";
894             my ( $added, $removed ) = &load_friends($fh);
895             if ( $added + $removed ) {
896                 print $fh "type:debug %R***%n Friends list updated: ",
897                   join( ", ",
898                     sprintf( "%d added",   $added ),
899                     sprintf( "%d removed", $removed ) ),
900                   "\n";
901             }
902         }
903
904         foreach ( sort keys %friends ) {
905             print $fh "$_ $friends{$_}\n";
906         }
907
908         if ($error) {
909             print $fh "type:debug Update encountered errors.  Aborted\n";
910             print $fh "-- $last_poll";
911         } else {
912             print $fh "-- $new_poll";
913         }
914         close $fh;
915         rename $filename, "$filename.done";
916         exit;
917     } else {
918         &ccrap("Failed to fork for updating: $!");
919     }
920     print scalar localtime, " - get_updates ends" if &debug;
921 }
922
923 sub do_updates {
924     my ( $fh, $username, $obj, $cache ) = @_;
925
926     my $rate_limit = $obj->rate_limit_status();
927     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
928         &notice("Rate limit exceeded for $username");
929         return undef;
930     }
931
932     print scalar localtime, " - Polling for updates for $username" if &debug;
933     my $tweets;
934     my $new_poll_id = 0;
935     eval {
936         if ( $id_map{__last_id}{$username}{timeline} )
937         {
938             $tweets = $obj->friends_timeline( { count => 100 } );
939         } else {
940             $tweets = $obj->friends_timeline();
941         }
942     };
943
944     if ($@) {
945         print $fh "type:debug Error during friends_timeline call: Aborted.\n";
946         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
947         return undef;
948     }
949
950     unless ( ref $tweets ) {
951         if ( $obj->can("get_error") ) {
952             my $error = "Unknown error";
953             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
954             unless ($@) { $error = $obj->get_error() }
955             print $fh
956               "type:debug API Error during friends_timeline call: Aborted\n";
957             print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
958
959         } else {
960             print $fh
961               "type:debug API Error during friends_timeline call. Aborted.\n";
962         }
963         return undef;
964     }
965
966     foreach my $t ( reverse @$tweets ) {
967         my $text = decode_entities( $t->{text} );
968         $text =~ s/[\n\r]/ /g;
969         my $reply = "tweet";
970         if (    Irssi::settings_get_bool("show_reply_context")
971             and $t->{in_reply_to_screen_name} ne $username
972             and $t->{in_reply_to_screen_name}
973             and not exists $friends{ $t->{in_reply_to_screen_name} } )
974         {
975             $nicks{ $t->{in_reply_to_screen_name} } = time;
976             my $context;
977             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
978                 eval {
979                     $cache->{ $t->{in_reply_to_status_id} } =
980                       $obj->show_status( $t->{in_reply_to_status_id} );
981                 };
982
983             }
984             $context = $cache->{ $t->{in_reply_to_status_id} };
985
986             if ($context) {
987                 my $ctext = decode_entities( $context->{text} );
988                 $ctext =~ s/[\n\r]/ /g;
989                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
990                     $ctext .=
991                         " -- http://twitter.com/$context->{user}{screen_name}"
992                       . "/status/$context->{id}";
993                 }
994                 printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
995                   $context->{id}, $username,
996                   $context->{user}{screen_name}, $ctext;
997                 $reply = "reply";
998             }
999         }
1000         next
1001           if $t->{user}{screen_name} eq $username
1002               and not Irssi::settings_get_bool("show_own_tweets");
1003         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
1004             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
1005               . "/status/$t->{id}";
1006         }
1007         printf $fh "id:%s account:%s nick:%s type:%s %s\n",
1008           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
1009         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1010     }
1011     printf $fh "id:%s account:%s type:last_id timeline\n",
1012       $new_poll_id, $username;
1013
1014     print scalar localtime, " - Polling for replies since ",
1015       $id_map{__last_id}{$username}{reply}
1016       if &debug;
1017     $new_poll_id = 0;
1018     eval {
1019         if ( $id_map{__last_id}{$username}{reply} )
1020         {
1021             $tweets = $obj->replies(
1022                 { since_id => $id_map{__last_id}{$username}{reply} } )
1023               || [];
1024         } else {
1025             $tweets = $obj->replies() || [];
1026         }
1027     };
1028
1029     if ($@) {
1030         print $fh "type:debug Error during replies call.  Aborted.\n";
1031         return undef;
1032     }
1033
1034     foreach my $t ( reverse @$tweets ) {
1035         next
1036           if exists $friends{ $t->{user}{screen_name} };
1037
1038         my $text = decode_entities( $t->{text} );
1039         $text =~ s/[\n\r]/ /g;
1040         if ( $t->{truncated} ) {
1041             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
1042               . "/status/$t->{id}";
1043         }
1044         printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
1045           $t->{id}, $username, $t->{user}{screen_name}, $text;
1046         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1047     }
1048     printf $fh "id:%s account:%s type:last_id reply\n", $new_poll_id, $username;
1049
1050     print scalar localtime, " - Polling for DMs" if &debug;
1051     $new_poll_id = 0;
1052     eval {
1053         if ( $id_map{__last_id}{$username}{dm} )
1054         {
1055             $tweets = $obj->direct_messages(
1056                 { since_id => $id_map{__last_id}{$username}{dm} } )
1057               || [];
1058         } else {
1059             $tweets = $obj->direct_messages() || [];
1060         }
1061     };
1062
1063     if ($@) {
1064         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
1065         return undef;
1066     }
1067
1068     foreach my $t ( reverse @$tweets ) {
1069         my $text = decode_entities( $t->{text} );
1070         $text =~ s/[\n\r]/ /g;
1071         printf $fh "id:%s account:%s nick:%s type:dm %s\n",
1072           $t->{id}, $username, $t->{sender_screen_name}, $text;
1073         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1074     }
1075     printf $fh "id:%s account:%s type:last_id dm\n", $new_poll_id, $username;
1076
1077     print scalar localtime, " - Polling for subscriptions" if &debug;
1078     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
1079         my $search;
1080         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
1081             print $fh "type:debug searching for $topic since ",
1082               "$id_map{__searches}{$username}{$topic}\n";
1083             eval {
1084                 $search = $obj->search(
1085                     {
1086                         q        => $topic,
1087                         since_id => $id_map{__searches}{$username}{$topic}
1088                     }
1089                 );
1090             };
1091
1092             if ($@) {
1093                 print $fh
1094                   "type:debug Error during search($topic) call.  Aborted.\n";
1095                 return undef;
1096             }
1097
1098             unless ( $search->{max_id} ) {
1099                 print $fh "type:debug Invalid search results when searching",
1100                   " for $topic. Aborted.\n";
1101                 return undef;
1102             }
1103
1104             $id_map{__searches}{$username}{$topic} = $search->{max_id};
1105             printf $fh "id:%s account:%s type:searchid topic:%s\n",
1106               $search->{max_id}, $username, $topic;
1107
1108             foreach my $t ( reverse @{ $search->{results} } ) {
1109                 my $text = decode_entities( $t->{text} );
1110                 $text =~ s/[\n\r]/ /g;
1111                 printf $fh "id:%s account:%s nick:%s type:search topic:%s %s\n",
1112                   $t->{id}, $username, $t->{from_user}, $topic, $text;
1113                 $new_poll_id = $t->{id}
1114                   if not $new_poll_id
1115                       or $t->{id} < $new_poll_id;
1116             }
1117         }
1118     }
1119
1120     print scalar localtime, " - Done" if &debug;
1121
1122     return 1;
1123 }
1124
1125 sub get_timeline {
1126     my ( $fh, $target, $username, $obj, $cache ) = @_;
1127     my $tweets;
1128     my $last_id = $id_map{__last_id}{$username}{$target};
1129
1130     print $fh "type:debug get_timeline("
1131       . "$fix_replies_index{$username}=$target > $last_id) started."
1132       . "  username = $username\n";
1133     eval {
1134         $tweets = $obj->user_timeline(
1135             {
1136                 id => $target,
1137                 ( $last_id ? ( since_id => $last_id ) : () ),
1138             }
1139         );
1140     };
1141
1142     if ($@) {
1143         print $fh
1144           "type:debug Error during user_timeline($target) call: Aborted.\n";
1145         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
1146         return undef;
1147     }
1148
1149     unless ($tweets) {
1150         print $fh
1151           "type:debug user_timeline($target) call returned undef!  Aborted\n";
1152         return 1;
1153     }
1154
1155     foreach my $t ( reverse @$tweets ) {
1156         my $text = decode_entities( $t->{text} );
1157         $text =~ s/[\n\r]/ /g;
1158         my $reply = "tweet";
1159         if (    Irssi::settings_get_bool("show_reply_context")
1160             and $t->{in_reply_to_screen_name} ne $username
1161             and $t->{in_reply_to_screen_name}
1162             and not exists $friends{ $t->{in_reply_to_screen_name} } )
1163         {
1164             $nicks{ $t->{in_reply_to_screen_name} } = time;
1165             my $context;
1166             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
1167                 eval {
1168                     $cache->{ $t->{in_reply_to_status_id} } =
1169                       $obj->show_status( $t->{in_reply_to_status_id} );
1170                 };
1171
1172             }
1173             $context = $cache->{ $t->{in_reply_to_status_id} };
1174
1175             if ($context) {
1176                 my $ctext = decode_entities( $context->{text} );
1177                 $ctext =~ s/[\n\r]/ /g;
1178                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
1179                     $ctext .=
1180                         " -- http://twitter.com/$context->{user}{screen_name}"
1181                       . "/status/$context->{id}";
1182                 }
1183                 printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
1184                   $context->{id}, $username,
1185                   $context->{user}{screen_name}, $ctext;
1186                 $reply = "reply";
1187             }
1188         }
1189         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
1190             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
1191               . "/status/$t->{id}";
1192         }
1193         printf $fh "id:%s account:%s nick:%s type:%s %s\n",
1194           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
1195         $last_id = $t->{id} if $last_id < $t->{id};
1196     }
1197     printf $fh "id:%s account:%s type:last_id_fixreplies %s\n",
1198       $last_id, $username, $target;
1199
1200     return 1;
1201 }
1202
1203 sub monitor_child {
1204     my ($data)   = @_;
1205     my $filename = $data->[0];
1206     my $attempt  = $data->[1];
1207
1208     print scalar localtime, " - checking child log at $filename ($attempt)"
1209       if &debug;
1210     my ($new_last_poll);
1211
1212     # first time we run we don't want to print out *everything*, so we just
1213     # pretend
1214
1215     if ( open FILE, $filename ) {
1216         binmode FILE, ":utf8";
1217         my @lines;
1218         my %new_cache;
1219         while (<FILE>) {
1220             last if /^__friends__/;
1221             unless (/\n$/) {    # skip partial lines
1222                                 # print "Skipping partial line: $_" if &debug;
1223                 next;
1224             }
1225             chomp;
1226             my $hilight = 0;
1227             my %meta;
1228
1229             foreach my $key (qw/id account nick type topic/) {
1230                 if (s/^$key:(\S+)\s*//) {
1231                     $meta{$key} = $1;
1232                 }
1233             }
1234
1235             if ( $meta{type} and $meta{type} eq 'fix_replies_index' ) {
1236                 $fix_replies_index{ $meta{account} } = $meta{id};
1237                 print "fix_replies_index for $meta{account} set to $meta{id}"
1238                   if &debug;
1239                 next;
1240             }
1241
1242             if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1243                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1244                     next;
1245                 }
1246
1247                 $new_cache{ $meta{id} } = time;
1248
1249                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1250                     next;
1251                 }
1252             }
1253
1254             my $account = "";
1255             $meta{account} =~ s/\@(\w+)$//;
1256             $meta{service} = $1;
1257             if (
1258                 lc $meta{service} eq
1259                 lc Irssi::settings_get_str("twirssi_default_service") )
1260             {
1261                 $account = "$meta{account}: "
1262                   if lc "$meta{account}\@$meta{service}" ne lc
1263                       "$user\@$defservice";
1264             } else {
1265                 $account = "$meta{account}\@$meta{service}: ";
1266             }
1267
1268             my $marker = "";
1269             if (    $meta{type} ne 'dm'
1270                 and Irssi::settings_get_bool("twirssi_track_replies")
1271                 and $meta{nick}
1272                 and $meta{id} )
1273             {
1274                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1275                 $id_map{ lc $meta{nick} }[$marker]           = $meta{id};
1276                 $id_map{__indexes}{ $meta{nick} }            = $marker;
1277                 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1278                 $marker                                      = ":$marker";
1279             }
1280
1281             my $hilight_color =
1282               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1283             my $nick = "\@$meta{account}";
1284             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1285                 and Irssi::settings_get_bool("twirssi_hilights") )
1286             {
1287                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1288                 $hilight = MSGLEVEL_HILIGHT;
1289             }
1290
1291             if ( $meta{type} =~ /tweet|reply/ ) {
1292                 push @lines,
1293                   [
1294                     ( MSGLEVEL_PUBLIC | $hilight ),
1295                     $meta{type}, $account, $meta{nick}, $marker, $_
1296                   ];
1297             } elsif ( $meta{type} eq 'search' ) {
1298                 push @lines,
1299                   [
1300                     ( MSGLEVEL_PUBLIC | $hilight ),
1301                     $meta{type}, $account, $meta{topic},
1302                     $meta{nick}, $marker,  $_
1303                   ];
1304                 if (
1305                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1306                     and $meta{id} >
1307                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1308                 {
1309                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1310                       $meta{id};
1311                 }
1312             } elsif ( $meta{type} eq 'dm' ) {
1313                 push @lines,
1314                   [
1315                     ( MSGLEVEL_MSGS | $hilight ),
1316                     $meta{type}, $account, $meta{nick}, $_
1317                   ];
1318             } elsif ( $meta{type} eq 'searchid' ) {
1319                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1320                 if (
1321                     not
1322                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1323                     or $meta{id} >=
1324                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1325                 {
1326                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1327                       $meta{id};
1328                 } elsif (&debug) {
1329                     print "Search '$meta{topic}' returned invalid id $meta{id}";
1330                 }
1331             } elsif ( $meta{type} eq 'last_id' ) {
1332                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1333                   $meta{id}
1334                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1335                       $meta{id};
1336             } elsif ( $meta{type} eq 'last_id_fixreplies' ) {
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 'error' ) {
1342                 push @lines, [ MSGLEVEL_MSGS, $_ ];
1343             } elsif ( $meta{type} eq 'debug' ) {
1344                 print "$_" if &debug,;
1345             } else {
1346                 print "Unknown line type $meta{type}: $_" if &debug,;
1347             }
1348         }
1349
1350         %friends = ();
1351         while (<FILE>) {
1352             if (/^__updated (\d+)$/) {
1353                 $last_friends_poll = $1;
1354                 print "Friend list updated" if &debug;
1355                 next;
1356             }
1357
1358             if (/^-- (\d+)$/) {
1359                 $new_last_poll = $1;
1360                 if ( $new_last_poll >= $last_poll ) {
1361                     last;
1362                 } else {
1363                     print "Impossible!  ",
1364                       "new_last_poll=$new_last_poll < last_poll=$last_poll!"
1365                       if &debug;
1366                     undef $new_last_poll;
1367                     next;
1368                 }
1369             }
1370             my ( $f, $t ) = split ' ', $_;
1371             $nicks{$f} = $friends{$f} = $t;
1372         }
1373
1374         if ($new_last_poll) {
1375             print "new last_poll    = $new_last_poll" if &debug;
1376             print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1377             if ($first_call) {
1378                 print "First call, not printing updates" if &debug;
1379             } else {
1380                 foreach my $line (@lines) {
1381                     $window->printformat(
1382                         $line->[0],
1383                         "twirssi_" . $line->[1],
1384                         @$line[ 2 .. $#$line - 1 ],
1385                         &hilight( $line->[-1] )
1386                     );
1387                 }
1388             }
1389
1390             close FILE;
1391             unlink $filename
1392               or warn "Failed to remove $filename: $!"
1393               unless &debug;
1394
1395             # commit the pending cache lines to the actual cache, now that
1396             # we've printed our output
1397             %tweet_cache = ( %tweet_cache, %new_cache );
1398
1399             # keep enough cached tweets, to make sure we don't show duplicates.
1400             foreach ( keys %tweet_cache ) {
1401                 next if $tweet_cache{$_} >= $last_poll - 3600;
1402                 delete $tweet_cache{$_};
1403             }
1404             $last_poll = $new_last_poll;
1405
1406             # make sure the pid is removed from the waitpid list
1407             Irssi::pidwait_remove($child_pid);
1408
1409             # and that we don't leave any zombies behind, somehow
1410             wait();
1411
1412             # save id_map hash
1413             if ( keys %id_map
1414                 and my $file =
1415                 Irssi::settings_get_str("twirssi_replies_store") )
1416             {
1417                 if ( open JSON, ">$file" ) {
1418                     print JSON JSON::Any->objToJson( \%id_map );
1419                     close JSON;
1420                 } else {
1421                     &ccrap("Failed to write replies to $file: $!");
1422                 }
1423             }
1424             $failwhale  = 0;
1425             $first_call = 0;
1426             return;
1427         }
1428     }
1429
1430     close FILE;
1431
1432     if ( $attempt < 24 ) {
1433         Irssi::timeout_add_once( 5000, 'monitor_child',
1434             [ $filename, $attempt + 1 ] );
1435     } else {
1436         print "Giving up on polling $filename" if &debug;
1437         Irssi::pidwait_remove($child_pid);
1438         wait();
1439         unlink $filename unless &debug;
1440
1441         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1442
1443         my $since;
1444         my @time = localtime($last_poll);
1445         if ( time - $last_poll < 24 * 60 * 60 ) {
1446             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1447         } else {
1448             $since = scalar localtime($last_poll);
1449         }
1450
1451         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1452             foreach my $whale (
1453                 q{     v  v        v},
1454                 q{     |  |  v     |  v},
1455                 q{     | .-, |     |  |},
1456                 q{  .--./ /  |  _.---.| },
1457                 q{   '-. (__..-"       \\},
1458                 q{      \\          a    |},
1459                 q{       ',.__.   ,__.-'/},
1460                 q{         '--/_.'----'`}
1461               )
1462             {
1463                 &ccrap($whale);
1464             }
1465             $failwhale = 1;
1466         }
1467
1468         if ( time - $last_poll < 600 ) {
1469             &ccrap("Haven't been able to get updated tweets since $since");
1470         }
1471     }
1472 }
1473
1474 sub debug {
1475     return Irssi::settings_get_bool("twirssi_debug");
1476 }
1477
1478 sub notice {
1479     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1480 }
1481
1482 sub ccrap {
1483     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1484 }
1485
1486 sub update_away {
1487     my $data = shift;
1488
1489     if (    Irssi::settings_get_bool("tweet_to_away")
1490         and $data !~ /\@\w/
1491         and $data !~ /^[dD] / )
1492     {
1493         my $server =
1494           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1495         if ($server) {
1496             $server->send_raw("away :$data");
1497             return 1;
1498         } else {
1499             &ccrap( "Can't find bitlbee server.",
1500                 "Update bitlbee_server or disable tweet_to_away" );
1501             return 0;
1502         }
1503     }
1504
1505     return 0;
1506 }
1507
1508 sub too_long {
1509     my $data    = shift;
1510     my $noalert = shift;
1511
1512     if ( length $data > 140 ) {
1513         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1514           unless $noalert;
1515         return 1;
1516     }
1517
1518     return 0;
1519 }
1520
1521 sub valid_username {
1522     my $username = shift;
1523
1524     $username = &normalize_username($username);
1525
1526     unless ( exists $twits{$username} ) {
1527         &notice("Unknown username $username");
1528         return undef;
1529     }
1530
1531     return $username;
1532 }
1533
1534 sub logged_in {
1535     my $obj = shift;
1536     unless ($obj) {
1537         &notice("Not logged in!  Use /twitter_login username pass!");
1538         return 0;
1539     }
1540
1541     return 1;
1542 }
1543
1544 sub sig_complete {
1545     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1546
1547     if (
1548         $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1549         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1550             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1551       )
1552     {    # /twitter_reply gets a nick:num
1553         $word =~ s/^@//;
1554         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1555           sort { $nicks{$b} <=> $nicks{$a} }
1556           grep /^\Q$word/i,
1557           keys %{ $id_map{__indexes} };
1558     }
1559
1560     if ( $linestart =~
1561 /^\/(twitter_unfriend|twitter_add_follow_extra|twitter_del_follow_extra)\s*$/
1562       )
1563     {    # /twitter_unfriend gets a nick
1564         $word =~ s/^@//;
1565         push @$complist, grep /^\Q$word/i,
1566           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1567     }
1568
1569     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1570     # arg to dm)
1571     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1572         my $prefix = $word =~ s/^@//;
1573         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1574         push @$complist, grep /^\Q$word/i,
1575           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1576         @$complist = map { "\@$_" } @$complist if $prefix;
1577     }
1578 }
1579
1580 sub event_send_text {
1581     my ( $line, $server, $win ) = @_;
1582     my $awin = Irssi::active_win();
1583
1584     # if the window where we got our text was the twitter window, and the user
1585     # wants to be lazy, tweet away!
1586     if ( ( $awin->get_active_name() eq $window->{name} )
1587         and Irssi::settings_get_bool("tweet_window_input") )
1588     {
1589         &cmd_tweet( $line, $server, $win );
1590     }
1591 }
1592
1593 sub get_poll_time {
1594     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1595     return $poll if $poll >= 60;
1596     return 60;
1597 }
1598
1599 sub hilight {
1600     my $text = shift;
1601
1602     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1603         my $c = Irssi::settings_get_str("twirssi_nick_color");
1604         $c = $irssi_to_mirc_colors{$c};
1605         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1606     }
1607     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1608         my $c = Irssi::settings_get_str("twirssi_topic_color");
1609         $c = $irssi_to_mirc_colors{$c};
1610         $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1611     }
1612     $text =~ s/[\n\r]/ /g;
1613
1614     return $text;
1615 }
1616
1617 sub shorten {
1618     my $data = shift;
1619
1620     my $provider = Irssi::settings_get_str("short_url_provider");
1621     if (
1622         (
1623             Irssi::settings_get_bool("twirssi_always_shorten")
1624             or &too_long( $data, 1 )
1625         )
1626         and $provider
1627       )
1628     {
1629         my @args;
1630         if ( $provider eq 'Bitly' ) {
1631             @args[ 1, 2 ] = split ',',
1632               Irssi::settings_get_str("short_url_args"), 2;
1633             unless ( @args == 3 ) {
1634                 &ccrap(
1635                     "WWW::Shorten::Bitly requires a username and API key.",
1636                     "Set short_url_args to username,API_key or change your",
1637                     "short_url_provider."
1638                 );
1639                 return decode "utf8", $data;
1640             }
1641         }
1642
1643         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1644             eval {
1645                 $args[0] = $url;
1646                 my $short = makeashorterlink(@args);
1647                 if ($short) {
1648                     $data =~ s/\Q$url/$short/g;
1649                 } else {
1650                     &notice("Failed to shorten $url!");
1651                 }
1652             };
1653         }
1654     }
1655
1656     return decode "utf8", $data;
1657 }
1658
1659 sub normalize_username {
1660     my $user = shift;
1661
1662     my ( $username, $service ) = split /\@/, $user, 2;
1663     if ($service) {
1664         $service = ucfirst lc $service;
1665     } else {
1666         $service =
1667           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1668         unless ( exists $twits{"$username\@$service"} ) {
1669             $service = undef;
1670             foreach my $t ( sort keys %twits ) {
1671                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1672                 $service = $1;
1673                 last;
1674             }
1675
1676             unless ($service) {
1677                 &notice("Can't find a logged in user '$user'");
1678             }
1679         }
1680     }
1681
1682     return "$username\@$service";
1683 }
1684
1685 Irssi::signal_add( "send text", "event_send_text" );
1686
1687 Irssi::theme_register(
1688     [
1689         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1690         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1691         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1692         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1693         'twirssi_error',  'ERROR: $0',
1694     ]
1695 );
1696
1697 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1698 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
1699 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
1700 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
1701 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
1702 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
1703 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
1704 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1705 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
1706 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
1707 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1708     'RT $n: "$t" ${-- $c$}' );
1709 Irssi::settings_add_str( "twirssi", "twirssi_location",
1710     ".irssi/scripts/twirssi.pl" );
1711 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1712     ".irssi/scripts/twirssi.json" );
1713
1714 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1715 Irssi::settings_add_int( "twirssi", "twitter_timeout",      30 );
1716
1717 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1718 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1719 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1720 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1721 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1722 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1723 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1724 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1725 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1726 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1727 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1728 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1729 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1730 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl",         0 );
1731
1732 $last_poll = time - &get_poll_time;
1733 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1734 if ( !$window ) {
1735     Irssi::active_win()
1736       ->print( "Couldn't find a window named '"
1737           . Irssi::settings_get_str('twitter_window')
1738           . "', trying to create it." );
1739     $window =
1740       Irssi::Windowitem::window_create(
1741         Irssi::settings_get_str('twitter_window'), 1 );
1742     $window->set_name( Irssi::settings_get_str('twitter_window') );
1743 }
1744
1745 if ($window) {
1746     Irssi::command_bind( "dm",                         "cmd_direct" );
1747     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1748     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1749     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1750     Irssi::command_bind( "retweet",                    "cmd_retweet" );
1751     Irssi::command_bind( "retweet_as",                 "cmd_retweet_as" );
1752     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1753     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1754     Irssi::command_bind( "twitter_login",              "cmd_login" );
1755     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1756     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1757     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1758     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1759     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1760     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1761     Irssi::command_bind( "twitter_updates",            "get_updates" );
1762     Irssi::command_bind( "twitter_add_follow_extra",   "cmd_add_follow" );
1763     Irssi::command_bind( "twitter_del_follow_extra",   "cmd_del_follow" );
1764     Irssi::command_bind( "twitter_list_follow_extra",  "cmd_list_follow" );
1765     Irssi::command_bind( "bitlbee_away",               "update_away" );
1766     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1767         Irssi::command_bind( "reply",    "cmd_reply" );
1768         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1769     }
1770     Irssi::command_bind(
1771         "twirssi_dump",
1772         sub {
1773             print "twits: ", join ", ",
1774               map { "u: $_->{username}\@" . ref($_) } values %twits;
1775             print "selected: $user\@$defservice";
1776             print "friends: ", join ", ", sort keys %friends;
1777             print "nicks: ",   join ", ", sort keys %nicks;
1778             print "searches: ", Dumper \%{ $id_map{__searches} };
1779             print "last poll: $last_poll";
1780             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1781                 print DUMP Dumper \%tweet_cache;
1782                 close DUMP;
1783                 print "cache written out to /tmp/twirssi.cache.txt";
1784             }
1785         }
1786     );
1787     Irssi::command_bind(
1788         "twirssi_version",
1789         sub {
1790             &notice(
1791                 "Twirssi v$VERSION; "
1792                   . (
1793                     $Net::Twitter::VERSION
1794                     ? "Net::Twitter v$Net::Twitter::VERSION. "
1795                     : ""
1796                   )
1797                   . (
1798                     $Net::Identica::VERSION
1799                     ? "Net::Identica v$Net::Identica::VERSION. "
1800                     : ""
1801                   )
1802                   . "JSON in use: "
1803                   . JSON::Any::handler()
1804                   . ".  See details at http://twirssi.com/"
1805             );
1806         }
1807     );
1808     Irssi::command_bind(
1809         "twitter_follow",
1810         &gen_cmd(
1811             "/twitter_follow <username>",
1812             "create_friend",
1813             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1814         )
1815     );
1816     Irssi::command_bind(
1817         "twitter_unfollow",
1818         &gen_cmd(
1819             "/twitter_unfriend <username>",
1820             "destroy_friend",
1821             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1822         )
1823     );
1824     Irssi::command_bind(
1825         "twitter_device_updates",
1826         &gen_cmd(
1827             "/twitter_device_updates none|im|sms",
1828             "update_delivery_device",
1829             sub { &notice("Device updated to $_[0]"); }
1830         )
1831     );
1832     Irssi::command_bind(
1833         "twitter_block",
1834         &gen_cmd(
1835             "/twitter_block <username>",
1836             "create_block",
1837             sub { &notice("Blocked $_[0]"); }
1838         )
1839     );
1840     Irssi::command_bind(
1841         "twitter_unblock",
1842         &gen_cmd(
1843             "/twitter_unblock <username>",
1844             "destroy_block",
1845             sub { &notice("Unblock $_[0]"); }
1846         )
1847     );
1848     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1849
1850     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N");
1851     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1852     &notice(
1853         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1854
1855     my $file = Irssi::settings_get_str("twirssi_replies_store");
1856     if ( $file and -r $file ) {
1857         if ( open( JSON, $file ) ) {
1858             local $/;
1859             my $json = <JSON>;
1860             close JSON;
1861             eval {
1862                 my $ref = JSON::Any->jsonToObj($json);
1863                 %id_map = %$ref;
1864                 my $num = keys %{ $id_map{__indexes} };
1865                 &notice( sprintf "Loaded old replies from %d contact%s.",
1866                     $num, ( $num == 1 ? "" : "s" ) );
1867                 &cmd_list_search;
1868                 &cmd_list_follow;
1869             };
1870         } else {
1871             &notice("Failed to load old replies from $file: $!");
1872         }
1873     }
1874
1875     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1876         &notice("Loading WWW::Shorten::$provider...");
1877         eval "use WWW::Shorten::$provider;";
1878
1879         if ($@) {
1880             &notice(
1881                 "Failed to load WWW::Shorten::$provider - either clear",
1882                 "short_url_provider or install the CPAN module"
1883             );
1884         }
1885     }
1886
1887     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1888         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1889     {
1890         &cmd_login();
1891         &get_updates;
1892     }
1893
1894 } else {
1895     Irssi::active_win()
1896       ->print( "Create a window named "
1897           . Irssi::settings_get_str('twitter_window')
1898           . " or change the value of twitter_window.  Then, reload twirssi." );
1899 }
1900
1901 # vim: set sts=4 expandtab: