summaryrefslogtreecommitdiff
path: root/modules/tvrage.py
blob: 02675cb3863b4d2c4e2dc6755db2c4625fbe9514 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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('<pre>'):
			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:]))