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