Ratings from .nfo files should no longer be converted to strings.
[pyTivo/wmcbrine.git] / httpserver.py
blob7b46ca4ff177fdbef51d50d7f2a0acae21a4a70b
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 or tsn in config.tivos):
111 attr = config.tivos.get(tsn, {})
112 if 'address' not in attr:
113 attr['address'] = self.address_string()
114 if 'name' not in attr:
115 attr['name'] = self.server.beacon.get_name(attr['address'])
116 config.tivos[tsn] = attr
118 if '?' in self.path:
119 path, opts = self.path.split('?', 1)
120 query = cgi.parse_qs(opts)
121 else:
122 path = self.path
123 query = {}
125 if path == '/TiVoConnect':
126 self.handle_query(query, tsn)
127 else:
128 ## Get File
129 splitpath = [x for x in unquote_plus(path).split('/') if x]
130 if splitpath:
131 self.handle_file(query, splitpath)
132 else:
133 ## Not a file not a TiVo command
134 self.infopage()
136 def do_POST(self):
137 tsn = self.headers.getheader('TiVo_TCD_ID',
138 self.headers.getheader('tsn', ''))
139 if not self.authorize(tsn):
140 return
141 ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
142 if ctype == 'multipart/form-data':
143 query = cgi.parse_multipart(self.rfile, pdict)
144 else:
145 length = int(self.headers.getheader('content-length'))
146 qs = self.rfile.read(length)
147 query = cgi.parse_qs(qs, keep_blank_values=1)
148 self.handle_query(query, tsn)
150 def do_command(self, query, command, target, tsn):
151 for name, container in config.getShares(tsn):
152 if target == name:
153 plugin = GetPlugin(container['type'])
154 if hasattr(plugin, command):
155 self.cname = name
156 self.container = container
157 method = getattr(plugin, command)
158 method(self, query)
159 return True
160 else:
161 break
162 return False
164 def handle_query(self, query, tsn):
165 mname = False
166 if 'Command' in query and len(query['Command']) >= 1:
168 command = query['Command'][0]
170 # If we are looking at the root container
171 if (command == 'QueryContainer' and
172 (not 'Container' in query or query['Container'][0] == '/')):
173 self.root_container()
174 return
176 if 'Container' in query:
177 # Dispatch to the container plugin
178 basepath = query['Container'][0].split('/')[0]
179 if self.do_command(query, command, basepath, tsn):
180 return
182 elif command == 'QueryItem':
183 path = query.get('Url', [''])[0]
184 splitpath = [x for x in unquote_plus(path).split('/') if x]
185 if splitpath and not '..' in splitpath:
186 if self.do_command(query, command, splitpath[0], tsn):
187 return
189 elif (command == 'QueryFormats' and 'SourceFormat' in query and
190 query['SourceFormat'][0].startswith('video')):
191 if config.is_ts_capable(tsn):
192 self.send_xml(VIDEO_FORMATS_TS)
193 else:
194 self.send_xml(VIDEO_FORMATS)
195 return
197 elif command == 'QueryServer':
198 self.send_xml(SERVER_INFO)
199 return
201 elif command in ('FlushServer', 'ResetServer'):
202 # Does nothing -- included for completeness
203 self.send_response(200)
204 self.send_header('Content-Length', '0')
205 self.end_headers()
206 self.wfile.flush()
207 return
209 # If we made it here it means we couldn't match the request to
210 # anything.
211 self.unsupported(query)
213 def send_content_file(self, path):
214 lmdate = os.path.getmtime(path)
215 try:
216 handle = open(path, 'rb')
217 except:
218 self.send_error(404)
219 return
221 # Send the header
222 mime = mimetypes.guess_type(path)[0]
223 self.send_response(200)
224 if mime:
225 self.send_header('Content-Type', mime)
226 self.send_header('Content-Length', os.path.getsize(path))
227 self.send_header('Last-Modified', formatdate(lmdate))
228 self.end_headers()
230 # Send the body of the file
231 try:
232 shutil.copyfileobj(handle, self.wfile)
233 except:
234 pass
235 handle.close()
236 self.wfile.flush()
238 def handle_file(self, query, splitpath):
239 if '..' not in splitpath: # Protect against path exploits
240 ## Pass it off to a plugin?
241 for name, container in self.server.containers.items():
242 if splitpath[0] == name:
243 self.cname = name
244 self.container = container
245 base = os.path.normpath(container['path'])
246 path = os.path.join(base, *splitpath[1:])
247 plugin = GetPlugin(container['type'])
248 plugin.send_file(self, path, query)
249 return
251 ## Serve it from a "content" directory?
252 base = os.path.join(SCRIPTDIR, *splitpath[:-1])
253 path = os.path.join(base, 'content', splitpath[-1])
255 if os.path.isfile(path):
256 self.send_content_file(path)
257 return
259 ## Give up
260 self.send_error(404)
262 def authorize(self, tsn=None):
263 # if allowed_clients is empty, we are completely open
264 allowed_clients = config.getAllowedClients()
265 if not allowed_clients or (tsn and config.isTsnInConfig(tsn)):
266 return True
267 client_ip = self.client_address[0]
268 for allowedip in allowed_clients:
269 if client_ip.startswith(allowedip):
270 return True
272 self.send_fixed('Unauthorized.', 'text/plain', 403)
273 return False
275 def log_message(self, format, *args):
276 self.server.logger.info("%s [%s] %s" % (self.address_string(),
277 self.log_date_time_string(), format%args))
279 def send_fixed(self, page, mime, code=200, refresh=''):
280 squeeze = (len(page) > 256 and mime.startswith('text') and
281 'gzip' in self.headers.getheader('Accept-Encoding', ''))
282 if squeeze:
283 out = StringIO()
284 gzip.GzipFile(mode='wb', fileobj=out).write(page)
285 page = out.getvalue()
286 out.close()
287 self.send_response(code)
288 self.send_header('Content-Type', mime)
289 self.send_header('Content-Length', len(page))
290 if squeeze:
291 self.send_header('Content-Encoding', 'gzip')
292 self.send_header('Expires', '0')
293 if refresh:
294 self.send_header('Refresh', refresh)
295 self.end_headers()
296 self.wfile.write(page)
297 self.wfile.flush()
299 def send_xml(self, page):
300 self.send_fixed(page, 'text/xml')
302 def send_html(self, page, code=200, refresh=''):
303 self.send_fixed(page, 'text/html; charset=utf-8', code, refresh)
305 def root_container(self):
306 tsn = self.headers.getheader('TiVo_TCD_ID', '')
307 tsnshares = config.getShares(tsn)
308 tsncontainers = []
309 for section, settings in tsnshares:
310 try:
311 mime = GetPlugin(settings['type']).CONTENT_TYPE
312 if mime.split('/')[1] in ('tivo-videos', 'tivo-music',
313 'tivo-photos'):
314 settings['content_type'] = mime
315 tsncontainers.append((section, settings))
316 except Exception, msg:
317 self.server.logger.error(section + ' - ' + str(msg))
318 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
319 'root_container.tmpl'),
320 filter=EncodeUnicode)
321 if self.server.beacon.bd:
322 t.renamed = self.server.beacon.bd.renamed
323 else:
324 t.renamed = {}
325 t.containers = tsncontainers
326 t.hostname = socket.gethostname()
327 t.escape = escape
328 t.quote = quote
329 self.send_xml(str(t))
331 def infopage(self):
332 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
333 'info_page.tmpl'),
334 filter=EncodeUnicode)
335 t.admin = ''
337 if config.get_server('tivo_mak') and config.get_server('togo_path'):
338 t.togo = '<br>Pull from TiVos:<br>'
339 else:
340 t.togo = ''
342 if (config.get_server('tivo_username') and
343 config.get_server('tivo_password')):
344 t.shares = '<br>Push from video shares:<br>'
345 else:
346 t.shares = ''
348 for section, settings in config.getShares():
349 plugin_type = settings.get('type')
350 if plugin_type == 'settings':
351 t.admin += ('<a href="/TiVoConnect?Command=Settings&amp;' +
352 'Container=' + quote(section) +
353 '">Settings</a><br>')
354 elif plugin_type == 'togo' and t.togo:
355 for tsn in config.tivos:
356 if tsn and 'address' in config.tivos[tsn]:
357 t.togo += ('<a href="/TiVoConnect?' +
358 'Command=NPL&amp;Container=' + quote(section) +
359 '&amp;TiVo=' + config.tivos[tsn]['address'] +
360 '">' + config.tivos[tsn]['name'] +
361 '</a><br>')
362 elif plugin_type and t.shares:
363 plugin = GetPlugin(plugin_type)
364 if hasattr(plugin, 'Push'):
365 t.shares += ('<a href="/TiVoConnect?Command=' +
366 'QueryContainer&amp;Container=' +
367 quote(section) + '&Format=text/html">' +
368 section + '</a><br>')
370 self.send_html(str(t))
372 def unsupported(self, query):
373 message = UNSUP % '\n'.join(['<li>%s: %s</li>' % (key, repr(value))
374 for key, value in query.items()])
375 text = BASE_HTML % message
376 self.send_html(text, code=404)
378 def redir(self, message, seconds=2):
379 url = self.headers.getheader('Referer')
380 if url:
381 message += RELOAD % (url, seconds)
382 refresh = '%d; url=%s' % (seconds, url)
383 else:
384 refresh = ''
385 text = (BASE_HTML % message).encode('utf-8')
386 self.send_html(text, refresh=refresh)