Remove the horrible viewport effect from the ToGo menu.
[pyTivo/wgw.git] / httpserver.py
blob1d21ae51fe223b6d80ca51c45f9642c15e065922
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 import logging
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 def reset(self):
33 self.containers.clear()
34 for section, settings in config.getShares():
35 self.add_container(section, settings)
37 def set_beacon(self, beacon):
38 self.beacon = beacon
40 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
41 tivos = {}
42 tivo_names = {}
44 def address_string(self):
45 host, port = self.client_address[:2]
46 return host
48 def do_GET(self):
49 tsn = self.headers.getheader('TiVo_TCD_ID', self.headers.getheader('tsn', ''))
50 ip = self.address_string()
51 self.tivos[tsn] = ip
53 if not tsn in self.tivo_names:
54 self.tivo_names[tsn] = self.server.beacon.get_name(ip)
56 basepath = unquote_plus(self.path).split('/')[1]
58 ## Get File
59 for name, container in self.server.containers.items():
60 if basepath == name:
61 plugin = GetPlugin(container['type'])
62 plugin.send_file(self, container, name)
63 return
65 ## Not a file not a TiVo command fuck them
66 if not self.path.startswith('/TiVoConnect'):
67 self.infopage()
68 return
70 o = urlparse("http://fake.host" + self.path)
71 query = parse_qs(o[4])
73 mname = False
74 if query.has_key('Command') and len(query['Command']) >= 1:
76 command = query['Command'][0]
78 # If we are looking at the root container
79 if command == "QueryContainer" and \
80 (not query.has_key('Container') or query['Container'][0] == '/'):
81 self.root_container()
82 return
84 if query.has_key('Container'):
85 # Dispatch to the container plugin
86 basepath = unquote(query['Container'][0].split('/')[0])
87 for name, container in self.server.containers.items():
88 if basepath == name:
89 plugin = GetPlugin(container['type'])
90 if hasattr(plugin, command):
91 method = getattr(plugin, command)
92 method(self, query)
93 return
94 else:
95 break
97 # If we made it here it means we couldn't match the request to
98 # anything.
99 self.unsupported(query)
101 def root_container(self):
102 tsn = self.headers.getheader('TiVo_TCD_ID', '')
103 tsnshares = config.getShares(tsn)
104 tsncontainers = {}
105 for section, settings in tsnshares:
106 try:
107 settings['content_type'] = \
108 GetPlugin(settings['type']).CONTENT_TYPE
109 tsncontainers[section] = settings
110 except Exception, msg:
111 print section, '-', msg
112 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
113 'root_container.tmpl'))
114 t.containers = tsncontainers
115 t.hostname = socket.gethostname()
116 t.escape = escape
117 t.quote = quote
118 self.send_response(200)
119 self.end_headers()
120 self.wfile.write(t)
122 def infopage(self):
123 self.send_response(200)
124 self.send_header('Content-type', 'text/html')
125 self.end_headers()
126 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
127 'info_page.tmpl'))
128 t.admin = ''
129 for section, settings in config.getShares():
130 if 'type' in settings and settings['type'] == 'admin':
131 t.admin += '<a href="/TiVoConnect?Command=Admin&Container=' + quote(section)\
132 + '">pyTivo Web Configuration</a><br>'\
133 + '<a href="/TiVoConnect?Command=NPL&Container=' + quote(section)\
134 + '">pyTivo ToGo</a><br>'
135 if t.admin == '':
136 t.admin = '<br><b>No Admin plugin installed in pyTivo.conf</b><br> If you wish to use'\
137 + ' the admin plugin add the following lines to pyTivo.conf<br><br>'\
138 + '[Admin]<br>type=admin'
140 t.shares = 'Video shares:<br/>'
141 for section, settings in config.getShares():
142 if settings.get('type') == 'video':
143 t.shares += '<a href="TiVoConnect?Command=QueryContainer&Container=' + quote(section)\
144 + '">' + section + '</a><br/>'
146 self.wfile.write(t)
147 self.end_headers()
149 def unsupported(self, query):
150 if hack83 and 'Command' in query and 'Filter' in query:
151 logger = logging.getLogger('pyTivo.hack83')
153 logger.debug('Unsupported request checking to see if it is video.')
154 command = query['Command'][0]
155 plugin = GetPlugin('video')
156 if ''.join(query['Filter']).find('video') >= 0 and \
157 hasattr(plugin, command):
158 logger.debug('Unsupported request yup it is video send to video plugin for it to sort out.')
159 method = getattr(plugin, command)
160 method(self, query)
161 return
163 self.send_response(404)
164 self.send_header('Content-type', 'text/html')
165 self.end_headers()
166 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
167 'unsupported.tmpl'))
168 t.query = query
169 self.wfile.write(t)
171 if __name__ == '__main__':
172 def start_server():
173 httpd = TivoHTTPServer(('', 9032), TivoHTTPHandler)
174 httpd.add_container('test', 'x-container/tivo-videos',
175 r'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')
176 httpd.serve_forever()
178 start_server()