forked from ValdikSS/aceproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathacehttp.py
More file actions
executable file
·438 lines (386 loc) · 16.3 KB
/
Copy pathacehttp.py
File metadata and controls
executable file
·438 lines (386 loc) · 16.3 KB
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
AceProxy: Ace Stream to HTTP Proxy
Website: https://github.com/ValdikSS/AceProxy
'''
import gevent
import gevent.monkey
# Monkeypatching and all the stuff
gevent.monkey.patch_all()
import gevent.queue
import glob
import os
import sys
import logging
import BaseHTTPServer
import SocketServer
import urllib2
import hashlib
import aceclient
from aceconfig import AceConfig
import vlcclient
from aceclient.clientcounter import ClientCounter
from plugins.PluginInterface import AceProxyPlugin
class HTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def closeConnection(self):
'''
Disconnecting client
'''
if self.clientconnected:
self.clientconnected = False
try:
self.wfile.close()
self.rfile.close()
except:
pass
def dieWithError(self, errorcode=500):
'''
Close connection with error
'''
logging.warning("Dying with error")
if self.clientconnected:
self.send_error(errorcode)
self.end_headers()
self.closeConnection()
def proxyReadWrite(self):
'''
Read video stream and send it to client
'''
logger = logging.getLogger('http_proxyReadWrite')
logger.debug("Started")
self.vlcstate = True
while True:
try:
if AceConfig.videoobey and not AceConfig.vlcuse:
# Wait for PlayEvent if videoobey is enabled. Not for VLC
self.ace.getPlayEvent()
if AceConfig.videoobey and AceConfig.vlcuse:
# For VLC
try:
# Waiting 0.5 seconds. If timeout, there would be exception.
# Set vlcstate to False in the exception and pause the
# stream
# A bit ugly, huh?
self.ace.getPlayEvent(0.5)
if not self.vlcstate:
AceStuff.vlcclient.unPauseBroadcast(self.vlcid)
self.vlcstate = True
except gevent.Timeout:
if self.vlcstate:
AceStuff.vlcclient.pauseBroadcast(self.vlcid)
self.vlcstate = False
if not self.clientconnected:
logger.debug("Client is not connected, terminating")
return
data = self.video.read(4096)
if data and self.clientconnected:
self.wfile.write(data)
else:
# Prevent 100% CPU usage
gevent.sleep(0.5)
except:
# Video connection dropped
logger.debug("Video Connection dropped")
self.video.close()
self.closeConnection()
gevent.sleep()
return
def hangDetector(self):
'''
Detect client disconnection while in the middle of something
or just normal connection close.
'''
logger = logging.getLogger('http_hangDetector')
logger.debug("Started")
try:
while True:
if not self.rfile.read():
break
except:
pass
finally:
self.clientconnected = False
logger.debug("Client disconnected")
try:
self.requestgreenlet.kill()
self.proxyReadWritegreenlet.kill()
gevent.sleep()
except:
pass
return
def do_GET(self):
'''
GET request handler
'''
logger = logging.getLogger('http_HTTPHandler')
self.clientconnected = True
# Don't wait videodestroydelay if error happened
self.errorhappened = True
# Headers sent flag for fake headers UAs
self.headerssent = False
# Current greenlet
self.requestgreenlet = gevent.getcurrent()
# Connected client IP address
self.clientip = self.request.getpeername()[0]
logger.info("Accepted connection from " + self.clientip + " path " + self.path)
try:
self.splittedpath = self.path.split('/')
self.reqtype = self.splittedpath[1].lower()
# If first parameter is 'pid' or 'torrent' or it should be handled
# by plugin
if not (self.reqtype in ('pid', 'torrent') or self.reqtype in AceStuff.pluginshandlers):
self.dieWithError(400) # 400 Bad Request
return
except IndexError:
self.dieWithError(400) # 400 Bad Request
return
# Handle request with plugin handler
if self.reqtype in AceStuff.pluginshandlers:
try:
AceStuff.pluginshandlers.get(self.reqtype).handle(self)
except Exception as e:
logger.error('Plugin exception: ' + repr(e))
self.dieWithError()
finally:
self.closeConnection()
return
# Check if third parameter exists
# …/pid/blablablablabla/video.mpg
# |_________|
# And if it ends with regular video extension
try:
if not self.path.endswith(('.3gp', '.avi', '.flv', '.mkv', '.mov', '.mp4', '.mpeg', '.mpg', '.ogv', '.ts')):
logger.error("Request seems like valid but no valid video extension was provided")
self.dieWithError(400)
return
except IndexError:
self.dieWithError(400) # 400 Bad Request
return
# Limit concurrent connections
if AceConfig.maxconns > 0 and AceStuff.clientcounter.total >= AceConfig.maxconns:
logger.debug("Maximum connections reached, can't serve this")
self.dieWithError(503) # 503 Service Unavailable
return
# Pretend to work fine with Fake UAs
if self.headers.get('User-Agent') and self.headers.get('User-Agent') in AceConfig.fakeuas:
logger.debug("Got fake UA: " + self.headers.get('User-Agent'))
# Return 200 and exit
self.send_response(200)
self.send_header("Content-Type", "video/mpeg")
self.end_headers()
self.closeConnection()
return
self.path_unquoted = urllib2.unquote(self.splittedpath[2])
# Make list with parameters
self.params = list()
for i in xrange(3, 8):
try:
self.params.append(int(self.splittedpath[i]))
except (IndexError, ValueError):
self.params.append('0')
# Adding client to clientcounter
clients = AceStuff.clientcounter.add(self.path_unquoted, self.clientip)
# If we are the one client, but sucessfully got ace from clientcounter,
# then somebody is waiting in the videodestroydelay state
self.ace = AceStuff.clientcounter.getAce(self.path_unquoted)
if not self.ace:
shouldcreateace = True
else:
shouldcreateace = False
# Use PID as VLC ID if PID requested
# Or torrent url MD5 hash if torrent requested
if self.reqtype == 'pid':
self.vlcid = self.path_unquoted
else:
self.vlcid = hashlib.md5(self.path_unquoted).hexdigest()
# If we don't use VLC and we're not the first client
if clients != 1 and not AceConfig.vlcuse:
AceStuff.clientcounter.delete(self.path_unquoted, self.clientip)
logger.error(
"Not the first client, cannot continue in non-VLC mode")
self.dieWithError(503) # 503 Service Unavailable
return
if shouldcreateace:
# If we are the only client, create AceClient
try:
self.ace = aceclient.AceClient(
AceConfig.acehost, AceConfig.aceport, connect_timeout=AceConfig.aceconntimeout,
result_timeout=AceConfig.aceresulttimeout)
# Adding AceClient instance to pool
AceStuff.clientcounter.addAce(self.path_unquoted, self.ace)
logger.debug("AceClient created")
except aceclient.AceException as e:
logger.error("AceClient create exception: " + repr(e))
AceStuff.clientcounter.delete(
self.path_unquoted, self.clientip)
self.dieWithError(502) # 502 Bad Gateway
return
# Send fake headers if this User-Agent is in fakeheaderuas tuple
if self.headers.get('User-Agent') and self.headers.get('User-Agent') in AceConfig.fakeheaderuas:
logger.debug(
"Sending fake headers for " + self.headers.get('User-Agent'))
self.send_response(200)
self.send_header("Content-Type", "video/mpeg")
self.end_headers()
# Do not send real headers at all
self.headerssent = True
try:
self.hanggreenlet = gevent.spawn(self.hangDetector)
logger.debug("hangDetector spawned")
gevent.sleep()
# Initializing AceClient
if shouldcreateace:
self.ace.aceInit(
gender=AceConfig.acesex, age=AceConfig.aceage,
product_key=AceConfig.acekey, pause_delay=AceConfig.videopausedelay)
logger.debug("AceClient inited")
if self.reqtype == 'pid':
self.ace.START(
self.reqtype, {'content_id': self.path_unquoted, 'file_indexes': self.params[0]})
elif self.reqtype == 'torrent':
self.paramsdict = dict(
zip(aceclient.acemessages.AceConst.START_TORRENT, self.params))
self.paramsdict['url'] = self.path_unquoted
self.ace.START(self.reqtype, self.paramsdict)
logger.debug("START done")
# Getting URL
self.url = self.ace.getUrl(AceConfig.videotimeout)
# Rewriting host for remote Ace Stream Engine
self.url = self.url.replace('127.0.0.1', AceConfig.acehost)
self.errorhappened = False
if shouldcreateace:
logger.debug("Got url " + self.url)
# If using VLC, add this url to VLC
if AceConfig.vlcuse:
# Force ffmpeg demuxing if set in config
if AceConfig.vlcforceffmpeg:
self.vlcprefix = 'http/ffmpeg://'
else:
self.vlcprefix = ''
# Sleeping videodelay
gevent.sleep(AceConfig.videodelay)
AceStuff.vlcclient.startBroadcast(
self.vlcid, self.vlcprefix + self.url, AceConfig.vlcmux, AceConfig.vlcpreaccess)
# Sleep a bit, because sometimes VLC doesn't open port in
# time
gevent.sleep(0.5)
# Building new VLC url
if AceConfig.vlcuse:
self.url = 'http://' + AceConfig.vlchost + \
':' + str(AceConfig.vlcoutport) + '/' + self.vlcid
logger.debug("VLC url " + self.url)
# Sending client headers to videostream
self.video = urllib2.Request(self.url)
for key in self.headers.dict:
self.video.add_header(key, self.headers.dict[key])
self.video = urllib2.urlopen(self.video)
# Sending videostream headers to client
if not self.headerssent:
self.send_response(self.video.getcode())
if self.video.info().dict.has_key('connection'):
del self.video.info().dict['connection']
if self.video.info().dict.has_key('server'):
del self.video.info().dict['server']
if self.video.info().dict.has_key('transfer-encoding'):
del self.video.info().dict['transfer-encoding']
if self.video.info().dict.has_key('keep-alive'):
del self.video.info().dict['keep-alive']
for key in self.video.info().dict:
self.send_header(key, self.video.info().dict[key])
# End headers. Next goes video data
self.end_headers()
logger.debug("Headers sent")
if not AceConfig.vlcuse:
# Sleeping videodelay
gevent.sleep(AceConfig.videodelay)
# Spawning proxyReadWrite greenlet
self.proxyReadWritegreenlet = gevent.spawn(self.proxyReadWrite)
# Waiting until all greenlets are joined
gevent.joinall((self.proxyReadWritegreenlet, self.hanggreenlet))
logger.debug("Greenlets joined")
except (aceclient.AceException, vlcclient.VlcException, urllib2.URLError) as e:
logger.error("Exception: " + repr(e))
self.errorhappened = True
self.dieWithError()
except gevent.GreenletExit:
# hangDetector told us about client disconnection
pass
except Exception as e:
# Unknown exception
logger.error("Unknown exception: " + repr(e))
self.errorhappened = True
self.dieWithError()
finally:
logger.debug("END REQUEST")
AceStuff.clientcounter.delete(self.path_unquoted, self.clientip)
if not self.errorhappened and not AceStuff.clientcounter.get(self.path_unquoted):
# If no error happened and we are the only client
logger.debug("Sleeping for " + str(
AceConfig.videodestroydelay) + " seconds")
gevent.sleep(AceConfig.videodestroydelay)
if not AceStuff.clientcounter.get(self.path_unquoted):
logger.debug("That was the last client, destroying AceClient")
if AceConfig.vlcuse:
try:
AceStuff.vlcclient.stopBroadcast(self.vlcid)
except:
pass
self.ace.destroy()
AceStuff.clientcounter.deleteAce(self.path_unquoted)
class HTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
def handle_error(self, request, client_address):
# Do not print HTTP tracebacks
try:
pass
except Exception as e:
print repr(e)
class AceStuff(object):
pass
logging.basicConfig(
filename=AceConfig.logpath + 'acehttp.log' if AceConfig.loggingtoafile else None,
format='%(asctime)s %(levelname)s %(name)s: %(message)s', datefmt='%d.%m.%Y %H:%M:%S', level=AceConfig.debug)
logger = logging.getLogger('INIT')
# Loading plugins
os.chdir(os.path.dirname(os.path.realpath(__file__)))
# Creating dict of handlers
AceStuff.pluginshandlers = dict()
# And a list with plugin instances
AceStuff.pluginlist = list()
pluginsmatch = glob.glob('plugins/*_plugin.py')
sys.path.insert(0, 'plugins')
pluginslist = [os.path.splitext(os.path.basename(x))[0] for x in pluginsmatch]
for i in pluginslist:
plugin = __import__(i)
plugname = i.split('_')[0].capitalize()
try:
plugininstance = getattr(plugin, plugname)(AceConfig, AceStuff)
except Exception as e:
logger.error("Cannot load plugin " + plugname + ": " + repr(e))
continue
logger.debug('Plugin loaded: ' + plugname)
for j in plugininstance.handlers:
AceStuff.pluginshandlers[j] = plugininstance
AceStuff.pluginlist.append(plugininstance)
server = HTTPServer((AceConfig.httphost, AceConfig.httpport), HTTPHandler)
logger = logging.getLogger('HTTP')
# Creating ClientCounter
AceStuff.clientcounter = ClientCounter()
if AceConfig.vlcuse:
# Creating VLC VLM Client
try:
AceStuff.vlcclient = vlcclient.VlcClient(
host=AceConfig.vlchost, port=AceConfig.vlcport, password=AceConfig.vlcpass,
out_port=AceConfig.vlcoutport)
except vlcclient.VlcException as e:
print repr(e)
quit()
try:
logger.info("Server started.")
server.serve_forever()
except KeyboardInterrupt:
logger.info("Stopping server...")
server.shutdown()
server.server_close()
for i in AceStuff.pluginlist:
del i