- {% if not ddocs.length %}
- {{ nothing.render('no blog yet...') }}
+ {% if not handler.user.hasPerm(perm.PERM_DELETE_DISCUSSION) %}
+ {{ nothing.render('仅超级管理员可以创建博客!') }}
{% else %}
-
- {%- for ddoc in ddocs -%}
-
-
@@ -41,7 +45,7 @@
- {% if handler.user._id == udoc._id %}
+ {% if handler.user._id == udoc._id and handler.user.hasPerm(perm.PERM_DELETE_DISCUSSION) %}
{{ _('Create a Post') }}
{% endif %}
diff --git a/packages/common/permission.ts b/packages/common/permission.ts
index ed9b0ad1c1..7d18fd9185 100644
--- a/packages/common/permission.ts
+++ b/packages/common/permission.ts
@@ -86,6 +86,9 @@ export const PERM = {
// Ranking
PERM_VIEW_RANKING: 1n << 59n,
+ // Wiki
+ PERM_EDIT_WIKI: 1n << 71n,
+
// Placeholder
PERM_ALL: -1n,
PERM_BASIC: 0n,
diff --git a/packages/contest-album/README.md b/packages/contest-album/README.md
new file mode 100644
index 0000000000..29bc38a0be
--- /dev/null
+++ b/packages/contest-album/README.md
@@ -0,0 +1,41 @@
+# HGNUOJ 比赛相册
+
+独立的比赛照片展示和管理插件。浏览入口 `/albums`,沿用所在域的公告权限。
+
+## 使用
+
+- 按年份浏览、按比赛名称搜索;每页以 12 本为目标,按完整年份分页,同一年不会拆到两页。
+- 获奖信息可选金牌、银牌、铜牌或不显示。配置后,卡片右下角和详情标题右侧显示统一的五角星矢量图标与奖牌名称;未配置时隐藏,卡片不再显示右上箭头。
+- 有“创建公告”权限的用户可新建相册;作者需有“编辑自己的公告”权限,管理员使用“编辑公告”权限管理。
+- 先填写名称、年份、可选日期和 Markdown 简介,再批量添加照片。相册默认草稿,可勾选公开展示。
+- 支持 JPG、PNG、静态 WebP,单张 20 MiB、80 MP,每本最多 500 张,并受用户文件配额限制。
+- 可设置封面、拖动或用按钮排序、编辑照片说明、移出照片。上传立即保存,封面、排序、移出和文字信息点击“保存相册”后生效。
+- 浏览页使用 480 px 缩略图和懒加载;点开使用 1600 px 大图,支持左右方向键、手机滑动和原图入口。无脚本时照片链接仍能打开原图。
+- 大图弹窗最大宽度 1800 px、高度为屏幕的 94%,照片按比例适应可用空间;放大加号使用居中的矢量图形。
+- 详情页编辑按钮放在上方,与面包屑同行,和标题右侧奖牌信息右对齐。
+- CSS 在页面 head 中以内容版本链接加载,避免插件脚本延迟导致刷新或切换年份时排版丢失。
+
+## 安装与数据
+
+在已安装 `@hgnuoj/image-preview` 和 `@hydrooj/ui-default` 的 Hydro 工作区中安装依赖,将本插件加入 `addon.json` 后重启。
+
+相册存储在 MongoDB 的 `hgnu.album` 集合中,按域隔离;公开用户文件由 Hydro 原文件存储管理,预览复用图片优化插件。草稿限制相册页面可见性,上传文件采用 Hydro 公开用户文件机制。
+
+已有公告可通过一次性整理建立相册,照片复用原 `/file/...` 地址。插件不会自动改写公告或推断比赛日期。关联相册具有 `source.discussion`、`source.section`、`source.fragment`,公告详情会显示相册入口,相册中保留对应章节链接。
+
+移出照片、删除相册只修改相册信息,不删除可能被公告共用的原文件;上传的新照片可在用户文件管理中管理。删除相册为软删除。
+
+保存、上传和删除使用 revision 检查,过期操作会提示刷新;照片来源不能通过保存表单替换为任意 URL,表单域和相册编号不能覆盖当前访问地址。
+
+## 当前测试数据
+
+测试服务器已从公告 `669f290c911ca250f716994c` 整理 16 本相册、93 张照片。
+
+- 第 51 届 ICPC 武汉站:2026 年。
+- 第 50 届 ICPC 武汉站:2025 年。
+- 按要求不展示“奖牌队牌物料合影”。
+- 原公告的 17 个章节、94 张图片及其 Markdown 保留。
+
+验证:后端与前端 TypeScript、ESLint、`test/hgnu-contest-album.cjs`,以及服务器浏览器中的编辑、权限、上传、移动端和样式加载回归检查。
+
+部署时需单独启用本插件、图片预览和公告目录插件,并整理相册元数据。Git 仓库包含功能代码与测试,不包含数据库、图片文件和私密运行配置。
diff --git a/packages/contest-album/frontend/album.css b/packages/contest-album/frontend/album.css
new file mode 100644
index 0000000000..adc97579fb
--- /dev/null
+++ b/packages/contest-album/frontend/album.css
@@ -0,0 +1,53 @@
+.album-app { --album-bg:#fff; --album-ink:#183149; --album-muted:#708397; --album-line:#dfe7ef; --album-soft:#f3f7fb; --album-blue:#246897; color:var(--album-ink); }
+.theme--dark .album-app { --album-bg:#292e34; --album-ink:#e2eaf2; --album-muted:#a6b4c3; --album-line:#414c57; --album-soft:#222a32; --album-blue:#8dc9f3; }
+.album-hero { display:flex; justify-content:space-between; align-items:center; gap:32px; padding:36px 0 30px; border-bottom:1px solid var(--album-line); }
+.album-eyebrow { color:var(--album-blue); font-size:12px; font-weight:600; letter-spacing:1.5px; margin:0 0 12px; }
+.album-app h1 { font-size:34px; line-height:1.3; font-weight:600; margin:0; color:var(--album-ink); }
+.album-lead { color:var(--album-muted); margin:12px 0 0; font-size:15px; }
+.album-hero-side { display:flex; gap:30px; align-items:center; }
+.album-totals { display:flex; gap:28px; color:var(--album-muted); font-size:12px; }
+.album-totals span { display:block; white-space:nowrap; }.album-totals strong { display:block; font-size:27px; line-height:1.3; font-weight:500; color:var(--album-ink); margin-bottom:4px; }
+.album-button { display:inline-flex; align-items:center; justify-content:center; min-height:42px; box-sizing:border-box; padding:9px 17px; border:1px solid var(--album-line); border-radius:8px; color:var(--album-ink); background:var(--album-bg); font:inherit; font-size:13px; cursor:pointer; text-decoration:none; gap:7px; }
+.album-button:hover { border-color:var(--album-blue); color:var(--album-blue); text-decoration:none; }.album-button--primary { color:#fff; background:#246897; border-color:#246897; }.album-button--primary:hover { background:#1a547d; color:#fff; }
+.album-button:disabled { opacity:.55; cursor:wait; }.album-app a:focus-visible,.album-app button:focus-visible { outline:2px solid #58a4f0; outline-offset:3px; }
+.album-filters { display:flex; flex-wrap:wrap; justify-content:space-between; gap:18px; padding:24px 0 6px; align-items:center; }
+.album-search { display:flex; gap:8px; order:2; }.album-search input { width:220px; border:1px solid var(--album-line); border-radius:8px; padding:10px 12px; font-size:13px; background:var(--album-bg); color:var(--album-ink); }
+.album-years { display:flex; flex-wrap:wrap; gap:7px; }.album-years a { display:inline-flex; gap:6px; padding:8px 12px; border-radius:7px; color:var(--album-muted); font-size:13px; }.album-years a span { font-size:11px; opacity:.7; }.album-years a.is-active { background:#246897; color:white; }.album-years a:hover { text-decoration:none; background:var(--album-bg); color:var(--album-blue); }.album-years a.is-active:hover { background:#246897; color:white; }
+.album-results { margin:20px 0 0; color:var(--album-muted); font-size:13px; }
+.album-year-group { margin-top:30px; }.album-year-group>h2 { display:flex; align-items:baseline; gap:12px; font-size:25px; font-weight:500; margin:0 0 17px; }.album-year-group>h2 span { color:var(--album-muted); font-size:12px; font-weight:400; letter-spacing:2px; }
+.album-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:24px; }.album-card { min-width:0; border:1px solid var(--album-line); border-radius:13px; background:var(--album-bg); color:var(--album-ink); overflow:hidden; transition:box-shadow .18s,transform .18s; }.album-card:hover { text-decoration:none; color:var(--album-ink); transform:translateY(-3px); box-shadow:0 10px 24px #153a5514; }
+.album-card-cover { position:relative; aspect-ratio:4/3; overflow:hidden; background:#d8e2ec; }.album-card-cover>img { width:100%; height:100%; object-fit:cover; object-position:50% 40%; }.album-photo-badge,.album-draft-badge { position:absolute; right:12px; bottom:12px; padding:5px 9px; border-radius:5px; color:#fff; background:#102c47c9; font-size:11px; }.album-draft-badge { top:12px; bottom:auto; background:#a5681de6; }.album-empty-cover { display:flex; justify-content:center; align-items:center; height:100%; color:#58718a; font-size:14px; }
+.album-card-body { padding:19px 20px 18px; }.album-card-date { color:var(--album-muted); font-size:11px; letter-spacing:1px; margin:0 0 9px; }.album-card h3 { font-size:16px; font-weight:500; line-height:1.6; margin:0; min-height:52px; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; }.album-card-open { display:flex; justify-content:space-between; border-top:1px solid var(--album-line); padding-top:13px; margin-top:16px; color:var(--album-blue); font-size:12px; }
+.album-pagination { display:flex; justify-content:center; align-items:center; gap:18px; margin:32px 0; font-size:13px; color:var(--album-muted); }.album-empty { padding:70px 20px; text-align:center; border:1px dashed var(--album-line); border-radius:12px; margin:28px 0; background:var(--album-bg); }.album-empty h2 { font-size:22px; margin:0 0 12px; }.album-empty p { color:var(--album-muted); margin-bottom:20px; }
+.album-breadcrumb { display:flex; gap:12px; align-items:center; color:var(--album-muted); margin:12px 0 24px; font-size:13px; }.album-breadcrumb a { color:var(--album-blue); }.album-detail-header { display:flex; align-items:flex-start; justify-content:space-between; gap:24px; padding-bottom:24px; border-bottom:1px solid var(--album-line); margin-bottom:28px; }.album-detail-header h1 { font-size:29px; max-width:900px; }.album-detail-header .album-button { flex-shrink:0; }
+.album-description { padding:22px 26px; background:var(--album-bg); border:1px solid var(--album-line); border-radius:10px; margin-bottom:28px; }.album-photo-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:22px; }.album-photo { margin:0; min-width:0; }.album-photo-open { display:block; width:100%; aspect-ratio:4/3; border:0; padding:0; border-radius:10px; overflow:hidden; background:#d8e2ec; position:relative; cursor:zoom-in; }.album-photo-open img { width:100%; height:100%; object-fit:cover; }.album-photo-zoom { position:absolute; right:10px; bottom:10px; width:28px; height:28px; border-radius:50%; background:#fffdfc; color:#17334e; display:grid; place-items:center; opacity:0; transition:opacity .15s; }.album-photo-zoom svg { display:block; width:16px; height:16px; }.album-photo-open:hover .album-photo-zoom,.album-photo-open:focus .album-photo-zoom { opacity:1; }.album-photo figcaption { padding:10px 2px; font-size:12px; color:var(--album-muted); }.album-source-link { margin:30px 0; font-size:13px; }
+.album-viewer { box-sizing:border-box; width:min(1800px,96vw); height:94dvh; max-width:96vw; max-height:94dvh; padding:0; border:1px solid #506176; border-radius:12px; background:#101a24; color:#e9f0f6; overflow:hidden; }.album-viewer[open] { display:grid; grid-template-rows:auto minmax(0,1fr) auto; }.album-viewer::backdrop { background:#07111ce8; }.album-viewer-bar { display:flex; justify-content:space-between; align-items:center; padding:12px 18px; font-size:13px; }.album-viewer-bar>div { display:flex; align-items:center; gap:20px; }.album-viewer-bar a { color:#b9dbfb; }.album-viewer-bar button { background:none; border:0; color:white; padding:8px; cursor:pointer; font-size:19px; }.album-viewer-stage { display:flex; align-items:center; justify-content:center; position:relative; min-height:0; overflow:hidden; background:#0b131c; }.album-viewer-stage>img { display:block; max-width:100%; width:100%; height:100%; max-height:100%; object-fit:contain; }.album-viewer-stage>button { position:absolute; z-index:1; top:calc(50% - 24px); width:44px; height:48px; border:0; border-radius:8px; background:#132c44bd; color:white; font-size:32px; cursor:pointer; }.album-viewer-previous { left:12px; }.album-viewer-next { right:12px; }.album-viewer-caption { padding:12px 22px; text-align:center; margin:0; min-height:22px; font-size:13px; line-height:1.5; color:#c5d1de; max-height:14dvh; overflow:auto; overflow-wrap:anywhere; box-sizing:border-box; }.album-viewer-caption:empty { display:none; }.album-viewer-open { overflow:hidden; }
+.album-editor { max-width:1100px; }.album-edit-form { border:1px solid var(--album-line); border-radius:12px; overflow:hidden; background:var(--album-bg); }.album-edit-section { padding:28px; border-bottom:1px solid var(--album-line); }.album-edit-section h2 { font-size:18px; font-weight:600; margin:0 0 22px; }.album-edit-fields { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:20px; }.album-field { display:flex; flex-direction:column; gap:8px; font-size:13px; color:var(--album-ink); }.album-field>span { color:var(--album-muted); font-size:12px; }.album-field--wide { grid-column:1/-1; }.album-field input,.album-field textarea,.album-field select,.album-caption-field input { width:100%; box-sizing:border-box; padding:10px 12px; border:1px solid var(--album-line); border-radius:7px; font:inherit; line-height:1.6; color:var(--album-ink); background:var(--album-bg); }.album-field textarea { resize:vertical; }.album-publish { display:flex; align-items:center; gap:8px; margin:22px 0 8px; font-size:14px; }.album-field-hint { color:var(--album-muted); font-size:12px; margin:8px 0; }.album-edit-section-title { display:flex; align-items:center; justify-content:space-between; gap:20px; }.album-edit-section-title h2 { margin-bottom:7px; }.album-edit-section-title p { color:var(--album-muted); font-size:12px; margin:0; }.album-edit-section-title h2>span { font-size:13px; color:var(--album-muted); }.album-upload-label { position:relative; overflow:hidden; flex-shrink:0; }.album-upload-label input { position:absolute; opacity:0; inset:0; width:100%; cursor:pointer; }
+.album-edit-photos { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:18px; margin:24px 0 0; padding:0; list-style:none; }.album-edit-photo { min-width:0; list-style:none; margin:0; padding:0; border:1px solid var(--album-line); border-radius:9px; overflow:hidden; }.album-edit-photo.is-cover { border-color:#2e80b6; box-shadow:0 0 0 1px #2e80b6; }.album-edit-photo.is-dragging { opacity:.4; }.album-edit-photo-image { position:relative; aspect-ratio:4/3; background:var(--album-soft); }.album-edit-photo-image>img { width:100%; height:100%; object-fit:cover; }.album-drag-handle { position:absolute; left:8px; top:8px; border:0; border-radius:4px; font-size:24px; background:#fffe; color:#203a53; width:34px; height:34px; cursor:grab; }.album-cover-choice { position:absolute; right:8px; top:8px; display:flex; gap:4px; align-items:center; background:#fffffff0; color:#183149; font-size:11px; padding:7px; border-radius:5px; }.album-caption-field { display:block; padding:12px; font-size:11px; color:var(--album-muted); }.album-caption-field input { display:block; margin-top:6px; padding:7px; font-size:12px; }.album-photo-actions { display:flex; justify-content:space-between; gap:2px; padding:0 8px 10px; }.album-photo-actions button { border:0; background:none; color:var(--album-blue); font-size:11px; padding:7px 3px; cursor:pointer; }.album-photo-actions button:disabled { color:var(--album-muted); opacity:.4; cursor:default; }.album-photo-actions button:last-child { color:#a54a43; }.album-edit-empty { text-align:center; padding:30px 0 10px; color:var(--album-muted); font-size:14px; }.album-upload-status { border:1px solid var(--album-line); border-radius:8px; padding:15px; margin-top:20px; font-size:12px; }.album-upload-status progress { display:block; width:100%; margin-bottom:8px; accent-color:#246897; }.album-upload-status ul { margin:8px 0 0; color:#b34237; }.album-editor-footer { display:flex; justify-content:flex-end; gap:12px; padding:20px 28px; background:var(--album-soft); }.album-create-note { padding:20px 28px; color:var(--album-muted); font-size:13px; }.album-delete-form { text-align:right; margin-top:18px; }.album-delete-form button { border:0; color:#a54a43; background:none; font-size:12px; cursor:pointer; padding:10px; }
+.album-source-banner { display:flex; justify-content:space-between; flex-wrap:wrap; gap:8px; background:#edf5fc; border:1px solid #d3e4f2; border-radius:8px; padding:12px 16px; margin:20px 0; font-size:13px; color:#3d6685; }.album-source-banner a { color:#21618e; }
+.album-sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
+@media(max-width:1000px) { .album-grid,.album-photo-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }.album-hero-side { flex-direction:column; align-items:flex-end; gap:16px; }.album-search { order:0; }.album-edit-photos { grid-template-columns:repeat(2,minmax(0,1fr)); } }
+@media(max-width:600px) { .album-hero { align-items:flex-start; padding-top:15px; gap:16px; }.album-app h1 { font-size:28px; }.album-lead { font-size:12px; max-width:180px; }.album-totals { gap:15px; font-size:10px; }.album-totals strong { font-size:23px; }.album-hero-side .album-button { padding:8px 10px; font-size:11px; }.album-filters { gap:14px; }.album-search { width:100%; }.album-search input { flex:1; min-width:0; }.album-years { gap:3px; }.album-years a { padding:7px 9px; font-size:12px; }.album-grid { gap:13px; }.album-card-body { padding:12px; }.album-card h3 { font-size:13px; min-height:63px; -webkit-line-clamp:3; }.album-card-date { font-size:10px; }.album-card-open { font-size:11px; margin-top:12px; padding-top:10px; }.album-photo-badge { right:7px; bottom:7px; padding:4px 6px; font-size:10px; }.album-year-group>h2 { font-size:22px; }.album-detail-header { flex-direction:column; gap:15px; }.album-detail-header h1 { font-size:24px; }.album-photo-grid { gap:12px; }.album-description { padding:16px; }.album-viewer { width:100vw; max-width:100vw; border-radius:0; }.album-viewer-bar { padding:8px 12px; }.album-viewer-stage>button { width:36px; }.album-viewer-previous { left:4px; }.album-viewer-next { right:4px; }.album-edit-section { padding:20px 16px; }.album-edit-fields { gap:16px; }.album-edit-section-title { align-items:flex-start; flex-direction:column; gap:14px; }.album-edit-photos { gap:12px; }.album-photo-actions { flex-wrap:wrap; }.album-editor-footer { padding:18px 16px; }.album-breadcrumb { margin-top:5px; } }
+@media(prefers-reduced-motion:reduce) { .album-card { transition:none; }.album-card:hover { transform:none; } }
+
+.album-app .album-button { line-height:1.4; white-space:nowrap; vertical-align:middle; }
+.album-app .album-button--primary,.album-app .album-button--primary:visited { color:#fff; background:#246897; border-color:#246897; }
+.album-app .album-button--primary:hover,.album-app .album-button--primary:focus-visible { color:#fff; background:#1a547d; border-color:#1a547d; }
+.album-app .album-create-button { min-width:124px; min-height:44px; font-size:14px; font-weight:500; flex-shrink:0; gap:8px; }
+.album-create-icon { display:block; font-size:20px; font-weight:400; line-height:1; }
+@media(max-width:600px) { .album-app .album-create-button { min-width:104px; font-size:12px; min-height:42px; padding:9px 12px; } }
+
+.album-card-open { align-items:center; }
+.album-award { display:inline-flex; align-items:center; gap:5px; font-size:12px; line-height:1.4; font-weight:500; white-space:nowrap; flex-shrink:0; }
+.album-award svg { display:block; width:16px; height:16px; flex-shrink:0; }
+.album-award--gold { color:#976a12; }.album-award--silver { color:#667385; }.album-award--bronze { color:#9b5c31; }
+.theme--dark .album-award--gold { color:#f0c66b; }.theme--dark .album-award--silver { color:#c6d2e1; }.theme--dark .album-award--bronze { color:#e6ad85; }
+.album-detail-top { display:flex; align-items:center; justify-content:space-between; gap:20px; min-height:42px; margin:0 0 20px; }
+.album-detail-top .album-breadcrumb { margin:0; min-width:0; }
+.album-detail-top>.album-button { flex-shrink:0; }
+.album-detail-heading { width:100%; min-width:0; }
+.album-title-row { display:flex; align-items:center; justify-content:space-between; gap:24px; }
+.album-title-row h1 { flex:1; min-width:0; max-width:none; }
+.album-title-row .album-award { margin-left:auto; font-size:16px; gap:7px; }
+.album-title-row .album-award svg { width:20px; height:20px; }
+@media(max-width:600px) { .album-edit-fields { grid-template-columns:1fr; }.album-detail-top { gap:12px; }.album-title-row { align-items:flex-start; gap:12px; }.album-title-row .album-award { font-size:14px; margin-top:4px; }.album-title-row .album-award svg { width:18px; height:18px; } }
diff --git a/packages/contest-album/frontend/album.page.ts b/packages/contest-album/frontend/album.page.ts
new file mode 100644
index 0000000000..8772ee2029
--- /dev/null
+++ b/packages/contest-album/frontend/album.page.ts
@@ -0,0 +1,228 @@
+import { addPage, ConfirmDialog, i18n, NamedPage, tpl } from '@hydrooj/ui-default';
+
+function viewer() {
+ const dialog = document.querySelector
('[data-album-viewer]');
+ const buttons = [...document.querySelectorAll('[data-album-photo]')];
+ if (!dialog || !buttons.length) return;
+ const image = dialog.querySelector('[data-viewer-image]');
+ const caption = dialog.querySelector('[data-viewer-caption]');
+ const counter = dialog.querySelector('[data-viewer-count]');
+ const original = dialog.querySelector('[data-viewer-original]');
+ let current = 0;
+ let touchX: number | undefined;
+ const show = (index: number) => {
+ current = (index + buttons.length) % buttons.length;
+ const photo = buttons[current];
+ image.src = photo.dataset.albumPreview;
+ image.alt = photo.dataset.caption || `第 ${current + 1} 张照片`;
+ caption.textContent = photo.dataset.caption || '';
+ counter.textContent = `${current + 1} / ${buttons.length}`;
+ original.href = photo.dataset.original;
+ if (!dialog.open) dialog.showModal();
+ document.body.classList.add('album-viewer-open');
+ };
+ for (const [index, button] of buttons.entries()) {
+ button.addEventListener('click', (event) => {
+ if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
+ event.preventDefault();
+ show(index);
+ });
+ }
+ dialog.querySelector('[data-viewer-close]').addEventListener('click', () => dialog.close());
+ dialog.querySelector('[data-viewer-previous]').addEventListener('click', () => show(current - 1));
+ dialog.querySelector('[data-viewer-next]').addEventListener('click', () => show(current + 1));
+ dialog.addEventListener('keydown', (event) => {
+ if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
+ event.preventDefault();
+ event.stopPropagation();
+ show(current + (event.key === 'ArrowLeft' ? -1 : 1));
+ }
+ });
+ image.addEventListener('touchstart', (event) => { touchX = event.changedTouches[0]?.clientX; }, { passive: true });
+ image.addEventListener('touchend', (event) => {
+ const distance = (event.changedTouches[0]?.clientX || 0) - (touchX || 0);
+ if (touchX !== undefined && Math.abs(distance) > 60) show(current + (distance < 0 ? 1 : -1));
+ touchX = undefined;
+ }, { passive: true });
+ dialog.addEventListener('click', (event) => { if (event.target === dialog) dialog.close(); });
+ dialog.addEventListener('close', () => {
+ document.body.classList.remove('album-viewer-open');
+ image.removeAttribute('src');
+ });
+}
+
+function editor() {
+ const form = document.querySelector('[data-album-editor]');
+ if (!form) return;
+ const list = form.querySelector('[data-edit-photos]');
+ const cover = form.elements.namedItem('cover') as HTMLInputElement;
+ const hidden = form.elements.namedItem('photos') as HTMLInputElement;
+ const upload = form.querySelector('[data-album-upload]');
+ const save = form.querySelector('[data-album-save]');
+ let busy = false;
+ let dirty = false;
+ const items = () => list ? [...list.querySelectorAll('[data-photo-id]')] : [];
+ const update = () => {
+ const rows = items();
+ if (!rows.some((row) => row.dataset.photoId === cover.value)) cover.value = rows[0]?.dataset.photoId || '';
+ hidden.value = JSON.stringify(rows.map((row, index) => {
+ const id = row.dataset.photoId;
+ (row.querySelector('input[type=radio]') as HTMLInputElement).checked = id === cover.value;
+ (row.querySelector('[data-photo-action=up]') as HTMLButtonElement).disabled = index === 0;
+ (row.querySelector('[data-photo-action=down]') as HTMLButtonElement).disabled = index === rows.length - 1;
+ row.classList.toggle('is-cover', id === cover.value);
+ return { id, caption: (row.querySelector('[data-photo-caption]') as HTMLInputElement).value };
+ }));
+ const count = document.querySelector('[data-edit-count]');
+ if (count) count.textContent = String(rows.length);
+ const empty = document.querySelector('[data-edit-empty]');
+ if (empty) empty.hidden = rows.length > 0;
+ };
+ form.addEventListener('input', () => { dirty = true; });
+ form.addEventListener('change', (event) => {
+ const target = event.target as HTMLInputElement;
+ if (target.name === 'coverChoice') {
+ cover.value = target.value;
+ update();
+ }
+ });
+ form.addEventListener('submit', (event) => {
+ if (busy) event.preventDefault();
+ else {
+ update();
+ dirty = false;
+ }
+ });
+ window.addEventListener('beforeunload', (event) => {
+ if (dirty || busy) {
+ event.preventDefault();
+ event.returnValue = '';
+ }
+ });
+ const deleteForm = document.querySelector('[data-album-delete]');
+ if (deleteForm) {
+ const button = deleteForm.querySelector('button');
+ button.type = 'button';
+ let confirming = false;
+ const remove = async (event: Event) => {
+ event.preventDefault();
+ if (busy || confirming) return;
+ confirming = true;
+ try {
+ const action = await new ConfirmDialog({ $body: tpl.typoMsg('确定删除这本相册吗?'), canCancel: true }).open();
+ if (action !== 'yes') return;
+ dirty = false;
+ HTMLFormElement.prototype.submit.call(deleteForm);
+ } finally {
+ confirming = false;
+ }
+ };
+ button.addEventListener('click', remove);
+ deleteForm.addEventListener('submit', remove);
+ }
+ if (!list) return;
+ list.addEventListener('click', (event) => {
+ const button = (event.target as HTMLElement).closest('[data-photo-action]');
+ if (!button) return;
+ const row = button.closest('[data-photo-id]');
+ if (button.dataset.photoAction === 'remove') row.remove();
+ if (button.dataset.photoAction === 'up' && row.previousElementSibling) list.insertBefore(row, row.previousElementSibling);
+ if (button.dataset.photoAction === 'down' && row.nextElementSibling) list.insertBefore(row.nextElementSibling, row);
+ dirty = true;
+ update();
+ });
+ let dragging: HTMLElement;
+ list.addEventListener('dragstart', (event) => {
+ const handle = (event.target as HTMLElement).closest('.album-drag-handle');
+ if (!handle) {
+ event.preventDefault();
+ return;
+ }
+ dragging = handle.closest('[data-photo-id]');
+ event.dataTransfer.setData('text/plain', dragging.dataset.photoId);
+ event.dataTransfer.effectAllowed = 'move';
+ dragging.classList.add('is-dragging');
+ });
+ list.addEventListener('dragover', (event) => {
+ if (dragging) {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = 'move';
+ }
+ });
+ list.addEventListener('drop', (event) => {
+ if (!dragging) return;
+ event.preventDefault();
+ const row = (event.target as HTMLElement).closest('[data-photo-id]');
+ if (row && row !== dragging) {
+ const box = row.getBoundingClientRect();
+ list.insertBefore(dragging, event.clientX > box.left + box.width / 2 ? row.nextSibling : row);
+ dirty = true;
+ }
+ update();
+ });
+ list.addEventListener('dragend', () => {
+ dragging?.classList.remove('is-dragging');
+ dragging = undefined;
+ });
+ upload.addEventListener('change', async () => {
+ const files = [...upload.files];
+ if (!files.length) return;
+ busy = true;
+ save.disabled = true;
+ upload.disabled = true;
+ const status = document.querySelector('[data-upload-status]');
+ const progress = document.querySelector('[data-upload-progress]');
+ const message = document.querySelector('[data-upload-message]');
+ const errors = document.querySelector('[data-upload-errors]');
+ status.hidden = false;
+ progress.max = files.length;
+ progress.value = 0;
+ errors.replaceChildren();
+ let successful = 0;
+ try {
+ for (const [index, file] of files.entries()) {
+ message.textContent = `正在上传 ${index + 1} / ${files.length}:${file.name}`;
+ try {
+ if (file.size > 20 * 1024 * 1024) throw new Error('图片超过 20 MB');
+ const data = new FormData();
+ data.set('operation', 'upload');
+ data.set('revision', (form.elements.namedItem('revision') as HTMLInputElement).value);
+ data.set('file', file);
+ const response = await fetch(form.dataset.uploadUrl, { method: 'POST', body: data, headers: { Accept: 'application/json' } });
+ const payload = await response.json();
+ if (!response.ok || !payload.photo) {
+ const error = payload.error;
+ throw new Error(error?.message ? i18n(error.message, ...(error.params || [])) : '上传失败,请重试');
+ }
+ const template = document.querySelector('[data-edit-photo-template]');
+ const row = template.content.firstElementChild.cloneNode(true) as HTMLElement;
+ row.dataset.photoId = payload.photo.id;
+ (row.querySelector('img') as HTMLImageElement).src = payload.photo.thumb;
+ (row.querySelector('input[type=radio]') as HTMLInputElement).value = payload.photo.id;
+ list.append(row);
+ document.querySelectorAll('input[name=revision]').forEach((input) => { input.value = payload.revision; });
+ successful++;
+ update();
+ } catch (error) {
+ const item = document.createElement('li');
+ item.textContent = `${file.name}:${error.message}`;
+ errors.append(item);
+ }
+ progress.value = index + 1;
+ }
+ } finally {
+ const failures = files.length > successful ? `,${files.length - successful} 张失败` : '';
+ message.textContent = `已添加 ${successful} 张照片${failures}。可继续设置封面、排序和照片说明。`;
+ busy = false;
+ save.disabled = false;
+ upload.disabled = false;
+ upload.value = '';
+ }
+ });
+ update();
+}
+
+addPage(new NamedPage(['album_main', 'album_detail', 'album_edit', 'album_create'], () => {
+ viewer();
+ editor();
+}));
diff --git a/packages/contest-album/index.ts b/packages/contest-album/index.ts
new file mode 100644
index 0000000000..74a087e961
--- /dev/null
+++ b/packages/contest-album/index.ts
@@ -0,0 +1,287 @@
+/* eslint-disable no-await-in-loop */
+import { createHash } from 'crypto';
+import { readFileSync } from 'fs';
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import type { ImagePreviewService } from '@hgnuoj/image-preview';
+import { userFile, version } from '@hgnuoj/image-preview/images';
+import type { Collection } from 'mongodb';
+import sharp from 'sharp';
+import {
+ Context, db, FileInfo, Handler, nanoid, NotFoundError, ObjectId, PERM, PRIV,
+ StorageModel, SystemModel, UserModel, ValidationError,
+} from 'hydrooj';
+import { Album, AWARD_LABELS, escapeSearch, fields, orderedPhotos, paginateYears, Photo } from './model';
+
+declare module 'hydrooj' {
+ interface Collections {
+ 'hgnu.album': Album;
+ }
+}
+
+export const albums = db.collection('hgnu.album');
+const fileAccounts = UserModel.coll as unknown as Collection<{ _id: number, _files?: FileInfo[] }>;
+const stylesheet = readFileSync(join(__dirname, 'frontend/album.css'), 'utf8');
+const styleVersion = createHash('sha256').update(stylesheet).digest('hex').slice(0, 16);
+
+class AlbumStylesheetHandler extends Handler {
+ noCheckPermView = true;
+
+ get() {
+ this.response.type = 'text/css';
+ this.response.addHeader('Cache-Control', 'public, max-age=31536000, immutable');
+ this.response.addHeader('ETag', `"${styleVersion}"`);
+ this.response.body = stylesheet;
+ }
+}
+
+async function images(ctx: Context, photos: Photo[]) {
+ const paths = [...new Set(photos.map((photo) => userFile(photo.src)).filter(Boolean))];
+ const rows = await StorageModel.coll.find({ path: { $in: paths }, autoDelete: null }).toArray();
+ const sources = new Map(rows.map((row) => [row.path, row]));
+ const service = ctx.get('image-preview') as ImagePreviewService;
+ const result = [];
+ for (const photo of photos) {
+ const source = sources.get(userFile(photo.src));
+ const info = source && service ? await service.previews.dimensions(source) : null;
+ const url = (width: number) => info ? `${photo.src}/preview/${width}/${version(source)}.webp` : photo.src;
+ result.push({
+ ...photo, thumb: url(480), preview: url(1600),
+ original: `${photo.src}?noDisposition=true`, width: info?.width || 4, height: info?.height || 3,
+ });
+ }
+ return result;
+}
+
+function validate(fn: () => T): T {
+ try {
+ return fn();
+ } catch (e) {
+ throw new ValidationError(e.message);
+ }
+}
+
+class AlbumBaseHandler extends Handler {
+ album?: Album;
+
+ renderAlbum(template: string, body: Record) {
+ this.response.template = template;
+ this.response.body = { ...body, awardLabels: AWARD_LABELS, albumStylesheet: this.url('album_style', { version: styleVersion }) };
+ }
+
+ async prepare() {
+ const domainId = this.domain._id;
+ const aid = this.request.params.aid;
+ // Hydro merges request fields into args before loading domain permissions.
+ if (this.args.domainId !== domainId || (this.args.aid && this.args.aid !== aid)) {
+ throw new ValidationError('相册地址与请求参数不一致');
+ }
+ this.checkPerm(PERM.PERM_VIEW_DISCUSSION);
+ if (!aid) return;
+ if (!ObjectId.isValid(aid)) throw new NotFoundError('相册');
+ this.album = await albums.findOne({ _id: new ObjectId(aid), domainId, deletedAt: null });
+ if (!this.album || (!this.album.published && !this.canEdit())) throw new NotFoundError('相册');
+ }
+
+ canEdit() {
+ return this.user.hasPriv(PRIV.PRIV_USER_PROFILE) && (this.user.hasPerm(PERM.PERM_EDIT_DISCUSSION)
+ || (this.album?.owner === this.user._id && this.user.hasPerm(PERM.PERM_EDIT_DISCUSSION_SELF)));
+ }
+
+ checkEdit() {
+ this.checkPriv(PRIV.PRIV_USER_PROFILE);
+ if (!this.canEdit()) this.checkPerm(PERM.PERM_EDIT_DISCUSSION);
+ }
+
+ canDelete() {
+ return this.canEdit() && (this.user.hasPerm(PERM.PERM_DELETE_DISCUSSION)
+ || (this.album.owner === this.user._id && this.user.hasPerm(PERM.PERM_DELETE_DISCUSSION_SELF)));
+ }
+
+ revision(value: any) {
+ if (!Number.isSafeInteger(+value) || +value !== this.album.revision) throw new ValidationError('相册已被更新,请刷新页面后再保存');
+ return +value;
+ }
+
+ async replace(revision: number, value: Partial) {
+ const result = await albums.findOneAndUpdate(
+ { _id: this.album._id, domainId: this.album.domainId, revision, deletedAt: null },
+ { $set: { ...value, updatedAt: new Date() }, $inc: { revision: 1 } },
+ { returnDocument: 'after' },
+ );
+ if (!result) throw new ValidationError('相册已被更新,请刷新页面后再保存');
+ return result;
+ }
+}
+
+class AlbumMainHandler extends AlbumBaseHandler {
+ async get({ q = '', year = '', page = 1 }) {
+ const domainId = this.domain._id;
+ const search = String(q).trim().slice(0, 100);
+ const selectedYear = String(year);
+ if (selectedYear && !/^(?:0|19\d\d|20\d\d|2100)$/.test(selectedYear)) throw new ValidationError('年份');
+ const requestedPage = Math.max(1, Math.min(10000, Number(page) || 1));
+ if (!Number.isInteger(requestedPage)) throw new ValidationError('页码');
+ const visible = this.user.hasPerm(PERM.PERM_EDIT_DISCUSSION) ? {} : this.user.hasPriv(PRIV.PRIV_USER_PROFILE)
+ ? { $or: [{ published: true }, { owner: this.user._id }] } : { published: true };
+ const scope = { domainId, deletedAt: null, ...visible };
+ const filter = {
+ ...scope, ...selectedYear ? { year: +selectedYear } : {},
+ ...search ? { title: new RegExp(escapeSearch(search), 'i') } : {},
+ };
+ const [stats, yearCounts, matchingYears] = await Promise.all([
+ albums.aggregate([{ $match: scope }, { $group: { _id: null, count: { $sum: 1 }, photos: { $sum: { $size: '$photos' } } } }]).toArray(),
+ albums.aggregate([{ $match: scope }, { $group: { _id: '$year', count: { $sum: 1 } } }, { $sort: { _id: -1 } }]).toArray(),
+ albums.aggregate([{ $match: filter }, { $group: { _id: '$year', count: { $sum: 1 } } }, { $sort: { _id: -1 } }]).toArray(),
+ ]);
+ const pages = paginateYears(matchingYears.map((row) => ({ year: row._id, count: row.count })));
+ const currentPage = Math.min(requestedPage, Math.max(1, pages.length));
+ const total = matchingYears.reduce((sum, row) => sum + row.count, 0);
+ const rows = await albums.find({ ...filter, year: { $in: pages[currentPage - 1] || [] } })
+ .sort({ year: -1, date: -1, createdAt: -1, _id: -1 }).toArray();
+ const coverPhotos = rows.map((album) => album.photos.find((photo) => photo.id === album.cover) || album.photos[0]);
+ const covers = await images(this.ctx, coverPhotos.filter(Boolean));
+ const groups: { year: number, items: any[] }[] = [];
+ for (const album of rows) {
+ if (!groups.length || groups.at(-1).year !== album.year) groups.push({ year: album.year, items: [] });
+ const cover = album.photos.find((photo) => photo.id === album.cover) || album.photos[0];
+ groups.at(-1).items.push({ ...album, coverImage: covers.find((photo) => photo.id === cover?.id) });
+ }
+ const pageUrl = (p: number, y = selectedYear) => `${this.url('album_main')}?${new URLSearchParams({ q: search, year: y, page: String(p) })}`;
+ this.renderAlbum('album_main.html', {
+ groups, years: yearCounts.map((row) => ({ year: row._id, count: row.count, url: pageUrl(1, String(row._id)) })),
+ stats: stats[0] || { count: 0, photos: 0 }, total, q: search, year: selectedYear, page: currentPage,
+ pageCount: pages.length, previous: pageUrl(currentPage - 1), next: pageUrl(currentPage + 1), allYears: pageUrl(1, ''),
+ canCreate: this.user.hasPriv(PRIV.PRIV_USER_PROFILE) && this.user.hasPerm(PERM.PERM_CREATE_DISCUSSION),
+ });
+ }
+}
+
+class AlbumDetailHandler extends AlbumBaseHandler {
+ async get() {
+ const photos = await images(this.ctx, this.album.photos);
+ this.renderAlbum('album_detail.html', { album: this.album, photos, canEdit: this.canEdit() });
+ }
+}
+
+class AlbumCreateHandler extends AlbumBaseHandler {
+ async get() {
+ this.checkPriv(PRIV.PRIV_USER_PROFILE);
+ this.checkPerm(PERM.PERM_CREATE_DISCUSSION);
+ this.renderAlbum('album_edit.html', {
+ album: { title: '', year: new Date().getFullYear(), date: '', description: '', published: false, photos: [], revision: 0 },
+ photos: [], isNew: true,
+ });
+ }
+
+ async post(args) {
+ this.checkPriv(PRIV.PRIV_USER_PROFILE);
+ this.checkPerm(PERM.PERM_CREATE_DISCUSSION);
+ await this.limitRate('album_create', 3600, 30);
+ const info = validate(() => fields(args));
+ const now = new Date();
+ const _id = new ObjectId();
+ await albums.insertOne({
+ _id, domainId: this.domain._id, owner: this.user._id, ...info,
+ photos: [], cover: '', createdAt: now, updatedAt: now, revision: 0,
+ });
+ this.response.redirect = this.url('album_edit', { aid: _id });
+ this.response.body = { id: _id.toHexString() };
+ }
+}
+
+class AlbumEditHandler extends AlbumBaseHandler {
+ async get() {
+ this.checkEdit();
+ this.renderAlbum('album_edit.html', {
+ album: this.album, photos: await images(this.ctx, this.album.photos), isNew: false, canDelete: this.canDelete(),
+ });
+ }
+
+ async post(args) {
+ this.checkEdit();
+ if (args.operation) return;
+ const revision = this.revision(args.revision);
+ const info = validate(() => fields(args));
+ const photos = validate(() => orderedPhotos(JSON.parse(args.photos || '[]'), this.album.photos));
+ const cover = photos.some((photo) => photo.id === args.cover) ? args.cover : photos[0]?.id || '';
+ await this.replace(revision, { ...info, photos, cover });
+ this.response.redirect = this.url('album_detail', { aid: this.album._id });
+ }
+
+ async postUpload(args) {
+ this.checkEdit();
+ this.checkPriv(PRIV.PRIV_CREATE_FILE);
+ await this.limitRate('album_upload', 60, 60);
+ const revision = this.revision(args.revision);
+ if (this.album.photos.length >= 500) throw new ValidationError('一个相册最多 500 张照片');
+ const file = this.request.files?.file;
+ if (!file || Array.isArray(file) || file.size > 20 * 1024 * 1024 || file.size === 0) throw new ValidationError('请选择不超过 20 MB 的图片');
+ const buffer = await readFile(file.filepath);
+ const info = await sharp(buffer, { limitInputPixels: 80 * 1000 * 1000 }).metadata().catch(() => null);
+ if (!info || !['jpeg', 'png', 'webp'].includes(info.format) || (info.pages || 1) > 1) {
+ throw new ValidationError('支持 JPG、PNG 和静态 WebP 图片');
+ }
+ const owner = await UserModel.coll.findOne({ _id: this.user._id });
+ const files = owner._files || [];
+ if (!this.user.hasPriv(PRIV.PRIV_UNLIMITED_QUOTA) && (files.length >= SystemModel.get('limit.user_files')
+ || files.reduce((sum, row) => sum + (row.size || 0), 0) + file.size > SystemModel.get('limit.user_files_size'))) {
+ throw new ValidationError('文件空间或数量已达到上限');
+ }
+ const filename = `album-${this.album._id}-${nanoid(12)}.${info.format === 'jpeg' ? 'jpg' : info.format}`;
+ const target = `user/${this.user._id}/${filename}`;
+ const photo = { id: nanoid(16), src: `/file/${this.user._id}/${filename}`, caption: '' };
+ try {
+ await StorageModel.put(target, buffer, this.user._id);
+ const meta = await StorageModel.getMeta(target);
+ await fileAccounts.updateOne({ _id: this.user._id }, {
+ $push: { _files: { _id: filename, name: filename, size: meta.size, etag: meta.etag, lastModified: meta.lastModified } },
+ });
+ UserModel._deleteUserCache(owner);
+ const view = (await images(this.ctx, [photo]))[0];
+ const result = await albums.findOneAndUpdate(
+ { _id: this.album._id, domainId: this.album.domainId, revision, deletedAt: null },
+ { $push: { photos: photo }, $set: { updatedAt: new Date(), ...this.album.cover ? {} : { cover: photo.id } }, $inc: { revision: 1 } },
+ { returnDocument: 'after' },
+ );
+ if (!result) throw new ValidationError('相册已被更新,请刷新后重试上传');
+ this.response.body = { photo: view, revision: result.revision };
+ } catch (e) {
+ await StorageModel.del([target], this.user._id);
+ await fileAccounts.updateOne({ _id: this.user._id }, { $pull: { _files: { _id: filename } } });
+ UserModel._deleteUserCache(owner);
+ throw e;
+ }
+ }
+
+ async postDelete(args) {
+ this.checkEdit();
+ const revision = this.revision(args.revision);
+ if (!this.user.hasPerm(PERM.PERM_DELETE_DISCUSSION)) {
+ if (this.album.owner !== this.user._id) this.checkPerm(PERM.PERM_DELETE_DISCUSSION);
+ this.checkPerm(PERM.PERM_DELETE_DISCUSSION_SELF);
+ }
+ await this.replace(revision, { deletedAt: new Date() });
+ this.response.redirect = this.url('album_main');
+ }
+}
+
+export const inject = ['db', 'storage'];
+export async function apply(ctx: Context) {
+ await albums.createIndex({ domainId: 1, year: -1, date: -1, createdAt: -1 });
+ await albums.createIndex({ domainId: 1, 'source.discussion': 1, 'source.section': 1 }, {
+ unique: true, partialFilterExpression: { 'source.discussion': { $exists: true } },
+ });
+ ctx.Route('album_main', '/albums', AlbumMainHandler);
+ ctx.Route('album_style', '/album-assets/:version/album.css', AlbumStylesheetHandler);
+ ctx.Route('album_create', '/albums/new', AlbumCreateHandler);
+ ctx.Route('album_edit', '/albums/:aid/edit', AlbumEditHandler);
+ ctx.Route('album_detail', '/albums/:aid', AlbumDetailHandler);
+ ctx.injectUI('Nav', 'album_main', { prefix: 'album', before: 'courses' }, PERM.PERM_VIEW_DISCUSSION);
+ ctx.on('handler/after/DiscussionDetail', async (handler) => {
+ if (await albums.findOne({ domainId: handler.domain._id, 'source.discussion': handler.ddoc.docId, published: true, deletedAt: null })) {
+ handler.response.body.albumCollection = handler.url('album_main');
+ handler.response.body.albumStylesheet = handler.url('album_style', { version: styleVersion });
+ }
+ });
+}
diff --git a/packages/contest-album/locales/en.yaml b/packages/contest-album/locales/en.yaml
new file mode 100644
index 0000000000..2ae3f29b7d
--- /dev/null
+++ b/packages/contest-album/locales/en.yaml
@@ -0,0 +1,3 @@
+album_main: Albums
+album_detail: Album
+album_edit: Edit album
diff --git a/packages/contest-album/locales/zh.yaml b/packages/contest-album/locales/zh.yaml
new file mode 100644
index 0000000000..1903d8bb91
--- /dev/null
+++ b/packages/contest-album/locales/zh.yaml
@@ -0,0 +1,3 @@
+album_main: 比赛相册
+album_detail: 比赛相册
+album_edit: 编辑相册
diff --git a/packages/contest-album/model.ts b/packages/contest-album/model.ts
new file mode 100644
index 0000000000..4e80bf2b43
--- /dev/null
+++ b/packages/contest-album/model.ts
@@ -0,0 +1,79 @@
+import { ObjectId } from 'mongodb';
+
+export const AWARD_LABELS = { gold: '金牌', silver: '银牌', bronze: '铜牌' } as const;
+export type Award = '' | keyof typeof AWARD_LABELS;
+
+export interface Photo {
+ id: string;
+ src: string;
+ caption: string;
+}
+
+export interface Album {
+ _id: ObjectId;
+ domainId: string;
+ owner: number;
+ title: string;
+ year: number;
+ date: string;
+ description: string;
+ award?: Award;
+ published: boolean;
+ cover: string;
+ photos: Photo[];
+ revision: number;
+ createdAt: Date;
+ updatedAt: Date;
+ deletedAt?: Date;
+ source?: { discussion: ObjectId, section: number, fragment: string };
+}
+
+export function fields(input: Record) {
+ const title = String(input.title || '').trim();
+ if (!title || title.length > 140) throw new Error('比赛名称需为 1–140 个字符');
+ const year = Number(input.year || 0);
+ if (!Number.isInteger(year) || (year !== 0 && (year < 1900 || year > 2100))) throw new Error('年份需在 1900–2100 之间');
+ const date = String(input.date || '').trim();
+ if (date && (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !Number.isFinite(new Date(date).getTime())
+ || new Date(date).toISOString().slice(0, 10) !== date)) throw new Error('请填写有效的比赛日期');
+ if (date && Number(date.slice(0, 4)) !== year) throw new Error('比赛日期与归档年份不一致');
+ const description = String(input.description || '').trim();
+ if (description.length > 20000) throw new Error('比赛简介最多 20000 个字符');
+ const award = String(input.award || '') as Award;
+ if (award && !Object.keys(AWARD_LABELS).includes(award)) throw new Error('请选择金牌、银牌、铜牌或不显示');
+ return { title, year, date, description, award, published: [true, 'true', 'on', '1'].includes(input.published) };
+}
+
+export function orderedPhotos(input: unknown, current: Photo[]) {
+ if (!Array.isArray(input) || input.length > 500) throw new Error('一个相册最多 500 张照片');
+ const byId = new Map(current.map((photo) => [photo.id, photo]));
+ const seen = new Set();
+ return input.map((item) => {
+ if (!item || typeof item.id !== 'string' || !byId.has(item.id) || seen.has(item.id)) throw new Error('照片列表无效,请刷新页面重试');
+ seen.add(item.id);
+ const caption = String(item.caption || '').trim();
+ if (caption.length > 200) throw new Error('单张照片的说明最多 200 个字符');
+ return { ...byId.get(item.id), caption };
+ });
+}
+
+export function escapeSearch(value: string) {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+export function paginateYears(years: { year: number, count: number }[], target = 12) {
+ const pages: number[][] = [];
+ let page: number[] = [];
+ let count = 0;
+ for (const item of years) {
+ if (page.length && count + item.count > target) {
+ pages.push(page);
+ page = [];
+ count = 0;
+ }
+ page.push(item.year);
+ count += item.count;
+ }
+ if (page.length) pages.push(page);
+ return pages;
+}
diff --git a/packages/contest-album/package.json b/packages/contest-album/package.json
new file mode 100644
index 0000000000..380785e121
--- /dev/null
+++ b/packages/contest-album/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "@hgnuoj/contest-album",
+ "version": "1.0.0",
+ "private": true,
+ "main": "index.ts",
+ "license": "AGPL-3.0-only",
+ "dependencies": { "sharp": "0.34.5" },
+ "peerDependencies": {
+ "hydrooj": "workspace:^",
+ "@hydrooj/ui-default": "workspace:^",
+ "@hgnuoj/image-preview": "workspace:^"
+ }
+}
diff --git a/packages/contest-album/templates/album_award.html b/packages/contest-album/templates/album_award.html
new file mode 100644
index 0000000000..1ca84569f0
--- /dev/null
+++ b/packages/contest-album/templates/album_award.html
@@ -0,0 +1,5 @@
+{% macro badge(value, labels) -%}
+{% if labels[value] %}
+{{ labels[value] }}
+{% endif %}
+{%- endmacro %}
diff --git a/packages/contest-album/templates/album_detail.html b/packages/contest-album/templates/album_detail.html
new file mode 100644
index 0000000000..3fc0f8fc7a
--- /dev/null
+++ b/packages/contest-album/templates/album_detail.html
@@ -0,0 +1,14 @@
+{% extends "album_layout.html" %}
+{% import "album_award.html" as awards %}
+{% block content %}
+
+
+
+ {% if album.description %}
{{ album.description|markdownImages|safe }}
{% endif %}
+ {% if photos.length %}
+ {% for photo in photos %}
{% if photo.caption %}{{ photo.caption }} {% endif %}{% endfor %}
+
{% else %}
相册已准备好 {% if canEdit %}进入编辑页,为这场比赛添加第一张照片。{% else %}照片正在整理中。{% endif %}
{% if canEdit %}
添加照片 {% endif %}
{% endif %}
+ {% if album.source %}
查看原公告中的这一章节 →
{% endif %}
+
‹ ›
+
+{% endblock %}
diff --git a/packages/contest-album/templates/album_edit.html b/packages/contest-album/templates/album_edit.html
new file mode 100644
index 0000000000..c8bb7ef2f6
--- /dev/null
+++ b/packages/contest-album/templates/album_edit.html
@@ -0,0 +1,18 @@
+{% extends "album_layout.html" %}
+{% block content %}
+
+
← 比赛相册 {% if not isNew %}/ 查看相册 {% endif %}
+
+
+ {% if not isNew and canDelete %}
删除这本相册 {% endif %}
+
照片说明 ↑ 上移 ↓ 下移 移出相册
+
+{% endblock %}
diff --git a/packages/contest-album/templates/album_layout.html b/packages/contest-album/templates/album_layout.html
new file mode 100644
index 0000000000..7ed937d2f6
--- /dev/null
+++ b/packages/contest-album/templates/album_layout.html
@@ -0,0 +1,5 @@
+{% extends "layout/basic.html" %}
+{% block ogp %}
+{{ super() }}
+
+{% endblock %}
diff --git a/packages/contest-album/templates/album_main.html b/packages/contest-album/templates/album_main.html
new file mode 100644
index 0000000000..d38e607ff3
--- /dev/null
+++ b/packages/contest-album/templates/album_main.html
@@ -0,0 +1,28 @@
+{% extends "album_layout.html" %}
+{% import "album_award.html" as awards %}
+{% block content %}
+
+
+
+
+ {% if q %}
“{{ q }}” · 找到 {{ total }} 本相册
{% endif %}
+ {% for group in groups %}
+
{{ group.year if group.year else '未注明年份' }}赛场记忆
+ {% else %}
还没有匹配的相册 换一个名称或年份试试。{% if canCreate %}也可以新建第一本比赛相册。{% endif %}
{% endfor %}
+ {% if pageCount > 1 %}{% endif %}
+
+
+{% endblock %}
diff --git a/packages/discussion-toc/README.md b/packages/discussion-toc/README.md
new file mode 100644
index 0000000000..bc95b7c180
--- /dev/null
+++ b/packages/discussion-toc/README.md
@@ -0,0 +1,11 @@
+# Discussion table of contents
+
+Enable this addon alongside the default UI. Discussion bodies with at least two nonempty headings automatically receive a directory. Markdown `#` through `######` and rendered HTML headings are supported; bold paragraphs do not count as headings. The post title and comments are excluded.
+
+Desktop layouts (1000px and wider) show a sticky sidebar directory with the current section highlighted. Narrower layouts show a floating, collapsible directory. Both have shortcuts to the start/end of the article. Navigation jumps instantly to avoid downloading lazy images in every intervening section.
+
+Existing heading IDs are preserved, including the default Markdown renderer's encoded Chinese IDs. Missing/duplicate IDs are assigned unique fallbacks. Links support reload, copying, and browser back/forward. Directory labels use plain text, never HTML from the post. Long directories scroll internally; the mobile panel closes after navigation, on Escape, or on an outside click.
+
+This is a frontend-only feature: original Markdown and stored images are not changed. Disabling the addon restores the ordinary discussion layout. The template only adds two `data-` markers for layout/sidebar placement.
+
+The browser regression check is `test/hgnu-discussion-toc.cjs` (requires Playwright with Chromium). Run it against the restored HGNU test site using `HGNUOJ_TEST_URL`, optionally setting `HGNUOJ_TOC_REPORT_DIR` for JSON/screenshots. It validates desktop/mobile/tablet jumps, sticky placement, copied Chinese fragments, reload/back, shortcuts, nested/duplicate headings, safe labels and repeated partial refresh. Its content fixtures only modify the browser DOM.
diff --git a/packages/discussion-toc/frontend/discussion-toc.css b/packages/discussion-toc/frontend/discussion-toc.css
new file mode 100644
index 0000000000..563df34292
--- /dev/null
+++ b/packages/discussion-toc/frontend/discussion-toc.css
@@ -0,0 +1,59 @@
+.discussion-toc {
+ --toc-bg: #fff;
+ --toc-text: #475569;
+ --toc-muted: #94a3b8;
+ --toc-border: #e7edf2;
+ --toc-accent: #2563a9;
+ --toc-active: #eef5fd;
+ color: var(--toc-text);
+ background: var(--toc-bg);
+ border: 1px solid var(--toc-border);
+ border-radius: 12px;
+ box-shadow: 0 4px 20px #243b5310;
+ font-size: 13px;
+ line-height: 1.55;
+ overflow: hidden;
+}
+.theme--dark .discussion-toc {
+ --toc-bg: #323334;
+ --toc-text: #e2e8f0;
+ --toc-muted: #a8b1bd;
+ --toc-border: #4a4e54;
+ --toc-accent: #75beff;
+ --toc-active: #293e54;
+}
+.discussion-toc-title { display: flex; align-items: center; justify-content: space-between; padding: 15px 16px 10px; }
+.discussion-toc-title strong { font-size: 16px; font-weight: 600; }
+.discussion-toc-count { color: var(--toc-muted); font-size: 12px; }
+.discussion-toc-list { margin: 0; padding: 0 8px 8px; list-style: none; overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; }
+.discussion-toc-list li { list-style: none; margin: 0; padding: 0; }
+.discussion-toc-link { display: block; padding: 9px 10px 9px calc(10px + var(--toc-depth) * 12px); border-left: 2px solid transparent; border-radius: 4px; color: var(--toc-text); overflow-wrap: anywhere; text-decoration: none; }
+.discussion-toc-link:hover { background: var(--toc-active); color: var(--toc-accent); text-decoration: none; }
+.discussion-toc-link[aria-current] { background: var(--toc-active); color: var(--toc-accent); border-left-color: var(--toc-accent); font-weight: 600; }
+.discussion-toc-shortcuts { display: flex; justify-content: space-between; gap: 8px; border-top: 1px solid var(--toc-border); padding: 8px 12px; }
+.discussion-toc-shortcut { padding: 4px; color: var(--toc-accent); font-size: 12px; }
+.discussion-toc a:focus-visible, .discussion-toc-toggle:focus-visible { outline: 2px solid #58a4f0; outline-offset: -2px; }
+.discussion-toc-target { scroll-margin-top: var(--discussion-toc-top, 65px); }
+span.discussion-toc-target { display: block; height: 1px; margin: 0; padding: 0; }
+.discussion-toc--desktop { display: none; }
+.discussion-toc-mobile { position: fixed; bottom: calc(18px + env(safe-area-inset-bottom)); left: 18px; z-index: 450; }
+.discussion-toc-toggle { list-style: none; cursor: pointer; border: 1px solid #cbd8e5; border-radius: 24px; padding: 11px 18px; min-height: 44px; box-sizing: border-box; background: #fff; color: #2563a9; box-shadow: 0 3px 16px #243b5326; font-size: 14px; user-select: none; }
+.discussion-toc-toggle::-webkit-details-marker { display: none; }
+.discussion-toc-toggle::before { content: '☰'; margin-right: 8px; }
+.discussion-toc--mobile { position: absolute; left: 0; bottom: calc(100% + 10px); width: min(380px, calc(100vw - 36px)); }
+.discussion-toc--mobile .discussion-toc-list { max-height: min(55vh, calc(100dvh - 240px)); }
+.discussion-toc--mobile .discussion-toc-link { padding-top: 12px; padding-bottom: 12px; }
+.discussion-toc--mobile .discussion-toc-shortcut { display: flex; align-items: center; min-height: 44px; }
+.theme--dark .discussion-toc-toggle { color: #75beff; background: #323334; border-color: #4a4e54; }
+@media (min-width: 1000px) {
+ .discussion-layout-toc { display: flex; align-items: stretch; }
+ .discussion-layout-toc > .columns { min-width: 0; }
+ .discussion-sidebar-toc { position: relative; }
+ .discussion-toc--desktop { display: block; position: sticky; top: var(--discussion-toc-top, 65px); margin-top: 20px; margin-bottom: 20px; }
+ .discussion-toc--desktop .discussion-toc-list { max-height: var(--discussion-toc-list-height, calc(100dvh - var(--discussion-toc-top, 65px) - 140px)); }
+ .discussion-toc-mobile { display: none; }
+}
+@media print {
+ .discussion-toc, .discussion-toc-mobile { display: none !important; }
+ .discussion-layout-toc { display: block; }
+}
diff --git a/packages/discussion-toc/frontend/discussion-toc.page.ts b/packages/discussion-toc/frontend/discussion-toc.page.ts
new file mode 100644
index 0000000000..0192325930
--- /dev/null
+++ b/packages/discussion-toc/frontend/discussion-toc.page.ts
@@ -0,0 +1,211 @@
+import './discussion-toc.css';
+
+import { $, addPage, NamedPage } from '@hydrooj/ui-default';
+
+interface Entry {
+ heading: HTMLElement;
+ level: number;
+ text: string;
+ links: HTMLAnchorElement[];
+}
+
+function element(tag: K, className = '', text = '') {
+ const node = document.createElement(tag);
+ node.className = className;
+ node.textContent = text;
+ return node;
+}
+
+function headingEntries(content: HTMLElement): Entry[] {
+ const seen = new Set();
+ return [...content.querySelectorAll('h1,h2,h3,h4,h5,h6')].filter((heading) =>
+ heading.textContent.trim() && !heading.closest('pre,code,.table-of-contents')).map((heading, index) => {
+ if (!heading.id || seen.has(heading.id) || document.getElementById(heading.id) !== heading) {
+ let suffix = index + 1;
+ while (document.getElementById(`discussion-heading-${suffix}`)) suffix++;
+ heading.id = `discussion-heading-${suffix}`;
+ }
+ seen.add(heading.id);
+ return { heading, level: Number(heading.tagName.slice(1)), text: heading.textContent.trim(), links: [] };
+ });
+}
+
+function createDirectory(content: HTMLElement, sidebar: HTMLElement, layout: HTMLElement) {
+ const entries = headingEntries(content);
+ if (entries.length < 2) return () => {};
+ layout.classList.add('discussion-layout-toc');
+ sidebar.classList.add('discussion-sidebar-toc');
+ const start = element('span', 'discussion-toc-target');
+ const end = element('span', 'discussion-toc-target');
+ const markerId = (base: string) => {
+ let id = base;
+ while (document.getElementById(id)) id += '-';
+ return id;
+ };
+ start.id = markerId('discussion-start');
+ end.id = markerId('discussion-end');
+ content.prepend(start);
+ content.append(end);
+ const targets = [start, ...entries.map((entry) => entry.heading), end];
+ for (const target of targets) target.classList.add('discussion-toc-target');
+
+ const mobile = element('details', 'discussion-toc-mobile');
+ const summary = element('summary', 'discussion-toc-toggle', '目录');
+ mobile.append(summary);
+ let active = -1;
+ let frame = 0;
+ const lists: HTMLOListElement[] = [];
+ const offset = () => {
+ const nav = document.querySelector('.nav');
+ return (nav && getComputedStyle(nav).position === 'fixed' ? nav.getBoundingClientRect().height : 0) + 16;
+ };
+ const jump = (target: HTMLElement, push = false) => {
+ mobile.open = false;
+ $('html,body').stop(true);
+ // Instant navigation avoids fetching every lazy image along a long animated scroll.
+ const top = target === start ? 0 : Math.max(0, window.scrollY + target.getBoundingClientRect().top - offset());
+ window.scrollTo({ top, behavior: 'instant' as ScrollBehavior });
+ if (push) {
+ if (!target.hasAttribute('tabindex')) target.tabIndex = -1;
+ target.focus({ preventScroll: true });
+ const hash = `#${encodeURIComponent(target.id)}`;
+ if (location.hash !== hash) history.pushState(history.state, '', hash);
+ }
+ };
+ const makeLink = (target: HTMLElement, text: string, className: string) => {
+ const link = element('a', className, text);
+ link.href = `#${encodeURIComponent(target.id)}`;
+ link.addEventListener('click', (event) => {
+ if (event.button || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
+ event.preventDefault();
+ event.stopPropagation();
+ jump(target, true);
+ });
+ return link;
+ };
+ const makeNavigation = (mobileVersion = false) => {
+ const nav = element('nav', `discussion-toc ${mobileVersion ? 'discussion-toc--mobile' : 'discussion-toc--desktop'}`);
+ nav.setAttribute('aria-label', '文章目录');
+ const title = element('div', 'discussion-toc-title');
+ title.append(element('strong', '', '目录'), element('span', 'discussion-toc-count', `${entries.length} 节`));
+ nav.append(title);
+ const list = element('ol', 'discussion-toc-list');
+ const minLevel = Math.min(...entries.map((entry) => entry.level));
+ for (const entry of entries) {
+ const item = element('li');
+ const link = makeLink(entry.heading, entry.text, 'discussion-toc-link');
+ link.style.setProperty('--toc-depth', String(entry.level - minLevel));
+ link.title = entry.text;
+ entry.links.push(link);
+ item.append(link);
+ list.append(item);
+ }
+ lists.push(list);
+ nav.append(list);
+ const shortcuts = element('div', 'discussion-toc-shortcuts');
+ shortcuts.append(makeLink(start, '回到顶部', 'discussion-toc-shortcut'), makeLink(end, '到正文底部', 'discussion-toc-shortcut'));
+ nav.append(shortcuts);
+ return nav;
+ };
+ const desktop = makeNavigation();
+ sidebar.append(desktop);
+ mobile.append(makeNavigation(true));
+ document.body.append(mobile);
+
+ function update() {
+ frame = 0;
+ if (!content.isConnected) return;
+ const top = offset();
+ layout.style.setProperty('--discussion-toc-top', `${top}px`);
+ const available = window.innerHeight - Math.max(top, desktop.getBoundingClientRect().top) - 120;
+ layout.style.setProperty('--discussion-toc-list-height', `${Math.max(120, available)}px`);
+ let current = 0;
+ for (let i = 0; i < entries.length; i++) {
+ if (entries[i].heading.getBoundingClientRect().top <= top + 8) current = i;
+ else break;
+ }
+ if (active === current) return;
+ if (entries[active]) for (const link of entries[active].links) link.removeAttribute('aria-current');
+ active = current;
+ for (const link of entries[current].links) link.setAttribute('aria-current', 'location');
+ for (const list of lists) {
+ if (!list.clientHeight) continue;
+ const link = list.querySelector('[aria-current]');
+ const box = link.getBoundingClientRect();
+ const viewport = list.getBoundingClientRect();
+ if (box.top < viewport.top || box.bottom > viewport.bottom) list.scrollTop += box.top - viewport.top - list.clientHeight / 3;
+ }
+ }
+ function schedule() {
+ frame ||= requestAnimationFrame(update);
+ }
+ const fragment = (event?: Event) => {
+ const raw = location.hash.slice(1);
+ let decoded = raw;
+ try { decoded = decodeURIComponent(raw); } catch { /* An unrelated malformed hash should not break navigation. */ }
+ const target = targets.find((node) => node.id === raw || node.id === decoded);
+ if (target) {
+ if (event?.type === 'hashchange') event.stopImmediatePropagation();
+ jump(target);
+ }
+ };
+ const closeOutside = (event: PointerEvent) => {
+ if (mobile.open && !mobile.contains(event.target as Node)) mobile.open = false;
+ };
+ const closeOnEscape = (event: KeyboardEvent) => {
+ if (event.key === 'Escape' && mobile.open) {
+ mobile.open = false;
+ summary.focus();
+ }
+ };
+ window.addEventListener('scroll', schedule, { passive: true });
+ window.addEventListener('resize', schedule);
+ window.addEventListener('hashchange', fragment, true);
+ window.addEventListener('popstate', fragment);
+ document.addEventListener('pointerdown', closeOutside);
+ document.addEventListener('keydown', closeOnEscape);
+ const resize = new ResizeObserver(schedule);
+ resize.observe(content);
+ schedule();
+ const initial = requestAnimationFrame(() => fragment());
+ let readyFrame = 0;
+ const pageReady = () => { readyFrame = requestAnimationFrame(() => fragment()); };
+ $(document).on('vjPageFullyInitialized.discussionToc', pageReady);
+ return () => {
+ cancelAnimationFrame(initial);
+ cancelAnimationFrame(readyFrame);
+ cancelAnimationFrame(frame);
+ resize.disconnect();
+ window.removeEventListener('scroll', schedule);
+ window.removeEventListener('resize', schedule);
+ window.removeEventListener('hashchange', fragment, true);
+ window.removeEventListener('popstate', fragment);
+ document.removeEventListener('pointerdown', closeOutside);
+ document.removeEventListener('keydown', closeOnEscape);
+ $(document).off('vjPageFullyInitialized.discussionToc', pageReady);
+ mobile.remove();
+ desktop.remove();
+ start.remove();
+ end.remove();
+ layout.classList.remove('discussion-layout-toc');
+ sidebar.classList.remove('discussion-sidebar-toc');
+ for (const entry of entries) entry.heading.classList.remove('discussion-toc-target');
+ };
+}
+
+let dispose: (() => void) | undefined;
+function initialize() {
+ dispose?.();
+ const content = document.querySelector('.topic__content');
+ const sidebar = document.querySelector('[data-discussion-sidebar]');
+ const layout = document.querySelector('[data-discussion-layout]');
+ if (content && sidebar && layout) dispose = createDirectory(content, sidebar, layout);
+}
+
+addPage(new NamedPage('discussion_detail', () => {
+ initialize();
+ $(document).off('vjContentNew.discussionToc').on('vjContentNew.discussionToc', initialize);
+ $(document).off('vjContentRemove.discussionToc').on('vjContentRemove.discussionToc', (event) => {
+ if ((event.target as Node).contains(document.querySelector('.topic__content'))) dispose?.();
+ });
+}));
diff --git a/packages/discussion-toc/index.ts b/packages/discussion-toc/index.ts
new file mode 100644
index 0000000000..38c3026970
--- /dev/null
+++ b/packages/discussion-toc/index.ts
@@ -0,0 +1,3 @@
+// The default UI bundles this addon's frontend assets at startup.
+export const name = 'discussion-toc';
+export function apply() {}
diff --git a/packages/discussion-toc/package.json b/packages/discussion-toc/package.json
new file mode 100644
index 0000000000..688d19c294
--- /dev/null
+++ b/packages/discussion-toc/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "@hgnuoj/discussion-toc",
+ "version": "1.0.0",
+ "private": true,
+ "main": "index.ts",
+ "license": "AGPL-3.0-only",
+ "hydro": {
+ "cli": false
+ },
+ "peerDependencies": {
+ "@hydrooj/ui-default": "workspace:^"
+ }
+}
diff --git a/packages/hydrojudge/src/config.ts b/packages/hydrojudge/src/config.ts
index 6c5b7617f8..75a8e28bb0 100644
--- a/packages/hydrojudge/src/config.ts
+++ b/packages/hydrojudge/src/config.ts
@@ -23,9 +23,9 @@ export const JudgeSettings = Schema.object({
testcases_max: Schema.number().default(100).min(1).step(1),
total_time_limit: Schema.number().default(60).min(1),
processLimit: Schema.number().default(32).min(1).step(1),
- parallelism: Schema.number().default(2).min(1).step(1),
- concurrency: Schema.number(),
- singleTaskParallelism: Schema.number().default(2).min(1).step(1),
+ parallelism: Schema.number().default(8).min(1).step(1),
+ concurrency: Schema.number().default(4),
+ singleTaskParallelism: Schema.number().default(4).min(1).step(1),
rerun: Schema.number().description('Re-Run testcase if time-limit-exceeded (max per submission)').default(0).min(0).step(1),
rate: Schema.number().default(1),
env: Schema.string().default(defaultEnv).role('textarea'),
diff --git a/packages/hydrojudge/src/index.ts b/packages/hydrojudge/src/index.ts
index c14c9ebd2a..98f5607f7b 100644
--- a/packages/hydrojudge/src/index.ts
+++ b/packages/hydrojudge/src/index.ts
@@ -5,7 +5,8 @@ export const Config = JudgeSettings;
export function apply(ctx: Context, config: ReturnType) {
overrideConfig(config);
- if (process.env.NODE_APP_INSTANCE !== '0') return;
+ // CLI processes exit after their command; only the running server should consume tasks.
+ if (process.env.HYDRO_CLI || process.env.NODE_APP_INSTANCE !== '0') return;
// eslint-disable-next-line consistent-return
if (!config.disable) return require('./hosts/builtin').apply(ctx);
}
diff --git a/packages/hydrooj/locales/zh.yaml b/packages/hydrooj/locales/zh.yaml
index dd1ac330d7..6e0c2cc961 100644
--- a/packages/hydrooj/locales/zh.yaml
+++ b/packages/hydrooj/locales/zh.yaml
@@ -1,11 +1,11 @@
__flag: 🇨🇳
__id: zh
-__interface: yes
+__interface: true
__langname: 简体中文
'"{data}" copied to clipboard!': “{data}”已复制到剪贴板!
-'{0} {1} delete your discussion reply {2} in "{3}"({4}).': '{0} {1} 从讨论 {3}({4}) 删除了你的回复 {2}。'
+'{0} {1} delete your discussion reply {2} in "{3}"({4}).': '{0} {1} 从公告 {3}({4}) 删除了你的回复 {2}。'
'{0} comments': '{0} 条评论'
-'{0} discussions': '{0} 条讨论'
+'{0} discussions': '{0} 条公告'
'{0} is a moderator of this domain.': '{0}是这个域的管理者之一。'
'{0} limit exceeded (limit: {2} operations in {1} seconds).': '{0} 超过频率限制。限制:{1} 秒内最多 {2} 次操作。'
'{0} problems': '{0} 道题'
@@ -15,35 +15,36 @@ __langname: 简体中文
'{0}: Permissions': '{0}: 权限'
'{0}: Roles': '{0}: 角色'
'{0}: Users': '{0}: 用户'
-'# My Submissions': '我的递交数'
-'# Submissions': '递交数'
-'↓ # Comments': '↓ 评论数'
-'↓ # Enrollees': '↓ 参与人数'
-'↓ # Likes': '↓ 赞数'
-'↓ # Stars': '↓ 收藏数'
-'↓ Create Time': '↓ 创建时间'
-'↓ Update Time': '↓ 更新时间'
-'A domain ID cannot be changed after creation. It is supposed to be:': '创建后将无法更改 ID。ID 必须满足以下条件:'
-'Copy "{data}" failed :(': '复制“{data}”失败 :('
-'Copy failed :(': '复制失败 :('
+'# My Submissions': 我的递交数
+'# Submissions': 递交数
+'↓ # Comments': ↓ 评论数
+'↓ # Enrollees': ↓ 参与人数
+'↓ # Likes': ↓ 赞数
+'↓ # Stars': ↓ 收藏数
+↓ Create Time: ↓ 创建时间
+↓ Update Time: ↓ 更新时间
+'A domain ID cannot be changed after creation. It is supposed to be:': 创建后将无法更改 ID。ID 必须满足以下条件:
+Copy "{data}" failed :(: 复制“{data}”失败 :(
+Copy failed :(: 复制失败 :(
'Current dataset: {0}': '当前测试数据: {0}'
-'Discussion: Terms Of Service': 讨论区服务条款
-'First Blood Notice\n{0} solved problem {1} ({2})': '题目一血提示\n{0} 解决了题目 {1} ({2})'
-'Format: category 1, sub category 1.1, sub category 1.2, ..., sub category 1.x, ..., category n, sub category n.1, sub category n.2, ..., sub category n.m, ...': 格式:分类 1, 子分类 1.1, 子分类 1.2, ..., 子分类 1.x, ..., 分类 n, 子分类 n.1, 子分类 n.2, ..., 子分类 n.m, ...
-'Format: one group per line, CSV: groupName,uid1,uid2,...': '格式:每行一个小组,CSV:组名,UID1,UID2,...'
-'Join {0}': '加入 {0}'
+'Discussion: Terms Of Service': 公告区服务条款
+First Blood Notice\n{0} solved problem {1} ({2}): 题目一血提示\n{0} 解决了题目 {1} ({2})
+? 'Format: category 1, sub category 1.1, sub category 1.2, ..., sub category 1.x, ..., category n, sub category n.1, sub category n.2, ..., sub category n.m, ...'
+: 格式:分类 1, 子分类 1.1, 子分类 1.2, ..., 子分类 1.x, ..., 分类 n, 子分类 n.1, 子分类 n.2, ..., 子分类 n.m, ...
+'Format: one group per line, CSV: groupName,uid1,uid2,...': 格式:每行一个小组,CSV:组名,UID1,UID2,...
+Join {0}: 加入 {0}
'No': 否
'Note: Problem title may not be hidden.': 注意:题目标题可能不会被隐藏。
'On line {0}: Read {1}, expect {2}.': 第 {0} 行的答案错误,读取到 {1},但期望 {2}。
'Or upload a file:': 或者上传一个文件:
'Original score: {0}': '原得分: {0}'
-'Role {1} already exists in domain {0}.': '域 {0} 中已存在角色 {1}。'
+Role {1} already exists in domain {0}.: 域 {0} 中已存在角色 {1}。
'Solved {0} problems, RP: {1} (No. {2})': '解决了 {0} 道题目,RP: {1} (No. {2})'
-'The value `{1}` of {0} already exists.': '{0} 的值 `{1}` 已经存在。'
+The value `{1}` of {0} already exists.: '{0} 的值 `{1}` 已经存在。'
'Yes': 是
-"Effects only when Difficulty is not 'Use algorithm calculated'.": 仅当难度不为“使用算法计算”时才起效。
-"Split by ',' '.'": 由“, ”或“,”分隔。
-"What's file?": 什么是文件?
+Effects only when Difficulty is not 'Use algorithm calculated'.: 仅当难度不为“使用算法计算”时才起效。
+Split by ',' '.': 由“, ”或“,”分隔。
+What's file?: 什么是文件?
(All Problems): (所有题目)
(None): (无)
(Not changed): 未更改
@@ -67,8 +68,8 @@ Add new data: 添加新数据
Add User: 添加用户
Add: 添加
Additional File: 附加文件
-Admin {0} delete your discussion "{1}".: 管理员 {0} 删除了你的讨论 "{1}"。
-Admin {0} delete your discussion tail reply {1} in "{2}"({3}).: 管理员 {0} 从讨论 {2}({3}) 中删除了你的楼中楼回复 {1}。
+Admin {0} delete your discussion "{1}".: 管理员 {0} 删除了你的公告 "{1}"。
+Admin {0} delete your discussion tail reply {1} in "{2}"({3}).: 管理员 {0} 从公告 {2}({3}) 中删除了你的楼中楼回复 {1}。
All {0} Contests: 所有 {0} 比赛
All Contests: 所有比赛
All Homeworks: 所有作业
@@ -191,13 +192,13 @@ Copy: 复制
Copyright Complaint: 版权申诉
CPU Info: CPU信息
Create a contest: 创建一个比赛
-Create a Discussion: 创建一个讨论
+Create a Discussion: 创建一个公告
Create a problem: 创建一个题目
Create Contest: 创建比赛
Create contests: 创建比赛
-Create Discussion in {0}: 在 {0} 下创建讨论
-Create Discussion: 创建讨论
-Create discussions: 创建讨论
+Create Discussion in {0}: 在 {0} 下创建公告
+Create Discussion: 创建公告
+Create discussions: 创建公告
Create Domain: 创建域
Create homework: 创建作业
Create Homework: 创建作业
@@ -231,11 +232,11 @@ Default display language: 默认显示语言
Default Privilege: 用户默认全站权限
Delay: 延迟
Delete a user: 删除用户
-Delete discussion replies of own discussion: 删除自己讨论中的回复
-Delete discussion replies: 删除讨论回复
-Delete discussions: 删除讨论
-Delete own discussion replies: 删除讨论中自己的回复
-Delete own discussions: 删除自己的讨论
+Delete discussion replies of own discussion: 删除自己公告中的回复
+Delete discussion replies: 删除公告回复
+Delete discussions: 删除公告
+Delete own discussion replies: 删除公告中自己的回复
+Delete own discussions: 删除自己的公告
Delete own problem solution replies: 删除题解中自己的回复
Delete own problem solutions: 删除自己的题解
Delete problem solution replies: 删除题解的回复
@@ -252,20 +253,20 @@ Difficulty by algorithm: 算法计算的难度
Difficulty displayed: 显示的难度
Difficulty: 难度
Disabled: 关闭
-Discussion {1} not found.: 讨论 {1} 不存在。
-Discussion category {1} already exists.: 讨论分类 {1} 已经存在。
-Discussion category {1} not found.: 讨论分类 {1} 不存在。
-Discussion node {1} already exists.: 讨论节点 {1} 已经存在。
-Discussion node {1} not found.: 讨论节点 {1} 不存在。
-Discussion Nodes: 讨论节点
-discussion_create: 创建讨论
-discussion_detail: 讨论详情
-discussion_edit: 编辑讨论
-discussion_main: 讨论
-discussion_node: 讨论
-Discussion: 讨论
-Discussions per page: 每页展示的讨论数量
-Discussions: 讨论
+Discussion {1} not found.: 公告 {1} 不存在。
+Discussion category {1} already exists.: 公告分类 {1} 已经存在。
+Discussion category {1} not found.: 公告分类 {1} 不存在。
+Discussion node {1} already exists.: 公告节点 {1} 已经存在。
+Discussion node {1} not found.: 公告节点 {1} 不存在。
+Discussion Nodes: 公告节点
+discussion_create: 创建公告
+discussion_detail: 公告详情
+discussion_edit: 编辑公告
+discussion_main: 公告
+discussion_node: 公告
+Discussion: 公告
+Discussions per page: 每页展示的公告数量
+Discussions: 公告
Display name {1} you want to set is used by others.: 您想要设置的显示名 {1} 已经被其他人使用了。
Display Name: 显示名
display_name: 显示名
@@ -278,7 +279,7 @@ Domain ID cannot be changed once the domain is created.: 在创建后不能更
Domain ID: 域 ID
domain_create: 创建域
domain_dashboard: 管理域
-domain_discussion: 讨论节点
+domain_discussion: 公告节点
domain_edit: 编辑域资料
domain_file: 我的文件
domain_group: 管理小组
@@ -303,15 +304,16 @@ Edit any contests: 修改任意的比赛
Edit any homework: 修改任意的作业
Edit Contest: 编辑比赛
Edit description of this domain: 修改此域描述
-Edit discussion replies of own discussion: 修改自己讨论中的回复
-Edit discussion replies: 修改讨论的回复
-Edit discussions: 修改讨论
+Edit discussion replies of own discussion: 修改自己公告中的回复
+Edit discussion replies: 修改公告的回复
+Edit discussions: 修改公告
Edit domain settings: 编辑域设置
+Edit Wiki articles: 编辑 Wiki 文章
Edit Domain: 编辑域
Edit Homework: 编辑作业
Edit own contests: 修改自己的比赛
-Edit own discussion replies: 修改讨论中自己的回复
-Edit own discussions: 修改自己的讨论
+Edit own discussion replies: 修改公告中自己的回复
+Edit own discussions: 修改自己的公告
Edit own homework: 修改自己的作业
Edit own problem solution replies: 修改题解中自己的回复
Edit own problem solutions: 修改自己的题解
@@ -370,7 +372,7 @@ Hidden: 隐藏
Hide all tags: 隐藏所有标签
Hide categorical tags: 隐藏分类标签
Hide Selected: 隐藏选中
-Highlight discussions: 高亮讨论
+Highlight discussions: 高亮公告
highlight: 高亮
Highlight: 高亮
Hint: 提示
@@ -419,7 +421,7 @@ In following homework: 在以下作业中
In following training plans: 在下列训练计划中
In Progress: 进行中
Information: 信息
-Init Discussion Nodes: 初始化讨论结点
+Init Discussion Nodes: 初始化公告结点
Initialize: 初始化
Inline codes: 行内代码
Inline formulas: 行内公式
@@ -428,7 +430,10 @@ Insert Code: 插入代码
Insert Image: 插入图像
Installed Modules: 已安装的模块
Instant Rendering: 即时渲染
-Instead of copying the test data directly, the test data of the copied problems will be linked to the test data of the source problems (called the source test data). Thus, the copied problems can observe the changes in the source test data. The permissions of the test data of the copied problems follow the source test data, e.g., you still might not download them but the judges can. By uploading some new test data, the link will be broken and the new test data will be used.: 虽然测试数据不会被复制,但是系统会将题目的测试数据链接到原题。因此在原题的数据被改动的时候,复制后的题目的数据也会同时改动。链接后的测试数据的权限以原题为准,比如您可能依旧无法下载数据,但是评测机可以。在题目设置页面中可以通过上传新的测试数据的方式,这个数据链接会被删除,以后将使用您的新测试数据。
+? Instead of copying the test data directly, the test data of the copied problems will be linked to the test data of the source problems (called the source test data). Thus, the copied problems can observe
+ the changes in the source test data. The permissions of the test data of the copied problems follow the source test data, e.g., you still might not download them but the judges can. By uploading some
+ new test data, the link will be broken and the new test data will be used.
+: 虽然测试数据不会被复制,但是系统会将题目的测试数据链接到原题。因此在原题的数据被改动的时候,复制后的题目的数据也会同时改动。链接后的测试数据的权限以原题为准,比如您可能依旧无法下载数据,但是评测机可以。在题目设置页面中可以通过上传新的测试数据的方式,这个数据链接会被删除,以后将使用您的新测试数据。
Introduce must not exceed 500 characters and it will be shown in the list view.: 简介不能超过 500 个字符,将显示在列表页面中。
Introduce: 简介
Invalid password for user {0}.: 用户 {0} 的密码错误。
@@ -461,11 +466,11 @@ List View: 列表视图
Live: 正在进行
Live...: 正在进行…
Location: 位置
-Lock discussions: 锁定讨论
+Lock discussions: 锁定公告
Lock Topic: 锁定主题
Login to Attend Contest: 登录后参加比赛
Login to Claim Homework: 登录后认领作业
-Login to Create a Discussion: 登录后创建讨论
+Login to Create a Discussion: 登录后创建公告
Login to join training plan: 登录以参加训练计划
Login to Submit: 登录后递交
Login: 登录
@@ -496,7 +501,7 @@ Allow Team: 允许团队
Allow team participation: 允许团队参赛
Choose how you want to participate in this contest.: 选择你参加本次比赛的方式。
Create a Team: 创建队伍
-'Create a team, invite teammates by their username, then choose "Team Participation" when attending an allow-team contest.': 创建队伍,按用户名邀请队友,之后在报名允许团队的比赛时选择“团队参赛”。
+Create a team, invite teammates by their username, then choose "Team Participation" when attending an allow-team contest.: 创建队伍,按用户名邀请队友,之后在报名允许团队的比赛时选择“团队参赛”。
How It Works: 使用说明
Invitation code: 邀请码
Invitation code is required.: 必须填写邀请码。
@@ -522,7 +527,7 @@ Team participation is not allowed for this contest.: 该比赛不允许团队参
Teams let multiple users participate in a contest together, sharing one set of submissions.: 队伍允许多名用户共同参加比赛,共享同一份提交记录。
You are not in any team.: 你还没有加入任何队伍。
You are not in any team yet. Create one from the panel on the right, or ask a teammate to invite you by your username.: 你还没有加入任何队伍。在右侧面板创建一个,或请队友按你的用户名邀请你。
-'You have {0} pending team invite(s)': '你有 {0} 个待处理的队伍邀请'
+You have {0} pending team invite(s): 你有 {0} 个待处理的队伍邀请
Max pretest count per minute: 每分钟自测数量限制
Max submission count per minute: 每分钟提交数量限制
Max total file size for user: 单用户最大总文件大小
@@ -552,10 +557,10 @@ New Training Plan: 新训练计划
New: 创建
No comments so far...: 目前还没有评论...
No dataset at present.: 暂无测试数据。
-No discussion yet...: 目前没有讨论…
+No discussion yet...: 目前没有公告…
No Permission to Attend Contest: 您没有权限参加比赛
No Permission to Claim Homework: 您没有权限认领作业
-No Permission to Create a Discussion: 您没有权限创建讨论
+No Permission to Create a Discussion: 您没有权限创建公告
No Permission to Submit: 您没有权限递交
No problem.: 没有题目。
No solutions so far...: 目前还没有题解...
@@ -572,7 +577,7 @@ Not started with a number: 不以数字开头
Not wrapped with space: 两侧不含空格
Numeric PID: 数字题号
Oh, the user doesn't have any contributions!: 啊哦,这个用户还没贡献过题目~
-Oh, the user hasn't created any discussions yet!: 这个用户还没有发布过讨论
+Oh, the user hasn't created any discussions yet!: 这个用户还没有发布过公告
Oh, the user hasn't submitted yet!: 这个用户还没有交过题 _(:зゝ∠)_
Oh, there are no tasks that match the filter!: 喔,目前没有符合过滤条件的任务。
Oh, there is no clarification!: 喔,目前没有答疑!
@@ -612,7 +617,7 @@ Path {0} not found.: 路径 {0} 不存在。
Peak Memory: 峰值内存
Penalty (Minutes): 罚时(分钟)
perm_contest: 比赛
-perm_discussion: 讨论
+perm_discussion: 公告
perm_general: 一般
perm_homework: 作业
perm_problem_solution: 题解
@@ -625,7 +630,7 @@ Permissions: 权限
Phone: 手机号
Pick a problem randomly based on the current filter.: 根据当前过滤条件随机选择一道题
pid: 题目 ID
-Pin discussions: 置顶讨论
+Pin discussions: 置顶公告
Pin training plans: 置顶训练计划
Plan: 计划
Please attend contest to see the problems.: 请参加比赛来查看题目。
@@ -699,7 +704,7 @@ Registered at: 注册于
Rejudge problems: 重测题目
Rejudge records: 重测记录
Rejudge: 重测
-Related Discussions: 相关讨论
+Related Discussions: 相关公告
Related: 相关
Relax and try to remember your password.: 放松,尝试回忆您设置的密码。
Remember me: 记住我
@@ -708,7 +713,7 @@ Remove this data: 移除这组数据
Remove: 移除
Repeat Password: 重复密码
Replies per page: 每页展示的回复数量
-Reply discussions: 回复讨论
+Reply discussions: 回复公告
Reply problem solutions: 回复题解
reply: 回复
Reply: 回复
@@ -745,7 +750,7 @@ Secret (visible to admins): 保密(对管理员可见)
Secret: 保密
Section: 章节
Security: 安全
-Select a node to create discussion.: 选择一个节点来发表讨论。
+Select a node to create discussion.: 选择一个节点来发表公告。
Select a role: 选择一个角色
Select Category: 选择标签
Select User: 选择用户
@@ -800,7 +805,7 @@ Sort by: 排序
Source type: 来源类型
Split View: 分屏预览
Standard answer longer than user output.: 答案比您的输出长。
-Star Topic: 收藏讨论
+Star Topic: 收藏公告
Star: 收藏
Starred Problems: 收藏的题目
Start at: 开始于
@@ -831,9 +836,10 @@ Terms of Service: 服务条款
Test data comes from: 测试数据来自
Testdata Config: 测试数据配置
Text: 文本
-The discussion is locked, you can not reply anymore.: 此讨论已经锁定,您不能再回复。
+The discussion is locked, you can not reply anymore.: 此公告已经锁定,您不能再回复。
The homework's deadline is due but in extension. You can still submit for this problem but your score will be penalized.: 作业已超过截止时间,但仍在延期时间内。您递交题目将无法获得全部分数。
-The invitation code to enter to successfully join the domain. You can only use letters and numbers in the code and it should not be longer than 64 characters.: 加入此域的邀请码。您只能使用字母和数字,并且不能长于 64 个字符。
+? The invitation code to enter to successfully join the domain. You can only use letters and numbers in the code and it should not be longer than 64 characters.
+: 加入此域的邀请码。您只能使用字母和数字,并且不能长于 64 个字符。
The invitation code you provided is invalid.: 您提供的邀请码无效。
The link is either invalid or expired.: 加域链接无效或已过期。
The link will be expired at {0}: 链接将于 {0} 过期
@@ -933,7 +939,7 @@ View contest scoreboard: 查看比赛成绩表
View Contest: 查看比赛
View contests: 查看比赛
View Details: 查看详情
-View discussions: 查看讨论
+View discussions: 查看公告
View domain user private info: 显示域中用户的私有信息
View hidden contest submission status and scoreboard: 查看隐藏的比赛递交状态和成绩表
View hidden homework submission status and scoreboard: 查看隐藏的作业递交状态和成绩表
@@ -941,7 +947,7 @@ View hidden problems: 查看隐藏的题目
View homework scoreboard: 查看作业成绩表
View homework: 查看作业
View Homework: 查看作业
-View or create discussion: 查看与发表讨论
+View or create discussion: 查看与发表公告
View or submit solution: 查看与发表题解
View Owned Problems: 查看自己的题目
View Owned Training Plans: 查看自己的训练计划
@@ -969,9 +975,12 @@ What's this?: 这是什么?
Whether to show tags in the problem list.: 是否在题目列表中显示题目的标签。
wiki_about: 关于
Will be used as the domain icon.: 将被用作系统图标。
-With this feature, you can copy problems that you can view from a domain to some other domain. Their title, content, tags and categories will be copied. However, their test data are not copied directly.: 您可以通过这个功能将某域下您能查看的题目复制到其它域中,题目的标题、描述、标签与分类将被复制过来。但是测试数据不会被直接复制。
-With this feature, you can import problems that you can view from a site to here. Their title, content, tags and categories will be imported. However, their test data are not copied directly.: 您可以通过这个功能将其他 OJ 的题目导入到本站。题目的标题、题面、标签和分类将会被直接导入,测试数据将会在后台自动导入。
-With this feature, you can import problems that you can view from a site to here. Their title, content, tags and categories will be imported.: 您可以通过这个功能将其他 OJ 的题目导入到本站。题目的标题、题面、标签和分类都将会被自动导入。
+? With this feature, you can copy problems that you can view from a domain to some other domain. Their title, content, tags and categories will be copied. However, their test data are not copied directly.
+: 您可以通过这个功能将某域下您能查看的题目复制到其它域中,题目的标题、描述、标签与分类将被复制过来。但是测试数据不会被直接复制。
+? With this feature, you can import problems that you can view from a site to here. Their title, content, tags and categories will be imported. However, their test data are not copied directly.
+: 您可以通过这个功能将其他 OJ 的题目导入到本站。题目的标题、题面、标签和分类将会被直接导入,测试数据将会在后台自动导入。
+? With this feature, you can import problems that you can view from a site to here. Their title, content, tags and categories will be imported.
+: 您可以通过这个功能将其他 OJ 的题目导入到本站。题目的标题、题面、标签和分类都将会被自动导入。
Write Your Comment: 发表您的评论
Write Your Solution: 发表您的题解
WYSIWYG: 所见即所得
@@ -979,7 +988,8 @@ Year: 年
You are banned by the domain moderator.: 您被该域的管理员封禁。
You are not allowed to join domain {0}. {1}: 您无法加入 {0}。{1}
You can create your own training plans and share them with others.: 您可以创建您自己的训练计划并且与他人分享。
-You cannot submit for this problem because the contest is ended. You can click "Open in Problem Set" to view this problem in normal mode.: 该比赛已结束,您无法在比赛模式下递交该题目。您可以点击“在题库中打开”以普通模式查看和递交本题。
+? You cannot submit for this problem because the contest is ended. You can click "Open in Problem Set" to view this problem in normal mode.
+: 该比赛已结束,您无法在比赛模式下递交该题目。您可以点击“在题库中打开”以普通模式查看和递交本题。
You cannot submit for this problem because the homework's deadline is due.: 作业已超过截止时间,您无法递交本题目。
You cannot visit this domain.: 您不能访问此域。
You don't have the required permission ({0}) in this domain.: 您在该域中无相应权限 ({0})。
@@ -998,3 +1008,9 @@ You've already claimed this homework.: 您已认领过该作业。
You've already voted.: 您已经投过票。
Your permission: 您的权限
Your role: 您的角色
+courses: 课程
+Stu_Name: 姓名
+Stu_Class: 班级
+Stu_Stuid: 学号
+class: 班级
+manage_student_import: 学生批量导入
diff --git a/packages/hydrooj/src/entry/worker.ts b/packages/hydrooj/src/entry/worker.ts
index cc9abc3aff..6787b34864 100644
--- a/packages/hydrooj/src/entry/worker.ts
+++ b/packages/hydrooj/src/entry/worker.ts
@@ -60,12 +60,16 @@ export async function apply(ctx: Context) {
resolve(c);
});
});
- const loadDir = async (dir: string) => Promise.all((await fs.readdir(dir)).filter((i) => i.endsWith('.ts'))
- .map((h) => ctx.loader.reloadPlugin(path.resolve(dir, h), '')));
+ const loadDir = async (dir: string, includeJavaScript = false) => {
+ const entries = await fs.readdir(dir);
+ const files = entries.filter((i) => i.endsWith('.ts')
+ || (includeJavaScript && i.endsWith('.js') && !entries.includes(`${i.slice(0, -3)}.ts`)));
+ return Promise.all(files.map((h) => ctx.loader.reloadPlugin(path.resolve(dir, h), '')));
+ };
await loadDir(path.resolve(__dirname, '..', 'handler'));
await ctx.plugin(require('../service/migration').default);
await addon(pending, fail, ctx);
- await loadDir(path.resolve(__dirname, '..', 'script'));
+ await loadDir(path.resolve(__dirname, '..', 'script'), true);
await ctx.parallel('app/started');
if (process.env.NODE_APP_INSTANCE === '0') {
const staticDir = path.join(os.homedir(), '.hydro/static');
diff --git a/packages/hydrooj/src/handler/contest.ts b/packages/hydrooj/src/handler/contest.ts
index 776841d7ec..560a0e9188 100644
--- a/packages/hydrooj/src/handler/contest.ts
+++ b/packages/hydrooj/src/handler/contest.ts
@@ -1173,9 +1173,8 @@ export async function apply(ctx: Context) {
].concat(
tdoc.pids.map((i, idx) => `@p ${pid(idx)},${escape(pdict[i]?.title || 'Unknown Problem')},20,0`),
teams.map((i, idx) => {
- const showName = this.user.hasPerm(PERM.PERM_VIEW_USER_PRIVATE_INFO) && udict[i.uid].displayName
- ? udict[i.uid].displayName : udict[i.uid].uname;
- const displayName = `${i.rank ? '*' : ''}${escape(udict[i.uid].school || unknownSchool)}-${escape(showName)}`;
+ const showName = udict[i.uid].name || udict[i.uid].uname;
+ const displayName = `${i.rank ? '*' : ''}${escape(udict[i.uid].class || unknownSchool)}-${escape(showName)}`;
return `@t ${idx + 1},0,1,"${displayName}"`;
}),
submissions,
diff --git a/packages/hydrooj/src/handler/discussion.ts b/packages/hydrooj/src/handler/discussion.ts
index 44667e6aec..83097df823 100644
--- a/packages/hydrooj/src/handler/discussion.ts
+++ b/packages/hydrooj/src/handler/discussion.ts
@@ -186,12 +186,10 @@ class DiscussionDetailHandler extends DiscussionHandler {
reactions[drdoc._id.toHexString()] = reaction;
})));
const udict = await user.getList(domainId, uids);
- if (!dsdoc?.view && this.user.hasPriv(PRIV.PRIV_USER_PROFILE)) {
- await Promise.all([
- discussion.inc(domainId, did, 'views', 1),
- discussion.setStatus(domainId, did, this.user._id, { view: true }),
- ]);
- }
+ await Promise.all([
+ discussion.inc(domainId, did, 'views', 1),
+ discussion.setStatus(domainId, did, this.user._id, { view: true }),
+ ]);
const path = [
['Hydro', 'homepage'],
['discussion_main', 'discussion_main'],
diff --git a/packages/hydrooj/src/handler/domain.ts b/packages/hydrooj/src/handler/domain.ts
index 40fc1f373c..32040f35e3 100644
--- a/packages/hydrooj/src/handler/domain.ts
+++ b/packages/hydrooj/src/handler/domain.ts
@@ -423,6 +423,22 @@ class DomainSearchHandler extends Handler {
}
}
+class CourseHandler extends Handler {
+ async get() {
+ const domains: any[] = await domain.getMulti({ _id: { $ne: 'system' }, publicToCourses: { $eq: true } }).toArray();
+ const uDocs: any = {};
+ for await (const d of domains) {
+ uDocs[d.owner] = await user.getById('system', d.owner);
+ d['users'] = await domain.getMultiUserInDomain(d._id, { join: true }).count();
+ }
+ this.response.template = 'courses_main.html';
+ this.response.body = {
+ domains,
+ uDocs,
+ };
+ }
+}
+
export const DomainApi = {
domain: Query(
Schema.object({
@@ -477,6 +493,7 @@ declare module '@hydrooj/framework' {
}
export async function apply(ctx: Context) {
+ ctx.Route('courses', '/courses', CourseHandler);
ctx.Route('ranking', '/ranking', DomainRankHandler, PERM.PERM_VIEW_RANKING);
ctx.Route('domain_dashboard', '/domain/dashboard', DomainDashboardHandler);
ctx.Route('domain_edit', '/domain/edit', DomainEditHandler);
diff --git a/packages/hydrooj/src/handler/home.ts b/packages/hydrooj/src/handler/home.ts
index 7b221c2515..444f452d4c 100644
--- a/packages/hydrooj/src/handler/home.ts
+++ b/packages/hydrooj/src/handler/home.ts
@@ -627,7 +627,7 @@ export function apply(ctx: Context) {
ctx.Route('home_avatar', '/home/avatar', HomeAvatarHandler, PRIV.PRIV_USER_PROFILE);
ctx.Route('home_domain', '/home/domain', HomeDomainHandler, PRIV.PRIV_USER_PROFILE);
ctx.Route('home_domain_create', '/home/domain/create', HomeDomainCreateHandler, PRIV.PRIV_CREATE_DOMAIN);
- ctx.Route('home_messages', '/home/messages', HomeMessagesHandler, PRIV.PRIV_USER_PROFILE);
+ if (system.get('server.message')) ctx.Route('home_messages', '/home/messages', HomeMessagesHandler, PRIV.PRIV_USER_PROFILE);
async function notifyMessage(uid: number[], mdoc: any, h) {
const udoc = (await user.getById('system', mdoc.from))!;
@@ -655,7 +655,7 @@ export function apply(ctx: Context) {
});
ctx.on('subscription/subscribe', (channel, udoc) => { // eslint-disable-line consistent-return
- if (channel === 'message' && udoc.hasPriv(PRIV.PRIV_USER_PROFILE)) {
+ if (system.get('server.message') && channel === 'message' && udoc.hasPriv(PRIV.PRIV_USER_PROFILE)) {
return {
ok: true,
channel: `message:${udoc._id}`,
diff --git a/packages/hydrooj/src/handler/homework.ts b/packages/hydrooj/src/handler/homework.ts
index 78b31dec36..b3bb216e87 100644
--- a/packages/hydrooj/src/handler/homework.ts
+++ b/packages/hydrooj/src/handler/homework.ts
@@ -155,7 +155,7 @@ class HomeworkEditHandler extends Handler {
? Math.round(
(tdoc.endAt.getTime() - tdoc.penaltySince.getTime()) / (Time.day / 100),
) / 100
- : 1;
+ : 0;
const beginAt = tid
? moment(tdoc.beginAt).tz(this.user.timeZone)
: moment().add(1, 'day').tz(this.user.timeZone).hour(0).minute(0).millisecond(0);
diff --git a/packages/hydrooj/src/handler/manage.ts b/packages/hydrooj/src/handler/manage.ts
index 147688fa86..72ff0a50d9 100644
--- a/packages/hydrooj/src/handler/manage.ts
+++ b/packages/hydrooj/src/handler/manage.ts
@@ -11,6 +11,7 @@ import { PRIV, STATUS } from '../model/builtin';
import domain from '../model/domain';
import record from '../model/record';
import * as setting from '../model/setting';
+import StudentModel, { validateStudentInfo } from '../model/stuinfo';
import system from '../model/system';
import user from '../model/user';
import {
@@ -308,6 +309,66 @@ class SystemUserImportHandler extends SystemHandler {
this.response.body.messages = messages;
}
}
+
+class SystemStudentImportHandler extends SystemHandler {
+ async get() {
+ this.response.body.users = [];
+ this.response.template = 'manage_student_import.html';
+ }
+
+ @param('students', Types.Content)
+ @param('draft', Types.Boolean)
+ async post(domainId: string, students: string, draft: boolean) {
+ const udocs = [];
+ const messages: string[] = [];
+ let created = 0;
+ let errors = 0;
+ const seenMail = new Set();
+ const seenName = new Set();
+ const seenId = new Set();
+ for (const [i, line] of students.split('\n').entries()) {
+ if (!line.trim()) continue;
+ const [email, username, password, realname, classname, stuid] = line.split(line.includes('\t') ? '\t' : ',').map((v) => v.trim());
+ try {
+ if (!email || !Types.Email[1](email)) throw new ValidationError('email');
+ if (!username || !Types.Username[1](username)) throw new ValidationError('username');
+ if (!password || !Types.Password[1](password)) throw new ValidationError('password');
+ if (!realname || !classname || !stuid) throw new ValidationError('student');
+ validateStudentInfo({ name: realname, class: classname, stuid });
+ const mailKey = user._handleMailLower(email);
+ const nameKey = username.toLowerCase();
+ if (seenMail.has(mailKey) || await user.getByEmail('system', email)) throw new ValidationError('email', '', 'Already exists');
+ if (seenName.has(nameKey) || await user.getByUname('system', username)) throw new ValidationError('username', '', 'Already exists');
+ if (seenId.has(stuid) || await StudentModel.getStuInfoByStuId(stuid)) throw new ValidationError('stuid', '', 'Already exists');
+ seenMail.add(mailKey);
+ seenName.add(nameKey);
+ seenId.add(stuid);
+ udocs.push({ email, username, password, realname, classname, stuid });
+ } catch (e) {
+ messages.push(`Line ${i + 1}: ${e.message} ${e.params || ''}`);
+ errors++;
+ }
+ }
+ messages.push(`${udocs.length} students found.`);
+ if (!draft) {
+ for (const item of udocs) {
+ try {
+ await StudentModel.createAccount(item.email, item.username, item.password, {
+ name: item.realname, class: item.classname, stuid: item.stuid,
+ });
+ created++;
+ } catch (e) {
+ messages.push(`${item.username}: ${e.message}`);
+ errors++;
+ }
+ }
+ }
+ this.response.body.users = udocs;
+ this.response.body.messages = messages;
+ this.response.body.created = created;
+ this.response.body.errors = errors;
+ }
+}
/* eslint-enable no-await-in-loop */
const Priv = omit(PRIV, ['PRIV_DEFAULT', 'PRIV_NEVER', 'PRIV_NONE', 'PRIV_ALL']);
@@ -359,6 +420,7 @@ export async function apply(ctx) {
ctx.Route('manage_setting', '/manage/setting', SystemSettingHandler);
ctx.Route('manage_config', '/manage/config', SystemConfigHandler);
ctx.Route('manage_user_import', '/manage/userimport', SystemUserImportHandler);
+ ctx.Route('manage_student_import', '/manage/studentimport', SystemStudentImportHandler);
ctx.Route('manage_user_priv', '/manage/userpriv', SystemUserPrivHandler);
ctx.Connection('manage_check', '/manage/check-conn', SystemCheckConnHandler);
}
diff --git a/packages/hydrooj/src/handler/record.ts b/packages/hydrooj/src/handler/record.ts
index b9e0551c57..81c7bcff04 100644
--- a/packages/hydrooj/src/handler/record.ts
+++ b/packages/hydrooj/src/handler/record.ts
@@ -234,7 +234,8 @@ export class RecordDetailHandler extends ContestDetailBaseHandler {
const priority = await record.submissionPriority(this.user._id, -20);
const rdoc = await record.reset(domainId, rid, true);
this.ctx.broadcast('record/change', rdoc);
- await record.judge(domainId, rid, priority, this.rdoc.contest ? { detail: false } : {});
+ const isContest = this.rdoc.contest && (await contest.get(domainId, this.rdoc.contest))?.rule !== 'homework';
+ await record.judge(domainId, rid, priority, isContest ? { detail: false } : {});
this.back();
}
diff --git a/packages/hydrooj/src/handler/user.ts b/packages/hydrooj/src/handler/user.ts
index 70f666b10b..bf0cdb539e 100644
--- a/packages/hydrooj/src/handler/user.ts
+++ b/packages/hydrooj/src/handler/user.ts
@@ -23,9 +23,11 @@ import * as oplog from '../model/oplog';
import problem, { ProblemDoc } from '../model/problem';
import ScheduleModel from '../model/schedule';
import SolutionModel from '../model/solution';
+import student from '../model/stuinfo';
import system from '../model/system';
import token from '../model/token';
import user, { deleteUserCache } from '../model/user';
+import bus from '../service/bus';
import {
Handler, param, post, Query, Types,
} from '../service/server';
@@ -315,19 +317,33 @@ class UserRegisterWithCodeHandler extends Handler {
@param('verifyPassword', Types.Password)
@param('uname', Types.Username, true)
@param('code', Types.String)
+ // 学生信息
+ @param('stuname', Types.String, (s) => /^[\u4E00-\u9FA5]{2,4}$/.test(s))
+ @param('stuid', Types.String, (s) => /^2(?:\d{7}|\d{12})$/.test(s))
+ @param('stuclass', Types.String, (s) => /^[\u4E00-\u9FA5]{2,4}[12][0-9]{3}$/.test(s))
async post(
- domainId: string, password: string, verify: string,
- uname = '', code: string,
+ domainId: string,
+ password: string,
+ verify: string,
+ uname: string,
+ code: string,
+ // 学生信息
+ stuname: string,
+ stuid: string,
+ stuclass: string,
) {
const provider = this.ctx.oauth.providers[this.tdoc.identity.provider];
if (!provider) throw new SystemError(`OAuth provider ${this.tdoc.identity.provider} not found`);
if (provider.lockUsername) uname = this.tdoc.username;
if (!Types.Username[1](uname)) throw new ValidationError('uname');
if (password !== verify) throw new VerifyPasswordError();
+ if (await student.getStuInfoByStuId(stuid)) throw new UserAlreadyExistError(stuid);
const randomEmail = `${randomstring(12)}@invalid.local`; // some random email to remove in the future
- const uid = await user.create(this.tdoc.mail || randomEmail, uname, password, undefined, this.request.ip);
+ const uid = await student.createAccount(this.tdoc.mail || randomEmail, uname, password, {
+ class: stuclass, name: stuname, stuid,
+ }, this.request.ip);
await token.del(code, token.TYPE_REGISTRATION);
- const [id, mailDomain] = this.tdoc.mail.split('@');
+ const [id, mailDomain] = (this.tdoc.mail || randomEmail).split('@');
const $set: any = this.tdoc.set || {};
if (mailDomain === 'qq.com' && !Number.isNaN(+id)) {
$set.avatar = `qq:${id}`;
@@ -431,12 +447,13 @@ class UserDetailHandler extends Handler {
}
}
const tags = Object.entries(acInfo).sort((a, b) => b[1] - a[1]).slice(0, 20);
+ const studoc = await student.getStuInfoById(uid);
const tsdocs = await ContestModel.getMultiStatus(domainId, { uid, attend: { $exists: true } }).project({ docId: 1 }).toArray();
const tdocs = await ContestModel.getMulti(domainId, { docId: { $in: tsdocs.map((i) => i.docId) } })
.project({ docId: 1, title: 1, rule: 1 }).sort({ _id: -1 }).toArray();
this.response.template = 'user_detail.html';
this.response.body = {
- isSelfProfile, udoc, sdoc, pdocs, tags, tdocs,
+ isSelfProfile, udoc, sdoc, pdocs, tags, tdocs, studoc,
};
if (this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_SOLUTION)) {
const psdocs = await SolutionModel.getByUser(domainId, uid).limit(10).toArray();
@@ -550,6 +567,72 @@ class OauthCallbackHandler extends Handler {
}
}
+// HGNUOJ 学生信息
+class StudentInfoHandler extends Handler {
+ // @param('uid', Types.Int)
+ // async get(domainId: string, uid: number) {
+ // const res = await student.getStuInfoById(uid);
+ // this.response.body = res;
+ // }
+
+ @param('uid', Types.Int)
+ @post('cls', Types.String, true)
+ @post('name', Types.String, true)
+ @post('stuid', Types.String, true)
+ async post(domainId: string, uid: number, cls?: string, name?: string, stuid?: string) {
+ if (uid !== this.user._id || name !== undefined || stuid !== undefined) this.checkPriv(PRIV.PRIV_EDIT_SYSTEM);
+ const studoc = {
+ class: cls, name, stuid,
+ };
+ const $set = {};
+ for (const key in studoc) {
+ if (studoc[key] !== undefined) $set[key] = studoc[key];
+ }
+ this.response.body = { student: await student.setById(uid, $set) };
+ }
+}
+
+// HGNUOJ 班级信息
+class StudentClassHandler extends Handler {
+ @param('cls', Types.String)
+ async get(domainId: string, cls: string) {
+ const udocs = await student.getUserListByClassName(domainId, cls);
+ udocs.sort((a, b) => parseInt(a.stuid, 10) - parseInt(b.stuid, 10));
+ const sdocsTemp = await Promise.all(udocs.map(async ({ _id }) => {
+ const { updateAt } = await token.getMostRecentSessionByUid(_id, ['createAt', 'updateAt']) || { updateAt: null };
+ return { _id, updateAt };
+ }));
+ const sdocs = {};
+ for (const sdoc of sdocsTemp) sdocs[sdoc['_id']] = sdoc['updateAt'];
+ this.response.template = 'stu_class_students.html';
+ this.response.body = {
+ className: cls,
+ udocs,
+ sdocs,
+ };
+ this.UiContext.extraTitleContent = cls;
+ }
+}
+class ClassHandler extends Handler {
+ async get(domainId: string) {
+ const cls: { clsList: any[] } = await student.getClassList();
+ const starStudents: any[] = await Promise.all(
+ cls.clsList.slice(0, 2).map(async ({ _id }) => ({ _id, students: await student.getUserListByClassNameOrdered(domainId, _id, 3) })),
+ );
+ this.response.template = 'stu_class_list.html';
+ this.response.body = {
+ ...cls, starStudents,
+ };
+ }
+
+ async postInvalidateCache() {
+ this.checkPriv(PRIV.PRIV_EDIT_SYSTEM);
+ await bus.broadcast('student/invalidateClassListCache');
+ await bus.broadcast('student/invalidateActivityCache');
+ this.back();
+ }
+}
+
class ContestModeHandler extends Handler {
async get() {
const bindings = await user.getMulti({ loginip: { $exists: true } })
@@ -645,6 +728,9 @@ export async function apply(ctx: Context) {
ctx.Route('user_lostpass_with_code', '/lostpass/:code', UserLostPassWithCodeHandler);
ctx.Route('user_delete', '/user/delete', UserDeleteHandler, PRIV.PRIV_USER_PROFILE);
ctx.Route('user_detail', '/user/:uid', UserDetailHandler);
+ ctx.Route('student_detail', '/student/:uid', StudentInfoHandler, PRIV.PRIV_USER_PROFILE);
+ ctx.Route('student_class', '/class/:cls', StudentClassHandler, PRIV.PRIV_USER_PROFILE);
+ ctx.Route('class', '/class', ClassHandler, PRIV.PRIV_USER_PROFILE);
if (system.get('server.contestmode')) {
ctx.Route('contest_mode', '/contestmode', ContestModeHandler, PRIV.PRIV_EDIT_SYSTEM);
}
diff --git a/packages/hydrooj/src/interface.ts b/packages/hydrooj/src/interface.ts
index c478e1d654..66279f1e9e 100644
--- a/packages/hydrooj/src/interface.ts
+++ b/packages/hydrooj/src/interface.ts
@@ -128,12 +128,22 @@ export interface UserPreferenceDoc {
content: string;
}
+export interface Student extends Dictionary {
+ _id: number;
+ name?: string;
+ stuid?: string;
+ class?: string;
+}
+
export interface OwnerInfo { owner: number, maintainer?: number[] }
export type User = import('./model/user').User;
export type Udict = Record;
export interface BaseUser {
+ name?: string;
+ class?: string;
+ stuid?: string;
_id: number;
uname: string;
mail: string;
@@ -240,7 +250,8 @@ export interface RecordStatDoc {
}
export interface ScoreboardNode {
- type: 'string' | 'rank' | 'user' | 'email' | 'record' | 'records' | 'problem' | 'solved' | 'time' | 'total_score';
+ type: 'stu_class' | 'stu_stuid' | 'stu_name' | 'string' | 'rank' | 'user' | 'email'
+ | 'record' | 'records' | 'problem' | 'solved' | 'time' | 'total_score';
value: string; // 显示分数
raw?: any;
score?: number; // 原始分数(100,不含赛制加成)
@@ -316,6 +327,7 @@ export interface DomainDoc extends Record {
bulletin: string;
_join?: any;
host?: string[];
+ publicToCourses?: boolean;
}
// Message
@@ -620,6 +632,7 @@ declare module './service/db' {
blacklist: BlacklistDoc;
domain: DomainDoc;
'domain.user': any;
+ 'stu.info': Student;
record: RecordDoc;
'record.stat': RecordStatDoc;
'record.history': RecordHistoryDoc;
@@ -651,6 +664,7 @@ declare module './service/db' {
}
export interface Model {
+ student: typeof import('./model/stuinfo').default;
blacklist: typeof import('./model/blacklist').default;
builtin: typeof import('./model/builtin');
contest: typeof import('./model/contest');
diff --git a/packages/hydrooj/src/lib/ui.ts b/packages/hydrooj/src/lib/ui.ts
index 9d3e61fd68..06f44c193d 100644
--- a/packages/hydrooj/src/lib/ui.ts
+++ b/packages/hydrooj/src/lib/ui.ts
@@ -45,10 +45,8 @@ export function getNodes(name: UIInjectableFields) {
inject('Nav', 'homepage', { prefix: 'homepage' });
inject('Nav', 'problem_main', { prefix: 'problem' }, PERM.PERM_VIEW_PROBLEM);
-inject('Nav', 'training_main', { prefix: 'training' }, PERM.PERM_VIEW_TRAINING);
-inject('Nav', 'contest_main', { prefix: 'contest' }, PERM.PERM_VIEW_CONTEST);
inject('Nav', 'homework_main', { prefix: 'homework' }, PERM.PERM_VIEW_HOMEWORK);
-inject('Nav', 'discussion_main', { prefix: 'discussion' }, PERM.PERM_VIEW_DISCUSSION);
+inject('Nav', 'contest_main', { prefix: 'contest' }, PERM.PERM_VIEW_CONTEST);
inject('Nav', 'record_main', {
prefix: 'record',
query: (handler) => (handler.user.hasPriv(PRIV.PRIV_USER_PROFILE)
@@ -57,12 +55,16 @@ inject('Nav', 'record_main', {
}, (handler) => (handler.user.hasPriv(PRIV.PRIV_USER_PROFILE)
? true : handler.user.hasPerm(PERM.PERM_VIEW_RECORD)));
inject('Nav', 'ranking', { prefix: 'ranking' }, PERM.PERM_VIEW_RANKING);
+inject('Nav', 'discussion_main', { prefix: 'discussion' }, PERM.PERM_VIEW_DISCUSSION);
+inject('Nav', 'courses', { prefix: 'courses' }, PRIV.PRIV_USER_PROFILE);
+inject('Nav', 'training_main', { prefix: 'training' }, PERM.PERM_VIEW_TRAINING);
inject('Nav', 'domain_dashboard', { prefix: 'domain' }, PERM.PERM_EDIT_DOMAIN);
inject('Nav', 'manage_dashboard', { prefix: 'manage' }, PRIV.PRIV_EDIT_SYSTEM);
inject('ProblemAdd', 'problem_create', { icon: 'add', text: 'Create Problem' });
inject('ControlPanel', 'manage_dashboard');
inject('ControlPanel', 'manage_script');
inject('ControlPanel', 'manage_user_import');
+inject('ControlPanel', 'manage_student_import');
inject('ControlPanel', 'manage_user_priv');
inject('ControlPanel', 'manage_setting');
inject('ControlPanel', 'manage_config');
diff --git a/packages/hydrooj/src/model/builtin.ts b/packages/hydrooj/src/model/builtin.ts
index 9131340250..a8083a7fc2 100644
--- a/packages/hydrooj/src/model/builtin.ts
+++ b/packages/hydrooj/src/model/builtin.ts
@@ -14,6 +14,7 @@ export const PERMS = [
Permission('perm_general', PERM.PERM_VIEW_USER_PRIVATE_INFO, 'View domain user private info'),
Permission('perm_general', PERM.PERM_EDIT_DOMAIN, 'Edit domain settings'),
Permission('perm_general', PERM.PERM_MOD_BADGE, 'Show MOD badge'),
+ Permission('perm_general', PERM.PERM_EDIT_WIKI, 'Edit Wiki articles'),
Permission('perm_problem', PERM.PERM_CREATE_PROBLEM, 'Create problems'),
Permission('perm_problem', PERM.PERM_EDIT_PROBLEM, 'Edit problems'),
Permission('perm_problem', PERM.PERM_EDIT_PROBLEM_SELF, 'Edit own problems'),
diff --git a/packages/hydrooj/src/model/contest.ts b/packages/hydrooj/src/model/contest.ts
index 089ef5a4e3..9f0330a9dc 100644
--- a/packages/hydrooj/src/model/contest.ts
+++ b/packages/hydrooj/src/model/contest.ts
@@ -165,13 +165,13 @@ const acm = buildContestRule({
async scoreboardHeader(config, _, tdoc, pdict) {
const columns: ScoreboardRow = [
{ type: 'rank', value: '#' },
+ { type: 'stu_class', value: _('Stu_Class') },
{ type: 'user', value: _('User') },
+ { type: 'stu_stuid', value: _('Stu_Stuid') },
];
if (config.isExport && config.showDisplayName) {
columns.push({ type: 'email', value: _('Email') });
- columns.push({ type: 'string', value: _('School') });
columns.push({ type: 'string', value: _('Name') });
- columns.push({ type: 'string', value: _('Student ID') });
}
columns.push({ type: 'solved', value: `${_('Solved')}\n${_('Total Time')}` });
for (let i = 1; i <= tdoc.pids.length; i++) {
@@ -201,13 +201,13 @@ const acm = buildContestRule({
async scoreboardRow(config, _, tdoc, pdict, udoc, rank, tsdoc, meta) {
const row: ScoreboardRow = [
{ type: 'rank', value: rank.toString() },
+ { type: 'string', value: udoc.class || '' },
{ type: 'user', value: udoc.uname, raw: tsdoc.uid },
+ { type: 'string', value: udoc.stuid || '' },
];
if (config.isExport && config.showDisplayName) {
row.push({ type: 'email', value: udoc.mail });
- row.push({ type: 'string', value: udoc.school || '' });
- row.push({ type: 'string', value: udoc.displayName || '' });
- row.push({ type: 'string', value: udoc.studentId || '' });
+ row.push({ type: 'string', value: udoc.name || udoc.displayName || udoc.uname });
}
row.push({
type: 'time',
@@ -338,13 +338,13 @@ const oi = buildContestRule({
async scoreboardHeader(config, _, tdoc, pdict) {
const columns: ScoreboardNode[] = [
{ type: 'rank', value: '#' },
+ { type: 'stu_class', value: _('Stu_Class') },
{ type: 'user', value: _('User') },
+ { type: 'stu_stuid', value: _('Stu_Stuid') },
];
if (config.isExport && config.showDisplayName) {
columns.push({ type: 'email', value: _('Email') });
- columns.push({ type: 'string', value: _('School') });
columns.push({ type: 'string', value: _('Name') });
- columns.push({ type: 'string', value: _('Student ID') });
}
columns.push({ type: 'total_score', value: _('Total Score') });
for (let i = 1; i <= tdoc.pids.length; i++) {
@@ -368,7 +368,9 @@ const oi = buildContestRule({
async scoreboardRow(config, _, tdoc, pdict, udoc, rank, tsdoc, meta) {
const row: ScoreboardNode[] = [
{ type: 'rank', value: rank.toString() },
+ { type: 'string', value: udoc.class || '' },
{ type: 'user', value: udoc.uname, raw: tsdoc.uid },
+ { type: 'string', value: udoc.stuid || '' },
];
const displayScore = (pid: number, score?: number) => {
if (typeof score !== 'number') return '-';
@@ -376,9 +378,7 @@ const oi = buildContestRule({
};
if (config.isExport && config.showDisplayName) {
row.push({ type: 'email', value: udoc.mail });
- row.push({ type: 'string', value: udoc.school || '' });
- row.push({ type: 'string', value: udoc.displayName || '' });
- row.push({ type: 'string', value: udoc.studentId || '' });
+ row.push({ type: 'string', value: udoc.name || udoc.displayName || udoc.uname });
}
row.push({ type: 'total_score', value: (tsdoc.score || 0).toString() });
const accepted = {};
@@ -520,13 +520,13 @@ const strictioi = buildContestRule({
const tsddict = tsdoc.detail || {};
const row: ScoreboardNode[] = [
{ type: 'rank', value: rank.toString() },
+ { type: 'string', value: udoc.class || '' },
{ type: 'user', value: udoc.uname, raw: tsdoc.uid },
+ { type: 'string', value: udoc.stuid || '' },
];
if (config.isExport && config.showDisplayName) {
row.push({ type: 'email', value: udoc.mail });
- row.push({ type: 'string', value: udoc.school || '' });
- row.push({ type: 'string', value: udoc.displayName || '' });
- row.push({ type: 'string', value: udoc.studentId || '' });
+ row.push({ type: 'string', value: udoc.name || udoc.displayName || udoc.uname });
}
row.push({ type: 'total_score', value: (tsdoc.score || 0).toString() });
const accepted = {};
@@ -611,13 +611,13 @@ const ledo = buildContestRule({
const tsddict = tsdoc.detail || {};
const row: ScoreboardRow = [
{ type: 'rank', value: rank.toString() },
+ { type: 'string', value: udoc.class || '' },
{ type: 'user', value: udoc.uname, raw: tsdoc.uid },
+ { type: 'string', value: udoc.stuid || '' },
];
if (config.isExport && config.showDisplayName) {
row.push({ type: 'email', value: udoc.mail });
- row.push({ type: 'string', value: udoc.school || '' });
- row.push({ type: 'string', value: udoc.displayName || '' });
- row.push({ type: 'string', value: udoc.studentId || '' });
+ row.push({ type: 'string', value: udoc.name || udoc.displayName || udoc.uname });
}
row.push({
type: 'total_score',
@@ -703,19 +703,16 @@ const homework = buildContestRule({
async scoreboardHeader(config, _, tdoc, pdict) {
const columns: ScoreboardNode[] = [
{ type: 'rank', value: _('Rank') },
+ { type: 'stu_class', value: _('Stu_Class') },
{ type: 'user', value: _('User') },
+ { type: 'total_score', value: _('Score') },
];
- if (config.isExport && config.showDisplayName) {
- columns.push({ type: 'email', value: _('Email') });
- columns.push({ type: 'string', value: _('School') });
- columns.push({ type: 'string', value: _('Name') });
- columns.push({ type: 'string', value: _('Student ID') });
- }
- columns.push({ type: 'total_score', value: _('Score') });
if (config.isExport) {
- columns.push({ type: 'string', value: _('Original Score') });
+ columns.push(
+ { type: 'string', value: _('Original Score') },
+ { type: 'stu_name', value: _('Stu_Name') },
+ { type: 'stu_stuid', value: _('Stu_Stuid') });
}
- columns.push({ type: 'time', value: _('Total Time') });
for (let i = 1; i <= tdoc.pids.length; i++) {
const pid = tdoc.pids[i - 1];
pdict[pid].nAccept = pdict[pid].nSubmit = 0;
@@ -729,10 +726,6 @@ const homework = buildContestRule({
type: 'string',
value: '#{0} {1}'.format(i, _('Original Score')),
},
- {
- type: 'time',
- value: '#{0} {1}'.format(i, _('Time (Seconds)')),
- },
);
} else {
columns.push({
@@ -748,23 +741,26 @@ const homework = buildContestRule({
const tsddict = tsdoc.detail || {};
const row: ScoreboardRow = [
{ type: 'rank', value: rank.toString() },
+ {
+ type: 'string',
+ value: udoc.class || '',
+ },
{
type: 'user',
value: udoc.uname,
raw: tsdoc.uid,
},
+ {
+ type: 'string',
+ value: (tsdoc.score || 0).toString(),
+ },
];
- if (config.isExport && config.showDisplayName) {
- row.push({ type: 'email', value: udoc.mail });
- row.push({ type: 'string', value: udoc.school || '' });
- row.push({ type: 'string', value: udoc.displayName || '' });
- row.push({ type: 'string', value: udoc.studentId || '' });
- }
- row.push({ type: 'string', value: (tsdoc.penaltyScore || 0).toString() });
if (config.isExport) {
- row.push({ type: 'string', value: (tsdoc.score || 0).toString() });
+ row.push(
+ { type: 'string', value: (tsdoc.score || 0).toString() },
+ { type: 'string', value: udoc.name || udoc.uname },
+ { type: 'string', value: udoc.stuid || '' });
}
- row.push({ type: 'time', value: formatSeconds(tsdoc.time || 0, false), raw: tsdoc.time });
const accepted = {};
for (const s of tsdoc.journal || []) {
if (!pdict[s.pid]) continue;
@@ -778,21 +774,18 @@ const homework = buildContestRule({
const rid = tsddict[pid]?.rid;
const colScore = (tsddict[pid]?.penaltyScore ?? '').toString();
const colOriginalScore = (tsddict[pid]?.score ?? '').toString();
- const colTime = (tsddict[pid]?.time || '').toString();
- const colTimeStr = colTime ? formatSeconds(colTime, false) : '';
if (config.isExport) {
row.push(
{ type: 'string', value: colScore },
{ type: 'string', value: colOriginalScore },
- { type: 'time', value: colTime },
);
} else {
row.push({
type: 'record',
score: tsddict[pid]?.score,
value: colScore === colOriginalScore
- ? '{0}\n{1}'.format(colScore, colTimeStr)
- : '{0} / {1}\n{2}'.format(colScore, colOriginalScore, colTimeStr),
+ ? '{0}'.format(colScore)
+ : '{0} / {1}'.format(colScore, colOriginalScore),
raw: rid,
});
}
diff --git a/packages/hydrooj/src/model/domain.ts b/packages/hydrooj/src/model/domain.ts
index 0a2d56f230..f6f5385fb6 100644
--- a/packages/hydrooj/src/model/domain.ts
+++ b/packages/hydrooj/src/model/domain.ts
@@ -69,6 +69,7 @@ class DomainModel {
bulletin,
roles: {},
avatar: '',
+ publicToCourses: false,
};
await bus.parallel('domain/create', ddoc);
await coll.insertOne(ddoc);
diff --git a/packages/hydrooj/src/model/record.ts b/packages/hydrooj/src/model/record.ts
index 7024f13408..c78332e676 100644
--- a/packages/hydrooj/src/model/record.ts
+++ b/packages/hydrooj/src/model/record.ts
@@ -12,6 +12,7 @@ import db from '../service/db';
import { MaybeArray, NumberKeys } from '../typeutils';
import { ArgMethod, buildProjection, Time } from '../utils';
import { STATUS } from './builtin';
+import * as contest from './contest';
import DomainModel from './domain';
import MessageModel from './message';
import problem from './problem';
@@ -104,7 +105,7 @@ export default class RecordModel {
const ddoc = await DomainModel.get(pdoc.domainId);
return await task.addMany(rdocs.map((rdoc) => {
let type = 'judge';
- if (typeof pdoc.config === 'string') throw new Error(pdoc.config);
+ if (typeof pdoc.config === 'string') throw new TypeError(pdoc.config);
if (pdoc.config.type === 'remote_judge' && rdoc.contest?.toHexString() !== '0'.repeat(24)) type = 'remotejudge';
else if (meta?.type === 'generate') type = 'generate';
return ({
@@ -157,6 +158,10 @@ export default class RecordModel {
rejudged: false,
};
let isContest = !!args.contest;
+ if (args.contest) {
+ const activity = await contest.get(domainId, args.contest);
+ if (activity?.rule === 'homework') isContest = false;
+ }
if (args.contest) data.contest = args.contest;
if (args.files) data.files = args.files;
if (args.hackTarget) data.hackTarget = args.hackTarget;
diff --git a/packages/hydrooj/src/model/setting.ts b/packages/hydrooj/src/model/setting.ts
index 93bd3a35f0..00ff246359 100644
--- a/packages/hydrooj/src/model/setting.ts
+++ b/packages/hydrooj/src/model/setting.ts
@@ -255,17 +255,20 @@ PreferenceSetting(
);
AccountSetting(
+ Setting('setting_student', 'stuid', '', 'text', 'Stu_ID',
+ '', FLAG_DISABLED | FLAG_PUBLIC, (s) => /^2(?:\d{7}|\d{12})$/.test(s)),
+ Setting('setting_student', 'name', '', 'text', 'Stu_RealName',
+ '', FLAG_DISABLED | FLAG_PUBLIC, (s) => /^[\u4E00-\u9FA5]{2,4}$/.test(s)),
+ Setting('setting_student', 'class', null, 'text', 'Stu_ClassName',
+ '', FLAG_PUBLIC, (s) => /^[\u4E00-\u9FA5]{2,4}[12][0-9]{3}$/.test(s)),
Setting('setting_info', 'avatar', '', 'text', 'Avatar',
'Allow using gravatar:email qq:id github:name url:link format.'),
Setting('setting_info', 'qq', null, 'text', 'QQ'),
Setting('setting_info', 'gender', builtin.USER_GENDER_OTHER, builtin.USER_GENDER_RANGE, 'Gender'),
- Setting('setting_info', 'bio', null, 'markdown', 'Bio'),
- Setting('setting_info', 'school', '', 'text', 'School', '', FLAG_PRIVATE),
- Setting('setting_info', 'studentId', '', 'text', 'Student ID', '', FLAG_PRIVATE),
Setting('setting_info', 'phone', null, 'text', 'Phone', null, FLAG_DISABLED | FLAG_PRIVATE),
Setting('setting_customize', 'backgroundImage',
'/components/profile/backgrounds/1.jpg', 'text', 'Profile Background Image',
- 'Choose the background image in your profile page.'),
+ 'Choose the background image in your profile page.', FLAG_DISABLED),
Setting('setting_storage', 'unreadMsg', 0, 'number', 'Unread Message Count', null, FLAG_DISABLED | FLAG_HIDDEN),
Setting('setting_storage', 'badge', '', 'text', 'badge info', null, FLAG_DISABLED | FLAG_HIDDEN | FLAG_PUBLIC),
Setting('setting_storage', 'banReason', '', 'text', 'ban reason', null, FLAG_DISABLED | FLAG_HIDDEN),
@@ -337,6 +340,7 @@ SystemSetting(Schema.object({
// We will keep the old settings as-is until new setting ui is ready.
SystemSetting(
Setting('setting_server', 'server.language', 'zh_CN', langRange, 'server.language', 'Default display language'),
+ Setting('setting_server', 'server.message', false, 'boolean', 'server.message', 'Allow users send messages'),
ServerLangSettingNode,
Setting('setting_limits', 'limit.by_user', false, 'boolean', 'limit.by_user', 'Use per-user limits instead of per ip limits'),
Setting('setting_limits', 'limit.problem_files_max', 100, 'number', 'limit.problem_files_max', 'Max files per problem'),
diff --git a/packages/hydrooj/src/model/stuinfo.ts b/packages/hydrooj/src/model/stuinfo.ts
new file mode 100644
index 0000000000..5653b16695
--- /dev/null
+++ b/packages/hydrooj/src/model/stuinfo.ts
@@ -0,0 +1,240 @@
+import { pick } from 'lodash';
+import { LRUCache } from 'lru-cache';
+import { UserAlreadyExistError, UserNotFoundError, ValidationError } from '../error';
+import { Student } from '../interface';
+import { Logger } from '../logger';
+import bus from '../service/bus';
+import db from '../service/db';
+import { Value } from '../typeutils';
+import { ArgMethod } from '../utils';
+import TokenModel from './token';
+import UserModel, { deleteUserCache, User } from './user';
+
+const coll = db.collection('stu.info');
+const domainUsercoll = db.collection('domain.user');
+
+const logger = new Logger('model/stuinfo');
+const cache = new LRUCache({ max: 500, ttl: 300 * 1000 });
+
+export function deleteStudentCache(studoc?: Student | string | null, receiver = false) {
+ // Student identity, class membership and both lookup keys change together.
+ cache.clear();
+ if (!receiver) bus.broadcast('student/delcache', JSON.stringify(studoc || null));
+}
+bus.on('student/delcache', (content) => deleteStudentCache(JSON.parse(content), true));
+
+export function validateStudentInfo(info: Partial) {
+ if (info.stuid !== undefined && !/^2(?:\d{7}|\d{12})$/.test(info.stuid)) throw new ValidationError('stuid');
+ if (info.name !== undefined && !/^[\u4E00-\u9FA5]{2,4}$/.test(info.name)) throw new ValidationError('name');
+ if (info.class !== undefined && !/^[\u4E00-\u9FA5]{2,4}[12][0-9]{3}$/.test(info.class)) throw new ValidationError('class');
+}
+
+class StudentModel {
+ @ArgMethod
+ static async getStuInfoById(_id: number): Promise {
+ if (cache.has(`uid/${_id}`)) return cache.get(`uid/${_id}`);
+ const studoc = await coll.findOne({ _id });
+ if (!studoc) return null;
+ cache.set(`uid/${studoc._id}`, studoc);
+ return studoc;
+ }
+
+ @ArgMethod
+ static async getStuInfoByStuId(stuid: string): Promise {
+ if (cache.has(`stuid/${stuid}`)) return cache.get(`stuid/${stuid}`);
+ const studoc = await coll.findOne({ stuid });
+ if (!studoc) return null;
+ cache.set(`stuid/${stuid}`, studoc);
+ return studoc;
+ }
+
+ @ArgMethod
+ static async create(uid: number, classname?: string, name?: string, stuid?: string) {
+ const info = Object.fromEntries(Object.entries({ name, class: classname, stuid }).filter(([, v]) => v !== undefined));
+ try {
+ await coll.insertOne({ _id: uid, ...info });
+ } catch (e) {
+ if (e?.code === 11000) throw new UserAlreadyExistError(stuid || uid);
+ throw e;
+ }
+ deleteStudentCache();
+ deleteUserCache(await UserModel.coll.findOne({ _id: uid }));
+ }
+
+ static async createAccount(mail: string, uname: string, password: string, info: Partial, ip?: string) {
+ validateStudentInfo(info);
+ if (info.stuid && await this.getStuInfoByStuId(info.stuid)) throw new UserAlreadyExistError(info.stuid);
+ const uid = await UserModel.create(mail, uname, password, undefined, ip);
+ try {
+ await this.create(uid, info.class, info.name, info.stuid);
+ } catch (e) {
+ // This account has not been logged in or returned to the caller yet.
+ // Roll back only the account created by this call, leaving existing users intact.
+ const created = await UserModel.coll.findOne({ _id: uid });
+ await domainUsercoll.deleteMany({ uid });
+ await UserModel.coll.deleteOne({ _id: uid });
+ deleteUserCache(created);
+ throw e;
+ }
+ return uid;
+ }
+
+ @ArgMethod
+ static async setById(uid: number, $set?: Partial, $unset?: Value, ''>) {
+ const owner = await UserModel.coll.findOne({ _id: uid });
+ if (!owner) throw new UserNotFoundError(uid);
+ const values = pick($set || {}, ['name', 'class', 'stuid']);
+ validateStudentInfo(values);
+ const op: any = {};
+ if (Object.keys(values).length) op.$set = values;
+ const unset = pick($unset || {}, ['name', 'class', 'stuid']);
+ if (Object.keys(unset).length) op.$unset = unset;
+ if (!Object.keys(op).length) return this.getStuInfoById(uid);
+ let result: Student;
+ try {
+ result = await coll.findOneAndUpdate({ _id: uid }, op, { returnDocument: 'after', upsert: true });
+ } catch (e) {
+ if (e?.code === 11000) throw new UserAlreadyExistError(values.stuid || uid);
+ throw e;
+ }
+ deleteStudentCache(result);
+ deleteUserCache(owner);
+ return result;
+ }
+
+ @ArgMethod
+ static setStuID(uid: number, stuid: string) {
+ return StudentModel.setById(uid, { stuid });
+ }
+
+ @ArgMethod
+ static setName(uid: number, name: string) {
+ return StudentModel.setById(uid, { name });
+ }
+
+ @ArgMethod
+ static setClass(uid: number, cls: string) {
+ return StudentModel.setById(uid, { class: cls });
+ }
+
+ static async getUserUidsByClassName(domain: string, cls: string): Promise {
+ return coll.find({ class: cls }, { sort: { stuid: 1 } }).sort({ _id: 1 }).map((stu) => stu._id).toArray();
+ }
+
+ static async getUserListByClassName(domain: string, cls: string): Promise {
+ const uids: number[] = await this.getUserUidsByClassName(domain, cls);
+ const udocs: User[] = await Promise.all(uids.map((uid) => UserModel.getById(domain, uid)));
+ return udocs.filter(Boolean);
+ }
+
+ static async getUserListByClassNameOrdered(domain: string, cls: string, limit: number = 3): Promise {
+ const uids: number[] = await this.getUserUidsByClassName(domain, cls);
+ const promises: Promise[] = await domainUsercoll.aggregate([
+ { $match: { uid: { $in: uids } } },
+ { $group: { _id: '$uid', rp: { $avg: '$rp' } } },
+ ])
+ .sort({ rp: -1 })
+ .limit(limit)
+ .map(async ({ _id }) => await UserModel.getById('system', _id))
+ .toArray();
+ const topUsers: User[] = await Promise.all(promises);
+ return topUsers;
+ }
+
+ static async getClassList(domain: string = 'system'): Promise {
+ if (cache.has('classList')) return cache.get('classList');
+ const startTime = Date.now();
+ const clsCursor = await coll.aggregate([
+ { $match: { class: { $not: { $in: [null, ''] } } } },
+ { $group: { _id: '$class', stuNum: { $sum: 1 } } },
+ ]).map(async (cls) => {
+ const users: number[] = await this.getUserUidsByClassName(domain, cls._id.toString());
+ const clsInfoList = await domainUsercoll.aggregate([
+ { $match: { uid: { $in: users } } },
+ {
+ $group: {
+ _id: 'result',
+ nAccept: { $sum: '$nAccept' },
+ nSubmit: { $sum: '$nSubmit' },
+ rpSum: { $sum: '$rp' },
+ rpAvg: { $avg: '$rp' },
+ },
+ },
+ ]).toArray();
+ let activityList: number[];
+ if (cache.has(`activity/${cls._id}`)) activityList = cache.get(`activity/${cls._id}`);
+ else {
+ activityList = await Promise.all(users.map(async (uid) => (
+ await TokenModel.getMostRecentSessionByUid(uid, ['createAt', 'updateAt']))?.updateAt?.valueOf()
+ || (await UserModel.getById(domain, uid))?.loginat?.valueOf()
+ || Date.now() - 7 * 24 * 60 * 60 * 1000));
+ activityList = activityList.map((ac) => Math.max(ac, Date.now() - 7 * 24 * 60 * 60 * 1000));
+ await bus.broadcast('student/cacheActivity', cls._id, JSON.stringify(activityList));
+ }
+ const activity = (activityList.reduce((sum, time) => sum + time, 0) / Math.max(activityList.length, 1));
+ if (!clsInfoList.length) {
+ return {
+ ...cls, nAccept: 0, nSubmit: 0, rpSum: 1500 * cls.stuNum, rpAvg: 1500, activity,
+ };
+ }
+ return { ...clsInfoList[0], ...cls, activity };
+ }).toArray();
+ const clsList: any[] = await Promise.all(clsCursor);
+ for (const cls of clsList) {
+ cls.rpAvg ||= 1500;
+ }
+ const sortWeights = {
+ rpAvg: 2,
+ stuNum: 10,
+ nAccept: 10,
+ nSubmit: 5,
+ activity: 2,
+ };
+ const calSortWeight = (cls) => Object.entries(sortWeights).reduce((pre, [key, val]) => pre + cls[key] * val, 0);
+ const normalize = (val, min, max, newMin, newMax) => ((val - min) / (max - min)) * (newMax - newMin) + newMin;
+
+ const activityList = clsList.map((cls: { activity: number }) => cls.activity / 1e5);
+ const activityMax = Math.max(...activityList);
+ const activityMin = Math.min(...activityList);
+ for (const cls of clsList) {
+ cls.activity = normalize(cls.activity / 1e5, activityMin - 1000, activityMax + 1000, 0, 1000);
+ }
+
+ for (const cls of clsList) {
+ cls.weight = calSortWeight(cls);
+ }
+ const weightList = clsList.map((cls: { weight: number }) => cls.weight);
+ const weightMax = Math.max(...weightList);
+ const weightMin = Math.min(...weightList);
+ for (const cls of clsList) {
+ cls.weight = normalize(cls.weight, weightMin - 1000, weightMax + 1000, 0, 1000);
+ }
+
+ clsList.sort((a, b) => b.weight - a.weight);
+
+ const res = { cacheTime: Date.now(), clsList };
+ await bus.broadcast('student/cacheClassList', JSON.stringify(res));
+ logger.info(`caching class list done. (${Date.now() - startTime}ms)`);
+ return res;
+ }
+}
+
+bus.on('student/cacheClassList', (content: string) => cache.set('classList', JSON.parse(content)));
+bus.on('student/cacheActivity', (cls: string, content: string) => cache.set(`activity/${cls}`, JSON.parse(content)));
+bus.on('student/invalidateClassListCache', () => cache.delete('classList'));
+bus.on('student/invalidateActivityCache', () => {
+ for (const cacheKey of [...cache.keys()].filter((key) => /^activity\//.test(key))) {
+ cache.delete(cacheKey);
+ }
+});
+
+bus.on('app/started', () => db.ensureIndexes(
+ coll,
+ {
+ key: { stuid: 1 }, name: 'stuid', unique: true, sparse: true,
+ },
+ { key: { name: 1 }, name: 'name', sparse: true },
+ { key: { class: 1, name: 1 }, name: '(class,name)', sparse: true },
+));
+global.Hydro.model.student = StudentModel;
+export default StudentModel;
diff --git a/packages/hydrooj/src/model/user.ts b/packages/hydrooj/src/model/user.ts
index 6969a10f4e..74aeccc013 100644
--- a/packages/hydrooj/src/model/user.ts
+++ b/packages/hydrooj/src/model/user.ts
@@ -15,6 +15,7 @@ import { ArgMethod, buildProjection, randomstring, sleep } from '../utils';
import { PERM, PRIV } from './builtin';
import domain from './domain';
import * as setting from './setting';
+import StudentModel from './stuinfo';
import system from './system';
import token from './token';
@@ -114,6 +115,8 @@ export class User {
}
async init() {
+ const student = await StudentModel.getStuInfoById(this._id);
+ if (student) Object.assign(this, pick(student, ['name', 'class', 'stuid']));
await bus.parallel('user/get', this);
return this;
}
@@ -269,11 +272,19 @@ class UserModel {
@ArgMethod
static async setById(uid: number, $set?: Partial, $unset?: Value, ''>, $push?: any) {
if (uid < -999) return null;
+ const studentSet = pick($set || {}, ['stuid', 'name', 'class']);
+ const studentUnset = pick($unset || {}, ['stuid', 'name', 'class']);
+ if (Object.keys(studentSet).length || Object.keys(studentUnset).length) {
+ await StudentModel.setById(uid, studentSet, studentUnset);
+ }
+ $set = omit($set || {}, ['stuid', 'name', 'class']);
+ $unset = omit($unset || {}, ['stuid', 'name', 'class']);
const op: any = {};
if ($set && Object.keys($set).length) op.$set = $set;
if ($unset && Object.keys($unset).length) op.$unset = $unset;
if ($push && Object.keys($push).length) op.$push = $push;
if (op.$set?.loginip) op.$addToSet = { ip: op.$set.loginip };
+ if (!Object.keys(op).length) return coll.findOne({ _id: uid });
const keys = new Set(Object.values(op).flatMap((i) => Object.keys(i)));
if (keys.has('mailLower') || keys.has('unameLower')) {
const udoc = await coll.findOne({ _id: uid });
@@ -451,14 +462,18 @@ class UserModel {
...(await UserModel.getById('system', 0)).getFields(showPrivateInfo ? 'private' : 'public'),
..._extraFields,
]));
- const [udocs, vudocs, dudocs] = await Promise.all([
+ const [udocs, vudocs, dudocs, students] = await Promise.all([
UserModel.getMulti({ _id: { $in: uids } }, fields).toArray(),
collV.find({ _id: { $in: uids } }).toArray(),
domain.getDomainUserMulti(domainId, uids).project(buildProjection(fields.concat('uid'))).toArray(),
+ db.collection('stu.info').find({ _id: { $in: uids } }).toArray(),
]);
const udict = {};
for (const udoc of udocs) udict[udoc._id] = udoc;
for (const udoc of vudocs) udict[udoc._id] = udoc;
+ for (const student of students) {
+ if (udict[student._id]) Object.assign(udict[student._id], pick(student, ['name', 'class', 'stuid']));
+ }
if (showPrivateInfo) {
for (const dudoc of dudocs) Object.assign(udict[dudoc.uid], omit(dudoc, ['_id', 'uid']));
}
diff --git a/packages/hydrooj/src/plugin-api.ts b/packages/hydrooj/src/plugin-api.ts
index ff0e312627..500f2d094e 100644
--- a/packages/hydrooj/src/plugin-api.ts
+++ b/packages/hydrooj/src/plugin-api.ts
@@ -35,6 +35,7 @@ export { default as OauthModel } from './model/oauth';
export { default as BlackListModel } from './model/blacklist';
export { default as DomainModel } from './model/domain';
export { default as StorageModel } from './model/storage';
+export { default as StudentModel } from './model/stuinfo';
export { default as TaskModel } from './model/task';
export * from './model/builtin';
/** @deprecated */
diff --git a/packages/hydrooj/src/script/hgnuFixCrlf.js b/packages/hydrooj/src/script/hgnuFixCrlf.js
new file mode 100644
index 0000000000..ef269ddd10
--- /dev/null
+++ b/packages/hydrooj/src/script/hgnuFixCrlf.js
@@ -0,0 +1,54 @@
+/* eslint-disable no-await-in-loop -- Preserve ordered updates and progress checkpoints. */
+// 将测试数据中的 CRLF 规范为 LF 并覆盖 OJ 上的对应文件。
+// 复制到 /opt/HGNUOJ-Hydro/Hydro/packages/hydrooj/src/script/hgnuFixCrlf.js
+// 预览:hydrooj cli script hgnuFixCrlf '{"base":"/root/hydro_export","list":"/root/hydro_export/crlf_fix_in.json"}'
+// 执行:加 "apply":true;可用 "pids":["P4963"] 只处理部分题。
+const fs = require('fs');
+const path = require('path');
+const schemastery = require('schemastery');
+const Schema = schemastery.default?.any ? schemastery.default : schemastery;
+const ProblemModel = require('../model/problem').default;
+
+const DOMAIN = 'system';
+
+async function run(arg = {}, report = console.log) {
+ const base = path.resolve(arg.base || '/root/hydro_export');
+ const listPath = path.resolve(arg.list || path.join(base, 'crlf_fix_in.json'));
+ const uid = Number(arg.uid || 607);
+ const apply = !!arg.apply;
+ const only = Array.isArray(arg.pids) ? new Set(arg.pids.map(String)) : null;
+ const list = JSON.parse(fs.readFileSync(listPath, 'utf8'));
+ let problems = 0;
+ let files = 0;
+ for (const pid of Object.keys(list)) {
+ if (only && !only.has(pid)) continue;
+ const pdoc = await ProblemModel.get(DOMAIN, pid);
+ if (!pdoc) {
+ report({ message: `MISSING ${pid}` });
+ continue;
+ }
+ const td = path.join(base, 'problems', pid, 'testdata');
+ const names = new Set(list[pid]);
+ for (const name of list[pid]) {
+ const stem = name.replace(/\.in$/, '');
+ if (fs.existsSync(path.join(td, `${stem}.out`))) names.add(`${stem}.out`);
+ }
+ for (const name of names) {
+ const p = path.join(td, name);
+ if (!fs.existsSync(p)) continue;
+ const old = fs.readFileSync(p);
+ const text = old.toString('utf8').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
+ const buf = Buffer.from(text, 'utf8');
+ if (buf.equals(old)) continue;
+ if (apply) await ProblemModel.addTestdata(DOMAIN, pdoc.docId, name, buf, uid);
+ files++;
+ }
+ problems++;
+ report({ message: `${problems} ${pid} docId=${pdoc.docId}` });
+ }
+ report({ message: `DONE problems=${problems} files=${files} apply=${apply}` });
+ return { problems, files };
+}
+
+const apply = (ctx) => ctx.addScript('hgnuFixCrlf', 'Normalize CRLF in testdata', Schema.any(), run);
+module.exports = { apply, run };
diff --git a/packages/hydrooj/src/script/hgnuImport413.js b/packages/hydrooj/src/script/hgnuImport413.js
new file mode 100644
index 0000000000..2011ae568e
--- /dev/null
+++ b/packages/hydrooj/src/script/hgnuImport413.js
@@ -0,0 +1,146 @@
+/* eslint-disable no-await-in-loop -- Preserve ordered updates and progress checkpoints. */
+// Copy this file to hydrooj/src/script/hgnuImport413.js on the Hydro 4.13.4 server.
+// Run through: node hydrooj/bin/hydrooj.js cli script hgnuImport413 '{"base":"/root/hydro_export"}'
+// The default is read-only. Pass apply:true only after a verified backup and dry run.
+const fs = require('fs');
+const path = require('path');
+const schemastery = require('schemastery');
+const Schema = schemastery.default?.any ? schemastery.default : schemastery;
+const ProblemModel = require('../model/problem').default;
+const db = require('../service/db').default;
+
+const DOMAIN = 'system';
+
+function plannedNew(pid) {
+ const match = /^P(\d+)$/.exec(pid);
+ return !!match && Number(match[1]) >= 4899 && Number(match[1]) <= 4999;
+}
+
+function readPackages(base, only) {
+ const root = path.resolve(base);
+ const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8'));
+ if (!Array.isArray(manifest)) throw new TypeError('manifest.json must be an array');
+ const seen = new Set();
+ const selected = [];
+ for (const item of manifest) {
+ if (!/^P\d+$/.test(item.pid) || seen.has(item.pid)) throw new Error(`Invalid/duplicate PID: ${item.pid}`);
+ seen.add(item.pid);
+ if (only && item.pid !== only) continue;
+ const dir = path.resolve(root, item.dir);
+ if (!dir.startsWith(root + path.sep)) throw new Error(`Unsafe path: ${item.dir}`);
+ const yaml = fs.readFileSync(path.join(dir, 'problem.yaml'), 'utf8');
+ if (!yaml.includes(`pid: ${item.pid}`)) throw new Error(`PID differs in problem.yaml: ${item.pid}`);
+ const statement = fs.readFileSync(path.join(dir, 'problem_zh.md'), 'utf8');
+ if (!statement.trim()) throw new Error(`Empty statement: ${item.pid}`);
+ const dataDir = path.join(dir, 'testdata');
+ const names = fs.readdirSync(dataDir).sort();
+ if (!names.includes('config.yaml')) throw new Error(`Missing config.yaml: ${item.pid}`);
+ for (const name of names) {
+ if (!fs.statSync(path.join(dataDir, name)).isFile()) throw new Error(`Nested testdata: ${item.pid}/${name}`);
+ if (name.endsWith('.in') && !names.includes(`${name.slice(0, -3)}.out`)) {
+ throw new Error(`Missing output: ${item.pid}/${name}`);
+ }
+ }
+ const tests = names.filter((name) => name.endsWith('.in')).length;
+ if (tests !== item.tests) throw new Error(`Test count differs: ${item.pid} ${tests}/${item.tests}`);
+ selected.push({ item, statement, dataDir, names });
+ }
+ if (only && selected.length !== 1) throw new Error(`PID not in manifest: ${only}`);
+ return selected;
+}
+
+async function run(arg = {}, report = console.log) {
+ const base = arg.base || '/root/hydro_export';
+ const only = arg.only || '';
+ const operator = Number(arg.operator);
+ if (arg.apply && (!Number.isSafeInteger(operator) || operator < 1)) {
+ throw new Error('apply requires a positive operator UID');
+ }
+ const packages = readPackages(base, only);
+ const progressPath = path.join(path.resolve(base), '.hgnu-import-progress.json');
+ const progress = fs.existsSync(progressPath) ? JSON.parse(fs.readFileSync(progressPath, 'utf8')) : {};
+ const coll = db.collection('document');
+ const pids = packages.map((p) => p.item.pid);
+ const existing = await coll.find(
+ { domainId: DOMAIN, docType: 10, pid: { $in: pids } },
+ { projection: { pid: 1, docId: 1, title: 1, data: 1 } },
+ ).toArray();
+ const byPid = new Map(existing.map((p) => [p.pid, p]));
+ const conflicts = [];
+ for (const p of packages) {
+ const old = byPid.get(p.item.pid);
+ if (plannedNew(p.item.pid) && old && progress[p.item.pid] !== old.docId) {
+ conflicts.push(`${p.item.pid} expected new, found docId=${old.docId}`);
+ }
+ if (plannedNew(p.item.pid) && !old && progress[p.item.pid]) {
+ conflicts.push(`${p.item.pid} missing after prior import docId=${progress[p.item.pid]}`);
+ }
+ if (!plannedNew(p.item.pid) && !old) conflicts.push(`${p.item.pid} expected existing, missing`);
+ }
+ const updates = packages.length - packages.filter((p) => plannedNew(p.item.pid)).length;
+ report({ message: `PLAN total=${packages.length} update=${updates} create=${packages.length - updates} conflicts=${conflicts.length}` });
+ for (const message of conflicts) report({ message: `CONFLICT ${message}` });
+ if (!arg.apply) return { dryRun: true, conflicts };
+ if (conflicts.length) throw new Error('Import blocked by PID conflict');
+
+ let done = 0;
+ for (const p of packages) {
+ const { item, statement, dataDir, names } = p;
+ report({ message: `START ${item.pid}` });
+ const current = await coll.findOne({ domainId: DOMAIN, docType: 10, pid: item.pid });
+ const originally = byPid.get(item.pid);
+ if (originally && current?.docId !== originally.docId) throw new Error(`docId changed: ${item.pid}`);
+ if (!originally && current) throw new Error(`PID became occupied: ${item.pid}`);
+ if (plannedNew(item.pid) && current && progress[item.pid] === current.docId) {
+ if (current.owner !== operator) {
+ await ProblemModel.edit(DOMAIN, current.docId, { owner: operator });
+ const updated = await coll.findOne({ domainId: DOMAIN, docType: 10, pid: item.pid });
+ if (updated?.owner !== operator) throw new Error(`Owner verification failed: ${item.pid}`);
+ }
+ done++;
+ report({ message: `${done}/${packages.length} RESUME-SKIP ${item.pid} docId=${current.docId} owner=${operator}` });
+ continue;
+ }
+ let docId = current?.docId;
+ if (!current) {
+ docId = await ProblemModel.add(DOMAIN, item.pid, item.title, JSON.stringify({ zh: statement }), operator, [item.root, item.chapter]);
+ const created = await coll.findOne({ domainId: DOMAIN, docType: 10, pid: item.pid });
+ if (created?.docId !== docId) throw new Error(`New PID mismatch: ${item.pid}`);
+ }
+ for (const name of names) {
+ await ProblemModel.addTestdata(DOMAIN, docId, name, path.join(dataDir, name), operator);
+ }
+ const stored = await coll.findOne({ domainId: DOMAIN, docType: 10, docId });
+ const storedFiles = new Map((stored?.data || []).map((f) => [f.name || f._id, f]));
+ const missing = names.filter((name) => {
+ const info = storedFiles.get(name);
+ return !info || info.size !== fs.statSync(path.join(dataDir, name)).size;
+ });
+ if (missing.length) throw new Error(`Uploaded metadata missing: ${item.pid} ${missing.join(',')}`);
+ if (current) {
+ await ProblemModel.edit(DOMAIN, docId, {
+ content: JSON.stringify({ zh: statement }),
+ owner: operator,
+ });
+ const stale = (current.data || []).map((f) => f.name || f._id).filter((name) => !names.includes(name));
+ if (stale.length) await ProblemModel.delTestdata(DOMAIN, docId, stale, operator);
+ }
+ const after = await coll.findOne({ domainId: DOMAIN, docType: 10, pid: item.pid });
+ if (after?.docId !== docId || after.content !== JSON.stringify({ zh: statement }) || after.owner !== operator) {
+ throw new Error(`Verification failed: ${item.pid}`);
+ }
+ if (plannedNew(item.pid) && !progress[item.pid]) {
+ progress[item.pid] = docId;
+ const tempPath = `${progressPath}.tmp`;
+ fs.writeFileSync(tempPath, JSON.stringify(progress, null, 2));
+ fs.renameSync(tempPath, progressPath);
+ }
+ done++;
+ const action = current ? 'UPDATE' : 'NEW';
+ report({ message: `${done}/${packages.length} ${action} ${item.pid} docId=${docId} owner=${operator} files=${names.length}` });
+ }
+ return { done };
+}
+
+const apply = (ctx) => ctx.addScript('hgnuImport413', 'HGNU Hydro 4.13.4 import', Schema.any(), run);
+module.exports = { apply, run, plannedNew, readPackages };
diff --git a/packages/hydrooj/src/script/hgnuRejudgeBatch.js b/packages/hydrooj/src/script/hgnuRejudgeBatch.js
new file mode 100644
index 0000000000..5ee456ef39
--- /dev/null
+++ b/packages/hydrooj/src/script/hgnuRejudgeBatch.js
@@ -0,0 +1,40 @@
+/* eslint-disable no-await-in-loop -- Preserve ordered updates and progress checkpoints. */
+const schemastery = require('schemastery');
+const Schema = schemastery.default?.any ? schemastery.default : schemastery;
+const RecordModel = require('../model/record').default;
+const db = require('../service/db').default;
+
+async function run(arg = {}, report = console.log) {
+ const domainId = arg.domain || 'system';
+ const uid = Number(arg.uid || 0);
+ const limit = Math.min(Math.max(Number(arg.limit || 200), 1), 50000);
+ const apply = !!arg.apply;
+ const match = { domainId, status: 0 };
+ if (uid) match.uid = uid;
+ const coll = db.collection('record');
+ const total = await coll.countDocuments(match);
+ const pids = await coll.aggregate([
+ { $match: match },
+ { $group: { _id: '$pid' } },
+ { $sort: { _id: 1 } },
+ ]).toArray();
+ report({ message: `PENDING ${total} waiting records across ${pids.length} problems` });
+ if (!apply) return { total };
+ let enqueued = 0;
+ let problems = 0;
+ for (const row of pids) {
+ if (enqueued >= limit) break;
+ const take = Math.min(limit - enqueued, 50000);
+ const rids = await coll.find({ ...match, pid: row._id })
+ .sort({ _id: 1 }).limit(take).project({ _id: 1 }).toArray();
+ if (!rids.length) continue;
+ await RecordModel.judge(domainId, rids.map((r) => r._id), 0, {}, { type: 'judge', rejudge: true });
+ enqueued += rids.length;
+ problems++;
+ }
+ report({ message: `DONE enqueued=${enqueued} problems=${problems} remaining=${total - enqueued}` });
+ return { enqueued, remaining: total - enqueued };
+}
+
+const apply = (ctx) => ctx.addScript('hgnuRejudgeBatch', 'Re-enqueue waiting records in batches', Schema.any(), run);
+module.exports = { apply, run };
diff --git a/packages/hydrooj/src/script/hgnuSubmitStd.js b/packages/hydrooj/src/script/hgnuSubmitStd.js
new file mode 100644
index 0000000000..2ccdaa7cc8
--- /dev/null
+++ b/packages/hydrooj/src/script/hgnuSubmitStd.js
@@ -0,0 +1,128 @@
+/* eslint-disable no-await-in-loop -- Preserve ordered updates and progress checkpoints. */
+// 批量提交题包 std.cpp 到学校 Hydro OJ(4.13.4 脚本格式)
+// 复制到 /opt/HGNUOJ-Hydro/Hydro/packages/hydrooj/src/script/hgnuSubmitStd.js
+//
+// 预览: hydrooj cli script hgnuSubmitStd '{"base":"/root/hydro_export","uid":607}'
+// 提交: hydrooj cli script hgnuSubmitStd '{"base":"/root/hydro_export","uid":607,"apply":true}'
+// 查结果:hydrooj cli script hgnuSubmitStd '{"base":"/root/hydro_export","uid":607,"check":true}'
+//
+// 可选参数:
+// only: "P5007" 或题名片段,只处理匹配的题
+// lang: 默认 cc.cc17o2(C++17 + O2)
+// delay: 每题间隔毫秒,默认 300
+// skipAccepted: 默认 true,已有 AC 记录的题跳过
+const fs = require('fs');
+const path = require('path');
+const schemastery = require('schemastery');
+const Schema = schemastery.default?.any ? schemastery.default : schemastery;
+const ProblemModel = require('../model/problem').default;
+const RecordModel = require('../model/record').default;
+const db = require('../service/db').default;
+const { STATUS, STATUS_TEXTS } = require('@hydrooj/common');
+
+const DOMAIN = 'system';
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+function loadItems(base, only, pidSet) {
+ const root = path.resolve(base);
+ const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8'));
+ if (!Array.isArray(manifest)) throw new TypeError('manifest.json must be an array');
+ return manifest
+ .filter((x) => (!pidSet || pidSet.has(x.pid))
+ && (!only || x.pid === only || String(x.title).includes(only)))
+ .map((x) => ({ ...x, stdFile: path.join(root, 'std', `${x.pid}.cpp`) }));
+}
+
+async function run(arg = {}, report = console.log) {
+ const base = arg.base || '/root/hydro_export';
+ const uid = Number(arg.uid);
+ const lang = arg.lang || 'cc.cc17o2';
+ const delay = Math.max(0, Number(arg.delay ?? 300));
+ const only = arg.only || '';
+ const apply = !!arg.apply;
+ const check = !!arg.check;
+ const skipAccepted = arg.skipAccepted !== false;
+ let pidSet = null;
+ if (Array.isArray(arg.pids)) pidSet = new Set(arg.pids.map(String));
+ else if (arg.list) {
+ const listPath = path.resolve(arg.list);
+ pidSet = new Set(Object.keys(JSON.parse(fs.readFileSync(listPath, 'utf8'))));
+ }
+ if (apply && (!Number.isSafeInteger(uid) || uid < 1)) throw new Error('apply 需要正整数 uid');
+ if (check && (!Number.isSafeInteger(uid) || uid < 1)) throw new Error('check 需要正整数 uid');
+
+ const items = loadItems(base, only, pidSet);
+ const missing = items.filter((x) => !fs.existsSync(x.stdFile));
+ if (missing.length) {
+ throw new Error(`缺少 std 文件: ${missing.slice(0, 10).map((x) => x.pid).join(', ')}`);
+ }
+
+ const coll = db.collection('record');
+ const statusText = (s) => (STATUS_TEXTS && STATUS_TEXTS[s]) || String(s);
+
+ if (check) {
+ const counts = {};
+ const bad = [];
+ for (const item of items) {
+ const pdoc = await ProblemModel.get(DOMAIN, item.pid);
+ if (!pdoc) {
+ bad.push([item.pid, 'MISSING_PROBLEM']);
+ continue;
+ }
+ const r = await coll.findOne({ domainId: DOMAIN, pid: pdoc.docId, uid }, { sort: { _id: -1 } });
+ if (!r) {
+ counts.NO_RECORD = (counts.NO_RECORD || 0) + 1;
+ bad.push([item.pid, 'NO_RECORD']);
+ continue;
+ }
+ const key = statusText(r.status);
+ counts[key] = (counts[key] || 0) + 1;
+ if (r.status !== STATUS.STATUS_ACCEPTED) bad.push([item.pid, key, r.score]);
+ }
+ report({ message: `CHECK ${JSON.stringify(counts)}` });
+ if (bad.length) report({ message: `NOT_AC ${JSON.stringify(bad.slice(0, 50))}` });
+ return { checked: items.length, counts, bad: bad.length };
+ }
+
+ if (!apply) {
+ report({
+ message: `PLAN submit=${items.length} uid=${uid} lang=${lang} delay=${delay}ms skipAccepted=${skipAccepted}`,
+ });
+ return { total: items.length };
+ }
+
+ let submitted = 0;
+ let skipped = 0;
+ const failed = [];
+ for (let i = 0; i < items.length; i++) {
+ const item = items[i];
+ try {
+ const pdoc = await ProblemModel.get(DOMAIN, item.pid);
+ if (!pdoc) throw new Error('题目不存在');
+ if (skipAccepted) {
+ const ac = await coll.findOne({
+ domainId: DOMAIN, pid: pdoc.docId, uid, status: STATUS.STATUS_ACCEPTED,
+ });
+ if (ac) {
+ skipped++;
+ report({ message: `${i + 1}/${items.length} SKIP-AC ${item.pid}` });
+ continue;
+ }
+ }
+ const code = fs.readFileSync(item.stdFile, 'utf8');
+ const rid = await RecordModel.add(DOMAIN, pdoc.docId, uid, lang, code, true);
+ submitted++;
+ report({ message: `${i + 1}/${items.length} SUBMIT ${item.pid} ${item.title} rid=${rid}` });
+ if (delay) await sleep(delay);
+ } catch (e) {
+ failed.push(`${item.pid}: ${e.message}`);
+ report({ message: `${i + 1}/${items.length} FAIL ${item.pid}: ${e.message}` });
+ }
+ }
+ report({ message: `DONE submitted=${submitted} skippedAC=${skipped} failed=${failed.length}` });
+ if (failed.length) report({ message: failed.join('\n') });
+ return { submitted, skipped, failed: failed.length };
+}
+
+const apply = (ctx) => ctx.addScript('hgnuSubmitStd', 'Submit std.cpp to problems', Schema.any(), run);
+module.exports = { apply, run, loadItems };
diff --git a/packages/hydrooj/src/script/hgnuSystemMembership.ts b/packages/hydrooj/src/script/hgnuSystemMembership.ts
new file mode 100644
index 0000000000..e4942ed1f4
--- /dev/null
+++ b/packages/hydrooj/src/script/hgnuSystemMembership.ts
@@ -0,0 +1,9 @@
+import type { Context } from '../context';
+import { ensureSystemMembership } from '../upgrade';
+
+// Repair installations that have already passed the upstream v4 -> v5 migration.
+// Use a separate channel so future upstream core migration numbers stay intact.
+export function apply(ctx: Context) {
+ if (process.env.HYDRO_CLI) return;
+ ctx.inject(['migration'], (c) => c.migration.registerChannel('hgnu-system-membership', [ensureSystemMembership]));
+}
diff --git a/packages/hydrooj/src/script/rating.ts b/packages/hydrooj/src/script/rating.ts
index c5a7b42c57..0f7107e5a2 100644
--- a/packages/hydrooj/src/script/rating.ts
+++ b/packages/hydrooj/src/script/rating.ts
@@ -25,7 +25,7 @@ interface RpDef {
base: number;
}
-const { log, max, min } = Math;
+const { max, min } = Math;
export const RpTypes: Record = {
problem: {
@@ -38,7 +38,6 @@ export const RpTypes: Record = {
{
docId: pdoc.docId,
rid: { $ne: null },
- uid: { $ne: pdoc.owner },
score: { $gt: 0 },
},
);
@@ -49,7 +48,7 @@ export const RpTypes: Record = {
udict[psdoc.uid] += min(psdoc.score, 100) * p;
}
}
- for (const key in udict) udict[key] = max(0, min(udict[key], log(udict[key]) / log(1.03)));
+ for (const key in udict) udict[key] /= 10;
},
hidden: false,
base: 0,
diff --git a/packages/hydrooj/src/service/bus.ts b/packages/hydrooj/src/service/bus.ts
index 858bfdf122..333ac3c8c7 100644
--- a/packages/hydrooj/src/service/bus.ts
+++ b/packages/hydrooj/src/service/bus.ts
@@ -46,6 +46,11 @@ export interface EventMap {
'user/get': (udoc: User) => void;
'user/delcache': (content: string | true) => void;
+ 'student/delcache': (content: string) => VoidReturn;
+ 'student/cacheActivity': (cls: string, content: string) => VoidReturn;
+ 'student/cacheClassList': (content: string) => VoidReturn;
+ 'student/invalidateClassListCache': () => VoidReturn;
+ 'student/invalidateActivityCache': () => VoidReturn;
'user/import/parse': (payload: any, messages: string[]) => VoidReturn;
'user/import/create': (uid: number, udoc: any) => VoidReturn;
diff --git a/packages/hydrooj/src/settings.ts b/packages/hydrooj/src/settings.ts
index 7f6f170bf7..4311065459 100644
--- a/packages/hydrooj/src/settings.ts
+++ b/packages/hydrooj/src/settings.ts
@@ -103,7 +103,7 @@ export class SettingService extends Service {
async _actualMigrate(schema: Schema) {
const processNode = async (path: string[], node: Schema) => {
for (const item of node.list || []) await processNode(path, item); // eslint-disable-line no-await-in-loop
- for (const key in node.dict || {}) await processNode([...path, ...key], node.dict[key]); // eslint-disable-line no-await-in-loop
+ for (const key in node.dict || {}) await processNode([...path, key], node.dict[key]); // eslint-disable-line no-await-in-loop
if (['string', 'number', 'boolean'].includes(node.type)) {
const value = this.initialValues[path.join('.')];
const migrated = this.initialValues[`${path.join('.')}__migrated`];
@@ -115,9 +115,10 @@ export class SettingService extends Service {
if (node.type === 'boolean') parsed = !!value && !['off', '0', 'false'].includes(value);
} catch (e) { }
if (parsed === undefined) return;
- await this.ctx.db.collection('system').updateOne({ _id: `${path.join('.')}__migrated` }, { $set: { value: true } }, { upsert: true });
- this.ctx.logger.info('Migrating %s: %o', path.join('.'), parsed);
await this.saveConfig(this.applyDelta(this.systemConfig, path.join('.'), parsed));
+ await this.ctx.db.collection('system').updateOne({ _id: `${path.join('.')}__migrated` }, { $set: { value: true } }, { upsert: true });
+ this.initialValues[`${path.join('.')}__migrated`] = true;
+ this.ctx.logger.info('Migrated %s', path.join('.'));
}
};
await processNode([], schema);
diff --git a/packages/hydrooj/src/upgrade.ts b/packages/hydrooj/src/upgrade.ts
index b7e70c444c..43cd5ecc13 100644
--- a/packages/hydrooj/src/upgrade.ts
+++ b/packages/hydrooj/src/upgrade.ts
@@ -20,7 +20,7 @@ import StorageModel from './model/storage';
import system from './model/system';
import TaskModel from './model/task';
import * as training from './model/training';
-import user, { handleMailLower } from './model/user';
+import user, { deleteUserCache, handleMailLower } from './model/user';
import {
iterateAllContest, iterateAllDomain, iterateAllProblem, iterateAllUser,
} from './pipelineUtils';
@@ -36,6 +36,21 @@ Please use hydrooj@4 to perform these upgrades before upgrading to v5');
const onPrimary = { readPreference: 'primary' } as const;
+export async function ensureSystemMembership() {
+ const members = await domain.collUser.find({ domainId: 'system', join: true }, onPrimary)
+ .project({ uid: 1 }).toArray();
+ const missing = await user.coll.find({ _id: { $gt: 1, $nin: members.map((u) => u.uid) } }, onPrimary)
+ .project({ _id: 1 }).toArray();
+ // updateMany + upsert creates at most one document, not one per uid in $in.
+ for (const udoc of missing) {
+ await domain.collUser.updateOne(
+ { uid: udoc._id, domainId: 'system' }, { $set: { join: true } }, { upsert: true },
+ );
+ }
+ if (missing.length) deleteUserCache('system');
+ return true;
+}
+
export const coreScripts: MigrationScript[] = [
// Mark as used
async function init() {
@@ -577,16 +592,7 @@ export const coreScripts: MigrationScript[] = [
{ $or: [{ _join: { $exists: false } }, { _join: { $eq: null } }, { '_join.method': domain.JOIN_METHOD_NONE }] },
{ $set: { _join: { method: domain.JOIN_METHOD_ALL, role: 'default', expire: null }, _migratedJoin: true } },
);
- const domainUser = await domain.collUser.find({ domainId: 'system', join: true }, onPrimary)
- .project({ uid: 1 }).toArray();
- const otherUsers = await user.coll.find({ _id: { $gt: 1, $nin: domainUser.map((u) => u.uid) } }, onPrimary)
- .project({ _id: 1 }).toArray();
- await domain.collUser.updateMany(
- { uid: { $in: otherUsers.map((u) => u._id) }, domainId: 'system' },
- { $set: { join: true } },
- { upsert: true },
- );
- return true;
+ return ensureSystemMembership();
},
async function _92_93(ctx) {
await ctx.inject(['oauth'], async (c) => {
diff --git a/packages/image-preview/README.md b/packages/image-preview/README.md
new file mode 100644
index 0000000000..1926d98280
--- /dev/null
+++ b/packages/image-preview/README.md
@@ -0,0 +1,13 @@
+# HGNU announcement image previews
+
+Enable this addon after `@hydrooj/ui-default`. Discussion bodies use `markdownImages`, which renders and sanitizes Markdown and authored HTML first, then adds image optimization. Existing discussion content and original files do not need migration.
+
+- The first body image loads normally; subsequent images use native lazy loading and asynchronous decoding.
+- Public `/file/:uid/:filename` raster images get versioned 480/960/1600px WebP variants. Responsive selection follows the browser's viewport and pixel density. PNG previews use lossless WebP to preserve screenshot text. GIF, SVG, animated WebP/PNG, corrupt images, files over 32 MiB or 80 megapixels, external images, and restricted attachments keep their original URLs.
+- Width/height and aspect ratio reserve space before loading, including existing percentage-width HTML images. Existing links keep their destinations; other previews link to the original in a new tab.
+- Previews are generated on demand with two concurrent jobs and deduplicated requests. Cached files are outside the project under `~/.hydro/cache/image-preview`. The default disk budget is 512 MiB; an hourly sweep removes oldest excess files and files older than 30 days.
+- Versioned preview responses have ETag and one-day caching. Each origin request verifies the live storage mapping, including deletion and replacement. Preview URLs cannot read problem/contest attachments or arbitrary storage paths.
+
+When changing encoding parameters or the derivative format, increment `revision` in `images.ts` so existing browser and disk caches use new URLs.
+
+The UI filter falls back to the usual Markdown renderer if the addon is disabled. Rollback consists of removing the addon from `.hydro/addon.json` and restarting OJ. The cache is disposable. To deploy to another machine, install dependencies from `yarn.lock` and enable the addon there.
diff --git a/packages/image-preview/images.ts b/packages/image-preview/images.ts
new file mode 100644
index 0000000000..776af2cb12
--- /dev/null
+++ b/packages/image-preview/images.ts
@@ -0,0 +1,187 @@
+import { createHash, randomUUID } from 'crypto';
+import { createReadStream } from 'fs';
+import { mkdir, readdir, rename, stat, unlink, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { load } from 'cheerio';
+import { LRUCache } from 'lru-cache';
+import sharp from 'sharp';
+
+export const widths = [480, 960, 1600];
+const maxBytes = 32 * 1024 * 1024;
+const maxPixels = 80 * 1000 * 1000;
+const revision = '1';
+
+export interface Source {
+ path: string;
+ _id: string;
+ link?: string;
+ size?: number;
+ etag?: string;
+ lastModified?: Date;
+}
+
+export interface Dimensions {
+ width: number;
+ height: number;
+ format: string;
+}
+
+// Only public user-file paths use this endpoint. Contest/problem attachments keep their access checks.
+export function userFile(src: string) {
+ if (!/^\/file\/\d+\/[^/?#]+$/.test(src)) return null;
+ try {
+ const path = `user/${decodeURIComponent(src.slice(6))}`;
+ if (path.includes('..') || path.includes('\\') || path.split('/').length !== 3) return null;
+ return path;
+ } catch {
+ return null;
+ }
+}
+
+export function version(source: Source) {
+ return createHash('sha256').update(JSON.stringify([
+ revision, source.link || source._id, source.size, source.etag, source.lastModified,
+ ])).digest('hex').slice(0, 24);
+}
+
+export class ImagePreviews {
+ private metadata = new LRUCache>({ max: 2048 });
+ private pending = new Map>();
+ private active = 0;
+ private waiting: (() => void)[] = [];
+
+ constructor(public directory: string, private read: (source: Source) => Promise) {}
+
+ private async limited(fn: () => Promise) {
+ if (this.active >= 2) {
+ if (this.waiting.length >= 64) throw new Error('Image preview queue is full');
+ await new Promise((resolve) => this.waiting.push(resolve));
+ } else this.active++;
+ try {
+ return await fn();
+ } finally {
+ const next = this.waiting.shift();
+ if (next) next();
+ else this.active--;
+ }
+ }
+
+ private async input(source: Source) {
+ if (!source.size || source.size > maxBytes) throw new Error('Image exceeds preview size limit');
+ const buffer = await this.read(source);
+ if (buffer.length > maxBytes) throw new Error('Image exceeds preview size limit');
+ return buffer;
+ }
+
+ async dimensions(source: Source) {
+ const key = version(source);
+ if (!this.metadata.has(key)) {
+ const result = this.limited(async () => {
+ if (source.size > maxBytes || !/\.(?:jpe?g|png|webp)$/i.test(source.path)) return null;
+ const info = await sharp(await this.input(source), { limitInputPixels: maxPixels }).metadata();
+ if (!['jpeg', 'png', 'webp'].includes(info.format) || (info.pages || 1) > 1 || !info.width || !info.height) return null;
+ const swap = (info.orientation || 1) >= 5;
+ return { width: swap ? info.height : info.width, height: swap ? info.width : info.height, format: info.format };
+ }).catch(() => null);
+ this.metadata.set(key, result);
+ }
+ return this.metadata.get(key);
+ }
+
+ async derivative(source: Source, width: number) {
+ if (!widths.includes(width)) throw new Error('Unsupported preview width');
+ const key = `${version(source)}-${width}`;
+ const target = join(this.directory, `${key}.webp`);
+ try {
+ await stat(target);
+ return target;
+ } catch { /* Generate a missing derivative once, including simultaneous requests. */ }
+ if (!this.pending.has(key)) {
+ const work = (async () => {
+ const info = await this.dimensions(source);
+ if (!info) throw new Error('Unsupported image');
+ return this.limited(async () => {
+ const buffer = await this.input(source);
+ const output = await sharp(buffer, { limitInputPixels: maxPixels }).rotate()
+ .resize({ width, withoutEnlargement: true })
+ .webp({ quality: 84, lossless: info.format === 'png', effort: 4 }).toBuffer();
+ await mkdir(this.directory, { recursive: true });
+ const temporary = `${target}.${randomUUID()}.tmp`;
+ try {
+ await writeFile(temporary, output, { mode: 0o600 });
+ await rename(temporary, target);
+ } finally {
+ await unlink(temporary).catch(() => {});
+ }
+ return target;
+ });
+ })().finally(() => this.pending.delete(key));
+ this.pending.set(key, work);
+ }
+ return this.pending.get(key);
+ }
+
+ async render(html: string, lookup: (paths: string[]) => Promise) {
+ const $ = load(html, null, false);
+ const images = $('img').toArray();
+ const paths = [...new Set(images.map((img) => userFile($(img).attr('src') || '')).filter(Boolean))];
+ const sources = new Map((paths.length ? await lookup(paths) : []).map((source) => [source.path, source]));
+ // Keep metadata work bounded too: a long article must not create 94 concurrent image decoders.
+ const dimensions = new Map();
+ const remaining = [...sources.values()];
+ await Promise.all([0, 1].map(async () => {
+ while (remaining.length) {
+ const source = remaining.shift();
+ const info = await this.dimensions(source); // eslint-disable-line no-await-in-loop
+ if (info) dimensions.set(source.path, info);
+ }
+ }));
+ for (const [i, element] of images.entries()) {
+ const img = $(element);
+ img.attr('loading', i === 0 ? 'eager' : 'lazy');
+ img.attr('decoding', 'async');
+ const src = img.attr('src') || '';
+ const path = userFile(src);
+ const source = sources.get(path);
+ const info = dimensions.get(path);
+ if (!source || !info) continue;
+ const url = (width: number) => `${src}/preview/${width}/${version(source)}.webp`;
+ const authoredWidth = img.attr('width');
+ const authoredHeight = img.attr('height');
+ const percent = /^\d+(?:\.\d+)?%$/.test(authoredWidth || '') ? Math.min(100, Number.parseFloat(authoredWidth)) : 100;
+ img.attr('src', url(960));
+ img.attr('srcset', widths.map((width) => `${url(width)} ${Math.min(width, info.width)}w`).filter((value, index, all) =>
+ all.findIndex((other) => other.split(' ').at(-1) === value.split(' ').at(-1)) === index).join(', '));
+ img.attr('sizes', `(max-width: 600px) ${percent}vw, (max-width: 1200px) ${Math.round(percent * 0.72)}vw, ${Math.round(percent * 8.4)}px`);
+ if (!authoredWidth) img.attr('width', String(info.width));
+ if (!authoredHeight) {
+ img.attr('height', String(info.height));
+ img.attr('style', `${img.attr('style') || ''};height:auto;aspect-ratio:${info.width}/${info.height}`);
+ }
+ // An existing link keeps its original destination (e.g. a linked poster).
+ if (!img.closest('a').length) {
+ img.wrap($(' ').attr({ href: `${src}?noDisposition=true`, target: '_blank', rel: 'noopener', title: '查看原图' }));
+ }
+ }
+ return $.html();
+ }
+
+ async prune(maxSize: number) {
+ await mkdir(this.directory, { recursive: true });
+ const entries = await readdir(this.directory);
+ const files = (await Promise.all(entries.filter((file) => /^[a-f0-9]{24}-\d+\.webp$/.test(file)).map(async (file) => {
+ const name = join(this.directory, file);
+ return { name, ...await stat(name).catch(() => ({ size: 0, mtimeMs: 0 })) };
+ }))).sort((a, b) => a.mtimeMs - b.mtimeMs);
+ let total = files.reduce((sum, file) => sum + file.size, 0);
+ for (const file of files) {
+ if (total <= maxSize && Date.now() - file.mtimeMs < 30 * 86400 * 1000) continue;
+ await unlink(file.name).catch(() => {}); // eslint-disable-line no-await-in-loop
+ total -= file.size;
+ }
+ }
+
+ stream(file: string) {
+ return createReadStream(file);
+ }
+}
diff --git a/packages/image-preview/index.ts b/packages/image-preview/index.ts
new file mode 100644
index 0000000000..8e48476b36
--- /dev/null
+++ b/packages/image-preview/index.ts
@@ -0,0 +1,84 @@
+import { stat } from 'fs/promises';
+import { homedir } from 'os';
+import { join } from 'path';
+import {
+ Context, Handler, NotFoundError, param, Schema, Service, StorageModel, Types,
+} from 'hydrooj';
+import { ImagePreviews, Source, version, widths } from './images';
+
+export const Config = Schema.object({
+ cacheMiB: Schema.number().default(512).min(64).max(4096).description('Disk budget for regenerable image previews'),
+});
+
+export class ImagePreviewService extends Service {
+ previews: ImagePreviews;
+
+ constructor(ctx: Context, config: ReturnType) {
+ super(ctx, 'image-preview');
+ this.previews = new ImagePreviews(join(homedir(), '.hydro/cache/image-preview'), async (source) => {
+ const stream = await ctx.storage.get(source.link || source._id);
+ const chunks: Buffer[] = [];
+ let size = 0;
+ for await (const chunk of stream) {
+ const buffer = Buffer.from(chunk);
+ size += buffer.length;
+ if (size > 32 * 1024 * 1024) {
+ stream.destroy();
+ throw new Error('Image exceeds preview size limit');
+ }
+ chunks.push(buffer);
+ }
+ return Buffer.concat(chunks);
+ });
+ const prune = () => this.previews.prune(config.cacheMiB * 1024 * 1024).catch((e) => ctx.logger.warn(e));
+ ctx.on('app/ready', prune);
+ ctx.interval(prune, 3600 * 1000);
+ }
+
+ render(html: string) {
+ return this.previews.render(html, (paths) => StorageModel.coll.find({ path: { $in: paths }, autoDelete: null }).toArray());
+ }
+}
+
+class ImagePreviewHandler extends Handler {
+ noCheckPermView = true;
+ notUsage = true;
+
+ @param('uid', Types.PositiveInt)
+ @param('filename', Types.Filename)
+ @param('width', Types.Range(widths))
+ @param('revision', Types.String)
+ async get(domainId: string, uid: number, filename: string, width: number, revision: string) {
+ const source: Source = await StorageModel.coll.findOne({ path: `user/${uid}/${filename}`, autoDelete: null });
+ if (!source || revision !== `${version(source)}.webp`) throw new NotFoundError(filename);
+ const service = this.ctx.get('image-preview') as ImagePreviewService;
+ let file: string;
+ try {
+ file = await service.previews.derivative(source, width);
+ } catch {
+ // Unsupported/corrupt images and temporary conversion failures keep the original download working.
+ this.response.redirect = this.url('fs_download', { uid, filename });
+ this.response.addHeader('Cache-Control', 'no-store');
+ return;
+ }
+ this.response.type = 'image/webp';
+ // The framework's response.etag shortcut resets Cache-Control to just "public".
+ const etag = `"${version(source)}-${width}"`;
+ this.response.addHeader('ETag', etag);
+ this.response.addHeader('Cache-Control', 'public, max-age=86400, immutable');
+ this.response.addHeader('X-Content-Type-Options', 'nosniff');
+ this.response.addHeader('Content-Length', String((await stat(file)).size));
+ if (this.request.headers['if-none-match'] === etag) {
+ this.response.status = 304;
+ this.response.body = Buffer.alloc(0);
+ } else this.response.body = service.previews.stream(file);
+ }
+}
+
+export const inject = ['db', 'storage'];
+
+export function apply(ctx: Context, config: ReturnType) {
+ if (process.env.HYDRO_CLI) return;
+ ctx.plugin(ImagePreviewService, config);
+ ctx.Route('image_preview', '/file/:uid/:filename/preview/:width/:revision', ImagePreviewHandler);
+}
diff --git a/packages/image-preview/package.json b/packages/image-preview/package.json
new file mode 100644
index 0000000000..d0f200dcdc
--- /dev/null
+++ b/packages/image-preview/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@hgnuoj/image-preview",
+ "version": "1.0.0",
+ "private": true,
+ "main": "index.ts",
+ "license": "AGPL-3.0-only",
+ "dependencies": {
+ "cheerio": "~1.0.0",
+ "lru-cache": "^11.5.3",
+ "sharp": "0.34.5"
+ },
+ "peerDependencies": {
+ "hydrooj": "workspace:^"
+ }
+}
diff --git a/packages/ui-default/backendlib/template.ts b/packages/ui-default/backendlib/template.ts
index 39f4512253..60139e8c12 100644
--- a/packages/ui-default/backendlib/template.ts
+++ b/packages/ui-default/backendlib/template.ts
@@ -234,6 +234,21 @@ export class TemplateService extends Service {
}
const env = new Nunjucks(Loader);
+ env.addFilter('markdownImages', (text, callback) => {
+ try {
+ const html = ensureTag(markdown.render(text));
+ const previews = ctx.get('image-preview') as { render: (html: string) => Promise } | undefined;
+ if (!previews) callback(null, html);
+ else {
+ previews.render(html).then((result) => callback(null, result), (error) => {
+ ctx.logger.warn('Image preview rendering failed: %s', error.message);
+ callback(null, html);
+ });
+ }
+ } catch (error) {
+ callback(error);
+ }
+ }, true);
env.addGlobal('findSubModule', (prefix) => Object.keys(that.registry).filter((n) => n.startsWith(prefix)));
env.addGlobal('templateExists', (name) => !!that.registry[name]);
diff --git a/packages/ui-default/common/variables.inc.styl b/packages/ui-default/common/variables.inc.styl
index 8adb3ef3bb..a581082a73 100644
--- a/packages/ui-default/common/variables.inc.styl
+++ b/packages/ui-default/common/variables.inc.styl
@@ -189,7 +189,7 @@ $badge-text-color = {
'lv10': #FFF,
}
$badge-bg-color = {
- 'mod': #cf70ab,
+ 'mod': #ffcdcd,
'su': #ff0000,
'lv0': #efefef,
'lv1': #9db4bd,
diff --git a/packages/ui-default/index.ts b/packages/ui-default/index.ts
index adcf3cf3b9..dab4895b6b 100644
--- a/packages/ui-default/index.ts
+++ b/packages/ui-default/index.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'crypto';
import { readFileSync } from 'fs';
import { join } from 'path';
import {
@@ -8,6 +9,26 @@ import convert from 'schemastery-jsonschema';
import { presetRenderers } from './backendlib/contentRenderer';
import markdown from './backendlib/markdown';
import { TemplateService } from './backendlib/template';
+import { registerWikiRoutes } from './wiki/handler';
+
+declare module 'hydrooj' {
+ interface UiContextBase {
+ assetRevision?: string;
+ }
+}
+
+function getAssetRevision(version: string) {
+ try {
+ const hash = createHash('sha256');
+ for (const name of [`theme-${version}.css`, `hydro-${version}.js`]) {
+ hash.update(readFileSync(join(__dirname, 'public', name)));
+ }
+ return hash.digest('hex').slice(0, 12);
+ } catch (err) {
+ if (err.code !== 'ENOENT') throw err;
+ return undefined;
+ }
+}
class WikiHelpHandler extends Handler {
noCheckPermView = true;
@@ -200,8 +221,11 @@ export function apply(ctx: Context, config: ReturnType) {
ctx.Route('config_schema', '/manage/config/schema.json', SystemConfigSchemaHandler, PRIV.PRIV_EDIT_SYSTEM);
});
if (process.env.HYDRO_CLI) return;
+ const assetRevision = !process.env.DEV && getAssetRevision(global.Hydro.version['ui-default']);
ctx.Route('wiki_help', '/wiki/help', WikiHelpHandler);
ctx.Route('wiki_about', '/wiki/about', WikiAboutHandler);
+ registerWikiRoutes(ctx);
+ ctx.injectUI('Nav', 'wiki_main', { prefix: 'Wiki', displayName: 'Wiki', before: 'homework_main' });
ctx.Route('set_theme', '/set_theme/:theme', SetThemeHandler);
ctx.Route('set_legacy', '/legacy', LegacyModeHandler);
ctx.Route('markdown', '/markdown', MarkdownHandler);
@@ -213,6 +237,7 @@ export function apply(ctx: Context, config: ReturnType) {
}
});
ctx.on('handler/after', async (that) => {
+ if (assetRevision) that.UiContext.assetRevision = assetRevision;
that.UiContext.SWConfig = {
preload: config.serviceWorker.preload,
hosts: [
diff --git a/packages/ui-default/locales/zh.yaml b/packages/ui-default/locales/zh.yaml
index 77429a3006..35a13994b6 100644
--- a/packages/ui-default/locales/zh.yaml
+++ b/packages/ui-default/locales/zh.yaml
@@ -2,7 +2,7 @@ __langname: 简体中文
'"{data}" copied to clipboard!': “{data}”已复制到剪贴板!
'[Richtext message]': '[富文本消息]'
'{0} comments': '{0} 条评论'
-'{0} discussions': '{0} 条讨论'
+'{0} discussions': '{0} 条公告'
'{0} is a moderator of this domain.': '{0}是这个域的管理者之一。'
'{0} is a superuser.': '{0}是超级管理员。'
'{0} limit exceeded (limit: {2} operations in {1} seconds).': '{0} 超过频率限制。限制:{1} 秒内最多 {2} 次操作。'
@@ -15,20 +15,20 @@ __langname: 简体中文
'{0}: Permissions': '{0}: 权限'
'{0}: Roles': '{0}: 角色'
'{0}: Users': '{0}: 用户'
-'# My Submissions': '我的递交数'
-'# Submissions': '递交数'
-'↓ # Comments': '↓ 评论数'
-'↓ # Enrollees': '↓ 参与人数'
-'↓ # Likes': '↓ 赞数'
-'↓ # Stars': '↓ 收藏数'
-'↓ Create Time': '↓ 创建时间'
-'↓ Update Time': '↓ 更新时间'
-'A domain ID cannot be changed after creation. It is supposed to be:': '创建后将无法更改 ID。ID 必须满足以下条件:'
-'Copy "{data}" failed :(': '复制“{data}”失败 :('
-'Copy failed :(': '复制失败 :('
+'# My Submissions': 我的递交数
+'# Submissions': 递交数
+'↓ # Comments': ↓ 评论数
+'↓ # Enrollees': ↓ 参与人数
+'↓ # Likes': ↓ 赞数
+'↓ # Stars': ↓ 收藏数
+↓ Create Time: ↓ 创建时间
+↓ Update Time: ↓ 更新时间
+'A domain ID cannot be changed after creation. It is supposed to be:': 创建后将无法更改 ID。ID 必须满足以下条件:
+Copy "{data}" failed :(: 复制“{data}”失败 :(
+Copy failed :(: 复制失败 :(
'Current dataset: {0}': '当前测试数据: {0}'
'Discussion: Terms Of Service': 讨论区服务条款
-'Drag and drop testcases here:': '拖拽测试点到此处:'
+'Drag and drop testcases here:': 拖拽测试点到此处:
'Enter a new name for the file: ': 请输入新的文件名:
'Failed to get credential: {0}': '获取认证数据失败: {0}'
'File IO: {0}': 文件IO:{0}
@@ -37,23 +37,24 @@ __langname: 简体中文
'Hello, {0}! You can click following link to active your new email of your {1} account:': 您好,{0}!您可以点击以下链接来激活您 {1} 账户的新电子邮件地址:
'Hello, {0}! You can click following link to reset the password of your {1} account:': 您好,{0}!您可以点击以下链接来重置您 {1} 账户的密码:
'Hello! You can click following link to sign up your {0} account:': 您好!您可以点击以下链接来注册您的 {0} 账户:
-'Join {0}': '加入 {0}'
+Join {0}: 加入 {0}
'No': 否
'Note: Problem title may not be hidden.': 注意:题目标题可能不会被隐藏。
'Or use the following link:': 或使用以下链接:
-'Packages have new version: {0}': '以下组件有新版本: {0}'
+'Packages have new version: {0}': 以下组件有新版本: {0}
'Please use your two factor authentication app to scan the qrcode below:': '请使用你的两步验证APP扫描此二维码:'
-'Role {1} already exists in domain {0}.': '域 {0} 中已存在角色 {1}。'
+Role {1} already exists in domain {0}.: 域 {0} 中已存在角色 {1}。
'Solved {0} problems, RP: {1} (No. {2})': '解决了 {0} 道题目,RP: {1} (No. {2})'
'The domain owner:': 域所有者:
-'The value `{1}` of {0} already exists.': '{0} 的值 `{1}` 已经存在。'
-'Tip: You are entering sudo mode.': '提示:您正在进行身份验证 。'
+The value `{1}` of {0} already exists.: '{0} 的值 `{1}` 已经存在。'
+'Tip: You are entering sudo mode.': 提示:您正在进行身份验证 。
'Yes': 是
-"After you've performed a sudo-protected action, you'll only be asked to re-authenticate again after a few hours of inactivity.": 在您执行受保护的操作后,只有账户连续数小时不活动时,系统才会再次要求您重新验证身份。
-"Effects only when Difficulty is not 'Use algorithm calculated'.": 仅当难度不为“使用算法计算”时才起效。
-"Split by ', '.": 由“, ”或“,”分隔。
-"View other's records": 查看他人的记录
-"What's file?": 什么是文件?
+? After you've performed a sudo-protected action, you'll only be asked to re-authenticate again after a few hours of inactivity.
+: 在您执行受保护的操作后,只有账户连续数小时不活动时,系统才会再次要求您重新验证身份。
+Effects only when Difficulty is not 'Use algorithm calculated'.: 仅当难度不为“使用算法计算”时才起效。
+Split by ', '.: 由“, ”或“,”分隔。
+View other's records: 查看他人的记录
+What's file?: 什么是文件?
(All Problems): (所有题目)
(leave blank if none): (若不需要则留空)
(None): (无)
@@ -150,7 +151,8 @@ By clicking the button, you will become a member of the domain {0}.: 点击按
By Contest: 由比赛
By Language: 由语言
By Problem: 由题目
-By signing up a {0} universal account, you can submit code and join discussions in all online judging services provided by us.: 注册一个 {0} 通用账户,您就可以在我们提供的所有在线评测服务上提交代码、参与讨论。
+? By signing up a {0} universal account, you can submit code and join discussions in all online judging services provided by us.
+: 注册一个 {0} 通用账户,您就可以在我们提供的所有在线评测服务上提交代码、参与讨论。
By Status: 由状态
By Username / UID: 由用户名或 UID
Calendar View: 日历视图
@@ -196,7 +198,7 @@ Config: 配置
Confirm Access: 确认授权
Confirm deleting the selected roles?: 您确定删除所选角色吗?
Confirm deleting this comment? Its replies will be deleted as well.: 确认删除这个评论吗?回复会被同时删除。
-Confirm deleting this domain? This action cannot be undone.: '确认删除此域?此操作无法撤销。'
+Confirm deleting this domain? This action cannot be undone.: 确认删除此域?此操作无法撤销。
Confirm deleting this reply?: 确认删除这个回复吗?
Confirm end contest early? You will not be able to submit after this.: 确认提前结束比赛吗?之后您将无法提交代码。
Confirm rejudge this problem?: 确定要重测这道题吗?
@@ -239,14 +241,14 @@ Copyright Complaint: 版权申诉
Correction: 补题
CPU Info: CPU信息
Create a contest: 创建一个比赛
-Create a Discussion: 创建一个讨论
+Create a Discussion: 创建一个公告
Create a Post: 创建一个博文
Create a problem: 创建一个题目
Create Contest: 创建比赛
Create contests: 创建比赛
-Create Discussion in {0}: 在 {0} 下创建讨论
-Create Discussion: 创建讨论
-Create discussions: 创建讨论
+Create Discussion in {0}: 在 {0} 下创建公告
+Create Discussion: 创建公告
+Create discussions: 创建公告
Create Domain: 创建域
Create File: 创建文件
Create Group: 创建小组
@@ -281,12 +283,12 @@ Day: 日
Deadline: 截止时间
Default Code Language: 默认代码语言
Default Code Template: 默认代码模板
-Delete discussion replies of own discussion: 删除自己讨论中的回复
-Delete discussion replies: 删除讨论回复
-Delete discussions: 删除讨论
+Delete discussion replies of own discussion: 删除自己公告中的回复
+Delete discussion replies: 删除公告回复
+Delete discussions: 删除公告
Delete Domain: 删除域
-Delete own discussion replies: 删除讨论中自己的回复
-Delete own discussions: 删除自己的讨论
+Delete own discussion replies: 删除公告中自己的回复
+Delete own discussions: 删除自己的公告
Delete own problem solution replies: 删除题解中自己的回复
Delete own problem solutions: 删除自己的题解
Delete problem solution replies: 删除题解的回复
@@ -305,18 +307,18 @@ Difficulty displayed: 显示的难度
Difficulty: 难度
Disabled: 关闭
Disconnected from the server. trying to reconnect...: 到服务器的连接断开。正在重新连接...
-Discussion {1} not found.: 讨论 {1} 不存在。
-Discussion category {1} already exists.: 讨论分类 {1} 已经存在。
-Discussion category {1} not found.: 讨论分类 {1} 不存在。
-Discussion node {1} already exists.: 讨论节点 {1} 已经存在。
-Discussion node {1} not found.: 讨论节点 {1} 不存在。
-Discussion Nodes: 讨论节点
-discussion_create: 创建讨论
-discussion_edit: 编辑讨论
-discussion_main: 讨论
-discussion_node: 讨论
-Discussion: 讨论
-Discussions: 讨论
+Discussion {1} not found.: 公告 {1} 不存在。
+Discussion category {1} already exists.: 公告分类 {1} 已经存在。
+Discussion category {1} not found.: 公告分类 {1} 不存在。
+Discussion node {1} already exists.: 公告节点 {1} 已经存在。
+Discussion node {1} not found.: 公告节点 {1} 不存在。
+Discussion Nodes: 公告节点
+discussion_create: 创建公告
+discussion_edit: 编辑公告
+discussion_main: 公告
+discussion_node: 公告
+Discussion: 公告
+Discussions: 公告
Dismiss: 忽略
Display name {1} you want to set is used by others.: 您想要设置的显示名 {1} 已经被其他人使用了。
Display Name: 显示名
@@ -330,7 +332,7 @@ Domain ID cannot be changed once the domain is created.: 在创建后不能更
Domain ID: 域 ID
Domain Settings: 域设置
domain_dashboard: 管理域
-domain_discussion: 讨论节点
+domain_discussion: 公告节点
domain_edit: 编辑域资料
domain_join: 加入域
domain_main: 首页
@@ -354,14 +356,14 @@ Edit any contests: 修改任意的比赛
Edit any homework: 修改任意的作业
Edit Contest: 编辑比赛
Edit description of this domain: 修改此域描述
-Edit discussion replies of own discussion: 修改自己讨论中的回复
-Edit discussion replies: 修改讨论的回复
-Edit discussions: 修改讨论
+Edit discussion replies of own discussion: 修改自己公告中的回复
+Edit discussion replies: 修改公告的回复
+Edit discussions: 修改公告
Edit Domain: 编辑域
Edit Homework: 编辑作业
Edit own contests: 修改自己的比赛
-Edit own discussion replies: 修改讨论中自己的回复
-Edit own discussions: 修改自己的讨论
+Edit own discussion replies: 修改公告中自己的回复
+Edit own discussions: 修改自己的公告
Edit own homework: 修改自己的作业
Edit own problem solution replies: 修改题解中自己的回复
Edit own problem solutions: 修改自己的题解
@@ -415,7 +417,7 @@ Filename: 文件名
Files: 文件
Fill to Pretest: 填充到自测
Filter: 过滤
-First of Contest: 全场一血
+First of Contest: 全场一血
First of Problem: 题目一血
fontFamily: 字体
Footer: 页脚
@@ -444,7 +446,7 @@ Hidden: 隐藏
Hide all tags: 隐藏所有标签
Hide categorical tags: 隐藏分类标签
Hide tags: 隐藏标签
-Highlight discussions: 高亮讨论
+Highlight discussions: 高亮公告
Highlight: 高亮
Hint: 提示
Hint::icon::difficulty: Hydro 中题目的难度,根据递交数、通过率以及每个递交的递交时间和评测结果,综合计算得出,可能不准确。
@@ -500,7 +502,10 @@ Input: 输入
Insert Code: 插入代码
Insert Image: 插入图像
Installed Modules: 已安装的模块
-Instead of copying the test data directly, the test data of the copied problems will be linked to the test data of the source problems (called the source test data). Thus, the copied problems can observe the changes in the source test data. The permissions of the test data of the copied problems follow the source test data, e.g., you still might not download them but the judges can. By uploading some new test data, the link will be broken and the new test data will be used.: 虽然测试数据不会被复制,但是系统会将题目的测试数据链接到原题。因此在原题的数据被改动的时候,复制后的题目的数据也会同时改动。链接后的测试数据的权限以原题为准,比如您可能依旧无法下载数据,但是评测机可以。在题目设置页面中可以通过上传新的测试数据的方式,这个数据链接会被删除,以后将使用您的新测试数据。
+? Instead of copying the test data directly, the test data of the copied problems will be linked to the test data of the source problems (called the source test data). Thus, the copied problems can observe
+ the changes in the source test data. The permissions of the test data of the copied problems follow the source test data, e.g., you still might not download them but the judges can. By uploading some
+ new test data, the link will be broken and the new test data will be used.
+: 虽然测试数据不会被复制,但是系统会将题目的测试数据链接到原题。因此在原题的数据被改动的时候,复制后的题目的数据也会同时改动。链接后的测试数据的权限以原题为准,比如您可能依旧无法下载数据,但是评测机可以。在题目设置页面中可以通过上传新的测试数据的方式,这个数据链接会被删除,以后将使用您的新测试数据。
Introduce must not exceed 500 characters and it will be shown in the list view.: 简介不能超过 500 个字符,将显示在列表页面中。
Introduce: 简介
Invalid password for user {0}.: 用户 {0} 的密码错误。
@@ -553,7 +558,7 @@ Loading file...: 正在加载文件内容...
Location: 位置
Login to Attend Contest: 登录后参加比赛
Login to Claim Homework: 登录后认领作业
-Login to Create a Discussion: 登录后创建讨论
+Login to Create a Discussion: 登录后创建公告
Login to Submit: 登录后递交
Login: 登录
Logout All Sessions: 注销所有会话
@@ -613,11 +618,11 @@ New: 创建
No {0} at current.: 当前没有{0}。
No changes to make.: 没有任何修改。
No comments so far...: 目前还没有评论...
-No discussion yet...: 目前没有讨论…
+No discussion yet...: 目前没有公告…
No group available: 没有可用小组
No Permission to Attend Contest: 您没有权限参加比赛
No Permission to Claim Homework: 您没有权限认领作业
-No Permission to Create a Discussion: 您没有权限创建讨论
+No Permission to Create a Discussion: 您没有权限创建公告
No Permission to Submit: 您没有权限递交
No problem.: 没有题目。
No solutions so far...: 目前还没有题解...
@@ -638,7 +643,7 @@ Not wrapped with space: 两侧不含空格
Numeric PID: 数字题号
objective: 客观题
Oh, the user doesn't have any contributions!: 啊哦,这个用户还没贡献过题目~
-Oh, the user hasn't created any discussions yet!: 这个用户还没有发布过讨论
+Oh, the user hasn't created any discussions yet!: 这个用户还没有发布过公告
Oh, the user hasn't submitted yet!: 这个用户还没有交过题 _(:зゝ∠)_
Oh, there are no tasks that match the filter!: 喔,目前没有符合过滤条件的任务。
Oh, there is no submission!: 喔,还没有评测记录呢!
@@ -679,7 +684,7 @@ Path {0} not found.: 路径 {0} 不存在。
Peak Memory: 峰值内存
Peak Time: 峰值时间
perm_contest: 比赛
-perm_discussion: 讨论
+perm_discussion: 公告
perm_general: 一般
perm_homework: 作业
perm_problem_solution: 题解
@@ -702,7 +707,8 @@ Please select at least one role to perform this operation.: 请选择至少一
Please select at least one user to perform this operation.: 请选择至少一个用户来进行操作。
Please set the balloon color for each problem first.: 请先为每道题设置气球颜色。
Please wait until contest host unfreeze the scoreboard.: 请等待比赛主办方解除封榜。
-Polyhedron supports managing problem version history, testing solutions, checking time limits, composing contest statements, cooperation and much more.: Polyhedron 支持题目版本管理,代码测试,时限检验,制作比赛题面,多人协作等等功能。
+? Polyhedron supports managing problem version history, testing solutions, checking time limits, composing contest statements, cooperation and much more.
+: Polyhedron 支持题目版本管理,代码测试,时限检验,制作比赛题面,多人协作等等功能。
Preference Settings: 偏好设置
preferredPrefix_hint: 此选项用于重排题号。例如,若题目包中所给的题号分别是 P1001, P1002, P1003,而此选项填写了 T,则导入后三道题的题号分别为 T1001, T1002 和 T1003。
Preparing Upload...: 准备上传...
@@ -778,7 +784,7 @@ Recent Activities: 最近活动
Recent Problems: 最新题目
Recent Solutions: 最近编写的题解
Recent Submissions: 最近递交
-Recently Created Discussions: 最近创建的讨论
+Recently Created Discussions: 最近创建的公告
Recommended: 推荐
Record {0} not found.: 记录 {0} 不存在。
record_detail: 记录详情
@@ -793,7 +799,7 @@ Rejudge all submissions: 重测整题
Rejudge problems: 重测题目
Rejudge records: 重测记录
Rejudge: 重测
-Related Discussions: 相关讨论
+Related Discussions: 相关公告
Related: 相关
Remember me: 记住我
Remove Selected Group: 移除所选小组
@@ -804,7 +810,7 @@ Remove: 移除
Rename Selected: 重命名选中
Repeat Password: 重复密码
Replace with: 替换为
-Reply discussions: 回复讨论
+Reply discussions: 回复公告
Reply problem solutions: 回复题解
reply: 回复
Reply: 回复
@@ -845,7 +851,7 @@ Secret (visible to admins): 保密(对管理员可见)
Secret: 保密
Section: 章节
Security: 安全
-Select a node to create discussion.: 选择一个节点来发表讨论。
+Select a node to create discussion.: 选择一个节点来发表公告。
Select a role: 选择一个角色
Select All: 全选
Select Category: 选择标签
@@ -913,7 +919,7 @@ Source type: 来源类型
Source: 来源
Standard mode: 标准模式
Standard Program: 标准程序
-Star Topic: 收藏讨论
+Star Topic: 收藏公告
Star: 收藏
Starred Users: 关注用户
Start at: 开始于
@@ -955,11 +961,13 @@ The contest is a flexible time contest. You need to complete the contest within
The contest is ended. New submissions will be treated as correction submissions and will not be counted in the contest.: 比赛已经结束。新提交将被视为补题提交,不计入比赛成绩。
The group to join when user joining the domain.: 加入域时自动加入的小组。
The homework's deadline is due but in extension. You can still submit for this problem but your score will be penalized.: 作业已超过截止时间,但仍在延期时间内。您递交题目将无法获得全部分数。
-The invitation code to enter to successfully join the domain. You can only use letters and numbers in the code and it should not be longer than 64 characters.: 加入此域的邀请码。您只能使用字母和数字,并且不能长于 64 个字符。
+? The invitation code to enter to successfully join the domain. You can only use letters and numbers in the code and it should not be longer than 64 characters.
+: 加入此域的邀请码。您只能使用字母和数字,并且不能长于 64 个字符。
The invitation code you provided is invalid.: 您提供的邀请码无效。
The link will be expired at {0}: 链接将于 {0} 过期
The role to assign when user joining the domain.: 用户加入此域时分配的角色。
-The scoreboard was frozen with {0} minutes remaining at {1} - submissions in the last {0} minutes of the contest are still shown as pending.: 比赛已于 {1} 在剩余 {0} 分钟时封榜 - 比赛最后 {0} 分钟的提交将显示为待定。
+? The scoreboard was frozen with {0} minutes remaining at {1} - submissions in the last {0} minutes of the contest are still shown as pending.
+: 比赛已于 {1} 在剩余 {0} 分钟时封榜 - 比赛最后 {0} 分钟的提交将显示为待定。
The uploaded file is too long.: 上传的文件太长。
The user is already a member of the domain.: 该用户已是域的成员。
The user is too lazy to leave something here...: 该用户太懒,这里啥也没写 (´・ω・`)
@@ -988,7 +996,8 @@ timeago_locale: zh_CN
Timezone: 时区
title: 标题
Title: 标题
-To get a better editing experience, with code highlighting and test runs, please go back to the problem detail page and use 'Open Scratchpad' button.: 为了获得更好的编辑体验,包括代码高亮和测试运行功能,请返回题目详情页面并点击“进入在线编程模式”按钮。
+? To get a better editing experience, with code highlighting and test runs, please go back to the problem detail page and use 'Open Scratchpad' button.
+: 为了获得更好的编辑体验,包括代码高亮和测试运行功能,请返回题目详情页面并点击“进入在线编程模式”按钮。
To join the domain, users can click the "Join Domain" button on "My Domain" page.: 要加入域,用户可以点击“我的域”页面中的“加入域”按钮。
Toggle Pretest Panel: 切换自测面板
Toggle Preview: 切换预览
@@ -1070,14 +1079,14 @@ View contest scoreboard: 查看比赛成绩表
View Contest: 查看比赛
View contests: 查看比赛
View Details: 查看详情
-View discussions: 查看讨论
+View discussions: 查看公告
View hidden contest submission status and scoreboard: 查看隐藏的比赛递交状态和成绩表
View hidden homework submission status and scoreboard: 查看隐藏的作业递交状态和成绩表
View hidden problems: 查看隐藏的题目
View homework scoreboard: 查看作业成绩表
View homework: 查看作业
View Homework: 查看作业
-View or create discussion: 查看与发表讨论
+View or create discussion: 查看与发表公告
View or submit solution: 查看与发表题解
View Owned Problems: 查看自己的题目
View Owned Training Plans: 查看自己的训练计划
@@ -1092,7 +1101,11 @@ Visible to registered users: 对注册用户可见
Visit: 查看
Vote problem solutions: 为题解投票
Vote: 投票
-warn::admin:unsupportedbrowser: "身为超级管理员,您仍在使用过于老旧的浏览器。\n这些浏览器可能不支持 Hydro 管理面板的部分功能,\n我们强烈建议您升级到最新的 Chrome 浏览器。"
+warn::admin:unsupportedbrowser: '身为超级管理员,您仍在使用过于老旧的浏览器。
+
+ 这些浏览器可能不支持 Hydro 管理面板的部分功能,
+
+ 我们强烈建议您升级到最新的 Chrome 浏览器。'
We will check code similarity after this contest.: 我们会在赛后检查代码相似度。
WeChat Visibility: 微信可见性
WeChat: 微信
@@ -1106,16 +1119,19 @@ What's this?: 这是什么?
Whether to show tags in the problem list.: 是否在题目列表中显示题目的标签。
wiki_help: 帮助
Will be used as the domain icon.: 将被用作系统图标。
-With this feature, you can copy problems that you can view from a domain to some other domain. Their title, content, tags and categories will be copied. However, their test data are not copied directly.: 您可以通过这个功能将某域下您能查看的题目复制到其它域中,题目的标题、描述、标签与分类将被复制过来。但是测试数据不会被直接复制。
+? With this feature, you can copy problems that you can view from a domain to some other domain. Their title, content, tags and categories will be copied. However, their test data are not copied directly.
+: 您可以通过这个功能将某域下您能查看的题目复制到其它域中,题目的标题、描述、标签与分类将被复制过来。但是测试数据不会被直接复制。
Write Your Comment: 发表您的评论
Write Your Solution: 发表您的题解
Year: 年
-You are currently in legacy mode. Some additional features will be unavailable. We strongly recommend switching to standard mode on a modern browser.: 您当前处于兼容模式。某些功能在此模式下不可用。我们强烈建议在现代浏览器上切换为标准模式以获得更好的体验。
-You are invited to join {0}: '您被邀请加入 {0}'
+? You are currently in legacy mode. Some additional features will be unavailable. We strongly recommend switching to standard mode on a modern browser.
+: 您当前处于兼容模式。某些功能在此模式下不可用。我们强烈建议在现代浏览器上切换为标准模式以获得更好的体验。
+You are invited to join {0}: 您被邀请加入 {0}
You are not allowed to join the domain. The link is either invalid or expired.: 您无法加入该域,链接无效或已过期。
You can also upload your avatar to Gravatar and it will be automatically updated here.: 你也可以将头像上传到 Gravatar ,本站的头像将自动更新。
You can create your own training plans and share them with others.: 您可以创建您自己的训练计划并且与他人分享。
-You cannot submit for this problem because the contest is ended. You can click "Open in Problem Set" to view this problem in normal mode.: 该比赛已结束,您无法在比赛模式下递交该题目。您可以点击“在题库中打开”以普通模式查看和递交本题。
+? You cannot submit for this problem because the contest is ended. You can click "Open in Problem Set" to view this problem in normal mode.
+: 该比赛已结束,您无法在比赛模式下递交该题目。您可以点击“在题库中打开”以普通模式查看和递交本题。
You cannot submit for this problem because the homework's deadline is due.: 作业已超过截止时间,您无法递交本题目。
You cannot visit this domain.: 您不能访问此域。
You don't have permission to upload file.: 您没有权限上传文件。
@@ -1152,3 +1168,22 @@ Confirm deleting this statement?: 确认删除这条题面?
Statement {0} is empty.: 题面 {0} 内容为空。
File {0} referenced by statement {1} does not exist.: 题面 {1} 引用的文件 {0} 不存在。
Unknown language: 未知语言
+courses_main: 课程
+discussion_detail: 公告详情
+domain_create: 创建域
+Enabled Contest Duration (hours): 可参赛时间 (小时)
+Lock scoreboard on last N minutes: 在赛事最后N分钟时锁定成绩表
+Lock Board (minutes): 封榜 (分钟)
+Recent Discussion: 最新公告
+Special Thanks: 特别鸣谢
+stu_class_list: 班级列表
+stu_class_students: 班级详情
+setting_student: 学生信息
+Stu_ID: 学号
+Stu_ClassName: 班级
+Reg_Stu_ClassName: 专业班级(例如:软工1901、计算机2006)
+Stu_RealName: 姓名
+reg_stuwarn: 请使用真实学生信息填写!
+manage_student_import: 学生批量导入
+manage_teacher_register: 教师注册
+manage_user_changepassword: 修改用户密码
diff --git a/packages/ui-default/misc/typography.styl b/packages/ui-default/misc/typography.styl
index 03e8040896..3d1946c8f2 100644
--- a/packages/ui-default/misc/typography.styl
+++ b/packages/ui-default/misc/typography.styl
@@ -479,6 +479,13 @@ textarea
outline: 0px;
outline-offset: 2px;
+// HGNUOJ Added
+.text-badge
+ display: inline-block
+ padding: 0 5px 0 5px
+ background-color: #6495ed
+ color: white
+
@font-face
font-family: "XiaoLai SC";
font-display: swap;
diff --git a/packages/ui-default/pages/courses_main.page.styl b/packages/ui-default/pages/courses_main.page.styl
new file mode 100644
index 0000000000..58b942dcfa
--- /dev/null
+++ b/packages/ui-default/pages/courses_main.page.styl
@@ -0,0 +1,51 @@
+.page--courses_main
+ .course-card
+ display: inline-block
+ padding: 15px 20px
+ padding-bottom: 0
+ width: 100%
+ border-style: solid
+ border-color: rgba(#AFC2C9, 0.4)
+ border-width: 1px
+ box-shadow: 0 2px 3px rgba(#AFC2C9, 0.4)
+ transition: transform .2s, box-shadow .5s
+
+ .course-card:hover
+ transform: scale(1.05) translateY(-5px)
+ box-shadow: 0 2px 8px rgba(#AFC2C9, 0.5)
+
+ .course-card .course-card-header
+ font-size: 12px
+
+ .course-card .course-card-header h1
+ overflow: hidden
+ text-overflow: ellipsis
+ white-space: nowrap
+ font-weight: normal
+
+ .course-card .course-card-body
+ font-size: 14px
+ margin-top: 10px
+
+ .course-card .course-card-body p
+ overflow: hidden
+ text-overflow: ellipsis
+ white-space: nowrap
+ padding: 5px 0 5px 0
+ line-height: 20px
+
+ +tablet()
+ .course-card .course-card-header
+ font-size: 10px
+ .course-card .course-card-body
+ font-size: 10px
+ .course-card .button
+ font-size: 4px
+
+ +mobile()
+ .course-card .course-card-header
+ font-size: 10px
+ .course-card .course-card-body
+ font-size: 10px
+ .course-card
+ box-shadow: none
\ No newline at end of file
diff --git a/packages/ui-default/pages/homework_scoreboard.page.styl b/packages/ui-default/pages/homework_scoreboard.page.styl
index ff1064a34f..afb37bb627 100644
--- a/packages/ui-default/pages/homework_scoreboard.page.styl
+++ b/packages/ui-default/pages/homework_scoreboard.page.styl
@@ -9,14 +9,23 @@
border-right: 1px solid $table-border-color
.col--user
- min-width: rem(150px)
+ width: 150px
+ text-align: center
- .col--total_score, .col--time
+ .col--stu_class
+ width: 7rem
+ text-align: center
+
+ .col--stu_name
width: rem(100px)
text-align: center
+ .col--total_score, .col--time
+ width: 3.5rem
+ text-align: center
+
.col--problem, .col--record
- width: rem(100px)
+ width: 3rem
border-left: 1px solid $table-border-color
text-align: center
diff --git a/packages/ui-default/pages/manage_student_import.page.js b/packages/ui-default/pages/manage_student_import.page.js
new file mode 100644
index 0000000000..33025b13fb
--- /dev/null
+++ b/packages/ui-default/pages/manage_student_import.page.js
@@ -0,0 +1,30 @@
+import $ from 'jquery';
+import Notification from 'vj/components/notification';
+import { NamedPage } from 'vj/misc/Page';
+import { delay, i18n, request } from 'vj/utils';
+
+const page = new NamedPage('manage_student_import', () => {
+ async function post(draft) {
+ try {
+ const res = await request.post('', {
+ students: $('[name="students"]').val(),
+ draft,
+ });
+ $('[name="messages"]').text(res.messages.join('\n'));
+ if (!draft) {
+ Notification.success(i18n('Created {0} users.', res.created));
+ if (!res.errors) {
+ await delay(2000);
+ window.location.reload();
+ }
+ }
+ } catch (error) {
+ Notification.error(error.message);
+ }
+ }
+
+ $('[name="preview"]').on('click', () => post(true));
+ $('[name="submit"]').on('click', () => post(false));
+});
+
+export default page;
diff --git a/packages/ui-default/pages/ranking.page.styl b/packages/ui-default/pages/ranking.page.styl
index a87d152bde..1fba732a7d 100644
--- a/packages/ui-default/pages/ranking.page.styl
+++ b/packages/ui-default/pages/ranking.page.styl
@@ -4,7 +4,7 @@
position: relative
.col--user
- width: rem(280px)
+ width: rem(300px)
.col--rp
width: rem(60px)
diff --git a/packages/ui-default/pages/record_main.page.styl b/packages/ui-default/pages/record_main.page.styl
index 4ecb3124a8..db3fe79014 100644
--- a/packages/ui-default/pages/record_main.page.styl
+++ b/packages/ui-default/pages/record_main.page.styl
@@ -11,7 +11,7 @@
width: rem(160px)
.col--submit-by
- width: rem(140px)
+ width: rem(200px)
text-align: right
.col--time, .col--memory, .col--lang
diff --git a/packages/ui-default/pages/stu_class_list.page.styl b/packages/ui-default/pages/stu_class_list.page.styl
new file mode 100644
index 0000000000..63b706192a
--- /dev/null
+++ b/packages/ui-default/pages/stu_class_list.page.styl
@@ -0,0 +1,38 @@
+.page--stu_class_list
+ .stu-classlist td
+ height: rem(50px)
+ font-size: 14px
+
+ .stu-classlist>tr:nth-child(-n+3) .col--rank
+ height: rem(80px)
+ font-size: 26px
+ font-weight: 200
+
+ .col--rank
+ width: rem(100px)
+ position: relative
+
+ .col--classname
+ min-width: rem(200px)
+ text-align: left
+
+ .col--stunum, .col--ac, .col--submit, .col--rpavg, .col--rpsum, .col--activity, .col--weight
+ min-width: rem(100px)
+ text-align: right
+
+ .col--user-rank
+ width: rem(60px)
+
+ .col--user-ac, .col--user-ac, .col--user-submit, .col--user-rp
+ width: rem(60px)
+ text-align: right
+
+ .col--user-bio
+ min-width: rem(400px)
+
+ .col--user
+ width: rem(160px)
+
+ +mobile()
+ .col--rpavg, .col--rpsum, .col--weight, .col--rpavg, .col--submit, .stu-starclass
+ display: none
\ No newline at end of file
diff --git a/packages/ui-default/pages/stu_class_students.page.styl b/packages/ui-default/pages/stu_class_students.page.styl
new file mode 100644
index 0000000000..0748e2d7f0
--- /dev/null
+++ b/packages/ui-default/pages/stu_class_students.page.styl
@@ -0,0 +1,36 @@
+.page--stu_class_students
+ .col--rank
+ width: rem(80px)
+ position: relative
+
+ .col--stuid
+ width: rem(150px)
+ text-align: left
+
+ .col--user
+ width: rem(200px)
+ text-align: left
+
+ .col--gender
+ width: rem(80px)
+ text-align: left
+
+ .col--rp
+ width: rem(80px)
+ text-align: right
+
+ .col--ac
+ width: rem(100px)
+ text-align: right
+
+ .col--lastactive
+ width: rem(120px)
+ text-align: right
+
+ .col--bio
+ height: 36px !important
+ display: block
+
+ +mobile()
+ .col--bio, .col--stuid, .col--lastactive, .col--gender
+ display: none
\ No newline at end of file
diff --git a/packages/ui-default/static/android-chrome-192x192.png b/packages/ui-default/static/android-chrome-192x192.png
index c740313cc5..13f806cb15 100644
Binary files a/packages/ui-default/static/android-chrome-192x192.png and b/packages/ui-default/static/android-chrome-192x192.png differ
diff --git a/packages/ui-default/static/apple-touch-icon-180x180.png b/packages/ui-default/static/apple-touch-icon-180x180.png
index 85dd784912..4b32b80fcc 100644
Binary files a/packages/ui-default/static/apple-touch-icon-180x180.png and b/packages/ui-default/static/apple-touch-icon-180x180.png differ
diff --git a/packages/ui-default/static/favicon-16x16.png b/packages/ui-default/static/favicon-16x16.png
index afa845788b..52c94fa4c3 100644
Binary files a/packages/ui-default/static/favicon-16x16.png and b/packages/ui-default/static/favicon-16x16.png differ
diff --git a/packages/ui-default/static/favicon-32x32.png b/packages/ui-default/static/favicon-32x32.png
index 2372340fb0..28cb92c31d 100644
Binary files a/packages/ui-default/static/favicon-32x32.png and b/packages/ui-default/static/favicon-32x32.png differ
diff --git a/packages/ui-default/static/favicon-96x96.png b/packages/ui-default/static/favicon-96x96.png
index b062922e85..118d76e7b7 100644
Binary files a/packages/ui-default/static/favicon-96x96.png and b/packages/ui-default/static/favicon-96x96.png differ
diff --git a/packages/ui-default/static/favicon.ico b/packages/ui-default/static/favicon.ico
index 98d24cb7a9..16835cd515 100644
Binary files a/packages/ui-default/static/favicon.ico and b/packages/ui-default/static/favicon.ico differ
diff --git a/packages/ui-default/templates/components/home.html b/packages/ui-default/templates/components/home.html
index cb58e67016..e367497c8c 100644
--- a/packages/ui-default/templates/components/home.html
+++ b/packages/ui-default/templates/components/home.html
@@ -3,7 +3,6 @@