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 if self
.path
.startswith('/' + name
):
29 plugin
= GetPlugin(container
['type'])
30 plugin
.SendFile(self
, container
, name
)
33 ## Not a file not a TiVo command fuck them
34 if not self
.path
.startswith('/TiVoConnect'):
38 o
= urlparse("http://fake.host" + self
.path
)
39 query
= parse_qs(o
.query
)
42 if query
.has_key('Command') and len(query
['Command']) >= 1:
44 command
= query
['Command'][0]
46 #If we are looking at the root container
47 if command
== "QueryContainer" and ( not query
.has_key('Container') or query
['Container'][0] == '/'):
51 #Dispatch to the container plugin
52 plugin
= GetPlugin(container
['type'])
53 if plugin
.commands
.has_key(command
):
54 method
= plugin
.commands
[command
]
57 self
.unsuported(query
)
59 self
.unsuported(query
)
61 def RootContiner(self
):
62 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates', 'root_container.tmpl'))
63 t
.containers
= self
.server
.containers
64 t
.hostname
= socket
.gethostname()
65 t
.GetPlugin
= GetPlugin
66 self
.send_response(200)
71 self
.send_response(200)
72 self
.send_header('Content-type', 'text/html')
74 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates', 'info_page.tmpl'))
78 def unsuported(self
, query
):
79 self
.send_response(404)
80 self
.send_header('Content-type', 'text/html')
82 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates','unsuported.tmpl'))
86 if __name__
== '__main__':
88 httpd
= TivoHTTPServer(('', 9032), TivoHTTPHandler
)
89 httpd
.add_container('test', 'x-container/tivo-videos', r
'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')