Another place to check for an exact share name match.
[pyTivo.git] / httpserver.py
blob13bb974e3129b45514172e9c578cff15ac2bf3cf
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 settings['content_type'] = GetPlugin(settings['type']).CONTENT_TYPE
37 self.containers[name] = settings
39 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
41 def address_string(self):
42 host, port = self.client_address[:2]
43 return host
45 def do_GET(self):
47 basepath = unquote_plus(self.path).split('/')[1]
49 ## Get File
50 for name, container in self.server.containers.items():
51 if basepath == name:
52 plugin = GetPlugin(container['type'])
53 plugin.send_file(self, container, name)
54 return
56 ## Not a file not a TiVo command fuck them
57 if not self.path.startswith('/TiVoConnect'):
58 self.infopage()
59 return
61 o = urlparse("http://fake.host" + self.path)
62 query = parse_qs(o[4])
64 mname = False
65 if query.has_key('Command') and len(query['Command']) >= 1:
67 command = query['Command'][0]
69 # If we are looking at the root container
70 if command == "QueryContainer" and \
71 (not query.has_key('Container') or query['Container'][0] == '/'):
72 self.root_container()
73 return
75 if query.has_key('Container'):
76 # Dispatch to the container plugin
77 basepath = query['Container'][0].split('/')[0]
78 for name, container in self.server.containers.items():
79 if basepath == name:
80 plugin = GetPlugin(container['type'])
81 if hasattr(plugin, command):
82 method = getattr(plugin, command)
83 method(self, query)
84 else:
85 self.unsupported(query)
86 break
87 else:
88 self.unsupported(query)
90 def root_container(self):
91 tsn = self.headers.getheader('TiVo_TCD_ID', '')
92 tsnshares = config.getShares(tsn)
93 tsncontainers = {}
94 for section, settings in tsnshares:
95 settings['content_type'] = GetPlugin(settings['type']).CONTENT_TYPE
96 tsncontainers[section] = settings
97 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
98 'root_container.tmpl'))
99 t.containers = tsncontainers
100 t.hostname = socket.gethostname()
101 t.escape = escape
102 self.send_response(200)
103 self.end_headers()
104 self.wfile.write(t)
106 def infopage(self):
107 self.send_response(200)
108 self.send_header('Content-type', 'text/html')
109 self.end_headers()
110 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
111 'info_page.tmpl'))
112 self.wfile.write(t)
113 self.end_headers()
115 def unsupported(self, query):
116 if hack83 and 'Command' in query and 'Filter' in query:
117 debug_write(['Unsupported request,',
118 'checking to see if it is video.\n'])
119 command = query['Command'][0]
120 plugin = GetPlugin('video')
121 if ''.join(query['Filter']).find('video') >= 0 and \
122 hasattr(plugin, command):
123 debug_write(['Unsupported request,',
124 'yup it is video',
125 'send to video plugin for it to sort out.\n'])
126 method = getattr(plugin, command)
127 method(self, query)
128 return
130 self.send_response(404)
131 self.send_header('Content-type', 'text/html')
132 self.end_headers()
133 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
134 'unsupported.tmpl'))
135 t.query = query
136 self.wfile.write(t)
138 if __name__ == '__main__':
139 def start_server():
140 httpd = TivoHTTPServer(('', 9032), TivoHTTPHandler)
141 httpd.add_container('test', 'x-container/tivo-videos',
142 r'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')
143 httpd.serve_forever()
145 start_server()