core: !EXPERIMENTAL! 支持跨域引用题目

This commit is contained in:
undefined committed 2021-05-28 22:10:16 +08:00
1 parent 33d7c70ef6
commit d897391e9a
25 files changed
+434 -392

No files matched your search

+79 -124
View File
@@ -1,11 +1,14 @@
import moment from 'moment-timezone';
import { ObjectID } from 'mongodb';
import AdmZip from 'adm-zip';
import { Time } from '@hydrooj/utils/lib/utils';
import {
ContestNotLiveError, ValidationError, ProblemNotFoundError,
ContestNotAttendedError, PermissionError, BadRequestError,
} from '../error';
import { ProblemDoc, Tdoc, User } from '../interface';
import {
ProblemId, ProblemDoc, Tdoc, User,
} from '../interface';
import paginate from '../lib/paginate';
import { PERM, PRIV } from '../model/builtin';
import * as contest from '../model/contest';
@@ -22,23 +25,13 @@ import {
import * as bus from '../service/bus';
import storage from '../service/storage';
class ContestListHandler extends Handler {
export class ContestListHandler extends Handler {
@param('rule', Types.Range(contest.RULES), true)
@param('page', Types.PositiveInt, true)
async get(domainId: string, rule = '', page = 1) {
this.response.template = 'contest_main.html';
let tdocs;
let qs;
let tpcount;
if (!rule) {
tdocs = contest.getMulti(domainId).sort({ beginAt: -1 });
qs = '';
} else {
tdocs = contest.getMulti(domainId, { rule }).sort({ beginAt: -1 });
qs = `rule=${rule}`;
}
// eslint-disable-next-line prefer-const
[tdocs, tpcount] = await paginate(tdocs, page, system.get('pagination.contest'));
const cursor = contest.getMulti(domainId, rule ? { rule } : undefined).sort({ beginAt: -1 });
const qs = rule ? `rule=${rule}` : '';
const [tdocs, tpcount] = await paginate(cursor, page, system.get('pagination.contest'));
const tids = [];
for (const tdoc of tdocs) tids.push(tdoc.docId);
const tsdict = await contest.getListStatus(domainId, this.user._id, tids);
@@ -46,13 +39,14 @@ class ContestListHandler extends Handler {
['Hydro', 'homepage'],
['contest_main', null],
];
this.response.template = 'contest_main.html';
this.response.body = {
page, tpcount, qs, rule, tdocs, tsdict, path,
};
}
}
class ContestDetailHandler extends Handler {
export class ContestDetailHandler extends Handler {
@param('tid', Types.ObjectID)
@param('page', Types.PositiveInt, true)
async get(domainId: string, tid: ObjectID, page = 1) {
@@ -165,42 +159,49 @@ class ContestScoreboardDownloadHandler extends Handler {
}
}
class ContestEditHandler extends Handler {
export class ContestEditHandler extends Handler {
tdoc: Tdoc;
@param('tid', Types.ObjectID)
@param('tid', Types.ObjectID, true)
async prepare(domainId: string, tid: ObjectID) {
this.tdoc = await contest.get(domainId, tid);
if (!this.user.own(this.tdoc)) this.checkPerm(PERM.PERM_EDIT_CONTEST);
else this.checkPerm(PERM.PERM_EDIT_CONTEST_SELF);
if (tid) {
this.tdoc = await contest.get(domainId, tid);
if (!this.user.own(this.tdoc)) this.checkPerm(PERM.PERM_EDIT_CONTEST);
else this.checkPerm(PERM.PERM_EDIT_CONTEST_SELF);
}
}
async get() {
@param('tid', Types.ObjectID, true)
async get(domainId: string, tid: ObjectID) {
this.response.template = 'contest_edit.html';
const rules = {};
for (const i in contest.RULES) {
rules[i] = contest.RULES[i].TEXT;
}
const duration = (this.tdoc.endAt.getTime() - this.tdoc.beginAt.getTime()) / 3600 / 1000;
for (const i in contest.RULES) rules[i] = contest.RULES[i].TEXT;
const path = [
['Hydro', 'homepage'],
['contest_main', 'contest_main'],
[this.tdoc.title, 'contest_detail', { tid: this.tdoc.docId }, true],
['contest_edit', null],
...tid
? [
[this.tdoc.title, 'contest_detail', { tid: this.tdoc.docId }, true],
['contest_edit', null],
]
: [['contest_create', null]],
];
const dt = this.tdoc.beginAt;
let ts = new Date().getTime();
ts = ts - (ts % (15 * Time.minute)) + 15 * Time.minute;
const dt = this.tdoc?.beginAt || new Date(ts);
this.response.body = {
rules,
tdoc: this.tdoc,
duration,
duration: tid ? (this.tdoc.endAt.getTime() - this.tdoc.beginAt.getTime()) / Time.hour : 2,
path,
pids: this.tdoc.pids.join(','),
pids: tid ? this.tdoc.pids.join(',') : '',
date_text: dt.format('%Y-%m-%d'),
time_text: dt.format('%H:%M'),
page_name: 'contest_edit',
page_name: tid ? 'contest_edit' : 'contest_create',
};
}
@param('tid', Types.ObjectID, true)
@param('beginAtDate', Types.Date)
@param('beginAtTime', Types.Time)
@param('duration', Types.Float)
@@ -210,31 +211,36 @@ class ContestEditHandler extends Handler {
@param('pids', Types.Content)
@param('rated', Types.Boolean)
async post(
domainId: string, beginAtDate: string, beginAtTime: string, duration: number,
domainId: string, tid: ObjectID, beginAtDate: string, beginAtTime: string, duration: number,
title: string, content: string, rule: string, _pids: string, rated = false,
) {
const pids = _pids.replace(/,/g, ',').split(',').map((i) => +i).filter((i) => i);
await problem.getList(domainId, pids, this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN), true);
const pids = _pids.replace(/,/g, ',').split(',').map((i) => {
if ((+i).toString() === i) return +i;
return i;
}).filter((i) => i);
const beginAtMoment = moment.tz(`${beginAtDate} ${beginAtTime}`, this.user.timeZone);
if (!beginAtMoment.isValid()) {
throw new ValidationError('beginAtDate', 'beginAtTime');
}
if (!beginAtMoment.isValid()) throw new ValidationError('beginAtDate', 'beginAtTime');
const endAt = beginAtMoment.clone().add(duration, 'hours').toDate();
if (beginAtMoment.isSameOrAfter(endAt)) throw new ValidationError('duration');
const beginAt = beginAtMoment.toDate();
await contest.edit(domainId, this.tdoc.docId, {
title, content, rule, beginAt, endAt, pids, rated,
});
if (this.tdoc.beginAt !== beginAt || this.tdoc.endAt !== endAt
|| Array.isDiff(this.tdoc.pids, pids) || this.tdoc.rule !== rule) {
await contest.recalcStatus(domainId, this.tdoc.docId);
await problem.getList(domainId, pids, this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN), true);
if (tid) {
await contest.edit(domainId, tid, {
title, content, rule, beginAt, endAt, pids, rated,
});
if (this.tdoc.beginAt !== beginAt || this.tdoc.endAt !== endAt
|| Array.isDiff(this.tdoc.pids, pids) || this.tdoc.rule !== rule) {
await contest.recalcStatus(domainId, this.tdoc.docId);
}
} else {
tid = await contest.add(domainId, title, content, this.user._id, rule, beginAt, endAt, pids, rated);
}
this.response.body = { tid: this.tdoc.docId };
this.response.redirect = this.url('contest_detail', { tid: this.tdoc.docId });
this.response.body = { tid };
this.response.redirect = this.url('contest_detail', { tid });
}
}
class ContestProblemHandler extends Handler {
export class ContestProblemHandler extends Handler {
tdoc: Tdoc<30 | 60>;
pdoc: ProblemDoc;
tsdoc: any;
@@ -242,25 +248,22 @@ class ContestProblemHandler extends Handler {
attended: boolean;
@param('tid', Types.ObjectID)
@param('pid', Types.UnsignedInt)
async _prepare(domainId: string, tid: ObjectID, pid: number) {
[this.tdoc, this.pdoc] = await Promise.all([
contest.get(domainId, tid),
@param('pid', Types.Name)
async _prepare(domainId: string, tid: ObjectID, pid: ProblemId) {
this.tdoc = await contest.get(domainId, tid);
if (!this.tdoc.pids.includes(pid)) throw new ProblemNotFoundError(domainId, pid);
[this.pdoc, this.tsdoc, this.udoc] = await Promise.all([
problem.get(domainId, pid),
]);
[this.tsdoc, this.udoc] = await Promise.all([
contest.getStatus(domainId, this.tdoc.docId, this.user._id),
contest.getStatus(domainId, tid, this.user._id),
user.getById(domainId, this.tdoc.owner),
]);
if (!this.pdoc) throw new ProblemNotFoundError(domainId, pid);
// @ts-ignore
if (this.pdoc.domainId !== domainId) this.pdoc.docId = `${this.pdoc.domainId}:${this.pdoc.docId}`;
this.attended = this.tsdoc && this.tsdoc.attend === 1;
if (contest.isNotStarted(this.tdoc)) throw new ContestNotLiveError(tid);
if (!contest.isDone(this.tdoc) && !this.attended) throw new ContestNotAttendedError(tid);
this.response.template = 'problem_detail.html';
if (!contest.isDone(this.tdoc)) {
if (!this.attended) throw new ContestNotAttendedError(this.tdoc.docId);
if (contest.isNotStarted(this.tdoc)) throw new ContestNotLiveError(this.tdoc.docId);
}
if (!this.tdoc.pids.map((s) => s.toString()).includes(this.pdoc.docId.toString())) {
throw new ProblemNotFoundError(domainId, this.tdoc.docId);
}
this.response.body = {
tdoc: this.tdoc,
tsdoc: this.tsdoc,
@@ -271,18 +274,19 @@ class ContestProblemHandler extends Handler {
};
}
// eslint-disable-next-line
@param('tid', Types.ObjectID)
@param('pid', Types.Name)
async get(...args: any[]) {
this.response.body.path = [
['Hydro', 'homepage'],
['contest_main', 'contest_main'],
[this.tdoc.title, 'contest_detail', { tid: this.tdoc.docId }, true],
[this.tdoc.title, 'contest_detail', { tid: args[1] }, true],
[this.pdoc.title, null, null, true],
];
// Navigate to current additional file download
// e.g. ![img](a.jpg) will navigate to ![img](./pid/file/a.jpg)
this.response.body.pdoc.content = this.response.body.pdoc.content
.replace(/\(file:\/\//g, `(./${this.pdoc.docId}/file/`);
.replace(/\(file:\/\//g, `(./${args[2]}/file/`);
}
}
@@ -301,19 +305,19 @@ export class ContestProblemFileDownloadHandler extends ContestProblemHandler {
}
}
class ContestDetailProblemSubmitHandler extends ContestProblemHandler {
export class ContestDetailProblemSubmitHandler extends ContestProblemHandler {
async prepare() {
if (!contest.isOngoing(this.tdoc)) throw new ContestNotLiveError(this.tdoc.docId);
}
@param('tid', Types.ObjectID)
@param('pid', Types.UnsignedInt)
async get(domainId: string, tid: ObjectID, pid: number) {
@param('pid', Types.Name)
async get(domainId: string, tid: ObjectID, pid: ProblemId) {
this.response.body.rdocs = [];
if (contest.canShowRecord.call(this, this.tdoc)) {
this.response.body.rdocs = await record.getUserInProblemMulti(
domainId, this.user._id,
this.pdoc.docId, true,
pid, { type: document.TYPE_CONTEST, tid },
).sort({ _id: -1 }).limit(10).toArray();
}
this.response.body.path = [
@@ -330,20 +334,21 @@ class ContestDetailProblemSubmitHandler extends ContestProblemHandler {
@param('tid', Types.ObjectID)
@param('lang', Types.Name)
@param('code', Types.Content)
async post(domainId: string, tid: ObjectID, lang: string, code: string) {
@param('pid', Types.Name)
async post(domainId: string, tid: ObjectID, lang: string, code: string, pid: ProblemId) {
if (this.response.body.pdoc.config?.langs && !this.response.body.pdoc.config.langs.includes(lang)) {
throw new BadRequestError('Language not allowed.');
}
await this.limitRate('add_record', 60, 10);
const rid = await record.add(domainId, this.pdoc.docId, this.user._id, lang, code, true, {
const rid = await record.add(domainId, pid, this.user._id, lang, code, true, {
type: document.TYPE_CONTEST,
tid,
});
const [rdoc] = await Promise.all([
record.get(domainId, rid),
problem.inc(domainId, this.pdoc.docId, 'nSubmit', 1),
problem.inc(domainId, pid, 'nSubmit', 1),
domain.incUserInDomain(domainId, this.user._id, 'nSubmit'),
contest.updateStatus(domainId, this.tdoc.docId, this.user._id, rid, this.pdoc.docId),
contest.updateStatus(domainId, tid, this.user._id, rid, pid),
]);
bus.boardcast('record/change', rdoc);
if (!contest.canShowRecord.call(this, this.tdoc)) {
@@ -356,7 +361,7 @@ class ContestDetailProblemSubmitHandler extends ContestProblemHandler {
}
}
class ContestCodeHandler extends Handler {
export class ContestCodeHandler extends Handler {
@param('tid', Types.ObjectID)
async get(domainId: string, tid: ObjectID) {
if (!this.user.hasPriv(PRIV.PRIV_READ_RECORD_CODE)) {
@@ -381,58 +386,8 @@ class ContestCodeHandler extends Handler {
}
}
class ContestCreateHandler extends Handler {
async get() {
this.response.template = 'contest_edit.html';
const rules = {};
for (const i in contest.RULES) rules[i] = contest.RULES[i].TEXT;
const now = new Date();
let ts = now.getTime();
ts = ts - (ts % (15 * 60 * 1000)) + 15 * 60 * 1000;
const dt = new Date(ts);
const path = [
['Hydro', 'homepage'],
['contest_main', 'contest_main'],
['contest_create', null],
];
this.response.body = {
rules,
path,
page_name: 'contest_create',
date_text: dt.format('%Y-%m-%d'),
time_text: dt.format('%H:%M'),
pids: '1000, 1001',
};
}
@param('beginAtDate', Types.Date)
@param('beginAtTime', Types.Time)
@param('duration', Types.Float)
@param('title', Types.Title)
@param('content', Types.Content)
@param('rule', Types.Name)
@param('pids', Types.Content)
@param('rated', Types.Boolean)
async post(
domainId: string, beginAtDate: string, beginAtTime: string, duration: number,
title: string, content: string, rule: string, _pids: string, rated = false,
) {
const pids = _pids.replace(/,/g, ',').split(',').map((i) => +i).filter((i) => i);
const beginAt = moment.tz(`${beginAtDate} ${beginAtTime}`, this.user.timeZone);
if (!beginAt.isValid()) throw new ValidationError('beginAtDate', 'beginAtTime');
const endAt = beginAt.clone().add(duration, 'hours').toDate();
await problem.getList(domainId, pids, this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN), true);
const tid = await contest.add(
domainId, title, content,
this.user._id, rule, beginAt.toDate(), endAt, pids, rated,
);
this.response.body = { tid };
this.response.redirect = this.url('contest_detail', { tid });
}
}
export async function apply() {
Route('contest_create', '/contest/create', ContestCreateHandler, PERM.PERM_CREATE_CONTEST);
Route('contest_create', '/contest/create', ContestEditHandler, PERM.PERM_CREATE_CONTEST);
Route('contest_main', '/contest', ContestListHandler, PERM.PERM_VIEW_CONTEST);
Route('contest_detail', '/contest/:tid', ContestDetailHandler, PERM.PERM_VIEW_CONTEST);
Route('contest_boardcast', '/contest/:tid/boardcast', ContestBoardcastHandler);
+2 -2
View File
@@ -11,7 +11,7 @@ import {
Route, Connection, Handler, ConnectionHandler, param, Types,
} from '../service/server';
import { md5 } from '../lib/crypto';
import { isPassword, isEmail } from '../lib/validator';
import { isPassword, isEmail, isDomainId } from '../lib/validator';
import avatar from '../lib/avatar';
import * as mail from '../lib/mail';
import * as contest from '../model/contest';
@@ -321,7 +321,7 @@ class HomeDomainCreateHandler extends Handler {
this.response.template = 'domain_create.html';
}
@param('id', Types.Name)
@param('id', Types.Name, isDomainId)
@param('name', Types.Title)
@param('bulletin', Types.Content)
@param('avatar', Types.Content, true)
+77 -121
View File
@@ -2,13 +2,13 @@ import yaml from 'js-yaml';
import moment from 'moment-timezone';
import { ObjectID } from 'mongodb';
import AdmZip from 'adm-zip';
import { Time } from '@hydrooj/utils/lib/utils';
import {
ValidationError, HomeworkNotLiveError, ProblemNotFoundError,
HomeworkNotAttendedError,
BadRequestError,
HomeworkNotAttendedError, BadRequestError,
} from '../error';
import {
PenaltyRules, Tdoc, ProblemDoc, User,
PenaltyRules, Tdoc, ProblemDoc, User, ProblemId,
} from '../interface';
import {
Route, Handler, Types, param,
@@ -24,11 +24,9 @@ import problem from '../model/problem';
import record from '../model/record';
import * as document from '../model/document';
import paginate from '../lib/paginate';
import { isExternalPid } from '../lib/validator';
const validatePenaltyRules = (input: string) => {
const s = yaml.load(input);
return s;
};
const validatePenaltyRules = (input: string) => yaml.load(input);
const convertPenaltyRules = validatePenaltyRules;
class HomeworkMainHandler extends Handler {
@@ -40,9 +38,7 @@ class HomeworkMainHandler extends Handler {
if (contest.isExtended(tdoc) || contest.isDone(tdoc)) {
cal.endAt = tdoc.endAt;
cal.penaltySince = tdoc.penaltySince;
} else {
cal.endAt = tdoc.penaltySince;
}
} else cal.endAt = tdoc.penaltySince;
calendar.push(cal);
}
const path = [
@@ -126,12 +122,14 @@ class HomeworkDetailProblemHandler extends Handler {
attended: boolean;
@param('tid', Types.ObjectID)
@param('pid', Types.UnsignedInt)
async prepare(domainId: string, tid: ObjectID, pid: number) {
this.checkPerm(PERM.PERM_VIEW_PROBLEM);
@param('pid', Types.String, isExternalPid)
async _prepare(domainId: string, tid: ObjectID, pid: ProblemId) {
if (!this.tdoc.pids.includes(pid)) throw new ProblemNotFoundError(domainId, pid, tid);
const pdomainId = typeof pid === 'string' ? pid.split(':')[0] : domainId;
const ppid = typeof pid === 'number' ? pid : +pid.split(':')[1];
[this.tdoc, this.pdoc, this.tsdoc] = await Promise.all([
contest.get(domainId, tid, document.TYPE_HOMEWORK),
problem.get(domainId, pid),
problem.get(pdomainId, ppid),
contest.getStatus(domainId, tid, this.user._id, document.TYPE_HOMEWORK),
]);
this.udoc = await user.getById(domainId, this.tdoc.owner);
@@ -146,13 +144,13 @@ class HomeworkDetailProblemHandler extends Handler {
}
@param('tid', Types.ObjectID)
@param('pid', Types.UnsignedInt)
async get(domainId: string, tid: ObjectID, pid: number) {
@param('pid', Types.Name)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async get(domainId: string, tid: ObjectID, pid: ProblemId) {
if (!contest.isDone(this.tdoc)) {
if (!this.attended) throw new HomeworkNotAttendedError(tid);
if (contest.isNotStarted(this.tdoc)) throw new HomeworkNotLiveError(tid);
}
if (!this.tdoc.pids.includes(pid)) throw new ProblemNotFoundError(domainId, pid, tid);
this.response.template = 'problem_detail.html';
this.response.body.page_name = 'homework_detail_problem';
this.response.body.path = [
@@ -166,13 +164,16 @@ class HomeworkDetailProblemHandler extends Handler {
class HomeworkDetailProblemSubmitHandler extends HomeworkDetailProblemHandler {
@param('tid', Types.ObjectID)
@param('pid', Types.UnsignedInt)
async get(domainId: string, tid: ObjectID, pid: number) {
async prepare(domainId: string, tid: ObjectID) {
if (!this.attended) throw new HomeworkNotAttendedError(tid);
if (!contest.isOngoing(this.tdoc)) throw new HomeworkNotLiveError(tid);
if (!this.tdoc.pids.includes(pid)) throw new ProblemNotFoundError(domainId, pid, tid);
}
@param('tid', Types.ObjectID)
@param('pid', Types.String, isExternalPid)
async get(domainId: string, tid: ObjectID, pid: ProblemId) {
this.response.body.rdocs = contest.canShowRecord.call(this, this.tdoc)
? await record.getUserInProblemMulti(domainId, this.user._id, pid, true)
? await record.getUserInProblemMulti(domainId, this.user._id, pid, { type: document.TYPE_HOMEWORK, tid })
.sort('_id', -1).limit(10).toArray()
: [];
this.response.body.path = [
@@ -186,24 +187,23 @@ class HomeworkDetailProblemSubmitHandler extends HomeworkDetailProblemHandler {
}
@param('tid', Types.ObjectID)
@param('pid', Types.UnsignedInt)
@param('pid', Types.String, isExternalPid)
@param('code', Types.Content)
@param('lang', Types.Name)
async post(domainId: string, tid: ObjectID, pid: number, code: string, lang: string) {
async post(domainId: string, tid: ObjectID, pid: ProblemId, code: string, lang: string) {
if (this.response.body.pdoc.config?.langs && !this.response.body.pdoc.config.langs.includes(lang)) {
throw new BadRequestError('Language not allowed.');
}
await this.limitRate('add_record', 60, 5);
if (!this.attended) throw new HomeworkNotAttendedError(tid);
if (!contest.isOngoing(this.tdoc)) throw new HomeworkNotLiveError(tid);
if (!this.tdoc.pids.includes(pid)) throw new ProblemNotFoundError(domainId, pid);
const rid = await record.add(domainId, pid, this.user._id, lang, code, true, {
type: document.TYPE_HOMEWORK,
tid,
});
const pdomainId = typeof pid === 'string' ? pid.split(':')[0] : domainId;
const ppid = typeof pid === 'number' ? pid : +pid.split(':')[1];
const [rdoc] = await Promise.all([
record.get(domainId, rid),
problem.inc(domainId, pid, 'nSubmit', 1),
problem.inc(pdomainId, ppid, 'nSubmit', 1),
domain.incUserInDomain(domainId, this.user._id, 'nSubmit'),
contest.updateStatus(domainId, tid, this.user._id,
rid, pid, false, 0, document.TYPE_HOMEWORK),
@@ -216,77 +216,35 @@ class HomeworkDetailProblemSubmitHandler extends HomeworkDetailProblemHandler {
}
}
class HomeworkCreateHandler extends Handler {
async get() {
const beginAt = moment().add(1, 'day');
const penaltySince = beginAt.clone().add(7, 'days');
const path = [
['Hydro', 'homepage'],
['homework_main', 'homework_main'],
['homework_create', null],
];
this.response.template = 'homework_edit.html';
this.response.body = {
path,
dateBeginText: beginAt.tz(this.user.timeZone).format('YYYY-M-D'),
timeBeginText: '00:00',
datePenaltyText: penaltySince.tz(this.user.timeZone).format('YYYY-M-D'),
timePenaltyText: '23:59',
pids: '1000, 1001',
extensionDays: 1,
page_name: 'homework_create',
};
}
@param('beginAtDate', Types.Date)
@param('beginAtTime', Types.Time)
@param('penaltySinceDate', Types.Date)
@param('penaltySinceTime', Types.Time)
@param('extensionDays', Types.Float)
@param('penaltyRules', Types.Content, validatePenaltyRules, convertPenaltyRules)
@param('title', Types.Title)
@param('content', Types.Content)
@param('pids', Types.Content)
@param('rated', Types.Boolean)
async post(
domainId: string, beginAtDate: string, beginAtTime: string,
penaltySinceDate: string, penaltySinceTime: string, extensionDays: number,
penaltyRules: PenaltyRules, title: string, content: string, _pids: string, rated = false,
) {
const pids = _pids.replace(/,/g, ',').split(',').map((i) => +i).filter((i) => i);
const beginAt = moment.tz(`${beginAtDate} ${beginAtTime}`, this.user.timeZone);
if (!beginAt.isValid()) throw new ValidationError('beginAtDate', 'beginAtTime');
const penaltySince = moment.tz(`${penaltySinceDate} ${penaltySinceTime}`, this.user.timeZone);
if (!penaltySince.isValid()) throw new ValidationError('endAtDate', 'endAtTime');
const endAt = penaltySince.clone().add(extensionDays, 'days');
if (beginAt.isSameOrAfter(penaltySince)) throw new ValidationError('endAtDate', 'endAtTime');
if (penaltySince.isAfter(endAt)) throw new ValidationError('extensionDays');
await problem.getList(domainId, pids, this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN), true);
const tid = await contest.add(domainId, title, content, this.user._id,
'homework', beginAt.toDate(), endAt.toDate(), pids, rated,
{ penaltySince: penaltySince.toDate(), penaltyRules }, document.TYPE_HOMEWORK);
this.response.body = { tid };
this.response.redirect = this.url('homework_detail', { tid });
}
}
class HomeworkEditHandler extends Handler {
@param('tid', Types.ObjectID)
@param('tid', Types.ObjectID, true)
async get(domainId: string, tid: ObjectID) {
const tdoc = await contest.get(domainId, tid, document.TYPE_HOMEWORK);
const tdoc = tid
? await contest.get(domainId, tid, document.TYPE_HOMEWORK)
: null;
if (!this.user.own(tdoc)) this.checkPerm(PERM.PERM_EDIT_HOMEWORK);
else this.checkPerm(PERM.PERM_EDIT_HOMEWORK_SELF);
const extensionDays = Math.round(
(tdoc.endAt.getTime() - tdoc.penaltySince.getTime()) / 36000 / 24,
) / 100;
const extensionDays = tid
? Math.round(
(tdoc.endAt.getTime() - tdoc.penaltySince.getTime()) / (Time.day / 100),
) / 100
: 1;
const path = [
['Hydro', 'homepage'],
['homework_main', 'homework_main'],
[tdoc.title, 'homework_detail', { tid }, true],
['homework_edit', null],
...tid
? [
[tdoc.title, 'homework_detail', { tid }, true],
['homework_edit', null],
]
: [['homework_create', null]],
];
const beginAt = moment(tdoc.beginAt).tz(this.user.timeZone);
const penaltySince = moment(tdoc.penaltySince).tz(this.user.timeZone);
const beginAt = tid
? moment(tdoc.beginAt).tz(this.user.timeZone)
: moment().add(1, 'day').tz(this.user.timeZone).hour(0).minute(0).millisecond(0);
const penaltySince = tid
? moment(tdoc.penaltySince).tz(this.user.timeZone)
: beginAt.clone().add(7, 'days').tz(this.user.timeZone).hour(23).minute(59).millisecond(0);
this.response.template = 'homework_edit.html';
this.response.body = {
tdoc,
@@ -298,10 +256,11 @@ class HomeworkEditHandler extends Handler {
penaltyRules: yaml.dump(tdoc.penaltyRules),
pids: tdoc.pids.join(','),
path,
page_name: tid ? 'homework_edit' : 'homework_create',
};
}
@param('tid', Types.ObjectID)
@param('tid', Types.ObjectID, true)
@param('beginAtDate', Types.Date)
@param('beginAtTime', Types.Time)
@param('penaltySinceDate', Types.Date)
@@ -315,38 +274,37 @@ class HomeworkEditHandler extends Handler {
async post(
domainId: string, tid: ObjectID, beginAtDate: string, beginAtTime: string,
penaltySinceDate: string, penaltySinceTime: string, extensionDays: number,
penaltyRules: string, title: string, content: string, _pids: string, rated = false,
penaltyRules: PenaltyRules, title: string, content: string, _pids: string, rated = false,
) {
const pids = _pids.replace(/,/g, ',').split(',').map((i) => +i).filter((i) => i);
const pids = _pids.replace(/,/g, ',').split(',').map((i) => {
if ((+i).toString() === i) return +i;
return i;
}).filter((i) => i);
const tdoc = await contest.get(domainId, tid, document.TYPE_HOMEWORK);
if (!this.user.own(tdoc)) this.checkPerm(PERM.PERM_EDIT_HOMEWORK);
else this.checkPerm(PERM.PERM_EDIT_HOMEWORK_SELF);
let beginAt;
let penaltySince;
try {
beginAt = moment.tz(`${beginAtDate} ${beginAtTime}`, this.user.timeZone);
} catch (e) {
throw new ValidationError('beginAtDate', 'beginAtTime');
}
try {
penaltySince = moment.tz(`${penaltySinceDate} ${penaltySinceTime}`, this.user.timeZone);
} catch (e) {
throw new ValidationError('endAtDate', 'endAtTime');
}
let endAt = penaltySince.clone().add(extensionDays, 'days');
const beginAt = moment.tz(`${beginAtDate} ${beginAtTime}`, this.user.timeZone);
if (!beginAt.isValid()) throw new ValidationError('beginAtDate', 'beginAtTime');
const penaltySince = moment.tz(`${penaltySinceDate} ${penaltySinceTime}`, this.user.timeZone);
if (!penaltySince.isValid()) throw new ValidationError('endAtDate', 'endAtTime');
const endAt = penaltySince.clone().add(extensionDays, 'days');
if (beginAt.isSameOrAfter(penaltySince)) throw new ValidationError('endAtDate', 'endAtTime');
if (penaltySince.isAfter(endAt)) throw new ValidationError('extensionDays');
await problem.getList(domainId, pids, this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN), true);
beginAt = beginAt.toDate();
endAt = endAt.toDate();
penaltySince = penaltySince.toDate();
await contest.edit(domainId, tid, {
title, content, beginAt, endAt, pids, penaltySince, penaltyRules, rated,
}, document.TYPE_HOMEWORK);
if (tdoc.beginAt !== beginAt
|| tdoc.endAt !== endAt
|| tdoc.penaltySince !== penaltySince
|| tdoc.pids.sort().join(' ') !== pids.sort().join(' ')) {
await contest.recalcStatus(domainId, tdoc.docId, document.TYPE_HOMEWORK);
if (!tid) {
tid = await contest.add(domainId, title, content, this.user._id,
'homework', beginAt.toDate(), endAt.toDate(), pids, rated,
{ penaltySince: penaltySince.toDate(), penaltyRules }, document.TYPE_HOMEWORK);
} else {
await contest.edit(domainId, tid, {
title, content, beginAt: beginAt.toDate(), endAt: endAt.toDate(), pids, penaltySince: penaltySince.toDate(), penaltyRules, rated,
}, document.TYPE_HOMEWORK);
if (tdoc.beginAt !== beginAt.toDate()
|| tdoc.endAt !== endAt.toDate()
|| tdoc.penaltySince !== penaltySince.toDate()
|| tdoc.pids.sort().join(' ') !== pids.sort().join(' ')) {
await contest.recalcStatus(domainId, tdoc.docId, document.TYPE_HOMEWORK);
}
}
this.response.body = { tid };
this.response.redirect = this.url('homework_detail', { tid });
@@ -405,9 +363,7 @@ class HomeworkCodeHandler extends Handler {
}
const zip = new AdmZip();
const rdocs = await record.getMulti(domainId, {
_id: {
$in: Array.from(Object.keys(rnames)).map((id) => new ObjectID(id)),
},
_id: { $in: Array.from(Object.keys(rnames)).map((id) => new ObjectID(id)) },
}).toArray();
for (const rdoc of rdocs) {
zip.addFile(`${rnames[rdoc._id.toHexString()]}.${rdoc.lang}`, Buffer.from(rdoc.code));
@@ -418,7 +374,7 @@ class HomeworkCodeHandler extends Handler {
export async function apply() {
Route('homework_main', '/homework', HomeworkMainHandler, PERM.PERM_VIEW_HOMEWORK);
Route('homework_create', '/homework/create', HomeworkCreateHandler, PERM.PERM_CREATE_HOMEWORK);
Route('homework_create', '/homework/create', HomeworkEditHandler, PERM.PERM_CREATE_HOMEWORK);
Route('homework_detail', '/homework/:tid', HomeworkDetailHandler, PERM.PERM_VIEW_HOMEWORK);
Route('homework_scoreboard', '/homework/:tid/scoreboard', HomeworkScoreboardHandler, PERM.PERM_VIEW_HOMEWORK_SCOREBOARD);
Route(
+12 -8
View File
@@ -23,16 +23,20 @@ const logger = new Logger('judge');
async function _postJudge(rdoc: RecordDoc) {
if (typeof rdoc.input === 'string') return;
const accept = rdoc.status === builtin.STATUS.STATUS_ACCEPTED;
const updated = await problem.updateStatus(rdoc.domainId, rdoc.pid, rdoc.uid, rdoc._id, rdoc.status, rdoc.score);
const updated = await problem.updateStatus(rdoc.pdomain, rdoc.pid, rdoc.uid, rdoc._id, rdoc.status, rdoc.score);
if (rdoc.contest) {
await contest.updateStatus(
rdoc.domainId, rdoc.contest.tid, rdoc.uid,
rdoc._id, rdoc.pid, accept, rdoc.score, rdoc.contest.type,
);
await contest.updateStatus(
rdoc.domainId, rdoc.contest.tid, rdoc.uid,
rdoc._id, `${rdoc.pdomain}:${rdoc.pid}`, accept, rdoc.score, rdoc.contest.type,
);
} else if (accept && updated) await domain.incUserInDomain(rdoc.domainId, rdoc.uid, 'nAccept', 1);
const pdoc = (accept && updated)
? await problem.inc(rdoc.domainId, rdoc.pid, 'nAccept', 1)
: await problem.get(rdoc.domainId, rdoc.pid);
? await problem.inc(rdoc.pdomain, rdoc.pid, 'nAccept', 1)
: await problem.get(rdoc.pdomain, rdoc.pid);
const difficulty = difficultyAlgorithm(pdoc.nSubmit, pdoc.nAccept);
if (!updated) await record.updateMulti(rdoc.domainId, { uid: rdoc.uid, status: builtin.STATUS.STATUS_ACCEPTED }, { effective: false });
await Promise.all([
@@ -45,8 +49,8 @@ async function _postJudge(rdoc: RecordDoc) {
}
export async function next(body: JudgeResultBody) {
if (body.rid) body.rid = new ObjectID(body.rid);
let rdoc = await record.get(body.domainId, body.rid);
body.rid = new ObjectID(body.rid);
let rdoc = await record.get(body.rid);
const $set: Partial<RecordDoc> = {};
const $push: any = {};
if (body.case) {
@@ -72,13 +76,13 @@ export async function next(body: JudgeResultBody) {
if (body.time !== undefined) $set.time = body.time;
if (body.memory !== undefined) $set.memory = body.memory;
if (body.progress !== undefined) $set.progress = body.progress;
rdoc = await record.update(body.domainId, body.rid, $set, $push);
rdoc = await record.update(rdoc.domainId, body.rid, $set, $push);
bus.boardcast('record/change', rdoc, $set, $push);
}
export async function end(body: JudgeResultBody) {
if (body.rid) body.rid = new ObjectID(body.rid);
let rdoc = await record.get(body.domainId, body.rid);
let rdoc = await record.get(body.rid);
const $set: Partial<RecordDoc> = {};
const $push: any = {};
const $unset: any = { progress: '' };
@@ -97,7 +101,7 @@ export async function end(body: JudgeResultBody) {
$set.judgeAt = new Date();
$set.judger = body.judger ?? 1;
await sleep(100); // Make sure that all 'next' event already triggered
rdoc = await record.update(body.domainId, body.rid, $set, $push, $unset);
rdoc = await record.update(rdoc.domainId, body.rid, $set, $push, $unset);
await _postJudge(rdoc);
bus.boardcast('record/change', rdoc); // trigger a full update
}
+1 -1
View File
@@ -247,7 +247,7 @@ export class ProblemSubmitHandler extends ProblemDetailHandler {
async get(domainId: string, pid: string | number) {
this.response.template = 'problem_submit.html';
const rdocs = await record
.getUserInProblemMulti(domainId, this.user._id, this.pdoc.docId)
.getUserInProblemMulti(domainId, this.user._id, pid)
.sort({ _id: -1 })
.limit(10)
.toArray();
+23 -21
View File
@@ -1,4 +1,5 @@
import { FilterQuery, ObjectID } from 'mongodb';
import { pick } from 'lodash';
import {
ContestNotFoundError, PermissionError, ProblemNotFoundError,
RecordNotFoundError, UserNotFoundError,
@@ -58,8 +59,10 @@ class RecordListHandler extends Handler {
const [udict, pdict] = await Promise.all([
user.getList(domainId, rdocs.map((rdoc) => rdoc.uid)),
canViewProblem
? problem.getList(domainId, rdocs.map((rdoc) => rdoc.pid), canViewProblemHidden, false)
: Object.fromEntries([rdocs.map((rdoc) => [rdoc.pid, problem.create(rdoc.pid, rdoc.pid.toString())])]),
? problem.getList(domainId, rdocs.map(
(rdoc) => (rdoc.domainId === domainId ? rdoc.pid : `${rdoc.pdomain}:${rdoc.pid}`)
), canViewProblemHidden, false)
: Object.fromEntries([rdocs.map((rdoc) => [rdoc.pid, { ...problem.default, pid: rdoc.pid }])]),
]);
const path = [
['Hydro', 'homepage'],
@@ -100,16 +103,15 @@ class RecordDetailHandler extends Handler {
}
// eslint-disable-next-line prefer-const
let [pdoc, udoc] = await Promise.all([
problem.get(domainId, rdoc.pid),
problem.get(rdoc.pdomain, rdoc.pid),
user.getById(domainId, rdoc.uid),
]);
if (!(pdoc && this.user.hasPerm(PERM.PERM_VIEW_PROBLEM))) {
pdoc = problem.create(pdoc?.docId || 0, pdoc?.pid || '*');
}
if (!rdoc.contest && pdoc.hidden && !this.user.own(pdoc)) {
if (!this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN)) {
pdoc = problem.create(pdoc.docId, pdoc.pid);
}
if (
!pdoc
|| !this.user.hasPerm(PERM.PERM_VIEW_PROBLEM)
|| (!rdoc.contest && pdoc.hidden && !this.user.own(pdoc) && !this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN))
) {
pdoc = { ...problem.default, docId: pdoc?.docId || 0, pid: '*' };
}
this.response.body = {
path: [
@@ -162,6 +164,7 @@ class RecordMainConnectionHandler extends ConnectionHandler {
dispose: bus.Disposable;
tid: string;
uid: number;
pdomain: string;
pid: number;
status: number;
pretest: boolean;
@@ -172,16 +175,11 @@ class RecordMainConnectionHandler extends ConnectionHandler {
@param('status', Types.Int, true)
@param('pretest', Types.Boolean)
async prepare(domainId: string, tid?: ObjectID, pid?: string, uidOrName?: string, status?: number, pretest = false) {
if (tid) {
const tdoc = await contest.get(domainId, tid, -1);
if (contest.canShowRecord.call(this, tdoc)) this.tid = tid.toHexString();
else throw new PermissionError(PERM.PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD);
}
if (tid) {
const tdoc = await contest.get(domainId, tid, -1);
if (!tdoc) throw new ContestNotFoundError(domainId, tid);
if (!contest.canShowScoreboard.call(this, tdoc, true)) throw new PermissionError(PERM.PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD);
this.tid = tid.toHexString();
if (contest.canShowScoreboard.call(this, tdoc, true)) this.tid = tid.toHexString();
else throw new PermissionError(PERM.PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD);
}
if (uidOrName) {
let udoc = await user.getById(domainId, +uidOrName);
@@ -193,9 +191,13 @@ class RecordMainConnectionHandler extends ConnectionHandler {
}
}
if (pid) {
const pdoc = await problem.get(domainId, pid);
if (pdoc) this.pid = pdoc.docId;
else throw new ProblemNotFoundError(domainId, pid);
const pdomain = pid.includes(':') ? pid.split(':')[0] : domainId;
const ppid = pid.includes(':') ? +pid.split(':')[1] : pid;
const pdoc = await problem.get(pdomain, ppid);
if (pdoc) {
this.pdomain = pdoc.domainId;
this.pid = pdoc.docId;
} else throw new ProblemNotFoundError(domainId, pid);
}
if (status) this.status = status;
if (pretest) this.pretest = true;
@@ -219,7 +221,7 @@ class RecordMainConnectionHandler extends ConnectionHandler {
if (!this.pretest && rdoc.input) return;
if (rdoc.contest && rdoc.contest.tid.toString() !== this.tid) return;
if (this.uid && rdoc.uid !== this.uid) return;
if (this.pid && rdoc.pid !== this.pid) return;
if (this.pid && (rdoc.pid !== this.pid || rdoc.pdomain !== this.pdomain)) return;
// eslint-disable-next-line prefer-const
let [udoc, pdoc] = await Promise.all([
user.getById(this.domainId, rdoc.uid),
+1 -1
View File
@@ -206,7 +206,7 @@ class UserDetailHandler extends Handler {
this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN), false,
)
: Object.fromEntries(rdocs.map(
(rdoc) => [rdoc.pid, problem.create(undefined, rdoc.pid.toString())],
(rdoc) => [rdoc.pid, { ...problem.default, pid: rdoc.pid }],
));
// Remove sensitive data
if (!isSelfProfile && sdoc) {