-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathrequests_.py
217 lines (181 loc) · 6.63 KB
/
requests_.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
import logging
import config
import time
import json
import threading
from flup.server.fcgi import WSGIServer
import MySQLdb
import manager
import bot
from multiprocessing.managers import BaseManager
import bootstrap
import hashlib
import hmac
debug = True
def songdelay(val):
"""Gives the time delay in seconds for a specific song
request count.
"""
import math
if val > 30:
val = 30
# return int(29145 * math.exp(0.0476 * val) + 0.5)
# return int(0.1791*val**4 - 17.184*val**3 + 557.07*val**2 - 3238.9*val + 30687 + 0.5)
# return int(25133*math.exp(0.1625*val)+0.5)
# return int(-123.82*val**3 + 3355.2*val**2 + 10110*val + 51584 + 0.5)
if 0 <= val <= 7:
cd = -11057 * val ** 2 + 172954 * val + 81720
else:
cd = int(599955 * math.exp(0.0372 * val) + 0.5)
return cd / 2
def check_hmac(value, hash):
key = config.request_key
signature = hmac.new(key, value, hashlib.sha256).hexdigest()
return hash == signature
def extract_ip_address(environ):
"""
Extracts the correct address to use from an wsgi environ.
"""
if "HTTP_X_RADIO_CLIENT" in environ:
if check_hmac(environ["HTTP_X_RADIO_CLIENT"], environ["HTTP_X_RADIO_AUTH"]):
ip = environ["HTTP_X_RADIO_CLIENT"]
else:
ip = environ["REMOTE_ADDR"]
else:
ip = environ["REMOTE_ADDR"]
return ip
def method_lock(f):
def wrapped_lock(self, environ, start_response):
with self.lock:
return f(self, environ, start_response)
return wrapped_lock
class FastCGIServer(object):
"""Starts a fastcgi server that handles our requests,
runs in a separate process, supply a problem_handler
and it will be called when the process shuts down.
DO NOTE that the handler is called in the separate process"""
__metaclass__ = bootstrap.Singleton
def __init__(self, problem_handler=lambda: None, queue=None):
# Thread.__init__(self)
object.__init__(self)
bootstrap.logging_setup()
self.handler = problem_handler
# Setup manager classes we need
self.queue = manager.Queue()
self.status = manager.Status()
print self.external_request
self.lock = threading.Lock()
print self.lock
self.server = WSGIServer(self.external_request,
bindAddress=config.fastcgi_socket,
umask=0, multithreaded=False)
# self.name = "Request FastCGI Server"
# self.daemon = 1
# self.start()
def run(self):
"""Internal"""
logging.info("Started FastCGI")
try:
self.server.run()
finally:
self.handler()
logging.info("Stopped FastCGI")
def shutdown(self):
self.server._exit()
def handle_request(self, trackid, ip):
canrequest_ip = False
canrequest_song = False
with manager.MySQLCursor(cursortype=MySQLdb.cursors.Cursor) as cur:
# SQL magic
query = ("SELECT UNIX_TIMESTAMP(time) AS time FROM requesttime WHERE ip="
"%s LIMIT 1;")
cur.execute(query, (ip,))
for iptime, in cur:
has_requesttime_entry = True
break
else:
has_requesttime_entry = False
iptime = 0
if debug:
print "Extracted iptime of: ", iptime
now = int(time.time())
if now - iptime > 1800:
canrequest_ip = True
if debug:
print "IP requestable: ", canrequest_ip
cur.execute("SELECT usable, UNIX_TIMESTAMP(lastrequested) as lr, "
"requestcount, UNIX_TIMESTAMP(lastplayed) as lp "
"FROM `tracks` WHERE `id`=%s LIMIT 1;", (trackid,))
for usable, lrtime, rc, lptime in cur:
canrequest_song = ((now - lrtime) > songdelay(rc) and
(now - lptime) > songdelay(rc))
if debug:
print "Song requestable: ", canrequest_song
if not canrequest_ip:
return "You need to wait longer before requesting again."
elif not canrequest_song:
return "You need to wait longer before requesting this song."
elif not usable:
return "This song can't be requested yet."
# SQL magic
if has_requesttime_entry:
cur.execute(
"UPDATE requesttime SET time=NOW() WHERE ip=%s;",
(ip,),
)
else:
cur.execute(
"INSERT INTO requesttime (ip) VALUES (%s);",
(ip,),
)
n = cur.execute(
"UPDATE tracks SET lastrequested=NOW(), requestcount=requestcount+2,priority=priority+1 WHERE id=%s;",
(trackid,),
)
print "finishing up request of: ", trackid
song = manager.Song(trackid)
try:
self.queue.append_request(song)
except:
logging.exception("QUEUE PROBLEMS BLAME VIN")
# Website search index update
song.update_index()
# Silly IRC announce
bot.request_announce(song.id)
return "Thank you for making your request!"
@method_lock
def external_request(self, environ, start_response):
print self.lock
if (self.status.requests_enabled):
def is_int(num):
try:
int(num)
return True
except:
return False
try:
postdata = environ['wsgi.input']\
.read(int(environ['CONTENT_LENGTH']))
except:
postdata = ""
splitdata = postdata.split('=')
sitetext = ""
if len(splitdata) == 2 and splitdata[0] == 'songid' \
and is_int(splitdata[1]):
trackid = int(splitdata[1])
if debug:
print "Extracting environ info"
ip = extract_ip_address(environ)
if debug:
print "Extracted IP: ", ip
sitetext = self.handle_request(trackid, ip)
else:
sitetext = "Invalid parameter."
else:
sitetext = "You can't request songs at the moment."
print sitetext
start_response('200 OK', [('Content-Type', 'application/json')])
return json.dumps(dict(response=sitetext))
if __name__ == "__main__":
server = FastCGIServer()
server.run()