Include the timestamp and IP in the log messages.
[pyTivo/wmcbrine.git] / httpserver.py
blob3a43fb3b2dae3416a1257e6e348f6a6de140ee3b
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
32 def add_container(self, name, settings):
33 if name in self.containers or name == 'TiVoConnect':
34 raise "Container Name in use"
35 try:
36 settings['content_type'] = GetPlugin(settings['type']).CONTENT_TYPE
37 self.containers[name] = settings
38 except KeyError:
39 print 'Unable to add container', name
41 def reset(self):
42 self.containers.clear()
43 for section, settings in config.getShares():
44 self.add_container(section, settings)
46 def handle_error(self, request, client_address):
47 logging.getLogger("pyTivo").exception("Exception during request from %s" % (client_address,))
49 def set_beacon(self, beacon):
50 self.beacon = beacon
52 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
53 tivos = {}
54 tivo_names = {}
56 def address_string(self):
57 host, port = self.client_address[:2]
58 return host
60 def do_GET(self):
61 tsn = self.headers.getheader('TiVo_TCD_ID',
62 self.headers.getheader('tsn', ''))
63 if tsn:
64 ip = self.address_string()
65 self.tivos[tsn] = ip
67 if not tsn in self.tivo_names:
68 self.tivo_names[tsn] = self.server.beacon.get_name(ip)
70 basepath = unquote_plus(self.path).split('/')[1]
72 ## Get File
73 for name, container in self.server.containers.items():
74 if basepath == name:
75 plugin = GetPlugin(container['type'])
76 plugin.send_file(self, container, name)
77 return
79 ## Not a file not a TiVo command
80 if not self.path.startswith('/TiVoConnect'):
81 self.infopage()
82 return
84 o = urlparse("http://fake.host" + self.path)
85 query = cgi.parse_qs(o[4])
87 self.handle_query(query)
89 def do_POST(self):
90 ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
91 if ctype == 'multipart/form-data':
92 query = cgi.parse_multipart(self.rfile, pdict)
93 else:
94 length = int(self.headers.getheader('content-length'))
95 qs = self.rfile.read(length)
96 query = cgi.parse_qs(qs, keep_blank_values=1)
97 self.handle_query(query)
99 def handle_query(self, query):
100 mname = False
101 if 'Command' in query and len(query['Command']) >= 1:
103 command = query['Command'][0]
105 # If we are looking at the root container
106 if (command == 'QueryContainer' and
107 (not 'Container' in query or query['Container'][0] == '/')):
108 self.root_container()
109 return
111 if 'Container' in query:
112 # Dispatch to the container plugin
113 basepath = unquote(query['Container'][0].split('/')[0])
114 for name, container in self.server.containers.items():
115 if basepath == name:
116 plugin = GetPlugin(container['type'])
117 if hasattr(plugin, command):
118 method = getattr(plugin, command)
119 method(self, query)
120 return
121 else:
122 break
124 elif (command == 'QueryFormats' and 'SourceFormat' in query and
125 query['SourceFormat'][0].startswith('video')):
126 self.send_response(200)
127 self.end_headers()
128 self.wfile.write(VIDEO_FORMATS)
129 return
131 # If we made it here it means we couldn't match the request to
132 # anything.
133 self.unsupported(query)
135 def log_message(self, format, *args):
136 logging.getLogger("pyTivo").info("%s [%s] %s" %
137 (self.address_string(),
138 self.log_date_time_string(),
139 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()