-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
518 lines (445 loc) · 20.5 KB
/
main.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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#!/usr/bin/env python3
from flask import Flask, request, redirect, url_for, stream_with_context
from flask import render_template
from markupsafe import escape
from web3 import Web3
import db
import logging
from datetime import timezone, datetime, timedelta
import utils
import payment
app = Flask(__name__)
@app.route("/")
def index():
return render_template('home.html')
@app.route("/summary")
def summary():
return render_template('summary.html')
@app.route("/hero")
@app.route("/heroes")
def heroes():
return render_template('heroes.html')
@app.route("/pet")
@app.route("/pets")
def pets():
return render_template('pets.html')
@app.route("/weapon")
@app.route("/accessory")
@app.route("/equipment")
def equipment():
return render_template('equipment.html')
@app.route("/hero/<heroid>")
def hero_page(heroid=None):
heroIdLong = utils.translateHeroId(escape(heroid))
tabOption = escape(request.args.get('tab', 'events'))
if tabOption not in ['events','levels','sales','summons']:
tabOption = 'events'
if type(heroIdLong) is int or heroIdLong.isnumeric():
return render_template('hero.html', heroIdLong=heroIdLong, heroIdShort=heroid, activeTab=tabOption)
else:
return render_template('hero.html', heroIdLong=23257, heroIdShort=23257, activeTab=tabOption)
@app.route("/pet/<petid>")
def pet_page(petid=None):
petIdLong = utils.translateHeroId(escape(petid))
tabOption = escape(request.args.get('tab', 'events'))
if tabOption not in ['events','sales']:
tabOption = 'events'
if type(petIdLong) is int or petIdLong.isnumeric():
return render_template('pet.html', petIdLong=petIdLong, petIdShort=petid, activeTab=tabOption)
else:
return render_template('pet.html', petIdLong=23257, petIdShort=23257, activeTab=tabOption)
@app.route("/weapon/<weaponid>")
def weapon_page(weaponid=None):
weaponIdLong = utils.translateHeroId(escape(weaponid))
tabOption = escape(request.args.get('tab', 'events'))
if tabOption not in ['events','sales']:
tabOption = 'events'
if type(weaponIdLong) is int or weaponIdLong.isnumeric():
return render_template('weapon.html', equipmentIdLong=weaponIdLong, equipmentIdShort=weaponid, activeTab=tabOption)
else:
return render_template('weapon.html', equipmentIdLong=23257, equipmentIdShort=23257, activeTab=tabOption)
@app.route("/accessory/<accessoryid>")
def accessory_page(accessoryid=None):
accessoryIdLong = utils.translateHeroId(escape(accessoryid))
tabOption = escape(request.args.get('tab', 'events'))
if tabOption not in ['events','sales']:
tabOption = 'events'
if type(accessoryIdLong) is int or accessoryIdLong.isnumeric():
return render_template('accessory.html', equipmentIdLong=accessoryIdLong, equipmentIdShort=accessoryid, activeTab=tabOption)
else:
return render_template('accessory.html', equipmentIdLong=23257, equipmentIdShort=23257, activeTab=tabOption)
@app.route("/armor/<armorid>")
def armor_page(armorid=None):
armorIdLong = utils.translateHeroId(escape(armorid))
tabOption = escape(request.args.get('tab', 'events'))
if tabOption not in ['events','sales']:
tabOption = 'events'
if type(armorIdLong) is int or armorIdLong.isnumeric():
return render_template('armor.html', equipmentIdLong=armorIdLong, equipmentIdShort=armorid, activeTab=tabOption)
else:
return render_template('armor.html', equipmentIdLong=23257, equipmentIdShort=23257, activeTab=tabOption)
@app.route("/summary/<period>", methods=['GET','POST'])
def summary_data(period=None):
return { "results": db.getSummaryData(period) }
@app.route("/csv/<period>", methods=['GET', 'POST'])
def csv(period=None):
def getEventDataCSV(period):
result = ''
todayDate = datetime.now(tzinfo=timezone.utc)
todayDate = todayDate - timedelta(hours=2)
minDate = datetime(todayDate.year, todayDate.month, todayDate.day, tzinfo=timezone.utc) - timedelta(days=1)
maxDate = minDate
if period == 'ytd':
minDate = datetime(todayDate.year, 1, 1, tzinfo=timezone.utc)
maxDate = todayDate - timedelta(days=1)
elif period == '30d':
minDate = todayDate - timedelta(days=31)
maxDate = todayDate - timedelta(days=1)
elif period == '90d':
minDate = todayDate - timedelta(days=91)
maxDate = todayDate - timedelta(days=1)
elif period == 'all':
minDate = datetime(2021, 8, 1, tzinfo=timezone.utc)
maxDate = todayDate
else:
try:
minDate = datetime.strptime(period, '%y-%M-%d')
maxDate = minDate
except Exception as e:
# default
result = 'defaulted {0}'.format(e)
try:
con = db.aConn()
cur = con.cursor()
except Exception as err:
logging.error('DB error trying to look up event data. {0}'.format(str(err)))
if con != None and not con.closed:
cur.execute("SELECT network,TO_CHAR(blockDate, 'YYYY-MM-DD'),heroSalesCount,heroSalesTotal,petSalesCount,petSalesTotal,weaponSalesCount,weaponSalesTotal,accessorySalesCount,accessorySalesTotal,armorSalesCount,armorSalesTotal,heroHireCount,heroHireTotal,tokenPrice,favorHatches,graceHatches,boonHatches,meditationCount,meditationLevels,summonCount,darkSummonCount,accessoryCreated,armorCreated,weaponCreated FROM summary WHERE blockDate BETWEEN %s AND %s", (minDate, maxDate))
resultHeader = ['network','blockDate','heroSalesCount','heroSalesTotal','petSalesCount','petSalesTotal','weaponSalesCount','weaponSalesTotal','accessorySalesCount','accessorySalesTotal','armorSalesCount','armorSalesTotal','heroHireCount','heroHireTotal','tokenPrice','favorHatches','graceHatches','boonHatches','meditationCount','meditationLevels','summonCount','darkSummonCount','accessoryCreated','armorCreated','weaponCreated']
yield f"{','.join(resultHeader)}\n"
rows = cur.fetchmany(10)
while len(rows) > 0:
for cLine in rows:
yield f"{','.join(str(x) for x in cLine)}\n"
rows = cur.fetchmany(10)
con.close()
else:
logging.info('Skipping data lookup due to db conn failure.')
rHeaders = { 'Content-disposition' : 'attachment; filename="dfkhistory.csv"', 'mimetype' : 'text/csv', 'Content-Type' : 'text/csv' }
return stream_with_context(getEventDataCSV(period)), rHeaders
@app.route("/hero/<heroid>/history/<hevent>", methods=['GET','POST'])
def hero_history(heroid=None, hevent=None):
heroid = utils.translateHeroId(escape(heroid))
if type(heroid) is not int and not heroid.isnumeric():
app.logger.warn('Invalid hero id for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid hero id" }
hevent = escape(hevent)
orderOption = escape(request.args.get('order', ''))
if hevent == 'levelup':
return { "results": db.getLevelUps(heroid, orderOption) }
elif hevent == 'life':
return { "results": db.getLifeEvents(heroid, orderOption) }
elif hevent == 'sales':
return { "results": db.getSales(heroid, orderOption) }
elif hevent == 'summons':
return { "results": db.getSummons(heroid, orderOption) }
elif hevent == 'rentals':
return { "results": db.getRentals(heroid, orderOption) }
elif hevent == 'equips':
return { "results": db.getEquips(heroid, orderOption) }
else:
app.logger.warn('Invalid event type for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid event type" }
@app.route("/pet/<petid>/history/<hevent>", methods=['GET','POST'])
def pet_history(petid=None, hevent=None):
petid = utils.translateHeroId(escape(petid))
if type(petid) is not int and not petid.isnumeric():
app.logger.warn('Invalid pet id for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid pet id" }
hevent = escape(hevent)
orderOption = escape(request.args.get('order', ''))
if hevent == 'life':
return { "results": db.getPetLifeEvents(petid, orderOption) }
elif hevent == 'sales':
return { "results": db.getPetSales(petid, orderOption) }
else:
app.logger.warn('Invalid event type for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid event type" }
@app.route("/weapon/<weaponid>/history/<hevent>", methods=['GET','POST'])
def weapon_history(weaponid=None, hevent=None):
weaponid = utils.translateHeroId(escape(weaponid))
if type(weaponid) is not int and not weaponid.isnumeric():
app.logger.warn('Invalid weapon id for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid weapon id" }
hevent = escape(hevent)
orderOption = escape(request.args.get('order', ''))
if hevent == 'life':
return { "results": db.getEquipmentLifeEvents(weaponid, 'weapon', orderOption) }
elif hevent == 'sales':
return { "results": db.getEquipmentSales(weaponid, 'weapon', orderOption) }
else:
app.logger.warn('Invalid event type for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid event type" }
@app.route("/accessory/<accessoryid>/history/<hevent>", methods=['GET','POST'])
def accessory_history(accessoryid=None, hevent=None):
accessoryid = utils.translateHeroId(escape(accessoryid))
if type(accessoryid) is not int and not accessoryid.isnumeric():
app.logger.warn('Invalid accessory id for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid accessory id" }
hevent = escape(hevent)
orderOption = escape(request.args.get('order', ''))
if hevent == 'life':
return { "results": db.getEquipmentLifeEvents(accessoryid, 'accessory', orderOption) }
elif hevent == 'sales':
return { "results": db.getEquipmentSales(accessoryid, 'accessory', orderOption) }
else:
app.logger.warn('Invalid event type for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid event type" }
@app.route("/armor/<armorid>/history/<hevent>", methods=['GET','POST'])
def armor_history(armorid=None, hevent=None):
armorid = utils.translateHeroId(escape(armorid))
if type(armorid) is not int and not armorid.isnumeric():
app.logger.warn('Invalid armor id for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid armor id" }
hevent = escape(hevent)
orderOption = escape(request.args.get('order', ''))
if hevent == 'life':
return { "results": db.getEquipmentLifeEvents(armorid, 'armor', orderOption) }
elif hevent == 'sales':
return { "results": db.getEquipmentSales(armorid, 'armor', orderOption) }
else:
app.logger.warn('Invalid event type for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid event type" }
@app.route("/about")
def about():
return render_template('about.html')
@app.route("/memberstats")
def memberstats():
memberStats = db.getMemberStats()
return { "memberCount" : memberStats[0], "latestExpiration" : memberStats[1] }
@app.route("/auth")
def auth():
account = request.args.get("account", "")
signature = request.args.get("signature", "")
# escape input to prevent sql injection
account = db.dbInsertSafe(account)
signature = db.dbInsertSafe(signature)
print('Content-type: text/json\n')
if not Web3.is_address(account):
sessionResult = 'Error: That is not a valid address. Make sure you enter the version that starts with 0x'
else:
# Ensure consistent checksum version of address
account = Web3.to_checksum_address(account)
sessionResult = db.getSession(account, signature)
return { "sid" : sessionResult }
@app.route("/login")
def login():
account = request.args.get("account", "")
sid = request.args.get('sid', '')
# escape input to prevent sql injection
account = db.dbInsertSafe(account)
sid = db.dbInsertSafe(sid)
# Get a session
print('Content-type: text/json\n')
if not Web3.is_address(account):
nonceResult = 'Error: That is not a valid address. Make sure you enter the version that starts with 0x'
return { "error" : str(nonceResult) }
else:
# Ensure consistent checksum version of address
account = Web3.to_checksum_address(account)
if sid != '':
sess = db.checkSession(sid)
if sess == account:
return { "sid" : sid }
else:
nonceResult = db.getAccountNonce(account)
return { "nonce" : str(nonceResult) }
else:
nonceResult = db.getAccountNonce(account)
return { "nonce" : str(nonceResult) }
@app.route("/logout")
def logout():
account = request.args.get("account", "")
sid = request.args.get('sid', '')
# escape input to prevent sql injection
account = db.dbInsertSafe(account)
sid = db.dbInsertSafe(sid)
loginState = 0
sess = db.checkSession(sid)
if (sess != ''):
loginState = 1
currentUser = sess
print('Content-type: text/json\n')
if not Web3.is_address(account):
logoutResult = 'Error: That is not a valid address. Make sure you enter the version that starts with 0x'
else:
# Ensure consistent checksum version of address
account = Web3.to_checksum_address(account)
if loginState > 0:
conn = db.aConn()
cursor = conn.cursor()
updatestr = 'DELETE FROM sessions WHERE account=%s AND sid=%s'
cursor.execute(updatestr, (account, sid))
cursor.close()
conn.close()
logoutResult = 'logout complete'
else:
logoutResult = 'Error: session was not valid'
return { "result" : str(logoutResult) }
@app.route("/player")
def member_connect():
secondsLeft = -1
loginState = readAccount(request.args, request.cookies)
# get subscription status
if loginState[0] > 0:
memberStatus = db.getMemberStatus(loginState[1])
memberState = memberStatus[0]
secondsLeft = memberStatus[1]
walletList = memberStatus[3]
else:
memberState = 0
walletList = []
return render_template('connect.html', memberState=memberState, memberAccount=loginState[1], secondsLeft=secondsLeft, expiryDescription=utils.timeDescription(secondsLeft), playerWallets=walletList)
@app.route("/player/<playerid>")
def player_page(playerid=None):
secondsLeft = -1
loginState = readAccount(request.args, request.cookies)
# get subscription status
if loginState[0] > 0:
memberStatus = db.getMemberStatus(loginState[1])
memberState = memberStatus[0]
secondsLeft = memberStatus[1]
else:
memberState = 0
tabOption = escape(request.args.get('tab', 'events'))
if tabOption not in ['events','levels','sales','summons','hatches']:
tabOption = 'events'
if Web3.is_address(playerid):
playerid = Web3.to_checksum_address(escape(playerid))
return render_template('player.html', playerId=playerid, activeTab=tabOption, memberState=memberState, memberAccount=loginState[1], secondsLeft=secondsLeft)
else:
return render_template('player.html', playerId='0x', activeTab=tabOption, memberState=memberState, memberAccount=loginState[1], secondsLeft=secondsLeft)
@app.route("/playerfeed/<playerid>")
def player_feed(playerid=None):
secondsLeft = -1
loginState = readAccount(request.args, request.cookies)
# get subscription status
if loginState[0] > 0:
memberStatus = db.getMemberStatus(loginState[1])
memberState = memberStatus[0]
secondsLeft = memberStatus[1]
else:
memberState = 0
if Web3.is_address(playerid):
playerid = Web3.to_checksum_address(escape(playerid))
return render_template('feed.html', playerId=playerid, memberState=memberState, memberAccount=loginState[1], secondsLeft=secondsLeft)
else:
return render_template('feed.html', playerId='0x', memberState=memberState, memberAccount=loginState[1], secondsLeft=secondsLeft)
@app.route("/player/<playerid>/history/<hevent>", methods=['GET','POST'])
def player_history(playerid=None, hevent=None):
if not Web3.is_address(playerid):
app.logger.warn('Invalid player id for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid player id" }
else:
playerid = Web3.to_checksum_address(escape(playerid))
loginState = readAccount(request.args, request.cookies)
# get subscription status
if loginState[0] > 0:
memberStatus = db.getMemberStatus(loginState[1])
memberState = memberStatus[0]
else:
memberState = 0
if loginState[1] != playerid:
return { "result": [], "error": "Wallet does not match account address."}
if memberState < 2:
return { "results": [], "error": "Active subscription required."}
hevent = escape(hevent)
orderOption = escape(request.args.get('order', 'desc'))
limitOption = request.args.get('limit', '0')
if not limitOption.isnumeric():
limitOption = 0
else:
limitOption = int(limitOption)
if hevent == 'levelup':
return { "results": db.getPlayerLevelUps(playerid, orderOption, limitOption) }
elif hevent == 'life':
return { "results": db.getPlayerLifeEvents(playerid, orderOption, limitOption) }
elif hevent == 'sales':
return { "results": db.getPlayerSales(playerid, orderOption, limitOption) }
elif hevent == 'purchases':
return { "results": db.getPlayerPurchases(playerid, orderOption, limitOption) }
elif hevent == 'summons':
return { "results": db.getPlayerSummons(playerid, orderOption, limitOption) }
elif hevent == 'hatches':
return { "results": db.getPlayerHatches(playerid, orderOption, limitOption) }
else:
app.logger.warn('Invalid event type for history call: {0}'.format(hevent))
return { "results": [], "error": "Invalid event type" }
@app.route("/addWallet", methods=['POST'])
def add_wallet():
loginState = readAccount(request.args, request.cookies)
wallet = request.args.get('wallet','')
# attempt add if logged in
if loginState[0] > 0:
if Web3.is_address(wallet):
wallet = Web3.to_checksum_address(escape(wallet))
ud = db.addWallet(loginState[1], wallet)
if ud > 0:
result = { "result": ud }
elif ud == -1:
result = { "result": ud, "error": "Too many wallets added"}
else:
result = { "result": ud, "error": "Wallet is already in list"}
else:
result = { "result": 0, "error": "Invalid address" }
else:
result = { "result": 0, "error": "Must be logged in" }
return result
@app.route("/removeWallet", methods=['POST'])
def remove_wallet():
loginState = readAccount(request.args, request.cookies)
wallet = request.args.get('wallet','')
# attempt removal if logged in
if loginState[0] > 0:
if Web3.is_address(wallet):
wallet = Web3.to_checksum_address(escape(wallet))
ud = db.removeWallet(loginState[1], wallet)
if ud > 0:
result = { "result": ud }
else:
result = { "result": ud, "error": "Unknown failure" }
else:
result = { "result": 0, "error": "Invalid address" }
else:
result = { "result": 0, "error": "Must be logged in" }
return result
@app.route("/validatePayment", methods=['POST'])
def validate_payment():
result = payment.validatePayment(request.args.get('network', ''), request.args.get('account', ''), request.args.get('txHash', ''))
return result
@app.errorhandler(404)
def page_not_found(error):
return render_template('missing.html'), 404
def readAccount(reqArgs, C):
useCookies = True
account = ''
if useCookies:
try:
account = C['selectedAccount']
except KeyError:
account = reqArgs.get('account', '')
try:
sid = C['sid-{0}'.format(account)]
except KeyError:
sid = reqArgs.get('sid', '')
else:
sid = reqArgs.get('sid', '')
account = reqArgs.get('account', '')
sid = db.dbInsertSafe(sid)
loginState = 0
if sid != '' and Web3.is_address(account):
account = Web3.to_checksum_address(account)
sess = db.checkSession(sid)
if sess == account:
loginState = 1
return [loginState, account]