forked from iBaa/PlexConnect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebServer.py
executable file
·226 lines (183 loc) · 8.21 KB
/
WebServer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env python
"""
Sources:
http://fragments.turtlemeat.com/pythonwebserver.php
http://www.linuxjournal.com/content/tech-tip-really-simple-http-server-python
...stackoverflow.com and such
"""
import sys
import string, cgi, time
from os import sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from multiprocessing import Pipe # inter process communication
import signal
try:
import xml.etree.cElementTree as etree
except ImportError:
import xml.etree.ElementTree as etree
import Settings, ATVSettings
from Debug import * # dprint()
import XMLConverter # XML_PMS2aTV, XML_PlayVideo
g_param = {}
def setParams(param):
global g_param
g_param = param
class MyHandler(BaseHTTPRequestHandler):
# Fixes slow serving speed under Windows
def address_string(self):
host, port = self.client_address[:2]
#return socket.getfqdn(host)
return host
def log_message(self, format, *args):
pass
def do_GET(self):
try:
dprint(__name__, 2, "http request header:\n{0}", self.headers)
dprint(__name__, 2, "http request path:\n{0}", self.path)
# brake up path, separate PlexConnect options
options = {}
while True:
cmd_start = self.path.find('&PlexConnect')
cmd_end = self.path.find('&', cmd_start+1)
if cmd_start==-1:
break
if cmd_end>-1:
cmd = self.path[cmd_start+1:cmd_end]
self.path = self.path[:cmd_start] + self.path[cmd_end:]
else:
cmd = self.path[cmd_start+1:]
self.path = self.path[:cmd_start]
parts = cmd.split('=', 1)
if len(parts)==1:
options[parts[0]] = ''
else:
options[parts[0]] = parts[1]
dprint(__name__, 2, "cleaned path:\n{0}", self.path)
dprint(__name__, 2, "request options:\n{0}", options)
if 'User-Agent' in self.headers and \
'AppleTV' in self.headers['User-Agent']:
# recieve simple logging messages from the ATV
if self.path.endswith("&atvlogger"):
msg = self.path.replace("%20", " ")
msg = msg.replace("<", "<")
msg = msg.replace(">", ">")
msg = msg.replace("&fs;", "/")
msg = msg.replace("&qo;", '"')
msg = msg[1:len(msg)-10]
dprint('ATVLogger', 0, msg)
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
return
# serve "application.js" to aTV
# disregard the path - it is different for different iOS versions
if self.path.endswith("application.js"):
dprint(__name__, 1, "serving application.js")
f = open(sys.path[0] + sep + "assets" + sep + "js" + sep + "application.js")
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
# serve all other .js files to aTV
if self.path.endswith(".js"):
dprint(__name__, 1, "serving " + sys.path[0] + sep + "assets" + self.path.replace('/',sep))
f = open(sys.path[0] + sep + "assets" + self.path.replace('/',sep))
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
# serve all .xml files to aTV including "plexconnect.xml" or "plexconnect_oldmenu.xml"
if self.path.endswith(".xml"):
dprint(__name__,1,"serving "+ sys.path[0] + sep + "assets" + self.path.replace('/',sep))
f = open(sys.path[0] + sep + "assets" + self.path.replace('/',sep))
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
# serve "*.jpg" - thumbnails for old-style mainpage
if self.path.endswith(".jpg"):
dprint(__name__, 1, "serving *.jpg: "+self.path)
f = open(sys.path[0] + sep + "assets" + self.path, "rb")
self.send_response(200)
self.send_header('Content-type', 'image/jpeg')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
# serve "*.png" - only png's support transparent colors
if self.path.endswith(".png"):
dprint(__name__, 1, "serving *.png: "+self.path)
f = open(sys.path[0] + sep + "assets" + self.path, "rb")
self.send_response(200)
self.send_header('Content-type', 'image/png')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
# get everything else from XMLConverter - formerly limited to trailing "/" and &PlexConnect Cmds
if True:
dprint(__name__, 1, "serving .xml: "+self.path)
XML = XMLConverter.XML_PMS2aTV(self.client_address, self.path, options)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(XML)
return
"""
# unexpected request
self.send_error(403,"Access denied: %s" % self.path)
"""
else:
self.send_error(403,"Not Serving Client %s" % self.client_address[0])
except IOError:
self.send_error(404,"File Not Found: %s" % self.path)
def Run(cmdPipe, param):
if not __name__ == '__main__':
signal.signal(signal.SIGINT, signal.SIG_IGN)
dinit(__name__, param) # init logging, WebServer process
cfg_IP_WebServer = param['CSettings'].getSetting('ip_webserver')
cfg_Port_WebServer = param['CSettings'].getSetting('port_webserver')
try:
server = HTTPServer((cfg_IP_WebServer,int(cfg_Port_WebServer)), MyHandler)
server.timeout = 1
sa = server.socket.getsockname()
except Exception, e:
dprint(__name__, 0, "Failed to connect to HTTP on {0} port {1}: {2}", cfg_IP_WebServer, cfg_Port_WebServer, e)
sys.exit(1)
dprint(__name__, 0, "***")
dprint(__name__, 0, "WebServer: Serving HTTP on {0} port {1}.", sa[0], sa[1])
dprint(__name__, 0, "***")
setParams(param)
XMLConverter.setParams(param)
cfg = ATVSettings.CATVSettings()
XMLConverter.setATVSettings(cfg)
XMLConverter.discoverPMS()
try:
while True:
# check command
if cmdPipe.poll():
cmd = cmdPipe.recv()
if cmd=='shutdown':
break
# do your work (with timeout)
server.handle_request()
except KeyboardInterrupt:
signal.signal(signal.SIGINT, signal.SIG_IGN) # we heard you!
dprint(__name__, 0,"^C received.")
finally:
dprint(__name__, 0, "Shutting down.")
cfg.saveSettings()
del cfg
server.socket.close()
if __name__=="__main__":
cmdPipe = Pipe()
cfg = Settings.CSettings()
param = {}
param['CSettings'] = cfg
Run(cmdPipe[1], param)