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

318 lines
12 KiB
JavaScript

4 years ago
const moment = require('moment-timezone');
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 document = require('../model/document');
5 years ago
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({ domainId, rule = 0, page = 1 }) {
this.response.template = 'contest_main.html';
5 years ago
let tdocs;
let qs;
let tpcount;
if (!rule) {
tdocs = contest.getMulti(domainId).sort({ beginAt: -1 });
qs = '';
} else {
if (!contest.CONTEST_RULES.includes(rule)) throw new ValidationError('rule');
tdocs = contest.getMulti(domainId, { 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.docId);
const tsdict = await contest.getListStatus(domainId, this.user._id, tids);
const path = [
4 years ago
['Hydro', 'homepage'],
['contest_main', null],
];
this.response.body = {
page, tpcount, qs, rule, tdocs, tsdict, path,
};
}
}
class ContestDetailHandler extends ContestHandler {
4 years ago
async _prepare({ domainId, tid }) {
this.tdoc = await contest.get(domainId, tid);
}
5 years ago
async get({ domainId, page = 1 }) {
this.response.template = 'contest_detail.html';
5 years ago
const [tsdoc, pdict] = await Promise.all([
contest.getStatus(domainId, this.tdoc.docId, this.user._id),
problem.getList(domainId, this.tdoc.pids),
]);
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);
rdict = await record.getList(domainId, q);
5 years ago
} else {
for (const i in psdict) rdict[psdict[i].rid] = { _id: psdict[i].rid };
}
} else attended = false;
4 years ago
const udict = await user.getList(domainId, [this.tdoc.owner]);
5 years ago
const path = [
4 years ago
['Hydro', 'homepage'],
['contest_main', 'contest_main'],
[this.tdoc.title, null, null, true],
];
this.response.body = {
5 years ago
path, tdoc: this.tdoc, tsdoc, attended, udict, pdict, psdict, rdict, page,
};
}
5 years ago
async postAttend({ domainId }) {
if (contest.isDone(this.tdoc)) throw new ContestNotLiveError(this.tdoc.docId);
await contest.attend(domainId, this.tdoc.docId, this.user._id);
this.back();
}
}
5 years ago
class ContestScoreboardHandler extends ContestDetailHandler {
async get({ domainId, tid }) {
const [tdoc, rows, udict] = await this.getScoreboard(domainId, tid);
5 years ago
const path = [
4 years ago
['Hydro', 'homepage'],
['contest_main', 'contest_main'],
[tdoc.title, 'contest_detail', { 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({ domainId, 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(domainId, tid, true);
this.binary(await getContent[ext](rows), `${this.tdoc.title}.${ext}`);
}
}
5 years ago
class ContestEditHandler extends ContestDetailHandler {
async prepare() {
if (this.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;
}
5 years ago
const duration = (this.tdoc.endAt.getTime() - this.tdoc.beginAt.getTime()) / 3600 / 1000;
const path = [
4 years ago
['Hydro', 'homepage'],
['contest_main', 'contest_main'],
[this.tdoc.title, 'contest_detail', { tid: this.tdoc.docId }, 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({
domainId, beginAtDate, beginAtTime, duration, title, content, rule, pids,
5 years ago
}) {
let beginAt;
5 years ago
try {
4 years ago
beginAt = moment.tz(`${beginAtDate} ${beginAtTime}`, this.uset.timeZone);
5 years ago
} catch (e) {
throw new ValidationError('beginAtDate', 'beginAtTime');
}
4 years ago
const endAt = beginAt.add(duration, 'hours').toDate();
if (beginAt.isSameOrAfter(endAt)) throw new ValidationError('duration');
beginAt = beginAt.toDate();
pids = await this.verifyProblems(domainId, pids);
await contest.edit(domainId, this.tdoc.docId, 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) {
await contest.recalcStatus(this.tdoc.docId);
5 years ago
}
if (this.preferJson) this.response.body = { tid: this.tdoc.docId };
else this.response.redirect = `/c/${this.tdoc.docId}`;
5 years ago
}
}
class ContestProblemHandler extends ContestDetailHandler {
async prepare({ domainId, tid, pid }) {
5 years ago
[this.tdoc, this.pdoc] = await Promise.all([
contest.get(domainId, tid),
problem.get(domainId, pid, this.user._id),
5 years ago
]);
5 years ago
[this.tsdoc, this.udoc] = await Promise.all([
contest.getStatus(domainId, this.tdoc.docId, this.user._id),
user.getById(domainId, 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)) {
if (!this.attended) throw new ContestNotAttendedError(this.tdoc.docId);
if (!contest.isOngoing(this.tdoc)) throw new ContestNotLiveError(this.tdoc.docId);
5 years ago
}
if (!this.tdoc.pids.map((s) => s.toString()).includes(this.pdoc.docId.toString())) {
throw new ProblemNotFoundError(pid, this.tdoc.docId);
5 years ago
}
5 years ago
}
5 years ago
5 years ago
async get({ tid }) {
5 years ago
const path = [
4 years ago
['Hydro', 'homepage'],
['contest_main', 'contest_main'],
[this.tdoc.title, 'contest_detail', { tid }, true],
[this.pdoc.title, null, 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
};
}
}
5 years ago
class ContestProblemSubmitHandler extends ContestProblemHandler {
async get({ domainId, tid, pid }) {
5 years ago
let rdocs = [];
5 years ago
if (this.canShowRecord(this.tdoc)) {
4 years ago
rdocs = await record.getUserInProblemMulti(
domainId, this.user._id,
this.pdoc.docId, true,
).sort({ _id: -1 }).limit(10).toArray();
5 years ago
}
5 years ago
this.response.template = 'problem_submit.html';
5 years ago
const path = [
4 years ago
['Hydro', 'homepage'],
['contest_main', 'contest_main'],
[this.tdoc.title, 'contest_detail', { tid }, true],
[this.pdoc.title, 'contest_detail_problem', { tid, 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
async post({
domainId, tid, lang, code,
}) {
5 years ago
await this.limitRate('add_record', 60, 100);
const rid = await record.add(domainId, {
pid: this.pdoc.docId,
uid: this.user._id,
tid: this.tdoc.docId,
ttype: document.TYPE_CONTEST,
lang,
code,
5 years ago
});
await contest.updateStatus(domainId, this.tdoc.docId, this.user._id, rid, this.pdoc.docId);
5 years ago
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 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);
const path = [
4 years ago
['Hydro', 'homepage'],
['contest_main', 'contest_main'],
['contest_create', null],
];
this.response.body = {
5 years ago
rules,
path,
5 years ago
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({
domainId, title, content, rule, beginAtDate, beginAtTime, duration, pids, rated = false,
5 years ago
}) {
let beginAt;
try {
4 years ago
beginAt = moment.tz(`${beginAtDate} ${beginAtTime}`, this.user.timeZone);
} catch (e) {
throw new ValidationError('beginAtDate', 'beginAtTime');
}
4 years ago
const endAt = beginAt.add(duration, 'hours');
pids = await this.verifyProblems(domainId, pids);
4 years ago
const tid = await contest.add(
domainId, title, content,
this.user._id, rule, beginAt, endAt, pids, rated,
4 years ago
);
this.response.body = { tid };
this.response.redirect = `/c/${tid}`;
}
}
5 years ago
async function apply() {
Route('contest_main', '/contest', ContestListHandler);
Route('contest_detail', '/contest/:tid', ContestDetailHandler);
Route('contest_edit', '/contest/:tid/edit', ContestEditHandler);
Route('contest_scoreboard', '/contest/:tid/scoreboard', ContestScoreboardHandler);
Route('contest_scoreboard_download', '/contest/:tid/export/:ext', ContestScoreboardDownloadHandler);
Route('contest_detail_problem', '/contest/:tid/p/:pid', ContestProblemHandler);
Route('contest_detail_problem_submit', '/contest/:tid/p/:pid/submit', ContestProblemSubmitHandler);
Route('contest_create', '/contest/create', ContestCreateHandler, PERM_CREATE_CONTEST);
}
4 years ago
global.Hydro.handler.contest = module.exports = apply;