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