Single quotes.
[pyTivo/wmcbrine.git] / httpserver.py
blob79fee363fc1147170e61aa079f32c7f4ade4182d
1 import BaseHTTPServer
2 import SocketServer
3 import cgi
4 import logging
5 import os
6 import re
7 import socket
8 import time
9 from urllib import unquote_plus, quote, unquote
10 from urlparse import urlparse
11 from xml.sax.saxutils import escape
13 from Cheetah.Template import Template
14 import config
15 from plugin import GetPlugin
17 SCRIPTDIR = os.path.dirname(__file__)
19 VIDEO_FORMATS = """<?xml version="1.0" encoding="utf-8"?>
20 <TiVoFormats><Format>
21 <ContentType>video/x-tivo-mpeg</ContentType><Description/>
22 </Format></TiVoFormats>"""
24 class TivoHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
25 containers = {}
27 def __init__(self, server_address, RequestHandlerClass):
28 BaseHTTPServer.HTTPServer.__init__(self, server_address,
29 RequestHandlerClass)
30 self.daemon_threads = True
31 self.logger = logging.getLogger('pyTivo')
33 def add_container(self, name, settings):
34 if name in self.containers or name == 'TiVoConnect':
35 raise "Container Name in use"
36 try:
37 settings['content_type'] = GetPlugin(settings['type']).CONTENT_TYPE
38 self.containers[name] = settings
39 except KeyError:
40 print 'Unable to add container', name
42 def reset(self):
43 self.containers.clear()
44 for section, settings in config.getShares():
45 self.add_container(section, settings)
47 def handle_error(self, request, client_address):
48 self.logger.exception('Exception during request from %s' %
49 (client_address,))
51 def set_beacon(self, beacon):
52 self.beacon = beacon
54 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
55 tivos = {}
56 tivo_names = {}
58 def address_string(self):
59 host, port = self.client_address[:2]
60 return host
62 def do_GET(self):
63 tsn = self.headers.getheader('TiVo_TCD_ID',
64 self.headers.getheader('tsn', ''))
65 if tsn:
66 ip = self.address_string()
67 self.tivos[tsn] = ip
69 if not tsn in self.tivo_names:
70 self.tivo_names[tsn] = self.server.beacon.get_name(ip)
72 basepath = unquote_plus(self.path).split('/')[1]
74 ## Get File
75 for name, container in self.server.containers.items():
76 if basepath == name:
77 plugin = GetPlugin(container['type'])
78 plugin.send_file(self, container, name)
79 return
81 ## Not a file not a TiVo command
82 if not self.path.startswith('/TiVoConnect'):
83 self.infopage()
84 return
86 o = urlparse("http://fake.host" + self.path)
87 query = cgi.parse_qs(o[4])
89 self.handle_query(query)
91 def do_POST(self):
92 ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
93 if ctype == 'multipart/form-data':
94 query = cgi.parse_multipart(self.rfile, pdict)
95 else:
96 length = int(self.headers.getheader('content-length'))
97 qs = self.rfile.read(length)
98 query = cgi.parse_qs(qs, keep_blank_values=1)
99 self.handle_query(query)
101 def handle_query(self, query):
102 mname = False
103 if 'Command' in query and len(query['Command']) >= 1:
105 command = query['Command'][0]
107 # If we are looking at the root container
108 if (command == 'QueryContainer' and
109 (not 'Container' in query or query['Container'][0] == '/')):
110 self.root_container()
111 return
113 if 'Container' in query:
114 # Dispatch to the container plugin
115 basepath = unquote(query['Container'][0].split('/')[0])
116 for name, container in self.server.containers.items():
117 if basepath == name:
118 plugin = GetPlugin(container['type'])
119 if hasattr(plugin, command):
120 method = getattr(plugin, command)
121 method(self, query)
122 return
123 else:
124 break
126 elif (command == 'QueryFormats' and 'SourceFormat' in query and
127 query['SourceFormat'][0].startswith('video')):
128 self.send_response(200)
129 self.end_headers()
130 self.wfile.write(VIDEO_FORMATS)
131 return
133 # If we made it here it means we couldn't match the request to
134 # anything.
135 self.unsupported(query)
137 def log_message(self, format, *args):
138 self.server.logger.info("%s [%s] %s" % (self.address_string(),
139 self.log_date_time_string(), format%args))
141 def root_container(self):
142 tsn = self.headers.getheader('TiVo_TCD_ID', '')
143 tsnshares = config.getShares(tsn)
144 tsncontainers = {}
145 for section, settings in tsnshares:
146 try:
147 settings['content_type'] = \
148 GetPlugin(settings['type']).CONTENT_TYPE
149 tsncontainers[section] = settings
150 except Exception, msg:
151 print section, '-', msg
152 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
153 'root_container.tmpl'))
154 t.containers = tsncontainers
155 t.hostname = socket.gethostname()
156 t.escape = escape
157 t.quote = quote
158 self.send_response(200)
159 self.end_headers()
160 self.wfile.write(t)
162 def infopage(self):
163 self.send_response(200)
164 self.send_header('Content-type', 'text/html')
165 self.end_headers()
166 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
167 'info_page.tmpl'))
168 t.admin = ''
169 for section, settings in config.getShares():
170 if 'type' in settings and settings['type'] == 'admin':
171 t.admin += ('<a href="/TiVoConnect?Command=Admin&Container=' +
172 quote(section) +
173 '">Web Configuration</a><br>' +
174 '<a href="/TiVoConnect?Command=NPL&Container=' +
175 quote(section) + '">ToGo</a><br>')
176 if t.admin == '':
177 t.admin = ('<br><b>No Admin plugin installed in pyTivo.conf</b>' +
178 '<br> If you wish to use the admin plugin add the ' +
179 'following lines to pyTivo.conf<br><br>' +
180 '[Admin]<br>type=admin')
182 t.shares = 'Video shares:<br/>'
183 for section, settings in config.getShares():
184 if settings.get('type') == 'video':
185 t.shares += ('<a href="TiVoConnect?Command=QueryContainer&' +
186 'Container=' + quote(section) + '">' + section +
187 '</a><br/>')
189 self.wfile.write(t)
191 def unsupported(self, query):
192 self.send_response(404)
193 self.send_header('Content-type', 'text/html')
194 self.end_headers()
195 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
196 'unsupported.tmpl'))
197 t.query = query
198 self.wfile.write(t)
200 if __name__ == '__main__':
201 def start_server():
202 httpd = TivoHTTPServer(('', 9032), TivoHTTPHandler)
203 httpd.add_container('test', 'x-container/tivo-videos',
204 r'C:\Documents and Settings\Armooo' +
205 r'\Desktop\pyTivo\test')
206 httpd.serve_forever()
208 start_server()