#! /usr/bin/perl -w
#
# wd - what doing? get/set your twitter.com status
#
# Copyright (c) 2007, Andrew J. Cosgriff, http://polydistortion.net/
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#    * redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#
#    * Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials provided
#      with the distribution.
#
#    * The names of its contributors may not be used to endorse or
#      promote products derived from this software without specific
#      prior written permission.
#
#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
#    CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
#    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
#    BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
#    TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
#    ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
#    OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#    POSSIBILITY OF SUCH DAMAGE.
#
##########
#
# Configuration:
#
# set your username (e-mail address) and password in your ~/.netrc file.
# eg.
# % echo "machine twitter.com login your@email.address password
# yourpass" > ~/.netrc
# % chmod 0600 ~/.netrc
#
my $username;
my $password;

# use .netrc instead - thanks ajft!
use Net::Netrc;

if ($mach = Net::Netrc->lookup('twitter.com')) {
  $username = $mach->login;
  $password = $mach->password;
} else {
  die "No credentials for twitter.com in .netrc: $!";
}
##########
use strict;
use POSIX qw(strftime);
use JSON;
use HTTP::Headers;
use LWP;
use Getopt::Std;
use DateTime::Format::Strptime;

my $wd_version = "1.10";

my $ua = LWP::UserAgent->new;
$ua->credentials('twitter.com:80','Twitter API',$username,$password);
$ua->default_headers->push_header("X-Twitter-Client" => "wd");
$ua->default_headers->push_header("X-Twitter-Client-URL:" => "http://polydistortion.net/sw/twitter/wd.xml");
$ua->default_headers->push_header("X-Twitter-Client-Version" => "$wd_version");

my %opts = ();
getopts('pvs', \%opts);

if (defined $opts{'p'}) {
    $ua->env_proxy;
}

if ((! defined $opts{'s'}) and ($#ARGV > 0)) {
    print "[warning] hmm, are you sure you didn't mean to add a -s to that?\n\n";
}

if (defined $opts{'s'}) {
    if ($#ARGV < 0) {
	print "well, what are you doing?\n";
	exit 1;
    }

    my $response = $ua->post('http://twitter.com/statuses/update.json',
			     [ "status" => join(' ',@ARGV) ]);

    die "Wrong content-type (",$response->content_type,") received - was expecting application/json\n"
	unless $response->content_type =~ m/^application\/json/;

    my $status = jsonToObj($response->content);
    my %user = %{$status};
    if (defined $opts{'v'}) {
	print "status set to: ",$user{'text'},"\n";
    }
} else {
    my $response = $ua->get('http://twitter.com/statuses/friends.json');

    die "Can't get Twitter status: ", $response->status_line
    unless $response->is_success;

    die "Wrong content-type (",$response->content_type,") received - was expecting application/json\n"
	unless $response->content_type =~ m/^application\/json/;

    my $status = jsonToObj($response->content);
    my $strp = new DateTime::Format::Strptime(pattern => '%a %b %d %T %z %Y');
    my %stati=();
    foreach my $userobj (@{$status}) {
	my %user=%{$userobj};
	next if ((($#ARGV >= 0) and
		 ($user{screen_name} !~ m/$ARGV[0]/))
		 or (! defined $user{status}));
	
	$stati{$user{screen_name}}{"text"} = $user{status}->{text};
	#$stati{$user{screen_name}}{"rel"} = $user{status}->{relative_created_at};
	$stati{$user{screen_name}}{"date"} = DateTime::Format::Strptime::strftime("%s",$strp->parse_datetime($user{status}->{created_at}));
    }

    foreach my $user (sort {$stati{$a}{"date"} cmp $stati{$b}{"date"};} keys %stati) {
	print "$user ",$stati{$user}{text}," (",strftime("%Y-%m-%d %H:%M:%S",localtime($stati{$user}{"date"})),")\n";
    }
							  
}

