#! /usr/bin/perl
# Copyright Toufeeq Hussain <toufeeq_hussain@infosys.com>
# This file is free software; you can redistribute it 
# and/or modify it under the same terms as Perl itself.
# http://toufeeq.blogspot.com/2007/01/twitish.html

# Modified by Adriaan Tijsseling (http://kung-foo.tv)

use strict;
use XML::Liberal;
use LWP::UserAgent;
use HTTP::Response;
use HTTP::Request;
use HTTP::Date;
use Term::ANSIColor;

#ensure standard streams use utf8
binmode( STDIN,  ':utf8' );
binmode( STDOUT, ':utf8' );

# LOGIN Credentials
my $USERNAME = 'USERNAME';
my $PASSWORD = 'PASSWORD';

# URLs
use constant FRIEND_URL => 'http://twitter.com/statuses/friends_timeline.xml';
use constant PUBLIC_URL => 'http://twitter.com/statuses/public_timeline.xml';
use constant POST_URL => 'http://twitter.com/statuses/update.xml';
use constant UA_STR => 'USERAGENT';

# REST
my $ua = LWP::UserAgent->new;
$ua->agent(UA_STR);
$ua->credentials(
    'twitter.com:80',
    'Twitter API',
    $USERNAME => $PASSWORD,);
# Make the UA use the environment proxy var $http_proxy
$ua->env_proxy;

$_ = $ARGV[0];
if (!$_) {
  twitter_updates(FRIEND_URL);
}
elsif (/^-p/) {
  # Show the public timeline.
  twitter_updates(PUBLIC_URL);
}
else {
  #post to twitter
  twitter_post($ARGV[0]);
}

# Post to twitter
sub twitter_post {
  my $input = $_[0];
  if ( length($input) > 140 ) {
    print color 'red';
    print "Text exceeds 140 chars!\n";
    exit;
  }
  
  # The passed in text is POST-ed to Twitter.
  my $response = $ua->post(POST_URL, [source => 'script', status => $input]);
  
  # Inform the user if we have a successful response.
  if ($response->is_success) {
      print color 'green';
      print "Twitter Updated\n";
  } else {
      print color 'red';
      print "Update to Twitter failed\n";
  }
  print color 'reset';
  return 1; 
}

# Fetch the latest updates from Twitter.
sub twitter_updates {
  my $updates_url = shift;
  my $parser = XML::Liberal->new('LibXML');
  my $updates_request = HTTP::Request->new(GET => $updates_url);
  my $response =  $ua->request($updates_request);
  if ($response->is_success) {
    my $curdate = time;
    my $xml_content = $response->content;
    my $doc = $parser->parse_string($xml_content);
    my $root = $doc->getDocumentElement;

    my @statuses = $root->getElementsByTagName('status');
    my $status_count = 0;
    if (scalar @statuses > 20) {
      $status_count = 20;
    } else {
      $status_count = scalar @statuses;
    }

    for (my $updates = 0; $updates < $status_count ; $updates++) {
      my @dates = $statuses[$updates]->getElementsByTagName('created_at');
      my $datestr = $dates[0]->getFirstChild->getData;
      $datestr =~ s/ \+0000 200\d//; 
      my $update = str2time($datestr);
      my $secs = int($curdate - $update - 32400);
      my $elapsed = ' (';
      my $hrs = int($secs/3600);
      $secs = int($secs % 3600 );
      my $mins  = int($secs / 60);
      if ( $hrs > 0 ) {
        $elapsed .= $hrs . "h:" . $mins . "m)\n";
      } elsif ( $mins > 0 ) {
        $elapsed .= $mins . "m)\n";
      } else {
        $secs  = int($secs % 60);
        $elapsed .= $secs . "s)\n";
      }
      # get the name of the person.
      my @id = $statuses[$updates]->getElementsByTagName('name');
      my $name = $id[0]->getFirstChild->getData;
      # get what the person is saying.
      my @desc = $statuses[$updates]->getElementsByTagName('text');
      my $description = $desc[0]->getFirstChild->getData,"\n";
      
      $description =~ s/&gt;/>/g;
      $description =~ s/&lt;/</g;
      print color 'red';
      print "$name";
      print color 'reset';
      print ": ";
      print color 'cyan';
      print "$description";
      print color 'reset';
      print color 'green';
      print "$elapsed";
      print color 'reset';
    }
  } else {
    print "Failed to fetch updates\n";
  }
  return 1;
}

__END__

