修复discussion模块

This commit is contained in:
undefined committed 2020-05-01 18:43:40 +08:00
1 parent 2554cf660a
commit 33e277f28f
30 files changed
+2460 -187

No files matched your search

+2 -2
View File
@@ -11,7 +11,7 @@ process.stdin.on('data', async (input) => {
global.Hydro = {
handler: {},
template: {}
template: {},
};
require('./lib/i18n');
@@ -44,7 +44,7 @@ async function run() {
for (const i in global.Hydro.handler) {
await global.Hydro.handler[i].apply();
}
const notfound = require(`./handler/notfound`);
const notfound = require('./handler/notfound');
await notfound.apply();
server.start();
}
+8 -6
View File
@@ -225,6 +225,13 @@ class DiscussionNotFoundError extends NotFoundError {
}
}
class MessageNotFoundError extends NotFoundError {
constructor(mid) {
super('Message {0} not found.');
this.params = [mid];
}
}
global.Hydro.error = module.exports = {
BadRequestError,
BlacklistedError,
@@ -258,6 +265,7 @@ global.Hydro.error = module.exports = {
DocumentNotFoundError,
DiscussionNotFoundError,
RoleAlreadyExistError,
MessageNotFoundError,
};
/*
@@ -314,12 +322,6 @@ class DiscussionNodeAlreadyExistError(ForbiddenError):
return 'Discussion node {1} already exists.'
class MessageNotFoundError(NotFoundError):
@property
def message(self):
return 'Message {0} not found.'
class TrainingRequirementNotSatisfiedError(ForbiddenError):
@property
def message(self):
+2 -2
View File
@@ -25,8 +25,8 @@ class DiscussionHandler extends Handler {
if (did) {
this.ddoc = await discussion.get(did);
if (!this.ddoc) throw new DiscussionNotFoundError(did);
type = this.ddoc.type;
docId = this.ddoc.parent;
type = this.ddoc.parentType;
docId = this.ddoc.parentId;
if (drid) {
this.drdoc = await discussion.getReply(drid, did);
if (!this.drdoc) throw new DiscussionNotFoundError(drid);
+72 -79
View File
@@ -1,13 +1,15 @@
const {
VerifyPasswordError, UserAlreadyExistError, InvalidTokenError,
NotFoundError,
NotFoundError, MessageNotFoundError,
} = require('../error');
const options = require('../options');
const bus = require('../service/bus');
const { Route, Handler } = require('../service/server');
const md5 = require('../lib/md5');
const contest = require('../model/contest');
const user = require('../model/user');
const setting = require('../model/setting');
const discussion = require('../model/discussion');
const token = require('../model/token');
const training = require('../model/training');
const {
@@ -45,14 +47,13 @@ class HomeHandler extends Handler {
}
async discussion() {
// TODO(masnn)
// if (this.user.hasPerm(PERM_VIEW_DISCUSSION)) {
// const ddocs = await discussion.getMulti()
// .limit(DISCUSSIONS_ON_MAIN)
// .toArray();
// const vndict = await discussion.getListVnodes(map(discussion.node_id, ddocs));
// return [ddocs, vndict];
// }
if (this.user.hasPerm(PERM_VIEW_DISCUSSION)) {
const ddocs = await discussion.getMulti()
.limit(DISCUSSIONS_ON_MAIN)
.toArray();
const vndict = await discussion.getListVnodes(ddocs, this);
return [ddocs, vndict];
}
return [[], {}];
}
@@ -164,13 +165,72 @@ class UserChangemailWithCodeHandler extends Handler {
const udoc = await user.getByEmail(tdoc.mail);
if (udoc) throw new UserAlreadyExistError(tdoc.mail);
// TODO(twd2): Ensure mail is unique.
await user.set_mail(this.user._id, tdoc.mail);
await user.setEmail(this.user._id, tdoc.mail);
await token.delete(code, token.TYPE_CHANGEMAIL);
this.response.body = {};
this.response.redirect = '/home/security';
}
}
class HomeMessagesHandler extends Handler {
udoc(udict, key) { // eslint-disable-line class-methods-use-this
const udoc = udict[key];
if (!udoc) return;
const gravatar_url = misc.gravatar_url(udoc.gravatar);
if (udoc.gravatar) udict[key] = { ...udoc, gravatar_url, gravatar: '' };
}
async prepare() {
this.checkPerm(PERM_LOGGEDIN);
}
async get() {
// TODO(iceboy): projection, pagination.
const mdocs = await message.getMulti(this.user._id).sort('_id', -1).limit(50).toArray();
const udict = await user.getList([
...mdocs.map((mdoc) => mdoc.from),
...mdocs.map((mdoc) => mdoc.to),
]);
// TODO(twd2): improve here:
for (const mdoc of mdocs) {
this.modify_udoc(udict, mdoc.from);
this.modify_udoc(udict, mdoc.to);
}
this.response.body = { messages: mdocs, udict };
this.response.template = 'home_message.html';
}
async postSendMessage({ uid, content }) {
const udoc = await user.getById(uid);
const mdoc = await message.add(this.user._id, udoc._id, content);
// TODO(twd2): improve here:
// projection
mdoc.from = this.user;
this.modify_udoc(mdoc, 'from');
mdoc.to = udoc;
this.modify_udoc(mdoc, 'to');
if (this.user._id !== uid) {
await bus.publish(`user_message-${uid}`, { type: 'new', data: mdoc });
}
this.back({ mdoc });
}
async postReplyMessage({ message_id, content }) {
const [mdoc, reply] = await message.addReply(message_id, this.user._id, content);
if (!mdoc) throw new MessageNotFoundError(message_id);
if (mdoc.from !== mdoc.to) {
const other = mdoc.from === this.user._id ? mdoc.from : mdoc.to;
await bus.publish(`user_message-${other}`, { type: 'reply', data: mdoc });
}
mdoc.reply = [reply];
this.back({ reply });
}
async postDeleteMessage({ message_id }) {
await message.delete(message_id, this.user._id);
this.back();
}
}
async function apply() {
Route('/', module.exports.HomeHandler);
Route('/home/security', module.exports.HomeSecurityHandler);
@@ -181,75 +241,8 @@ async function apply() {
global.Hydro.handler.home = module.exports = {
HomeHandler, HomeSecurityHandler, HomeSettingsHandler, UserChangemailWithCodeHandler, apply,
};
/*
@app.route('/home/messages', 'home_messages', global_route=True)
class HomeMessagesHandler(base.OperationHandler):
def modify_udoc(this, udict, key):
udoc = udict.get(key)
if not udoc:
return
gravatar_url = misc.gravatar_url(udoc.get('gravatar'))
if 'gravatar' in udoc and udoc['gravatar']:
udict[key] = {**udoc,
'gravatar_url': gravatar_url,
'gravatar': ''}
@base.require_priv(builtin.PRIV_USER_PROFILE)
async def get(this):
# TODO(iceboy): projection, pagination.
mdocs = await message.get_multi(this.user['_id']).sort([('_id', -1)]).limit(50).to_list()
udict = await user.get_dict(
itertools.chain.from_iterable((mdoc['sender_uid'], mdoc['sendee_uid']) for mdoc in mdocs),
fields=user.PROJECTION_PUBLIC)
# TODO(twd2): improve here:
for mdoc in mdocs:
this.modify_udoc(udict, mdoc['sender_uid'])
this.modify_udoc(udict, mdoc['sendee_uid'])
this.json_or_render('home_messages.html', messages=mdocs, udict=udict)
@base.require_priv(builtin.PRIV_USER_PROFILE)
@base.require_csrf_token
@base.sanitize
async def post_send_message(this, *, uid: int, content: str):
udoc = await user.get_by_uid(uid, user.PROJECTION_PUBLIC)
if not udoc:
raise error.UserNotFoundError(uid)
mdoc = await message.add(this.user['_id'], udoc['_id'], content)
# TODO(twd2): improve here:
# projection
sender_udoc = await user.get_by_uid(this.user['_id'], user.PROJECTION_PUBLIC)
mdoc['sender_udoc'] = sender_udoc
this.modify_udoc(mdoc, 'sender_udoc')
mdoc['sendee_udoc'] = udoc
this.modify_udoc(mdoc, 'sendee_udoc')
if this.user['_id'] != uid:
await bus.publish('message_received-' + str(uid), {'type': 'new', 'data': mdoc})
this.json_or_redirect(this.url, mdoc=mdoc)
@base.require_priv(builtin.PRIV_USER_PROFILE)
@base.require_csrf_token
@base.sanitize
async def post_reply_message(this, *, message_id: objectid.ObjectId, content: str):
mdoc, reply = await message.add_reply(message_id, this.user['_id'], content)
if not mdoc:
return error.MessageNotFoundError(message_id)
if mdoc['sender_uid'] != mdoc['sendee_uid']:
if mdoc['sender_uid'] == this.user['_id']:
other_uid = mdoc['sendee_uid']
else:
other_uid = mdoc['sender_uid']
mdoc['reply'] = [reply]
await bus.publish('message_received-' + str(other_uid), {'type': 'reply', 'data': mdoc})
this.json_or_redirect(this.url, reply=reply)
@base.require_priv(builtin.PRIV_USER_PROFILE)
@base.require_csrf_token
@base.sanitize
async def post_delete_message(this, *, message_id: objectid.ObjectId):
await message.delete(message_id, this.user['_id'])
this.back();
@app.connection_route('/home/messages-conn', 'home_messages-conn', global_route=True)
class HomeMessagesConnection(base.Connection):
@base.require_priv(builtin.PRIV_USER_PROFILE)
+1 -3
View File
@@ -90,7 +90,6 @@ class JudgeHandler extends Handler {
}
async get({ check = false }) {
this.response.body = {};
if (check) return;
const tasks = [];
let rid = await queue.get('judge', false);
@@ -122,17 +121,16 @@ class JudgeHandler extends Handler {
tasks.push(task);
rid = await queue.get('judge', false); // eslint-disable-line no-await-in-loop
}
this.response.body = { tasks };
}
async postNext() {
await next(this.request.body);
this.response.body = {};
}
async postEnd() {
this.request.body.judger = this.user._id;
await end(this.request.body);
this.response.body = {};
}
}
class JudgeConnectionHandler extends ConnectionHandler {
+3 -3
View File
@@ -34,7 +34,7 @@ class ManageEditHandler extends ManageHandler {
await user.setById(0, {
uname, unameLower, gravatar, bio,
});
this.back();
this.response.redirect = '/manage/dashboard';
}
}
@@ -43,7 +43,7 @@ class ManageUserHandler extends ManageHandler {
const uids = [];
const rudocs = {};
const [udocs, roles, system] = await Promise.all([
user.getMulti({ role: { $ne: 'default' } }).toArray(),
user.getMulti({ role: { $nin: ['default', 'guest'] } }).toArray(),
user.getRoles(),
user.getById(0),
]);
@@ -61,7 +61,7 @@ class ManageUserHandler extends ManageHandler {
}
async postSetUser({ uid, role }) {
await user.setById(uid, { role });
await user.setRole(uid, role);
this.back();
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ const { NotFoundError } = require('../error');
class NotFoundHandler extends Handler {
async prepare() {
throw new NotFoundError();
throw new NotFoundError(); // eslint-disable-line class-methods-use-this
}
}
+1 -6
View File
@@ -25,7 +25,6 @@ class UserLoginHandler extends Handler {
udoc.password = '';
this.session.uid = udoc._id;
this.session.rememberme = rememberme;
this.response.body = {};
const referer = this.request.headers.referer || '/';
this.response.redirect = referer.endsWith('/login') ? '/' : referer;
}
@@ -42,7 +41,6 @@ class UserLogoutHandler extends Handler {
async post() {
this.session = { uid: 1 };
this.response.body = {};
}
}
@@ -66,7 +64,6 @@ class UserRegisterHandler extends Handler {
if (options.smtp.user) {
const 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]}`;
@@ -98,7 +95,6 @@ class UserRegisterWithCodeHandler extends Handler {
});
await token.delete(code, token.TYPE_REGISTRATION);
this.session.uid = uid;
this.response.body = {};
this.response.redirect = '/';
}
}
@@ -123,7 +119,6 @@ class UserLostPassHandler extends Handler {
);
const m = await this.renderHTML('user_lostpass_mail', { url: `/lostpass/${tid}`, uname: udoc.uname });
await sendMail(mail, 'Lost Password', 'user_lostpass_mail', m);
this.response.body = {};
this.response.template = 'user_lostpass_mail_sent.html';
}
}
@@ -174,7 +169,7 @@ class UserSearchHandler extends Handler {
}
for (const i in udocs) {
if (udocs[i].gravatar) {
udocs[i].gravatar_url = misc.gravatar_url[udocs[i].gravatar];
udocs[i].gravatar_url = misc.gravatar_url(udocs[i].gravatar);
}
}
this.response.body = udocs;
+1
View File
@@ -15,6 +15,7 @@ exports.udoc = {
regat: new Date(),
regip: '0.0.0.0',
gravatar: '',
viewLang: 'zh_CN',
loginat: new Date(),
loginip: '0.0.0.0',
};
+4
View File
@@ -13,6 +13,10 @@ export interface Udoc {
nSubmit: number
nLike: number
perm: string
viewLang: string
codeLang: string
codeTemplate: string
gravatar: string
hasPerm: Function
checkPassword: Function
}
+4 -1
View File
@@ -1,8 +1,9 @@
const md5 = require('./md5');
exports.gravatar_url = function gravatarUrl(email, size) {
exports.gravatar_url = function gravatarUrl(email, size = 32) {
return `//gravatar.loli.net/avatar/${md5((email || '').toString().trim().toLowerCase())}?d=mm&s=${size}`;
};
exports.datetime_span = function datetimeSpan(dt, relative = true, format = '%Y-%m-%d %H:%M:%S') {
if (!dt) return 'DATETIME_SPAN_ERROR';
if (dt.generationTime) dt = new Date(dt.generationTime * 1000);
@@ -13,6 +14,7 @@ exports.datetime_span = function datetimeSpan(dt, relative = true, format = '%Y-
dt.format(format),
);
};
exports.paginate = function* paginate(page, numPages) {
const radius = 2; let first; let
last;
@@ -33,6 +35,7 @@ exports.paginate = function* paginate(page, numPages) {
if (page < numPages) yield ['next', page + 1];
yield ['last', numPages];
};
exports.format_size = function formatSize(size, base = 1) {
size *= base;
const unit = 1024;
+26 -2
View File
@@ -1,4 +1,5 @@
const { ObjectID } = require('bson');
const problem = require('./problem');
const { DocumentNotFoundError } = require('../error');
const db = require('../service/db.js');
@@ -6,8 +7,8 @@ const coll = db.collection('discussion');
const collReply = db.collection('discussion.reply');
const collStatus = db.collection('discussion.status');
function add(parentType, parentId, owner, title, content, ip = null, highlight = false) {
return coll.insertOne({
async function add(parentType, parentId, owner, title, content, ip = null, highlight = false) {
let res = await coll.insertOne({
owner,
title,
content,
@@ -18,6 +19,7 @@ function add(parentType, parentId, owner, title, content, ip = null, highlight =
nReply: 0,
updateAt: new Date(),
});
return res.insertedId;
}
function get(did) {
@@ -128,6 +130,26 @@ function getStatus(did, uid) {
return collStatus.findOne({ did, uid });
}
async function getVnode(ddoc, handler) {
if (ddoc.parentType === 'problem') {
const pdoc = await problem.getById(ddoc.parentId);
if (!pdoc) return null;
if (pdoc.hidden && handler) handler.checkPerm(PERM_VIEW_PROBLEM_HIDDEN);
return { ...pdoc, parentType: ddoc.parentType, parentId: ddoc.parentId };
} if (ddoc.parentType === 'contest') {
const tdoc = await contest.get(ddoc.parentId);
return { ...tdoc, parentType: ddoc.parentType, parentId: ddoc.parentId };
} return null;
}
async function getListVnodes(ddocs, handler) {
const res = {};
for (const ddoc of ddocs) {
res[ddoc._id] = await getVnode(ddoc, handler);
}
return res;
}
module.exports = {
add,
get,
@@ -147,4 +169,6 @@ module.exports = {
delTailReply,
setStar,
getStatus,
getVnode,
getListVnodes,
};
+3 -2
View File
@@ -15,12 +15,13 @@ class USER {
this.salt = user.salt;
this.hash = user.hash;
this.perm = user.perm;
this.lang = user.language || 'zh_CN';
this.viewLang = user.language || 'zh_CN';
this.codeLang = user.codeLang || 'c';
this.codeTemplate = user.codeTemplate || '';
this.regat = user.regat;
this.loginat = user.loginat;
this.bio = user.bio || '';
this.gravatar = user.gravatar || '';
this.nAccept = user.nAccept || 0;
this.nSubmit = user.nSubmit || 0;
}
@@ -144,7 +145,7 @@ async function getPrefixList(prefix, limit = 50) {
async function setRole(uid, role) {
const udoc = await getById(uid);
return await Promise.all([
coll.findOneAndUpdate({ _id: uid }, { role }),
coll.findOneAndUpdate({ _id: uid }, { $set: { role } }),
collRole.updateOne({ _id: udoc.role }, { $inc: { count: -1 } }),
collRole.updateOne({ _id: role }, { $inc: { count: 1 } }),
]);
+1
View File
@@ -44,6 +44,7 @@ let options = {
CONTEST_PER_PAGE: 20,
TRAINING_PER_PAGE: 10,
DISCUSSION_PER_PAGE: 50,
REPLY_PER_PAGE: 50,
CONTESTS_ON_MAIN: 5,
TRAININGS_ON_MAIN: 5,
DISCUSSIONS_ON_MAIN: 20,
+2 -2
View File
@@ -113,7 +113,6 @@ class Handler {
back(body) {
if (body) this.response.body = body;
else if (this.preferJson) this.response.body = {};
this.response.redirect = this.request.headers.referer || '/';
}
@@ -129,6 +128,7 @@ class Handler {
}
async ___prepare() {
this.response.body = {};
this.now = new Date();
this._handler.sid = this.request.cookies.get('sid');
this._handler.save = this.request.cookies.get('save');
@@ -241,7 +241,7 @@ class Handler {
}
}
const check = ['tid', 'rid', 'did', 'drid', 'drrid', 'psid', 'psrid'];
const check = ['tid', 'rid', 'did', 'drid', 'drrid', 'psid', 'psrid', 'docId'];
function Route(route, RouteHandler) {
router.all(route, async (ctx) => {