flag console debug echoes
[pyTivo/wgw.git] / httpserver.py
blob86d4eb5f10af75e4cd35d30e93fd3398dce6d834
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
9 from debug import debug_write, fn_attr
11 SCRIPTDIR = os.path.dirname(__file__)
13 hack83 = config.getHack83()
15 class TivoHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
16 containers = {}
18 def __init__(self, server_address, RequestHandlerClass):
19 BaseHTTPServer.HTTPServer.__init__(self, server_address,
20 RequestHandlerClass)
21 self.daemon_threads = True
23 def add_container(self, name, settings):
24 if self.containers.has_key(name) or name == 'TiVoConnect':
25 raise "Container Name in use"
26 try:
27 settings['content_type'] = GetPlugin(settings['type']).CONTENT_TYPE
28 self.containers[name] = settings
29 except KeyError:
30 print 'Unable to add container', name
32 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
34 def address_string(self):
35 host, port = self.client_address[:2]
36 return host
38 def do_GET(self):
40 basepath = unquote_plus(self.path).split('/')[1]
42 ## Get File
43 for name, container in self.server.containers.items():
44 if basepath == name:
45 plugin = GetPlugin(container['type'])
46 plugin.send_file(self, container, name)
47 return
49 ## Not a file not a TiVo command fuck them
50 if not self.path.startswith('/TiVoConnect'):
51 self.infopage()
52 return
54 o = urlparse("http://fake.host" + self.path)
55 query = parse_qs(o[4])
57 mname = False
58 if query.has_key('Command') and len(query['Command']) >= 1:
60 command = query['Command'][0]
62 # If we are looking at the root container
63 if command == "QueryContainer" and \
64 (not query.has_key('Container') or query['Container'][0] == '/'):
65 self.root_container()
66 return
68 if query.has_key('Container'):
69 # Dispatch to the container plugin
70 basepath = query['Container'][0].split('/')[0]
71 for name, container in self.server.containers.items():
72 if basepath == name:
73 plugin = GetPlugin(container['type'])
74 if hasattr(plugin, command):
75 method = getattr(plugin, command)
76 method(self, query)
77 return
78 else:
79 break
81 # If we made it here it means we couldn't match the request to
82 # anything.
83 self.unsupported(query)
85 def root_container(self):
86 tsn = self.headers.getheader('TiVo_TCD_ID', '')
87 tsnshares = config.getShares(tsn)
88 tsncontainers = {}
89 for section, settings in tsnshares:
90 try:
91 settings['content_type'] = \
92 GetPlugin(settings['type']).CONTENT_TYPE
93 tsncontainers[section] = settings
94 except Exception, msg:
95 print section, '-', msg
96 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
97 'root_container.tmpl'))
98 t.containers = tsncontainers
99 t.hostname = socket.gethostname()
100 t.escape = escape
101 self.send_response(200)
102 self.end_headers()
103 self.wfile.write(t)
105 def infopage(self):
106 self.send_response(200)
107 self.send_header('Content-type', 'text/html')
108 self.end_headers()
109 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
110 'info_page.tmpl'))
111 self.wfile.write(t)
112 self.end_headers()
114 def unsupported(self, query):
115 if hack83 and 'Command' in query and 'Filter' in query:
116 debug_write(__name__, fn_attr(), ['Unsupported request,',
117 'checking to see if it is video.'])
118 command = query['Command'][0]
119 plugin = GetPlugin('video')
120 if ''.join(query['Filter']).find('video') >= 0 and \
121 hasattr(plugin, command):
122 debug_write(__name__, fn_attr(), ['Unsupported request,',
123 'yup it is video',
124 'send to video plugin for it to sort out.'])
125 method = getattr(plugin, command)
126 method(self, query)
127 return
129 self.send_response(404)
130 self.send_header('Content-type', 'text/html')
131 self.end_headers()
132 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
133 'unsupported.tmpl'))
134 t.query = query
135 self.wfile.write(t)
137 if __name__ == '__main__':
138 def start_server():
139 httpd = TivoHTTPServer(('', 9032), TivoHTTPHandler)
140 httpd.add_container('test', 'x-container/tivo-videos',
141 r'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')
142 httpd.serve_forever()
144 start_server()