11 from urllib
import unquote_plus
, quote
12 from xml
.sax
.saxutils
import escape
14 from Cheetah
.Template
import Template
16 from plugin
import GetPlugin
, GetPluginPath
, EncodeUnicode
18 SCRIPTDIR
= os
.path
.dirname(__file__
)
20 VIDEO_FORMATS
= """<?xml version="1.0" encoding="utf-8"?>
22 <ContentType>video/x-tivo-mpeg</ContentType><Description/>
23 </Format></TiVoFormats>"""
25 RE_PLUGIN_CONTENT
= re
.compile( r
"/plugin/([^/]+)/content/(.+)" )
27 class TivoHTTPServer(SocketServer
.ThreadingMixIn
, BaseHTTPServer
.HTTPServer
):
30 def __init__(self
, server_address
, RequestHandlerClass
):
31 BaseHTTPServer
.HTTPServer
.__init
__(self
, server_address
,
33 self
.daemon_threads
= True
34 self
.logger
= logging
.getLogger('pyTivo')
36 def add_container(self
, name
, settings
):
37 if name
in self
.containers
or name
== 'TiVoConnect':
38 raise "Container Name in use"
40 self
.containers
[name
] = settings
42 self
.logger
.error('Unable to add container ' + name
)
45 self
.containers
.clear()
46 for section
, settings
in config
.getShares():
47 self
.add_container(section
, settings
)
49 def handle_error(self
, request
, client_address
):
50 self
.logger
.exception('Exception during request from %s' %
53 def set_beacon(self
, beacon
):
56 class TivoHTTPHandler(BaseHTTPServer
.BaseHTTPRequestHandler
):
57 def __init__(self
, request
, client_address
, server
):
58 self
.wbufsize
= 0x10000
59 BaseHTTPServer
.BaseHTTPRequestHandler
.__init
__(self
, request
,
60 client_address
, server
)
62 def address_string(self
):
63 host
, port
= self
.client_address
[:2]
67 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
68 self
.headers
.getheader('tsn', ''))
69 if not self
.authorize(tsn
):
72 ip
= self
.address_string()
73 config
.tivos
[tsn
] = ip
75 if not tsn
in config
.tivo_names
or config
.tivo_names
[tsn
] == tsn
:
76 config
.tivo_names
[tsn
] = self
.server
.beacon
.get_name(ip
)
79 path
, opts
= self
.path
.split('?', 1)
80 query
= cgi
.parse_qs(opts
)
85 regm
= RE_PLUGIN_CONTENT
.match( path
)
87 if path
== '/TiVoConnect':
88 self
.handle_query(query
, tsn
)
90 # Handle general plugin content requests of the form
91 # /plugin/<plugin type>/content/<file>
94 # Protect ourself from path exploits
95 file_bits
= regm
.group(2).split( "/" )
100 # Get the plugin path
101 plugin_path
= GetPluginPath( regm
.group(1) )
103 # Build up the actual path based on the plugin path
104 filen
= os
.path
.join( plugin_path
, "content", *file_bits
)
106 # If it's not a file, then just error out
107 if not os
.path
.isfile( filen
):
110 # Read in the full file
111 handle
= open( filen
, "rb" )
120 self
.send_response(200)
121 self
.send_header( "Content-type", \
122 mimetypes
.guess_type( filen
) )
123 self
.send_header( "Content-length", \
124 os
.path
.getsize( filen
) )
127 # Send the body of the file
128 self
.wfile
.write( text
)
133 self
.send_response(404)
135 self
.wfile
.write( "File not found" )
141 path
= unquote_plus(path
)
142 basepath
= path
.split('/')[1]
143 for name
, container
in self
.server
.containers
.items():
145 path
= os
.path
.join(os
.path
.normpath(container
['path']),
146 os
.path
.normpath(path
[len(name
) + 2:]))
147 plugin
= GetPlugin(container
['type'])
148 plugin
.send_file(self
, path
, query
)
151 ## Not a file not a TiVo command
155 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
156 self
.headers
.getheader('tsn', ''))
157 if not self
.authorize(tsn
):
159 ctype
, pdict
= cgi
.parse_header(self
.headers
.getheader('content-type'))
160 if ctype
== 'multipart/form-data':
161 query
= cgi
.parse_multipart(self
.rfile
, pdict
)
163 length
= int(self
.headers
.getheader('content-length'))
164 qs
= self
.rfile
.read(length
)
165 query
= cgi
.parse_qs(qs
, keep_blank_values
=1)
166 self
.handle_query(query
, tsn
)
168 def handle_query(self
, query
, tsn
):
170 if 'Command' in query
and len(query
['Command']) >= 1:
172 command
= query
['Command'][0]
174 # If we are looking at the root container
175 if (command
== 'QueryContainer' and
176 (not 'Container' in query
or query
['Container'][0] == '/')):
177 self
.root_container()
180 if 'Container' in query
:
181 # Dispatch to the container plugin
182 basepath
= query
['Container'][0].split('/')[0]
183 for name
, container
in config
.getShares(tsn
):
185 plugin
= GetPlugin(container
['type'])
186 if hasattr(plugin
, command
):
187 method
= getattr(plugin
, command
)
193 elif (command
== 'QueryFormats' and 'SourceFormat' in query
and
194 query
['SourceFormat'][0].startswith('video')):
195 self
.send_response(200)
196 self
.send_header('Content-type', 'text/xml')
198 self
.wfile
.write(VIDEO_FORMATS
)
201 elif command
== 'FlushServer':
202 # Does nothing -- included for completeness
203 self
.send_response(200)
207 # If we made it here it means we couldn't match the request to
209 self
.unsupported(query
)
211 def authorize(self
, tsn
=None):
212 # if allowed_clients is empty, we are completely open
213 allowed_clients
= config
.getAllowedClients()
214 if not allowed_clients
or (tsn
and config
.isTsnInConfig(tsn
)):
216 client_ip
= self
.client_address
[0]
217 for allowedip
in allowed_clients
:
218 if client_ip
.startswith(allowedip
):
221 self
.send_response(404)
222 self
.send_header('Content-type', 'text/plain')
224 self
.wfile
.write("Unauthorized.")
227 def log_message(self
, format
, *args
):
228 self
.server
.logger
.info("%s [%s] %s" % (self
.address_string(),
229 self
.log_date_time_string(), format
%args
))
231 def root_container(self
):
232 tsn
= self
.headers
.getheader('TiVo_TCD_ID', '')
233 tsnshares
= config
.getShares(tsn
)
235 for section
, settings
in tsnshares
:
237 settings
['content_type'] = \
238 GetPlugin(settings
['type']).CONTENT_TYPE
239 tsncontainers
[section
] = settings
240 except Exception, msg
:
241 self
.server
.logger
.error(section
+ ' - ' + str(msg
))
242 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
243 'root_container.tmpl'),
244 filter=EncodeUnicode
)
245 t
.containers
= tsncontainers
246 t
.hostname
= socket
.gethostname()
249 self
.send_response(200)
250 self
.send_header('Content-type', 'text/xml')
255 self
.send_response(200)
256 self
.send_header('Content-type', 'text/html')
258 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
260 shares
= dict(config
.getShares())
263 if config
.get_server('tivo_mak') and config
.get_server('togo_path'):
264 t
.togo
= '<br>Pull from TiVos:<br>'
268 if (config
.get_server('tivo_username') and
269 config
.get_server('tivo_password')):
270 t
.shares
= '<br>Push from video shares:<br>'
274 for section
in shares
:
275 plugin_type
= shares
[section
].get('type')
276 if plugin_type
== 'settings':
277 t
.admin
+= ('<a href="/TiVoConnect?Command=Settings&' +
278 'Container=' + quote(section
) +
279 '">Web Configuration</a><br>')
280 elif plugin_type
== 'togo' and t
.togo
:
281 for tsn
in config
.tivos
:
283 t
.togo
+= ('<a href="/TiVoConnect?' +
284 'Command=NPL&Container=' + quote(section
) +
285 '&TiVo=' + config
.tivos
[tsn
] + '">' +
286 config
.tivo_names
[tsn
] + '</a><br>')
287 elif plugin_type
== 'video' and t
.shares
:
288 t
.shares
+= ('<a href="TiVoConnect?Command=' +
289 'QueryContainer&Container=' +
290 quote(section
) + '">' + section
+ '</a><br>')
294 def unsupported(self
, query
):
295 self
.send_response(404)
296 self
.send_header('Content-type', 'text/html')
298 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',