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 SERVER_INFO
= """<?xml version="1.0" encoding="utf-8"?>
21 <Version>1.6</Version>
22 <InternalName>pyTivo</InternalName>
23 <InternalVersion>1.0</InternalVersion>
24 <Organization>pyTivo Developers</Organization>
25 <Comment>http://pytivo.sf.net/</Comment>
28 VIDEO_FORMATS
= """<?xml version="1.0" encoding="utf-8"?>
30 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
33 VIDEO_FORMATS_TS
= """<?xml version="1.0" encoding="utf-8"?>
35 <Format><ContentType>video/x-tivo-mpeg</ContentType><Description/></Format>
36 <Format><ContentType>video/x-tivo-mpeg-ts</ContentType><Description/></Format>
39 BASE_HTML
= """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
40 "http://www.w3.org/TR/html4/strict.dtd">
41 <html> <head><title>pyTivo</title></head> <body> %s </body> </html>"""
43 RELOAD
= '<p>The <a href="%s">page</a> will reload in %d seconds.</p>'
44 UNSUP
= '<h3>Unsupported Command</h3> <p>Query:</p> <ul>%s</ul>'
46 class TivoHTTPServer(SocketServer
.ThreadingMixIn
, BaseHTTPServer
.HTTPServer
):
47 def __init__(self
, server_address
, RequestHandlerClass
):
51 self
.logger
= logging
.getLogger('pyTivo')
52 BaseHTTPServer
.HTTPServer
.__init
__(self
, server_address
,
54 self
.daemon_threads
= True
56 def add_container(self
, name
, settings
):
57 if name
in self
.containers
or name
== 'TiVoConnect':
58 raise "Container Name in use"
60 self
.containers
[name
] = settings
62 self
.logger
.error('Unable to add container ' + name
)
65 self
.containers
.clear()
66 for section
, settings
in config
.getShares():
67 self
.add_container(section
, settings
)
69 def handle_error(self
, request
, client_address
):
70 self
.logger
.exception('Exception during request from %s' %
73 def set_beacon(self
, beacon
):
76 def set_service_status(self
, status
):
77 self
.in_service
= status
79 class TivoHTTPHandler(BaseHTTPServer
.BaseHTTPRequestHandler
):
80 def __init__(self
, request
, client_address
, server
):
81 self
.wbufsize
= 0x10000
82 self
.server_version
= 'pyTivo/1.0'
84 BaseHTTPServer
.BaseHTTPRequestHandler
.__init
__(self
, request
,
85 client_address
, server
)
87 def address_string(self
):
88 host
, port
= self
.client_address
[:2]
92 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
93 self
.headers
.getheader('tsn', ''))
94 if not self
.authorize(tsn
):
97 ip
= self
.address_string()
98 config
.tivos
[tsn
] = ip
100 if not tsn
in config
.tivo_names
or config
.tivo_names
[tsn
] == tsn
:
101 config
.tivo_names
[tsn
] = self
.server
.beacon
.get_name(ip
)
104 path
, opts
= self
.path
.split('?', 1)
105 query
= cgi
.parse_qs(opts
)
110 if path
== '/TiVoConnect':
111 self
.handle_query(query
, tsn
)
114 splitpath
= [x
for x
in unquote_plus(path
).split('/') if x
]
116 self
.handle_file(query
, splitpath
)
118 ## Not a file not a TiVo command
122 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
123 self
.headers
.getheader('tsn', ''))
124 if not self
.authorize(tsn
):
126 ctype
, pdict
= cgi
.parse_header(self
.headers
.getheader('content-type'))
127 if ctype
== 'multipart/form-data':
128 query
= cgi
.parse_multipart(self
.rfile
, pdict
)
130 length
= int(self
.headers
.getheader('content-length'))
131 qs
= self
.rfile
.read(length
)
132 query
= cgi
.parse_qs(qs
, keep_blank_values
=1)
133 self
.handle_query(query
, tsn
)
135 def do_command(self
, query
, command
, target
, tsn
):
136 for name
, container
in config
.getShares(tsn
):
138 plugin
= GetPlugin(container
['type'])
139 if hasattr(plugin
, command
):
141 self
.container
= container
142 method
= getattr(plugin
, command
)
149 def handle_query(self
, query
, tsn
):
151 if 'Command' in query
and len(query
['Command']) >= 1:
153 command
= query
['Command'][0]
155 # If we are looking at the root container
156 if (command
== 'QueryContainer' and
157 (not 'Container' in query
or query
['Container'][0] == '/')):
158 self
.root_container()
161 if 'Container' in query
:
162 # Dispatch to the container plugin
163 basepath
= query
['Container'][0].split('/')[0]
164 if self
.do_command(query
, command
, basepath
, tsn
):
167 elif command
== 'QueryItem':
168 path
= query
.get('Url', [''])[0]
169 splitpath
= [x
for x
in unquote_plus(path
).split('/') if x
]
170 if splitpath
and not '..' in splitpath
:
171 if self
.do_command(query
, command
, splitpath
[0], tsn
):
174 elif (command
== 'QueryFormats' and 'SourceFormat' in query
and
175 query
['SourceFormat'][0].startswith('video')):
176 if config
.hasTStivo(tsn
):
177 self
.send_xml(VIDEO_FORMATS_TS
)
179 self
.send_xml(VIDEO_FORMATS
)
182 elif command
== 'QueryServer':
183 self
.send_xml(SERVER_INFO
)
186 elif command
in ('FlushServer', 'ResetServer'):
187 # Does nothing -- included for completeness
188 self
.send_response(200)
192 # If we made it here it means we couldn't match the request to
194 self
.unsupported(query
)
196 def handle_file(self
, query
, splitpath
):
197 if '..' not in splitpath
: # Protect against path exploits
198 ## Pass it off to a plugin?
199 for name
, container
in self
.server
.containers
.items():
200 if splitpath
[0] == name
:
202 self
.container
= container
203 base
= os
.path
.normpath(container
['path'])
204 path
= os
.path
.join(base
, *splitpath
[1:])
205 plugin
= GetPlugin(container
['type'])
206 plugin
.send_file(self
, path
, query
)
209 ## Serve it from a "content" directory?
210 base
= os
.path
.join(SCRIPTDIR
, *splitpath
[:-1])
211 path
= os
.path
.join(base
, 'content', splitpath
[-1])
213 if os
.path
.isfile(path
):
215 handle
= open(path
, 'rb')
221 mime
= mimetypes
.guess_type(path
)[0]
222 self
.send_response(200)
224 self
.send_header('Content-type', mime
)
225 self
.send_header('Content-length', os
.path
.getsize(path
))
228 # Send the body of the file
230 shutil
.copyfileobj(handle
, self
.wfile
)
239 def authorize(self
, tsn
=None):
240 # if allowed_clients is empty, we are completely open
241 allowed_clients
= config
.getAllowedClients()
242 if not allowed_clients
or (tsn
and config
.isTsnInConfig(tsn
)):
244 client_ip
= self
.client_address
[0]
245 for allowedip
in allowed_clients
:
246 if client_ip
.startswith(allowedip
):
249 self
.send_fixed('Unauthorized.', 'text/plain', 403)
252 def log_message(self
, format
, *args
):
253 self
.server
.logger
.info("%s [%s] %s" % (self
.address_string(),
254 self
.log_date_time_string(), format
%args
))
256 def send_fixed(self
, page
, mime
, code
=200, refresh
=''):
257 self
.send_response(code
)
258 self
.send_header('Content-Type', mime
)
259 self
.send_header('Content-Length', len(page
))
260 self
.send_header('Connection', 'close')
261 self
.send_header('Expires', '0')
263 self
.send_header('Refresh', refresh
)
265 self
.wfile
.write(page
)
267 def send_xml(self
, page
):
268 self
.send_fixed(page
, 'text/xml')
270 def send_html(self
, page
, code
=200, refresh
=''):
271 self
.send_fixed(page
, 'text/html; charset=utf-8', code
, refresh
)
273 def root_container(self
):
274 tsn
= self
.headers
.getheader('TiVo_TCD_ID', '')
275 tsnshares
= config
.getShares(tsn
)
277 for section
, settings
in tsnshares
:
279 mime
= GetPlugin(settings
['type']).CONTENT_TYPE
280 if mime
.split('/')[1] in ('tivo-videos', 'tivo-music',
282 settings
['content_type'] = mime
283 tsncontainers
.append((section
, settings
))
284 except Exception, msg
:
285 self
.server
.logger
.error(section
+ ' - ' + str(msg
))
286 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
287 'root_container.tmpl'),
288 filter=EncodeUnicode
)
289 t
.containers
= tsncontainers
290 t
.hostname
= socket
.gethostname()
293 self
.send_xml(str(t
))
296 useragent
= self
.headers
.getheader('User-Agent', '')
297 if useragent
.lower().find('mobile') > 0:
298 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
299 'info_page_mob.tmpl'),
300 filter=EncodeUnicode
)
302 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
304 filter=EncodeUnicode
)
307 if config
.get_server('tivo_mak') and config
.get_server('togo_path'):
308 t
.togo
= 'Pull from TiVos:<br>'
312 if (config
.get_server('tivo_username') and
313 config
.get_server('tivo_password')):
314 t
.shares
= 'Push from video shares:<br>'
318 for section
, settings
in config
.getShares():
319 plugin_type
= settings
.get('type')
320 if plugin_type
== 'settings':
321 t
.admin
+= ('<a href="/TiVoConnect?Command=Settings&' +
322 'Container=' + quote(section
) +
323 '">Web Configuration</a><br>')
324 elif plugin_type
== 'togo' and t
.togo
:
325 for tsn
in config
.tivos
:
327 t
.togo
+= ('<a href="/TiVoConnect?' +
328 'Command=NPL&Container=' + quote(section
) +
329 '&TiVo=' + config
.tivos
[tsn
] + '">' +
330 escape(config
.tivo_names
[tsn
]) + '</a><br>')
331 elif plugin_type
and t
.shares
:
332 plugin
= GetPlugin(plugin_type
)
333 if hasattr(plugin
, 'Push'):
334 t
.shares
+= ('<a href="/TiVoConnect?Command=' +
335 'QueryContainer&Container=' +
336 quote(section
) + '&Format=text/html">' +
337 section
+ '</a><br>')
339 self
.send_html(str(t
))
341 def unsupported(self
, query
):
342 message
= UNSUP
% '\n'.join(['<li>%s: %s</li>' % (escape(key
),
344 for key
, value
in query
.items()])
345 text
= BASE_HTML
% message
346 self
.send_html(text
, code
=404)
348 def redir(self
, message
, seconds
=2):
349 url
= self
.headers
.getheader('Referer')
351 message
+= RELOAD
% (escape(url
), seconds
)
352 refresh
= '%d; url=%s' % (seconds
, url
)
355 text
= (BASE_HTML
% message
).encode('utf-8')
356 self
.send_html(text
, refresh
=refresh
)