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
8 SCRIPTDIR
= os
.path
.dirname(__file__
)
10 class TivoHTTPServer(SocketServer
.ThreadingMixIn
, BaseHTTPServer
.HTTPServer
):
13 def __init__(self
, server_address
, RequestHandlerClass
):
14 BaseHTTPServer
.HTTPServer
.__init
__(self
, server_address
, RequestHandlerClass
)
15 self
.daemon_threads
= True
17 def add_container(self
, name
, settings
):
18 if self
.containers
.has_key(name
) or name
== 'TivoConnect':
19 raise "Container Name in use"
20 self
.containers
[name
] = settings
22 class TivoHTTPHandler(BaseHTTPServer
.BaseHTTPRequestHandler
):
24 def address_string(self
):
25 host
, port
= self
.client_address
[:2]
31 for name
, container
in self
.server
.containers
.items():
33 path
= unquote_plus(self
.path
)
34 if path
.startswith('/' + name
):
35 plugin
= GetPlugin(container
['type'])
36 plugin
.SendFile(self
, container
, name
)
39 ## Not a file not a TiVo command fuck them
40 if not self
.path
.startswith('/TiVoConnect'):
44 o
= urlparse("http://fake.host" + self
.path
)
45 query
= parse_qs(o
[4])
48 if query
.has_key('Command') and len(query
['Command']) >= 1:
50 command
= query
['Command'][0]
52 #If we are looking at the root container
53 if command
== "QueryContainer" and ( not query
.has_key('Container') or query
['Container'][0] == '/'):
57 if query
.has_key('Container'):
58 #Dispatch to the container plugin
59 for name
, container
in self
.server
.containers
.items():
60 if query
['Container'][0].startswith(name
):
61 plugin
= GetPlugin(container
['type'])
62 if hasattr(plugin
,command
):
63 method
= getattr(plugin
, command
)
66 self
.unsuported(query
)
69 self
.unsuported(query
)
71 def RootContiner(self
):
72 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates', 'root_container.tmpl'))
73 t
.containers
= self
.server
.containers
74 t
.hostname
= socket
.gethostname()
75 t
.GetPlugin
= GetPlugin
76 self
.send_response(200)
81 self
.send_response(200)
82 self
.send_header('Content-type', 'text/html')
84 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates', 'info_page.tmpl'))
88 def unsuported(self
, query
):
89 self
.send_response(404)
90 self
.send_header('Content-type', 'text/html')
92 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates','unsuported.tmpl'))
96 if __name__
== '__main__':
98 httpd
= TivoHTTPServer(('', 9032), TivoHTTPHandler
)
99 httpd
.add_container('test', 'x-container/tivo-videos', r
'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')
100 httpd
.serve_forever()