10 use POSIX qw/:sys_wait_h/;
 
  11 use Net::Twitter qw/3.05/;
 
  12 $Data::Dumper::Indent = 1;
 
  14 use vars qw($VERSION %IRSSI);
 
  16 $VERSION = "2.4.1beta";
 
  18     authors     => 'Dan Boger',
 
  19     contact     => 'zigdon@gmail.com',
 
  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',
 
  36 my $last_friends_poll = 0;
 
  44 my %fix_replies_index;
 
  46 my %irssi_to_mirc_colors = (
 
  66     my ( $data, $server, $win ) = @_;
 
  68     return unless &logged_in($twit);
 
  70     my ( $target, $text ) = split ' ', $data, 2;
 
  71     unless ( $target and $text ) {
 
  72         ¬ice("Usage: /dm <nick> <message>");
 
  76     &cmd_direct_as( "$user $data", $server, $win );
 
  80     my ( $data, $server, $win ) = @_;
 
  82     return unless &logged_in($twit);
 
  84     my ( $username, $target, $text ) = split ' ', $data, 3;
 
  85     unless ( $username and $target and $text ) {
 
  86         ¬ice("Usage: /dm_as <username> <nick> <message>");
 
  90     return unless $username = &valid_username($username);
 
  93         if ( $twits{$username}
 
  94             ->new_direct_message( { user => $target, text => $text } ) )
 
  96             ¬ice("DM sent to $target: $text");
 
  97             $nicks{$target} = time;
 
 101                 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
 
 102                 $error = $error->{error};
 
 104             die $error if $error;
 
 105             ¬ice("DM to $target failed");
 
 110         ¬ice("DM caused an error: $@");
 
 116     my ( $data, $server, $win ) = @_;
 
 118     return unless &logged_in($twit);
 
 120     $data =~ s/^\s+|\s+$//;
 
 122         ¬ice("Usage: /retweet <nick[:num]> [comment]");
 
 126     my ( $id, $data ) = split ' ', $data, 2;
 
 128     &cmd_retweet_as( "$user $id $data", $server, $win );
 
 132     my ( $data, $server, $win ) = @_;
 
 134     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
 
 135         ¬ice("twirssi_track_replies is required in order to reteet.");
 
 139     return unless &logged_in($twit);
 
 141     $data =~ s/^\s+|\s+$//;
 
 142     my ( $username, $id, $data ) = split ' ', $data, 3;
 
 145         ¬ice("Usage: /retweet_as <username> <nick[:num]> [comment]");
 
 149     return unless $username = &valid_username($username);
 
 152     $id =~ s/[^\w\d\-:]+//g;
 
 153     ( $nick, $id ) = split /:/, $id;
 
 154     unless ( exists $id_map{ lc $nick } ) {
 
 155         ¬ice("Can't find a tweet from $nick to retweet!");
 
 159     $id = $id_map{__indexes}{$nick} unless $id;
 
 160     unless ( $id_map{ lc $nick }[$id] ) {
 
 161         ¬ice("Can't find a tweet numbered $id from $nick to retweet!");
 
 165     unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
 
 166         ¬ice("The text of this tweet isn't saved, sorry!");
 
 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;
 
 174         $text =~ s/\${|\$}//g;
 
 175         $text =~ s/\$c/$data/;
 
 177         $text =~ s/\${.*?\$}//;
 
 179     $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
 
 181     my $modified = $data;
 
 182     $data = &shorten($text);
 
 184     return if $modified and &too_long($data);
 
 190             $success = $twits{$username}->update(
 
 194                     # in_reply_to_status_id => $id_map{ lc $nick }[$id]
 
 199               $twits{$username}->retweet( { id => $id_map{ lc $nick }[$id] } );
 
 200             $success = $success->{id} if ref $success;
 
 202         ¬ice("Update failed") unless $success;
 
 204     return unless $success;
 
 207         ¬ice("Update caused an error: $@.  Aborted");
 
 211     foreach ( $data =~ /@([-\w]+)/ ) {
 
 215     ¬ice("Retweet sent");
 
 219     my ( $data, $server, $win ) = @_;
 
 221     return unless &logged_in($twit);
 
 223     $data =~ s/^\s+|\s+$//;
 
 225         ¬ice("Usage: /tweet <update>");
 
 229     &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
 
 233     my ( $data, $server, $win ) = @_;
 
 235     return unless &logged_in($twit);
 
 237     $data =~ s/^\s+|\s+$//;
 
 238     $data =~ s/\s\s+/ /g;
 
 239     my ( $username, $data ) = split ' ', $data, 2;
 
 241     unless ( $username and $data ) {
 
 242         ¬ice("Usage: /tweet_as <username> <update>");
 
 246     return unless $username = &valid_username($username);
 
 248     $data = &shorten($data);
 
 250     return if &too_long($data);
 
 254         unless ( $twits{$username}->update($data) )
 
 256             ¬ice("Update failed");
 
 260     return unless $success;
 
 263         ¬ice("Update caused an error: $@.  Aborted.");
 
 267     foreach ( $data =~ /@([-\w]+)/ ) {
 
 271     my $away = &update_away($data);
 
 273     ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
 
 277     my ( $data, $server, $win ) = @_;
 
 279     return unless &logged_in($twit);
 
 281     $data =~ s/^\s+|\s+$//;
 
 283         ¬ice("Usage: /reply <nick[:num]> <update>");
 
 287     my ( $id, $data ) = split ' ', $data, 2;
 
 288     unless ( $id and $data ) {
 
 289         ¬ice("Usage: /reply <nick[:num]> <update>");
 
 293     &cmd_reply_as( "$user $id $data", $server, $win );
 
 297     my ( $data, $server, $win ) = @_;
 
 299     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
 
 300         ¬ice("twirssi_track_replies is required in order to reply to "
 
 301               . "specific tweets.  Either enable it, or just use /tweet "
 
 302               . "\@username <text>." );
 
 306     return unless &logged_in($twit);
 
 308     $data =~ s/^\s+|\s+$//;
 
 309     my ( $username, $id, $data ) = split ' ', $data, 3;
 
 311     unless ( $username and $data ) {
 
 312         ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
 
 316     return unless $username = &valid_username($username);
 
 319     $id =~ s/[^\w\d\-:]+//g;
 
 320     ( $nick, $id ) = split /:/, $id;
 
 321     unless ( exists $id_map{ lc $nick } ) {
 
 322         ¬ice("Can't find a tweet from $nick to reply to!");
 
 326     $id = $id_map{__indexes}{$nick} unless $id;
 
 327     unless ( $id_map{ lc $nick }[$id] ) {
 
 328         ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
 
 332     if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
 
 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;
 
 339     $data = &shorten($data);
 
 341     return if &too_long($data);
 
 346             $twits{$username}->update(
 
 349                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
 
 354             ¬ice("Update failed");
 
 358     return unless $success;
 
 361         ¬ice("Update caused an error: $@.  Aborted");
 
 365     foreach ( $data =~ /@([-\w]+)/ ) {
 
 369     my $away = &update_away($data);
 
 371     ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
 
 375     my ( $usage_str, $api_name, $post_ref ) = @_;
 
 378         my ( $data, $server, $win ) = @_;
 
 380         return unless &logged_in($twit);
 
 382         $data =~ s/^\s+|\s+$//;
 
 384             ¬ice("Usage: $usage_str");
 
 390             unless ( $twit->$api_name($data) )
 
 392                 ¬ice("$api_name failed");
 
 396         return unless $success;
 
 399             ¬ice("$api_name caused an error.  Aborted.");
 
 403         &$post_ref($data) if $post_ref;
 
 408     my ( $data, $server, $win ) = @_;
 
 410     $data =~ s/^\s+|\s+$//g;
 
 411     $data = &normalize_username($data);
 
 412     if ( exists $twits{$data} ) {
 
 413         ¬ice("Switching to $data");
 
 414         $twit = $twits{$data};
 
 415         if ( $data =~ /(.*)\@(.*)/ ) {
 
 419             ¬ice("Couldn't figure out what service '$data' is on");
 
 422         ¬ice("Unknown user $data");
 
 427     my ( $data, $server, $win ) = @_;
 
 429     $data =~ s/^\s+|\s+$//g;
 
 430     $data = $user unless $data;
 
 431     return unless $data = &valid_username($data);
 
 433     ¬ice("Logging out $data...");
 
 434     eval { $twits{$data}->end_session(); };
 
 435     delete $twits{$data};
 
 438         &cmd_switch( ( keys %twits )[0], $server, $win );
 
 440         Irssi::timeout_remove($poll) if $poll;
 
 446     my ( $data, $server, $win ) = @_;
 
 448     print "logging in: $data" if &debug;
 
 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             ¬ice("usage: /twitter_login <username>[\@<service>] <password>");
 
 456     } elsif ( Irssi::settings_get_bool("twirssi_use_oauth")
 
 457         and my $autouser = Irssi::settings_get_str("twitter_usernames") )
 
 459         print "oauth autouser login" if &debug;
 
 460         foreach my $user ( split /,/, $autouser ) {
 
 464     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
 
 465         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
 
 467         print "autouser login" if &debug;
 
 468         my @user = split /\s*,\s*/, $autouser;
 
 469         my @pass = split /\s*,\s*/, $autopass;
 
 471         # if a password ends with a '\', it was meant to escape the comma, and
 
 472         # it should be concatinated with the next one
 
 476             while ( $p =~ /\\$/ and @pass ) {
 
 477                 $p .= "," . shift @pass;
 
 482         if ( @user != @unescaped ) {
 
 483             ¬ice("Number of usernames doesn't match "
 
 484                   . "the number of passwords - auto-login failed" );
 
 487             while ( @user and @unescaped ) {
 
 489                 $p = shift @unescaped;
 
 495         ¬ice("/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 "
 
 502     %friends = %nicks = ();
 
 505     if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
 
 506         ( $user, $service ) = ( $1, $2 );
 
 508         $service = Irssi::settings_get_str("twirssi_default_service");
 
 510     $defservice = $service = ucfirst lc $service;
 
 512     if ( $service eq 'Twitter'
 
 513         and Irssi::settings_get_bool("twirssi_use_oauth") )
 
 515         print "Attempting OAuth for $user\@$service" if &debug;
 
 517             if ( $service eq 'Identica' )
 
 519                 $twit = Net::Twitter->new(
 
 521                     traits   => [ 'API::REST' ],
 
 523                     ssl      => !Irssi::settings_get_bool("twirssi_avoid_ssl"),
 
 526                 $twit = Net::Twitter->new(
 
 527                     traits       => [ 'API::REST', 'OAuth' ],
 
 528                     consumer_key => 'BZVAvBma4GxdiRwXIvbnw',
 
 530                       '0T5kahwLyb34vciGZsgkA9lsjtGCQ05vxVE2APXM',
 
 532                     ssl    => !Irssi::settings_get_bool("twirssi_avoid_ssl"),
 
 538             if ( open( OAUTH, Irssi::settings_get_str("twirssi_oauth_store") ) )
 
 542                     next unless m/$user\@$service (\S+) (\S+)/i;
 
 543                     print "Trying cached oauth creds for $user\@$service"
 
 545                     $twit->access_token($1);
 
 546                     $twit->access_token_secret($2);
 
 552             unless ( $twit->authorized ) {
 
 554                 eval { $url = $twit->get_authorization_url; };
 
 558 "ERROR: Failed to get OAuth authorization_url.  Try again later."
 
 563                 ¬ice("Twirssi not autorized to access $service for $user.");
 
 565                     "Please authorize at the following url, then enter the pin "
 
 567                 ¬ice("supplied with /twirssi_oauth $user\@$service <pin>");
 
 570                 $oauth{pending}{"$user\@$service"} = $twit;
 
 575         $twit = Net::Twitter->new(
 
 576             $service eq 'Identica' ? ( identica => 1 ) : (),
 
 580             ssl      => Irssi::settings_get_bool("twirssi_avoid_ssl") ? 0 : 1,
 
 585         ¬ice("Failed to create object!  Aborting.");
 
 589     return &verify_twitter_object( $server, $win, $user, $service, $twit );
 
 593     my ( $data, $server, $win ) = @_;
 
 594     my ( $key, $pin ) = split ' ', $data;
 
 595     my ( $user, $service );
 
 596     $key = &normalize_username($key);
 
 597     if ( $key =~ /^(.*)@(Twitter|Identica)$/ ) {
 
 598         ( $user, $service ) = ( $1, $2 );
 
 601     print "Applying pin to $key" if &debug;
 
 603     unless ( exists $oauth{pending}{$key} ) {
 
 604         ¬ice("There isn't a pending oauth request for $key. "
 
 605               . "Try /twitter_login first" );
 
 609     my $twit = $oauth{pending}{$key};
 
 610     my ( $access_token, $access_token_secret );
 
 612         ( $access_token, $access_token_secret ) =
 
 613           $twit->request_access_token( verifier => $pin );
 
 617         ¬ice("Invalid pin, try again.");
 
 621     delete $oauth{pending}{$key};
 
 623     my $store_file = Irssi::settings_get_str("twirssi_oauth_store");
 
 626         if ( open( OAUTH, $store_file ) ) {
 
 636         push @store, "$key $access_token $access_token_secret";
 
 638         if ( open( OAUTH, ">$store_file.new" ) ) {
 
 639             print OAUTH "$_\n" foreach @store;
 
 641             rename "$store_file.new", $store_file
 
 642               or ¬ice("Failed to rename $store_file.new: $!");
 
 644             ¬ice("Failed to write $store_file.new: $!");
 
 647         ¬ice("No persistant storage set for OAuth.  "
 
 648               . "Please /set twirssi_oauth_store to a writable filename." );
 
 651     return &verify_twitter_object( $server, $win, $user, $service, $twit );
 
 654 sub verify_twitter_object {
 
 655     my ( $server, $win, $user, $service, $twit ) = @_;
 
 657     if ( my $timeout = Irssi::settings_get_int("twitter_timeout")
 
 658         and $twit->can('ua') )
 
 660         $twit->ua->timeout($timeout);
 
 661         ¬ice("Twitter timeout set to $timeout");
 
 664     unless ( $twit->verify_credentials() ) {
 
 665         ¬ice("Login as $user\@$service failed");
 
 667         if ( not Irssi::settings_get_bool("twirssi_avoid_ssl") ) {
 
 669                 "It's possible you're missing one of the modules required for "
 
 670                   . "SSL logins.  Try setting twirssi_avoid_ssl to on.  See "
 
 671                   . "http://cpansearch.perl.org/src/GAAS/libwww-perl-5.831/README.SSL "
 
 672                   . "for the detailed requirements." );
 
 677             &cmd_switch( ( keys %twits )[0], $server, $win );
 
 682     my $rate_limit = $twit->rate_limit_status();
 
 683     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
 
 685             "Rate limit exceeded, try again after $rate_limit->{reset_time}");
 
 690     print "saving object for $user\@$service" if &debug;
 
 691     $twits{"$user\@$service"} = $twit;
 
 692     Irssi::timeout_remove($poll) if $poll;
 
 693     $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
 
 694     ¬ice("Logged in as $user\@$service, loading friends list...");
 
 696     ¬ice( "loaded friends: ", scalar keys %friends );
 
 697     if ( Irssi::settings_get_bool("twirssi_first_run") ) {
 
 698         Irssi::settings_set_bool( "twirssi_first_run", 0 );
 
 706     my ( $data, $server, $win ) = @_;
 
 709         ¬ice("Usage: /twitter_add_follow_extra <username>");
 
 713     $data =~ s/^\s+|\s+$//;
 
 717     if ( exists $id_map{__fixreplies}{"$user\@$defservice"}{$data} ) {
 
 718         ¬ice("Already following all replies by \@$data");
 
 722     $id_map{__fixreplies}{"$user\@$defservice"}{$data} = 1;
 
 723     ¬ice("Will now follow all replies by \@$data");
 
 727     my ( $data, $server, $win ) = @_;
 
 730         ¬ice("Usage: /twitter_del_follow_extra <username>");
 
 734     $data =~ s/^\s+|\s+$//;
 
 738     unless ( exists $id_map{__fixreplies}{"$user\@$defservice"}{$data} ) {
 
 739         ¬ice("Wasn't following all replies by \@$data");
 
 743     delete $id_map{__fixreplies}{"$user\@$defservice"}{$data};
 
 744     ¬ice("Will no longer follow all replies by \@$data");
 
 747 sub cmd_list_follow {
 
 748     my ( $data, $server, $win ) = @_;
 
 751     foreach my $suser ( sort keys %{ $id_map{__fixreplies} } ) {
 
 753         foreach my $fruser ( sort keys %{ $id_map{__fixreplies}{$suser} } ) {
 
 754             $frusers = $frusers ? "$frusers, $fruser" : $fruser;
 
 758             ¬ice("Following all replies as \@$suser: $frusers");
 
 763         ¬ice("Not following all replies by anyone");
 
 768     my ( $data, $server, $win ) = @_;
 
 770     unless ( $twit and $twit->can('search') ) {
 
 771         ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
 
 772               . "doesn't support searches." );
 
 776     $data =~ s/^\s+|\s+$//;
 
 780         ¬ice("Usage: /twitter_subscribe <topic>");
 
 784     if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
 
 785         ¬ice("Already had a subscription for '$data'");
 
 789     $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
 
 790     ¬ice("Added subscription for '$data'");
 
 794     my ( $data, $server, $win ) = @_;
 
 796     unless ( $twit and $twit->can('search') ) {
 
 797         ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
 
 798               . "doesn't support searches." );
 
 801     $data =~ s/^\s+|\s+$//;
 
 805         ¬ice("Usage: /twitter_unsubscribe <topic>");
 
 809     unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
 
 810         ¬ice("No subscription found for '$data'");
 
 814     delete $id_map{__searches}{"$user\@$defservice"}{$data};
 
 815     ¬ice("Removed subscription for '$data'");
 
 818 sub cmd_list_search {
 
 819     my ( $data, $server, $win ) = @_;
 
 822     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
 
 824         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
 
 825             $topics = $topics ? "$topics, $topic" : $topic;
 
 829             ¬ice("Search subscriptions for \@$suser: $topics");
 
 834         ¬ice("No search subscriptions set up");
 
 839     my ( $data, $server, $win ) = @_;
 
 841     my $loc = Irssi::settings_get_str("twirssi_location");
 
 843         ¬ice("$loc isn't writable, can't upgrade."
 
 844               . "  Perhaps you need to /set twirssi_location?" );
 
 849     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
 
 850         eval { use Digest::MD5; };
 
 853             ¬ice("Failed to load Digest::MD5."
 
 854                   . "  Try '/twirssi_upgrade nomd5' to skip MD5 verification" );
 
 858         $md5 = get("http://twirssi.com/md5sum");
 
 862             ¬ice("Failed to download md5sum from peeron!  Aborting.");
 
 866         unless ( open( CUR, $loc ) ) {
 
 867             ¬ice("Failed to read $loc."
 
 868                   . "  Check that /set twirssi_location is set to the correct location."
 
 873         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
 
 876         if ( $cur_md5 eq $md5 ) {
 
 877             ¬ice("Current twirssi seems to be up to date.");
 
 883       Irssi::settings_get_bool("twirssi_upgrade_beta")
 
 884       ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
 
 885       : "http://twirssi.com/twirssi.pl";
 
 886     ¬ice("Downloading twirssi from $URL");
 
 887     LWP::Simple::getstore( $URL, "$loc.upgrade" );
 
 889     unless ( -s "$loc.upgrade" ) {
 
 890         ¬ice("Failed to save $loc.upgrade."
 
 891               . "  Check that /set twirssi_location is set to the correct location."
 
 896     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
 
 897         unless ( open( NEW, "$loc.upgrade" ) ) {
 
 898             ¬ice("Failed to read $loc.upgrade."
 
 899                   . "  Check that /set twirssi_location is set to the correct location."
 
 904         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
 
 907         if ( $new_md5 ne $md5 ) {
 
 908             ¬ice("MD5 verification failed. expected $md5, got $new_md5");
 
 913     rename $loc, "$loc.backup"
 
 914       or ¬ice("Failed to back up $loc: $!.  Aborting")
 
 916     rename "$loc.upgrade", $loc
 
 917       or ¬ice("Failed to rename $loc.upgrade: $!.  Aborting")
 
 920     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
 
 921     if ( -e "$dir/autorun/$file" ) {
 
 922         ¬ice("Updating $dir/autorun/$file");
 
 923         unlink "$dir/autorun/$file"
 
 924           or ¬ice("Failed to remove old $file from autorun: $!");
 
 925         symlink "../$file", "$dir/autorun/$file"
 
 926           or ¬ice("Failed to create symlink in autorun directory: $!");
 
 929     ¬ice("Download complete.  Reload twirssi with /script load $file");
 
 938         while ( $page < 11 and $cursor ne "0" )
 
 940             print $fh "type:debug Loading friends page $page...\n"
 
 941               if ( $fh and &debug );
 
 943             if ( ref $twit =~ /^Net::Twitter/ ) {
 
 944                 $friends = $twit->friends( { cursor => $cursor } );
 
 945                 last unless $friends;
 
 946                 $cursor  = $friends->{next_cursor};
 
 947                 $friends = $friends->{users};
 
 949                 $friends = $twit->friends( { page => $page } );
 
 950                 last unless $friends;
 
 952             $new_friends{ $_->{screen_name} } = time foreach @$friends;
 
 958         print $fh "type:debug Error during friends list update.  Aborted.\n";
 
 962     my ( $added, $removed ) = ( 0, 0 );
 
 963     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
 
 964     foreach ( keys %new_friends ) {
 
 965         next if exists $friends{$_};
 
 970     print $fh "type:debug Scanning for removed friends...\n"
 
 971       if ( $fh and &debug );
 
 972     foreach ( keys %friends ) {
 
 973         next if exists $new_friends{$_};
 
 978     return ( $added, $removed );
 
 982     print scalar localtime, " - get_updates starting" if &debug;
 
 985       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
 
 988           ->print( "Can't find a window named '"
 
 989               . Irssi::settings_get_str('twitter_window')
 
 990               . "'.  Create it or change the value of twitter_window" );
 
 993     return unless &logged_in($twit);
 
 995     my ( $fh, $filename ) = File::Temp::tempfile();
 
 996     binmode( $fh, ":utf8" );
 
 999     if ($child_pid) {    # parent
 
1000         Irssi::timeout_add_once( 5000, 'monitor_child',
 
1001             [ "$filename.done", 0 ] );
 
1002         Irssi::pidwait_add($child_pid);
 
1003     } elsif ( defined $child_pid ) {    # child
 
1008         my $new_poll = time;
 
1012         foreach ( keys %twits ) {
 
1013             $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
 
1015             if ( $id_map{__fixreplies}{$_} ) {
 
1016                 my @frusers = sort keys %{ $id_map{__fixreplies}{$_} };
 
1019                   unless &get_timeline( $fh, $frusers[ $fix_replies_index{$_} ],
 
1020                     $_, $twits{$_}, \%context_cache );
 
1022                 $fix_replies_index{$_}++;
 
1023                 $fix_replies_index{$_} = 0
 
1024                   if $fix_replies_index{$_} >= @frusers;
 
1025                 print $fh "id:$fix_replies_index{$_} ",
 
1026                   "account:$_ type:fix_replies_index\n";
 
1030         print $fh "__friends__\n";
 
1032             time - $last_friends_poll >
 
1033             Irssi::settings_get_int('twitter_friends_poll') )
 
1035             print $fh "__updated ", time, "\n";
 
1036             my ( $added, $removed ) = &load_friends($fh);
 
1037             if ( $added + $removed ) {
 
1038                 print $fh "type:debug %R***%n Friends list updated: ",
 
1040                     sprintf( "%d added",   $added ),
 
1041                     sprintf( "%d removed", $removed ) ),
 
1046         foreach ( sort keys %friends ) {
 
1047             print $fh "$_ $friends{$_}\n";
 
1051             print $fh "type:debug Update encountered errors.  Aborted\n";
 
1052             print $fh "-- $last_poll";
 
1054             print $fh "-- $new_poll";
 
1057         rename $filename, "$filename.done";
 
1060         &ccrap("Failed to fork for updating: $!");
 
1062     print scalar localtime, " - get_updates ends" if &debug;
 
1066     my ( $fh, $username, $obj, $cache ) = @_;
 
1069         my $rate_limit = $obj->rate_limit_status();
 
1070         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
 
1071             ¬ice("Rate limit exceeded for $username");
 
1076     print scalar localtime, " - Polling for updates for $username" if &debug;
 
1078     my $new_poll_id = 0;
 
1080         if ( $id_map{__last_id}{$username}{timeline} )
 
1082             $tweets = $obj->home_timeline( { count => 100 } );
 
1084             $tweets = $obj->home_timeline();
 
1089         print $fh "type:debug Error during home_timeline call: Aborted.\n";
 
1090         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
 
1094     unless ( ref $tweets ) {
 
1095         if ( $obj->can("get_error") ) {
 
1096             my $error = "Unknown error";
 
1097             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
 
1098             unless ($@) { $error = $obj->get_error() }
 
1100               "type:debug API Error during home_timeline call: Aborted\n";
 
1101             print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
 
1105               "type:debug API Error during home_timeline call. Aborted.\n";
 
1110     foreach my $t ( reverse @$tweets ) {
 
1111         my $text = &get_text( $t, $obj );
 
1112         my $reply = "tweet";
 
1113         if (    Irssi::settings_get_bool("show_reply_context")
 
1114             and $t->{in_reply_to_screen_name} ne $username
 
1115             and $t->{in_reply_to_screen_name}
 
1116             and not exists $friends{ $t->{in_reply_to_screen_name} } )
 
1118             $nicks{ $t->{in_reply_to_screen_name} } = time;
 
1120             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
 
1122                     $cache->{ $t->{in_reply_to_status_id} } =
 
1123                       $obj->show_status( $t->{in_reply_to_status_id} );
 
1127             $context = $cache->{ $t->{in_reply_to_status_id} };
 
1130                 my $ctext = &get_text( $context, $obj );
 
1131                 printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
 
1132                   $context->{id}, $username,
 
1133                   $context->{user}{screen_name}, $ctext;
 
1138           if $t->{user}{screen_name} eq $username
 
1139               and not Irssi::settings_get_bool("show_own_tweets");
 
1140         printf $fh "id:%s account:%s nick:%s type:%s %s\n",
 
1141           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
 
1142         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
 
1144     printf $fh "id:%s account:%s type:last_id timeline\n",
 
1145       $new_poll_id, $username;
 
1147     print scalar localtime, " - Polling for replies since ",
 
1148       $id_map{__last_id}{$username}{reply}
 
1152         if ( $id_map{__last_id}{$username}{reply} )
 
1154             $tweets = $obj->replies(
 
1155                 { since_id => $id_map{__last_id}{$username}{reply} } )
 
1158             $tweets = $obj->replies() || [];
 
1163         print $fh "type:debug Error during replies call.  Aborted.\n";
 
1167     foreach my $t ( reverse @$tweets ) {
 
1169           if exists $friends{ $t->{user}{screen_name} };
 
1171         my $text = &get_text( $t, $obj );
 
1172         printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
 
1173           $t->{id}, $username, $t->{user}{screen_name}, $text;
 
1174         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
 
1176     printf $fh "id:%s account:%s type:last_id reply\n", $new_poll_id, $username;
 
1178     print scalar localtime, " - Polling for DMs" if &debug;
 
1181         if ( $id_map{__last_id}{$username}{dm} )
 
1183             $tweets = $obj->direct_messages(
 
1184                 { since_id => $id_map{__last_id}{$username}{dm} } )
 
1187             $tweets = $obj->direct_messages() || [];
 
1192         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
 
1196     foreach my $t ( reverse @$tweets ) {
 
1197         my $text = decode_entities( $t->{text} );
 
1198         $text =~ s/[\n\r]/ /g;
 
1199         printf $fh "id:%s account:%s nick:%s type:dm %s\n",
 
1200           $t->{id}, $username, $t->{sender_screen_name}, $text;
 
1201         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
 
1203     printf $fh "id:%s account:%s type:last_id dm\n", $new_poll_id, $username;
 
1205     print scalar localtime, " - Polling for subscriptions" if &debug;
 
1206     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
 
1208         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
 
1209             print $fh "type:debug searching for $topic since ",
 
1210               "$id_map{__searches}{$username}{$topic}\n";
 
1212                 $search = $obj->search(
 
1215                         since_id => $id_map{__searches}{$username}{$topic}
 
1222                   "type:debug Error during search($topic) call.  Aborted.\n";
 
1226             unless ( $search->{max_id} ) {
 
1227                 print $fh "type:debug Invalid search results when searching",
 
1228                   " for $topic. Aborted.\n";
 
1232             $id_map{__searches}{$username}{$topic} = $search->{max_id};
 
1233             printf $fh "id:%s account:%s type:searchid topic:%s\n",
 
1234               $search->{max_id}, $username, $topic;
 
1236             foreach my $t ( reverse @{ $search->{results} } ) {
 
1237                 my $text = &get_text( $t, $obj );
 
1238                 printf $fh "id:%s account:%s nick:%s type:search topic:%s %s\n",
 
1239                   $t->{id}, $username, $t->{from_user}, $topic, $text;
 
1240                 $new_poll_id = $t->{id}
 
1242                       or $t->{id} < $new_poll_id;
 
1247     print scalar localtime, " - Done" if &debug;
 
1253     my ( $fh, $target, $username, $obj, $cache ) = @_;
 
1255     my $last_id = $id_map{__last_id}{$username}{$target};
 
1257     print $fh "type:debug get_timeline("
 
1258       . "$fix_replies_index{$username}=$target > $last_id) started."
 
1259       . "  username = $username\n";
 
1261         $tweets = $obj->user_timeline(
 
1264                 ( $last_id ? ( since_id => $last_id ) : () ),
 
1271           "type:debug Error during user_timeline($target) call: Aborted.\n";
 
1272         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
 
1278           "type:debug user_timeline($target) call returned undef!  Aborted\n";
 
1282     foreach my $t ( reverse @$tweets ) {
 
1283         my $text = &get_text( $t, $obj );
 
1284         my $reply = "tweet";
 
1285         if (    Irssi::settings_get_bool("show_reply_context")
 
1286             and $t->{in_reply_to_screen_name} ne $username
 
1287             and $t->{in_reply_to_screen_name}
 
1288             and not exists $friends{ $t->{in_reply_to_screen_name} } )
 
1290             $nicks{ $t->{in_reply_to_screen_name} } = time;
 
1292             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
 
1294                     $cache->{ $t->{in_reply_to_status_id} } =
 
1295                       $obj->show_status( $t->{in_reply_to_status_id} );
 
1299             $context = $cache->{ $t->{in_reply_to_status_id} };
 
1302                 my $ctext = &get_text( $context, $obj );
 
1303                 printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
 
1304                   $context->{id}, $username,
 
1305                   $context->{user}{screen_name}, $ctext;
 
1309         printf $fh "id:%s account:%s nick:%s type:%s %s\n",
 
1310           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
 
1311         $last_id = $t->{id} if $last_id < $t->{id};
 
1313     printf $fh "id:%s account:%s type:last_id_fixreplies %s\n",
 
1314       $last_id, $username, $target;
 
1321     my $filename = $data->[0];
 
1322     my $attempt  = $data->[1];
 
1324     print scalar localtime, " - checking child log at $filename ($attempt)"
 
1326     my ($new_last_poll);
 
1328     # reap any random leftover processes - work around a bug in irssi on gentoo
 
1329     waitpid( -1, WNOHANG );
 
1331     # first time we run we don't want to print out *everything*, so we just
 
1334     if ( open FILE, $filename ) {
 
1335         binmode FILE, ":utf8";
 
1339             last if /^__friends__/;
 
1340             unless (/\n$/) {    # skip partial lines
 
1341                                 # print "Skipping partial line: $_" if &debug;
 
1348             foreach my $key (qw/id account nick type topic/) {
 
1349                 if (s/^$key:(\S+)\s*//) {
 
1354             if ( $meta{type} and $meta{type} eq 'fix_replies_index' ) {
 
1355                 $fix_replies_index{ $meta{account} } = $meta{id};
 
1356                 print "fix_replies_index for $meta{account} set to $meta{id}"
 
1361             if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
 
1362                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
 
1366                 $new_cache{ $meta{id} } = time;
 
1368                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
 
1374             $meta{account} =~ s/\@(\w+)$//;
 
1375             $meta{service} = $1;
 
1377                 lc $meta{service} eq
 
1378                 lc Irssi::settings_get_str("twirssi_default_service") )
 
1380                 $account = "$meta{account}: "
 
1381                   if lc "$meta{account}\@$meta{service}" ne lc
 
1382                       "$user\@$defservice";
 
1384                 $account = "$meta{account}\@$meta{service}: ";
 
1388             if (    $meta{type} ne 'dm'
 
1389                 and Irssi::settings_get_bool("twirssi_track_replies")
 
1393                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
 
1394                 $id_map{ lc $meta{nick} }[$marker]           = $meta{id};
 
1395                 $id_map{__indexes}{ $meta{nick} }            = $marker;
 
1396                 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
 
1397                 $marker                                      = ":$marker";
 
1401               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
 
1402             my $nick = "\@$meta{account}";
 
1403             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
 
1404                 and Irssi::settings_get_bool("twirssi_hilights") )
 
1406                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
 
1407                 $hilight = MSGLEVEL_HILIGHT;
 
1410             if ( $meta{type} =~ /tweet|reply/ ) {
 
1413                     ( MSGLEVEL_PUBLIC | $hilight ),
 
1414                     $meta{type}, $account, $meta{nick}, $marker, $_
 
1416             } elsif ( $meta{type} eq 'search' ) {
 
1419                     ( MSGLEVEL_PUBLIC | $hilight ),
 
1420                     $meta{type}, $account, $meta{topic},
 
1421                     $meta{nick}, $marker,  $_
 
1424                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
 
1426                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
 
1428                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
 
1431             } elsif ( $meta{type} eq 'dm' ) {
 
1434                     ( MSGLEVEL_MSGS | $hilight ),
 
1435                     $meta{type}, $account, $meta{nick}, $_
 
1437             } elsif ( $meta{type} eq 'searchid' ) {
 
1438                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
 
1441                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
 
1443                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
 
1445                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
 
1448                     print "Search '$meta{topic}' returned invalid id $meta{id}";
 
1450             } elsif ( $meta{type} eq 'last_id' ) {
 
1451                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
 
1453                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
 
1455             } elsif ( $meta{type} eq 'last_id_fixreplies' ) {
 
1456                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
 
1458                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
 
1460             } elsif ( $meta{type} eq 'error' ) {
 
1461                 push @lines, [ MSGLEVEL_MSGS, $_ ];
 
1462             } elsif ( $meta{type} eq 'debug' ) {
 
1463                 print "$_" if &debug,;
 
1465                 print "Unknown line type $meta{type}: $_" if &debug,;
 
1471             if (/^__updated (\d+)$/) {
 
1472                 $last_friends_poll = $1;
 
1473                 print "Friend list updated" if &debug;
 
1478                 $new_last_poll = $1;
 
1479                 if ( $new_last_poll >= $last_poll ) {
 
1482                     print "Impossible!  ",
 
1483                       "new_last_poll=$new_last_poll < last_poll=$last_poll!"
 
1485                     undef $new_last_poll;
 
1489             my ( $f, $t ) = split ' ', $_;
 
1490             $nicks{$f} = $friends{$f} = $t;
 
1493         if ($new_last_poll) {
 
1494             print "new last_poll    = $new_last_poll" if &debug;
 
1495             print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
 
1497                 print "First call, not printing updates" if &debug;
 
1499                 foreach my $line (@lines) {
 
1500                     $window->printformat(
 
1502                         "twirssi_" . $line->[1],
 
1503                         @$line[ 2 .. $#$line - 1 ],
 
1504                         &hilight( $line->[-1] )
 
1511               or warn "Failed to remove $filename: $!"
 
1514             # commit the pending cache lines to the actual cache, now that
 
1515             # we've printed our output
 
1516             %tweet_cache = ( %tweet_cache, %new_cache );
 
1518             # keep enough cached tweets, to make sure we don't show duplicates.
 
1519             foreach ( keys %tweet_cache ) {
 
1520                 next if $tweet_cache{$_} >= $last_poll - 3600;
 
1521                 delete $tweet_cache{$_};
 
1523             $last_poll = $new_last_poll;
 
1525             # make sure the pid is removed from the waitpid list
 
1526             Irssi::pidwait_remove($child_pid);
 
1528             # and that we don't leave any zombies behind, somehow
 
1534                 Irssi::settings_get_str("twirssi_replies_store") )
 
1536                 if ( open JSON, ">$file" ) {
 
1537                     print JSON JSON::Any->objToJson( \%id_map );
 
1540                     &ccrap("Failed to write replies to $file: $!");
 
1551     if ( $attempt < 24 ) {
 
1552         Irssi::timeout_add_once( 5000, 'monitor_child',
 
1553             [ $filename, $attempt + 1 ] );
 
1555         print "Giving up on polling $filename" if &debug;
 
1556         Irssi::pidwait_remove($child_pid);
 
1558         unlink $filename unless &debug;
 
1560         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
 
1563         my @time = localtime($last_poll);
 
1564         if ( time - $last_poll < 24 * 60 * 60 ) {
 
1565             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
 
1567             $since = scalar localtime($last_poll);
 
1570         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
 
1575                 q{  .--./ /  |  _.---.| },
 
1587         if ( time - $last_poll < 600 ) {
 
1588             &ccrap("Haven't been able to get updated tweets since $since");
 
1594     return Irssi::settings_get_bool("twirssi_debug");
 
1598     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
 
1602     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
 
1608     if (    Irssi::settings_get_bool("tweet_to_away")
 
1610         and $data !~ /^[dD] / )
 
1613           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
 
1615             $server->send_raw("away :$data");
 
1618             &ccrap( "Can't find bitlbee server.",
 
1619                 "Update bitlbee_server or disable tweet_to_away" );
 
1629     my $noalert = shift;
 
1631     if ( length $data > 140 ) {
 
1632         ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
 
1640 sub valid_username {
 
1641     my $username = shift;
 
1643     $username = &normalize_username($username);
 
1645     unless ( exists $twits{$username} ) {
 
1646         ¬ice("Unknown username $username");
 
1656         ¬ice("Not logged in!  Use /twitter_login username pass!");
 
1664     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
 
1667         $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
 
1668         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
 
1669             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
 
1671     {    # /twitter_reply gets a nick:num
 
1673         @$complist = map { "$_:$id_map{__indexes}{$_}" }
 
1674           sort { $nicks{$b} <=> $nicks{$a} }
 
1676           keys %{ $id_map{__indexes} };
 
1680 /^\/(twitter_unfriend|twitter_add_follow_extra|twitter_del_follow_extra)\s*$/
 
1682     {    # /twitter_unfriend gets a nick
 
1684         push @$complist, grep /^\Q$word/i,
 
1685           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
 
1688     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
 
1690     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
 
1691         my $prefix = $word =~ s/^@//;
 
1692         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
 
1693         push @$complist, grep /^\Q$word/i,
 
1694           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
 
1695         @$complist = map { "\@$_" } @$complist if $prefix;
 
1699 sub event_send_text {
 
1700     my ( $line, $server, $win ) = @_;
 
1701     my $awin = Irssi::active_win();
 
1703     # if the window where we got our text was the twitter window, and the user
 
1704     # wants to be lazy, tweet away!
 
1705     if ( ( $awin->get_active_name() eq $window->{name} )
 
1706         and Irssi::settings_get_bool("tweet_window_input") )
 
1708         &cmd_tweet( $line, $server, $win );
 
1713     my $poll = Irssi::settings_get_int("twitter_poll_interval");
 
1714     return $poll if $poll >= 60;
 
1721     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
 
1722         my $c = Irssi::settings_get_str("twirssi_nick_color");
 
1723         $c = $irssi_to_mirc_colors{$c};
 
1724         $text =~ s/(^|\W)\@(\w+)/$1\cC$c\@$2\cO/g if $c;
 
1726     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
 
1727         my $c = Irssi::settings_get_str("twirssi_topic_color");
 
1728         $c = $irssi_to_mirc_colors{$c};
 
1729         $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
 
1731     $text =~ s/[\n\r]/ /g;
 
1739     my $provider = Irssi::settings_get_str("short_url_provider");
 
1742             Irssi::settings_get_bool("twirssi_always_shorten")
 
1743             or &too_long( $data, 1 )
 
1749         if ( $provider eq 'Bitly' ) {
 
1750             @args[ 1, 2 ] = split ',',
 
1751               Irssi::settings_get_str("short_url_args"), 2;
 
1752             unless ( @args == 3 ) {
 
1754                     "WWW::Shorten::Bitly requires a username and API key.",
 
1755                     "Set short_url_args to username,API_key or change your",
 
1756                     "short_url_provider."
 
1758                 return decode "utf8", $data;
 
1762         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
 
1765                 my $short = makeashorterlink(@args);
 
1767                     $data =~ s/\Q$url/$short/g;
 
1769                     ¬ice("Failed to shorten $url!");
 
1775     return decode "utf8", $data;
 
1778 sub normalize_username {
 
1781     my ( $username, $service ) = split /\@/, $user, 2;
 
1783         $service = ucfirst lc $service;
 
1786           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
 
1787         unless ( exists $twits{"$username\@$service"} ) {
 
1789             foreach my $t ( sort keys %twits ) {
 
1790                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
 
1796                 ¬ice("Can't find a logged in user '$user'");
 
1801     return "$username\@$service";
 
1807     my $text   = decode_entities( $tweet->{text} );
 
1808     if ( $tweet->{truncated} ) {
 
1809         if ( exists $tweet->{retweeted_status} ) {
 
1810             $text = "RT \@$tweet->{retweeted_status}{user}{screen_name}: "
 
1811               . "$tweet->{retweeted_status}{text}";
 
1812         } elsif ( $object->isa('Net::Twitter') ) {
 
1813             $text .= " -- http://twitter.com/$tweet->{user}{screen_name}"
 
1814               . "/status/$tweet->{id}";
 
1818     $text =~ s/[\n\r]/ /g;
 
1823 Irssi::signal_add( "send text", "event_send_text" );
 
1825 Irssi::theme_register(
 
1827         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
 
1828         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
 
1829         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
 
1830         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
 
1831         'twirssi_error',  'ERROR: $0',
 
1835 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
 
1836 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
 
1837 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
 
1838 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
 
1839 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
 
1840 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
 
1841 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
 
1842 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
 
1843 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
 
1844 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
 
1845 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
 
1846     'RT $n: "$t" ${-- $c$}' );
 
1847 Irssi::settings_add_str( "twirssi", "twirssi_location",
 
1848     "$ENV{HOME}/.irssi/scripts/twirssi.pl" );
 
1849 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
 
1850     "$ENV{HOME}/.irssi/scripts/twirssi.json" );
 
1851 Irssi::settings_add_str( "twirssi", "twirssi_oauth_store",
 
1852     "$ENV{HOME}/.irssi/scripts/twirssi.oauth" );
 
1854 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
 
1855 Irssi::settings_add_int( "twirssi", "twitter_timeout",      30 );
 
1857 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
 
1858 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
 
1859 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
 
1860 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
 
1861 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
 
1862 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
 
1863 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
 
1864 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
 
1865 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
 
1866 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
 
1867 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
 
1868 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
 
1869 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
 
1870 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl",         0 );
 
1871 Irssi::settings_add_bool( "twirssi", "twirssi_use_oauth",         1 );
 
1873 $last_poll = time - &get_poll_time;
 
1874 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
 
1877       ->print( "Couldn't find a window named '"
 
1878           . Irssi::settings_get_str('twitter_window')
 
1879           . "', trying to create it." );
 
1881       Irssi::Windowitem::window_create(
 
1882         Irssi::settings_get_str('twitter_window'), 1 );
 
1883     $window->set_name( Irssi::settings_get_str('twitter_window') );
 
1887     Irssi::command_bind( "dm",                         "cmd_direct" );
 
1888     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
 
1889     Irssi::command_bind( "tweet",                      "cmd_tweet" );
 
1890     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
 
1891     Irssi::command_bind( "retweet",                    "cmd_retweet" );
 
1892     Irssi::command_bind( "retweet_as",                 "cmd_retweet_as" );
 
1893     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
 
1894     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
 
1895     Irssi::command_bind( "twitter_login",              "cmd_login" );
 
1896     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
 
1897     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
 
1898     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
 
1899     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
 
1900     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
 
1901     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
 
1902     Irssi::command_bind( "twirssi_oauth",              "cmd_oauth" );
 
1903     Irssi::command_bind( "twitter_updates",            "get_updates" );
 
1904     Irssi::command_bind( "twitter_add_follow_extra",   "cmd_add_follow" );
 
1905     Irssi::command_bind( "twitter_del_follow_extra",   "cmd_del_follow" );
 
1906     Irssi::command_bind( "twitter_list_follow_extra",  "cmd_list_follow" );
 
1907     Irssi::command_bind( "bitlbee_away",               "update_away" );
 
1908     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
 
1909         Irssi::command_bind( "reply",    "cmd_reply" );
 
1910         Irssi::command_bind( "reply_as", "cmd_reply_as" );
 
1912     Irssi::command_bind(
 
1915             print "twits: ", join ", ",
 
1916               map { "u: $_->{username}\@" . ref($_) } values %twits;
 
1917             print "selected: $user\@$defservice";
 
1918             print "friends: ", join ", ", sort keys %friends;
 
1919             print "nicks: ",   join ", ", sort keys %nicks;
 
1920             print "searches: ", Dumper \%{ $id_map{__searches} };
 
1921             print "last poll: $last_poll";
 
1922             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
 
1923                 print DUMP Dumper \%tweet_cache;
 
1925                 print "cache written out to /tmp/twirssi.cache.txt";
 
1929     Irssi::command_bind(
 
1933                 "Twirssi v$VERSION; "
 
1935                     $Net::Twitter::VERSION
 
1936                     ? "Net::Twitter v$Net::Twitter::VERSION. "
 
1940                     $Net::Identica::VERSION
 
1941                     ? "Net::Identica v$Net::Identica::VERSION. "
 
1945                   . JSON::Any::handler()
 
1946                   . ".  See details at http://twirssi.com/"
 
1950     Irssi::command_bind(
 
1953             "/twitter_follow <username>",
 
1955             sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
 
1958     Irssi::command_bind(
 
1961             "/twitter_unfriend <username>",
 
1963             sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
 
1966     Irssi::command_bind(
 
1967         "twitter_device_updates",
 
1969             "/twitter_device_updates none|im|sms",
 
1970             "update_delivery_device",
 
1971             sub { ¬ice("Device updated to $_[0]"); }
 
1974     Irssi::command_bind(
 
1977             "/twitter_block <username>",
 
1979             sub { ¬ice("Blocked $_[0]"); }
 
1982     Irssi::command_bind(
 
1985             "/twitter_unblock <username>",
 
1987             sub { ¬ice("Unblock $_[0]"); }
 
1990     Irssi::signal_add_last( 'complete word' => \&sig_complete );
 
1992     ¬ice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N");
 
1993     ¬ice("   %C(_(\\%N           http://twirssi.com/ for full docs");
 
1995         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
 
1997     my $file = Irssi::settings_get_str("twirssi_replies_store");
 
1998     if ( $file and -r $file ) {
 
1999         if ( open( JSON, $file ) ) {
 
2004                 my $ref = JSON::Any->jsonToObj($json);
 
2006                 my $num = keys %{ $id_map{__indexes} };
 
2007                 ¬ice( sprintf "Loaded old replies from %d contact%s.",
 
2008                     $num, ( $num == 1 ? "" : "s" ) );
 
2013             ¬ice("Failed to load old replies from $file: $!");
 
2017     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
 
2018         ¬ice("Loading WWW::Shorten::$provider...");
 
2019         eval "use WWW::Shorten::$provider;";
 
2023                 "Failed to load WWW::Shorten::$provider - either clear",
 
2024                 "short_url_provider or install the CPAN module"
 
2029     if ( my $autouser = Irssi::settings_get_str("twitter_usernames") ) {
 
2036       ->print( "Create a window named "
 
2037           . Irssi::settings_get_str('twitter_window')
 
2038           . " or change the value of twitter_window.  Then, reload twirssi." );
 
2041 # vim: set sts=4 expandtab: