- {% 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 -%}
-
+
+{% 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..806c84f3c5 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,15 @@ 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 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 +371,7 @@ Hidden: 隐藏
Hide all tags: 隐藏所有标签
Hide categorical tags: 隐藏分类标签
Hide Selected: 隐藏选中
-Highlight discussions: 高亮讨论
+Highlight discussions: 高亮公告
highlight: 高亮
Highlight: 高亮
Hint: 提示
@@ -419,7 +420,7 @@ In following homework: 在以下作业中
In following training plans: 在下列训练计划中
In Progress: 进行中
Information: 信息
-Init Discussion Nodes: 初始化讨论结点
+Init Discussion Nodes: 初始化公告结点
Initialize: 初始化
Inline codes: 行内代码
Inline formulas: 行内公式
@@ -428,7 +429,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 +465,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 +500,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 +526,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 +556,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 +576,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 +616,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 +629,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 +703,7 @@ Registered at: 注册于
Rejudge problems: 重测题目
Rejudge records: 重测记录
Rejudge: 重测
-Related Discussions: 相关讨论
+Related Discussions: 相关公告
Related: 相关
Relax and try to remember your password.: 放松,尝试回忆您设置的密码。
Remember me: 记住我
@@ -708,7 +712,7 @@ Remove this data: 移除这组数据
Remove: 移除
Repeat Password: 重复密码
Replies per page: 每页展示的回复数量
-Reply discussions: 回复讨论
+Reply discussions: 回复公告
Reply problem solutions: 回复题解
reply: 回复
Reply: 回复
@@ -745,7 +749,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 +804,7 @@ Sort by: 排序
Source type: 来源类型
Split View: 分屏预览
Standard answer longer than user output.: 答案比您的输出长。
-Star Topic: 收藏讨论
+Star Topic: 收藏公告
Star: 收藏
Starred Problems: 收藏的题目
Start at: 开始于
@@ -831,9 +835,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 +938,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 +946,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 +974,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 +987,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 +1007,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..c3397ac146 100644
--- a/packages/hydrooj/src/handler/domain.ts
+++ b/packages/hydrooj/src/handler/domain.ts
@@ -14,6 +14,9 @@ import * as discussion from '../model/discussion';
import domain from '../model/domain';
import MessageModel from '../model/message';
import * as oplog from '../model/oplog';
+import {
+ EXTERNAL_RANKING_PLATFORMS, getExternalRanking, getGradeOptions, getGradeRpRanking,
+} from '../model/ranking';
import { DOMAIN_SETTINGS, DOMAIN_SETTINGS_BY_KEY } from '../model/setting';
import system from '../model/system';
import user from '../model/user';
@@ -24,17 +27,52 @@ import { log2 } from '../utils';
class DomainRankHandler extends Handler {
@query('page', Types.PositiveInt, true)
- async get(domainId: string, page = 1) {
- const [dudocs, upcount, ucount] = await this.paginate(
- domain.getMultiUserInDomain(domainId, { uid: { $gt: 1 }, rp: { $gt: 0 }, join: true }).sort({ rp: -1 }),
- page,
- 'ranking',
- );
- const udict = await user.getList(domainId, dudocs.map((dudoc) => dudoc.uid));
- const udocs = dudocs.map((i) => udict[i.uid]);
+ @query('grade', Types.String, true)
+ @query('externalPage', Types.PositiveInt, true)
+ @query('externalSort', Types.String, true)
+ @query('externalScope', Types.String, true)
+ async get(domainId: string, page = 1, grade = 'all', externalPage = 1, sort = 'total', scope = 'all') {
+ const { db } = this.ctx;
+ const externalSort = EXTERNAL_RANKING_PLATFORMS.find(({ key }) => key === sort)?.key ?? 'total';
+ const externalScope = scope === 'synced' ? 'synced' : 'all';
+ const grades = await getGradeOptions(db, domainId);
+ if (grade !== 'unknown' && !grades.includes(grade)) grade = 'all';
+ const pageSize = this.ctx.setting.get('pagination.ranking') || 20;
+ const viewerUid = this.user.hasPriv(PRIV.PRIV_USER_PROFILE) ? this.user._id : undefined;
+ const [rp, external] = await Promise.all([
+ grade === 'all'
+ ? this.paginate(
+ domain.getMultiUserInDomain(domainId, { uid: { $gt: 1 }, rp: { $gt: 0 }, join: true }).sort({ rp: -1 }),
+ page,
+ 'ranking',
+ ).then(([rows, pages, count]) => ({ rows, pages, count, viewerRank: this.user.rank }))
+ : getGradeRpRanking(db, domainId, grade, page, pageSize, viewerUid)
+ .then((result) => ({ ...result, pages: Math.ceil(result.count / pageSize) })),
+ getExternalRanking(db, domainId, grade, externalPage, pageSize, externalSort, new Date(), externalScope),
+ ]);
+ const udict = await user.getList(domainId, [...rp.rows, ...external.rows].map(({ uid }) => uid));
+ const externalUsers = Object.fromEntries(external.rows.map(({ uid, uname }) => [uid, {
+ _id: uid, uname, class: udict[uid]?.class, name: udict[uid]?.name,
+ }]));
this.response.template = 'ranking.html';
this.response.body = {
- udocs, upcount, ucount, page,
+ udocs: rp.rows.map(({ uid }) => udict[uid]),
+ upcount: rp.pages,
+ ucount: rp.count,
+ page,
+ rpRanks: grade === 'all' ? undefined : rp.rows.map(({ rank }) => rank),
+ viewerRpRank: rp.viewerRank,
+ grades,
+ grade,
+ externalRows: external.rows,
+ externalUsers,
+ externalPlatforms: EXTERNAL_RANKING_PLATFORMS,
+ externalPage,
+ externalSort,
+ externalScope,
+ externalAllCount: external.allCount,
+ externalSyncedCount: external.syncedCount,
+ externalPageCount: Math.ceil(external.count / pageSize),
};
}
}
@@ -423,6 +461,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 +531,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/externalOj.ts b/packages/hydrooj/src/handler/externalOj.ts
new file mode 100644
index 0000000000..0a7d6b96d6
--- /dev/null
+++ b/packages/hydrooj/src/handler/externalOj.ts
@@ -0,0 +1,53 @@
+import type { Context } from '../context';
+import { PRIV } from '../model/builtin';
+import {
+ bindExternalOj, describeExternalOjBindings, ExternalOjBindingError, externalPlatform, getExternalOjBindings, unbindExternalOj,
+} from '../model/externalOj';
+import { Handler, post, Types } from '../service/server';
+
+class HomeExternalOjHandler extends Handler {
+ private async renderBindings(feedback?: { platform: string, message: string, input: string }) {
+ this.response.template = 'home_external_oj.html';
+ this.response.body = {
+ accounts: describeExternalOjBindings(await getExternalOjBindings(this.user._id), true),
+ feedback,
+ };
+ }
+
+ async get() {
+ await this.renderBindings();
+ }
+
+ @post('platform', Types.Name)
+ @post('handle', Types.String, true)
+ async postBind(_: string, platform: string, handle = '') {
+ await this.limitRate('external_oj_binding', 60, 20, '{{user}}');
+ try {
+ await bindExternalOj(this.user._id, externalPlatform(platform), handle);
+ } catch (error) {
+ if (!(error instanceof ExternalOjBindingError)) throw error;
+ const message = {
+ format: ['luogu', 'nowcoder'].includes(platform)
+ ? '请输入数字 UID,或粘贴该平台的公开个人主页链接。'
+ : '请输入该平台的用户名,或粘贴公开个人主页链接。',
+ taken: '该外站账号已绑定到另一个 HGNUOJ 用户。同一账号只能入榜一次,请先在原账号解绑。',
+ changed: '绑定刚刚被更新,请刷新后再试。',
+ }[error.reason];
+ this.response.status = error.reason === 'format' ? 400 : 409;
+ await this.renderBindings({ platform, message, input: handle.slice(0, 256) });
+ return;
+ }
+ this.response.redirect = this.url('home_external_oj');
+ }
+
+ @post('platform', Types.Name)
+ async postUnbind(_: string, platform: string) {
+ await this.limitRate('external_oj_binding', 60, 20, '{{user}}');
+ await unbindExternalOj(this.user._id, externalPlatform(platform));
+ this.response.redirect = this.url('home_external_oj');
+ }
+}
+
+export function apply(ctx: Context) {
+ ctx.Route('home_external_oj', '/home/external-oj', HomeExternalOjHandler, PRIV.PRIV_USER_PROFILE);
+}
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..8731c8d507 100644
--- a/packages/hydrooj/src/handler/user.ts
+++ b/packages/hydrooj/src/handler/user.ts
@@ -13,6 +13,7 @@ import {
} from '../error';
import { TokenDoc, Udoc, User } from '../interface';
import avatar from '../lib/avatar';
+import { loadExternalOjProfile } from '../lib/externalOjProfile';
import { sendMail } from '../lib/mail';
import { verifyTFA } from '../lib/verifyTFA';
import BlackListModel from '../model/blacklist';
@@ -23,9 +24,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 +318,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 +448,16 @@ 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,
+ externalOj: await loadExternalOjProfile(domainId, uid, this.user.hasPerm(PERM.PERM_VIEW_PROBLEM)
+ ? pdocs.filter((p) => !p.hidden || isSelfProfile || this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN)).map((p) => p.docId)
+ : null),
};
if (this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_SOLUTION)) {
const psdocs = await SolutionModel.getByUser(domainId, uid).limit(10).toArray();
@@ -550,6 +571,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 +732,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/externalOjProfile.ts b/packages/hydrooj/src/lib/externalOjProfile.ts
new file mode 100644
index 0000000000..3b766ce363
--- /dev/null
+++ b/packages/hydrooj/src/lib/externalOjProfile.ts
@@ -0,0 +1,55 @@
+import type { ObjectId } from 'mongodb';
+import { STATUS } from '@hydrooj/common';
+import { describeExternalOjBindings, getExternalOjBindings } from '../model/externalOj';
+import RecordModel from '../model/record';
+import { externalOjActivityUrl, externalOjProfileUrl } from './externalOjs';
+import { buildDailyActivity, FirstPass } from './externalOjStats';
+
+async function localPasses(domainId: string, uid: number, visiblePids: number[]): Promise {
+ if (!visiblePids.length) return [];
+ const first = await RecordModel.coll.aggregate<{ _id: number, first: ObjectId }>([
+ {
+ $match: {
+ domainId, uid, status: STATUS.STATUS_ACCEPTED, pid: { $in: visiblePids },
+ contest: { $nin: [RecordModel.RECORD_PRETEST, RecordModel.RECORD_GENERATE] },
+ },
+ },
+ { $group: { _id: '$pid', first: { $min: '$_id' } } },
+ ]).toArray();
+ return first.map((r) => ({ problem: String(r._id), at: r.first.getTimestamp() }));
+}
+
+export async function loadExternalOjProfile(domainId: string, uid: number, visiblePids: number[] | null) {
+ const [entries, local] = await Promise.all([
+ getExternalOjBindings(uid),
+ visiblePids === null ? undefined : localPasses(domainId, uid, visiblePids),
+ ]);
+ const accounts = describeExternalOjBindings(entries, true).map((account) => ({
+ ...account,
+ profileUrl: account.handle ? externalOjProfileUrl(account.platform, account.handle) : undefined,
+ activityUrl: account.handle ? externalOjActivityUrl(account.platform, account.handle) : undefined,
+ }));
+ const sources = [
+ { id: 'hgnu', label: '本校 OJ', solves: local },
+ ...accounts.filter((account) => account.state !== 'unbound').map((account) => {
+ const entry = entries.find(({ platform }) => platform === account.platform);
+ return {
+ id: account.platform, label: account.label, solves: entry?.solves, through: entry?.lastSuccessAt,
+ };
+ }),
+ ];
+ const days = buildDailyActivity(sources);
+ const leading = (new Date(`${days[0].day}T00:00:00Z`).getUTCDay() + 6) % 7;
+ const months = days.flatMap(({ day }, i) => day.endsWith('-01')
+ ? [{ label: `${Number(day.slice(5, 7))}月`, column: Math.floor((leading + i) / 7) + 1 }]
+ : []);
+ return {
+ accounts,
+ labels: sources.map(({ label }) => label),
+ missing: sources.filter(({ solves }) => !solves).map(({ label }) => label),
+ leading: Array.from({ length: leading }),
+ months,
+ hasRecentPasses: days.some(({ total }) => total > 0),
+ days,
+ };
+}
diff --git a/packages/hydrooj/src/lib/externalOjStats.ts b/packages/hydrooj/src/lib/externalOjStats.ts
new file mode 100644
index 0000000000..c8d94ec936
--- /dev/null
+++ b/packages/hydrooj/src/lib/externalOjStats.ts
@@ -0,0 +1,62 @@
+const DAY = 24 * 60 * 60 * 1000;
+const BEIJING_OFFSET = 8 * 60 * 60 * 1000;
+
+export interface FirstPass {
+ problem: string;
+ at: Date;
+}
+
+export interface ActivitySource {
+ id: string;
+ solves?: FirstPass[];
+ through?: Date;
+}
+
+export function beijingDay(at: Date) {
+ return new Date(at.getTime() + BEIJING_OFFSET).toISOString().slice(0, 10);
+}
+
+export function nextBeijingNoon(at: Date) {
+ const today = Date.parse(`${beijingDay(at)}T12:00:00+08:00`);
+ return new Date(today > at.getTime() ? today : today + DAY);
+}
+
+export function firstPasses(solves: FirstPass[]) {
+ const earliest = new Map();
+ for (const { problem, at } of solves) {
+ if (!problem || !Number.isFinite(at?.getTime())) continue;
+ const old = earliest.get(problem);
+ if (!old || at < old) earliest.set(problem, at);
+ }
+ return [...earliest].map(([problem, at]) => ({ problem, at }));
+}
+
+export function buildDailyActivity(sources: ActivitySource[], now = new Date(), days = 365) {
+ const countsBySource = sources.map(({ solves, through }) => {
+ if (!solves) return null;
+ const counts = new Map();
+ for (const { at } of firstPasses(solves)) {
+ const day = beijingDay(at);
+ counts.set(day, (counts.get(day) || 0) + 1);
+ }
+ return { counts, through: through && beijingDay(through) };
+ });
+ return Array.from({ length: days }, (_, i) => {
+ const day = beijingDay(new Date(now.getTime() - (days - 1 - i) * DAY));
+ const counts = countsBySource.map((source) => (
+ source && (!source.through || day <= source.through) ? source.counts.get(day) || 0 : null
+ ));
+ return {
+ day,
+ counts,
+ total: counts.some((n) => n !== null) ? counts.reduce((acc, n) => acc + (n || 0), 0) : null,
+ };
+ });
+}
+
+export function syncState(binding?: { lastSuccessAt?: Date, failedAt?: Date }) {
+ if (!binding) return 'unbound';
+ if (binding.failedAt && (!binding.lastSuccessAt || binding.failedAt >= binding.lastSuccessAt)) return 'failed';
+ if (binding.lastSuccessAt) return 'success';
+ return 'pending';
+}
diff --git a/packages/hydrooj/src/lib/externalOjs.ts b/packages/hydrooj/src/lib/externalOjs.ts
new file mode 100644
index 0000000000..e74a2b912f
--- /dev/null
+++ b/packages/hydrooj/src/lib/externalOjs.ts
@@ -0,0 +1,392 @@
+import { beijingDay } from './externalOjStats';
+
+export const EXTERNAL_PLATFORMS = Object.freeze(['codeforces', 'atcoder', 'nowcoder', 'luogu', 'leetcode'] as const);
+export type ExternalPlatform = typeof EXTERNAL_PLATFORMS[number];
+// eslint-disable-next-line ts/consistent-type-definitions -- Public type alias for the adapter result.
+export type ExternalStats = {
+ total: number;
+ solves?: { problem: string, at: Date }[];
+ olderSolved?: string[];
+};
+
+interface Previous {
+ solves?: ExternalStats['solves'];
+ olderSolved?: string[];
+ cursorAt?: Date;
+ lastSuccessAt?: Date;
+}
+
+type BeforeRequest = () => Promise;
+interface FetchOptions {
+ now?: Date;
+ beforeRequest?: BeforeRequest;
+}
+
+// null is an older first AC whose exact date is no longer needed.
+type FirstAc = Map;
+
+const HANDLE_PATTERN: Record = {
+ codeforces: /^[A-Za-z0-9_.-]{1,64}$/,
+ atcoder: /^[A-Za-z0-9_]{1,64}$/,
+ nowcoder: /^[0-9]{1,32}$/,
+ luogu: /^[0-9]{1,32}$/,
+ leetcode: /^[A-Za-z0-9_-]{1,64}$/,
+};
+
+const PROFILE_PATHS: Record> = {
+ codeforces: { 'codeforces.com': /^\/profile\/([^/]+)\/?$/ },
+ atcoder: { 'atcoder.jp': /^\/users\/([^/]+)\/?$/ },
+ nowcoder: {
+ 'ac.nowcoder.com': /^\/acm\/contest\/profile\/([^/]+)(?:\/practice-coding)?\/?$/,
+ 'www.nowcoder.com': /^\/users\/([^/]+)\/?$/,
+ },
+ luogu: { 'www.luogu.com.cn': /^\/user\/([^/]+)\/?$/, 'luogu.com.cn': /^\/user\/([^/]+)\/?$/ },
+ leetcode: { 'leetcode.cn': /^\/u\/([^/]+)\/?$/ },
+};
+
+export function externalOjHandle(platform: ExternalPlatform, handle: string): string {
+ if (!EXTERNAL_PLATFORMS.includes(platform)) throw new Error('Unsupported external platform');
+ let value = typeof handle === 'string' ? handle.trim() : '';
+ if (/^https?:\/\//i.test(value)) {
+ const url = new URL(value);
+ const paths = PROFILE_PATHS[platform];
+ value = !url.username && !url.password && !url.port && Object.hasOwn(paths, url.hostname)
+ ? paths[url.hostname].exec(url.pathname)?.[1] || ''
+ : '';
+ }
+ if (HANDLE_PATTERN[platform].test(value) && /[A-Za-z0-9]/.test(value)) {
+ if (platform !== 'nowcoder' && platform !== 'luogu') return value;
+ const uid = Number(value);
+ if (Number.isSafeInteger(uid) && uid > 0) return String(uid);
+ }
+ throw new Error(`Malformed ${platform} account handle`);
+}
+
+export function externalAccountKey(platform: ExternalPlatform, handle: string): string {
+ return `${platform}:${externalOjHandle(platform, handle).toLowerCase()}`;
+}
+
+export function externalOjProfileUrl(platform: ExternalPlatform, handle: string): string {
+ const value = encodeURIComponent(externalOjHandle(platform, handle));
+ switch (platform) {
+ case 'codeforces': return `https://codeforces.com/profile/${value}`;
+ case 'atcoder': return `https://atcoder.jp/users/${value}`;
+ case 'nowcoder': return `https://ac.nowcoder.com/acm/contest/profile/${value}/practice-coding`;
+ case 'luogu': return `https://www.luogu.com.cn/user/${value}`;
+ case 'leetcode': return `https://leetcode.cn/u/${value}/`;
+ default: throw new Error('Unsupported external platform');
+ }
+}
+
+export function externalOjActivityUrl(platform: ExternalPlatform, handle: string): string | undefined {
+ return platform === 'atcoder'
+ ? `https://kenkoooo.com/atcoder/#/user/${encodeURIComponent(externalOjHandle(platform, handle))}`
+ : undefined;
+}
+
+// Shared across accounts in this process. Codeforces allows one request per two
+// seconds; AtCoder Problems asks callers to wait more than one second.
+const requestInterval: Record = {
+ codeforces: 2100, atcoder: 1100, nowcoder: 1000, luogu: 1000, leetcode: 1000,
+};
+const gates = new Map, nextStart: number }>();
+const REQUEST_TIMEOUT_MS = 10_000;
+const PAGE_CAP = 32;
+const HOUR_MS = 60 * 60 * 1000;
+const DAY_MS = 24 * HOUR_MS;
+
+export class ExternalOjRateLimit extends Error {
+ constructor(readonly retryMs: number = 30 * 60 * 1000) {
+ super('Upstream rate limit');
+ }
+}
+
+export class ExternalOjHistoryLimit extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'ExternalOjHistoryLimit';
+ }
+}
+
+function retryDelay(value: string | null) {
+ if (!value) return undefined;
+ const millis = /^\d+$/.test(value) ? Number(value) * 1000 : Date.parse(value) - Date.now();
+ return Number.isNaN(millis) ? undefined : Math.min(DAY_MS, Math.max(60_000, millis));
+}
+
+function reserveRequest(platform: ExternalPlatform, beforeRequest?: BeforeRequest) {
+ let gate = gates.get(platform);
+ if (!gate) {
+ gate = { tail: Promise.resolve(), nextStart: 0 };
+ gates.set(platform, gate);
+ }
+ const slot = gate.tail.then(async () => {
+ const wait = Math.ceil(gate.nextStart - performance.now());
+ if (wait > 0) await new Promise((resolve) => { setTimeout(resolve, wait); });
+ // Keep the slot until quota resolves so concurrent fetches stay spaced.
+ await beforeRequest?.();
+ gate.nextStart = performance.now() + requestInterval[platform];
+ });
+ gate.tail = slot.catch(() => {});
+ return slot;
+}
+
+async function publicResponse(platform: ExternalPlatform, url: URL, beforeRequest?: BeforeRequest, body?: string): Promise {
+ await reserveRequest(platform, beforeRequest);
+ const signal = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
+ try {
+ const res = await fetch(url, {
+ method: body ? 'POST' : 'GET',
+ headers: body ? { 'Content-Type': 'application/json' } : undefined,
+ body,
+ signal,
+ credentials: 'omit',
+ redirect: 'error',
+ });
+ if (res.status === 429 || (res.status === 503 && res.headers.has('Retry-After'))) {
+ throw new ExternalOjRateLimit(retryDelay(res.headers.get('Retry-After')));
+ }
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return await res.text();
+ } catch (cause) {
+ if (cause instanceof ExternalOjRateLimit) throw cause;
+ const reason = signal.aborted ? 'request timed out' : (cause as Error).message;
+ throw new Error(`${platform}: ${reason}`, { cause });
+ }
+}
+
+function endpoint(source: string, params: Record) {
+ const url = new URL(source);
+ url.search = new URLSearchParams(params).toString();
+ return url;
+}
+
+function obj(x: unknown): Record {
+ if (!x || typeof x !== 'object' || Array.isArray(x)) throw new Error('Invalid upstream object');
+ return x as Record;
+}
+
+function page(x: unknown, max: number): unknown[] {
+ if (!Array.isArray(x) || x.length > max) throw new Error('Invalid upstream submissions page');
+ return x;
+}
+
+function count(x: unknown): number {
+ if (typeof x !== 'number' || !Number.isSafeInteger(x) || x < 0) throw new Error('Invalid or unavailable upstream count');
+ return x;
+}
+
+function positive(x: unknown): number {
+ const value = count(x);
+ if (!value) throw new Error('Invalid upstream ID or timestamp');
+ return value;
+}
+
+function token(x: unknown, pattern: RegExp): string {
+ if (typeof x !== 'string' || !pattern.test(x)) throw new Error('Invalid upstream string');
+ return x;
+}
+
+function historyCursor(now: Date, previous?: Previous): number | undefined {
+ const cursor = (previous?.cursorAt || previous?.lastSuccessAt)?.getTime();
+ return cursor !== undefined && Number.isFinite(cursor) && cursor > 0 && cursor <= +now ? cursor : undefined;
+}
+
+function historyStart(cursor: number | undefined, overlapMs: number): number {
+ return cursor === undefined ? 0 : Math.max(0, Math.floor((cursor - overlapMs) / 1000));
+}
+
+function remember(solves: FirstAc, problem: string, at: Date) {
+ const prior = solves.get(problem);
+ if (prior === undefined || (prior !== null && at < prior)) solves.set(problem, at);
+}
+
+function initialHistory(previous?: Previous): FirstAc {
+ const solves: FirstAc = new Map();
+ for (const problem of previous?.olderSolved || []) solves.set(problem, null);
+ for (const { problem, at } of previous?.solves || []) remember(solves, problem, new Date(at.getTime()));
+ return solves;
+}
+
+function timestamp(seconds: unknown): Date {
+ const at = new Date(positive(seconds) * 1000);
+ if (!Number.isFinite(at.getTime())) throw new TypeError('Invalid upstream timestamp');
+ return at;
+}
+
+function historyResult(problems: FirstAc, now: Date): ExternalStats {
+ const firstDay = beijingDay(new Date(+now - 364 * DAY_MS));
+ const cutoff = Date.parse(`${firstDay}T00:00:00+08:00`);
+ const solves: NonNullable = [];
+ const olderSolved: string[] = [];
+ for (const [problem, at] of problems) {
+ if (at === null || +at < cutoff) olderSolved.push(problem);
+ else solves.push({ problem, at });
+ }
+ solves.sort((a, b) => +a.at - +b.at || (a.problem < b.problem ? -1 : Number(a.problem > b.problem)));
+ olderSolved.sort();
+ return { total: solves.length + olderSolved.length, solves, olderSolved };
+}
+
+const CF_STATUS = 'https://codeforces.com/api/user.status';
+async function codeforces(handle: string, previous: Previous | undefined, { now = new Date(), beforeRequest }: FetchOptions): Promise {
+ const cursor = historyCursor(now, previous);
+ const since = historyStart(cursor, 6 * HOUR_MS);
+ const pageSize = cursor !== undefined && +now - cursor <= 48 * HOUR_MS ? 100 : 500;
+ const solves = initialHistory(previous);
+ let lastId = Infinity;
+ let lastTime = Infinity;
+ let from = 1;
+ for (let i = 0; i < PAGE_CAP; i++) {
+ const url = endpoint(CF_STATUS, { handle, from: String(from), count: String(pageSize) });
+ // eslint-disable-next-line no-await-in-loop -- Offset pagination must check the preceding page boundary.
+ const body = obj(JSON.parse(await publicResponse('codeforces', url, beforeRequest)));
+ if (body.status !== 'OK') {
+ if (typeof body.comment === 'string' && /call limit exceeded/i.test(body.comment)) throw new ExternalOjRateLimit();
+ throw new Error('Codeforces submissions request failed');
+ }
+ const rows = page(body.result, pageSize);
+ if (i && (!rows.length || obj(rows[0]).id !== lastId)) throw new Error('Codeforces pagination changed during fetch');
+ for (let row = i ? 1 : 0; row < rows.length; row++) {
+ const submission = obj(rows[row]);
+ const id = positive(submission.id);
+ const at = timestamp(submission.creationTimeSeconds);
+ const seconds = +at / 1000;
+ if (id >= lastId || (since && seconds > lastTime)) throw new Error('Codeforces pagination is out of order');
+ lastId = id;
+ lastTime = seconds;
+ if (seconds < since || submission.verdict === undefined
+ || token(submission.verdict, /^[A-Z_]+$/) !== 'OK') continue;
+ // A verdict of OK on samples or pretests is not a final acceptance.
+ const testset = token(submission.testset, /^(?:SAMPLES|PRETESTS|CHALLENGES|TESTS(?:[1-9]|10)?)$/);
+ if (!testset.startsWith('TESTS')) continue;
+ const problem = obj(submission.problem);
+ const index = token(problem.index, /^[A-Za-z0-9]+$/);
+ const set = problem.contestId === undefined
+ ? token(problem.problemsetName, /^[A-Za-z][A-Za-z0-9_-]*$/)
+ : positive(problem.contestId);
+ remember(solves, `${set}:${index}`, at);
+ }
+ if (rows.length < pageSize || lastTime < since) return historyResult(solves, now);
+ // One overlapping submission detects shifts in the offset caused by new inserts or deletions.
+ from += pageSize - 1;
+ }
+ throw new ExternalOjHistoryLimit('Codeforces history exceeded the page cap');
+}
+
+const AT_PAGE_SIZE = 500;
+const AT_SUBMISSIONS = 'https://kenkoooo.com/atcoder/atcoder-api/v3/user/submissions';
+async function atcoder(handle: string, previous: Previous | undefined, { now = new Date(), beforeRequest }: FetchOptions): Promise {
+ const cursor = historyCursor(now, previous);
+ let from = historyStart(cursor, DAY_MS);
+ const solves = initialHistory(previous);
+ let boundary = new Map();
+ for (let i = 0; i < PAGE_CAP; i++) {
+ const url = endpoint(AT_SUBMISSIONS, { user: handle, from_second: String(from) });
+ // eslint-disable-next-line no-await-in-loop -- Each page determines the next inclusive timestamp.
+ const rows = page(JSON.parse(await publicResponse('atcoder', url, beforeRequest)), AT_PAGE_SIZE);
+ if (!rows.length && cursor === undefined && !from) throw new Error('No public submissions to verify the AtCoder account');
+ let second = from;
+ let atSecond = new Map();
+ const ids = new Set();
+ for (const row of rows) {
+ const submission = obj(row);
+ const id = positive(submission.id);
+ const at = timestamp(submission.epoch_second);
+ const seconds = +at / 1000;
+ const user = token(submission.user_id, HANDLE_PATTERN.atcoder);
+ const verdict = token(submission.result, /\S/);
+ const problem = token(submission.problem_id, /^[A-Za-z0-9_-]+$/);
+ if (user.toLowerCase() !== handle || seconds < second || ids.has(id)) {
+ throw new Error('Invalid AtCoder submissions pagination');
+ }
+ ids.add(id);
+ if (seconds > second) {
+ second = seconds;
+ atSecond = new Map();
+ }
+ const signature = `${problem}:${verdict}`;
+ atSecond.set(id, signature);
+ if (seconds === from && boundary.has(id)) {
+ if (boundary.get(id) !== signature) throw new Error('AtCoder pagination changed during fetch');
+ boundary.delete(id);
+ }
+ if (verdict === 'AC') remember(solves, problem, at);
+ }
+ if (boundary.size) throw new Error('AtCoder pagination changed during fetch');
+ if (rows.length < AT_PAGE_SIZE) return historyResult(solves, now);
+ if (second === from) throw new ExternalOjHistoryLimit('AtCoder pagination cannot advance past a saturated second');
+ // The endpoint is inclusive. Re-read the entire boundary second rather than lose ties.
+ from = second;
+ boundary = atSecond;
+ }
+ throw new ExternalOjHistoryLimit('AtCoder history exceeded the page cap');
+}
+
+async function nowcoder(handle: string, beforeRequest?: BeforeRequest): Promise {
+ const path = `/acm/contest/profile/${handle}/practice-coding`;
+ const html = await publicResponse('nowcoder', new URL(path, 'https://ac.nowcoder.com'), beforeRequest);
+ const menu = /
([\s\S]*?)<\/ul>/.exec(html)?.[1];
+ if (!menu?.includes(`href="${path}"`)) throw new Error('Nowcoder practice profile not found');
+ const matches = Array.from(html.matchAll(
+ /
]*>\s*
\s*(\d+)\s*<\/div>\s*\s*题已通过\s*<\/span>\s*<\/div>/g,
+ ));
+ if (matches.length !== 1) throw new Error('Nowcoder practice count unavailable');
+ return { total: count(Number(matches[0][1])) };
+}
+
+async function luogu(handle: string, beforeRequest?: BeforeRequest): Promise {
+ const url = new URL(`/user/${handle}`, 'https://www.luogu.com.cn');
+ const html = await publicResponse('luogu', url, beforeRequest);
+ const context = /
+`);
+const leetcodeProgress = (entries: { difficulty: string, count: number }[]) => Response.json({
+ data: { userProfileUserQuestionProgressV2: { numAcceptedQuestions: entries } },
+});
+
+it('uses the official total fields without inventing timestamps', async (t) => {
+ useFixtures(t, (url, init) => {
+ const source = url.origin + url.pathname;
+ if (source === 'https://ac.nowcoder.com/acm/contest/profile/42/practice-coding') return nowcoderProfile(0);
+ if (source === 'https://www.luogu.com.cn/user/42') return luoguProfile(131);
+ assert.equal(source, 'https://leetcode.cn/graphql/');
+ assert.equal(init.method, 'POST');
+ assert.deepEqual(JSON.parse(String(init.body)).variables, { userSlug: 'my-slug' });
+ return leetcodeProgress([
+ { difficulty: 'HARD', count: 7 }, { difficulty: 'EASY', count: 10 }, { difficulty: 'MEDIUM', count: 3 },
+ ]);
+ });
+ assert.deepEqual(await fetchExternalStats('nowcoder', '00042'), { total: 0 });
+ assert.deepEqual(await fetchExternalStats('luogu', '42'), { total: 131 });
+ assert.deepEqual(await fetchExternalStats('leetcode', 'My-Slug'), { total: 20 });
+});
+
+it('rejects a missing profile, hidden or mismatched count, partial GraphQL, and HTTP errors', async (t) => {
+ const responses = [
+ () => new Response('牛客网-用户不存在'),
+ () => luoguProfile(null),
+ () => luoguProfile(12, 43),
+ () => leetcodeProgress([{ difficulty: 'EASY', count: 3 }, { difficulty: 'HARD', count: 7 }]),
+ () => new Response('Too Many Requests', { status: 429 }),
+ ];
+ useFixtures(t, () => responses.shift()!());
+ await assert.rejects(fetchExternalStats('nowcoder', '42'));
+ await assert.rejects(fetchExternalStats('luogu', '42'));
+ await assert.rejects(fetchExternalStats('luogu', '42'));
+ await assert.rejects(fetchExternalStats('leetcode', 'my-slug'));
+ await assert.rejects(fetchExternalStats('codeforces', 'Alice'), ExternalOjRateLimit);
+});
+
+it('shares the Codeforces limiter across concurrent accounts and stops on a failed request', async (t) => {
+ const starts = useFixtures(t, (url) => {
+ if (url.searchParams.get('handle') === 'alice') {
+ return Response.json({ status: 'FAILED', comment: 'Call limit exceeded' });
+ }
+ return Response.json({ status: 'OK', result: [] });
+ });
+ const [alice, bob] = await Promise.allSettled([
+ fetchExternalStats('codeforces', 'Alice'),
+ fetchExternalStats('codeforces', 'Bob'),
+ ]);
+ assert.equal(alice.status, 'rejected');
+ assert.deepEqual(bob, { status: 'fulfilled', value: { total: 0, solves: [], olderSolved: [] } });
+ assert.equal(starts.length, 2);
+ assert.ok(starts[1].time - starts[0].time >= 2000);
+});
+
+it('propagates a request timeout instead of returning empty data', async (t) => {
+ t.mock.method(AbortSignal, 'timeout', (timeout: number) => {
+ assert.ok(timeout > 0 && timeout <= 15_000);
+ return AbortSignal.abort(new DOMException('Request timed out', 'TimeoutError'));
+ });
+ const starts = useFixtures(t, (_url, init) => { throw init.signal!.reason; });
+ await assert.rejects(fetchExternalStats('luogu', '42'), /timed out/i);
+ assert.equal(starts.length, 1);
+});
+
+for (const platform of ['codeforces', 'atcoder'] as const) {
+ it(`${platform} seeds lifetime IDs and keeps dates starting at the 365-day Beijing boundary`, async (t) => {
+ useFixtures(t, (url) => {
+ if (platform === 'codeforces') {
+ assert.equal(url.searchParams.get('count'), '500');
+ return Response.json({
+ status: 'OK',
+ result: [
+ ac(4, windowStart + 100, 'A'), ac(3, windowStart, 'B'),
+ ac(2, windowStart - 1, 'A'), ac(1, windowStart - 100, 'C'),
+ ],
+ });
+ }
+ assert.equal(url.searchParams.get('from_second'), '0');
+ return Response.json([
+ at(1, windowStart - 100, '42_C'), at(2, windowStart - 1, '42_A'),
+ at(3, windowStart, '42_B'), at(4, windowStart + 100, '42_A'),
+ ]);
+ });
+ const id = (index: string) => platform === 'codeforces' ? `42:${index}` : `42_${index}`;
+ assert.deepEqual(await fetchExternalStats(platform, 'Alice', undefined, { now: historyNow }), {
+ total: 3,
+ solves: [{ problem: id('B'), at: date(windowStart) }],
+ olderSolved: [id('A'), id('C')],
+ });
+ });
+}
+
+it('Codeforces uses cursorAt and a 100-row page for short gaps and compacts legacy solves', async (t) => {
+ const cursor = +historyNow / 1000 - 2 * 24 * 60 * 60;
+ const cutoff = cursor - 6 * 60 * 60;
+ const previous = {
+ lastSuccessAt: date(cursor + 60),
+ cursorAt: date(cursor),
+ olderSolved: ['42:A'],
+ solves: [
+ { problem: '42:A', at: date(cutoff) },
+ { problem: '42:B', at: date(windowStart - 1) },
+ ],
+ };
+ const starts = useFixtures(t, (url) => {
+ const size = Number(url.searchParams.get('count'));
+ assert.equal(size, 100);
+ return Response.json({
+ status: 'OK',
+ result: [
+ ac(size + 4, cursor + 60, 'A'), ac(size + 3, cursor, 'B'), ac(size + 2, cutoff, 'C'),
+ ...Array.from({ length: size - 3 }, (_, i) => ac(size + 1 - i, cutoff - 1, 'D')),
+ ],
+ });
+ });
+ assert.deepEqual(await fetchExternalStats('codeforces', 'Alice', previous, { now: historyNow }), {
+ total: 3,
+ solves: [{ problem: '42:C', at: date(cutoff) }],
+ olderSolved: ['42:A', '42:B'],
+ });
+ assert.equal(starts.length, 1);
+ assert.equal(previous.solves.length, 2);
+ assert.deepEqual(previous.olderSolved, ['42:A']);
+});
+
+it('Codeforces catches up from lastSuccessAt after a long outage with 500-row pages', async (t) => {
+ const success = windowStart - 8 * 24 * 60 * 60;
+ const starts = useFixtures(t, (url) => {
+ const size = Number(url.searchParams.get('count'));
+ assert.equal(size, 500);
+ if (url.searchParams.get('from') === '1') {
+ return Response.json({
+ status: 'OK',
+ result: Array.from({ length: size }, (_, i) => ac(size + 2 - i, windowStart + 1, 'A')),
+ });
+ }
+ assert.equal(url.searchParams.get('from'), '500');
+ return Response.json({ status: 'OK', result: [ac(3, windowStart + 1, 'A'), ac(2, success + 1, 'B')] });
+ });
+ assert.deepEqual(await fetchExternalStats('codeforces', 'Alice', {
+ lastSuccessAt: date(success), solves: [],
+ }, { now: historyNow }), {
+ total: 2,
+ solves: [{ problem: '42:A', at: date(windowStart + 1) }],
+ olderSolved: ['42:B'],
+ });
+ assert.equal(starts.length, 2);
+});
+
+it('AtCoder catches up from cursorAt and never re-dates an old ID', async (t) => {
+ const cursor = windowStart - 24 * 60 * 60;
+ const cutoff = cursor - 24 * 60 * 60;
+ useFixtures(t, (url) => {
+ assert.equal(url.searchParams.get('from_second'), String(cutoff));
+ return Response.json([
+ at(1, cutoff, 'old'), at(2, cursor + 1, 'missed'), at(3, windowStart + 1, 'old'), at(4, windowStart + 2, 'new'),
+ ]);
+ });
+ assert.deepEqual(await fetchExternalStats('atcoder', 'Alice', {
+ cursorAt: date(cursor), lastSuccessAt: date(windowStart + 10), olderSolved: ['old'],
+ }, { now: historyNow }), {
+ total: 3,
+ solves: [{ problem: 'new', at: date(windowStart + 2) }],
+ olderSolved: ['missed', 'old'],
+ });
+});
+
+it('checks quota after the local limiter for each page and propagates the rejection unchanged', async (t) => {
+ const starts = useFixtures(t, () => Response.json({
+ status: 'OK',
+ result: Array.from({ length: 500 }, (_, i) => ac(500 - i, 100, 'A')),
+ }));
+ const error = new Error('local quota exhausted');
+ const checks: number[] = [];
+ await assert.rejects(fetchExternalStats('codeforces', 'Alice', undefined, {
+ beforeRequest: async () => {
+ checks.push(now);
+ if (checks.length === 2) throw error;
+ },
+ }), (cause: unknown) => cause === error);
+ assert.equal(starts.length, 1);
+ assert.equal(checks.length, 2);
+ assert.equal(checks[0], starts[0].time);
+ assert.ok(checks[1] - checks[0] >= 2000);
+});
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/components/tab/Tab.js b/packages/ui-default/components/tab/Tab.js
index bb61d97fb2..22ebac938e 100644
--- a/packages/ui-default/components/tab/Tab.js
+++ b/packages/ui-default/components/tab/Tab.js
@@ -97,7 +97,11 @@ export default class Tab extends DOMAttachedObject {
// 4. Finalize
this.currentIndex = idx;
- if (this.hasMemo) location.hash = `#tab-${idx}`;
+ if (this.hasMemo) {
+ const anchor = $newTab.attr('data-tab-anchor');
+ if (anchor) history.replaceState(history.state, '', `#${anchor}`);
+ else location.hash = `#tab-${idx}`;
+ }
this.isAnimating = false;
}
@@ -144,14 +148,15 @@ export default class Tab extends DOMAttachedObject {
return idx;
}
}
- return null;
+ const idx = this.$content.children().get().findIndex((panel) => panel.dataset.tabAnchor === hash);
+ return idx < 0 ? null : idx;
};
const handleIdChange = () => {
const idx = getIdx();
if (typeof idx === 'number') this.switchToTab(idx);
};
$(window).on('hashchange', handleIdChange);
- handleIdChange();
+ this.currentIndex = getIdx() ?? 0;
} else this.currentIndex = 0;
this.$content
diff --git a/packages/ui-default/index.ts b/packages/ui-default/index.ts
index adcf3cf3b9..3f84fa3dce 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 {
@@ -9,6 +10,25 @@ import { presetRenderers } from './backendlib/contentRenderer';
import markdown from './backendlib/markdown';
import { TemplateService } from './backendlib/template';
+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,6 +220,7 @@ 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);
ctx.Route('set_theme', '/set_theme/:theme', SetThemeHandler);
@@ -213,6 +234,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/external_oj.page.styl b/packages/ui-default/pages/external_oj.page.styl
new file mode 100644
index 0000000000..3182cd31b1
--- /dev/null
+++ b/packages/ui-default/pages/external_oj.page.styl
@@ -0,0 +1,128 @@
+.external-oj-account
+ display: grid
+ grid-template-columns: minmax(165px, 2fr) minmax(125px, 1fr) auto
+ gap: 12px
+ align-items: end
+ margin-top: 12px
+ padding-block: 12px
+ border-bottom: 1px solid rgba(128, 128, 128, .25)
+
+ label
+ display: block
+ margin-bottom: 4px
+
+ p
+ margin: 0
+
+ p.external-oj-account__error
+ margin-top: .375rem
+ font-weight: 600
+ color: #ad274a
+
+ .button
+ margin: 0 0 4px
+
+ small
+ display: block
+
+ +mobile()
+ grid-template-columns: 1fr
+
+.external-oj-activity__header
+ display: flex
+ flex-wrap: wrap
+ align-items: flex-end
+ justify-content: space-between
+ gap: 12px
+ margin-bottom: 14px
+
+ h2
+ margin-bottom: 4px
+
+ p
+ margin: 0
+
+.external-oj-activity__overflow
+ overflow-x: auto
+ padding: 4px
+
+.external-oj-activity__months,
+.external-oj-activity__calendar
+ display: grid
+ grid-auto-flow: column
+ grid-auto-columns: 12px
+ gap: 3px
+ width: max-content
+
+.external-oj-activity__months
+ font-size: rem(11px)
+ white-space: nowrap
+ margin-bottom: 4px
+
+.external-oj-activity__calendar
+ grid-template-rows: repeat(7, 12px)
+
+.external-oj-activity__day,
+.external-oj-activity__legend i
+ appearance: none
+ padding: 0
+ width: 12px
+ height: 12px
+ border: 1px solid rgba(90, 110, 100, .22)
+ border-radius: 3px
+
+.external-oj-activity
+ [data-oj-level="0"]
+ background: rgba(120, 135, 130, .22)
+ [data-oj-level="1"]
+ background: #a6dfaf
+ [data-oj-level="2"]
+ background: #5eb775
+ [data-oj-level="3"]
+ background: #2f9253
+ [data-oj-level="4"]
+ background: #16633d
+ [data-oj-level="missing"]
+ background: repeating-linear-gradient(135deg, transparent 0 2px, rgba(120, 135, 130, .35) 2px 4px)
+
+ [data-oj-day]:focus-visible,
+ [data-oj-day][aria-pressed="true"]
+ outline: 2px solid #07878b
+ outline-offset: 2px
+
+.external-oj-activity__legend
+ display: flex
+ align-items: center
+ gap: 4px
+ margin: 8px 0 14px
+
+.external-oj-activity__day-detail
+ min-height: 40px
+ margin-bottom: 12px
+
+ ul
+ display: flex
+ flex-wrap: wrap
+ gap: 6px 16px
+ padding: 0
+ margin: 6px 0 0
+ list-style: none
+
+.external-oj-activity__accounts
+ table-layout: fixed
+ width: 100%
+
+ .external-oj-activity__platform-col
+ width: 26%
+
+ .external-oj-activity__handle-col
+ width: 27%
+
+ .external-oj-activity__handle
+ overflow-wrap: anywhere
+
+ td span
+ margin-inline-start: 4px
+
+ small
+ margin-inline-start: 8px
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..1230265872 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)
@@ -33,5 +33,126 @@
height: 36px !important;
+mobile()
- .col--bio, .col--detail
+ .col--bio
display: none
+
+.page--homepage
+ +mobile()
+ .col--detail
+ display: none
+
+.page--ranking
+ .ranking-grades
+ display: flex
+ flex-wrap: wrap
+ gap: rem(4px) rem(12px)
+ margin-bottom: rem(12px)
+
+ a
+ padding: rem(4px) rem(6px)
+
+ a[aria-current="page"]
+ font-weight: bold
+ text-decoration: underline
+
+ .ranking-boards
+ display: grid
+ grid-template-columns: minmax(0, 1fr)
+ align-items: start
+ gap: 0 rem(16px)
+
+ @media (min-width: 75rem)
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1.2fr)
+
+ .ranking-table-scroll
+ overflow-x: auto
+
+ .ranking-external-scope
+ display: flex
+ flex-wrap: wrap
+ gap: rem(8px) rem(16px)
+ margin-top: rem(8px)
+
+ a[aria-current="page"]
+ font-weight: bold
+ text-decoration: underline
+
+ .ranking-rp-table
+ width: 100%
+ table-layout: fixed
+
+ .col--rank
+ width: rem(46px)
+
+ .col--user
+ width: auto
+ overflow-wrap: anywhere
+
+ .col--rp, .col--detail, .col--ac
+ width: rem(50px)
+ white-space: nowrap
+
+ th, td
+ padding-left: rem(7px)
+ padding-right: rem(7px)
+
+ +mobile()
+ font-size: rem(12px)
+
+ .col--rank, .col--rp, .col--detail, .col--ac
+ width: rem(38px)
+
+ th, td
+ padding-left: rem(3px)
+ padding-right: rem(3px)
+
+ .ranking-external-table
+ width: 100%
+ min-width: rem(520px)
+ table-layout: fixed
+
+ &__rank
+ width: rem(60px)
+
+ &__site
+ width: rem(45px)
+
+ &__site--codeforces
+ width: rem(91px)
+
+ &__site--atcoder
+ width: rem(68px)
+
+ &__total
+ width: rem(63px)
+
+ th, td
+ padding-left: rem(6px)
+ padding-right: rem(6px)
+ text-align: right
+ white-space: nowrap
+
+ th:nth-child(2), td:nth-child(2)
+ text-align: left
+
+ td:first-child
+ font-variant-numeric: tabular-nums
+ text-overflow: clip
+
+ td:nth-child(2)
+ max-width: rem(160px)
+ white-space: normal
+ overflow-wrap: anywhere
+
+ th[aria-sort="descending"] .ranking-sort-link
+ font-weight: bold
+ text-decoration: underline
+
+ .ranking-stale
+ display: inline-block
+ margin-left: rem(2px)
+ font-weight: bold
+
+ .ranking-external-note
+ padding: rem(8px) rem(12px)
+ font-size: rem(12px)
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/pages/user_detail.page.ts b/packages/ui-default/pages/user_detail.page.ts
new file mode 100644
index 0000000000..cfcc41c31e
--- /dev/null
+++ b/packages/ui-default/pages/user_detail.page.ts
@@ -0,0 +1,72 @@
+import $ from 'jquery';
+import { NamedPage } from 'vj/misc/Page';
+
+function level(count: number | null) {
+ if (count === null) return 'missing';
+ if (!count) return '0';
+ if (count === 1) return '1';
+ if (count < 4) return '2';
+ if (count < 7) return '3';
+ return '4';
+}
+
+export default new NamedPage('user_detail', () => {
+ const view = document.querySelector('[data-external-oj-activity]');
+ const selector = view?.querySelector('#external-oj-source');
+ const detail = view?.querySelector('.external-oj-activity__day-detail');
+ if (!view || !selector || !detail) return;
+ const labels = JSON.parse(view.dataset.ojLabels) as string[];
+ const cells = [...view.querySelectorAll('[data-oj-day]')].map((button) => ({
+ button,
+ counts: JSON.parse(button.dataset.ojCounts) as (number | null)[],
+ }));
+ if (!cells.length) return;
+ const calendar = view.querySelector('.external-oj-activity__overflow');
+ const openRecent = () => { if (calendar) calendar.scrollLeft = calendar.scrollWidth; };
+ $(view.closest('.section__tab-main')).on('vjContentShow', openRecent);
+ openRecent();
+ let current = cells.length - 1;
+ let selected = false;
+ const describe = (count: number | null) => count === null ? '暂无数据' : `${count} 题`;
+ function showDay(index: number) {
+ cells[current].button.tabIndex = -1;
+ cells[current].button.setAttribute('aria-pressed', 'false');
+ current = index;
+ selected = true;
+ const { button, counts } = cells[index];
+ button.tabIndex = 0;
+ button.setAttribute('aria-pressed', 'true');
+ const heading = document.createElement('strong');
+ heading.textContent = button.dataset.ojDay;
+ const list = document.createElement('ul');
+ labels.forEach((label, i) => {
+ const line = document.createElement('li');
+ line.textContent = `${label}:${describe(counts[i])}`;
+ list.append(line);
+ });
+ detail.replaceChildren(heading, list);
+ }
+ selector.addEventListener('change', () => {
+ for (const { button, counts } of cells) {
+ const count = selector.value === 'all'
+ ? (counts.some((n) => n !== null) ? counts.reduce((a, b) => a + (b ?? 0), 0) : null)
+ : counts[Number(selector.value)] ?? null;
+ button.dataset.ojLevel = level(count);
+ button.setAttribute('aria-label', `${button.dataset.ojDay},${describe(count)}`);
+ button.title = `${button.dataset.ojDay} · ${describe(count)}`;
+ }
+ if (selected) showDay(current);
+ });
+ cells.forEach(({ button }, i) => {
+ button.title = button.getAttribute('aria-label');
+ button.addEventListener('click', () => showDay(i));
+ button.addEventListener('keydown', (event) => {
+ const offset = { ArrowLeft: -7, ArrowRight: 7, ArrowUp: -1, ArrowDown: 1 }[event.key];
+ if (offset === undefined) return;
+ event.preventDefault();
+ const target = Math.min(cells.length - 1, Math.max(0, i + offset));
+ showDay(target);
+ cells[target].button.focus();
+ });
+ });
+});
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..3c12dd4bab 100644
--- a/packages/ui-default/templates/components/home.html
+++ b/packages/ui-default/templates/components/home.html
@@ -3,7 +3,6 @@