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