9 from urllib
import unquote_plus
, quote
, unquote
10 from urlparse
import urlparse
11 from xml
.sax
.saxutils
import escape
13 from Cheetah
.Template
import Template
15 from plugin
import GetPlugin
17 SCRIPTDIR
= os
.path
.dirname(__file__
)
19 VIDEO_FORMATS
= """<?xml version="1.0" encoding="utf-8"?>
21 <ContentType>video/x-tivo-mpeg</ContentType><Description/>
22 </Format></TiVoFormats>"""
24 class TivoHTTPServer(SocketServer
.ThreadingMixIn
, BaseHTTPServer
.HTTPServer
):
27 def __init__(self
, server_address
, RequestHandlerClass
):
28 BaseHTTPServer
.HTTPServer
.__init
__(self
, server_address
,
30 self
.daemon_threads
= True
31 self
.logger
= logging
.getLogger('pyTivo')
33 def add_container(self
, name
, settings
):
34 if name
in self
.containers
or name
== 'TiVoConnect':
35 raise "Container Name in use"
37 settings
['content_type'] = GetPlugin(settings
['type']).CONTENT_TYPE
38 self
.containers
[name
] = settings
40 self
.logger
.error('Unable to add container ' + name
)
43 self
.containers
.clear()
44 for section
, settings
in config
.getShares():
45 self
.add_container(section
, settings
)
47 def handle_error(self
, request
, client_address
):
48 self
.logger
.exception('Exception during request from %s' %
51 def set_beacon(self
, beacon
):
54 class TivoHTTPHandler(BaseHTTPServer
.BaseHTTPRequestHandler
):
58 def address_string(self
):
59 host
, port
= self
.client_address
[:2]
63 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
64 self
.headers
.getheader('tsn', ''))
66 ip
= self
.address_string()
69 if not tsn
in self
.tivo_names
:
70 self
.tivo_names
[tsn
] = self
.server
.beacon
.get_name(ip
)
72 basepath
= unquote_plus(self
.path
).split('/')[1]
75 for name
, container
in self
.server
.containers
.items():
77 plugin
= GetPlugin(container
['type'])
78 plugin
.send_file(self
, container
, name
)
81 ## Not a file not a TiVo command
82 if not self
.path
.startswith('/TiVoConnect'):
86 o
= urlparse("http://fake.host" + self
.path
)
87 query
= cgi
.parse_qs(o
[4])
89 self
.handle_query(query
)
92 ctype
, pdict
= cgi
.parse_header(self
.headers
.getheader('content-type'))
93 if ctype
== 'multipart/form-data':
94 query
= cgi
.parse_multipart(self
.rfile
, pdict
)
96 length
= int(self
.headers
.getheader('content-length'))
97 qs
= self
.rfile
.read(length
)
98 query
= cgi
.parse_qs(qs
, keep_blank_values
=1)
99 self
.handle_query(query
)
101 def handle_query(self
, query
):
103 if 'Command' in query
and len(query
['Command']) >= 1:
105 command
= query
['Command'][0]
107 # If we are looking at the root container
108 if (command
== 'QueryContainer' and
109 (not 'Container' in query
or query
['Container'][0] == '/')):
110 self
.root_container()
113 if 'Container' in query
:
114 # Dispatch to the container plugin
115 basepath
= unquote(query
['Container'][0].split('/')[0])
116 for name
, container
in self
.server
.containers
.items():
118 plugin
= GetPlugin(container
['type'])
119 if hasattr(plugin
, command
):
120 method
= getattr(plugin
, command
)
126 elif (command
== 'QueryFormats' and 'SourceFormat' in query
and
127 query
['SourceFormat'][0].startswith('video')):
128 self
.send_response(200)
130 self
.wfile
.write(VIDEO_FORMATS
)
133 # If we made it here it means we couldn't match the request to
135 self
.unsupported(query
)
137 def log_message(self
, format
, *args
):
138 self
.server
.logger
.info("%s [%s] %s" % (self
.address_string(),
139 self
.log_date_time_string(), format
%args
))
141 def root_container(self
):
142 tsn
= self
.headers
.getheader('TiVo_TCD_ID', '')
143 tsnshares
= config
.getShares(tsn
)
145 for section
, settings
in tsnshares
:
147 settings
['content_type'] = \
148 GetPlugin(settings
['type']).CONTENT_TYPE
149 tsncontainers
[section
] = settings
150 except Exception, msg
:
151 self
.server
.logger
.error(section
+ ' - ' + msg
)
152 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
153 'root_container.tmpl'))
154 t
.containers
= tsncontainers
155 t
.hostname
= socket
.gethostname()
158 self
.send_response(200)
163 self
.send_response(200)
164 self
.send_header('Content-type', 'text/html')
166 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
169 for section
, settings
in config
.getShares():
170 if 'type' in settings
and settings
['type'] == 'admin':
171 t
.admin
+= ('<a href="/TiVoConnect?Command=Admin&Container=' +
173 '">Web Configuration</a><br>' +
174 '<a href="/TiVoConnect?Command=NPL&Container=' +
175 quote(section
) + '">ToGo</a><br>')
177 t
.admin
= ('<br><b>No Admin plugin installed in pyTivo.conf</b>' +
178 '<br> If you wish to use the admin plugin add the ' +
179 'following lines to pyTivo.conf<br><br>' +
180 '[Admin]<br>type=admin')
182 t
.shares
= 'Video shares:<br/>'
183 for section
, settings
in config
.getShares():
184 if settings
.get('type') == 'video':
185 t
.shares
+= ('<a href="TiVoConnect?Command=QueryContainer&' +
186 'Container=' + quote(section
) + '">' + section
+
191 def unsupported(self
, query
):
192 self
.send_response(404)
193 self
.send_header('Content-type', 'text/html')
195 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
200 if __name__
== '__main__':
202 httpd
= TivoHTTPServer(('', 9032), TivoHTTPHandler
)
203 httpd
.add_container('test', 'x-container/tivo-videos',
204 r
'C:\Documents and Settings\Armooo' +
205 r
'\Desktop\pyTivo\test')
206 httpd
.serve_forever()