diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 292a628c3e..d93036dffa 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -75,7 +75,7 @@ jobs: env: SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} - name: Publish - if: ${{ github.event_name == 'push' }} + if: ${{ github.event_name == 'push' && github.repository == 'hydro-dev/Hydro' }} run: node -r @hydrooj/register build/publish.ts # - name: Benchmark # run: yarn benchmark @@ -136,4 +136,4 @@ jobs: # context: ./install/docker/judge # tags: | # docker.pkg.github.com/hydro-dev/judge:${{ github.sha }} - # docker.pkg.github.com/hydro-dev/judge:${{ github.ref }} \ No newline at end of file + # docker.pkg.github.com/hydro-dev/judge:${{ github.ref }} diff --git a/.gitignore b/.gitignore index c6b38a96c0..b5d769d0e2 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,8 @@ dist/ /build/*.js .cache/ *.log +*.log.gz +*.js.map *.js.map *.tsbuildinfo *.hydro @@ -61,6 +63,7 @@ __* !__mocks__ !.gitkeep *.local +ceshi.sh # Monokle .monokle diff --git a/.yarn/patches/@types-koa-npm-3.0.3-content-disposition.patch b/.yarn/patches/@types-koa-npm-3.0.3-content-disposition.patch new file mode 100644 index 0000000000..03f676cd19 --- /dev/null +++ b/.yarn/patches/@types-koa-npm-3.0.3-content-disposition.patch @@ -0,0 +1,6 @@ +diff --git a/index.d.ts b/index.d.ts +--- a/index.d.ts ++++ b/index.d.ts +@@ -358,1 +358,1 @@ +- attachment(filename?: string, options?: contentDisposition.Options): void; ++ attachment(filename?: string, options?: contentDisposition.CreateOptions): void; diff --git a/README.md b/README.md index e465a06130..ae0ac14370 100644 --- a/README.md +++ b/README.md @@ -1,1087 +1 @@ -# Hydro - -![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/hydro-dev/hydro/build.yml?branch=master) -![hydrooj](https://img.shields.io/npm/dm/hydrooj) -![npm](https://img.shields.io/npm/v/hydrooj?label=hydrooj) -![node-current](https://img.shields.io/node/v/hydrooj) -![GitHub contributors](https://img.shields.io/github/contributors/hydro-dev/Hydro) -![GitHub commit activity](https://img.shields.io/github/commit-activity/y/hydro-dev/Hydro) - -Hydro 是一个高效信息学在线测评系统。易安装,跨平台,多功能,可扩展,有题库。 - -对于不熟悉 Linux 或是懒得运维的老师,我们也提供了免费开通即用的在线版本, -详情前往 [https://hydro.ac](https://hydro.ac) 查看 [操作指引](https://hydro.ac/discuss/6172ceeed850d38c79ae18f9) - -将安装命令粘贴到控制台一键安装,安装后注册首个用户自动获得超级管理员权限。 -兼容主流 Linux 发行版,推荐使用 Debian 12,支持 arm64 设备(树莓派等) - -```sh -LANG=zh . <(curl https://hydro.ac/setup.sh) -``` - -[中文文档](https://hydro.js.org/) / [English](./README-EN.md) - -相关文档若说明的不够详细,请提交 Pull Request 或联系开发组说明。 -bug 和功能建议请在 Issues 提出。 - -## 系统特点 - -### 模块化设计,插件系统,功能热插拔 - -Hydro 设计了一套模块化的插件系统,可以方便地扩展系统功能。 -使用插件系统,可以在修改功能后,仍然保证系统的可升级性。 -Hydro 的所有历史版本均可平滑升级到最新版本。 - -插件使用和开发指南,请前往文档 [插件](https://docs.hydro.ac/docs/Hydro/plugins) 和 [开发](https://docs.hydro.ac/docs/Hydro/dev/typescript) 章节。 - -### 跨平台兼容,数据一键备份/导入 - -Hydro 支持所有主流的 Linux 发行版,兼容 x86_64 和 arm64 架构设备,且均可一键安装。 -Hydro 可在 树莓派 或是 Apple M1/M2 上正常运行。 - -使用 `hydrooj backup` 即可备份系统全部数据,使用 `hydrooj restore 文件名` 即可导入备份数据。 -整个过程无需手工干预。 - -### 单系统多空间,不同班级/院校,分开管理 - -Hydro 提供了单系统多空间支持,可以方便地为不同的班级/年级/院校等创建独立的空间。 -不同空间内除用户外数据默认隔离,且可分配独立管理员,互不干扰。 -题目可跨域复制,在系统内仅占用一份空间。 - -### 粒度精细的权限系统,灵活调节 - -Hydro 的权限可以按比赛/作业分配给对应的用户,也可以将用户分组(班级),按组分配权限。 -有关权限节点,可以查看 [介绍](https://docs.hydro.ac/docs/Hydro) 下方截图。 - -### 规模化支持,上千用户无压力,伸缩组秒级自动扩展 - -Hydro 系统本身是无状态的,这意味着你可以随意增删服务节点,而不会影响系统的正常运行。 -评测队列会自动在当前在线的所有评测机间均衡分配。接入弹性伸缩组后,可根据服务器负载情况自动增删评测机。 -不像其他系统,Hydro 会管理不同服务器间的测试数据缓存,按需拉取,做到评测机上线即用,无需手动同步数据。 - -### 全题型支持,跟随时代潮流 - -Hydro 支持所有题型。无论是传统题型,Special Judge,还是文件输入输出,提交答案题,IO 交互,函数交互,乃至选择填空题等, -Hydro 都有相应的支持。安装相关运行环境后,Hydro 甚至可以做到: - -- 调用小海龟画图,与标准图片比对; -- 调用 GPU 进行机器学习模型的评测; - -更多的样例可前往 [样例区](https://hydro.ac/d/system_test/) 查看并下载。 - -### 丰富的题库 - -Hydro 支持导入常见格式的题库文件,包括 Hydro 通用的 zip 格式,HUSTOJ 导出的 FPS (xml) 格式题目,QDUOJ 导出的压缩包。 -可以在 [Hydro 题库](https://hydro.ac/d/tk/p) 下载免费题库使用。 -Hydro 同时支持 VJudge,这意味着你可以直接在系统内导入其他平台的题目,修改题面后编入自己的作业或比赛,快速搭建自己的题库体系。 -当前支持的平台有: - -- [一本通编程启蒙](https://hydro.ac/ybtbas.zip):官方提供一本通编程启蒙题库,免费使用,参照压缩包内导入说明。 -- [深入浅出程序设计竞赛](https://hydro.ac/srqc.zip):官方提供洛谷《深入浅出程序设计竞赛(基础篇)》配套题库,免费使用,参照压缩包内导入说明。 -- [UOJ](https://uoj.ac):国内知名 OJ,国家集训队常用; -- [Codeforces](https://codeforces.com):国外大型竞赛平台,大量高质量题目; -- [洛谷](https://www.luogu.com.cn):使用此功能需要向洛谷购买授权; -- [HDUOJ](https://acm.hdu.edu.cn):杭州电子科技大学在线评测系统,其中包含多校训练题; -- [CSGOJ](https://cpc.csgrandeur.cn):广东省赛与湖南省赛赛题评测平台; -- [SPOJ](https://www.spoj.com):国内连接很不稳定,不推荐; -- [POJ](https://poj.org):较为古董,服务器稳定性差; -- [YACS](https://iai.sh.cn):上海市计算机学会竞赛平台,单账号每日提交有限制; -- HUSTOJ:理论上支持所有 HUSTOJ 驱动的系统,但由于各个系统中 UI 有差异,通常需要手动适配。 - -### 多赛制支持 - -Hydro 支持多种赛制,包括 ACM/ICPC 赛制(支持封榜),OI 赛制,IOI 赛制,乐多赛制,以及作业功能。 -在 IOI 和 OI 赛制下,支持订正题目功能,学生在赛后可以在题库中提交对应题目,其分数会在榜单旁边显示。 -在 IOI 和 OI 赛制下,支持灵活时间功能,学生可以在设定的时间范围内,自选 X 小时参赛。 - -### 轻松添加其他编程语言 - -Hydro 的语言设置并非硬编码于系统中,而是使用了配置文件。 -只要能写出对应语言的编译命令和运行命令,Hydro 都可以进行判题。 - -## 联系我们 - -Email:i@undefined.moe -Telegram [@undefinedmoe](https://t.me/undefinedmoe) -Hydro 用户群:1085853538 - -注:加入用户群请先阅读[《提问的智慧》](https://github.com/ryanhanwu/How-To-Ask-Questions-The-Smart-Way/blob/main/README-zh_CN.md)。 -同时群内可能存在部分令您感到不适或感到冒犯的内容。若对此有顾虑**请勿加群**。 - -
-

更新日志(点击展开)

- -## Hydro 5.1.0 / UI 4.59.1 - -- core: 支持同语言添加多个题面 -- ui: 优化 monaco worker 加载 -- db: 添加 HYDRO_BACKUP_DIR 选项 -- ui: UserSelectAutoComplete: 添加查询缓存 -- core: 支持组队参赛 -- core: 修复自测过滤 -- core: 修复批量设置用户角色 -- judge: 添加交互题退出顺序检测 -- core&ui: 交互优化 - -## Hydro 5.0.5 / UI 4.58.5 - -- elastic: 修复基于 ID 搜索 -- ui: 将代码存储移动至 indexeddb -- core: 允许比赛开始前移除参赛者 - -## Hydro 5.0.4 / UI 4.58.4 - -- onsite-toolkit: 允许导入用户到指定域 -- core: cli: 添加交互模式 -- ui: 添加 domain 缓存 -- judge: 修复文件IO空输出检查 -- core: 默认关闭查看他人提交记录权限 - -## Hydro 5.0.2 / UI 4.58.2 - -- judge: 支持 multi-pass 题型 - -## Hydro 5.0.0 / UI 4.58.0 - -- oauth: 添加 oidc 模块 -- onsite-toolkit: 对接外置滚榜组件 -- core&ui: 支持在管理用户中显示 default 权限用户 -- ui: 客观题:支持下拉菜单 -- core: 支持提前退出比赛 -- ui: 用户权限:支持多选 -- ui: 用户小组:支持批量导入导出 -- ui: 用户小组:支持统计小组人数 -- core&ui: 支持设置比赛结束后不公开榜单 -- judge: 支持配置叠加层 -- judge: 添加 pipe_proxy 选项 -- judge: 优化 \r 处理 - -## Hydro 5.0.0-beta.18 / UI 4.58.0-beta.19 - -- ui: problemconfig: 修复子任务测试点拖拽 -- ui: problemconfig: 修复子任务依赖设置 -- ui: 调整默认编译空间设置 -- core: 修复重载设置导致设置项复制的问题 -- core: 修复题解被赞数量显示 -- ui: 修复题解区长数学公式显示 - -## Hydro 5.0.0-beta.17 / UI 4.58.0-beta.18 - -- ui: 自动折叠过长的题解内容 -- core: 添加比赛功能白名单 -- core: 支持多文件 patch -- core: buildContent: 支持 background 字段 -- core: 排名:排除不在本域内的用户 - -## Hydro 5.0.0-beta.16 / UI 4.58.0-beta.17 - -- core: 修复繁体中文 i18n 自动检测 -- scoreboard-xcpcio: 修复子域中自动重定向 -- core&ui: 繁体中文翻译完善 -- core&ui: 支持搜索训练计划 -- core: 修复 judge 特定情况下的竞态 -- onsite-toolkit: 添加比赛模式 -- ui: 支持自动填写测试数据输入到在线 IDE -- ui: 默认禁用提交列表页面统计数据 -- judge: 支持同时运行多组自测数据 - -## Hydro 5.0.0-beta.15 / UI 4.58.0-beta.16 - -- core: 修复题目创建页面多语言切换 -- ui: 修复比赛题目列表显示 -- scoreboard-xcpcio: 内置外榜推送功能 -- onsite-toolkit: 优先使用座位号作为 cdp id -- scoreboard-xcpcio: 支持定时刷新 -- onsite-toolkit: 支持从 URL 加载头像 -- onsite-toolkit: 支持展平的队伍照片目录 -- core: 复制题目时同时复制难度 -- core&ui: 训练页面题目缺失不影响正常显示 -- migrate: add jnoj support - -## Hydro 5.0.0-beta.13 / UI 4.58.0-beta.14 - -- ui: 比赛页面添加打印快捷入口 -- ui: 比赛题目列表显示时空限制和提交按钮 -- core: 检查题解投票权限 -- ui: 修复题目配置页文件操作 -- ui: 移除旧的 window.Hydro.util 和 window.Hydro.component 对象 -- onsite-toolkit: 添加导入工具 -- onsite-toolkit: 添加 submit 和 printfile 支持 -- onsite-toolkit: 支持限制通信功能 -- core: backup: 速度优化 -- ui: 优化超长公式显示 -- core&ui: 添加允许所有人邀请的选项 -- ui: 优化题目配置页暗色模式 -- scoreboard-xcpcio: 支持注册为默认榜单 - -## Hydro 5.0.0-beta.12 / UI 4.58.0-beta.12 - -- framework: 修复 SSE 模式参数识别 -- ui: 记忆比赛计分板筛选状态 -- ui: 修复封榜后提交记录动态更新 -- scoreboard-xcpcio: 实验性榜单缓存支持 -- ui: 添加比赛一血提示 -- core: 添加 hydrooj diag 快速诊断工具 -- ui: 禁用链接自动折叠,复制链接自动转义括号 -- ui: 优化资源缓存 -- core&ui: 支持题目排序 - -*Breaking API Changes* -- 升级到 React 19 -- 升级到 MongoDB Driver 7 -- 移除 blueprint.js, react-query 内置,优化资源大小 -- 使用 @mongodb-js/saslprep 替代 saslprep - -## Hydro 5.0.0-beta.11 / UI 4.58.0-beta.10 - -- core&ui: 优化新设置页面 -- core: 修复乐多榜单尝试数为负 -- ui: 修复内置 qface 表情包链接 -- core: 修复编辑题号冲突提示 -- ui: 修复题目配置页语言选择 -- vjudge: 功能优化 -- judge: 稳定性修复 -- ui: 修复 css 动态加载 -- core: 支持比赛材料上传 -- core: 性能和内存占用优化 -- core: 重命名 PERM_VIEW_DISPLAYNAME 为 PERM_VIEW_USER_PRIVATE_INFO - -## Hydro 5.0.0-beta.9 / UI 4.58.0-beta.9 - -- core: 修复 OI/IOI 赛制一血计算 -- judge: 修复 detail 设置 -- core: problems 接口按请求顺序返回 -- core: 添加解绑 OAuth 账户支持 -- framework: 支持 API namespace -- judge: 优化比较器性能 -- core: 检查作业延期规则合法性 -- core: 踢出用户时自动标记权限为 Guest -- ui: 删除域增加确认弹框 -- core: 允许重测同一记录覆盖题目状态 - -## Hydro 5.0.0-beta.8 / UI 4.58.0-beta.8 - -- core&ui: 添加比赛打印功能 -- core: 允许使用管理员权限直接邀请用户加入域 -- vjudge: 支持拉取远端题解 -- core: settings: 禁止 displayName 使用特殊 unicode 字符 - -## Hydro 5.0.0-beta.6 / UI 4.58.0-beta.6 - -- core: 修复网页端执行脚本返回值 -- core: patch: 支持从本地文件读取 -- core: 支持复制/导入题目时设置隐藏 -- prom-client: 添加连接数指标 -- core: 支持基于 restic 增量备份 -- ui: 添加 alert/prompt/confirm 函数 -- core&ui: 支持复制/导入题目时设置为隐藏 -- core: 添加比赛语言限制 - -## Hydro 5.0.0-beta.3 / UI 4.58.0-beta.3 - -### New Features - -- judge: 添加 checker 编译缓存 -- ui: 优化题目详情页面 OGP 信息 -- core&ui: 升级 simplewebauthn -- register: 添加 tsdown 支持 -- ui&judge: 支持指定 checker 语言 -- core: 基于相对时间计算一血而非绝对时间 -- ui&judge: 添加栈空间回显 -- install: 在树莓派中自动启用 cgroup.memory -- install: 添加 shm 空间大小警告 -- core: 升级到 cordis@4 -- framework: 支持同时启用多个 renderer -- core: 分离 HMR 和 Watcher 组件 -- core: i18n: 添加 interface 选项 -- judge: 添加 kattis checker 支持 -- core: Settings: 支持使用 Schemastery -- ui: 更新系统设置页面样式 -- core: 支持存储并显示提交记录重测历史 -- core: 新的加域逻辑 -- ui: UserSelect.Multi: 支持批量粘贴用户名 -- core: oauth: 支持绑定/解绑三方平台账户 (#971) -- core: 优化 icpc 题目包导入 (#966) -- judge: 弃用 diff (#965) -- core: 支持设置加域时自动加入小组 -- core: 添加 `--disable-worker` 启动选项 -- ui: 支持使用自定义字体 -- framework&core: 重构 Subscription API -- core: 添加 fixStorage 脚本 -- ui: 允许跨页选择题目,支持批量选择题目 -- judge: 重构 config.detail 设置 -- core: 自动清理多余的静态文件 -- ui: 优化比赛题目列表显示 -- core: 添加比赛补题模式 - -### Bug Fixes - -- migrate: 修复 hustoj 自动运行 -- import-qduoj: 修复 spj=null -- core: 修复文件复制 -- ui: 修复在线 IDE 右键菜单 -- ui: 修复未登录用户查看题目文件页 -- ui: 修复暗色模式表格边框 (#968) -- ui: 修复题解回复编辑权限 -- ui: 修复高亮行号显示 -- core: 修复 `User.serialize()` 参数 -- ui: 修复更换邮箱功能 -- ui: 修复比赛侧栏 -- ui: 修复文档链接 - -### Breaking API Changes - -- vjudge: 使用 vjudge.mount 表替代 domain.mount -- judge: breaking: 不再支持在 checker 等的编译阶段读取选手代码 -- core: 强制要求使用 inject 声明插件依赖 -- core: 移除旧版本 bus 调用 -- core: 移除 global.Hydro.service -- core: 移除 global.Hydro.ui.template -- core: 移除 global.Hydro.lib -- core: 移除 String.prototype.translate (使用 ctx.i18n.translate) -- core: 升级至 Mongo Driver 6 -- core: 移除 registerResolver, registerValue, registerUnion (使用 ctx.api.resolver/...) -- core: 移除 paginate, rank (使用 ctx.db.paginate, ctx.db.ranked) -- core: 移除 setting.yaml -- core: oauth: 改为使用 ctx.oauth.provide() 注册 -- framework: 移除 ready 与 dispose 事件 (使用 ctx.effect 代替) -- core: 最低要求 node 22 -- core: 弃用 AdmZip -- utils: 移除 String.random 与 Array.isDiff - -## Hydro 4.19.0 / UI 4.57.0 - -- core&ui&judge: 添加通信题支持 -- core: 优化语言列表筛选 -- ui: builder: 支持 css 引入 -- ui: 优化客观题题目导航样式 -- ui: 在引用题目中添加显示来源按钮 -- core: problem.export: 将 pidFilter 参数标记为可选 -- onsite-toolkit: resolver: 区分打星队伍 -- judge: 文件上传出错时重试 -- framework: 文件自动回收 -- core: DomainEdit: 添加 boolean 设置项支持 -- ui: contest_boolean: 修复默认值 -- ui: 修复排名分页 -- core: RecordConnection: 支持 noTemplate 选项 - -## Hydro 4.18.2 / UI 4.56.2 - -- core: 修复提交答案题压缩包提交 (#917) -- ui: 优化 domain_user 页面性能 -- core: 优化评测任务调度 -- ui: 下载文件失败时自动重试 -- core: Consumer: 从错误中自动恢复 - -## Hydro 4.18.0 / UI 4.56.0 - -- core&ui: ScoreboardView API -- onsite-toolkit: Resolver -- core: 优化 icpc 格式导入 -- core: 添加 limit.pretest 选项 -- core: 添加 task/daily 性能日志 -- framework: 默认移除 UiContext 和 UserContext - -## Hydro 4.17.4 / UI 4.55.3 - -- core: 修复 markdown 模式下使用 HTML 导入时解析异常 -- core: 允许复制引用的题目 -- core&judge: 添加 trusted 选项 -- core: 修复导入用户 metadata 解析 -- core: 修改 pid 校验格式 -- ui: 禁用自动播放 -- core: 题目列表性能优化 - -## Hydro 4.17.3 / UI 4.55.2 - -- core: 限制显示名长度 -- core: 支持调整代码长度限制 -- core: 在作业中关闭在线 IDE 代码缓存 -- core: API: 检查 PERM_VIEW -- judge: 添加 HYDRO_TIME_USAGE 和 HYDRO_MEMORY_USAGE 环境变量 -- core&ui: 支持 i18n 热重载 -- fps-import: 优化图片导入 -- ui: 支持圆角设置 -- core: 支持 StorageModel.copy 和 StorageModel.exists -- core: 弃用 ProblemModel.list -- core: 添加 user/import/parse 和 user/import/create 钩子 - -## Hydro 4.16.0 / UI 4.54.3 - -- core: 停用 handler, lib, script 组件类型 -- core: 升级到 ts5.6, cordis3.18 -- recaptcha: 移除 -- core: 大幅提升每日任务性能 -- core: (部分)支持 icpc package format -- core: limitRate: 支持自定义 id -- core: 弃用 array 格式题面 -- core: backup: 添加 `--withAddons` 选项 (测试) -- core: session 性能优化 -- install: mongodb 默认监听 127.0.0.1 -- core&ui: 其他错误修复 - -## UI 4.54.2 - -- ui: 修复 markdown 预览 -- ui: 优化禁用内置登录时的登录框显示 - -## UI 4.54.1 - -- ui: 修复 view-transitions -- onlyoffice: 支持处理 PDF 文件 -- ui: markdown 支持显示代码行号 -- ui: 支持扩展 richmedia 功能 -- ui: 支持嵌入优酷视频 -- ui: 移除部分页面组件多余的横向滚动条 - -### Hydro 4.15.0 / UI 4.54.0 - -- core: 修复题解投票数量计算 -- ui: 优化暗色模式 404 页图片 -- ui: 点击展开编译信息 -- ui: 修复比赛计分板关注用户 -- core: ProblemModel.import: 支持 delSource 选项 -- ui: 修复生成测试数据实时推送 -- prom-client: 上报状态至控制台 -- core: oauth: 支持固定用户名 -- utils: 支持查找 nix 安装的 pm2 -- ui: 优化比赛页题目导航 -- ui: 弃用 monacoTheme 选项 -- ui: markdown 编辑器支持暗色模式 -- framework: 优化堆栈追踪 -- core: oplog: 记录访问路径 -- migrate: 加长超时时间 -- vjudge: 修复 yacs 导致系统崩溃的问题 -- sonic: 支持按题目 ID 搜索题目 -- core: 修复导入用户时若含小组会覆盖原有小组设置的问题 - -### Hydro 4.14.1 / UI 4.53.2 -- core: 修复分数泄露 -- core: 优化错误堆栈 -- core: UserModel.getListForRender: 支持额外字段 -- core: ProblemModel.import: 合并参数为导入选项 -- ui: 启用 view-transistions - -### Hydro 4.14.0 / UI 4.53.1 -- core: 修复能够越权查看隐藏题目的问题 [security] -- ui: 优化提交记录详情富文本展示 -- ui: 支持头像缓存 -- ui: 禁止文本越界显示 -- vjudge: codeforces: 优化提交 ID 获取 -- ui: 默认禁用 sentry -- core: 支持隐藏训练左侧用户栏 -- core: cli: 支持 eval -- ui: 添加实验性 speculation rules 支持 -- core: 修复训练参加人数计数 - -### Hydro 4.13.4 / UI 4.52.3 -- framework: 修复 404 返回页 -- ui: 优化用户权限页布局 -- vjudge: codeforces: 优化 katex 显示 -- core: cli: 修复 script 加载顺序 -- install: 默认禁用 yarn 更新检查 -- core: 添加 contest/edit 和 contest/del 钩子 -- ui: 支持展开测试点详情 -- core: 修复 IOI 赛制封榜 -- core: 修复缓存文件不会删除的问题 -- core: 导入题目时显示进度 -- ui: 修复含空格标签的筛选 - -### Hydro 4.13.2 / UI 4.52.0 -- a11y: 优化网页测性能测试输出顺序 -- ui: 使用新 markdown 编辑器 -- core: 优化计分板逻辑 -- ui: 将缓存移至 IndexedDB -- core: 转写 migration 为服务 -- ui: 优化 safari 浏览器兼容 -- core: 修复题目 maintainer 字段 -- judge: 支持 pretest 中使用文件 IO -- vjudge: codeforces: 添加检查是否提交成功 - -### Hydro 4.13.0 / UI 4.51.0 -- ui: 添加 sentry -- core&ui: 支持显示当前编译器版本 -- core: 数据库索引优化 -- core: 文件复制使用软链接 -- a11y: 添加性能测试工具 -- utils: 支持识别大写文件扩展名 -- ui: 优化下拉菜单样式 -- core: 优化页面标题 -- register: 支持从文件读取原 sourcemap -- ui: 修复站内消息推送 -- ui: ranking 页面添加说明 -- ui: 添加生成测试数据提示 -- framework: 从 core 解离 -- core: loader: 支持多 profile 切换 -- ui: 修复比赛计分板选手组显示 -- core: 重设比赛分数时自动重算分数 - -本版本同时引入下述插件 API 修改: - -- 移除了 app/load/${category} 钩子 -- 移除了 ctx.app (请使用 ctx.root) -- 移除了 ctx.options (请使用 ctx.root.config) -- serializer: 移除 showDisplayName 参数 -- 移除了 loader.addScript, loader.addon 函数 -- 移除了 Hydro.module.render (请使用 ctx.server.registerRenderer) -- 移除了 lib/paginate 和 lib/rank (请使用 db.paginate 和 db.ranked) - -### Hydro 4.12.3 / UI 4.50.2 -- core: 将 API 模块移入 service -- core: 比赛时提交被 hack 不触发整体重测 -- core: 将添加 pid match 的逻辑移入搜索中 -- ui: 修正 cssFilter -- judge: builtin: 维护 callback 顺序 -- core: 优化邮件地址处理 -- ui: 显示提交记录长度 -- migrate: 支持仅为冲突用户设置随机邮件地址 -- core&ui: 支持自动整理 hack 输入 -- elastic: 优化模糊搜索 -- ui: 修复客观题中多选题载入答案出错的问题 -- core: 修复 hack 按钮 - -### Hydro 4.12.0 / UI 4.50.0 -- core: 添加题目统计页 -- core: 在记录详情页显示测评进度 -- core: problem_list: 允许 hook 修改排序逻辑 -- migrate: 添加 poj 支持 -- core: api: 支持查询 rpInfo 与 avatarUrl -- ui: 允许禁用 timeago -- core: 修复 IOI(strict) 下取消成绩 -- ui: 比赛计分板中高亮自己与关注的用户 -- core: 修正比赛榜单 AC 量计算 -- core: 禁止重测自测提交 -- ui: 优化讨论编辑历史显示 -- core: 登录/注册后返回当前的 UserContext -- core: 修复比赛计分板导出的 PERM_VIEW_DISPLAYNAME 检查 -- ui: 修复 domain_user 选择框的默认值 -- ui: 修复客观题加载上次答案 -- core: 重置密码时自动禁用 2FA -- core: import: 题目包导入时支持导入题解和标程 -- core: 性能优化和漏洞修复 - -### Hydro 4.11.2 / UI 4.49.8 -- core: 支持给比赛题目设置分数倍率 (#765) -- workspace: 升级 ts 版本至 5.4.3 -- core: ws: 处理 JSON 解析异常 -- core: 允许向作业中上传文件 (#755) -- ui: 在比赛管理页显示赛题的题目标签 -- judge: 修复部分情况下客观题返回结果异常的问题 (#770) -- ui: 在 `mdInline` 中禁用部分标签 (#767) -- core: 添加 R 语言和 cpp20 支持 -- ui: 在评测记录页显示峰值耗时 -- core: 修复比赛管理员无法查看代码的问题 (#764) -- judge: 提供 `hydrojudge terminal` 入口 (#725) -- core: 支持从 `/nix/store` 加载插件 -- core: 添加 `contest/list` 钩子 -- judge: vj4 支持 -- ui: 修复评测设置面板 testlib 选择 (#762) -- fps-importer: 支持设置大小限制 -- core: 添加 `PERM_VIEW_RECORD` 权限组 (#753) -- core: 修复未登录可以查看比赛公告的问题 (#756) -- ui: 允许使用 Enter 键提交 2FA (#752) -- core: 优化训练参与成员列表 (#750) -- core&ui: 其他性能优化和漏洞修复 - -### Hydro 4.11.0 / UI 4.49.6 -- core: 升级至 cordis@3 -- core: 优化 katex 处理 -- core: 添加 monitor/collect 钩子 -- judge: 修复 analysis -- judge: 修复独立评测机首次同步测试数据错误的问题 -- migrate: 优化 hustoj 导入 -- ui: 修复部分区域 katex 错误渲染的问题 - -### Hydro 4.10.7 / UI 4.49.5 -- core: 优化比赛成绩版按照小组筛选 -- core: inject -> injectUI -- core: 修复一处内存泄漏 -- ui: 支持 `/record?nopush=1` -- judge: 修复错误的测试数据被缓存的问题 (#726) -- judge: 比赛时不显示 `RuntimeError` 详情 -- core: 比赛中题目文件跳过 PERM_VIEW_PROBLEM 检查 - -### Hydro 4.10.5 / UI 4.49.4 - -- judge: 性能优化 (thanks @criyle) -- utils: 解离 @hydrooj/register -- core: 对客观题禁用测试点数量检查 -- core: 登入时切换 sessionId -- core: 优化 require hook -- core: 修复高并发下用户创建失败问题 -- prom-client: 支持推送至 pushgateway -- core&ui: 压缩评测列表页 ws 传输 -- utils: 优化测试点识别 -- ui: 移除 serializer 函数 -- core: 添加 SettingService -- fps: 支持 `[md]` 标签 -- vjudge: codeforces: 添加频率限制 -- migrate: hustoj: 支持 remote_oj 字段 -- core: 其他漏洞修复 - -### Hydro 4.10.3 / UI 4.49.3 - -- core: 修复返回状态码异常的问题 -- core: 同步排名页行为 -- install: 不再预装 pascal 编译器 -- judge: 处理心跳包 -- core: judge: 优化任务分配 -- judge: 优化缓存管理 -- core: contest_export_ghost: 当队伍不参与排名时导出星号开头的队伍名 -- ui: 修复 monaco 粘贴动作 -- ui: 支持批量粘贴用户/题号 - -### Hydro 4.10.0 / UI 4.49.0 - -新功能: -- core&ui&judge: 支持从网页端生成测试数据 -- vjudge: 添加 yacs 支持 -- core: 支持 /record?all=1 -- core&ui: 在 ACM 赛制下隐藏测试点详情 -- onsite-toolkit: 支持基于IP地址登录 -- core&ui: 支持在网页端重命名文件 -- core&judge: 允许在单个连接中同时分发多个任务 - -优化与修复: -- core: 优化文件名过滤 -- utils: 优化测试数据匹配逻辑 -- install: caddy 默认开启压缩 -- ui: 补全部分翻译 -- install: 默认使用 mongodb6 -- core: 提交记录页性能优化 -- judge: 更新 testlib 版本 -- core: install: 支持 strip -- ui: 升级最低支持目标为 chrome65 -- core: 优化搜索题目时显示的题目数量 -- core: 修复 0 分提交记录不会显示在乐多赛排行榜的问题 -- core: 修复比赛题面中 file:// 替换 -- core: discussion: 校验 vnode 输入 -- core: 移除默认 mongo connection options -- ui: 错误页回显名称 -- ui: 修复未登录时跨域 WebSocket 连接出错的问题 -- core: 修复删除域导致 pinnedDomains 重复的问题 -- migrate: hustoj: 处理旧版本系统题目无来源字段的问题 -- migrate: 修复 UOJ 迁移脚本 -- ui: 修复 reactions 组件 -- core: 校验 referer -- core: 修复气球发放 -- 其他漏洞修复与性能优化 - -### Hydro 4.9.26 / UI 4.48.26 -- core: 修复创建题目设置难度异常的问题 -- core: 优化 document 索引 -- core&ui: 比赛气球功能 -- core&ui: clarification -- core: 修复 webauthn -- import: add HOJ support -- judge: address space limit (beta) -- install: 支持使用环境变量指定安装区域 -- ui: 修复登录时用户不存在错误 -- core: 修复登录重定向 - -### Hydro 4.9.25 / UI 4.48.25 -- core: 修复忘记密码邮件发送速率限制 -- core: 修复比赛讨论 -- ui: 修复题目编辑页子算法标签选择 -- utils: 修复 input1.txt 测试点识别 -- core: 提交列表:不在第一页时禁用实时推送 -- judge: 优化 exitcode 识别 -- core: 修复比赛题目提交页边栏 -- fps-importer: 修复 remote_oj 字段识别 -- ui: 修复使用独立 socketUrl 时 cookie 传入 -- vjudge: 更新 csgoj 题面爬取 -- vjudge: hduoj 支持 - -### Hydro 4.9.23 / UI 4.48.23 -- migrate: hustoj: 导入时忽略不存在的图片 -- core: oauth: 使用 OpenID 进行账号关联 -- core: 支持根据显示名搜索用户 -- core: 支持根据题目难度搜索题目 -- ui: 优化首页比赛作业过滤逻辑 -- core: 优化测试点识别 -- ui: 禁用自测输入的拼写检查 - -### Hydro 4.9.22 / UI 4.48.22 -- ui: 在线IDE:添加设置页面 -- core: 导出题目时添加难度信息 -- ui: 修复特定情况下 markdown 标签补全出错的问题 -- import-qduoj: 检查 pid 合法性 -- core: 排序作业列表 -- ui: 修复讨论编辑显示 -- core: 导出 pwsh 函数 -- vjudge: codeforces: 修复比赛 921 爬取异常 - -### Hydro 4.9.21 / UI 4.48.21 -- core: 修复 strictioi 比赛计分 -- ui: 修复已参加训练列表显示 -- core: 在比赛开始前禁用计分板 -- ui: 在添加用户到域的时候隐藏 default 和 guest 选项 -- core: 允许管理员筛选所有小组 -- ui: 修复语言过滤(#598) -- ui: 修复讨论 reaction - -### Hydro 4.9.20 / UI 4.48.20 -- vjudge: 修复 Codeforces 提交结果获取 -- core: 优化系统自检功能 -- vjudge: 支持 detail 设置(#582) -- ui: 禁用视频自动播放 -- install: 支持安装时自动从 UOJ 导入数据 -- ui: 修复 preferredPrefix 功能异常的问题 - -### Hydro 4.9.19 / UI 4.48.19 -- core: 修复比赛代码导出功能无法处理选手提交的二进制文件的问题 -- core: 修复比赛管理显示用户参与排名状态 -- core&ui: 支持按小组筛选比赛/作业 -- core: 显示 spj 编译超时等详情信息 -- core&ui: 导入题目:支持重新整理题号 -- core: loader: 添加 git 集成 -- install: 添加 k3s 安装样例 -- core: 默认仅使用小写文件名 -- ui: 在比赛中忽略记住的客观题答案 -- core: 移除 langs.domain 选项 -- core: 修复修改邮箱后旧邮箱仍被占用的问题 -- ui: 部分样式修复 - -### Hydro 4.9.18 / UI 4.48.18 -- ui: 客观题:支持记住上次选择的答案并添加快速跳题 -- core: 使用 $HOME/.hydro 存储临时文件 -- core: import: 导入时检查 pid 是否合法 -- ui: 添加 validAs 相关语言自测支持 -- ui: 修复灵活时间模式下比赛进度条显示 -- core: 优化导入用户识别 -- ui: 记住编辑器字体大小 -- core: 支持按标签搜索题目 - -### Hydro 4.9.17 / UI 4.48.17 -- core&ui: 比赛成绩表和训练支持基于组过滤 -- judge: 添加并行优先级处理 -- core: 为域设置操作添加操作日志 -- core: storage: 保存文件时避开 -_ 等字符 -- core: 修复评测记录列表页过滤 Waiting 提交不生效的问题 -- ui: 修复 Typescript Language Service 工作异常的问题 -- ui: 添加域快速导航开关 -- core: 添加 PERM_VIEW_HIDDEN_CONTEST 与 PERM_VIEW_HIDDEN_HOMEWORK 权限 -- ui: 翻译优化 -- core: langs: 添加 validAs 选项 -- migrate: 添加 UOJ 支持 -- core&ui: 其他漏洞修复和优化 - -### Hydro 4.9.15 / UI 4.48.15 -- ui: 客观题:允许多行答案 -- core: 修复 pinnedDomains 无法修改的问题 -- install: 调大默认限制 -- ui: 优化比赛弹窗通知 -- core: 修复比赛选手管理页时间计算 -- core: cli: 题目导出时生成默认题目 ID -- core: dump: 支持 --dbOnly 参数 -- core: 用户导入: 重复信息检查 -- ui: 更改默认版权信息 -- core: 支持训练基于置顶等级排序 -- ui: 模板热重载 - -### Hydro 4.9.13 / UI 4.48.13 -- fps-import: 支持处理远端评测题目 -- vjudge: 添加 VERDICT.WAITING 属性 -- ui: 优化测试数据自动识别 -- vjudge: 添加一本通编程启蒙支持 -- ui: 添加 `problemset/download` 钩子 -- ui: 在打印模式下隐藏部分控件 -- core: addon create 使用符号链接 -- ui: 评测记录页面显示代码行号 -- core: 支持从解压的题目文件夹导入题目 -- core: setJudge 时添加 PRIV_UNLIMITED_ACCESS - -### Hydro 4.9.12 / UI 4.48.12 -- core: 修复比赛中讨论不会随比赛删除的问题 -- vjudge: codeforces: 更新登陆检查逻辑 -- ui: 在题目提交页面显示提示 -- core: 更新用户缓存 -- core: 强制终止不回应心跳包的 Websocket 连接 -- core: 设置导入题目的默认 tag -- core: 默认禁用 Python2 -- core: 支持重排序导航栏 -- ui: 修复部分情况下进入编辑模式按钮不生效的问题 -- core: 添加 hydrooj patch 功能 -- core: 允许查看作业中自己的提交 -- core: 其他漏洞修复 - -### Hydro 4.9.8 / UI 4.48.11 -- core: 修复 strictioi 下的计分板显示问题 -- core: 允许普通用户查看比赛讨论 -- core: 启动时自动建立静态资源文件夹 -- core: 允许使用其他 UI 模块 -- judge: 修复文件 IO 题目输出重定向的问题 -- core: 不再向 Guest 用户分配 sessionId -- judge: 修复提交答案题 - -### Hydro 4.9.7 / UI 4.48.10 -- ui: websocket: 添加心跳包 -- judge: 修复客观题和文件 IO 题提交 -- judge: 添加 compile_time_limit 选项 -- core: 添加 kotlin 和 pypy3 预设 -- ui: scoreboard: 支持自动更新 -- core: contest: 封榜后允许管理员查看实时分数 -- judge: 支持按题目设置语言时空限制倍率 -- install: 支持自动导入 hustoj 数据 -- install: 支持指定安装源 -- core: 支持从 npmjs 自动安装插件 -- core&ui: 漏洞修复 -- judge: 设置最低评测优先级 -- core: 修复部分赛制下封榜时仍能查看提交列表的问题 - -### Hydro 4.9.0 / UI 4.48.0 -- core: 优化讨论鉴权 -- judge: 优化统一回调评测状态回显 -- judge: 移除 `processTestdata` 步骤 -- judge: 客观题子任务分数回显 -- core: 压平测试数据结构 -- core: rp: 修复比赛分数 -- core&ui: 首次使用 OAuth 时要求设置密码 -- ui: 评测设置 UI 升级 -- install: 根据系统内存调整 wtCacheSize -- ui: 加载速度优化 -- core: 检测域 ID 大小写 -- ui: 导航栏域索引 -- ui: 支持按权限组过滤作业/比赛 -- judge: 将 Javascript 默认解释器设置为 node -- judge: 修复删除未评测完成的题目导致评测队列卡死的问题 - -### Hydro 4.8.0 / UI 4.47.6 -- core: 升级至 mongodb@5 -- ui: 评测详情中显示子任务得分 -- core: 修复测试数据文件名以空格开头导致操作异常的问题 -- dev: 升级 devcontainer 环境 -- ui: 优化 IDE 页面布局 -- ui: 使用 cordis 进行生命周期管理(移除旧 bus) -- blog: 移动功能到独立的 `@hydrooj/blog` 插件 -- core: 支持动态设置 -- judge: 性能模式(关闭单点回调) -- ui: 支持为作业设置维护者 -- core: 放行提交答案题至提交语言白名单 -- import-qduoj: 修复空标签导致无法导入的问题 -- ui: 精简 serviceworker 逻辑 -- ui: 修复训练计划加入失败的问题 -- core: 简化 user 返回字段列表 -- core&ui: contest.rule.ioi.strict -- 其他漏洞修复和体验优化 - -### Hydro 4.7.3 / UI 4.47.3 -- core: 修复无输入自测 -- core: 修复 endpointForUser 域名不一致导致的 token 无效问题 -- core: 移除 isBinaryFile 检查 -- core: 修复 allowViewCode 设置 -- core: cli: 优先使用 mongosh -- workspace: 提供 `@hydrooj/eslint-config` 包 -- 其他漏洞修复和体验优化 - -### Hydro 4.7.2 / UI 4.47.2 -- core: 修复提交答案题 -- ui: 修复作业页面编辑与删除操作 -- vjudge: 适配 codeforces 新接口 -- core: 过滤空 `$set` 操作 -- ui: domain_dashboard 页显示域创建者 -- judge: 修复 hack -- core: 提交时检查所选语言是否存在 - -### Hydro 4.7.0 / UI 4.47.0 -- core: 支持检测导致启动卡死的问题 -- core: 修复特定情况下 rating 信息无法写入的问题 -- core: 添加更多 validator 字段类型支持,移除旧版 validator -- core&ui: 支持 CORS -- ui: 支持模块懒加载 -- ui: 修复邮箱登录 -- ui: 修复站内信显示异常的问题 -- vjudge: luogu: 修复登录 -- judge: 修复客观题部分题目未答导致评测出错的问题 -- core: `ConnectionHandler` 支持 `@subscribe(event)` -- util: 修复 `Message.sendNotification` 格式化异常的问题 -- core: 数据库优化 -- core: 校验用户头像 -- judge: 移除 onDestory 钩子,使用 disposables 替代 -- ui: 优化资源加载 - -### Hydro 4.6.0 / UI 4.46.0 -- core&ui: 添加 webauthn 支持 -- ui: 修复题解投票 -- ui: 优化比赛详情页布局 -- ui: 修复快捷搜索中评测记录链接 -- core: 添加 `Types.ArrayOf()` 支持 -- ui: 修复侧栏预览保存 -- core: 添加 CookieDomain 设置 -- ui: 修复 dev 模式下页面无限刷新的问题 -- vjudge: 提供 BasicFetcher 组件 -- core: DomainModel 缓存 -- core&ui: 其他漏洞修复 - -### Hydro 4.5.2 / UI 4.45.1 -- core: 添加乐多赛支持 -- vjudge: 移除 puppeteer 相关依赖 -- judge: 修复客观题未设置答案导致评测结果不返回的问题 -- ui: 默认移除首页右侧搜索模块 -- ui: 添加站内头像上传模块 -- core: 允许比赛创建者查看隐藏的计分板 -- core: 讨论更改为按照创建时间排序 -- ui: 修复题解投票回显 -- core: 修复找回密码链接合成错误的问题 -- judge: 修复文件 IO 题目编译输出限制过小的问题 -- core: 修复 `%` 作为关键词会导致题目搜索出错的问题 -- core: 修复比赛题目列表下方提交记录模块不显示的问题 -- ui: 修复讨论区部分表情预设 ID 和实际图像不匹配的问题 -- install: 默认设置 vm.swappiness=1 以提高性能 -- ui: 允许普通用户在设置了查询条件时按页翻阅评测记录 -- ui: 提交记录列表添加取消成绩按钮 -- core: 修复特定情况下访问日志无法记录的问题 -- workspace: 支持 pnpm -- workspace: 移除 mocha -- core: 支持使用形如 `handler/before/Name#method` 的筛选 -- judge: 性能优化 -- ui: 评测记录列表点击重测时页面不再刷新 - -### Hydro 4.5.1 / UI 4.45.0 -- ui: 支持全局快捷搜索 -- core: problem_list: 支持 limit 参数 -- core: 精简默认讨论节点列表 -- core: validator: 双汉字也被认为是合法用户名 -- judge: objective: 支持多答案题目 -- core: problemStat: 忽略已取消成绩的提交 -- ui: 修复讨论编辑 Ctrl+Enter 快捷键 -- ui: 修复锁定讨论主题功能 -- core: 优化作业鉴权设置 -- core: 封榜功能修复 -- ui: contest: 允许手动管理参赛人员 -- ui: contest: 支持赛时广播消息提醒 -- ui: 其他漏洞修复和性能优化 - -### Hydro 4.5.0 / UI 4.44.0 -- fps: 修复题目中含空文件导致导入失败的问题 -- core: 封禁用户时支持附加理由 -- vjudge: codeforces: 跳过无法访问的 1769 和 1772 比赛 -- ui: 收藏题目操作不再触发页面刷新 -- core: 重测时检查题目配置文件有效性 -- core: 退出时自动清理临时文件 -- core: 禁止使用 . 作为文件名 -- import-qduoj: 跳过不合法的题目 -- core: 修复提交答案题的比赛代码导出 -- judge: 添加 stdioLimit 项 -- ui: 修复 message.FLAG_ALERT 显示 -- core: training 可上传文件 -- ui: 优化比赛导航栏 -- ui: 比赛成绩表支持关注队伍 -- core: 允许克隆比赛/作业 -- ui: 比赛编辑页面添加功能入口 -- core: 支持打星参赛 -- core: 整题重测时跳过已取消成绩的提交 - -### Hydro 4.4.5 / UI 4.43.0 -- core: 修复比赛基于 ID 搜索题目的功能 -- judge: 修复 testlib 错误信息显示异常的问题 -- sandbox: 提高默认 stdio 限制 -- core: 修复讨论历史记录异常的问题 -- core: 优化每日任务的运行速度 -- core: 用户详情页支持显示用户近期参加的比赛/作业 -- judge: 将 Bash 添加到预设语言列表 -- vjudge: 在 cli 模式下跳过加载 -- lsp: 修复了自动补全的提示,可能需要手动更新后生效 -- judge: 优化 diff 输出 -- install: 默认使用 mongodb uri 作为数据库连接方式 -- ui: 在用户背景加载失败时 fallback 到默认背景 -- 文件路径更改为大小写敏感。 -- 在前端插件中支持使用 `import { ... } from '@hydrooj/ui-default'` 引入内置库。 -- `ctx.inject('Notification')` 支持插入多行文本。 - -### 4.4.3 -- core: 优化了比赛计分板页面的性能 -- core: 导入用户时支持指定用户所属小组和学校 -- core&ui: 其他漏洞修复和性能优化 -- 添加了 `UserModel.getListForRender(domainId, uids)` 方法。 -- 添加 `IHandler.response.pjax` 属性。 - -### 4.4.0 -- core: 移除了 Problem.assign -- core: 修复了比赛结束后,若题目仍处于隐藏状态,无法查看代码的问题 -- ui: 修复了 IE 浏览器端页脚的显示 -- judge: 修复 lemon checker 异常退出导致题目计分为 0 的问题 -- ui: 优化管理端的 Firefox 兼容性警告 -- ui: 优化 fps 题目导入后的显示 -- ui: 修复 IE 浏览器显示语言识别的问题 -- install: 检测已安装的宝塔环境并抛出不兼容警告 -- ui: 优化部分错误提示 -- migrate: 性能优化 -- vjudge: 修复 Codeforces 提交记录爬取异常的问题 -- `ProblemModel.getList()` 移除了 group 参数,后续参数前移 -- `cordis` 升级至 2.6 - -### 4.3.2 -- 修复评测详情页面在特定情况下不会即时更新的问题 -- 将 testlib spj 的错误返回至用户侧 -- 修复题目文件无法从管理员侧预览的问题 - -### 4.3.1 -- 终止对 NodeJS <14 的支持 -- ui: api: 更新了 API Workbench -- judge: 移除环境变量中 \r,添加 Python Packages 说明 -- ui: 修改了部分推荐链接 -- prom-client: 记录 EventEmitter 信息 -- core: contest: 支持导出比赛信息为 Ghost 格式 -- core: contest: 优化比赛中提交量和通过量的计算 -- core: contest: 封榜时显示 Pending 提交 -- judge: 修复客观题未设置答案导致评测跳过的问题 -- core: 优化 CsrfTokenError 和 DomainNotFoundError 回显 -- core: server: 捕获 WebSocket 错误 -- core: validator: 修复可以发送空站内消息的问题 -- 其他漏洞修复和性能优化 -- 在题目详情页中,Scratchpad.store 可从 Window 上公开访问 - -### 4.3.0 -- 安装时自动安装 Caddy 配置反向代理监听 80 端口。 -- 支持使用 `hydrooj install ` 和 `hydrooj uninstall ` 快速管理插件。 -- 在 管理域 -> 编辑域资料 处添加了语言选择的自动补全。 -- 支持在 OI 赛制下查看自己已提交的代码。 -- import-qduoj:支持导入 SPJ 题目。 -- fps-importer:适配 FPS 文件 1.4 版本。 -- 其他漏洞修复和体验优化。 -- 支持使用 `ctx.i18n.load(lang, Record)` 加载翻译文件。 -- 支持 `ctx.withHandlerClass(name, callback)` 获取类原型。 -- prom-client: 支持自定义 ConnectionHandler 上报分类。 -- 将 Handler.ctx 移动至 Handler.context,新的 Handler.ctx 为 PluginContext。 - -
- -## 开源许可 - -本项目中 framework/ examples/ install/ 下的内容采用 MIT 协议授权,您可自由使用。 -本项目中 packages/ui-default/ 下的内容仅采用 AGPL-3.0 进行授权。 -项目其余部分使用双重许可: - -1. 您可以在遵守 AGPL-3.0 许可证和下述附加条款章节的前提下免费使用这些代码: -2. 如确需闭源,您也可以联系我们购买其他授权。 - -### 附加条款 - -基于 AGPL3 协议第七条,您在使用本项目时,需要遵守以下额外条款: - -1. 不可移除、隐藏、遮挡本项目的版权声明与作者/来源署名;([AGPL3 7(b)](LICENSE#L356)) -2. 当重分发经修改后的本软件时,需要在软件名或版本号中采用可识别的方式进行注明;([AGPL3 7(c)](LICENSE#L360)) -3. 除非得到许可,不得以宣传为目的使用作者姓名;([AGPL3 7(d)](LICENSE#364)) - -即: -在您部署 Hydro 时,需要保留底部的 `Powered by Hydro` 字样,其中的 `Hydro` 字样需指向 `hydro.js.org/本仓库/fork` 之一的链接。 -若您对源码做出修改/扩展,同样需要以 AGPL-3.0-or-later 开源,您可以以 `Powered by Hydro, Modified by xxx` 格式在页脚注明。 - -对于经提醒仍不整改的项目,将列入 [HALL_OF_SHAME.md](HALL_OF_SHAME.md),同时项目组保留通过法律途径追究责任的权利。 - -## 贡献代码 - -参照 [CONTRIBUTING.md](CONTRIBUTING.md) - -## 鸣谢 - -排名不分先后,按照链接字典序 - -- [GitHub](https://github.com/) 为 Hydro 提供了代码托管与自动构建。 -- [criyle](https://github.com/criyle) 提供评测沙箱实现。 -- [Vijos](https://github.com/vijos/vj4) 为 Hydro 提供了 UI 框架。 - -## Sponsors - -- [云斗学院](https://www.yundouxueyuan.com) +本项目为HGNU ACM二开项目,fork于https://github.com/hydro-dev/Hydro diff --git a/docs/wiki-framework-deployment.md b/docs/wiki-framework-deployment.md new file mode 100644 index 0000000000..5332dab984 --- /dev/null +++ b/docs/wiki-framework-deployment.md @@ -0,0 +1,7 @@ +# 算法 Wiki 框架交接 + +本分支默认不带演示文章。第一次部署时,「Wiki」显示空目录。维护者可在「管理域 → 权限 → 常规」给指定角色勾选「编辑 Wiki 文章」,随后通过 Wiki 的「新建文章」和「管理目录」维护内容。普通读者没有编辑权限。 + +「管理目录」可集中调整左侧导航各文章的分类及顺序。数字越小越靠前;分类按其中最靠前的文章排列。网页编辑适用于当期域;右侧「本页目录」仍从 Markdown 正文的二、三级标题自动生成。文章地址在创建后不变。 + +文章和目录设置分别存在 MongoDB 的 `wiki.article`、`wiki.directory` 集合,启动或首次写入时自动创建。请在与生产版本相同的隔离实例中,用匿名、普通成员和授权角色分别验证查看、搜索、新建、编辑、目录排序和越权阻止,并确认旧的「帮助」「关于本站」和站内其他插件入口仍然可用。不要迁入测试库或 WSL 的预览文章。 diff --git a/package.json b/package.json index 7382a2a68a..68f050c8f3 100644 --- a/package.json +++ b/package.json @@ -66,6 +66,7 @@ }, "resolutions": { "mongodb": "^7.0.0", + "@types/koa": "patch:@types/koa@npm%3A3.0.3#~/.yarn/patches/@types-koa-npm-3.0.3-content-disposition.patch", "@types/express-serve-static-core": "patch:@types/express-serve-static-core@npm%3A4.19.6#~/.yarn/patches/@types-express-serve-static-core-npm-4.19.6-cc0017aaf4.patch" } } diff --git a/packages/blog/templates/blog_main.html b/packages/blog/templates/blog_main.html index c33fea4288..5fd95e7433 100644 --- a/packages/blog/templates/blog_main.html +++ b/packages/blog/templates/blog_main.html @@ -6,31 +6,35 @@
- {% 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 -%} -
  1. -
    -
    -
    -
    {{ datetimeSpan(ddoc._id, false, 'D')|safe }}
    -
    {{ datetimeSpan(ddoc._id, false, 'YYYY-M')|safe }}
    + {% if not ddocs.length %} + {{ nothing.render('no blog yet...') }} + {% else %} +
      + {%- for ddoc in ddocs -%} +
    1. +
      +
      +
      +
      {{ datetimeSpan(ddoc._id, false, 'D')|safe }}
      +
      {{ datetimeSpan(ddoc._id, false, 'YYYY-M')|safe }}
      +
      +
      +
      +

      {{ ddoc['title'] }}

      +
        +
      • {{ _('{0} views').format(ddoc.views) }}
      • +
      • {{ datetimeSpan(ddoc.updateAt)|safe }}
      • +
      -
      -

      {{ ddoc['title'] }}

      -
        -
      • {{ _('{0} views').format(ddoc.views) }}
      • -
      • {{ datetimeSpan(ddoc.updateAt)|safe }}
      • -
      -
      -
    -
  2. - {%- endfor -%} -
- {% if page and dpcount %}{{ paginator.render(page, dpcount) }}{% endif %} + + {%- endfor -%} + + {% if page and dpcount %}{{ paginator.render(page, dpcount) }}{% endif %} + {% endif %} {% endif %}
@@ -41,7 +45,7 @@

{{ _("{0}'s blog").format(udoc.uname) }}

- {% if handler.user._id == udoc._id %} + {% if handler.user._id == udoc._id and handler.user.hasPerm(perm.PERM_DELETE_DISCUSSION) %}

{{ _('Create a Post') }}

{% endif %}
diff --git a/packages/common/permission.ts b/packages/common/permission.ts index ed9b0ad1c1..7d18fd9185 100644 --- a/packages/common/permission.ts +++ b/packages/common/permission.ts @@ -86,6 +86,9 @@ export const PERM = { // Ranking PERM_VIEW_RANKING: 1n << 59n, + // Wiki + PERM_EDIT_WIKI: 1n << 71n, + // Placeholder PERM_ALL: -1n, PERM_BASIC: 0n, diff --git a/packages/contest-album/README.md b/packages/contest-album/README.md new file mode 100644 index 0000000000..29bc38a0be --- /dev/null +++ b/packages/contest-album/README.md @@ -0,0 +1,41 @@ +# HGNUOJ 比赛相册 + +独立的比赛照片展示和管理插件。浏览入口 `/albums`,沿用所在域的公告权限。 + +## 使用 + +- 按年份浏览、按比赛名称搜索;每页以 12 本为目标,按完整年份分页,同一年不会拆到两页。 +- 获奖信息可选金牌、银牌、铜牌或不显示。配置后,卡片右下角和详情标题右侧显示统一的五角星矢量图标与奖牌名称;未配置时隐藏,卡片不再显示右上箭头。 +- 有“创建公告”权限的用户可新建相册;作者需有“编辑自己的公告”权限,管理员使用“编辑公告”权限管理。 +- 先填写名称、年份、可选日期和 Markdown 简介,再批量添加照片。相册默认草稿,可勾选公开展示。 +- 支持 JPG、PNG、静态 WebP,单张 20 MiB、80 MP,每本最多 500 张,并受用户文件配额限制。 +- 可设置封面、拖动或用按钮排序、编辑照片说明、移出照片。上传立即保存,封面、排序、移出和文字信息点击“保存相册”后生效。 +- 浏览页使用 480 px 缩略图和懒加载;点开使用 1600 px 大图,支持左右方向键、手机滑动和原图入口。无脚本时照片链接仍能打开原图。 +- 大图弹窗最大宽度 1800 px、高度为屏幕的 94%,照片按比例适应可用空间;放大加号使用居中的矢量图形。 +- 详情页编辑按钮放在上方,与面包屑同行,和标题右侧奖牌信息右对齐。 +- CSS 在页面 head 中以内容版本链接加载,避免插件脚本延迟导致刷新或切换年份时排版丢失。 + +## 安装与数据 + +在已安装 `@hgnuoj/image-preview` 和 `@hydrooj/ui-default` 的 Hydro 工作区中安装依赖,将本插件加入 `addon.json` 后重启。 + +相册存储在 MongoDB 的 `hgnu.album` 集合中,按域隔离;公开用户文件由 Hydro 原文件存储管理,预览复用图片优化插件。草稿限制相册页面可见性,上传文件采用 Hydro 公开用户文件机制。 + +已有公告可通过一次性整理建立相册,照片复用原 `/file/...` 地址。插件不会自动改写公告或推断比赛日期。关联相册具有 `source.discussion`、`source.section`、`source.fragment`,公告详情会显示相册入口,相册中保留对应章节链接。 + +移出照片、删除相册只修改相册信息,不删除可能被公告共用的原文件;上传的新照片可在用户文件管理中管理。删除相册为软删除。 + +保存、上传和删除使用 revision 检查,过期操作会提示刷新;照片来源不能通过保存表单替换为任意 URL,表单域和相册编号不能覆盖当前访问地址。 + +## 当前测试数据 + +测试服务器已从公告 `669f290c911ca250f716994c` 整理 16 本相册、93 张照片。 + +- 第 51 届 ICPC 武汉站:2026 年。 +- 第 50 届 ICPC 武汉站:2025 年。 +- 按要求不展示“奖牌队牌物料合影”。 +- 原公告的 17 个章节、94 张图片及其 Markdown 保留。 + +验证:后端与前端 TypeScript、ESLint、`test/hgnu-contest-album.cjs`,以及服务器浏览器中的编辑、权限、上传、移动端和样式加载回归检查。 + +部署时需单独启用本插件、图片预览和公告目录插件,并整理相册元数据。Git 仓库包含功能代码与测试,不包含数据库、图片文件和私密运行配置。 diff --git a/packages/contest-album/frontend/album.css b/packages/contest-album/frontend/album.css new file mode 100644 index 0000000000..adc97579fb --- /dev/null +++ b/packages/contest-album/frontend/album.css @@ -0,0 +1,53 @@ +.album-app { --album-bg:#fff; --album-ink:#183149; --album-muted:#708397; --album-line:#dfe7ef; --album-soft:#f3f7fb; --album-blue:#246897; color:var(--album-ink); } +.theme--dark .album-app { --album-bg:#292e34; --album-ink:#e2eaf2; --album-muted:#a6b4c3; --album-line:#414c57; --album-soft:#222a32; --album-blue:#8dc9f3; } +.album-hero { display:flex; justify-content:space-between; align-items:center; gap:32px; padding:36px 0 30px; border-bottom:1px solid var(--album-line); } +.album-eyebrow { color:var(--album-blue); font-size:12px; font-weight:600; letter-spacing:1.5px; margin:0 0 12px; } +.album-app h1 { font-size:34px; line-height:1.3; font-weight:600; margin:0; color:var(--album-ink); } +.album-lead { color:var(--album-muted); margin:12px 0 0; font-size:15px; } +.album-hero-side { display:flex; gap:30px; align-items:center; } +.album-totals { display:flex; gap:28px; color:var(--album-muted); font-size:12px; } +.album-totals span { display:block; white-space:nowrap; }.album-totals strong { display:block; font-size:27px; line-height:1.3; font-weight:500; color:var(--album-ink); margin-bottom:4px; } +.album-button { display:inline-flex; align-items:center; justify-content:center; min-height:42px; box-sizing:border-box; padding:9px 17px; border:1px solid var(--album-line); border-radius:8px; color:var(--album-ink); background:var(--album-bg); font:inherit; font-size:13px; cursor:pointer; text-decoration:none; gap:7px; } +.album-button:hover { border-color:var(--album-blue); color:var(--album-blue); text-decoration:none; }.album-button--primary { color:#fff; background:#246897; border-color:#246897; }.album-button--primary:hover { background:#1a547d; color:#fff; } +.album-button:disabled { opacity:.55; cursor:wait; }.album-app a:focus-visible,.album-app button:focus-visible { outline:2px solid #58a4f0; outline-offset:3px; } +.album-filters { display:flex; flex-wrap:wrap; justify-content:space-between; gap:18px; padding:24px 0 6px; align-items:center; } +.album-search { display:flex; gap:8px; order:2; }.album-search input { width:220px; border:1px solid var(--album-line); border-radius:8px; padding:10px 12px; font-size:13px; background:var(--album-bg); color:var(--album-ink); } +.album-years { display:flex; flex-wrap:wrap; gap:7px; }.album-years a { display:inline-flex; gap:6px; padding:8px 12px; border-radius:7px; color:var(--album-muted); font-size:13px; }.album-years a span { font-size:11px; opacity:.7; }.album-years a.is-active { background:#246897; color:white; }.album-years a:hover { text-decoration:none; background:var(--album-bg); color:var(--album-blue); }.album-years a.is-active:hover { background:#246897; color:white; } +.album-results { margin:20px 0 0; color:var(--album-muted); font-size:13px; } +.album-year-group { margin-top:30px; }.album-year-group>h2 { display:flex; align-items:baseline; gap:12px; font-size:25px; font-weight:500; margin:0 0 17px; }.album-year-group>h2 span { color:var(--album-muted); font-size:12px; font-weight:400; letter-spacing:2px; } +.album-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:24px; }.album-card { min-width:0; border:1px solid var(--album-line); border-radius:13px; background:var(--album-bg); color:var(--album-ink); overflow:hidden; transition:box-shadow .18s,transform .18s; }.album-card:hover { text-decoration:none; color:var(--album-ink); transform:translateY(-3px); box-shadow:0 10px 24px #153a5514; } +.album-card-cover { position:relative; aspect-ratio:4/3; overflow:hidden; background:#d8e2ec; }.album-card-cover>img { width:100%; height:100%; object-fit:cover; object-position:50% 40%; }.album-photo-badge,.album-draft-badge { position:absolute; right:12px; bottom:12px; padding:5px 9px; border-radius:5px; color:#fff; background:#102c47c9; font-size:11px; }.album-draft-badge { top:12px; bottom:auto; background:#a5681de6; }.album-empty-cover { display:flex; justify-content:center; align-items:center; height:100%; color:#58718a; font-size:14px; } +.album-card-body { padding:19px 20px 18px; }.album-card-date { color:var(--album-muted); font-size:11px; letter-spacing:1px; margin:0 0 9px; }.album-card h3 { font-size:16px; font-weight:500; line-height:1.6; margin:0; min-height:52px; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; }.album-card-open { display:flex; justify-content:space-between; border-top:1px solid var(--album-line); padding-top:13px; margin-top:16px; color:var(--album-blue); font-size:12px; } +.album-pagination { display:flex; justify-content:center; align-items:center; gap:18px; margin:32px 0; font-size:13px; color:var(--album-muted); }.album-empty { padding:70px 20px; text-align:center; border:1px dashed var(--album-line); border-radius:12px; margin:28px 0; background:var(--album-bg); }.album-empty h2 { font-size:22px; margin:0 0 12px; }.album-empty p { color:var(--album-muted); margin-bottom:20px; } +.album-breadcrumb { display:flex; gap:12px; align-items:center; color:var(--album-muted); margin:12px 0 24px; font-size:13px; }.album-breadcrumb a { color:var(--album-blue); }.album-detail-header { display:flex; align-items:flex-start; justify-content:space-between; gap:24px; padding-bottom:24px; border-bottom:1px solid var(--album-line); margin-bottom:28px; }.album-detail-header h1 { font-size:29px; max-width:900px; }.album-detail-header .album-button { flex-shrink:0; } +.album-description { padding:22px 26px; background:var(--album-bg); border:1px solid var(--album-line); border-radius:10px; margin-bottom:28px; }.album-photo-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:22px; }.album-photo { margin:0; min-width:0; }.album-photo-open { display:block; width:100%; aspect-ratio:4/3; border:0; padding:0; border-radius:10px; overflow:hidden; background:#d8e2ec; position:relative; cursor:zoom-in; }.album-photo-open img { width:100%; height:100%; object-fit:cover; }.album-photo-zoom { position:absolute; right:10px; bottom:10px; width:28px; height:28px; border-radius:50%; background:#fffdfc; color:#17334e; display:grid; place-items:center; opacity:0; transition:opacity .15s; }.album-photo-zoom svg { display:block; width:16px; height:16px; }.album-photo-open:hover .album-photo-zoom,.album-photo-open:focus .album-photo-zoom { opacity:1; }.album-photo figcaption { padding:10px 2px; font-size:12px; color:var(--album-muted); }.album-source-link { margin:30px 0; font-size:13px; } +.album-viewer { box-sizing:border-box; width:min(1800px,96vw); height:94dvh; max-width:96vw; max-height:94dvh; padding:0; border:1px solid #506176; border-radius:12px; background:#101a24; color:#e9f0f6; overflow:hidden; }.album-viewer[open] { display:grid; grid-template-rows:auto minmax(0,1fr) auto; }.album-viewer::backdrop { background:#07111ce8; }.album-viewer-bar { display:flex; justify-content:space-between; align-items:center; padding:12px 18px; font-size:13px; }.album-viewer-bar>div { display:flex; align-items:center; gap:20px; }.album-viewer-bar a { color:#b9dbfb; }.album-viewer-bar button { background:none; border:0; color:white; padding:8px; cursor:pointer; font-size:19px; }.album-viewer-stage { display:flex; align-items:center; justify-content:center; position:relative; min-height:0; overflow:hidden; background:#0b131c; }.album-viewer-stage>img { display:block; max-width:100%; width:100%; height:100%; max-height:100%; object-fit:contain; }.album-viewer-stage>button { position:absolute; z-index:1; top:calc(50% - 24px); width:44px; height:48px; border:0; border-radius:8px; background:#132c44bd; color:white; font-size:32px; cursor:pointer; }.album-viewer-previous { left:12px; }.album-viewer-next { right:12px; }.album-viewer-caption { padding:12px 22px; text-align:center; margin:0; min-height:22px; font-size:13px; line-height:1.5; color:#c5d1de; max-height:14dvh; overflow:auto; overflow-wrap:anywhere; box-sizing:border-box; }.album-viewer-caption:empty { display:none; }.album-viewer-open { overflow:hidden; } +.album-editor { max-width:1100px; }.album-edit-form { border:1px solid var(--album-line); border-radius:12px; overflow:hidden; background:var(--album-bg); }.album-edit-section { padding:28px; border-bottom:1px solid var(--album-line); }.album-edit-section h2 { font-size:18px; font-weight:600; margin:0 0 22px; }.album-edit-fields { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:20px; }.album-field { display:flex; flex-direction:column; gap:8px; font-size:13px; color:var(--album-ink); }.album-field>span { color:var(--album-muted); font-size:12px; }.album-field--wide { grid-column:1/-1; }.album-field input,.album-field textarea,.album-field select,.album-caption-field input { width:100%; box-sizing:border-box; padding:10px 12px; border:1px solid var(--album-line); border-radius:7px; font:inherit; line-height:1.6; color:var(--album-ink); background:var(--album-bg); }.album-field textarea { resize:vertical; }.album-publish { display:flex; align-items:center; gap:8px; margin:22px 0 8px; font-size:14px; }.album-field-hint { color:var(--album-muted); font-size:12px; margin:8px 0; }.album-edit-section-title { display:flex; align-items:center; justify-content:space-between; gap:20px; }.album-edit-section-title h2 { margin-bottom:7px; }.album-edit-section-title p { color:var(--album-muted); font-size:12px; margin:0; }.album-edit-section-title h2>span { font-size:13px; color:var(--album-muted); }.album-upload-label { position:relative; overflow:hidden; flex-shrink:0; }.album-upload-label input { position:absolute; opacity:0; inset:0; width:100%; cursor:pointer; } +.album-edit-photos { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:18px; margin:24px 0 0; padding:0; list-style:none; }.album-edit-photo { min-width:0; list-style:none; margin:0; padding:0; border:1px solid var(--album-line); border-radius:9px; overflow:hidden; }.album-edit-photo.is-cover { border-color:#2e80b6; box-shadow:0 0 0 1px #2e80b6; }.album-edit-photo.is-dragging { opacity:.4; }.album-edit-photo-image { position:relative; aspect-ratio:4/3; background:var(--album-soft); }.album-edit-photo-image>img { width:100%; height:100%; object-fit:cover; }.album-drag-handle { position:absolute; left:8px; top:8px; border:0; border-radius:4px; font-size:24px; background:#fffe; color:#203a53; width:34px; height:34px; cursor:grab; }.album-cover-choice { position:absolute; right:8px; top:8px; display:flex; gap:4px; align-items:center; background:#fffffff0; color:#183149; font-size:11px; padding:7px; border-radius:5px; }.album-caption-field { display:block; padding:12px; font-size:11px; color:var(--album-muted); }.album-caption-field input { display:block; margin-top:6px; padding:7px; font-size:12px; }.album-photo-actions { display:flex; justify-content:space-between; gap:2px; padding:0 8px 10px; }.album-photo-actions button { border:0; background:none; color:var(--album-blue); font-size:11px; padding:7px 3px; cursor:pointer; }.album-photo-actions button:disabled { color:var(--album-muted); opacity:.4; cursor:default; }.album-photo-actions button:last-child { color:#a54a43; }.album-edit-empty { text-align:center; padding:30px 0 10px; color:var(--album-muted); font-size:14px; }.album-upload-status { border:1px solid var(--album-line); border-radius:8px; padding:15px; margin-top:20px; font-size:12px; }.album-upload-status progress { display:block; width:100%; margin-bottom:8px; accent-color:#246897; }.album-upload-status ul { margin:8px 0 0; color:#b34237; }.album-editor-footer { display:flex; justify-content:flex-end; gap:12px; padding:20px 28px; background:var(--album-soft); }.album-create-note { padding:20px 28px; color:var(--album-muted); font-size:13px; }.album-delete-form { text-align:right; margin-top:18px; }.album-delete-form button { border:0; color:#a54a43; background:none; font-size:12px; cursor:pointer; padding:10px; } +.album-source-banner { display:flex; justify-content:space-between; flex-wrap:wrap; gap:8px; background:#edf5fc; border:1px solid #d3e4f2; border-radius:8px; padding:12px 16px; margin:20px 0; font-size:13px; color:#3d6685; }.album-source-banner a { color:#21618e; } +.album-sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; } +@media(max-width:1000px) { .album-grid,.album-photo-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }.album-hero-side { flex-direction:column; align-items:flex-end; gap:16px; }.album-search { order:0; }.album-edit-photos { grid-template-columns:repeat(2,minmax(0,1fr)); } } +@media(max-width:600px) { .album-hero { align-items:flex-start; padding-top:15px; gap:16px; }.album-app h1 { font-size:28px; }.album-lead { font-size:12px; max-width:180px; }.album-totals { gap:15px; font-size:10px; }.album-totals strong { font-size:23px; }.album-hero-side .album-button { padding:8px 10px; font-size:11px; }.album-filters { gap:14px; }.album-search { width:100%; }.album-search input { flex:1; min-width:0; }.album-years { gap:3px; }.album-years a { padding:7px 9px; font-size:12px; }.album-grid { gap:13px; }.album-card-body { padding:12px; }.album-card h3 { font-size:13px; min-height:63px; -webkit-line-clamp:3; }.album-card-date { font-size:10px; }.album-card-open { font-size:11px; margin-top:12px; padding-top:10px; }.album-photo-badge { right:7px; bottom:7px; padding:4px 6px; font-size:10px; }.album-year-group>h2 { font-size:22px; }.album-detail-header { flex-direction:column; gap:15px; }.album-detail-header h1 { font-size:24px; }.album-photo-grid { gap:12px; }.album-description { padding:16px; }.album-viewer { width:100vw; max-width:100vw; border-radius:0; }.album-viewer-bar { padding:8px 12px; }.album-viewer-stage>button { width:36px; }.album-viewer-previous { left:4px; }.album-viewer-next { right:4px; }.album-edit-section { padding:20px 16px; }.album-edit-fields { gap:16px; }.album-edit-section-title { align-items:flex-start; flex-direction:column; gap:14px; }.album-edit-photos { gap:12px; }.album-photo-actions { flex-wrap:wrap; }.album-editor-footer { padding:18px 16px; }.album-breadcrumb { margin-top:5px; } } +@media(prefers-reduced-motion:reduce) { .album-card { transition:none; }.album-card:hover { transform:none; } } + +.album-app .album-button { line-height:1.4; white-space:nowrap; vertical-align:middle; } +.album-app .album-button--primary,.album-app .album-button--primary:visited { color:#fff; background:#246897; border-color:#246897; } +.album-app .album-button--primary:hover,.album-app .album-button--primary:focus-visible { color:#fff; background:#1a547d; border-color:#1a547d; } +.album-app .album-create-button { min-width:124px; min-height:44px; font-size:14px; font-weight:500; flex-shrink:0; gap:8px; } +.album-create-icon { display:block; font-size:20px; font-weight:400; line-height:1; } +@media(max-width:600px) { .album-app .album-create-button { min-width:104px; font-size:12px; min-height:42px; padding:9px 12px; } } + +.album-card-open { align-items:center; } +.album-award { display:inline-flex; align-items:center; gap:5px; font-size:12px; line-height:1.4; font-weight:500; white-space:nowrap; flex-shrink:0; } +.album-award svg { display:block; width:16px; height:16px; flex-shrink:0; } +.album-award--gold { color:#976a12; }.album-award--silver { color:#667385; }.album-award--bronze { color:#9b5c31; } +.theme--dark .album-award--gold { color:#f0c66b; }.theme--dark .album-award--silver { color:#c6d2e1; }.theme--dark .album-award--bronze { color:#e6ad85; } +.album-detail-top { display:flex; align-items:center; justify-content:space-between; gap:20px; min-height:42px; margin:0 0 20px; } +.album-detail-top .album-breadcrumb { margin:0; min-width:0; } +.album-detail-top>.album-button { flex-shrink:0; } +.album-detail-heading { width:100%; min-width:0; } +.album-title-row { display:flex; align-items:center; justify-content:space-between; gap:24px; } +.album-title-row h1 { flex:1; min-width:0; max-width:none; } +.album-title-row .album-award { margin-left:auto; font-size:16px; gap:7px; } +.album-title-row .album-award svg { width:20px; height:20px; } +@media(max-width:600px) { .album-edit-fields { grid-template-columns:1fr; }.album-detail-top { gap:12px; }.album-title-row { align-items:flex-start; gap:12px; }.album-title-row .album-award { font-size:14px; margin-top:4px; }.album-title-row .album-award svg { width:18px; height:18px; } } diff --git a/packages/contest-album/frontend/album.page.ts b/packages/contest-album/frontend/album.page.ts new file mode 100644 index 0000000000..8772ee2029 --- /dev/null +++ b/packages/contest-album/frontend/album.page.ts @@ -0,0 +1,228 @@ +import { addPage, ConfirmDialog, i18n, NamedPage, tpl } from '@hydrooj/ui-default'; + +function viewer() { + const dialog = document.querySelector('[data-album-viewer]'); + const buttons = [...document.querySelectorAll('[data-album-photo]')]; + if (!dialog || !buttons.length) return; + const image = dialog.querySelector('[data-viewer-image]'); + const caption = dialog.querySelector('[data-viewer-caption]'); + const counter = dialog.querySelector('[data-viewer-count]'); + const original = dialog.querySelector('[data-viewer-original]'); + let current = 0; + let touchX: number | undefined; + const show = (index: number) => { + current = (index + buttons.length) % buttons.length; + const photo = buttons[current]; + image.src = photo.dataset.albumPreview; + image.alt = photo.dataset.caption || `第 ${current + 1} 张照片`; + caption.textContent = photo.dataset.caption || ''; + counter.textContent = `${current + 1} / ${buttons.length}`; + original.href = photo.dataset.original; + if (!dialog.open) dialog.showModal(); + document.body.classList.add('album-viewer-open'); + }; + for (const [index, button] of buttons.entries()) { + button.addEventListener('click', (event) => { + if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return; + event.preventDefault(); + show(index); + }); + } + dialog.querySelector('[data-viewer-close]').addEventListener('click', () => dialog.close()); + dialog.querySelector('[data-viewer-previous]').addEventListener('click', () => show(current - 1)); + dialog.querySelector('[data-viewer-next]').addEventListener('click', () => show(current + 1)); + dialog.addEventListener('keydown', (event) => { + if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { + event.preventDefault(); + event.stopPropagation(); + show(current + (event.key === 'ArrowLeft' ? -1 : 1)); + } + }); + image.addEventListener('touchstart', (event) => { touchX = event.changedTouches[0]?.clientX; }, { passive: true }); + image.addEventListener('touchend', (event) => { + const distance = (event.changedTouches[0]?.clientX || 0) - (touchX || 0); + if (touchX !== undefined && Math.abs(distance) > 60) show(current + (distance < 0 ? 1 : -1)); + touchX = undefined; + }, { passive: true }); + dialog.addEventListener('click', (event) => { if (event.target === dialog) dialog.close(); }); + dialog.addEventListener('close', () => { + document.body.classList.remove('album-viewer-open'); + image.removeAttribute('src'); + }); +} + +function editor() { + const form = document.querySelector('[data-album-editor]'); + if (!form) return; + const list = form.querySelector('[data-edit-photos]'); + const cover = form.elements.namedItem('cover') as HTMLInputElement; + const hidden = form.elements.namedItem('photos') as HTMLInputElement; + const upload = form.querySelector('[data-album-upload]'); + const save = form.querySelector('[data-album-save]'); + let busy = false; + let dirty = false; + const items = () => list ? [...list.querySelectorAll('[data-photo-id]')] : []; + const update = () => { + const rows = items(); + if (!rows.some((row) => row.dataset.photoId === cover.value)) cover.value = rows[0]?.dataset.photoId || ''; + hidden.value = JSON.stringify(rows.map((row, index) => { + const id = row.dataset.photoId; + (row.querySelector('input[type=radio]') as HTMLInputElement).checked = id === cover.value; + (row.querySelector('[data-photo-action=up]') as HTMLButtonElement).disabled = index === 0; + (row.querySelector('[data-photo-action=down]') as HTMLButtonElement).disabled = index === rows.length - 1; + row.classList.toggle('is-cover', id === cover.value); + return { id, caption: (row.querySelector('[data-photo-caption]') as HTMLInputElement).value }; + })); + const count = document.querySelector('[data-edit-count]'); + if (count) count.textContent = String(rows.length); + const empty = document.querySelector('[data-edit-empty]'); + if (empty) empty.hidden = rows.length > 0; + }; + form.addEventListener('input', () => { dirty = true; }); + form.addEventListener('change', (event) => { + const target = event.target as HTMLInputElement; + if (target.name === 'coverChoice') { + cover.value = target.value; + update(); + } + }); + form.addEventListener('submit', (event) => { + if (busy) event.preventDefault(); + else { + update(); + dirty = false; + } + }); + window.addEventListener('beforeunload', (event) => { + if (dirty || busy) { + event.preventDefault(); + event.returnValue = ''; + } + }); + const deleteForm = document.querySelector('[data-album-delete]'); + if (deleteForm) { + const button = deleteForm.querySelector('button'); + button.type = 'button'; + let confirming = false; + const remove = async (event: Event) => { + event.preventDefault(); + if (busy || confirming) return; + confirming = true; + try { + const action = await new ConfirmDialog({ $body: tpl.typoMsg('确定删除这本相册吗?'), canCancel: true }).open(); + if (action !== 'yes') return; + dirty = false; + HTMLFormElement.prototype.submit.call(deleteForm); + } finally { + confirming = false; + } + }; + button.addEventListener('click', remove); + deleteForm.addEventListener('submit', remove); + } + if (!list) return; + list.addEventListener('click', (event) => { + const button = (event.target as HTMLElement).closest('[data-photo-action]'); + if (!button) return; + const row = button.closest('[data-photo-id]'); + if (button.dataset.photoAction === 'remove') row.remove(); + if (button.dataset.photoAction === 'up' && row.previousElementSibling) list.insertBefore(row, row.previousElementSibling); + if (button.dataset.photoAction === 'down' && row.nextElementSibling) list.insertBefore(row.nextElementSibling, row); + dirty = true; + update(); + }); + let dragging: HTMLElement; + list.addEventListener('dragstart', (event) => { + const handle = (event.target as HTMLElement).closest('.album-drag-handle'); + if (!handle) { + event.preventDefault(); + return; + } + dragging = handle.closest('[data-photo-id]'); + event.dataTransfer.setData('text/plain', dragging.dataset.photoId); + event.dataTransfer.effectAllowed = 'move'; + dragging.classList.add('is-dragging'); + }); + list.addEventListener('dragover', (event) => { + if (dragging) { + event.preventDefault(); + event.dataTransfer.dropEffect = 'move'; + } + }); + list.addEventListener('drop', (event) => { + if (!dragging) return; + event.preventDefault(); + const row = (event.target as HTMLElement).closest('[data-photo-id]'); + if (row && row !== dragging) { + const box = row.getBoundingClientRect(); + list.insertBefore(dragging, event.clientX > box.left + box.width / 2 ? row.nextSibling : row); + dirty = true; + } + update(); + }); + list.addEventListener('dragend', () => { + dragging?.classList.remove('is-dragging'); + dragging = undefined; + }); + upload.addEventListener('change', async () => { + const files = [...upload.files]; + if (!files.length) return; + busy = true; + save.disabled = true; + upload.disabled = true; + const status = document.querySelector('[data-upload-status]'); + const progress = document.querySelector('[data-upload-progress]'); + const message = document.querySelector('[data-upload-message]'); + const errors = document.querySelector('[data-upload-errors]'); + status.hidden = false; + progress.max = files.length; + progress.value = 0; + errors.replaceChildren(); + let successful = 0; + try { + for (const [index, file] of files.entries()) { + message.textContent = `正在上传 ${index + 1} / ${files.length}:${file.name}`; + try { + if (file.size > 20 * 1024 * 1024) throw new Error('图片超过 20 MB'); + const data = new FormData(); + data.set('operation', 'upload'); + data.set('revision', (form.elements.namedItem('revision') as HTMLInputElement).value); + data.set('file', file); + const response = await fetch(form.dataset.uploadUrl, { method: 'POST', body: data, headers: { Accept: 'application/json' } }); + const payload = await response.json(); + if (!response.ok || !payload.photo) { + const error = payload.error; + throw new Error(error?.message ? i18n(error.message, ...(error.params || [])) : '上传失败,请重试'); + } + const template = document.querySelector('[data-edit-photo-template]'); + const row = template.content.firstElementChild.cloneNode(true) as HTMLElement; + row.dataset.photoId = payload.photo.id; + (row.querySelector('img') as HTMLImageElement).src = payload.photo.thumb; + (row.querySelector('input[type=radio]') as HTMLInputElement).value = payload.photo.id; + list.append(row); + document.querySelectorAll('input[name=revision]').forEach((input) => { input.value = payload.revision; }); + successful++; + update(); + } catch (error) { + const item = document.createElement('li'); + item.textContent = `${file.name}:${error.message}`; + errors.append(item); + } + progress.value = index + 1; + } + } finally { + const failures = files.length > successful ? `,${files.length - successful} 张失败` : ''; + message.textContent = `已添加 ${successful} 张照片${failures}。可继续设置封面、排序和照片说明。`; + busy = false; + save.disabled = false; + upload.disabled = false; + upload.value = ''; + } + }); + update(); +} + +addPage(new NamedPage(['album_main', 'album_detail', 'album_edit', 'album_create'], () => { + viewer(); + editor(); +})); diff --git a/packages/contest-album/index.ts b/packages/contest-album/index.ts new file mode 100644 index 0000000000..74a087e961 --- /dev/null +++ b/packages/contest-album/index.ts @@ -0,0 +1,287 @@ +/* eslint-disable no-await-in-loop */ +import { createHash } from 'crypto'; +import { readFileSync } from 'fs'; +import { readFile } from 'fs/promises'; +import { join } from 'path'; +import type { ImagePreviewService } from '@hgnuoj/image-preview'; +import { userFile, version } from '@hgnuoj/image-preview/images'; +import type { Collection } from 'mongodb'; +import sharp from 'sharp'; +import { + Context, db, FileInfo, Handler, nanoid, NotFoundError, ObjectId, PERM, PRIV, + StorageModel, SystemModel, UserModel, ValidationError, +} from 'hydrooj'; +import { Album, AWARD_LABELS, escapeSearch, fields, orderedPhotos, paginateYears, Photo } from './model'; + +declare module 'hydrooj' { + interface Collections { + 'hgnu.album': Album; + } +} + +export const albums = db.collection('hgnu.album'); +const fileAccounts = UserModel.coll as unknown as Collection<{ _id: number, _files?: FileInfo[] }>; +const stylesheet = readFileSync(join(__dirname, 'frontend/album.css'), 'utf8'); +const styleVersion = createHash('sha256').update(stylesheet).digest('hex').slice(0, 16); + +class AlbumStylesheetHandler extends Handler { + noCheckPermView = true; + + get() { + this.response.type = 'text/css'; + this.response.addHeader('Cache-Control', 'public, max-age=31536000, immutable'); + this.response.addHeader('ETag', `"${styleVersion}"`); + this.response.body = stylesheet; + } +} + +async function images(ctx: Context, photos: Photo[]) { + const paths = [...new Set(photos.map((photo) => userFile(photo.src)).filter(Boolean))]; + const rows = await StorageModel.coll.find({ path: { $in: paths }, autoDelete: null }).toArray(); + const sources = new Map(rows.map((row) => [row.path, row])); + const service = ctx.get('image-preview') as ImagePreviewService; + const result = []; + for (const photo of photos) { + const source = sources.get(userFile(photo.src)); + const info = source && service ? await service.previews.dimensions(source) : null; + const url = (width: number) => info ? `${photo.src}/preview/${width}/${version(source)}.webp` : photo.src; + result.push({ + ...photo, thumb: url(480), preview: url(1600), + original: `${photo.src}?noDisposition=true`, width: info?.width || 4, height: info?.height || 3, + }); + } + return result; +} + +function validate(fn: () => T): T { + try { + return fn(); + } catch (e) { + throw new ValidationError(e.message); + } +} + +class AlbumBaseHandler extends Handler { + album?: Album; + + renderAlbum(template: string, body: Record) { + this.response.template = template; + this.response.body = { ...body, awardLabels: AWARD_LABELS, albumStylesheet: this.url('album_style', { version: styleVersion }) }; + } + + async prepare() { + const domainId = this.domain._id; + const aid = this.request.params.aid; + // Hydro merges request fields into args before loading domain permissions. + if (this.args.domainId !== domainId || (this.args.aid && this.args.aid !== aid)) { + throw new ValidationError('相册地址与请求参数不一致'); + } + this.checkPerm(PERM.PERM_VIEW_DISCUSSION); + if (!aid) return; + if (!ObjectId.isValid(aid)) throw new NotFoundError('相册'); + this.album = await albums.findOne({ _id: new ObjectId(aid), domainId, deletedAt: null }); + if (!this.album || (!this.album.published && !this.canEdit())) throw new NotFoundError('相册'); + } + + canEdit() { + return this.user.hasPriv(PRIV.PRIV_USER_PROFILE) && (this.user.hasPerm(PERM.PERM_EDIT_DISCUSSION) + || (this.album?.owner === this.user._id && this.user.hasPerm(PERM.PERM_EDIT_DISCUSSION_SELF))); + } + + checkEdit() { + this.checkPriv(PRIV.PRIV_USER_PROFILE); + if (!this.canEdit()) this.checkPerm(PERM.PERM_EDIT_DISCUSSION); + } + + canDelete() { + return this.canEdit() && (this.user.hasPerm(PERM.PERM_DELETE_DISCUSSION) + || (this.album.owner === this.user._id && this.user.hasPerm(PERM.PERM_DELETE_DISCUSSION_SELF))); + } + + revision(value: any) { + if (!Number.isSafeInteger(+value) || +value !== this.album.revision) throw new ValidationError('相册已被更新,请刷新页面后再保存'); + return +value; + } + + async replace(revision: number, value: Partial) { + const result = await albums.findOneAndUpdate( + { _id: this.album._id, domainId: this.album.domainId, revision, deletedAt: null }, + { $set: { ...value, updatedAt: new Date() }, $inc: { revision: 1 } }, + { returnDocument: 'after' }, + ); + if (!result) throw new ValidationError('相册已被更新,请刷新页面后再保存'); + return result; + } +} + +class AlbumMainHandler extends AlbumBaseHandler { + async get({ q = '', year = '', page = 1 }) { + const domainId = this.domain._id; + const search = String(q).trim().slice(0, 100); + const selectedYear = String(year); + if (selectedYear && !/^(?:0|19\d\d|20\d\d|2100)$/.test(selectedYear)) throw new ValidationError('年份'); + const requestedPage = Math.max(1, Math.min(10000, Number(page) || 1)); + if (!Number.isInteger(requestedPage)) throw new ValidationError('页码'); + const visible = this.user.hasPerm(PERM.PERM_EDIT_DISCUSSION) ? {} : this.user.hasPriv(PRIV.PRIV_USER_PROFILE) + ? { $or: [{ published: true }, { owner: this.user._id }] } : { published: true }; + const scope = { domainId, deletedAt: null, ...visible }; + const filter = { + ...scope, ...selectedYear ? { year: +selectedYear } : {}, + ...search ? { title: new RegExp(escapeSearch(search), 'i') } : {}, + }; + const [stats, yearCounts, matchingYears] = await Promise.all([ + albums.aggregate([{ $match: scope }, { $group: { _id: null, count: { $sum: 1 }, photos: { $sum: { $size: '$photos' } } } }]).toArray(), + albums.aggregate([{ $match: scope }, { $group: { _id: '$year', count: { $sum: 1 } } }, { $sort: { _id: -1 } }]).toArray(), + albums.aggregate([{ $match: filter }, { $group: { _id: '$year', count: { $sum: 1 } } }, { $sort: { _id: -1 } }]).toArray(), + ]); + const pages = paginateYears(matchingYears.map((row) => ({ year: row._id, count: row.count }))); + const currentPage = Math.min(requestedPage, Math.max(1, pages.length)); + const total = matchingYears.reduce((sum, row) => sum + row.count, 0); + const rows = await albums.find({ ...filter, year: { $in: pages[currentPage - 1] || [] } }) + .sort({ year: -1, date: -1, createdAt: -1, _id: -1 }).toArray(); + const coverPhotos = rows.map((album) => album.photos.find((photo) => photo.id === album.cover) || album.photos[0]); + const covers = await images(this.ctx, coverPhotos.filter(Boolean)); + const groups: { year: number, items: any[] }[] = []; + for (const album of rows) { + if (!groups.length || groups.at(-1).year !== album.year) groups.push({ year: album.year, items: [] }); + const cover = album.photos.find((photo) => photo.id === album.cover) || album.photos[0]; + groups.at(-1).items.push({ ...album, coverImage: covers.find((photo) => photo.id === cover?.id) }); + } + const pageUrl = (p: number, y = selectedYear) => `${this.url('album_main')}?${new URLSearchParams({ q: search, year: y, page: String(p) })}`; + this.renderAlbum('album_main.html', { + groups, years: yearCounts.map((row) => ({ year: row._id, count: row.count, url: pageUrl(1, String(row._id)) })), + stats: stats[0] || { count: 0, photos: 0 }, total, q: search, year: selectedYear, page: currentPage, + pageCount: pages.length, previous: pageUrl(currentPage - 1), next: pageUrl(currentPage + 1), allYears: pageUrl(1, ''), + canCreate: this.user.hasPriv(PRIV.PRIV_USER_PROFILE) && this.user.hasPerm(PERM.PERM_CREATE_DISCUSSION), + }); + } +} + +class AlbumDetailHandler extends AlbumBaseHandler { + async get() { + const photos = await images(this.ctx, this.album.photos); + this.renderAlbum('album_detail.html', { album: this.album, photos, canEdit: this.canEdit() }); + } +} + +class AlbumCreateHandler extends AlbumBaseHandler { + async get() { + this.checkPriv(PRIV.PRIV_USER_PROFILE); + this.checkPerm(PERM.PERM_CREATE_DISCUSSION); + this.renderAlbum('album_edit.html', { + album: { title: '', year: new Date().getFullYear(), date: '', description: '', published: false, photos: [], revision: 0 }, + photos: [], isNew: true, + }); + } + + async post(args) { + this.checkPriv(PRIV.PRIV_USER_PROFILE); + this.checkPerm(PERM.PERM_CREATE_DISCUSSION); + await this.limitRate('album_create', 3600, 30); + const info = validate(() => fields(args)); + const now = new Date(); + const _id = new ObjectId(); + await albums.insertOne({ + _id, domainId: this.domain._id, owner: this.user._id, ...info, + photos: [], cover: '', createdAt: now, updatedAt: now, revision: 0, + }); + this.response.redirect = this.url('album_edit', { aid: _id }); + this.response.body = { id: _id.toHexString() }; + } +} + +class AlbumEditHandler extends AlbumBaseHandler { + async get() { + this.checkEdit(); + this.renderAlbum('album_edit.html', { + album: this.album, photos: await images(this.ctx, this.album.photos), isNew: false, canDelete: this.canDelete(), + }); + } + + async post(args) { + this.checkEdit(); + if (args.operation) return; + const revision = this.revision(args.revision); + const info = validate(() => fields(args)); + const photos = validate(() => orderedPhotos(JSON.parse(args.photos || '[]'), this.album.photos)); + const cover = photos.some((photo) => photo.id === args.cover) ? args.cover : photos[0]?.id || ''; + await this.replace(revision, { ...info, photos, cover }); + this.response.redirect = this.url('album_detail', { aid: this.album._id }); + } + + async postUpload(args) { + this.checkEdit(); + this.checkPriv(PRIV.PRIV_CREATE_FILE); + await this.limitRate('album_upload', 60, 60); + const revision = this.revision(args.revision); + if (this.album.photos.length >= 500) throw new ValidationError('一个相册最多 500 张照片'); + const file = this.request.files?.file; + if (!file || Array.isArray(file) || file.size > 20 * 1024 * 1024 || file.size === 0) throw new ValidationError('请选择不超过 20 MB 的图片'); + const buffer = await readFile(file.filepath); + const info = await sharp(buffer, { limitInputPixels: 80 * 1000 * 1000 }).metadata().catch(() => null); + if (!info || !['jpeg', 'png', 'webp'].includes(info.format) || (info.pages || 1) > 1) { + throw new ValidationError('支持 JPG、PNG 和静态 WebP 图片'); + } + const owner = await UserModel.coll.findOne({ _id: this.user._id }); + const files = owner._files || []; + if (!this.user.hasPriv(PRIV.PRIV_UNLIMITED_QUOTA) && (files.length >= SystemModel.get('limit.user_files') + || files.reduce((sum, row) => sum + (row.size || 0), 0) + file.size > SystemModel.get('limit.user_files_size'))) { + throw new ValidationError('文件空间或数量已达到上限'); + } + const filename = `album-${this.album._id}-${nanoid(12)}.${info.format === 'jpeg' ? 'jpg' : info.format}`; + const target = `user/${this.user._id}/${filename}`; + const photo = { id: nanoid(16), src: `/file/${this.user._id}/${filename}`, caption: '' }; + try { + await StorageModel.put(target, buffer, this.user._id); + const meta = await StorageModel.getMeta(target); + await fileAccounts.updateOne({ _id: this.user._id }, { + $push: { _files: { _id: filename, name: filename, size: meta.size, etag: meta.etag, lastModified: meta.lastModified } }, + }); + UserModel._deleteUserCache(owner); + const view = (await images(this.ctx, [photo]))[0]; + const result = await albums.findOneAndUpdate( + { _id: this.album._id, domainId: this.album.domainId, revision, deletedAt: null }, + { $push: { photos: photo }, $set: { updatedAt: new Date(), ...this.album.cover ? {} : { cover: photo.id } }, $inc: { revision: 1 } }, + { returnDocument: 'after' }, + ); + if (!result) throw new ValidationError('相册已被更新,请刷新后重试上传'); + this.response.body = { photo: view, revision: result.revision }; + } catch (e) { + await StorageModel.del([target], this.user._id); + await fileAccounts.updateOne({ _id: this.user._id }, { $pull: { _files: { _id: filename } } }); + UserModel._deleteUserCache(owner); + throw e; + } + } + + async postDelete(args) { + this.checkEdit(); + const revision = this.revision(args.revision); + if (!this.user.hasPerm(PERM.PERM_DELETE_DISCUSSION)) { + if (this.album.owner !== this.user._id) this.checkPerm(PERM.PERM_DELETE_DISCUSSION); + this.checkPerm(PERM.PERM_DELETE_DISCUSSION_SELF); + } + await this.replace(revision, { deletedAt: new Date() }); + this.response.redirect = this.url('album_main'); + } +} + +export const inject = ['db', 'storage']; +export async function apply(ctx: Context) { + await albums.createIndex({ domainId: 1, year: -1, date: -1, createdAt: -1 }); + await albums.createIndex({ domainId: 1, 'source.discussion': 1, 'source.section': 1 }, { + unique: true, partialFilterExpression: { 'source.discussion': { $exists: true } }, + }); + ctx.Route('album_main', '/albums', AlbumMainHandler); + ctx.Route('album_style', '/album-assets/:version/album.css', AlbumStylesheetHandler); + ctx.Route('album_create', '/albums/new', AlbumCreateHandler); + ctx.Route('album_edit', '/albums/:aid/edit', AlbumEditHandler); + ctx.Route('album_detail', '/albums/:aid', AlbumDetailHandler); + ctx.injectUI('Nav', 'album_main', { prefix: 'album', before: 'courses' }, PERM.PERM_VIEW_DISCUSSION); + ctx.on('handler/after/DiscussionDetail', async (handler) => { + if (await albums.findOne({ domainId: handler.domain._id, 'source.discussion': handler.ddoc.docId, published: true, deletedAt: null })) { + handler.response.body.albumCollection = handler.url('album_main'); + handler.response.body.albumStylesheet = handler.url('album_style', { version: styleVersion }); + } + }); +} diff --git a/packages/contest-album/locales/en.yaml b/packages/contest-album/locales/en.yaml new file mode 100644 index 0000000000..2ae3f29b7d --- /dev/null +++ b/packages/contest-album/locales/en.yaml @@ -0,0 +1,3 @@ +album_main: Albums +album_detail: Album +album_edit: Edit album diff --git a/packages/contest-album/locales/zh.yaml b/packages/contest-album/locales/zh.yaml new file mode 100644 index 0000000000..1903d8bb91 --- /dev/null +++ b/packages/contest-album/locales/zh.yaml @@ -0,0 +1,3 @@ +album_main: 比赛相册 +album_detail: 比赛相册 +album_edit: 编辑相册 diff --git a/packages/contest-album/model.ts b/packages/contest-album/model.ts new file mode 100644 index 0000000000..4e80bf2b43 --- /dev/null +++ b/packages/contest-album/model.ts @@ -0,0 +1,79 @@ +import { ObjectId } from 'mongodb'; + +export const AWARD_LABELS = { gold: '金牌', silver: '银牌', bronze: '铜牌' } as const; +export type Award = '' | keyof typeof AWARD_LABELS; + +export interface Photo { + id: string; + src: string; + caption: string; +} + +export interface Album { + _id: ObjectId; + domainId: string; + owner: number; + title: string; + year: number; + date: string; + description: string; + award?: Award; + published: boolean; + cover: string; + photos: Photo[]; + revision: number; + createdAt: Date; + updatedAt: Date; + deletedAt?: Date; + source?: { discussion: ObjectId, section: number, fragment: string }; +} + +export function fields(input: Record) { + const title = String(input.title || '').trim(); + if (!title || title.length > 140) throw new Error('比赛名称需为 1–140 个字符'); + const year = Number(input.year || 0); + if (!Number.isInteger(year) || (year !== 0 && (year < 1900 || year > 2100))) throw new Error('年份需在 1900–2100 之间'); + const date = String(input.date || '').trim(); + if (date && (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !Number.isFinite(new Date(date).getTime()) + || new Date(date).toISOString().slice(0, 10) !== date)) throw new Error('请填写有效的比赛日期'); + if (date && Number(date.slice(0, 4)) !== year) throw new Error('比赛日期与归档年份不一致'); + const description = String(input.description || '').trim(); + if (description.length > 20000) throw new Error('比赛简介最多 20000 个字符'); + const award = String(input.award || '') as Award; + if (award && !Object.keys(AWARD_LABELS).includes(award)) throw new Error('请选择金牌、银牌、铜牌或不显示'); + return { title, year, date, description, award, published: [true, 'true', 'on', '1'].includes(input.published) }; +} + +export function orderedPhotos(input: unknown, current: Photo[]) { + if (!Array.isArray(input) || input.length > 500) throw new Error('一个相册最多 500 张照片'); + const byId = new Map(current.map((photo) => [photo.id, photo])); + const seen = new Set(); + return input.map((item) => { + if (!item || typeof item.id !== 'string' || !byId.has(item.id) || seen.has(item.id)) throw new Error('照片列表无效,请刷新页面重试'); + seen.add(item.id); + const caption = String(item.caption || '').trim(); + if (caption.length > 200) throw new Error('单张照片的说明最多 200 个字符'); + return { ...byId.get(item.id), caption }; + }); +} + +export function escapeSearch(value: string) { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +export function paginateYears(years: { year: number, count: number }[], target = 12) { + const pages: number[][] = []; + let page: number[] = []; + let count = 0; + for (const item of years) { + if (page.length && count + item.count > target) { + pages.push(page); + page = []; + count = 0; + } + page.push(item.year); + count += item.count; + } + if (page.length) pages.push(page); + return pages; +} diff --git a/packages/contest-album/package.json b/packages/contest-album/package.json new file mode 100644 index 0000000000..380785e121 --- /dev/null +++ b/packages/contest-album/package.json @@ -0,0 +1,13 @@ +{ + "name": "@hgnuoj/contest-album", + "version": "1.0.0", + "private": true, + "main": "index.ts", + "license": "AGPL-3.0-only", + "dependencies": { "sharp": "0.34.5" }, + "peerDependencies": { + "hydrooj": "workspace:^", + "@hydrooj/ui-default": "workspace:^", + "@hgnuoj/image-preview": "workspace:^" + } +} diff --git a/packages/contest-album/templates/album_award.html b/packages/contest-album/templates/album_award.html new file mode 100644 index 0000000000..1ca84569f0 --- /dev/null +++ b/packages/contest-album/templates/album_award.html @@ -0,0 +1,5 @@ +{% macro badge(value, labels) -%} +{% if labels[value] %} +{{ labels[value] }} +{% endif %} +{%- endmacro %} diff --git a/packages/contest-album/templates/album_detail.html b/packages/contest-album/templates/album_detail.html new file mode 100644 index 0000000000..3fc0f8fc7a --- /dev/null +++ b/packages/contest-album/templates/album_detail.html @@ -0,0 +1,14 @@ +{% extends "album_layout.html" %} +{% import "album_award.html" as awards %} +{% block content %} +
+
{% if canEdit %}编辑相册{% endif %}
+

{{ album.date or (album.year.toString() + ' 年' if album.year else '赛场记忆') }} · {{ photos.length }} 张照片{% if not album.published %} · 草稿{% endif %}

{{ album.title }}

{{ awards.badge(album.award, awardLabels) }}
+ {% if album.description %}
{{ album.description|markdownImages|safe }}
{% endif %} + {% if photos.length %}
+ {% for photo in photos %}
{{ photo.caption or ('第 ' + loop.index.toString() + ' 张照片') }}{% if photo.caption %}
{{ photo.caption }}
{% endif %}
{% endfor %} +
{% else %}

相册已准备好

{% if canEdit %}进入编辑页,为这场比赛添加第一张照片。{% else %}照片正在整理中。{% endif %}

{% if canEdit %}添加照片{% endif %}
{% endif %} + {% if album.source %}{% endif %} +

+
+{% endblock %} diff --git a/packages/contest-album/templates/album_edit.html b/packages/contest-album/templates/album_edit.html new file mode 100644 index 0000000000..c8bb7ef2f6 --- /dev/null +++ b/packages/contest-album/templates/album_edit.html @@ -0,0 +1,18 @@ +{% extends "album_layout.html" %} +{% block content %} +
+ +

整理每一次相聚

{{ '新建比赛相册' if isNew else '编辑比赛相册' }}

+
+ +

比赛信息

取消公开后,仅作者和有编辑权限的管理员可以查看。

+ {% if not isNew %}

照片 {{ photos.length }}

拖动左上角手柄调整顺序,也可以用上移、下移按钮。选择一张作为封面。

支持 JPG、PNG、静态 WebP,每张最多 20 MB,每本相册最多 500 张。

+
    {% for photo in photos %}
  1. 照片预览
  2. {% endfor %}
+

还没有照片,点击“批量添加照片”开始整理。

+
{% else %}
先创建相册,下一步即可批量添加照片、挑选封面。
{% endif %} + +
+ {% if not isNew and canDelete %}
{% endif %} + +
+{% endblock %} diff --git a/packages/contest-album/templates/album_layout.html b/packages/contest-album/templates/album_layout.html new file mode 100644 index 0000000000..7ed937d2f6 --- /dev/null +++ b/packages/contest-album/templates/album_layout.html @@ -0,0 +1,5 @@ +{% extends "layout/basic.html" %} +{% block ogp %} +{{ super() }} + +{% endblock %} diff --git a/packages/contest-album/templates/album_main.html b/packages/contest-album/templates/album_main.html new file mode 100644 index 0000000000..d38e607ff3 --- /dev/null +++ b/packages/contest-album/templates/album_main.html @@ -0,0 +1,28 @@ +{% extends "album_layout.html" %} +{% import "album_award.html" as awards %} +{% block content %} +
+
+
+

HGNU · ACM

比赛相册

记录赛场、颁奖和同行的瞬间。

+
{{ stats.count }} 本相册{{ stats.photos }} 张照片
{% if canCreate %}新建相册{% endif %}
+
+
+ + +
+ {% if q %}

“{{ q }}” · 找到 {{ total }} 本相册

{% endif %} + {% for group in groups %} +

{{ group.year if group.year else '未注明年份' }}赛场记忆

+ {% else %}

还没有匹配的相册

换一个名称或年份试试。{% if canCreate %}也可以新建第一本比赛相册。{% endif %}

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