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