info = { 'author': 'Jon Bergli Heier', 'title': 'TVRage', 'description': 'TVRage.com feed parser', } import urllib, urllib2, datetime, rfc3339, pytz from lxml import etree class Module: def __init__(self, bot): self.irc = bot if self.irc: self.irc.register_keyword('!tv', self) def find_show(self, search): try: u = urllib2.urlopen('http://services.tvrage.com/tools/quickinfo.php?%s' % urllib.urlencode({'show': search})) except: return 'Could not fetch show data from TVRage.' rawdata = u.read() if rawdata.startswith('No Show Results'): return rawdata.strip() # Why is there a pre-tag here in the first place? if rawdata.startswith('
'):
			rawdata = rawdata[5:]

		data = {}
		for line in rawdata.strip().split('\n'):
			key, values = line.split('@')
			values = values.split('^')
			data[key] = values

		status = data['Status'][0]
		if 'Ended' in status or 'Canceled' in status:
			return '\002%s\002 does not currently air.' % data['Show Name'][0]

		if not 'RFC3339' in data:
			if 'Next Episode' in data:
				return '\002%s\002 %s airs in %s, on %s' % (data['Show Name'][0],
						data['Next Episode'][1],
						data['Next Episode'][2],
						data['Airtime'][0])
			else:
				return '\002%s\002 does not yet air.' % data['Show Name'][0]

		# TODO: Fetch this from somewhere user-configurable
		local_tz = pytz.timezone('Europe/Oslo')

		airdate = data['RFC3339'][0]
		if len(airdate) == 24: # Assume missing 0 in timezone
			airdate = airdate[:20] + '0' + airdate[20:]
		airdate = rfc3339.parse_datetime(airdate)

		# Convert airdate to our local timezone
		airdate = airdate.astimezone(local_tz)

		# Localize utcnow() as UTC
		now = pytz.utc.localize(datetime.datetime.utcnow())

		eta = airdate - now
		# Get rid of microseconds
		eta = datetime.timedelta(eta.days, eta.seconds)


		aired = eta.days < 0 or eta.seconds < 0

		if aired:
			return '\002%s\002 aired on \002%s\002' % (data['Show Name'][0], airdate.strftime('%d.%m.%Y %H:%M %Z'))
		else:
			return '\002%s\002 %s airs on \002%s\002 (eta: %s)' % (data['Show Name'][0],
				data['Next Episode'][1],
				airdate.strftime('%d.%m.%Y %H:%M %Z'),
				eta)

	def keyword(self, nick, channel, kw, msg):
		target = channel if not channel == self.irc.nickname else nick.split('!')[0]
		args = msg.split()
		if len(args) == 0:
			self.irc.msg(target, 'Usage: !tv search')
			return

		self.irc.msg(target, self.find_show(' '.join(args)))

if __name__ == '__main__':
	import sys
	m = Module(None)
	print m.find_show(' '.join(sys.argv[1:]))