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 settings
['content_type'] = GetPlugin(settings
['type']).CONTENT_TYPE
21 self
.containers
[name
] = settings
23 class TivoHTTPHandler(BaseHTTPServer
.BaseHTTPRequestHandler
):
25 def address_string(self
):
26 host
, port
= self
.client_address
[:2]
32 for name
, container
in self
.server
.containers
.items():
34 path
= unquote_plus(self
.path
)
35 if path
.startswith('/' + name
):
36 plugin
= GetPlugin(container
['type'])
37 plugin
.send_file(self
, container
, name
)
40 ## Not a file not a TiVo command fuck them
41 if not self
.path
.startswith('/TiVoConnect'):
45 o
= urlparse("http://fake.host" + self
.path
)
46 query
= parse_qs(o
[4])
49 if query
.has_key('Command') and len(query
['Command']) >= 1:
51 command
= query
['Command'][0]
53 #If we are looking at the root container
54 if command
== "QueryContainer" and ( not query
.has_key('Container') or query
['Container'][0] == '/'):
58 if query
.has_key('Container'):
59 #Dispatch to the container plugin
60 for name
, container
in self
.server
.containers
.items():
61 if query
['Container'][0].startswith(name
):
62 plugin
= GetPlugin(container
['type'])
63 if hasattr(plugin
,command
):
64 method
= getattr(plugin
, command
)
67 self
.unsuported(query
)
70 self
.unsuported(query
)
72 def root_continer(self
):
73 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates', 'root_container.tmpl'))
74 t
.containers
= self
.server
.containers
75 t
.hostname
= socket
.gethostname()
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()