10 from urllib
import unquote_plus
, quote
11 from xml
.sax
.saxutils
import escape
13 from Cheetah
.Template
import Template
15 from plugin
import GetPlugin
, EncodeUnicode
17 SCRIPTDIR
= os
.path
.dirname(__file__
)
19 VIDEO_FORMATS
= """<?xml version="1.0" encoding="utf-8"?>
21 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
24 VIDEO_FORMATS_TS
= """<?xml version="1.0" encoding="utf-8"?>
26 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
27 <Format><ContentType>video/x-tivo-mpeg-ts</ContentType><Description/></Format>
30 BASE_HTML
= """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
31 "http://www.w3.org/TR/html4/strict.dtd">
32 <html> <head><title>pyTivo</title></head> <body> %s </body> </html>"""
34 RELOAD
= '<p>The <a href="%s">page</a> will reload in %d seconds.</p>'
35 UNSUP
= '<h3>Unsupported Command</h3> <p>Query:</p> <ul>%s</ul>'
37 class TivoHTTPServer(SocketServer
.ThreadingMixIn
, BaseHTTPServer
.HTTPServer
):
40 def __init__(self
, server_address
, RequestHandlerClass
):
41 BaseHTTPServer
.HTTPServer
.__init
__(self
, server_address
,
43 self
.daemon_threads
= True
44 self
.logger
= logging
.getLogger('pyTivo')
46 def add_container(self
, name
, settings
):
47 if name
in self
.containers
or name
== 'TiVoConnect':
48 raise "Container Name in use"
50 self
.containers
[name
] = settings
52 self
.logger
.error('Unable to add container ' + name
)
55 self
.containers
.clear()
56 for section
, settings
in config
.getShares():
57 self
.add_container(section
, settings
)
59 def handle_error(self
, request
, client_address
):
60 self
.logger
.exception('Exception during request from %s' %
63 def set_beacon(self
, beacon
):
66 class TivoHTTPHandler(BaseHTTPServer
.BaseHTTPRequestHandler
):
67 def __init__(self
, request
, client_address
, server
):
68 self
.wbufsize
= 0x10000
69 self
.server_version
= 'pyTivo/1.0'
71 BaseHTTPServer
.BaseHTTPRequestHandler
.__init
__(self
, request
,
72 client_address
, server
)
74 def address_string(self
):
75 host
, port
= self
.client_address
[:2]
79 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
80 self
.headers
.getheader('tsn', ''))
81 if not self
.authorize(tsn
):
84 ip
= self
.address_string()
85 config
.tivos
[tsn
] = ip
87 if not tsn
in config
.tivo_names
or config
.tivo_names
[tsn
] == tsn
:
88 config
.tivo_names
[tsn
] = self
.server
.beacon
.get_name(ip
)
91 path
, opts
= self
.path
.split('?', 1)
92 query
= cgi
.parse_qs(opts
)
97 if path
== '/TiVoConnect':
98 self
.handle_query(query
, tsn
)
101 splitpath
= [x
for x
in unquote_plus(path
).split('/') if x
]
103 self
.handle_file(query
, splitpath
)
105 ## Not a file not a TiVo command
109 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
110 self
.headers
.getheader('tsn', ''))
111 if not self
.authorize(tsn
):
113 ctype
, pdict
= cgi
.parse_header(self
.headers
.getheader('content-type'))
114 if ctype
== 'multipart/form-data':
115 query
= cgi
.parse_multipart(self
.rfile
, pdict
)
117 length
= int(self
.headers
.getheader('content-length'))
118 qs
= self
.rfile
.read(length
)
119 query
= cgi
.parse_qs(qs
, keep_blank_values
=1)
120 self
.handle_query(query
, tsn
)
122 def handle_query(self
, query
, tsn
):
124 if 'Command' in query
and len(query
['Command']) >= 1:
126 command
= query
['Command'][0]
128 # If we are looking at the root container
129 if (command
== 'QueryContainer' and
130 (not 'Container' in query
or query
['Container'][0] == '/')):
131 self
.root_container()
134 if 'Container' in query
:
135 # Dispatch to the container plugin
136 basepath
= query
['Container'][0].split('/')[0]
137 for name
, container
in config
.getShares(tsn
):
139 plugin
= GetPlugin(container
['type'])
140 if hasattr(plugin
, command
):
141 method
= getattr(plugin
, command
)
147 elif (command
== 'QueryFormats' and 'SourceFormat' in query
and
148 query
['SourceFormat'][0].startswith('video')):
149 self
.send_response(200)
150 self
.send_header('Content-type', 'text/xml')
152 if config
.hasTStivo(tsn
):
153 self
.wfile
.write(VIDEO_FORMATS_TS
)
155 self
.wfile
.write(VIDEO_FORMATS
)
158 elif command
== 'FlushServer':
159 # Does nothing -- included for completeness
160 self
.send_response(200)
164 # If we made it here it means we couldn't match the request to
166 self
.unsupported(query
)
168 def handle_file(self
, query
, splitpath
):
169 if '..' not in splitpath
: # Protect against path exploits
170 ## Pass it off to a plugin?
171 for name
, container
in self
.server
.containers
.items():
172 if splitpath
[0] == name
:
173 base
= os
.path
.normpath(container
['path'])
174 path
= os
.path
.join(base
, *splitpath
[1:])
175 plugin
= GetPlugin(container
['type'])
176 plugin
.send_file(self
, path
, query
)
179 ## Serve it from a "content" directory?
180 base
= os
.path
.join(SCRIPTDIR
, *splitpath
[:-1])
181 path
= os
.path
.join(base
, 'content', splitpath
[-1])
183 if os
.path
.isfile(path
):
185 handle
= open(path
, 'rb')
191 mime
= mimetypes
.guess_type(path
)[0]
192 self
.send_response(200)
194 self
.send_header('Content-type', mime
)
195 self
.send_header('Content-length', os
.path
.getsize(path
))
198 # Send the body of the file
200 shutil
.copyfileobj(handle
, self
.wfile
)
209 def authorize(self
, tsn
=None):
210 # if allowed_clients is empty, we are completely open
211 allowed_clients
= config
.getAllowedClients()
212 if not allowed_clients
or (tsn
and config
.isTsnInConfig(tsn
)):
214 client_ip
= self
.client_address
[0]
215 for allowedip
in allowed_clients
:
216 if client_ip
.startswith(allowedip
):
219 self
.send_response(404)
220 self
.send_header('Content-type', 'text/plain')
222 self
.wfile
.write("Unauthorized.")
225 def log_message(self
, format
, *args
):
226 self
.server
.logger
.info("%s [%s] %s" % (self
.address_string(),
227 self
.log_date_time_string(), format
%args
))
229 def root_container(self
):
230 tsn
= self
.headers
.getheader('TiVo_TCD_ID', '')
231 tsnshares
= config
.getShares(tsn
)
233 for section
, settings
in tsnshares
:
235 settings
['content_type'] = \
236 GetPlugin(settings
['type']).CONTENT_TYPE
237 tsncontainers
.append((section
, settings
))
238 except Exception, msg
:
239 self
.server
.logger
.error(section
+ ' - ' + str(msg
))
240 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
241 'root_container.tmpl'),
242 filter=EncodeUnicode
)
243 t
.containers
= tsncontainers
244 t
.hostname
= socket
.gethostname()
247 self
.send_response(200)
248 self
.send_header('Content-type', 'text/xml')
253 self
.send_response(200)
254 self
.send_header('Content-type', 'text/html; charset=utf-8')
256 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
258 filter=EncodeUnicode
)
261 if config
.get_server('tivo_mak') and config
.get_server('togo_path'):
262 t
.togo
= '<br>Pull from TiVos:<br>'
266 if (config
.get_server('tivo_username') and
267 config
.get_server('tivo_password')):
268 t
.shares
= '<br>Push from video shares:<br>'
272 for section
, settings
in config
.getShares():
273 plugin_type
= settings
.get('type')
274 if plugin_type
== 'settings':
275 t
.admin
+= ('<a href="/TiVoConnect?Command=Settings&' +
276 'Container=' + quote(section
) +
277 '">Web Configuration</a><br>')
278 elif plugin_type
== 'togo' and t
.togo
:
279 for tsn
in config
.tivos
:
281 t
.togo
+= ('<a href="/TiVoConnect?' +
282 'Command=NPL&Container=' + quote(section
) +
283 '&TiVo=' + config
.tivos
[tsn
] + '">' +
284 escape(config
.tivo_names
[tsn
]) + '</a><br>')
285 elif plugin_type
== 'video' and t
.shares
:
286 t
.shares
+= ('<a href="TiVoConnect?Command=' +
287 'QueryContainer&Container=' +
288 quote(section
) + '&Format=text/html">' +
289 section
+ '</a><br>')
293 def unsupported(self
, query
):
294 message
= UNSUP
% '\n'.join(['<li>%s: %s</li>' % (escape(key
),
296 for key
, value
in query
.items()])
297 text
= BASE_HTML
% message
298 self
.send_response(404)
299 self
.send_header('Content-Type', 'text/html; charset=utf-8')
300 self
.send_header('Content-Length', len(text
))
302 self
.wfile
.write(text
)
304 def redir(self
, message
, seconds
=2):
305 url
= self
.headers
.getheader('Referer')
307 message
+= RELOAD
% (escape(url
), seconds
)
308 text
= (BASE_HTML
% message
).encode('utf-8')
309 self
.send_response(200)
310 self
.send_header('Content-Type', 'text/html; charset=utf-8')
311 self
.send_header('Content-Length', len(text
))
312 self
.send_header('Expires', '0')
314 self
.send_header('Refresh', '%d; url=%s' % (seconds
, url
))
316 self
.wfile
.write(text
)