-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
224 lines (161 loc) · 5.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
from flask import Flask, request, send_file, send_from_directory, render_template
from waitress import serve
import AOC
from config import get_config
import threading
import time
from clientmanager import ClientManager
from functools import wraps
from log import log
import log as Logger
from flask_limiter import Limiter
dev = get_config()["dev"]
# Stateful info
class State():
totalLeaderboardData = None
todayLeaderboardData = None
lastUpdatedLeaderboardData = None
doEarlyRefresh = False
manager = ClientManager(120)
Logger.start_logging()
log("Starting server...")
def getWaitTime():
if dev:
return 20
day = AOC.get_event_start_time().day
current_month = time.localtime().tm_mon
if current_month != 12:
return 2 * 60
# Change the amount of time between refresh over time
if day == 1:
return 20 * 60
elif day < 5:
return 15 * 60
elif day < 10:
return 8 * 60
else:
return 4 * 60
# Periodic update
def periodic_update_data():
leaderboardID = get_config()["leaderboardID"]
year = get_config()["year"]
sessionCode = get_config()["sessionCode"]
while True:
refreshTime = getWaitTime()
while True:
error, total_leaderboard = AOC.get_total_leaderboard(leaderboardID, year, sessionCode)
if not error:
break
log(f"ERROR: {str(total_leaderboard)}")
time.sleep(20)
while True:
error, todays_leaderboard = AOC.get_todays_leaderboard(leaderboardID, year, sessionCode)
print(todays_leaderboard)
if not error:
break
log(f"ERROR: {str(todays_leaderboard)}")
time.sleep(20)
State.totalLeaderboardData = total_leaderboard
State.todayLeaderboardData = todays_leaderboard
State.lastUpdatedLeaderboardData = time.time()
while True:
time.sleep(0.2)
if State.doEarlyRefresh:
log("Breaking due to early refresh!")
State.doEarlyRefresh = False
break
# Do it one second earlier than you tell the clients you will
if time.time() - refreshTime + 1 > State.lastUpdatedLeaderboardData:
break
threading.Thread(target=periodic_update_data).start()
while State.lastUpdatedLeaderboardData is None:
print("Waiting for data to be loaded...")
time.sleep(1)
app = Flask(__name__)
def get_remote_address():
if request.headers.get("CF-Connecting-IP"):
return request.headers.get("CF-Connecting-IP")
return request.remote_addr
limiter = Limiter(
get_remote_address,
app=app,
default_limits=["200000 per day", "50000 per hour"],
storage_uri="memory://",
)
@app.route("/")
def index():
return render_template("leaderboard.html", leaderboardCode=get_config()["leaderboardCode"])
@app.route("/assets/<path:path>")
def serve_assets(path):
return send_from_directory("assets/", path)
@app.route("/api/data")
def leaderboard():
event_start = AOC.get_event_start_time()
if event_start != "INVALID":
event_start = str(event_start.day).rjust(2, "0")
decoded = manager.decode_data(request.args.get("uid"))
print(str(decoded) + " - decoded data from client")
manager.registerClientConnect(decoded["id"], request.headers.get("CF-Connecting-IP"), decoded)
evaluations = manager.getClientEvaluations(decoded["id"])
manager.clearClientEvaluations(decoded["id"])
return {
"total": State.totalLeaderboardData,
"today": State.todayLeaderboardData,
"lastUpdated": State.lastUpdatedLeaderboardData,
"refreshTime": getWaitTime(),
"day": event_start,
"evaluate": evaluations,
"reload": True, # make old clients reload,
}
def is_admin(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if request.cookies.get("auth") != get_config()["adminKey"]:
return render_template("login.html"), 401
return f(*args, **kwargs)
return decorated_function
@app.route("/admin")
@is_admin
def admin():
return render_template("admin.html")
@app.route("/api/admin/admindata")
@is_admin
def clients():
clientData = manager.getClients()
return {"clients": clientData, "lastLogChange": Logger.Buffer.lastChangedTime,
"lastClientChange": manager.lastChangeTime}
@app.route("/api/admin/logs/from/<int:fromLine>")
@is_admin
def pull_logs(fromLine):
with open(get_config()["logfile"], "r") as f:
lines = f.readlines()
inBuffer = Logger.Buffer.data
totalLogs = lines + inBuffer
return {"logs": totalLogs[fromLine:]}
@app.route("/api/admin/evaluate", methods=["POST"])
@is_admin
def evaluate():
data = request.get_json()
manager.addClientEvaluation(data.get("uid"), data.get("code"))
return "OK"
@app.route("/api/admin/refresh", methods=["POST"])
@is_admin
def refresh():
State.doEarlyRefresh = True
return "OK: Refresh Early"
@app.route("/login", methods=["POST"])
@limiter.limit("200 per day")
@limiter.limit("1 per second")
def login():
jdata = request.get_json()
if jdata.get("password") == get_config()["adminKey"]:
resp = app.make_response({"success": True})
resp.set_cookie("auth", get_config()["adminKey"])
return resp
return {"success": False}, 401
if get_config()["dev"]:
log("Running in dev mode")
app.run(host="127.0.0.1", port=8095)
else:
log("Serving on 0.0.0.0:8095")
serve(app, host="0.0.0.0", port=8095)