-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·291 lines (228 loc) · 9.21 KB
/
server.py
File metadata and controls
executable file
·291 lines (228 loc) · 9.21 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
#!/usr/bin/env python3
import json
import random
import threading
import time
import os
import math
import cherrypy
import shapely.geometry
import psycopg2
from psycopg2.extras import execute_batch
def random_point_in_polygon(polygon, force_minx=None, force_maxx=None, force_miny=None, force_maxy=None):
result = None
minx, miny, maxx, maxy = polygon.bounds
if force_minx is not None and force_minx > minx:
minx = force_minx
if force_maxx is not None and force_maxx < maxx:
maxx = force_maxx
if force_miny is not None and force_miny > miny:
miny = force_miny
if force_maxy is not None and force_maxy < maxy:
maxy = force_maxy
while result is None:
pnt = shapely.geometry.Point(random.uniform(minx, maxx), random.uniform(miny, maxy))
if polygon.contains(pnt):
result = list(pnt.coords[0])
return result
def randomString(stringLength):
letters = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
return ''.join(random.choice(letters) for i in range(stringLength))
def long2tileFrac(lon,zoom):
return (lon+180.0)/360.0 * (2.0 ** zoom)
def lat2tileFrac(lat,zoom):
return (
1.0-math.log(math.tan(lat*math.pi/180.0) + 1.0/math.cos(lat*math.pi/180.0))/math.pi
)/2.0 * (2.0 ** zoom)
valid_answers = [0, 1]
city_poly = None
preferred_maxx = 34.7654 # 34.7807
preferred_maxy = 32.0582 # 32.0646
SESSION_LENGTH_SEC = 6 * 60 * 60 # 6 hours?
class IDb:
def store_new_answers(self, points, answers):
pass
def get_all_answers(self):
pass
def new_session(self, points):
pass
def get_and_delete_session(self, session_id):
pass
def clean_stale_sessions(self):
pass
def renew_session(self, session_id):
pass
class DbPostgres(IDb):
def __init__(self, db_url):
self.db_url = db_url
def store_new_answers(self, points, answers):
if len(points) != len(answers):
raise ValueError("invalid number of answers")
t = time.time()
with psycopg2.connect(self.db_url, sslmode='prefer') as conn:
with conn.cursor() as cursor:
execute_batch(
cursor,
"INSERT INTO Answer (point_json, answer_val, answer_time) VALUES (%s, %s, %s);",
[(json.dumps(point), answer, t) for point, answer in zip(points, answers)]
)
def get_all_answers(self):
with psycopg2.connect(self.db_url, sslmode='prefer') as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT point_json, answer_val FROM Answer ORDER BY answer_time ASC;")
return [
json.loads(point_json) + [float(answer_val)]
for point_json, answer_val in cursor.fetchall()
]
def new_session(self, points):
with psycopg2.connect(self.db_url, sslmode='prefer') as conn:
with conn.cursor() as cursor:
# generate a unique random session id lol
session_id = None
while session_id is None or cursor.fetchone()[0] != 0:
session_id = randomString(64)
cursor.execute(
"SELECT COUNT(*) FROM WebSession WHERE session_id = %s;",
(session_id,)
)
ttl = time.time() + SESSION_LENGTH_SEC
cursor.execute(
"INSERT INTO WebSession (session_id, ttl, points_json) VALUES (%s, %s, %s);",
(session_id, ttl, json.dumps(points))
)
return {
"session_id": session_id,
"ttl": ttl,
"points": points
}
def get_and_delete_session(self, session_id):
with psycopg2.connect(self.db_url, sslmode='prefer') as conn:
row = None
with conn.cursor() as cursor:
cursor.execute(
"SELECT session_id, ttl, points_json FROM WebSession WHERE session_id = %s;",
(session_id,)
)
row = cursor.fetchone()
if row is not None:
with conn.cursor() as cursor:
cursor.execute("DELETE FROM WebSession WHERE session_id = %s;", (session_id,))
else:
raise KeyError("session not found")
if row[1] < time.time():
raise ValueError("session expired")
return json.loads(row[2])
def clean_stale_sessions(self):
with psycopg2.connect(self.db_url, sslmode='prefer') as conn:
with conn.cursor() as cursor:
cursor.execute(
"DELETE FROM WebSession WHERE ttl < %s;",
(time.time(),)
)
def renew_session(self, session_id):
# q: is this a glaring security hole or a useful ui usability feature?
# a: why not both?
with psycopg2.connect(self.db_url, sslmode='prefer') as conn:
row = None
with conn.cursor() as cursor:
cursor.execute(
"SELECT session_id, ttl, points_json FROM WebSession WHERE session_id = %s;",
(session_id,)
)
row = cursor.fetchone()
if row is None:
raise KeyError("session not found")
new_ttl = time.time() + SESSION_LENGTH_SEC
with conn.cursor() as cursor:
cursor.execute(
"UPDATE WebSession SET ttl=%s WHERE session_id=%s;",
(new_ttl,session_id)
)
return new_ttl
if row[1] < time.time():
raise ValueError("session expired")
class TlvOrJServer:
def __init__(self):
self.db = DbPostgres(os.environ['DATABASE_URL'])
self.cleanup_thread = threading.Thread(target=self.cleanup_loop)
self.cleanup_thread.daemon = True
self.cleanup_thread.start()
def cleanup_loop(self):
while True:
time.sleep(5*60)
self.db.clean_stale_sessions()
@cherrypy.expose
def index(self, **params):
return open('index.html')
@cherrypy.expose
@cherrypy.tools.json_out()
def answer_session(self, session_id, answers, get_all_answers=False):
points = self.db.get_and_delete_session(session_id)
answers = list(map(int, str(answers).split(',')))
all_answers = None
if get_all_answers:
all_answers = self.db.get_all_answers()
if len(answers) != len(points):
raise ValueError('wrong number of answers')
for a in answers:
if a not in valid_answers:
raise ValueError('invalid answer')
self.db.store_new_answers(points, answers)
if all_answers is not None:
return all_answers
@cherrypy.expose
@cherrypy.tools.json_out()
def generate_session(self):
points = [
random_point_in_polygon(
city_poly,
force_miny=preferred_maxy + random.uniform(-0.02, 0)
)
for i in range(2)
] + [
random_point_in_polygon(
city_poly,
force_maxx=preferred_maxx + random.uniform(0, 0.01),
force_maxy=preferred_maxy + random.uniform(0, 0.005)
)
for i in range(3)
]
# sort either north to south or south to north
# sort_direction = random.choice([False, True])
# points.sort(key=lambda p: p[1], reverse=sort_direction)
random.shuffle(points)
return self.db.new_session(points)
@cherrypy.expose
@cherrypy.tools.json_out()
def renew_session(self, session_id):
return {
"ttl": self.db.renew_session(session_id)
}
config = {
'global': {
'server.socket_host': '0.0.0.0',
'server.socket_port': int(os.environ.get('PORT', 5000)),
},
'/assets': {
'tools.staticdir.root': os.path.dirname(os.path.abspath(__file__)),
'tools.staticdir.on': True,
'tools.staticdir.dir': 'assets',
},
'/favicon.ico': {
'tools.staticfile.root': os.path.dirname(os.path.abspath(__file__)),
'tools.staticfile.on': True,
'tools.staticfile.filename': 'assets/icons/favicon.ico'
},
'/privacy.html': {
'tools.staticfile.root': os.path.dirname(os.path.abspath(__file__)),
'tools.staticfile.on': True,
'tools.staticfile.filename': 'privacy.html'
}
}
def main():
global city_poly
with open('citylimits.geojson.json', 'r', encoding='utf-8-sig') as f:
city_poly = shapely.geometry.shape(json.load(f)['features'][0]['geometry'])
cherrypy.quickstart(TlvOrJServer(), config=config)
if __name__ == "__main__":
main()