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
, type, path
):
18 if self
.containers
.has_key(name
) or name
== 'TivoConnect':
19 raise "Container Name in use"
20 self
.containers
[name
] = {'type' : type, 'path' : path
}
22 class TivoHTTPHandler(BaseHTTPServer
.BaseHTTPRequestHandler
):
26 for name
, container
in self
.server
.containers
.items():
28 path
= unquote_plus(self
.path
)
29 if path
.startswith('/' + name
):
30 plugin
= GetPlugin(container
['type'])
31 plugin
.SendFile(self
, container
, name
)
34 ## Not a file not a TiVo command fuck them
35 if not self
.path
.startswith('/TiVoConnect'):
39 o
= urlparse("http://fake.host" + self
.path
)
40 query
= parse_qs(o
.query
)
43 if query
.has_key('Command') and len(query
['Command']) >= 1:
45 command
= query
['Command'][0]
47 #If we are looking at the root container
48 if command
== "QueryContainer" and ( not query
.has_key('Container') or query
['Container'][0] == '/'):
52 if query
.has_key('Container'):
53 #Dispatch to the container plugin
54 for name
, container
in self
.server
.containers
.items():
55 print name
, query
['Container'][0]
56 if query
['Container'][0].startswith(name
):
57 plugin
= GetPlugin(container
['type'])
58 if hasattr(plugin
,command
):
59 method
= getattr(plugin
, command
)
62 self
.unsuported(query
)
65 self
.unsuported(query
)
67 def RootContiner(self
):
68 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates', 'root_container.tmpl'))
69 t
.containers
= self
.server
.containers
70 t
.hostname
= socket
.gethostname()
71 t
.GetPlugin
= GetPlugin
72 self
.send_response(200)
77 self
.send_response(200)
78 self
.send_header('Content-type', 'text/html')
80 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates', 'info_page.tmpl'))
84 def unsuported(self
, query
):
85 self
.send_response(404)
86 self
.send_header('Content-type', 'text/html')
88 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates','unsuported.tmpl'))
92 if __name__
== '__main__':
94 httpd
= TivoHTTPServer(('', 9032), TivoHTTPHandler
)
95 httpd
.add_container('test', 'x-container/tivo-videos', r
'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')