__module_name__ = "urlarge"
__module_version__ = "1.0"
__module_description__ = "Python module for resolving tinyurl like links"

EVENTS = [
  ("Channel Action", 1),
  ("Channel Action Hilight", 1),
  ("Channel Message", 1),
  ("Channel Msg Hilight", 1),
  ("Channel Notice", 2),
  ("Generic Message", (0, 1)),
  ("Kick", 3),
  ("Killed", 1),
  ("Motd", 0),
  ("Notice", 1),
  ("Part with Reason", 3),
  ("Private Message", 1),
  ("Private Message to Dialog", 1),
  ("Quit", 1),
  ("Receive Wallops", 1),
  ("Server Notice", 0),
  ("Server Text", 0),
  ("Topic", 1),
  ("Topic Change", 1),
]

import xchat, re, socket

domains = [
	'tinyurl.com',
	'is.gd',
	'bit.ly',
	'twurl.cc',
	'hex.io',
	'lin.cd',
	'budurl.com',
	'icanhaz.com',
	'poprl.com',
	'snipurl.com',
	'urlborg.com',
	'zi.ma',
	]

shurl_re = re.compile('http://(?:%s)/[^\s]+' % '|'.join(domains), re.I)
urlsplit_re = re.compile('^http://([^/]+)(/[^\s]+)$')
loc_re = re.compile('Location: (http[^\r]+)', re.I)


def expand_urls(word, word_eol, userdata):
	event, pos = userdata
	if type(pos) is int:
		pos = (pos,)
	changed = False
	if len(word) < 2:
		return xchat.EAT_NONE
	string = word[1]
	list_of_urls = shurl_re.findall(string)
	
	for url in list_of_urls:
		host, path_info = urlsplit_re.match(url).groups()
		s = socket.socket()
		s.settimeout(10.0)
		s.connect((host,80))
		req = '\r\n'.join(['GET %s HTTP/1.0' % path_info, 'Host: %s' % host, '', ''])
		#xchat.prnt(repr(req))
		s.send(req)
		umm = s.recv(1000)
		s.close()
		m = loc_re.search(umm)
		if m:
			#xchat.prnt('%s -> %s' % (url, m.group(1)))
			string = string.replace(url, m.group(1))
			changed = True
	if changed:
		word = (word[0], string)
		xchat.emit_print(event, *word)
		return xchat.EAT_XCHAT
	return xchat.EAT_NONE

for event in EVENTS:
    xchat.hook_print(event[0], expand_urls, event)

print 'urlarge.py loaded.'
