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 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
332 filter=EncodeUnicode
)
335 if config
.get_server('tivo_mak') and config
.get_server('togo_path'):
336 t
.togo
= '<br>Pull from TiVos:<br>'
340 if (config
.get_server('tivo_username') and
341 config
.get_server('tivo_password')):
342 t
.shares
= '<br>Push from video shares:<br>'
346 for section
, settings
in config
.getShares():
347 plugin_type
= settings
.get('type')
348 if plugin_type
== 'settings':
349 t
.admin
+= ('<a href="/TiVoConnect?Command=Settings&' +
350 'Container=' + quote(section
) +
351 '">Settings</a><br>')
352 elif plugin_type
== 'togo' and t
.togo
:
353 for tsn
in config
.tivos
:
355 t
.togo
+= ('<a href="/TiVoConnect?' +
356 'Command=NPL&Container=' + quote(section
) +
357 '&TiVo=' + config
.tivos
[tsn
]['address'] +
358 '">' + escape(config
.tivos
[tsn
]['name']) +
360 elif plugin_type
and t
.shares
:
361 plugin
= GetPlugin(plugin_type
)
362 if hasattr(plugin
, 'Push'):
363 t
.shares
+= ('<a href="/TiVoConnect?Command=' +
364 'QueryContainer&Container=' +
365 quote(section
) + '&Format=text/html">' +
366 section
+ '</a><br>')
368 self
.send_html(str(t
))
370 def unsupported(self
, query
):
371 message
= UNSUP
% '\n'.join(['<li>%s: %s</li>' % (escape(key
),
373 for key
, value
in query
.items()])
374 text
= BASE_HTML
% message
375 self
.send_html(text
, code
=404)
377 def redir(self
, message
, seconds
=2):
378 url
= self
.headers
.getheader('Referer')
380 message
+= RELOAD
% (escape(url
), seconds
)
381 refresh
= '%d; url=%s' % (seconds
, url
)
384 text
= (BASE_HTML
% message
).encode('utf-8')
385 self
.send_html(text
, refresh
=refresh
)