10 $Data::Dumper::Indent = 1;
 
  12 use vars qw($VERSION %IRSSI);
 
  14 $VERSION = "2.2.5beta";
 
  15 my ($REV) = '$Rev: 687 $' =~ /(\d+)/;
 
  17     authors     => 'Dan Boger',
 
  18     contact     => 'zigdon@gmail.com',
 
  20     description => 'Send twitter updates using /tweet.  '
 
  21       . 'Can optionally set your bitlbee /away message to same',
 
  22     license => 'GNU GPL v2',
 
  23     url     => 'http://twirssi.com',
 
  24     changed => '$Date: 2009-08-07 01:24:53 -0700 (Fri, 07 Aug 2009) $',
 
  34 my $last_friends_poll = 0;
 
  42 my %irssi_to_mirc_colors = (
 
  62     my ( $data, $server, $win ) = @_;
 
  64     return unless &logged_in($twit);
 
  66     my ( $target, $text ) = split ' ', $data, 2;
 
  67     unless ( $target and $text ) {
 
  68         ¬ice("Usage: /dm <nick> <message>");
 
  72     &cmd_direct_as( "$user $data", $server, $win );
 
  76     my ( $data, $server, $win ) = @_;
 
  78     return unless &logged_in($twit);
 
  80     my ( $username, $target, $text ) = split ' ', $data, 3;
 
  81     unless ( $username and $target and $text ) {
 
  82         ¬ice("Usage: /dm_as <username> <nick> <message>");
 
  86     return unless $username = &valid_username($username);
 
  89         if ( $twits{$username}
 
  90             ->new_direct_message( { user => $target, text => $text } ) )
 
  92             ¬ice("DM sent to $target");
 
  93             $nicks{$target} = time;
 
  97                 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
 
  98                 $error = $error->{error};
 
 100             die $error if $error;
 
 101             ¬ice("DM to $target failed");
 
 106         ¬ice("DM caused an error: $@");
 
 112     my ( $data, $server, $win ) = @_;
 
 114     return unless &logged_in($twit);
 
 116     $data =~ s/^\s+|\s+$//;
 
 118         ¬ice("Usage: /retweet <nick[:num]> [comment]");
 
 122     my ( $id, $data ) = split ' ', $data, 2;
 
 124     &cmd_retweet_as( "$user $id $data", $server, $win );
 
 128     my ( $data, $server, $win ) = @_;
 
 130     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
 
 131         ¬ice("twirssi_track_replies is required in order to reteet.");
 
 135     return unless &logged_in($twit);
 
 137     $data =~ s/^\s+|\s+$//;
 
 138     my ( $username, $id, $data ) = split ' ', $data, 3;
 
 141         ¬ice("Usage: /retweet_as <username> <nick[:num]> [comment]");
 
 145     return unless $username = &valid_username($username);
 
 148     $id =~ s/[^\w\d\-:]+//g;
 
 149     ( $nick, $id ) = split /:/, $id;
 
 150     unless ( exists $id_map{ lc $nick } ) {
 
 151         ¬ice("Can't find a tweet from $nick to retweet!");
 
 155     $id = $id_map{__indexes}{$nick} unless $id;
 
 156     unless ( $id_map{ lc $nick }[$id] ) {
 
 157         ¬ice("Can't find a tweet numbered $id from $nick to retweet!");
 
 161     unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
 
 162         ¬ice("The text of this tweet isn't saved, sorry!");
 
 166 # Irssi::settings_add_str( "twirssi", "twirssi_retweet_format", 'RT $n: $t ${-- $c$}' );
 
 167     my $text = Irssi::settings_get_str("twirssi_retweet_format");
 
 168     $text =~ s/\$n/\@$nick/g;
 
 170         $text =~ s/\${|\$}//g;
 
 171         $text =~ s/\$c/$data/;
 
 173         $text =~ s/\${.*?\$}//;
 
 175     $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
 
 177     $data = &shorten($text);
 
 179     return if &too_long($data);
 
 184             $twits{$username}->update(
 
 188                     # in_reply_to_status_id => $id_map{ lc $nick }[$id]
 
 193             ¬ice("Update failed");
 
 197     return unless $success;
 
 200         ¬ice("Update caused an error: $@.  Aborted");
 
 204     foreach ( $data =~ /@([-\w]+)/ ) {
 
 208     ¬ice("Retweet sent");
 
 212     my ( $data, $server, $win ) = @_;
 
 214     return unless &logged_in($twit);
 
 216     $data =~ s/^\s+|\s+$//;
 
 218         ¬ice("Usage: /tweet <update>");
 
 222     &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
 
 226     my ( $data, $server, $win ) = @_;
 
 228     return unless &logged_in($twit);
 
 230     $data =~ s/^\s+|\s+$//;
 
 231     $data =~ s/\s\s+/ /g;
 
 232     my ( $username, $data ) = split ' ', $data, 2;
 
 234     unless ( $username and $data ) {
 
 235         ¬ice("Usage: /tweet_as <username> <update>");
 
 239     return unless $username = &valid_username($username);
 
 241     $data = &shorten($data);
 
 243     return if &too_long($data);
 
 247         unless ( $twits{$username}->update($data) )
 
 249             ¬ice("Update failed");
 
 253     return unless $success;
 
 256         ¬ice("Update caused an error: $@.  Aborted.");
 
 260     foreach ( $data =~ /@([-\w]+)/ ) {
 
 264     my $away = &update_away($data);
 
 266     ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
 
 270     my ( $data, $server, $win ) = @_;
 
 272     return unless &logged_in($twit);
 
 274     $data =~ s/^\s+|\s+$//;
 
 276         ¬ice("Usage: /reply <nick[:num]> <update>");
 
 280     my ( $id, $data ) = split ' ', $data, 2;
 
 281     unless ( $id and $data ) {
 
 282         ¬ice("Usage: /reply <nick[:num]> <update>");
 
 286     &cmd_reply_as( "$user $id $data", $server, $win );
 
 290     my ( $data, $server, $win ) = @_;
 
 292     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
 
 293         ¬ice("twirssi_track_replies is required in order to reply to "
 
 294               . "specific tweets.  Either enable it, or just use /tweet "
 
 295               . "\@username <text>." );
 
 299     return unless &logged_in($twit);
 
 301     $data =~ s/^\s+|\s+$//;
 
 302     my ( $username, $id, $data ) = split ' ', $data, 3;
 
 304     unless ( $username and $data ) {
 
 305         ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
 
 309     return unless $username = &valid_username($username);
 
 312     $id =~ s/[^\w\d\-:]+//g;
 
 313     ( $nick, $id ) = split /:/, $id;
 
 314     unless ( exists $id_map{ lc $nick } ) {
 
 315         ¬ice("Can't find a tweet from $nick to reply to!");
 
 319     $id = $id_map{__indexes}{$nick} unless $id;
 
 320     unless ( $id_map{ lc $nick }[$id] ) {
 
 321         ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
 
 325     if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
 
 327         # remove any @nick at the beginning of the reply, as we'll add it anyway
 
 328         $data =~ s/^\s*\@?$nick\s*//;
 
 329         $data = "\@$nick " . $data;
 
 332     $data = &shorten($data);
 
 334     return if &too_long($data);
 
 339             $twits{$username}->update(
 
 342                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
 
 347             ¬ice("Update failed");
 
 351     return unless $success;
 
 354         ¬ice("Update caused an error: $@.  Aborted");
 
 358     foreach ( $data =~ /@([-\w]+)/ ) {
 
 362     my $away = &update_away($data);
 
 364     ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
 
 368     my ( $usage_str, $api_name, $post_ref ) = @_;
 
 371         my ( $data, $server, $win ) = @_;
 
 373         return unless &logged_in($twit);
 
 375         $data =~ s/^\s+|\s+$//;
 
 377             ¬ice("Usage: $usage_str");
 
 383             unless ( $twit->$api_name($data) )
 
 385                 ¬ice("$api_name failed");
 
 389         return unless $success;
 
 392             ¬ice("$api_name caused an error.  Aborted.");
 
 396         &$post_ref($data) if $post_ref;
 
 401     my ( $data, $server, $win ) = @_;
 
 403     $data =~ s/^\s+|\s+$//g;
 
 404     $data = &normalize_username($data);
 
 405     if ( exists $twits{$data} ) {
 
 406         ¬ice("Switching to $data");
 
 407         $twit = $twits{$data};
 
 408         if ( $data =~ /(.*)\@(.*)/ ) {
 
 412             ¬ice("Couldn't figure out what service '$data' is on");
 
 415         ¬ice("Unknown user $data");
 
 420     my ( $data, $server, $win ) = @_;
 
 422     $data =~ s/^\s+|\s+$//g;
 
 423     $data = $user unless $data;
 
 424     return unless $data = &valid_username($data);
 
 426     ¬ice("Logging out $data...");
 
 427     $twits{$data}->end_session();
 
 428     delete $twits{$data};
 
 431         &cmd_switch( ( keys %twits )[0], $server, $win );
 
 433         Irssi::timeout_remove($poll) if $poll;
 
 439     my ( $data, $server, $win ) = @_;
 
 442         ( $user, $pass ) = split ' ', $data, 2;
 
 443     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
 
 444         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
 
 446         my @user = split /\s*,\s*/, $autouser;
 
 447         my @pass = split /\s*,\s*/, $autopass;
 
 449         # if a password ends with a '\', it was meant to escape the comma, and
 
 450         # it should be concatinated with the next one
 
 454             while ( $p =~ /\\$/ and @pass ) {
 
 455                 $p .= "," . shift @pass;
 
 460         if ( @user != @unescaped ) {
 
 461             ¬ice("Number of usernames doesn't match "
 
 462                   . "the number of passwords - auto-login failed" );
 
 465             while ( @user and @unescaped ) {
 
 467                 $p = shift @unescaped;
 
 473         ¬ice("/twitter_login requires either a username and password "
 
 474               . "or twitter_usernames and twitter_passwords to be set." );
 
 478     %friends = %nicks = ();
 
 481     if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
 
 482         ( $user, $service ) = ( $1, $2 );
 
 484         $service = Irssi::settings_get_str("twirssi_default_service");
 
 486     $defservice = $service = ucfirst lc $service;
 
 488     eval "use Net::$service";
 
 491             "Failed to load Net::$service when trying to log in as $user: $@");
 
 495     $twit = "Net::$service"->new(
 
 499         ssl      => Irssi::settings_get_bool("twirssi_avoid_ssl") ? 0 : 1,
 
 503         ¬ice("Failed to create Net::$service object!  Aborting.");
 
 507     if ( my $timeout = Irssi::settings_get_int("twitter_timeout") ) {
 
 508         $twit->ua->timeout($timeout);
 
 511     unless ( $twit->verify_credentials() ) {
 
 512         ¬ice("Login as $user\@$service failed");
 
 515             &cmd_switch( ( keys %twits )[0], $server, $win );
 
 521         my $rate_limit = $twit->rate_limit_status();
 
 522         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
 
 524                 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
 
 530         $twits{"$user\@$service"} = $twit;
 
 531         Irssi::timeout_remove($poll) if $poll;
 
 532         $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
 
 533         ¬ice("Logged in as $user\@$service, loading friends list...");
 
 535         ¬ice( "loaded friends: ", scalar keys %friends );
 
 536         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
 
 537             Irssi::settings_set_bool( "twirssi_first_run", 0 );
 
 538             unless ( exists $friends{twirssi} ) {
 
 539                 ¬ice("Welcome to twirssi!"
 
 540                       . "  Perhaps you should add \@twirssi to your friends list,"
 
 541                       . " so you can be notified when a new version is release?"
 
 542                       . "  Just type /twitter_follow twirssi." );
 
 549         ¬ice("Login failed");
 
 554     my ( $data, $server, $win ) = @_;
 
 556     unless ( $twit and $twit->can('search') ) {
 
 557         ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
 
 558               . "doesn't support searches." );
 
 562     $data =~ s/^\s+|\s+$//;
 
 566         ¬ice("Usage: /twitter_subscribe <topic>");
 
 570     if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
 
 571         ¬ice("Already had a subscription for '$data'");
 
 575     $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
 
 576     ¬ice("Added subscription for '$data'");
 
 580     my ( $data, $server, $win ) = @_;
 
 582     unless ( $twit and $twit->can('search') ) {
 
 583         ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
 
 584               . "doesn't support searches." );
 
 587     $data =~ s/^\s+|\s+$//;
 
 591         ¬ice("Usage: /twitter_unsubscribe <topic>");
 
 595     unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
 
 596         ¬ice("No subscription found for '$data'");
 
 600     delete $id_map{__searches}{"$user\@$defservice"}{$data};
 
 601     ¬ice("Removed subscription for '$data'");
 
 604 sub cmd_list_search {
 
 605     my ( $data, $server, $win ) = @_;
 
 608     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
 
 610         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
 
 611             $topics = $topics ? "$topics, $topic" : $topic;
 
 615             ¬ice("Search subscriptions for \@$suser: $topics");
 
 620         ¬ice("No search subscriptions set up");
 
 625     my ( $data, $server, $win ) = @_;
 
 627     my $loc = Irssi::settings_get_str("twirssi_location");
 
 630 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
 
 636     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
 
 637         eval { use Digest::MD5; };
 
 641 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
 
 646         $md5 = get("http://twirssi.com/md5sum");
 
 650             ¬ice("Failed to download md5sum from peeron!  Aborting.");
 
 654         unless ( open( CUR, $loc ) ) {
 
 656 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
 
 661         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
 
 664         if ( $cur_md5 eq $md5 ) {
 
 665             ¬ice("Current twirssi seems to be up to date.");
 
 671       Irssi::settings_get_bool("twirssi_upgrade_beta")
 
 672       ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
 
 673       : "http://twirssi.com/twirssi.pl";
 
 674     ¬ice("Downloading twirssi from $URL");
 
 675     LWP::Simple::getstore( $URL, "$loc.upgrade" );
 
 677     unless ( -s "$loc.upgrade" ) {
 
 678         ¬ice("Failed to save $loc.upgrade."
 
 679               . "  Check that /set twirssi_location is set to the correct location."
 
 684     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
 
 685         unless ( open( NEW, "$loc.upgrade" ) ) {
 
 686             ¬ice("Failed to read $loc.upgrade."
 
 687                   . "  Check that /set twirssi_location is set to the correct location."
 
 692         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
 
 695         if ( $new_md5 ne $md5 ) {
 
 696             ¬ice("MD5 verification failed. expected $md5, got $new_md5");
 
 701     rename $loc, "$loc.backup"
 
 702       or ¬ice("Failed to back up $loc: $!.  Aborting")
 
 704     rename "$loc.upgrade", $loc
 
 705       or ¬ice("Failed to rename $loc.upgrade: $!.  Aborting")
 
 708     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
 
 709     if ( -e "$dir/autorun/$file" ) {
 
 710         ¬ice("Updating $dir/autorun/$file");
 
 711         unlink "$dir/autorun/$file"
 
 712           or ¬ice("Failed to remove old $file from autorun: $!");
 
 713         symlink "../$file", "$dir/autorun/$file"
 
 714           or ¬ice("Failed to create symlink in autorun directory: $!");
 
 717     ¬ice("Download complete.  Reload twirssi with /script load $file");
 
 727             print $fh "type:debug Loading friends page $page...\n"
 
 728               if ( $fh and &debug );
 
 729             my $friends = $twit->friends( { page => $page } );
 
 730             last unless $friends;
 
 731             $new_friends{ $_->{screen_name} } = time foreach @$friends;
 
 733             last if @$friends == 0 or $page == 10;
 
 738         print $fh "type:debug Error during friends list update.  Aborted.\n";
 
 742     my ( $added, $removed ) = ( 0, 0 );
 
 743     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
 
 744     foreach ( keys %new_friends ) {
 
 745         next if exists $friends{$_};
 
 750     print $fh "type:debug Scanning for removed friends...\n"
 
 751       if ( $fh and &debug );
 
 752     foreach ( keys %friends ) {
 
 753         next if exists $new_friends{$_};
 
 758     return ( $added, $removed );
 
 762     print scalar localtime, " - get_updates starting" if &debug;
 
 765       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
 
 768           ->print( "Can't find a window named '"
 
 769               . Irssi::settings_get_str('twitter_window')
 
 770               . "'.  Create it or change the value of twitter_window" );
 
 773     return unless &logged_in($twit);
 
 775     my ( $fh, $filename ) = File::Temp::tempfile();
 
 776     binmode( $fh, ":utf8" );
 
 780         Irssi::timeout_add_once( 5000, 'monitor_child',
 
 781             [ "$filename.done", 0 ] );
 
 782         Irssi::pidwait_add($pid);
 
 783     } elsif ( defined $pid ) {    # child
 
 792         foreach ( keys %twits ) {
 
 793             $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
 
 796         print $fh "__friends__\n";
 
 798             time - $last_friends_poll >
 
 799             Irssi::settings_get_int('twitter_friends_poll') )
 
 801             print $fh "__updated ", time, "\n";
 
 802             my ( $added, $removed ) = &load_friends($fh);
 
 803             if ( $added + $removed ) {
 
 804                 print $fh "type:debug %R***%n Friends list updated: ",
 
 806                     sprintf( "%d added",   $added ),
 
 807                     sprintf( "%d removed", $removed ) ),
 
 812         foreach ( sort keys %friends ) {
 
 813             print $fh "$_ $friends{$_}\n";
 
 817             print $fh "type:debug Update encountered errors.  Aborted\n";
 
 818             print $fh "-- $last_poll";
 
 820             print $fh "-- $new_poll";
 
 823         rename $filename, "$filename.done";
 
 826         &ccrap("Failed to fork for updating: $!");
 
 828     print scalar localtime, " - get_updates ends" if &debug;
 
 832     my ( $fh, $username, $obj, $cache ) = @_;
 
 834     my $rate_limit = $obj->rate_limit_status();
 
 835     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
 
 836         ¬ice("Rate limit exceeded for $username");
 
 840     print scalar localtime, " - Polling for updates for $username" if &debug;
 
 844         if ( $id_map{__last_id}{$username}{timeline} )
 
 846             $tweets = $obj->friends_timeline( { count => 100 } );
 
 848             $tweets = $obj->friends_timeline();
 
 853         print $fh "type:debug Error during friends_timeline call: Aborted.\n";
 
 854         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
 
 858     unless ( ref $tweets ) {
 
 859         if ( $obj->can("get_error") ) {
 
 860             my $error = "Unknown error";
 
 861             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
 
 862             unless ($@) { $error = $obj->get_error() }
 
 864               "type:debug API Error during friends_timeline call: Aborted\n";
 
 865             print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
 
 869               "type:debug API Error during friends_timeline call. Aborted.\n";
 
 874     foreach my $t ( reverse @$tweets ) {
 
 875         my $text = decode_entities( $t->{text} );
 
 876         $text =~ s/[\n\r]/ /g;
 
 878         if (    Irssi::settings_get_bool("show_reply_context")
 
 879             and $t->{in_reply_to_screen_name} ne $username
 
 880             and $t->{in_reply_to_screen_name}
 
 881             and not exists $friends{ $t->{in_reply_to_screen_name} } )
 
 883             $nicks{ $t->{in_reply_to_screen_name} } = time;
 
 885             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
 
 887                     $cache->{ $t->{in_reply_to_status_id} } =
 
 888                       $obj->show_status( $t->{in_reply_to_status_id} );
 
 892             $context = $cache->{ $t->{in_reply_to_status_id} };
 
 895                 my $ctext = decode_entities( $context->{text} );
 
 896                 $ctext =~ s/[\n\r]/ /g;
 
 897                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
 
 899                         " -- http://twitter.com/$context->{user}{screen_name}"
 
 900                       . "/status/$context->{id}";
 
 902                 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
 
 903                   $context->{id}, $username,
 
 904                   $context->{user}{screen_name}, $ctext;
 
 909           if $t->{user}{screen_name} eq $username
 
 910               and not Irssi::settings_get_bool("show_own_tweets");
 
 911         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
 
 912             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
 
 913               . "/status/$t->{id}";
 
 915         printf $fh "id:%u account:%s nick:%s type:%s %s\n",
 
 916           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
 
 917         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
 
 919     printf $fh "id:%u account:%s type:last_id timeline\n",
 
 920       $new_poll_id, $username;
 
 922     print scalar localtime, " - Polling for replies since ",
 
 923       $id_map{__last_id}{$username}{reply}
 
 927         if ( $id_map{__last_id}{$username}{reply} )
 
 929             $tweets = $obj->replies(
 
 930                 { since_id => $id_map{__last_id}{$username}{reply} } )
 
 933             $tweets = $obj->replies() || [];
 
 938         print $fh "type:debug Error during replies call.  Aborted.\n";
 
 942     foreach my $t ( reverse @$tweets ) {
 
 944           if exists $friends{ $t->{user}{screen_name} };
 
 946         my $text = decode_entities( $t->{text} );
 
 947         $text =~ s/[\n\r]/ /g;
 
 948         if ( $t->{truncated} ) {
 
 949             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
 
 950               . "/status/$t->{id}";
 
 952         printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
 
 953           $t->{id}, $username, $t->{user}{screen_name}, $text;
 
 954         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
 
 956     printf $fh "id:%u account:%s type:last_id reply\n", $new_poll_id, $username;
 
 958     print scalar localtime, " - Polling for DMs" if &debug;
 
 961         if ( $id_map{__last_id}{$username}{dm} )
 
 963             $tweets = $obj->direct_messages(
 
 964                 { since_id => $id_map{__last_id}{$username}{dm} } )
 
 967             $tweets = $obj->direct_messages() || [];
 
 972         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
 
 976     foreach my $t ( reverse @$tweets ) {
 
 977         my $text = decode_entities( $t->{text} );
 
 978         $text =~ s/[\n\r]/ /g;
 
 979         printf $fh "id:%u account:%s nick:%s type:dm %s\n",
 
 980           $t->{id}, $username, $t->{sender_screen_name}, $text;
 
 981         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
 
 983     printf $fh "id:%u account:%s type:last_id dm\n", $new_poll_id, $username;
 
 985     print scalar localtime, " - Polling for subscriptions" if &debug;
 
 986     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
 
 988         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
 
 989             print $fh "type:debug searching for $topic since ",
 
 990               "$id_map{__searches}{$username}{$topic}\n";
 
 992                 $search = $obj->search(
 
 995                         since_id => $id_map{__searches}{$username}{$topic}
 
1002                   "type:debug Error during search($topic) call.  Aborted.\n";
 
1006             unless ( $search->{max_id} ) {
 
1007                 print $fh "type:debug Invalid search results when searching",
 
1008                   " for $topic. Aborted.\n";
 
1012             $id_map{__searches}{$username}{$topic} = $search->{max_id};
 
1013             printf $fh "id:%u account:%s type:searchid topic:%s\n",
 
1014               $search->{max_id}, $username, $topic;
 
1016             foreach my $t ( reverse @{ $search->{results} } ) {
 
1017                 my $text = decode_entities( $t->{text} );
 
1018                 $text =~ s/[\n\r]/ /g;
 
1019                 printf $fh "id:%u account:%s nick:%s type:search topic:%s %s\n",
 
1020                   $t->{id}, $username, $t->{from_user}, $topic, $text;
 
1021                 $new_poll_id = $t->{id}
 
1023                       or $t->{id} < $new_poll_id;
 
1028     print scalar localtime, " - Done" if &debug;
 
1035     my $filename = $data->[0];
 
1036     my $attempt  = $data->[1];
 
1038     print scalar localtime, " - checking child log at $filename ($attempt)"
 
1040     my ($new_last_poll);
 
1042     # first time we run we don't want to print out *everything*, so we just
 
1045     if ( open FILE, $filename ) {
 
1046         binmode FILE, ":utf8";
 
1050             last if /^__friends__/;
 
1051             unless (/\n$/) {    # skip partial lines
 
1052                                 # print "Skipping partial line: $_" if &debug;
 
1059             foreach my $key (qw/id account nick type topic/) {
 
1060                 if (s/^$key:(\S+)\s*//) {
 
1065             if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
 
1066                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
 
1070                 $new_cache{ $meta{id} } = time;
 
1072                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
 
1078             $meta{account} =~ s/\@(\w+)$//;
 
1079             $meta{service} = $1;
 
1081                 lc $meta{service} eq
 
1082                 lc Irssi::settings_get_str("twirssi_default_service") )
 
1084                 $account = "$meta{account}: "
 
1085                   if lc "$meta{account}\@$meta{service}" ne lc
 
1086                       "$user\@$defservice";
 
1088                 $account = "$meta{account}\@$meta{service}: ";
 
1092             if (    $meta{type} ne 'dm'
 
1093                 and Irssi::settings_get_bool("twirssi_track_replies")
 
1097                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
 
1098                 $id_map{ lc $meta{nick} }[$marker]           = $meta{id};
 
1099                 $id_map{__indexes}{ $meta{nick} }            = $marker;
 
1100                 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
 
1101                 $marker                                      = ":$marker";
 
1105               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
 
1106             my $nick = "\@$meta{account}";
 
1107             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
 
1108                 and Irssi::settings_get_bool("twirssi_hilights") )
 
1110                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
 
1111                 $hilight = MSGLEVEL_HILIGHT;
 
1114             if ( $meta{type} =~ /tweet|reply/ ) {
 
1117                     ( MSGLEVEL_PUBLIC | $hilight ),
 
1118                     $meta{type}, $account, $meta{nick}, $marker, $_
 
1120             } elsif ( $meta{type} eq 'search' ) {
 
1123                     ( MSGLEVEL_PUBLIC | $hilight ),
 
1124                     $meta{type}, $account, $meta{topic},
 
1125                     $meta{nick}, $marker,  $_
 
1128                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
 
1130                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
 
1132                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
 
1135             } elsif ( $meta{type} eq 'dm' ) {
 
1138                     ( MSGLEVEL_MSGS | $hilight ),
 
1139                     $meta{type}, $account, $meta{nick}, $_
 
1141             } elsif ( $meta{type} eq 'searchid' ) {
 
1142                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
 
1145                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
 
1147                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
 
1149                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
 
1152                     print "Search '$meta{topic}' returned invalid id $meta{id}";
 
1154             } elsif ( $meta{type} eq 'last_id' ) {
 
1155                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
 
1157                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
 
1159             } elsif ( $meta{type} eq 'error' ) {
 
1160                 push @lines, [ MSGLEVEL_MSGS, $_ ];
 
1161             } elsif ( $meta{type} eq 'debug' ) {
 
1162                 print "$_" if &debug,;
 
1164                 print "Unknown line type $meta{type}: $_" if &debug,;
 
1170             if (/^__updated (\d+)$/) {
 
1171                 $last_friends_poll = $1;
 
1172                 print "Friend list updated" if &debug;
 
1177                 $new_last_poll = $1;
 
1178                 if ( $new_last_poll >= $last_poll ) {
 
1181                     print "Impossible!  ",
 
1182                       "new_last_poll=$new_last_poll < last_poll=$last_poll!"
 
1184                     undef $new_last_poll;
 
1188             my ( $f, $t ) = split ' ', $_;
 
1189             $nicks{$f} = $friends{$f} = $t;
 
1192         if ($new_last_poll) {
 
1193             print "new last_poll    = $new_last_poll" if &debug;
 
1194             print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
 
1196                 print "First call, not printing updates" if &debug;
 
1198                 foreach my $line (@lines) {
 
1199                     $window->printformat(
 
1201                         "twirssi_" . $line->[1],
 
1202                         @$line[ 2 .. $#$line - 1 ],
 
1203                         &hilight( $line->[-1] )
 
1210               or warn "Failed to remove $filename: $!"
 
1213             # commit the pending cache lines to the actual cache, now that
 
1214             # we've printed our output
 
1215             %tweet_cache = ( %tweet_cache, %new_cache );
 
1217             # keep enough cached tweets, to make sure we don't show duplicates.
 
1218             foreach ( keys %tweet_cache ) {
 
1219                 next if $tweet_cache{$_} >= $last_poll - 3600;
 
1220                 delete $tweet_cache{$_};
 
1222             $last_poll = $new_last_poll;
 
1227                 Irssi::settings_get_str("twirssi_replies_store") )
 
1229                 if ( open JSON, ">$file" ) {
 
1230                     print JSON JSON::Any->objToJson( \%id_map );
 
1233                     &ccrap("Failed to write replies to $file: $!");
 
1244     if ( $attempt < 24 ) {
 
1245         Irssi::timeout_add_once( 5000, 'monitor_child',
 
1246             [ $filename, $attempt + 1 ] );
 
1248         print "Giving up on polling $filename" if &debug;
 
1249         unlink $filename unless &debug;
 
1251         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
 
1254         my @time = localtime($last_poll);
 
1255         if ( time - $last_poll < 24 * 60 * 60 ) {
 
1256             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
 
1258             $since = scalar localtime($last_poll);
 
1261         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
 
1266                 q{  .--./ /  |  _.---.| },
 
1278         if ( time - $last_poll < 600 ) {
 
1279             &ccrap("Haven't been able to get updated tweets since $since");
 
1285     return Irssi::settings_get_bool("twirssi_debug");
 
1289     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
 
1293     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
 
1299     if (    Irssi::settings_get_bool("tweet_to_away")
 
1301         and $data !~ /^[dD] / )
 
1304           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
 
1306             $server->send_raw("away :$data");
 
1309             &ccrap( "Can't find bitlbee server.",
 
1310                 "Update bitlbee_server or disable tweet_to_away" );
 
1320     my $noalert = shift;
 
1322     if ( length $data > 140 ) {
 
1323         ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
 
1331 sub valid_username {
 
1332     my $username = shift;
 
1334     $username = &normalize_username($username);
 
1336     unless ( exists $twits{$username} ) {
 
1337         ¬ice("Unknown username $username");
 
1347         ¬ice("Not logged in!  Use /twitter_login username pass!");
 
1355     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
 
1358         $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
 
1359         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
 
1360             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
 
1362     {    # /twitter_reply gets a nick:num
 
1364         @$complist = map { "$_:$id_map{__indexes}{$_}" }
 
1365           sort { $nicks{$b} <=> $nicks{$a} }
 
1367           keys %{ $id_map{__indexes} };
 
1370     if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
 
1371     {    # /twitter_unfriend gets a nick
 
1373         push @$complist, grep /^\Q$word/i,
 
1374           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
 
1377     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
 
1379     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
 
1380         my $prefix = $word =~ s/^@//;
 
1381         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
 
1382         push @$complist, grep /^\Q$word/i,
 
1383           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
 
1384         @$complist = map { "\@$_" } @$complist if $prefix;
 
1388 sub event_send_text {
 
1389     my ( $line, $server, $win ) = @_;
 
1390     my $awin = Irssi::active_win();
 
1392     # if the window where we got our text was the twitter window, and the user
 
1393     # wants to be lazy, tweet away!
 
1394     if ( ( $awin->get_active_name() eq $window->{name} )
 
1395         and Irssi::settings_get_bool("tweet_window_input") )
 
1397         &cmd_tweet( $line, $server, $win );
 
1402     my $poll = Irssi::settings_get_int("twitter_poll_interval");
 
1403     return $poll if $poll >= 60;
 
1410     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
 
1411         my $c = Irssi::settings_get_str("twirssi_nick_color");
 
1412         $c = $irssi_to_mirc_colors{$c};
 
1413         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
 
1415     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
 
1416         my $c = Irssi::settings_get_str("twirssi_topic_color");
 
1417         $c = $irssi_to_mirc_colors{$c};
 
1418         $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
 
1420     $text =~ s/[\n\r]/ /g;
 
1428     my $provider = Irssi::settings_get_str("short_url_provider");
 
1431             Irssi::settings_get_bool("twirssi_always_shorten")
 
1432             or &too_long( $data, 1 )
 
1438         if ( $provider eq 'Bitly' ) {
 
1439             @args[ 1, 2 ] = split ',',
 
1440               Irssi::settings_get_str("short_url_args"), 2;
 
1441             unless ( @args == 3 ) {
 
1443                     "WWW::Shorten::Bitly requires a username and API key.",
 
1444                     "Set short_url_args to username,API_key or change your",
 
1445                     "short_url_provider."
 
1451         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
 
1454                 my $short = makeashorterlink(@args);
 
1456                     $data =~ s/\Q$url/$short/g;
 
1458                     ¬ice("Failed to shorten $url!");
 
1464     return decode "utf8", $data;
 
1467 sub normalize_username {
 
1470     my ( $username, $service ) = split /\@/, $user, 2;
 
1472         $service = ucfirst lc $service;
 
1475           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
 
1476         unless ( exists $twits{"$username\@$service"} ) {
 
1478             foreach my $t ( sort keys %twits ) {
 
1479                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
 
1485                 ¬ice("Can't find a logged in user '$user'");
 
1490     return "$username\@$service";
 
1493 Irssi::signal_add( "send text", "event_send_text" );
 
1495 Irssi::theme_register(
 
1497         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
 
1498         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
 
1499         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
 
1500         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
 
1501         'twirssi_error',  'ERROR: $0',
 
1505 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
 
1506 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
 
1507 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
 
1508 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
 
1509 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
 
1510 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
 
1511 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
 
1512 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
 
1513 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
 
1514 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
 
1515 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
 
1516     'RT $n: "$t" ${-- $c$}' );
 
1517 Irssi::settings_add_str( "twirssi", "twirssi_location",
 
1518     ".irssi/scripts/twirssi.pl" );
 
1519 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
 
1520     ".irssi/scripts/twirssi.json" );
 
1522 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
 
1523 Irssi::settings_add_int( "twirssi", "twitter_timeout", 30 );
 
1525 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
 
1526 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
 
1527 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
 
1528 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
 
1529 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
 
1530 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
 
1531 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
 
1532 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
 
1533 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
 
1534 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
 
1535 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
 
1536 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
 
1537 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
 
1538 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl",         0 );
 
1540 $last_poll = time - &get_poll_time;
 
1541 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
 
1544       ->print( "Couldn't find a window named '"
 
1545           . Irssi::settings_get_str('twitter_window')
 
1546           . "', trying to create it." );
 
1548       Irssi::Windowitem::window_create(
 
1549         Irssi::settings_get_str('twitter_window'), 1 );
 
1550     $window->set_name( Irssi::settings_get_str('twitter_window') );
 
1554     Irssi::command_bind( "dm",                         "cmd_direct" );
 
1555     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
 
1556     Irssi::command_bind( "tweet",                      "cmd_tweet" );
 
1557     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
 
1558     Irssi::command_bind( "retweet",                    "cmd_retweet" );
 
1559     Irssi::command_bind( "retweet_as",                 "cmd_retweet_as" );
 
1560     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
 
1561     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
 
1562     Irssi::command_bind( "twitter_login",              "cmd_login" );
 
1563     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
 
1564     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
 
1565     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
 
1566     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
 
1567     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
 
1568     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
 
1569     Irssi::command_bind( "twitter_updates",            "get_updates" );
 
1570     Irssi::command_bind( "bitlbee_away",               "update_away" );
 
1571     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
 
1572         Irssi::command_bind( "reply",    "cmd_reply" );
 
1573         Irssi::command_bind( "reply_as", "cmd_reply_as" );
 
1575     Irssi::command_bind(
 
1578             print "twits: ", join ", ",
 
1579               map { "u: $_->{username}\@" . ref($_) } values %twits;
 
1580             print "selected: $user\@$defservice";
 
1581             print "friends: ", join ", ", sort keys %friends;
 
1582             print "nicks: ",   join ", ", sort keys %nicks;
 
1583             print "searches: ", Dumper \%{ $id_map{__searches} };
 
1584             print "last poll: $last_poll";
 
1585             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
 
1586                 print DUMP Dumper \%tweet_cache;
 
1588                 print "cache written out to /tmp/twirssi.cache.txt";
 
1592     Irssi::command_bind(
 
1595             ¬ice("Twirssi v$VERSION (r$REV); "
 
1596                   . "Net::Twitter v$Net::Twitter::VERSION. "
 
1598                   . JSON::Any::handler()
 
1599                   . ".  See details at http://twirssi.com/" );
 
1602     Irssi::command_bind(
 
1605             "/twitter_follow <username>",
 
1607             sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
 
1610     Irssi::command_bind(
 
1613             "/twitter_unfriend <username>",
 
1615             sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
 
1618     Irssi::command_bind(
 
1619         "twitter_device_updates",
 
1621             "/twitter_device_updates none|im|sms",
 
1622             "update_delivery_device",
 
1623             sub { ¬ice("Device updated to $_[0]"); }
 
1626     Irssi::signal_add_last( 'complete word' => \&sig_complete );
 
1628     ¬ice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
 
1629     ¬ice("   %C(_(\\%N           http://twirssi.com/ for full docs");
 
1631         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
 
1633     my $file = Irssi::settings_get_str("twirssi_replies_store");
 
1634     if ( $file and -r $file ) {
 
1635         if ( open( JSON, $file ) ) {
 
1640                 my $ref = JSON::Any->jsonToObj($json);
 
1642                 my $num = keys %{ $id_map{__indexes} };
 
1643                 ¬ice( sprintf "Loaded old replies from %d contact%s.",
 
1644                     $num, ( $num == 1 ? "" : "s" ) );
 
1648             ¬ice("Failed to load old replies from $file: $!");
 
1652     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
 
1653         ¬ice("Loading WWW::Shorten::$provider...");
 
1654         eval "use WWW::Shorten::$provider;";
 
1658                 "Failed to load WWW::Shorten::$provider - either clear",
 
1659                 "short_url_provider or install the CPAN module"
 
1664     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
 
1665         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
 
1673       ->print( "Create a window named "
 
1674           . Irssi::settings_get_str('twitter_window')
 
1675           . " or change the value of twitter_window.  Then, reload twirssi." );
 
1678 # vim: set sts=4 expandtab: