SYZOJ 部署&魔改记录

应教练要求,给学校搞个 OJ。

(就学校那电脑十几年没换了还部署什么 OJ)

部署

一开始用的是 UOJ,但是不会 PHP,为了魔改于是换了 SYZOJ。

然后出了很多奇奇怪怪的错误,装了几次都没成功。

一直用的是清华的更新源,结果 potatoler 无意中发现把更新源换成阿里的就没有遇到之前的问题……

魔改

名字颜色

话说 SYZOJ 怎么都没有个按 rating 显示名字颜色的功能啊 (隔壁 UOJ 早就有了

新建 static/self/custom.css 并加入每种颜色的样式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.user-gray {
color: rgb(191, 191, 191) !important;
}
.user-blue {
color: rgb(52, 152, 219) !important;
}
.user-green {
color: rgb(82, 196, 26) !important;
}
.user-orange {
color: rgb(243, 156, 17) !important;
}
.user-red {
color: rgb(254, 76, 97) !important;
}
.user-purple {
color: rgb(157, 61, 207) !important;
}

然后在 views/header.ejs 中加入 <link href="/self/custom.css" rel="stylesheet">

打开 utility.js,在 module.exports 中加入用于计算颜色的代码:

1
2
3
4
5
6
7
8
makeUserColor(rating, is_admin) {
if (is_admin) return 'purple';
else if (rating < 1400) return 'gray';
else if (rating < 1600) return 'blue';
else if (rating < 1800) return 'green';
else if (rating < 2000) return 'orange';
else return 'red';
}

之后就是在所有 ejs 文件中,将类似 <%= xxx.username %> 的代码改为 <span class="user-<%= syzoj.utils.makeUserColor(xxx.rating, xxx.is_admin) %>"><%= xxx.username %></span>

改完后发现用户名的字体太细,加上颜色后看着很不舒服,所以把用户名加粗一些。

在 static/self/custom.css 中加入:

1
2
3
.user-name {
font-weight: bold;
}

然后在上面修改的代码中,把 class="user-<%= syzoj.utils.makeUserColor(xxx.rating, xxx.is_admin) %>" 改为 class="user-name user-<%= syzoj.utils.makeUserColor(xxx.rating, xxx.is_admin) %>"

显示姓名

作为校内 OJ,为了方便辨识,所以要加这个功能。(毕竟直接用姓名做用户名看着还是怪难受的(

数据库中用户有 nameplate 属性,代码中也有显示 nameplate 的处理,但是没有修改的接口,于是直接用 nameplate 表示姓名,添加一些代码即可。

首先是在注册页面加一个输入框,将以下代码加入 views/sign_up.ejs 中对应位置:

1
2
3
4
<div class="field">
<label for="nameplate">姓名</label>
<input type="text" placeholder="" id="nameplate">
</div>

然后在这个文件中的 javascript 代码部分加入提交 nameplate 的代码:

1
2
3
4
5
6
7
8
9
10
 url: '/api/sign_up',
type: 'POST',
async: true,
data: {
username: $("#username").val(),
+ nameplate: $("#nameplate").val(),
password: password,
email: $("#email").val(),
prevUrl: <%- serializejs(req.query.url || '/') %>
},

之后在 modules/api.js 中加入几段代码:

1
2
3
4
5
6
 let sendObj = {
username: req.body.username,
password: req.body.password,
+ nameplate: req.body.nameplate,
email: req.body.email,
};
1
2
3
4
5
6
7
 user = await User.create({
username: req.body.username,
password: req.body.password,
+ nameplate: req.body.nameplate,
email: req.body.email,
is_show: syzoj.config.default.user.show,
rating: syzoj.config.default.user.rating,
1
2
3
4
5
6
7
 user = await User.create({
username: obj.username,
password: obj.password,
+ nameplate: obj.nameplate,
email: obj.email,
is_show: syzoj.config.default.user.show,
rating: syzoj.config.default.user.rating,
1
2
3
4
5
6
7
 user = await User.create({
username: obj.username,
password: obj.password,
+ nameplate: obj.nameplate,
email: obj.email,
public_email: true
});

另外在修改个人信息的页面也要加入修改姓名的接口,所以在 views/user_edit.ejs 中加入代码:

1
2
3
4
<div class="field">
<label for="nameplate">姓名</label>
<input type="text" id="nameplate" name="nameplate" value="<%= edited_user.nameplate %>"<% if (!user.allowedManage) { %> readonly<% } %>>
</div>

然后在 modules/user.js 中加入修改的代码:

1
2
3
4
5
6
 if (res.locals.user && await res.locals.user.hasPrivilege('manage_user')) {
if (!syzoj.utils.isValidUsername(req.body.username)) throw new ErrorMessage('无效的用户名。');
user.username = req.body.username;
user.email = req.body.email;
+ user.nameplate = req.body.nameplate;
}

为了让显示效果更美观,在 static/self/custom.css 中加一个样式:

1
2
3
.user-nameplate {
font-size: 6px;
}

最后在所有 ejs 文件中,将显示 nameplate 的代码改一下:

1
<span class="user-gray user-nameplate"><%= xxx.nameplate %></span>

姓名就会在用户名的后面显示为灰色小字。


改 views/sign_up.ejs 的时候还发现了这样一段代码:

1
alert("注册确认邮件已经发送到您的邮箱的垃圾箱,点击邮件内的链接即可完成注册。");

(………………?)

用户 Tag

在数据库中,每个用户有一个 nickname 属性,但在代码中没有关于 nickname 的任何操作,所以就直接用 nickname 储存 tag。

首先要在修改个人信息的页面加一个输入框,那么往 views/user_edit.ejs 里添加代码:

1
2
3
4
5
6
<% if (edited_user.nickname || user.is_admin) { %>
<div class="field">
<label for="nickname">Tag</label>
<input type="text" id="nickname" name="nickname" value="<%= edited_user.nickname %>"<% if (!user.is_admin) { %> readonly<% } %>>
</div>
<% } %>

然后在 modules/user.js 中加入修改的代码:

1
2
3
4
5
 if (res.locals.user && res.locals.user.is_admin) {
+ user.nickname = req.body.nickname;
if (!req.body.privileges) {
req.body.privileges = [];
} else if (!Array.isArray(req.body.privileges)) {

之后在 static/self/custom.css 中添加显示效果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
.bg-gray {
background-color: rgb(191, 191, 191) !important;
}
.bg-blue {
background-color: rgb(52, 152, 219) !important;
}
.bg-green {
background-color: rgb(82, 196, 26) !important;
}
.bg-orange {
background-color: rgb(243, 156, 17) !important;
}
.bg-red {
background-color: rgb(254, 76, 97) !important;
}
.bg-purple {
background-color: rgb(157, 61, 207) !important;
}

.user-tag {
border-radius: 3px;
display: inline-block;
padding: .3em .5em;
font-weight: 700;
color: #fff;
line-height: 1;
font-size: 11px;
margin: .2em;
}

最后修改所有 ejs 文件,在 username 和 nameplate 之间加入显示 tag 的代码:

1
<% if (xxx.nickname) { %><span class="user-tag bg-<%= syzoj.utils.makeUserColor(xxx.rating, xxx.is_admin) %>"><%- xxx.nickname %></span><% } %>

结果发现需要显示的内容太长,在有些位置显示时被拆成了两行,所以再修改一下有问题的位置。

views/index.ejs:

1
2
-<th style="width: 170px; ">用户名</th>
+<th style="width: 200px; ">用户名</th>

views/discussion.ejs:

1
2
-<th style="width: 10%; ">作者</th>
+<th style="width: 25%; ">作者</th>

(感谢 potatoler 用一晚上的时间为 OJ 画的 logo)

在 views/header.ejs 中添加 <link rel="icon" href="xxx" type="image/x-icon">,用于设置网页标题旁的 logo。

在这个文件中添加 <img src="xxx" style="width: 32px; height: 32px; margin-right: 16px;">,用于设置顶栏上的 logo。

讨论修改权限

SYZOJ 的讨论区中,发帖人和全站管理员可以修改帖子。

感觉这个设定不太合适,决定去掉发帖人修改帖子的权限,再添加一个“管理社区”权限,可以修改所有讨论。

首先在 views/user_edit.ejs 中加入“管理社区”的选项:

1
2
3
4
<div class="ui toggle <% if (!allowedManagePrivilege) { %>disabled <% } %>checkbox checkbox_privilege" data-name="manage_community">
<input <% if (!allowedManagePrivilege) { %>disabled="disabled" <% } %>type="checkbox"<% if (edited_user.privileges.includes('manage_community')) { %> checked<% } %>>
<label>管理社区</label>
</div>

然后在 modules/discussion.js 中将 await article.isAllowedEditBy(res.locals.user) 改为 res.locals.user.is_admin || await res.locals.user.hasPrivilege('manage_community')

回复删除权限

同样还是去掉回复人删除回复的权限,再让“管理社区”权限可以删除回复。

在 modules/discussion.js 中将 await comment.isAllowedEditBy(res.locals.user) 改为 res.locals.user.is_admin || await res.locals.user.hasPrivilege('manage_community')

Testlib

SYZOJ 不支持用 Testlib 写的 spj,为了加上这个功能,本来想着再魔改一下,但发现已经有改好的版本在 pastebin 上,直接放到 /opt/syzoj/sandbox/rootfs/usr/include/ 即可。

结果突然发现这个 Testlib 还有锅……不能处理 Partially Correct 的情况……

在这个 Testlib 中找到这句:

1
std::string stringPoints = removeDoubleTrailingZeroes(format("%.10f", __testlib_points));

改为

1
std::string stringPoints = format("%d", (int)(__testlib_points * 100));

另外这个 Testlib 还不支持交互器,找到 registerInteraction 函数改为这样即可:

1
2
3
4
5
6
7
8
9
void registerInteraction (int argc, char* argv[]) {
__testlib_ensuresPreconditions ();
testlibMode = _interactor;
__testlib_set_binary (stdin);
inf.init ("input", _input);
ouf.init (stdin, _output);
resultName = "";
appesMode = false;
}

注册审核功能

因为是校内 OJ,所以要加入注册审核功能,注册信息必须通过审核才可以使用 OJ。

但是当 OJ 还没有用户时,就无法注册用户,因为还没有管理员审核。

于是直接将注册审核捆绑到邮箱验证上,当邮箱验证关闭时也同时关闭注册审核。(反正都是用于验证的)

(好然后又写了很多不可维护代码


考虑在注册账号后将注册信息存入数据库,然后邮件通知管理员审核。

但这样又太麻烦,当有一个用户注册时就必须遍历一遍当前的所有用户,然后再判断是否为管理员。

于是改成当管理员登录 OJ 时查询数据库,将待审核用户显示在主页上。

这个功能因为 (似乎) 比较复杂,所以我负责后端,前端主要由 potatoler 编写。


首先就需要一个用于存待审核用户的表,新建 models/pending_user.ts 文件并写入以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import * as TypeORM from "typeorm";
import Model from "./common";

@TypeORM.Entity()
export default class PendingUser extends Model {
@TypeORM.Index()
@TypeORM.PrimaryColumn({type: "varchar", length: 80 })
username: string;

@TypeORM.Column({type: "varchar", length: 120 })
password: string;

@TypeORM.Column({type: "text" })
nameplate: string;

@TypeORM.Column({type: "integer" })
sex: number;

@TypeORM.Column({type: "varchar", length: 120 })
email: string;
}

另外还需要一个显示信息的页面,新建 views/info.ejs 并写入以下内容:

1
2
3
4
5
6
7
8
9
10
11
<% this.title = '信息' %>
<% include header %>

<div class="ui info icon message">
<i class="info icon"></i>
<div class="header">
<%= info %>
</div>
</div>

<% include footer %>

然后修改注册时的操作,在 modules/api.js 的开头加入 let PendingUser = syzoj.model('pending_user');,用于操作数据库中的待审核用户。

然后找到 app.get('/api/sign_up_confirm', async (req, res) => {,去掉新建用户的操作,改为向待审核用户中添加:

1
2
3
4
5
6
7
8
9
10
11
12
user = await PendingUser.create({
username: obj.username,
password: obj.password,
nameplate: obj.nameplate,
sex: obj.sex,
email: obj.email
});
await user.save();

res.render('info', {
info: '请等待管理员审核。'
});

另外还需要处理前端向 /api/allow_user/:username/api/block_user/:username 发送的 post 请求,表示审核状态:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
app.post('/api/allow_user/:username', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
let allowed = await res.locals.user.hasPrivilege('manage_user');
if (!allowed) throw new ErrorMessage('您没有权限进行此操作。');

let pending_user = await PendingUser.findOne ({
where: {
username: req.params.username
}
});
if (!pending_user) throw new ErrorMessage('无此用户。');
let user = await User.fromName(req.params.username);
if (user) throw new ErrorMessage('用户名已被占用。');
user = await User.findOne({ where: { email: pending_user.email } });
if (user) throw new ErrorMessage('邮件地址已被占用。');

user = await User.create({
username: pending_user.username,
password: pending_user.password,
nameplate: pending_user.nameplate,
sex: pending_user.sex,
email: pending_user.email,
is_show: syzoj.config.default.user.show,
rating: syzoj.config.default.user.rating,
register_time: parseInt((new Date()).getTime() / 1000)
});
await user.save();

try {
await Email.send(pending_user.email,
`${pending_user.username}${syzoj.config.title} 注册审核通知`,
`<p>您在 ${syzoj.config.title} 的注册已通过审核。</p>`
);
} catch (e) {}

await pending_user.destroy();

} catch (e) {
syzoj.log(e);
res.send(e);
}
});

app.post('/api/block_user/:username', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
let allowed = await res.locals.user.hasPrivilege('manage_user');
if (!allowed) throw new ErrorMessage('您没有权限进行此操作。');

let pending_user = await PendingUser.findOne ({
where: {
username: req.params.username
}
});
if (!pending_user) throw new ErrorMessage('无此用户。');

try {
await Email.send(pending_user.email,
`${pending_user.username}${syzoj.config.title} 注册审核通知`,
`<p>您在 ${syzoj.config.title} 的注册已被拒绝。</p>`
);
} catch (e) {}

await pending_user.destroy();

} catch (e) {
syzoj.log(e);
res.send(e);
}
});

最后修改 modules/index.js,向前端传递权限信息和待审核用户。

先在开头加入 let PendingUser = syzoj.model('pending_user');,然后找到 app.get('/', async (req, res) => {,修改其中加载页面的位置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
+let pending_user = await PendingUser.find ();

res.render('index', {
ranklist: ranklist,
notices: notices,
fortune: fortune,
contests: contests,
problems: problems,
links: syzoj.config.links,
- is_logined: !!res.locals.user
+ is_logined: !!res.locals.user,
+ allowedManage: res.locals.user && await res.locals.user.hasPrivilege('manage_user'),
+ pending_user: pending_user
});

对于前端部分,首先在 views/index.ejs 找到侧边栏,然后加入以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<% if (is_logined && allowedManage && pending_user && pending_user.length) { %>
<h4 class="ui top attached block header"><i class="user icon"></i>待审核用户</h4>
<div class="ui bottom attached segment">
<table class="ui very basic center aligned table" style="table-layout: fixed; ">
<tbody>
<%
for (let i = 0; i < pending_user.length; i++) {
let user = pending_user[i];
%>
<tr id = "pending_<%= user.username %>">
<td style="text-align:left;"><span class="user-name user-blue"><%= user.username %></span><span class="user-gray user-nameplate"><%= user.nameplate %></span></td>
<td style="width: 90px;">
<a style="width: 35px; padding-right: 5px; padding-left: 5px; padding-top: 5px; padding-bottom: 5px" class="ui mini green right button" onclick=userAllow("<%= user.username %>")>
通过
</a>
<a style="width: 35px; padding-right: 5px; padding-left: 5px; padding-top: 5px; padding-bottom: 5px" class="ui mini gray right button" onclick=userBlock("<%= user.username %>")>
忽略
</a>
</td>
</tr>
<% } %>
</tbody>
</table>
</div>
<% } %>

然后在 script 部分加入点击按钮时的操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function userAllow (username) {
$.ajax({
url: '/api/allow_user/' + username,
type: 'POST',
async: true
});
let nod = document.getElementById ("pending_" + username);
let par = nod.parentNode;
par.removeChild (nod);
if (!par.childElementCount) {
par.parentNode.removeChild (par);
}
}
function userBlock (username) {
$.ajax({
url: '/api/block_user/' + username,
type: 'POST',
async: true
});
let nod = document.getElementById ("pending_" + username);
let par = nod.parentNode;
par.removeChild (nod);
if (!par.childElementCount) {
par.parentNode.removeChild (par);
}
}

另外,在注册页面加上一个提示信息:

1
<label for="nameplate">真实姓名<span style="color: red; font-weight: 500;">真实姓名填写错误会影响管理员对该账号的审核</span></label>

最后,因为修改了 ts 文件,所以需要执行 yarn 重新编译才会使修改生效。

NOIp 倒计时

在主页的侧边栏加一个 NOIp 倒计时的功能,再加上一个圆环形的类似进度条的东西,根据剩余时间改变颜色。

本来是用 css 做了很久,最后发现还是 svg 最方便。

首先显示一个灰色的圆环,然后再显示一个半径相同、宽度相同的环形虚线,设置虚线的间隔为大于环长的值,那么就可以显示出指定长度的圆弧。

在 views/index.ejs 中加入以下代码:

1
2
3
4
5
6
7
8
<h4 class="ui top attached block header"><i class="ui clock icon" style="display: inline-block; margin-right: .75rem;"></i>距离 <span style="color: <%= noip_color %>">NOIp<%= noip_year %></span> 还有</h4>
<div class="ui bottom attached center aligned segment">
<svg width="140" height="140" viewBox="0 0 140 140">
<circle cx="70" cy="70" r="65" stroke-width="10" stroke="#E5E5E5" fill="none"></circle>
<circle cx="70" cy="70" r="65" stroke-width="10" stroke="<%= noip_color %>" fill="none" transform="matrix(0, -1, 1, 0, 0, 140)" stroke-dasharray="<%= noip_arc %> 409"></circle>
<text style="dominant-baseline:middle;text-anchor:middle;font-size: 30px;font-weight: 800; fill: <%= noip_color %>" y="70" x="70"><%= noip_day %>天</text>
</svg>
</div>

然后在 modules/index.js 中加入以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
let getNOIpDay = function (year) {
let fg = 0;
let d;
for (let i = 1; i <= 14; ++i) {
d = new Date (year, 10, i);
if (d.getDay () == 6) {
if (fg) {
return d;
}
else {
fg = 1;
}
}
}
}
let year = new Date ().getFullYear ();
let day = parseInt ((getNOIpDay (year) - new Date ()) / (1000 * 60 * 60 * 24));
if (day == -1) {
day = 0;
}
else if (day < -1) {
++year;
day = parseInt ((getNOIpDay (year) - new Date ()) / (1000 * 60 * 60 * 24));
}

let noip_color;
if (day <= 91) {
noip_color = "#e74c3c";
}
else if (day <= 182) {
noip_color = "#e67e22";
}
else if (day <= 273) {
noip_color = "#f1c40f";
}
else {
noip_color = "#2dce89";
}

然后再将数据传给前端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 res.render('index', {
ranklist: ranklist,
notices: notices,
fortune: fortune,
contests: contests,
problems: problems,
links: syzoj.config.links,
is_logined: !!res.locals.user,
allowedManage: res.locals.user && res.locals.user.hasPrivilege('manage_user'),
- pending_user: pending_user
+ pending_user: pending_user,
+ noip_year: year,
+ noip_day: day,
+ noip_color: noip_color,
+ noip_arc: day / 365 * 409
});

就可以实现这样的效果:

比赛界面

因为在比赛界面中点击排行榜会跳到另一个页面,看不到原来的比赛信息,所以决定修改一下,同时也改了改其他部分。

modules/contest.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
let Contest = syzoj.model('contest');
let ContestRanklist = syzoj.model('contest_ranklist');
let ContestPlayer = syzoj.model('contest_player');
let Problem = syzoj.model('problem');
let JudgeState = syzoj.model('judge_state');
let User = syzoj.model('user');

const jwt = require('jsonwebtoken');
const { getSubmissionInfo, getRoughResult, processOverallResult } = require('../libs/submissions_process');

app.get('/contests', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
let where;
if (res.locals.user && res.locals.user.is_admin) where = {}
else where = { is_public: true };

let paginate = syzoj.utils.paginate(await Contest.countForPagination(where), req.query.page, syzoj.config.page.contest);
let contests = await Contest.queryPage(paginate, where, {
start_time: 'DESC'
});

await contests.forEachAsync(async x => x.subtitle = await syzoj.utils.markdown(x.subtitle));

res.render('contests', {
contests: contests,
paginate: paginate
})
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

app.get('/contest/:id/edit', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
if (!res.locals.user || !res.locals.user.is_admin) throw new ErrorMessage('您没有权限进行此操作。');

let contest_id = parseInt(req.params.id);
let contest = await Contest.findById(contest_id);
if (!contest) {
contest = await Contest.create();
contest.id = 0;
} else {
await contest.loadRelationships();
}

let problems = [], admins = [];
if (contest.problems) problems = await contest.problems.split('|').mapAsync(async id => await Problem.findById(id));
if (contest.admins) admins = await contest.admins.split('|').mapAsync(async id => await User.findById(id));

res.render('contest_edit', {
contest: contest,
problems: problems,
admins: admins
});
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

app.post('/contest/:id/edit', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
if (!res.locals.user || !res.locals.user.is_admin) throw new ErrorMessage('您没有权限进行此操作。');

let contest_id = parseInt(req.params.id);
let contest = await Contest.findById(contest_id);
let ranklist = null;
if (!contest) {
contest = await Contest.create();

contest.holder_id = res.locals.user.id;

ranklist = await ContestRanklist.create();
} else {
await contest.loadRelationships();
ranklist = contest.ranklist;
}

if (!['NOI', 'IOI', 'ACM'].includes(req.body.type)) throw new ErrorMessage('无效的赛制。');
contest.type = req.body.type;

try {
ranklist.ranking_params = JSON.parse(req.body.ranking_params);
} catch (e) {
ranklist.ranking_params = {};
}
await ranklist.save();
contest.ranklist_id = ranklist.id;

if (!req.body.title.trim()) throw new ErrorMessage('比赛名不能为空。');
contest.title = req.body.title;
contest.subtitle = req.body.subtitle;
if (!Array.isArray(req.body.problems)) req.body.problems = [req.body.problems];
if (!Array.isArray(req.body.admins)) req.body.admins = [req.body.admins];
contest.problems = req.body.problems.join('|');
contest.admins = req.body.admins.join('|');
contest.information = req.body.information;
contest.start_time = syzoj.utils.parseDate(req.body.start_time);
contest.end_time = syzoj.utils.parseDate(req.body.end_time);
contest.is_public = req.body.is_public === 'on';
contest.hide_statistics = req.body.hide_statistics === 'on';

await contest.save();

res.redirect(syzoj.utils.makeUrl(['contest', contest.id]));
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

app.get('/contest/:id', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
const curUser = res.locals.user;
let contest_id = parseInt(req.params.id);

let contest = await Contest.findById(contest_id);
if (!contest) throw new ErrorMessage('无此比赛。');
if (!contest.is_public && (!res.locals.user || !res.locals.user.is_admin)) throw new ErrorMessage('比赛未公开,请耐心等待 (´∀ `)');

const isSupervisior = await contest.isSupervisior(curUser);
contest.running = contest.isRunning();
contest.ended = contest.isEnded();
contest.subtitle = await syzoj.utils.markdown(contest.subtitle);
contest.information = await syzoj.utils.markdown(contest.information);

let hasStatistics = false;
if ((!contest.hide_statistics) || (contest.ended) || (isSupervisior)) {
hasStatistics = true;
}

res.render('contest', {
contest: contest,
hasStatistics: hasStatistics,
isSupervisior: isSupervisior
});
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

app.get('/contest/:id/problem', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
const curUser = res.locals.user;
let contest_id = parseInt(req.params.id);

let contest = await Contest.findById(contest_id);
if (!contest) throw new ErrorMessage('无此比赛。');
if (!contest.is_public && (!res.locals.user || !res.locals.user.is_admin)) throw new ErrorMessage('比赛未公开,请耐心等待 (´∀ `)');

const isSupervisior = await contest.isSupervisior(curUser);
contest.running = contest.isRunning();
contest.ended = contest.isEnded();
contest.subtitle = await syzoj.utils.markdown(contest.subtitle);

if (!contest.running && !contest.ended && (!res.locals.user || !res.locals.user.is_admin)) throw new ErrorMessage('比赛未开始,请耐心等待 (´∀ `)');

let problems_id = await contest.getProblems();
let problems = await problems_id.mapAsync(async id => await Problem.findById(id));

let player = null;

if (res.locals.user) {
player = await ContestPlayer.findInContest({
contest_id: contest.id,
user_id: res.locals.user.id
});
}

problems = problems.map(x => ({ problem: x, status: null, judge_id: null, statistics: null }));
if (player) {
for (let problem of problems) {
if (contest.type === 'NOI') {
if (player.score_details[problem.problem.id]) {
let judge_state = await JudgeState.findById(player.score_details[problem.problem.id].judge_id);
problem.status = judge_state.status;
if (!contest.ended && !await problem.problem.isAllowedEditBy(res.locals.user) && !['Compile Error', 'Waiting', 'Compiling'].includes(problem.status)) {
problem.status = 'Submitted';
}
problem.judge_id = player.score_details[problem.problem.id].judge_id;
}
} else if (contest.type === 'IOI') {
if (player.score_details[problem.problem.id]) {
let judge_state = await JudgeState.findById(player.score_details[problem.problem.id].judge_id);
problem.status = judge_state.status;
problem.judge_id = player.score_details[problem.problem.id].judge_id;
await contest.loadRelationships();
let multiplier = contest.ranklist.ranking_params[problem.problem.id] || 1.0;
problem.feedback = (judge_state.score * multiplier).toString() + ' / ' + (100 * multiplier).toString();
}
} else if (contest.type === 'ACM') {
if (player.score_details[problem.problem.id]) {
problem.status = {
accepted: player.score_details[problem.problem.id].accepted,
unacceptedCount: player.score_details[problem.problem.id].unacceptedCount
};
problem.judge_id = player.score_details[problem.problem.id].judge_id;
} else {
problem.status = null;
}
}
}
}

let hasStatistics = false;
if ((!contest.hide_statistics) || (contest.ended) || (isSupervisior)) {
hasStatistics = true;

await contest.loadRelationships();
let players = await contest.ranklist.getPlayers();
for (let problem of problems) {
problem.statistics = { attempt: 0, accepted: 0 };

if (contest.type === 'IOI' || contest.type === 'NOI') {
problem.statistics.partially = 0;
}

for (let player of players) {
if (player.score_details[problem.problem.id]) {
problem.statistics.attempt++;
if ((contest.type === 'ACM' && player.score_details[problem.problem.id].accepted) || ((contest.type === 'NOI' || contest.type === 'IOI') && player.score_details[problem.problem.id].score === 100)) {
problem.statistics.accepted++;
}

if ((contest.type === 'NOI' || contest.type === 'IOI') && player.score_details[problem.problem.id].score > 0) {
problem.statistics.partially++;
}
}
}
}
}

res.render('contest_problem', {
contest: contest,
problems: problems,
hasStatistics: hasStatistics,
isSupervisior: isSupervisior
});
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

app.get('/contest/:id/ranklist', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
let contest_id = parseInt(req.params.id);
let contest = await Contest.findById(contest_id);
const curUser = res.locals.user;

if (!contest) throw new ErrorMessage('无此比赛。');
if (!contest.is_public && (!res.locals.user || !res.locals.user.is_admin)) throw new ErrorMessage('比赛未公开,请耐心等待 (´∀ `)');
if ([contest.allowedSeeingResult() && contest.allowedSeeingOthers(),
contest.isEnded(),
await contest.isSupervisior(curUser)].every(x => !x))
throw new ErrorMessage('您没有权限进行此操作。');

const isSupervisior = await contest.isSupervisior(curUser);
contest.ended = contest.isEnded();

await contest.loadRelationships();

let players_id = [];
for (let i = 1; i <= contest.ranklist.ranklist.player_num; i++) players_id.push(contest.ranklist.ranklist[i]);

let ranklist = await players_id.mapAsync(async player_id => {
let player = await ContestPlayer.findById(player_id);

if (contest.type === 'NOI' || contest.type === 'IOI') {
player.score = 0;
}

for (let i in player.score_details) {
player.score_details[i].judge_state = await JudgeState.findById(player.score_details[i].judge_id);

/*** XXX: Clumsy duplication, see ContestRanklist::updatePlayer() ***/
if (contest.type === 'NOI' || contest.type === 'IOI') {
let multiplier = (contest.ranklist.ranking_params || {})[i] || 1.0;
player.score_details[i].weighted_score = player.score_details[i].score == null ? null : Math.round(player.score_details[i].score * multiplier);
player.score += player.score_details[i].weighted_score;
}
}

let user = await User.findById(player.user_id);

return {
user: user,
player: player
};
});

let problems_id = await contest.getProblems();
let problems = await problems_id.mapAsync(async id => await Problem.findById(id));

res.render('contest_ranklist', {
contest: contest,
ranklist: ranklist,
problems: problems,
isSupervisior: isSupervisior
});
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

function getDisplayConfig(contest) {
return {
showScore: contest.allowedSeeingScore(),
showUsage: false,
showCode: false,
showResult: contest.allowedSeeingResult(),
showOthers: contest.allowedSeeingOthers(),
showDetailResult: contest.allowedSeeingTestcase(),
showTestdata: false,
inContest: true,
showRejudge: false
};
}

app.get('/contest/:id/submissions', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
let contest_id = parseInt(req.params.id);
let contest = await Contest.findById(contest_id);
if (!contest.is_public && (!res.locals.user || !res.locals.user.is_admin)) throw new ErrorMessage('比赛未公开,请耐心等待 (´∀ `)');

const displayConfig = getDisplayConfig(contest);
let problems_id = await contest.getProblems();
const curUser = res.locals.user;
const isSupervisior = await contest.isSupervisior(curUser);

if (contest.isEnded() || (curUser && await contest.isSupervisior(curUser))) {
res.redirect(syzoj.utils.makeUrl(['submissions'], { contest: contest_id }));
return;
}

let user = req.query.submitter && await User.fromName(req.query.submitter);

let query = JudgeState.createQueryBuilder();

let isFiltered = false;
if (displayConfig.showOthers) {
if (user) {
query.andWhere('user_id = :user_id', { user_id: user.id });
isFiltered = true;
}
} else {
if (curUser == null || // Not logined
(user && user.id !== curUser.id)) { // Not querying himself
throw new ErrorMessage("您没有权限执行此操作。");
}
query.andWhere('user_id = :user_id', { user_id: curUser.id });
isFiltered = true;
}

if (displayConfig.showScore) {
let minScore = parseInt(req.body.min_score);
if (!isNaN(minScore)) query.andWhere('score >= :minScore', { minScore });
let maxScore = parseInt(req.body.max_score);
if (!isNaN(maxScore)) query.andWhere('score <= :maxScore', { maxScore });

if (!isNaN(minScore) || !isNaN(maxScore)) isFiltered = true;
}

if (req.query.language) {
if (req.body.language === 'submit-answer') {
query.andWhere(new TypeORM.Brackets(qb => {
qb.orWhere('language = :language', { language: '' })
.orWhere('language IS NULL');
}));
} else if (req.body.language === 'non-submit-answer') {
query.andWhere('language != :language', { language: '' })
.andWhere('language IS NOT NULL');
} else {
query.andWhere('language = :language', { language: req.body.language })
}
isFiltered = true;
}

if (displayConfig.showResult) {
if (req.query.status) {
query.andWhere('status = :status', { status: req.query.status });
isFiltered = true;
}
}

if (req.query.problem_id) {
problem_id = problems_id[parseInt(req.query.problem_id) - 1] || 0;
query.andWhere('problem_id = :problem_id', { problem_id })
isFiltered = true;
}

query.andWhere('type = 1')
.andWhere('type_info = :contest_id', { contest_id });

let judge_state, paginate;

if (syzoj.config.submissions_page_fast_pagination) {
const queryResult = await JudgeState.queryPageFast(query, syzoj.utils.paginateFast(
req.query.currPageTop, req.query.currPageBottom, syzoj.config.page.judge_state
), -1, parseInt(req.query.page));

judge_state = queryResult.data;
paginate = queryResult.meta;
} else {
paginate = syzoj.utils.paginate(
await JudgeState.countQuery(query),
req.query.page,
syzoj.config.page.judge_state
);
judge_state = await JudgeState.queryPage(paginate, query, { id: "DESC" }, true);
}

await judge_state.forEachAsync(async obj => {
await obj.loadRelationships();
obj.problem_id = problems_id.indexOf(obj.problem_id) + 1;
obj.problem.title = syzoj.utils.removeTitleTag(obj.problem.title);
});

const pushType = displayConfig.showResult ? 'rough' : 'compile';
res.render('submissions', {
contest: contest,
isSupervisior: isSupervisior,
items: judge_state.map(x => ({
info: getSubmissionInfo(x, displayConfig),
token: (getRoughResult(x, displayConfig) == null && x.task_id != null) ? jwt.sign({
taskId: x.task_id,
type: pushType,
displayConfig: displayConfig
}, syzoj.config.session_secret) : null,
result: getRoughResult(x, displayConfig),
running: false,
})),
paginate: paginate,
form: req.query,
displayConfig: displayConfig,
pushType: pushType,
isFiltered: isFiltered,
fast_pagination: syzoj.config.submissions_page_fast_pagination
});
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});


app.get('/contest/submission/:id', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
const id = parseInt(req.params.id);
const judge = await JudgeState.findById(id);
if (!judge) throw new ErrorMessage("提交记录 ID 不正确。");
const curUser = res.locals.user;
if ((!curUser) || judge.user_id !== curUser.id) throw new ErrorMessage("您没有权限执行此操作。");

if (judge.type !== 1) {
return res.redirect(syzoj.utils.makeUrl(['submission', id]));
}

const contest = await Contest.findById(judge.type_info);
contest.ended = contest.isEnded();

const displayConfig = getDisplayConfig(contest);
displayConfig.showCode = true;

await judge.loadRelationships();
const problems_id = await contest.getProblems();
judge.problem_id = problems_id.indexOf(judge.problem_id) + 1;
judge.problem.title = syzoj.utils.removeTitleTag(judge.problem.title);

if (judge.problem.type !== 'submit-answer') {
judge.codeLength = Buffer.from(judge.code).length;
judge.code = await syzoj.utils.highlight(judge.code, syzoj.languages[judge.language].highlight);
}

res.render('submission', {
info: getSubmissionInfo(judge, displayConfig),
roughResult: getRoughResult(judge, displayConfig),
code: (displayConfig.showCode && judge.problem.type !== 'submit-answer') ? judge.code.toString("utf8") : '',
formattedCode: judge.formattedCode ? judge.formattedCode.toString("utf8") : null,
preferFormattedCode: res.locals.user ? res.locals.user.prefer_formatted_code : false,
detailResult: processOverallResult(judge.result, displayConfig),
socketToken: (displayConfig.showDetailResult && judge.pending && judge.task_id != null) ? jwt.sign({
taskId: judge.task_id,
displayConfig: displayConfig,
type: 'detail'
}, syzoj.config.session_secret) : null,
displayConfig: displayConfig,
contest: contest,
});
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

app.get('/contest/:id/problem/:pid', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
let contest_id = parseInt(req.params.id);
let contest = await Contest.findById(contest_id);
if (!contest) throw new ErrorMessage('无此比赛。');
const curUser = res.locals.user;

let problems_id = await contest.getProblems();

let pid = parseInt(req.params.pid);
if (!pid || pid < 1 || pid > problems_id.length) throw new ErrorMessage('无此题目。');

let problem_id = problems_id[pid - 1];
let problem = await Problem.findById(problem_id);
await problem.loadRelationships();

contest.ended = contest.isEnded();
if (!await contest.isSupervisior(curUser) && !(contest.isRunning() || contest.isEnded())) {
if (await problem.isAllowedUseBy(res.locals.user)) {
return res.redirect(syzoj.utils.makeUrl(['problem', problem_id]));
}
throw new ErrorMessage('比赛尚未开始。');
}

problem.specialJudge = await problem.hasSpecialJudge();

await syzoj.utils.markdown(problem, ['description', 'input_format', 'output_format', 'example', 'limit_and_hint']);

let state = await problem.getJudgeState(res.locals.user, false);
let testcases = await syzoj.utils.parseTestdata(problem.getTestdataPath(), problem.type === 'submit-answer');

await problem.loadRelationships();

res.render('problem', {
pid: pid,
contest: contest,
problem: problem,
state: state,
lastLanguage: res.locals.user ? await res.locals.user.getLastSubmitLanguage() : null,
testcases: testcases
});
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

app.get('/contest/:id/:pid/download/additional_file', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
let id = parseInt(req.params.id);
let contest = await Contest.findById(id);
if (!contest) throw new ErrorMessage('无此比赛。');

let problems_id = await contest.getProblems();

let pid = parseInt(req.params.pid);
if (!pid || pid < 1 || pid > problems_id.length) throw new ErrorMessage('无此题目。');

let problem_id = problems_id[pid - 1];
let problem = await Problem.findById(problem_id);

contest.ended = contest.isEnded();
if (!(contest.isRunning() || contest.isEnded())) {
if (await problem.isAllowedUseBy(res.locals.user)) {
return res.redirect(syzoj.utils.makeUrl(['problem', problem_id, 'download', 'additional_file']));
}
throw new ErrorMessage('比赛尚未开始。');
}

await problem.loadRelationships();

if (!problem.additional_file) throw new ErrorMessage('无附加文件。');

res.download(problem.additional_file.getPath(), `additional_file_${id}_${pid}.zip`);
} catch (e) {
syzoj.log(e);
res.status(404);
res.render('error', {
err: e
});
}
});

views/contests.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<% this.title = '比赛' %>
<% include header %>
<div class="padding">
<% if (contests.length) { %>
<% if (user && user.is_admin) { %>
<form class="ui mini form">
<div class="inline fields" style="margin-bottom: 25px; white-space: nowrap; ">
<a href="<%= syzoj.utils.makeUrl(['contest', 0, 'edit']) %>" class="ui mini labeled icon right floated button" style="margin-left: auto; ">
<i class="ui icon write"></i>
添加比赛
</a>
</div>
</form>
<% } %>
<table class="ui very basic center aligned table">
<thead>
<tr>
<th><span style="float:left; margin-left: 20px;">比赛名称</span></th>
<th style="width: 170px;">开始时间</th>
<th style="width: 170px;">结束时间</th>
<th>描述</th>
<th style="width: 75px;">赛制</th>
</tr>
</thead>
<tbody>
<%
for (let contest of contests) {
let now = syzoj.utils.getCurrentDate();
let tag = '';
%>
<tr>
<% if (now < contest.start_time) { %>
<% tag = '<span class="ui header"><div class="ui mini red label">未开始</div></span>' %>
<% } else if (now >= contest.start_time && now < contest.end_time) { %>
<% tag = '<span class="ui header"><div class="ui mini green label">进行中</div></span>' %>
<% } else { %>
<% tag = '<span class="ui header"><div class="ui mini grey label">已结束</div></span>' %>
<% } %>
<% if (!contest.is_public) { %>
<% tag += '<span class="ui header"><div class="ui tiny red label">未公开</div></span>' %>
<% } %>
<td><a style="float:left; margin-left: 20px;" href="<%= syzoj.utils.makeUrl(['contest', contest.id]) %>"><%= contest.title %> <%- tag %></a></td>
<td><%= syzoj.utils.formatDate(contest.start_time) %></td>
<td><%= syzoj.utils.formatDate(contest.end_time) %></td>
<td class="font-content"><%- contest.subtitle %></td>
<td><%= contest.type %></td>
</tr>
<% } %>
</tbody>
</table>
<% } else { %>
<div class="ui placeholder segment">
<div class="ui icon header">
<i class="calendar icon" style="margin-bottom: 20px; "></i>
暂无比赛
</div>
<% if (user && user.is_admin) { %>
<a href="<%= syzoj.utils.makeUrl(['contest', 0, 'edit']) %>" class="ui primary labeled icon button">
<i class="ui icon write"></i>
添加第一场比赛
</a>
<% } %>
</div>
<% } %>
<br>
<% include page %>
</div>
<% include footer %>

views/contest_edit.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<% this.title = contest.id ? '编辑比赛' : '新建比赛' %>
<% include header %>
<div class="padding">
<form action="<%= syzoj.utils.makeUrl(['contest', contest.id, 'edit']) %>" method="post">
<div class="ui form">
<div class="field">
<label>比赛名称</label>
<input type="text" name="title" value="<%= contest.title %>">
</div>
<div class="field">
<label>比赛描述</label>
<input type="text" name="subtitle" class="markdown-edit" value="<%= contest.subtitle %>">
</div>
<div class="field">
<label>试题列表</label>
<select class="ui fluid search dropdown" multiple="" id="search_problems" name="problems">
<% for (let problem of problems) { %>
<option value="<%= problem.id %>" selected>#<%= problem.id %>. <%= problem.title %></option>
<% } %>
</select>
</div>
<div class="field">
<label>比赛管理员</label>
<select class="ui fluid search dropdown" multiple="" id="search_admins" name="admins">
<% for (let admin of admins) { %>
<option value="<%= admin.id %>" selected><span class="user-name user-<%= syzoj.utils.makeUserColor(admin.rating, admin.is_admin) %>"><%= admin.username %></span><span class="user-gray"><span class="user-nameplate"><%= admin.nameplate %></span></span></option>
<% } %>
</select>
</div>
<div class="inline fields">
<label>赛制</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="type" id="type-NOI" value="NOI"<% if (contest.type === 'NOI') { %> checked="checked"<% } %>>
<label for="type-NOI">NOI</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="type" id="type-IOI" value="IOI"<% if (contest.type === 'IOI') { %> checked="checked"<% } %>>
<label for="type-IOI">IOI</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="type" id="type-ACM" value="ACM"<% if (contest.type === 'ACM') { %> checked="checked"<% } %>>
<label for="type-ACM">ICPC</label>
</div>
</div>
</div>
<div class="field">
<label>排行参数(格式:<code>{ "题目 ID": 分值倍数 }</code></label>
<input type="text" name="ranking_params" value="<%= contest.ranklist ? JSON.stringify(contest.ranklist.ranking_params) : '' %>">
</div>
<div class="field">
<label>比赛公告</label>
<textarea rows="5" name="information" class="markdown-edit"><%= contest.information %></textarea>
</div>
<div class="field">
<label>开始时间</label>
<input type="text" name="start_time" value="<%= syzoj.utils.formatDate(contest.start_time || syzoj.utils.getCurrentDate()) %>">
</div>
<div class="field">
<label>结束时间</label>
<input type="text" name="end_time" value="<%= syzoj.utils.formatDate(contest.end_time || syzoj.utils.getCurrentDate()) %>">
</div>
<div class="inline field">
<label class="ui header">公开</label>
<div class="ui toggle checkbox">
<input type="checkbox"<% if (contest.is_public) { %> checked<% } %> name="is_public">
<label><span style="visibility: hidden; "> </span></label>
</div>
</div>
<div class="inline field">
<label class="ui header">隐藏统计信息</label>
<div class="ui toggle checkbox">
<input type="checkbox"<% if (contest.hide_statistics) { %> checked<% } %> name="hide_statistics">
<label><span style="visibility: hidden; "> </span></label>
</div>
</div>
<div style="text-align: center; "><button id="submit_button" type="submit" class="ui labeled icon blue button"><i class="ui edit icon"></i>提交</button></div>
</div>
</form>
<script>
$(function () {
$('#search_admins')
.dropdown({
debug: true,
apiSettings: {
url: '/api/v2/search/users/{query}',
onResponse: function (response) {
var a = $('#search_admins').val().map(function (x) { return parseInt(x) });
if (response.results) {
response.results = response.results.filter(function(x){ return !a.includes(parseInt(x.value))});
}
return response;
},
cache: false
}
});
$('#search_problems')
.dropdown({
debug: true,
apiSettings: {
url: '/api/v2/search/problems/{query}',
onResponse: function (response) {
var a = $('#search_problems').val().map(function (x) { return parseInt(x) });
if (response.results) {
response.results = response.results.filter(function(x) {return !a.includes(parseInt(x.value));});
}
return response;
},
cache: false
}
});
});
</script>
<% include footer %>

views/contest_header.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<style>
.ui.label.pointing.below.left::before { left: 12%; }
.ui.label.pointing.below.right::before { left: 88%; }
.ui.label.pointing.below.left { margin-bottom: 0; }
.ui.label.pointing.below.right { margin-bottom: 0; float: right; }
#back_to_contest { display: none; }
</style>
<div class="padding">
<h1><%= contest.title %></h1>
<div style="margin-bottom: 30px;"><%- contest.subtitle %></div>
<% let unveiled = (isSupervisior || syzoj.utils.getCurrentDate() >= contest.start_time); %>
<% const seeResult = (isSupervisior || contest.ended); %>
<% const seeRanklist = seeResult || (contest.allowedSeeingResult() && contest.allowedSeeingOthers()); %>
<% let start = syzoj.utils.formatDate(contest.start_time), end = syzoj.utils.formatDate(contest.end_time); %>
<% if (contest.running && start.split(' ')[0] === end.split(' ')[0]) {
start = start.split(' ')[1]; end = end.split(' ')[1];
} %>
<div class="ui pointing below left label"><%= start %></div>
<div class="ui pointing below right label"><%= end %></div>
<% let timePercentage = Math.floor(Math.min(1, (syzoj.utils.getCurrentDate() - contest.start_time) / (contest.end_time - contest.start_time)) * 100); %>
<div id="timer-progress" class="ui tiny indicating progress<% if (timePercentage == 100) { %> success<% } %>" data-percent="<%= timePercentage %>">
<div class="bar" style="width: <%= timePercentage %>%;"></div>
</div>
<div class="ui grid" style="display: block;">
<div class="row">
<div class="column">
<div class="ui buttons">
<a class="ui small orange button" href="<%= syzoj.utils.makeUrl(['contest', contest.id]) %>">信息</a>
<% if (unveiled) { %><a class="ui small yellow button" href="<%= syzoj.utils.makeUrl(['contest', contest.id, 'problem']) %>">题目</a><% } %>
<% if(seeRanklist) { %>
<a class="ui small blue button" href="<%= syzoj.utils.makeUrl(['contest', contest.id, 'ranklist']) %>">排行榜</a>
<% } %>
<% let submissionsUrl = seeResult ?
syzoj.utils.makeUrl(['submissions'], {contest: contest.id}) :
syzoj.utils.makeUrl(['contest', contest.id, 'submissions']); %>
<a class="ui small positive button" href="<%= syzoj.utils.makeUrl(['contest', contest.id, 'submissions']) %>">提交记录</a>
<% if (isSupervisior) { %>
<a class="ui small button" href="<%= syzoj.utils.makeUrl(['contest', contest.id, 'edit']) %>">编辑比赛</a>
<% } %>
</div>
</div>
</div>

views/contest_footer.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
</div>
</div>

<script>
$(function () {
setInterval(function () {
$('#timer-progress').progress({
value: Date.now() / 1000 - <%= contest.start_time %>,
total: <%= contest.end_time - contest.start_time %>
});
}, 5000);
});
</script>

views/contest.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<% this.title = contest.title + ' - 比赛' %>
<% include header %>
<% include contest_header %>
<div class="row">
<div class="column">
<h4 class="ui top attached block header">信息与公告</h4>
<div class="ui bottom attached segment font-contest">
<%- contest.information %>
</div>
</div>
</div>
<% include contest_footer %>
<% include footer %>

views/contest_problem.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<% this.title = contest.title + ' - 题目' %>
<% include header %>
<% include contest_header %>
<div class="row">
<div class="column">
<table class="ui selectable celled table">
<thead>
<tr>
<th class="one wide" style="text-align: center">状态</th>
<th>题目</th>
<% if (hasStatistics) { %>
<th class="one wide center aligned">统计</th>
<% } %>
</tr>
</thead>
<tbody>
<%
let i = 0;
for (let problem of problems) {
i++;
%>
<tr>
<td class="center aligned" style="white-space: nowrap; ">
<% if (problem.judge_id) { %>
<a href="<%= syzoj.utils.makeUrl(['contest', 'submission', problem.judge_id]) %>">
<% if (typeof problem.status === 'string') { %>
<span class="status <%= problem.status.toLowerCase().split(' ').join('_') %>">
<b>
<i class="<%= icon[getStatusMeta(problem.status)] || 'remove' %> icon"></i>
<%= problem.feedback || problem.status %>
</b>
</span>
<% } else if (typeof problem.status === 'object') { %>
<% if (problem.status.accepted) { %>
<span class="score score_10">
<% if (problem.status.unacceptedCount === 0) { %>
+
<% } else { %>
+<%= problem.status.unacceptedCount %>
<% } %>
</span>
<% } else { %>
<span class="score score_0">
<% if (problem.status.unacceptedCount !== 0) { %>
-<%= problem.status.unacceptedCount %>
<% } %>
</span>
<% } %>
<% } %>
<% } %>
</td>
<td><a href="<%= syzoj.utils.makeUrl(['contest', contest.id, 'problem', i]) %>"><%= syzoj.utils.removeTitleTag(problem.problem.title) %></a></td>
<% if (hasStatistics) { %>
<td class="center aligned" style="white-space: nowrap; ">
<a href="<%= syzoj.utils.makeUrl(['contest', contest.id, 'submissions'], { problem_id: i, status: 'Accepted' }) %>"><%= problem.statistics.accepted %></a>
/
<a href="<%= syzoj.utils.makeUrl(['contest', contest.id, 'submissions'], { problem_id: i, min_score: 1 }) %>"><%= problem.statistics.partially %></a>
<% if (contest.type === 'NOI' || contest.type === 'IOI') { %>
/
<% } %>
<a href="<%= syzoj.utils.makeUrl(['contest', contest.id, 'submissions'], { problem_id: i }) %>"><%= problem.statistics.attempt %></a>
</td>
<% } %>
</tr>
<% } %>
</tbody>
</table>
</div>
</div>
<% include contest_footer %>
<% include footer %>

views/contest_ranklist.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
<% this.title = contest.title + ' - 排名' %>
<% include header %>
<% include contest_header %>
<style>
.submit_time {
font-size: 0.8em;
margin-top: 5px;
color: #000;
}
</style>
<table class="ui very basic center aligned table">
<thead>
<tr>
<th>#</th>
<th>用户名</th>
<% if (contest.type === 'ACM') { %>
<th>通过数量</th>
<th>罚时</th>
<% } %>
<% for (let i = 0; i < problems.length; i++) { %>
<th>
<a href="<%= syzoj.utils.makeUrl(['contest', contest.id, 'problem', i + 1]) %>">
<%= syzoj.utils.removeTitleTag(problems[i].title) %>
</a>
</th>
<% } %>
<% if (contest.type === 'NOI' || contest.type === 'IOI') { %>
<th>总分</th>
<% } %>
</tr>
</thead>
<tbody>
<%
for (let problem of problems) {
let i = 0, min, minPos = -1;
for (let item of ranklist) {
i++;
let condition;
if (contest.type === 'ACM') condition = item.player.score_details[problem.id] && item.player.score_details[problem.id].accepted && (minPos === -1 || item.player.score_details[problem.id].acceptedTime < min.player.score_details[problem.id].acceptedTime);
else condition = item.player.score_details[problem.id] && item.player.score_details[problem.id].score === 100 && (minPos === -1 || item.player.score_details[problem.id].judge_state.submit_time < min.player.score_details[problem.id].judge_state.submit_time);
if (condition) {
min = item;
minPos = i;
}
}
problem.min = minPos;
}

let i = 0, rank = 0, lastItem;
for (let item of ranklist) {
i++;
let latest = contest.start_time, timeSum = 0, unacceptedCount = 0;
%>
<tr>
<%
if (contest.type === 'NOI' || contest.type === 'IOI') {
if (i === 1 || item.player.score !== lastItem.player.score) rank = i;
} else if (contest.type === 'ACM') {
for (let problem of problems) {
if (item.player.score_details[problem.id] && item.player.score_details[problem.id].accepted) {
timeSum += (item.player.score_details[problem.id].acceptedTime - contest.start_time) + (item.player.score_details[problem.id].unacceptedCount * 20 * 60);
unacceptedCount += item.player.score_details[problem.id].unacceptedCount;
}
}
item.player.timeSum = timeSum;

if (i === 1 || item.player.score !== lastItem.player.score || item.player.timeSum !== lastItem.player.timeSum) rank = i;
}
%>
<td>
<% if (rank == 1) { %>
<div class="ui yellow ribbon label">
<% } else if (rank == 2) { %>
<div class="ui ribbon label">
<% } else if (rank == 3) { %>
<div class="ui brown ribbon label" style="background-color: #C47222 !important;">
<% } else { %>
<div>
<% } %>
<%= rank %>
</div>
</td>
<td><a href="<%= syzoj.utils.makeUrl(['user', item.user.id]) %>"><span class="user-name user-<%= syzoj.utils.makeUserColor(item.user.rating, item.user.is_admin) %>"><%= item.user.username %></span></a><% if (item.user.nickname) { %><span class="user-tag bg-<%= syzoj.utils.makeUserColor(item.user.rating, item.user.is_admin) %>"><%- item.user.nickname %></span><% } %><span class="user-gray"><span class="user-nameplate"><%= item.user.nameplate %></span></span></td>
<% if (contest.type === 'ACM') { %>
<td>
<span class="score score_<%= parseInt((item.player.score / ranklist[0].player.score * 10) || 0) %>">
<%= item.player.score %>
</span>
</td>
<td>
<%= syzoj.utils.formatTime(timeSum) %>
</td>
<% } %>
<% for (let problem of problems) { %>
<% if (problem.min === i) { %>
<td style="background: rgb(244, 255, 245); ">
<% } else { %>
<td>
<% } %>
<% if (!item.player.score_details[problem.id]) { %>
</td>
<% } else if (contest.type === 'ACM') { %>
<a href="<%= syzoj.utils.makeUrl(['submission', item.player.score_details[problem.id].judge_id]) %>">
<% if (item.player.score_details[problem.id].accepted) { %>
<span class="score score_10">
<% if (item.player.score_details[problem.id].unacceptedCount) { %>
+<%= item.player.score_details[problem.id].unacceptedCount %>
<% } else { %>
+
<% } %>
</span>

<div class="submit_time">
<%= syzoj.utils.formatTime(item.player.score_details[problem.id].acceptedTime - contest.start_time) %>
</div>
<% } else if (item.player.score_details[problem.id].unacceptedCount) { %>
<span class="score score_0">
-<%= item.player.score_details[problem.id].unacceptedCount %>
</span>
<% } %>
</a>
</td>
<% } else if (contest.type === 'NOI' || contest.type === 'IOI') { %>
<a href="<%= syzoj.utils.makeUrl(['submission', item.player.score_details[problem.id].judge_id]) %>">
<% if (item.player.score_details[problem.id].weighted_score != null) { %>
<span class="score score_<%= parseInt((item.player.score_details[problem.id].score / 10) || 0) %>">
<%= Math.round(item.player.score_details[problem.id].weighted_score) %>
</span>
<% } else { %>
<span class="status compile_error">
0
</span>
<% } %>
</a>
<div class="submit_time">
<%= syzoj.utils.formatTime(item.player.score_details[problem.id].judge_state.submit_time - contest.start_time) %>
<% latest = Math.max(latest, item.player.score_details[problem.id].judge_state.submit_time) %>
</div>
</td>
<% } %>
<% } %>
<% if (contest.type === 'NOI' || contest.type === 'IOI') { %>
<td>
<span class="score score_<%= parseInt((item.player.score / ranklist[0].player.score * 10) || 0) %>">
<%= item.player.score %>
</span>
<div class="submit_time">
<%= syzoj.utils.formatTime(latest - contest.start_time) %>
</div>
</td>
<% } %>
</tr>
<% lastItem = item; %>
<% } %>
</tbody>
</table>
<% if (!ranklist.length) { %>
<div style="background-color: #fff; height: 18px; margin-top: -18px; "></div>
<div class="ui placeholder segment" style="margin-top: 0px; ">
<div class="ui icon header">
<i class="ui file icon" style="margin-bottom: 20px; "></i>
暂无选手提交
</div>
</div>
<% } %>
<% include contest_footer %>
<% include footer %>

作业功能

教练要求可以布置作业,但是 SYZOJ 并没有这个功能,所以需要自己写一个。

因为和比赛很像,所以前后端都可以从比赛功能抄一些代码。

首先定义一个用于存数据的表,新建 models/homework.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import * as TypeORM from "typeorm";
import Model from "./common";

declare var syzoj, ErrorMessage: any;

import User from "./user";
import Problem from "./problem";

@TypeORM.Entity()
export default class Homework extends Model {
static cache = true;

@TypeORM.PrimaryGeneratedColumn()
id: number;

@TypeORM.Column({ nullable: true, type: "varchar", length: 80 })
title: string;

@TypeORM.Column({ nullable: true, type: "text" })
subtitle: string;

@TypeORM.Column({ nullable: true, type: "text" })
information: string;

@TypeORM.Column({ nullable: true, type: "text" })
problems: string;

@TypeORM.Column({ nullable: true, type: "text" })
users: string;

@TypeORM.Column({ nullable: true, type: "boolean" })
is_public: boolean;

async getUsers() {
if (!this.users) return [];
return this.users.split('|').map(x => parseInt(x));
}

async getProblems() {
if (!this.problems) return [];
return this.problems.split('|').map(x => parseInt(x));
}

async setProblemsNoCheck(problemIDs) {
this.problems = problemIDs.join('|');
}

async setProblems(s) {
let a = [];
await s.split('|').forEachAsync(async x => {
let problem = await Problem.findById(x);
if (!problem) return;
a.push(x);
});
this.problems = a.join('|');
}
}

然后修改后端代码,新建 modules/homework.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
let Homework = syzoj.model('homework');
let Problem = syzoj.model('problem');
let User = syzoj.model('user');

app.get ('/homeworks', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
let where;
if (res.locals.user && res.locals.user.is_admin) where = {}
else where = { is_public: true };

let paginate = syzoj.utils.paginate(await Homework.countForPagination(where), req.query.page, syzoj.config.page.contest);
let homeworks = await Homework.queryPage (paginate, where);

await homeworks.forEachAsync(async x => x.subtitle = await syzoj.utils.markdown(x.subtitle));

res.render('homeworks', {
homeworks: homeworks,
paginate: paginate
})
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
})

app.get('/homework/:id/edit', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
if (!res.locals.user || !res.locals.user.is_admin) throw new ErrorMessage('您没有权限进行此操作。');

let homework_id = parseInt(req.params.id);
let homework = await Homework.findById(homework_id);
if (!homework) {
homework = await Homework.create();
homework.id = 0;
}

let problems = [], users_id = [];
if (homework.problems) problems = await homework.problems.split('|').mapAsync(async id => await Problem.findById(id));
if (homework.users) users_id = await homework.users.split('|');

let items = [];
let user_count = await User.count ();
for (let user_id = 1; user_id <= user_count; ++user_id) {
items.push ([await User.findById (user_id), users_id.includes (user_id.toString ())]);
}

res.render('homework_edit', {
homework: homework,
problems: problems,
items: items
});
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

app.post('/homework/:id/edit', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
if (!res.locals.user || !res.locals.user.is_admin) throw new ErrorMessage('您没有权限进行此操作。');

let homework_id = parseInt(req.params.id);
let homework = await Homework.findById(homework_id);
if (!homework) {
homework = await Homework.create();
}

if (!req.body.title.trim()) throw new ErrorMessage('作业名不能为空。');
homework.title = req.body.title;
homework.subtitle = req.body.subtitle;
if (!Array.isArray(req.body.problems)) req.body.problems = [req.body.problems];
if (!Array.isArray(req.body.items)) req.body.items = [req.body.items];
homework.problems = req.body.problems.join('|');
homework.information = req.body.information;
homework.is_public = req.body.is_public === 'on';
homework.users = '';
for (let user of req.body.items) {
homework.users += user + '|';
}
homework.users = homework.users.substr (0, homework.users.length - 1);

await homework.save();

res.redirect(syzoj.utils.makeUrl(['homework', homework.id]));
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

app.get('/homework/:id', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
const curUser = res.locals.user;
let homework_id = parseInt(req.params.id);

let homework = await Homework.findById(homework_id);
if (!homework) throw new ErrorMessage('无此作业。');
if (!homework.is_public && (!res.locals.user || !res.locals.user.is_admin)) throw new ErrorMessage('您无权查看此作业。');

const isSupervisior = res.locals.user.is_admin;
homework.subtitle = await syzoj.utils.markdown(homework.subtitle);
homework.information = await syzoj.utils.markdown(homework.information);

res.render('homework', {
homework: homework,
isSupervisior: isSupervisior
});
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

app.get('/homework/:id/problem', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
const curUser = res.locals.user;
let homework_id = parseInt(req.params.id);

let homework = await Homework.findById(homework_id);
if (!homework) throw new ErrorMessage('无此作业。');
if (!homework.is_public && (!curUser || !curUser.is_admin)) throw new ErrorMessage('您无权查看此作业。');

const isSupervisior = curUser.is_admin;
homework.subtitle = await syzoj.utils.markdown(homework.subtitle);

let problems_id = await homework.getProblems();
let problems = await problems_id.mapAsync(async id => await Problem.findById(id));

let state = [];
let users_id = await homework.users.split ('|');
if (users_id.includes (curUser.id.toString ())) {
for (let problem of problems) {
state.push (await curUser.getProblemScore (problem.id));
}
}

res.render('homework_problem', {
homework: homework,
problems: problems,
state: state,
isSupervisior: isSupervisior
});
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

app.get('/homework/:id/ranklist', async (req, res) => {
try {
if (!res.locals.user) throw new ErrorMessage('请登录后继续。', { '登录': syzoj.utils.makeUrl(['login'], { 'url': req.originalUrl }) });
let homework_id = parseInt(req.params.id);
let homework = await Homework.findById(homework_id);
const curUser = res.locals.user;

if (!homework) throw new ErrorMessage('无此作业。');
if (!homework.is_public && (!res.locals.user || !res.locals.user.is_admin)) throw new ErrorMessage('您无权查看此作业。');

const isSupervisior = res.locals.user.is_admin;

let problems_id = await homework.getProblems();
let problems = await problems_id.mapAsync(async id => await Problem.findById(id));

let users = await homework.getUsers ();
users = await users.mapAsync(async id => await User.findById(id));
let ranklist = [];

for (let user of users) {
let state = [user];
let sum = 0;
for (let problem of problems) {
let score = await user.getProblemScore (problem.id);
state.push (score);
sum += score;
}
state.push (sum);
ranklist.push (state);
}
ranklist.sort (function (a, b) {
if (a[a.length - 1] > b[b.length - 1]) {
return -1;
}
if (a[a.length - 1] == b[b.length - 1]) {
return 0;
}
return 1;
})

res.render('homework_ranklist', {
homework: homework,
problems: problems,
ranklist: ranklist,
isSupervisior: isSupervisior
});
} catch (e) {
syzoj.log(e);
res.render('error', {
err: e
});
}
});

前端部分虽然要写的代码很多,但与比赛页面几乎一样,除了完成情况需要重写,其他页面可以直接从比赛部分抄然后修改一下。

views/homeworks.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<% this.title = '作业' %>
<% include header %>
<div class="padding">
<% if (homeworks.length) { %>
<% if (user && user.is_admin) { %>
<form class="ui mini form">
<div class="inline fields" style="margin-bottom: 25px; white-space: nowrap; ">
<a href="<%= syzoj.utils.makeUrl(['homework', 0, 'edit']) %>" class="ui mini labeled icon right floated button" style="margin-left: auto; ">
<i class="ui icon write"></i>
新建作业
</a>
</div>
</form>
<% } %>
<table class="ui very basic center aligned table">
<thead>
<tr>
<th><span style="float:left; margin-left: 20px;">作业名称</span></th>
<th style="text-align: left; width: 70%;">描述</th>
</tr>
</thead>
<tbody>
<% for (let homework of homeworks) { %>
<tr>
<td><a style="float:left; margin-left: 20px;" href="<%= syzoj.utils.makeUrl(['homework', homework.id]) %>"><%= homework.title %> <% if (!homework.is_public) { %><span class="ui header"><div class="ui tiny red label">未布置</div></span><% } %></a></td>
<td class="font-content" style="text-align: left;"><%- homework.subtitle %></td>
</tr>
<% } %>
</tbody>
</table>
<% } else { %>
<div class="ui placeholder segment">
<div class="ui icon header">
<i class="calendar icon" style="margin-bottom: 20px; "></i>
暂无作业
</div>
<% if (user && user.is_admin) { %>
<a href="<%= syzoj.utils.makeUrl(['homework', 0, 'edit']) %>" class="ui primary labeled icon button">
<i class="ui icon write"></i>
布置第一份作业
</a>
<% } %>
</div>
<% } %>
<br>
<% include page %>
</div>
<% include footer %>

views/homework_edit.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<% this.title = homework.id ? '编辑作业' : '新建作业' %>
<% include header %>
<div class="padding">
<form action="<%= syzoj.utils.makeUrl(['homework', homework.id, 'edit']) %>" method="post">
<div class="ui form">
<div class="field">
<label>作业名称</label>
<input type="text" name="title" value="<%= homework.title %>">
</div>
<div class="field">
<label>作业描述</label>
<input type="text" name="subtitle" class="markdown-edit" value="<%= homework.subtitle %>">
</div>
<div class="field">
<label>题目列表</label>
<select class="ui fluid search dropdown" multiple="" id="search_problems" name="problems">
<% for (let problem of problems) { %>
<option value="<%= problem.id %>" selected>#<%= problem.id %>. <%= problem.title %></option>
<% } %>
</select>
</div>
<div class="inline fields">
<label>参与成员</label>
<% for (let item of items) { %>
<div class="field">
<div>
<input style="vertical-align: middle;" type="checkbox" name="items" value="<%= item[0].id %>" <% if (item[1]) { %> checked="checked"<% } %>>
<label for="condition_participate">
<span class="user-name user-<%= syzoj.utils.makeUserColor(item[0].rating, item[0].is_admin) %>"><%= item[0].username %></span><span class="user-gray"><span class="user-nameplate"><%= item[0].nameplate %></span></span>
</label>
</div>
</div>
<% } %>
</div>
<div class="field">
<label>作业公告</label>
<textarea rows="5" name="information" class="markdown-edit"><%= homework.information %></textarea>
</div>
<div class="inline field">
<label class="ui header">布置</label>
<div class="ui toggle checkbox">
<input type="checkbox"<% if (homework.is_public) { %> checked<% } %> name="is_public">
<label><span style="visibility: hidden; "> </span></label>
</div>
</div>
<div style="text-align: center; "><button id="submit_button" type="submit" class="ui labeled icon blue button"><i class="ui edit icon"></i>提交</button></div>
</div>
</form>
<script>
$(function () {
$('#search_problems')
.dropdown({
debug: true,
apiSettings: {
url: '/api/v2/search/problems/{query}',
onResponse: function (response) {
var a = $('#search_problems').val().map(function (x) { return parseInt(x) });
if (response.results) {
response.results = response.results.filter(function(x) {return !a.includes(parseInt(x.value));});
}
return response;
},
cache: false
}
});
});
</script>
<% include footer %>

views/homework_header.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<style>
.ui.label.pointing.below.left::before { left: 12%; }
.ui.label.pointing.below.right::before { left: 88%; }
.ui.label.pointing.below.left { margin-bottom: 0; }
.ui.label.pointing.below.right { margin-bottom: 0; float: right; }
#back_to_homework { display: none; }
</style>
<div class="padding">
<h1><%= homework.title %></h1>
<div style="margin-bottom: 30px;"><%- homework.subtitle %></div>
<div class="ui grid" style="display: block;">
<div class="row">
<div class="column">
<div class="ui buttons">
<a class="ui small orange button" href="<%= syzoj.utils.makeUrl(['homework', homework.id]) %>">信息</a>
<a class="ui small yellow button" href="<%= syzoj.utils.makeUrl(['homework', homework.id, 'problem']) %>">题目</a>
<a class="ui small blue button" href="<%= syzoj.utils.makeUrl(['homework', homework.id, 'ranklist']) %>">完成情况</a>
<% if (isSupervisior) { %>
<a class="ui small button" href="<%= syzoj.utils.makeUrl(['homework', homework.id, 'edit']) %>">编辑作业</a>
<% } %>
</div>
</div>
</div>

views/homework_footer.ejs:

1
2
</div>
</div>

views/homework.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
<% this.title = homework.title + ' - 作业' %>
<% include header %>
<% include homework_header %>
<div class="row">
<div class="column">
<h4 class="ui top attached block header">信息与公告</h4>
<div class="ui bottom attached segment font-content">
<%- homework.information %>
</div>
</div>
</div>
<% include homework_footer %>
<% include footer %>

views/homework_problem.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<% this.title = homework.title + ' - 题目' %>
<% include header %>
<% include homework_header %>
<div class="row">
<div class="column">
<table class="ui selectable celled table">
<thead>
<tr>
<% if (state.length) { %>
<th class="one wide" style="text-align: center">状态</th>
<% } %>
<th>题目</th>
</tr>
</thead>
<tbody>
<%
let i = 0;
for (let problem of problems) {
%>
<tr>
<% if (state.length) { %>
<td class="center aligned" style="white-space: nowrap; ">
<% if (state[i] != null) { %>
<b>
<% if (state[i] == 100) { %>
<i class="check icon score_10"></i>
<% } else { %>
<span class="score score_<%= parseInt (state[i] / 10) %>"><%= state[i] %></span>
<% } %>
</b>
<% } %>
</td>
<% } %>
<td><a href="<%= syzoj.utils.makeUrl(['problem', problem.id]) %>"><%= syzoj.utils.removeTitleTag(problem.title) %></a></td>
</tr>
<%
i++;
}
%>
</tbody>
</table>
</div>
</div>
<% include homework_footer %>
<% include footer %>

views/homework_ranklist.ejs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<% this.title = homework.title + ' - 完成情况' %>
<% include header %>
<% include homework_header %>
<style>
.submit_time {
font-size: 0.8em;
margin-top: 5px;
color: #000;
}
</style>
<table class="ui very basic center aligned table">
<thead>
<tr>
<th>用户名</th>
<% for (let problem of problems) { %>
<th>
<a href="<%= syzoj.utils.makeUrl(['problem', problem.id]) %>">
<%= syzoj.utils.removeTitleTag(problem.title) %>
</a>
</th>
<% } %>
</tr>
</thead>
<tbody>
<% for (let item of ranklist) { %>
<tr>
<td><a href="<%= syzoj.utils.makeUrl(['user', item[0].id]) %>"><span class="user-name user-<%= syzoj.utils.makeUserColor(item[0].rating, item[0].is_admin) %>"><%= item[0].username %></span></a><% if (item[0].nickname) { %><span class="user-tag bg-<%= syzoj.utils.makeUserColor(item[0].rating, item[0].is_admin) %>"><%- item[0].nickname %></span><% } %><span class="user-gray"><span class="user-nameplate"><%= item[0].nameplate %></span></span></td>
<%
let i = 1;
for (let problem of problems) {
%>
<td>
<% if (item[i] != null) { %>
<b>
<% if (item[i] == 100) { %>
<i class="check icon score_10"></i>
<% } else { %>
<span class="score score_<%= parseInt (item[i] / 10) %>"><%= item[i] %></span>
<% } %>
</b>
<% } %>
</td>
<%
++i;
}
%>
</tr>
<% } %>
</tbody>
</table>
<% include homework_footer %>
<% include footer %>

最后,需要顶栏中显示作业按钮,所以在 views/header.ejs 中加入以下代码:

1
<a class="item<% if (active.startsWith('homework')) { %> active<% } %>" href="/homeworks"><i class="book icon"></i> 作业</a>