forked from iBaa/PlexConnect
-
Notifications
You must be signed in to change notification settings - Fork 1
/
WebServer.py
executable file
·338 lines (268 loc) · 12.1 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#!/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
after 27Aug - Apple's switch to https:
- added https WebServer with SSL encryption - needs valid (private) vertificate on aTV and server
- for additional information see http://langui.sh/2013/08/27/appletv-ssl-plexconnect/
Thanks to reaperhulk for showing this solution!
"""
import sys
import string, cgi, time
from os import sep, path
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import ssl
from multiprocessing import Pipe # inter process communication
import urllib
import signal
import Settings, ATVSettings
from Debug import * # dprint()
import XMLConverter # XML_PMS2aTV, XML_PlayVideo
import re
import Localize
g_param = {}
def setParams(param):
global g_param
g_param = param
def JSConverter(file, options):
f = open(sys.path[0] + "/assets/js/" + file)
JS = f.read()
f.close()
# PlexConnect {{URL()}}->baseURL
for path in set(re.findall(r'\{\{URL\((.+?)\)\}\}', JS)):
JS = JS.replace('{{URL(%s)}}' % path, g_param['baseURL']+path)
# localization
JS = Localize.replaceTEXT(JS, options['aTVLanguage']).encode('utf-8')
return JS
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):
global g_param
try:
dprint(__name__, 2, "http request header:\n{0}", self.headers)
dprint(__name__, 2, "http request path:\n{0}", self.path)
# check for PMS address
PMSaddress = ''
pms_end = self.path.find(')')
if self.path.startswith('/PMS(') and pms_end>-1:
PMSaddress = urllib.unquote_plus(self.path[5:pms_end])
self.path = self.path[pms_end+1:]
# break 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]] = urllib.unquote(parts[1])
# break up path, separate additional arguments
# clean path needed for filetype decoding... has to be merged back when forwarded.
parts = self.path.split('?', 1)
if len(parts)==1:
args = ''
else:
self.path = parts[0]
args = '?'+parts[1]
# get aTV language setting
options['aTVLanguage'] = Localize.pickLanguage(self.headers.get('Accept-Language', 'en'))
# add client address - to be used in case UDID is unknown
options['aTVAddress'] = self.client_address[0]
dprint(__name__, 2, "pms address:\n{0}", PMSaddress)
dprint(__name__, 2, "cleaned path:\n{0}", self.path)
dprint(__name__, 2, "PlexConnect options:\n{0}", options)
dprint(__name__, 2, "additional arguments:\n{0}", args)
if 'User-Agent' in self.headers and \
'AppleTV' in self.headers['User-Agent']:
# recieve simple logging messages from the ATV
if 'PlexConnectATVLogLevel' in options:
dprint('ATVLogger', int(options['PlexConnectATVLogLevel']), options['PlexConnectLog'])
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
return
# serve "*.cer" - Serve up certificate file to atv
if self.path.endswith(".cer"):
dprint(__name__, 1, "serving *.cer: "+self.path)
if g_param['CSettings'].getSetting('certfile').startswith('.'):
# relative to current path
cfg_certfile = sys.path[0] + sep + g_param['CSettings'].getSetting('certfile')
else:
# absolute path
cfg_certfile = g_param['CSettings'].getSetting('certfile')
cfg_certfile = path.splitext(cfg_certfile)[0] + '.cer'
try:
f = open(cfg_certfile, "rb")
except:
dprint(__name__, 0, "Failed to access certificate: {0}", cfg_certfile)
return
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
# serve .js files to aTV
# application, main: ignore path, send /assets/js/application.js
# otherwise: path should be '/js', send /assets/js/*.js
dirname = path.dirname(self.path)
basename = path.basename(self.path)
if basename in ("application.js", "main.js", "javascript-packed.js") or \
basename.endswith(".js") and dirname == '/js':
if basename in ("main.js", "javascript-packed.js"):
basename = "application.js"
dprint(__name__, 1, "serving /js/{0}", basename)
JS = JSConverter(basename, options)
self.send_response(200)
self.send_header('Content-type', 'text/javascript')
self.end_headers()
self.wfile.write(JS)
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(PMSaddress, self.path + args, options)
self.send_response(200)
self.send_header('Content-type', 'text/xml')
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['IP_self']
cfg_Port_WebServer = param['CSettings'].getSetting('port_webserver')
try:
server = HTTPServer((cfg_IP_WebServer,int(cfg_Port_WebServer)), MyHandler)
server.timeout = 1
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)
socketinfo = server.socket.getsockname()
dprint(__name__, 0, "***")
dprint(__name__, 0, "WebServer: Serving HTTP on {0} port {1}.", socketinfo[0], socketinfo[1])
dprint(__name__, 0, "***")
setParams(param)
XMLConverter.setParams(param)
cfg = ATVSettings.CATVSettings()
XMLConverter.setATVSettings(cfg)
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()
def Run_SSL(cmdPipe, param):
if not __name__ == '__main__':
signal.signal(signal.SIGINT, signal.SIG_IGN)
dinit(__name__, param) # init logging, WebServer process
cfg_IP_WebServer = param['IP_self']
cfg_Port_SSL = param['CSettings'].getSetting('port_ssl')
if param['CSettings'].getSetting('certfile').startswith('.'):
# relative to current path
cfg_certfile = sys.path[0] + sep + param['CSettings'].getSetting('certfile')
else:
# absolute path
cfg_certfile = param['CSettings'].getSetting('certfile')
try:
certfile = open(cfg_certfile, 'r')
except:
dprint(__name__, 0, "Failed to access certificate: {0}", cfg_certfile)
sys.exit(1)
certfile.close()
try:
server = HTTPServer((cfg_IP_WebServer,int(cfg_Port_SSL)), MyHandler)
server.socket = ssl.wrap_socket(server.socket, certfile=cfg_certfile, server_side=True)
server.timeout = 1
except Exception, e:
dprint(__name__, 0, "Failed to connect to HTTPS on {0} port {1}: {2}", cfg_IP_WebServer, cfg_Port_SSL, e)
sys.exit(1)
socketinfo = server.socket.getsockname()
dprint(__name__, 0, "***")
dprint(__name__, 0, "WebServer: Serving HTTPS on {0} port {1}.", socketinfo[0], socketinfo[1])
dprint(__name__, 0, "***")
setParams(param)
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.")
server.socket.close()
if __name__=="__main__":
cmdPipe = Pipe()
cfg = Settings.CSettings()
param = {}
param['CSettings'] = cfg
param['IP_self'] = '192.168.178.20' # IP_self?
param['baseURL'] = 'http://'+ param['IP_self'] +':'+ cfg.getSetting('port_webserver')
param['HostToIntercept'] = 'trailers.apple.com'
if len(sys.argv)==1:
Run(cmdPipe[1], param)
elif len(sys.argv)==2 and sys.argv[1]=='SSL':
Run_SSL(cmdPipe[1], param)