-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
258 lines (198 loc) · 8 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
import os
from random import randint
import uuid
import time
from flask import Flask, request, render_template, redirect, make_response
from werkzeug import secure_filename
from data_manager import DataManager
from model.puzzle_manager import PuzzleManager
from model.puzzle import Puzzle, PuzzleState
from model.problem import Problem
from model.problem_attempt import ProblemAttempt
########## Initialization ###########
app = Flask(__name__, static_url_path="/content", static_folder = "content")
datamgr = DataManager()
datamgr.load()
puzzmgr = PuzzleManager(datamgr)
puzzmgr.load()
ADMIN_PASSWORD = 'puzzles'
# Setup web app configurations
app.config['SOLUTION_FOLDER'] = 'solutions/'
if not os.path.exists(app.config['SOLUTION_FOLDER']):
os.makedirs(app.config['SOLUTION_FOLDER'])
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 # 10KB
########## Routes ###########
@app.route('/', methods=['GET', 'POST'])
def home():
try:
if request.method == 'GET':
teamname = request.cookies.get('teamname')
if not teamname: # not set
return render_template('team_login.html')
return render_template('home.html', puzzles=puzzmgr.puzzles,
global_point_totals=puzzmgr.get_global_point_totals(),
teamname=teamname)
else:
# Post
# Get the teamname from the form post
teamname = request.form['teamname']
if not teamname: # not set
return render_template('team_login.html')
resp = make_response(render_template('home.html', puzzles=puzzmgr.puzzles,
global_point_totals=puzzmgr.get_global_point_totals(),
teamname=teamname))
resp.set_cookie('teamname', teamname)
return resp
except Exception as ex:
return render_template('error.html', error=str(ex)), 500
@app.route('/changeteamname')
def change_teamname():
resp = make_response(redirect('/'))
resp.set_cookie('teamname', '')
return resp
@app.route('/puzzle/<puzzle_id>', methods=['GET', 'POST'])
def show_puzzle(puzzle_id):
try:
if request.method == 'GET':
if not request.cookies.get('teamname'): # teamname not set, can't view puzzle
return render_template('team_login.html')
puzzle = puzzmgr.get_puzzle(puzzle_id)
if puzzle is None:
return render_template('error.html', error="Puzzle does not exist!"), 403
if puzzle.state == PuzzleState.OPEN:
return render_template('puzzle.html', puzzle=puzzle,
global_point_totals=puzzmgr.get_global_point_totals(),
puzzle_point_totals=puzzle.get_puzzle_point_totals(),
teamname=request.cookies.get('teamname'))
elif puzzle.state == PuzzleState.CLOSED:
return render_template('puzzle_closed.html', puzzle=puzzle,
global_point_totals=puzzmgr.get_global_point_totals(),
puzzle_point_totals=puzzle.get_puzzle_point_totals(),
teamname=request.cookies.get('teamname'))
elif puzzle.state == PuzzleState.NEW:
return render_template('error.html', error="Puzzle is not yet available!"), 403
else:
if 'submit_teamname' in request.form:
# Teamname just submitted
# Get the teamname from the form post
teamname = request.form['teamname']
if not teamname: # not set
return render_template('team_login.html')
resp = make_response(redirect('/puzzle/' + puzzle_id))
resp.set_cookie('teamname', teamname)
return resp
# Problem attempt submission
# retrieve form data
prob_id = request.form['prob_id']
teamname = request.cookies.get('teamname')
solution_file = request.files['solution_file'] # Returns the actual File obj
# ensure the puzzle is open and accepting submissions
puzzle = puzzmgr.get_puzzle(puzzle_id)
if puzzle.state != PuzzleState.OPEN:
# The puzzle is not open, redirect to the closed puzzle page
return render_template('puzzle_closed.html', puzzle=puzzle,
global_point_totals=puzzmgr.get_global_point_totals(),
puzzle_point_totals=puzzle.get_puzzle_point_totals(),
teamname=request.cookies.get('teamname'))
# Clean and truncate teamname to prevent abuse
teamname = teamname.strip()
if len(teamname) > 15:
teamname = teamname[0:12] + '...'
# Store the uploaded solution file
solution_filepath = ''
if solution_file:
filename = secure_filename(solution_file.filename)
filename += str(uuid.uuid1())
solution_filepath = os.path.join(app.config['SOLUTION_FOLDER'],
filename)
solution_file.save(solution_filepath)
else:
# A solution file is required, can't continue without it
return redirect('/', code=302)
# Feed solution and problem files to puzzle app to score the attempt.
problem = puzzle.get_problem(prob_id)
score, error_msg = puzzmgr.score_attempt(puzzle.app_path, problem.problem_file, solution_filepath)
# Record the attempt
attempt = ProblemAttempt()
attempt.teamname = teamname
attempt.score = -1 # -1 indicates an error
if score > 0:
attempt.score = score
attempt.timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
attempt.timedata = time.time()
attempt.solution_filepath = solution_filepath
problem.attempts.append(attempt)
puzzmgr.save() # Data changed, lets save it.
else:
pass # TODO log it
return render_template('puzzle_submitted.html', puzzle_id=puzzle_id, attempt=attempt,
global_point_totals=puzzmgr.get_global_point_totals(),
teamname=request.cookies.get('teamname'),
error_msg=error_msg)
except Exception as ex:
return render_template('error.html', error=str(ex)), 500
@app.route('/admin', methods=['GET', 'POST'])
def show_admin():
try:
if request.method == 'GET':
return render_template('admin_login.html',
global_point_totals=puzzmgr.get_global_point_totals(),
teamname=request.cookies.get('teamname'))
else:
if 'passcode' in request.form:
# Admin is attempting to login
passcode = request.form['passcode']
if passcode == ADMIN_PASSWORD:
return render_template('admin.html', puzzmgr=puzzmgr,
global_point_totals=puzzmgr.get_global_point_totals(),
teamname=request.cookies.get('teamname'))
else:
return render_template('admin_login.html',
global_point_totals=puzzmgr.get_global_point_totals(),
teamname=request.cookies.get('teamname'))
elif 'puzzle_id' in request.form:
# Admin is updating a puzzle
puzzle = puzzmgr.get_puzzle(request.form['puzzle_id'])
assert(puzzle)
# Determine which action the admin is taking on the puzzle
if 'open_puzzle' in request.form and puzzle.state != PuzzleState.OPEN:
puzzle.state = PuzzleState.OPEN
elif 'close_puzzle' in request.form and puzzle.state != PuzzleState.CLOSED:
puzzle.state = PuzzleState.CLOSED
elif 'reset_puzzle' in request.form and puzzle.state != PuzzleState.NEW:
puzzle.reset()
puzzmgr.save() # Data changed, save it
# Return to the admin page after updating the puzzle
return render_template('admin.html', puzzmgr=puzzmgr,
global_point_totals=puzzmgr.get_global_point_totals(),
teamname=request.cookies.get('teamname'))
elif 'reload_data' in request.form:
# Admin is requesting a data reload
datamgr.load()
puzzmgr.load()
# Reload the admin page
return render_template('admin.html', puzzmgr=puzzmgr,
global_point_totals=puzzmgr.get_global_point_totals(),
teamname=request.cookies.get('teamname'))
except Exception as ex:
return render_template('error.html', error=str(ex)), 500
# Error handlers
@app.errorhandler(403)
def forbidden_request(error):
return render_template('error.html', error=error), 403
@app.errorhandler(404)
def page_not_found_request(error):
return render_template('error.html', error=error), 404
@app.errorhandler(410)
def gone_request(error):
return render_template('error.html', error=error), 410
@app.errorhandler(413)
def file_too_large_request(error):
return render_template('error.html', error=error), 413
@app.errorhandler(500)
def internal_server_error_request(error):
return render_template('error.html', error=error), 500
########## Main ###########
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0')