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 ip
= self
.address_string()
111 config
.tivos
[tsn
] = ip
113 if not tsn
in config
.tivo_names
or config
.tivo_names
[tsn
] == tsn
:
114 config
.tivo_names
[tsn
] = self
.server
.beacon
.get_name(ip
)
117 path
, opts
= self
.path
.split('?', 1)
118 query
= cgi
.parse_qs(opts
)
123 if path
== '/TiVoConnect':
124 self
.handle_query(query
, tsn
)
127 splitpath
= [x
for x
in unquote_plus(path
).split('/') if x
]
129 self
.handle_file(query
, splitpath
)
131 ## Not a file not a TiVo command
135 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
136 self
.headers
.getheader('tsn', ''))
137 if not self
.authorize(tsn
):
139 ctype
, pdict
= cgi
.parse_header(self
.headers
.getheader('content-type'))
140 if ctype
== 'multipart/form-data':
141 query
= cgi
.parse_multipart(self
.rfile
, pdict
)
143 length
= int(self
.headers
.getheader('content-length'))
144 qs
= self
.rfile
.read(length
)
145 query
= cgi
.parse_qs(qs
, keep_blank_values
=1)
146 self
.handle_query(query
, tsn
)
148 def do_command(self
, query
, command
, target
, tsn
):
149 for name
, container
in config
.getShares(tsn
):
151 plugin
= GetPlugin(container
['type'])
152 if hasattr(plugin
, command
):
154 self
.container
= container
155 method
= getattr(plugin
, command
)
162 def handle_query(self
, query
, tsn
):
164 if 'Command' in query
and len(query
['Command']) >= 1:
166 command
= query
['Command'][0]
168 # If we are looking at the root container
169 if (command
== 'QueryContainer' and
170 (not 'Container' in query
or query
['Container'][0] == '/')):
171 self
.root_container()
174 if 'Container' in query
:
175 # Dispatch to the container plugin
176 basepath
= query
['Container'][0].split('/')[0]
177 if self
.do_command(query
, command
, basepath
, tsn
):
180 elif command
== 'QueryItem':
181 path
= query
.get('Url', [''])[0]
182 splitpath
= [x
for x
in unquote_plus(path
).split('/') if x
]
183 if splitpath
and not '..' in splitpath
:
184 if self
.do_command(query
, command
, splitpath
[0], tsn
):
187 elif (command
== 'QueryFormats' and 'SourceFormat' in query
and
188 query
['SourceFormat'][0].startswith('video')):
189 if config
.is_ts_capable(tsn
):
190 self
.send_xml(VIDEO_FORMATS_TS
)
192 self
.send_xml(VIDEO_FORMATS
)
195 elif command
== 'QueryServer':
196 self
.send_xml(SERVER_INFO
)
199 elif command
in ('FlushServer', 'ResetServer'):
200 # Does nothing -- included for completeness
201 self
.send_response(200)
202 self
.send_header('Content-Length', '0')
207 # If we made it here it means we couldn't match the request to
209 self
.unsupported(query
)
211 def send_content_file(self
, path
):
212 lmdate
= os
.path
.getmtime(path
)
214 handle
= open(path
, 'rb')
220 mime
= mimetypes
.guess_type(path
)[0]
221 self
.send_response(200)
223 self
.send_header('Content-Type', mime
)
224 self
.send_header('Content-Length', os
.path
.getsize(path
))
225 self
.send_header('Last-Modified', formatdate(lmdate
))
228 # Send the body of the file
230 shutil
.copyfileobj(handle
, self
.wfile
)
236 def handle_file(self
, query
, splitpath
):
237 if '..' not in splitpath
: # Protect against path exploits
238 ## Pass it off to a plugin?
239 for name
, container
in self
.server
.containers
.items():
240 if splitpath
[0] == name
:
242 self
.container
= container
243 base
= os
.path
.normpath(container
['path'])
244 path
= os
.path
.join(base
, *splitpath
[1:])
245 plugin
= GetPlugin(container
['type'])
246 plugin
.send_file(self
, path
, query
)
249 ## Serve it from a "content" directory?
250 base
= os
.path
.join(SCRIPTDIR
, *splitpath
[:-1])
251 path
= os
.path
.join(base
, 'content', splitpath
[-1])
253 if os
.path
.isfile(path
):
254 self
.send_content_file(path
)
260 def authorize(self
, tsn
=None):
261 # if allowed_clients is empty, we are completely open
262 allowed_clients
= config
.getAllowedClients()
263 if not allowed_clients
or (tsn
and config
.isTsnInConfig(tsn
)):
265 client_ip
= self
.client_address
[0]
266 for allowedip
in allowed_clients
:
267 if client_ip
.startswith(allowedip
):
270 self
.send_fixed('Unauthorized.', 'text/plain', 403)
273 def log_message(self
, format
, *args
):
274 self
.server
.logger
.info("%s [%s] %s" % (self
.address_string(),
275 self
.log_date_time_string(), format
%args
))
277 def send_fixed(self
, page
, mime
, code
=200, refresh
=''):
278 squeeze
= (len(page
) > 256 and mime
.startswith('text') and
279 'gzip' in self
.headers
.getheader('Accept-Encoding', ''))
282 gzip
.GzipFile(mode
='wb', fileobj
=out
).write(page
)
283 page
= out
.getvalue()
285 self
.send_response(code
)
286 self
.send_header('Content-Type', mime
)
287 self
.send_header('Content-Length', len(page
))
289 self
.send_header('Content-Encoding', 'gzip')
290 self
.send_header('Expires', '0')
292 self
.send_header('Refresh', refresh
)
294 self
.wfile
.write(page
)
297 def send_xml(self
, page
):
298 self
.send_fixed(page
, 'text/xml')
300 def send_html(self
, page
, code
=200, refresh
=''):
301 self
.send_fixed(page
, 'text/html; charset=utf-8', code
, refresh
)
303 def root_container(self
):
304 tsn
= self
.headers
.getheader('TiVo_TCD_ID', '')
305 tsnshares
= config
.getShares(tsn
)
307 for section
, settings
in tsnshares
:
309 mime
= GetPlugin(settings
['type']).CONTENT_TYPE
310 if mime
.split('/')[1] in ('tivo-videos', 'tivo-music',
312 settings
['content_type'] = mime
313 tsncontainers
.append((section
, settings
))
314 except Exception, msg
:
315 self
.server
.logger
.error(section
+ ' - ' + str(msg
))
316 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
317 'root_container.tmpl'),
318 filter=EncodeUnicode
)
319 if self
.server
.beacon
.bd
:
320 t
.renamed
= self
.server
.beacon
.bd
.renamed
323 t
.containers
= tsncontainers
324 t
.hostname
= socket
.gethostname()
327 self
.send_xml(str(t
))
330 useragent
= self
.headers
.getheader('User-Agent', '')
331 if useragent
.lower().find('mobile') > 0:
332 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
333 'info_page_mob.tmpl'),
334 filter=EncodeUnicode
)
336 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
338 filter=EncodeUnicode
)
341 if config
.get_server('tivo_mak') and config
.get_server('togo_path'):
342 t
.togo
= 'Pull from TiVos:<br>'
346 if (config
.get_server('tivo_username') and
347 config
.get_server('tivo_password')):
348 t
.shares
= 'Push from video shares:<br>'
352 for section
, settings
in config
.getShares():
353 plugin_type
= settings
.get('type')
354 if plugin_type
== 'settings':
355 t
.admin
+= ('<a href="/TiVoConnect?Command=Settings&' +
356 'Container=' + quote(section
) +
357 '">Settings</a><br>')
358 elif plugin_type
== 'togo' and t
.togo
:
359 for tsn
in config
.tivos
:
361 t
.togo
+= ('<a href="/TiVoConnect?' +
362 'Command=NPL&Container=' + quote(section
) +
363 '&TiVo=' + config
.tivos
[tsn
] + '">' +
364 escape(config
.tivo_names
[tsn
]) + '</a><br>')
365 elif plugin_type
and t
.shares
:
366 plugin
= GetPlugin(plugin_type
)
367 if hasattr(plugin
, 'Push'):
368 t
.shares
+= ('<a href="/TiVoConnect?Command=' +
369 'QueryContainer&Container=' +
370 quote(section
) + '&Format=text/html">' +
371 section
+ '</a><br>')
373 self
.send_html(str(t
))
375 def unsupported(self
, query
):
376 message
= UNSUP
% '\n'.join(['<li>%s: %s</li>' % (escape(key
),
378 for key
, value
in query
.items()])
379 text
= BASE_HTML
% message
380 self
.send_html(text
, code
=404)
382 def redir(self
, message
, seconds
=2):
383 url
= self
.headers
.getheader('Referer')
385 message
+= RELOAD
% (escape(url
), seconds
)
386 refresh
= '%d; url=%s' % (seconds
, url
)
389 text
= (BASE_HTML
% message
).encode('utf-8')
390 self
.send_html(text
, refresh
=refresh
)