重构框架,增加比赛功能

This commit is contained in:
masnn committed 2020-04-11 20:37:47 +08:00
1 parent 0e590ebe0d
commit 9bf3343a64
54 files changed
+1117 -789

No files matched your search

+1 -2
View File
@@ -35,13 +35,12 @@ async function run() {
}); });
require('./service/gridfs'); require('./service/gridfs');
let server = require('./service/server'); let server = require('./service/server');
require('./handler/ui');
require('./handler/base');
require('./handler/home'); require('./handler/home');
require('./handler/problem'); require('./handler/problem');
require('./handler/record'); require('./handler/record');
require('./handler/judge'); require('./handler/judge');
require('./handler/user'); require('./handler/user');
require('./handler/contest');
server.start(); server.start();
} }
run().catch(e => { run().catch(e => {
-73
View File
@@ -1,73 +0,0 @@
const
{ MIDDLEWARE } = require('../service/server.js'),
user = require('../model/user'),
blacklist = require('../model/blacklist'),
token = require('../model/token'),
options = require('../options'),
{
UserNotFoundError,
BlacklistedError,
PermissionError
} = require('../error');
MIDDLEWARE(async (ctx, next) => {
try {
let sid = ctx.cookies.get('sid');
let save = ctx.cookies.get('save');
let tokenType, expireSeconds;
tokenType = token.TYPE_SESSION;
if (save) expireSeconds = options.session.saved_expire_seconds;
else expireSeconds = options.session.unsaved_expire_seconds;
ctx.session = sid ?
await token.update(sid, tokenType, expireSeconds, Object.assign({
update_ip: ctx.request.ip,
update_ua: ctx.request.headers['user-agent'] || ''
})) : { uid: 1 };
if (!ctx.session) ctx.session = { uid: 1 };
let bdoc = await blacklist.get(ctx.request.ip);
if (bdoc) throw new BlacklistedError(ctx.request.ip);
ctx.state.user = await user.getById(ctx.session.uid);
if (!ctx.state.user) throw new UserNotFoundError(ctx.session.uid);
ctx.checkPerm = function (perm) {
for (let i in arguments) {
if (arguments[i] instanceof Array) {
let p = false;
for (let j in arguments)
if (ctx.state.user.hasPerm(arguments[i][j])) {
p = true;
break;
}
if (!p) throw new PermissionError([arguments[i]]);
} else {
if (ctx.state.user.hasPerm(arguments[i])) continue;
else throw new PermissionError([[arguments[i]]]);
}
}
};
ctx.back = () => ctx.redirect(ctx.request.headers.referer || '/');
ctx.csrf_token = (await token.add(token.TYPE_CSRF_TOKEN, 600, ctx.path))[0];
await next();
if (ctx.session.sid)
await token.update(ctx.session.sid, tokenType, expireSeconds, Object.assign({
updateIp: ctx.request.ip,
updateUa: ctx.request.headers['user-agent'] || ''
}));
else
[ctx.session.sid] = await token.add(tokenType, expireSeconds, Object.assign({
create_ip: ctx.request.ip,
create_ua: ctx.request.headers['user-agent'] || '',
update_ip: ctx.request.ip,
update_ua: ctx.request.headers['user-agent'] || ''
}, ctx.session));
let cookie = { secure: options.session.secure };
if (save) {
cookie.expires = ctx.session.expireAt, cookie.maxAge = expireSeconds;
ctx.cookies.set('save', 'true', cookie);
}
ctx.cookies.set('sid', ctx.session.sid, cookie);
} catch (e) {
console.error(e.message, e.params);
console.error(e.stack);
ctx.body = { error: { message: e.message, params: e.params, stack: e.stack } };
}
}, true);
+146
View File
@@ -0,0 +1,146 @@
const
{ ContestNotLiveError, ValidationError, ProblemNotFoundError } = require('../error'),
{ PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD, PERM_CREATE_CONTEST } = require('../permission'),
{ constants } = require('../options'),
paginate = require('../lib/paginate'),
contest = require('../model/contest'),
problem = require('../model/problem'),
record = require('../model/record'),
user = require('../model/user'),
{ Route, Handler } = require('../service/server');
class ContestHandler extends Handler {
canViewHiddenScoreboard() {
return this.hasPerm(PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD);
}
canShowRecord(tdoc, allowPermOverride = true) {
if (contest.RULES[tdoc.rule].showRecordFunc(tdoc, new Date())) return true;
if (allowPermOverride && this.canViewHiddenScoreboard(tdoc)) return true;
return false;
}
canShowScoreboard(tdoc, allowPermOverride = true) {
if (contest.RULES[tdoc.rule].showScoreboardFunc(tdoc, new Date())) return true;
if (allowPermOverride && this.canViewHiddenScoreboard(tdoc)) return true;
return false;
}
async verifyProblems(pids) {
let pdocs = await problem.getMulti({ _id: { $in: pids } }).sort({ doc_id: 1 }).toArray();
if (pids.length != pdocs.length)
for (let pid of pids) {
let p = false;
for (let pdoc of pdocs)
if (pid == pdoc._id) {
p = true;
break;
}
if (!p) throw new ProblemNotFoundError(pid);
}
return pids;
}
}
class ContestListHandler extends ContestHandler {
async get({ rule = 0, page = 1 }) {
this.response.template = 'contest_main.html';
let tdocs, qs, tpcount;
if (!rule) {
tdocs = contest.getMulti();
qs = '';
} else {
if (!contest.CONTEST_RULES.includes(rule)) throw new ValidationError('rule');
tdocs = contest.getMulti({ rule });
qs = 'rule={0}'.format(rule);
}
[tdocs, tpcount] = await paginate(tdocs, page, constants.CONTEST_PER_PAGE);
let tids = [];
for (let tdoc of tdocs) tids.push(tdoc._id);
let tsdict = await contest.getListStatus(this.uid, tids);
this.response.body = {
page, tpcount, qs, rule, tdocs, tsdict
};
}
}
class ContestDetailHandler extends ContestHandler {
async _prepare({ tid }) {
this.tdoc = await contest.get(tid);
}
async get({ page = 1 }) {
this.response.template = 'contest_detail.html';
let [tsdoc, pdict] = await Promise.all([
contest.getStatus(this.tdoc._id, this.uid),
problem.getList(this.tdoc.pids)
]);
let psdict = {}, rdict = {}, attended;
if (tsdoc) {
attended = tsdoc.attend == 1;
for (let pdetail in tsdoc.detail || [])
psdict[pdetail['pid']] = pdetail;
if (this.canShowRecord(this.tdoc)) {
let q = [];
for (let i in psdict) q.push(psdict[i].rid);
rdict = await record.getList(q, { getHidden: true });
} else
for (let i in psdict)
rdict[psdict[i].rid] = { _id: psdict[i].rid };
} else attended = false;
let udict = await user.get_dict([this.tdoc.owner]);
let path = [
['contest_main', '/c'],
[this.tdoc['title'], null, true]
];
this.response.body = {
path, tdoc: this.tdoc, tsdoc, attended, udict, pdict, psdict, rdict, page
};
}
async post_attend() {
if (contest.isDone(this.tdoc)) throw new ContestNotLiveError(this.tdoc._id);
await contest.attend(this.tdoc._id, this.uid);
this.back();
}
}
class ContestProblemHandler extends ContestDetailHandler {
constructor(ctx) {
super(ctx);
this.response.template = '';
}
}
class ContestCreateHandler extends ContestHandler {
async prepare() {
this.checkPerm(PERM_CREATE_CONTEST);
}
async get() {
this.response.template = 'contest_edit.html';
let rules = {};
for (let i in contest.RULES)
rules[i] = contest.RULES[i].TEXT;
let now = new Date();
let ts = now.getTime();
ts = ts - ts % (15 * 60 * 1000) + 15 * 60 * 1000;
let dt = new Date(ts);
this.response.body = {
rules, page_name: 'contest_create',
date_text: `${dt.getFullYear()}-${dt.getMonth()}-${dt.getDate()}`,
time_text: `${dt.getHours()}-${dt.getMinutes()}`,
pids: '1000, 1001'
};
}
async post({ title, content, rule, beginAtDate, beginAtTime, duration, pids }) {
let beginAt, endAt;
try {
beginAt = Date.parse(`${beginAtDate}T${beginAtTime}+8:00`);
} catch (e) {
throw new ValidationError('beginAtDate', 'beginAtTime');
}
endAt = new Date(beginAt + duration * 3600 * 1000);
if (beginAt >= endAt) throw new ValidationError('duration');
await this.verifyProblems(pids);
let tid = await contest.add(title, content, this.user._id, rule, beginAt, endAt, pids);
this.response.body = { tid };
this.response.redirect = `/c/${tid}`;
}
}
Route('/c', ContestListHandler);
Route('/c/:cid', ContestDetailHandler);
Route('/c/:cid/p/:pid', ContestProblemHandler);
Route('/contest/create', ContestCreateHandler);
+8 -4
View File
@@ -1,5 +1,9 @@
const { GET } = require('../service/server'); const { Route, Handler } = require('../service/server');
GET('/', async ctx => { class HomeHandler extends Handler {
ctx.body = {}; async get() {
}); this.response.body = {};
}
}
Route('/', HomeHandler);
+38 -39
View File
@@ -1,12 +1,10 @@
const const
{ requirePerm } = require('./tools'),
{ sleep } = require('../utils'),
{ PERM_JUDGE } = require('../permission'), { PERM_JUDGE } = require('../permission'),
record = require('../model/record'), record = require('../model/record'),
problem = require('../model/problem'), problem = require('../model/problem'),
bus = require('../service/bus'), bus = require('../service/bus'),
queue = require('../service/queue'), queue = require('../service/queue'),
{ GET, POST, SOCKET } = require('../service/server'); { Route, Handler, Connection, ConnectionHandler } = require('../service/server');
queue.assert('judge'); queue.assert('judge');
@@ -57,10 +55,11 @@ async function end(body) {
bus.publish('record_change', rdoc); bus.publish('record_change', rdoc);
} }
GET('/judge/noop', requirePerm(PERM_JUDGE), async ctx => { class JudgeHandler extends Handler {
ctx.body = {}; async prepare(){
}); this.checkPerm(PERM_JUDGE);
GET('/judge/fetch', requirePerm(PERM_JUDGE), async ctx => { }
async get() {
let rid = await queue.get('judge', false); let rid = await queue.get('judge', false);
if (rid) { if (rid) {
let rdoc = await record.get(rid); let rdoc = await record.get(rid);
@@ -73,29 +72,28 @@ GET('/judge/fetch', requirePerm(PERM_JUDGE), async ctx => {
lang: rdoc.lang, lang: rdoc.lang,
code: rdoc.code code: rdoc.code
}; };
ctx.body = { task }; this.response.body = { task };
} }
else ctx.body = {}; else this.response.body = {};
});
SOCKET('/judge/conn', [requirePerm(PERM_JUDGE)], async conn => {
let isOpen = true, processing = null;
conn.on('close', async () => {
isOpen = false;
if (processing) {
await record.reset(processing);
queue.push('judge', processing);
} }
}); async post_next() {
conn.on('data', async message => { await next(this.request.body);
message = JSON.parse(message); this.response.body = {};
if (message.key == 'next') await next(message);
else if (message.key == 'end') {
await end(Object.assign({ judger: conn.state.user._id }, message));
processing = null;
} }
}); async post_end() {
while (isOpen) { await end(this.request.body);
if (!processing) { this.response.body = {};
}
}
class JudgeConnectionHandler extends ConnectionHandler {
async prepare() {
this.checkPerm(PERM_JUDGE);
}
async message(msg) {
if (msg.key == 'next') await next(msg);
else if (msg.key == 'end') {
await end({ judger: this.user._id, ...msg });
this.processing = null;
let rid = await queue.get('judge'); let rid = await queue.get('judge');
let rdoc = await record.get(rid); let rdoc = await record.get(rid);
let pdoc = await problem.getById(rdoc.pid); let pdoc = await problem.getById(rdoc.pid);
@@ -107,16 +105,17 @@ SOCKET('/judge/conn', [requirePerm(PERM_JUDGE)], async conn => {
lang: rdoc.lang, lang: rdoc.lang,
code: rdoc.code code: rdoc.code
}; };
conn.write(JSON.stringify({ task })); this.send({ task });
processing = task.rid; this.processing = task.rid;
} else await sleep(100);
} }
}); }
POST('/judge/next', requirePerm(PERM_JUDGE), async ctx => { async cleanup() {
await next(ctx.request.body); if (this.processing) {
ctx.body = {}; await record.reset(this.processing);
}); queue.push('judge', this.processing);
POST('/judge/end', requirePerm(PERM_JUDGE), async ctx => { }
await end(Object.assign({ judger: ctx.state.user._id }, ctx.request.body)); }
ctx.body = {}; }
});
Route('/judge', JudgeHandler);
Connection('/judge/conn', JudgeConnectionHandler);
+103 -151
View File
@@ -7,42 +7,31 @@ const
user = require('../model/user'), user = require('../model/user'),
solution = require('../model/solution'), solution = require('../model/solution'),
system = require('../model/system'), system = require('../model/system'),
{ ROUTE } = require('../service/server'), { Route, Handler } = require('../service/server'),
gridfs = require('../service/gridfs'), gridfs = require('../service/gridfs'),
queue = require('../service/queue'), queue = require('../service/queue'),
{ NoProblemError, ProblemDataNotFoundError, BadRequestError, { NoProblemError, ProblemDataNotFoundError, BadRequestError,
SolutionNotFoundError } = require('../error'), SolutionNotFoundError } = require('../error'),
{ constants } = require('../options'), { constants } = require('../options'),
{ { PERM_VIEW_PROBLEM, PERM_VIEW_PROBLEM_HIDDEN, PERM_SUBMIT_PROBLEM,
PERM_VIEW_PROBLEM, PERM_CREATE_PROBLEM, PERM_READ_PROBLEM_DATA, PERM_EDIT_PROBLEM,
PERM_VIEW_PROBLEM_HIDDEN, PERM_JUDGE, PERM_VIEW_PROBLEM_SOLUTION, PERM_CREATE_PROBLEM_SOLUTION,
PERM_SUBMIT_PROBLEM, PERM_EDIT_PROBLEM_SOLUTION, PERM_DELETE_PROBLEM_SOLUTION, PERM_EDIT_PROBLEM_SOLUTION_REPLY,
PERM_CREATE_PROBLEM, PERM_REPLY_PROBLEM_SOLUTION } = require('../permission');
PERM_READ_PROBLEM_DATA,
PERM_EDIT_PROBLEM,
PERM_JUDGE,
PERM_VIEW_PROBLEM_SOLUTION,
PERM_CREATE_PROBLEM_SOLUTION,
PERM_EDIT_PROBLEM_SOLUTION,
PERM_DELETE_PROBLEM_SOLUTION,
PERM_EDIT_PROBLEM_SOLUTION_REPLY,
PERM_REPLY_PROBLEM_SOLUTION
} = require('../permission');
queue.assert('judge'); queue.assert('judge');
class ProblemHandler { class ProblemHandler extends Handler {
constructor(ctx) { async _prepare() {
this.ctx = ctx; this.checkPerm(PERM_VIEW_PROBLEM);
this.ctx.templateName = 'problem_main.html';
this.ctx.checkPerm(PERM_VIEW_PROBLEM);
} }
async get({ page = 1, category = null }) { async get({ page = 1, category = null }) {
this.response.template = 'problem_main.html';
let q = {}; let q = {};
if (category) q.category = category; if (category) q.category = category;
if (!this.ctx.state.user.hasPerm(PERM_VIEW_PROBLEM_HIDDEN)) q.hidden = false; if (!this.user.hasPerm(PERM_VIEW_PROBLEM_HIDDEN)) q.hidden = false;
let pdocs = await problem.getMany(q, { pid: 1 }, page, constants.PROBLEM_PER_PAGE); let pdocs = await problem.getMany(q, { pid: 1 }, page, constants.PROBLEM_PER_PAGE);
this.ctx.body = { this.response.body = {
path: [ path: [
['Hydro', '/'], ['Hydro', '/'],
['problem_main', null] ['problem_main', null]
@@ -53,15 +42,12 @@ class ProblemHandler {
} }
class ProblemRandomHandler extends ProblemHandler { class ProblemRandomHandler extends ProblemHandler {
constructor(ctx) {
super(ctx);
}
async get() { async get() {
let q = {}; let q = {};
if (!this.ctx.state.user.hasPerm(PERM_VIEW_PROBLEM_HIDDEN)) q.hidden = false; if (!this.user.hasPerm(PERM_VIEW_PROBLEM_HIDDEN)) q.hidden = false;
let pid = await problem.random(q); let pid = await problem.random(q);
if (!pid) throw new NoProblemError(); if (!pid) throw new NoProblemError();
this.ctx.body = { pid }; this.response.body = { pid };
} }
} }
@@ -70,20 +56,20 @@ class ProblemDetailHandler extends ProblemHandler {
super(ctx); super(ctx);
this.uid = ctx.state.user._id; this.uid = ctx.state.user._id;
this.pid = ctx.params.pid; this.pid = ctx.params.pid;
this.ctx.templateName = 'problem_detail.html'; this.response.template = 'problem_detail.html';
} }
async _prepare() { async _prepare() {
if (this.pid) this.pdoc = await problem.get(this); if (this.pid) this.pdoc = await problem.get(this);
if (this.pdoc.hidden && this.pdoc.owner != this.uid) this.ctx.checkPerm(PERM_VIEW_PROBLEM_HIDDEN); if (this.pdoc.hidden && this.pdoc.owner != this.uid) this.checkPerm(PERM_VIEW_PROBLEM_HIDDEN);
if (this.pdoc) this.udoc = await user.getById(this.pdoc.owner); if (this.pdoc) this.udoc = await user.getById(this.pdoc.owner);
this.ctx.body = { this.response.body = {
pdoc: this.pdoc, pdoc: this.pdoc,
udoc: this.udoc, udoc: this.udoc,
title: (this.pdoc || {}).title || '' title: (this.pdoc || {}).title || ''
}; };
} }
async get() { async get() {
this.ctx.body.path = [ this.response.body.path = [
['Hydro', '/'], ['Hydro', '/'],
['problem_main', '/p'], ['problem_main', '/p'],
[this.pdoc.title, null, true] [this.pdoc.title, null, true]
@@ -92,14 +78,13 @@ class ProblemDetailHandler extends ProblemHandler {
} }
class ProblemSubmitHandler extends ProblemDetailHandler { class ProblemSubmitHandler extends ProblemDetailHandler {
constructor(ctx) { async prepare() {
super(ctx); this.checkPerm(PERM_SUBMIT_PROBLEM);
this.ctx.templateName = 'problem_submit.html';
this.ctx.checkPerm(PERM_SUBMIT_PROBLEM);
} }
async get() { async get() {
this.response.template = 'problem_submit.html';
let rdocs = await record.getUserInProblemMulti(this.uid, this.pdoc._id).sort({ _id: -1 }).limit(10).toArray(); let rdocs = await record.getUserInProblemMulti(this.uid, this.pdoc._id).sort({ _id: -1 }).limit(10).toArray();
this.ctx.body = { this.response.body = {
path: [ path: [
['Hydro', '/'], ['Hydro', '/'],
['problem_main', '/p'], ['problem_main', '/p'],
@@ -113,26 +98,26 @@ class ProblemSubmitHandler extends ProblemDetailHandler {
}; };
} }
async post() { async post() {
let { lang, code } = this.ctx.request.body; let { lang, code } = this.request.body;
let rid = await record.add({ let rid = await record.add({
uid: this.uid, lang, code, pid: this.pdoc._id uid: this.uid, lang, code, pid: this.pdoc._id
}); });
await queue.push('judge', rid); await queue.push('judge', rid);
this.ctx.state.user.nSubmit++; this.user.nSubmit++;
this.ctx.body = { rid }; this.response.body = { rid };
this.ctx.setRedirect = `/r/${rid}`; this.response.redirect = `/r/${rid}`;
} }
} }
class ProblemSettingsHandler extends ProblemDetailHandler { class ProblemManageHandler extends ProblemDetailHandler {
constructor(ctx) {
super(ctx);
this.ctx.templateName = 'problem_settings.html';
}
async prepare() { async prepare() {
if (this.pdoc.owner != this.uid) this.ctx.checkPerm(PERM_EDIT_PROBLEM); if (this.pdoc.owner != this.uid) this.checkPerm(PERM_EDIT_PROBLEM);
} }
}
class ProblemSettingsHandler extends ProblemManageHandler {
async get() { async get() {
this.response.template = 'problem_settings.html';
this.ctx.body.path = [ this.ctx.body.path = [
['Hydro', '/'], ['Hydro', '/'],
['problem_main', '/p'], ['problem_main', '/p'],
@@ -142,57 +127,44 @@ class ProblemSettingsHandler extends ProblemDetailHandler {
} }
async post() { async post() {
// TODO(masnn) // TODO(masnn)
this.ctx.back(); this.back();
} }
} }
class ProblemEditHandler extends ProblemDetailHandler { class ProblemEditHandler extends ProblemManageHandler {
constructor(ctx) {
super(ctx);
this.ctx.templateName = 'problem_edit.html';
}
async prepare() {
if (this.pdoc.owner != this.uid) this.ctx.checkPerm(PERM_EDIT_PROBLEM);
}
async get() { async get() {
this.ctx.body.path = [ this.response.template = 'problem_edit.html';
this.response.body.path = [
['Hydro', '/'], ['Hydro', '/'],
['problem_main', '/p'], ['problem_main', '/p'],
[this.pdoc.title, `/p/${this.ctx.params.pid}`, true], [this.pdoc.title, `/p/${this.request.params.pid}`, true],
['problem_edit', null] ['problem_edit', null]
]; ];
this.ctx.page_name = 'problem_edit'; this.response.body.page_name = 'problem_edit';
} }
async post() { async post({ title, content }) {
let title = validator.checkTitle(this.ctx.request.body.title); let pid = validator.checkPid(this.request.body.pid);
let content = validator.checkContent(this.ctx.request.body.content); let pdoc = await problem.get({ pid: this.params.pid });
let pid = validator.checkPid(this.ctx.request.body.pid); await problem.edit(pdoc._id, { title, content, pid });
let pdoc = await problem.get({ pid: this.ctx.params.pid }); this.response.redirect = `/p/${pid}`;
await problem.edit(pdoc._id, {
title, content, pid
});
this.ctx.setRedirect = `/p/${pid}`;
} }
} }
class ProblemDataUploadHandler extends ProblemDetailHandler { class ProblemDataUploadHandler extends ProblemManageHandler {
constructor(ctx) { constructor(ctx) {
super(ctx); super(ctx);
this.ctx.templateName = 'problem_upload.html'; this.response.template = 'problem_upload.html';
} }
async prepare() { async get() {
if (this.pdoc.owner != this.uid) this.ctx.checkPerm(PERM_EDIT_PROBLEM);
if (this.pdoc.data && typeof this.pdoc.data == 'object') { if (this.pdoc.data && typeof this.pdoc.data == 'object') {
let files = await gridfs.find({ _id: this.pdoc.data }).toArray(); let files = await gridfs.find({ _id: this.pdoc.data }).toArray();
this.md5 = files[0].md5; this.md5 = files[0].md5;
} }
} this.response.body.md5 = this.md5;
async get() {
this.ctx.body.md5 = this.md5;
} }
async post() { async post() {
if (!this.ctx.request.files.file) throw new BadRequestError(); if (!this.request.files.file) throw new BadRequestError();
const r = fs.createReadStream(this.ctx.request.files.file.path); const r = fs.createReadStream(this.request.files.file.path);
let f = gridfs.openUploadStream('data.zip'); let f = gridfs.openUploadStream('data.zip');
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
r.pipe(f); r.pipe(f);
@@ -206,136 +178,117 @@ class ProblemDataUploadHandler extends ProblemDetailHandler {
let files = await gridfs.find({ _id: this.pdoc.data }).toArray(); let files = await gridfs.find({ _id: this.pdoc.data }).toArray();
this.md5 = files[0].md5; this.md5 = files[0].md5;
} }
this.ctx.body.md5 = this.md5; this.response.body.md5 = this.md5;
} }
} }
class ProblemDataDownloadHandler extends ProblemDetailHandler { class ProblemDataDownloadHandler extends ProblemDetailHandler {
constructor(ctx) {
super(ctx);
}
async get({ pid }) { async get({ pid }) {
if (this.uid != this.pdoc.owner) this.ctx.checkPerm([PERM_READ_PROBLEM_DATA, PERM_JUDGE]); if (this.uid != this.pdoc.owner) this.checkPerm([PERM_READ_PROBLEM_DATA, PERM_JUDGE]);
if (!this.pdoc.data) throw new ProblemDataNotFoundError(pid); if (!this.pdoc.data) throw new ProblemDataNotFoundError(pid);
else if (typeof this.pdoc.data == 'string') this.ctx.setRedirect = this.pdoc.data.split('from:')[1]; else if (typeof this.pdoc.data == 'string') this.ctx.setRedirect = this.pdoc.data.split('from:')[1];
this.ctx.attachment(`${this.pdoc.title}.zip`); this.response.attachment(`${this.pdoc.title}.zip`);
this.ctx.body = gridfs.openDownloadStream(this.pdoc.data); this.response.body = gridfs.openDownloadStream(this.pdoc.data);
} }
} }
class ProblemSolutionHandler extends ProblemDetailHandler { class ProblemSolutionHandler extends ProblemDetailHandler {
constructor(ctx) { async get({ page = 1 }) {
super(ctx); this.response.template = 'problem_solution.html';
ctx.templateName = 'problem_solution.html'; this.checkPerm(PERM_VIEW_PROBLEM_SOLUTION);
}
async get() {
let page = this.ctx.query.page || 1;
this.ctx.checkPerm(PERM_VIEW_PROBLEM_SOLUTION);
let [psdocs, pcount, pscount] = await paginate(solution.getMulti(this.pdoc._id), page, constants.SOLUTION_PER_PAGE); let [psdocs, pcount, pscount] = await paginate(solution.getMulti(this.pdoc._id), page, constants.SOLUTION_PER_PAGE);
let uids = [this.pdoc.owner], docids = []; let uids = [this.pdoc.owner], docids = [];
for (let psdoc of psdocs) { for (let psdoc of psdocs) {
docids.push(psdoc._id); docids.push(psdoc._id);
uids.push(psdoc.owner); uids.push(psdoc.owner);
if (psdoc.reply.length) { if (psdoc.reply.length)
for (let psrdoc of psdoc.reply) { for (let psrdoc of psdoc.reply)
uids.push(psrdoc.owner); uids.push(psrdoc.owner);
} }
}
}
let udict = await user.getList(uids); let udict = await user.getList(uids);
let pssdict = solution.getListStatus(docids, this.uid); let pssdict = solution.getListStatus(docids, this.uid);
this.ctx.body.path = [ let path = [
['problem_main', '/p'], ['problem_main', '/p'],
[this.pdoc.title, `/p/${this.pdoc.pid}`, true], [this.pdoc.title, `/p/${this.pdoc.pid}`, true],
['problem_solution', null] ['problem_solution', null]
]; ];
this.ctx.body = Object.assign(this.ctx.body, { this.response.body = {
psdocs, page, pcount, pscount, udict, pssdict path, psdocs, page, pcount, pscount, udict, pssdict
}); };
} }
async post({ psid }) { async post({ psid }) {
if (psid) this.psdoc = await solution.get(psid); if (psid) this.psdoc = await solution.get(psid);
} }
async post_submit({ content }) { async post_submit({ content }) {
this.ctx.checkPerm(PERM_CREATE_PROBLEM_SOLUTION); this.checkPerm(PERM_CREATE_PROBLEM_SOLUTION);
await solution.add(this.pdoc._id, this.uid, content); await solution.add(this.pdoc._id, this.uid, content);
this.ctx.back(); this.back();
} }
async post_edit_solution({ content }) { async post_edit_solution({ content }) {
if (this.psdoc.owner != this.uid) this.ctx.checkPerm(PERM_EDIT_PROBLEM_SOLUTION); if (this.psdoc.owner != this.uid) this.checkPerm(PERM_EDIT_PROBLEM_SOLUTION);
this.psdoc = await solution.edit(this.psdoc._id, content); this.psdoc = await solution.edit(this.psdoc._id, content);
this.ctx.body.psdoc = this.psdoc; this.ctx.body.psdoc = this.psdoc;
this.ctx.back(); this.back();
} }
async post_delete_solution() { async post_delete_solution() {
if (this.psdoc.owner != this.uid) this.ctx.checkPerm(PERM_DELETE_PROBLEM_SOLUTION); if (this.psdoc.owner != this.uid) this.checkPerm(PERM_DELETE_PROBLEM_SOLUTION);
await solution.del(this.psdoc._id); await solution.del(this.psdoc._id);
this.ctx.back(); this.back();
} }
async post_reply({ psid, content }) { async post_reply({ psid, content }) {
this.ctx.checkPerm(PERM_REPLY_PROBLEM_SOLUTION); this.checkPerm(PERM_REPLY_PROBLEM_SOLUTION);
let psdoc = await solution.get(psid); let psdoc = await solution.get(psid);
await solution.reply(psdoc._id, this.uid, content); await solution.reply(psdoc._id, this.uid, content);
} }
async post_edit_reply({ content }) { async post_edit_reply({ content, psid, psrid }) {
let { psid, psrid } = this.ctx.request.body;
let [psdoc, psrdoc] = await solution.getReply(psid, psrid); let [psdoc, psrdoc] = await solution.getReply(psid, psrid);
if ((!psdoc) || psdoc.pid != this.pdoc._id) throw new SolutionNotFoundError(psid); if ((!psdoc) || psdoc.pid != this.pdoc._id) throw new SolutionNotFoundError(psid);
if (psrdoc.owner != this.uid) this.ctx.checkPerm(PERM_EDIT_PROBLEM_SOLUTION_REPLY); if (psrdoc.owner != this.uid) this.checkPerm(PERM_EDIT_PROBLEM_SOLUTION_REPLY);
await solution.editReply(psid, psrid, content); await solution.editReply(psid, psrid, content);
} }
async post_delete_reply({ psid, psrid }) { async post_delete_reply({ psid, psrid }) {
let [psdoc, psrdoc] = await solution.getReply(psid, psrid); let [psdoc, psrdoc] = await solution.getReply(psid, psrid);
if ((!psdoc) || psdoc.pid != this.pdoc._id) throw new SolutionNotFoundError(psid); if ((!psdoc) || psdoc.pid != this.pdoc._id) throw new SolutionNotFoundError(psid);
if (psrdoc.owner != this.uid) this.ctx.checkPerm(PERM_EDIT_PROBLEM_SOLUTION_REPLY); if (psrdoc.owner != this.uid) this.checkPerm(PERM_EDIT_PROBLEM_SOLUTION_REPLY);
await solution.delReply(psid, psrid); await solution.delReply(psid, psrid);
this.ctx.back(); this.back();
} }
async post_upvote() { async post_upvote() {
let [psdoc, pssdoc] = await solution.vote(this.psdoc._id, this.uid, 1); let [psdoc, pssdoc] = await solution.vote(this.psdoc._id, this.uid, 1);
this.ctx.body = { vote: psdoc.vote, user_vote: pssdoc.vote }; this.response.body = { vote: psdoc.vote, user_vote: pssdoc.vote };
if (!this.ctx.preferJson) this.ctx.back(); if (!this.preferJson) this.back();
} }
async post_downvote() { async post_downvote() {
let [psdoc, pssdoc] = await solution.vote(this.psdoc._id, this.uid, -1); let [psdoc, pssdoc] = await solution.vote(this.psdoc._id, this.uid, -1);
this.ctx.body = { vote: psdoc.vote, user_vote: pssdoc.vote }; this.response.body = { vote: psdoc.vote, user_vote: pssdoc.vote };
if (!this.ctx.preferJson) this.ctx.back(); if (!this.preferJson) this.back();
} }
} }
class ProblemSolutionRawHandler extends ProblemDetailHandler { class ProblemSolutionRawHandler extends ProblemDetailHandler {
constructor(ctx) {
super(ctx);
ctx.checkPerm(PERM_VIEW_PROBLEM_SOLUTION);
}
async get({ psid }) { async get({ psid }) {
this.checkPerm(PERM_VIEW_PROBLEM_SOLUTION);
let psdoc = await solution.get(psid); let psdoc = await solution.get(psid);
this.ctx.response.type = 'text/markdown'; this.response.type = 'text/markdown';
this.ctx.body = psdoc.content; this.response.body = psdoc.content;
} }
} }
class ProblemSolutionReplyRawHandler extends ProblemDetailHandler { class ProblemSolutionReplyRawHandler extends ProblemDetailHandler {
constructor(ctx) {
super(ctx);
ctx.checkPerm(PERM_VIEW_PROBLEM_SOLUTION);
}
async get({ psid }) { async get({ psid }) {
this.checkPerm(PERM_VIEW_PROBLEM_SOLUTION);
let [psdoc, psrdoc] = await solution.getReply(psid); let [psdoc, psrdoc] = await solution.getReply(psid);
if ((!psdoc) || psdoc.pid != this.pdoc._id) throw new SolutionNotFoundError(psid); if ((!psdoc) || psdoc.pid != this.pdoc._id) throw new SolutionNotFoundError(psid);
this.ctx.response.type = 'text/markdown'; this.response.type = 'text/markdown';
this.ctx.body = psrdoc.content; this.response.body = psrdoc.content;
} }
} }
class ProblemCreateHandler { class ProblemCreateHandler extends Handler {
constructor(ctx) {
this.ctx = ctx;
this.ctx.templateName = 'problem_edit.html';
this.ctx.checkPerm(PERM_CREATE_PROBLEM);
}
async get() { async get() {
this.ctx.body = { this.response.template = 'problem_edit.html';
this.checkPerm(PERM_CREATE_PROBLEM);
this.response.body = {
path: [ path: [
['Hydro', '/'], ['Hydro', '/'],
['problem_main', '/p'], ['problem_main', '/p'],
@@ -343,28 +296,27 @@ class ProblemCreateHandler {
], page_name: 'problem_create' ], page_name: 'problem_create'
}; };
} }
async post() { async post({ title, pid, content, hidden }) {
let { title, pid, content, hidden } = this.ctx.request.body;
validator.checkPid(pid); validator.checkPid(pid);
pid = pid || await system.incPidCounter(); pid = pid || await system.incPidCounter();
await problem.add({ title, content, owner: this.ctx.state.user._id, pid, hidden }); await problem.add({ title, content, owner: this.user._id, pid, hidden });
this.ctx.body = { pid }; this.response.body = { pid };
this.ctx.setRedirect = `/p/${pid}/settings`; this.response.redirect = `/p/${pid}/settings`;
} }
} }
ROUTE('/p', ProblemHandler); Route('/p', ProblemHandler);
ROUTE('/problem/random', ProblemRandomHandler); Route('/problem/random', ProblemRandomHandler);
ROUTE('/p/:pid', ProblemDetailHandler); Route('/p/:pid', ProblemDetailHandler);
ROUTE('/p/:pid/submit', ProblemSubmitHandler); Route('/p/:pid/submit', ProblemSubmitHandler);
ROUTE('/p/:pid/settings', ProblemSettingsHandler); Route('/p/:pid/settings', ProblemSettingsHandler);
ROUTE('/p/:pid/edit', ProblemEditHandler); Route('/p/:pid/edit', ProblemEditHandler);
ROUTE('/p/:pid/upload', ProblemDataUploadHandler); Route('/p/:pid/upload', ProblemDataUploadHandler);
ROUTE('/p/:pid/data', ProblemDataDownloadHandler); Route('/p/:pid/data', ProblemDataDownloadHandler);
ROUTE('/p/:pid/solution', ProblemSolutionHandler); Route('/p/:pid/solution', ProblemSolutionHandler);
ROUTE('/p/:pid/solution/:psid/raw', ProblemSolutionRawHandler); Route('/p/:pid/solution/:psid/raw', ProblemSolutionRawHandler);
ROUTE('/p/:pid/solution/:psid/:psrid/raw', ProblemSolutionReplyRawHandler); Route('/p/:pid/solution/:psid/:psrid/raw', ProblemSolutionReplyRawHandler);
ROUTE('/problem/create', ProblemCreateHandler); Route('/problem/create', ProblemCreateHandler);
/* /*
+69 -61
View File
@@ -1,99 +1,107 @@
const const
bson = require('bson'),
{ constants } = require('../options'), { constants } = require('../options'),
{ PERM_READ_RECORD_CODE, PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD, { PERM_READ_RECORD_CODE, PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD,
PERM_REJUDGE, PERM_VIEW_PROBLEM_HIDDEN } = require('../permission'), PERM_REJUDGE, PERM_VIEW_PROBLEM_HIDDEN } = require('../permission'),
{ requirePerm } = require('../handler/tools'),
problem = require('../model/problem'), problem = require('../model/problem'),
record = require('../model/record'), record = require('../model/record'),
user = require('../model/user'), user = require('../model/user'),
bus = require('../service/bus'), bus = require('../service/bus'),
queue = require('../service/queue'), queue = require('../service/queue'),
{ GET, POST, SOCKET } = require('../service/server'); { Route, Handler, Connection, ConnectionHandler } = require('../service/server');
GET('/r', async ctx => { class RecordListHandler extends Handler {
ctx.templateName = 'record_main.html'; async get({ page = 1 }) {
let q = {}, this.response.template = 'record_main.html';
page = ctx.query.page || 1; let q = {};
let rdocs = await record.getMany(q, { _id: -1 }, page, constants.RECORD_PER_PAGE); let rdocs = await record.getMany(q, { _id: -1 }, page, constants.RECORD_PER_PAGE);
let pdict = {}, udict = {}; let pdict = {}, udict = {};
for (let rdoc of rdocs) { for (let rdoc of rdocs) {
udict[rdoc.uid] = await user.getById(rdoc.uid); udict[rdoc.uid] = await user.getById(rdoc.uid);
pdict[rdoc.pid] = await problem.get({ pid: rdoc.pid, uid: ctx.state.user._id }); pdict[rdoc.pid] = await problem.get({ pid: rdoc.pid, uid: this.user._id });
} }
ctx.body = { this.response.body = {
path: [ path: [
['Hydro', '/'], ['Hydro', '/'],
['record_main', null] ['record_main', null]
], ],
page, rdocs, pdict, udict page, rdocs, pdict, udict
}; };
});
SOCKET('/record-conn', [], conn => {
let tid = conn.params.tid;
async function onRecordChange(data) {
let rdoc = data.value;
if (rdoc.tid && rdoc.tid.toString() != tid) return;
let [udoc, pdoc] = await Promise.all([user.getById(rdoc.uid), problem.get({ pid: rdoc.pid })]);
if (pdoc.hidden && !conn.state.user.hasPerm(PERM_VIEW_PROBLEM_HIDDEN)) pdoc = null;
conn.send({ html: await conn.renderHTML('record_main_tr.html', { rdoc, udoc, pdoc }) });
} }
bus.subscribe(['record_change'], onRecordChange);
conn.on('data', async message => {
console.log(message);
let { rids } = JSON.parse(message);
for (let rid of rids) {
let rdoc = await record.get(rid);
await onRecordChange({ value: rdoc });
} }
}); class RecordDetailHandler extends Handler {
conn.on('close', () => { async get({ rid }) {
bus.unsubscribe(['record_change'], onRecordChange); this.response.template = 'record_detail.html';
});
});
GET('/r/:rid', async ctx => {
ctx.templateName = 'record_detail.html';
let uid = ctx.state.user._id, rid = new bson.ObjectID(ctx.params.rid);
let rdoc = await record.get(rid); let rdoc = await record.get(rid);
if (rdoc.hidden) ctx.checkPerm(PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD); if (rdoc.hidden) this.checkPerm(PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD);
if (rdoc.uid != uid && !ctx.state.user.hasPerm(PERM_READ_RECORD_CODE)) rdoc.code = null; if (rdoc.uid != this.user.uid && !this.user.hasPerm(PERM_READ_RECORD_CODE)) rdoc.code = null;
ctx.body = { this.response.body = {
path: [ path: [
['Hydro', '/'], ['Hydro', '/'],
['record_detail', null] ['record_detail', null]
], ],
rdoc, show_status: true rdoc, show_status: true
}; };
});
SOCKET('/record-detail-conn', [], async conn => {
let rdoc = await record.get(conn.params.rid);
if (rdoc.tid)
if (!await conn.rdoc_contest_visible(rdoc)) {
conn.close();
return;
} }
async function onRecordChange(data) {
let rdoc = data.value;
if (rdoc._id.toString() != conn.params.rid) return;
conn.send({
status_html: await conn.renderHTML('record_detail_status.html', { rdoc }),
summary_html: await conn.renderHTML('record_detail_summary.html', { rdoc })
});
} }
bus.subscribe(['record_change'], onRecordChange); class RecordRejudgeHandler extends Handler {
onRecordChange({ value: rdoc }); async post({ rid }) {
conn.on('close', () => { this.checkPerm(PERM_REJUDGE);
bus.unsubscribe(['record_change'], onRecordChange);
});
});
POST('/r/:rid/rejudge', requirePerm(PERM_REJUDGE), async ctx => {
let uid = ctx.state.user._id, rid = new bson.ObjectID(ctx.params.rid);
let rdoc = await record.get(rid); let rdoc = await record.get(rid);
if (rdoc.hidden) ctx.checkPerm(PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD);
if (rdoc.uid != uid && !ctx.state.user.hasPerm(PERM_READ_RECORD_CODE)) rdoc.code = null;
if (rdoc) { if (rdoc) {
await record.reset(rid); await record.reset(rid);
await queue.push('judge', rid); await queue.push('judge', rid);
} }
ctx.back(); this.response.back();
}
}
class RecordConnectionHandler extends ConnectionHandler {
async prepare() {
bus.subscribe(['record_change'], this.onRecordChange);
}
async message(msg) {
for (let rid of msg.rids) {
let rdoc = await record.get(rid);
await this.onRecordChange({ value: rdoc });
}
}
async cleanup() {
bus.unsubscribe(['record_change'], this.onRecordChange);
}
async onRecordChange(data) {
let rdoc = data.value;
if (rdoc.tid && rdoc.tid.toString() != this.tid) return;
let [udoc, pdoc] = await Promise.all([user.getById(rdoc.uid), problem.get({ pid: 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 }) });
}
}
class RecordDetailConnectionHandler extends ConnectionHandler {
async prepare({ rid }) {
let rdoc = await record.get(rid);
if (rdoc.tid)
if (!await this.rdocContestVisible(rdoc)) {
this.close();
return;
}
this.rid = rid;
bus.subscribe(['record_change'], this.onRecordChange);
this.onRecordChange({ value: rdoc });
}
async onRecordChange(data) {
let rdoc = data.value;
if (rdoc._id.toString() != this.rid) return;
this.send({
status_html: await this.renderHTML('record_detail_status.html', { rdoc }),
summary_html: await this.renderHTML('record_detail_summary.html', { rdoc })
}); });
}
async cleanup() {
bus.unsubscribe(['record_change'], this.onRecordChange);
}
}
Route('/r', RecordListHandler);
Route('/r/:rid', RecordDetailHandler);
Route('/r/:rid/rejudge', RecordRejudgeHandler);
Connection('/record-conn', RecordConnectionHandler);
Connection('/record-detail-conn', RecordDetailConnectionHandler);
+1 -6
View File
@@ -22,10 +22,5 @@ module.exports = {
await next(); await next();
}; };
}, },
limitRate(op, period_secs, max_operations) {
return async (ctx, next) => {
await opcount.inc(op, ctx.request.ip, period_secs, max_operations);
await next();
};
}
}; };
-123
View File
@@ -1,123 +0,0 @@
const
path = require('path'),
staticCache = require('koa-static-cache'),
nunjucks = require('nunjucks'),
hljs = require('highlight.js'),
MarkdownIt = require('markdown-it'),
katex = require('markdown-it-katex'),
options = require('../options'),
perm = require('../permission'),
builtin = require('../model/builtin'),
misc=require('../lib/misc'),
{ MIDDLEWARE } = require('../service/server'),
{ NotFoundError } = require('../error');
class Markdown extends MarkdownIt {
constructor() {
super({
linkify: true,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang))
try {
return hljs.highlight(lang, str).value;
} catch (__) { } // eslint-disable-line no-empty
return '';
}
});
this.linkify.tlds('.py', false);
this.use(katex);
}
}
const md = new Markdown();
class Nunjucks extends nunjucks.Environment {
constructor() {
super(
new nunjucks.FileSystemLoader(path.resolve(options.template.path)),
{ autoescape: true, trimBlocks: true }
);
this.addFilter('json', function (self) {
return JSON.stringify(self);
}, false);
this.addFilter('assign', function (self, data) {
return Object.assign(self, data);
});
this.addFilter('markdown', function (self) {
return md.render(self);
});
this.addFilter('gravatar_url', misc.gravatar_url);
this.addFilter('format_size', misc.format_size);
this.addGlobal('typeof', o => typeof o);
this.addGlobal('console', console);
this.addGlobal('static_url', str => `/${str}`);
this.addGlobal('reverse_url', str => str);
this.addGlobal('datetime_span', misc.datetime_span);
this.addGlobal('paginate', misc.paginate);
this.addGlobal('perm', perm);
this.addGlobal('builtin', builtin);
this.addGlobal('status', builtin.STATUS);
}
}
let env = new Nunjucks();
MIDDLEWARE(staticCache(path.join(process.cwd(), '.uibuild'), {
maxAge: 365 * 24 * 60 * 60
}));
MIDDLEWARE(async (ctx, next) => {
ctx.render_title = str => str;
ctx.UIContext = {
cdn_prefix: '/',
url_prefix: '/'
};
ctx.preferJson = (ctx.request.headers['accept'] || '').includes('application/json');
ctx.renderHTML = (name, context) => {
ctx.user = ctx.state.user;
ctx.translate = str => {
if (!str) return '';
return str.toString().translate(ctx.state.user.language);
};
ctx.has_perm = perm => ctx.state.user.hasPerm(perm);
return new Promise((resolve, reject) => {
env.render(name, Object.assign(ctx.state, context, {
handler: ctx,
_: ctx.translate,
user: ctx.state.user
}), (error, res) => {
if (error) reject(error);
else resolve(res);
});
});
};
ctx.render = async (name, context) => {
ctx.body = await ctx.renderHTML(name, context);
ctx.response.type = 'text/html';
};
try {
try {
await next();
if (ctx.setRedirect) {
ctx.response.type = 'application/octet-stream';
ctx.redirect(ctx.setRedirect);
} else if (ctx.body || ctx.templateName) {
if (ctx.query.noTemplate || ctx.preferJson) return;
if (ctx.query.template || ctx.templateName) {
ctx.body = ctx.body || {};
Object.assign(ctx.body, JSON.parse(ctx.query.data || '{}'));
await ctx.render(ctx.query.template || ctx.templateName, ctx.body);
}
} else {
throw new NotFoundError();
}
} catch (e) {
let error;
if (ctx.body && ctx.body.error) error = ctx.body.error;
else error = e;
if (error instanceof NotFoundError) ctx.status = 404;
if (error.toString().startsWith('NotFoundError')) console.log(error);
if (error.toString().startsWith('Template render error')) throw error;
if (ctx.preferJson) ctx.body = { error };
else await ctx.render('error.html', { error });
}
} catch (error) {
if (ctx.preferJson) ctx.body = { error };
else await ctx.render('bsod.html', { error });
}
}, true);
+113 -94
View File
@@ -1,122 +1,136 @@
const const
{ GET, POST, ROUTE } = require('../service/server.js'), { Route, Handler } = require('../service/server.js'),
user = require('../model/user'), user = require('../model/user'),
token = require('../model/token'), token = require('../model/token'),
system = require('../model/system'), system = require('../model/system'),
mail = require('../lib/mail'), { sendMail } = require('../lib/mail'),
misc = require('../lib/misc'), misc = require('../lib/misc'),
validator = require('../lib/validator'), validator = require('../lib/validator'),
options = require('../options'), options = require('../options'),
{ PERM_REGISTER_USER, PERM_LOGGEDIN } = require('../permission'), { PERM_REGISTER_USER, PERM_LOGGEDIN } = require('../permission'),
{ requirePerm, limitRate } = require('./tools'), { UserAlreadyExistError, InvalidTokenError, VerifyPasswordError,
{ UserAlreadyExistError, InvalidTokenError, VerifyPasswordError, UserNotFoundError, LoginError } = require('../error'); UserNotFoundError, LoginError, SystemError } = require('../error');
GET('/user', async ctx => { class UserLoginHandler extends Handler {
let udoc = await user.getById(ctx.session.uid); async get() {
ctx.templateName = 'user_detail.html'; this.response.template = 'user_login.html';
ctx.body = { udoc }; }
}); async post({ uname, password, rememberme = false }) {
GET('/login', async ctx => {
ctx.templateName = 'user_login.html';
});
POST('/login', async ctx => {
let { uname, password, rememberme = false } = ctx.request.body;
let udoc = await user.getByUname(uname); let udoc = await user.getByUname(uname);
if (!udoc) throw new LoginError(uname); if (!udoc) throw new LoginError(uname);
if (udoc) udoc.checkPassword(password); if (udoc) udoc.checkPassword(password);
await user.setById(udoc._id, { loginat: new Date(), loginip: ctx.request.ip }); await user.setById(udoc._id, { loginat: new Date(), loginip: this.request.ip });
udoc.salt = ''; udoc.salt = '';
udoc.password = ''; udoc.password = '';
console.log(udoc); this.session.uid = udoc._id;
ctx.session.uid = udoc._id; this.session.rememberme = rememberme;
ctx.session.rememberme = rememberme; this.response.body = {};
ctx.body = {}; let referer = this.request.headers.referer || '/';
let referer = ctx.request.headers.referer || '/'; this.response.redirect = referer.endsWith('/login') ? '/' : referer;
ctx.setRedirect = referer.endsWith('/login') ? '/' : referer; }
}); }
POST('/logout', requirePerm(PERM_LOGGEDIN), async ctx => { class UserLogoutHandler extends Handler {
ctx.session = { uid: 1 }; constructor(ctx) {
ctx.body = {}; super(ctx);
}); this.checkPerm(PERM_LOGGEDIN);
GET('/register', requirePerm(PERM_REGISTER_USER), async ctx => { }
ctx.templateName = 'user_register.html'; async get() {
}); this.response.template = 'user_logout.html';
GET('/register/:code', requirePerm(PERM_REGISTER_USER), async ctx => { }
ctx.templateName = 'user_register_with_code.html'; async post() {
let code = ctx.params.code; this.session = { uid: 1 };
let { email } = await token.get(code, token.TYPE_REGISTRATION); this.response.body = {};
if (!email) throw new InvalidTokenError(token.TYPE_REGISTRATION, code); }
ctx.body = { email }; }
}); class UserRegisterHandler extends Handler {
POST('/register/:code', requirePerm(PERM_REGISTER_USER), async ctx => { constructor(ctx) {
let code = ctx.params.code; super(ctx);
let { password, verify_password, uname } = ctx.request.body; this.checkPerm(PERM_REGISTER_USER);
let { email } = await token.get(code, token.TYPE_REGISTRATION); }
if (!email) throw new InvalidTokenError(token.TYPE_REGISTRATION, code); async get() {
this.response.template = 'user_register.html';
}
async post({ mail }) {
validator.checkEmail(mail);
if (await user.getByEmail(mail, true)) throw new UserAlreadyExistError(mail);
this.limitRate('send_mail', 3600, 30);
let t = await token.add(token.TYPE_REGISTRATION, options.registration_token_expire_seconds, { mail });
if (options.smtp.user) {
let m = await this.renderHTML('user_register_mail', { url: `/register/${t}` });
await sendMail(mail, 'Sign Up', 'user_register_mail', m);
this.response.body = {};
this.response.template = 'user_register_mail_sent.html';
} else {
this.response.redirect = `/register/${t[0]}`;
}
}
}
class UserRegisterWithCodeHandler extends Handler {
constructor(ctx) {
super(ctx);
this.checkPerm(PERM_REGISTER_USER);
}
async get({ code }) {
this.response.template = 'user_register_with_code.html';
let { mail } = await token.get(code, token.TYPE_REGISTRATION);
if (!mail) throw new InvalidTokenError(token.TYPE_REGISTRATION, code);
this.response.body = { mail };
}
async post({ code, password, verify_password, uname }) {
let { mail } = await token.get(code, token.TYPE_REGISTRATION);
if (!mail) throw new InvalidTokenError(token.TYPE_REGISTRATION, code);
if (password != verify_password) throw new VerifyPasswordError(); if (password != verify_password) throw new VerifyPasswordError();
let uid = await system.incUserCounter(); let uid = await system.incUserCounter();
await user.create({ uid, uname, password, email, regip: ctx.request.ip }); await user.create({ uid, uname, password, mail, regip: this.request.ip });
await token.delete(code, token.TYPE_REGISTRATION); await token.delete(code, token.TYPE_REGISTRATION);
ctx.session.uid = uid; this.session.uid = uid;
ctx.body = {}; this.response.body = {};
ctx.setRedirect = '/'; this.response.redirect = '/';
}); }
}
if (options.smtp.user) { class UserLostPassHandler extends Handler {
POST('/register', requirePerm(PERM_REGISTER_USER), limitRate('send_mail', 3600, 30), async ctx => { constructor(ctx) {
let email = ctx.request.body.mail; if (!options.smtp.user) throw new SystemError('Cannot send mail');
validator.checkEmail(email); super(ctx);
if (await user.getByEmail(email, true)) throw new UserAlreadyExistError(email); }
let rid = await token.add(token.TYPE_REGISTRATION, options.registration_token_expire_seconds, { email }); async get() {
let m = await ctx.render('user_register_mail', { url: `/register/${rid}` }, true); this.response.template = 'user_lostpass.html';
await mail.sendMail(email, 'Sign Up', 'user_register_mail', m); }
ctx.body = {}; async post({ mail }) {
}); validator.checkEmail(mail);
POST('/lostpass', limitRate('send_mail', 3600, 30), async ctx => { let udoc = await user.getByEmail(mail);
let email = ctx.request.body.mail; if (!udoc) throw new UserNotFoundError(mail);
validator.checkEmail(email);
let udoc = await user.getByEmail(email);
if (!udoc) throw new UserNotFoundError(email);
let tid = await token.add( let tid = await token.add(
token.TYPE_LOSTPASS, token.TYPE_LOSTPASS,
options.lostpass_token_expire_seconds, options.lostpass_token_expire_seconds,
{ uid: udoc._id } { uid: udoc._id }
); );
let m = await ctx.render('user_lostpass_mail', { url: `/lostpass/${tid}`, uname: udoc.uname }, true); let m = await this.renderHTML('user_lostpass_mail', { url: `/lostpass/${tid}`, uname: udoc.uname });
await mail.sendMail(email, 'Lost Password', 'user_lostpass_mail', m); await sendMail(mail, 'Lost Password', 'user_lostpass_mail', m);
ctx.body = {}; this.response.body = {};
}); this.response.template = 'user_lostpass_mail_sent.html';
GET('/lostpass/:code', async ctx => { }
let code = ctx.params.code; }
class UserLostPassWithCodeHandler extends Handler {
async get({ code }) {
let tdoc = await token.get(code, token.TYPE_LOSTPASS); let tdoc = await token.get(code, token.TYPE_LOSTPASS);
if (!tdoc) throw new InvalidTokenError(token.TYPE_LOSTPASS, code); if (!tdoc) throw new InvalidTokenError(token.TYPE_LOSTPASS, code);
let udoc = await user.getById(tdoc.uid); let udoc = await user.getById(tdoc.uid);
ctx.body = { uname: udoc.uname }; this.response.body = { uname: udoc.uname };
}); }
POST('/lostpass/:code', async ctx => { async post({ code, password, verify_password }) {
let code = ctx.params.code;
let password = ctx.request.body.password;
let verify_password = ctx.request.body.verify_password;
let tdoc = await token.get(code, token.TYPE_LOSTPASS); let tdoc = await token.get(code, token.TYPE_LOSTPASS);
if (!tdoc) throw new InvalidTokenError(token.TYPE_LOSTPASS, code); if (!tdoc) throw new InvalidTokenError(token.TYPE_LOSTPASS, code);
if (password != verify_password) throw new VerifyPasswordError(); if (password != verify_password) throw new VerifyPasswordError();
await user.setPassword(tdoc.uid, password); await user.setPassword(tdoc.uid, password);
await token.delete(code, token.TYPE_LOSTPASS); await token.delete(code, token.TYPE_LOSTPASS);
ctx.redirect('/'); this.response.redirect = '/';
}); }
} else }
POST('/register', requirePerm(PERM_REGISTER_USER), limitRate('send_mail', 3600, 60), async ctx => { class UserDetailHandler extends Handler {
let email = ctx.request.body.mail;
validator.checkEmail(email);
if (await user.getByEmail(email, true)) throw new UserAlreadyExistError(email);
let t = await token.add(token.TYPE_REGISTRATION, options.session.registration_token_expire_seconds, { email });
ctx.setRedirect = `/register/${t[0]}`;
});
ROUTE('/user/:uid', class UserDetailHandler {
constructor(ctx) { constructor(ctx) {
this.ctx = ctx; super(ctx);
this.ctx.templateName = 'user_detail.html'; this.response.template = 'user_detail.html';
} }
async get({ uid }) { async get({ uid }) {
let isSelfProfile = this.ctx.state.user._id == uid; let isSelfProfile = this.ctx.state.user._id == uid;
@@ -125,12 +139,8 @@ ROUTE('/user/:uid', class UserDetailHandler {
let sdoc = await token.getMostRecentSessionByUid(uid); let sdoc = await token.getMostRecentSessionByUid(uid);
this.ctx.body = { isSelfProfile, udoc, sdoc }; this.ctx.body = { isSelfProfile, udoc, sdoc };
} }
});
ROUTE('/user/search', class UserSearchHandler {
constructor(ctx) {
this.ctx = ctx;
} }
class UserSearchHandler extends Handler {
async get({ q, exact_match = false }) { async get({ q, exact_match = false }) {
let udocs; let udocs;
if (exact_match) udocs = []; if (exact_match) udocs = [];
@@ -146,4 +156,13 @@ ROUTE('/user/search', class UserSearchHandler {
udocs[i].gravatar_url = misc.gravatar_url[udocs[i].gravatar]; udocs[i].gravatar_url = misc.gravatar_url[udocs[i].gravatar];
this.ctx.body = { udocs }; this.ctx.body = { udocs };
} }
}); }
Route('/login', UserLoginHandler);
Route('/register', UserRegisterHandler);
Route('/register/:code', UserRegisterWithCodeHandler);
Route('/logout', UserLogoutHandler);
Route('/lostpass', UserLostPassHandler);
Route('/lostpass/:code', UserLostPassWithCodeHandler);
Route('/user/:uid', UserDetailHandler);
Route('/user/search', UserSearchHandler);
+2 -2
View File
@@ -10,12 +10,12 @@ String.prototype.format = function (args) {
if (arguments.length == 1 && typeof (args) == 'object') { if (arguments.length == 1 && typeof (args) == 'object') {
for (var key in args) for (var key in args)
if (args[key] != undefined) { if (args[key] != undefined) {
let reg = new RegExp('({' + key + '})', 'g'); let reg = new RegExp('(\\{' + key + '\\})', 'g');
result = result.replace(reg, args[key]); result = result.replace(reg, args[key]);
} }
} else for (var i = 0; i < arguments.length; i++) } else for (var i = 0; i < arguments.length; i++)
if (arguments[i] != undefined) { if (arguments[i] != undefined) {
let reg = new RegExp('({)' + i + '(})', 'g'); let reg = new RegExp('(\\{)' + i + '(\\})', 'g');
result = result.replace(reg, arguments[i]); result = result.replace(reg, arguments[i]);
} }
} }
+22
View File
@@ -0,0 +1,22 @@
const
hljs = require('highlight.js'),
MarkdownIt = require('markdown-it'),
katex = require('markdown-it-katex');
class Markdown extends MarkdownIt {
constructor() {
super({
linkify: true,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang))
try {
return hljs.highlight(lang, str).value;
} catch (__) { } // eslint-disable-line no-empty
return '';
}
});
this.linkify.tlds('.py', false);
this.use(katex);
}
}
module.exports = new Markdown();
+41
View File
@@ -0,0 +1,41 @@
const
path = require('path'),
nunjucks = require('nunjucks'),
markdown = require('./markdown'),
options = require('../options'),
perm = require('../permission'),
builtin = require('../model/builtin'),
model = require('../model'),
misc = require('../lib/misc');
class Nunjucks extends nunjucks.Environment {
constructor() {
super(
new nunjucks.FileSystemLoader(path.resolve(options.template.path)),
{ autoescape: true, trimBlocks: true }
);
this.addFilter('json', function (self) {
return JSON.stringify(self);
}, false);
this.addFilter('assign', function (self, data) {
return Object.assign(self, data);
});
this.addFilter('markdown', function (self) {
return markdown.render(self);
});
this.addFilter('gravatar_url', misc.gravatar_url);
this.addFilter('format_size', misc.format_size);
this.addGlobal('typeof', o => typeof o);
this.addGlobal('console', console);
this.addGlobal('static_url', str => `/${str}`);
this.addGlobal('reverse_url', str => str);
this.addGlobal('datetime_span', misc.datetime_span);
this.addGlobal('paginate', misc.paginate);
this.addGlobal('perm', perm);
this.addGlobal('status', builtin.STATUS);
this.addGlobal('model', model);
}
}
let env = new Nunjucks();
module.exports = env;
+54 -22
View File
@@ -1,18 +1,15 @@
const const
validator = require('../lib/validator'), validator = require('../lib/validator'),
{ ValidationError, ContestNotFoundError } = require('../error'), { ValidationError, ContestNotFoundError } = require('../error'),
RULE_HOMEWORK = require('../module/contest/homework'),
RULE_OI = require('../module/contest/oi'),
RULE_ACM = require('../module/contest/acm'),
db = require('../service/db.js'), db = require('../service/db.js'),
coll = db.collection('contest'), coll = db.collection('contest'),
coll_status = db.collection('contest.status'); coll_status = db.collection('contest.status');
const RULES = { const RULES = {
homework: RULE_HOMEWORK, homework: require('../module/contest/homework'),
oi: RULE_OI, oi: require('../module/contest/oi'),
acm: RULE_ACM acm: require('../module/contest/acm')
}; };
module.exports = { module.exports = {
@@ -28,26 +25,26 @@ module.exports = {
return await coll.insertOne(data); return await coll.insertOne(data);
}, },
count: query => coll.find(query).count(), count: query => coll.find(query).count(),
async edit(cid, $set) { async edit(tid, $set) {
if ($set.title) validator.checkTitle($set.title); if ($set.title) validator.checkTitle($set.title);
if ($set.content) validator.checkIntro($set.content); if ($set.content) validator.checkIntro($set.content);
if ($set.rule) if ($set.rule)
if (!this.RULES[$set.rule]) throw new ValidationError('rule'); if (!this.RULES[$set.rule]) throw new ValidationError('rule');
if ($set.beginAt && $set.endAt) if ($set.beginAt && $set.endAt)
if ($set.beginAt >= $set.endAt) throw new ValidationError('beginAt', 'endAt'); if ($set.beginAt >= $set.endAt) throw new ValidationError('beginAt', 'endAt');
let cdoc = await coll.findOne({ cid }); let tdoc = await coll.findOne({ tid });
if (!cdoc) throw new ContestNotFoundError(cid); if (!tdoc) throw new ContestNotFoundError(tid);
this.RULES[$set.rule || cdoc.rule].check(Object.assign(cdoc, $set)); this.RULES[$set.rule || tdoc.rule].check(Object.assign(tdoc, $set));
await coll.findOneAndUpdate({ cid }, { $set }); await coll.findOneAndUpdate({ tid }, { $set });
return cdoc;
},
async get( cid) {
let tdoc = await coll.findOne({ cid });
if (!tdoc) throw new ContestNotFoundError(cid);
return tdoc; return tdoc;
}, },
get_multi: (query, fields) => coll.find(query, { fields }), async get(tid) {
get_multi_status: (query, fields) => coll_status.find(query, { fields }), let tdoc = await coll.findOne({ tid });
if (!tdoc) throw new ContestNotFoundError(tid);
return tdoc;
},
getMulti: query => coll.find(query),
getMultiStatus: query => coll_status.find(query),
async get_random_id(query) { async get_random_id(query) {
let pdocs = coll.find(query); let pdocs = coll.find(query);
let pcount = await pdocs.count(); let pcount = await pdocs.count();
@@ -56,8 +53,43 @@ module.exports = {
return pdoc.pid; return pdoc.pid;
} else return null; } else return null;
}, },
get_status: (cid, uid, fields) => coll_status.findOne({ cid, uid }, { fields }), getStatus: (tid, uid) => coll_status.findOne({ tid, uid }),
set_status: (cid, uid, $set) => coll_status.findOneAndUpdate({ cid, uid }, { $set }) setStatus: (tid, uid, $set) => coll_status.findOneAndUpdate({ tid, uid }, { $set }),
async getListStatus(uid, tids) {
let r = {};
for (let tid of tids) r[tid] = await this.getStatus(tid, uid);
return r;
},
is_new(tdoc, days = 1) {
let now = new Date().getTime();
let readyAt = tdoc.beginAt.getTime();
return (now < readyAt - days * 24 * 3600 * 1000);
},
is_upcoming(tdoc, days = 1) {
let now = new Date().getTime();
let readyAt = tdoc.beginAt.getTime();
return (now > readyAt + days * 24 * 3600 * 1000 && now < tdoc.beginAt);
},
is_not_started: tdoc => new Date() < tdoc.beginAt,
is_ongoing(tdoc) {
let now = new Date();
return (tdoc.beginAt <= now && now < tdoc.endAt);
},
is_done: tdoc => tdoc.endAt <= new Date(),
status_text: tdoc =>
this.is_new(tdoc)
? 'New'
: this.is_upcoming(tdoc)
? 'Ready (☆▽☆)'
: this.is_ongoing(tdoc)
? 'Live...'
: 'Done',
get_status: tdoc =>
this.is_not_started(tdoc)
? 'not_started'
: this.is_ongoing(tdoc)
? 'ongoing'
: 'finished',
}; };
/* /*
@@ -275,9 +307,9 @@ class ContestVisibilityMixin(object):
if self.domainId != tdoc['domainId']: if self.domainId != tdoc['domainId']:
return False return False
if tdoc['doc_type'] == document.TYPE_CONTEST: if tdoc['doc_type'] == document.TYPE_CONTEST:
return self.has_perm(builtin.PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD) return self.hasPerm(builtin.PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD)
elif tdoc['doc_type'] == document.TYPE_HOMEWORK: elif tdoc['doc_type'] == document.TYPE_HOMEWORK:
return self.has_perm(builtin.PERM_VIEW_HOMEWORK_HIDDEN_SCOREBOARD) return self.hasPerm(builtin.PERM_VIEW_HOMEWORK_HIDDEN_SCOREBOARD)
else: else:
return False return False
+13
View File
@@ -0,0 +1,13 @@
module.exports = {
blacklist: require('./blacklist'),
builtin: require('./builtin'),
contest: require('./contest'),
opcount: require('./opcount'),
problem: require('./problem'),
record: require('./record'),
solution: require('./solution'),
system: require('./system'),
token: require('./token'),
training: require('./training'),
user: require('./user')
};
+5 -1
View File
@@ -63,6 +63,9 @@ async function getById(_id) {
async function getMany(query, sort, page, limit) { async function getMany(query, sort, page, limit) {
return await coll.find(query).sort(sort).skip((page - 1) * limit).limit(limit).toArray(); return await coll.find(query).sort(sort).skip((page - 1) * limit).limit(limit).toArray();
} }
function getMulti(query) {
return coll.find(query);
}
async function edit(_id, $set) { async function edit(_id, $set) {
if ($set.title) validator.checkTitle($set.title); if ($set.title) validator.checkTitle($set.title);
if ($set.content) validator.checkContent($set.content); if ($set.content) validator.checkContent($set.content);
@@ -90,5 +93,6 @@ module.exports = {
edit, edit,
count, count,
random, random,
getById getById,
getMulti
}; };
+1 -1
View File
@@ -66,7 +66,7 @@ module.exports = {
return !!result.deletedCount; return !!result.deletedCount;
}, },
async getMostRecentSessionByUid(uid) { async getMostRecentSessionByUid(uid) {
return await coll.findOne({ data: { uid }, token_type: this.TYPE_SESSION }, { sort: { updateAt: -1 } }); return await coll.findOne({ uid, token_type: this.TYPE_SESSION }, { sort: { updateAt: -1 } });
}, },
init: () => Promise.all([ init: () => Promise.all([
coll.createIndex([{ uid: 1 }, { tokenType: 1 }, { updateAt: -1 }], { sparse: true }), coll.createIndex([{ uid: 1 }, { tokenType: 1 }, { updateAt: -1 }], { sparse: true }),
+1
View File
@@ -1,4 +1,5 @@
module.exports = { module.exports = {
TEXT: 'ACM/ICPC',
check: () => { }, check: () => { },
stat: (tdoc, journal) => { stat: (tdoc, journal) => {
let naccept = {}, effective = {}, detail = [], accept = 0, time = 0; let naccept = {}, effective = {}, detail = [], accept = 0, time = 0;
+1
View File
@@ -1,5 +1,6 @@
const { ValidationError } = require('../../error'); const { ValidationError } = require('../../error');
module.exports = { module.exports = {
TEXT: 'Assignment',
check(data) { check(data) {
if (!data.penalty_since) throw new ValidationError('penalty_since'); if (!data.penalty_since) throw new ValidationError('penalty_since');
if (data.penalty_since < data.begin_at) throw new ValidationError('penalty_since', 'begin_at'); if (data.penalty_since < data.begin_at) throw new ValidationError('penalty_since', 'begin_at');
+1
View File
@@ -1,4 +1,5 @@
module.exports = { module.exports = {
TEXT: 'OI',
check: () => { }, check: () => { },
stat: (tdoc, journal) => { stat: (tdoc, journal) => {
let detail = {}, score = 0; let detail = {}, score = 0;
+2 -1
View File
@@ -40,7 +40,8 @@ let options = {
constants: { constants: {
PROBLEM_PER_PAGE: 100, PROBLEM_PER_PAGE: 100,
RECORD_PER_PAGE: 100, RECORD_PER_PAGE: 100,
SOLUTION_PER_PAGE: 20 SOLUTION_PER_PAGE: 20,
CONTEST_PER_PAGE: 20
} }
}; };
+257 -64
View File
@@ -1,17 +1,29 @@
const const
path = require('path'),
{ ObjectID } = require('bson'),
Koa = require('koa'), Koa = require('koa'),
morgan = require('koa-morgan'), morgan = require('koa-morgan'),
Body = require('koa-body'), Body = require('koa-body'),
Router = require('koa-router'), Router = require('koa-router'),
cache = require('koa-static-cache'),
sockjs = require('sockjs'), sockjs = require('sockjs'),
validator = require('../lib/validator'); validator = require('../lib/validator'),
template = require('../lib/template'),
user = require('../model/user'),
blacklist = require('../model/blacklist'),
token = require('../model/token'),
opcount = require('../model/opcount'),
{ UserNotFoundError, BlacklistedError, PermissionError,
NotFoundError } = require('../error');
const options = require('../options'); const options = require('../options');
let http = options.listen.https ? require('https') : require('http'); let http = options.listen.https ? require('https') : require('http');
let app = new Koa(); let app = new Koa();
let server = http.createServer(app.callback()); let server = http.createServer(app.callback());
app.keys = options.session.keys; app.keys = options.session.keys;
app.use(cache(path.join(process.cwd(), '.uibuild'), {
maxAge: 365 * 24 * 60 * 60
}));
app.use(Body({ app.use(Body({
multipart: true, multipart: true,
formidable: { formidable: {
@@ -19,121 +31,302 @@ app.use(Body({
} }
})); }));
let router = new Router(); let router = new Router();
let m = [];
class Handler {
/** /**
* @param {import('koa').Middleware} middleware * @param {import('koa').Context} ctx
* @param {boolean} installForSocket
*/ */
function MIDDLEWARE(middleware, installForSocket = false) { constructor(ctx) {
app.use(middleware); this.ctx = ctx;
if (installForSocket) m.push(middleware); this.request = {
ip: ctx.request.ip,
headers: ctx.request.headers,
cookies: ctx.cookies,
body: ctx.request.body,
files: ctx.request.files,
query: ctx.query,
path: ctx.path
};
this.response = {
body: '',
type: '',
status: 404,
template: null,
redirect: null,
attachment: name => ctx.attachment(name)
};
this.UIContext = {
cdn_prefix: '/',
url_prefix: '/'
};
this._handler = {};
} }
/** renderHTML(name, context) {
* @param {string} route console.time(name);
* @param {...import('koa').Middleware} handler this.hasPerm = perm => this.user.hasPerm(perm);
*/ return new Promise((resolve, reject) => {
function GET(route, ...handler) { template.render(name, Object.assign(context, {
router.get(route, ...handler); handler: this,
_: str => str ? str.toString().translate(this.user.language) : '',
user: this.user
}), (error, res) => {
console.timeEnd(name);
if (error) reject(error);
else resolve(res);
});
});
} }
/** async render(name, context) {
* @param {string} route this.response.body = await this.renderHTML(name, context);
* @param {...import('koa').Middleware} handler this.response.type = 'text/html';
*/
function POST(route, ...handler) {
router.post(route, ...handler);
} }
/** render_title(str) {
* @param {string} route return str;
* @param {...import('koa').Middleware} handler
*/
function ALL(route, ...handler) {
router.all(route, ...handler);
} }
/** checkPerm(perm) {
* @param {string} route for (let i in arguments) {
* @param {class} handler if (arguments[i] instanceof Array) {
*/ let p = false;
function ROUTE(route, handler) { for (let j in arguments)
if (this.user.hasPerm(arguments[i][j])) {
p = true;
break;
}
if (!p) throw new PermissionError([arguments[i]]);
} else {
if (this.user.hasPerm(arguments[i])) continue;
else throw new PermissionError([[arguments[i]]]);
}
}
}
async limitRate(op, period_secs, max_operations) {
await opcount.inc(op, this.request.ip, period_secs, max_operations);
}
back() {
this.ctx.redirect(this.request.headers.referer || '/');
}
async ___prepare() {
this._handler.sid = this.request.cookies.get('sid');
this._handler.save = this.request.cookies.get('save');
this._handler.tokenType = token.TYPE_SESSION;
if (this._handler.save) this._handler.expireSeconds = options.session.saved_expire_seconds;
else this._handler.expireSeconds = options.session.unsaved_expire_seconds;
this.session = this._handler.sid ?
await token.update(this._handler.sid, this._handler.tokenType, this._handler.expireSeconds, {
update_ip: this.request.ip,
update_ua: this.request.headers['user-agent'] || ''
}) : { uid: 1 };
if (!this.session) this.session = { uid: 1 };
let bdoc = await blacklist.get(this.request.ip);
if (bdoc) throw new BlacklistedError(this.request.ip);
this.user = await user.getById(this.session.uid);
console.log(this.user, this.session.uid);
if (!this.user) throw new UserNotFoundError(this.session.uid);
this.csrf_token = (await token.add(token.TYPE_CSRF_TOKEN, 600, this.request.path))[0];
this.preferJson = (this.request.headers['accept'] || '').includes('application/json');
}
async ___cleanup() {
try {
await this.renderBody();
} catch (e) {
try {
let error;
if (this.response.body && this.response.body.error) error = this.response.body.error;
else error = e;
if (error instanceof NotFoundError) this.response.status = 404;
if (error.name == 'Template render error') throw error;
if (this.preferJson) this.response.body = { error };
else await this.render('error.html', { error });
} catch (error) {
if (this.preferJson) this.response.body = { error };
else await this.render('bsod.html', { error });
}
}
await this.putResponse();
await this.saveCookie();
}
async renderBody() {
if (this.response.body || this.response.template) {
if (this.request.query.noTemplate || this.preferJson) return;
if (this.request.query.template || this.response.template) {
this.response.body = this.response.body || {};
await this.render(this.request.query.template || this.response.template, this.response.body);
}
}
}
async putResponse() {
if (this.response.redirect) {
this.response.type = 'application/octet-stream';
this.redirect(this.response.redirect);
}
if (this.response.body) this.ctx.body = this.response.body;
if (this.response.type) this.ctx.response.type = this.response.type;
if (this.response.status) this.ctx.response.status = this.response.status;
}
async saveCookie() {
if (this.session.sid)
await token.update(this.session.sid, this._handler.tokenType, this._handler.expireSeconds, {
updateIp: this.request.ip,
updateUa: this.request.headers['user-agent'] || ''
});
else
[this.session.sid] = await token.add(this._handler.tokenType, this._handler.expireSeconds, {
createIp: this.request.ip,
createUa: this.request.headers['user-agent'] || '',
updateIp: this.request.ip,
updateUa: this.request.headers['user-agent'] || '',
...this.session
});
let cookie = { secure: options.session.secure };
if (this._handler.save) {
cookie.expires = this.session.expireAt, cookie.maxAge = this._handler.expireSeconds;
this.request.cookies.set('save', 'true', cookie);
}
this.ctx.cookies.set('sid', this.session.sid, cookie);
}
async onerror(e) {
console.error(e.message, e.params);
console.error(e.stack);
await this.___cleanup();
}
}
function Route(route, handler) {
router.all(route, async (ctx) => { router.all(route, async (ctx) => {
let h = new handler(ctx); let h = new handler(ctx);
try {
let method = ctx.method.toLowerCase(); let method = ctx.method.toLowerCase();
let args = Object.assign({}, ctx.params, ctx.query, ctx.request.body); let args = Object.assign({}, ctx.params, ctx.query, ctx.request.body);
if (args.content) validator.checkContent(args.content); if (args.content) validator.checkContent(args.content);
if (args.title) validator.checkContent(args.title); if (args.title) validator.checkContent(args.title);
if (args.uid) args.uid = parseInt(validator.checkUid(args.uid)); if (args.uid) args.uid = parseInt(validator.checkUid(args.uid));
if (args.page) args.page = parseInt(args.page);
if (args.rid) args.rid = new ObjectID(args.rid);
if (args.tid) args.tid = new ObjectID(args.tid);
if (h.___prepare) await h.___prepare(args);
if (h.__prepare) await h.__prepare(args);
if (h._prepare) await h._prepare(args); if (h._prepare) await h._prepare(args);
if (h.prepare) await h.prepare(args); if (h.prepare) await h.prepare(args);
if (h[`___${method}`]) await h[`___${method}`](args);
if (h[`__${method}`]) await h[`__${method}`](args);
if (h[`_${method}`]) await h[`_${method}`](args); if (h[`_${method}`]) await h[`_${method}`](args);
if (h[method]) await h[method](args); if (h[method]) await h[method](args);
console.log(ctx.request.body); console.log(ctx.request.body);
if (method == 'post' && ctx.request.body.operation) { if (method == 'post' && ctx.request.body.operation) {
if (h[`${method}_${ctx.request.body.operation}`]) if (h[`${method}_${ctx.request.body.operation}`])
await h[`${method}_${ctx.request.body.operation}`](args); await h[`${method}_${ctx.request.body.operation}`](args);
} }
if (h.cleanup) await h.cleanup(args);
if (h._cleanup) await h._cleanup(args);
if (h.__cleanup) await h.__cleanup(args);
if (h.___cleanup) await h.___cleanup(args);
} catch (e) {
if (h.onerror) await h.onerror(e);
}
}); });
} }
class ConnectionHandler {
/** /**
* @callback SockJSHandler
* @param {import('sockjs').Connection} conn * @param {import('sockjs').Connection} conn
*/ */
/** constructor(conn) {
* @param {string} prefix this.conn = conn;
* @param {SockJSHandler} handler this.request = {
*/ cookies: {
function SOCKET(prefix, middlewares, handler) {
const sock = sockjs.createServer({ prefix });
sock.on('connection', async conn => {
try {
conn.cookies = {
get(name) { get(name) {
return conn.cookies[name]; return conn.cookies[name];
}, },
set() { } set() { }
}; },
conn.state = {}; params: {},
conn.params = {};
conn.request = {
headers: conn.headers headers: conn.headers
}; };
let p = (conn.url.split('?')[1] || '').split('&'); let p = (conn.url.split('?')[1] || '').split('&');
for (let i in p) p[i] = p[i].split('='); for (let i in p) p[i] = p[i].split('=');
for (let i in p) conn.params[p[i][0]] = decodeURIComponent(p[i][1]); for (let i in p) conn.params[p[i][0]] = decodeURIComponent(p[i][1]);
}
renderHTML(name, context) {
console.time(name);
this.hasPerm = perm => this.user.hasPerm(perm);
return new Promise((resolve, reject) => {
template.render(name, Object.assign(context, {
handler: this,
_: this.translate,
user: this.user
}), (error, res) => {
console.timeEnd(name);
if (error) reject(error);
else resolve(res);
});
});
}
send(data) {
this.conn.write(JSON.stringify(data));
}
close(code, reason) {
this.conn.close(code, reason);
}
async ___prepare() {
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
conn.once('data', msg => { this.conn.once('data', msg => {
for (let i of msg.split(';')) { for (let i of msg.split(';')) {
i = i.trim().split('='); i = i.trim().split('=');
conn.cookies[i[0]] = i[1]; this.request.cookies[i[0]] = i[1];
} }
resolve(); resolve();
}); });
setTimeout(reject, 5000); setTimeout(reject, 5000);
}); });
for (let i of m) this._handler.sid = this.request.cookies.get('sid');
await new Promise((resolve, reject) => { this.session = this._handler.sid ? await token.get(this._handler.sid, token.TYPE_SESSION) : { uid: 1 };
i(conn, resolve).catch(reject); if (!this.session) this.session = { uid: 1 };
let bdoc = await blacklist.get(this.request.ip);
if (bdoc) throw new BlacklistedError(this.request.ip);
this.user = await user.getById(this.session.uid);
if (!this.user) throw new UserNotFoundError(this.session.uid);
}
}
function Connection(prefix, handler) {
const sock = sockjs.createServer({ prefix });
sock.on('connection', async conn => {
let h = new handler(conn);
try {
let args = Object.assign({}, h.conn.params);
if (args.uid) args.uid = parseInt(validator.checkUid(args.uid));
if (args.page) args.page = parseInt(args.page);
if (args.rid) args.rid = new ObjectID(args.rid);
if (args.tid) args.tid = new ObjectID(args.tid);
if (h.___prepare) await h.___prepare(args);
if (h.__prepare) await h.__prepare(args);
if (h._prepare) await h._prepare(args);
if (h.prepare) await h.prepare(args);
if (h.message) conn.on('data', data => {
h.message(JSON.parse(data));
}); });
for (let i of middlewares) conn.on('close', async () => {
await new Promise((resolve, reject) => { if (h.cleanup) await h.cleanup(args);
i(conn, resolve).catch(reject); if (h._cleanup) await h._cleanup(args);
if (h.__cleanup) await h.__cleanup(args);
if (h.___cleanup) await h.___cleanup(args);
}); });
conn.send = data => {
conn.write(JSON.stringify(data));
};
handler(conn);
} catch (e) { } catch (e) {
console.error(e); if (h.onerror) await h.onerror(e);
} }
}); });
sock.installHandlers(server); sock.installHandlers(server);
} }
exports.ROUTE = ROUTE; exports.Handler = Handler;
exports.MIDDLEWARE = MIDDLEWARE; exports.ConnectionHandler = ConnectionHandler;
exports.GET = GET; exports.Route = Route;
exports.POST = POST; exports.Connection = Connection;
exports.ALL = ALL;
exports.SOCKET = SOCKET;
exports.start = function start() { exports.start = function start() {
app.use(morgan(':method :url :status :res[content-length] - :response-time ms')); app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
app.use(router.routes()).use(router.allowedMethods()); app.use(router.routes()).use(router.allowedMethods());
+1 -1
View File
@@ -688,7 +688,7 @@ Recent Submissions: 最近递交
Oh, the user hasn't submitted yet!: 这个用户还没有交过题 _(:зゝ∠)_ Oh, the user hasn't submitted yet!: 这个用户还没有交过题 _(:зゝ∠)_
Oh, the user hasn't created any discussions yet!: 这个用户还没有发布过讨论 Oh, the user hasn't created any discussions yet!: 这个用户还没有发布过讨论
Recently Created Discussions: 最近创建的讨论 Recently Created Discussions: 最近创建的讨论
Oh, the user doesn't have any contributions!: 啊哦,这个用户还没贡献过题目和题解~ Oh, the user doesn't have any contributions!: 啊哦,这个用户还没贡献过题目~
Recent Solutions: 最近编写的题解 Recent Solutions: 最近编写的题解
Most Upvoted Solutions: 最被赞同的题解 Most Upvoted Solutions: 最被赞同的题解
The user is too lazy to leave something here...: 该用户太懒,这里啥也没写 (´・ω・`) The user is too lazy to leave something here...: 该用户太懒,这里啥也没写 (´・ω・`)
@@ -28,15 +28,15 @@
{% macro reply_operations(doc, rdoc) %} {% macro reply_operations(doc, rdoc) %}
<div class="dczcomments__operations nojs--hide"> <div class="dczcomments__operations nojs--hide">
{% if handler.has_perm(reply_post_perm) %} {% if handler.hasPerm(reply_post_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Reply') }}" name="dczcomments__op-reply-reply"><span class="icon icon-reply"></span></a> <a href="javascript:;" data-tooltip="{{ _('Reply') }}" name="dczcomments__op-reply-reply"><span class="icon icon-reply"></span></a>
{% endif %} {% endif %}
{% if doc.owner == handler.state.user._id or handler.has_perm(reply_edit_perm) %} {% if doc.owner == handler.state.user._id or handler.hasPerm(reply_edit_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Edit') }}" name="dczcomments__op-edit-reply" <a href="javascript:;" data-tooltip="{{ _('Edit') }}" name="dczcomments__op-edit-reply"
data-form="{&quot;operation&quot;:&quot;{{reply_edit_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;,&quot;{{reply_ref}}&quot;:&quot;{{rdoc._id}}&quot;}" data-form="{&quot;operation&quot;:&quot;{{reply_edit_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;,&quot;{{reply_ref}}&quot;:&quot;{{rdoc._id}}&quot;}"
><span class="icon icon-edit"></span></a> ><span class="icon icon-edit"></span></a>
{% endif %} {% endif %}
{% if doc.owner == handler.state.user._id or handler.has_perm(reply_delete_perm) %} {% if doc.owner == handler.state.user._id or handler.hasPerm(reply_delete_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Delete') }}" name="dczcomments__op-delete-reply" <a href="javascript:;" data-tooltip="{{ _('Delete') }}" name="dczcomments__op-delete-reply"
data-form="{&quot;operation&quot;:&quot;{{reply_delete_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;,&quot;{{reply_ref}}&quot;:&quot;{{rdoc._id}}&quot;}" data-form="{&quot;operation&quot;:&quot;{{reply_delete_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;,&quot;{{reply_ref}}&quot;:&quot;{{rdoc._id}}&quot;}"
><span class="icon icon-delete"></span></a> ><span class="icon icon-delete"></span></a>
@@ -71,7 +71,7 @@
reply_delete_op = 'delete_tail_reply' reply_delete_op = 'delete_tail_reply'
) %} ) %}
<ul class="dczcomments__list view--discussion"> <ul class="dczcomments__list view--discussion">
{% if handler.has_perm(comment_post_perm) %} {% if handler.hasPerm(comment_post_perm) %}
<li class="dczcomments__item"> <li class="dczcomments__item">
<div class="media"> <div class="media">
<div class="media__left top"> <div class="media__left top">
@@ -116,17 +116,17 @@
@ {{ datetime_span(doc['_id'])|safe }} @ {{ datetime_span(doc['_id'])|safe }}
</div> </div>
<div class="dczcomments__operations nojs--hide"> <div class="dczcomments__operations nojs--hide">
{% if handler.has_perm(reply_post_perm) %} {% if handler.hasPerm(reply_post_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Reply') }}" name="dczcomments__op-reply-comment" <a href="javascript:;" data-tooltip="{{ _('Reply') }}" name="dczcomments__op-reply-comment"
data-form="{&quot;operation&quot;:&quot;{{reply_post_op}}&quot;, &quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}" data-form="{&quot;operation&quot;:&quot;{{reply_post_op}}&quot;, &quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}"
><span class="icon icon-reply"></span></a> ><span class="icon icon-reply"></span></a>
{% endif %} {% endif %}
{% if doc.owner == handler.state.user._id or handler.has_perm(comment_edit_perm) %} {% if doc.owner == handler.state.user._id or handler.hasPerm(comment_edit_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Edit') }}" name="dczcomments__op-edit-comment" <a href="javascript:;" data-tooltip="{{ _('Edit') }}" name="dczcomments__op-edit-comment"
data-form="{&quot;operation&quot;:&quot;{{comment_edit_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}" data-form="{&quot;operation&quot;:&quot;{{comment_edit_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}"
><span class="icon icon-edit"></span></a> ><span class="icon icon-edit"></span></a>
{% endif %} {% endif %}
{% if doc.owner == handler.state.user._id or handler.has_perm(comment_delete_perm) %} {% if doc.owner == handler.state.user._id or handler.hasPerm(comment_delete_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Delete') }}" name="dczcomments__op-delete-comment" <a href="javascript:;" data-tooltip="{{ _('Delete') }}" name="dczcomments__op-delete-comment"
data-form="{&quot;operation&quot;:&quot;{{comment_delete_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}" data-form="{&quot;operation&quot;:&quot;{{comment_delete_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}"
><span class="icon icon-delete"></span></a> ><span class="icon icon-delete"></span></a>
+8 -8
View File
@@ -30,7 +30,7 @@
reply_delete_op = 'delete_tail_reply' reply_delete_op = 'delete_tail_reply'
) %} ) %}
<ul class="dczcomments__list view--solution"> <ul class="dczcomments__list view--solution">
{% if handler.has_perm(comment_post_perm) %} {% if handler.hasPerm(comment_post_perm) %}
<li class="dczcomments__item"> <li class="dczcomments__item">
<div class="media"> <div class="media">
<div class="media__left top"> <div class="media__left top">
@@ -85,7 +85,7 @@
<div class="media"> <div class="media">
<div class="media__left top"> <div class="media__left top">
<div class="vote vote--discussion"> <div class="vote vote--discussion">
{% if handler.has_perm(perm.PERM_VOTE_PROBLEM_SOLUTION) %} {% if handler.hasPerm(perm.PERM_VOTE_PROBLEM_SOLUTION) %}
<div class="vote-number rotator--enabled">{{ doc.vote }}</div> <div class="vote-number rotator--enabled">{{ doc.vote }}</div>
<div class="vote-op clearfix"> <div class="vote-op clearfix">
<form method="post"> <form method="post">
@@ -113,17 +113,17 @@
@ {{ datetime_span(doc._id)|safe }} @ {{ datetime_span(doc._id)|safe }}
</div> </div>
<div class="dczcomments__operations nojs--hide"> <div class="dczcomments__operations nojs--hide">
{% if handler.has_perm(reply_post_perm) %} {% if handler.hasPerm(reply_post_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Reply') }}" name="dczcomments__op-reply-comment" <a href="javascript:;" data-tooltip="{{ _('Reply') }}" name="dczcomments__op-reply-comment"
data-form="{&quot;operation&quot;:&quot;{{reply_post_op}}&quot;, &quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}" data-form="{&quot;operation&quot;:&quot;{{reply_post_op}}&quot;, &quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}"
><span class="icon icon-reply"></span></a> ><span class="icon icon-reply"></span></a>
{% endif %} {% endif %}
{% if doc.owner == handler.state.user._id or handler.has_perm(comment_edit_perm) %} {% if doc.owner == handler.state.user._id or handler.hasPerm(comment_edit_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Edit') }}" name="dczcomments__op-edit-comment" <a href="javascript:;" data-tooltip="{{ _('Edit') }}" name="dczcomments__op-edit-comment"
data-form="{&quot;operation&quot;:&quot;{{comment_edit_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}" data-form="{&quot;operation&quot;:&quot;{{comment_edit_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}"
><span class="icon icon-edit"></span></a> ><span class="icon icon-edit"></span></a>
{% endif %} {% endif %}
{% if doc.owner == handler.state.user._id or handler.has_perm(comment_delete_perm) %} {% if doc.owner == handler.state.user._id or handler.hasPerm(comment_delete_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Delete') }}" name="dczcomments__op-delete-comment" <a href="javascript:;" data-tooltip="{{ _('Delete') }}" name="dczcomments__op-delete-comment"
data-form="{&quot;operation&quot;:&quot;{{comment_delete_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}" data-form="{&quot;operation&quot;:&quot;{{comment_delete_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;}"
><span class="icon icon-delete"></span></a> ><span class="icon icon-delete"></span></a>
@@ -145,15 +145,15 @@
{{ user.render_inline(udoc, badge=false) }} @ {{ datetime_span(rdoc['_id'])|safe }} {{ user.render_inline(udoc, badge=false) }} @ {{ datetime_span(rdoc['_id'])|safe }}
</div> </div>
<div class="dczcomments__operations nojs--hide"> <div class="dczcomments__operations nojs--hide">
{% if handler.has_perm(reply_post_perm) %} {% if handler.hasPerm(reply_post_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Reply') }}" name="dczcomments__op-reply-reply"><span class="icon icon-reply"></span></a> <a href="javascript:;" data-tooltip="{{ _('Reply') }}" name="dczcomments__op-reply-reply"><span class="icon icon-reply"></span></a>
{% endif %} {% endif %}
{% if doc.owner == handler.state.user._id or handler.has_perm(reply_edit_perm) %} {% if doc.owner == handler.state.user._id or handler.hasPerm(reply_edit_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Edit') }}" name="dczcomments__op-edit-reply" <a href="javascript:;" data-tooltip="{{ _('Edit') }}" name="dczcomments__op-edit-reply"
data-form="{&quot;operation&quot;:&quot;{{reply_edit_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;,&quot;{{reply_ref}}&quot;:&quot;{{rdoc._id}}&quot;}" data-form="{&quot;operation&quot;:&quot;{{reply_edit_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;,&quot;{{reply_ref}}&quot;:&quot;{{rdoc._id}}&quot;}"
><span class="icon icon-edit"></span></a> ><span class="icon icon-edit"></span></a>
{% endif %} {% endif %}
{% if doc.owner == handler.state.user._id or handler.has_perm(reply_delete_perm) %} {% if doc.owner == handler.state.user._id or handler.hasPerm(reply_delete_perm) %}
<a href="javascript:;" data-tooltip="{{ _('Delete') }}" name="dczcomments__op-delete-reply" <a href="javascript:;" data-tooltip="{{ _('Delete') }}" name="dczcomments__op-delete-reply"
data-form="{&quot;operation&quot;:&quot;{{reply_delete_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;,&quot;{{reply_ref}}&quot;:&quot;{{rdoc._id}}&quot;}" data-form="{&quot;operation&quot;:&quot;{{reply_delete_op}}&quot;,&quot;{{comment_ref}}&quot;:&quot;{{doc._id}}&quot;,&quot;{{reply_ref}}&quot;:&quot;{{rdoc._id}}&quot;}"
><span class="icon icon-delete"></span></a> ><span class="icon icon-delete"></span></a>
+5 -5
View File
@@ -1,12 +1,12 @@
{% macro form_begin(args) %} {% macro form_begin(args) %}
{% set label = args.label %} {% set label = args.label %}
{% set columns = args.columns %} {% set columns = args.columns %}
{% set last_column = args.last_column or true %} {% set last_column = args.last_column|default(true) %}
{% set required = args.required or false %} {% set required = args.required or false %}
{% set hotkeys = args.hotkeys or none %} {% set hotkeys = args.hotkeys or none %}
{% set row = args.row or true %} {% set row = args.row|default(true) %}
{% set no_label = args.no_label or false %} {% set no_label = args.no_label or false %}
{% set label_wrap = args.label_wrap or true %} {% set label_wrap = args.label_wrap|default(true) %}
{% if row %} {% if row %}
<div class="row"> <div class="row">
{% endif %} {% endif %}
@@ -28,9 +28,9 @@
{% macro form_end(args) %} {% macro form_end(args) %}
{% set help_text = args.help_text or none %} {% set help_text = args.help_text or none %}
{% set row = args.row or true %} {% set row = args.row|default(true) %}
{% set no_label = args.no_label or false %} {% set no_label = args.no_label or false %}
{% set label_wrap = args.label_wrap or true %} {% set label_wrap = args.label_wrap|default(true) %}
{% if not no_label and label_wrap %} {% if not no_label and label_wrap %}
</label> </label>
{% endif %} {% endif %}
+1 -1
View File
@@ -13,7 +13,7 @@
</a> </a>
{% if badge %} {% if badge %}
<a class="user-profile-badge v-center badge--lv{{ udoc['level']|default(0) }}" href="/u/{{ udoc['_id']|default(0) }}" title="LV {{ udoc['level']|default(0) }}: Top {{ builtin.LEVELS[udoc['level']|default(0)]|default('N/A') }}%">LV {{ udoc['level']|default(0) }}</a> <a class="user-profile-badge v-center badge--lv{{ udoc['level']|default(0) }}" href="/u/{{ udoc['_id']|default(0) }}" title="LV {{ udoc['level']|default(0) }}: Top {{ builtin.LEVELS[udoc['level']|default(0)]|default('N/A') }}%">LV {{ udoc['level']|default(0) }}</a>
{% if modbadge and handler.has_perm(perm.PERM_MOD_BADGE) %} {% if modbadge and handler.hasPerm(perm.PERM_MOD_BADGE) %}
<span class="user-profile-badge v-center badge--mod" title="Moderator">MOD</span> <span class="user-profile-badge v-center badge--mod" title="Moderator">MOD</span>
{% endif %} {% endif %}
{% endif %} {% endif %}
+3 -3
View File
@@ -24,7 +24,7 @@
<div class="section__body no-padding"> <div class="section__body no-padding">
<table class="data-table"> <table class="data-table">
<colgroup> <colgroup>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<col class="col--status"> <col class="col--status">
<col class="col--submit-at"> <col class="col--submit-at">
{% endif %} {% endif %}
@@ -32,7 +32,7 @@
</colgroup> </colgroup>
<thead> <thead>
<tr> <tr>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<th class="col--status record-status--border">{{ _('Status') }}</th> <th class="col--status record-status--border">{{ _('Status') }}</th>
<th class="col--submit-at">{{ _('Last Submit At') }}</th> <th class="col--submit-at">{{ _('Last Submit At') }}</th>
{% endif %} {% endif %}
@@ -42,7 +42,7 @@
<tbody> <tbody>
{% for pid in tdoc['pids'] %} {% for pid in tdoc['pids'] %}
<tr> <tr>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
{% if psdict[pid] and psdict[pid]['rid'] %} {% if psdict[pid] and psdict[pid]['rid'] %}
{% with rdoc=rdict[psdict[pid]['rid']] %} {% with rdoc=rdict[psdict[pid]['rid']] %}
{% if handler.can_show_record(tdoc) %} {% if handler.can_show_record(tdoc) %}
+55 -7
View File
@@ -6,15 +6,63 @@
<div class="section__body"> <div class="section__body">
<form method="post"> <form method="post">
<div class="row"> <div class="row">
{{ form.form_select(columns=4, label='Rule', name='rule', options=rules, value=tdoc['rule']|default(''), row=False) }} {{ form.form_select({
{{ form.form_text(columns=8, label='Title', name='title', placeholder=_('title'), value=tdoc['title']|default(''), autofocus=True, row=False) }} columns:4,
label:'Rule',
name:'rule',
options:rules,
value:tdoc['rule']|default(''),
row:false
}) }}
{{ form.form_text({
columns:8,
label:'Title',
name:'title',
placeholder:_('title'),
value:tdoc['title']|default(''),
autofocus:true,
row:false
}) }}
</div><div class="row"> </div><div class="row">
{{ form.form_text(columns=4, label='Begin Date', name='begin_at_date', placeholder='YYYY-mm-dd', value=date_text, date=True, row=False) }} {{ form.form_text({
{{ form.form_text(columns=4, label='Begin Time', name='begin_at_time', placeholder='HH:MM', value=time_text, time=True, row=False) }} columns:4,
{{ form.form_text(columns=4, label='Duration (hours)', name='duration', value=duration|default('3'), row=False) }} label:'Begin Date',
name:'beginAtDate',
placeholder:'YYYY-mm-dd',
value:date_text,
date:true,
row:false
}) }}
{{ form.form_text({
columns:4,
label:'Begin Time',
name:'beginAtTime',
placeholder:'HH:MM',
value:time_text,
time:true,
row:false
}) }}
{{ form.form_text({
columns:4,
label:'Duration (hours)',
name:'duration',
value:duration|default('3'),
row:false
}) }}
</div> </div>
{{ form.form_text(columns=None, label='Problems', name='pids', value=pids) }} {{ form.form_text({
{{ form.form_textarea(columns=None, label='Content', name='content', value=tdoc['content']|default(''), markdown=True) }} columns:null,
label:'Problems',
name:'pids',
value:pids
}) }}
{{ form.form_textarea({
columns:null,
label:'Content',
name:'content',
value:tdoc['content']|default(''),
markdown:true
}) }}
<div class="row"><div class="columns"> <div class="row"><div class="columns">
<input type="hidden" name="csrf_token" value="{{ handler.csrf_token }}"> <input type="hidden" name="csrf_token" value="{{ handler.csrf_token }}">
{% if page_name == 'contest_edit' %} {% if page_name == 'contest_edit' %}
+16 -15
View File
@@ -1,3 +1,4 @@
{% set page_name = "contest_main" %}
{% extends "layout/basic.html" %} {% extends "layout/basic.html" %}
{% import "components/contest.html" as contest with context %} {% import "components/contest.html" as contest with context %}
{% macro render_important_contest(view, title, tdoc) %} {% macro render_important_contest(view, title, tdoc) %}
@@ -12,15 +13,15 @@
<ul class="info"> <ul class="info">
<li> <li>
<span class="icon icon-award"></span> <span class="icon icon-award"></span>
{{ _('Rule') }}: {{ vj4.constant.contest.RULE_TEXTS[tdoc['rule']] }} {{ _('Rule') }}: {{ model.contest.RULES[tdoc['rule']].TEXT }}
</li> </li>
<li> <li>
<span class="icon icon-calendar"></span> <span class="icon icon-calendar"></span>
{{ _('Start at') }}: {{ contest.render_time(tdoc['begin_at']) }} {{ _('Start at') }}: {{ model.contest.render_time(tdoc['beginAt']) }}
</li> </li>
<li> <li>
<span class="icon icon-schedule--fill"></span> <span class="icon icon-schedule--fill"></span>
{{ _('Duration') }}: {{ contest.render_duration(tdoc) }} {{ _('hour(s)') }} {{ _('Duration') }}: {{ model.contest.render_duration(tdoc) }} {{ _('hour(s)') }}
</li> </li>
<li> <li>
<span class="icon icon-user--multiple"></span> <span class="icon icon-user--multiple"></span>
@@ -33,7 +34,7 @@
<div class="section__body"> <div class="section__body">
<a href="/t/{{ tdoc._id }}" class="detail-button">{{ _('View Details') }}</a> <a href="/t/{{ tdoc._id }}" class="detail-button">{{ _('View Details') }}</a>
<div class="typo text-center"> <div class="typo text-center">
{% if tsdict[tdoc['doc_id']]['attend'] == 1 %} {% if tsdict[tdoc._id].attend %}
<p><span class="icon icon-check"></span> {{ _('Attended') }}</p> <p><span class="icon icon-check"></span> {{ _('Attended') }}</p>
{% else %} {% else %}
<p><span class="icon icon-schedule"></span> {{ _('Not Attended') }}</p> <p><span class="icon icon-schedule"></span> {{ _('Not Attended') }}</p>
@@ -56,14 +57,14 @@
{% endfor %} {% endfor %}
<div class="section"> <div class="section">
<div class="section__header"> <div class="section__header">
<h1 class="section__title">{% if not rule %}{{ _('All Contests') }}{% else %}{{ _('All {0} Contests').format(_(vj4.constant.contest.RULE_TEXTS[rule])) }}{% endif %}</h1> <h1 class="section__title">{% if not rule %}{{ _('All Contests') }}{% else %}{{ _('All {0} Contests').format(_(model.contest.RULES[rule].TEXT)) }}{% endif %}</h1>
<div class="section__tools"> <div class="section__tools">
<form method="get" name="filter-form"> <form method="get" name="filter-form">
{{ _('Show') }}: {{ _('Show') }}:
<select class="inline compact select" name="rule"> <select class="inline compact select" name="rule">
<option value="0"{% if not rule %} selected{% endif %}>{{ _('All') }}</option> <option value="0"{% if not rule %} selected{% endif %}>{{ _('All') }}</option>
{% for k, v in vj4.constant.contest.RULE_TEXTS.items() %} {% for k, v in model.contest.RULES %}
<option value="{{ k }}"{% if rule == k %} selected{% endif %}>{{ _('All {0} Contests').format(_(v)) }}</option> <option value="{{ k }}"{% if rule == k %} selected{% endif %}>{{ _('All {0} Contests').format(_(v.TEXT)) }}</option>
{% endfor %} {% endfor %}
</select> </select>
<button type="submit" class="button hasjs--hide"> <button type="submit" class="button hasjs--hide">
@@ -73,24 +74,24 @@
</div> </div>
</div> </div>
<div class="section__body no-padding"> <div class="section__body no-padding">
{% if not tdocs %} {% if not tdocs.length %}
{{ nothing.render('There are no contests...') }} {{ nothing.render('There are no contests...') }}
{% else %} {% else %}
<ol class="section__list contest__list"> <ol class="section__list contest__list">
{% for tdoc in tdocs %} {% for tdoc in tdocs %}
<li class="section__list__item contest__item contest-type--{{ vj4.constant.contest.RULE_ID[tdoc['rule']] }}"> <li class="section__list__item contest__item contest-type--{{ tdoc['rule'] }}">
<div class="media"> <div class="media">
<div class="media__left medium"> <div class="media__left medium">
<div class="contest__date numbox"> <div class="contest__date numbox">
<div class="numbox__num large">{{ datetime_span(tdoc['begin_at'], false, '%d') }}</div> <div class="numbox__num large">{{ datetime_span(tdoc['beginAt'], false, '%d') }}</div>
<div class="numbox__text">{{ datetime_span(tdoc['begin_at'], false, '%Y-%m') }}</div> <div class="numbox__text">{{ datetime_span(tdoc['beginAt'], false, '%Y-%m') }}</div>
</div> </div>
</div> </div>
<div class="media__body medium"> <div class="media__body medium">
<h1 class="contest__title"><a href="/t/{{ tdoc._id }}" data-emoji-enabled>{{ tdoc['title'] }}</a></h1> <h1 class="contest__title"><a href="/t/{{ tdoc._id }}" data-emoji-enabled>{{ tdoc['title'] }}</a></h1>
<ul class="supplementary list"> <ul class="supplementary list">
<li> <li>
<a href="?rule={{ tdoc['rule'] }}" class="contest-type-tag"><span class="icon icon-award"></span>{{ vj4.constant.contest.RULE_TEXTS[tdoc['rule']] }}</a> <a href="?rule={{ tdoc['rule'] }}" class="contest-type-tag"><span class="icon icon-award"></span>{{ model.contest.RULES[tdoc.rule].TEXT }}</a>
</li> </li>
<li> <li>
<span class="icon icon-schedule--fill text-blue"></span> {{ contest.render_duration(tdoc) }} {{ _('hour(s)') }} <span class="icon icon-schedule--fill text-blue"></span> {{ contest.render_duration(tdoc) }} {{ _('hour(s)') }}
@@ -98,7 +99,7 @@
<li> <li>
<span class="icon icon-user--multiple"></span> {{ tdoc['attend']|default(0) }} <span class="icon icon-user--multiple"></span> {{ tdoc['attend']|default(0) }}
</li> </li>
{% if tsdict[tdoc['doc_id']]['attend'] == 1 %} {% if tsdict[tdoc._id]['attend'] == 1 %}
<li class="contest__info-attended"> <li class="contest__info-attended">
<span class="icon icon-check"></span> {{ _('Attended') }} <span class="icon icon-check"></span> {{ _('Attended') }}
</li> </li>
@@ -115,7 +116,7 @@
</div> </div>
</div> </div>
<div class="medium-3 columns"> <div class="medium-3 columns">
{% if handler.has_perm(perm.PERM_CREATE_CONTEST) %} {% if handler.hasPerm(perm.PERM_CREATE_CONTEST) %}
<div class="section side"> <div class="section side">
<div class="section__header"> <div class="section__header">
<h1 class="section__title"> <h1 class="section__title">
@@ -123,7 +124,7 @@
</h1> </h1>
</div> </div>
<div class="section__body"> <div class="section__body">
<p><a href="{{ reverse_url('contest_create') }}" class="expanded primary button">{{ _('Create a contest') }}</a></p> <p><a href="/contest/create" class="expanded primary button">{{ _('Create a contest') }}</a></p>
</div> </div>
</div> </div>
{% endif %} {% endif %}
+2 -2
View File
@@ -29,7 +29,7 @@
</div> </div>
</div> </div>
<ul class="section__footer supplementary dot list"> <ul class="section__footer supplementary dot list">
{% if handler.own(ddoc, perm.PERM_EDIT_DISCUSSION_SELF) or handler.has_perm(perm.PERM_EDIT_DISCUSSION) %} {% if handler.own(ddoc, perm.PERM_EDIT_DISCUSSION_SELF) or handler.hasPerm(perm.PERM_EDIT_DISCUSSION) %}
<li> <li>
<a href="{{ reverse_url('discussion_edit', did=ddoc['doc_id']) }}"><span class="icon icon-edit"></span> {{ _('Edit') }}</a> <a href="{{ reverse_url('discussion_edit', did=ddoc['doc_id']) }}"><span class="icon icon-edit"></span> {{ _('Edit') }}</a>
</li> </li>
@@ -37,7 +37,7 @@
<li> <li>
{{ _('{0} views').format(ddoc['views']) }} {{ _('{0} views').format(ddoc['views']) }}
</li> </li>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<li><form class="form--inline" method="post"> <li><form class="form--inline" method="post">
<input type="hidden" name="operation" value="{% if not dsdoc['star'] %}star{% else %}unstar{% endif %}"> <input type="hidden" name="operation" value="{% if not dsdoc['star'] %}star{% else %}unstar{% endif %}">
<input type="hidden" name="csrf_token" value="{{ handler.csrf_token }}"> <input type="hidden" name="csrf_token" value="{{ handler.csrf_token }}">
+1 -1
View File
@@ -11,7 +11,7 @@
<button name="operation" value="update" type="submit" class="rounded primary button"> <button name="operation" value="update" type="submit" class="rounded primary button">
{{ _('Update') }} (Ctrl+Enter) {{ _('Update') }} (Ctrl+Enter)
</button> </button>
{% if handler.own(ddoc, perm.PERM_DELETE_DISCUSSION_SELF) or handler.has_perm(perm.PERM_DELETE_DISCUSSION) %} {% if handler.own(ddoc, perm.PERM_DELETE_DISCUSSION_SELF) or handler.hasPerm(perm.PERM_DELETE_DISCUSSION) %}
<button name="operation" value="delete" type="submit" class="rounded button"> <button name="operation" value="delete" type="submit" class="rounded button">
{{ _('Delete') }} {{ _('Delete') }}
</button> </button>
+2 -2
View File
@@ -23,10 +23,10 @@
</div> </div>
<div class="section__body"> <div class="section__body">
{% if vnode %} {% if vnode %}
{% if handler.has_perm(perm.PERM_CREATE_DISCUSSION) %} {% if handler.hasPerm(perm.PERM_CREATE_DISCUSSION) %}
<p><a href="{{ reverse_url('discussion_create', doc_id=vnode['doc_id']) }}" class="expanded primary button">{{ _('Create a Discussion') }}</a></p> <p><a href="{{ reverse_url('discussion_create', doc_id=vnode['doc_id']) }}" class="expanded primary button">{{ _('Create a Discussion') }}</a></p>
{% else %} {% else %}
{% if not handler.has_perm(perm.PERM_LOGGEDIN) %} {% if not handler.hasPerm(perm.PERM_LOGGEDIN) %}
<p><a href="javascript:showSignInDialog();" class="expanded primary button">{{ _('Login to Create a Discussion') }}</a></p> <p><a href="javascript:showSignInDialog();" class="expanded primary button">{{ _('Login to Create a Discussion') }}</a></p>
{% else %} {% else %}
<p><a href="javascript:;" class="disabled expanded primary button">{{ _('No Permission to Create a Discussion') }}</a></p> <p><a href="javascript:;" class="disabled expanded primary button">{{ _('No Permission to Create a Discussion') }}</a></p>
+2 -2
View File
@@ -13,7 +13,7 @@
</div> </div>
<ol class="menu collapsed"> <ol class="menu collapsed">
{{ sidemenu.render_item(null, 'domain_manage_dashboard') }} {{ sidemenu.render_item(null, 'domain_manage_dashboard') }}
{% if handler.has_perm(perm.PERM_EDIT_DESCRIPTION) %} {% if handler.hasPerm(perm.PERM_EDIT_DESCRIPTION) %}
{{ sidemenu.render_item(null, 'domain_manage_edit') }} {{ sidemenu.render_item(null, 'domain_manage_edit') }}
{{ sidemenu.render_item(null, 'domain_manage_join_applications') }} {{ sidemenu.render_item(null, 'domain_manage_join_applications') }}
{{ sidemenu.render_item(null, 'domain_manage_discussion') }} {{ sidemenu.render_item(null, 'domain_manage_discussion') }}
@@ -21,7 +21,7 @@
<!-- Ranking Settings --> <!-- Ranking Settings -->
</ol> </ol>
</li> </li>
{% if handler.has_perm(perm.PERM_EDIT_PERM) %} {% if handler.hasPerm(perm.PERM_EDIT_PERM) %}
<li class="menu__item"> <li class="menu__item">
<div class="menu__link expandable"> <div class="menu__link expandable">
<span class="icon icon-user"></span> {{ _('Access Control') }} <span class="icon icon-user"></span> {{ _('Access Control') }}
+2 -2
View File
@@ -139,7 +139,7 @@
<span class="icon training-status--icon done"></span> <span class="icon training-status--icon done"></span>
<span class="training-status--text done">{{ _('Completed') }} 100%</span> <span class="training-status--text done">{{ _('Completed') }} 100%</span>
{% endif %} {% endif %}
{% elif handler.has_perm(perm.PERM_LOGGEDIN) %} {% elif handler.hasPerm(perm.PERM_LOGGEDIN) %}
<span class="icon training-status--icon outside"></span> <span class="training-status--text outside">{{ _('Not Enrolled') }}</span> <span class="icon training-status--icon outside"></span> <span class="training-status--text outside">{{ _('Not Enrolled') }}</span>
{% endif %} {% endif %}
</li> </li>
@@ -164,7 +164,7 @@
{% endif %} {% endif %}
</div> </div>
<div class="large-3 columns"> <div class="large-3 columns">
{% if handler.has_perm(perm.PERM_VIEW_DISCUSSION) %} {% if handler.hasPerm(perm.PERM_VIEW_DISCUSSION) %}
{% include 'discussion_nodes_widget.html' %} {% include 'discussion_nodes_widget.html' %}
{% endif %} {% endif %}
{% if domain_id == vj4.model.builtin.DOMAIN_ID_SYSTEM %} {% if domain_id == vj4.model.builtin.DOMAIN_ID_SYSTEM %}
+3 -3
View File
@@ -23,7 +23,7 @@
<div class="section__body no-padding"> <div class="section__body no-padding">
<table class="data-table"> <table class="data-table">
<colgroup> <colgroup>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<col class="col--status"> <col class="col--status">
<col class="col--submit-at"> <col class="col--submit-at">
{% endif %} {% endif %}
@@ -31,7 +31,7 @@
</colgroup> </colgroup>
<thead> <thead>
<tr> <tr>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<th class="col--status record-status--border">{{ _('Status') }}</th> <th class="col--status record-status--border">{{ _('Status') }}</th>
<th class="col--submit-at">{{ _('Last Submit At') }}</th> <th class="col--submit-at">{{ _('Last Submit At') }}</th>
{% endif %} {% endif %}
@@ -41,7 +41,7 @@
<tbody> <tbody>
{% for pid in tdoc['pids'] %} {% for pid in tdoc['pids'] %}
<tr> <tr>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
{% if psdict[pid] and psdict[pid]['rid'] %} {% if psdict[pid] and psdict[pid]['rid'] %}
{% with rdoc=rdict[psdict[pid]['rid']] %} {% with rdoc=rdict[psdict[pid]['rid']] %}
{% if handler.can_show_record(tdoc) %} {% if handler.can_show_record(tdoc) %}
+1 -1
View File
@@ -18,7 +18,7 @@
<option value="list">{{ _('List View') }}</option> <option value="list">{{ _('List View') }}</option>
</select> </select>
</span> </span>
{% if handler.has_perm(perm.PERM_CREATE_HOMEWORK) %} {% if handler.hasPerm(perm.PERM_CREATE_HOMEWORK) %}
<a class="compact button" href="{{ reverse_url('homework_create') }}">{{ _('Create Homework') }}</a> <a class="compact button" href="{{ reverse_url('homework_create') }}">{{ _('Create Homework') }}</a>
{% endif %} {% endif %}
</div> </div>
+6 -6
View File
@@ -18,12 +18,12 @@
<div> <div>
<ol class="menu"> <ol class="menu">
{% if page_name == 'discussion_node' %} {% if page_name == 'discussion_node' %}
{% if handler.has_perm(perm.PERM_CREATE_DISCUSSION) %} {% if handler.hasPerm(perm.PERM_CREATE_DISCUSSION) %}
<li class="menu__item"><a class="menu__link highlight" href="{{ reverse_url('discussion_create_document_as_node', doc_type=tdoc['doc_type'], doc_id=tdoc['doc_id']) }}"> <li class="menu__item"><a class="menu__link highlight" href="{{ reverse_url('discussion_create_document_as_node', doc_type=tdoc['doc_type'], doc_id=tdoc['doc_id']) }}">
<span class="icon icon-add"></span> {{ _('Create a Discussion') }} <span class="icon icon-add"></span> {{ _('Create a Discussion') }}
</a></li> </a></li>
{% else %} {% else %}
{% if not handler.has_perm(perm.PERM_LOGGEDIN) %} {% if not handler.hasPerm(perm.PERM_LOGGEDIN) %}
<li class="menu__item"><a class="menu__link" href="javascript:showSignInDialog();"> <li class="menu__item"><a class="menu__link" href="javascript:showSignInDialog();">
<span class="icon icon-add"></span> {{ _('Login to Create a Discussion') }}</a></li> <span class="icon icon-add"></span> {{ _('Login to Create a Discussion') }}</a></li>
{% else %} {% else %}
@@ -40,7 +40,7 @@
{% endif %} {% endif %}
{% if not attended and not handler.is_done(tdoc) %} {% if not attended and not handler.is_done(tdoc) %}
<li class="menu__item"> <li class="menu__item">
{% if handler.has_perm(perm.PERM_ATTEND_CONTEST) and handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_ATTEND_CONTEST) and handler.hasPerm(perm.PERM_LOGGEDIN) %}
<form action="/t/{{ tdoc._id }}" method="POST"> <form action="/t/{{ tdoc._id }}" method="POST">
<input type="hidden" name="operation" value="attend"> <input type="hidden" name="operation" value="attend">
<input type="hidden" name="csrf_token" value="{{ handler.csrf_token }}"> <input type="hidden" name="csrf_token" value="{{ handler.csrf_token }}">
@@ -48,7 +48,7 @@
<span class="icon icon-add"></span> {{ _('Attend Contest') }} <span class="icon icon-add"></span> {{ _('Attend Contest') }}
</button> </button>
</form> </form>
{% elif not handler.has_perm(perm.PERM_LOGGEDIN) %} {% elif not handler.hasPerm(perm.PERM_LOGGEDIN) %}
<a class="menu__link" href="javascript:showSignInDialog()"> <a class="menu__link" href="javascript:showSignInDialog()">
<span class="icon icon-add"></span> {{ _('Login to Attend Contest') }} <span class="icon icon-add"></span> {{ _('Login to Attend Contest') }}
</a> </a>
@@ -68,12 +68,12 @@
<span class="icon icon-statistics"></span> {{ _('Scoreboard (Hidden)') }} <span class="icon icon-statistics"></span> {{ _('Scoreboard (Hidden)') }}
</a></li> </a></li>
{% endif %} {% endif %}
{% if handler.own(tdoc, perm.PERM_EDIT_CONTEST_SELF) or handler.has_perm(perm.PERM_EDIT_CONTEST) %} {% if handler.own(tdoc, perm.PERM_EDIT_CONTEST_SELF) or handler.hasPerm(perm.PERM_EDIT_CONTEST) %}
<li class="menu__item"><a class="menu__link" href="{{ reverse_url('contest_edit', tid=tdoc['doc_id']) }}"> <li class="menu__item"><a class="menu__link" href="{{ reverse_url('contest_edit', tid=tdoc['doc_id']) }}">
<span class="icon icon-edit"></span> {{ _('Edit Contest') }} <span class="icon icon-edit"></span> {{ _('Edit Contest') }}
</a></li> </a></li>
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_READ_RECORD_CODE) %} {% if handler.hasPerm(perm.PERM_READ_RECORD_CODE) %}
<li class="menu__item"><a class="menu__link" href="{{ reverse_url('contest_code', tid=tdoc['doc_id']) }}"> <li class="menu__item"><a class="menu__link" href="{{ reverse_url('contest_code', tid=tdoc['doc_id']) }}">
<span class="icon icon-download"></span> {{ _('Export All Code') }} <span class="icon icon-download"></span> {{ _('Export All Code') }}
</a></li> </a></li>
+1 -1
View File
@@ -1,5 +1,5 @@
{% import "components/form.html" as form with context %} {% import "components/form.html" as form with context %}
{% if ddoc['highlight'] or handler.has_perm(perm.PERM_HIGHLIGHT_DISCUSSION) %} {% if ddoc['highlight'] or handler.hasPerm(perm.PERM_HIGHLIGHT_DISCUSSION) %}
{{ form.form_checkbox(label='Highlight', name='highlight', value=ddoc['highlight']|default(false)) }} {{ form.form_checkbox(label='Highlight', name='highlight', value=ddoc['highlight']|default(false)) }}
{% endif %} {% endif %}
{{ form.form_text(label='Title', name='title', value=ddoc['title']|default(''), autofocus=true, required=true) }} {{ form.form_text(label='Title', name='title', value=ddoc['title']|default(''), autofocus=true, required=true) }}
+4 -4
View File
@@ -24,7 +24,7 @@
{% endif %} {% endif %}
{% if not attended and not handler.is_done(tdoc) %} {% if not attended and not handler.is_done(tdoc) %}
<li class="menu__item"> <li class="menu__item">
{% if handler.has_perm(perm.PERM_ATTEND_HOMEWORK) and handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_ATTEND_HOMEWORK) and handler.hasPerm(perm.PERM_LOGGEDIN) %}
<form action="{{ reverse_url('homework_detail', tid=tdoc['doc_id']) }}" method="POST"> <form action="{{ reverse_url('homework_detail', tid=tdoc['doc_id']) }}" method="POST">
<input type="hidden" name="operation" value="attend"> <input type="hidden" name="operation" value="attend">
<input type="hidden" name="csrf_token" value="{{ handler.csrf_token }}"> <input type="hidden" name="csrf_token" value="{{ handler.csrf_token }}">
@@ -32,7 +32,7 @@
<span class="icon icon-add"></span> {{ _('Claim Homework') }} <span class="icon icon-add"></span> {{ _('Claim Homework') }}
</button> </button>
</form> </form>
{% elif not handler.has_perm(perm.PERM_LOGGEDIN) %} {% elif not handler.hasPerm(perm.PERM_LOGGEDIN) %}
<a class="menu__link" href="javascript:showSignInDialog()"> <a class="menu__link" href="javascript:showSignInDialog()">
<span class="icon icon-add"></span> {{ _('Login to Claim Homework') }} <span class="icon icon-add"></span> {{ _('Login to Claim Homework') }}
</a> </a>
@@ -52,12 +52,12 @@
<span class="icon icon-statistics"></span> {{ _('Scoreboard (Hidden)') }} <span class="icon icon-statistics"></span> {{ _('Scoreboard (Hidden)') }}
</a></li> </a></li>
{% endif %} {% endif %}
{% if handler.own(tdoc, perm.PERM_EDIT_HOMEWORK_SELF) or handler.has_perm(perm.PERM_EDIT_HOMEWORK) %} {% if handler.own(tdoc, perm.PERM_EDIT_HOMEWORK_SELF) or handler.hasPerm(perm.PERM_EDIT_HOMEWORK) %}
<li class="menu__item"><a class="menu__link" href="{{ reverse_url('homework_edit', tid=tdoc['doc_id']) }}"> <li class="menu__item"><a class="menu__link" href="{{ reverse_url('homework_edit', tid=tdoc['doc_id']) }}">
<span class="icon icon-edit"></span> {{ _('Edit Homework') }} <span class="icon icon-edit"></span> {{ _('Edit Homework') }}
</a></li> </a></li>
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_READ_RECORD_CODE) %} {% if handler.hasPerm(perm.PERM_READ_RECORD_CODE) %}
<li class="menu__item"><a class="menu__link" href="{{ reverse_url('homework_code', tid=tdoc['doc_id']) }}"> <li class="menu__item"><a class="menu__link" href="{{ reverse_url('homework_code', tid=tdoc['doc_id']) }}">
<span class="icon icon-download"></span> {{ _('Export All Code') }} <span class="icon icon-download"></span> {{ _('Export All Code') }}
</a></li> </a></li>
+7 -7
View File
@@ -11,27 +11,27 @@
<ol class="nav__list nav__list--main clearfix"> <ol class="nav__list nav__list--main clearfix">
<li class="nav__list-item"><a href="/" class="nav__logo">&nbsp;</a></li> <li class="nav__list-item"><a href="/" class="nav__logo">&nbsp;</a></li>
{{ nav_item('/', 'domain_main', 'domain_main') }} {{ nav_item('/', 'domain_main', 'domain_main') }}
{% if handler.has_perm(perm.PERM_VIEW_PROBLEM) %} {% if handler.hasPerm(perm.PERM_VIEW_PROBLEM) %}
{{ nav_item('/p', 'problem_main', 'problem') }} {{ nav_item('/p', 'problem_main', 'problem') }}
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_VIEW_TRAINING) %} {% if handler.hasPerm(perm.PERM_VIEW_TRAINING) %}
{{ nav_item('/t', 'training_main', 'training') }} {{ nav_item('/t', 'training_main', 'training') }}
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_VIEW_DISCUSSION) %} {% if handler.hasPerm(perm.PERM_VIEW_DISCUSSION) %}
{{ nav_item('/d', 'discussion_main', 'discussion') }} {{ nav_item('/d', 'discussion_main', 'discussion') }}
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_VIEW_CONTEST) %} {% if handler.hasPerm(perm.PERM_VIEW_CONTEST) %}
{{ nav_item('/c', 'contest_main', 'contest') }} {{ nav_item('/c', 'contest_main', 'contest') }}
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_VIEW_HOMEWORK) %} {% if handler.hasPerm(perm.PERM_VIEW_HOMEWORK) %}
{{ nav_item('/h', 'homework_main', 'homework') }} {{ nav_item('/h', 'homework_main', 'homework') }}
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_EDIT_DESCRIPTION) or handler.has_perm(perm.PERM_EDIT_PERM) %} {% if handler.hasPerm(perm.PERM_EDIT_DESCRIPTION) or handler.hasPerm(perm.PERM_EDIT_PERM) %}
{{ nav_item('/d', 'domain_manage', 'domain_manage') }} {{ nav_item('/d', 'domain_manage', 'domain_manage') }}
{% endif %} {% endif %}
</ol> </ol>
<ol class="nav__list nav__list--secondary clearfix"> <ol class="nav__list nav__list--secondary clearfix">
{% if not handler.has_perm(perm.PERM_LOGGEDIN) %} {% if not handler.hasPerm(perm.PERM_LOGGEDIN) %}
<li class="nav__list-item"><a href="/login" class="nav__item" name="nav_login">{{ _('Login') }}</a></li> <li class="nav__list-item"><a href="/login" class="nav__item" name="nav_login">{{ _('Login') }}</a></li>
<li class="nav__list-item"><a href="/register" class="nav__item--round">{{ _('Sign Up') }}</a></li> <li class="nav__list-item"><a href="/register" class="nav__item--round">{{ _('Sign Up') }}</a></li>
{% else %} {% else %}
+3 -3
View File
@@ -8,7 +8,7 @@
{% else %} {% else %}
<table class="data-table"> <table class="data-table">
<colgroup> <colgroup>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<col class="col--status"> <col class="col--status">
{% endif %} {% endif %}
<col class="col--name"> <col class="col--name">
@@ -18,7 +18,7 @@
</colgroup> </colgroup>
<thead> <thead>
<tr> <tr>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<th class="col--status record-status--border">{{ _('Status') }}</th> <th class="col--status record-status--border">{{ _('Status') }}</th>
{% endif %} {% endif %}
<th class="col--name">{{ _('Problem') }}</th> <th class="col--name">{{ _('Problem') }}</th>
@@ -31,7 +31,7 @@
{% for pdoc in pdocs %} {% for pdoc in pdocs %}
{% set psdoc = psdict[pdoc['_id']] %} {% set psdoc = psdict[pdoc['_id']] %}
<tr> <tr>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
{% if psdoc['rid'] %} {% if psdoc['rid'] %}
{{ record.render_status_td(psdoc, rid_key='rid') }} {{ record.render_status_td(psdoc, rid_key='rid') }}
{% else %} {% else %}
@@ -28,7 +28,7 @@
<span class="icon icon-send"></span> {{ _('Open in Problem Set') }} <span class="icon icon-send"></span> {{ _('Open in Problem Set') }}
</a></li> </a></li>
{% endif %} {% endif %}
{% if handler.own(pdoc, perm.PERM_EDIT_PROBLEM_SELF) or handler.has_perm(perm.PERM_EDIT_PROBLEM) %} {% if handler.own(pdoc, perm.PERM_EDIT_PROBLEM_SELF) or handler.hasPerm(perm.PERM_EDIT_PROBLEM) %}
<li class="menu__seperator"></li> <li class="menu__seperator"></li>
<li class="menu__item"><a class="menu__link{% if page_name == 'problem_edit' %} active{% endif %}" href="/p/{{ pdoc.pid }}/edit"> <li class="menu__item"><a class="menu__link{% if page_name == 'problem_edit' %} active{% endif %}" href="/p/{{ pdoc.pid }}/edit">
<span class="icon icon-edit"></span> {{ _('Edit') }} <span class="icon icon-edit"></span> {{ _('Edit') }}
@@ -28,7 +28,7 @@
<span class="icon icon-send"></span> {{ _('Open in Problem Set') }} <span class="icon icon-send"></span> {{ _('Open in Problem Set') }}
</a></li> </a></li>
{% endif %} {% endif %}
{% if handler.own(pdoc, perm.PERM_EDIT_PROBLEM_SELF) or handler.has_perm(perm.PERM_EDIT_PROBLEM) %} {% if handler.own(pdoc, perm.PERM_EDIT_PROBLEM_SELF) or handler.hasPerm(perm.PERM_EDIT_PROBLEM) %}
<li class="menu__seperator"></li> <li class="menu__seperator"></li>
<li class="menu__item"><a class="menu__link{% if page_name == 'problem_edit' %} active{% endif %}" href="/p/{{ pdoc.pid }}/edit"> <li class="menu__item"><a class="menu__link{% if page_name == 'problem_edit' %} active{% endif %}" href="/p/{{ pdoc.pid }}/edit">
<span class="icon icon-edit"></span> {{ _('Edit') }} <span class="icon icon-edit"></span> {{ _('Edit') }}
+12 -12
View File
@@ -9,12 +9,12 @@
<div> <div>
<ol class="menu"> <ol class="menu">
{% if page_name == 'discussion_node' or page_name == 'discussion_detail' %} {% if page_name == 'discussion_node' or page_name == 'discussion_detail' %}
{% if handler.has_perm(perm.PERM_CREATE_DISCUSSION) %} {% if handler.hasPerm(perm.PERM_CREATE_DISCUSSION) %}
<li class="menu__item"><a class="menu__link highlight" href="{{ reverse_url('discussion_create_document_as_node', doc_type=pdoc['doc_type'], doc_id=pdoc['_id']) }}"> <li class="menu__item"><a class="menu__link highlight" href="{{ reverse_url('discussion_create_document_as_node', doc_type=pdoc['doc_type'], doc_id=pdoc['_id']) }}">
<span class="icon icon-add"></span> {{ _('Create a Discussion') }} <span class="icon icon-add"></span> {{ _('Create a Discussion') }}
</a></li> </a></li>
{% else %} {% else %}
{% if not handler.has_perm(perm.PERM_LOGGEDIN) %} {% if not handler.hasPerm(perm.PERM_LOGGEDIN) %}
<li class="menu__item"><a class="menu__link" href="javascript:showSignInDialog();"> <li class="menu__item"><a class="menu__link" href="javascript:showSignInDialog();">
<span class="icon icon-add"></span> {{ _('Login to Create a Discussion') }}</a></li> <span class="icon icon-add"></span> {{ _('Login to Create a Discussion') }}</a></li>
{% else %} {% else %}
@@ -25,7 +25,7 @@
<li class="menu__seperator"></li> <li class="menu__seperator"></li>
{% endif %} {% endif %}
{% if page_name == 'problem_detail' %} {% if page_name == 'problem_detail' %}
{% if handler.has_perm(perm.PERM_SUBMIT_PROBLEM) %} {% if handler.hasPerm(perm.PERM_SUBMIT_PROBLEM) %}
<li class="menu__item scratchpad--hide"><a class="menu__link highlight" name="problem-sidebar__open-scratchpad" href="javascript:;" data-global-hotkey="alt+e"> <li class="menu__item scratchpad--hide"><a class="menu__link highlight" name="problem-sidebar__open-scratchpad" href="javascript:;" data-global-hotkey="alt+e">
<span class="icon icon-enlarge"></span> {{ _('Open Scratchpad') }} (Alt+E) <span class="icon icon-enlarge"></span> {{ _('Open Scratchpad') }} (Alt+E)
</a></li> </a></li>
@@ -38,11 +38,11 @@
<span class="icon icon-flag"></span> {{ _('View Problem') }} <span class="icon icon-flag"></span> {{ _('View Problem') }}
</a></li> </a></li>
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_SUBMIT_PROBLEM) %} {% if handler.hasPerm(perm.PERM_SUBMIT_PROBLEM) %}
<li class="menu__item scratchpad--hide"><a class="menu__link{% if page_name == 'problem_submit' %} active{% endif %}" href="/p/{{ pdoc.pid }}/submit"> <li class="menu__item scratchpad--hide"><a class="menu__link{% if page_name == 'problem_submit' %} active{% endif %}" href="/p/{{ pdoc.pid }}/submit">
<span class="icon icon-send"></span> {{ _('Submit') }} <span class="icon icon-send"></span> {{ _('Submit') }}
</a></li> </a></li>
{% elif not handler.has_perm(perm.PERM_LOGGEDIN) %} {% elif not handler.hasPerm(perm.PERM_LOGGEDIN) %}
<li class="menu__item scratchpad--hide"><a class="menu__link{% if page_name == 'problem_submit' %} active{% endif %}" href="javascript:showSignInDialog();"> <li class="menu__item scratchpad--hide"><a class="menu__link{% if page_name == 'problem_submit' %} active{% endif %}" href="javascript:showSignInDialog();">
<span class="icon icon-send"></span> {{ _('Login to Submit') }} <span class="icon icon-send"></span> {{ _('Login to Submit') }}
</a></li> </a></li>
@@ -51,26 +51,26 @@
<span class="icon icon-send"></span> {{ _('No Permission to Submit') }} <span class="icon icon-send"></span> {{ _('No Permission to Submit') }}
</a></li> </a></li>
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_VIEW_DISCUSSION) or handler.has_perm(perm.PERM_VIEW_PROBLEM_SOLUTION) %} {% if handler.hasPerm(perm.PERM_VIEW_DISCUSSION) or handler.hasPerm(perm.PERM_VIEW_PROBLEM_SOLUTION) %}
<li class="menu__seperator"></li> <li class="menu__seperator"></li>
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_VIEW_DISCUSSION) %} {% if handler.hasPerm(perm.PERM_VIEW_DISCUSSION) %}
<li class="menu__item"><a class="menu__link{% if page_name == 'discussion_node' or page_name == 'discussion_detail' %} active{% endif %}" href="{{ reverse_url('discussion_node_document_as_node', doc_type=pdoc['doc_type'], doc_id=pdoc['_id']) }}"> <li class="menu__item"><a class="menu__link{% if page_name == 'discussion_node' or page_name == 'discussion_detail' %} active{% endif %}" href="{{ reverse_url('discussion_node_document_as_node', doc_type=pdoc['doc_type'], doc_id=pdoc['_id']) }}">
<span class="icon icon-comment--text"></span> {{ _('Discussions') }} <span class="icon icon-comment--text"></span> {{ _('Discussions') }}
</a></li> </a></li>
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_VIEW_PROBLEM_SOLUTION) %} {% if handler.hasPerm(perm.PERM_VIEW_PROBLEM_SOLUTION) %}
<li class="menu__item"><a class="menu__link{% if page_name == 'problem_solution' %} active{% endif %}" href="/p/{{ pdoc.pid }}/solution"> <li class="menu__item"><a class="menu__link{% if page_name == 'problem_solution' %} active{% endif %}" href="/p/{{ pdoc.pid }}/solution">
<span class="icon icon-comment--text"></span> {{ _('Solutions') }} <span class="icon icon-comment--text"></span> {{ _('Solutions') }}
</a></li> </a></li>
{% endif %} {% endif %}
{% if page_name == 'problem_detail' and handler.has_perm(perm.PERM_LOGGEDIN) %} {% if page_name == 'problem_detail' and handler.hasPerm(perm.PERM_LOGGEDIN) %}
<li class="menu__seperator"></li> <li class="menu__seperator"></li>
<li class="menu__item"><a class="menu__link" name="problem-sidebar__copy-to" href="javascript:;"> <li class="menu__item"><a class="menu__link" name="problem-sidebar__copy-to" href="javascript:;">
<span class="icon icon-copy"></span> {{ _('Copy Problem') }} <span class="icon icon-copy"></span> {{ _('Copy Problem') }}
</a></li> </a></li>
{% endif %} {% endif %}
{% if user._id == pdoc.owner or handler.has_perm(perm.PERM_EDIT_PROBLEM) %} {% if user._id == pdoc.owner or handler.hasPerm(perm.PERM_EDIT_PROBLEM) %}
<li class="menu__seperator"></li> <li class="menu__seperator"></li>
<li class="menu__item"><a class="menu__link{% if page_name == 'problem_edit' %} active{% endif %}" href="/p/{{ pdoc.pid }}/edit"> <li class="menu__item"><a class="menu__link{% if page_name == 'problem_edit' %} active{% endif %}" href="/p/{{ pdoc.pid }}/edit">
<span class="icon icon-edit"></span> {{ _('Edit') }} <span class="icon icon-edit"></span> {{ _('Edit') }}
@@ -94,7 +94,7 @@
<dd>{{ pdoc['_id'] }}</dd> <dd>{{ pdoc['_id'] }}</dd>
{% endif %} {% endif %}
{% if page_name != 'discussion_node' and page_name != 'discussion_detail' %} {% if page_name != 'discussion_node' and page_name != 'discussion_detail' %}
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<dt>{{ _('Submission') }}</dt> <dt>{{ _('Submission') }}</dt>
<dd> <dd>
{% if pdoc['psdoc']['status'] %} {% if pdoc['psdoc']['status'] %}
@@ -139,7 +139,7 @@
<dt>{{ _('# Submissions') }}</dt> <dt>{{ _('# Submissions') }}</dt>
<dd><a href="/r?pid={{ pdoc['_id'] }}">{{ pdoc.nSubmit }}</a></dd> <dd><a href="/r?pid={{ pdoc['_id'] }}">{{ pdoc.nSubmit }}</a></dd>
{% if page_name != 'discussion_node' and page_name != 'discussion_detail' %} {% if page_name != 'discussion_node' and page_name != 'discussion_detail' %}
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<dt>{{ _('# My Submissions') }}</dt> <dt>{{ _('# My Submissions') }}</dt>
<dd><a href="/r?pid={{ pdoc['_id'] }}&uid_or_name={{ handler.user['_id'] }}">{{ pdoc['psdoc'].nSubmit|default(0) }}</a></dd> <dd><a href="/r?pid={{ pdoc['_id'] }}&uid_or_name={{ handler.user['_id'] }}">{{ pdoc['psdoc'].nSubmit|default(0) }}</a></dd>
{% endif %} {% endif %}
+1 -1
View File
@@ -60,7 +60,7 @@
</div> </div>
</form> </form>
</div> </div>
{% if handler.has_perm(perm.PERM_CREATE_PROBLEM) %} {% if handler.hasPerm(perm.PERM_CREATE_PROBLEM) %}
<div class="section side"> <div class="section side">
<div class="section__header"> <div class="section__header">
<h1 class="section__title">{{ _('Create Problem') }}</h1> <h1 class="section__title">{{ _('Create Problem') }}</h1>
+1 -1
View File
@@ -10,7 +10,7 @@
<div class="section__body"> <div class="section__body">
<iframe src="/p/{{ pdoc.pid }}/upload" frameborder="0" style="width: 100%; height: 100px;"></iframe> <iframe src="/p/{{ pdoc.pid }}/upload" frameborder="0" style="width: 100%; height: 100px;"></iframe>
<p class="help-text">{{ _('Hint') }}: <a href="/wiki/help#upload">{{ _('Dataset Format') }}</a>, {{ _('An example of dataset') }}: <a href="https://github.com/vijos/jd4/blob/master/jd4/testdata/aplusb-legacy.zip?raw=true">{{ _('Download') }}</a></p> <p class="help-text">{{ _('Hint') }}: <a href="/wiki/help#upload">{{ _('Dataset Format') }}</a>, {{ _('An example of dataset') }}: <a href="https://github.com/vijos/jd4/blob/master/jd4/testdata/aplusb-legacy.zip?raw=true">{{ _('Download') }}</a></p>
{% if pdoc and (pdoc.owner == user._id or handler.has_perm(perm.PERM_READ_PROBLEM_DATA)) %} {% if pdoc and (pdoc.owner == user._id or handler.hasPerm(perm.PERM_READ_PROBLEM_DATA)) %}
<p><a href="/p/{{ pdoc.pid }}/data" class="expanded button">{{ _('Download Dataset') }}</a></p> <p><a href="/p/{{ pdoc.pid }}/data" class="expanded button">{{ _('Download Dataset') }}</a></p>
{% endif %} {% endif %}
</div> </div>
+2 -2
View File
@@ -28,7 +28,7 @@
<div class="section__header"> <div class="section__header">
<h1 class="section__title">{{ _('Information') }}</h1> <h1 class="section__title">{{ _('Information') }}</h1>
</div> </div>
{% if handler.has_perm(perm.PERM_REJUDGE) %} {% if handler.hasPerm(perm.PERM_REJUDGE) %}
<div class="section__body no-padding"> <div class="section__body no-padding">
<ol class="menu"> <ol class="menu">
<li class="menu__item"> <li class="menu__item">
@@ -76,7 +76,7 @@
</dd> </dd>
{% endif %}{# tdoc['doc_type'] == vj4.model.document.TYPE_CONTEST #} {% endif %}{# tdoc['doc_type'] == vj4.model.document.TYPE_CONTEST #}
{% endif %}{# tdoc #} {% endif %}{# tdoc #}
{% if pdoc and (user._id == pdoc.owner or handler.has_perm(perm.PERM_READ_PROBLEM_DATA)) %} {% if pdoc and (user._id == pdoc.owner or handler.hasPerm(perm.PERM_READ_PROBLEM_DATA)) %}
<dt>{{ _('Problem Data') }}</dt> <dt>{{ _('Problem Data') }}</dt>
<dd><a href="/p/{{ pdoc.pid }}/data"><span class="icon icon-download"></span> {{ _('Download') }}</a></dd> <dd><a href="/p/{{ pdoc.pid }}/data"><span class="icon icon-download"></span> {{ _('Download') }}</a></dd>
{% endif %} {% endif %}
+1 -1
View File
@@ -83,7 +83,7 @@
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
{% if handler.has_perm(perm.PERM_VIEW_JUDGE_STATISTICS) %} {% if handler.hasPerm(perm.PERM_VIEW_JUDGE_STATISTICS) %}
<ul class="pager"> <ul class="pager">
<li> <li>
<a class="pager__item next link" href="?start={{ rdocs[-1]['_id'] }}&{{ query_string }}">{{ _('pager_next') }}</a> <a class="pager__item next link" href="?start={{ rdocs[-1]['_id'] }}&{{ query_string }}">{{ _('pager_next') }}</a>
+2 -2
View File
@@ -3,7 +3,7 @@
<tr data-rid="{{ rdoc['_id'] }}"> <tr data-rid="{{ rdoc['_id'] }}">
{{ record.render_status_td(rdoc) }} {{ record.render_status_td(rdoc) }}
<td class="col--problem col--problem-name"> <td class="col--problem col--problem-name">
{% if handler.has_perm(perm.PERM_REJUDGE) %} {% if handler.hasPerm(perm.PERM_REJUDGE) %}
<form class="form--inline" method="post" action="/r/{{ rdoc._id }}/rejudge"> <form class="form--inline" method="post" action="/r/{{ rdoc._id }}/rejudge">
<input type="hidden" name="csrf_token" value="{{ handler.csrf_token }}"> <input type="hidden" name="csrf_token" value="{{ handler.csrf_token }}">
<button type="submit" class="link text-maroon lighter"> <button type="submit" class="link text-maroon lighter">
@@ -12,7 +12,7 @@
</button> | </button> |
</form> </form>
{% endif %} {% endif %}
{% if pdoc and (not pdoc.hidden or handler.has_perm(perm.PERM_VIEW_PROBLEM_HIDDEN)) %} {% if pdoc and (not pdoc.hidden or handler.hasPerm(perm.PERM_VIEW_PROBLEM_HIDDEN)) %}
{{ problem.render_problem_title(pdoc, show_tags=false) }} {{ problem.render_problem_title(pdoc, show_tags=false) }}
{% else %} {% else %}
* *
+7 -7
View File
@@ -79,7 +79,7 @@
<div class="section__body no-padding training__problems"> <div class="section__body no-padding training__problems">
<table class="data-table"> <table class="data-table">
<colgroup> <colgroup>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<col class="col--status"> <col class="col--status">
{% endif %} {% endif %}
<col class="col--name"> <col class="col--name">
@@ -89,7 +89,7 @@
</colgroup> </colgroup>
<thead> <thead>
<tr> <tr>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<th class="col--status record-status--border">{{ _('Status') }}</th> <th class="col--status record-status--border">{{ _('Status') }}</th>
{% endif %} {% endif %}
<th class="col--name">{{ _('Problem') }}</th> <th class="col--name">{{ _('Problem') }}</th>
@@ -103,7 +103,7 @@
{% if pid in pdict %} {% if pid in pdict %}
{% with pdoc=pdict[pid], psdoc=psdict[pid] %} {% with pdoc=pdict[pid], psdoc=psdict[pid] %}
<tr> <tr>
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
{% if psdoc['rid'] %} {% if psdoc['rid'] %}
{{ record.render_status_td(psdoc, rid_key='rid') }} {{ record.render_status_td(psdoc, rid_key='rid') }}
{% else %} {% else %}
@@ -111,7 +111,7 @@
{% endif %} {% endif %}
{% endif %} {% endif %}
<td class="col--name col--problem-name"> <td class="col--name col--problem-name">
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<form class="form--inline" action="{{ reverse_url('problem_main') }}" method="post"> <form class="form--inline" action="{{ reverse_url('problem_main') }}" method="post">
<input type="hidden" name="pid" value="{{ pdoc['_id'] }}"> <input type="hidden" name="pid" value="{{ pdoc['_id'] }}">
<input type="hidden" name="operation" value="{% if not psdoc['star'] %}star{% else %}unstar{% endif %}"> <input type="hidden" name="operation" value="{% if not psdoc['star'] %}star{% else %}unstar{% endif %}">
@@ -164,7 +164,7 @@
<div class="section side"> <div class="section side">
<div> <div>
<ol class="menu"> <ol class="menu">
{% if not tsdoc['enroll'] and handler.has_perm(perm.PERM_LOGGEDIN) %} {% if not tsdoc['enroll'] and handler.hasPerm(perm.PERM_LOGGEDIN) %}
<li class="menu__item"> <li class="menu__item">
<form action="" method="POST"> <form action="" method="POST">
<input type="hidden" name="operation" value="enroll"> <input type="hidden" name="operation" value="enroll">
@@ -175,7 +175,7 @@
</form> </form>
</li> </li>
{% endif %} {% endif %}
{% if handler.own(tdoc, perm.PERM_EDIT_TRAINING_SELF) or handler.has_perm(perm.PERM_EDIT_TRAINING) %} {% if handler.own(tdoc, perm.PERM_EDIT_TRAINING_SELF) or handler.hasPerm(perm.PERM_EDIT_TRAINING) %}
<li class="menu__item"><a class="menu__link" href="{{ reverse_url('training_edit', tid=tdoc['doc_id']) }}"> <li class="menu__item"><a class="menu__link" href="{{ reverse_url('training_edit', tid=tdoc['doc_id']) }}">
<span class="icon icon-edit"></span> {{ _('Edit') }} <span class="icon icon-edit"></span> {{ _('Edit') }}
</a></li> </a></li>
@@ -188,7 +188,7 @@
</div> </div>
<div class="section__body typo"> <div class="section__body typo">
<dl class="large horizontal"> <dl class="large horizontal">
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<dt>{{ _('Status') }}</dt><dd>{% if tsdoc['enroll'] %}{{ _('Completed' if tsdoc['done'] else 'In Progress') }}{% else %}{{ _('Not Enrolled') }}{% endif %}</dd> <dt>{{ _('Status') }}</dt><dd>{% if tsdoc['enroll'] %}{{ _('Completed' if tsdoc['done'] else 'In Progress') }}{% else %}{{ _('Not Enrolled') }}{% endif %}</dd>
{% endif %} {% endif %}
{% if tsdoc['enroll'] %} {% if tsdoc['enroll'] %}
+3 -3
View File
@@ -37,7 +37,7 @@
<span class="icon training-status--icon done"></span> <span class="icon training-status--icon done"></span>
<span class="training-status--text done">{{ _('Completed') }} 100%</span> <span class="training-status--text done">{{ _('Completed') }} 100%</span>
{% endif %} {% endif %}
{% elif handler.has_perm(perm.PERM_LOGGEDIN) %} {% elif handler.hasPerm(perm.PERM_LOGGEDIN) %}
<span class="icon training-status--icon outside"></span> <span class="training-status--text outside">{{ _('Not Enrolled') }}</span> <span class="icon training-status--icon outside"></span> <span class="training-status--text outside">{{ _('Not Enrolled') }}</span>
{% endif %} {% endif %}
</li> </li>
@@ -52,7 +52,7 @@
</div> </div>
</div> </div>
<div class="large-3 columns"> <div class="large-3 columns">
{% if handler.has_perm(perm.PERM_LOGGEDIN) %} {% if handler.hasPerm(perm.PERM_LOGGEDIN) %}
<div class="section side"> <div class="section side">
<div class="section__header"> <div class="section__header">
<h1 class="section__title">{{ _('Enrolled') }}</h1> <h1 class="section__title">{{ _('Enrolled') }}</h1>
@@ -76,7 +76,7 @@
</div> </div>
</div> </div>
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_CREATE_TRAINING) %} {% if handler.hasPerm(perm.PERM_CREATE_TRAINING) %}
<div class="section side"> <div class="section side">
<div class="section__header"> <div class="section__header">
<h1 class="section__title">{{ _('Create Training Plan') }}</h1> <h1 class="section__title">{{ _('Create Training Plan') }}</h1>
+71 -3
View File
@@ -5,7 +5,7 @@
<div class="row"> <div class="row">
<div class="medium-9 columns"> <div class="medium-9 columns">
<div class="section"> <div class="section">
<div class="profile-header user-profile-bg--{{ udoc.background_img }}"> <div class="profile-header user-profile-bg--{{ udoc.background_img or 1 }}">
<div class="profile-header__content"> <div class="profile-header__content">
<div class="media"> <div class="media">
<div class="media__left"> <div class="media__left">
@@ -58,7 +58,7 @@
{{ builtin.USER_GENDER_ICONS[udoc.gender] }} {{ builtin.USER_GENDER_ICONS[udoc.gender] }}
</span> </span>
{% endif %} {% endif %}
{% if handler.has_perm(perm.PERM_MOD_BADGE) %} {% if handler.hasPerm(perm.PERM_MOD_BADGE) %}
<span <span
class="profile-header__contact-item user-profile-badge badge--mod" class="profile-header__contact-item user-profile-badge badge--mod"
data-tooltip="{{ _('{0} is a moderator of this domain.').format(_('She' if udoc.gender == 1 else 'He')) }}" data-tooltip="{{ _('{0} is a moderator of this domain.').format(_('She' if udoc.gender == 1 else 'He')) }}"
@@ -74,14 +74,82 @@
<div class="profile-content"> <div class="profile-content">
<div class="section__tab-container immersive"> <div class="section__tab-container immersive">
<ul class="section__tabs"> <ul class="section__tabs">
<li class="section__tab-item">
<h1 class="section__tab-title">{{ _('Bio') }}</h1>
<div class="section__tab-main">
{% if not udoc.bio %}
{{ nothing.render("This person is lazy and didn't wrote anything.") }}
{% else %}
{{ udoc.bio|markdown|safe }} {{ udoc.bio|markdown|safe }}
{% endif %}
</div>
</li>
<li class="section__tab-item">
<h1 class="section__tab-title">{{ _('Contributions') }} ({{ pcount }})</h1>
<div class="section__tab-main">
{% if not pdocs %}
{{ nothing.render("Oh, the user doesn't have any contributions!") }}
{% else %}
<div class="section__header">
<h1 class="section__title">{{ _('Contributed Problems') }}</h1>
</div>
<div class="section__body">
{% for pdoc in pdocs %}
<p><a href="/p/{{pdoc.pid}}">{{ pdoc['title'] }}</a></p>
{% endfor %}
</div>
{% endif %}
</div>
</li>
<li class="section__tab-item">
<h1 class="section__tab-title">{{ _('Submissions') }} ({{ udoc['nSubmit']|default(0) }})</h1>
<div class="section__tab-main">
{% if not rdocs %}
{{ nothing.render("Oh, the user hasn't submitted yet!") }}
{% else %}
<div class="section__header">
<h1 class="section__title">{{ _('Recent Submissions') }}</h1>
</div>
<div class="section__body no-padding">
<table class="data-table record_main__table">
<colgroup>
<col class="col--status">
<col class="col--problem">
<col class="col--submit-by">
<col class="col--time">
<col class="col--memory">
<col class="col--lang">
<col class="col--submit-at">
</colgroup>
<thead>
<tr>
<th class="col--status record-status--border">{{ _('Status') }}</th>
<th class="col--problem">{{ _('Problem') }}</th>
<th class="col--submit-by">{{ _('Submit By') }}</th>
<th class="col--time">{{ _('Time') }}</th>
<th class="col--memory">{{ _('Memory') }}</th>
<th class="col--lang">{{ _('Language') }}</th>
<th class="col--submit-at">{{ _('Submit At') }}</th>
</tr>
</thead>
<tbody>
{% for rdoc in rdocs %}
{% set pdoc = pdict[rdoc.pid] %}
{% include 'record_main_tr.html' %}
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
</div>
</li>
</ul> </ul>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="medium-3 columns"> <div class="medium-3 columns">
{% if is_self_profile %} {% if isSelfProfile %}
{{ home.render_sidebar() }} {{ home.render_sidebar() }}
{% endif %} {% endif %}
<div class="section side"> <div class="section side">
+6 -30
View File
@@ -1,42 +1,18 @@
import attachObjectMeta from './util/objectMeta'; import attachObjectMeta from './util/objectMeta';
export const CONTEST_TYPE_CONTEST = 1; export const RULE_OI = 'oi';
export const CONTEST_TYPE_HOMEWORK = 2; export const RULE_ACM = 'acm';
export const RULE_HOMEWORK = 'homework';
export const RULE_OI = 2; export const RULES = [
export const RULE_ACM = 3;
export const RULE_ASSIGNMENT = 11;
export const DOCTYPE_TO_CTYPE = {
30: 'contest',
60: 'homework',
};
attachObjectMeta(DOCTYPE_TO_CTYPE, 'intKey', true);
export const CTYPE_TO_DOCTYPE = {
contest: 30,
homework: 60,
};
export const CONTEST_RULES = [
RULE_OI, RULE_OI,
RULE_ACM, RULE_ACM,
RULE_HOMEWORK,
]; ];
export const HOMEWORK_RULES = [
RULE_ASSIGNMENT,
];
export const RULE_ID = {
[RULE_OI]: 'oi',
[RULE_ACM]: 'acm',
[RULE_ASSIGNMENT]: 'assignment',
};
attachObjectMeta(RULE_ID, 'intKey', true);
export const RULE_TEXTS = { export const RULE_TEXTS = {
[RULE_OI]: 'OI', [RULE_OI]: 'OI',
[RULE_ACM]: 'ACM/ICPC', [RULE_ACM]: 'ACM/ICPC',
[RULE_ASSIGNMENT]: 'Assignment', [RULE_HOMEWORK]: 'Assignment',
}; };
attachObjectMeta(RULE_TEXTS, 'intKey', true); attachObjectMeta(RULE_TEXTS, 'intKey', true);