-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.py
386 lines (361 loc) · 13.8 KB
/
index.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
from flask import *
import subprocess
from threading import Timer
from pysmx.SM3 import SM3
import zipfile
from config import *
import json
import shutil
import shlex
import os
import sys
from markdown import markdown
sm3 = SM3()
# from gevent import monkey
# monkey.patch_all()
def digest(data):
global sm3
sm3.update(data)
return sm3.hexdigest()
def kill_command(obj):
obj.kill()
def run(name: str, count: int):
global flag
flag = False
result = 'Accepted'
for i in range(1, count + 1):
in_file = 'problem/' + name + '/' + str(i) + '.in'
out_file = 'problem/' + name + '/' + str(i) + '.out'
obj_out = ''
lst = judge_command.format(name).split('|')
for j in lst:
obj = subprocess.Popen(shlex.split(j), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True)
timer = Timer(2, kill_command, [obj])
try:
timer.start()
with open(in_file) as f:
lines = f.readlines()
for line in lines:
obj.stdin.write(line)
_obj_out, _obj_err = obj.communicate()
_obj_out = _obj_out.strip(' ')
_obj_out = _obj_out.strip('\n')
_obj_out = _obj_out.strip('\r')
obj_out += _obj_out
if _obj_err == '':
pass
else:
result = 'Compile Error'
except:
result = 'Compile Error'
finally:
timer.cancel()
with open(out_file) as f:
context = f.read()
context = context.strip(' ')
context = context.strip('\n')
context = context.strip('\r')
if context == obj_out:
pass
else:
result = 'Wrong Answer / Time Limit Exceeded'
return result
def createBackup(outFullName):
dirpath = os.getcwd() + '/problem'
zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
for path, dirnames, filenames in os.walk(dirpath):
print(path, dirnames, filenames)
fpath = path.replace(os.getcwd(), '')
for filename in filenames:
zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
zip.write(os.path.join(os.getcwd(), 'data.json'), os.path.join('', 'data.json'))
zip.write(os.path.join(os.getcwd(), 'user.json'), os.path.join('', 'user.json'))
zip.close()
problems = []
try:
with open('data.json', 'r') as f:
problems = json.loads(f.read())
except:
problems = []
with open('data.json', 'w') as f:
f.write(json.dumps(problems))
users = []
try:
with open('user.json', 'r') as f:
users = json.loads(f.read())
except:
users = [{'username': 'admin', 'password': 'admin_password', 'ac': [], 'profile': '', 'ban': False}]
with open('user.json', 'w') as f:
f.write(json.dumps(users))
try:
os.mkdir('problem/')
except:
pass
try:
os.mkdir('temp/')
except:
pass
def user_sort_key(elem):
return len(elem['ac'])
app = Flask(__name__)
app.config['SECRET_KEY'] = admin_password
@app.route('/', methods = ['GET'])
def index():
if session.get('username') is None:
return render_template('index.html', problems = problems)
return render_template('index_logined.html', username = session.get('username'), problems = problems, ac = session.get('ac'))
@app.route('/<path:ojpath>', methods = ['GET', 'POST'])
def problem(ojpath):
for problem in problems:
if problem['id'] == str(ojpath):
if request.method == 'POST':
file = request.files.get('file')
file.save('temp/' + problem['id'] + '/' + problem['id'] + '.' + judge_language_ext)
with open('temp/' + problem['id'] + '/' + problem['id'] + '.' + judge_language_ext) as f:
code = f.read()
if ('__builtins__' in code or 'exec' in code or 'eval' in code or 'import' in code or 'open' in code or 'system' in code):
result = "Dangerous Syscalls"
result = run(str(problem['id']), int(problem['count']))
global user
if result == 'Accepted' and session.get('username') is not None and problem['id'] not in session.get('ac'):
global users
for user in users:
if user['username'] == session.get('username'):
user['ac'].append(problem['id'])
session['ac'] = user['ac']
break
with open('user.json', 'w') as f:
f.write(json.dumps(users))
return render_template("test.html", result = result)
elif request.method == 'GET':
try:
os.mkdir('temp/' + problem['id'] + '/')
except:
pass
return render_template('problem.html', problem_description = markdown(problem['description']), problem_id = problem['id'], language = judge_language)
return "404 Not Found"
@app.route('/contest')
def contest():
problems = request.values.get('problems')
if session.get('ac') == None:
return redirect('/login')
minute = request.values.get('time')
return render_template('contest.html', time = minute, len = len, problems = problems)
@app.route('/frame_contest')
def frame_contest():
problems = request.values.get('problems').split(';')
return render_template('contest_problems.html', problems = problems, ac = session.get('ac'))
@app.route('/login')
def login():
return render_template('login.html')
@app.route('/login_admin')
def login_admin():
return render_template('login_admin.html')
@app.route('/logout')
def logout():
session.clear()
return redirect('/')
@app.route('/admin', methods = ['POST'])
def admin():
passwd = request.values.get('password')
global admin_password
global problem_template
if passwd == admin_password:
return render_template('admin.html', problems = problems, admin_password = admin_password, users = users, len = len, problem_template = problem_template)
return "403 Foridden"
@app.route('/backup')
def backup():
passwd = request.values.get("password")
global admin_password
if passwd == admin_password:
createBackup("static/backup.zip")
return redirect("/static/backup.zip")
return "403 Foridden"
@app.route('/rank')
def rank():
users.sort(key = user_sort_key)
return render_template('rank.html', users = users, len = len)
@app.route('/change_profile', methods = ["GET", "POST"])
def change_profile():
global users
if request.method == "GET":
if session.get('username') is not None:
for user in users:
if user['username'] == session.get('username'):
return render_template('change_profile.html', user = user)
return redirect('/login')
username = session.get('username')
profile = request.values.get('profile')
cnt = 0
while profile.find('```') != -1:
cnt += 1
if cnt % 2 != 0:
profile = profile.replace('```', '<textarea>', 1)
else:
profile = profile.replace('```', '</textarea>', 1)
cnt = 0
while profile.find('`') != -1:
cnt += 1
if cnt % 2 != 0:
profile = profile.replace('`', '<textarea>', 1)
else:
profile = profile.replace('`', '</textarea>', 1)
for user in users:
if username == user['username']:
user['profile'] = markdown(profile)
break
with open('user.json', 'w') as f:
f.write(json.dumps(users))
return redirect('/')
@app.route('/profile')
def profile():
username = request.values.get('username')
if username is None:
return redirect('/')
global users
for user in users:
if user['username'] == username:
return render_template('profile.html', user = user)
return redirect('/')
@app.route('/api/problem', methods = ['POST'])
def problem_api():
Type = request.values.get('type')
problem_id = request.values.get('id')
problem_name = request.values.get('name')
problem_description = request.values.get('description')
zip_file = request.files.get('file')
problem_count = request.values.get('count')
if Type == 'add':
cnt = 0
while problem_description.find('```') != -1:
cnt += 1
if cnt % 2 != 0:
problem_description = problem_description.replace('```', '<textarea>', 1)
else:
problem_description = problem_description.replace('```', '</textarea>', 1)
cnt = 0
while problem_description.find('`') != -1:
cnt += 1
if cnt % 2 != 0:
problem_description = problem_description.replace('`', '<textarea>', 1)
else:
problem_description = problem_description.replace('`', '</textarea>', 1)
os.mkdir('problem/' + problem_id + '/')
os.mkdir('temp/' + problem_id + '/')
zip_file.save('problem/' + problem_id + '/' + problem_id + '.zip')
zipfile.ZipFile('problem/' + problem_id + '/' + problem_id + '.zip').extractall('problem/' + problem_id + '/')
problems.append({'id': problem_id, 'name': problem_name, 'description': problem_description, 'count': problem_count})
with open('data.json', 'w') as f:
f.write(json.dumps(problems))
elif Type == 'del':
for problem in problems:
if problem['id'] == problem_id:
problems.remove(problem)
shutil.rmtree('problem/' + problem_id + '/')
with open('data.json', 'w') as f:
f.write(json.dumps(problems))
else:
return '404 Not Found'
global password
return render_template('redirect.html', passwd = admin_password)
@app.route('/api/user', methods = ['POST'])
def user_api():
Type = request.values.get('type')
username = request.values.get('username')
password = request.values.get('password')
global users
if Type == 'add':
flag = True
for user in users:
if user['username'] == username:
flag = False
break
if flag == False:
return "Username is already."
users.append({'username': username, 'password': password, 'email': '', 'ac': [], 'profile': '', 'ban': False})
with open('user.json', 'w') as f:
f.write(json.dumps(users))
elif Type == 'del':
if username == 'admin':
return "You cannot delete the Administrator account."
for user in users:
if user['username'] == username:
users.remove(user)
break
elif Type == 'ban':
if username == 'admin':
return "You cannot ban the Administrator account."
for user in users:
if user['username'] == username:
user['ban'] = True
break
else:
return '404 Not Found'
with open('user.json', 'w') as f:
f.write(json.dumps(users))
global admin_password
return render_template('redirect.html', passwd = admin_password)
@app.route("/api/login", methods = ['POST'])
def login_api():
username = request.values.get('username')
password = request.values.get('password')
global users
for user in users:
if user['username'] == username and user['password'] == 'admin_password':
session['username'] = username
session['ac'] = user['ac']
break
if user['username'] == username and user['password'] == digest(password):
if user['ban'] == True:
return render_template('login_redirect.html', message = "Your account is ban.")
session['username'] = username
session['ac'] = user['ac']
break
return redirect('/')
@app.route("/api/register", methods = ['POST'])
def register_api():
username = request.values.get('username')
password = digest(request.values.get('password'))
email = request.values.get('email')
flag = True
for user in users:
if user['username'] == username:
flag = False
break
if flag == False:
return render_template('login_redirect.html', message = "Username is already.")
users.append({'username': username, 'password': password, 'email': email, 'ac': [], 'profile': '', 'ban': False})
print(users)
with open('user.json', 'w') as f:
f.write(json.dumps(users))
session['username'] = username
session['ac'] = []
return redirect('/')
@app.route("/api/backup", methods = ["POST"])
def upload_backup():
backup_file = request.files.get('file')
passwd = request.values.get('passwd')
backup_file.save('backup.zip')
zipfile.ZipFile('backup.zip').extractall()
global problems
try:
with open('data.json', 'r') as f:
problems = json.loads(f.read())
except:
problems = []
global users
try:
with open('user.json', 'r') as f:
users = json.loads(f.read())
except:
users = []
try:
os.mkdir('problem/')
except:
pass
return render_template("redirect.html", passwd = passwd)
if __name__ == '__main__':
# from gevent import pywsgi
# server = pywsgi.WSGIServer(('0.0.0.0', 80), app)
# server.serve_forever()
app.run('0.0.0.0', port = 80)