Allow restart/quit to work from the Windows service. Not yet tested.
[pyTivo/wmcbrine/lucasnz.git] / httpserver.py
blob2f812d981adbf8b7e18c699a865a94149c611d2e
1 import BaseHTTPServer
2 import SocketServer
3 import cgi
4 import logging
5 import mimetypes
6 import os
7 import shutil
8 import socket
9 import time
10 from urllib import unquote_plus, quote
11 from xml.sax.saxutils import escape
13 from Cheetah.Template import Template
14 import config
15 from plugin import GetPlugin, EncodeUnicode
17 SCRIPTDIR = os.path.dirname(__file__)
19 VIDEO_FORMATS = """<?xml version="1.0" encoding="utf-8"?>
20 <TiVoFormats>
21 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
22 </TiVoFormats>"""
24 VIDEO_FORMATS_TS = """<?xml version="1.0" encoding="utf-8"?>
25 <TiVoFormats>
26 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
27 <Format><ContentType>video/x-tivo-mpeg-ts</ContentType><Description/></Format>
28 </TiVoFormats>"""
30 BASE_HTML = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
31 "http://www.w3.org/TR/html4/strict.dtd">
32 <html> <head><title>pyTivo</title></head> <body> %s </body> </html>"""
34 RELOAD = '<p>The <a href="%s">page</a> will reload in %d seconds.</p>'
35 UNSUP = '<h3>Unsupported Command</h3> <p>Query:</p> <ul>%s</ul>'
37 class TivoHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
38 def __init__(self, server_address, RequestHandlerClass):
39 self.containers = {}
40 self.stop = False
41 self.restart = False
42 self.logger = logging.getLogger('pyTivo')
43 BaseHTTPServer.HTTPServer.__init__(self, server_address,
44 RequestHandlerClass)
46 def add_container(self, name, settings):
47 if name in self.containers or name == 'TiVoConnect':
48 raise "Container Name in use"
49 try:
50 self.containers[name] = settings
51 except KeyError:
52 self.logger.error('Unable to add container ' + name)
54 def reset(self):
55 self.containers.clear()
56 for section, settings in config.getShares():
57 self.add_container(section, settings)
59 def handle_error(self, request, client_address):
60 self.logger.exception('Exception during request from %s' %
61 (client_address,))
63 def set_beacon(self, beacon):
64 self.beacon = beacon
66 def set_service_status(self, status):
67 self.in_service = status
69 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
70 def __init__(self, request, client_address, server):
71 self.wbufsize = 0x10000
72 self.server_version = 'pyTivo/1.0'
73 self.sys_version = ''
74 BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request,
75 client_address, server)
77 def address_string(self):
78 host, port = self.client_address[:2]
79 return host
81 def do_GET(self):
82 tsn = self.headers.getheader('TiVo_TCD_ID',
83 self.headers.getheader('tsn', ''))
84 if not self.authorize(tsn):
85 return
86 if tsn:
87 ip = self.address_string()
88 config.tivos[tsn] = ip
90 if not tsn in config.tivo_names or config.tivo_names[tsn] == tsn:
91 config.tivo_names[tsn] = self.server.beacon.get_name(ip)
93 if '?' in self.path:
94 path, opts = self.path.split('?', 1)
95 query = cgi.parse_qs(opts)
96 else:
97 path = self.path
98 query = {}
100 if path == '/TiVoConnect':
101 self.handle_query(query, tsn)
102 else:
103 ## Get File
104 splitpath = [x for x in unquote_plus(path).split('/') if x]
105 if splitpath:
106 self.handle_file(query, splitpath)
107 else:
108 ## Not a file not a TiVo command
109 self.infopage()
111 def do_POST(self):
112 tsn = self.headers.getheader('TiVo_TCD_ID',
113 self.headers.getheader('tsn', ''))
114 if not self.authorize(tsn):
115 return
116 ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
117 if ctype == 'multipart/form-data':
118 query = cgi.parse_multipart(self.rfile, pdict)
119 else:
120 length = int(self.headers.getheader('content-length'))
121 qs = self.rfile.read(length)
122 query = cgi.parse_qs(qs, keep_blank_values=1)
123 self.handle_query(query, tsn)
125 def handle_query(self, query, tsn):
126 mname = False
127 if 'Command' in query and len(query['Command']) >= 1:
129 command = query['Command'][0]
131 # If we are looking at the root container
132 if (command == 'QueryContainer' and
133 (not 'Container' in query or query['Container'][0] == '/')):
134 self.root_container()
135 return
137 if 'Container' in query:
138 # Dispatch to the container plugin
139 basepath = query['Container'][0].split('/')[0]
140 for name, container in config.getShares(tsn):
141 if basepath == name:
142 plugin = GetPlugin(container['type'])
143 if hasattr(plugin, command):
144 method = getattr(plugin, command)
145 method(self, query)
146 return
147 else:
148 break
150 elif (command == 'QueryFormats' and 'SourceFormat' in query and
151 query['SourceFormat'][0].startswith('video')):
152 self.send_response(200)
153 self.send_header('Content-type', 'text/xml')
154 self.end_headers()
155 if config.hasTStivo(tsn):
156 self.wfile.write(VIDEO_FORMATS_TS)
157 else:
158 self.wfile.write(VIDEO_FORMATS)
159 return
161 elif command == 'FlushServer':
162 # Does nothing -- included for completeness
163 self.send_response(200)
164 self.end_headers()
165 return
167 # If we made it here it means we couldn't match the request to
168 # anything.
169 self.unsupported(query)
171 def handle_file(self, query, splitpath):
172 if '..' not in splitpath: # Protect against path exploits
173 ## Pass it off to a plugin?
174 for name, container in self.server.containers.items():
175 if splitpath[0] == name:
176 base = os.path.normpath(container['path'])
177 path = os.path.join(base, *splitpath[1:])
178 plugin = GetPlugin(container['type'])
179 plugin.send_file(self, path, query)
180 return
182 ## Serve it from a "content" directory?
183 base = os.path.join(SCRIPTDIR, *splitpath[:-1])
184 path = os.path.join(base, 'content', splitpath[-1])
186 if os.path.isfile(path):
187 try:
188 handle = open(path, 'rb')
189 except:
190 self.send_error(404)
191 return
193 # Send the header
194 mime = mimetypes.guess_type(path)[0]
195 self.send_response(200)
196 if mime:
197 self.send_header('Content-type', mime)
198 self.send_header('Content-length', os.path.getsize(path))
199 self.end_headers()
201 # Send the body of the file
202 try:
203 shutil.copyfileobj(handle, self.wfile)
204 except:
205 pass
206 handle.close()
207 return
209 ## Give up
210 self.send_error(404)
212 def authorize(self, tsn=None):
213 # if allowed_clients is empty, we are completely open
214 allowed_clients = config.getAllowedClients()
215 if not allowed_clients or (tsn and config.isTsnInConfig(tsn)):
216 return True
217 client_ip = self.client_address[0]
218 for allowedip in allowed_clients:
219 if client_ip.startswith(allowedip):
220 return True
222 self.send_response(404)
223 self.send_header('Content-type', 'text/plain')
224 self.end_headers()
225 self.wfile.write("Unauthorized.")
226 return False
228 def log_message(self, format, *args):
229 self.server.logger.info("%s [%s] %s" % (self.address_string(),
230 self.log_date_time_string(), format%args))
232 def root_container(self):
233 tsn = self.headers.getheader('TiVo_TCD_ID', '')
234 tsnshares = config.getShares(tsn)
235 tsncontainers = []
236 for section, settings in tsnshares:
237 try:
238 settings['content_type'] = \
239 GetPlugin(settings['type']).CONTENT_TYPE
240 tsncontainers.append((section, settings))
241 except Exception, msg:
242 self.server.logger.error(section + ' - ' + str(msg))
243 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
244 'root_container.tmpl'),
245 filter=EncodeUnicode)
246 t.containers = tsncontainers
247 t.hostname = socket.gethostname()
248 t.escape = escape
249 t.quote = quote
250 self.send_response(200)
251 self.send_header('Content-type', 'text/xml')
252 self.end_headers()
253 self.wfile.write(t)
255 def infopage(self):
256 useragent = self.headers.getheader('User-Agent', '')
257 self.send_response(200)
258 self.send_header('Content-type', 'text/html; charset=utf-8')
259 self.end_headers()
260 if useragent.lower().find('mobile') > 0:
261 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
262 'info_page_mob.tmpl'),
263 filter=EncodeUnicode)
264 else:
265 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
266 'info_page.tmpl'),
267 filter=EncodeUnicode)
268 t.admin = ''
270 if config.get_server('tivo_mak') and config.get_server('togo_path'):
271 t.togo = 'Pull from TiVos:<br>'
272 else:
273 t.togo = ''
275 if (config.get_server('tivo_username') and
276 config.get_server('tivo_password')):
277 t.shares = 'Push from video shares:<br>'
278 else:
279 t.shares = ''
281 for section, settings in config.getShares():
282 plugin_type = settings.get('type')
283 if plugin_type == 'settings':
284 t.admin += ('<a href="/TiVoConnect?Command=Settings&amp;' +
285 'Container=' + quote(section) +
286 '">Web Configuration</a><br>')
287 elif plugin_type == 'togo' and t.togo:
288 for tsn in config.tivos:
289 if tsn:
290 t.togo += ('<a href="/TiVoConnect?' +
291 'Command=NPL&amp;Container=' + quote(section) +
292 '&amp;TiVo=' + config.tivos[tsn] + '">' +
293 escape(config.tivo_names[tsn]) + '</a><br>')
294 elif ( plugin_type == 'video' or plugin_type == 'dvdvideo' ) \
295 and t.shares:
296 t.shares += ('<a href="TiVoConnect?Command=' +
297 'QueryContainer&amp;Container=' +
298 quote(section) + '&Format=text/html">' +
299 section + '</a><br>')
301 self.wfile.write(t)
303 def unsupported(self, query):
304 message = UNSUP % '\n'.join(['<li>%s: %s</li>' % (escape(key),
305 escape(repr(value)))
306 for key, value in query.items()])
307 text = BASE_HTML % message
308 self.send_response(404)
309 self.send_header('Content-Type', 'text/html; charset=utf-8')
310 self.send_header('Content-Length', len(text))
311 self.end_headers()
312 self.wfile.write(text)
314 def redir(self, message, seconds=2):
315 url = self.headers.getheader('Referer')
316 if url:
317 message += RELOAD % (escape(url), seconds)
318 text = (BASE_HTML % message).encode('utf-8')
319 self.send_response(200)
320 self.send_header('Content-Type', 'text/html; charset=utf-8')
321 self.send_header('Content-Length', len(text))
322 self.send_header('Expires', '0')
323 if url:
324 self.send_header('Refresh', '%d; url=%s' % (seconds, url))
325 self.end_headers()
326 self.wfile.write(text)