#!/usr/bin/env python
#
# Simple util to uncloak a tinyurl spams.  In short, it takes
# the tinyurl and then receives the request and looks for
# the location: parameter returned by the webserver.  It should
# then display that to the user.  It's designed to be used as a 
# plugin inside an IRC client such as xchat.

__author__ = "Nick Guy"
__license__ = "GPL"

# get libraries for console streams and http client support
import sys;
import httplib;
from urlparse import urlparse;

mystery_url = '';

if ( len( sys.argv ) == 1):
	mystery_url = sys.stdin.read();	# works
elif ( len( sys.argv ) == 2):
	mystery_url = sys.argv[1];
else:
	print "Usage: " + sys.argv[0] + "  -or- echo \"\" | " + sys.argv[0]
	sys.exit(1)

# break URL into component ports..
mystery_object = urlparse( mystery_url );

# only need netloc and path for tinyurl.  Consider adding query to generalize this.
if mystery_object[0] == "http":
	connection = httplib.HTTPConnection( mystery_object[1] );
elif mystery_object[0] == "https":
	connection = httplib.HTTPSConnection( mystery_object[1] );

# Do the actual networking here.
connection.request('GET', mystery_object[2] );
response = connection.getresponse();
decloaked = response.getheader('Location');
connection.close();

print decloaked;