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
):
38 def __init__(self
, server_address
, RequestHandlerClass
):
42 self
.logger
= logging
.getLogger('pyTivo')
43 BaseHTTPServer
.HTTPServer
.__init
__(self
, server_address
,
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 def set_service_status(self
, status
):
67 self
.in_service
= status
69 class TivoHTTPHandler(BaseHTTPServer
.BaseHTTPRequestHandler
):
70 def __init__(self
, request
, client_address
, server
):
71 self
.wbufsize
= 0x10000
72 self
.server_version
= 'pyTivo/1.0'
74 BaseHTTPServer
.BaseHTTPRequestHandler
.__init
__(self
, request
,
75 client_address
, server
)
77 def address_string(self
):
78 host
, port
= self
.client_address
[:2]
82 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
83 self
.headers
.getheader('tsn', ''))
84 if not self
.authorize(tsn
):
87 ip
= self
.address_string()
88 config
.tivos
[tsn
] = ip
90 if not tsn
in config
.tivo_names
or config
.tivo_names
[tsn
] == tsn
:
91 config
.tivo_names
[tsn
] = self
.server
.beacon
.get_name(ip
)
94 path
, opts
= self
.path
.split('?', 1)
95 query
= cgi
.parse_qs(opts
)
100 if path
== '/TiVoConnect':
101 self
.handle_query(query
, tsn
)
104 splitpath
= [x
for x
in unquote_plus(path
).split('/') if x
]
106 self
.handle_file(query
, splitpath
)
108 ## Not a file not a TiVo command
112 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
113 self
.headers
.getheader('tsn', ''))
114 if not self
.authorize(tsn
):
116 ctype
, pdict
= cgi
.parse_header(self
.headers
.getheader('content-type'))
117 if ctype
== 'multipart/form-data':
118 query
= cgi
.parse_multipart(self
.rfile
, pdict
)
120 length
= int(self
.headers
.getheader('content-length'))
121 qs
= self
.rfile
.read(length
)
122 query
= cgi
.parse_qs(qs
, keep_blank_values
=1)
123 self
.handle_query(query
, tsn
)
125 def handle_query(self
, query
, tsn
):
127 if 'Command' in query
and len(query
['Command']) >= 1:
129 command
= query
['Command'][0]
131 # If we are looking at the root container
132 if (command
== 'QueryContainer' and
133 (not 'Container' in query
or query
['Container'][0] == '/')):
134 self
.root_container()
137 if 'Container' in query
:
138 # Dispatch to the container plugin
139 basepath
= query
['Container'][0].split('/')[0]
140 for name
, container
in config
.getShares(tsn
):
142 plugin
= GetPlugin(container
['type'])
143 if hasattr(plugin
, command
):
144 method
= getattr(plugin
, command
)
150 elif (command
== 'QueryFormats' and 'SourceFormat' in query
and
151 query
['SourceFormat'][0].startswith('video')):
152 self
.send_response(200)
153 self
.send_header('Content-type', 'text/xml')
155 if config
.hasTStivo(tsn
):
156 self
.wfile
.write(VIDEO_FORMATS_TS
)
158 self
.wfile
.write(VIDEO_FORMATS
)
161 elif command
== 'FlushServer':
162 # Does nothing -- included for completeness
163 self
.send_response(200)
167 # If we made it here it means we couldn't match the request to
169 self
.unsupported(query
)
171 def handle_file(self
, query
, splitpath
):
172 if '..' not in splitpath
: # Protect against path exploits
173 ## Pass it off to a plugin?
174 for name
, container
in self
.server
.containers
.items():
175 if splitpath
[0] == name
:
176 base
= os
.path
.normpath(container
['path'])
177 path
= os
.path
.join(base
, *splitpath
[1:])
178 plugin
= GetPlugin(container
['type'])
179 plugin
.send_file(self
, path
, query
)
182 ## Serve it from a "content" directory?
183 base
= os
.path
.join(SCRIPTDIR
, *splitpath
[:-1])
184 path
= os
.path
.join(base
, 'content', splitpath
[-1])
186 if os
.path
.isfile(path
):
188 handle
= open(path
, 'rb')
194 mime
= mimetypes
.guess_type(path
)[0]
195 self
.send_response(200)
197 self
.send_header('Content-type', mime
)
198 self
.send_header('Content-length', os
.path
.getsize(path
))
201 # Send the body of the file
203 shutil
.copyfileobj(handle
, self
.wfile
)
212 def authorize(self
, tsn
=None):
213 # if allowed_clients is empty, we are completely open
214 allowed_clients
= config
.getAllowedClients()
215 if not allowed_clients
or (tsn
and config
.isTsnInConfig(tsn
)):
217 client_ip
= self
.client_address
[0]
218 for allowedip
in allowed_clients
:
219 if client_ip
.startswith(allowedip
):
222 self
.send_response(404)
223 self
.send_header('Content-type', 'text/plain')
225 self
.wfile
.write("Unauthorized.")
228 def log_message(self
, format
, *args
):
229 self
.server
.logger
.info("%s [%s] %s" % (self
.address_string(),
230 self
.log_date_time_string(), format
%args
))
232 def root_container(self
):
233 tsn
= self
.headers
.getheader('TiVo_TCD_ID', '')
234 tsnshares
= config
.getShares(tsn
)
236 for section
, settings
in tsnshares
:
238 settings
['content_type'] = \
239 GetPlugin(settings
['type']).CONTENT_TYPE
240 tsncontainers
.append((section
, settings
))
241 except Exception, msg
:
242 self
.server
.logger
.error(section
+ ' - ' + str(msg
))
243 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
244 'root_container.tmpl'),
245 filter=EncodeUnicode
)
246 t
.containers
= tsncontainers
247 t
.hostname
= socket
.gethostname()
250 self
.send_response(200)
251 self
.send_header('Content-type', 'text/xml')
256 self
.send_response(200)
257 self
.send_header('Content-type', 'text/html; charset=utf-8')
259 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
261 filter=EncodeUnicode
)
264 if config
.get_server('tivo_mak') and config
.get_server('togo_path'):
265 t
.togo
= '<br>Pull from TiVos:<br>'
269 if (config
.get_server('tivo_username') and
270 config
.get_server('tivo_password')):
271 t
.shares
= '<br>Push from video shares:<br>'
275 for section
, settings
in config
.getShares():
276 plugin_type
= settings
.get('type')
277 if plugin_type
== 'settings':
278 t
.admin
+= ('<a href="/TiVoConnect?Command=Settings&' +
279 'Container=' + quote(section
) +
280 '">Web Configuration</a><br>')
281 elif plugin_type
== 'togo' and t
.togo
:
282 for tsn
in config
.tivos
:
284 t
.togo
+= ('<a href="/TiVoConnect?' +
285 'Command=NPL&Container=' + quote(section
) +
286 '&TiVo=' + config
.tivos
[tsn
] + '">' +
287 escape(config
.tivo_names
[tsn
]) + '</a><br>')
288 elif plugin_type
== 'video' and t
.shares
:
289 t
.shares
+= ('<a href="TiVoConnect?Command=' +
290 'QueryContainer&Container=' +
291 quote(section
) + '&Format=text/html">' +
292 section
+ '</a><br>')
296 def unsupported(self
, query
):
297 message
= UNSUP
% '\n'.join(['<li>%s: %s</li>' % (escape(key
),
299 for key
, value
in query
.items()])
300 text
= BASE_HTML
% message
301 self
.send_response(404)
302 self
.send_header('Content-Type', 'text/html; charset=utf-8')
303 self
.send_header('Content-Length', len(text
))
305 self
.wfile
.write(text
)
307 def redir(self
, message
, seconds
=2):
308 url
= self
.headers
.getheader('Referer')
310 message
+= RELOAD
% (escape(url
), seconds
)
311 text
= (BASE_HTML
% message
).encode('utf-8')
312 self
.send_response(200)
313 self
.send_header('Content-Type', 'text/html; charset=utf-8')
314 self
.send_header('Content-Length', len(text
))
315 self
.send_header('Expires', '0')
317 self
.send_header('Refresh', '%d; url=%s' % (seconds
, url
))
319 self
.wfile
.write(text
)