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