pyTivo
[pyTivo/krkeegan.git] / httpserver.py
blob309917161db009029ffbcdc43b0b65821f2ebeaa
1 import time, os, BaseHTTPServer, SocketServer, socket, re
2 from urllib import unquote_plus, quote, unquote
3 from urlparse import urlparse
4 from cgi import parse_qs
5 from Cheetah.Template import Template
6 from plugin import GetPlugin
8 SCRIPTDIR = os.path.dirname(__file__)
10 class TivoHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
11 containers = {}
13 def __init__(self, server_address, RequestHandlerClass):
14 BaseHTTPServer.HTTPServer.__init__(self, server_address, RequestHandlerClass)
15 self.daemon_threads = True
17 def add_container(self, name, type, path):
18 if self.containers.has_key(name) or name == 'TivoConnect':
19 raise "Container Name in use"
20 self.containers[name] = {'type' : type, 'path' : path}
22 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
23 def do_GET(self):
25 ## Get File
26 for name, container in self.server.containers.items():
27 #XXX make a regex
28 if self.path.startswith('/' + name):
29 plugin = GetPlugin(container['type'])
30 plugin.SendFile(self, container, name)
31 return
33 ## Not a file not a TiVo command fuck them
34 if not self.path.startswith('/TiVoConnect'):
35 self.infopage()
36 return
38 o = urlparse("http://fake.host" + self.path)
39 query = parse_qs(o.query)
41 mname = False
42 if query.has_key('Command') and len(query['Command']) >= 1:
44 command = query['Command'][0]
46 #If we are looking at the root container
47 if command == "QueryContainer" and ( not query.has_key('Container') or query['Container'][0] == '/'):
48 self.RootContiner()
49 return
51 #Dispatch to the container plugin
52 plugin = GetPlugin(container['type'])
53 if plugin.commands.has_key(command):
54 method = plugin.commands[command]
55 method(self, query)
56 else:
57 self.unsuported(query)
58 else:
59 self.unsuported(query)
61 def RootContiner(self):
62 t = Template(file=os.path.join(SCRIPTDIR, 'templates', 'root_container.tmpl'))
63 t.containers = self.server.containers
64 t.hostname = socket.gethostname()
65 t.GetPlugin = GetPlugin
66 self.send_response(200)
67 self.end_headers()
68 self.wfile.write(t)
70 def infopage(self):
71 self.send_response(200)
72 self.send_header('Content-type', 'text/html')
73 self.end_headers()
74 t = Template(file=os.path.join(SCRIPTDIR, 'templates', 'info_page.tmpl'))
75 self.wfile.write(t)
76 self.end_headers()
78 def unsuported(self, query):
79 self.send_response(404)
80 self.send_header('Content-type', 'text/html')
81 self.end_headers()
82 t = Template(file=os.path.join(SCRIPTDIR,'templates','unsuported.tmpl'))
83 t.query = query
84 self.wfile.write(t)
86 if __name__ == '__main__':
87 def start_server():
88 httpd = TivoHTTPServer(('', 9032), TivoHTTPHandler)
89 httpd.add_container('test', 'x-container/tivo-videos', r'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')
90 httpd.serve_forever()
92 start_server()