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
18 from plugin
import GetPlugin
, EncodeUnicode
20 SCRIPTDIR
= os
.path
.dirname(__file__
)
22 SERVER_INFO
= """<?xml version="1.0" encoding="utf-8"?>
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>
31 VIDEO_FORMATS
= """<?xml version="1.0" encoding="utf-8"?>
33 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
36 VIDEO_FORMATS_TS
= """<?xml version="1.0" encoding="utf-8"?>
38 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
39 <Format><ContentType>video/x-tivo-mpeg-ts</ContentType><Description/></Format>
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
):
56 self
.logger
= logging
.getLogger('pyTivo')
57 BaseHTTPServer
.HTTPServer
.__init
__(self
, server_address
,
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"
65 self
.containers
[name
] = settings
67 self
.logger
.error('Unable to add container ' + name
)
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' %
78 def set_beacon(self
, 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'
90 BaseHTTPServer
.BaseHTTPRequestHandler
.__init
__(self
, request
,
91 client_address
, server
)
93 def address_string(self
):
94 host
, port
= self
.client_address
[:2]
97 def version_string(self
):
98 """ Override version_string() so it doesn't include the Python
102 return self
.server_version
105 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
106 self
.headers
.getheader('tsn', ''))
107 if not self
.authorize(tsn
):
110 if tsn
and (not config
.tivos_found
or tsn
in config
.tivos
):
111 attr
= config
.tivos
.get(tsn
, {})
112 if 'address' not in attr
:
113 attr
['address'] = self
.address_string()
114 if 'name' not in attr
:
115 attr
['name'] = self
.server
.beacon
.get_name(attr
['address'])
116 config
.tivos
[tsn
] = attr
119 path
, opts
= self
.path
.split('?', 1)
120 query
= cgi
.parse_qs(opts
)
125 if path
== '/TiVoConnect':
126 self
.handle_query(query
, tsn
)
129 splitpath
= [x
for x
in unquote_plus(path
).split('/') if x
]
131 self
.handle_file(query
, splitpath
)
133 ## Not a file not a TiVo command
137 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
138 self
.headers
.getheader('tsn', ''))
139 if not self
.authorize(tsn
):
141 ctype
, pdict
= cgi
.parse_header(self
.headers
.getheader('content-type'))
142 if ctype
== 'multipart/form-data':
143 query
= cgi
.parse_multipart(self
.rfile
, pdict
)
145 length
= int(self
.headers
.getheader('content-length'))
146 qs
= self
.rfile
.read(length
)
147 query
= cgi
.parse_qs(qs
, keep_blank_values
=1)
148 self
.handle_query(query
, tsn
)
150 def do_command(self
, query
, command
, target
, tsn
):
151 for name
, container
in config
.getShares(tsn
):
153 plugin
= GetPlugin(container
['type'])
154 if hasattr(plugin
, command
):
156 self
.container
= container
157 method
= getattr(plugin
, command
)
164 def handle_query(self
, query
, tsn
):
166 if 'Command' in query
and len(query
['Command']) >= 1:
168 command
= query
['Command'][0]
170 # If we are looking at the root container
171 if (command
== 'QueryContainer' and
172 (not 'Container' in query
or query
['Container'][0] == '/')):
173 self
.root_container()
176 if 'Container' in query
:
177 # Dispatch to the container plugin
178 basepath
= query
['Container'][0].split('/')[0]
179 if self
.do_command(query
, command
, basepath
, tsn
):
182 elif command
== 'QueryItem':
183 path
= query
.get('Url', [''])[0]
184 splitpath
= [x
for x
in unquote_plus(path
).split('/') if x
]
185 if splitpath
and not '..' in splitpath
:
186 if self
.do_command(query
, command
, splitpath
[0], tsn
):
189 elif (command
== 'QueryFormats' and 'SourceFormat' in query
and
190 query
['SourceFormat'][0].startswith('video')):
191 if config
.is_ts_capable(tsn
):
192 self
.send_xml(VIDEO_FORMATS_TS
)
194 self
.send_xml(VIDEO_FORMATS
)
197 elif command
== 'QueryServer':
198 self
.send_xml(SERVER_INFO
)
201 elif command
in ('FlushServer', 'ResetServer'):
202 # Does nothing -- included for completeness
203 self
.send_response(200)
204 self
.send_header('Content-Length', '0')
209 # If we made it here it means we couldn't match the request to
211 self
.unsupported(query
)
213 def send_content_file(self
, path
):
214 lmdate
= os
.path
.getmtime(path
)
216 handle
= open(path
, 'rb')
222 mime
= mimetypes
.guess_type(path
)[0]
223 self
.send_response(200)
225 self
.send_header('Content-Type', mime
)
226 self
.send_header('Content-Length', os
.path
.getsize(path
))
227 self
.send_header('Last-Modified', formatdate(lmdate
))
230 # Send the body of the file
232 shutil
.copyfileobj(handle
, self
.wfile
)
238 def handle_file(self
, query
, splitpath
):
239 if '..' not in splitpath
: # Protect against path exploits
240 ## Pass it off to a plugin?
241 for name
, container
in self
.server
.containers
.items():
242 if splitpath
[0] == name
:
244 self
.container
= container
245 base
= os
.path
.normpath(container
['path'])
246 path
= os
.path
.join(base
, *splitpath
[1:])
247 plugin
= GetPlugin(container
['type'])
248 plugin
.send_file(self
, path
, query
)
251 ## Serve it from a "content" directory?
252 base
= os
.path
.join(SCRIPTDIR
, *splitpath
[:-1])
253 path
= os
.path
.join(base
, 'content', splitpath
[-1])
255 if os
.path
.isfile(path
):
256 self
.send_content_file(path
)
262 def authorize(self
, tsn
=None):
263 # if allowed_clients is empty, we are completely open
264 allowed_clients
= config
.getAllowedClients()
265 if not allowed_clients
or (tsn
and config
.isTsnInConfig(tsn
)):
267 client_ip
= self
.client_address
[0]
268 for allowedip
in allowed_clients
:
269 if client_ip
.startswith(allowedip
):
272 self
.send_fixed('Unauthorized.', 'text/plain', 403)
275 def log_message(self
, format
, *args
):
276 self
.server
.logger
.info("%s [%s] %s" % (self
.address_string(),
277 self
.log_date_time_string(), format
%args
))
279 def send_fixed(self
, page
, mime
, code
=200, refresh
=''):
280 squeeze
= (len(page
) > 256 and mime
.startswith('text') and
281 'gzip' in self
.headers
.getheader('Accept-Encoding', ''))
284 gzip
.GzipFile(mode
='wb', fileobj
=out
).write(page
)
285 page
= out
.getvalue()
287 self
.send_response(code
)
288 self
.send_header('Content-Type', mime
)
289 self
.send_header('Content-Length', len(page
))
291 self
.send_header('Content-Encoding', 'gzip')
292 self
.send_header('Expires', '0')
294 self
.send_header('Refresh', refresh
)
296 self
.wfile
.write(page
)
299 def send_xml(self
, page
):
300 self
.send_fixed(page
, 'text/xml')
302 def send_html(self
, page
, code
=200, refresh
=''):
303 self
.send_fixed(page
, 'text/html; charset=utf-8', code
, refresh
)
305 def root_container(self
):
306 tsn
= self
.headers
.getheader('TiVo_TCD_ID', '')
307 tsnshares
= config
.getShares(tsn
)
309 for section
, settings
in tsnshares
:
311 mime
= GetPlugin(settings
['type']).CONTENT_TYPE
312 if mime
.split('/')[1] in ('tivo-videos', 'tivo-music',
314 settings
['content_type'] = mime
315 tsncontainers
.append((section
, settings
))
316 except Exception, msg
:
317 self
.server
.logger
.error(section
+ ' - ' + str(msg
))
318 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
319 'root_container.tmpl'),
320 filter=EncodeUnicode
)
321 if self
.server
.beacon
.bd
:
322 t
.renamed
= self
.server
.beacon
.bd
.renamed
325 t
.containers
= tsncontainers
326 t
.hostname
= socket
.gethostname()
329 self
.send_xml(str(t
))
332 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
334 filter=EncodeUnicode
)
337 if config
.get_server('tivo_mak') and config
.get_server('togo_path'):
338 t
.togo
= '<br>Pull from TiVos:<br>'
342 if (config
.get_server('tivo_username') and
343 config
.get_server('tivo_password')):
344 t
.shares
= '<br>Push from video shares:<br>'
348 for section
, settings
in config
.getShares():
349 plugin_type
= settings
.get('type')
350 if plugin_type
== 'settings':
351 t
.admin
+= ('<a href="/TiVoConnect?Command=Settings&' +
352 'Container=' + quote(section
) +
353 '">Settings</a><br>')
354 elif plugin_type
== 'togo' and t
.togo
:
355 for tsn
in config
.tivos
:
356 if tsn
and 'address' in config
.tivos
[tsn
]:
357 t
.togo
+= ('<a href="/TiVoConnect?' +
358 'Command=NPL&Container=' + quote(section
) +
359 '&TiVo=' + config
.tivos
[tsn
]['address'] +
360 '">' + config
.tivos
[tsn
]['name'] +
362 elif plugin_type
and t
.shares
:
363 plugin
= GetPlugin(plugin_type
)
364 if hasattr(plugin
, 'Push'):
365 t
.shares
+= ('<a href="/TiVoConnect?Command=' +
366 'QueryContainer&Container=' +
367 quote(section
) + '&Format=text/html">' +
368 section
+ '</a><br>')
370 self
.send_html(str(t
))
372 def unsupported(self
, query
):
373 message
= UNSUP
% '\n'.join(['<li>%s: %s</li>' % (key
, repr(value
))
374 for key
, value
in query
.items()])
375 text
= BASE_HTML
% message
376 self
.send_html(text
, code
=404)
378 def redir(self
, message
, seconds
=2):
379 url
= self
.headers
.getheader('Referer')
381 message
+= RELOAD
% (url
, seconds
)
382 refresh
= '%d; url=%s' % (seconds
, url
)
385 text
= (BASE_HTML
% message
).encode('utf-8')
386 self
.send_html(text
, refresh
=refresh
)