Merge branch 'master' of git://repo.or.cz/pyTivo/wmcbrine
[pyTivo.git] / httpserver.py
blobdcba933ac04df8783793d576e7fd951bb7258bf6
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 def reset(self):
33 self.containers.clear()
34 for section, settings in config.getShares():
35 self.add_container(section, settings)
37 class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
39 def address_string(self):
40 host, port = self.client_address[:2]
41 return host
43 def do_GET(self):
45 basepath = unquote_plus(self.path).split('/')[1]
47 ## Get File
48 for name, container in self.server.containers.items():
49 if basepath == name:
50 plugin = GetPlugin(container['type'])
51 plugin.send_file(self, container, name)
52 return
54 ## Not a file not a TiVo command fuck them
55 if not self.path.startswith('/TiVoConnect'):
56 self.infopage()
57 return
59 o = urlparse("http://fake.host" + self.path)
60 query = parse_qs(o[4])
62 mname = False
63 if query.has_key('Command') and len(query['Command']) >= 1:
65 command = query['Command'][0]
67 # If we are looking at the root container
68 if command == "QueryContainer" and \
69 (not query.has_key('Container') or query['Container'][0] == '/'):
70 self.root_container()
71 return
73 if query.has_key('Container'):
74 # Dispatch to the container plugin
75 basepath = query['Container'][0].split('/')[0]
76 for name, container in self.server.containers.items():
77 if basepath == name:
78 plugin = GetPlugin(container['type'])
79 if hasattr(plugin, command):
80 method = getattr(plugin, command)
81 method(self, query)
82 return
83 else:
84 break
86 # If we made it here it means we couldn't match the request to
87 # anything.
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 try:
96 settings['content_type'] = \
97 GetPlugin(settings['type']).CONTENT_TYPE
98 tsncontainers[section] = settings
99 except Exception, msg:
100 print section, '-', msg
101 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
102 'root_container.tmpl'))
103 t.containers = tsncontainers
104 t.hostname = socket.gethostname()
105 t.escape = escape
106 self.send_response(200)
107 self.end_headers()
108 self.wfile.write(t)
110 def infopage(self):
111 self.send_response(200)
112 self.send_header('Content-type', 'text/html')
113 self.end_headers()
114 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
115 'info_page.tmpl'))
116 t.admin = ''
117 for section, settings in config.getShares():
118 if 'type' in settings and settings['type'] == 'admin':
119 t.admin += '<a href="/TiVoConnect?Command=Admin&Container=' + section\
120 + '">pyTivo Web Configuration</a><br>'
121 self.wfile.write(t)
122 self.end_headers()
124 def unsupported(self, query):
125 if hack83 and 'Command' in query and 'Filter' in query:
126 debug_write(__name__, fn_attr(), ['Unsupported request,',
127 'checking to see if it is video.'])
128 command = query['Command'][0]
129 plugin = GetPlugin('video')
130 if ''.join(query['Filter']).find('video') >= 0 and \
131 hasattr(plugin, command):
132 debug_write(__name__, fn_attr(), ['Unsupported request,',
133 'yup it is video',
134 'send to video plugin for it to sort out.'])
135 method = getattr(plugin, command)
136 method(self, query)
137 return
139 self.send_response(404)
140 self.send_header('Content-type', 'text/html')
141 self.end_headers()
142 t = Template(file=os.path.join(SCRIPTDIR, 'templates',
143 'unsupported.tmpl'))
144 t.query = query
145 self.wfile.write(t)
147 if __name__ == '__main__':
148 def start_server():
149 httpd = TivoHTTPServer(('', 9032), TivoHTTPHandler)
150 httpd.add_container('test', 'x-container/tivo-videos',
151 r'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')
152 httpd.serve_forever()
154 start_server()