This repository was archived by the owner on Aug 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
194 lines (175 loc) · 7.73 KB
/
main.py
File metadata and controls
194 lines (175 loc) · 7.73 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
from sanic import Sanic
from sanic.response import html, redirect, text, raw
from sanic.log import logger
import analyzor
import asyncio
import os
import glob
import util
import time
from sanic_jinja2 import SanicJinja2
import config
from collections import OrderedDict
import json
from sanic.websocket import WebSocketProtocol
app = Sanic(name="CTA")
jinja = SanicJinja2(app, pkg_name="main")
lastClearMatches = 0
lastClearEverything = 0
app.static("/assets", "./assets")
async def clearDB():
global lastClearMatches, lastClearEverything
currentTime = time.time()
if currentTime - lastClearEverything > 7200:
logger.info("Clearing cache of league, masterys, matchlists and players...")
files = glob.glob("cache/*/league/*")
files += glob.glob("cache/*/masterys/*")
files += glob.glob("cache/*/matchlists/*")
files += glob.glob("cache/*/players/*")
for f in files:
os.remove(f)
lastClearEverything = currentTime
if currentTime - lastClearMatches > 86400:
logger.info("Clearing cache of matches...")
files = glob.glob("cache/*/matches/*")
for f in files:
os.remove(f)
lastClearMatches = currentTime
@app.route('/')
async def main(request):
asyncio.create_task(util.addPageAnalytic("/"))
asyncio.create_task(clearDB())
if hasValidKey:
return jinja.render("index.html", request, demo=False, host=config.getHostname() + ":" + str(config.getPort()))
else:
return jinja.render("index.html", request, demo=True, host=config.getHostname() + ":" + str(config.getPort()))
@app.route('/team')
async def getTeam(request):
asyncio.create_task(util.addPageAnalytic("/team"))
asyncio.create_task(clearDB())
if "p1" not in request.args or "p2" not in request.args or "p3" not in request.args or "p4" not in request.args or "p5" not in request.args or "region" not in request.args:
return redirect("/")
playerOBJs = util.loadPlayersFromCache(request.args["p1"][0], request.args["p2"][0], request.args["p3"][0], request.args["p4"][0], request.args["p5"][0], request.args["region"][0])
if playerOBJs == -1:
return redirect("/")
else:
mPC = {}
for player in playerOBJs:
tmp = OrderedDict()
sortedChamps = OrderedDict(sorted(player.getMostPlayedChampions().items(), key=lambda item: item[1], reverse=True))
for champ in sortedChamps:
try:
champName = util.getChampionName(champ)
except KeyError:
util.getChampInfo()
try:
champName = util.getChampionName(champ)
except KeyError:
champName = "unknown"
try:
champID = util.getChampionID(champ)
except KeyError:
util.getChampInfo()
try:
champID = util.getChampionID(champ)
except KeyError:
champID = "unknown"
tmp2 = {"champID": champID,
"champ": champName,
"times": sortedChamps[champ]}
tmp[champName] = tmp2
tmp.move_to_end(champName)
mPC[player] = tmp
mC = {}
for player in playerOBJs:
mC[player] = []
for champ in player.getMastery():
try:
champName = util.getChampionName(champ["championId"])
except KeyError:
util.getChampInfo()
try:
champName = util.getChampionName(champ["championId"])
except KeyError:
champName = "unknown"
try:
champID = util.getChampionID(champ["championId"])
except KeyError:
util.getChampInfo()
try:
champID = util.getChampionID(champ["championId"])
except KeyError:
champID = "unknown"
tmp = {"champ": champName,
"champID": champID,
"level": champ["championLevel"],
"points": champ["championPoints"]}
mC[player].append(tmp)
return jinja.render("team.html", request, players=playerOBJs, mostPlayedChamps=mPC, mastery=mC, patch=util.getVersion())
@app.route('/demodata')
async def getDemoData(request):
asyncio.create_task(util.addPageAnalytic("/demodata"))
asyncio.create_task(clearDB())
playerOBJs = util.loadDemoData()
mPC = {}
for player in playerOBJs:
tmp = OrderedDict()
sortedChamps = OrderedDict(sorted(player.getMostPlayedChampions().items(), key=lambda item: item[1], reverse=True))
for champ in sortedChamps:
tmp[util.getChampionName(champ)] = sortedChamps[champ]
tmp.move_to_end(util.getChampionName(champ))
mPC[player] = tmp
mC = {}
for player in playerOBJs:
mC[player] = []
for champ in player.getMastery():
tmp = {"champ": util.getChampionName(champ["championId"]),
"level": champ["championLevel"],
"points": champ["championPoints"]}
mC[player].append(tmp)
return jinja.render("team.html", request, players=playerOBJs, mostPlayedChamps=mPC, mastery=mC, matchesPlayedAsTeam=util.getMatchesPlayedAsFullTeam(playerOBJs), patch=util.getVersion())
@app.route('/favicon.ico')
async def getFavicon(request):
return raw(b"")
@app.route('/statistics')
async def getStatistics(request):
if "date" not in request.args:
dataX = util.getStatistics()
else:
dataX = util.getStatistics(request.args["date"][0])
return jinja.render("statistics.html", request, data=dataX)
@app.websocket("/analyze")
async def analyzeWSRoute(request, ws):
while True:
data = json.loads(await ws.recv())
asyncio.create_task(util.addStatAnalyze())
asyncio.create_task(analyzor.newAnalyzeWrapper(data, ws, logger))
if __name__ == '__main__':
util.createFolderStructure()
hasValidKey = analyzor.hasValidAPIKey()
if hasValidKey:
logger.info("We've got a valid API-Key. Full functionality.")
else:
logger.warning("! We've got no valid API-Key! Limited functionality. !")
if not util.getChampInfo():
logger.error("! We could not get up-to-date champ information from the Data Dragon !")
try:
config.readConfig()
except FileNotFoundError:
logger.error("! No config file was found! Standard development-configuration loaded. !")
config.loadDefaultConfig()
finally:
logger.info("Current configuration:")
logger.info("Key-Type: " + config.getAPIType())
if config.getAPIType() == "production":
logger.info("Ratelimit per 10 seconds: " + str(config.getRateLimitPer10Seconds()))
logger.info("Ratelimit per 10 minutes: " + str(config.getRateLimitPer10Minutes()))
elif config.getAPIType() == "dev":
logger.info("Ratelimit per 1 second: " + str(config.getRateLimitPerSecond()))
logger.info("Ratelimit per 2 minutes: " + str(config.getRateLimitPer2Minutes()))
else:
logger.warning("Couldn't read API-Key-Type! Using development-settings...")
logger.info("Ratelimit per 1 second: " + str(config.getRateLimitPerSecond()))
logger.info("Ratelimit per 2 minutes: " + str(config.getRateLimitPer2Minutes()))
logger.info("Matches to analyze per player: " + str(config.getMatchCountToAnalyze()))
app.run(host=config.getHostname(), port=config.getPort(), protocol=WebSocketProtocol)