-
-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathproblem.ts
More file actions
1039 lines (989 loc) · 48 KB
/
problem.ts
File metadata and controls
1039 lines (989 loc) · 48 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
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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import AdmZip from 'adm-zip';
import { readFile, statSync } from 'fs-extra';
import {
escapeRegExp, flattenDeep, intersection, pick, uniqBy,
} from 'lodash';
import { Filter, ObjectId } from 'mongodb';
import { nanoid } from 'nanoid';
import { sortFiles, streamToBuffer } from '@hydrooj/utils/lib/utils';
import {
BadRequestError, ContestNotAttendedError, ContestNotEndedError, ContestNotFoundError, ContestNotLiveError,
FileLimitExceededError, HackFailedError, NoProblemError, NotFoundError,
PermissionError, ProblemAlreadyExistError, ProblemAlreadyUsedByContestError, ProblemConfigError,
ProblemIsReferencedError, ProblemLockError,
ProblemNotAllowLanguageError, ProblemNotAllowPretestError, ProblemNotFoundError,
RecordNotFoundError, SolutionNotFoundError, ValidationError,
} from '../error';
import {
ProblemDoc, ProblemSearchOptions, ProblemStatusDoc, RecordDoc, User,
} from '../interface';
import paginate from '../lib/paginate';
import { PERM, PRIV, STATUS } from '../model/builtin';
import * as contest from '../model/contest';
import * as discussion from '../model/discussion';
import domain from '../model/domain';
import * as oplog from '../model/oplog';
import problem from '../model/problem';
import record from '../model/record';
import * as setting from '../model/setting';
import solution from '../model/solution';
import storage from '../model/storage';
import * as system from '../model/system';
import user from '../model/user';
import {
Handler, param, post, query, route, Types,
} from '../service/server';
import { buildProjection } from '../utils';
import { registerResolver, registerValue } from './api';
import { ContestDetailBaseHandler } from './contest';
export const parseCategory = (value: string) => value.replace(/,/g, ',').split(',').map((e) => e.trim());
registerValue('FileInfo', [
['_id', 'String!'],
['name', 'String!'],
['size', 'Int'],
['lastModified', 'Date'],
]);
registerValue('Problem', [
['_id', 'ObjectID!'],
['owner', 'Int!'],
['domainId', 'String!'],
['docId', 'Int!'],
['docType', 'Int!'],
['pid', 'String'],
['title', 'String!'],
['content', 'String!'],
['config', 'String!'],
['data', '[FileInfo]'],
['additional_file', '[FileInfo]'],
['nSubmit', 'Int'],
['nAccept', 'Int'],
['difficulty', 'Int'],
['tag', '[String]'],
['hidden', 'Boolean'],
]);
registerResolver(
'Query', 'problem(id: Int, pid: String)', 'Problem',
async (arg, ctx) => {
ctx.checkPerm(PERM.PERM_VIEW);
const pdoc = await problem.get(ctx.args.domainId, arg.pid || arg.id);
if (!pdoc) return null;
if (pdoc.hidden) ctx.checkPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN);
ctx.pdoc = pdoc;
return pdoc;
},
);
registerResolver('Query', 'problems(ids: [Int])', '[Problem]', async (arg, ctx) => {
ctx.checkPerm(PERM.PERM_VIEW);
const res = await problem.getList(ctx.args.domainId, arg.ids, ctx.user.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN) || ctx.user._id,
undefined, undefined, true);
return Object.keys(res).map((id) => res[+id]);
}, 'Get a list of problem by ids');
registerResolver(
'Problem', 'manage', 'ProblemManage',
(arg, ctx) => {
if (!ctx.user.own(ctx.pdoc, PERM.PERM_EDIT_PROBLEM_SELF)) ctx.checkPerm(PERM.PERM_EDIT_PROBLEM);
return {};
},
);
registerResolver(
'ProblemManage', 'delete', 'Boolean!',
async (arg, ctx) => {
const tdocs = await contest.getRelated(ctx.args.domainId, ctx.pdoc.docId);
if (tdocs.length) throw new ProblemAlreadyUsedByContestError(ctx.pdoc.docId, tdocs[0]._id);
return problem.del(ctx.pdoc.domainId, ctx.pdoc.docId);
},
);
registerResolver(
'ProblemManage', 'edit(title: String, content: String, tag: [String], hidden: Boolean)', 'Problem!',
(arg, ctx) => problem.edit(ctx.args.domainId, ctx.pdoc.docId, arg),
);
function buildQuery(udoc: User) {
const q: Filter<ProblemDoc> = {};
if (!udoc.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN)) {
q.$or = [
{ hidden: false },
{ owner: udoc._id },
{ maintainer: udoc._id },
];
}
return q;
}
const defaultSearch = async (domainId: string, q: string, options?: ProblemSearchOptions) => {
const escaped = escapeRegExp(q.toLowerCase());
const $regex = new RegExp(q.length >= 3 ? escaped : `\\A${escaped}`, 'gmi');
const filter = { $or: [{ pid: { $regex } }, { title: { $regex } }] };
const pdocs = await problem.getMulti(domainId, filter, ['domainId', 'docId', 'pid'])
.skip(options.skip || 0).limit(options.limit || system.get('pagination.problem')).toArray();
if (!Number.isNaN(+q)) {
const pdoc = await problem.get(domainId, +q, ['domainId', 'docId', 'pid', 'title']);
if (pdoc) pdocs.unshift(pdoc);
}
return {
hits: pdocs.map((i) => `${i.domainId}/${i.docId}`),
total: await problem.count(domainId, filter),
countRelation: 'eq',
};
};
export class ProblemMainHandler extends Handler {
@param('page', Types.PositiveInt, true)
@param('q', Types.Content, true)
@param('limit', Types.PositiveInt, true)
@param('pjax', Types.Boolean)
async get(domainId: string, page = 1, q = '', limit: number, pjax = false) {
this.response.template = 'problem_main.html';
if (!limit || limit > system.get('pagination.problem') || page > 1) limit = system.get('pagination.problem');
// eslint-disable-next-line @typescript-eslint/no-shadow
const query = buildQuery(this.user);
const psdict = {};
const search = global.Hydro.lib.problemSearch || defaultSearch;
let sort: string[];
let fail = false;
let pcountRelation = 'eq';
const category = flattenDeep(q.split(' ')
.filter((i) => i.startsWith('category:'))
.map((i) => i.split('category:')[1]?.split(',')));
const text = q.split(' ').filter((i) => !i.startsWith('category:')).join(' ');
if (category.length) query.$and = category.map((tag) => ({ tag }));
if (text) category.push(text);
if (category.length) this.UiContext.extraTitleContent = category.join(',');
let total = 0;
if (text) {
const result = await search(domainId, q, { skip: (page - 1) * limit, limit });
total = result.total;
pcountRelation = result.countRelation;
if (!result.hits.length) fail = true;
query.$and ||= [];
query.$and.push({
$or: result.hits.map((i) => {
const [did, docId] = i.split('/');
return { domainId: did, docId: +docId };
}),
});
sort = result.hits;
}
await this.ctx.parallel('problem/list', query, this);
// eslint-disable-next-line prefer-const
let [pdocs, ppcount, pcount] = fail
? [[], 0, 0]
: await problem.list(domainId, query, sort?.length ? 1 : page, limit, undefined, this.user._id);
if (total) {
pcount = total;
ppcount = Math.ceil(total / limit);
}
if (sort) pdocs = pdocs.sort((a, b) => sort.indexOf(`${a.domainId}/${a.docId}`) - sort.indexOf(`${b.domainId}/${b.docId}`));
if (q && page === 1) {
const pdoc = await problem.get(domainId, +q || q, problem.PROJECTION_LIST);
if (pdoc && problem.canViewBy(pdoc, this.user)) {
const count = pdocs.length;
pdocs = pdocs.filter((doc) => doc.docId !== pdoc.docId);
pdocs.unshift(pdoc);
pcount = pcount - count + pdocs.length;
}
}
if (this.user.hasPriv(PRIV.PRIV_USER_PROFILE)) {
const domainIds = Array.from(new Set(pdocs.map((i) => i.domainId)));
await Promise.all(
domainIds.map((did) =>
problem.getListStatus(
did, this.user._id,
pdocs.filter((i) => i.domainId === did).map((i) => i.docId),
).then((res) => Object.assign(psdict, res))),
);
}
if (pjax) {
this.response.body = {
title: this.renderTitle(this.translate('problem_main')),
fragments: (await Promise.all([
this.renderHTML('partials/problem_list.html', {
page, ppcount, pcount, pdocs, psdict, qs: q,
}),
this.renderHTML('partials/problem_stat.html', { pcount, pcountRelation }),
this.renderHTML('partials/problem_lucky.html', { qs: q }),
])).map((i) => ({ html: i })),
};
} else {
this.response.body = {
page,
pcount,
ppcount,
pcountRelation,
pdocs,
psdict,
category: category.join(','),
qs: q,
};
}
}
@param('pid', Types.UnsignedInt)
async postStar(domainId: string, pid: number) {
await problem.setStar(domainId, pid, this.user._id, true);
this.back({ star: true });
}
@param('pid', Types.UnsignedInt)
async postUnstar(domainId: string, pid: number) {
await problem.setStar(domainId, pid, this.user._id, false);
this.back({ star: false });
}
@param('pids', Types.NumericArray)
@param('target', Types.String)
async postCopy(domainId: string, pids: number[], target: string) {
const t = `,${this.domain.share || ''},`;
if (t !== ',*,' && !t.includes(`,${target},`)) throw new PermissionError(target);
const ddoc = await domain.get(target);
if (!ddoc) throw new NotFoundError(target);
const dudoc = await user.getById(target, this.user._id);
if (!dudoc.hasPerm(PERM.PERM_CREATE_PROBLEM)) throw new PermissionError(PERM.PERM_CREATE_PROBLEM);
const ids = [];
for (const pid of pids) {
// eslint-disable-next-line no-await-in-loop
ids.push(await problem.copy(domainId, pid, target));
}
this.response.body = ids;
}
@param('pids', Types.NumericArray)
async postDelete(domainId: string, pids: number[]) {
let i = 0;
for (const pid of pids) {
// eslint-disable-next-line no-await-in-loop
const pdoc = await problem.get(domainId, pid);
if (!pdoc) continue;
if (!this.user.own(pdoc, PERM.PERM_EDIT_PROBLEM_SELF)) this.checkPerm(PERM.PERM_EDIT_PROBLEM);
// eslint-disable-next-line no-await-in-loop
await problem.del(domainId, pid);
i++;
this.progress(`Deleting: (${i}/${pids.length})`);
}
this.back();
}
@param('pids', Types.NumericArray)
async postHide(domainId: string, pids: number[]) {
for (const pid of pids) {
// eslint-disable-next-line no-await-in-loop
const pdoc = await problem.get(domainId, pid);
if (!this.user.own(pdoc, PERM.PERM_EDIT_PROBLEM_SELF)) this.checkPerm(PERM.PERM_EDIT_PROBLEM);
// eslint-disable-next-line no-await-in-loop
await problem.edit(domainId, pid, { hidden: true });
}
this.back();
}
@param('pids', Types.NumericArray)
async postUnhide(domainId: string, pids: number[]) {
for (const pid of pids) {
// eslint-disable-next-line no-await-in-loop
const pdoc = await problem.get(domainId, pid);
if (!this.user.own(pdoc, PERM.PERM_EDIT_PROBLEM_SELF)) this.checkPerm(PERM.PERM_EDIT_PROBLEM);
// eslint-disable-next-line no-await-in-loop
await problem.edit(domainId, pid, { hidden: false });
}
this.back();
}
}
export class ProblemRandomHandler extends Handler {
@param('q', Types.Content, true)
async get(domainId: string, qs = '') {
const category = flattenDeep(qs.split(' ')
.filter((i) => i.startsWith('category:'))
.map((i) => i.split('category:')[1]?.split(',')));
const q = buildQuery(this.user);
if (category.length) q.$and = category.map((tag) => ({ tag }));
await this.ctx.parallel('problem/list', q, this);
const pid = await problem.random(domainId, q);
if (!pid) throw new NoProblemError();
this.response.body = { pid };
this.response.redirect = this.url('problem_detail', { pid });
}
}
export class ProblemDetailHandler extends ContestDetailBaseHandler {
pdoc: ProblemDoc;
udoc: User;
psdoc: ProblemStatusDoc;
@route('pid', Types.ProblemId, true)
@query('tid', Types.ObjectId, true)
async _prepare(domainId: string, pid: number | string, tid?: ObjectId) {
this.pdoc = await problem.get(domainId, pid);
if (!this.pdoc) throw new ProblemNotFoundError(domainId, pid);
if (tid) {
if (!this.tdoc?.pids?.includes(this.pdoc.docId)) throw new ContestNotFoundError(domainId, tid);
if (contest.isNotStarted(this.tdoc)) throw new ContestNotLiveError(tid);
if (!contest.isDone(this.tdoc, this.tsdoc) && (!this.tsdoc?.attend || !this.tsdoc.startAt)) throw new ContestNotAttendedError(tid);
// Delete problem-related info in contest mode
this.pdoc.tag.length = 0;
delete this.pdoc.nAccept;
delete this.pdoc.nSubmit;
delete this.pdoc.difficulty;
delete this.pdoc.stats;
} else if (!problem.canViewBy(this.pdoc, this.user)) {
throw new PermissionError(PERM.PERM_VIEW_PROBLEM_HIDDEN);
}
let ddoc = this.domain;
if (this.pdoc.reference) {
ddoc = await domain.get(this.pdoc.reference.domainId);
const pdoc = await problem.get(this.pdoc.reference.domainId, this.pdoc.reference.pid);
if (!ddoc || !pdoc) throw new ProblemNotFoundError(this.pdoc.reference.domainId, this.pdoc.reference.pid);
this.pdoc.config = pdoc.config;
}
if (typeof this.pdoc.config !== 'string') {
let baseLangs;
if (this.pdoc.config.type === 'remote_judge') {
const p = this.pdoc.config.subType;
const dl = [p, ...Object.keys(setting.langs).filter((i) => i.startsWith(`${p}.`))];
baseLangs = dl;
} else {
baseLangs = Object.keys(setting.langs).filter((i) => !setting.langs[i].remote);
}
const t = [];
if (this.pdoc.config.langs) t.push(this.pdoc.config.langs);
if (ddoc.langs) t.push(ddoc.langs.split(',').map((i) => i.trim()).filter((i) => i));
if (this.domain.langs) t.push(this.domain.langs.split(',').map((i) => i.trim()).filter((i) => i));
this.pdoc.config.langs = ['objective', 'submit_answer'].includes(this.pdoc.config.type) ? ['_'] : intersection(baseLangs, ...t);
}
await this.ctx.parallel('problem/get', this.pdoc, this);
[this.psdoc, this.udoc] = await Promise.all([
problem.getStatus(domainId, this.pdoc.docId, this.user._id),
user.getById(domainId, this.pdoc.owner),
]);
const [scnt, dcnt] = await Promise.all([
solution.count(domainId, { parentId: this.pdoc.docId }),
discussion.count(domainId, { parentId: this.pdoc.docId }),
]);
this.response.body = {
pdoc: this.pdoc,
udoc: this.udoc,
psdoc: tid ? null : this.psdoc,
title: this.pdoc.title,
solutionCount: scnt,
discussionCount: dcnt,
tdoc: this.tdoc,
};
if (this.tdoc && this.tsdoc) {
const fields = ['attend', 'startAt'];
if (contest.canShowSelfRecord.call(this, this.tdoc, true)) fields.push('detail');
this.response.body.tsdoc = pick(this.tsdoc, fields);
}
this.response.template = 'problem_detail.html';
this.UiContext.extraTitleContent = this.pdoc.title;
}
@query('tid', Types.ObjectId, true)
@query('pjax', Types.Boolean)
async get(...args: any[]) {
// Navigate to current additional file download
// e.g.  will navigate to 
if (!this.request.json || args[2]) {
if (args[1]) {
this.response.body.pdoc.content = this.response.body.pdoc.content
.replace(/\(file:\/\/(.+?)\)/g, (str) => {
const info = str.match(/\(file:\/\/(.+?)\)/);
return `(./${this.pdoc.docId}/file/${info[1]}${info[1].includes('?') ? '&' : '?'}tid=${args[1]})`;
})
.replace(/="file:\/\/(.+?)"/g, (str) => {
const info = str.match(/="file:\/\/(.+?)"/);
return `="./${this.pdoc.docId}/file/${info[1]}${info[1].includes('?') ? '&' : '?'}tid=${args[1]}"`;
})
.replace(/=\\"file:\/\/(.+?)\\"/g, (str) => {
const info = str.match(/=\\"file:\/\/(.+?)\\"/);
return `=\\"./${this.pdoc.docId}/file/${info[1]}${info[1].includes('?') ? '&' : '?'}tid=${args[1]}\\"`;
});
} else {
this.response.body.pdoc.content = this.response.body.pdoc.content
.replace(/\(file:\/\//g, `(./${this.pdoc.docId}/file/`)
.replace(/="file:\/\//g, `="./${this.pdoc.docId}/file/`)
.replace(/=\\"file:\/\//g, `=\\"${this.pdoc.docId}/file/`);
}
}
this.response.body.page_name = this.tdoc
? this.tdoc.rule === 'homework'
? 'homework_detail_problem'
: 'contest_detail_problem'
: 'problem_detail';
if (args[2]) {
const data = { pdoc: this.pdoc, tdoc: this.tdoc };
this.response.body = {
title: this.renderTitle(this.response.body.page_name),
fragments: [
{ html: await this.renderHTML('partials/problem_description.html', data) },
],
raw: data,
};
}
if (!this.response.body.tdoc) {
if (this.psdoc?.rid) {
this.response.body.rdoc = await record.get(this.args.domainId, this.psdoc.rid);
}
[this.response.body.ctdocs, this.response.body.htdocs] = await Promise.all([
contest.getRelated(this.args.domainId, this.pdoc.docId),
contest.getRelated(this.args.domainId, this.pdoc.docId, 'homework'),
]);
}
}
@param('pid', Types.UnsignedInt)
async postRejudge(domainId: string, pid: number) {
this.checkPerm(PERM.PERM_REJUDGE_PROBLEM);
const rdocs = await record.getMulti(domainId, {
pid,
contest: { $ne: new ObjectId('0'.repeat(24)) },
status: { $ne: STATUS.STATUS_CANCELED },
'files.hack': { $exists: false },
}).project({ _id: 1, contest: 1 }).toArray();
if (!this.pdoc.config || typeof this.pdoc.config === 'string') throw new ProblemConfigError();
const priority = await record.submissionPriority(this.user._id, -10000 - rdocs.length * 5 - 50);
await record.reset(domainId, rdocs.map((rdoc) => rdoc._id), true);
await Promise.all([
record.judge(domainId, rdocs.filter((i) => i.contest).map((i) => i._id), priority, { detail: false }, { rejudge: true }),
record.judge(domainId, rdocs.filter((i) => !i.contest).map((i) => i._id), priority, {}, { rejudge: true }),
]);
this.back();
}
@param('target', Types.String)
async postCopy(domainId: string, target: string) {
if (this.pdoc.reference) throw new BadRequestError('Cannot copy a referenced problem');
const t = `,${this.domain.share || ''},`;
if (t !== ',*,' && !t.includes(`,${target},`)) throw new PermissionError(target);
const ddoc = await domain.get(target);
if (!ddoc) throw new NotFoundError(target);
const dudoc = await user.getById(target, this.user._id);
if (!dudoc.hasPerm(PERM.PERM_CREATE_PROBLEM)) throw new PermissionError(PERM.PERM_CREATE_PROBLEM);
const docId = await problem.copy(domainId, this.pdoc.docId, target);
this.response.redirect = this.url('problem_detail', { domainId: target, pid: docId });
}
async postDelete() {
if (!this.user.own(this.pdoc, PERM.PERM_EDIT_PROBLEM_SELF)) this.checkPerm(PERM.PERM_EDIT_PROBLEM);
const tdocs = await contest.getRelated(this.args.domainId, this.pdoc.docId);
if (tdocs.length) throw new ProblemAlreadyUsedByContestError(this.pdoc.docId, tdocs[0]._id);
await problem.del(this.pdoc.domainId, this.pdoc.docId);
this.response.redirect = this.url('problem_main');
}
}
export class ProblemSubmitHandler extends ProblemDetailHandler {
@param('tid', Types.ObjectId, true)
async prepare(domainId: string, tid?: ObjectId) {
if (tid && !contest.isOngoing(this.tdoc, this.tsdoc)) throw new ContestNotLiveError(this.tdoc.docId);
if (typeof this.pdoc.config === 'string') throw new ProblemConfigError();
}
async get(domainId: string, tid?: ObjectId) {
this.response.template = 'problem_submit.html';
const langRange = (typeof this.pdoc.config === 'object' && this.pdoc.config.langs)
? Object.fromEntries(this.pdoc.config.langs.map((i) => [i, setting.langs[i]?.display || i]))
: setting.SETTINGS_BY_KEY.codeLang.range;
this.response.body = {
langRange,
pdoc: this.pdoc,
udoc: this.udoc,
tdoc: this.tdoc,
title: this.pdoc.title,
page_name: this.tdoc
? this.tdoc.rule === 'homework'
? 'homework_detail_problem_submit'
: 'contest_detail_problem_submit'
: 'problem_submit',
};
}
@param('lang', Types.Name)
@param('code', Types.Content, true)
@param('pretest', Types.Boolean)
@param('input', Types.String, true)
@param('tid', Types.ObjectId, true)
async post(domainId: string, lang: string, code: string, pretest = false, input = '', tid?: ObjectId) {
if (tid) {
const tdoc = await contest.get(domainId, tid);
if (tdoc.rule === 'cf' && tdoc.lockedList[this.pdoc.docId].includes(this.user._id)) {
throw new ProblemLockError('You have locked this problem.');
}
}
const config = this.pdoc.config;
if (typeof config === 'string' || config === null) throw new ProblemConfigError();
if (['submit_answer', 'objective'].includes(config.type)) {
lang = '_';
} else if ((config.langs && !config.langs.includes(lang)) || !setting.langs[lang] || setting.langs[lang].disabled) {
throw new ProblemNotAllowLanguageError();
}
if (pretest) {
if (setting.langs[lang]?.pretest) lang = setting.langs[lang].pretest as string;
if (setting.langs[lang]?.pretest === false) throw new ProblemNotAllowPretestError('language');
if (!['default', 'fileio', 'remote_judge'].includes(this.response.body.pdoc.config?.type)) {
throw new ProblemNotAllowPretestError('type');
}
}
await this.limitRate('add_record', 60, system.get('limit.submission_user'), true);
await this.limitRate('add_record', 60, system.get('limit.submission'), false);
const files: Record<string, string> = {};
if (!code) {
const file = this.request.files?.file;
if (!file || file.size === 0) throw new ValidationError('code');
const sizeLimit = config.type === 'submit_answer' ? 128 * 1024 * 1024 : 65535;
if (file.size > sizeLimit) throw new ValidationError('file');
if (file.size < 65535 && !file.filepath.endsWith('.zip')) {
// TODO auto detect & convert encoding
// TODO submission file shape
code = await readFile(file.filepath, 'utf-8');
} else {
const id = nanoid();
await storage.put(`submission/${this.user._id}/${id}`, file.filepath, this.user._id);
files.code = `${this.user._id}/${id}#${file.originalFilename}`;
}
}
const rid = await record.add(
domainId, this.pdoc.docId, this.user._id, lang, code, true,
pretest ? { input, type: 'pretest' } : { contest: tid, files, type: tid ? 'contest' : 'judge' },
);
const rdoc = await record.get(domainId, rid);
if (!pretest) {
await Promise.all([
problem.inc(domainId, this.pdoc.docId, 'nSubmit', 1),
problem.incStatus(domainId, this.pdoc.docId, this.user._id, 'nSubmit', 1),
domain.incUserInDomain(domainId, this.user._id, 'nSubmit'),
tid && contest.updateStatus(domainId, tid, this.user._id, rid, this.pdoc.docId),
]);
}
this.ctx.broadcast('record/change', rdoc);
if (tid && !pretest && !contest.canShowSelfRecord.call(this, this.tdoc)) {
this.response.body = { tid };
this.response.redirect = this.url(this.tdoc.rule === 'homework' ? 'homework_detail' : 'contest_detail', { tid });
} else {
this.response.body = { rid };
this.response.redirect = this.url('record_detail', { rid });
}
}
}
export class ProblemHackHandler extends ProblemDetailHandler {
rdoc: RecordDoc;
@param('rid', Types.ObjectId)
@param('tid', Types.ObjectId, true)
async prepare(domainId: string, rid: ObjectId, tid?: ObjectId) {
if (typeof this.pdoc.config !== 'object' || !this.pdoc.config.hackable) throw new HackFailedError('This problem is not hackable.');
this.rdoc = await record.get(domainId, rid);
if (!this.rdoc || this.rdoc.pid !== this.pdoc.docId
|| this.rdoc.contest?.toString() !== tid?.toString()) throw new RecordNotFoundError(domainId, rid);
if (tid) {
if (this.tdoc.rule !== 'cf') throw new HackFailedError('This contest is not hackable.');
if (!contest.isOngoing(this.tdoc, this.tsdoc)) throw new ContestNotLiveError(this.tdoc.docId);
}
if (this.rdoc.uid === this.user._id) throw new HackFailedError('You cannot hack your own submission');
if (this.psdoc?.status !== STATUS.STATUS_ACCEPTED) throw new HackFailedError('You must accept this problem before hacking.');
if (this.rdoc.status !== STATUS.STATUS_ACCEPTED) throw new HackFailedError('You cannot hack a unsuccessful submission.');
}
async get() {
this.response.template = 'problem_hack.html';
this.response.body = {
pdoc: this.pdoc,
udoc: this.udoc,
rid: this.rdoc._id,
title: this.pdoc.title,
page_name: this.tdoc ? 'contest_detail_problem_hack' : 'problem_hack',
};
}
@param('input', Types.String, true)
@param('tid', Types.ObjectId, true)
async post(domainId: string, input = '', tid?: ObjectId) {
await this.limitRate('add_record', 60, system.get('limit.submission_user'), true);
await this.limitRate('add_record', 60, system.get('limit.submission'), false);
const id = `${this.user._id}/${nanoid()}`;
if (this.request.files?.file?.size > 0) {
const file = this.request.files.file;
if (!file || file.size > 128 * 1024 * 1024) throw new ValidationError('input');
await storage.put(`submission/${id}`, file.filepath, this.user._id);
} else if (input) {
await storage.put(`submission/${id}`, Buffer.from(input), this.user._id);
}
const rid = await record.add(
domainId, this.pdoc.docId, this.user._id,
this.rdoc.lang, this.rdoc.code, true,
{ contest: tid, type: 'hack', files: { hack: `${id}#input.txt` } },
);
const rdoc = await record.get(domainId, rid);
// TODO contest: update status;
this.ctx.broadcast('record/change', rdoc);
this.response.body = { rid };
this.response.redirect = this.url('record_detail', { rid });
}
}
export class ProblemManageHandler extends ProblemDetailHandler {
async prepare() {
if (!this.user.own(this.pdoc, PERM.PERM_EDIT_PROBLEM_SELF)) this.checkPerm(PERM.PERM_EDIT_PROBLEM);
}
}
export class ProblemEditHandler extends ProblemManageHandler {
async get() {
this.response.body.additional_file = sortFiles(this.pdoc.additional_file || []);
this.response.template = 'problem_edit.html';
}
@route('pid', Types.ProblemId)
@post('title', Types.Title)
@post('content', Types.Content)
@post('pid', Types.ProblemId, true, (i) => /^[a-zA-Z]+[a-zA-Z0-9]*$/i.test(i))
@post('hidden', Types.Boolean)
@post('tag', Types.Content, true, null, parseCategory)
@post('difficulty', Types.PositiveInt, (i) => +i <= 10, true)
async post(
domainId: string, pid: string | number, title: string, content: string,
newPid: string | number = '', hidden = false, tag: string[] = [], difficulty = 0,
) {
if (typeof newPid !== 'string') newPid = `P${newPid}`;
if (newPid !== this.pdoc.pid && await problem.get(domainId, newPid)) throw new ProblemAlreadyExistError(pid);
const $update: Partial<ProblemDoc> = {
title, content, pid: newPid, hidden, tag: tag ?? [], difficulty, html: false,
};
const pdoc = await problem.edit(domainId, this.pdoc.docId, $update);
this.response.redirect = this.url('problem_detail', { pid: newPid || pdoc.docId });
}
}
export class ProblemConfigHandler extends ProblemManageHandler {
async get() {
if (this.pdoc.reference) throw new ProblemIsReferencedError('edit config');
this.response.body.testdata = sortFiles(this.pdoc.data || []);
const configFile = (this.pdoc.data || []).filter((i) => i.name.toLowerCase() === 'config.yaml');
this.response.body.config = '';
if (configFile.length > 0) {
try {
this.response.body.config = (await streamToBuffer(
await storage.get(`problem/${this.pdoc.domainId}/${this.pdoc.docId}/testdata/${configFile[0].name}`),
)).toString();
} catch (e) { /* ignore */ }
}
this.response.template = 'problem_config.html';
}
}
export class ProblemFilesHandler extends ProblemDetailHandler {
notUsage = true;
@param('d', Types.CommaSeperatedArray, true)
@param('pjax', Types.Boolean)
@param('sidebar', Types.Boolean)
async get(domainId: string, d = ['testdata', 'additional_file'], pjax = false, sidebar = false) {
this.response.body.testdata = d.includes('testdata') ? sortFiles(this.pdoc.data || []) : [];
this.response.body.reference = this.pdoc.reference;
this.response.body.additional_file = d.includes('additional_file') ? sortFiles(this.pdoc.additional_file || []) : [];
if (pjax) {
const { testdata, additional_file } = this.response.body;
const owner = await user.getById(domainId, this.pdoc.owner);
const args = {
testdata, additional_file, pdoc: this.pdoc, owner_udoc: owner, sidebar,
};
const tasks = [];
if (d.includes('testdata')) tasks.push(this.renderHTML('partials/problem_files.html', { ...args, filetype: 'testdata' }));
if (d.includes('additional_file')) tasks.push(this.renderHTML('partials/problem_files.html', { ...args, filetype: 'additional_file' }));
if (!sidebar) tasks.push(this.renderHTML('partials/problem-sidebar-information.html', args));
this.response.body = {
fragments: (await Promise.all(tasks)).map((i) => ({ html: i })),
};
this.response.template = '';
} else this.response.template = 'problem_files.html';
}
@post('files', Types.Set)
@post('type', Types.Range(['testdata', 'additional_file']), true)
async postGetLinks(domainId: string, files: Set<string>, type = 'testdata') {
if (type === 'testdata' && !this.user.own(this.pdoc)) {
if (this.pdoc.reference) throw new ProblemIsReferencedError('download testdata.');
if (!this.user.hasPriv(PRIV.PRIV_READ_PROBLEM_DATA)) this.checkPerm(PERM.PERM_READ_PROBLEM_DATA);
if (this.tdoc && !contest.isDone(this.tdoc)) throw new ContestNotEndedError(this.tdoc.domainId, this.tdoc.docId);
}
if (this.pdoc.reference) this.pdoc = await problem.get(this.pdoc.reference.domainId, this.pdoc.reference.pid);
const links = {};
const size = Math.sum(
this.pdoc[type === 'testdata' ? 'data' : 'additional_file']
?.filter((i) => files.has(i.name))
?.map((i) => i.size),
) || 0;
await oplog.log(this, 'download.problem.bulk', {
target: Array.from(files).map((file) => `problem/${this.pdoc.domainId}/${this.pdoc.docId}/${type}/${file}`),
size,
});
for (const file of files) {
// eslint-disable-next-line no-await-in-loop
links[file] = await storage.signDownloadLink(
`problem/${this.pdoc.domainId}/${this.pdoc.docId}/${type}/${file}`,
file, false, 'user',
);
}
this.response.body.links = links;
}
@post('filename', Types.Filename, true)
@post('type', Types.Range(['testdata', 'additional_file']), true)
async postUploadFile(domainId: string, filename: string, type = 'testdata') {
if (this.pdoc.reference) throw new ProblemIsReferencedError('edit files');
if (!this.request.files.file) throw new ValidationError('file');
filename ||= this.request.files.file.originalFilename || String.random(16);
if (filename.includes('/') || filename.includes('..')) throw new ValidationError('filename', null, 'Bad filename');
if (!this.user.own(this.pdoc, PERM.PERM_EDIT_PROBLEM_SELF)) this.checkPerm(PERM.PERM_EDIT_PROBLEM);
const files = [];
if (filename.endsWith('.zip') && type === 'testdata') {
let zip: AdmZip;
try {
zip = new AdmZip(this.request.files.file.filepath);
} catch (e) {
throw new ValidationError('zip', null, e.message);
}
const entries = zip.getEntries();
for (const entry of entries) {
if (!entry.name) continue;
files.push({
type,
name: entry.name,
size: entry.header.size,
data: () => entry.getData(),
});
}
} else {
files.push({
type,
name: filename,
size: statSync(this.request.files.file.filepath).size,
data: () => this.request.files.file.filepath,
});
}
if (!this.user.hasPriv(PRIV.PRIV_EDIT_SYSTEM)) {
if ((this.pdoc.data?.length || 0)
+ (this.pdoc.additional_file?.length || 0)
+ files.length
>= system.get('limit.problem_files_max')) {
throw new FileLimitExceededError('count');
}
const size = Math.sum(
(this.pdoc.data || []).map((i) => i.size),
(this.pdoc.additional_file || []).map((i) => i.size),
files.map((i) => i.size),
);
if (size >= system.get('limit.problem_files_max_size')) {
throw new FileLimitExceededError('size');
}
}
for (const entry of files) {
const method = entry.type === 'testdata' ? 'addTestdata' : 'addAdditionalFile';
// eslint-disable-next-line no-await-in-loop
await problem[method](domainId, this.pdoc.docId, entry.name, entry.data(), this.user._id);
}
this.back();
}
@post('files', Types.ArrayOf(Types.Filename))
@post('type', Types.Range(['testdata', 'additional_file']), true)
async postDeleteFiles(domainId: string, files: string[], type = 'testdata') {
if (this.pdoc.reference) throw new ProblemIsReferencedError('delete files');
if (!this.user.own(this.pdoc, PERM.PERM_EDIT_PROBLEM_SELF)) this.checkPerm(PERM.PERM_EDIT_PROBLEM);
if (type === 'testdata') await problem.delTestdata(domainId, this.pdoc.docId, files, this.user._id);
else await problem.delAdditionalFile(domainId, this.pdoc.docId, files, this.user._id);
this.back();
}
}
export class ProblemFileDownloadHandler extends ProblemDetailHandler {
@query('type', Types.Range(['additional_file', 'testdata']), true)
@param('filename', Types.Filename)
@param('noDisposition', Types.Boolean)
async get(domainId: string, type = 'additional_file', filename: string, noDisposition = false) {
if (this.pdoc.reference) {
if (type === 'testdata') throw new ProblemIsReferencedError('download testdata');
this.pdoc = await problem.get(this.pdoc.reference.domainId, this.pdoc.reference.pid);
if (!this.pdoc) throw new ProblemNotFoundError();
}
if (type === 'testdata' && !this.user.own(this.pdoc)) {
if (!this.user.hasPriv(PRIV.PRIV_READ_PROBLEM_DATA)) this.checkPerm(PERM.PERM_READ_PROBLEM_DATA);
if (this.tdoc && !contest.isDone(this.tdoc)) throw new ContestNotEndedError(this.tdoc.domainId, this.tdoc.docId);
}
const target = `problem/${this.pdoc.domainId}/${this.pdoc.docId}/${type}/${filename}`;
const file = await storage.getMeta(target);
await oplog.log(this, 'download.problem.single', {
target,
size: file?.size || 0,
});
this.response.redirect = await storage.signDownloadLink(
target, noDisposition ? undefined : filename, false, 'user',
);
}
}
export class ProblemSolutionHandler extends ProblemDetailHandler {
@param('page', Types.PositiveInt, true)
@param('tid', Types.ObjectId, true)
@param('sid', Types.ObjectId, true)
async get(domainId: string, page = 1, tid?: ObjectId, sid?: ObjectId) {
if (tid) throw new PermissionError(PERM.PERM_VIEW_PROBLEM_SOLUTION);
this.response.template = 'problem_solution.html';
const accepted = this.tsdoc?.status === STATUS.STATUS_ACCEPTED;
if (!accepted || !this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_SOLUTION_ACCEPT)) {
this.checkPerm(PERM.PERM_VIEW_PROBLEM_SOLUTION);
}
// eslint-disable-next-line prefer-const
let [psdocs, pcount, pscount] = await paginate(
solution.getMulti(domainId, this.pdoc.docId),
page,
system.get('pagination.solution'),
);
if (sid) {
psdocs = [await solution.get(domainId, sid)];
if (!psdocs[0]) throw new SolutionNotFoundError(domainId, sid);
}
const uids = [this.pdoc.owner];
const docids = [];
for (const psdoc of psdocs) {
docids.push(psdoc.docId);
uids.push(psdoc.owner);
if (psdoc.reply.length) {
for (const psrdoc of psdoc.reply) uids.push(psrdoc.owner);
}
}
const udict = await user.getList(domainId, uids);
const pssdict = await solution.getListStatus(domainId, docids, this.user._id);
this.response.body = {
psdocs, page, pcount, pscount, udict, pssdict, pdoc: this.pdoc, sid,
};
}
@param('content', Types.Content)
async postSubmit(domainId: string, content: string) {
this.checkPerm(PERM.PERM_CREATE_PROBLEM_SOLUTION);
const psid = await solution.add(domainId, this.pdoc.docId, this.user._id, content);
this.back({ psid });
}
@param('content', Types.Content)
@param('psid', Types.ObjectId)
async postEditSolution(domainId: string, content: string, psid: ObjectId) {
let psdoc = await solution.get(domainId, psid);
if (!this.user.own(psdoc)) this.checkPerm(PERM.PERM_EDIT_PROBLEM_SOLUTION);
else this.checkPerm(PERM.PERM_EDIT_PROBLEM_SOLUTION_SELF);
psdoc = await solution.edit(domainId, psdoc.docId, content);
this.back({ psdoc });
}
@param('psid', Types.ObjectId)
async postDeleteSolution(domainId: string, psid: ObjectId) {
const psdoc = await solution.get(domainId, psid);
if (!this.user.own(psdoc)) this.checkPerm(PERM.PERM_DELETE_PROBLEM_SOLUTION);
else this.checkPerm(PERM.PERM_DELETE_PROBLEM_SOLUTION_SELF);
await solution.del(domainId, psdoc.docId);
this.back();
}
@param('psid', Types.ObjectId)
@param('content', Types.Content)
async postReply(domainId: string, psid: ObjectId, content: string) {
this.checkPerm(PERM.PERM_REPLY_PROBLEM_SOLUTION);
const psdoc = await solution.get(domainId, psid);
await solution.reply(domainId, psdoc.docId, this.user._id, content);
this.back();
}
@param('psid', Types.ObjectId)
@param('psrid', Types.ObjectId)
@param('content', Types.Content)
async postEditReply(domainId: string, psid: ObjectId, psrid: ObjectId, content: string) {
const [psdoc, psrdoc] = await solution.getReply(domainId, psid, psrid);
if ((!psdoc) || psdoc.parentId !== this.pdoc.docId) throw new SolutionNotFoundError(domainId, psid);
if (!(this.user.own(psrdoc)
&& this.user.hasPerm(PERM.PERM_EDIT_PROBLEM_SOLUTION_REPLY_SELF))) {
throw new PermissionError(PERM.PERM_EDIT_PROBLEM_SOLUTION_REPLY_SELF);
}
await solution.editReply(domainId, psid, psrid, content);
this.back();
}
@param('psid', Types.ObjectId)
@param('psrid', Types.ObjectId)
async postDeleteReply(domainId: string, psid: ObjectId, psrid: ObjectId) {
const [psdoc, psrdoc] = await solution.getReply(domainId, psid, psrid);
if ((!psdoc) || psdoc.parentId !== this.pdoc.docId) throw new SolutionNotFoundError(psid);
if (!(this.user.own(psrdoc)
&& this.user.hasPerm(PERM.PERM_DELETE_PROBLEM_SOLUTION_REPLY_SELF))) {
this.checkPerm(PERM.PERM_DELETE_PROBLEM_SOLUTION_REPLY);
}
await solution.delReply(domainId, psid, psrid);
this.back();
}
@param('psid', Types.ObjectId)
async postUpvote(domainId: string, psid: ObjectId) {
const [psdoc, pssdoc] = await solution.vote(domainId, psid, this.user._id, 1);
this.back({ vote: psdoc.vote, user_vote: pssdoc.vote });
}
@param('psid', Types.ObjectId)
async postDownvote(domainId: string, psid: ObjectId) {
const [psdoc, pssdoc] = await solution.vote(domainId, psid, this.user._id, -1);
this.back({ vote: psdoc.vote, user_vote: pssdoc.vote });
}
}
export class ProblemSolutionRawHandler extends ProblemDetailHandler {
@param('psid', Types.ObjectId)
@route('psrid', Types.ObjectId, true)
@param('tid', Types.ObjectId, true)
async get(domainId: string, psid: ObjectId, psrid?: ObjectId, tid?: ObjectId) {
if (tid) throw new PermissionError(PERM.PERM_VIEW_PROBLEM_SOLUTION);
const accepted = this.tsdoc?.status === STATUS.STATUS_ACCEPTED;
if (!accepted || !this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_SOLUTION_ACCEPT)) {
this.checkPerm(PERM.PERM_VIEW_PROBLEM_SOLUTION);
}
if (psrid) {
const [psdoc, psrdoc] = await solution.getReply(domainId, psid, psrid);
if ((!psdoc) || psdoc.parentId !== this.pdoc.docId) throw new SolutionNotFoundError(psid, psrid);
this.response.body = psrdoc.content;
} else {
const psdoc = await solution.get(domainId, psid);
this.response.body = psdoc.content;
}
this.response.type = 'text/markdown';
}
}
export class ProblemCreateHandler extends Handler {
async get() {
this.response.template = 'problem_edit.html';
this.response.body = {
page_name: 'problem_create',
additional_file: [],
};
}
@post('title', Types.Title)
@post('content', Types.Content)
@post('pid', Types.ProblemId, true, (i) => /^[a-zA-Z]+[a-zA-Z0-9]*$/i.test(i))
@post('hidden', Types.Boolean)
@post('difficulty', Types.PositiveInt, (i) => +i <= 10, true)
@post('tag', Types.Content, true, null, parseCategory)
async post(
domainId: string, title: string, content: string, pid: string | number = '',
hidden = false, difficulty = 0, tag: string[] = [],
) {
if (typeof pid !== 'string') pid = `P${pid}`;
if (pid && await problem.get(domainId, pid)) throw new ProblemAlreadyExistError(pid);
const docId = await problem.add(domainId, pid, title, content, this.user._id, tag ?? [], hidden);
const files = new Set(Array.from(content.matchAll(/file:\/\/([a-zA-Z0-9_-]+\.[a-zA-Z0-9]+)/g)).map((i) => i[1]));
const tasks = [];
for (const file of files) {
if (this.user._files.find((i) => i.name === file)) {
tasks.push(
storage.rename(`user/${this.user._id}/${file}`, `problem/${domainId}/${docId}/additional_file/${file}`, this.user._id)
.then(() => problem.addAdditionalFile(domainId, docId, file, '', this.user._id, true)),
user.setById(this.user._id, { _files: this.user._files.filter((i) => i.name !== file) }),
);
}
}
await Promise.all(tasks);
if (difficulty) await problem.edit(domainId, docId, { difficulty });
this.response.body = { pid: pid || docId };
this.response.redirect = this.url('problem_files', { pid: pid || docId });
}
}