More handling of missing names and addresses.
[pyTivo/wmcbrine.git] / httpserver.py
bloba7143d2855b7df45216031fc34488d4ae3e6406c
1 import BaseHTTPServer
2 import SocketServer
3 import cgi
4 import gzip
5 import logging
6 import mimetypes
7 import os
8 import shutil
9 import socket
10 import time
11 from cStringIO import StringIO
12 from email.utils import formatdate
13 from urllib import unquote_plus, quote
14 from xml.sax.saxutils import escape
16 from Cheetah.Template import Template
17 import config
18 from plugin import GetPlugin, EncodeUnicode
20 SCRIPTDIR = os.path.dirname(__file__)
22 SERVER_INFO = """<?xml version="1.0" encoding="utf-8"?>
23 <TiVoServer>
24 <Version>1.6</Version>
25 <InternalName>pyTivo</InternalName>
26 <InternalVersion>1.0</InternalVersion>
27 <Organization>pyTivo Developers</Organization>
28 <Comment>http://pytivo.sf.net/</Comment>
29 </TiVoServer>"""
31 VIDEO_FORMATS = """<?xml version="1.0" encoding="utf-8"?>
32 <TiVoFormats>
33 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
34 </TiVoFormats>"""
36 VIDEO_FORMATS_TS = """<?xml version="1.0" encoding="utf-8"?>
37 <TiVoFormats>
38 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
39 <Format><ContentType>video/x-tivo-mpeg-ts</ContentType><Description/></Format>
40 </TiVoFormats>"""
42 BASE_HTML = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
43 "http://www.w3.org/TR/html4/strict.dtd">
44 <html> <head><title>pyTivo</title>
45 <link rel="stylesheet" type="text/css" href="/main.css">
46 </head> <body> %s </body> </html>"""
48 RELOAD = '<p>The <a href="%s">page</a> will reload in %d seconds.</p>'
49 UNSUP = '<h3>Unsupported Command</h3> <p>Query:</p> <ul>%s</ul>'
51 class TivoHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
52 def __init__(self, server_address, RequestHandlerClass):
53 self.containers = {}
54 self.stop = False
55 self.restart = False
56 self.logger = logging.getLogger('pyTivo')
57 BaseHTTPServer.HTTPServer.__init__(self, server_address,
58 RequestHandlerClass)
59 self.daemon_threads = True
61 def add_container(self, name, settings):
62 if name in self.containers or name == 'TiVoConnect':
63 raise "Container Name in use"
64 try:
65 self.containers[name] = settings
66 except KeyError:
67 self.logger.error('Unable to add container ' + name)
69 def reset(self):
70 self.containers.clear()
71 for section, settings in config.getShares():
72 self.add_container(section, settings)
74 def handle_error(self, request, client_address):
75 self.logger.exception('Exception during request from %s' %
76 (client_address,))
78 def set_beacon(self, beacon):
79 self.beacon = beacon
81 def set_service_status(self, status):
82 self.in_service = status
84 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
85 def __init__(self, request, client_address, server):
86 self.wbufsize = 0x10000
87 self.server_version = 'pyTivo/1.0'
88 self.protocol_version = 'HTTP/1.1'
89 self.sys_version = ''
90 BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request,
91 client_address, server)
93 def address_string(self):
94 host, port = self.client_address[:2]
95 return host
97 def version_string(self):
98 """ Override version_string() so it doesn't include the Python
99 version.
102 return self.server_version
104 def do_GET(self):
105 tsn = self.headers.getheader('TiVo_TCD_ID',
106 self.headers.getheader('tsn', ''))
107 if not self.authorize(tsn):
108 return
110 if tsn and not config.tivos_found and not tsn in config.tivos:
111 ip = self.address_string()
112 name = self.server.beacon.get_name(ip)
113 config.tivos[tsn] = {'address': ip, 'name': name}
115 if '?' in self.path:
116 path, opts = self.path.split('?', 1)
117 query = cgi.parse_qs(opts)
118 else:
119 path = self.path
120 query = {}
122 if path == '/TiVoConnect':
123 self.handle_query(query, tsn)
124 else:
125 ## Get File
126 splitpath = [x for x in unquote_plus(path).split('/') if x]
127 if splitpath:
128 self.handle_file(query, splitpath)
129 else:
130 ## Not a file not a TiVo command
131 self.infopage()
133 def do_POST(self):
134 tsn = self.headers.getheader('TiVo_TCD_ID',
135 self.headers.getheader('tsn', ''))
136 if not self.authorize(tsn):
137 return
138 ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
139 if ctype == 'multipart/form-data':
140 query = cgi.parse_multipart(self.rfile, pdict)
141 else:
142 length = int(self.headers.getheader('content-length'))
143 qs = self.rfile.read(length)
144 query = cgi.parse_qs(qs, keep_blank_values=1)
145 self.handle_query(query, tsn)
147 def do_command(self, query, command, target, tsn):
148 for name, container in config.getShares(tsn):
149 if target == name:
150 plugin = GetPlugin(container['type'])
151 if hasattr(plugin, command):
152 self.cname = name
153 self.container = container
154 method = getattr(plugin, command)
155 method(self, query)
156 return True
157 else:
158 break
159 return False
161 def handle_query(self, query, tsn):
162 mname = False
163 if 'Command' in query and len(query['Command']) >= 1:
165 command = query['Command'][0]
167 # If we are looking at the root container
168 if (command == 'QueryContainer' and
169 (not 'Container' in query or query['Container'][0] == '/')):
170 self.root_container()
171 return
173 if 'Container' in query:
174 # Dispatch to the container plugin
175 basepath = query['Container'][0].split('/')[0]
176 if self.do_command(query, command, basepath, tsn):
177 return
179 elif command == 'QueryItem':
180 path = query.get('Url', [''])[0]
181 splitpath = [x for x in unquote_plus(path).split('/') if x]
182 if splitpath and not '..' in splitpath:
183 if self.do_command(query, command, splitpath[0], tsn):
184 return
186 elif (command == 'QueryFormats' and 'SourceFormat' in query and
187 query['SourceFormat'][0].startswith('video')):
188 if config.is_ts_capable(tsn):
189 self.send_xml(VIDEO_FORMATS_TS)
190 else:
191 self.send_xml(VIDEO_FORMATS)
192 return
194 elif command == 'QueryServer':
195 self.send_xml(SERVER_INFO)
196 return
198 elif command in ('FlushServer', 'ResetServer'):
199 # Does nothing -- included for completeness
200 self.send_response(200)
201 self.send_header('Content-Length', '0')
202 self.end_headers()
203 self.wfile.flush()
204 return
206 # If we made it here it means we couldn't match the request to
207 # anything.
208 self.unsupported(query)
210 def send_content_file(self, path):
211 lmdate = os.path.getmtime(path)
212 try:
213 handle = open(path, 'rb')
214 except:
215 self.send_error(404)
216 return
218 # Send the header
219 mime = mimetypes.guess_type(path)[0]
220 self.send_response(200)
221 if mime:
222 self.send_header('Content-Type', mime)
223 self.send_header('Content-Length', os.path.getsize(path))
224 self.send_header('Last-Modified', formatdate(lmdate))
225 self.end_headers()
227 # Send the body of the file
228 try:
229 shutil.copyfileobj(handle, self.wfile)
230 except:
231 pass
232 handle.close()
233 self.wfile.flush()
235 def handle_file(self, query, splitpath):
236 if '..' not in splitpath: # Protect against path exploits
237 ## Pass it off to a plugin?
238 for name, container in self.server.containers.items():
239 if splitpath[0] == name:
240 self.cname = name
241 self.container = container
242 base = os.path.normpath(container['path'])
243 path = os.path.join(base, *splitpath[1:])
244 plugin = GetPlugin(container['type'])
245 plugin.send_file(self, path, query)
246 return
248 ## Serve it from a "content" directory?
249 base = os.path.join(SCRIPTDIR, *splitpath[:-1])
250 path = os.path.join(base, 'content', splitpath[-1])
252 if os.path.isfile(path):
253 self.send_content_file(path)
254 return
256 ## Give up
257 self.send_error(404)
259 def authorize(self, tsn=None):
260 # if allowed_clients is empty, we are completely open
261 allowed_clients = config.getAllowedClients()
262 if not allowed_clients or (tsn and config.isTsnInConfig(tsn)):
263 return True
264 client_ip = self.client_address[0]
265 for allowedip in allowed_clients:
266 if client_ip.startswith(allowedip):
267 return True
269 self.send_fixed('Unauthorized.', 'text/plain', 403)
270 return False
272 def log_message(self, format, *args):
273 self.server.logger.info("%s [%s] %s" % (self.address_string(),
274 self.log_date_time_string(), format%args))
276 def send_fixed(self, page, mime, code=200, refresh=''):
277 squeeze = (len(page) > 256 and mime.startswith('text') and
278 'gzip' in self.headers.getheader('Accept-Encoding', ''))
279 if squeeze:
280 out = StringIO()
281 gzip.GzipFile(mode='wb', fileobj=out).write(page)
282 page = out.getvalue()
283 out.close()
284 self.send_response(code)
285 self.send_header('Content-Type', mime)
286 self.send_header('Content-Length', len(page))
287 if squeeze:
288 self.send_header('Content-Encoding', 'gzip')
289 self.send_header('Expires', '0')
290 if refresh:
291 self.send_header('Refresh', refresh)
292 self.end_headers()
293 self.wfile.write(page)
294 self.wfile.flush()
296 def send_xml(self, page):
297 self.send_fixed(page, 'text/xml')
299 def send_html(self, page, code=200, refresh=''):
300 self.send_fixed(page, 'text/html; charset=utf-8', code, refresh)
302 def root_container(self):
303 tsn = self.headers.getheader('TiVo_TCD_ID', '')
304 tsnshares = config.getShares(tsn)
305 tsncontainers = []
306 for section, settings in tsnshares:
307 try:
308 mime = GetPlugin(settings['type']).CONTENT_TYPE
309 if mime.split('/')[1] in ('tivo-videos', 'tivo-music',
310 'tivo-photos'):
311 settings['content_type'] = mime
312 tsncontainers.append((section, settings))
313 except Exception, msg:
314 self.server.logger.error(section + ' - ' + str(msg))
315 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
316 'root_container.tmpl'),
317 filter=EncodeUnicode)
318 if self.server.beacon.bd:
319 t.renamed = self.server.beacon.bd.renamed
320 else:
321 t.renamed = {}
322 t.containers = tsncontainers
323 t.hostname = socket.gethostname()
324 t.escape = escape
325 t.quote = quote
326 self.send_xml(str(t))
328 def infopage(self):
329 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
330 'info_page.tmpl'),
331 filter=EncodeUnicode)
332 t.admin = ''
334 if config.get_server('tivo_mak') and config.get_server('togo_path'):
335 t.togo = '<br>Pull from TiVos:<br>'
336 else:
337 t.togo = ''
339 if (config.get_server('tivo_username') and
340 config.get_server('tivo_password')):
341 t.shares = '<br>Push from video shares:<br>'
342 else:
343 t.shares = ''
345 for section, settings in config.getShares():
346 plugin_type = settings.get('type')
347 if plugin_type == 'settings':
348 t.admin += ('<a href="/TiVoConnect?Command=Settings&amp;' +
349 'Container=' + quote(section) +
350 '">Settings</a><br>')
351 elif plugin_type == 'togo' and t.togo:
352 for tsn in config.tivos:
353 if tsn and 'address' in config.tivos[tsn]:
354 t.togo += ('<a href="/TiVoConnect?' +
355 'Command=NPL&amp;Container=' + quote(section) +
356 '&amp;TiVo=' + config.tivos[tsn]['address'] +
357 '">' + config.tivos[tsn]['name'] +
358 '</a><br>')
359 elif plugin_type and t.shares:
360 plugin = GetPlugin(plugin_type)
361 if hasattr(plugin, 'Push'):
362 t.shares += ('<a href="/TiVoConnect?Command=' +
363 'QueryContainer&amp;Container=' +
364 quote(section) + '&Format=text/html">' +
365 section + '</a><br>')
367 self.send_html(str(t))
369 def unsupported(self, query):
370 message = UNSUP % '\n'.join(['<li>%s: %s</li>' % (key, repr(value))
371 for key, value in query.items()])
372 text = BASE_HTML % message
373 self.send_html(text, code=404)
375 def redir(self, message, seconds=2):
376 url = self.headers.getheader('Referer')
377 if url:
378 message += RELOAD % (url, seconds)
379 refresh = '%d; url=%s' % (seconds, url)
380 else:
381 refresh = ''
382 text = (BASE_HTML % message).encode('utf-8')
383 self.send_html(text, refresh=refresh)