-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpartyrockin.py
501 lines (373 loc) · 15.3 KB
/
partyrockin.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
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import bottle
from beaker.middleware import SessionMiddleware
from bottle import route, run, template
from bottle import route, run, template, get, post, request, static_file, error, Bottle, redirect, abort, debug, response
from bottle import debug, Bottle
import simplejson as json
import MySQLdb as mdb
import sys
import hashlib
import copy
import os
import base64
userName = "yourdbname"
password = "yourdbpassword"
database = "partyrockin"
serverName = "localhost"
session_opts = {
'session.type': 'file',
'session.cookie_expires': True,
'session.data_dir': './tmp',
'session.auto': True
}
application = SessionMiddleware(bottle.default_app(), session_opts)
@route('/upload', method='POST')
def do_upload():
responseObj = {}
userid = request.forms.get('userid')
upload = request.files.get('filename')
randDir = base64.urlsafe_b64encode(os.urandom(10))
name, ext = os.path.splitext(upload.filename)
if ext not in ('.png','.jpg','.jpeg'):
return "File extension not allowed."
path_prefix = "/usr/share/nginx/www/"
save_path = "images/{userid}/{directory_path}".format(userid=userid, directory_path=randDir)
#save_path = "images/{userid}/{directory_path}".format(userid=userid, directory_path=randDir)
#save_path = "./images/"
full_path = path_prefix + save_path
if not os.path.exists(full_path):
os.makedirs(full_path)
full_file_path = "{path}/{file}".format(path=full_path, file=upload.filename)
url_file_path = "{path}/{file}".format(path=save_path, file=upload.filename)
#upload.save(file_path)
with open(full_file_path, 'w') as open_file:
open_file.write(upload.file.read())
#associate this file path with the user
try:
con = mdb.connect(serverName, userName, password, database)
cur = con.cursor(mdb.cursors.DictCursor)
updateUser = "update USER set IMG_REF = %s where USER_ID = %s"
cur.execute(updateUser, (url_file_path, userid) )
rows = cur.fetchall()
if cur.rowcount > 0:
responseObj["responseCd"] = 0
responseObj["responseMsg"] = "User img_ref updated. File Save to {0}".format(full_file_path)
else:
responseObj["responseCd"] = 1
responseObj["responseMsg"] = "User Not Found Error!";
except mdb.Error, e:
con.rollback()
responseObj["responseCd"] = -1
errMsg = "error occurred %d %s", (e.args[0], e.args[1] )
responseObj["responseMsg"] = errMsg
finally:
if con:
con.commit()
con.close()
response.headers['Content-Type'] = 'application/json'
return json.dumps(responseObj)
@route('/images/<filepath:path>')
def server_static(filepath):
return static_file(filepath, root='./images')
@route('/')
def root():
return static_file('test.html', root='.')
@route('/uploadimages')
def uploadimages():
return static_file('imageform.html', root='.')
@route('/testclaim')
def testclaim():
return static_file('testclaim.html', root='.')
@route('/testregister')
def testregister():
return static_file('testregister.html', root='.')
@route('/testupdatename')
def testupdatename():
return static_file('testupdatename.html', root='.')
@route('/deleteuser/<userId:int>')
def deleteuser(userId):
responseObj = {}
try:
con = mdb.connect(serverName, userName, password, database)
cur = con.cursor(mdb.cursors.DictCursor)
deleteUser = "delete from USER where USER_ID = %s"
cur.execute(deleteUser, (userId))
rows = cur.fetchall()
print "rows affected %s" % cur.rowcount
if cur.rowcount > 0:
responseObj["responseCd"] = 0
responseObj["responseMsg"] = "User Deleted"
else:
responseObj["responseCd"] = 1
responseObj["responseMsg"] = "User Not Found"
except mdb.Error, e:
con.rollback()
responseObj["responseCd"] = -1
errMsg = "error occurred %d %s", (e.args[0], e.args[1] )
responseObj["responseMsg"] = errMsg
finally:
if con:
con.commit()
con.close()
response.headers['Content-Type'] = 'application/json'
return json.dumps(responseObj)
@route('/users')
def users():
responseObj = {}
dataArray = []
try:
con = mdb.connect(serverName, userName, password, database)
cur = con.cursor(mdb.cursors.DictCursor)
allUsers = "select USER_ID, NAME, IMG_REF, BAR_SCORE, BEACON_1, BEACON_2, BEACON_3, BEACON_4, BEACON_5, BEACON_6, DATE_FORMAT(LAST_BAR_DETECTION, '%m/%d/%y %H:%i:%s') AS LAST_BAR_DETECTION, DATE_FORMAT(LAST_BEACON_CLAIM, '%m/%d/%y %H:%i:%s') AS LAST_BEACON_CLAIM, DEVICE_ID from USER"
cur.execute(allUsers)
rows = cur.fetchall()
dataArray = copy.deepcopy(rows)
responseObj["responseCd"] = 0
responseObj["responseMsg"] = "all rows"
responseObj["allUsers"] = dataArray
except mdb.Error, e:
con.rollback()
responseObj["responseCd"] = -1
errMsg = "error occurred %d %s", (e.args[0], e.args[1] )
responseObj["responseMsg"] = errMsg
finally:
if con:
con.commit()
con.close()
response.headers['Content-Type'] = 'application/json'
return json.dumps(responseObj)
@route('/userreview')
def userreview():
responseObj = {}
try:
con = mdb.connect(serverName, userName, password, database)
cur = con.cursor(mdb.cursors.DictCursor)
allUsers = "select USER_ID, NAME, IMG_REF, BAR_SCORE, (BEACON_1 + BEACON_2 + BEACON_3 + BEACON_4 + BEACON_5 + BEACON_6) as TOTAL_CLAIMS from USER"
cur.execute(allUsers)
rows = cur.fetchall()
dataArray = copy.deepcopy(rows)
except mdb.Error, e:
con.rollback()
responseObj["responseCd"] = -1
errMsg = "error occurred %d %s", (e.args[0], e.args[1] )
responseObj["responseMsg"] = errMsg
finally:
if con:
con.commit()
con.close()
return template('userreview', rows=rows)
@route('/register', method='POST')
def register_user():
responseObj = {}
responseObj = {}
dataObj = {}
# JSON input
device = request.json["device"]
name = request.json["name"]
# regular POST input
#device = request.forms.get('device')
#name = request.forms.get('name')
try:
con = mdb.connect(serverName, userName, password, database)
cur = con.cursor(mdb.cursors.DictCursor)
checkUser = "select USER_ID from USER where device_id = %s"
cur.execute(checkUser, (device) )
row = cur.fetchone()
if row:
responseObj["responseCd"] = 1
responseObj["responseMsg"] = "user already exists"
responseObj["userId"] = (row["USER_ID"])
else:
#create this user
createUser = "insert into USER(NAME, DEVICE_ID) values (%s, %s)"
cur.execute(createUser, (name, device) )
rows = cur.fetchall()
responseObj["responseCd"] = 0
responseObj["responseMsg"] = "user created"
responseObj["userId"] = (con.insert_id())
except mdb.Error, e:
con.rollback()
responseObj["responseCd"] = -1
errMsg = "error occurred %d %s", (e.args[0], e.args[1] )
responseObj["responseMsg"] = errMsg
finally:
if con:
con.commit()
con.close()
response.headers['Content-Type'] = 'application/json'
return json.dumps(responseObj)
@route('/update_name', method='POST')
def update_name():
responseObj = {}
responseObj = {}
dataObj = {}
# JSON input
user_id = request.json["user_id"]
name = request.json["name"]
# regular POST input
#user_id = request.forms.get('user_id')
#name = request.forms.get('name')
try:
con = mdb.connect(serverName, userName, password, database)
cur = con.cursor(mdb.cursors.DictCursor)
updateUser = "update USER set NAME = '" + name + "' where USER_ID =" + user_id
cur.execute(updateUser)
rows = cur.fetchall()
responseObj["responseCd"] = 0
responseObj["responseMsg"] = "name updated"
except mdb.Error, e:
con.rollback()
responseObj["responseCd"] = -1
errMsg = "error occurred %d %s", (e.args[0], e.args[1] )
responseObj["responseMsg"] = errMsg
finally:
if con:
con.commit()
con.close()
response.headers['Content-Type'] = 'application/json'
return json.dumps(responseObj)
@route('/leaderboard/<maxResults:int>')
def leaderboard(maxResults):
responseObj = {}
responseObj = {}
dataObj = {}
try:
con = mdb.connect(serverName, userName, password, database)
cur = con.cursor(mdb.cursors.DictCursor)
leaderboard_1 = "select USER_ID, NAME, IMG_REF, BAR_SCORE from USER where BAR_SCORE > 0 order by BAR_SCORE desc LIMIT " + str(maxResults)
cur.execute(leaderboard_1)
rows1 = cur.fetchall()
dataArray1 = copy.deepcopy(rows1)
responseObj["responseCd"] = 0
responseObj["responseMsg"] = "leaders"
responseObj["scoreLeaders"] = dataArray1
leaderboard_2 = "select USER_ID, NAME, IMG_REF, (BEACON_1 + BEACON_2 + BEACON_3 + BEACON_4 + BEACON_5 + BEACON_6) as TOTAL_CLAIMS, DATE_FORMAT(LAST_BEACON_CLAIM, '%m/%d/%y %H:%i:%s') AS LAST_BEACON_CLAIM, BEACON_1, BEACON_2, BEACON_3, BEACON_4, BEACON_5, BEACON_6 from USER where (BEACON_1 + BEACON_2 + BEACON_3 + BEACON_4 + BEACON_5 + BEACON_6) > 0 order by (BEACON_1 + BEACON_2 + BEACON_3 + BEACON_4 + BEACON_5 + BEACON_6) desc, LAST_BEACON_CLAIM LIMIT " + str(maxResults)
cur.execute(leaderboard_2)
rows2 = cur.fetchall()
dataArray2 = copy.deepcopy(rows2)
responseObj["claimLeaders"] = dataArray2
except mdb.Error, e:
con.rollback()
responseObj["responseCd"] = -1
errMsg = "error occurred %d %s", (e.args[0], e.args[1] )
responseObj["responseMsg"] = errMsg
finally:
if con:
con.commit()
con.close()
response.headers['Content-Type'] = 'application/json'
return json.dumps(responseObj)
@route('/increment_bar_score/<user_id:int>')
def increment_bar_score(user_id):
responseObj = {}
responseObj = {}
dataObj = {}
try:
con = mdb.connect(serverName, userName, password, database)
cur = con.cursor(mdb.cursors.DictCursor)
getCurScore = "select BAR_SCORE from USER where USER_ID = " + str(user_id)
cur.execute(getCurScore)
row = cur.fetchone()
curScore = 0
timestamp_phrase = ''
if row:
curScore = int(row["BAR_SCORE"] + 1)
timestamp_phrase = ', LAST_BAR_DETECTION = CURRENT_TIMESTAMP'
incrementScore = "update USER set BAR_SCORE = " + str(curScore) + timestamp_phrase + " where USER_ID = " + str(user_id)
cur.execute(incrementScore)
rows = cur.fetchall()
responseObj["responseCd"] = 0
responseObj["bar_score"] = curScore
responseObj["responseMsg"] = "incremented"
except mdb.Error, e:
con.rollback()
responseObj["responseCd"] = -1
errMsg = "error occurred %d %s", (e.args[0], e.args[1] )
responseObj["responseMsg"] = errMsg
finally:
if con:
con.commit()
con.close()
response.headers['Content-Type'] = 'application/json'
return json.dumps(responseObj)
@route('/claim', method='POST')
def claim():
responseObj = {}
responseObj = {}
dataObj = {}
# JSON input
beacon_id = request.json["beacon_id"]
user_id = request.json["user_id"]
# regular POST input
#beacon_id = request.forms.get('beacon_id')
#user_id = request.forms.get('user_id')
try:
con = mdb.connect(serverName, userName, password, database)
cur = con.cursor(mdb.cursors.DictCursor)
getCurScore = "select BEACON_" + beacon_id + " as SCORE from USER where USER_ID = " + user_id
cur.execute(getCurScore)
row = cur.fetchone()
curScore = 0
timestamp_phrase = ''
if row:
curScore = int(row["SCORE"])
if curScore == 0:
curScore = 1
timestamp_phrase = ', LAST_BEACON_CLAIM = CURRENT_TIMESTAMP'
incrementScore = "update USER set BEACON_" + beacon_id + " = " + str(curScore) + timestamp_phrase + " where USER_ID = " + user_id
cur.execute(incrementScore)
rows = cur.fetchall()
responseObj["responseCd"] = 0
responseObj["responseMsg"] = "claimed"
except mdb.Error, e:
con.rollback()
responseObj["responseCd"] = -1
errMsg = "error occurred %d %s", (e.args[0], e.args[1] )
responseObj["responseMsg"] = errMsg
finally:
if con:
con.commit()
con.close()
response.headers['Content-Type'] = 'application/json'
return json.dumps(responseObj)
@route('/atbeacon/<maxResults:int>')
def atbeacon(maxResults):
responseObj = {}
responseObj = {}
dataObj = {}
try:
con = mdb.connect(serverName, userName, password, database)
cur = con.cursor(mdb.cursors.DictCursor)
atbeacon = "select USER_ID, NAME, IMG_REF, BAR_SCORE, (BEACON_2 + BEACON_3 + BEACON_4 + BEACON_5 + BEACON_6 + BEACON_7 + BEACON_8) as TOTAL_CLAIMS, DATE_FORMAT(LAST_BAR_DETECTION, '%m/%d/%y %H:%i:%s') AS LAST_BAR_DETECTION from USER where BAR_SCORE > 0 order by LAST_BAR_DETECTION desc LIMIT " + str(maxResults)
cur.execute(atbeacon)
rows = cur.fetchall()
dataArray = copy.deepcopy(rows)
responseObj["responseCd"] = 0
responseObj["responseMsg"] = "at beacon"
responseObj["atBeacon"] = dataArray
except mdb.Error, e:
con.rollback()
responseObj["responseCd"] = -1
errMsg = "error occurred %d %s", (e.args[0], e.args[1] )
responseObj["responseMsg"] = errMsg
finally:
if con:
con.commit()
con.close()
response.headers['Content-Type'] = 'application/json'
return json.dumps(responseObj)
@route('/hello/<name>')
def index(name='World'):
beaker_session = request.environ['beaker.session']
beaker_session['user_id'] = 10
beaker_session.save()
# Check to see if a value is in the session
# Set some other session variable
return template('<b>Hello {{name}}</b>!', name=name)
debug(True)
#if running from python.. 'python partyrockin.py' BLAH
#run(app=mainApp, server='gunicorn', host='0.0.0.0', port=8080, workers=20)
#if running from python, then this, otherwise this will run from the uwsgi container
if __name__ == "__main__":
run(app=application, host='0.0.0.0', port=9080)
#app = bottle.default_app()