添加功能:pretest discuss user dashboard statistics

This commit is contained in:
undefined committed 2020-04-27 12:18:36 +08:00
1 parent 61cba6f180
commit 15d43636c0
41 files changed
+920 -523

No files matched your search

+259
View File
@@ -0,0 +1,259 @@
const paginate = require('../lib/paginate');
const problem = require('../model/problem');
const contest = require('../model/contest');
const user = require('../model/user');
const discussion = require('../model/discussion');
const {
Route, Handler,
} = require('../service/server');
const {
DiscussionNodeNotFoundError, DiscussionNotFoundError, DocumentNotFoundError,
} = require('../error');
const { constants } = require('../options');
const {
PERM_VIEW_DISCUSSION, PERM_EDIT_DISCUSSION, PERM_EDIT_DISCUSSION_REPLY,
PERM_VIEW_PROBLEM_HIDDEN, PERM_DELETE_DISCUSSION, PERM_DELETE_DISCUSSION_REPLY,
PERM_HIGHLIGHT_DISCUSSION, PERM_LOGGEDIN, PERM_CREATE_DISCUSSION,
PERM_REPLY_DISCUSSION,
} = require('../permission');
class DiscussionHandler extends Handler {
async _prepare({
type, docId, did, drid, drrid,
}) {
this.checkPerm(PERM_VIEW_DISCUSSION);
if (did) {
this.ddoc = await discussion.get(did);
if (!this.ddoc) throw new DiscussionNotFoundError(did);
type = this.ddoc.type;
docId = this.ddoc.parent;
if (drid) {
this.drdoc = await discussion.getReply(drid, did);
if (!this.drdoc) throw new DiscussionNotFoundError(drid);
if (this.drdoc.parent !== this.ddoc._id) throw new DocumentNotFoundError(drid);
if (drrid) {
[, this.drrdoc] = await discussion.getTailReply(drid, drrid);
if (!this.drrdoc) throw new DiscussionNotFoundError(drrid);
if (this.drrdoc.parent !== this.drdoc._id) throw new DocumentNotFoundError(drid);
}
}
}
// TODO(twd2): do more visibility check eg. contest
// TODO(twd2): exclude problem/contest discussions?
// TODO(iceboy): continuation based pagination.
if (type && docId) {
if (type === 'problem') {
const pdoc = await problem.getById(docId);
if (!pdoc) throw new DiscussionNodeNotFoundError(type, docId);
if (pdoc.hidden) this.checkPerm(PERM_VIEW_PROBLEM_HIDDEN);
this.title = pdoc.title;
} else if (type === 'contest') {
const tdoc = await contest.get(docId);
if (!tdoc) throw new DiscussionNodeNotFoundError(type, docId);
this.title = tdoc.title;
} else throw new DiscussionNodeNotFoundError(type, docId);
}
}
}
class DiscussionMainHandler extends DiscussionHandler {
async get({ page = 1 }) {
const [ddocs, dpcount] = await paginate(discussion.getMulti(), page, constants.DISCUSSION_PER_PAGE);
const udict = await user.getList(ddocs.map((ddoc) => ddoc.owner));
this.response.template = 'discussion_main_or_node.html';
this.response.body = {
ddocs, dpcount, udict, page,
};
}
}
class DiscussionNodeHandler extends DiscussionHandler {
async get({ type, docId, page = 1 }) {
const [ddocs, dpcount] = await paginate(
discussion.getMulti({ type, docId }),
page,
constants.DISCUSSION_PER_PAGE,
);
const udict = await user.getList(ddocs.map((ddoc) => ddoc.owner));
const path = [
['discussion_main', '/discuss'],
[this.title, null, true],
];
this.response.template = 'discussion_main_or_node.html';
this.response.body = {
ddocs, dpcount, udict, path, page,
};
}
}
class DiscussionCreateHandler extends DiscussionHandler {
async prepare() {
this.checkPerm(PERM_LOGGEDIN);
this.checkPerm(PERM_CREATE_DISCUSSION);
}
async get({ type, docId }) {
const path = [
['discussion_main', '/discuss'],
[this.title, `/discuss/${type}/${docId}`, true],
['discussion_create', null],
];
this.response.template = 'discussion_create.html';
this.response.body = { path, title: this.title };
}
async post({
type, docId, title, content, highlight,
}) {
this.limitRate('add_discussion', 3600, 30);
const flags = {};
if (highlight) {
this.checkPerm(PERM_HIGHLIGHT_DISCUSSION);
flags.highlight = true;
}
const did = await discussion.add(type, docId, this.user._id, title, content, this.request.ip, flags);
this.response.body = { did };
this.response.redirect = `/discuss/${did}`;
}
}
class DiscussionDetailHandler extends DiscussionHandler {
async get({ did, page = 1 }) {
const dsdoc = this.user.hasPerm(PERM_LOGGEDIN)
? await discussion.getStatus(did, this.user._id)
: null;
const [drdocs, pcount, drcount] = await paginate(
discussion.getMultiReply(did),
page,
constants.REPLY_PER_PAGE,
);
const uids = drdocs.map((drdoc) => drdoc.owner);
uids.push(this.ddoc.owner);
for (const drdoc of drdocs) {
if (drdoc.reply) {
for (const drrdoc of drdocs) {
uids.push(drrdoc.owner);
}
}
}
const udict = await user.getList(uids);
const path = [
['discussion_main', '/discuss'],
[this.title, '/discuss/{type}', true],
[this.ddoc.title, null, true],
];
this.response.template = 'discussion_detail.html';
this.response.body = {
path, ddoc: this.ddoc, dsdoc, drdocs, page, pcount, drcount, udict,
};
}
async postReply({ did, content }) {
this.checkPerm(PERM_LOGGEDIN);
this.checkPerm(PERM_REPLY_DISCUSSION);
this.limitRate('add_discussion', 3600, 30);
await discussion.addReply(did, this.user._id, content, this.request.ip);
this.back();
}
async postTailReply({ drid, content }) {
this.checkPerm(PERM_LOGGEDIN);
this.checkPerm(PERM_REPLY_DISCUSSION);
this.limitRate('add_discussion', 3600, 30);
await discussion.addTailReply(drid, this.user._id, content, this.request.ip);
this.back();
}
async postEditReply({ drid, content }) {
if (this.drdoc.owner !== this.user._id) this.checkPerm(PERM_EDIT_DISCUSSION_REPLY);
await discussion.editReply(drid, content);
this.back();
}
async postDeleteReply({ drid }) {
if (this.drdoc.owner !== this.user._id) this.checkPerm(PERM_DELETE_DISCUSSION_REPLY);
await discussion.deleteReply(drid);
this.back();
}
async postEditTailReply({ drid, drrid, content }) {
if (this.drdoc.owner !== this.user._id) this.checkPerm(PERM_EDIT_DISCUSSION_REPLY);
await discussion.editTailReply(drid, drrid, content);
this.back();
}
async postDeleteTailReply({ drid, drrid }) {
if (this.drrdoc.owner !== this.user._id) this.checkPerm(PERM_DELETE_DISCUSSION_REPLY);
await discussion.deleteTailReply(drid, drrid);
this.back();
}
async postStar({ did, star }) {
await discussion.setStar(did, this.user._id, true);
this.response.body = { star };
this.response.direct = this.request.path;
}
async postUnstar({ did, star }) {
await discussion.setStar(did, this.user._id, false);
this.response.body = { star };
this.response.direct = this.request.path;
}
}
class DiscussionDetailRawHandler extends DiscussionHandler {
async get() {
this.response.type = 'text/markdown';
this.response.body = this.ddoc.content;
}
}
class DiscussionReplyRawHandler extends DiscussionHandler {
async get() {
this.response.type = 'text/markdown';
this.response.body = this.drdoc.content;
}
}
class DiscussionTailReplyRawHandler extends DiscussionHandler {
async get() {
this.response.type = 'text/markdown';
this.response.body = this.drrdoc.content;
}
}
class DiscussionEditHandler extends DiscussionHandler {
async get() {
if (this.ddoc.owner !== this.user._id) this.checkPerm(PERM_EDIT_DISCUSSION);
this.response.template = 'discussion_edit.html';
this.response.body = { ddoc: this.ddoc };
}
async post({
did, title, content, highlight, operation,
}) {
if (operation) return;
if (this.ddoc.owner !== this.user._id) this.checkPerm(PERM_EDIT_DISCUSSION);
if (highlight && !this.ddoc.highlight) this.checkPerm(PERM_HIGHLIGHT_DISCUSSION);
await discussion.edit(did, title, content, highlight);
this.response.body = { did };
this.response.redirect = `/discuss/${did}`;
}
async postDelete({ did }) {
if (this.ddoc.owner !== this.user._id) this.checkPerm(PERM_DELETE_DISCUSSION);
await discussion.delete(did);
this.response.body = { type: this.ddoc.type, parent: this.ddoc.parent };
this.response.redirect = `/discuss/${this.ddoc.type}/${this.ddoc.parent}`;
}
}
Route('/discuss', DiscussionMainHandler);
Route('/discuss/:did', DiscussionDetailHandler);
Route('/discuss/:did/edit', DiscussionEditHandler);
Route('/discuss/:did/raw', DiscussionDetailRawHandler);
Route('/discuss/:did/:drid/raw', DiscussionReplyRawHandler);
Route('/discuss/:did/:drid/:drrid/raw', DiscussionTailReplyRawHandler);
Route('/discuss/:type/:docId', DiscussionNodeHandler);
Route('/discuss/:type/:docId/create', DiscussionCreateHandler);
+1 -1
View File
@@ -8,7 +8,7 @@ const { ValidationError, RemoteOnlineJudgeError } = require('../error');
class ProblemImportHandler extends Handler {
async syzoj(url) {
const RE_SYZOJ = /https?:\/\/([a-zA-Z0-9\.]+)\/problem\/([0-9]+)\/?/i;
const RE_SYZOJ = /https?:\/\/([a-zA-Z0-9.]+)\/problem\/([0-9]+)\/?/i;
assert(url.match(RE_SYZOJ), new ValidationError('url'));
if (!url.endsWith('/')) url += '/';
const [, host, pid] = RE_SYZOJ.exec(url);
+46 -20
View File
@@ -96,16 +96,29 @@ class JudgeHandler extends Handler {
let rid = await queue.get('judge', false);
while (rid) {
const rdoc = await record.get(rid); // eslint-disable-line no-await-in-loop
const pdoc = await problem.getById(rdoc.pid); // eslint-disable-line no-await-in-loop
const task = {
event: 'judge',
rid,
type: 0,
pid: rdoc.pid,
data: pdoc.data,
lang: rdoc.lang,
code: rdoc.code,
};
let task;
if (!rdoc.input) {
// eslint-disable-next-line no-await-in-loop
const pdoc = await problem.getById(rdoc.pid);
task = {
event: 'judge',
rid,
type: 0,
pid: rdoc.pid,
data: pdoc.data,
lang: rdoc.lang,
code: rdoc.code,
};
} else {
task = {
event: 'pretest',
rid,
type: 0,
input: rdoc.input,
lang: rdoc.lang,
code: rdoc.code,
};
}
tasks.push(task);
rid = await queue.get('judge', false); // eslint-disable-line no-await-in-loop
}
@@ -134,16 +147,29 @@ class JudgeConnectionHandler extends ConnectionHandler {
this.processing = null;
const rid = await queue.get('judge');
const rdoc = await record.get(rid);
const pdoc = await problem.getById(rdoc.pid);
const task = {
event: 'judge',
rid,
type: 0,
pid: rdoc.pid,
data: pdoc.data,
lang: rdoc.lang,
code: rdoc.code,
};
let task;
if (!rdoc.input) {
// eslint-disable-next-line no-await-in-loop
const pdoc = await problem.getById(rdoc.pid);
task = {
event: 'judge',
rid,
type: 0,
pid: rdoc.pid,
data: pdoc.data,
lang: rdoc.lang,
code: rdoc.code,
};
} else {
task = {
event: 'pretest',
rid,
type: 0,
input: rdoc.input,
lang: rdoc.lang,
code: rdoc.code,
};
}
this.send({ task });
this.processing = task.rid;
}
+112
View File
@@ -0,0 +1,112 @@
const system = require('../model/system');
const user = require('../model/user');
const builtin = require('../model/builtin');
const { Route, Handler } = require('../service/server');
const { PERM_ADMIN } = require('../permission');
const { RoleAlreadyExistError } = require('../error');
class ManageHandler extends Handler {
async prepare() {
this.checkPerm(PERM_ADMIN);
}
}
class ManageMainHandler extends ManageHandler {
async get() {
this.response.redirect = '/manage/dashboard';
}
}
class ManageDashboardHandler extends ManageHandler {
async get() {
this.response.template = 'domain_manage_dashboard.html';
}
}
class ManageEditHandler extends ManageHandler {
async get() {
this.response.template = 'domain_manage_edit.html';
}
async post({ name, gravatar, bulletin }) {
await Promise.all([
system.set('name', name),
system.set('gravatar', gravatar),
system.set('bulletin', bulletin),
]);
this.back();
}
}
class ManageUserHandler extends ManageHandler {
async get() {
const uids = [];
const [rudocs, udocs, roles] = await Promise.all([
system.get(),
user.getMulti({ role: { $neq: 'default' } }).toArray(),
user.getRoles(),
]);
for (const udoc of udocs) {
uids.push(udoc._id);
rudocs[udoc.role].push(udoc);
}
const roles_with_text = roles.map((role) => [role, role]);
const udict = await user.getList(uids);
this.response.template = 'domain_manage_user.html';
this.response.body = {
roles, roles_with_text, rudocs, udict,
};
}
async postSetUser({ uid, role }) {
await user.setById(uid, { role });
this.back();
}
}
class ManagePermissionHandler extends ManageHandler {
async get() {
const roles = await user.getRoles();
this.response.template = 'domain_manage_permission.html';
this.response.body = { roles };
}
async post({ roles }) {
for (const role of roles) {
let perms = '';
for (const perm of roles) {
perms += perm;
}
roles[role] = perms;
}
await user.setRoles(roles);
this.back();
}
}
class ManageRoleHandler extends ManageHandler {
async get() {
const roles = await user.getRoles();
this.response.template = 'domain_manage_role.html';
this.response.body = { roles };
}
async postAdd({ role }) {
const roles = await user.getRoles();
if (roles.includes(role)) throw new RoleAlreadyExistError(role);
await user.setRole(role, builtin.PERM_DEFAULT);
this.back();
}
async postDelete({ role }) {
await user.deleteRoles(role);
this.back();
}
}
Route('/manage', ManageMainHandler);
Route('/manage/dashboard', ManageDashboardHandler);
Route('/manage/edit', ManageEditHandler);
Route('/manage/user', ManageUserHandler);
Route('/manage/permission', ManagePermissionHandler);
Route('/manage/role', ManageRoleHandler);
+50 -98
View File
@@ -6,7 +6,10 @@ const record = require('../model/record');
const user = require('../model/user');
const solution = require('../model/solution');
const system = require('../model/system');
const { Route, Handler } = require('../service/server');
const bus = require('../service/bus');
const {
Route, Connection, Handler, ConnectionHandler,
} = require('../service/server');
const gridfs = require('../service/gridfs');
const queue = require('../service/queue');
const {
@@ -123,6 +126,48 @@ class ProblemSubmitHandler extends ProblemDetailHandler {
}
}
class ProblemPretestHandler extends ProblemDetailHandler {
async post({ lang, code, input }) {
this.limitRate('add_record', 60, 100);
const rid = await record.add({
uid: this.uid, lang, code, pid: this.pdoc._id, input,
});
await queue.push('judge', rid);
this.response.body = { rid };
}
}
class ProblemPretestConnectionHandler extends ConnectionHandler {
async prepare({ pid }) {
this.pid = pid.toString();
bus.subscribe(['record_change'], this.onRecordChange);
}
async onRecordChange(data) {
const rdoc = data.value;
if (rdoc.uid !== this.user._id || rdoc.pid.toString() !== this.pid) return;
if (rdoc.tid) return;
this.send({ rdoc });
}
async cleanup() {
bus.unsubscribe(['record_change'], this.onRecordChange);
}
}
class ProblemStatisticsHandler extends ProblemDetailHandler {
async get() {
const udoc = await user.getById(this.pdoc.owner);
const path = [
['problem_main', '/p'],
[this.pdoc.title, `/p/${this.pdoc.pid}`, true],
['problem_statistics', null],
];
this.response.template = 'problem_statistics.html';
this.response.body = { pdoc: this.pdoc, udoc, path };
}
}
class ProblemManageHandler extends ProblemDetailHandler {
async prepare() {
if (this.pdoc.owner !== this.uid) this.checkPerm(PERM_EDIT_PROBLEM);
@@ -322,7 +367,7 @@ class ProblemCreateHandler extends Handler {
title, pid, content, hidden,
}) {
validator.checkPid(pid);
pid = pid || await system.incPidCounter();
pid = pid || await system.inc('pid');
await problem.add({
title, content, owner: this.user._id, pid, hidden,
});
@@ -335,7 +380,9 @@ Route('/p', ProblemHandler);
Route('/problem/random', ProblemRandomHandler);
Route('/p/:pid', ProblemDetailHandler);
Route('/p/:pid/submit', ProblemSubmitHandler);
Route('/p/:pid/pretest', ProblemPretestHandler);
Route('/p/:pid/settings', ProblemSettingsHandler);
Route('/p/:pid/statistics', ProblemStatisticsHandler);
Route('/p/:pid/edit', ProblemEditHandler);
Route('/p/:pid/upload', ProblemDataUploadHandler);
Route('/p/:pid/data', ProblemDataDownloadHandler);
@@ -343,99 +390,4 @@ Route('/p/:pid/solution', ProblemSolutionHandler);
Route('/p/:pid/solution/:psid/raw', ProblemSolutionRawHandler);
Route('/p/:pid/solution/:psid/:psrid/raw', ProblemSolutionReplyRawHandler);
Route('/problem/create', ProblemCreateHandler);
/*
@app.route('/p/{pid}/pretest', 'problem_pretest')
class ProblemPretestHandler(base.Handler):
@base.requirePerm(builtin.PERM_SUBMIT_PROBLEM)
@base.route_argument
@base.post_argument
@base.require_csrfToken
@base.sanitize
@base.limitRate('add_record', 60, 100)
async def post(self, *, pid: document.convert_doc_id, lang: str, code: str,
data_input: str, data_output: str):
pdoc = await problem.get(self.domainId, pid)
# don't need to check hidden status
# create zip file, TODO(twd2): check file size
post = await self.request.post()
content = list(zip(post.getall('data_input'), post.getall('data_output')))
output_buffer = io.BytesIO()
zip_file = zipfile.ZipFile(output_buffer, 'a', zipfile.ZIP_DEFLATED)
config_content = str(len(content)) + '\n'
for i, (data_input, data_output) in enumerate(content):
input_file = 'input{0}.txt'.format(i)
output_file = 'output{0}.txt'.format(i)
config_content += '{0}|{1}|1|10|262144\n'.format(input_file, output_file)
zip_file.writestr('Input/{0}'.format(input_file), data_input)
zip_file.writestr('Output/{0}'.format(output_file), data_output)
zip_file.writestr('Config.ini', config_content)
# mark all files as created in Windows :p
for zfile in zip_file.filelist:
zfile.create_system = 0
zip_file.close()
fid = await fs.add_data('application/zip', output_buffer.getvalue())
output_buffer.close()
rid = await record.add(self.domainId, pdoc['_id'], constant.record.TYPE_PRETEST,
self.user['_id'], lang, code, fid)
self.json_or_redirect(self.reverse_url('record_detail', rid=rid))
@app.connection_route('/p/{pid}/pretest-conn', 'problem_pretest-conn')
class ProblemPretestConnection(record_handler.RecordVisibilityMixin, base.Connection):
async def on_open(self):
await super(ProblemPretestConnection, self).on_open()
self.pid = document.convert_doc_id(self.request.match_info['pid'])
bus.subscribe(self.on_record_change, ['record_change'])
async def on_record_change(self, e):
rdoc = e['value']
if rdoc['uid'] != self.user['_id'] or \
rdoc['domainId'] != self.domainId or rdoc['pid'] != self.pid:
return
# check permission for visibility: contest
if rdoc['tid']:
show_status, tdoc = await self.rdoc_contest_visible(rdoc)
if not show_status:
return
self.send(rdoc=rdoc)
async def on_close(self):
bus.unsubscribe(self.on_record_change)
@base.requirePriv(builtin.PRIV_USER_PROFILE)
@base.route_argument
@base.post_argument
@base.require_csrfToken
@base.sanitize
async def post(self, *, pid: document.convert_doc_id, title: str, content: str):
pdoc = await problem.get(self.domainId, pid)
if not self.own(pdoc, builtin.PERM_EDIT_PROBLEM_SELF):
self.check_perm(builtin.PERM_EDIT_PROBLEM)
await problem.edit(self.domainId, pdoc['_id'], title=title, content=content)
self.json_or_redirect(self.reverse_url('problem_detail', pid=pid))
@app.route('/p/{pid}/statistics', 'problem_statistics')
class ProblemStatisticsHandler(base.Handler):
@base.route_argument
@base.sanitize
async def get(self, *, pid: document.convert_doc_id):
# TODO(twd2)
uid = self.user['_id'] if self.has_priv(builtin.PRIV_USER_PROFILE) else None
pdoc = await problem.get(self.domainId, pid, uid)
if pdoc.get('hidden', False):
self.check_perm(builtin.PERM_VIEW_PROBLEM_HIDDEN)
udoc, dudoc = await asyncio.gather(user.get_by_uid(pdoc['owner_uid']),
domain.get_user(self.domainId, pdoc['owner_uid']))
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['_id'])),
(self.translate('problem_statistics'), None))
self.render('problem_statistics.html', pdoc=pdoc, udoc=udoc, dudoc=dudoc,
page_title=pdoc['title'], path_components=path_components)
*/
Connection('/p/:pid/pretest-conn', ProblemPretestConnectionHandler);
+1
View File
@@ -96,6 +96,7 @@ class RecordConnectionHandler extends ConnectionHandler {
async onRecordChange(data) {
const rdoc = data.value;
if (rdoc.tid && rdoc.tid.toString() !== this.tid) return;
// eslint-disable-next-line prefer-const
let [udoc, pdoc] = await Promise.all([user.getById(rdoc.uid), problem.getById(rdoc.pid)]);
if (pdoc.hidden && !this.user.hasPerm(PERM_VIEW_PROBLEM_HIDDEN)) pdoc = null;
this.send({ html: await this.renderHTML('record_main_tr.html', { rdoc, udoc, pdoc }) });
+1 -1
View File
@@ -91,7 +91,7 @@ class UserRegisterWithCodeHandler extends Handler {
const { mail } = await token.get(code, token.TYPE_REGISTRATION);
if (!mail) throw new InvalidTokenError(token.TYPE_REGISTRATION, code);
if (password !== verifyPassword) throw new VerifyPasswordError();
const uid = await system.incUserCounter();
const uid = await system.inc('user');
await user.create({
uid, uname, password, mail, regip: this.request.ip,
});