1 import time
, os
, BaseHTTPServer
, SocketServer
, socket
, re
2 from urllib
import unquote_plus
, quote
, unquote
3 from urlparse
import urlparse
4 from cgi
import parse_qs
5 from Cheetah
.Template
import Template
6 from plugin
import GetPlugin
7 from xml
.sax
.saxutils
import escape
9 SCRIPTDIR
= os
.path
.dirname(__file__
)
11 class TivoHTTPServer(SocketServer
.ThreadingMixIn
, BaseHTTPServer
.HTTPServer
):
14 def __init__(self
, server_address
, RequestHandlerClass
):
15 BaseHTTPServer
.HTTPServer
.__init
__(self
, server_address
,
17 self
.daemon_threads
= True
19 def add_container(self
, name
, settings
):
20 if self
.containers
.has_key(name
) or name
== 'TiVoConnect':
21 raise "Container Name in use"
22 settings
['content_type'] = GetPlugin(settings
['type']).CONTENT_TYPE
23 self
.containers
[name
] = settings
25 class TivoHTTPHandler(BaseHTTPServer
.BaseHTTPRequestHandler
):
27 def address_string(self
):
28 host
, port
= self
.client_address
[:2]
33 basepath
= unquote_plus(self
.path
).split('/')[1]
36 for name
, container
in self
.server
.containers
.items():
38 plugin
= GetPlugin(container
['type'])
39 plugin
.send_file(self
, container
, name
)
42 ## Not a file not a TiVo command fuck them
43 if not self
.path
.startswith('/TiVoConnect'):
47 o
= urlparse("http://fake.host" + self
.path
)
48 query
= parse_qs(o
[4])
51 if query
.has_key('Command') and len(query
['Command']) >= 1:
53 command
= query
['Command'][0]
55 # If we are looking at the root container
56 if command
== "QueryContainer" and \
57 (not query
.has_key('Container') or query
['Container'][0] == '/'):
61 if query
.has_key('Container'):
62 # Dispatch to the container plugin
63 for name
, container
in self
.server
.containers
.items():
64 if query
['Container'][0].startswith(name
):
65 plugin
= GetPlugin(container
['type'])
66 if hasattr(plugin
,command
):
67 method
= getattr(plugin
, command
)
70 self
.unsupported(query
)
73 self
.unsupported(query
)
75 def root_container(self
):
76 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
77 'root_container.tmpl'))
78 t
.containers
= self
.server
.containers
79 t
.hostname
= socket
.gethostname()
81 self
.send_response(200)
86 self
.send_response(200)
87 self
.send_header('Content-type', 'text/html')
89 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
94 def unsupported(self
, query
):
95 self
.send_response(404)
96 self
.send_header('Content-type', 'text/html')
98 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
103 if __name__
== '__main__':
105 httpd
= TivoHTTPServer(('', 9032), TivoHTTPHandler
)
106 httpd
.add_container('test', 'x-container/tivo-videos',
107 r
'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')
108 httpd
.serve_forever()