You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Hydro/hydro/handler/contest.js

294 lines
11 KiB
JavaScript

5 years ago
const {
ContestNotLiveError, ValidationError, ProblemNotFoundError,
ContestNotAttendedError,
} = require('../error');
const { PERM_CREATE_CONTEST, PERM_EDIT_CONTEST } = require('../permission');
const paginate = require('../lib/paginate');
const contest = require('../model/contest');
const problem = require('../model/problem');
const record = require('../model/record');
const user = require('../model/user');
5 years ago
const system = require('../model/system');
5 years ago
const { Route, Handler } = require('../service/server');
5 years ago
const ContestHandler = contest.ContestHandlerMixin(Handler);
class ContestListHandler extends ContestHandler {
async get({ rule = 0, page = 1 }) {
this.response.template = 'contest_main.html';
5 years ago
let tdocs;
let qs;
let tpcount;
if (!rule) {
tdocs = contest.getMulti().sort({ beginAt: -1 });
qs = '';
} else {
if (!contest.CONTEST_RULES.includes(rule)) throw new ValidationError('rule');
tdocs = contest.getMulti({ rule }).sort({ beginAt: -1 });
qs = 'rule={0}'.format(rule);
}
5 years ago
// eslint-disable-next-line prefer-const
5 years ago
[tdocs, tpcount] = await paginate(tdocs, page, await system.get('CONTEST_PER_PAGE'));
5 years ago
const tids = [];
for (const tdoc of tdocs) tids.push(tdoc._id);
const tsdict = await contest.getListStatus(this.user._id, tids);
this.response.body = {
5 years ago
page, tpcount, qs, rule, tdocs, tsdict,
};
}
}
class ContestDetailHandler extends ContestHandler {
async _prepare({ tid }) {
this.tdoc = await contest.get(tid);
}
5 years ago
async get({ page = 1 }) {
this.response.template = 'contest_detail.html';
5 years ago
const [tsdoc, pdict] = await Promise.all([
contest.getStatus(this.tdoc._id, this.user._id),
5 years ago
problem.getList(this.tdoc.pids),
]);
5 years ago
const psdict = {}; let rdict = {}; let
attended;
if (tsdoc) {
5 years ago
attended = tsdoc.attend === 1;
5 years ago
for (const pdetail of tsdoc.journal || []) psdict[pdetail.pid] = pdetail;
if (this.canShowRecord(this.tdoc)) {
5 years ago
const q = [];
for (const i in psdict) q.push(psdict[i].rid);
5 years ago
rdict = await record.getList(q);
5 years ago
} else {
for (const i in psdict) rdict[psdict[i].rid] = { _id: psdict[i].rid };
}
} else attended = false;
5 years ago
const udict = await user.getList([this.tdoc.owner]);
const path = [
['contest_main', '/c'],
5 years ago
[this.tdoc.title, null, true],
];
this.response.body = {
5 years ago
path, tdoc: this.tdoc, tsdoc, attended, udict, pdict, psdict, rdict, page,
};
}
5 years ago
async postAttend() {
if (contest.isDone(this.tdoc)) throw new ContestNotLiveError(this.tdoc._id);
await contest.attend(this.tdoc._id, this.user._id);
this.back();
}
}
5 years ago
class ContestScoreboardHandler extends ContestDetailHandler {
async get({ tid }) {
5 years ago
const [tdoc, rows, udict] = await this.getScoreboard(tid);
const path = [
5 years ago
['contest_main', '/c'],
[tdoc.title, `/c/${tid}`, true],
5 years ago
['contest_scoreboard', null],
5 years ago
];
this.response.template = 'contest_scoreboard.html';
5 years ago
this.response.body = {
tdoc, rows, path, udict,
};
5 years ago
}
}
class ContestScoreboardDownloadHandler extends ContestDetailHandler {
async get({ tid, ext }) {
const getContent = {
csv: async (rows) => `\uFEFF${rows.map((c) => (c.map((i) => i.value).join(','))).join('\n')}`,
html: (rows) => this.renderHTML('contest_scoreboard_download_html.html', { rows }),
};
if (!getContent[ext]) throw new ValidationError('ext');
const [, rows] = await this.getScoreboard(tid, true);
this.binary(await getContent[ext](rows), `${this.tdoc.title}.${ext}`);
}
}
5 years ago
class ContestEditHandler extends ContestDetailHandler {
async prepare({ tid }) {
5 years ago
const tdoc = await contest.get(tid);
if (!tdoc.owner !== this.user._id) this.checkPerm(PERM_EDIT_CONTEST);
5 years ago
}
5 years ago
5 years ago
async get() {
this.response.template = 'contest_edit.html';
5 years ago
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;
const path = [
5 years ago
['contest_main', '/c'],
[this.tdoc.title, `/c/${this.tdoc._id}`, true],
5 years ago
['contest_edit', null],
5 years ago
];
5 years ago
const dt = this.tdoc.beginAt;
5 years ago
this.response.body = {
5 years ago
rules,
tdoc: this.tdoc,
duration,
path,
pids: this.tdoc.pids.join(','),
date_text: `${dt.getFullYear()}-${dt.getMonth() + 1}-${dt.getDate()}`,
5 years ago
time_text: `${dt.getHours()}:${dt.getMinutes()}`,
5 years ago
page_name: 'contest_edit',
5 years ago
};
}
5 years ago
async post({
beginAtDate, beginAtTime, duration, title, content, rule, pids,
}) {
let beginAt;
5 years ago
try {
beginAt = new Date(Date.parse(`${beginAtDate} ${beginAtTime.replace('-', ':')}`));
5 years ago
} catch (e) {
throw new ValidationError('beginAtDate', 'beginAtTime');
}
5 years ago
const endAt = new Date(beginAt + duration * 3600 * 1000);
5 years ago
if (beginAt >= endAt) throw new ValidationError('duration');
5 years ago
pids = await this.verifyProblems(pids);
5 years ago
await contest.edit(this.tdoc._id, title, content, rule, beginAt, endAt, pids);
5 years ago
if (this.tdoc.beginAt !== beginAt || this.tdoc.endAt !== endAt
|| Array.isDiff(this.tdoc.pids, pids) || this.tdoc.rule !== rule) {
5 years ago
await contest.recalcStatus(this.tdoc._id);
5 years ago
}
5 years ago
if (this.preferJson) this.response.body = { tid: this.tdoc._id };
else this.response.redirect = `/c/${this.tdoc._id}`;
}
}
class ContestProblemHandler extends ContestDetailHandler {
5 years ago
async prepare({ tid, pid }) {
5 years ago
[this.tdoc, this.pdoc] = await Promise.all([
contest.get(tid),
problem.get(pid, this.user._id),
]);
5 years ago
[this.tsdoc, this.udoc] = await Promise.all([
contest.getStatus(this.tdoc._id, this.user._id),
5 years ago
user.getById(this.tdoc.owner),
5 years ago
]);
5 years ago
this.attended = this.tsdoc && this.tsdoc.attend === 1;
5 years ago
this.response.template = 'problem_detail.html';
if (contest.isDone(this.tdoc)) {
5 years ago
if (!this.attended) throw new ContestNotAttendedError(this.tdoc._id);
if (!contest.isOngoing(this.tdoc)) throw new ContestNotLiveError(this.tdoc._id);
5 years ago
}
5 years ago
console.log(this.tdoc.pids, this.pdoc._id);
5 years ago
if (!this.tdoc.pids.map((s) => s.toString()).includes(this.pdoc._id.toString())) {
5 years ago
throw new ProblemNotFoundError(pid, this.tdoc._id);
5 years ago
}
5 years ago
}
5 years ago
5 years ago
async get({ tid }) {
5 years ago
const path = [
5 years ago
['contest_main', '/c'],
[this.tdoc.title, `/c/${tid}`, true],
5 years ago
[this.pdoc.title, null, true],
5 years ago
];
this.response.body = {
5 years ago
tdoc: this.tdoc,
pdoc: this.pdoc,
tsdoc: this.tsdoc,
udoc: this.udoc,
attended: this.attended,
path,
5 years ago
};
}
}
class ContestProblemSubmitHandler extends ContestProblemHandler {
async get({ tid, pid }) {
let rdocs = [];
5 years ago
if (this.canShowRecord(this.tdoc)) {
5 years ago
rdocs = await record.getUserInProblemMulti(this.user._id, this.pdoc._id, true)
.sort({ _id: -1 }).limit(10).toArray();
5 years ago
}
5 years ago
this.response.template = 'problem_submit.html';
5 years ago
const path = [
5 years ago
['contest_main', '/c'],
[this.tdoc.title, `/c/${tid}`, true],
[this.pdoc.title, `/c/${tid}/p/${pid}`, true],
5 years ago
['contest_detail_problem_submit', null],
5 years ago
];
this.response.body = {
5 years ago
tdoc: this.tdoc,
pdoc: this.pdoc,
tsdoc: this.tsdoc,
udoc: this.udoc,
attended: this.attend,
path,
rdocs,
5 years ago
};
}
5 years ago
5 years ago
async post({ tid, lang, code }) {
await this.limitRate('add_record', 60, 100);
5 years ago
const rid = await record.add({
pid: this.pdoc._id, uid: this.user._id, lang, code, tid: this.tdoc._id, hidden: true,
});
5 years ago
await contest.updateStatus(this.tdoc._id, this.user._id, rid, this.pdoc._id, false, 0);
if (!this.canShowRecord(this.tdoc)) {
this.response.body = { tid };
this.response.redirect = `/c/${tid}`;
} else {
this.response.body = { rid };
this.response.redirect = `/r/${rid}`;
}
}
}
class ContestCreateHandler extends ContestHandler {
async prepare() {
this.checkPerm(PERM_CREATE_CONTEST);
}
5 years ago
async get() {
this.response.template = 'contest_edit.html';
5 years ago
const rules = {};
for (const i in contest.RULES) { rules[i] = contest.RULES[i].TEXT; }
const now = new Date();
let ts = now.getTime();
5 years ago
ts = ts - (ts % (15 * 60 * 1000)) + 15 * 60 * 1000;
const dt = new Date(ts);
this.response.body = {
5 years ago
rules,
page_name: 'contest_create',
date_text: `${dt.getFullYear()}-${dt.getMonth() + 1}-${dt.getDate()}`,
time_text: `${dt.getHours()}:${dt.getMinutes()}`,
5 years ago
pids: '1000, 1001',
};
}
5 years ago
async post({
title, content, rule, beginAtDate, beginAtTime, duration, pids,
}) {
let beginAt;
try {
beginAt = new Date(Date.parse(`${beginAtDate} ${beginAtTime.replace('-', ':')}`));
} catch (e) {
throw new ValidationError('beginAtDate', 'beginAtTime');
}
5 years ago
const endAt = new Date(beginAt.getTime() + duration * 3600 * 1000);
if (beginAt >= endAt) throw new ValidationError('duration');
5 years ago
pids = await this.verifyProblems(pids);
5 years ago
const tid = await contest.add(title, content, this.user._id, rule, beginAt, endAt, pids);
this.response.body = { tid };
this.response.redirect = `/c/${tid}`;
}
}
5 years ago
async function apply() {
Route('/c', module.exports.ContestListHandler);
Route('/c/:tid', module.exports.ContestDetailHandler);
Route('/c/:tid/edit', module.exports.ContestEditHandler);
Route('/c/:tid/scoreboard', module.exports.ContestScoreboardHandler);
Route('/c/:tid/export/:ext', module.exports.ContestScoreboardDownloadHandler);
Route('/c/:tid/p/:pid', module.exports.ContestProblemHandler);
Route('/c/:tid/p/:pid/submit', module.exports.ContestProblemSubmitHandler);
Route('/contest/create', module.exports.ContestCreateHandler);
}
5 years ago
global.Hydro.handler.contest = module.exports = {
ContestListHandler,
ContestDetailHandler,
ContestEditHandler,
ContestScoreboardHandler,
ContestScoreboardDownloadHandler,
ContestProblemHandler,
ContestProblemSubmitHandler,
ContestCreateHandler,
apply,
};