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
32 def add_container(self
, name
, settings
):
33 if name
in self
.containers
or name
== 'TiVoConnect':
34 raise "Container Name in use"
36 settings
['content_type'] = GetPlugin(settings
['type']).CONTENT_TYPE
37 self
.containers
[name
] = settings
39 print 'Unable to add container', name
42 self
.containers
.clear()
43 for section
, settings
in config
.getShares():
44 self
.add_container(section
, settings
)
46 def handle_error(self
, request
, client_address
):
47 logging
.getLogger("pyTivo").exception("Exception during request from %s" % (client_address
,))
49 def set_beacon(self
, beacon
):
52 class TivoHTTPHandler(BaseHTTPServer
.BaseHTTPRequestHandler
):
56 def address_string(self
):
57 host
, port
= self
.client_address
[:2]
61 tsn
= self
.headers
.getheader('TiVo_TCD_ID',
62 self
.headers
.getheader('tsn', ''))
64 ip
= self
.address_string()
67 if not tsn
in self
.tivo_names
:
68 self
.tivo_names
[tsn
] = self
.server
.beacon
.get_name(ip
)
70 basepath
= unquote_plus(self
.path
).split('/')[1]
73 for name
, container
in self
.server
.containers
.items():
75 plugin
= GetPlugin(container
['type'])
76 plugin
.send_file(self
, container
, name
)
79 ## Not a file not a TiVo command
80 if not self
.path
.startswith('/TiVoConnect'):
84 o
= urlparse("http://fake.host" + self
.path
)
85 query
= cgi
.parse_qs(o
[4])
87 self
.handle_query(query
)
90 ctype
, pdict
= cgi
.parse_header(self
.headers
.getheader('content-type'))
91 if ctype
== 'multipart/form-data':
92 query
= cgi
.parse_multipart(self
.rfile
, pdict
)
94 length
= int(self
.headers
.getheader('content-length'))
95 qs
= self
.rfile
.read(length
)
96 query
= cgi
.parse_qs(qs
, keep_blank_values
=1)
97 self
.handle_query(query
)
99 def handle_query(self
, query
):
101 if 'Command' in query
and len(query
['Command']) >= 1:
103 command
= query
['Command'][0]
105 # If we are looking at the root container
106 if (command
== 'QueryContainer' and
107 (not 'Container' in query
or query
['Container'][0] == '/')):
108 self
.root_container()
111 if 'Container' in query
:
112 # Dispatch to the container plugin
113 basepath
= unquote(query
['Container'][0].split('/')[0])
114 for name
, container
in self
.server
.containers
.items():
116 plugin
= GetPlugin(container
['type'])
117 if hasattr(plugin
, command
):
118 method
= getattr(plugin
, command
)
124 elif (command
== 'QueryFormats' and 'SourceFormat' in query
and
125 query
['SourceFormat'][0].startswith('video')):
126 self
.send_response(200)
128 self
.wfile
.write(VIDEO_FORMATS
)
131 # If we made it here it means we couldn't match the request to
133 self
.unsupported(query
)
135 def log_message(self
, format
, *args
):
136 logging
.getLogger("pyTivo").info("%s [%s] %s" %
137 (self
.address_string(),
138 self
.log_date_time_string(),
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 print 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()