Provide Unsupported response if container does not exist
[pyTivo.git] / httpserver.py
bloba3ddabb37c0d53f3def19692bac28d910fde5ecb
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
7 import config
8 from xml.sax.saxutils import escape
10 SCRIPTDIR = os.path.dirname(__file__)
12 debug = config.getDebug()
13 hack83 = config.getHack83()
15 def debug_write(data):
16 if debug:
17 debug_out = []
18 debug_out.append('httpserver.py - ')
19 for x in data:
20 debug_out.append(str(x))
21 fdebug = open('debug.txt', 'a')
22 fdebug.write(' '.join(debug_out))
23 fdebug.close()
25 class TivoHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
26 containers = {}
28 def __init__(self, server_address, RequestHandlerClass):
29 BaseHTTPServer.HTTPServer.__init__(self, server_address,
30 RequestHandlerClass)
31 self.daemon_threads = True
33 def add_container(self, name, settings):
34 if self.containers.has_key(name) or name == 'TiVoConnect':
35 raise "Container Name in use"
36 try:
37 settings['content_type'] = GetPlugin(settings['type']).CONTENT_TYPE
38 self.containers[name] = settings
39 except KeyError:
40 print 'Unable to add container', name
42 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
44 def address_string(self):
45 host, port = self.client_address[:2]
46 return host
48 def do_GET(self):
50 basepath = unquote_plus(self.path).split('/')[1]
52 ## Get File
53 for name, container in self.server.containers.items():
54 if basepath == name:
55 plugin = GetPlugin(container['type'])
56 plugin.send_file(self, container, name)
57 return
59 ## Not a file not a TiVo command fuck them
60 if not self.path.startswith('/TiVoConnect'):
61 self.infopage()
62 return
64 o = urlparse("http://fake.host" + self.path)
65 query = parse_qs(o[4])
67 mname = False
68 if query.has_key('Command') and len(query['Command']) >= 1:
70 command = query['Command'][0]
72 # If we are looking at the root container
73 if command == "QueryContainer" and \
74 (not query.has_key('Container') or query['Container'][0] == '/'):
75 self.root_container()
76 return
78 if query.has_key('Container'):
79 # Dispatch to the container plugin
80 for name, container in self.server.containers.items():
81 if query['Container'][0].startswith(name):
82 plugin = GetPlugin(container['type'])
83 if hasattr(plugin, command):
84 method = getattr(plugin, command)
85 method(self, query)
86 return
87 else:
88 self.unsupported(query)
89 return
90 break
92 #if we made it here it means we couldn't match the request to anything.
93 self.unsupported(query)
94 return
95 else:
96 self.unsupported(query)
98 def root_container(self):
99 tsn = self.headers.getheader('TiVo_TCD_ID', '')
100 tsnshares = config.getShares(tsn)
101 tsncontainers = {}
102 for section, settings in tsnshares:
103 try:
104 settings['content_type'] = GetPlugin(settings['type']).CONTENT_TYPE
105 tsncontainers[section] = settings
106 except:
107 None
108 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
109 'root_container.tmpl'))
110 t.containers = tsncontainers
111 t.hostname = socket.gethostname()
112 t.escape = escape
113 self.send_response(200)
114 self.end_headers()
115 self.wfile.write(t)
117 def infopage(self):
118 self.send_response(200)
119 self.send_header('Content-type', 'text/html')
120 self.end_headers()
121 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
122 'info_page.tmpl'))
123 self.wfile.write(t)
124 self.end_headers()
126 def unsupported(self, query):
127 if hack83 and 'Command' in query and 'Filter' in query:
128 debug_write(['Unsupported request,',
129 'checking to see if it is video.\n'])
130 command = query['Command'][0]
131 plugin = GetPlugin('video')
132 if ''.join(query['Filter']).find('video') >= 0 and \
133 hasattr(plugin, command):
134 debug_write(['Unsupported request,',
135 'yup it is video',
136 'send to video plugin for it to sort out.\n'])
137 method = getattr(plugin, command)
138 method(self, query)
139 return
141 self.send_response(404)
142 self.send_header('Content-type', 'text/html')
143 self.end_headers()
144 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
145 'unsupported.tmpl'))
146 t.query = query
147 self.wfile.write(t)
149 if __name__ == '__main__':
150 def start_server():
151 httpd = TivoHTTPServer(('', 9032), TivoHTTPHandler)
152 httpd.add_container('test', 'x-container/tivo-videos',
153 r'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')
154 httpd.serve_forever()
156 start_server()