Merge git://repo.or.cz/pyTivo/krkeegan
[pyTivo/TheBayer.git] / httpserver.py
bloba246eebb4b27da2f3abe534cf27743fe74a6371b
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 import config
8 from xml.sax.saxutils import escape
10 SCRIPTDIR = os.path.dirname(__file__)
12 debug = config.getDebug()
13 hack83 = config.getHack83()
15 def debug_write(data):
16 if debug:
17 debug_out = []
18 debug_out.append('httpserver.py - ')
19 for x in data:
20 debug_out.append(str(x))
21 fdebug = open('debug.txt', 'a')
22 fdebug.write(' '.join(debug_out))
23 fdebug.close()
25 class TivoHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
26 containers = {}
28 def __init__(self, server_address, RequestHandlerClass):
29 BaseHTTPServer.HTTPServer.__init__(self, server_address,
30 RequestHandlerClass)
31 self.daemon_threads = True
33 def add_container(self, name, settings):
34 if self.containers.has_key(name) or name == 'TiVoConnect':
35 raise "Container Name in use"
36 try:
37 settings['content_type'] = GetPlugin(settings['type']).CONTENT_TYPE
38 self.containers[name] = settings
39 except KeyError:
40 print 'Unable to add container', name
42 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
44 def address_string(self):
45 host, port = self.client_address[:2]
46 return host
48 def do_GET(self):
50 basepath = unquote_plus(self.path).split('/')[1]
52 ## Get File
53 for name, container in self.server.containers.items():
54 if basepath == name:
55 plugin = GetPlugin(container['type'])
56 plugin.send_file(self, container, name)
57 return
59 ## Not a file not a TiVo command fuck them
60 if not self.path.startswith('/TiVoConnect'):
61 self.infopage()
62 return
64 o = urlparse("http://fake.host" + self.path)
65 query = parse_qs(o[4])
67 mname = False
68 if query.has_key('Command') and len(query['Command']) >= 1:
70 command = query['Command'][0]
72 # If we are looking at the root container
73 if command == "QueryContainer" and \
74 (not query.has_key('Container') or query['Container'][0] == '/'):
75 self.root_container()
76 return
78 if query.has_key('Container'):
79 # Dispatch to the container plugin
80 basepath = query['Container'][0].split('/')[0]
81 for name, container in self.server.containers.items():
82 if basepath == name:
83 plugin = GetPlugin(container['type'])
84 if hasattr(plugin, command):
85 method = getattr(plugin, command)
86 method(self, query)
87 return
88 else:
89 self.unsupported(query)
90 return
91 break
93 #if we made it here it means we couldn't match the request to anything.
94 self.unsupported(query)
95 return
96 else:
97 self.unsupported(query)
99 def root_container(self):
100 tsn = self.headers.getheader('TiVo_TCD_ID', '')
101 tsnshares = config.getShares(tsn)
102 tsncontainers = {}
103 for section, settings in tsnshares:
104 try:
105 settings['content_type'] = GetPlugin(settings['type']).CONTENT_TYPE
106 tsncontainers[section] = settings
107 except:
108 None
109 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
110 'root_container.tmpl'))
111 t.containers = tsncontainers
112 t.hostname = socket.gethostname()
113 t.escape = escape
114 self.send_response(200)
115 self.end_headers()
116 self.wfile.write(t)
118 def infopage(self):
119 self.send_response(200)
120 self.send_header('Content-type', 'text/html')
121 self.end_headers()
122 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
123 'info_page.tmpl'))
124 self.wfile.write(t)
125 self.end_headers()
127 def unsupported(self, query):
128 if hack83 and 'Command' in query and 'Filter' in query:
129 debug_write(['Unsupported request,',
130 'checking to see if it is video.\n'])
131 command = query['Command'][0]
132 plugin = GetPlugin('video')
133 if ''.join(query['Filter']).find('video') >= 0 and \
134 hasattr(plugin, command):
135 debug_write(['Unsupported request,',
136 'yup it is video',
137 'send to video plugin for it to sort out.\n'])
138 method = getattr(plugin, command)
139 method(self, query)
140 return
142 self.send_response(404)
143 self.send_header('Content-type', 'text/html')
144 self.end_headers()
145 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
146 'unsupported.tmpl'))
147 t.query = query
148 self.wfile.write(t)
150 if __name__ == '__main__':
151 def start_server():
152 httpd = TivoHTTPServer(('', 9032), TivoHTTPHandler)
153 httpd.add_container('test', 'x-container/tivo-videos',
154 r'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')
155 httpd.serve_forever()
157 start_server()