-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpro.py
859 lines (703 loc) · 27.9 KB
/
pro.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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
import os
import json
import msgpack
import math
import datetime
import tornado.process
import tornado.concurrent
import tornado.web
import tornado.gen
import time
import random
import re
from collections import OrderedDict
from req import RequestHandler
from req import reqenv
from user import UserService
from user import UserConst
from chal import ChalService
from pack import PackService
from log import LogService
from req import Service
class ProConst:
NAME_MIN = 1
NAME_MAX = 64
CODE_MAX = 16384
STATUS_ONLINE = 0
STATUS_HIDDEN = 1
STATUS_OFFLINE = 2
class ProService:
NAME_MIN = 1
NAME_MAX = 64
CODE_MAX = 16384
STATUS_ONLINE = 0
STATUS_HIDDEN = 1
STATUS_OFFLINE = 2
PACKTYPE_FULL = 1
PACKTYPE_CONTHTML = 2
PACKTYPE_CONTPDF = 3
def __init__(self, db, rs):
self.db = db
self.rs = rs
ProService.inst = self
def get_pclass_list(self, pro_clas):
clas = self.rs.get(str(pro_clas) + '_pro_list')
if clas == None:
return ('Eexist', None)
return (None, msgpack.unpackb(clas, encoding='utf-8'))
def get_class_list_old(self):
clas_list = self.rs.get('pro_class_list')
if clas_list == None:
self.rs.set('pro_class_list', msgpack.packb([]))
return []
return msgpack.unpackb(clas_list, encoding='utf-8')
def get_class_list(self):
clas_list = self.rs.get('pro_class_list2')
if clas_list == None:
res = []
for row in self.get_class_list_old():
res.append({
'key': row,
'name': row,
})
self.rs.set('pro_class_list2', msgpack.packb(res))
return res
return msgpack.unpackb(clas_list, encoding='utf-8')
def get_pclass_name_by_key(self, pclas_key):
clas_list = self.get_class_list()
for row in clas_list:
if row['key'] == str(pclas_key):
return row['name']
return None
def get_pclass_key_by_name(self, pclas_name):
clas_list = self.get_class_list()
for row in clas_list:
if row['name'] == str(pclas_name):
return row['key']
return None
def add_pclass(self, pclas_key, pclas_name, p_list):
if str(pclas_key) == '':
return 'EbadKey'
clas_list = self.get_class_list()
clas_list_keys = [row['key'] for row in clas_list]
if str(pclas_key) in clas_list_keys:
return 'Eexist'
clas_list.append({
'key': pclas_key,
'name': pclas_name,
})
self.rs.set('pro_class_list2', msgpack.packb(clas_list))
self.rs.set(str(pclas_key) + '_pro_list', msgpack.packb(p_list))
return None
def remove_pclass(self, pclas_key):
clas_list = self.get_class_list()
clas_list_keys = [row['key'] for row in clas_list]
try:
clas_index = clas_list_keys.index(str(pclas_key))
except ValueError:
return 'Eexist'
clas_list.pop(clas_index)
self.rs.set('pro_class_list2', msgpack.packb(clas_list))
self.rs.delete(str(pclas_key) + '_pro_list')
return None
def edit_pclass(self, pclas_key, new_pclas_key, pclas_name, p_list):
if str(new_pclas_key) == '':
return 'EbadKey'
clas_list = self.get_class_list()
clas_list_keys = [row['key'] for row in clas_list]
try:
clas_index = clas_list_keys.index(str(pclas_key))
except ValueError:
return 'Exist'
clas_list[clas_index]['key'] = str(new_pclas_key)
clas_list[clas_index]['name'] = str(pclas_name)
self.rs.set('pro_class_list2', msgpack.packb(clas_list))
if pclas_key != new_pclas_key:
self.rs.delete(str(pclas_key) + '_pro_list')
self.rs.set(str(new_pclas_key) + '_pro_list', msgpack.packb(p_list))
return None
def get_pro(self, pro_id, acct=None, special=None):
max_status = self._get_acct_limit(acct, special)
cur = yield self.db.cursor()
yield cur.execute(('SELECT "name","status","class","expire","tags" '
'FROM "problem" WHERE "pro_id" = %s AND "status" <= %s;'),
(pro_id, max_status))
if cur.rowcount != 1:
return ('Enoext', None)
name, status, clas, expire, tags = cur.fetchone()
clas = clas[0]
if expire == datetime.datetime.max:
expire = None
yield cur.execute(('SELECT "test_idx","compile_type","score_type",'
'"check_type","timelimit","memlimit","weight","metadata","chalmeta" '
'FROM "test_config" WHERE "pro_id" = %s ORDER BY "test_idx" ASC;'),
(pro_id,))
testm_conf = OrderedDict()
for (test_idx, comp_type, score_type, check_type, timelimit, memlimit, weight,
metadata, chalmeta) in cur:
testm_conf[test_idx] = {
'comp_type': comp_type,
'score_type': score_type,
'check_type': check_type,
'timelimit': timelimit,
'memlimit': memlimit,
'weight': weight,
'chalmeta': json.loads(chalmeta, 'utf-8'),
'metadata': json.loads(metadata, 'utf-8')
}
return (None, {
'pro_id': pro_id,
'name': name,
'status': status,
'expire': expire,
'class': clas,
'testm_conf': testm_conf,
'tags': tags,
})
def list_pro(self, acct=None, state=False, clas=None):
def _mp_encoder(obj):
if isinstance(obj, datetime.datetime):
return obj.astimezone(datetime.timezone.utc).timestamp()
return obj
if acct == None:
max_status = ProService.STATUS_ONLINE
else:
max_status = self._get_acct_limit(acct)
if clas == None:
clas = [1, 2]
else:
clas = [clas]
cur = yield self.db.cursor()
statemap = {}
if state == True:
yield cur.execute(('SELECT "problem"."pro_id",'
'MIN("challenge_state"."state") AS "state" '
'FROM "challenge" '
'INNER JOIN "challenge_state" '
'ON "challenge"."chal_id" = "challenge_state"."chal_id" '
'AND "challenge"."acct_id" = %s '
'INNER JOIN "problem" '
'ON "challenge"."pro_id" = "problem"."pro_id" '
'WHERE "problem"."status" <= %s AND "problem"."class" && %s '
'GROUP BY "problem"."pro_id" '
'ORDER BY "pro_id" ASC;'),
(acct['acct_id'], max_status, clas))
for pro_id, state in cur:
statemap[pro_id] = state
field = '%d|%s' % (max_status, str(clas))
prolist = self.rs.hget('prolist', field)
if prolist != None:
prolist = msgpack.unpackb(prolist, encoding='utf-8')
for pro in prolist:
expire = pro['expire']
if expire != None:
expire = datetime.datetime.fromtimestamp(expire)
expire = expire.replace(tzinfo=datetime.timezone(
datetime.timedelta(hours=8)))
pro['expire'] = expire
else:
yield cur.execute(('select '
'"problem"."pro_id",'
'"problem"."name",'
'"problem"."status",'
'"problem"."expire",'
'"problem"."class",'
'"problem"."tags",'
'sum("test_valid_rate"."rate") as "rate" '
'from "problem" '
'inner join "test_valid_rate" '
'on "test_valid_rate"."pro_id" = "problem"."pro_id" '
'where "problem"."status" <= %s and "problem"."class" && %s '
'group by "problem"."pro_id" '
'order by "pro_id" asc;'),
(max_status, clas))
prolist = list()
for pro_id, name, status, expire, clas, tags, rate in cur:
if expire == datetime.datetime.max:
expire = None
prolist.append({
'pro_id': pro_id,
'name': name,
'status': status,
'expire': expire,
'class': clas[0],
'tags': tags,
'rate': rate,
})
self.rs.hset('prolist', field, msgpack.packb(prolist,
default=_mp_encoder))
now = datetime.datetime.utcnow()
now = now.replace(tzinfo=datetime.timezone.utc)
for pro in prolist:
pro_id = pro['pro_id']
if pro_id in statemap:
pro['state'] = statemap[pro_id]
else:
pro['state'] = None
if pro['expire'] == None:
pro['outdate'] = False
else:
delta = (pro['expire'] - now).total_seconds()
if delta < 0:
pro['outdate'] = True
else:
pro['outdate'] = False
return (None, prolist)
def add_pro(self, name, status, clas, expire, pack_token):
if len(name) < ProService.NAME_MIN:
return ('Enamemin', None)
if len(name) > ProService.NAME_MAX:
return ('Enamemax', None)
if (status < ProService.STATUS_ONLINE
or status > ProService.STATUS_OFFLINE):
return ('Eparam', None)
if clas not in [1, 2]:
return ('Eparam', None)
if expire == None:
expire = datetime.datetime(2099, 12, 31, 0, 0, 0, 0,
tzinfo=datetime.timezone.utc)
cur = yield self.db.cursor()
yield cur.execute(('INSERT INTO "problem" '
'("name","status","class","expire") '
'VALUES (%s,%s,%s,%s) RETURNING "pro_id";'),
(name, status, [clas], expire))
if cur.rowcount != 1:
return ('Eunk', None)
pro_id = cur.fetchone()[0]
err, ret = yield from self._unpack_pro(pro_id, ProService.PACKTYPE_FULL, pack_token)
if err:
return (err, None)
yield cur.execute('REFRESH MATERIALIZED VIEW test_valid_rate;')
self.rs.delete('prolist')
self.rs.delete('rate@kernel_True')
self.rs.delete('rate@kernel_False')
return (None, pro_id)
def update_pro(self, pro_id, name, status, clas, expire,
pack_type, pack_token=None, tags=''):
if len(name) < ProService.NAME_MIN:
return ('Enamemin', None)
if len(name) > ProService.NAME_MAX:
return ('Enamemax', None)
if (status < ProService.STATUS_ONLINE
or status > ProService.STATUS_OFFLINE):
return ('Eparam', None)
if clas not in [1, 2]:
return ('Eparam', None)
if tags and not re.match(r'^[a-zA-Z0-9-_, ]+$', tags):
return ('Etags', None)
if expire == None:
expire = datetime.datetime(2099, 12, 31, 0, 0, 0, 0,
tzinfo=datetime.timezone.utc)
cur = yield self.db.cursor()
yield cur.execute(('UPDATE "problem" '
'SET "name" = %s,"status" = %s,"class" = %s,"expire" = %s,"tags" = %s '
'WHERE "pro_id" = %s;'),
(name, status, [clas], expire, tags, pro_id))
if cur.rowcount != 1:
return ('Enoext', None)
if pack_token != None:
err, ret = yield from self._unpack_pro(pro_id, pack_type, pack_token)
if err:
return (err, None)
yield cur.execute('REFRESH MATERIALIZED VIEW test_valid_rate;')
self.rs.delete('prolist')
self.rs.delete('rate@kernel_True')
self.rs.delete('rate@kernel_False')
return (None, None)
def update_limit(self, pro_id, timelimit, memlimit):
if timelimit <= 0:
return ('Etimelimitmin', None)
if memlimit <= 0:
return ('Ememlimitmin', None)
memlimit = memlimit * 1024
cur = yield self.db.cursor()
yield cur.execute(
('UPDATE "test_config" '
'SET "timelimit" = %s, "memlimit" = %s '
'WHERE "pro_id" = %s;'),
(timelimit, memlimit, pro_id))
if cur.rowcount == 0:
return ('Enoext', None)
return (None, None)
def _get_acct_limit(self, acct, special=None):
if special == True:
return ProService.STATUS_OFFLINE
if acct['acct_type'] == UserService.ACCTTYPE_KERNEL:
return ProService.STATUS_OFFLINE
else:
return ProService.STATUS_ONLINE
def _unpack_pro(self, pro_id, pack_type, pack_token):
def _clean_cont(prefix):
try:
os.remove(prefix + 'cont.html')
except OSError:
pass
try:
os.remove(prefix + 'cont.pdf')
except OSError:
pass
if (pack_type != ProService.PACKTYPE_FULL
and pack_type != ProService.PACKTYPE_CONTHTML
and pack_type != ProService.PACKTYPE_CONTPDF):
return ('Eparam', None)
if pack_type == ProService.PACKTYPE_CONTHTML:
prefix = 'problem/%d/http/' % pro_id
_clean_cont(prefix)
ret = PackService.inst.direct_copy(pack_token, prefix + 'cont.html')
elif pack_type == ProService.PACKTYPE_CONTPDF:
prefix = 'problem/%d/http/' % pro_id
_clean_cont(prefix)
ret = PackService.inst.direct_copy(pack_token, prefix + 'cont.pdf')
elif pack_type == ProService.PACKTYPE_FULL:
err, ret = yield from PackService.inst.unpack(
pack_token, 'problem/%d' % pro_id, True)
if err:
return (err, None)
try:
os.chmod('problem/%d' % pro_id, 0o755)
os.symlink(os.path.abspath('problem/%d/http' % pro_id),
'/srv/oj/http/problem/%d' % pro_id)
except FileExistsError:
pass
try:
conf_f = open('problem/%d/conf.json' % pro_id)
conf = json.load(conf_f)
conf_f.close()
except Exception:
return ('Econf', None)
comp_type = conf['compile']
score_type = conf['score']
check_type = conf['check']
timelimit = conf['timelimit']
memlimit = conf['memlimit'] * 1024
chalmeta = conf['metadata']
cur = yield self.db.cursor()
yield cur.execute('DELETE FROM "test_config" WHERE "pro_id" = %s;',
(pro_id,))
for test_idx, test_conf in enumerate(conf['test']):
metadata = {
'data': test_conf['data']
}
yield cur.execute(('insert into "test_config" '
'("pro_id","test_idx",'
'"compile_type","score_type","check_type",'
'"timelimit","memlimit","weight","metadata","chalmeta") '
'values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);'),
(pro_id, test_idx, comp_type, score_type, check_type,
timelimit, memlimit, test_conf['weight'],
json.dumps(metadata), json.dumps(chalmeta)))
return (None, None)
class ProsetHandler(RequestHandler):
@reqenv
def get(self):
try:
off = int(self.get_argument('off'))
except tornado.web.HTTPError:
off = 0
try:
clas = int(self.get_argument('class'))
except tornado.web.HTTPError:
clas = None
try:
pclas_key = str(self.get_argument('pclas_key'))
except:
pclas_key = None
# Backward compatibility
if pclas_key is None:
try:
pclas_name = str(self.get_argument('pclas_name'))
pclas_key = Service.Pro.get_pclass_key_by_name(pclas_name)
except:
pass
err, prolist = yield from ProService.inst.list_pro(
self.acct, state=True, clas=clas)
if pclas_key == None:
pronum = len(prolist)
prolist = prolist[off:off + 40]
self.render('proset', pronum=pronum, prolist=prolist, clas=clas, pclas_key=pclas_key, pclist=ProService.inst.get_class_list(), pageoff=off)
return
else:
err, p_list = ProService.inst.get_pclass_list(pclas_key)
if err:
self.finish(err)
return
prolist2 = []
for pro in prolist:
if pro['pro_id'] in p_list:
prolist2.append(pro)
prolist = prolist2
pronum = len(prolist)
prolist = prolist[off:off + 40]
self.render('proset', pronum=pronum, prolist=prolist, clas=clas, pclas_key=pclas_key, pclist=ProService.inst.get_class_list(), pageoff=off)
return
return
@reqenv
def post(self):
pass
class ProStaticHandler(RequestHandler):
@reqenv
def get(self, pro_id, path):
pro_id = int(pro_id)
err, pro = yield from ProService.inst.get_pro(pro_id, self.acct)
if err:
self.finish(err)
return
if pro['status'] == ProService.STATUS_OFFLINE:
self.finish('Eacces')
return
if path[-3:] == 'pdf':
self.set_header('Pragma', 'public')
self.set_header('Expires', '0')
self.set_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
self.add_header('Content-Type', 'application/pdf')
try:
download = self.get_argument('download')
except tornado.web.HTTPError:
download = None
if download:
self.set_header('Content-Disposition', 'attachment; filename="pro%s.pdf"' % (pro_id))
else:
self.set_header('Content-Disposition', 'inline')
self.set_header('X-Accel-Redirect', '/oj/problem/%d/%s' % (pro_id, path))
return
class ProHandler(RequestHandler):
@reqenv
def get(self, pro_id):
pro_id = int(pro_id)
err, pro = yield from ProService.inst.get_pro(pro_id, self.acct)
if err:
self.finish(err)
return
if pro['status'] == ProService.STATUS_OFFLINE:
self.finish('Eacces')
return
testl = list()
for test_idx, test_conf in pro['testm_conf'].items():
testl.append({
'test_idx': test_idx,
'timelimit': test_conf['timelimit'],
'memlimit': test_conf['memlimit'],
'weight': test_conf['weight'],
'rate': 2000
})
cur = yield self.db.cursor()
yield cur.execute(('SELECT "test_idx","rate" FROM "test_valid_rate" '
'WHERE "pro_id" = %s ORDER BY "test_idx" ASC;'),
(pro_id,))
countmap = {}
for test_idx, count in cur:
countmap[test_idx] = count
for test in testl:
if test['test_idx'] in countmap:
test['rate'] = math.floor(countmap[test['test_idx']])
isadmin = (self.acct['acct_type'] == UserService.ACCTTYPE_KERNEL)
self.render('pro', pro={
'pro_id': pro['pro_id'],
'name': pro['name'],
'status': pro['status'],
'tags': pro['tags'],
}, testl=testl, isadmin=isadmin)
return
class ProTagsHandler(RequestHandler):
@reqenv
def post(self):
if self.acct['acct_id'] == UserService.ACCTID_GUEST:
self.finish('Esign')
return
tags = self.get_argument('tags')
pro_id = int(self.get_argument('pro_id'))
if isinstance(tags, str) and self.acct['acct_type'] == UserService.ACCTTYPE_KERNEL:
err, pro = yield from ProService.inst.get_pro(pro_id, self.acct)
if err:
self.finish(err)
return
yield from LogService.inst.add_log((self.acct['name'] + " updated the tag of problem #" + str(pro_id) + " to: \"" + str(tags) + "\"."))
err, ret = yield from ProService.inst.update_pro(
pro_id, pro['name'], pro['status'], pro['class'], pro['expire'], '', None, tags)
if err:
self.finish(err)
return
else:
self.finish('Eaccess')
return
self.finish('setting tags done')
return
class SubmitHandler(RequestHandler):
@reqenv
def get(self, pro_id):
if self.acct['acct_id'] == UserService.ACCTID_GUEST:
self.finish('login first')
return
pro_id = int(pro_id)
err, pro = yield from ProService.inst.get_pro(pro_id, self.acct)
if err:
self.finish(err)
return
if pro['status'] == ProService.STATUS_OFFLINE:
self.finish('Eacces')
return
self.render('submit', pro=pro)
return
@reqenv
def post(self):
if self.acct['acct_id'] == UserService.ACCTID_GUEST:
self.finish('Esign')
return
reqtype = self.get_argument('reqtype')
if reqtype == 'submit':
pro_id = int(self.get_argument('pro_id'))
code = self.get_argument('code')
if len(code.strip()) == 0:
self.finish('Eempty')
return
if len(code) > ProService.CODE_MAX:
self.finish('Ecodemax')
return
if self.acct['acct_type'] != UserConst.ACCTTYPE_KERNEL:
last_submit_name = 'last_submit_time_%s' % self.acct['acct_id']
if self.rs.get(last_submit_name) == None:
self.rs.set(last_submit_name, int(time.time()))
else:
last_submit_time = int(str(self.rs.get(last_submit_name))[2:-1])
if int(time.time()) - last_submit_time < 30:
self.finish('Einternal')
return
else:
self.rs.set(last_submit_name, int(time.time()))
err, pro = yield from ProService.inst.get_pro(pro_id, self.acct)
if err:
self.finish(err)
return
if pro['status'] == ProService.STATUS_OFFLINE:
self.finish('Eacces')
return
#code = code.replace('bits/stdc++.h','DontUseMe.h')
err, chal_id = yield from ChalService.inst.add_chal(
pro_id, self.acct['acct_id'], code)
if err:
self.finish(err)
return
elif (reqtype == 'rechal'
and self.acct['acct_type'] == UserService.ACCTTYPE_KERNEL):
chal_id = int(self.get_argument('chal_id'))
err, ret = yield from ChalService.inst.reset_chal(chal_id)
err, chal = yield from ChalService.inst.get_chal(chal_id, self.acct)
pro_id = chal['pro_id']
err, pro = yield from ProService.inst.get_pro(pro_id, self.acct)
if err:
self.finish(err)
return
else:
self.finish('Eparam')
return
err, ret = yield from ChalService.inst.emit_chal(
chal_id,
pro_id,
pro['testm_conf'],
'/nfs/code/%d/main.cpp' % chal_id,
'/nfs/problem/%d/res' % pro_id)
if err:
self.finish(err)
return
if reqtype == 'submit' and pro['status'] == ProService.STATUS_ONLINE:
self.rs.publish('challist_sub', 1)
self.finish(json.dumps(chal_id))
return
class ChalListHandler(RequestHandler):
@reqenv
def get(self):
try:
off = int(self.get_argument('off'))
except tornado.web.HTTPError:
off = 0
try:
ppro_id = str(self.get_argument('proid'))
tmp_pro_id = ppro_id.replace(' ', '').split(',')
pro_id = list()
for p in tmp_pro_id:
try:
pro_id.append(int(p))
except ValueError:
pass
if len(pro_id) == 0:
pro_id = None
except tornado.web.HTTPError:
pro_id = None
ppro_id = ''
try:
pacct_id = str(self.get_argument('acctid'))
tmp_acct_id = pacct_id.replace(' ', '').split(',')
acct_id = list()
for a in tmp_acct_id:
acct_id.append(int(a))
except tornado.web.HTTPError:
acct_id = None
pacct_id = ''
try:
state = int(self.get_argument('state'))
except (tornado.web.HTTPError, ValueError):
state = 0
flt = {
'pro_id': pro_id,
'acct_id': acct_id,
'state': state
}
err, chalstat = yield from ChalService.inst.get_stat(
min(self.acct['acct_type'], UserService.ACCTTYPE_USER), flt)
err, challist = yield from ChalService.inst.list_chal(off, 20,
min(self.acct['acct_type'], UserService.ACCTTYPE_USER), flt)
isadmin = (self.acct['acct_type'] == UserService.ACCTTYPE_KERNEL)
chalids = []
for chal in challist:
chalids.append(chal['chal_id'])
self.render('challist',
chalstat=chalstat,
challist=challist,
flt=flt,
pageoff=off,
ppro_id=ppro_id,
pacct_id=pacct_id,
acct=self.acct,
chalids=json.dumps(chalids),
isadmin=isadmin)
return
@reqenv
def post(self):
seq = self.get_argument('seq')
import tornadoredis
from req import WebSocketHandler
class ChalSubHandler(WebSocketHandler):
@tornado.gen.engine
def open(self):
self.ars = tornadoredis.Client(selected_db=1)
self.ars.connect()
yield tornado.gen.Task(self.ars.subscribe, 'challist_sub')
self.ars.listen(self.on_message)
def on_message(self, msg):
if msg.kind == 'message':
self.write_message(str(int(msg.body)))
def on_close(self):
self.ars.disconnect()
class ChalHandler(RequestHandler):
@reqenv
def get(self, chal_id):
chal_id = int(chal_id)
err, chal = yield from ChalService.inst.get_chal(chal_id, self.acct)
if err:
self.finish(err)
return
err, pro = yield from ProService.inst.get_pro(chal['pro_id'], self.acct)
if err:
self.finish(err)
return
if self.acct['acct_type'] == UserService.ACCTTYPE_KERNEL:
rechal = True
else:
rechal = False
self.render('chal', pro=pro, chal=chal, rechal=rechal)
return
@reqenv
def post(self):
reqtype = self.get_argument('reqtype')
self.finish('Eunk')
return