Tidy up for audio_lang. If we match more than one item we keep checking the matching...
[pyTivo/wmcbrine/lucasnz.git] / httpserver.py
blobc8c8faaec77d199dbb1558dfad3186415d497b9c
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 SERVER_INFO = """<?xml version="1.0" encoding="utf-8"?>
20 <TiVoServer>
21 <Version>1.6</Version>
22 <InternalName>pyTivo</InternalName>
23 <InternalVersion>1.0</InternalVersion>
24 <Organization>pyTivo Developers</Organization>
25 <Comment>http://pytivo.sf.net/</Comment>
26 </TiVoServer>"""
28 VIDEO_FORMATS = """<?xml version="1.0" encoding="utf-8"?>
29 <TiVoFormats>
30 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
31 </TiVoFormats>"""
33 VIDEO_FORMATS_TS = """<?xml version="1.0" encoding="utf-8"?>
34 <TiVoFormats>
35 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
36 <Format><ContentType>video/x-tivo-mpeg-ts</ContentType><Description/></Format>
37 </TiVoFormats>"""
39 BASE_HTML = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
40 "http://www.w3.org/TR/html4/strict.dtd">
41 <html> <head><title>pyTivo</title></head> <body> %s </body> </html>"""
43 RELOAD = '<p>The <a href="%s">page</a> will reload in %d seconds.</p>'
44 UNSUP = '<h3>Unsupported Command</h3> <p>Query:</p> <ul>%s</ul>'
46 class TivoHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
47 def __init__(self, server_address, RequestHandlerClass):
48 self.containers = {}
49 self.stop = False
50 self.restart = False
51 self.logger = logging.getLogger('pyTivo')
52 BaseHTTPServer.HTTPServer.__init__(self, server_address,
53 RequestHandlerClass)
54 self.daemon_threads = True
56 def add_container(self, name, settings):
57 if name in self.containers or name == 'TiVoConnect':
58 raise "Container Name in use"
59 try:
60 self.containers[name] = settings
61 except KeyError:
62 self.logger.error('Unable to add container ' + name)
64 def reset(self):
65 self.containers.clear()
66 for section, settings in config.getShares():
67 self.add_container(section, settings)
69 def handle_error(self, request, client_address):
70 self.logger.exception('Exception during request from %s' %
71 (client_address,))
73 def set_beacon(self, beacon):
74 self.beacon = beacon
76 def set_service_status(self, status):
77 self.in_service = status
79 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
80 def __init__(self, request, client_address, server):
81 self.wbufsize = 0x10000
82 self.server_version = 'pyTivo/1.0'
83 self.sys_version = ''
84 BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request,
85 client_address, server)
87 def address_string(self):
88 host, port = self.client_address[:2]
89 return host
91 def do_GET(self):
92 tsn = self.headers.getheader('TiVo_TCD_ID',
93 self.headers.getheader('tsn', ''))
94 if not self.authorize(tsn):
95 return
96 if tsn:
97 ip = self.address_string()
98 config.tivos[tsn] = ip
100 if not tsn in config.tivo_names or config.tivo_names[tsn] == tsn:
101 config.tivo_names[tsn] = self.server.beacon.get_name(ip)
103 if '?' in self.path:
104 path, opts = self.path.split('?', 1)
105 query = cgi.parse_qs(opts)
106 else:
107 path = self.path
108 query = {}
110 if path == '/TiVoConnect':
111 self.handle_query(query, tsn)
112 else:
113 ## Get File
114 splitpath = [x for x in unquote_plus(path).split('/') if x]
115 if splitpath:
116 self.handle_file(query, splitpath)
117 else:
118 ## Not a file not a TiVo command
119 self.infopage()
121 def do_POST(self):
122 tsn = self.headers.getheader('TiVo_TCD_ID',
123 self.headers.getheader('tsn', ''))
124 if not self.authorize(tsn):
125 return
126 ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
127 if ctype == 'multipart/form-data':
128 query = cgi.parse_multipart(self.rfile, pdict)
129 else:
130 length = int(self.headers.getheader('content-length'))
131 qs = self.rfile.read(length)
132 query = cgi.parse_qs(qs, keep_blank_values=1)
133 self.handle_query(query, tsn)
135 def do_command(self, query, command, target, tsn):
136 for name, container in config.getShares(tsn):
137 if target == name:
138 plugin = GetPlugin(container['type'])
139 if hasattr(plugin, command):
140 self.cname = name
141 self.container = container
142 method = getattr(plugin, command)
143 method(self, query)
144 return True
145 else:
146 break
147 return False
149 def handle_query(self, query, tsn):
150 mname = False
151 if 'Command' in query and len(query['Command']) >= 1:
153 command = query['Command'][0]
155 # If we are looking at the root container
156 if (command == 'QueryContainer' and
157 (not 'Container' in query or query['Container'][0] == '/')):
158 self.root_container()
159 return
161 if 'Container' in query:
162 # Dispatch to the container plugin
163 basepath = query['Container'][0].split('/')[0]
164 if self.do_command(query, command, basepath, tsn):
165 return
167 elif command == 'QueryItem':
168 path = query.get('Url', [''])[0]
169 splitpath = [x for x in unquote_plus(path).split('/') if x]
170 if splitpath and not '..' in splitpath:
171 if self.do_command(query, command, splitpath[0], tsn):
172 return
174 elif (command == 'QueryFormats' and 'SourceFormat' in query and
175 query['SourceFormat'][0].startswith('video')):
176 if config.hasTStivo(tsn):
177 self.send_xml(VIDEO_FORMATS_TS)
178 else:
179 self.send_xml(VIDEO_FORMATS)
180 return
182 elif command == 'QueryServer':
183 self.send_xml(SERVER_INFO)
184 return
186 elif command in ('FlushServer', 'ResetServer'):
187 # Does nothing -- included for completeness
188 self.send_response(200)
189 self.end_headers()
190 return
192 # If we made it here it means we couldn't match the request to
193 # anything.
194 self.unsupported(query)
196 def handle_file(self, query, splitpath):
197 if '..' not in splitpath: # Protect against path exploits
198 ## Pass it off to a plugin?
199 for name, container in self.server.containers.items():
200 if splitpath[0] == name:
201 self.cname = name
202 self.container = container
203 base = os.path.normpath(container['path'])
204 path = os.path.join(base, *splitpath[1:])
205 plugin = GetPlugin(container['type'])
206 plugin.send_file(self, path, query)
207 return
209 ## Serve it from a "content" directory?
210 base = os.path.join(SCRIPTDIR, *splitpath[:-1])
211 path = os.path.join(base, 'content', splitpath[-1])
213 if os.path.isfile(path):
214 try:
215 handle = open(path, 'rb')
216 except:
217 self.send_error(404)
218 return
220 # Send the header
221 mime = mimetypes.guess_type(path)[0]
222 self.send_response(200)
223 if mime:
224 self.send_header('Content-type', mime)
225 self.send_header('Content-length', os.path.getsize(path))
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 return
236 ## Give up
237 self.send_error(404)
239 def authorize(self, tsn=None):
240 # if allowed_clients is empty, we are completely open
241 allowed_clients = config.getAllowedClients()
242 if not allowed_clients or (tsn and config.isTsnInConfig(tsn)):
243 return True
244 client_ip = self.client_address[0]
245 for allowedip in allowed_clients:
246 if client_ip.startswith(allowedip):
247 return True
249 self.send_fixed('Unauthorized.', 'text/plain', 403)
250 return False
252 def log_message(self, format, *args):
253 self.server.logger.info("%s [%s] %s" % (self.address_string(),
254 self.log_date_time_string(), format%args))
256 def send_fixed(self, page, mime, code=200, refresh=''):
257 self.send_response(code)
258 self.send_header('Content-Type', mime)
259 self.send_header('Content-Length', len(page))
260 self.send_header('Connection', 'close')
261 self.send_header('Expires', '0')
262 if refresh:
263 self.send_header('Refresh', refresh)
264 self.end_headers()
265 self.wfile.write(page)
267 def send_xml(self, page):
268 self.send_fixed(page, 'text/xml')
270 def send_html(self, page, code=200, refresh=''):
271 self.send_fixed(page, 'text/html; charset=utf-8', code, refresh)
273 def root_container(self):
274 tsn = self.headers.getheader('TiVo_TCD_ID', '')
275 tsnshares = config.getShares(tsn)
276 tsncontainers = []
277 for section, settings in tsnshares:
278 try:
279 mime = GetPlugin(settings['type']).CONTENT_TYPE
280 if mime.split('/')[1] in ('tivo-videos', 'tivo-music',
281 'tivo-photos'):
282 settings['content_type'] = mime
283 tsncontainers.append((section, settings))
284 except Exception, msg:
285 self.server.logger.error(section + ' - ' + str(msg))
286 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
287 'root_container.tmpl'),
288 filter=EncodeUnicode)
289 t.containers = tsncontainers
290 t.hostname = socket.gethostname()
291 t.escape = escape
292 t.quote = quote
293 self.send_xml(str(t))
295 def infopage(self):
296 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
297 'info_page.tmpl'),
298 filter=EncodeUnicode)
299 t.admin = ''
301 if config.get_server('tivo_mak') and config.get_server('togo_path'):
302 t.togo = '<br>Pull from TiVos:<br>'
303 else:
304 t.togo = ''
306 if (config.get_server('tivo_username') and
307 config.get_server('tivo_password')):
308 t.shares = '<br>Push from video shares:<br>'
309 else:
310 t.shares = ''
312 for section, settings in config.getShares():
313 plugin_type = settings.get('type')
314 if plugin_type == 'settings':
315 t.admin += ('<a href="/TiVoConnect?Command=Settings&amp;' +
316 'Container=' + quote(section) +
317 '">Web Configuration</a><br>')
318 elif plugin_type == 'togo' and t.togo:
319 for tsn in config.tivos:
320 if tsn:
321 t.togo += ('<a href="/TiVoConnect?' +
322 'Command=NPL&amp;Container=' + quote(section) +
323 '&amp;TiVo=' + config.tivos[tsn] + '">' +
324 escape(config.tivo_names[tsn]) + '</a><br>')
325 elif plugin_type and t.shares:
326 plugin = GetPlugin(plugin_type)
327 if hasattr(plugin, 'Push'):
328 t.shares += ('<a href="/TiVoConnect?Command=' +
329 'QueryContainer&amp;Container=' +
330 quote(section) + '&Format=text/html">' +
331 section + '</a><br>')
333 self.send_html(str(t))
335 def unsupported(self, query):
336 message = UNSUP % '\n'.join(['<li>%s: %s</li>' % (escape(key),
337 escape(repr(value)))
338 for key, value in query.items()])
339 text = BASE_HTML % message
340 self.send_html(text, code=404)
342 def redir(self, message, seconds=2):
343 url = self.headers.getheader('Referer')
344 if url:
345 message += RELOAD % (escape(url), seconds)
346 refresh = '%d; url=%s' % (seconds, url)
347 else:
348 refresh = ''
349 text = (BASE_HTML % message).encode('utf-8')
350 self.send_html(text, refresh=refresh)