chore(release): 1.3.3 发布并退役旧联动

This commit is contained in:
LoveChengke committed 2026-10-17 03:06:46 +08:00
1 parent b7cdc7c9ea
commit c0ebf88138
184 files changed
+5450 -11705

No files matched your search

-4
View File
@@ -1,4 +0,0 @@
# .NET 构建产物(与仓库根的 .gitignore 分开:根 .gitignore 是 GBK 编码,apply_patch 读不了)
bin/
obj/
cipx/
@@ -1,45 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!--
ClassIsland 2.0 / 2.1.0.x 面向 net8.0;2.1.1 起改为 net10.0。
本插件按 net8.0 交付,因此 SDK 版本固定到最后一个 net8.0 的版本(2.1.0.1),
这样 ClassIsland 2.0.x 与 2.1.0.x 都能加载(apiVersion 见 manifest.yml)。
-->
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>12</LangVersion>
<RootNamespace>ClassHelper.ClassIslandPlugin</RootNamespace>
<AssemblyName>ClassHelper.ClassIslandPlugin</AssemblyName>
<ClassIslandPluginSdkVersion>2.1.0.1</ClassIslandPluginSdkVersion>
<!-- 插件由 ClassIsland 加载,不需要生成自带运行时(ExcludeAssets 见下) -->
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<!-- 设置页是 .axaml:需要让 Avalonia 的默认项把 **/*.axaml 收成 AvaloniaXaml 并编译 -->
<EnableDefaultItems>true</EnableDefaultItems>
<!-- 绑定走运行时解析:插件与主程序各自编译,编译期绑定会因看不到对方的类型而失败 -->
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
<!-- 运行时与原生资源由 ClassIsland 本体提供,插件只编译期依赖 -->
<PackageReference Include="ClassIsland.PluginSdk" Version="$(ClassIslandPluginSdkVersion)">
<ExcludeAssets>runtime;native</ExcludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<None Update="manifest.yml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="README.md">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="icon.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
@@ -1,10 +0,0 @@
{
"profiles": {
"ClassIsland 插件": {
"commandName": "Executable",
"executablePath": "$(ClassIsland_DebugBinaryFile)",
"commandLineArgs": "-epp $(TargetDir)",
"workingDirectory": "$(ClassIsland_DebugBinaryDirectory)"
}
}
}
-163
View File
@@ -1,163 +0,0 @@
# ClassHelper 联动插件
把 [ClassIsland](https://classisland.tech) 与 [ClassHelper](https://github.com/LoveChengke/ClassHelper) 连起来:
让 ClassHelper**读到教室真实的课表与上课状态**,也让老师的提醒**在教室的 ClassIsland 上弹出来**。
## 它能做什么
| 方向 | 说明 |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| ClassIsland → ClassHelper | 上报课表与节次时间、上报上课状态(当前科目 / 下一节 / 本节起止时间) |
| ClassHelper → ClassIsland | 老师在 Web 端下发提醒 → 教室的 ClassIsland 上**全屏弹出**(可语音朗读),播完回执、不重复弹 |
| ClassHelper → ClassIsland(可选) | 把 ClassHelper上排好的课表**镜像**回 ClassIsland(新建 `ClassHelper-<班级名>` 档案课表,不改动老师原有的课表) |
## 安装
1. 把插件放进 ClassIsland 的插件目录,二选一:
- 用打包好的 `ClassHelper.ClassIslandPlugin.cipx`:ClassIsland →「设置 → 插件 → 从文件安装」;
- 或直接把 `ClassHelper.ClassIslandPlugin/` 目录(含 `manifest.yml` 与 dll)丢进插件目录
(Windows 默认 `%APPDATA%\ClassIsland\Plugins`,便携版在安装目录下的 `Plugins`)。
2. 重启 ClassIsland,在「设置 → 插件」里确认「ClassHelper 联动」已启用。
3. 打开「设置 → ClassHelper 联动」,填入:
- **服务器地址**:ClassHelper后端地址,例如 `http://127.0.0.1:4000`;
- **设备令牌**:在 ClassHelper Web 端「ClassIsland 联动」页面为本班新建一台设备后复制(形如 `chci_...`,只显示一次)。
4. 点「立即上报」验证连接状态;状态卡片显示「已连接」即接入成功。
## 配置项(全部在「设置 → ClassHelper 联动」里)
| 配置项 | 说明 |
| ---------------------------- | -------------------------------------------------------------------------------------------------- |
| 服务器地址 | ClassHelper后端地址(含端口;末尾斜杠与多余的 `/api` 后缀都会被自动容错) |
| 设备令牌 | 由 Web 端「ClassIsland 联动」页生成;服务端只存 sha256,明文只在页面上出现一次 |
| 上报课表到 ClassHelper | 把 ClassIsland 里**已启用**的课表同步过去(合并写入:同星期同时间更新,不产生重复行) |
| 把班级课表镜像回 ClassIsland | 反方向同步,新建带前缀的档案课表;关闭后仍会照常上报「现在上什么课」 |
| 自动上报 | 启动 / 课程事件(上课、下课、放学、状态变化)/ 定时各上报一次;关闭后只能用「立即上报」手动触发 |
| 上报间隔(秒) | 定时上报间隔,最小 15 秒,教室机器建议 60 秒 |
| 接收 ClassHelper提醒 | **本机总闸**:关掉后本机忽略老师下发的提醒(提醒仍留在班级通知中心) |
| 语音朗读 | 是否允许本机朗读(老师下发时也勾了「语音朗读」才会念,两个条件都满足才出声) |
| 默认显示时长(秒) | 老师未指定时长时用这个值;单条提醒可以在 Web 端单独指定更长的时长 |
| 提醒轮询间隔(秒) | **老师按下发送 → 教室弹出之间的最大延迟**(插件不持有长连接,是轮询取回的),默认 10 秒、最小 5 秒 |
| 显示调试信息 | 展开设备标识、与服务端的时钟差、配置目录等,排查「为什么同步不上」时打开 |
设置保存在 `<插件配置目录>/Settings.json`(随 ClassIsland 档案备份走,升级插件不丢)。
改动即时生效 —— 改地址 / 令牌 / 间隔会立刻重建上报定时器,不需要重启 ClassIsland。
> **上课时段策略(与 ClassHelper 客户端同一套规则)**:
> 上课时段里,通知类提醒会**先暂存、下课后自动补弹**;**紧急提醒**与**叫人**属于「主动通知」,立刻弹。
> 暂存期间不回执,服务端会保留这条待提醒。
> **课间**:镜像回 ClassIsland 的课表会自动补上课间 —— **每两节之间**一段
> (上一节下课 → 下一节上课),**最后一节之后不补**(放学)。课间由插件按课目时间算出来,
> 不依赖 ClassHelper那边是否维护节次时间表,因此 ClassIsland 档案里一定有完整作息。
> **两个方向各自需要的开关**:
>
> - 服务端 → ClassIsland(镜像课表):插件「把班级课表镜像回 ClassIsland」**且** Web 端该设备「镜像课表」都打开;
> - ClassIsland → 服务端(上报课表):插件「上报课表到 ClassHelper」打开;
> 关着时是正常行为(日志会写「仅状态(本机「上报课表到 ClassHelper」开关已关闭)」),不是上报失败;
> - ClassIsland 里一张课表都没有时不会上报课表(日志会写「ClassIsland 里没有**启用的课表**」)。
> **提醒到底会不会弹,取决于两个开关:**
>
> 1. 教室机器的 **ClassHelper 客户端**在「设置 → 通知显示位置」里选了「只在 ClassHelper 客户端弹」时,
> 服务端根本不会推过来(此时本插件收不到东西,属正常);
> 2. 本插件的「接收 ClassHelper提醒」关掉时,即使推过来也不弹。
>
> 两者都开着,提醒才会在 ClassIsland 上出现。
## 工作原理(为什么这么写)
- **不用跨进程 IPC,插件内直接读课程服务**:ClassIsland 的 IPC 暴露的是缓存数据,不足以还原课表;
插件直接读 `ILessonsService`(当前科目 / 状态 / 时间点)与 `IProfileService`(档案里的课表、时间表、科目),
拿到的才是「教室此刻真实的状态」。
- **「上报即拉取」,不引入 Socket 依赖**:每次上报的返回值里会顺带带一条「尚未确认的提醒」,
插件收到就交给提醒提供方显示;应用启动时额外拉一次 `pending`,
补上「教室机器关机期间老师发的通知」。上报间隔本身就是心跳,插件因此少一个长连接故障面。
- **提醒必须由「提醒提供方」发出**:只有通过 `NotificationProviderBase` 发出的提醒,
才会走 ClassIsland 主界面的全屏特效 / 语音 / 音效那一整套流程,因此插件注册了
「ClassHelper提醒」提供方(可以在 ClassIsland 的「提醒」设置里整体开关它)。
- **回执时机 = 真的播完**:回执挂在提醒的 `Completed` / `Canceled` 上,
中途退出 ClassIsland 不会回执,下次上报会重发 —— 既不静默丢提醒,也不会重复弹。
- **镜像时重建时间点**:ClassIsland 的 `ClassPlan.Classes[i]` 必须与时间表里
**第 i 个 `TimeType == 0`(上课)的时间点**一一对应,
因此镜像接口为每条课目带上 `startTime` / `endTime`,插件据此重建时间表
(课间点从服务端的时间表里按起始时刻对齐)。少一个时间点,整份课表就会错位。
- **单双周口径与三端一致**:`WeekCountDiv/WeekCountDivTotal` ⇄ `ALL/ODD/EVEN`
与 `@classhelper/shared` 的 `weekParityFromDiv` / `weekDivFromParity` 互逆;
3 周及以上的轮换本系统无法表达,会降级为「每周」并在日志里提示。
- **非破坏性**:镜像只创建 / 更新名字以 `ClassHelper-` 开头的课表与时间表;
老师手动建的课表不删不改名,同一星期已有启用课表时会在日志里给出重叠提示。
## 上机联调记录(ClassIsland 2.1.0.1 实测)
下面几条都是把插件装进真实 ClassIsland 跑出来的问题与结论,改动理由就写在这里,避免以后被“顺手优化”回去:
1. **提醒内容必须在 UI 线程构造并显示。** 上报回调在线程池上,而提醒模板里的图标是 Avalonia 对象
(`LucideIconSource → IconSource → AvaloniaObject` 的构造函数会 `Dispatcher.VerifyAccess()`),
在线程池上直接构造会抛 `Call from invalid thread`,表现就是“ClassHelper 客户端收到了、ClassIsland 毫无反应”。
现在统一用 `Dispatcher.UIThread.Post` 切回 UI 线程。
2. **同一条提醒在播放期间要按 id 去重。** 服务端在收到回执前会一直把提醒算作“待弹出”,
而轮询间隔(默认 10 秒)可能小于提醒时长(最长 120 秒)—— 不去重就会一遍遍重复弹。
只有播完(`Completed`/`Canceled`)才把 id 从“正在播放”里移除并回执。
3. **不要自己拼图标串。** 双图标遮罩模板的默认图标由模板自己创建(`new LucideIconSource("\ue0ff")` 这种**字形字符**),
自己传 `"fluent(...)"` 之类既可能格式不对、也可能字形不存在。紧急提醒改用 ClassIsland 自带的**滚动文本**正文来表达。
4. **`Subject.Fallback` 是占位符(名字就是 `???`)。** 没有课表时 ClassIsland 会把它挂到
`CurrentSubject`/`NextClassSubject` 上,直接上报会让 Web 端显示“正在上 ???”,因此上报前归一化成“没有科目”。
实测截图(真机弹出提醒的遮罩):[普通提醒](../../docs/screenshots/classisland/02-normal-mask.png)、
[紧急提醒](../../docs/screenshots/classisland/01-urgent-mask.png)。
## 构建与打包
```bash
pnpm build:classisland-plugin # Release 构建(产物:packages/classisland-plugin/bin/Release)
pnpm dist:classisland-plugin # 追加打包 .cipx 并归集到 releases/classisland-plugin/
pnpm verify:classisland-plugin # 45 项静态契约校验(清单一致性 / 注册完整性 / DTO ↔ 服务端契约)
```
构建脚本会把 NuGet 缓存与临时目录指到仓库内的 `.cache/`(避免写满 C 盘),
并在打包后自检「清单 / 程序集名 / 版本号」三者一致。
## 开发提示
- 需要 **.NET 8 SDK**;SDK 包固定 `ClassIsland.PluginSdk 2.1.0.1`(2.1.1 起改为 net10.0,
本插件按 net8.0 交付,因此 2.0.x / 2.1.0.x 都能加载,见 `manifest.yml` 的 `apiVersion`)。
- 设置页是 Avalonia 的 `.axaml`(继承 `SettingsPageBase`);绑定走运行时解析
(`AvaloniaUseCompiledBindingsByDefault=false`),因为插件与主程序各自编译,编译期绑定看不到对方类型。
- **开发机没有安装 ClassIsland 本体**,所以插件只能做到编译 + 打包 + 静态校验;
运行期行为需要在装了 ClassIsland 的机器上按上面的「安装」步骤实测。
## 常见问题
**填好令牌后点「立即上报」,提示 `HTTP 404`(响应不是 ClassHelper的标准格式)**
这台机器上的**系统代理拦了内网请求**。Windows 的代理设置里 `127.0.0.1` 并不在默认绕过列表里,
于是浏览器/插件对「本地服务」的请求也被送到代理,拿到的是**代理自己的 404 错误页**。
插件已对本地/内网地址(localhost、回环、10/172.16-31/192.168、链路本地、无点主机名)**强制直连、绕开系统代理**;
如果仍然报 404,请依次检查:
1. 服务器地址是否写成了别的端口 / 别的机器(提示里会带上实际请求的完整 URL,照着核对最快);
2. 该地址在浏览器里打开 `<服务器地址>/api/health` 是否返回 `{"success":true,...}`;
3. 反向代理(Nginx 等)是否把 `/api/integrations` 也转发到了后端。
**上报失败,提示「设备令牌无效」**
在 Web 端重置该设备的令牌,然后把新令牌填回插件设置(旧令牌会立即失效)。
**发布提醒后 ClassIsland 没反应,或者要等一会儿才弹**
插件不持有长连接,提醒是**轮询取回**的:默认最多 10 秒(设置页「提醒轮询间隔」可调到 5 秒)。超过这个时间还没弹,按下面逐条排查。
**ClassIsland 上完全不弹提醒**
1. 确认插件设置里打开了「接收提醒」;
2. 确认 Web 端「ClassIsland 联动」页面上该设备是「已接入」状态(停用后服务端会直接 403);
3. 提醒会在 24 小时后过期,避免教室机器一开机弹出一堆旧通知。
**课表上报了但 ClassHelper上没变化**
确认插件设置里打开了「上报课表到服务端」,且 Web 端该设备的「回传课表」开关也是允许状态。
**镜像开关打开了,但 ClassIsland 的课表没变**
镜像需要 Web 端该设备开启「镜像课表」且班级里已有课表;插件只在**上报时**顺路拉取镜像,
所以打开开关后点一下「立即上报」或等一个上报间隔即可。镜像不会覆盖老师原有的课表。
## 许可
与 ClassHelper仓库一致。
Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

-19
View File
@@ -1,19 +0,0 @@
# ClassHelper ClassIsland 联动插件 —— 清单文件
#
# 字段说明见 https://docs.classisland.tech/dev/plugins/create-project/
# apiVersion 指向 ClassIsland 2.0.0.0:本插件只用到 2.0 就有的插件 / 提醒 / 课程服务 API。
id: classhelper.classisland.bridge
name: ClassHelper 联动
description: |-
把 ClassIsland 的课表与上课状态同步到 ClassHelper,并在 ClassIsland 上显示老师下发的提醒。
功能:
1. 上报当前课表与节次时间(ClassHelper Web 端与桌面客户端据此显示课程);
2. 上报"正在上哪节课 / 下一节是什么 / 还有多久下课"的实时状态;
3. 接收老师在 ClassHelper上发布的提醒,在 ClassIsland 上全屏弹出(支持语音朗读);
4. 可选:把 ClassHelper上排好的课表镜像回 ClassIsland。
entranceAssembly: 'ClassHelper.ClassIslandPlugin.dll'
url: https://github.com/LoveChengke/ClassHelper
version: 1.3.2.0
apiVersion: 2.0.0.0
author: ClassHelper
@@ -1,168 +0,0 @@
/**
* ClassIsland 联动插件构建脚本:`pnpm build:classisland-plugin` / `pnpm dist:classisland-plugin`
*
* 用法:
* node scripts/build.mjs # Release 构建,产物在 packages/classisland-plugin/bin/Release
* node scripts/build.mjs --cipx # 追加打包 .cipx 并归集到 releases/classisland-plugin/<版本>/
* 额外参数会原样透传给 `dotnet build`(例如 `-p:ClassIslandPluginSdkVersion=2.1.1.1`)
*
* 为什么需要这层包装(本机踩过的坑,写在这里免得换台机器又踩一遍):
* 1. `dotnet` 默认把 NuGet 缓存与临时文件写在 C 盘(`%USERPROFILE%\.nuget`、`%TEMP%`),
* 本机 C 盘紧张时会直接构建失败。这里统一改到仓库内 `.cache/`(已 gitignore)。
* 2. 插件包(.cipx)的最后一步要调 PowerShell 生成哈希清单,SDK 默认用 `pwsh`;
* 没有 pwsh 的机器会失败,因此这里探测一次并显式传给 MSBuild。
* 3. 构建完顺手校验"清单 / 程序集 / 版本号"三者一致,避免打出装不上的包。
*/
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const pluginDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const repoRoot = path.resolve(pluginDir, '..', '..');
const cacheDir = path.join(repoRoot, '.cache');
const releasesRoot = path.join(repoRoot, 'releases', 'classisland-plugin');
const argv = process.argv.slice(2);
const withCipx = argv.includes('--cipx');
/** `--` 之后的参数原样透传给 dotnet build;其余以 - 开头的参数同样透传 */
const passthrough = argv.filter((item) => item !== '--cipx' && item !== '--');
const log = (message) => console.log(`[classisland-plugin] ${message}`);
/* ------------------------------------------------------------ 1. 环境准备 */
const env = { ...process.env };
for (const sub of ['nuget', 'tmp', 'dotnet-home']) {
fs.mkdirSync(path.join(cacheDir, sub), { recursive: true });
}
const setDefault = (key, value) => {
if (!env[key]) env[key] = value;
};
setDefault('NUGET_PACKAGES', path.join(cacheDir, 'nuget'));
setDefault('TEMP', path.join(cacheDir, 'tmp'));
setDefault('TMP', env.TEMP);
setDefault('DOTNET_CLI_HOME', path.join(cacheDir, 'dotnet-home'));
env.DOTNET_NOLOGO = '1';
env.DOTNET_CLI_TELEMETRY_OPTOUT = '1';
/** 可执行文件探测:先看显式配置,再问 PATH,最后试常见安装路径 */
function resolveExecutable(envKey, names, fallbacks) {
const candidates = [];
if (env[envKey]) candidates.push(env[envKey]);
const finder = process.platform === 'win32' ? 'where' : 'which';
for (const name of names) {
const found = spawnSync(finder, [name], { encoding: 'utf8', env });
if (found.status === 0) {
for (const line of String(found.stdout ?? '').split(/\r?\n/)) candidates.push(line.trim());
}
}
candidates.push(...fallbacks);
for (const candidate of candidates) {
if (!candidate) continue;
try {
if (fs.statSync(candidate).isFile()) return candidate;
} catch {
/* 继续试下一个 */
}
}
return null;
}
const dotnet = resolveExecutable(
'DOTNET_EXE',
['dotnet'],
process.platform === 'win32'
? [path.join(env.ProgramFiles ?? 'C:\\Program Files', 'dotnet', 'dotnet.exe')]
: ['/usr/local/bin/dotnet', '/usr/bin/dotnet'],
);
if (!dotnet) {
throw new Error('未找到 dotnet SDK(需要 .NET 8 SDK)。安装后用 DOTNET_EXE 指定完整路径。');
}
const powerShell = resolveExecutable(
'POWERSHELL_EXE',
['pwsh', 'powershell'],
process.platform === 'win32'
? [path.join(env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')]
: [],
);
/* ------------------------------------------------------------ 2. 构建 */
const buildArgs = ['build', '-c', 'Release'];
if (withCipx) {
buildArgs.push('-p:CreateCipx=true');
// SDK 的 cipx 目标默认调 pwsh;这里按探测结果显式指定,避免"没有 pwsh 就打包失败"
if (powerShell) buildArgs.push(`-p:PowershellBinaryName=${powerShell}`);
}
buildArgs.push(...passthrough);
log(`dotnet build(缓存目录 ${path.relative(repoRoot, cacheDir)})`);
const build = spawnSync(dotnet, buildArgs, { cwd: pluginDir, stdio: 'inherit', env });
if (build.error) throw new Error(`无法启动 dotnet:${build.error.message}`);
if (build.status !== 0) throw new Error(`dotnet build 失败(退出码 ${build.status})`);
/* ------------------------------------------------------------ 3. 产物自检 */
const outputDir = path.join(pluginDir, 'bin', 'Release');
const manifestPath = path.join(outputDir, 'manifest.yml');
const assemblyPath = path.join(outputDir, 'ClassHelper.ClassIslandPlugin.dll');
for (const required of [manifestPath, assemblyPath, path.join(outputDir, 'icon.png')]) {
if (!fs.existsSync(required)) {
throw new Error(`构建产物缺少 ${path.relative(pluginDir, required)},ClassIsland 会加载失败`);
}
}
const manifest = fs.readFileSync(manifestPath, 'utf8');
// prettier 会把 YAML 字符串统一成单引号,因此两种引号都要能剥掉
const entrance = /^entranceAssembly:\s*(.+?)\s*$/m.exec(manifest)?.[1]?.replace(/^['"]|['"]$/g, '');
if (entrance !== path.basename(assemblyPath)) {
throw new Error(
`manifest.yml 的 entranceAssembly(${entrance})与程序集(${path.basename(assemblyPath)})不一致`,
);
}
const manifestVersion = /^version:\s*([\d.]+)/m.exec(manifest)?.[1];
const bridgeSource = fs.readFileSync(path.join(pluginDir, 'src', 'Services', 'BridgeService.cs'), 'utf8');
const codeVersion = /PluginVersion = "([\d.]+)"/.exec(bridgeSource)?.[1];
if (!manifestVersion || manifestVersion !== codeVersion) {
throw new Error(
`版本号不一致:manifest.yml=${manifestVersion ?? '缺失'},BridgeService.cs=${codeVersion ?? '缺失'}`,
);
}
log(`产物自检通过(版本 ${manifestVersion},入口程序集 ${entrance})`);
/* ------------------------------------------------------------ 4. 打包归集 */
if (!withCipx) {
log('完成。加 --cipx 可同时打包成 ClassIsland 插件包(.cipx)');
process.exit(0);
}
const cipxDir = path.join(pluginDir, 'cipx');
const cipxFile = path.join(cipxDir, 'ClassHelper.ClassIslandPlugin.cipx');
if (!fs.existsSync(cipxFile)) {
throw new Error(`未生成插件包:${path.relative(pluginDir, cipxFile)}`);
}
// 归集到 releases/classisland-plugin/<版本>/(与客户端、服务端交付产物同一约定;releases/ 不入库)。
// 只清理**当前版本**目录,历史版本原样保留 —— 原先这里是 rmSync 整个组件目录,重打一次就把
// 上一版的留档抹掉了(插件版本是四段 <产品版本>.0,目录名取前三段与产品版本对齐)。
// 产物只有 `安装包/*.cipx` + `checksums.md`:**.cipx 本身就是个 zip**,解压即用的那份
// 「免安装目录」与它内容完全一样,纯属重复留档,已不再产出。
const pluginVersion = manifestVersion.split('.').slice(0, 3).join('.');
const versionDir = path.join(releasesRoot, pluginVersion);
const installerDir = path.join(versionDir, '安装包');
fs.rmSync(installerDir, { recursive: true, force: true });
fs.rmSync(path.join(versionDir, '免安装'), { recursive: true, force: true });
fs.mkdirSync(installerDir, { recursive: true });
for (const file of fs.readdirSync(cipxDir)) {
// .cipx 是插件包本体,校验清单跟着版本目录走
const to = file.toLowerCase().endsWith('.cipx') ? installerDir : versionDir;
fs.copyFileSync(path.join(cipxDir, file), path.join(to, file));
}
log(`插件包已归集到 ${path.relative(repoRoot, versionDir)}`);
for (const file of fs.readdirSync(installerDir)) log(` 安装包/${file}`);
@@ -1,405 +0,0 @@
/**
* ClassIsland 联动插件静态校验:`pnpm verify:classisland-plugin`
*
* 为什么是"静态"校验:插件要跑起来必须有 ClassIsland 本体,而本机(以及 CI)都没有,
* 所以这里校验"装不上 / 对不上"的那几类问题 —— 它们不需要运行就能发现:
*
* 1. 清单三件套一致性:manifest.yml ↔ csproj ↔ 代码里的版本号;
* 2. 注册完整性:插件入口、提醒提供方、设置页是否都挂上了(挂漏了功能会"静默消失");
* 3. **接口契约**:C# DTO 的 JSON 字段名 ↔ 服务端路由 / 请求字段,
* 这类错误(比如 dayOfWeek 写成 dayofweek)在运行时只会表现为"上报成功但课表是空的",
* 最难排查,所以专门盯住。
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const pluginDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const repoRoot = path.resolve(pluginDir, '..', '..');
const results = [];
const check = (name, ok, detail = '') => results.push({ name, ok: Boolean(ok), detail });
const read = (relative) => fs.readFileSync(path.join(pluginDir, relative), 'utf8');
const readRepo = (relative) => fs.readFileSync(path.join(repoRoot, relative), 'utf8');
const manifest = read('manifest.yml');
const csproj = read('ClassHelper.ClassIslandPlugin.csproj');
const pluginSource = read('src/Plugin.cs');
const providerSource = read('src/Services/ClassHelperNotificationProvider.cs');
const bridgeSource = read('src/Services/BridgeService.cs');
const clientSource = read('src/Interop/ClassHelperClient.cs');
const settingsPageSource = read('src/Views/BridgeSettingsPage.axaml.cs');
const settingsPageXaml = read('src/Views/BridgeSettingsPage.axaml');
const mapperSource = read('src/Services/ScheduleMapper.cs');
const writerSource = read('src/Services/ClassPlanWriter.cs');
const settingsSource = read('src/Models/PluginSettings.cs');
const serverModule = readRepo('packages/server/src/modules/integrations/integrations.module.ts');
const serverSchemas = readRepo('packages/server/src/modules/integrations/integrations.schemas.ts');
const serverService = readRepo('packages/server/src/modules/integrations/integrations.service.ts');
const sharedTypes = readRepo('packages/shared/src/types.ts');
const sharedConstants = readRepo('packages/shared/src/constants.ts');
/* ------------------------------------------------------------ 1. 清单一致性 */
/** 取 YAML 里某个顶层字段的值(prettier 会把字符串统一成单引号,两种引号都要能剥掉) */
function field(name) {
const raw = new RegExp('^' + name + ':\\s*(.+?)\\s*$', 'm').exec(manifest)?.[1];
return raw?.replace(/^['"]|['"]$/g, '');
}
check('manifest.yml 有插件 id', Boolean(field('id')));
check('manifest.yml 声明了入口程序集', Boolean(field('entranceAssembly')));
check('manifest.yml 声明了 apiVersion', /\d+\.\d+\.\d+\.\d+/.test(field('apiVersion') ?? ''));
const assemblyName = /<AssemblyName>([^<]+)<\/AssemblyName>/.exec(csproj)?.[1];
check(
'entranceAssembly 与 csproj 的 AssemblyName 一致',
field('entranceAssembly') === assemblyName + '.dll',
'entranceAssembly=' + field('entranceAssembly') + ' AssemblyName=' + assemblyName,
);
const manifestVersion = field('version');
const codeVersion = /PluginVersion = "([\d.]+)"/.exec(bridgeSource)?.[1];
check(
'插件版本号在清单与代码里一致',
Boolean(manifestVersion) && manifestVersion === codeVersion,
'manifest=' + manifestVersion + ' code=' + codeVersion,
);
check(
'图标与自述文件按清单约定命名(icon.png / README.md)',
fs.existsSync(path.join(pluginDir, 'icon.png')) && fs.existsSync(path.join(pluginDir, 'README.md')),
);
/* ------------------------------------------------------------ 2. 注册完整性 */
check(
'插件入口带 [PluginEntrance] 且继承 PluginBase',
/\[PluginEntrance\]/.test(pluginSource) && /:\s*PluginBase/.test(pluginSource),
);
check(
'初始化时注册了提醒提供方',
/AddNotificationProvider<\s*ClassHelperNotificationProvider\s*>/.test(pluginSource),
);
check('初始化时注册了设置页', /AddSettingsPage<\s*BridgeSettingsPage\s*>/.test(pluginSource));
check('初始化时把联动服务注册为单例', /AddSingleton<\s*BridgeService\s*>/.test(pluginSource));
check('应用启动后才接课程服务(不能更早)', /AppStarted/.test(pluginSource));
check(
'设置以 JSON 持久化到插件配置目录',
/PluginConfigFolder/.test(pluginSource) && /Settings\.json/.test(pluginSource),
);
const providerGuid = /ProviderGuidValue = "([0-9A-Fa-f-]{36})"/.exec(providerSource)?.[1];
check('提醒提供方声明了合法 GUID', Boolean(providerGuid));
check(
'提醒提供方属性引用同一个 GUID 常量',
/NotificationProviderInfo\(\s*ProviderGuidValue/.test(providerSource),
);
check(
'提醒提供方会在播完后回执给服务端',
/Completed/.test(providerSource) && /AckAsync/.test(providerSource),
);
check(
'设置页带 [SettingsPageInfo] 且声明了页面 id',
/\[SettingsPageInfo\(/.test(settingsPageSource) && /"ClassHelper 联动"/.test(settingsPageSource),
);
check(
'设置页 XAML 的 x:Class 与代码后置类一致',
settingsPageXaml.includes('x:Class="ClassHelper.ClassIslandPlugin.Views.BridgeSettingsPage"') &&
/namespace ClassHelper\.ClassIslandPlugin\.Views;/.test(settingsPageSource),
);
check('设置页 XAML 继承 ClassIsland 的设置页基类', /SettingsPageBase/.test(settingsPageXaml));
/* ------------------------------------------------------------ 3. 接口契约 */
// 3.1 路由:插件调用的路径必须都在服务端注册过
const clientPaths = [...clientSource.matchAll(/"(\/classisland\/[a-z-]+)"/g)].map((item) => item[1]);
const registeredPaths = new Set(
[...serverModule.matchAll(/router\.(?:get|post|patch|delete)\(\s*'(\/classisland\/[a-z-]+)'/g)].map(
(item) => item[1],
),
);
for (const route of [
'/classisland/report',
'/classisland/pending',
'/classisland/ack',
'/classisland/class-plan',
]) {
check('服务端注册了 ' + route, registeredPaths.has(route));
}
check(
'插件调用的路由都存在于服务端',
clientPaths.length > 0 && clientPaths.every((item) => registeredPaths.has(item)),
'插件调用=[' + clientPaths.join(',') + ']',
);
check('插件把接口前缀拼成 /api/integrations', clientSource.includes('/api/integrations'));
check('插件用设备令牌头鉴权', clientSource.includes('X-ClassIsland-Token'));
// 3.2 上报请求字段:服务端 zod schema 里出现的字段名,插件必须真的会发
const reportBlock = /export const classIslandReportSchema[\s\S]*?\n\}\);/.exec(serverSchemas)?.[0] ?? '';
const requestFields = [
'pluginVersion',
'classIslandVersion',
'state',
'schedule',
'timeLayout',
'inClass',
'subject',
'nextSubject',
'timeState',
'periodStart',
'periodEnd',
'classPlanLoaded',
'clientTime',
'mode',
'entries',
'items',
];
const missingRequestFields = requestFields.filter(
(name) => reportBlock.includes(name) && !new RegExp('\\b' + name + '\\b').test(clientSource),
);
check(
'上报请求字段都出现在插件 DTO 里',
missingRequestFields.length === 0,
missingRequestFields.length > 0 ? '缺少=' + missingRequestFields.join(',') : '',
);
// 3.3 课表条目字段:这些是"上报成功但课表为空"的典型来源
const entrySchema = /export const reportScheduleEntrySchema[\s\S]*?\n\}\);/.exec(serverSchemas)?.[0] ?? '';
const entryFields = [
'dayOfWeek',
'startTime',
'endTime',
'subject',
'teacherName',
'weekParity',
'weekCountDiv',
'weekCountDivTotal',
'planName',
];
const csharpJsonNames = new Set(
[...clientSource.matchAll(/\[JsonPropertyName\("([^"]+)"\)\]/g)].map((item) => item[1]),
);
const missingEntryFields = entryFields.filter(
(name) => entrySchema.includes(name) && !csharpJsonNames.has(name),
);
check(
'课表条目字段服务端 zod 与插件 DTO 对齐',
missingEntryFields.length === 0,
missingEntryFields.length > 0 ? '插件缺少=' + missingEntryFields.join(',') : '',
);
// 3.4 插件 DTO 里的 JSON 字段名必须能在共享契约里找到(防错拼)
const knownLocalOnly = new Set(['data', 'success', 'message', 'code']);
const unknownJsonNames = [...csharpJsonNames].filter((name) => {
if (knownLocalOnly.has(name)) return false;
return !new RegExp('\\b' + name + '\\b').test(sharedTypes);
});
check(
'插件 DTO 的 JSON 字段名都能在 @classhelper/shared 里找到',
unknownJsonNames.length === 0,
unknownJsonNames.length > 0 ? '疑似拼写错误=' + unknownJsonNames.join(',') : '',
);
// 3.5 课表镜像:服务端给了 Classes[i] 对齐所需的时间,插件必须读
for (const name of ['startTime', 'endTime', 'timeLayouts', 'profileName', 'weekDay', 'weekCountDivTotal']) {
check('镜像契约字段 ' + name + ' 在插件侧存在', csharpJsonNames.has(name));
}
// 3.6 提醒下发字段(Web 端 → 服务端 → 插件)
const notifySchema = /export const sendNotificationSchema[\s\S]*?\n\}\);/.exec(serverSchemas)?.[0] ?? '';
for (const name of [
'classId',
'title',
'content',
'durationSeconds',
'speech',
'speechContent',
'saveToNotifications',
'priority',
]) {
check('下发提醒字段 ' + name + ' 在服务端 schema 里', notifySchema.includes(name));
}
check(
'提醒时长有上界(避免老师发出永不消失的提醒)',
/CLASSISLAND_NOTIFICATION_MAX_DURATION/.test(serverSchemas) &&
/CLASSISLAND_NOTIFICATION_MAX_DURATION/.test(sharedConstants),
);
// 3.7 实时事件:Web 端订阅的事件名必须在共享契约里声明过
check(
'共享契约声明了 classisland 实时事件',
sharedTypes.includes("'classisland:state'") && sharedTypes.includes("'classisland:notification'"),
);
check(
'服务端广播事件名取自共享常量(不是手写字符串)',
/SOCKET_EVENTS\.classislandState/.test(serverService),
);
// 3.8 网络层:教室机器(以及开发机)常配了系统代理,而 Windows 的代理设置默认连 127.0.0.1
// 也会走代理,表现为"填了令牌立刻 HTTP 404"(其实是代理自己的错误页,跟本服务无关)。
// 插件必须对本地/内网地址绕开系统代理,否则内网部署必然失败。
check(
'HttpClient 显式配置代理(不裸用默认行为)',
/SocketsHttpHandler\s*\{[^}]*Proxy\s*=/.test(clientSource),
);
check(
'本地/内网地址绕开系统代理',
/class LocalAwareProxy/.test(clientSource) && /IsBypassed\(Uri host\)/.test(clientSource),
);
check(
'代理判定覆盖回环与内网网段',
/IsLoopback/.test(clientSource) &&
/10\.0\.0\.0\/8/.test(clientSource) &&
/192\.168\.0\.0\/16/.test(clientSource),
);
check('失败信息带上请求 URL(便于定位代理/网关拦截)', /request\.RequestUri/.test(clientSource));
// 3.10 课表同步方向(2026-10-11 定稿):**两个方向都只由 Web 端的一次性动作触发**。
// 2026-10-06 曾经把它做成"服务端 → 教室自动下发 + 本机两个开关",但默认 15 秒一轮的
// 自动上传 + 自动镜像会让服务端与教室里的课表每 15 秒互相覆盖一次,老师看到的是
// "课表被反复删改"(2026-10-11 实测)。现在本机没有任何"一直同步"的开关:
// · 教室 → 服务端:`scheduleRequested` 一次性待办(Web 端「从教室机器获取课表」)
// · 服务端 → 教室:`mirrorRequested` 一次性待办(Web 端「下发课表到教室」,强制替换)
// 这几条盯着新契约,别删。
check(
'课表两个方向都改为按需:本机不再有「自动回传 / 自动镜像」开关',
!/_uploadSchedule/.test(settingsSource) && !/_mirrorSchedule/.test(settingsSource),
);
check(
'定时上报只报运行状态,课表仅在服务端显式请求时上传',
/var uploadSchedule = forceSchedule;/.test(bridgeSource),
);
check(
'响应 DTO 里有 scheduleRequested / mirrorRequested(两个方向的一次性待办)',
/scheduleRequested/.test(clientSource) && /mirrorRequested/.test(clientSource),
);
check(
'收到 scheduleRequested 会补发一次带课表的上报(且不受本机自动上报开关限制)',
/ScheduleRequested\s*==\s*true/.test(bridgeSource) &&
/forceSchedule:\s*true/.test(bridgeSource),
);
check(
'只有收到 mirrorRequested 才镜像(不再跟着每一次上报走)',
/MirrorRequested\s*==\s*true/.test(bridgeSource),
);
check(
'镜像写入是「强制替换」(停用冲突的旧课表,而不是只留一条警告)',
/Apply\(profile, plan, force: true\)/.test(bridgeSource) &&
/IsEnabled = false/.test(writerSource),
);
check(
'补发课表发生在镜像之前(顺序反了会把刚拿到的课表盖掉)',
bridgeSource.indexOf('ScheduleRequested == true') < bridgeSource.indexOf('MirrorScheduleAsync()'),
);
check(
'课表拉取 DTO 带 weekRanges(管理员逐周配的学期周次区间)',
/weekRanges/.test(clientSource) && /TermWeekRangeDto/.test(clientSource),
);
// 3.9 提醒显示链路:下面几条全是"在真机上跑出来的",回归时别删
check(
'提醒在 UI 线程构造并显示(否则 Avalonia 直接抛 Call from invalid thread)',
providerSource.includes('Dispatcher.UIThread.Post'),
);
check(
'同一条提醒在播放期间按 id 去重(否则轮询会让它反复弹)',
providerSource.includes('_playing') && providerSource.includes('HashSet<string>'),
);
check(
'不再自造图标串(用模板默认图标,紧急用滚动文本表达)',
// 不再给 CreateTwoIconsMask 传 leftIcon(自造图标串会踩格式/字形坑)
!providerSource.includes('leftIcon') && providerSource.includes('CreateRollingTextContent'),
);
check(
'ClassIsland 的占位科目(Subject.Fallback)折算成"没有科目"',
mapperSource.includes('Subject.Fallback'),
);
check(
'上课时段暂存非主动通知(与客户端灵动岛同一套规则)',
providerSource.includes('_deferred') &&
providerSource.includes('IsImmediate') &&
providerSource.includes('FlushDeferred') &&
providerSource.includes('OnBreakingTime'),
);
check(
'主动通知(紧急 / 叫人)上课时段也立即弹',
providerSource.includes("\"call\"") && providerSource.includes('notification.Urgent'),
);
check(
'「上报课表」开关关闭时会在日志里说明(避免被当成"上报失败")',
bridgeSource.includes('上报课表到 ClassHelper') && bridgeSource.includes('开关已关闭'),
);
check(
'提醒轮询独立于上报间隔(老师发完通知不必等一个上报周期)',
settingsSource.includes('NotificationPollSeconds') &&
bridgeSource.includes('_notifyTimer') &&
bridgeSource.includes('NotificationPollSeconds'),
);
/* ------------------------------------------------------------ 8. 回归护栏:本次修复过的坑 */
check(
'课表配对用原始 TimeType==0 列表,**不用** ValidTimeLayoutItems(后者会剔除被停用的节次,导致整份课表错位)',
// 只查代码形态(`.Count`),因为源码注释里特意点名了这个属性来说明"为什么不能用它"
mapperSource.includes('classPoints[index]') && !mapperSource.includes('.ValidTimeLayoutItems.Count'),
);
check(
'上报字段按服务端 zod 上限截断(一个超长名字会让整批上报 400,连状态与心跳一起丢掉)',
mapperSource.includes('Truncate(') &&
mapperSource.includes('SubjectMaxLength') &&
mapperSource.includes('PlanNameMaxLength'),
);
check(
'课表镜像在 UI 线程改写档案(线程池上改 Observable 集合会与落盘并发,可能写坏档案)',
bridgeSource.includes('Dispatcher.UIThread.InvokeAsync') && bridgeSource.includes('SaveProfile()'),
);
check(
'镜像内容未变化时跳过(否则每次上报都重建课表并全量落盘)',
bridgeSource.includes('_lastMirrorSignature') && bridgeSource.includes('MirrorSignature('),
);
check(
'上报异常有 catch(fire-and-forget 的异常会被静默吞掉)',
bridgeSource.includes('catch (Exception exception)') && bridgeSource.includes('上报异常'),
);
check(
'镜像前过滤时间非法的条目(避免档案里出现 00:00 的课次,且必须与 Classes 同步过滤)',
read('src/Services/ClassPlanWriter.cs').includes('IsValidTime'),
);
check(
'上报体带上 deviceKey,且服务端 schema 也声明了该字段(回填机器码的契约两端一致)',
clientSource.includes('"deviceKey"') && serverSchemas.includes('deviceKey:'),
);
check(
'2xx 但不是本服务响应体时给出原因(而不是"成功但无数据 + 空消息"),并限制响应体大小',
clientSource.includes('响应不是 ClassHelper的标准格式') &&
clientSource.includes('MaxResponseContentBufferSize'),
);
check(
'提醒提供方惰性获取课程服务并重试(拿不到服务时"上课暂存"会永久失效且静默)',
providerSource.includes('EnsureLessons') && providerSource.includes('_lessonsHooked'),
);
check(
'设置落盘先写临时文件再原子替换(逐字符写盘 + 截断式写入会留下坏 JSON)',
pluginSource.includes('File.Move(temp, path, overwrite: true)'),
);
check(
'服务器地址只接受 http/https(裸 Uri.TryCreate 会放过 file:// / ftp://)',
settingsSource.includes('TryGetServerUri') && settingsSource.includes('UriSchemeHttp'),
);
/* ------------------------------------------------------------ 结果 */
const failed = results.filter((item) => !item.ok);
for (const item of results) {
console.log((item.ok ? '√ ' : '× ') + item.name + (item.detail ? ' (' + item.detail + ')' : ''));
}
console.log('');
console.log(
'ClassIsland 联动插件静态校验:' + (results.length - failed.length) + '/' + results.length + ' 项通过',
);
if (failed.length > 0) {
console.log('未通过:\n - ' + failed.map((item) => item.name).join('\n - '));
process.exit(1);
}
@@ -1,485 +0,0 @@
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using ClassHelper.ClassIslandPlugin.Models;
namespace ClassHelper.ClassIslandPlugin.Interop;
/* ---------------------------------------------------------------- 服务端契约(与 packages/shared 保持一致) */
/// <summary>插件上报的课表条目。</summary>
public class ScheduleEntryDto
{
[JsonPropertyName("dayOfWeek")] public int DayOfWeek { get; set; }
[JsonPropertyName("startTime")] public string StartTime { get; set; } = "";
[JsonPropertyName("endTime")] public string EndTime { get; set; } = "";
[JsonPropertyName("subject")] public string Subject { get; set; } = "";
[JsonPropertyName("teacherName")] public string? TeacherName { get; set; }
/// <summary>ALL / ODD / EVEN;留空则由服务端按 weekCountDiv 推导。</summary>
[JsonPropertyName("weekParity")] public string? WeekParity { get; set; }
[JsonPropertyName("weekCountDiv")] public int WeekCountDiv { get; set; }
[JsonPropertyName("weekCountDivTotal")] public int WeekCountDivTotal { get; set; }
[JsonPropertyName("planName")] public string? PlanName { get; set; }
}
/// <summary>插件上报的节次时间。</summary>
public class TimeLayoutItemDto
{
[JsonPropertyName("index")] public int Index { get; set; }
[JsonPropertyName("name")] public string Name { get; set; } = "";
[JsonPropertyName("startTime")] public string StartTime { get; set; } = "";
[JsonPropertyName("endTime")] public string EndTime { get; set; } = "";
/// <summary>class / break / divider / action</summary>
[JsonPropertyName("type")] public string Type { get; set; } = "class";
[JsonPropertyName("skipped")] public bool Skipped { get; set; }
}
/// <summary>本机运行状态快照。</summary>
public class StateDto
{
[JsonPropertyName("inClass")] public bool InClass { get; set; }
[JsonPropertyName("subject")] public string? Subject { get; set; }
[JsonPropertyName("nextSubject")] public string? NextSubject { get; set; }
[JsonPropertyName("timeState")] public string? TimeState { get; set; }
[JsonPropertyName("periodStart")] public string? PeriodStart { get; set; }
[JsonPropertyName("periodEnd")] public string? PeriodEnd { get; set; }
[JsonPropertyName("week")] public int? Week { get; set; }
[JsonPropertyName("classPlanLoaded")] public bool ClassPlanLoaded { get; set; }
[JsonPropertyName("clientTime")] public string ClientTime { get; set; } = "";
}
public class SchedulePayloadDto
{
[JsonPropertyName("mode")] public string Mode { get; set; } = "merge";
[JsonPropertyName("entries")] public List<ScheduleEntryDto> Entries { get; set; } = new();
}
public class TimeLayoutPayloadDto
{
[JsonPropertyName("name")] public string Name { get; set; } = "ClassIsland 时间表";
[JsonPropertyName("mode")] public string Mode { get; set; } = "replace";
[JsonPropertyName("items")] public List<TimeLayoutItemDto> Items { get; set; } = new();
}
public class ReportRequestDto
{
[JsonPropertyName("pluginVersion")] public string PluginVersion { get; set; } = "";
[JsonPropertyName("classIslandVersion")] public string ClassIslandVersion { get; set; } = "";
/// <summary>本机机器码:设备创建时服务端还不知道它,靠这里回填(见服务端 syncDeviceKey)。</summary>
[JsonPropertyName("deviceKey")] public string DeviceKey { get; set; } = "";
[JsonPropertyName("state")] public StateDto? State { get; set; }
[JsonPropertyName("schedule")] public SchedulePayloadDto? Schedule { get; set; }
[JsonPropertyName("timeLayout")] public TimeLayoutPayloadDto? TimeLayout { get; set; }
}
public class ReportSettingsDto
{
[JsonPropertyName("mirrorScheduleToClassIsland")] public bool MirrorScheduleToClassIsland { get; set; }
[JsonPropertyName("enabled")] public bool Enabled { get; set; }
/// <summary>
/// 服务端请求**立刻上报一次课表**(老师在 Web 端点了「从教室机器获取课表」)。
///
/// 它与本机的「上报课表到 ClassHelper」开关无关:那个开关管的是"要不要**自动**回传",
/// 现在是默认关闭的;而这是一次显式的人工请求,看到就要照做。
/// </summary>
[JsonPropertyName("scheduleRequested")] public bool ScheduleRequested { get; set; }
/// <summary>
/// 服务端请求**下发一次课表到教室**(老师在 Web 端点了「下发课表到教室」)。
///
/// 与 <see cref="ScheduleRequested"/> 反方向,同样是一次性待办:看到就拉本班课表并
/// **强制替换**写进 ClassIsland;拉取成功时由服务端清除标记。
/// 没有"后台定时镜像"那条路径了 —— 那会让教室课表被反复重写(见 BridgeService 的说明)。
/// </summary>
[JsonPropertyName("mirrorRequested")] public bool MirrorRequested { get; set; }
}
public class ReportResultDto
{
[JsonPropertyName("scheduleApplied")] public bool ScheduleApplied { get; set; }
[JsonPropertyName("scheduleCreated")] public int ScheduleCreated { get; set; }
[JsonPropertyName("scheduleUpdated")] public int ScheduleUpdated { get; set; }
[JsonPropertyName("courses")] public List<string> Courses { get; set; } = new();
[JsonPropertyName("timeLayoutApplied")] public bool TimeLayoutApplied { get; set; }
[JsonPropertyName("week")] public int Week { get; set; }
[JsonPropertyName("serverTime")] public string ServerTime { get; set; } = "";
[JsonPropertyName("settings")] public ReportSettingsDto? Settings { get; set; }
[JsonPropertyName("pendingNotification")] public PushNotificationDto? PendingNotification { get; set; }
}
/// <summary>服务端下发的提醒。</summary>
public class PushNotificationDto
{
[JsonPropertyName("id")] public string Id { get; set; } = "";
[JsonPropertyName("title")] public string Title { get; set; } = "";
[JsonPropertyName("content")] public string Content { get; set; } = "";
[JsonPropertyName("durationSeconds")] public int DurationSeconds { get; set; } = 8;
[JsonPropertyName("speechContent")] public string? SpeechContent { get; set; }
[JsonPropertyName("createdAt")] public string CreatedAt { get; set; } = "";
[JsonPropertyName("urgent")] public bool Urgent { get; set; }
/// <summary>提醒类型:notification(默认)/ call(叫人,算"主动通知",上课时段也立刻弹)</summary>
[JsonPropertyName("kind")] public string? Kind { get; set; }
[JsonPropertyName("classId")] public string ClassId { get; set; } = "";
[JsonPropertyName("className")] public string? ClassName { get; set; }
[JsonPropertyName("teacherName")] public string? TeacherName { get; set; }
}
public class PendingResultDto
{
[JsonPropertyName("notifications")] public List<PushNotificationDto> Notifications { get; set; } = new();
[JsonPropertyName("serverTime")] public string ServerTime { get; set; } = "";
[JsonPropertyName("week")] public int Week { get; set; }
}
/* ---------------------------------------------------------------- 课表镜像(服务端 → ClassIsland) */
public class ClassPlanEntryMirrorDto
{
[JsonPropertyName("weekDay")] public int WeekDay { get; set; }
[JsonPropertyName("weekCountDiv")] public int WeekCountDiv { get; set; }
[JsonPropertyName("weekCountDivTotal")] public int WeekCountDivTotal { get; set; }
[JsonPropertyName("subject")] public string Subject { get; set; } = "";
[JsonPropertyName("teacherName")] public string? TeacherName { get; set; }
/// <summary>起止时间(HH:mm)。Classes[i] 必须与第 i 个上课时间点对齐,靠它重建时间表。</summary>
[JsonPropertyName("startTime")] public string StartTime { get; set; } = "";
[JsonPropertyName("endTime")] public string EndTime { get; set; } = "";
[JsonPropertyName("timeLayoutId")] public string TimeLayoutId { get; set; } = "";
}
public class TimeLayoutMirrorDto
{
[JsonPropertyName("id")] public string Id { get; set; } = "";
[JsonPropertyName("name")] public string Name { get; set; } = "";
[JsonPropertyName("layouts")] public List<TimeLayoutItemMirrorDto> Layouts { get; set; } = new();
}
public class TimeLayoutItemMirrorDto
{
[JsonPropertyName("startTime")] public string StartTime { get; set; } = "";
[JsonPropertyName("endTime")] public string EndTime { get; set; } = "";
[JsonPropertyName("timeType")] public int TimeType { get; set; }
}
public class ClassPlanMirrorDto
{
[JsonPropertyName("entries")] public List<ClassPlanEntryMirrorDto> Entries { get; set; } = new();
[JsonPropertyName("timeLayouts")] public List<TimeLayoutMirrorDto> TimeLayouts { get; set; } = new();
[JsonPropertyName("profileName")] public string ProfileName { get; set; } = "";
[JsonPropertyName("termStartDate")] public string TermStartDate { get; set; } = "";
}
/// <summary>服务端逐周配的学期周次区间(管理员在「学期周次」里维护)。</summary>
public class TermWeekRangeDto
{
[JsonPropertyName("weekNumber")] public int WeekNumber { get; set; }
/// <summary>YYYY-MM-DD</summary>
[JsonPropertyName("startDate")] public string StartDate { get; set; } = "";
/// <summary>YYYY-MM-DD</summary>
[JsonPropertyName("endDate")] public string EndDate { get; set; } = "";
}
public class PullResultDto
{
[JsonPropertyName("classPlan")] public ClassPlanMirrorDto? ClassPlan { get; set; }
[JsonPropertyName("week")] public int Week { get; set; }
/// <summary>
/// 学期逐周区间;空 = 服务端只按学期开始日期线性推算。
///
/// ClassIsland 自身只认"教学周序号 + 单双周",没有"按日期区间定义某一周"的模型
/// (本机装的 2.1.0.1 没有该字段),所以这份区间在插件侧只用于:
/// 1) 校正"现在是第几周"(调休会让线性推算整体错位);
/// 2) 在设置页里显示教室这台机器当前处在哪一段日期区间,方便老师核对。
/// 课表本身的周次口径仍由 <see cref="ClassPlanMirrorDto.TermStartDate"/> 与单双周表达。
/// </summary>
[JsonPropertyName("weekRanges")] public List<TermWeekRangeDto> WeekRanges { get; set; } = new();
[JsonPropertyName("serverTime")] public string ServerTime { get; set; } = "";
}
/* ---------------------------------------------------------------- 统一响应体 */
internal class ApiEnvelope<T>
{
[JsonPropertyName("success")] public bool Success { get; set; }
[JsonPropertyName("data")] public T? Data { get; set; }
[JsonPropertyName("message")] public string Message { get; set; } = "";
[JsonPropertyName("code")] public string? Code { get; set; }
}
/// <summary>调用 ClassHelper后端的结果(不抛异常,便于设置页展示原因)。</summary>
public class ApiCallResult
{
public bool Ok { get; init; }
public string Message { get; init; } = "";
public bool NetworkError { get; init; }
public static ApiCallResult Success(string message) => new() { Ok = true, Message = message };
public static ApiCallResult Failure(string message) => new() { Ok = false, Message = message };
public static ApiCallResult Offline(string message) => new() { Ok = false, Message = message, NetworkError = true };
}
/// <summary>
/// ClassHelper后端客户端。
///
/// 只用 <see cref="HttpClient"/> + System.Text.Json:不引入额外依赖包,
/// 避免插件加载时因为"插件程序集隔离"缺少依赖而无法启动
/// (见 https://docs.classisland.tech/dev/plugins/basics.html 的程序集隔离说明)。
/// </summary>
public sealed class ClassHelperClient : IDisposable
{
/// <summary>
/// 单次请求超时。教室机器可能是内网慢链路,但也不该卡住上报线程太久。
/// </summary>
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(12);
/// <summary>
/// 响应体上限(4MB)。默认是 2GB —— 服务器地址填错(指到一个会吐大页面的地址)时,
/// 一次请求就能在 12 秒内把内存吃光。
/// </summary>
private const long MaxResponseBytes = 4 * 1024 * 1024;
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
/// <summary>
/// 与 ClassHelper通信的 HttpClient。
///
/// **必须显式处理代理**:教室机器(以及开发机)常常配了系统代理,
/// 而 Windows 的代理设置默认连 `127.0.0.1` 也会走代理 —— 于是"填写令牌后立刻 HTTP 404",
/// 那个 404 其实是**代理自己的错误页**,跟本服务毫无关系。
/// 因此这里用 <see cref="LocalAwareProxy"/>:本地/内网地址直连,公网地址照旧走系统代理。
/// </summary>
private readonly HttpClient _http = new(new SocketsHttpHandler { Proxy = new LocalAwareProxy() })
{
Timeout = Timeout,
MaxResponseContentBufferSize = MaxResponseBytes,
};
public string LastError { get; private set; } = "";
public DateTimeOffset? LastSuccessAt { get; private set; }
/// <summary>
/// 包装系统代理:**本地/内网地址标记为"绕过"**,其余交给系统代理决定。
///
/// 判定为本地/内网的情形:localhost、回环地址、IPv4/IPv6 私有段与链路本地段,
/// 以及不含点的主机名(`server` / `classhelper` 这类校内机器名,DNS 也可能解析不出来)。
/// 判定为公网时保持原行为,避免"云服务器 + 公司代理"这种场景被我们改坏。
/// </summary>
private sealed class LocalAwareProxy : IWebProxy
{
private readonly IWebProxy _inner = HttpClient.DefaultProxy;
// 只读透传即可:HttpClient.DefaultProxy 是全局单例,改它的凭据会波及宿主进程里的其它请求
public ICredentials? Credentials { get; set; }
public Uri? GetProxy(Uri destination) => _inner.GetProxy(destination);
public bool IsBypassed(Uri host) => IsLocalHost(host) || _inner.IsBypassed(host);
/// <summary>该地址是否属于"不该走代理"的本地/内网范围。</summary>
internal static bool IsLocalHost(Uri uri)
{
var host = uri.Host;
if (host.Equals("localhost", StringComparison.OrdinalIgnoreCase)) return true;
// 不含点的主机名(校内机器名)走直连:解析成内网 IP 的可能性远大于公网
if (!host.Contains('.')) return true;
if (!IPAddress.TryParse(host, out var address)) return false;
if (IPAddress.IsLoopback(address)) return true;
if (address.AddressFamily == AddressFamily.InterNetwork)
{
var bytes = address.GetAddressBytes();
return bytes[0] == 10 // 10.0.0.0/8
|| (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) // 172.16.0.0/12
|| (bytes[0] == 192 && bytes[1] == 168) // 192.168.0.0/16
|| (bytes[0] == 169 && bytes[1] == 254); // 169.254.0.0/16(链路本地)
}
// IPv6:fc00::/7(唯一本地地址)与 fe80::/10(链路本地)
var first = address.GetAddressBytes()[0];
return (first & 0xFE) == 0xFC || (first & 0xC0) == 0x80;
}
}
/// <summary>拼接 API 地址,容忍用户填了带/不带末尾斜杠、甚至带 /api 后缀的地址。</summary>
private static string BuildUrl(string serverUrl, string path)
{
var baseUrl = (serverUrl ?? "").Trim().TrimEnd('/');
if (baseUrl.EndsWith("/api", StringComparison.OrdinalIgnoreCase))
{
baseUrl = baseUrl[..^4];
}
return $"{baseUrl}/api/integrations{path}";
}
private HttpRequestMessage BuildRequest(HttpMethod method, string serverUrl, string path, string token)
{
var request = new HttpRequestMessage(method, BuildUrl(serverUrl, path));
if (!string.IsNullOrWhiteSpace(token))
{
request.Headers.TryAddWithoutValidation("X-ClassIsland-Token", token);
}
return request;
}
private async Task<ApiEnvelope<T>?> SendAsync<T>(
HttpMethod method,
string serverUrl,
string path,
string token,
object? body,
CancellationToken cancellationToken)
{
try
{
using var request = BuildRequest(method, serverUrl, path, token);
if (body is not null)
{
var json = JsonSerializer.Serialize(body, JsonOptions);
request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
}
using var response = await _http.SendAsync(request, cancellationToken).ConfigureAwait(false);
var text = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
ApiEnvelope<T>? envelope = null;
try
{
envelope = JsonSerializer.Deserialize<ApiEnvelope<T>>(text, JsonOptions);
}
catch (JsonException)
{
// 非 JSON 响应(例如被网关拦截)——交给下面的兜底分支
}
if (!response.IsSuccessStatusCode)
{
var message = envelope?.Message;
if (string.IsNullOrWhiteSpace(message))
{
// 响应不是本服务的统一响应体:最常见的原因就是被系统代理 / 网关拦下来
// (典型表现:HTTP 404 且 body 是一张 HTML 错误页)。把 URL 一起报出来,
// 老师截图给我们就能一眼定位。
message = envelope is null
? $"HTTP {(int)response.StatusCode}({method.Method} {request.RequestUri})——" +
"响应不是 ClassHelper的标准格式,请检查服务器地址是否正确、" +
"或该系统代理是否拦截了内网请求"
: $"HTTP {(int)response.StatusCode}({method.Method} {request.RequestUri})";
}
LastError = message!;
return envelope ?? new ApiEnvelope<T> { Success = false, Message = message! };
}
if (envelope is null)
{
// 2xx 但响应不是本服务的统一响应体(网关/反代的 HTML 错误页、地址指到了别的服务等)。
// 必须留下原因:否则调用方拿到的是"成功但无数据 + 空错误消息",
// 设置页显示"连接异常"却没有原因,与上面专门为代理错误页写的诊断自相矛盾。
LastError =
$"HTTP {(int)response.StatusCode}({method.Method} {request.RequestUri})——" +
"响应不是 ClassHelper的标准格式,请检查服务器地址是否正确,或该系统代理是否拦截了内网请求";
return new ApiEnvelope<T> { Success = false, Message = LastError };
}
LastError = "";
LastSuccessAt = DateTimeOffset.Now;
return envelope;
}
catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested)
{
LastError = "请求超时(请检查服务器地址与网络)";
return null;
}
catch (HttpRequestException exception)
{
LastError = $"无法连接 ClassHelper服务:{exception.Message}";
return null;
}
catch (Exception exception)
{
LastError = exception.Message;
return null;
}
}
/// <summary>上报状态 +(可选)课表。</summary>
public async Task<(ApiCallResult Result, ReportResultDto? Data)> ReportAsync(
PluginSettings settings,
ReportRequestDto payload,
CancellationToken cancellationToken)
{
var envelope = await SendAsync<ReportResultDto>(
HttpMethod.Post, settings.ServerUrl, "/classisland/report", settings.DeviceToken, payload, cancellationToken);
if (envelope is null)
{
return (ApiCallResult.Offline(LastError), null);
}
if (!envelope.Success || envelope.Data is null)
{
return (ApiCallResult.Failure(envelope.Message.Length > 0 ? envelope.Message : LastError), null);
}
return (ApiCallResult.Success(envelope.Message), envelope.Data);
}
/// <summary>拉取尚未确认的下发提醒(插件启动/重连时补齐)。</summary>
public async Task<(ApiCallResult Result, List<PushNotificationDto> Items)> PendingAsync(
PluginSettings settings,
CancellationToken cancellationToken)
{
var envelope = await SendAsync<PendingResultDto>(
HttpMethod.Get, settings.ServerUrl, "/classisland/pending", settings.DeviceToken, null, cancellationToken);
if (envelope is null) return (ApiCallResult.Offline(LastError), new List<PushNotificationDto>());
if (!envelope.Success || envelope.Data is null)
{
return (ApiCallResult.Failure(envelope.Message.Length > 0 ? envelope.Message : LastError),
new List<PushNotificationDto>());
}
return (ApiCallResult.Success(envelope.Message), envelope.Data.Notifications);
}
/// <summary>确认提醒已弹出(之后服务端不再补发)。</summary>
public async Task<ApiCallResult> AckAsync(PluginSettings settings, string id, CancellationToken cancellationToken)
{
var envelope = await SendAsync<JsonElement>(
HttpMethod.Post, settings.ServerUrl, "/classisland/ack", settings.DeviceToken, new { id }, cancellationToken);
if (envelope is null) return ApiCallResult.Offline(LastError);
return envelope.Success
? ApiCallResult.Success("已确认")
: ApiCallResult.Failure(envelope.Message.Length > 0 ? envelope.Message : LastError);
}
/// <summary>拉取班级课表(用于镜像回 ClassIsland)。未开启镜像时服务端返回 data=null。</summary>
public async Task<(ApiCallResult Result, ClassPlanMirrorDto? Plan)> PullClassPlanAsync(
PluginSettings settings,
CancellationToken cancellationToken)
{
var envelope = await SendAsync<PullResultDto>(
HttpMethod.Get, settings.ServerUrl, "/classisland/class-plan", settings.DeviceToken, null, cancellationToken);
if (envelope is null) return (ApiCallResult.Offline(LastError), null);
if (!envelope.Success)
{
return (ApiCallResult.Failure(envelope.Message.Length > 0 ? envelope.Message : LastError), null);
}
if (envelope.Data?.ClassPlan is null)
{
return (ApiCallResult.Failure(envelope.Message.Length > 0
? envelope.Message
: "该设备未开启「把班级课表镜像到 ClassIsland」"), null);
}
return (ApiCallResult.Success(envelope.Message), envelope.Data.ClassPlan);
}
public void Dispose() => _http.Dispose();
}
@@ -1,159 +0,0 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace ClassHelper.ClassIslandPlugin.Models;
/// <summary>
/// 插件设置。
///
/// 存储由 ClassIsland 负责:插件入口把它保存在 <c>PluginConfigFolder/Settings.json</c>
/// (**不要**放在插件安装目录,那里不会随档案备份、升级时还会被清掉)。
/// 因此这里必须继承 <see cref="ObservableObject"/> 并让每个属性都走 <c>SetProperty</c>:
/// ClassIsland 通过监听 <c>PropertyChanged</c> 来即时保存。
/// </summary>
public class PluginSettings : ObservableObject
{
private string _serverUrl = "http://127.0.0.1:4000";
private string _deviceToken = "";
private string _deviceKey = "";
private bool _autoReport = true;
private int _reportIntervalSeconds = 60;
// 课表同步(2026-10-11 起):**两个方向都只由 Web 端的一次性动作触发** ——
// 「从教室机器获取课表」与「下发课表到教室」,都走服务端的一个待办标记。
// 原先这里有两个开关(自动回传 / 自动镜像),默认 15 秒一轮,结果是服务端与教室里
// 的课表每 15 秒互相覆盖一次,老师看到的就是"课表被反复删改"。
// 定时上报现在**只报运行状态**(当前上什么课),不带课表。
private bool _receiveNotifications = true;
private int _notificationDurationSeconds = 8;
private int _notificationPollSeconds = 10;
private bool _speechEnabled = false;
private bool _showDebugInfo = false;
/// <summary>
/// ClassHelper后端地址,例如 <c>http://127.0.0.1:4000</c>。
/// </summary>
public string ServerUrl
{
get => _serverUrl;
set => SetProperty(ref _serverUrl, value);
}
/// <summary>
/// 设备令牌(形如 <c>chci_...</c>):在 ClassHelper Web 端「ClassIsland 联动」页面生成。
/// </summary>
public string DeviceToken
{
get => _deviceToken;
// 在 setter 里就去掉首尾空白:粘贴令牌时带前导空格非常常见,
// 而 Normalize() 只在启动加载时跑一次 —— 运行期粘进来的脏值会让 IsConfigured
// 一直为 false,用户看着明明填好了却查不出原因。
set => SetProperty(ref _deviceToken, (value ?? "").Trim());
}
/// <summary>
/// 本机标识(首次生成后固定):服务端据此把同一台机器识别为同一设备,重装插件不会产生重复设备。
/// </summary>
public string DeviceKey
{
get => _deviceKey;
set => SetProperty(ref _deviceKey, value);
}
/// <summary>
/// 是否自动上报:启动后、课表变化时、以及每隔 <see cref="ReportIntervalSeconds"/> 秒各上报一次。
/// </summary>
public bool AutoReport
{
get => _autoReport;
set => SetProperty(ref _autoReport, value);
}
/// <summary>
/// 定时上报间隔(秒),最小 15 秒。
/// </summary>
public int ReportIntervalSeconds
{
get => _reportIntervalSeconds;
set => SetProperty(ref _reportIntervalSeconds, Math.Clamp(value, 15, 3600));
}
/// <summary>
/// 是否接收老师在 ClassHelper上发布的提醒,并在 ClassIsland 上弹出。
/// </summary>
public bool ReceiveNotifications
{
get => _receiveNotifications;
set => SetProperty(ref _receiveNotifications, value);
}
/// <summary>
/// 提醒轮询间隔(秒),最小 5 秒。
///
/// 插件与后端之间没有长连接(刻意不引入 Socket 依赖),提醒是"轮询取回"的,
/// 因此这个值就是**老师按下发送到教室弹出之间的最大延迟**。
/// 单独一个轻量轮询(只查待提醒,不上传课表)比把上报间隔改小划算得多。
/// </summary>
public int NotificationPollSeconds
{
get => _notificationPollSeconds;
set => SetProperty(ref _notificationPollSeconds, Math.Clamp(value, 5, 600));
}
/// <summary>
/// 默认提醒显示时长(秒);老师在下发时可以单独指定更长的时长。
/// </summary>
public int NotificationDurationSeconds
{
get => _notificationDurationSeconds;
set => SetProperty(ref _notificationDurationSeconds, Math.Clamp(value, 1, 120));
}
/// <summary>
/// 提醒弹出时是否语音朗读(沿用 ClassIsland 的语音设置与语音提供方)。
/// </summary>
public bool SpeechEnabled
{
get => _speechEnabled;
set => SetProperty(ref _speechEnabled, value);
}
/// <summary>
/// 是否在设置页显示调试信息(最后一次上报结果、课表条目数等),排查问题时打开。
/// </summary>
public bool ShowDebugInfo
{
get => _showDebugInfo;
set => SetProperty(ref _showDebugInfo, value);
}
/// <summary>
/// 兼容旧配置:反序列化后把 DeviceKey 补齐(首次运行时由服务生成)。
/// </summary>
public void Normalize()
{
ServerUrl = (ServerUrl ?? "").Trim().TrimEnd('/');
DeviceToken = (DeviceToken ?? "").Trim();
DeviceKey = (DeviceKey ?? "").Trim();
ReportIntervalSeconds = Math.Clamp(ReportIntervalSeconds, 15, 3600);
NotificationDurationSeconds = Math.Clamp(NotificationDurationSeconds, 1, 120);
NotificationPollSeconds = Math.Clamp(NotificationPollSeconds, 5, 600);
}
/// <summary>是否已经配置好(地址 + 令牌都填了)。</summary>
public bool IsConfigured =>
TryGetServerUri(out _) && DeviceToken.StartsWith("chci_", StringComparison.Ordinal);
/// <summary>
/// 解析服务器地址,**只接受 http/https 绝对地址**。
///
/// 不用裸的 `Uri.TryCreate(..., UriKind.Absolute)`:它会接受 `file://` / `ftp://`,
/// 那种地址会在发请求时抛一句难以理解的 NotSupportedException,用户根本猜不到是地址填错了。
/// </summary>
public bool TryGetServerUri(out Uri uri)
{
uri = null!;
if (!Uri.TryCreate((ServerUrl ?? "").Trim(), UriKind.Absolute, out var parsed)) return false;
if (parsed.Scheme != Uri.UriSchemeHttp && parsed.Scheme != Uri.UriSchemeHttps) return false;
uri = parsed;
return true;
}
}
-171
View File
@@ -1,171 +0,0 @@
using System.Text.Json;
using ClassHelper.ClassIslandPlugin.Models;
using ClassHelper.ClassIslandPlugin.Services;
using ClassHelper.ClassIslandPlugin.Views;
using ClassIsland.Core;
using ClassIsland.Core.Abstractions;
using ClassIsland.Core.Abstractions.Services;
using ClassIsland.Core.Attributes;
using ClassIsland.Core.Extensions.Registry;
using ClassIsland.Shared;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ClassHelper.ClassIslandPlugin;
/// <summary>
/// 插件入口。
///
/// 职责只有三件:读配置 → 注册扩展(提醒提供方 / 设置页 / 联动服务)→ 在应用启动后接上课程服务。
/// 真正的联动逻辑都在 <see cref="BridgeService"/> 里,入口保持"看一眼就知道装了哪些东西"。
/// </summary>
[PluginEntrance]
public class Plugin : PluginBase
{
/// <summary>插件设置文件名。存在 <see cref="PluginBase.PluginConfigFolder"/> 下:随档案备份走,升级插件不丢。</summary>
private const string SettingsFileName = "Settings.json";
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
/// <summary>插件设置。注册成单例后,设置页与 <see cref="BridgeService"/> 拿到的是同一个对象。</summary>
public PluginSettings Settings { get; private set; } = new();
/// <summary>联动只接一次(AppStarted 与"运行中启用"两条路都会走到这里)</summary>
private bool _bridgeStarted;
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
Settings = LoadSettings();
// 设置页与联动服务共用一个实例:设置页改了值,服务立刻能看到(不需要重启 ClassIsland)
services.AddSingleton(Settings);
services.AddSingleton<BridgeService>();
services.AddSettingsPage<BridgeSettingsPage>();
services.AddNotificationProvider<ClassHelperNotificationProvider>();
// 初始化阶段课程服务还没准备好(它在主机启动流程里才被创建),
// 因此这里先挂一个"应用已启动"的回调,等到那时再取 ILessonsService 并开始上报。
var application = AppBase.Current;
if (application is null)
{
Logger?.LogError("ClassHelper 联动:拿不到 ClassIsland 应用实例,联动未启动");
return;
}
application.AppStarted += (_, _) => StartBridge();
// 插件是"运行中才被启用"时,AppStarted 早就过去了 —— 主窗口已经存在就直接接一次
if (application.MainWindow is not null) StartBridge();
}
private void StartBridge()
{
if (_bridgeStarted) return;
try
{
var lessons = IAppHost.TryGetService<ILessonsService>();
if (lessons is null)
{
Logger?.LogError("ClassHelper 联动:拿不到课程服务,联动已停用");
return;
}
var bridge = IAppHost.TryGetService<BridgeService>();
if (bridge is null)
{
Logger?.LogError("ClassHelper 联动:拿不到联动服务,联动已停用");
return;
}
_bridgeStarted = true;
bridge.Attach(lessons);
bridge.RestartTimer();
// 应用刚起来时还没有第一个上报点,先主动拉一次未弹出的提醒(离线期间老师发的通知):
// 不这么做的话,最长要等一个上报间隔才会弹出来
_ = bridge.PullPendingAsync();
Logger?.LogInformation("ClassHelper 联动:已接入课程服务(服务器 {Server})", Settings.ServerUrl);
}
catch (Exception exception)
{
// 联动失败绝不能把 ClassIsland 本体拖下水
Logger?.LogError(exception, "ClassHelper 联动:初始化联动服务失败");
}
}
private ILogger<Plugin>? Logger => IAppHost.TryGetService<ILogger<Plugin>>();
/// <summary>
/// 读取设置。首次运行时 <c>DeviceKey</c> 为空,这里补一个随机值并立即落盘 ——
/// 服务端用它把同一台机器识别为同一设备,重装插件不会堆出重复设备。
/// </summary>
private PluginSettings LoadSettings()
{
var path = Path.Combine(PluginConfigFolder, SettingsFileName);
var settings = new PluginSettings();
try
{
if (File.Exists(path))
{
var loaded = JsonSerializer.Deserialize<PluginSettings>(File.ReadAllText(path), JsonOptions);
if (loaded is not null) settings = loaded;
}
}
catch (Exception exception)
{
// 配置损坏不该拦住插件加载:用默认值继续,原文件保留供排查
IAppHost.TryGetService<ILogger<Plugin>>()?.LogWarning(exception,
"ClassHelper 联动:读取设置失败,已回退到默认设置({Path})", path);
}
var needGenerateKey = string.IsNullOrWhiteSpace(settings.DeviceKey);
settings.Normalize();
if (needGenerateKey)
{
// 机器名 + 随机短码:既是人眼可读的"这台机器",又不会两台同名机器撞车。
// 注意长度:原先写的是 `[..Math.Min(24, machine.Length + 33)]`,而 machine.Length + 33
// 恒大于 24,所以实际**永远只取前 24 个字符** —— 机器名稍长就把随机段整个切掉,
// "同名机器不撞车"的保障就没了。这里改成"机器名按需截短 + 保留 8 位随机段"。
var machine = Environment.MachineName.ToLowerInvariant();
var suffix = Guid.NewGuid().ToString("N")[..8];
var maxMachineLength = Math.Max(4, 24 - suffix.Length - 1);
if (machine.Length > maxMachineLength) machine = machine[..maxMachineLength];
settings.DeviceKey = $"{machine}-{suffix}";
}
Settings = settings;
// 落盘:一是固定首次生成的 DeviceKey,二是把缺字段的旧配置补齐成完整文件
SaveSettings(settings, path);
// 设置变化时即时保存
settings.PropertyChanged += (_, _) => SaveSettings(settings, path);
return settings;
}
private static void SaveSettings(PluginSettings settings, string path)
{
try
{
var folder = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(folder)) Directory.CreateDirectory(folder);
// 先写临时文件再原子替换。
//
// 设置页的地址/令牌输入框是 TwoWay 绑定(逐字符提交),直接 `File.WriteAllText`
// 会就地截断原文件;一旦此刻进程被杀或断电,留下的是半截 JSON,而 LoadSettings 的
// catch 会**静默回退到默认设置** —— 用户看到的是"令牌和地址莫名其妙没了",
// 而且原文件已被覆盖,无从恢复。
var temp = path + ".tmp";
File.WriteAllText(temp, JsonSerializer.Serialize(settings, JsonOptions));
File.Move(temp, path, overwrite: true);
}
catch (Exception exception)
{
IAppHost.TryGetService<ILogger<Plugin>>()?.LogWarning(exception,
"ClassHelper 联动:保存设置失败({Path})", path);
}
}
}
@@ -1,647 +0,0 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using Avalonia.Threading;
using ClassHelper.ClassIslandPlugin.Interop;
using ClassHelper.ClassIslandPlugin.Models;
using ClassIsland.Core;
using ClassIsland.Core.Abstractions.Services;
using ClassIsland.Core.Models.Notification;
using ClassIsland.Shared;
using Microsoft.Extensions.Logging;
namespace ClassHelper.ClassIslandPlugin.Services;
/// <summary>
/// 联动主循环。三件事:
/// 1. <b>上报</b>:应用启动后、课程事件(上课/下课/放学/状态变化)发生时、以及每 N 秒,
/// 把"当前上什么课"与(可选的)全量课表推给 ClassHelper;
/// 2. <b>接收</b>:每次上报的返回值里带一条"尚未确认的下发提醒",
/// 交给 <see cref="ClassHelperNotificationProvider"/> 在 ClassIsland 上弹出;
/// 3. <b>镜像</b>:开启镜像开关时,把 ClassHelper上排好的课表写回 ClassIsland 档案。
///
/// 为什么用"上报即拉取"而不是长连接:
/// 插件不需要额外的 Socket/WebSocket 依赖(避免程序集隔离带来的加载问题),
/// 而教室机器的上报间隔本身就是心跳 —— 顺路把待提醒带回来,依赖更少、故障面更小。
///
/// 线程约定:HttpClient 回调在线程池上,因此所有跨线程可见的状态都用 <c>lock</c> 或
/// 赋值引用(<c>string</c> / <c>int</c>)保护,属性变化通过 <see cref="PropertyChanged"/> 通知设置页。
/// </summary>
public sealed class BridgeService : INotifyPropertyChanged, IDisposable
{
private readonly PluginSettings _settings;
private readonly ILogger<BridgeService> _logger;
private readonly ClassHelperClient _client = new();
private readonly object _gate = new();
private ILessonsService? _lessons;
private Timer? _timer;
private Timer? _notifyTimer;
private bool _disposed;
private bool _reporting;
private bool _pulling;
private bool _eventsHooked;
/// <summary>
/// 上次成功镜像的课表内容指纹。内容没变就完全跳过镜像:既省掉每分钟一次的全量重建 + 落盘,
/// 也把"跨线程改档案"的窗口从"每分钟一次"降回"只在课表真的变化时"。
/// </summary>
private volatile string? _lastMirrorSignature;
public BridgeService(PluginSettings settings, ILogger<BridgeService> logger)
{
_settings = settings;
_logger = logger;
}
public event PropertyChangedEventHandler? PropertyChanged;
/// <summary>上报结果变化时触发(设置页据此刷新)。</summary>
public event EventHandler? StateChanged;
/// <summary>需要把提醒丢给提醒提供方去显示。</summary>
public event EventHandler<PushNotificationDto>? NotificationReceived;
/* ---------------------------------------------------------------- 供设置页绑定的状态 */
private string _lastReportMessage = "尚未上报";
/// <summary>最近一次上报的结果描述。</summary>
public string LastReportMessage
{
get => _lastReportMessage;
private set => SetField(ref _lastReportMessage, value);
}
private bool _lastReportOk;
public bool LastReportOk
{
get => _lastReportOk;
private set => SetField(ref _lastReportOk, value);
}
private DateTimeOffset? _lastReportAt;
public DateTimeOffset? LastReportAt
{
get => _lastReportAt;
private set
{
if (SetField(ref _lastReportAt, value)) Raise(nameof(LastReportAtText));
}
}
/// <summary>供界面直接显示的"最后上报时间"。</summary>
public string LastReportAtText => LastReportAt is null
? "从未"
: LastReportAt.Value.LocalDateTime.ToString("yyyy-MM-dd HH:mm:ss");
private int _lastScheduleEntryCount;
/// <summary>最近一次上报里的课表条目数。</summary>
public int LastScheduleEntryCount
{
get => _lastScheduleEntryCount;
private set => SetField(ref _lastScheduleEntryCount, value);
}
private int _lastTimeLayoutItemCount;
/// <summary>最近一次上报里的节次数量。</summary>
public int LastTimeLayoutItemCount
{
get => _lastTimeLayoutItemCount;
private set => SetField(ref _lastTimeLayoutItemCount, value);
}
private int? _lastServerWeek;
/// <summary>服务端返回的教学周。</summary>
public int? LastServerWeek
{
get => _lastServerWeek;
private set
{
if (SetField(ref _lastServerWeek, value)) Raise(nameof(ClientTimeOffsetText));
}
}
private int _notificationCount;
/// <summary>已弹出并回执的提醒数量。</summary>
public int NotificationCount
{
get => _notificationCount;
private set => SetField(ref _notificationCount, value);
}
private bool _busy;
/// <summary>是否正在上报("立即上报"按钮据此禁用)。</summary>
public bool Busy
{
get => _busy;
private set => SetField(ref _busy, value);
}
private TimeSpan? _serverTimeOffset;
/// <summary>服务端与本机的时钟差(诊断用:差得多说明教室机器时间不对)。</summary>
public string ClientTimeOffsetText => _serverTimeOffset is null
? "—"
: $"{_serverTimeOffset.Value.TotalSeconds:+0;-0;0} 秒";
/// <summary>当前配置是否完整(设置页据此提示"还没填令牌")。</summary>
public bool IsConfigured => _settings.IsConfigured;
/// <summary>是否已接入课程服务(拿到 ILessonsService 才算真正跑起来)。</summary>
public bool IsAttached
{
get { lock (_gate) return _lessons is not null; }
}
/* ---------------------------------------------------------------- 生命周期 */
/// <summary>接入课程服务并订阅课程事件(由插件入口在 AppStarted 时调用)。</summary>
public void Attach(ILessonsService lessons)
{
lock (_gate)
{
_lessons = lessons;
}
if (!_eventsHooked)
{
// 上课 / 下课 / 放学 / 状态变化时立刻上报一次,不等到下一个定时点。
// 这些事件在 ClassIsland 的公开约定里是在**主线程**触发的,可以直接订阅。
lessons.OnClass += (_, _) => RequestReport("上课");
lessons.OnBreakingTime += (_, _) => RequestReport("下课");
lessons.OnAfterSchool += (_, _) => RequestReport("放学");
lessons.CurrentTimeStateChanged += (_, _) => RequestReport("状态变化");
_eventsHooked = true;
}
Raise(nameof(IsAttached));
_logger.LogInformation("ClassHelper 联动:已订阅课程事件");
RequestReport("应用启动");
}
/// <summary>按设置重建定时器(设置页改间隔后调用)。</summary>
public void RestartTimer()
{
lock (_gate)
{
_timer?.Dispose();
_timer = null;
_notifyTimer?.Dispose();
_notifyTimer = null;
if (!_settings.IsConfigured) return;
if (_settings.AutoReport)
{
var interval = TimeSpan.FromSeconds(Math.Clamp(_settings.ReportIntervalSeconds, 15, 3600));
_timer = new Timer(_ => RequestReport("定时"), null, interval, interval);
}
// 提醒单独用一个轻量轮询(只查待提醒,不上传课表):
// 老师按下发送到教室弹出之间的延迟就是这个间隔,因此默认 10 秒,不跟随上报间隔。
if (_settings.ReceiveNotifications)
{
var poll = TimeSpan.FromSeconds(Math.Clamp(_settings.NotificationPollSeconds, 5, 600));
_notifyTimer = new Timer(_ => _ = PullPendingAsync(), null, poll, poll);
}
}
}
/// <summary>
/// 发起一次**仅状态**的上报(定时器与课程事件都走这里)。
///
/// 刻意不带课表:课表只在服务端显式点「从教室机器获取课表」时上传(见 <see cref="ReportAsync"/>
/// 的 <c>forceSchedule</c>)。原先每次上报都带全量课表、默认 15 秒一次,服务端于是每 15 秒
/// merge + 清理一次幽灵行 —— 老师看到的就是"课表被反复删改"(2026-10-11 实测)。
/// </summary>
public void RequestReport(string reason)
{
_ = ReportAsync(reason, includeSchedule: false);
}
/// <summary>
/// 执行一次上报并返回是否真的发出去了。
/// <paramref name="includeSchedule"/> 为 true 时带上全量课表与节次时间。
/// </summary>
public async Task<bool> ReportAsync(string reason, bool includeSchedule = true, bool forceSchedule = false)
{
if (_disposed) return false;
ILessonsService? lessons;
lock (_gate) lessons = _lessons;
if (lessons is null) return false;
if (!_settings.IsConfigured)
{
SetState(false, "尚未配置服务器地址或设备令牌", 0, 0, null);
return false;
}
lock (_gate)
{
if (_reporting) return false;
_reporting = true;
}
Busy = true;
try
{
var profile = ResolveProfile();
var request = new ReportRequestDto
{
PluginVersion = PluginVersion,
ClassIslandVersion = SafeAppVersion(),
// 机器码:设备创建时服务端只能用 pending-… 占位,靠这里回填,Web 端设备列表才能与教室机器对上
DeviceKey = _settings.DeviceKey,
State = BuildState(lessons),
};
var entryCount = 0;
var layoutCount = 0;
// 课表**只在服务端显式请求时**上传:没有"本机自动回传"这条路径了
// (原先由本机 `UploadSchedule` 开关决定,默认开 + 定时 15 秒 = 服务端课表被反复 merge)。
// forceSchedule:服务端点了「从教室机器获取课表」,这是一次人工请求。
var uploadSchedule = forceSchedule;
if (includeSchedule && !uploadSchedule)
{
_logger.LogInformation("ClassHelper 联动:本次只上报运行状态;课表由 Web 端点「从教室机器获取课表」时才会拉取");
}
if (includeSchedule && uploadSchedule && profile is not null)
{
var entries = ScheduleMapper.MapAllClassPlans(profile, out var warnings);
foreach (var warning in warnings) _logger.LogWarning("ClassHelper 联动:{Warning}", warning);
entryCount = entries.Count;
request.Schedule = new SchedulePayloadDto { Mode = "merge", Entries = entries };
// 课表为空时不发(否则会把服务端已有课表"合并"成空),但**必须把原因写清楚**:
// 日志里只出现"仅状态"时,用户会以为上报失败,实际是 ClassIsland 里还没有课表。
if (entries.Count == 0)
{
request.Schedule = null;
_logger.LogWarning(
"ClassHelper 联动:ClassIsland 里没有**启用的课表**(0 条),本次未上报课表。" +
"请在 ClassIsland 里排好课表,或在 Web 端打开「镜像课表」由 ClassHelper下发一份");
}
var layout = ResolvePrimaryTimeLayout(profile);
if (layout is not null)
{
var items = ScheduleMapper.MapTimeLayout(layout);
layoutCount = items.Count;
request.TimeLayout = new TimeLayoutPayloadDto
{
Name = ScheduleMapper.Truncate(
string.IsNullOrWhiteSpace(layout.Name) ? "ClassIsland 时间表" : layout.Name,
ScheduleMapper.PlanNameMaxLength)!,
Mode = "replace",
Items = items,
};
}
}
var (result, data) = await _client.ReportAsync(_settings, request, CancellationToken.None)
.ConfigureAwait(false);
if (!result.Ok || data is null)
{
_logger.LogWarning("ClassHelper 联动上报失败({Reason}):{Message}", reason, result.Message);
SetState(false, result.Message, entryCount, layoutCount, null);
return false;
}
LastServerWeek = data.Week;
UpdateClockOffset(data.ServerTime);
if (data.ScheduleApplied)
{
_logger.LogInformation(
"ClassHelper 联动:课表已同步(新增 {Created} / 更新 {Updated})",
data.ScheduleCreated, data.ScheduleUpdated);
}
var detail = entryCount > 0
? $"课表 {entryCount} 节 / 节次 {layoutCount} 条"
: uploadSchedule
? "仅状态(ClassIsland 里还没有启用的课表)"
: "仅状态(本机「上报课表到 ClassHelper」开关已关闭)";
SetState(true, $"上报成功({reason}):{detail},服务端第 {data.Week} 周",
entryCount, layoutCount, data.Week);
// 顺路把"还没弹出过的"提醒带回来
var pending = data.PendingNotification;
if (pending is not null && _settings.ReceiveNotifications)
{
NotificationReceived?.Invoke(this, pending);
}
// 服务端请求"立刻上报一次课表"(老师在 Web 端点了「从教室机器获取课表」)。
// 放在镜像之前:先把教室的现状推上去,再做服务端→教室的镜像,顺序反了会把刚拿到的课表盖掉。
if (data.Settings?.ScheduleRequested == true && !uploadSchedule)
{
_logger.LogInformation("ClassHelper 联动:服务端请求立即上报课表,正在补发一次…");
_ = ReportAsync("服务端请求课表", includeSchedule: true, forceSchedule: true);
}
// 只有服务端点了「下发课表到教室」才镜像。原先跟着**每一次上报**走(本机 MirrorSchedule
// 开关 + 默认 15 秒周期),教室的课表被反复重写 —— 与服务端那边的 merge/清理叠在一起,
// 就是老师反馈的"课表一直在变"。现在是一次性待办,拉取成功由服务端清标记。
if (data.Settings?.MirrorRequested == true)
{
_logger.LogInformation("ClassHelper 联动:服务端请求下发课表,正在拉取并强制替换教室课表…");
await MirrorScheduleAsync().ConfigureAwait(false);
}
return true;
}
catch (Exception exception)
{
// ReportAsync 是通过 `_ = ReportAsync(reason)` 这种 fire-and-forget 方式发起的
// (事件回调与定时器都是),没有这个 catch,中途抛出的异常(例如跨线程改档案时的
// "Collection was modified")会被 unobserved task 静默吞掉:日志里一条都没有,
// 而 LastReportMessage 还停在上一次的成功结果,用户以为一切正常。
_logger.LogError(exception, "ClassHelper 联动:上报异常({Reason})", reason);
SetState(false, $"上报异常:{exception.Message}", 0, 0, null);
return false;
}
finally
{
Busy = false;
lock (_gate) _reporting = false;
}
}
/// <summary>
/// 拉取本班尚未弹出过的提醒并逐条交给提醒提供方(用于"应用刚起来还没到第一个上报点"的场景)。
/// </summary>
public async Task PullPendingAsync()
{
if (_disposed) return;
if (!_settings.IsConfigured || !_settings.ReceiveNotifications) return;
// 轮询与"上报顺路拉取"可能同时到达:同一时刻只放一个请求过去
lock (_gate)
{
if (_pulling) return;
_pulling = true;
}
try
{
var (result, items) = await _client.PendingAsync(_settings, CancellationToken.None).ConfigureAwait(false);
if (!result.Ok)
{
_logger.LogInformation("ClassHelper 联动:拉取待提醒失败({Message})", result.Message);
return;
}
foreach (var item in items)
{
_logger.LogInformation("ClassHelper 联动:取到待弹出提醒「{Title}」(id={Id})", item.Title, item.Id);
NotificationReceived?.Invoke(this, item);
}
}
finally
{
lock (_gate) _pulling = false;
}
}
/// <summary>把服务端的一条提醒标记为已弹出。</summary>
public async Task AckAsync(string id)
{
var result = await _client.AckAsync(_settings, id, CancellationToken.None).ConfigureAwait(false);
if (result.Ok)
{
NotificationCount += 1;
_logger.LogInformation("ClassHelper 联动:已确认提醒 {Id}", id);
}
else
{
// 回执失败无妨:服务端会按 24 小时有效期补发,最坏是重复弹一次
_logger.LogWarning("ClassHelper 联动:确认提醒失败 {Message}", result.Message);
}
}
/// <summary>把 ClassHelper上排好的课表写回 ClassIsland(新建带前缀的档案课表,不动老师原有的课表)。</summary>
public async Task MirrorScheduleAsync()
{
var profile = ResolveProfile();
if (profile is null) return;
var (result, plan) = await _client.PullClassPlanAsync(_settings, CancellationToken.None).ConfigureAwait(false);
if (!result.Ok || plan is null)
{
// 服务端在"镜像开关没开"时会返回 data=null —— 这不是错误,但要告诉用户去哪儿开
_logger.LogInformation(
"ClassHelper 联动:跳过课表镜像({Message})。" +
"需要在 Web 端「ClassIsland 联动」页给这台设备打开「镜像课表」,然后点一次「立即上报」或等下一个上报周期",
result.Message);
return;
}
// 内容没变就直接返回:上报是"启动 + 每个课程事件 + 每 N 秒"触发的,原先每次都要
// 重建全部课表对象并整体落盘 —— 无谓的网络/磁盘 I/O,还会把档案页刷得不停重绘。
var signature = MirrorSignature(plan);
if (signature == _lastMirrorSignature)
{
_logger.LogDebug("ClassHelper 联动:课表内容与上次一致,跳过镜像");
return;
}
try
{
// **必须在 UI 线程上改写档案**:ClassIsland 的档案是 ObservableDictionary /
// ObservableCollection,落盘是"属性变化即整体序列化 + FileStream 就地截断"。
// 而本方法是从线程池线程继续执行的(ReportAsync 里 ConfigureAwait(false) 之后,
// 定时器回调本就在线程池上),在线程池上改集合会与 UI 线程的保存/绑定并发:
// 轻则 InvalidOperationException(Collection was modified),重则两次写入互相截断,
// **把整个档案写成半截 JSON**(老师的课表/科目全丢,只能靠 .bak 兜底)。
var outcome = await Dispatcher.UIThread.InvokeAsync(() =>
{
var applied = ClassPlanWriter.Apply(profile, plan, force: true);
if (!applied.Applied)
{
return applied;
}
// 改写的是 Profile 里的集合,ClassIsland 会靠 INotifyCollectionChanged 落盘;
// 这里显式 SaveProfile() 是为了"打开开关马上就能在课表里看到",不用等下一次自动保存。
IAppHost.TryGetService<IProfileService>()?.SaveProfile();
return applied;
});
if (!outcome.Applied)
{
_logger.LogInformation("ClassHelper 联动:课表镜像未生效({Reason})",
outcome.Warnings.FirstOrDefault() ?? "服务端课表为空");
return;
}
_lastMirrorSignature = signature;
_logger.LogInformation("ClassHelper 联动:已把班级课表写入 ClassIsland({Plans})",
string.Join("、", outcome.PlanNames.Select(name => $"「{name}」")));
foreach (var warning in outcome.Warnings)
{
_logger.LogWarning("ClassHelper 联动镜像提示:{Warning}", warning);
}
}
catch (Exception exception)
{
_logger.LogError(exception, "ClassHelper 联动:课表镜像失败");
}
}
/// <summary>镜像载荷的内容指纹(只用于"内容没变就跳过",不参与任何业务判断)</summary>
private static string MirrorSignature(ClassPlanMirrorDto plan)
{
var builder = new StringBuilder();
foreach (var entry in plan.Entries)
{
builder.Append(entry.WeekDay).Append('|').Append(entry.WeekCountDiv).Append('|')
.Append(entry.WeekCountDivTotal).Append('|').Append(entry.Subject).Append('|')
.Append(entry.StartTime).Append('|').Append(entry.EndTime).Append(';');
}
foreach (var layout in plan.TimeLayouts)
{
builder.Append('#').Append(layout.Id).Append(':');
foreach (var item in layout.Layouts)
{
builder.Append(item.StartTime).Append('-').Append(item.EndTime).Append('@')
.Append(item.TimeType).Append(',');
}
}
return builder.ToString();
}
/* ---------------------------------------------------------------- 内部实现 */
/// <summary>插件版本(与 manifest.yml / csproj 保持一致)。</summary>
private const string PluginVersion = "1.3.2.0";
/// <summary>ClassIsland 版本读不到时不该让上报失败(开发版可能为 null)。</summary>
private static string SafeAppVersion()
{
try
{
return AppBase.AppVersion ?? "";
}
catch
{
return "";
}
}
/// <summary>
/// 取得当前状态快照。
/// <c>CurrentTimeLayoutItem</c> 在"没有课表"时是 <see cref="ClassIsland.Shared.Models.Profile.TimeLayoutItem.Empty"/>,
/// 语义上等价于"没有节次",因此要转成 null 而不是 00:00。
/// </summary>
private StateDto BuildState(ILessonsService lessons)
{
try
{
return ScheduleMapper.BuildState(lessons, LastServerWeek);
}
catch (Exception exception)
{
// 课程服务在"应用启动中/课表未加载"时可能抛异常,这里降级为只有心跳的上报
_logger.LogWarning(exception, "ClassHelper 联动:读取课程状态失败,本次只上报心跳");
return new StateDto { ClientTime = DateTimeOffset.Now.ToString("o") };
}
}
/// <summary>
/// 选一份"最有代表性"的时间表上报给 ClassHelper:**上课点最多的那一份**。
///
/// 为什么不按"当前课表"选:镜像会给每个(星期 + 单双周)建一份时间表,
/// 于是"今天"那一份可能只有一两节课 —— 按当前课表选就会把只有一节的时间表报上去,
/// 服务端那边的节次时间表就退化了。取上课点最多的那份,得到的是完整作息。
/// 并列时优先"每周"型(单双周的两份内容一致,每周型更通用)。
/// </summary>
private static ClassIsland.Shared.Models.Profile.TimeLayout? ResolvePrimaryTimeLayout(
ClassIsland.Shared.Models.Profile.Profile profile)
{
if (profile.TimeLayouts.Count == 0) return null;
var best = profile.TimeLayouts
.Select(pair => (pair.Value, ClassPoints: pair.Value.Layouts.Count(item => item.TimeType == 0)))
.Where(item => item.ClassPoints > 0)
.OrderByDescending(item => item.ClassPoints)
.ToList();
if (best.Count > 0) return best[0].Value;
// 兜底:档案里被激活的时间表,最后才是任意一个
return profile.TimeLayouts.Values.FirstOrDefault(item => item.IsActivated)
?? profile.TimeLayouts.Values.First();
}
private static ClassIsland.Shared.Models.Profile.ClassPlan? CurrentClassPlan(
ClassIsland.Shared.Models.Profile.Profile profile)
{
// 用课程服务拿"今天该上哪张课表"最准
try
{
var lessons = IAppHost.TryGetService<ILessonsService>();
return lessons?.CurrentClassPlan;
}
catch
{
return null;
}
}
private ClassIsland.Shared.Models.Profile.Profile? ResolveProfile()
{
try
{
// 档案由 ProfileService 持有;这里用 TryGetService 避免服务未注册时抛异常
return IAppHost.TryGetService<IProfileService>()?.Profile;
}
catch (Exception exception)
{
_logger.LogWarning(exception, "ClassHelper 联动:读取档案失败");
return null;
}
}
/// <summary>用服务端时间校准本机时钟差(只影响设置页展示,不改系统时间)。</summary>
private void UpdateClockOffset(string serverTime)
{
if (!DateTimeOffset.TryParse(serverTime, out var parsed)) return;
_serverTimeOffset = parsed - DateTimeOffset.Now;
Raise(nameof(ClientTimeOffsetText));
}
private void SetState(bool ok, string message, int entryCount, int layoutCount, int? week)
{
LastReportOk = ok;
LastReportMessage = message;
LastReportAt = DateTimeOffset.Now;
LastScheduleEntryCount = entryCount;
LastTimeLayoutItemCount = layoutCount;
if (week.HasValue) LastServerWeek = week;
StateChanged?.Invoke(this, EventArgs.Empty);
}
private void Raise(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
private bool SetField<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
Raise(propertyName!);
return true;
}
public void Dispose()
{
_disposed = true;
lock (_gate)
{
_timer?.Dispose();
_timer = null;
_notifyTimer?.Dispose();
_notifyTimer = null;
}
_client.Dispose();
}
}
@@ -1,260 +0,0 @@
using Avalonia.Threading;
using ClassHelper.ClassIslandPlugin.Interop;
using ClassHelper.ClassIslandPlugin.Models;
using ClassIsland.Core.Abstractions.Services;
using ClassIsland.Shared;
using ClassIsland.Shared.Enums;
using ClassIsland.Core.Abstractions.Services.NotificationProviders;
using ClassIsland.Core.Attributes;
using ClassIsland.Core.Models.Notification;
using Microsoft.Extensions.Logging;
namespace ClassHelper.ClassIslandPlugin.Services;
/// <summary>
/// 提醒提供方:把老师在 ClassHelper上发布的提醒显示到 ClassIsland 上。
///
/// 与 <see cref="BridgeService"/> 的分工:
/// - <see cref="BridgeService"/> 负责"拉"(上报时顺路把待提醒带回来)与"回执"(ack);
/// - 本类只负责"显示"——提醒必须由提醒提供方发出,ClassIsland 才会走主界面的
/// 全屏特效 / 语音 / 音效那一整套流程。
///
/// 为什么不给这个提供方再配一套"提醒设置":本插件的开关全在「ClassHelper 联动」设置页里,
/// 再在「提醒」设置页放第二份开关只会让老师困惑(两处都能关,到底以哪个为准)。
/// 因此这里用无设置的 <see cref="NotificationProviderBase"/>,读的是同一份 <see cref="PluginSettings"/>。
/// </summary>
// 第 3 个参数是 Fluent 图标字体里的字形字符(ClassIsland 内置提醒提供方用的也是字形字符,
// 不是 "fluent(...)" 表达式):E8BD 是喇叭字形。
[NotificationProviderInfo(
ProviderGuidValue,
"ClassHelper提醒",
"\uE8BD",
"显示老师从 ClassHelper下发的提醒。")]
public sealed class ClassHelperNotificationProvider : NotificationProviderBase
{
/// <summary>
/// 提醒提供方 GUID(全局唯一,别改:改了等于换了一个提供方,用户原有的提醒设置会失联)。
/// 名字带 Value 后缀是为了不和基类的 <see cref="NotificationProviderBase.ProviderGuid"/> 属性撞名。
/// </summary>
public const string ProviderGuidValue = "7C4B1F6E-2A85-4A1F-9E3C-5B7D0C1A9E42";
private readonly BridgeService _bridge;
private readonly PluginSettings _settings;
private readonly ILogger<ClassHelperNotificationProvider> _logger;
/// <summary>
/// 正在播放(尚未回执)的提醒 id。
///
/// 服务端在提醒被回执前会**一直**把它算作"待弹出",而插件是按固定间隔轮询取回的,
/// 因此时长超过轮询间隔的提醒会被反复取到 —— 没有这层去重就会一遍遍重复弹。
/// 只有播完(或用户关掉)才从集合里移除,那一刻才回执。
/// </summary>
private readonly HashSet<string> _playing = new();
/// <summary>
/// 上课时段被暂存的提醒(与客户端灵动岛同一套规则)。
///
/// 为什么要有它:老师在**上课时段**发通知,教室里正上着课,直接全屏弹会打断课堂。
/// 客户端的灵动岛就是"上课先收着、下课再弹",ClassIsland 这侧必须一致,
/// 否则学生在客户端看不到、却在 ClassIsland 上被打断。
///
/// 例外("主动通知"):紧急提醒与**叫人**,老师正在等学生,必须立刻弹。
/// </summary>
private readonly List<PushNotificationDto> _deferred = new();
private ILessonsService? _lessons;
private bool _lessonsHooked;
public ClassHelperNotificationProvider(
BridgeService bridge,
PluginSettings settings,
ILogger<ClassHelperNotificationProvider> logger)
{
_bridge = bridge;
_settings = settings;
_logger = logger;
_bridge.NotificationReceived += OnNotificationReceived;
// 尽力而为地先订阅一次;拿不到也没关系,后面每次需要判定时都会重试
// (本类的构造函数可能在课程服务建好之前就被 DI 调用)
EnsureLessons();
}
/// <summary>
/// 惰性获取课程服务并**只订阅一次**课程事件(下课后补弹上课时段暂存的提醒)。
///
/// 为什么不能只在构造函数里订阅:提供方是随主机启动被构造的,而课程服务在启动流程里的
/// 创建时机并不固定。一旦构造函数里拿到 null,原先的实现既不重试、也不打日志,
/// 于是 `IsInClass()` 恒为 false —— "上课时段先暂存、下课再补弹"这条规则**永久失效**,
/// 老师在课上发的通知会直接全屏打断课堂,而且完全静默、无从排查。
/// </summary>
private void EnsureLessons()
{
if (_lessonsHooked) return;
try
{
_lessons = IAppHost.TryGetService<ILessonsService>();
if (_lessons is null) return;
_lessons.OnBreakingTime += (_, _) => Dispatcher.UIThread.Post(FlushDeferred);
_lessons.OnAfterSchool += (_, _) => Dispatcher.UIThread.Post(FlushDeferred);
_lessons.CurrentTimeStateChanged += (_, _) => Dispatcher.UIThread.Post(FlushDeferred);
_lessonsHooked = true;
_logger.LogInformation("ClassHelper 联动:提醒提供方已订阅课程事件(上课时段暂存、下课补弹)");
}
catch (Exception exception)
{
_logger.LogWarning(exception, "ClassHelper 联动:订阅课程事件失败,将在下次提醒时重试");
}
}
/// <summary>当前是否处于上课时段(读不到课程服务时按"不在上课"处理,宁可弹也不静默丢)</summary>
private bool IsInClass()
{
EnsureLessons();
try
{
return _lessons?.CurrentState == TimeState.OnClass;
}
catch
{
return false;
}
}
/// <summary>
/// 这条提醒是否必须立刻弹("主动通知"):
/// 紧急提醒,或叫人(老师正在等学生)。
/// </summary>
private static bool IsImmediate(PushNotificationDto notification) =>
notification.Urgent || string.Equals(notification.Kind, "call", StringComparison.OrdinalIgnoreCase);
/// <summary>下课后补弹暂存的提醒(按进入顺序)</summary>
private void FlushDeferred()
{
if (IsInClass()) return; // 还在上课(例如只是状态在 OnClass 内部变化)
if (_deferred.Count == 0) return;
var pending = _deferred.ToList();
_deferred.Clear();
_logger.LogInformation("ClassHelper 联动:下课了,补弹 {Count} 条上课时段暂存的提醒", pending.Count);
foreach (var item in pending) ShowOnUiThread(item);
}
private void OnNotificationReceived(object? sender, PushNotificationDto notification)
{
if (!_settings.ReceiveNotifications) return;
if (string.IsNullOrWhiteSpace(notification.Id)) return;
// 同一条提醒在播放期间会被后续轮询反复取回,这里按 id 去重(详见 _playing 的说明)
lock (_playing)
{
if (!_playing.Add(notification.Id))
{
_logger.LogDebug("ClassHelper 联动:提醒 {Id} 正在播放,跳过重复投递", notification.Id);
return;
}
}
// 必须切回 UI 线程:提醒内容里的图标、以及提醒主机本身都是 Avalonia 的 UI 对象,
// 而本方法是从上报回调(线程池)里被调用的 —— 在线程池上直接显示会静默失败/抛异常。
Dispatcher.UIThread.Post(() => ShowOnUiThread(notification));
}
private void ShowOnUiThread(PushNotificationDto notification)
{
try
{
// 上课时段:非"主动通知"先收着(与客户端灵动岛同一套规则),下课后补弹
if (IsInClass() && !IsImmediate(notification))
{
_deferred.Add(notification);
_logger.LogInformation("ClassHelper 联动:上课中,「{Title}」已暂存,下课后弹出", notification.Title);
return;
}
var request = BuildRequest(notification);
// 只有真正播完(或被用户关掉)才回执:中途退出 ClassIsland 时下次上报还会补发,不会静默丢失
AckWhenFinished(request, notification);
ShowNotification(request);
_logger.LogInformation("ClassHelper 联动:已弹出提醒「{Title}」({Seconds} 秒)",
notification.Title, notification.DurationSeconds);
}
catch (Exception exception)
{
// 显示失败不能让 ClassIsland 崩掉:记日志,且**不回执**,服务端下次轮询还会重发。
// 同时要把 id 从"正在播放"里放出来,否则本次失败后再也不会重试。
lock (_playing) _playing.Remove(notification.Id);
_logger.LogError(exception, "ClassHelper 联动:显示提醒「{Title}」失败", notification.Title);
}
}
/// <summary>
/// 把服务端下发的提醒转成 ClassIsland 的提醒请求。
///
/// 时长口径:老师指定的时长给**正文**(正文才是持续显示的那一段),遮罩只停留几秒 ——
/// 遮罩占满整个时长会把正文压没,不如"遮罩几秒 + 正文 N 秒"清楚。
/// </summary>
private NotificationRequest BuildRequest(PushNotificationDto notification)
{
var seconds = Math.Clamp(
notification.DurationSeconds > 0 ? notification.DurationSeconds : _settings.NotificationDurationSeconds,
1,
120);
var duration = TimeSpan.FromSeconds(seconds);
var maskDuration = TimeSpan.FromSeconds(Math.Min(notification.Urgent ? 5 : 3, seconds));
var title = string.IsNullOrWhiteSpace(notification.Title) ? "ClassHelper" : notification.Title;
var content = string.IsNullOrWhiteSpace(notification.Content) ? title : notification.Content;
// 语音:老师勾了朗读 + 本机允许朗读,两者都满足才念(本机开关是给学生机的总闸)
var speech = _settings.SpeechEnabled ? notification.SpeechContent : null;
var speechEnabled = !string.IsNullOrWhiteSpace(speech);
// 遮罩用双图标模板的**默认图标**:这两个图标由模板自己创建(LucideIconSource),
// 自己塞图标串很容易踩到"图标表达式格式不对/字形不存在",没必要冒这个险。
var mask = NotificationContent.CreateTwoIconsMask(title, factory: content_ =>
{
content_.Duration = maskDuration;
content_.SpeechContent = speech ?? string.Empty;
// 没勾朗读时明确关掉,否则 ClassIsland 会按默认设置把标题也念出来
content_.IsSpeechEnabled = speechEnabled;
});
// 正文:普通提醒用静态文本;紧急提醒改用**滚动文本**(ClassIsland 自带的抢注意力模板),
// 这样"紧急"在视觉上真的有区别,而不是只靠一个可能不存在的图标。
NotificationContent overlay = notification.Urgent
? NotificationContent.CreateRollingTextContent(content, factory: content_ =>
{
content_.Duration = duration;
content_.SpeechContent = speech ?? string.Empty;
content_.IsSpeechEnabled = speechEnabled;
})
: NotificationContent.CreateSimpleTextContent(content, factory: content_ =>
{
content_.Duration = duration;
content_.SpeechContent = speech ?? string.Empty;
content_.IsSpeechEnabled = speechEnabled;
});
return new NotificationRequest { MaskContent = mask, OverlayContent = overlay };
}
/// <summary>提醒播完 / 被关掉后回执给 ClassHelper,服务端不再补发。</summary>
private void AckWhenFinished(NotificationRequest request, PushNotificationDto notification)
{
void Handler(object? sender, EventArgs args)
{
request.Completed -= Handler;
request.Canceled -= Handler;
// 播完再放行:即使回执失败(例如断网)也移除,让后续轮询能重新投递一次,
// 避免"回执丢了 + 不再重试"把提醒彻底吞掉
lock (_playing) _playing.Remove(notification.Id);
_ = _bridge.AckAsync(notification.Id);
}
request.Completed += Handler;
request.Canceled += Handler;
}
}
@@ -1,299 +0,0 @@
using System.Collections.ObjectModel;
using ClassHelper.ClassIslandPlugin.Interop;
using ClassIsland.Shared.Models.Profile;
namespace ClassHelper.ClassIslandPlugin.Services;
/// <summary>
/// 把 ClassHelper拉回来的课表写进 ClassIsland 档案。
///
/// **核心约束**:ClassIsland 的一份 <see cref="ClassPlan"/> 只带**一个** <see cref="TimeRule"/>
/// (即一个星期几 + 一个单双周相位),而 ClassHelper的课表同时覆盖 7 天与单双周。
/// 因此这里把服务端的条目**按(星期几 + 单双周)分组**,每一组生成一份独立的档案课表。
///
/// **时间点的构造方式**:ClassIsland 的 <c>ClassPlan.Classes[i]</c> 必须与
/// <c>TimeLayout.Layouts</c> 里第 i 个 <c>TimeType == 0</c>(上课)的点一一对应。
/// 与其去"匹配服务端时间表里的时间点"(一旦对不齐整份课表就错位),
/// 这里**按分组内的条目顺序直接重建时间点**:每条课目生成一个上课点,
/// 并在其结束后接上服务端时间表里同一起始时刻的课间点。这样索引关系天然成立。
///
/// **非破坏性**:
/// - 只创建/更新名字带 <see cref="PlanNamePrefix"/> 前缀的课表与时间表;
/// - 老师手动建的课表一律不删除、不改名(同名星期的冲突会在日志里警告);
/// - 重复镜像时原地更新,不会越积越多。
/// </summary>
public static class ClassPlanWriter
{
/// <summary>识别前缀:只有名字带此前缀的课表才由本插件创建与维护。</summary>
public const string PlanNamePrefix = "ClassHelper-";
/// <summary>时间表名字后缀。</summary>
public const string TimeLayoutNameSuffix = "(ClassHelper)";
/// <summary>一次镜像的结果(写入的课表名与冲突提示)。</summary>
public sealed class ApplyResult
{
public List<string> PlanNames { get; } = new();
public List<string> Warnings { get; } = new();
public bool Applied { get; set; }
}
/// <summary>
/// 应用服务端下发的课表。
/// </summary>
/// <param name="force">
/// 「强制更换课表」:同一星期几 + 同一单双周相位下老师还开着别的课表时,**停用**它们,
/// 让教室大屏立刻改成以 ClassHelper 下发的这份为准。
/// 由 Web 端的「下发课表到教室」按钮触发(服务端那个一次性待办)。
/// **只停用不删除** —— 课表内容原样留在档案里,老师随时能在 ClassIsland 里重新启用。
/// </param>
public static ApplyResult Apply(Profile profile, ClassPlanMirrorDto source, bool force = false)
{
var result = new ApplyResult();
if (source.Entries.Count == 0 || source.TimeLayouts.Count == 0)
{
result.Warnings.Add("服务端返回的课表为空,未改动 ClassIsland 档案");
return result;
}
var layout = source.TimeLayouts[0];
// 1) 补齐科目(同名的复用,避免每次镜像堆出新的 Subject)
EnsureSubjects(profile, source);
// 2) 按(星期几 + 单双周)分组,每组一份课表
var groups = source.Entries
.GroupBy(entry => new
{
entry.WeekDay,
entry.WeekCountDiv,
entry.WeekCountDivTotal,
})
.Select(group => new
{
group.Key.WeekDay,
group.Key.WeekCountDiv,
group.Key.WeekCountDivTotal,
// 时间点顺序 = 课表顺序:`Classes[i]` 靠这个顺序与上课时间点对齐,
// 「HH:mm」是定长字符串,字典序就是时间序
Entries = group.OrderBy(entry => entry.StartTime, StringComparer.Ordinal).ToList(),
})
.OrderBy(group => group.WeekDay)
.ToList();
foreach (var group in groups)
{
var planName = BuildPlanName(source.ProfileName, group.WeekDay, group.WeekCountDiv,
group.WeekCountDivTotal, groups.Count);
// 时间非法的条目必须**在这里**就整批丢掉:`Classes` 与时间表里的上课点必须等长且同序,
// 只在一处跳过会让整份课表错位。原先 ParseTime 把无法解析的值悄悄变成 00:00,
// 于是档案里凭空出现 00:00-00:00 的课次(时间轴显示与当前节次判断都会乱),还没有任何日志。
var usable = group.Entries
.Where(entry => IsValidTime(entry.StartTime) && IsValidTime(entry.EndTime))
.ToList();
if (usable.Count < group.Entries.Count)
{
result.Warnings.Add(
$"「{planName}」有 {group.Entries.Count - usable.Count} 节的时间无法解析(需要 HH:mm),已跳过");
}
if (usable.Count == 0) continue;
var planId = FindPlanId(profile, planName);
var (timeLayoutId, timeLayout) = BuildTimeLayout(profile, planName, usable);
var plan = profile.ClassPlans.TryGetValue(planId, out var existing)
? existing
: new ClassPlan();
plan.Name = planName;
plan.TimeLayoutId = timeLayoutId;
plan.TimeRule = new TimeRule
{
WeekDay = group.WeekDay,
WeekCountDiv = group.WeekCountDiv,
WeekCountDivTotal = group.WeekCountDivTotal,
};
// Classes[i] ↔ 第 i 个上课点:按分组内条目的时间顺序直接构造,索引天然一致
// ClassIsland 的 `ClassInfo.CurrentTimeLayoutItem` = CurrentTimeLayout 里第 Index 个上课点,
// 因此这里必须显式把 Index 与 CurrentTimeLayout 一起写上 —— 只在构造时依赖
// `RefreshClassesList()` 是不够的:更新已有课表时 `TimeLayouts` 引用没变,
// 档案不会重新触发刷新,课次就会停留在旧时间点上。
var classes = new ObservableCollection<ClassInfo>();
var index = 0;
foreach (var entry in usable)
{
var subjectId = profile.Subjects
.FirstOrDefault(pair => pair.Value.Name == entry.Subject).Key;
classes.Add(new ClassInfo
{
Index = index++,
CurrentTimeLayout = timeLayout,
SubjectId = subjectId,
IsEnabled = true,
});
}
plan.Classes = classes;
plan.IsEnabled = true;
profile.ClassPlans[planId] = plan;
result.PlanNames.Add(planName);
// 冲突处理:同一星期几 + 同一单双周相位下老师还开着别的课表。
// ClassIsland 在同一个时间点上只会用一份**启用**的课表,所以"强制更换"就是把冲突的
// 那份停用 —— 教室大屏上立刻显示成 ClassHelper 下发的这一份。
var conflicts = profile.ClassPlans
.Where(pair => pair.Key != planId
&& pair.Value.IsEnabled
&& !pair.Value.Name.StartsWith(PlanNamePrefix, StringComparison.Ordinal)
&& pair.Value.TimeRule.WeekDay == group.WeekDay
&& pair.Value.TimeRule.WeekCountDivTotal == group.WeekCountDivTotal
&& pair.Value.TimeRule.WeekCountDiv == group.WeekCountDiv)
.ToList();
if (conflicts.Count > 0)
{
var names = string.Join("、", conflicts.Select(pair => pair.Value.Name));
if (force)
{
foreach (var pair in conflicts) pair.Value.IsEnabled = false;
result.Warnings.Add(
$"星期 {group.WeekDay} 原有的课表({names})已停用,教室显示改以 ClassHelper 下发的课表为准" +
"(只停用、未删除,可在 ClassIsland 的课表面板里重新启用)");
}
else
{
result.Warnings.Add(
$"星期 {group.WeekDay} 已有启用的课表({names}),两者重叠时以 ClassHelper 同步的课表为准");
}
}
}
// 3) 停用上一次镜像留下来的、本次不再需要的课表(只动自己创建的)
var currentNames = new HashSet<string>(result.PlanNames);
foreach (var pair in profile.ClassPlans)
{
if (!pair.Value.Name.StartsWith(PlanNamePrefix, StringComparison.Ordinal)) continue;
if (currentNames.Contains(pair.Value.Name)) continue;
pair.Value.IsEnabled = false;
}
result.Applied = true;
return result;
}
private static void EnsureSubjects(Profile profile, ClassPlanMirrorDto source)
{
foreach (var name in source.Entries.Select(entry => entry.Subject).Distinct())
{
if (string.IsNullOrWhiteSpace(name)) continue;
if (profile.Subjects.Any(pair => pair.Value.Name == name)) continue;
profile.Subjects[Guid.NewGuid()] = new Subject { Name = name };
}
}
private static Guid FindPlanId(Profile profile, string planName)
{
var existing = profile.ClassPlans.FirstOrDefault(pair => pair.Value.Name == planName);
return existing.Key != Guid.Empty ? existing.Key : Guid.NewGuid();
}
/// <summary>
/// 按分组内的条目重建时间表:**每节课之间补一个课间**(最后一节之后不补)。
///
/// 课间 = 「上一节下课」到「下一节上课」之间的那段空隙,直接由两条课目的时间算出来,
/// 不依赖服务端有没有给课间点 —— 这样无论 ClassHelper那边是否维护节次时间表,
/// ClassIsland 档案里的课表都会有一致的课间(需求:每节课的间隔都是课间,放学后除外)。
/// </summary>
private static (Guid Id, TimeLayout Layout) BuildTimeLayout(
Profile profile,
string planName,
IReadOnlyList<ClassPlanEntryMirrorDto> entries)
{
var layoutName = planName + TimeLayoutNameSuffix;
var existing = profile.TimeLayouts.FirstOrDefault(pair => pair.Value.Name == layoutName);
var id = existing.Key != Guid.Empty ? existing.Key : Guid.NewGuid();
var layout = new TimeLayout { Name = layoutName, IsActivated = true };
for (var index = 0; index < entries.Count; index++)
{
var entry = entries[index];
layout.Layouts.Add(new TimeLayoutItem
{
TimeType = 0, // 上课
StartTime = ParseTime(entry.StartTime),
EndTime = ParseTime(entry.EndTime),
});
// 课间:下一节开始晚于本节结束才有空隙;最后一节之后(放学)不插
if (index + 1 >= entries.Count) continue;
var next = entries[index + 1];
var breakStart = ParseTime(entry.EndTime);
var breakEnd = ParseTime(next.StartTime);
if (breakEnd <= breakStart) continue;
layout.Layouts.Add(new TimeLayoutItem
{
TimeType = 1, // 课间
StartTime = breakStart,
EndTime = breakEnd,
});
}
profile.TimeLayouts[id] = layout;
return (id, layout);
}
/// <summary>
/// 课表名:单组时用「ClassHelper-&lt;班级名&gt;」;多组时补上星期与单双周以免互相覆盖。
/// </summary>
private static string BuildPlanName(
string profileName,
int weekDay,
int weekCountDiv,
int weekCountDivTotal,
int groupCount)
{
var baseName = string.IsNullOrWhiteSpace(profileName) ? "ClassHelper课表" : profileName.Trim();
if (!baseName.StartsWith(PlanNamePrefix, StringComparison.Ordinal))
{
baseName = PlanNamePrefix + baseName;
}
if (groupCount <= 1) return baseName;
var weekday = weekDay switch
{
0 => "周日",
1 => "周一",
2 => "周二",
3 => "周三",
4 => "周四",
5 => "周五",
6 => "周六",
_ => $"星期{weekDay}",
};
var parity = weekCountDivTotal <= 1
? "每周"
: $"第{weekCountDiv}/{weekCountDivTotal}周";
return $"{baseName} · {weekday} · {parity}";
}
/// <summary>"HH:mm" / "HH:mm:ss" → TimeSpan(解析失败回退到 0 点)。</summary>
private static TimeSpan ParseTime(string value)
{
return TimeSpan.TryParse(value, out var parsed) ? parsed : TimeSpan.Zero;
}
/// <summary>
/// 时间字符串是否可用(HH:mm / HH:mm:ss)。
///
/// 服务端输出侧没有校验 `Schedule.startTime`(老数据/异常数据可能是空串),
/// 而 <see cref="ParseTime"/> 会把非法值变成 0 点 —— 因此调用方必须先用本方法过滤,
/// 并把 Classes 与时间表**同时**按过滤后的列表构造,保证索引仍然一致。
/// </summary>
private static bool IsValidTime(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return false;
return TimeSpan.TryParse(value, out var parsed)
&& parsed >= TimeSpan.Zero
&& parsed < TimeSpan.FromDays(1);
}
}
@@ -1,272 +0,0 @@
using System.Collections.ObjectModel;
using ClassHelper.ClassIslandPlugin.Interop;
using ClassIsland.Core.Abstractions.Services;
using ClassIsland.Shared;
using ClassIsland.Shared.Enums;
using ClassIsland.Shared.Models.Profile;
namespace ClassHelper.ClassIslandPlugin.Services;
/// <summary>
/// 课表 / 状态 → 上报载荷 的换算层。
///
/// 这里集中全部"ClassIsland 口径 ↔ ClassHelper口径"的转换,保证只有一处需要跟着
/// ClassIsland 的模型变化而修改:
/// - 星期:ClassIsland <c>WeekDay</c> 是 0=周日、1=周一…6=周六;本系统是 1=周一…7=周日;
/// - 单双周:ClassIsland <c>WeekCountDiv</c>/<c>WeekCountDivTotal</c>;本系统 ALL/ODD/EVEN;
/// - 节次:ClassIsland <c>TimeLayoutItem.TimeType</c> 0=上课 1=课间 2=分割线 3=行动。
/// </summary>
public static class ScheduleMapper
{
/// <summary>
/// ClassIsland 的 WeekDay(0=周日…6=周六)→ 本系统 dayOfWeek(1=周一…7=周日)。
/// </summary>
public static int ToServerDayOfWeek(int weekDay)
{
var normalized = ((weekDay % 7) + 7) % 7;
return normalized == 0 ? 7 : normalized;
}
/// <summary>
/// ClassIsland 的 WeekCountDiv/Total → 本系统单双周。
/// 与 <c>packages/shared/src/utils.ts</c> 的 <c>weekParityFromDiv</c> 完全一致:
/// 3 周及以上的循环本系统无法表达,降级为「每周」。
/// </summary>
public static string ToWeekParity(int weekCountDiv, int weekCountDivTotal)
{
if (weekCountDiv <= 0 || weekCountDivTotal <= 1) return "ALL";
var position = ((weekCountDiv - 1) % weekCountDivTotal) + 1;
if (weekCountDivTotal == 2) return position == 1 ? "ODD" : "EVEN";
return "ALL";
}
/// <summary>ClassIsland TimeType → 本系统节次类型。</summary>
public static string ToTimeLayoutType(int timeType) => timeType switch
{
1 => "break",
2 => "divider",
3 => "action",
_ => "class",
};
/// <summary>TimeSpan → "HH:mm"(跨天的时间点做钳制,避免出现 24:xx)。</summary>
public static string ToHhMm(TimeSpan time)
{
var totalMinutes = (int)Math.Round(time.TotalMinutes);
totalMinutes = Math.Clamp(totalMinutes, 0, 24 * 60 - 1);
return $"{totalMinutes / 60:D2}:{totalMinutes % 60:D2}";
}
/// <summary>
/// 把档案里的一张课表(ClassPlan)展开成"每个上课时间点一条"的课表条目。
///
/// 与 ClassIsland 的语义严格对齐:<c>ClassPlan.Classes[i]</c> 对应
/// <c>TimeLayout.Layouts</c> 里**第 i 个 TimeType=0(上课)的点**,课间 / 分割线 / 行动不占位。
///
/// **注意不要用 `plan.ValidTimeLayoutItems`**:它的口径与 `Classes` 不同 ——
/// `GetValidTimeLayoutItems()`(ClassIsland ClassPlan.cs)会正反两遍扫描,
/// 把 `ClassInfo.IsEnabled == false`(老师在课表编辑里"停用"这一节)的课**连同其后的课间**
/// 一起从结果里剔除;而 `RefreshClassesList()` 只按 `TimeType == 0` 的**总数**对齐
/// `Classes` 的长度,`ClassInfo.CurrentTimeLayoutItem` 也是按原始列表的第 `Index` 个取的。
/// 于是只要停用过任意一节,用 ValidTimeLayoutItems 配对就会让索引整体前移:
/// 第 i 节配上第 i+1 节的时间点、最后一节丢失,且 `Math.Min` 会把缺口静默吃掉 ——
/// 表现就是"课表看着有内容、每节课都对不上",极难排查。
/// </summary>
public static List<ScheduleEntryDto> MapClassPlan(ClassPlan plan, Profile profile, out string? warning)
{
warning = null;
var entries = new List<ScheduleEntryDto>();
var timeLayout = ResolveTimeLayout(plan, profile);
if (timeLayout is null)
{
warning = $"课表「{plan.Name}」找不到对应的时间表,已跳过";
return entries;
}
// 只保留上课类型的时间点,顺序必须与 Classes 的索引一致(见上面注释)
var classPoints = timeLayout.Layouts.Where(item => item.TimeType == 0).ToList();
var weekDay = ToServerDayOfWeek(plan.TimeRule.WeekDay);
var parity = ToWeekParity(plan.TimeRule.WeekCountDiv, plan.TimeRule.WeekCountDivTotal);
if (plan.TimeRule.WeekCountDivTotal > 2)
{
warning = "存在 3 周以上的轮换课表,ClassHelper只支持单双周,已按「每周」处理";
}
var classes = plan.Classes;
var count = Math.Min(classes.Count, classPoints.Count);
for (var index = 0; index < count; index++)
{
var info = classes[index];
// 索引必须与 Classes 对齐:这里按下标取时间点,**不能**先用 Where 过滤再取
var point = classPoints[index];
if (info is null) continue;
// 老师停用的一节:本系统没有"停用"概念,不上报(否则 ClassHelper 班级端会看到一节实际上不上的课)
if (!info.IsEnabled) continue;
// 空课(未安排科目)不上报:服务端的科目是必填的,空课由课表里的缺席表达
var subject = ResolveSubjectName(info.SubjectId, profile);
if (string.IsNullOrWhiteSpace(subject)) continue;
entries.Add(new ScheduleEntryDto
{
DayOfWeek = weekDay,
StartTime = ToHhMm(point.StartTime),
EndTime = ToHhMm(point.EndTime),
// 服务端对这几个字段有 zod 长度上限,且是**整批**校验:一个超长名字会让整次上报
// 400,连"现在上什么课"的状态与心跳都不更新,Web 端把教室显示成离线。
Subject = Truncate(subject, SubjectMaxLength)!,
TeacherName = Truncate(ResolveSubjectTeacher(info.SubjectId, profile), NameMaxLength),
WeekParity = parity,
WeekCountDiv = plan.TimeRule.WeekCountDiv,
WeekCountDivTotal = plan.TimeRule.WeekCountDivTotal,
PlanName = Truncate(plan.Name, PlanNameMaxLength),
});
}
return entries;
}
/// <summary>服务端 zod 对各类名称的长度上限(超出会让整批上报 400,所以要截断) */
public const int SubjectMaxLength = 40;
public const int NameMaxLength = 40;
public const int PlanNameMaxLength = 60;
/// <summary>按服务端上限截断(null / 空串原样返回)</summary>
public static string? Truncate(string? value, int max)
{
if (string.IsNullOrEmpty(value)) return value;
var trimmed = value.Trim();
return trimmed.Length <= max ? trimmed : trimmed[..max];
}
/// <summary>把时间表(TimeLayout)转成本系统的节次时间配置。</summary>
public static List<TimeLayoutItemDto> MapTimeLayout(TimeLayout layout)
{
var items = new List<TimeLayoutItemDto>();
// ClassIsland 的上课时间点没有独立名称,这里按"它之前有几个上课点"编出"第 N 节"
var classPointIndex = 0;
for (var index = 0; index < layout.Layouts.Count; index++)
{
var point = layout.Layouts[index];
items.Add(new TimeLayoutItemDto
{
Index = index + 1,
// 节次名同样是服务端有上限的字段(max 40),超长会让整批上报失败
Name = Truncate(BuildTimePointName(point, ref classPointIndex), NameMaxLength)!,
StartTime = ToHhMm(point.StartTime),
EndTime = ToHhMm(point.EndTime),
Type = ToTimeLayoutType(point.TimeType),
Skipped = false,
});
}
return items;
}
/// <summary>
/// 节次名称:ClassIsland 只有课间有名字(BreakName),上课时间点没有独立名称,
/// 因此按类型生成"第 N 节 / 课间 / 分割线",保证本系统的时间轴可读。
/// </summary>
private static string BuildTimePointName(TimeLayoutItem point, ref int classPointIndex)
{
switch (point.TimeType)
{
case 1:
return string.IsNullOrWhiteSpace(point.BreakName) ? "课间" : point.BreakName!;
case 2:
return "分割线";
case 3:
return "行动";
default:
classPointIndex++;
return $"第 {classPointIndex} 节";
}
}
/// <summary>取出课表使用的时间表:优先按 TimeLayoutId,其次用档案里第一个。</summary>
public static TimeLayout? ResolveTimeLayout(ClassPlan plan, Profile profile)
{
if (profile.TimeLayouts.Count == 0) return null;
if (plan.TimeLayoutId != Guid.Empty && profile.TimeLayouts.TryGetValue(plan.TimeLayoutId, out var byId))
{
return byId;
}
return plan.TimeLayout ?? profile.TimeLayouts.Values.FirstOrDefault();
}
/// <summary>科目名(找不到时返回空字符串,由调用方决定是否跳过)。</summary>
public static string? ResolveSubjectName(Guid subjectId, Profile profile)
{
if (subjectId == Guid.Empty) return null;
return profile.Subjects.TryGetValue(subjectId, out var subject) ? subject.Name : null;
}
/// <summary>科目任课老师(ClassIsland 在 Subject 上记录 TeacherName)。</summary>
public static string? ResolveSubjectTeacher(Guid subjectId, Profile profile)
{
if (subjectId == Guid.Empty) return null;
return profile.Subjects.TryGetValue(subjectId, out var subject) ? subject.TeacherName : null;
}
/// <summary>
/// 收集档案里今天(按当前周次与星期)应该上的课表,
/// 用于"只上报今天"这类轻量场景;当前实现为上报全部课表(服务端按周次并存)。
/// </summary>
public static List<ScheduleEntryDto> MapAllClassPlans(Profile profile, out List<string> warnings)
{
warnings = new List<string>();
var all = new List<ScheduleEntryDto>();
foreach (var plan in profile.ClassPlans.Values)
{
if (!plan.IsEnabled) continue;
if (plan.IsOverlay) continue; // 临时层课表不下发,避免把临时调整固化到班级课表
var entries = MapClassPlan(plan, profile, out var warning);
if (!string.IsNullOrWhiteSpace(warning) && !warnings.Contains(warning!))
{
warnings.Add(warning!);
}
all.AddRange(entries);
}
return all;
}
/// <summary>
/// 科目名归一化。
///
/// 没有课表 / 没有当前科目时,ClassIsland 会把 <see cref="Subject.Fallback"/> 挂到
/// `CurrentSubject` / `NextClassSubject` 上(见 LessonsService:
/// `CurrentSubject = currentSubject ?? Subject.Fallback`),而它的名字就是占位符本身。
/// 直接上报会让 Web 端显示成"正在上 ???",因此这里统一折算成"没有科目"。
/// </summary>
private static string? NormalizeSubjectName(Subject? subject)
{
if (subject is null) return null;
if (ReferenceEquals(subject, Subject.Fallback)) return null;
var name = subject.Name?.Trim();
if (string.IsNullOrEmpty(name)) return null;
// 兜底:万一拿到的是另一个同名占位符实例(不是同一个引用)
if (string.Equals(name, Subject.Fallback.Name, StringComparison.Ordinal)) return null;
return name;
}
/// <summary>当前状态快照:服务端据此在 Web 端展示"现在上什么课"。</summary>
public static StateDto BuildState(ILessonsService lessons, int? currentWeek)
{
var current = lessons.CurrentTimeLayoutItem;
var state = lessons.CurrentState;
return new StateDto
{
InClass = state == TimeState.OnClass,
Subject = NormalizeSubjectName(lessons.CurrentSubject),
NextSubject = NormalizeSubjectName(lessons.NextClassSubject),
TimeState = state.ToString(),
PeriodStart = current is null || current == TimeLayoutItem.Empty ? null : ToHhMm(current.StartTime),
PeriodEnd = current is null || current == TimeLayoutItem.Empty ? null : ToHhMm(current.EndTime),
Week = currentWeek,
ClassPlanLoaded = lessons.IsClassPlanLoaded,
ClientTime = DateTimeOffset.Now.ToString("o"),
};
}
}
@@ -1,150 +0,0 @@
<controls:SettingsPageBase x:Class="ClassHelper.ClassIslandPlugin.Views.BridgeSettingsPage"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ClassHelper.ClassIslandPlugin.Views"
xmlns:controls="clr-namespace:ClassIsland.Core.Abstractions.Controls;assembly=ClassIsland.Core"
xmlns:ci="clr-namespace:ClassIsland.Core.Controls;assembly=ClassIsland.Core"
xmlns:fa="clr-namespace:FluentAvalonia.UI.Controls;assembly=FluentAvalonia"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
d:DataContext="{d:DesignInstance local:BridgeSettingsPage}"
Loaded="OnLoaded"
Unloaded="OnUnloaded">
<ScrollViewer>
<StackPanel Classes="settings-container animated-intro" Spacing="0">
<!-- 连接 -->
<TextBlock Text="连接 ClassHelper"
Theme="{StaticResource SubtitleTextBlockStyle}" />
<TextBlock Margin="0 6 0 12" TextWrapping="Wrap"
Text="填入 ClassHelper后端的地址与设备令牌。设备令牌在 ClassHelper Web 端「ClassIsland 联动」页面里为本班新建设备后生成,只显示一次。" />
<TextBox Watermark="http://127.0.0.1:4000"
Text="{Binding Settings.ServerUrl, Mode=TwoWay}" />
<TextBox Margin="0 8 0 0"
Watermark="chci_..."
PasswordChar="●"
Text="{Binding Settings.DeviceToken, Mode=TwoWay}" />
<!-- 令牌是设备级长期凭证(只有管理员在 Web 端重置才会失效),而 ClassIsland 的插件配置
是明文 JSON 且会随档案备份/迁移一起被带走,所以这里明确提示用户别外传。 -->
<TextBlock Margin="0 6 0 0" TextWrapping="Wrap" Opacity="0.7"
Text="令牌是这台教室机器的长期凭证(仅管理员在 Web 端重置才会失效),会明文保存在本机配置文件里并随 ClassIsland 档案备份一起复制,请不要外传或提交到版本库。" />
<StackPanel Orientation="Horizontal" Margin="0 12 0 0" Spacing="8">
<Button Content="立即上报" Command="{Binding ReportCommand}" IsEnabled="{Binding !Bridge.Busy}" />
<Button Content="检查连接" Command="{Binding TestCommand}" IsEnabled="{Binding !Bridge.Busy}" />
<Button Content="拉取待提醒" Command="{Binding PullCommand}" IsEnabled="{Binding !Bridge.Busy}" />
<Button Content="重建档案课表" Command="{Binding MirrorCommand}" IsEnabled="{Binding !Bridge.Busy}" />
</StackPanel>
<!-- 状态 -->
<Border Margin="0 16 0 0" Padding="12" CornerRadius="4"
Background="{DynamicResource SystemFillColorNeutralBackgroundBrush}">
<StackPanel Spacing="4">
<TextBlock Text="{Binding StatusText}" TextWrapping="Wrap" FontWeight="SemiBold" />
<TextBlock Text="{Binding Bridge.LastReportMessage}" TextWrapping="Wrap" />
<TextBlock Text="{Binding DetailText}" TextWrapping="Wrap" Opacity="0.8" />
</StackPanel>
</Border>
<!-- 同步 -->
<TextBlock Margin="0 24 0 0" Text="课表同步"
Theme="{StaticResource SubtitleTextBlockStyle}" />
<TextBlock Margin="0 6 0 12" TextWrapping="Wrap"
Text="课表的两个方向都是按需的,由 Web 端「ClassIsland 联动」页的两个按钮触发,本机不再提供「一直同步」的开关:「从教室机器获取课表」把 ClassIsland 里启用的课表合并进 ClassHelper;「下发课表到教室」把 ClassHelper 排好的课表写回 ClassIsland,并把同一天同一单双周相位下冲突的旧课表停用(只停用、不删除,可在 ClassIsland 的课表面板里重新启用)。" />
<fa:SettingsExpander Header="自动上报"
Description="应用启动、课程事件以及每隔一段时间各上报一次**运行状态**(现在上什么课、ClassIsland 版本等)。课表不在这条路径上 —— 它只由 Web 端「从教室机器获取课表」按需拉取。关闭后只能用上面的「立即上报」手动触发。">
<fa:SettingsExpander.IconSource>
<ci:FluentIconSource Glyph="&#xE895;" />
</fa:SettingsExpander.IconSource>
<fa:SettingsExpander.Footer>
<ToggleSwitch IsChecked="{Binding Settings.AutoReport, Mode=TwoWay}" />
</fa:SettingsExpander.Footer>
</fa:SettingsExpander>
<Grid Margin="0 8 0 0" ColumnDefinitions="*,Auto">
<StackPanel>
<TextBlock Text="上报间隔(秒)" />
<TextBlock Text="最小 15 秒;教室机器建议 60 秒。" Opacity="0.7" TextWrapping="Wrap" />
</StackPanel>
<NumericUpDown Grid.Column="1" Width="140"
Minimum="15" Maximum="3600" Increment="15"
FormatString="0"
IsEnabled="{Binding Settings.AutoReport}"
Value="{Binding Settings.ReportIntervalSeconds, Mode=TwoWay}" />
</Grid>
<!-- 提醒 -->
<TextBlock Margin="0 24 0 0" Text="提醒"
Theme="{StaticResource SubtitleTextBlockStyle}" />
<TextBlock Margin="0 6 0 12" TextWrapping="Wrap"
Text="老师在 ClassHelper上发布的提醒会以 ClassIsland 的全屏提醒呈现;未弹出的提醒在应用重开后会自动补发,确认弹出后不再重复。" />
<fa:SettingsExpander Header="接收 ClassHelper提醒"
Description="关闭后本机会忽略老师在 ClassHelper上发布的提醒(提醒仍会留在班级通知中心)。">
<fa:SettingsExpander.IconSource>
<ci:FluentIconSource Glyph="&#xE8BD;" />
</fa:SettingsExpander.IconSource>
<fa:SettingsExpander.Footer>
<ToggleSwitch IsChecked="{Binding Settings.ReceiveNotifications, Mode=TwoWay}" />
</fa:SettingsExpander.Footer>
</fa:SettingsExpander>
<fa:SettingsExpander Header="语音朗读"
Description="提醒弹出时按 ClassIsland 的语音设置为全机朗读提醒内容。">
<fa:SettingsExpander.IconSource>
<ci:FluentIconSource Glyph="&#xE8D6;" />
</fa:SettingsExpander.IconSource>
<fa:SettingsExpander.Footer>
<ToggleSwitch IsChecked="{Binding Settings.SpeechEnabled, Mode=TwoWay}" />
</fa:SettingsExpander.Footer>
</fa:SettingsExpander>
<Grid Margin="0 8 0 0" ColumnDefinitions="*,Auto">
<StackPanel>
<TextBlock Text="默认显示时长(秒)" />
<TextBlock Text="老师在下发单条提醒时可以另外指定更长的时长。" Opacity="0.7" TextWrapping="Wrap" />
</StackPanel>
<NumericUpDown Grid.Column="1" Width="140"
Minimum="1" Maximum="120" Increment="1"
FormatString="0"
Value="{Binding Settings.NotificationDurationSeconds, Mode=TwoWay}" />
</Grid>
<Grid Margin="0 8 0 0" ColumnDefinitions="*,Auto">
<StackPanel>
<TextBlock Text="提醒轮询间隔(秒)" />
<TextBlock Text="老师按下发送到教室弹出之间的最大延迟(插件不持有长连接,是轮询取回提醒)。默认 10 秒。"
Opacity="0.7" TextWrapping="Wrap" />
</StackPanel>
<NumericUpDown Grid.Column="1" Width="140"
Minimum="5" Maximum="600" Increment="5"
FormatString="0"
IsEnabled="{Binding Settings.ReceiveNotifications}"
Value="{Binding Settings.NotificationPollSeconds, Mode=TwoWay}" />
</Grid>
<!-- 调试 -->
<TextBlock Margin="0 24 0 0" Text="调试"
Theme="{StaticResource SubtitleTextBlockStyle}" />
<fa:SettingsExpander Header="显示调试信息"
Description="显示设备标识、时钟差等细节,排查「为什么同步不上」时打开。">
<fa:SettingsExpander.IconSource>
<ci:FluentIconSource Glyph="&#xE7EF;" />
</fa:SettingsExpander.IconSource>
<fa:SettingsExpander.Footer>
<ToggleSwitch IsChecked="{Binding Settings.ShowDebugInfo, Mode=TwoWay}" />
</fa:SettingsExpander.Footer>
</fa:SettingsExpander>
<StackPanel Margin="0 8 0 0" Spacing="2" IsVisible="{Binding Settings.ShowDebugInfo}">
<TextBlock Text="{Binding DebugText}" TextWrapping="Wrap" FontFamily="Consolas,monospace" />
</StackPanel>
<TextBlock Margin="0 24 0 0" Opacity="0.6" TextWrapping="Wrap"
Text="提示:ClassHelper Web 端 →「ClassIsland 联动」可以新建/重置设备令牌、开关同步项,并实时看到本机当前上的课。" />
</StackPanel>
</ScrollViewer>
</controls:SettingsPageBase>
@@ -1,198 +0,0 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Avalonia.Threading;
using ClassHelper.ClassIslandPlugin.Models;
using ClassHelper.ClassIslandPlugin.Services;
using ClassIsland.Core.Abstractions.Controls;
using ClassIsland.Core.Attributes;
using ClassIsland.Core.Enums.SettingsWindow;
using CommunityToolkit.Mvvm.Input;
namespace ClassHelper.ClassIslandPlugin.Views;
/// <summary>
/// 「ClassHelper 联动」设置页。
///
/// 页面上的绑定源就是本页自己(<c>DataContext = this</c>):<see cref="Settings"/> 暴露全部配置项,
/// <see cref="Bridge"/> 暴露运行状态。这样 XAML 里能直接写 <c>{Binding Settings.Xxx}</c>,
/// 不需要再套一层 ViewModel,改配置项时也少一处"两边同步"的机会。
/// </summary>
// 图标用 Fluent 字体的码位(与 ClassIsland 内置设置页写法一致):未选中/选中同一枚插头图标
[SettingsPageInfo(
"classhelper.classisland.bridge.settings",
"ClassHelper 联动",
"\uE71B",
"\uE71B",
SettingsPageCategory.External)]
public partial class BridgeSettingsPage : SettingsPageBase, INotifyPropertyChanged
{
public BridgeSettingsPage(PluginSettings settings, BridgeService bridge)
{
Settings = settings;
Bridge = bridge;
ReportCommand = new AsyncRelayCommand(ReportAsync);
TestCommand = new AsyncRelayCommand(TestAsync);
PullCommand = new AsyncRelayCommand(PullAsync);
MirrorCommand = new AsyncRelayCommand(MirrorAsync);
InitializeComponent();
DataContext = this;
Raise(nameof(StatusText));
}
public PluginSettings Settings { get; }
public BridgeService Bridge { get; }
public IAsyncRelayCommand ReportCommand { get; }
public IAsyncRelayCommand TestCommand { get; }
public IAsyncRelayCommand PullCommand { get; }
public IAsyncRelayCommand MirrorCommand { get; }
private PropertyChangedEventHandler? _propertyChanged;
/// <summary>
/// 显式实现 <see cref="INotifyPropertyChanged"/>:<c>AvaloniaObject</c> 自带一个同名但类型不同的事件,
/// 直接声明会遮蔽基类成员。显式实现既不影响 Avalonia 的绑定查找(它按接口取),也不会有歧义。
/// </summary>
event PropertyChangedEventHandler? INotifyPropertyChanged.PropertyChanged
{
add => _propertyChanged += value;
remove => _propertyChanged -= value;
}
/* ---------------------------------------------------------------- 绑定用的展示文本 */
/// <summary>一句话结论:还没配 / 已配置 / 已连接 / 连接异常。</summary>
public string StatusText
{
get
{
if (!Settings.IsConfigured) return "尚未配置:请填写服务器地址与设备令牌";
if (!Bridge.IsAttached) return "已填写配置,等待 ClassIsland 课程服务就绪";
return Bridge.LastReportOk ? "已连接" : "连接异常";
}
}
public string DetailText
{
get
{
var week = Bridge.LastServerWeek?.ToString() ?? "—";
return $"最后上报:{Bridge.LastReportAtText} 教学周:{week} " +
$"课表 {Bridge.LastScheduleEntryCount} 节 / 节次 {Bridge.LastTimeLayoutItemCount} 条 " +
$"已弹出提醒:{Bridge.NotificationCount} 条";
}
}
/// <summary>调试信息(设置页里打开"显示调试信息"才可见)。</summary>
public string DebugText
{
get
{
var lines = new List<string>
{
$"服务器地址:{(string.IsNullOrWhiteSpace(Settings.ServerUrl) ? "(未填)" : Settings.ServerUrl)}",
$"设备令牌:{(string.IsNullOrWhiteSpace(Settings.DeviceToken) ? "(未填)" : Mask(Settings.DeviceToken))}",
$"设备标识:{(string.IsNullOrWhiteSpace(Settings.DeviceKey) ? "(未生成)" : Settings.DeviceKey)}",
$"课程服务:{(Bridge.IsAttached ? "已接入" : "未接入")}",
$"与服务端时钟差:{Bridge.ClientTimeOffsetText}",
$"ClassIsland 版本:{SafeVersion()}",
$"配置目录:{PluginConfigFolder}",
};
return string.Join(Environment.NewLine, lines);
}
}
/// <summary>设置页所在的插件配置目录(从插件入口拿;拿不到时留空)。</summary>
private string PluginConfigFolder =>
ClassIsland.Shared.IAppHost.TryGetService<ClassIsland.Core.Abstractions.PluginBase>()?.PluginConfigFolder ?? "—";
private static string SafeVersion()
{
try { return ClassIsland.Core.AppBase.AppVersion ?? "—"; }
catch { return "—"; }
}
/// <summary>令牌只露头尾,避免设置页截图时把可用凭证泄露出去。</summary>
private static string Mask(string token) =>
token.Length <= 14 ? token : $"{token[..12]}…{token[^4..]}";
/* ---------------------------------------------------------------- 交互 */
private async Task ReportAsync()
{
await Bridge.ReportAsync("手动").ConfigureAwait(true);
}
/// <summary>不带课表上报一次:用来快速验证"地址 + 令牌"是否可用,不会因为课表为空而出错。</summary>
private async Task TestAsync()
{
await Bridge.ReportAsync("连接检查", includeSchedule: false).ConfigureAwait(true);
}
private async Task PullAsync()
{
await Bridge.PullPendingAsync().ConfigureAwait(true);
}
private async Task MirrorAsync()
{
await Bridge.MirrorScheduleAsync().ConfigureAwait(true);
}
private void OnSettingsChanged(object? sender, PropertyChangedEventArgs args)
{
// 影响上报链路的改动需要立刻重建定时器;纯界面项(如"显示调试信息")不用管
if (args.PropertyName is nameof(PluginSettings.ServerUrl)
or nameof(PluginSettings.DeviceToken)
or nameof(PluginSettings.AutoReport)
or nameof(PluginSettings.ReportIntervalSeconds)
or nameof(PluginSettings.ReceiveNotifications)
or nameof(PluginSettings.NotificationPollSeconds))
{
Bridge.RestartTimer();
}
Raise(nameof(StatusText));
Raise(nameof(DebugText));
}
private void OnBridgeChanged(object? sender, PropertyChangedEventArgs args)
{
// Bridge 的属性变化可能来自线程池(HttpClient 回调),绑定必须在 UI 线程上更新
if (Dispatcher.UIThread.CheckAccess())
{
RaiseStateProperties();
}
else
{
Dispatcher.UIThread.Post(RaiseStateProperties);
}
}
private void RaiseStateProperties()
{
Raise(nameof(StatusText));
Raise(nameof(DetailText));
Raise(nameof(DebugText));
}
private void OnLoaded(object sender, Avalonia.Interactivity.RoutedEventArgs args)
{
// 改完地址/令牌/间隔要重建定时器,否则"改了设置但上报节奏还是旧的"
Settings.PropertyChanged += OnSettingsChanged;
// 运行状态(上一次上报结果 / 待弹出提醒数)变了要刷新状态卡片
Bridge.PropertyChanged += OnBridgeChanged;
}
private void OnUnloaded(object sender, Avalonia.Interactivity.RoutedEventArgs args)
{
Settings.PropertyChanged -= OnSettingsChanged;
Bridge.PropertyChanged -= OnBridgeChanged;
}
private void Raise([CallerMemberName] string? propertyName = null) =>
_propertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@classhelper/desktop-client",
"version": "1.3.2",
"version": "1.3.3",
"private": true,
"description": "ClassHelper EXE 客户端(Electron + Vue 3 + Element Plus + Socket.IO + IndexedDB 离线缓存)",
"author": "Class Helper",
+44 -121
View File
@@ -9,10 +9,17 @@ import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { provisionSmokeClass } from '../../../scripts/lib/smoke-class.mjs';
import { resolveElectronEnv, resolveElectronExecutable } from '../../../scripts/lib/electron-env.mjs';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const repoRoot = path.resolve(root, '..', '..');
const startedAt = Date.now();
const mode = process.argv.includes('--visual') ? 'visual' : (process.env.ELECTRON_SMOKE_MODE ?? 'quick');
if (!['quick', 'visual'].includes(mode)) throw new Error('冒烟模式只能是 quick 或 visual');
const resultFile =
process.env.ELECTRON_SMOKE_RESULT ?? path.join(repoRoot, '.cache', 'desktop-smoke-result.json');
console.log(`[smoke] 模式:${mode === 'visual' ? '视觉验收(会使用桌面)' : '后台快速检查(不占用前台)'}`);
const electronPath = resolveElectronExecutable(path.join(root, 'node_modules', 'electron'));
const required = [path.join(root, 'dist/main/index.js'), path.join(root, 'dist/renderer/index.html')];
const missing = required.filter((file) => !fs.existsSync(file));
@@ -37,124 +44,13 @@ try {
}
console.log(`[smoke] 独立配置目录:${profileDir}`);
// 未显式指定时自动探测后端:可达则启用联网集成 + 侧边栏点击测试
let online = process.env.ELECTRON_SMOKE_ONLINE;
if (online === undefined) {
online = '0';
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 2500);
const response = await fetch('http://127.0.0.1:4000/api/health', { signal: controller.signal });
clearTimeout(timer);
online = response.ok ? '1' : '0';
} catch {
online = '0';
}
console.log(
online === '1'
? '[smoke] 检测到后端在线,将执行联网集成与侧边栏点击测试'
: '[smoke] 后端未在线,仅执行本地检查(离线缓存/界面渲染);如需联网测试请先启动 pnpm dev:server',
);
}
/**
* 准备一个已知可用的班级账号(ClassHelper 班级端已改为班级码 + 班级密码登录):
* 用管理员账号登录 → 取第一个班级 → 先试"已知密码"(冒烟密码 / 种子默认 123456),
* 命中就直接用、**不改动任何数据**;都不行才把该班重置成冒烟专用密码,
* 并在脚本收尾时恢复为种子默认密码(避免把演示实例的 123456 悄悄改掉)。
*/
async function provisionClassAccount() {
const base = process.env.ELECTRON_SMOKE_API ?? 'http://127.0.0.1:4000/api';
const username = process.env.ELECTRON_SMOKE_ADMIN ?? 'admin';
const adminPassword = process.env.ELECTRON_SMOKE_ADMIN_PASSWORD ?? 'admin123';
const password = process.env.ELECTRON_SMOKE_CLASS_PASSWORD ?? 'smoke123456';
const CANDIDATES = [...new Set([password, process.env.ELECTRON_SMOKE_SEED_PASSWORD ?? '123456'])];
const tryLogin = async (code, candidate) => {
const response = await fetch(`${base}/auth/class-login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, password: candidate }),
});
return response.ok;
};
try {
const loginResponse = await fetch(`${base}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password: adminPassword }),
});
const login = await loginResponse.json();
const token = login?.data?.token;
if (!token) return null;
const authHeaders = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
const classesResponse = await fetch(`${base}/classes`, { headers: authHeaders });
const classes = (await classesResponse.json())?.data ?? [];
const target = classes[0];
if (!target) return null;
// 冒烟**永不修改班级码**(班级码是给学生用的,不应被测试工具改写):
// 只有"现有班级码 + 已知密码全部登录失败"时才重置密码,班级码原样保留。
const code = target.code;
if (!code) return null;
for (const candidate of CANDIDATES) {
if (await tryLogin(code, candidate)) return { code, password: candidate, className: target.name };
}
const patchResponse = await fetch(`${base}/classes/${target.id}/class-account`, {
method: 'PATCH',
headers: authHeaders,
body: JSON.stringify({ code, password }),
});
if (!patchResponse.ok) return null;
const patched = (await patchResponse.json())?.data;
// 记下"需要恢复",脚本收尾时改回种子默认密码(已知密码都不通时无法得知原密码)
patchedAccount = { id: target.id, code: patched?.code ?? code, base, authHeaders };
console.log(
`[smoke] 已知密码均不可用,已把班级 ${target.name} 的密码临时重置为 ${password}` +
`(结束时恢复为 ${CANDIDATES[1]})`,
);
return { code: patched?.code ?? code, password, className: target.name };
} catch {
return null;
}
}
/** 冒烟临时重置过的班级账号(结束时恢复) */
let patchedAccount = null;
/** 恢复被冒烟临时改过的班级密码(失败只告警,不影响冒烟结论) */
async function restoreClassAccount() {
if (!patchedAccount) return;
try {
const response = await fetch(`${patchedAccount.base}/classes/${patchedAccount.id}/class-account`, {
method: 'PATCH',
headers: patchedAccount.authHeaders,
body: JSON.stringify({
code: patchedAccount.code,
password: process.env.ELECTRON_SMOKE_SEED_PASSWORD ?? '123456',
}),
});
console.log(
response.ok
? '[smoke] 已恢复班级密码为种子默认 123456(冒烟不留副作用)'
: `[smoke] [WARN] 班级密码恢复失败:status=${response.status},请到后台重新设置`,
);
} catch (error) {
console.log(`[smoke] [WARN] 班级密码恢复失败:${error?.message ?? error}`);
}
}
// 联网验收必须显式指定,避免自动碰到用户正在使用的实例。
const online = process.argv.includes('--online') ? '1' : (process.env.ELECTRON_SMOKE_ONLINE ?? '0');
let classCredentials = null;
if (online === '1') {
classCredentials = await provisionClassAccount();
console.log(
classCredentials
? `[smoke] 班级账号就绪:${classCredentials.code}(${classCredentials.className})`
: '[smoke] 未能准备班级账号,联网集成将使用种子默认凭据',
);
classCredentials = await provisionSmokeClass();
if (!classCredentials) throw new Error('无法建立独立验证班级,请检查测试服务端与管理员凭据');
console.log('[smoke] 已建立独立验证班级:' + classCredentials.code);
}
/** 启动一次冒烟(返回退出码) */
@@ -163,26 +59,48 @@ function launchSmoke(extraEnv) {
const child = spawn(electronPath, ['.'], {
cwd: root,
stdio: 'inherit',
windowsHide: true,
env: resolveElectronEnv({
ELECTRON_SMOKE_TEST: '1',
ELECTRON_SMOKE_MODE: mode,
ELECTRON_SMOKE_RESULT: resultFile,
ELECTRON_SMOKE_ONLINE: online,
ELECTRON_SMOKE_PROFILE: profileDir,
ELECTRON_SMOKE_CLASS_CODE: classCredentials?.code ?? '',
ELECTRON_SMOKE_CLASS_PASSWORD: classCredentials?.password ?? '',
// 教师凭据只从这里传入:主进程的冒烟代码从环境变量读,
// 因此安装包(app.asar)里不会留下教师口令字面量(本脚本不进安装包)
ELECTRON_SMOKE_USER: process.env.ELECTRON_SMOKE_USER ?? 'teacher1',
ELECTRON_SMOKE_PASSWORD: process.env.ELECTRON_SMOKE_PASSWORD ?? 'teacher123',
ELECTRON_SMOKE_USER:
classCredentials?.teacherUsername ?? process.env.ELECTRON_SMOKE_USER ?? 'teacher1',
ELECTRON_SMOKE_PASSWORD:
classCredentials?.teacherPassword ?? process.env.ELECTRON_SMOKE_PASSWORD ?? 'teacher123',
ELECTRON_SMOKE_CLASS_ID: classCredentials?.classId ?? '',
...extraEnv,
}),
});
child.on('exit', (code) => resolve(code ?? 1));
const deadline = setTimeout(
() => {
console.error('[smoke] 超时,结束验证进程');
child.kill();
resolve(124);
},
mode === 'visual' ? 360_000 : 45_000,
);
child.once('exit', (code) => {
clearTimeout(deadline);
resolve(code ?? 1);
});
child.once('error', (error) => {
clearTimeout(deadline);
console.error(error);
resolve(1);
});
});
}
const code = await launchSmoke();
console.log(`\n[smoke] Electron 退出,code=${code}`);
await restoreClassAccount();
await classCredentials?.cleanup();
if (code !== 0) process.exit(code);
/**
@@ -208,7 +126,11 @@ try {
}
console.log('\n[smoke] 二次启动校验(单实例锁 / 句柄是否已释放)...');
const relaunchCode = await launchSmoke({ ELECTRON_SMOKE_ONLINE: '0', ELECTRON_SMOKE_RESULT: relaunchResult });
const relaunchCode = await launchSmoke({
ELECTRON_SMOKE_ONLINE: '0',
ELECTRON_SMOKE_MODE: 'quick',
ELECTRON_SMOKE_RESULT: relaunchResult,
});
let relaunchPassed = 0;
let relaunchTotal = 0;
@@ -232,4 +154,5 @@ try {
} catch {
// 二次启动可能又建了目录,删除失败不影响结论(首次删除已证明锁已释放)
}
console.log('[smoke] 总耗时:' + ((Date.now() - startedAt) / 1000).toFixed(1) + ' 秒');
process.exit(resourcesOk ? 0 : 1);
@@ -208,7 +208,7 @@ function rowBadgeClass(item: IslandNotification): string {
const itemKind = rowKind(item);
if (itemKind === 'call') return 'badge-call';
if (itemKind === 'homework') return 'badge-homework';
return `badge-${item.priority.toLowerCase()}`;
return `badge-${(item.priority ?? 'NORMAL').toLowerCase()}`;
}
function rowSubText(item: IslandNotification): string {
@@ -674,37 +674,37 @@ onMounted(async () => {
再随卡片变窄被省略号收回(用户反馈的"新消息那行字往右跳一下再缩回")。
-->
<span class="pill-inner">
<span class="pill-icon" :class="{ urgent: isUrgent, call: isCall, homework: isHomework }">
<svg v-if="isHomework" viewBox="0 0 24 24" aria-hidden="true">
<path
fill="currentColor"
d="M6 3h9a3 3 0 0 1 3 3v13.5a.5.5 0 0 1-.75.43L15 18.5l-2.25 1.43a.5.5 0 0 1-.53 0L10 18.5l-2.25 1.43a.5.5 0 0 1-.53 0L5 18.5V5a2 2 0 0 1 1-2Zm2 4v1.6h7V7H8Zm0 3.4V12h7v-1.6H8Z"
/>
</svg>
<svg v-else-if="isCall" viewBox="0 0 24 24" aria-hidden="true">
<path
fill="currentColor"
d="M4 10v4a1 1 0 0 0 1 1h2l4 3.5a1 1 0 0 0 1.65-.76V5.26A1 1 0 0 0 11 4.5L7 8H5a1 1 0 0 0-1 1Zm12.5-2.9a1 1 0 0 1 1.4.1 8 8 0 0 1 0 9.6 1 1 0 1 1-1.5-1.3 6 6 0 0 0 0-7 1 1 0 0 1 .1-1.4Z"
/>
</svg>
<svg v-else viewBox="0 0 24 24" aria-hidden="true">
<path
fill="currentColor"
d="M12 2a6 6 0 0 0-6 6v3.1L4.6 14a1 1 0 0 0 .9 1.5h13a1 1 0 0 0 .9-1.5L18 11.1V8a6 6 0 0 0-6-6Zm0 20a3 3 0 0 0 3-2.6H9A3 3 0 0 0 12 22Z"
/>
</svg>
</span>
<span class="pill-text">
<span class="pill-title">{{ pillSummaryTitle }}</span>
<span class="pill-sub">
<template v-if="pendingCount > 1">点击查看</template>
<template v-else>{{ notification?.teacherName || '老师' }} · 点击查看</template>
<span class="pill-icon" :class="{ urgent: isUrgent, call: isCall, homework: isHomework }">
<svg v-if="isHomework" viewBox="0 0 24 24" aria-hidden="true">
<path
fill="currentColor"
d="M6 3h9a3 3 0 0 1 3 3v13.5a.5.5 0 0 1-.75.43L15 18.5l-2.25 1.43a.5.5 0 0 1-.53 0L10 18.5l-2.25 1.43a.5.5 0 0 1-.53 0L5 18.5V5a2 2 0 0 1 1-2Zm2 4v1.6h7V7H8Zm0 3.4V12h7v-1.6H8Z"
/>
</svg>
<svg v-else-if="isCall" viewBox="0 0 24 24" aria-hidden="true">
<path
fill="currentColor"
d="M4 10v4a1 1 0 0 0 1 1h2l4 3.5a1 1 0 0 0 1.65-.76V5.26A1 1 0 0 0 11 4.5L7 8H5a1 1 0 0 0-1 1Zm12.5-2.9a1 1 0 0 1 1.4.1 8 8 0 0 1 0 9.6 1 1 0 1 1-1.5-1.3 6 6 0 0 0 0-7 1 1 0 0 1 .1-1.4Z"
/>
</svg>
<svg v-else viewBox="0 0 24 24" aria-hidden="true">
<path
fill="currentColor"
d="M12 2a6 6 0 0 0-6 6v3.1L4.6 14a1 1 0 0 0 .9 1.5h13a1 1 0 0 0 .9-1.5L18 11.1V8a6 6 0 0 0-6-6Zm0 20a3 3 0 0 0 3-2.6H9A3 3 0 0 0 12 22Z"
/>
</svg>
</span>
<span class="pill-text">
<span class="pill-title">{{ pillSummaryTitle }}</span>
<span class="pill-sub">
<template v-if="pendingCount > 1">点击查看</template>
<template v-else>{{ notification?.teacherName || '老师' }} · 点击查看</template>
</span>
</span>
<!-- 多类型时把类型也做成小圆点,收起状态一眼看出有什么 -->
<span v-if="pendingCount > 1 && pendingTypes.length > 1" class="pill-types" aria-hidden="true">
<span v-for="item in pendingTypes" :key="item" class="pill-type">{{ item }}</span>
</span>
</span>
<!-- 多类型时把类型也做成小圆点,收起状态一眼看出有什么 -->
<span v-if="pendingCount > 1 && pendingTypes.length > 1" class="pill-types" aria-hidden="true">
<span v-for="item in pendingTypes" :key="item" class="pill-type">{{ item }}</span>
</span>
<span class="pill-chevron" aria-hidden="true">
<svg viewBox="0 0 24 24">
<path
+103 -21
View File
@@ -4,7 +4,12 @@ import fsp from 'node:fs/promises';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { BrowserWindow, app } from 'electron';
import { CLIENT_UPDATE_IDLE_MS, type ClientUpdateInfoDto } from '@classhelper/shared';
import {
isNewerVersion,
CLIENT_UPDATE_IDLE_MS,
type ClientHeartbeatResponse,
type ClientUpdateInfoDto,
} from '@classhelper/shared';
import { getConfig, saveConfig } from './config.js';
import { island } from './island.js';
import { logger } from './logger.js';
@@ -13,16 +18,58 @@ import { logger } from './logger.js';
* 服务端统一下发的自动更新(下载 + 空闲时静默安装)。
*
* 设计要点(都是"教室机器"这个使用场景逼出来的):
* 1. **下载随时进行、安装只在完全空闲时**:教室机的带宽与注意力都有限,上课期间重启应用是灾难,
* 所以安装的三个必要条件缺一不可 —— 不在上课、主窗口已隐藏满 `CLIENT_UPDATE_IDLE_MS`(5 分钟)、
* 本进程还没装过;
* 1. **下载随时进行,按下发策略安装**:立即安装;放学后到指定时刻且不在上课时安装;
* 空闲安装要求不在上课且主窗口隐藏满五分钟;
* 2. **下完先校验 sha256**:服务端给的哈希对不上就删掉文件、记 error,**不做任何信任放行**
* (宁可这次更新失败,也不能把一个来源不明的 exe 装到教室里);
* 3. **安装脚本脱离本进程**:`start /wait` 等安装器跑完后重新拉起应用,
* 3. **安装脚本脱离本进程**:PowerShell 等旧进程退出、安装器完成后重新拉起应用,
* 本进程随即走既有退出路径退出(重启应用这件事交给安装脚本,而不是自己 `relaunch`,
* 否则会与"安装器正在覆盖自己"撞车 —— Windows 上正在运行的程序文件是删不掉的)。
*/
let policy: Pick<ClientHeartbeatResponse, 'updateTargetVersion' | 'updateMode' | 'updateNotBefore'> | null =
null;
function policyPath(): string {
return path.join(pendingUpdateDir(), 'policy.json');
}
function loadPolicy(): typeof policy {
if (policy) return policy;
try {
policy = JSON.parse(fs.readFileSync(policyPath(), 'utf8'));
} catch {
/* 尚无下发策略 */
}
return policy;
}
/** 更新包只来自专用目录;清理与执行均不得接受目录外的配置路径。 */
function isManagedInstaller(file: string): boolean {
return path.dirname(path.resolve(file)) === path.resolve(pendingUpdateDir()) && /\.exe$/i.test(file);
}
function removeManagedInstaller(file: string): void {
if (!file || !isManagedInstaller(file)) return;
try {
fs.rmSync(file, { force: true });
} catch (error) {
logger.warn(`清理旧更新包失败:${String(error)}`);
}
}
/** 每次成功心跳先同步策略;取消或更换目标后旧包不得自行安装。 */
export function syncUpdatePolicy(next: ClientHeartbeatResponse): void {
policy = {
updateTargetVersion: next.updateTargetVersion,
updateMode: next.updateMode ?? 'idle',
updateNotBefore: next.updateNotBefore ?? null,
};
fs.mkdirSync(pendingUpdateDir(), { recursive: true });
fs.writeFileSync(policyPath(), JSON.stringify(policy), 'utf8');
if (getConfig().pendingUpdateVersion !== (next.updateTargetVersion ?? '')) {
removeManagedInstaller(getConfig().pendingUpdateFile);
saveConfig({ pendingUpdateVersion: '', pendingUpdateFile: '' });
}
}
/** 单个安装包的下载超时:教室机网络慢,给足 10 分钟 */
const DOWNLOAD_TIMEOUT_MS = 10 * 60_000;
@@ -77,7 +124,7 @@ export function watchMainWindow(win: BrowserWindow): void {
mainWindowHiddenAt = null;
if (hookedWindow === win) hookedWindow = null;
});
if (win.isVisible()) mainWindowHiddenAt = null;
mainWindowHiddenAt = win.isVisible() ? null : Date.now();
}
/** 主窗口是否已经隐藏满 `CLIENT_UPDATE_IDLE_MS` */
@@ -187,11 +234,15 @@ export async function considerUpdate(info: ClientUpdateInfoDto, targetVersion: s
await fsp.rm(target, { force: true });
await fsp.rename(temp, target);
if (loadPolicy()?.updateTargetVersion !== version) {
removeManagedInstaller(target);
return;
}
saveConfig({ pendingUpdateVersion: version, pendingUpdateFile: target });
logger.info(
`更新 ${version} 已下载并校验通过(${formatSize(fs.statSync(target).size)},耗时 ${Math.round(
(Date.now() - startedAt) / 1000,
)} 秒),将在空闲时自动安装`,
)} 秒),将按服务端指定的时机安装`,
);
await maybeInstallPendingUpdate();
} catch (error) {
@@ -230,9 +281,8 @@ function formatSize(bytes: number): string {
/**
* 如果条件全部满足就装更新。
*
* 条件(缺一不可):非冒烟模式 / 配置里有待安装版本 / 文件还在 / 不在上课 /
* 主窗口已隐藏满 5 分钟 / 本进程没装过。**每次心跳后与主窗口 hide 后都会调用**,
* 所以"老师下课关掉窗口 → 5 分钟后自动装上"就是靠这里触发的。
* 非冒烟模式、有有效目标与安装包且自动更新开启;其余条件按安装策略判断。
* 每次心跳后与主窗口隐藏后都会调用。
*/
export async function maybeInstallPendingUpdate(): Promise<void> {
if (installing) return;
@@ -241,21 +291,40 @@ export async function maybeInstallPendingUpdate(): Promise<void> {
const config = getConfig();
const version = config.pendingUpdateVersion?.trim() ?? '';
const installer = config.pendingUpdateFile?.trim() ?? '';
if (!version || !installer) return;
if (!version || !installer || config.autoUpdate === false || !config.token) return;
if (!isNewerVersion(app.getVersion(), version)) {
removeManagedInstaller(installer);
saveConfig({ pendingUpdateVersion: '', pendingUpdateFile: '' });
return;
}
const active = loadPolicy();
if (!active || active.updateTargetVersion !== version) return;
if (active.updateMode === 'after-school') {
const at = Date.parse(active.updateNotBefore ?? '');
if (!Number.isFinite(at) || Date.now() < at) return;
}
if (!fs.existsSync(installer)) {
logger.warn(`待安装的更新 ${version} 已不存在(${installer}),清除待安装记录`);
saveConfig({ pendingUpdateVersion: '', pendingUpdateFile: '' });
return;
}
if (island.getState().inClass) {
if (
!isManagedInstaller(installer) ||
path.dirname(fs.realpathSync(installer)) !== fs.realpathSync(pendingUpdateDir())
) {
logger.error('拒绝执行更新目录之外的安装文件');
saveConfig({ pendingUpdateVersion: '', pendingUpdateFile: '' });
return;
}
if (active.updateMode !== 'immediate' && island.getState().inClass) {
logger.info(`更新 ${version} 已就绪,但正在上课,暂不安装`);
return;
}
if (mainWindowVisible()) {
if (active.updateMode === 'idle' && mainWindowVisible()) {
logger.debug(`更新 ${version} 已就绪,但主窗口可见(人正在用),暂不安装`);
return;
}
if (!mainWindowIdleLongEnough()) {
if (active.updateMode === 'idle' && !mainWindowIdleLongEnough()) {
const waited = mainWindowHiddenAt === null ? 0 : Math.round((Date.now() - mainWindowHiddenAt) / 1000);
logger.debug(
`更新 ${version} 已就绪,但主窗口隐藏仅 ${waited} 秒` +
@@ -276,14 +345,27 @@ export async function maybeInstallPendingUpdate(): Promise<void> {
logger.info(`开始静默安装更新 ${version}:${installer}`);
try {
const exe = app.getPath('exe');
const command = `start "" /wait "${installer}" /S && start "" "${exe}"`;
const child = spawn('cmd.exe', ['/c', command], {
detached: true,
stdio: 'ignore',
windowsHide: true,
const quote = (value: string): string => "'" + value.replaceAll("'", "''") + "'";
const script =
`$ErrorActionPreference = 'Stop'; Wait-Process -Id ${process.pid} -ErrorAction SilentlyContinue; ` +
`$installer = Start-Process -FilePath ${quote(installer)} -ArgumentList '/S','--updated','--force-run' -Wait -PassThru; ` +
`if ($installer.ExitCode -ne 0 -and (Test-Path -LiteralPath ${quote(exe)})) { Start-Process -FilePath ${quote(exe)} }`;
const encoded = Buffer.from(script, 'utf16le').toString('base64');
const child = spawn(
'powershell.exe',
['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-EncodedCommand', encoded],
{
detached: true,
stdio: 'ignore',
windowsHide: true,
},
);
await new Promise<void>((resolve, reject) => {
child.once('spawn', resolve);
child.once('error', reject);
});
child.unref();
// 安装脚本会等安装器结束后重新拉起应用;本进程随即退出(复用既有退出路径,保证配置已落盘)
// 安装器从实际安装目录启动新版;免安装版的旧 exe 可能随退出消失,只在安装失败时尝试恢复它。
if (quitHandler) {
quitHandler();
} else {
@@ -293,7 +375,7 @@ export async function maybeInstallPendingUpdate(): Promise<void> {
} catch (error) {
installing = false;
logger.error(
`启动更新安装失败(将在下次空闲时重试):${error instanceof Error ? error.message : String(error)}`,
`启动更新安装失败(将在下次满足安装条件时重试):${error instanceof Error ? error.message : String(error)}`,
);
}
}
@@ -1,17 +1,20 @@
import { spawn } from 'node:child_process';
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
import { BrowserWindow, app, dialog } from 'electron';
import {
CLIENT_COMMAND_LABELS,
CLIENT_HEARTBEAT_INTERVAL_MS,
isNewerVersion,
type ClientCommandDto,
type ApiResponse,
type ClientCommandKind,
type ClientHeartbeatRequest,
type ClientHeartbeatResponse,
type ClientUpdateInfoDto,
} from '@classhelper/shared';
import { maybeInstallPendingUpdate, considerUpdate } from './auto-update.js';
import { maybeInstallPendingUpdate, considerUpdate, syncUpdatePolicy } from './auto-update.js';
import { getConfig } from './config.js';
import { island } from './island.js';
import { logger } from './logger.js';
@@ -21,7 +24,7 @@ import { logger } from './logger.js';
*
* **为什么是"客户端定时拉"而不是服务端推**:教室机的连接经常断(代理、休眠、重启),
* 而「这台机器是什么版本、要不要更新、有没有待执行命令」必须下次上线就能补上 —— 所以统一用
* 「服务端记状态 + 客户端定时上报」的范式(与 ClassIsland 插件的上报同一套路),不引入新的长连接握手。
* 「服务端记状态 + 客户端定时上报」的范式,不引入新的长连接握手。
* 每次上报的响应里同时带回「服务端指定的目标版本 + 待执行命令」。
*
* 三条边界:
@@ -111,7 +114,7 @@ function isAgentSuppressed(): boolean {
* 上报里的"这台机器现在在干什么"。
*
* 取值就三种(服务端设备列表直接展示这段文字):
* - `上课中` —— 灵动岛按渲染进程上报的课表状态判定正在上课(此时绝不安装更新);
* - `上课中` —— 灵动岛按渲染进程上报的课表状态判定正在上课(延后策略此时不安装更新);
* - `使用中` —— 主窗口可见,人正在用;
* - `待机` —— 窗口隐藏(最小化到托盘),机器空闲。
*/
@@ -172,10 +175,12 @@ async function beat(): Promise<void> {
let backoff = false;
try {
const body: ClientHeartbeatRequest = {
agentProtocol: 2,
deviceKey: config.deviceKey,
name: os.hostname(),
clientVersion: app.getVersion(),
platform: `${process.platform}-${process.arch}`,
autoUpdate: config.autoUpdate !== false,
pendingVersion: pendingVersionOrNull(),
stateNote: currentStateNote(),
};
@@ -202,7 +207,9 @@ async function beat(): Promise<void> {
return;
}
const payload = (await response.json()) as ClientHeartbeatResponse;
const envelope = (await response.json()) as ApiResponse<ClientHeartbeatResponse>;
if (!envelope.success || !envelope.data?.deviceId) throw new Error('心跳响应格式不正确');
const payload = envelope.data;
state.lastHeartbeatAt = new Date().toISOString();
state.lastError = '';
state.updateTargetVersion = payload.updateTargetVersion?.trim() ?? '';
@@ -211,15 +218,19 @@ async function beat(): Promise<void> {
`${state.updateTargetVersion ? `,服务端要求升到 ${state.updateTargetVersion}` : ''})`,
);
void handleCommand(payload.command);
await handleUpdate(payload.update, payload.updateTargetVersion);
void handleCommand(payload.command).catch((error) => logger.error(`远控处理失败:${String(error)}`));
// 下载不能阻塞心跳,否则慢速下载期间远控和在线状态都会失效。
syncUpdatePolicy(payload);
void handleUpdate(payload.update, payload.updateTargetVersion).catch((error) =>
logger.error(`更新处理失败:${String(error)}`),
);
} catch (error) {
// 网络错误 / 超时 / JSON 解析失败:按原节奏重试
state.lastError = error instanceof Error ? error.message : String(error);
logger.warn(`客户端上报失败(将于 ${HEARTBEAT_INTERVAL_TEXT} 后重试):${state.lastError}`);
} finally {
state.beating = false;
// 每次心跳(无论成败)都顺手看一下有没有下载好的更新该装了 —— 上课/窗口可见时会自动跳过
// 每次心跳后检查已下载的更新是否满足安装策略。
void maybeInstallPendingUpdate();
scheduleNext(backoff ? UNAUTHORIZED_BACKOFF_MS : CLIENT_HEARTBEAT_INTERVAL_MS);
}
@@ -233,14 +244,45 @@ const HEARTBEAT_INTERVAL_TEXT = `${Math.round(CLIENT_HEARTBEAT_INTERVAL_MS / 100
* 两道护栏缺一不可(用户要求「必须二次确认」):
* 1. **本机二次确认**:弹一个默认选中「取消」的对话框,60 秒不确认按取消处理 ——
* 服务端那边虽然也确认过,但真正会被关掉的机器上必须有人当场知道;
* 2. **同一条命令只弹一次**:它随每次心跳重复下发,用内存集合去重,避免 30 秒弹一个框。
* 2. **同一条命令只执行一次**:等待确认时内存去重,处理结果落盘,重启后也只重试回执。
*
* 执行后**必须回执**(`POST /api/clients/commands/:id/ack`,body 带 deviceKey):
* 否则服务端那条命令会一直挂在"待执行"里,Web 端看不到结果。回执失败时把结果暂存,
* 下一次心跳只重试回执、不重复弹窗。
*/
const inFlightCommands = new Set<string>();
const unackedResults = new Map<string, { ok: boolean; result: string }>();
type CommandOutcome = { ok: boolean; result: string };
const commandResults = new Map<string, CommandOutcome>();
let resultsLoaded = false;
function commandResultsPath(): string {
return path.join(app.getPath('userData'), 'command-results.json');
}
function readCommandResults(): void {
if (resultsLoaded) return;
try {
const entries: unknown = JSON.parse(fs.readFileSync(commandResultsPath(), 'utf8'));
if (Array.isArray(entries))
for (const entry of entries.slice(-200)) {
if (
Array.isArray(entry) &&
typeof entry[0] === 'string' &&
typeof entry[1]?.ok === 'boolean' &&
typeof entry[1]?.result === 'string'
)
commandResults.set(entry[0], entry[1]);
}
} catch {
/* 首次运行尚无记录 */
}
resultsLoaded = true;
}
function rememberCommand(commandId: string, outcome: CommandOutcome): void {
readCommandResults();
commandResults.set(commandId, outcome);
while (commandResults.size > 200) commandResults.delete(commandResults.keys().next().value!);
fs.mkdirSync(app.getPath('userData'), { recursive: true });
fs.writeFileSync(commandResultsPath(), JSON.stringify([...commandResults]), 'utf8');
}
async function handleCommand(command: ClientCommandDto | null): Promise<void> {
if (!command) return;
@@ -255,15 +297,15 @@ async function handleCommand(command: ClientCommandDto | null): Promise<void> {
return;
}
// 正在确认或执行时不能用预存的中间结果抢先回执。
if (inFlightCommands.has(command.id)) return;
// 处理过但回执没送达:只重试回执
const pending = unackedResults.get(command.id);
readCommandResults();
const pending = commandResults.get(command.id);
if (pending) {
await ackCommand(command.id, pending.ok, pending.result);
return;
}
// 正在等本机确认:不要再弹第二个框
if (inFlightCommands.has(command.id)) return;
inFlightCommands.add(command.id);
try {
const confirmed = await confirmCommand(label, command.payload);
@@ -273,6 +315,11 @@ async function handleCommand(command: ClientCommandDto | null): Promise<void> {
await ackCommand(command.id, false, result);
return;
}
// 注销可能立刻结束本进程,先落盘,重启后不能再次执行同一条指令。
rememberCommand(command.id, {
ok: false,
result: '本机已确认并提交系统执行,最终结果未回传,请核对设备状态',
});
const outcome = await executeCommand(command.kind);
logger.warn(`远控命令「${label}」执行${outcome.ok ? '成功' : '失败'}:${outcome.result}`);
await ackCommand(command.id, outcome.ok, outcome.result);
@@ -283,8 +330,11 @@ async function handleCommand(command: ClientCommandDto | null): Promise<void> {
/** 本机二次确认对话框:默认「取消」,60 秒未操作按取消处理 */
async function confirmCommand(label: string, note: string): Promise<boolean> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), COMMAND_CONFIRM_TIMEOUT_MS);
const answered = dialog
.showMessageBox({
signal: controller.signal,
type: 'warning',
title: '来自管理员的远程指令',
message: `管理员要求本机「${label}」`,
@@ -294,13 +344,14 @@ async function confirmCommand(label: string, note: string): Promise<boolean> {
cancelId: 0,
noLink: true,
})
.then((result) => result.response === 1)
.then((result) => !controller.signal.aborted && result.response === 1)
.catch(() => false);
return Promise.race([
answered,
new Promise<boolean>((resolve) => setTimeout(() => resolve(false), COMMAND_CONFIRM_TIMEOUT_MS)),
]);
try {
return await answered;
} finally {
clearTimeout(timer);
}
}
/** 执行系统命令:只支持 Windows(本项目客户端只发 Windows 版) */
@@ -308,32 +359,31 @@ async function executeCommand(kind: ClientCommandKind): Promise<{ ok: boolean; r
if (process.platform !== 'win32') return { ok: false, result: '仅支持 Windows' };
const commands: Record<ClientCommandKind, { file: string; args: string[] }> = {
shutdown: { file: 'shutdown.exe', args: ['/s', '/t', '0'] },
restart: { file: 'shutdown.exe', args: ['/r', '/t', '0'] },
shutdown: { file: 'shutdown.exe', args: ['/s', '/t', '5'] },
restart: { file: 'shutdown.exe', args: ['/r', '/t', '5'] },
logoff: { file: 'shutdown.exe', args: ['/l'] },
lock: { file: 'rundll32.exe', args: ['user32.dll,LockWorkStation'] },
};
const plan = commands[kind];
try {
// detached + unref:不能等它退出(关机/注销会把本进程一起带走)
// 关机/重启预留 5 秒用于回执;检查系统命令进程的真实退出码。
const child = spawn(plan.file, plan.args, { detached: true, stdio: 'ignore', windowsHide: true });
/**
* **必须监听 `error` 事件**:`spawn` 找不到可执行文件(或没权限)时不是抛异常,而是在
* next tick 上发一个 `error` 事件 —— 只包 `try/catch` 的话,这种情况会一路走到
* `return { ok: true }`,回执写着"已下达系统命令",Web 端看起来一切正常,机器却纹丝不动。
* 等一个很短的窗口(200ms)确认没有立刻报错;真执行成功时子进程本来也要跑一会儿。
* 同时检查非零退出码,系统拒绝指令时不能回报成功。
*/
const failure = await new Promise<string | null>((resolve) => {
child.once('error', (error) => resolve(error.message));
setTimeout(() => resolve(null), 200);
return await new Promise((resolve) => {
child.once('error', (error) => resolve({ ok: false, result: error.message }));
child.once('exit', (code) =>
resolve({
ok: code === 0,
result: code === 0 ? '系统已接受指令' : `系统命令执行失败(退出码 ${code ?? '未知'})`,
}),
);
});
child.unref();
if (failure) {
logger.warn(`远控命令「${CLIENT_COMMAND_LABELS[kind] ?? kind}」无法执行:${failure}`);
return { ok: false, result: failure };
}
return { ok: true, result: '已下达系统命令' };
} catch (error) {
return { ok: false, result: error instanceof Error ? error.message : String(error) };
}
@@ -341,6 +391,7 @@ async function executeCommand(kind: ClientCommandKind): Promise<{ ok: boolean; r
/** 回执:服务端用 body 里的 deviceKey 校验"这条命令是发给这台机器的" */
async function ackCommand(commandId: string, ok: boolean, result: string): Promise<void> {
rememberCommand(commandId, { ok, result });
const config = getConfig();
if (!config.token) return;
try {
@@ -352,16 +403,13 @@ async function ackCommand(commandId: string, ok: boolean, result: string): Promi
});
if (!response.ok) {
logger.warn(`远控命令回执失败(HTTP ${response.status}),将在下次心跳重试`);
unackedResults.set(commandId, { ok, result });
return;
}
unackedResults.delete(commandId);
logger.info(`远控命令回执已送达(${ok ? '成功' : '失败'}):${result}`);
} catch (error) {
logger.warn(
`远控命令回执失败(${error instanceof Error ? error.message : String(error)}),将在下次心跳重试`,
);
unackedResults.set(commandId, { ok, result });
}
}
+1 -21
View File
@@ -3,14 +3,11 @@ import fs from 'node:fs';
import path from 'node:path';
import { app, safeStorage } from 'electron';
import {
CLASSISLAND_NOTIFICATION_CHANNELS,
DEFAULT_CLASSISLAND_NOTIFICATION_CHANNEL,
DEFAULT_ISLAND_APPEARANCE,
DEFAULT_SERVER_URL,
HOMEWORK_PHRASE_DEFAULTS,
HOMEWORK_PHRASE_MAX_COUNT,
HOMEWORK_PHRASE_MAX_LENGTH,
type ClassIslandNotificationChannel,
type IslandAppearance,
} from '@classhelper/shared';
import { logger } from './logger.js';
@@ -33,8 +30,6 @@ interface PersistedConfig {
island?: Partial<IslandAppearance>;
/** 作业页展示偏好(向后兼容:旧配置文件没有该字段时用默认值补齐) */
homeworkBoard?: Partial<HomeworkBoardSettings>;
/** 通知显示位置(向后兼容:旧配置文件没有该字段时按默认 both 补齐) */
notificationChannel?: ClassIslandNotificationChannel;
/** 作业录入快捷短语(向后兼容:旧配置没有该字段时用默认那一组) */
homeworkPhrases?: string[];
/** 是否已看过初次启动引导(向后兼容:旧配置没有该字段视为没看过,首启弹一次) */
@@ -68,7 +63,6 @@ const DEFAULT_CONFIG: PersistedConfig = {
tokenEncrypted: false,
island: { ...DEFAULT_ISLAND_APPEARANCE },
homeworkBoard: { ...DEFAULT_HOMEWORK_BOARD },
notificationChannel: DEFAULT_CLASSISLAND_NOTIFICATION_CHANNEL,
homeworkPhrases: [...HOMEWORK_PHRASE_DEFAULTS],
onboardingDone: false,
theme: 'light',
@@ -107,15 +101,6 @@ function normalizeHomeworkPhrases(input?: string[]): string[] {
return result;
}
/** 通知显示位置的白名单校验:非法值一律回落到默认值,避免坏配置把提醒"静默吞掉" */
function normalizeNotificationChannel(
input?: ClassIslandNotificationChannel,
): ClassIslandNotificationChannel {
return CLASSISLAND_NOTIFICATION_CHANNELS.includes(input as ClassIslandNotificationChannel)
? (input as ClassIslandNotificationChannel)
: DEFAULT_CLASSISLAND_NOTIFICATION_CHANNEL;
}
/** 作业页偏好的合法化(模式白名单、字号夹紧) */
function normalizeHomeworkBoard(input?: Partial<HomeworkBoardSettings>): HomeworkBoardSettings {
const mode = input?.mode === 'list' ? 'list' : 'board';
@@ -218,7 +203,6 @@ function readPersistedFromDisk(): PersistedConfig {
tokenEncrypted: parsed.tokenEncrypted === true,
island: normalizeIslandAppearance(parsed.island),
homeworkBoard: normalizeHomeworkBoard(parsed.homeworkBoard),
notificationChannel: normalizeNotificationChannel(parsed.notificationChannel),
homeworkPhrases: normalizeHomeworkPhrases(parsed.homeworkPhrases),
onboardingDone: parsed.onboardingDone === true,
theme: normalizeTheme(parsed.theme),
@@ -381,7 +365,6 @@ function toDesktopConfig(state: ConfigCache): DesktopStoredConfig {
token: state.token,
island: normalizeIslandAppearance(persisted.island),
homeworkBoard: normalizeHomeworkBoard(persisted.homeworkBoard),
notificationChannel: normalizeNotificationChannel(persisted.notificationChannel),
homeworkPhrases: normalizeHomeworkPhrases(persisted.homeworkPhrases),
onboardingDone: persisted.onboardingDone === true,
theme: normalizeTheme(persisted.theme),
@@ -463,9 +446,6 @@ export function saveConfig(patch: Partial<DesktopStoredConfig>): DesktopStoredCo
if (patch.homeworkPhrases !== undefined) {
persisted.homeworkPhrases = normalizeHomeworkPhrases(patch.homeworkPhrases);
}
if (patch.notificationChannel !== undefined) {
persisted.notificationChannel = normalizeNotificationChannel(patch.notificationChannel);
}
// 引导只接受"已看过":重看入口不走这里(看过与否只有 true 与"没看过"两种状态,
// 想 re-arm 只能清配置 clearConfig)。传 false 一律忽略,避免任何调用点误把用户退回首启状态。
if (patch.onboardingDone === true) {
@@ -493,7 +473,7 @@ export function saveConfig(patch: Partial<DesktopStoredConfig>): DesktopStoredCo
if (patch.careMode !== undefined) {
persisted.careMode = patch.careMode === true;
}
// 待安装的更新只由主进程的 auto-update 模块写入;渲染进程传进来也照收(退出登录/重置走 clearConfig)
// 仅供主进程更新模块写入;IPC 层会剔除这两个字段。
if (typeof patch.pendingUpdateVersion === 'string') {
persisted.pendingUpdateVersion = patch.pendingUpdateVersion;
}
@@ -10,8 +10,7 @@ import { logger } from './logger.js';
*
* 1. `render-process-gone` —— 渲染进程没了(崩溃 / 被杀),**静默重建窗口**;
* 2. `unresponsive` —— 界面卡住超过 10 秒还没缓过来,同样重建;期间恢复(`responsive`)就取消;
* 3. `uncaughtException` / `unhandledRejection` —— 主进程的未捕获错误,
* 记完整堆栈,并且**只有在本机确认空闲时**才重启自己。
* 3. `uncaughtException` 只在本机空闲时重启;普通 `unhandledRejection` 仅记录堆栈。
*
* 两条限流(照抄灵动岛 supervisor 的口径,避免"崩溃 → 重建 → 立刻又崩"死循环刷日志):
* **10 分钟内最多 3 次**,超了只记日志、停下来等人工处理。
@@ -27,7 +26,7 @@ const UNRESPONSIVE_GRACE_MS = 10_000;
export interface CrashGuardOptions {
/** 销毁并重建主窗口(index.ts 里复用原有的"建窗 + 载入界面"逻辑) */
recoverMainWindow: () => void;
recoverMainWindow: () => void | Promise<void>;
/** 本机是否空闲(不在上课且主窗口不可见)—— 决定主进程崩溃后能不能自动重启 */
isIdle: () => boolean;
/** 退出应用(复用既有的退出路径,保证配置落盘) */
@@ -56,7 +55,7 @@ export function installCrashGuard(guard: CrashGuardOptions): void {
logger.error(
`主窗口渲染进程异常退出:reason=${details.reason} exitCode=${details.exitCode}(准备重建窗口)`,
);
recoverWindow(`渲染进程退出(${details.reason})`);
void recoverWindow(`渲染进程退出(${details.reason})`);
});
app.on('child-process-gone', (_event, details) => {
@@ -72,7 +71,6 @@ export function installCrashGuard(guard: CrashGuardOptions): void {
process.on('unhandledRejection', (reason) => {
logger.error('主进程未处理的 Promise 拒绝:', reason);
restartIfIdle('unhandledRejection');
});
}
@@ -107,18 +105,17 @@ function armUnresponsiveTimer(): void {
unresponsiveTimer = setTimeout(() => {
unresponsiveTimer = null;
if (!mainWindow || mainWindow.isDestroyed()) return;
recoverWindow('界面无响应超过 10 秒');
void recoverWindow('界面无响应超过 10 秒');
}, UNRESPONSIVE_GRACE_MS);
}
function isMainWindowContents(id: number): boolean {
// 主窗口引用还没建立(启动早期)时按"就是它"处理,避免漏掉重建
if (!mainWindow || mainWindow.isDestroyed()) return true;
if (!mainWindow || mainWindow.isDestroyed()) return false;
return mainWindow.webContents.id === id;
}
/** 静默重建主窗口(限流) */
function recoverWindow(reason: string): void {
async function recoverWindow(reason: string): Promise<void> {
const recover = options?.recoverMainWindow;
if (recovering) return;
if (!recover) {
@@ -145,7 +142,7 @@ function recoverWindow(reason: string): void {
win.hide();
}
logger.warn(`开始重建主窗口(${reason},本窗口期第 ${windowRecoverAt.length} 次)`);
recover();
await recover();
} catch (error) {
logger.error(`重建主窗口失败:${error instanceof Error ? error.message : String(error)}`);
} finally {
+94 -85
View File
@@ -18,6 +18,7 @@ const currentDir = __dirname;
const devServerUrl = process.env.VITE_DEV_SERVER_URL;
const isSmokeTest = process.env.ELECTRON_SMOKE_TEST === '1';
const isQuickSmoke = isSmokeTest && process.env.ELECTRON_SMOKE_MODE !== 'visual';
/**
* 这次启动是否需要"直接进托盘、不弹窗"——开机自启专用(见 `applyAutoLaunch()`)。
@@ -73,6 +74,7 @@ function createWindow(options: { hidden?: boolean } = {}): BrowserWindow {
title: 'ClassHelper',
// 冒烟验证时不弹窗,避免打扰使用者;开机自启(--hidden)时直接进托盘
show: !isSmokeTest && options.hidden !== true,
focusable: !isQuickSmoke,
autoHideMenuBar: true,
backgroundColor: theme === 'dark' ? '#161719' : '#f3f3f3',
webPreferences: {
@@ -81,6 +83,8 @@ function createWindow(options: { hidden?: boolean } = {}): BrowserWindow {
nodeIntegration: false,
sandbox: true,
webSecurity: true,
backgroundThrottling: false,
offscreen: isQuickSmoke,
},
});
@@ -99,6 +103,12 @@ function createWindow(options: { hidden?: boolean } = {}): BrowserWindow {
win.on('closed', () => {
if (mainWindow === win) mainWindow = null;
});
win.on('close', (event) => {
if (isQuitting) return;
event.preventDefault();
win.hide();
logger.info('主窗口已隐藏到系统托盘(后台继续运行)');
});
// 崩溃自愈与「空闲安装更新」都要盯着主窗口:窗口重建后换的是新实例,因此每次建窗都重挂一次
watchCrashGuardWindow(win);
@@ -117,7 +127,7 @@ function ensureMainWindow(options: { hidden?: boolean } = {}): BrowserWindow | n
if (mainWindow && !mainWindow.isDestroyed()) return mainWindow;
try {
mainWindow = createWindow(options);
void loadRenderer(mainWindow);
void loadRenderer(mainWindow).catch((error) => logger.error('重建主窗口加载失败', error));
} catch (error) {
logger.error(`创建主窗口失败:${error instanceof Error ? error.message : String(error)}`);
mainWindow = null;
@@ -172,95 +182,95 @@ if (!gotLock) {
showMainWindow();
});
app.whenReady().then(async () => {
// 日志级别跟开发者模式走:debug 只在开启时才输出(设置页「开发者模式」)
logger.setVerbose(getConfig().developerMode === true);
registerIpcHandlers();
registerIslandIpc();
app
.whenReady()
.then(async () => {
// 日志级别跟开发者模式走:debug 只在开启时才输出(设置页「开发者模式」)
logger.setVerbose(getConfig().developerMode === true);
registerIpcHandlers();
registerIslandIpc();
// 开机自启:登录项要与配置保持一致(用户在设置页改过之后由 IPC 立即同步)
applyAutoLaunch();
// 开机自启:登录项要与配置保持一致(用户在设置页改过之后由 IPC 立即同步)
applyAutoLaunch();
mainWindow = createWindow({ hidden: startHidden });
await loadRenderer(mainWindow);
mainWindow = createWindow({ hidden: startHidden });
// 崩溃自愈:主窗口渲染进程崩溃 / 界面无响应时静默重建;主进程崩溃且本机空闲时自动重启
installCrashGuard({
recoverMainWindow: () => {
const alive = mainWindow && !mainWindow.isDestroyed() ? mainWindow : null;
if (alive) {
alive.hide();
alive.destroy();
}
mainWindow = ensureMainWindow();
},
isIdle: () =>
island.getState().inClass === false &&
mainWindow?.isVisible() !== true &&
!BrowserWindow.getAllWindows().some((win) => !win.isDestroyed() && win.isVisible()),
quitApp: () => quitApp(),
});
// 空闲安装更新:先把手动退出的回调交给 auto-update(它不能再 import 本文件,否则循环导入)
setQuitHandler(() => quitApp());
// 灵动岛:独立的置顶透明小窗口(桌面中上方)
try {
await island.init(devServerUrl ? `${devServerUrl.replace(/\/+$/, '')}/island.html` : null);
// 点击灵动岛里的"打开应用"时把主窗口拉到前台
island.setOpenAppHandler(() => {
if (!mainWindow || mainWindow.isDestroyed()) return;
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.show();
mainWindow.focus();
// 崩溃自愈:主窗口渲染进程崩溃 / 界面无响应时静默重建;主进程崩溃且本机空闲时自动重启
installCrashGuard({
recoverMainWindow: async () => {
const alive = mainWindow && !mainWindow.isDestroyed() ? mainWindow : null;
if (alive) {
alive.hide();
alive.destroy();
}
mainWindow = createWindow({ hidden: true });
await loadRenderer(mainWindow);
},
isIdle: () =>
island.getState().inClass === false &&
mainWindow?.isVisible() !== true &&
!BrowserWindow.getAllWindows().some((win) => !win.isDestroyed() && win.isVisible()),
quitApp: () => quitApp(),
});
// 灵动岛点"标为已读":转交主窗口渲染进程调用接口并刷新通知中心
island.setMarkReadHandler((id) => {
if (!mainWindow || mainWindow.isDestroyed()) return;
mainWindow.webContents.send('island:mark-read', id);
});
// 多条通知时的"标为已读"是**整批**操作:一次把列表里的通知都标上
island.setMarkAllReadHandler((ids) => {
if (!mainWindow || mainWindow.isDestroyed()) return;
mainWindow.webContents.send('island:mark-all-read', ids);
});
} catch (error) {
logger.error('灵动岛初始化失败(不影响主功能)', error);
}
await loadRenderer(mainWindow).catch((error) => logger.error('主窗口启动加载失败', error));
// 空闲安装更新:先把手动退出的回调交给 auto-update(它不能再 import 本文件,否则循环导入)
setQuitHandler(() => quitApp());
// 关闭主窗口 → 隐藏到系统托盘(需求 5),只有托盘"退出"才真正结束进程
// 注意:必须在冒烟验证之前挂载,否则 close() 会真的销毁窗口
mainWindow?.on('close', (event) => {
if (isQuitting) return;
event.preventDefault();
mainWindow?.hide();
logger.info('主窗口已隐藏到系统托盘(后台继续运行,左键托盘图标可恢复)');
});
try {
createTray({
onShow: () => showMainWindow(),
onHide: () => mainWindow?.hide(),
onQuit: () => quitApp(),
});
} catch (error) {
logger.warn(`系统托盘初始化失败(不影响主功能):${error instanceof Error ? error.message : error}`);
}
// 启动后自动查一次更新(延迟几秒,不跟首屏抢带宽);冒烟模式下自动跳过,见 main/update.ts
scheduleStartupUpdateCheck(() => mainWindow);
// 服务端统一下发:定时上报本机状态并领取「待执行命令 / 统一更新」(冒烟默认不上报)
startClientAgent();
if (isSmokeTest) {
// 灵动岛:独立的置顶透明小窗口(桌面中上方)
try {
await runSmokeTest(mainWindow);
if (!isQuickSmoke)
await island.init(devServerUrl ? `${devServerUrl.replace(/\/+$/, '')}/island.html` : null);
// 点击灵动岛里的"打开应用"时把主窗口拉到前台
island.setOpenAppHandler(() => {
if (!mainWindow || mainWindow.isDestroyed()) return;
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.show();
mainWindow.focus();
});
// 灵动岛点"标为已读":转交主窗口渲染进程调用接口并刷新通知中心
island.setMarkReadHandler((id) => {
if (!mainWindow || mainWindow.isDestroyed()) return;
mainWindow.webContents.send('island:mark-read', id);
});
// 多条通知时的"标为已读"是**整批**操作:一次把列表里的通知都标上
island.setMarkAllReadHandler((ids) => {
if (!mainWindow || mainWindow.isDestroyed()) return;
mainWindow.webContents.send('island:mark-all-read', ids);
});
} catch (error) {
console.error('[SMOKE] 冒烟验证异常', error);
app.exit(1);
logger.error('灵动岛初始化失败(不影响主功能)', error);
}
}
});
try {
if (!isQuickSmoke)
createTray({
onShow: () => showMainWindow(),
onHide: () => mainWindow?.hide(),
onQuit: () => quitApp(),
});
} catch (error) {
logger.warn(`系统托盘初始化失败(不影响主功能):${error instanceof Error ? error.message : error}`);
}
// 启动后自动查一次更新(延迟几秒,不跟首屏抢带宽);冒烟模式下自动跳过,见 main/update.ts
scheduleStartupUpdateCheck(() => mainWindow);
// 服务端统一下发:定时上报本机状态并领取「待执行命令 / 统一更新」(冒烟默认不上报)
startClientAgent();
if (isSmokeTest) {
try {
await runSmokeTest(mainWindow);
} catch (error) {
console.error('[SMOKE] 冒烟验证异常', error);
app.exit(1);
}
}
})
.catch((error) => {
logger.error('应用初始化失败', error);
if (isSmokeTest) app.exit(1);
});
/** 显示主窗口(托盘左键 / 托盘菜单 / 二次启动 / 灵动岛"打开应用") */
function showMainWindow(): void {
@@ -326,10 +336,9 @@ if (!gotLock) {
logger.info(`应用退出清理:${summary}`);
});
app.on('activate', async () => {
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
const win = ensureMainWindow();
if (win) await loadRenderer(win);
ensureMainWindow();
}
});
}
+5 -1
View File
@@ -17,7 +17,11 @@ export function registerIpcHandlers(): void {
ipcMain.handle(
IPC_CHANNELS.saveConfig,
(_event, patch: Partial<DesktopStoredConfig>): DesktopStoredConfig => {
return saveConfig(patch ?? {});
// 更新安装记录只允许主进程内部写入,渲染进程不得借配置通道指定可执行文件。
const allowed = { ...patch };
delete allowed.pendingUpdateFile;
delete allowed.pendingUpdateVersion;
return saveConfig(allowed);
},
);
+38 -18
View File
@@ -341,9 +341,7 @@ class IslandController {
if (this.previewId && this.state.active?.id === this.previewId) return;
const sinceActivated = Date.now() - this.state.updatedAt;
if (this.isCursorOnIsland()) {
logger.info(
`灵动岛:忽略失焦(指针仍在岛上,判定为展开时的激活抖动)距上次状态=${sinceActivated}ms`,
);
logger.info(`灵动岛:忽略失焦(指针仍在岛上,判定为展开时的激活抖动)距上次状态=${sinceActivated}ms`);
return;
}
// 触摸屏上没有"指针"可依据(isCursorOnIsland 恒为 false),只能用更宽的宽限期覆盖
@@ -828,10 +826,13 @@ class IslandController {
*/
this.setState({ mode: 'pill', reason: 'closing' }, { skipWindow: true });
const speed = clamp(this.appearance.speed, 0.5, 2, 1);
this.closeTimer = setTimeout(() => {
this.closeTimer = null;
this.finishClose();
}, Math.round(CLOSE_ANIMATION_MS / speed));
this.closeTimer = setTimeout(
() => {
this.closeTimer = null;
this.finishClose();
},
Math.round(CLOSE_ANIMATION_MS / speed),
);
}
/**
@@ -876,6 +877,13 @@ class IslandController {
this.win = null;
}
/** 教师撤回通知后,同时移除正在展示和等待下课的副本。 */
removeNotification(id: string): void {
this.state.queued = this.state.queued.filter((item) => item.id !== id);
if (this.state.active?.id === id) this.dismissActive();
else this.setState({});
}
/* ------------------------------------------------------------ 内部实现 */
private dismissActive(): void {
@@ -908,7 +916,6 @@ class IslandController {
this.hide();
}
private activate(notification: IslandNotification, reason: IslandState['reason'], mode: IslandMode): void {
this.clearTimers();
// 正在展示的通知从队列中移出,queue 只保留"尚未看过"的
@@ -1010,11 +1017,7 @@ class IslandController {
? 'right'
: 'center';
const hValue =
hMode === 'left'
? area.x + marginX
: hMode === 'right'
? area.x + area.width - marginX
: center;
hMode === 'left' ? area.x + marginX : hMode === 'right' ? area.x + area.width - marginX : center;
return { hMode, hValue, vMode, vValue };
}
@@ -1834,7 +1837,6 @@ const PREVIEW_DURATION_MS = 30_000;
*/
const MIN_CARD_HEIGHT = 120;
/**
* 渲染进程心跳(渲染进程每 5s 上报一次,间隔写死在 `src/island/IslandApp.vue`):
* 超过这个时间没上报就认为它已经卡死/不响应。
@@ -1866,6 +1868,9 @@ export const island = new IslandController();
/** 注册灵动岛相关 IPC(主窗口渲染进程 -> 主进程;灵动岛渲染进程 -> 主进程) */
export function registerIslandIpc(): void {
ipcMain.on('island:remove-notification', (_event, id: string) => {
if (typeof id === 'string') island.removeNotification(id);
});
ipcMain.on(
'island:push',
(_event, payload: { notification: IslandNotification; context?: IslandPushContext }) => {
@@ -1884,13 +1889,28 @@ export function registerIslandIpc(): void {
island.noteRendererAlive();
});
ipcMain.handle('island:get-state', () => island.getState());
let appearancePatch: Partial<IslandAppearance> | null = null;
let appearanceTimer: ReturnType<typeof setTimeout> | null = null;
const flushAppearance = (): void => {
if (appearanceTimer) clearTimeout(appearanceTimer);
appearanceTimer = null;
if (appearancePatch) island.setAppearance(appearancePatch);
appearancePatch = null;
};
ipcMain.handle('island:get-state', () => {
flushAppearance();
return island.getState();
});
ipcMain.on('island:set-appearance', (_event, patch: Partial<IslandAppearance>) => {
if (patch) island.setAppearance(patch);
if (!patch) return;
appearancePatch = { ...appearancePatch, ...patch };
if (!appearanceTimer) appearanceTimer = setTimeout(flushAppearance, 16);
});
ipcMain.handle('island:get-appearance', () => island.getAppearance());
ipcMain.handle('island:get-appearance', () => {
flushAppearance();
return island.getAppearance();
});
// 渲染进程命中测试结果 → **只用于立刻打开命中**(比 60ms 轮询更快)。
// 关闭命中一律由主进程按真实光标决定:两边都下发 true/false 会互相覆盖,
@@ -0,0 +1,106 @@
import fs from 'node:fs';
import path from 'node:path';
import { app, BrowserWindow } from 'electron';
import { getConfig } from './config.js';
/** 后台冒烟只检启动、桥接、缓存与窗口生命周期;屏幕像素和动画由显式视觉验收覆盖。 */
export async function runQuickSmoke(win: BrowserWindow): Promise<void> {
const startedAt = Date.now();
const results: Array<{ name: string; ok: boolean; detail: string; durationMs: number }> = [];
async function check(name: string, action: () => Promise<boolean | string> | boolean): Promise<void> {
const start = Date.now();
try {
const result = await action();
results.push({
name,
ok: result !== false,
detail: typeof result === 'string' ? result : '',
durationMs: Date.now() - start,
});
} catch (error) {
results.push({ name, ok: false, detail: String(error), durationMs: Date.now() - start });
}
const last = results.at(-1)!;
console.log(`[${last.ok ? 'PASS' : 'FAIL'}] ${name}(${last.durationMs}ms)${last.detail}`);
}
await check('后台启动并挂载界面', async () => {
const deadline = Date.now() + 10_000;
while (Date.now() < deadline) {
if (
await win.webContents.executeJavaScript(
`Boolean(window.__classhelperSmoke__ && document.querySelector('input, .el-menu-item'))`,
)
)
return true;
await new Promise((resolve) => setTimeout(resolve, 50));
}
return false;
});
await check('所有验证窗口保持隐藏且不获取焦点', () =>
BrowserWindow.getAllWindows().every((item) => !item.isVisible() && !item.isFocused()),
);
await check('预加载桥接白名单', async () =>
win.webContents.executeJavaScript(`Boolean(window.desktop?.getConfig && !window.desktop.ipcRenderer)`),
);
await check('渲染进程不能改写安装记录或设备身份', async () => {
const before = getConfig();
const after = await win.webContents.executeJavaScript(
`window.desktop.saveConfig({ pendingUpdateFile: 'C:/unexpected.exe', pendingUpdateVersion: '999.0.0', deviceKey: 'unexpected' })`,
);
return (
after.pendingUpdateFile === before.pendingUpdateFile &&
after.pendingUpdateVersion === before.pendingUpdateVersion &&
after.deviceKey === before.deviceKey
);
});
for (const [name, method] of [
['IndexedDB 缓存读写', 'cacheSelfTest'],
['断网缓存回退', 'offlineScenario'],
['服务端与班级缓存隔离', 'cacheIsolationSelfTest'],
]) {
await check(name!, async () => {
const result = await win.webContents.executeJavaScript(`window.__classhelperSmoke__.${method}()`);
if (!result.ok) throw new Error(result.detail);
return result.detail;
});
}
if (process.env.ELECTRON_SMOKE_ONLINE === '1') {
await check('后台登录与数据、实时通道集成', async () => {
const credentials = {
code: process.env.ELECTRON_SMOKE_CLASS_CODE ?? '',
password: process.env.ELECTRON_SMOKE_CLASS_PASSWORD ?? '',
serverUrl: (process.env.ELECTRON_SMOKE_API ?? 'http://127.0.0.1:4000/api').replace(/\/api\/?$/, ''),
};
const result = await win.webContents.executeJavaScript(
`window.__classhelperSmoke__.onlineScenario(${JSON.stringify(credentials)})`,
);
if (!result.ok) throw new Error(result.detail);
await win.webContents.executeJavaScript('window.__classhelperSmoke__.sessionCleanup()');
return result.detail;
});
}
await check('检查结束时没有可见或聚焦的验证窗口', () =>
BrowserWindow.getAllWindows().every((item) => !item.isVisible() && !item.isFocused()),
);
await check('关闭窗口仍隐藏而不销毁', () => {
win.close();
return !win.isDestroyed() && !win.isVisible() && app.isReady();
});
const failed = results.filter((result) => !result.ok);
const result = {
passed: results.length - failed.length,
total: results.length,
ok: !failed.length,
mode: 'quick',
durationMs: Date.now() - startedAt,
results,
appVersion: app.getVersion(),
packaged: app.isPackaged,
};
if (process.env.ELECTRON_SMOKE_RESULT) {
fs.mkdirSync(path.dirname(process.env.ELECTRON_SMOKE_RESULT), { recursive: true });
fs.writeFileSync(process.env.ELECTRON_SMOKE_RESULT, JSON.stringify(result, null, 2));
}
console.log(`[SMOKE] 后台快速检查 ${result.passed}/${result.total} 项通过,${result.durationMs}ms`);
app.exit(failed.length ? 1 : 0);
}
+23 -64
View File
@@ -1,4 +1,5 @@
import fs from 'node:fs';
import { runQuickSmoke } from './smoke-quick.js';
import path from 'node:path';
import { app, BrowserWindow, desktopCapturer, screen } from 'electron';
import type { NativeImage } from 'electron';
@@ -1150,7 +1151,10 @@ async function runIslandChecks(
const shotAppearance: Parameters<typeof island.setAppearance>[0] = {
accent: process.env.ELECTRON_SMOKE_ISLAND_ACCENT ?? '#e91e8c',
};
if (process.env.ELECTRON_SMOKE_ISLAND_STYLE === 'black' || process.env.ELECTRON_SMOKE_ISLAND_STYLE === 'glass') {
if (
process.env.ELECTRON_SMOKE_ISLAND_STYLE === 'black' ||
process.env.ELECTRON_SMOKE_ISLAND_STYLE === 'glass'
) {
shotAppearance.style = process.env.ELECTRON_SMOKE_ISLAND_STYLE;
} else if (!process.env.ELECTRON_SMOKE_ISLAND_STYLE) {
shotAppearance.style = 'tinted';
@@ -4125,67 +4129,17 @@ async function runSettingsPageMarginCheck(
};
}
async function runSettingsPageChannelCheck(win: BrowserWindow): Promise<{ ok: boolean; detail: string }> {
const result = (await win.webContents
.executeJavaScript(
`(async () => {
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const before = (await window.desktop.getConfig()).notificationChannel;
location.hash = '#/settings/reminder';
// 找到「通知显示位置」那张卡片里的单选组
let group = null;
for (let i = 0; i < 40 && !group; i += 1) {
await wait(100);
group = Array.from(document.querySelectorAll('.el-card')).find((card) =>
(card.querySelector('.el-card__header')?.textContent ?? '').includes('ClassIsland 联动'),
);
}
if (!group) return { ok: false, detail: '设置页没有「ClassIsland 联动」卡片' };
const radios = Array.from(group.querySelectorAll('.el-radio'));
// 注意:这段脚本本身是外层模板字符串,里面不能再出现反引号(会截断外层字符串)
if (radios.length < 3) return { ok: false, detail: '单选项只有 ' + radios.length + ' 个' };
// 点第二个(只在 ClassHelper 客户端弹),断言配置真的写下去了
radios[1].click();
await wait(600);
const afterClient = (await window.desktop.getConfig()).notificationChannel;
const clientChecked = radios[1].classList.contains('is-checked');
// 再点回第一个(两端都弹),避免影响后续用例
radios[0].click();
await wait(600);
const afterBoth = (await window.desktop.getConfig()).notificationChannel;
location.hash = '#/schedule';
return { ok: true, before, afterClient, afterBoth, clientChecked, labels: radios.map((n) => n.textContent.trim()) };
})()`,
)
.catch((error: unknown) => ({
ok: false as const,
detail: `执行失败:${error instanceof Error ? error.message : String(error)}`,
}))) as
| {
ok: true;
before: string;
afterClient: string;
afterBoth: string;
clientChecked: boolean;
labels: string[];
}
| { ok: false; detail: string }
| null;
if (result?.ok) {
return {
ok: result.afterClient === 'client' && result.clientChecked && result.afterBoth === 'both',
detail:
`单选项=[${result.labels.join(' / ')}],` +
`选择「只在 ClassHelper 客户端弹」后配置 ${result.before} → ${result.afterClient}(选中=${result.clientChecked}),` +
`切回后 ${result.afterBoth}`,
};
}
return { ok: false, detail: result?.detail ?? '未执行' };
const text = await win.webContents.executeJavaScript(`(async () => {
location.hash = '#/settings/reminder';
await new Promise((resolve) => setTimeout(resolve, 500));
return document.body.innerText;
})()`);
return {
ok: text.includes('通知提醒') && !text.includes('ClassIsland 联动'),
detail: '通知统一由客户端提醒',
};
}
/**
* Electron 冒烟验证(ELECTRON_SMOKE_TEST=1 时触发,跑完自动退出)。
* 覆盖:preload 桥接、渲染进程挂载、登录页 DOM、IndexedDB 缓存读写、离线回退,
@@ -4227,6 +4181,7 @@ async function runTrayAndShutdownChecks(mainWin: BrowserWindow, record: Recorder
);
}
export async function runSmokeTest(win: BrowserWindow): Promise<void> {
if (process.env.ELECTRON_SMOKE_MODE !== 'visual') return runQuickSmoke(win);
const results: SmokeResult[] = [];
const record = (name: string, ok: boolean, detail = ''): void => {
results.push({ name, ok, detail });
@@ -4395,10 +4350,14 @@ export async function runSmokeTest(win: BrowserWindow): Promise<void> {
// 班级账号凭据由 scripts/smoke.mjs 通过管理端接口准备(渲染进程读不到 process.env)
const classCode = process.env.ELECTRON_SMOKE_CLASS_CODE ?? '';
const classPassword = process.env.ELECTRON_SMOKE_CLASS_PASSWORD ?? '';
const serverUrl = (process.env.ELECTRON_SMOKE_API ?? 'http://127.0.0.1:4000/api').replace(
/\/api\/?$/,
'',
);
const online = await win.webContents.executeJavaScript(
`(async () => {
if (!window.__classhelperSmoke__) return { ok: false, detail: '渲染进程未注册冒烟钩子' };
return await window.__classhelperSmoke__.onlineScenario(${JSON.stringify({ code: classCode, password: classPassword })});
return await window.__classhelperSmoke__.onlineScenario(${JSON.stringify({ code: classCode, password: classPassword, serverUrl })});
})()`,
);
record(
@@ -4413,9 +4372,9 @@ export async function runSmokeTest(win: BrowserWindow): Promise<void> {
const settingsAppearance = await runSettingsPageAppearanceCheck(win);
record('设置页真实 UI:拖拽滑块即时改变灵动岛外观', settingsAppearance.ok, settingsAppearance.detail);
// 通知显示位置(客户端自己选):提醒弹在 ClassHelper 还是 ClassIsland
// 提醒设置:仅保留本机通知与教师管理的成绩查询状态
const settingsChannel = await runSettingsPageChannelCheck(win);
record('设置页真实 UI:切换「通知显示位置」写回本地配置', settingsChannel.ok, settingsChannel.detail);
record('设置页真实 UI:提醒规则展示且无退役联动入口', settingsChannel.ok, settingsChannel.detail);
// 改密入口(2026-10-01 用户要求移除:班级密码只由管理员在 Web 端维护)——负断言防退化
const settingsPassword = await runSettingsPagePasswordEntryCheck(win);
@@ -50,6 +50,9 @@ const bridge: DesktopBridge = {
islandPush: (payload: { notification: IslandNotification; context?: IslandPushContext }): void => {
ipcRenderer.send('island:push', payload);
},
islandRemoveNotification: (id: string): void => {
ipcRenderer.send('island:remove-notification', id);
},
islandSetClassState: (payload: IslandClassStatePayload): void => {
ipcRenderer.send('island:class-state', payload);
},
@@ -102,14 +102,6 @@ onMounted(async () => {
bootText.value = '正在恢复登录状态...';
const session = await auth.restore();
// 通知显示位置:先用本地配置兜底(断网也要按上次的选择决定本机弹不弹),
// 登录态就绪后再向服务器对齐一次(服务端才是单一事实来源)
const storedConfig = await window.desktop?.getConfig?.();
if (storedConfig?.notificationChannel) {
appStore.applyLocalNotificationChannel(storedConfig.notificationChannel);
}
void appStore.loadNotificationChannel(auth.classId);
// 连通性探测与健康轮询放到后台,不阻塞进入界面(离线时也能立刻看到缓存数据)
void appStore.init(session.serverUrl);
@@ -2,7 +2,6 @@ import {
API_PATHS,
type ClassDetailDto,
type ClassDto,
type ClassIslandNotificationChannel,
type CourseDto,
type ExamDto,
type ExamRankingDto,
@@ -47,36 +46,6 @@ export const classApi = {
detail: (id: string): Promise<ClassDetailDto> => api.get(`${API_PATHS.classes}/${id}`),
};
/**
* 通知显示位置(both / client / classisland)。
*
* 由**这台教室机器自己**决定"提醒弹在 ClassHelper 还是 ClassIsland":
* 本地存一份用于本机的弹窗/上岛判断,同时写回班级记录,服务端据此决定要不要推 ClassIsland。
*/
export const classChannelApi = {
get: (classId: string): Promise<{ notificationChannel: ClassIslandNotificationChannel }> =>
api.get(`${API_PATHS.classes}/${classId}/notification-channel`),
set: (
classId: string,
notificationChannel: ClassIslandNotificationChannel,
): Promise<{ notificationChannel: ClassIslandNotificationChannel }> =>
api.patch(`${API_PATHS.classes}/${classId}/notification-channel`, { notificationChannel }),
};
/** 本班 ClassIsland 联动状态(教室客户端「设置 → ClassIsland 联动」展示) */
export const classIslandStatusApi = {
get: (
classId: string,
): Promise<{
connected: boolean;
deviceName: string | null;
deviceCount: number;
lastSeenAt: string | null;
pluginVersion: string | null;
classIslandVersion: string | null;
}> => api.get(`${API_PATHS.classes}/${classId}/classisland-status`),
};
export const scheduleApi = {
list: (params: { classId?: string; week?: number }): Promise<ScheduleDto[]> =>
api.get(API_PATHS.schedules, params),
@@ -151,13 +120,11 @@ export const gradeApi = {
/**
* ClassHelper 班级端设置:「是否允许按学号查询本班学生成绩明细」。
* 与通知显示位置同一套模式 —— 由教室机器自己决定,教师/管理员在 Web 端也能改。
* 教师/管理员在 Web 端控制,教室机器只读取当前状态。
*/
export const classGradeQueryApi = {
get: (classId: string): Promise<{ studentGradeQueryEnabled: boolean }> =>
api.get(`${API_PATHS.classes}/${classId}/student-grade-query`),
set: (classId: string, enabled: boolean): Promise<{ studentGradeQueryEnabled: boolean }> =>
api.patch(`${API_PATHS.classes}/${classId}/student-grade-query`, { enabled }),
};
export const dashboardApi = {
+55 -12
View File
@@ -1,3 +1,5 @@
import { getCacheScope, scopedKey } from './scope.js';
/**
* IndexedDB 缓存层(无第三方依赖)。
*
@@ -37,7 +39,8 @@ let databasePromise: Promise<IDBDatabase> | null = null;
function openDatabase(): Promise<IDBDatabase> {
if (databasePromise) return databasePromise;
databasePromise = new Promise<IDBDatabase>((resolve, reject) => {
let failed = false;
const opening = new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onupgradeneeded = () => {
@@ -49,12 +52,36 @@ function openDatabase(): Promise<IDBDatabase> {
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error ?? new Error('IndexedDB 打开失败'));
request.onblocked = () => reject(new Error('IndexedDB 被其它窗口占用'));
request.onsuccess = () => {
const db = request.result;
if (failed) {
db.close();
return;
}
const reset = (): void => {
if (databasePromise === opening) databasePromise = null;
};
db.onversionchange = () => {
db.close();
reset();
};
db.onclose = reset;
resolve(db);
};
request.onerror = () => {
failed = true;
reject(request.error ?? new Error('IndexedDB 打开失败'));
};
request.onblocked = () => {
failed = true;
reject(new Error('IndexedDB 被其它窗口占用'));
};
});
return databasePromise;
databasePromise = opening;
void opening.catch(() => {
if (databasePromise === opening) databasePromise = null;
});
return opening;
}
function runRequest<T>(
@@ -67,7 +94,8 @@ function runRequest<T>(
new Promise<T>((resolve, reject) => {
const transaction = db.transaction(store, mode);
const request = action(transaction.objectStore(store));
request.onsuccess = () => resolve(request.result as T);
transaction.oncomplete = () => resolve(request.result as T);
transaction.onabort = () => reject(transaction.error ?? new Error('IndexedDB 事务已中止'));
request.onerror = () => reject(request.error ?? new Error('IndexedDB 操作失败'));
}),
);
@@ -89,14 +117,28 @@ function toPlain<T>(value: T): T {
}
}
export async function cacheSet<T>(store: CacheStore, key: string, value: T): Promise<void> {
const record: CacheRecord<T> = { key, value: toPlain(value), updatedAt: Date.now() };
export async function cacheSet<T>(
store: CacheStore,
key: string,
value: T,
scope = getCacheScope(),
): Promise<void> {
const record: CacheRecord<T> = {
key: store === 'profile' ? key : scopedKey(key, scope),
value: toPlain(value),
updatedAt: Date.now(),
};
await runRequest<IDBValidKey>(store, 'readwrite', (objectStore) => objectStore.put(record));
}
export function cacheGet<T>(store: CacheStore, key: string): Promise<CacheRecord<T> | null> {
export function cacheGet<T>(
store: CacheStore,
key: string,
scope = getCacheScope(),
): Promise<CacheRecord<T> | null> {
const resolvedKey = store === 'profile' ? key : scopedKey(key, scope);
return runRequest<CacheRecord<T> | undefined>(store, 'readonly', (objectStore) =>
objectStore.get(key),
objectStore.get(resolvedKey),
).then((record) => record ?? null);
}
@@ -105,7 +147,8 @@ export function cacheList<T>(store: CacheStore): Promise<Array<CacheRecord<T>>>
}
export async function cacheRemove(store: CacheStore, key: string): Promise<void> {
await runRequest<undefined>(store, 'readwrite', (objectStore) => objectStore.delete(key));
const resolvedKey = store === 'profile' ? key : scopedKey(key);
await runRequest<undefined>(store, 'readwrite', (objectStore) => objectStore.delete(resolvedKey));
}
export async function cacheClearStore(store: CacheStore): Promise<void> {
+9 -2
View File
@@ -1,4 +1,5 @@
import { cacheGet, cacheSet, type CacheStore } from './db.js';
import { getCacheScope } from './scope.js';
export interface CachedFetchResult<T> {
data: T;
@@ -23,13 +24,19 @@ export async function fetchWithCache<T>(
loader: () => Promise<T>,
fallback: T,
): Promise<CachedFetchResult<T>> {
const scope = getCacheScope();
try {
const data = await loader();
await cacheSet(store, key, data);
if (scope !== getCacheScope())
return { data: fallback, fromCache: false, updatedAt: null, error: '会话已切换' };
// 网络成功但本地磁盘不可用时,仍返回刚获取的数据。
await cacheSet(store, key, data, scope).catch(() => undefined);
return { data, fromCache: false, updatedAt: Date.now(), error: null };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
const cached = await cacheGet<T>(store, key).catch(() => null);
const cached = await cacheGet<T>(store, key, scope).catch(() => null);
if (scope !== getCacheScope())
return { data: fallback, fromCache: false, updatedAt: null, error: '会话已切换' };
if (cached) {
return { data: cached.value, fromCache: true, updatedAt: cached.updatedAt, error: message };
}
+22
View File
@@ -0,0 +1,22 @@
let activeScope = 'anonymous';
const listeners = new Set<() => void>();
/** 同一台机器可切换服务端与班级,两者都必须纳入缓存命名空间。 */
export function setCacheScope(server: string, identity: string): void {
const next = `${encodeURIComponent(server.replace(/\/+$/, ''))}@${encodeURIComponent(identity)}`;
if (next === activeScope) return;
activeScope = next;
for (const listener of listeners) listener();
}
export function getCacheScope(): string {
return activeScope;
}
export function scopedKey(key: string, scope = activeScope): string {
return `${scope}::${key}`;
}
export function onCacheScopeChanged(listener: () => void): void {
listeners.add(listener);
}
export function profileCacheKey(server: string, username: string): string {
return `${encodeURIComponent(server.replace(/\/+$/, ''))}@${encodeURIComponent(username)}::profile`;
}
+31 -6
View File
@@ -1,5 +1,27 @@
import { cacheGet, cacheRemove, cacheSet, cacheStats } from './db.js';
import { fetchWithCache } from './index.js';
import { setCacheScope } from './scope.js';
export async function cacheIsolationSelfTest(): Promise<SmokeCheckResult> {
const key = `scope-check-${Date.now()}`;
try {
setCacheScope('http://scope-a.invalid', 'class-a');
await cacheSet('grades', key, ['班级甲']);
setCacheScope('http://scope-a.invalid', 'class-b');
if (await cacheGet('grades', key)) return { ok: false, detail: '跨班级读到了缓存' };
setCacheScope('http://scope-b.invalid', 'class-a');
if (await cacheGet('grades', key)) return { ok: false, detail: '跨服务端读到了缓存' };
setCacheScope('http://scope-a.invalid', 'class-a');
const own = await cacheGet<string[]>('grades', key);
await cacheRemove('grades', key);
return { ok: own?.value[0] === '班级甲', detail: '换班和换服务端均隔离,原班缓存仍可读取' };
} finally {
setCacheScope('', 'anonymous');
}
}
/** 联网自检与造数、清理始终使用同一服务端。 */
let smokeServerUrl = 'http://127.0.0.1:4000';
export interface SmokeCheckResult {
ok: boolean;
@@ -208,7 +230,7 @@ async function seedSmokeContent(
need: { homework: boolean; notification: boolean },
): Promise<SmokeCheckResult> {
if (!classId) return { ok: false, detail: '缺少班级,无法自建数据' };
const serverUrl = 'http://127.0.0.1:4000';
const serverUrl = smokeServerUrl;
const stamp = `自检 ${new Date().toLocaleTimeString('zh-CN')}`;
try {
@@ -275,7 +297,7 @@ async function cleanupTemporaryContent(): Promise<string> {
if (!temporaryContent) return '';
const { token, homeworks, notifications } = temporaryContent;
temporaryContent = null;
const serverUrl = 'http://127.0.0.1:4000';
const serverUrl = smokeServerUrl;
const removals = [
...homeworks.map((id) => `/api/homeworks/${id}`),
...notifications.map((id) => `/api/notifications/${id}`),
@@ -298,6 +320,7 @@ async function cleanupTemporaryContent(): Promise<string> {
export async function onlineScenario(credentials?: {
code: string;
password: string;
serverUrl?: string;
}): Promise<SmokeCheckResult> {
const [{ useAuthStore }, { useAppStore }, { useRealtimeStore }, api, cache] = await Promise.all([
import('../stores/auth.js'),
@@ -311,7 +334,8 @@ export async function onlineScenario(credentials?: {
const appStore = useAppStore();
const realtime = useRealtimeStore();
const serverUrl = 'http://127.0.0.1:4000';
const serverUrl = credentials?.serverUrl ?? smokeServerUrl;
smokeServerUrl = serverUrl;
const detail: string[] = [];
try {
@@ -441,7 +465,7 @@ export async function islandRealtimeScenario(): Promise<{
import('../island/bridge.js'),
]);
const auth = useAuthStore();
const serverUrl = 'http://127.0.0.1:4000';
const serverUrl = smokeServerUrl;
const classId = auth.classId ?? null;
if (!classId) return { ok: false, detail: '当前学生没有班级,无法投递通知' };
@@ -499,7 +523,7 @@ export async function islandRealtimeCleanup(
teacherToken: string,
): Promise<SmokeCheckResult> {
try {
const response = await fetch(`http://127.0.0.1:4000/api/notifications/${notificationId}`, {
const response = await fetch(`${smokeServerUrl}/api/notifications/${notificationId}`, {
method: 'DELETE',
headers: { authorization: `Bearer ${teacherToken}` },
});
@@ -544,7 +568,7 @@ export async function scheduleTimelineSelfTest(): Promise<SmokeCheckResult> {
import('../router/index.js'),
]);
const auth = useAuthStore();
const serverUrl = 'http://127.0.0.1:4000';
const serverUrl = smokeServerUrl;
const classId = auth.classId ?? null;
if (!classId) return { ok: false, detail: '当前学生没有班级,无法构造课表' };
@@ -1172,6 +1196,7 @@ export async function aboutPageSelfTest(): Promise<SmokeCheckResult> {
export function registerSmokeHooks(): void {
window.__classhelperSmoke__ = {
cacheSelfTest,
cacheIsolationSelfTest,
offlineScenario,
layoutNavigationSelfTest,
onlineScenario,
@@ -102,7 +102,7 @@ function finish(): void {
}
function onKeydown(event: KeyboardEvent): void {
if (event.key === 'Escape') finish();
if (onboarding.visible && event.key === 'Escape') finish();
}
if (typeof window !== 'undefined') {
window.addEventListener('keydown', onKeydown);
@@ -154,9 +154,7 @@ onUnmounted(() => {
</div>
<div class="onboarding-actions">
<el-button v-if="!isFirst" data-action="prev" @click="goPrev">上一步</el-button>
<el-button v-if="!isLast" type="primary" data-action="next" @click="goNext">
下一步
</el-button>
<el-button v-if="!isLast" type="primary" data-action="next" @click="goNext">下一步</el-button>
<el-button v-else type="primary" data-action="finish" @click="finish">开始使用</el-button>
</div>
</div>
@@ -250,7 +248,7 @@ onUnmounted(() => {
margin: 0 0 8px;
font-size: 13px;
line-height: 1.8;
color: var(--ch-text-regular, #606266);
color: var(--ch-text-secondary);
}
.onboarding-foot {
@@ -0,0 +1,12 @@
import { ElMessageBox } from 'element-plus';
/** 取消是正常交互;真实异常继续交给调用方处理。 */
export async function confirmAction(...args: Parameters<typeof ElMessageBox.confirm>): Promise<boolean> {
try {
await ElMessageBox.confirm(...args);
return true;
} catch (reason) {
if (reason === 'cancel' || reason === 'close') return false;
throw reason;
}
}
@@ -1,3 +1,4 @@
import { watch, type WatchStopHandle } from 'vue';
import {
SOCKET_EVENTS,
resolveClassStatus,
@@ -8,6 +9,7 @@ import {
} from '@classhelper/shared';
import { notificationApi, scheduleApi } from '../api/index.js';
import { fetchWithCache } from '../cache/index.js';
import { getCacheScope } from '../cache/scope.js';
import { clearOfflineSince, readOfflineSince, useAppStore } from '../stores/app.js';
import { useAuthStore } from '../stores/auth.js';
import { useNotificationStore } from '../stores/notifications.js';
@@ -30,6 +32,9 @@ let currentPeriod: ClassPeriod | null = null;
let inClass = false;
let tickTimer: ReturnType<typeof setInterval> | null = null;
let refreshTimer: ReturnType<typeof setInterval> | null = null;
let stopWeekWatch: WatchStopHandle | null = null;
let scheduleRequest = 0;
let scheduleWeek = 1;
/** 供通知投递时读取:当前是否上课 + 本节课结束时间 */
export function getIslandClassContext(): { inClass: boolean; currentPeriodEnd: string | null } {
@@ -45,21 +50,28 @@ export async function refreshIslandSchedules(): Promise<void> {
const appStore = useAppStore();
const auth = useAuthStore();
if (!auth.token) return;
const scope = getCacheScope();
const classId = auth.classId ?? undefined;
await appStore.refreshTerm(classId);
if (scope !== getCacheScope() || !auth.token) return;
const request = ++scheduleRequest;
const week = appStore.currentWeek;
const result = await fetchWithCache<ScheduleDto[]>(
'schedules',
`week:${week}`,
() => scheduleApi.list({ classId: auth.classId ?? undefined, week }),
() => scheduleApi.list({ classId, week }),
[],
);
if (scope !== getCacheScope() || request !== scheduleRequest) return;
if (result.error && !result.updatedAt) return;
schedules = result.data;
scheduleWeek = week;
recomputeClassState(true);
}
function recomputeClassState(force = false): void {
const appStore = useAppStore();
const status = resolveClassStatus(schedules, new Date(), appStore.currentWeek);
const status = resolveClassStatus(schedules, new Date(), scheduleWeek);
const nextInClass = status.inClass;
currentPeriod = status.current;
@@ -313,6 +325,12 @@ function onScheduleUpdated(): void {
export function startIslandBridge(): void {
if (tickTimer) return;
stopWeekWatch = watch(
() => useAppStore().currentWeek,
() => {
void refreshIslandSchedules();
},
);
void refreshIslandSchedules().catch(() => undefined);
@@ -338,6 +356,9 @@ export function stopIslandBridge(): void {
if (refreshTimer) clearInterval(refreshTimer);
tickTimer = null;
refreshTimer = null;
scheduleRequest += 1;
stopWeekWatch?.();
stopWeekWatch = null;
useRealtimeStore().off(SOCKET_EVENTS.scheduleUpdated, onScheduleUpdated);
schedules = [];
@@ -1,7 +1,8 @@
<script setup lang="ts">
import { confirmAction } from '../composables/confirm.js';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, type MenuInstance } from 'element-plus';
import { ElMessage, type MenuInstance } from 'element-plus';
import { SOCKET_EVENTS, type NotificationDto } from '@classhelper/shared';
import { startIslandBridge, stopIslandBridge } from '../island/bridge.js';
import { useThemeReveal } from '../composables/motion.js';
@@ -354,7 +355,7 @@ const connectionText = computed(() => {
});
async function handleLogout(): Promise<void> {
await ElMessageBox.confirm('确认退出当前账号?离线缓存会保留。', '退出登录', { type: 'warning' });
if (!(await confirmAction('确认退出当前账号?离线缓存会保留。', '退出登录', { type: 'warning' }))) return;
realtime.disconnect();
await auth.logout();
ElMessage.success('已退出登录');
@@ -370,6 +371,10 @@ async function handleLogout(): Promise<void> {
function onNotification(payload: unknown): void {
void notifications.pushRealtime(payload as NotificationDto);
}
function onNotificationDeleted(payload: unknown): void {
void notifications.removeRealtime((payload as { id: string }).id);
window.desktop?.islandRemoveNotification((payload as { id: string }).id);
}
/** 服务器从不可达恢复为可达:自动同步一次(联网后自动同步) */
function onRecovered(): void {
@@ -378,9 +383,10 @@ function onRecovered(): void {
}
onMounted(async () => {
realtime.on(SOCKET_EVENTS.notificationNew, onNotification);
realtime.on(SOCKET_EVENTS.notificationDeleted, onNotificationDeleted);
await notifications.load().catch(() => undefined);
await notifications.refreshUnreadCount();
realtime.on(SOCKET_EVENTS.notificationNew, onNotification);
appStore.onServerRecovered(onRecovered);
// 灵动岛桥接跟着"已登录布局"的生命周期走:这样退出登录会随布局卸载而停止,
// 重新登录(或换班登录)时又会重新启动,不会拿旧课表算上课状态。
@@ -389,6 +395,7 @@ onMounted(async () => {
onUnmounted(() => {
realtime.off(SOCKET_EVENTS.notificationNew, onNotification);
realtime.off(SOCKET_EVENTS.notificationDeleted, onNotificationDeleted);
appStore.offServerRecovered(onRecovered);
stopIslandBridge();
});
@@ -410,7 +417,10 @@ onUnmounted(() => {
data-test="sidebar-toggle"
@click="ui.toggleSidebar()"
>
<el-icon :size="16"><Expand v-if="ui.sidebarCollapsed" /><Fold v-else /></el-icon>
<el-icon :size="16">
<Expand v-if="ui.sidebarCollapsed" />
<Fold v-else />
</el-icon>
</button>
<!-- 品牌区在折叠时**不是 v-if 删掉**,而是靠 CSS 收宽度 + 淡出:
v-if 会在动画中途把节点直接摘掉,看上去是"啪"地一跳;收放要连续就得让它们一直在。 -->
@@ -422,11 +432,7 @@ onUnmounted(() => {
把"跟着菜单滚出视口"的底片裁掉,不让它盖到品牌区/页脚上。
两层都 pointer-events:none —— 底片盖在菜单项上,否则会把点击吃掉。 -->
<div class="nav-indicator-clip" :style="clipStyle" aria-hidden="true">
<div
class="nav-indicator"
:class="{ 'is-following': indicatorFollowing }"
:style="indicatorStyle"
/>
<div class="nav-indicator" :class="{ 'is-following': indicatorFollowing }" :style="indicatorStyle" />
</div>
<el-menu
ref="menuRef"
@@ -495,7 +501,10 @@ onUnmounted(() => {
:aria-label="ui.theme === 'dark' ? '切换到浅色模式' : '切换到深色模式'"
@click="handleThemeToggle"
>
<el-icon><Sunny v-if="ui.theme === 'dark'" /><Moon v-else /></el-icon>
<el-icon>
<Sunny v-if="ui.theme === 'dark'" />
<Moon v-else />
</el-icon>
</el-button>
</el-tooltip>
<el-dropdown trigger="click">
@@ -1,15 +1,12 @@
import { computed, ref } from 'vue';
import { defineStore } from 'pinia';
import {
DEFAULT_CLASSISLAND_NOTIFICATION_CHANNEL,
STORAGE_KEYS,
formatDate,
type ClassIslandNotificationChannel,
} from '@classhelper/shared';
import { STORAGE_KEYS, formatDate } from '@classhelper/shared';
import { pingHealth, setApiBaseUrl, setReachabilityReporter } from '../api/http.js';
import { classChannelApi } from '../api/index.js';
import { cacheClearAll, cacheStats, type CacheStoreStat } from '../cache/db.js';
import { DEFAULT_SERVER, normalizeServerUrl } from '../config.js';
import { dashboardApi } from '../api/index.js';
import { fetchWithCache } from '../cache/index.js';
import { getCacheScope, onCacheScopeChanged } from '../cache/scope.js';
type RecoveryHandler = () => void;
@@ -70,13 +67,26 @@ export const useAppStore = defineStore('app', () => {
const currentWeek = ref(1);
const maxWeek = ref(20);
const initialized = ref(false);
/**
* 通知显示位置:这台教室机器把提醒弹在哪个端。
*
* 单一事实来源是**班级记录**(服务端),本地这份只是缓存:断网时也要能按上次的选择
* 决定本机弹不弹,所以启动时先读本地配置、登录后再向服务器对齐一次。
*/
const notificationChannel = ref<ClassIslandNotificationChannel>(DEFAULT_CLASSISLAND_NOTIFICATION_CHANNEL);
let termRequest = 0;
onCacheScopeChanged(() => {
currentWeek.value = 1;
maxWeek.value = 20;
termRequest += 1;
clearOfflineSince();
});
/** 当前教学周的单一写入入口,课表页与灵动岛共用。 */
async function refreshTerm(classId?: string): Promise<void> {
const request = ++termRequest;
const scope = getCacheScope();
const result = await fetchWithCache('classes', 'term', () => dashboardApi.term(classId), {
currentWeek: 1,
maxWeek: 20,
});
if (request !== termRequest || scope !== getCacheScope() || (result.error && !result.updatedAt)) return;
currentWeek.value = result.data.currentWeek;
maxWeek.value = result.data.maxWeek;
}
const offline = computed(() => !serverReachable.value);
const lastSyncText = computed(() => (lastSyncAt.value ? formatDate(lastSyncAt.value, true) : '尚未同步'));
@@ -178,53 +188,6 @@ export const useAppStore = defineStore('app', () => {
void refreshCacheStats();
}
/* ------------------------------------------------------------ 通知显示位置 */
/** 启动时用本地配置兜底(此时可能还没登录/断网) */
function applyLocalNotificationChannel(value: ClassIslandNotificationChannel): void {
notificationChannel.value = value;
}
/**
* 向服务器对齐显示位置。
* 登录后调用:以服务端为准(多台机器/老师改过之后,本地缓存可能已经过期)。
*/
async function loadNotificationChannel(classId: string | null): Promise<void> {
if (!classId) return;
try {
const result = await classChannelApi.get(classId);
notificationChannel.value = result.notificationChannel;
await window.desktop?.saveConfig({ notificationChannel: result.notificationChannel });
} catch {
// 离线/无权限:保留本地值,不影响展示
}
}
/**
* 改显示位置:先落本地(立刻生效),再写回班级记录。
* 服务端写失败时返回 false,由设置页提示"已保存在本机,联网后请重试"。
*/
async function setNotificationChannel(
classId: string | null,
value: ClassIslandNotificationChannel,
): Promise<boolean> {
notificationChannel.value = value;
await window.desktop?.saveConfig({ notificationChannel: value });
if (!classId) return false;
try {
const result = await classChannelApi.set(classId, value);
notificationChannel.value = result.notificationChannel;
return true;
} catch {
return false;
}
}
/** 本次提醒是否要在本机弹(弹窗 + 灵动岛);"只在 ClassIsland 上弹"时为 false */
function shouldPopupLocally(): boolean {
return notificationChannel.value !== 'classisland';
}
return {
serverUrl,
serverReachable,
@@ -236,17 +199,13 @@ export const useAppStore = defineStore('app', () => {
currentWeek,
maxWeek,
initialized,
notificationChannel,
init,
ping,
applyServerUrl,
applyLocalNotificationChannel,
loadNotificationChannel,
setNotificationChannel,
shouldPopupLocally,
refreshCacheStats,
clearCache,
markSynced,
refreshTerm,
onServerRecovered,
offServerRecovered,
stopHealthPolling,
@@ -5,8 +5,9 @@ import { authApi } from '../api/index.js';
import { setApiBaseUrl, setTokenProvider } from '../api/http.js';
import { cacheGet, cacheSet } from '../cache/db.js';
import { normalizeServerUrl } from '../config.js';
const PROFILE_KEY = 'me';
import { profileCacheKey, setCacheScope } from '../cache/scope.js';
let profileKey = '';
let sessionServer = '';
/**
* 登录态。
@@ -58,10 +59,13 @@ export const useAuthStore = defineStore('auth', () => {
loading.value = true;
try {
const payload: LoginResponse = await authApi.classLogin({ code, password });
profileKey = profileCacheKey(normalized, code);
sessionServer = normalized;
setCacheScope(normalized, payload.user.classId ?? payload.user.id);
applyToken(payload.token);
user.value = payload.user;
offlineSession.value = false;
await cacheSet('profile', PROFILE_KEY, user.value);
await cacheSet('profile', profileKey, user.value).catch(() => undefined);
await persistSession(normalized, code, payload.token);
} finally {
loading.value = false;
@@ -90,8 +94,11 @@ export const useAuthStore = defineStore('auth', () => {
}
}
const cachedProfile = await cacheGet<SessionUser>('profile', PROFILE_KEY).catch(() => null);
profileKey = profileCacheKey(serverUrl, username);
sessionServer = serverUrl;
const cachedProfile = await cacheGet<SessionUser>('profile', profileKey).catch(() => null);
if (cachedProfile) user.value = cachedProfile.value;
setCacheScope(serverUrl, user.value?.classId ?? user.value?.id ?? `unresolved:${username}`);
// 服务器刷新放到后台,绝不阻塞启动:离线时也能立刻进入界面看缓存数据
if (token.value) void refreshProfile();
@@ -102,11 +109,14 @@ export const useAuthStore = defineStore('auth', () => {
/** 后台刷新个人资料;服务器不可达时保持缓存资料与离线会话标记 */
async function refreshProfile(): Promise<void> {
if (!token.value) return;
const requestedToken = token.value;
try {
const profile = await authApi.me();
if (token.value !== requestedToken) return;
user.value = profile;
setCacheScope(sessionServer, profile.classId ?? profile.id);
offlineSession.value = false;
await cacheSet('profile', PROFILE_KEY, profile);
await cacheSet('profile', profileKey, profile).catch(() => undefined);
} catch {
offlineSession.value = Boolean(user.value);
}
@@ -120,6 +130,7 @@ export const useAuthStore = defineStore('auth', () => {
}
applyToken(null);
user.value = null;
setCacheScope('', 'anonymous');
offlineSession.value = false;
if (window.desktop) await window.desktop.saveConfig({ token: null });
}
@@ -5,6 +5,7 @@ import { notificationApi } from '../api/index.js';
import { cacheSet } from '../cache/db.js';
import { fetchWithCache } from '../cache/index.js';
import { useAppStore } from './app.js';
import { getCacheScope, onCacheScopeChanged } from '../cache/scope.js';
/**
* 通知状态:列表 + 未读数。
@@ -18,6 +19,23 @@ export const useNotificationStore = defineStore('notifications', () => {
const fromCache = ref(false);
const updatedAt = ref<number | null>(null);
const error = ref<string | null>(null);
let requestId = 0;
let revision = 0;
const changes = new Map<string, { revision: number; value: NotificationDto | null }>();
onCacheScopeChanged(() => {
requestId += 1;
revision = 0;
changes.clear();
items.value = [];
unreadCount.value = 0;
loading.value = false;
fromCache.value = false;
updatedAt.value = null;
error.value = null;
});
function changed(id: string, value: NotificationDto | null): void {
changes.set(id, { revision: ++revision, value });
}
const unreadItems = computed(() => items.value.filter((item) => !item.read));
@@ -34,6 +52,9 @@ export const useNotificationStore = defineStore('notifications', () => {
}
async function load(): Promise<void> {
const request = ++requestId;
const scope = getCacheScope();
const startedAt = revision;
loading.value = true;
try {
const result = await fetchWithCache<NotificationDto[]>(
@@ -42,14 +63,23 @@ export const useNotificationStore = defineStore('notifications', () => {
() => notificationApi.list(),
[],
);
items.value = result.data;
if (request !== requestId || scope !== getCacheScope()) return;
const merged = new Map(result.data.map((item) => [item.id, item]));
for (const [id, change] of changes) {
if (change.revision <= startedAt) continue;
if (change.value) merged.set(id, change.value);
else merged.delete(id);
}
items.value = [...merged.values()].sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
changes.clear();
fromCache.value = result.fromCache;
updatedAt.value = result.updatedAt;
error.value = result.error;
recount();
await persist();
if (!result.fromCache) useAppStore().markSynced();
} finally {
loading.value = false;
if (request === requestId) loading.value = false;
}
}
@@ -57,6 +87,14 @@ export const useNotificationStore = defineStore('notifications', () => {
async function pushRealtime(payload: NotificationDto): Promise<void> {
if (items.value.some((item) => item.id === payload.id)) return;
items.value = [{ ...payload, read: false }, ...items.value];
changed(payload.id, items.value[0]!);
recount();
await persist();
}
async function removeRealtime(id: string): Promise<void> {
items.value = items.value.filter((item) => item.id !== id);
changed(id, null);
recount();
await persist();
}
@@ -67,6 +105,7 @@ export const useNotificationStore = defineStore('notifications', () => {
if (target) {
target.read = true;
target.readAt = new Date().toISOString();
changed(id, { ...target });
}
recount();
await persist();
@@ -76,6 +115,7 @@ export const useNotificationStore = defineStore('notifications', () => {
const result = await notificationApi.markAllRead();
const now = new Date().toISOString();
items.value = items.value.map((item) => ({ ...item, read: true, readAt: item.readAt ?? now }));
for (const item of items.value) changed(item.id, item);
recount();
await persist();
return result.marked;
@@ -100,6 +140,7 @@ export const useNotificationStore = defineStore('notifications', () => {
error,
load,
pushRealtime,
removeRealtime,
markRead,
markAllRead,
refreshUnreadCount,
@@ -12,7 +12,6 @@ import {
} from '@classhelper/shared';
import { socketUrlOf } from '../config.js';
import { pushCallToIsland, pushHomeworkToIsland, pushNotificationToIsland } from '../island/bridge.js';
import { useAppStore } from './app.js';
type RealtimeEventName = keyof ServerToClientEvents;
type EventHandler = (payload: unknown) => void;
@@ -23,18 +22,6 @@ type EventHandler = (payload: unknown) => void;
* 还会把数据写回 IndexedDB,保证断网时看到的是最后同步到的内容。
*/
export const useRealtimeStore = defineStore('realtime', () => {
const app = useAppStore();
/**
* 本机要不要弹这次提醒。
*
* 教室在设置页选了「只在 ClassIsland 上弹」时,客户端仍然把通知收进通知中心(列表里有记录、
* 未读红点照常),但**不再弹窗、也不上岛** —— 否则老师会看到两个地方同时炸出来。
*/
function popupLocally(): boolean {
return app.shouldPopupLocally();
}
const connected = ref(false);
const connecting = ref(false);
const lastEventName = ref<string | null>(null);
@@ -76,18 +63,20 @@ export const useRealtimeStore = defineStore('realtime', () => {
dispatch('__connect_error__', error.message);
});
instance.on(SOCKET_EVENTS.notificationDeleted, (payload) => {
mark(SOCKET_EVENTS.notificationDeleted);
dispatch(SOCKET_EVENTS.notificationDeleted, payload);
});
instance.on(SOCKET_EVENTS.notificationNew, (payload: NotificationDto) => {
mark(SOCKET_EVENTS.notificationNew);
if (popupLocally()) {
ElMessage({
message: `【${PRIORITY_LABELS[payload.priority] ?? payload.priority}】${payload.title}`,
type: payload.priority === 'URGENT' ? 'error' : 'info',
duration: 5000,
showClose: true,
});
// 投递到桌面灵动岛:紧急通知立即展开;上课期间的非紧急通知会暂存,下课后自动弹出
pushNotificationToIsland(payload);
}
ElMessage({
message: `【${PRIORITY_LABELS[payload.priority] ?? payload.priority}】${payload.title}`,
type: payload.priority === 'URGENT' ? 'error' : 'info',
duration: 5000,
showClose: true,
});
// 投递到桌面灵动岛:紧急通知立即展开;上课期间的非紧急通知会暂存,下课后自动弹出
pushNotificationToIsland(payload);
dispatch(SOCKET_EVENTS.notificationNew, payload);
});
@@ -101,16 +90,14 @@ export const useRealtimeStore = defineStore('realtime', () => {
instance.on(SOCKET_EVENTS.callNew, (payload: NotificationDto) => {
mark(SOCKET_EVENTS.callNew);
if (popupLocally()) {
ElMessage({
message: payload.title,
type: 'warning',
duration: 8000,
showClose: true,
});
// 叫人:无论是否上课都立即展开(老师正在等这位同学)
pushCallToIsland(payload);
}
ElMessage({
message: payload.title,
type: 'warning',
duration: 8000,
showClose: true,
});
// 叫人:无论是否上课都立即展开(老师正在等这位同学)
pushCallToIsland(payload);
dispatch(SOCKET_EVENTS.callNew, payload);
});
@@ -384,7 +384,7 @@ onUnmounted(() => {
</el-table-column>
<el-table-column label="等级" width="80">
<template #default="{ row }">
{{ gradeLevel(gradePercent(row.score, row.totalScore)) }}
{{ row.level || gradeLevel(gradePercent(row.score, row.totalScore)) }}
</template>
</el-table-column>
<el-table-column label="发布时间" width="170">
@@ -70,8 +70,6 @@ async function submit(): Promise<void> {
try {
await auth.login(form.serverUrl, form.code.trim(), form.password);
await appStore.init(form.serverUrl);
// 登录后对齐"通知显示位置":这台机器上次选的是弹 ClassHelper 还是弹 ClassIsland
await appStore.loadNotificationChannel(auth.classId);
if (auth.token) realtime.connect(appStore.serverUrl, auth.token);
ElMessage.success(`已进入 ${auth.displayName}`);
await router.replace('/schedule');
@@ -12,7 +12,7 @@ import {
type ScheduleDto,
type ScheduleWeekView,
} from '@classhelper/shared';
import { dashboardApi, scheduleApi } from '../api/index.js';
import { scheduleApi } from '../api/index.js';
import { fetchWithCache } from '../cache/index.js';
import { useAppStore } from '../stores/app.js';
import { useAuthStore } from '../stores/auth.js';
@@ -172,14 +172,9 @@ function remainText(minutes: number): string {
async function loadTerm(): Promise<void> {
// 带 classId:周次上限取本班"教学周数"(班主任可调,默认 20 周)
const result = await fetchWithCache('classes', 'term', () => dashboardApi.term(auth.classId ?? undefined), {
currentWeek: 1,
maxWeek: 20,
});
appStore.currentWeek = result.data.currentWeek;
appStore.maxWeek = result.data.maxWeek;
weekOptions.value = buildWeekOptions(result.data.maxWeek);
if (!week.value || week.value === 1) week.value = result.data.currentWeek;
await appStore.refreshTerm(auth.classId ?? undefined);
weekOptions.value = buildWeekOptions(appStore.maxWeek);
if (!week.value || week.value === 1) week.value = appStore.currentWeek;
}
async function loadSchedules(): Promise<void> {
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { confirmAction } from '../../composables/confirm.js';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '../../stores/auth.js';
import { useRealtimeStore } from '../../stores/realtime.js';
@@ -13,7 +14,7 @@ const auth = useAuthStore();
const realtime = useRealtimeStore();
async function logout(): Promise<void> {
await ElMessageBox.confirm('确认退出当前账号?', '退出登录', { type: 'warning' });
if (!(await confirmAction('确认退出当前账号?', '退出登录', { type: 'warning' }))) return;
realtime.disconnect();
await auth.logout();
ElMessage.success('已退出登录');
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { confirmAction } from '../../composables/confirm.js';
import { computed, onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus';
import { formatDate, relativeTime, type UpdateInfo } from '@classhelper/shared';
import type { ClientAgentStatus, DesktopAppInfo } from '../../../types/desktop.js';
import { useAppStore } from '../../stores/app.js';
@@ -198,9 +199,12 @@ const cacheRows = computed(() =>
);
async function clearCache(): Promise<void> {
await ElMessageBox.confirm('清空后离线时将无法查看历史数据,确认继续?', '清空离线缓存', {
type: 'warning',
});
if (
!(await confirmAction('清空后离线时将无法查看历史数据,确认继续?', '清空离线缓存', {
type: 'warning',
}))
)
return;
await appStore.clearCache();
ElMessage.success('离线缓存已清空');
}
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { confirmAction } from '../../composables/confirm.js';
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus';
import {
HOMEWORK_PHRASE_DEFAULTS,
HOMEWORK_PHRASE_MAX_COUNT,
@@ -93,9 +94,12 @@ async function manualSync(): Promise<void> {
}
async function clearCache(): Promise<void> {
await ElMessageBox.confirm('清空后离线时将无法查看历史数据,确认继续?', '清空离线缓存', {
type: 'warning',
});
if (
!(await confirmAction('清空后离线时将无法查看历史数据,确认继续?', '清空离线缓存', {
type: 'warning',
}))
)
return;
await appStore.clearCache();
ElMessage.success('离线缓存已清空');
}
@@ -151,7 +155,7 @@ async function removePhrase(value: string): Promise<void> {
}
async function resetPhrases(): Promise<void> {
await ElMessageBox.confirm('恢复为默认快捷短语?', '恢复默认', { type: 'warning' });
if (!(await confirmAction('恢复为默认快捷短语?', '恢复默认', { type: 'warning' }))) return;
phrases.value = [...HOMEWORK_PHRASE_DEFAULTS];
await savePhrases();
ElMessage.success('已恢复默认');
@@ -192,7 +196,7 @@ const updateTargetText = computed(() => {
const pendingUpdateText = computed(() => {
const pending = agent.value?.pendingUpdateVersion ?? '';
if (!pending) return '无';
return `${pending}(已下载,空闲时自动安装)`;
return `${pending}(已下载,等待按服务端指定的时机安装)`;
});
const lastErrorText = computed(() => agent.value?.lastError?.trim() || '无');
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { confirmAction } from '../../composables/confirm.js';
import { computed, onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus';
import {
DEFAULT_ISLAND_APPEARANCE,
ISLAND_APPEARANCE_RANGES as RANGES,
@@ -65,7 +66,7 @@ async function saveIslandAppearance(): Promise<void> {
}
async function resetIslandAppearance(): Promise<void> {
await ElMessageBox.confirm('恢复灵动岛的默认外观?', '恢复默认', { type: 'warning' });
if (!(await confirmAction('恢复灵动岛的默认外观?', '恢复默认', { type: 'warning' }))) return;
applyIslandAppearance({ ...DEFAULT_ISLAND_APPEARANCE });
await saveIslandAppearance();
}
@@ -1,42 +1,8 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import {
CLASSISLAND_NOTIFICATION_CHANNEL_HINTS,
CLASSISLAND_NOTIFICATION_CHANNEL_LABELS,
CLASSISLAND_NOTIFICATION_CHANNELS,
formatDate,
type ClassIslandNotificationChannel,
} from '@classhelper/shared';
import { classGradeQueryApi, classIslandStatusApi } from '../../api/index.js';
import { useAppStore } from '../../stores/app.js';
import { onMounted, ref } from 'vue';
import { classGradeQueryApi } from '../../api/index.js';
import { useAuthStore } from '../../stores/auth.js';
/**
* 提醒设置:这台教室机器把提醒弹在哪个端(客户端 / ClassIsland / 两端都弹)。
* 值同时落本地配置与班级记录(服务端据此决定是否推送 ClassIsland)。
*/
const appStore = useAppStore();
const auth = useAuthStore();
const channelSaving = ref(false);
/**
* 本班有没有接入 ClassIsland 设备。
*
* 只用来禁用「只在 ClassIsland 上弹」——没有设备时选它等于把提醒静默丢掉;
* 注意**不能**顺手把「两端都弹」也禁掉:那样教室一旦选过"只在客户端",没设备时就再也切不回来了。
*/
const classIslandConnected = ref(false);
/** 本班 ClassIsland 设备的展示信息(设备名 / 最后上报),来自 /classes/:id/classisland-status */
const classIslandStatus = ref<{
connected: boolean;
deviceName: string | null;
deviceCount: number;
lastSeenAt: string | null;
pluginVersion: string | null;
classIslandVersion: string | null;
} | null>(null);
/* ------------------------------------------------------------ 班级端成绩查询状态(只读)
*
* 「是否允许班级端查看成绩」是**服务端口径**:管理员在 Web 端「班级管理」里开关,
@@ -56,43 +22,7 @@ async function loadGradeQuery(): Promise<void> {
}
}
const classIslandStatusText = computed(() => {
const status = classIslandStatus.value;
if (!status || !status.connected) return '未接入';
const seen = status.lastSeenAt ? `最后上报 ${formatDate(status.lastSeenAt, true)}` : '尚未上报过';
return `已接入 · ${status.deviceName ?? 'ClassIsland 设备'} · ${seen}`;
});
const channelOptions = computed(() =>
CLASSISLAND_NOTIFICATION_CHANNELS.map((value) => ({
value,
label: CLASSISLAND_NOTIFICATION_CHANNEL_LABELS[value],
disabled: value === 'classisland' && !classIslandConnected.value,
})),
);
async function applyChannel(value: ClassIslandNotificationChannel): Promise<void> {
channelSaving.value = true;
try {
const saved = await appStore.setNotificationChannel(auth.classId, value);
if (saved) ElMessage.success('提醒显示位置已更新');
else ElMessage.warning('已保存在本机,但同步到服务器失败(离线或权限不足),联网后请再点一次');
} finally {
channelSaving.value = false;
}
}
onMounted(async () => {
await appStore.loadNotificationChannel(auth.classId);
// 本班 ClassIsland 联动状态:没接设备就别让选「只在 ClassIsland 上弹」
if (auth.classId) {
const status = await classIslandStatusApi.get(auth.classId).catch(() => null);
classIslandStatus.value = status;
classIslandConnected.value = status?.connected === true;
}
// 班级端成绩查询开关(存在班级上,与 Web 端共享同一个值)
await loadGradeQuery();
});
onMounted(loadGradeQuery);
</script>
<template>
@@ -100,44 +30,14 @@ onMounted(async () => {
<div class="page-header">
<div>
<h2 class="page-title">提醒</h2>
<p class="page-subtitle">老师发通知 / 叫人时,提醒弹在哪个端</p>
<p class="page-subtitle">通知提醒与成绩查询状态</p>
</div>
</div>
<el-card shadow="never">
<template #header><span>ClassIsland 联动</span></template>
<el-descriptions :column="1" border size="small" class="mb-12">
<el-descriptions-item label="联动状态">{{ classIslandStatusText }}</el-descriptions-item>
<el-descriptions-item label="插件 / ClassIsland">
{{ classIslandStatus?.pluginVersion ?? '—' }} /
{{ classIslandStatus?.classIslandVersion ?? '—' }}
</el-descriptions-item>
</el-descriptions>
<template #header>通知提醒</template>
<p class="text-muted">
<strong>通知模式</strong>
:老师在 ClassHelper 上发布通知 / 叫人时,提醒弹在灵动岛还是 ClassIsland,
由这台教室机器决定。选择会同步到班级,服务端据此决定是否推送到教室的 ClassIsland。
</p>
<el-radio-group
:model-value="appStore.notificationChannel"
:disabled="channelSaving"
class="channel-group"
@change="
(value: string | number | boolean | undefined) =>
applyChannel(value as ClassIslandNotificationChannel)
"
>
<el-radio v-for="item in channelOptions" :key="item.value" :value="item.value" :disabled="item.disabled">
{{ item.label }}
</el-radio>
</el-radio-group>
<p class="text-muted channel-hint">
{{ CLASSISLAND_NOTIFICATION_CHANNEL_HINTS[appStore.notificationChannel] }}
<template v-if="!classIslandConnected">
<br />
提示:本班还没有接入 ClassIsland 设备(在 Web 端「ClassHelper 联动」里接入后才能选"只在
ClassIsland 上弹")。
</template>
通知与叫人通过 ClassHelper 客户端和灵动岛提醒。普通通知在上课期间暂存,下课后补弹;紧急通知立即提醒。
</p>
</el-card>
@@ -150,9 +50,7 @@ onMounted(async () => {
打开后,可以在「成绩」页看到本班成绩与排名。学生本身没有账号、不能登录,
查成绩就是由这台教室机器代做。关闭后本机查成绩会被服务端拒绝,教师端不受影响。
</p>
<p class="text-muted">
本开关由管理员在服务端「班级管理」和「客户端设备」里统一设置,教室机器不提供本地开关。
</p>
<p class="text-muted">本开关由管理员在服务端「班级管理」里统一设置,教室机器不提供本地开关。</p>
<el-tag :type="gradeQueryEnabled ? 'success' : 'info'" effect="plain">
{{ gradeQueryEnabled ? '当前:已允许查看成绩与排名' : '当前:已由管理员关闭' }}
</el-tag>
+3 -14
View File
@@ -2,13 +2,7 @@
* 主进程与渲染进程之间的桥接契约(preload 通过 contextBridge 暴露)。
* 渲染进程只依赖这些最小 API,不接触 Node.js。
*/
import type {
ClassIslandNotificationChannel,
IslandAppearance,
IslandNotification,
IslandState,
UpdateInfo,
} from '@classhelper/shared';
import type { IslandAppearance, IslandNotification, IslandState, UpdateInfo } from '@classhelper/shared';
import type { ClientAgentStatus } from '../main/client-agent.js';
/** 服务端联动状态:渲染进程要显示它,因此在这里转出(`desktop.d.ts` 是两端契约的单一入口) */
@@ -45,13 +39,6 @@ export interface DesktopStoredConfig {
* 录入作业时点一下就追加到标题/内容里,少打字(例如 P、大本、背诵)。
*/
homeworkPhrases: string[];
/**
* 通知显示位置(both / client / classisland)。
*
* 这台教室机器"提醒到底弹在哪个端"由它决定:值同时存本地(决定本机要不要弹窗/上岛)
* 与班级记录(服务端据此决定要不要推给 ClassIsland)。
*/
notificationChannel: ClassIslandNotificationChannel;
/**
* 是否已看过「初次启动引导」。
*
@@ -170,6 +157,7 @@ export interface DesktopBridge {
/* 灵动岛 */
/** 把一条通知投递到灵动岛(payload 必须是纯数据,说明见 saveConfig) */
islandPush(payload: { notification: IslandNotification; context?: IslandPushContext }): void;
islandRemoveNotification(id: string): void;
/** 同步上课状态:进入上课隐藏,下课后自动弹出暂存通知 */
islandSetClassState(payload: IslandClassStatePayload): void;
/** 读取灵动岛当前状态(设置页/冒烟验证用) */
@@ -255,6 +243,7 @@ declare global {
/** 冒烟验证钩子,仅在 ELECTRON_SMOKE_TEST=1 时由渲染进程注册 */
__classhelperSmoke__?: {
cacheSelfTest(): Promise<{ ok: boolean; detail: string }>;
cacheIsolationSelfTest(): Promise<{ ok: boolean; detail: string }>;
offlineScenario(): Promise<{ ok: boolean; detail: string }>;
layoutNavigationSelfTest(): Promise<{ ok: boolean; detail: string }>;
onlineScenario(credentials?: {
+3 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@classhelper/server",
"version": "1.3.2",
"version": "1.3.3",
"private": true,
"description": "ClassHelper后端服务:REST API + Socket.IO 实时推送 + Prisma 数据访问",
"type": "module",
@@ -9,7 +9,7 @@
"dev": "tsx watch src/index.ts",
"start": "node dist/index.js",
"start:tsx": "tsx src/index.ts",
"build": "tsc -p tsconfig.build.json",
"build": "node scripts/build.mjs",
"typecheck": "tsc -p tsconfig.json",
"db:generate": "prisma generate",
"db:migrate": "prisma migrate dev",
@@ -18,8 +18,7 @@
"db:seed": "prisma db seed",
"db:reset": "prisma migrate reset --force",
"db:studio": "prisma studio",
"verify:e2e": "node scripts/verify-e2e.mjs",
"verify:classisland": "node scripts/verify-classisland.mjs"
"verify:e2e": "node scripts/verify-e2e.mjs"
},
"dependencies": {
"@classhelper/shared": "workspace:*",
@@ -0,0 +1,13 @@
-- 移除退役联动数据;业务课表保留并归为手工管理。
DROP TABLE IF EXISTS "ClassIslandPush";
DROP TABLE IF EXISTS "IntegrationDevice";
ALTER TABLE "Class" DROP COLUMN "notificationChannel";
UPDATE "Schedule" SET "source" = 'manual' WHERE "source" = 'classisland';
-- 默认组按角色绑定,改名也不会失去对应关系。
ALTER TABLE "PermissionGroup" ADD COLUMN "defaultRole" TEXT;
CREATE UNIQUE INDEX "PermissionGroup_defaultRole_key" ON "PermissionGroup"("defaultRole");
DELETE FROM "PermissionGroupItem" WHERE "key" IN ('device:manage', 'classisland:notify');
ALTER TABLE "ClientDevice" ADD COLUMN "updateMode" TEXT NOT NULL DEFAULT 'idle';
ALTER TABLE "ClientDevice" ADD COLUMN "updateNotBefore" DATETIME;
@@ -0,0 +1,6 @@
-- 未实现独立接口的权限不再展示;原有管理组继承对应只读能力。
DELETE FROM "PermissionGroupItem" WHERE "key" IN ('log:read', 'developer:mode');
INSERT OR IGNORE INTO "PermissionGroupItem" ("id", "groupId", "key")
SELECT "groupId" || ':roster:read', "groupId", 'roster:read' FROM "PermissionGroupItem" WHERE "key" = 'roster:manage';
INSERT OR IGNORE INTO "PermissionGroupItem" ("id", "groupId", "key")
SELECT "groupId" || ':teacher:read', "groupId", 'teacher:read' FROM "PermissionGroupItem" WHERE "key" = 'teacher:manage';
+6 -124
View File
@@ -219,11 +219,8 @@ model Class {
/// 本学期教学周数(班主任可调,默认 20):课表周次选择与 weekEnd 默认值都用它
termWeeks Int @default(20)
/// 本班学期开始日期(YYYY-MM-DD,本地日期);留空则用全局配置(.env 的 TERM_START_DATE)。
/// 管理员改它会重算「当前第几周」,并随镜像课表下发给教室的 ClassIsland。
/// 管理员改它会重算「当前第几周」,并广播课表更新。
termStartDate String?
/// 通知显示位置(由 ClassHelper 班级端在设置页里选):
/// both=班级端与 ClassIsland 都弹 / client=只弹班级端 / classisland=只弹 ClassIsland
notificationChannel String @default("both")
/// 是否允许 ClassHelper 班级端按学号查询本班学生的成绩明细(默认开启)。
/// 关闭后班级端查成绩一律 403;教师端不受影响。
studentGradeQueryEnabled Boolean @default(true)
@@ -243,8 +240,6 @@ model Class {
grades Grade[]
exams Exam[]
timeLayouts TimeLayout[]
integrationDevices IntegrationDevice[]
classIslandPushes ClassIslandPush[]
clientDevices ClientDevice[]
@@index([teacherId])
@@ -295,9 +290,6 @@ model Schedule {
/// 单双周:ALL=每周(默认)/ ODD=单周 / EVEN=双周(ClassIsland WeekCountDiv + WeekCountDivTotal 的映射)
weekParity String @default("ALL")
/// 该行的来源:manual=手工建立(Web 端录入 / ClassIsland JSON 导入)
/// / classisland=插件上报同步得到。
/// 插件每次全量上报时只清理「classisland 来源且本次未再上报」的行(解决"老师在 ClassIsland
/// 里删掉一节、服务端却永远留着"的幽灵课),老师手排的课一律不删。
source String @default("manual")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -436,120 +428,9 @@ model Grade {
@@index([courseId])
}
/// ClassIsland 联动设备(一台装有联动插件的机器 = 某个班的 ClassHelper 班级端)
///
/// 说明:
/// 1) 令牌是「设备级」的,不是用户级:插件在本机保存明文,服务端只存 sha256 哈希 + 前缀提示;
/// 2) 同一班级下按 deviceKey(机器码)唯一:插件重装后带同一 deviceKey 会自动重绑到原记录,
/// 避免设备列表里堆满重复项;
/// 3) 状态字段是「最后一次上报的快照」,Web 端据此展示"某班现在上什么课";
/// 4) `lastHeartbeatAt` 每次上报都刷新(在线判定用它),`lastSeenAt` 只在**带运行状态**的
/// 上报时刷新 —— 这样"能连上但一直没上报状态"的设备不会被误判成完全正常。
model IntegrationDevice {
id String @id @default(cuid())
classId String
/// 设备显示名(默认取机器名)
name String
/// 设备唯一标识(插件上报的机器码)
deviceKey String
/// 联动方式:plugin=实时插件联动 / import=仅一次性导入
mode String @default("plugin")
/// 是否接入(关闭后插件上报与下发一律 403)
enabled Boolean @default(true)
/// 设备令牌的 sha256(明文只在创建/重置时返回一次)
tokenHash String
/// 令牌前缀(chci_xxxxxxxx),设备列表里用于人眼识别与排查
tokenHint String
/// 是否允许插件把 ClassIsland 的课表回传到本服务
///
/// **默认关闭**(2026-10-06 起):课表以服务端为准,由服务端**自动下发**到教室;
/// 「从教室机器取一次课表」改成 Web 端的手动动作(点击前会弹警告),
/// 因为自动回传会在老师手排课之后被教室的旧课表悄悄覆盖。
syncScheduleToServer Boolean @default(false)
/// 是否允许把本班课表镜像回 ClassIsland(由插件执行)。
///
/// **2026-10-11 起含义收窄为"允许下发"**:不再是"自动同步的主方向" —— 插件以前每 15 秒
/// 上报一次、每次上报完都顺手镜像一遍(`MirrorSchedule` 开着时),教室的课表被反复重写;
/// 现在镜像只由 `requestMirrorSchedule` 这个一次性待办触发,这里只表示"这台设备接不接受下发"。
mirrorScheduleToClassIsland Boolean @default(true)
/// 待办的「立即上报一次课表」请求:Web 端点「从教室机器获取课表」时置位,
/// 插件在下一次心跳看到它就把当前课表推上来并清除标记。
requestScheduleReport Boolean @default(false)
/// 待办的「立即下发一次课表」请求:Web 端点「下发课表到教室」时置位,
/// 插件在下一次心跳看到它就去拉本班课表并**强制替换**写进 ClassIsland,
/// 拉取成功即由服务端清除标记(见 `pullClassPlanForDevice`)。
///
/// 为什么要一次性待办而不是"开关":教室机常常离线,一个实时下发的长连接握手不值得,
/// 而后台定时镜像会与老师在教室本地做的调整互相打架(2026-10-11 实测:
/// 插件每 15 秒重写一遍课表,服务端那边看起来就是课表被反复删改)。
requestMirrorSchedule Boolean @default(false)
classIslandVersion String?
pluginVersion String?
/// 最后一次**带运行状态**的上报时间
lastSeenAt DateTime?
/// 最后一次心跳时间(每次上报都刷新);「在线」看它
lastHeartbeatAt DateTime?
/// 以下为最后一次上报的快照
classPlanLoaded Boolean @default(false)
currentSubject String?
currentTimeState String?
currentPeriodStart String?
currentPeriodEnd String?
nextSubject String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
class Class @relation(fields: [classId], references: [id], onDelete: Cascade)
pushes ClassIslandPush[]
@@unique([classId, deviceKey])
@@index([classId])
@@index([tokenHash])
}
/// 下发给 ClassIsland 的提醒:教师发通知 → 学生机器全屏弹出。
/// 落库是为了「设备离线时通知不丢」——插件重连后拉取未确认的一条立即弹出。
model ClassIslandPush {
id String @id @default(cuid())
classId String
deviceId String?
title String
content String
/// 显示时长(秒):映射到 ClassIsland 的 NotificationContent.Duration
durationSeconds Int @default(8)
/// 语音朗读内容;null = 不朗读
speechContent String?
urgent Boolean @default(false)
/// 提醒类型:notification=通知类 / call=叫人(叫人算「主动通知」,上课时段也立刻弹)
kind String @default("notification")
/// 发起人的用户 id(教师/管理员)
createdBy String?
/// 同时落库到通知中心的通知 id(saveToNotifications 时写入)
notificationId String?
/// 插件确认弹出的时间(确认后不再重复下发)
ackedAt DateTime?
createdAt DateTime @default(now())
/// 过期时间:超过后不再补发(避免学生几天后突然弹出旧提醒)
expiresAt DateTime
class Class @relation(fields: [classId], references: [id], onDelete: Cascade)
device IntegrationDevice? @relation(fields: [deviceId], references: [id], onDelete: SetNull)
@@index([classId, createdAt])
@@index([deviceId, ackedAt])
}
/* -------------------------------------------------------------------------- */
/* 权限组 / 全局设置 / 客户端设备 / 远控命令 / 客户端安装包 / 大模型审计 */
/* -------------------------------------------------------------------------- */
/// 权限组:管理员自定义的一组**权限键**(`shared` 的 `PERMISSION_KEYS`),可分配给多个账号。
///
/// 语义(与 `packages/shared/src/permissions.ts` 的目录一一对应):
/// - 账号**没有**任何 `UserPermissionGroup` 时,生效集合 = 角色默认模板(`ROLE_DEFAULT_PERMISSIONS`);
/// - 一旦分了组,生效集合 = 这些组的键并集(可以比默认更少 ⇒ 也能用来**收回**权限);
/// - `ADMIN` 永远补上 `permission:manage` / `system:manage`,避免把自己锁死。
model PermissionGroup {
/// 角色默认组;自定义组为空,改名不影响对应角色。
defaultRole String? @unique
id String @id @default(cuid())
name String @unique
description String @default("")
@@ -606,8 +487,7 @@ model AppSetting {
///
/// 身份由客户端主进程生成并持久化的 `deviceKey`(UUID)标识,心跳每 30 秒一次:
/// 服务端由此知道**每台机器在哪个班、版本多少、是否在线**,并把更新与远控
/// 指令按「查库 + 心跳拉取」的范式下发(不新增长连接握手,照抄
/// `IntegrationDevice.requestScheduleReport` 的做法)。
/// 指令按「查库 + 心跳拉取」的范式下发,不新增长连接握手。
model ClientDevice {
id String @id @default(cuid())
/// 该设备当前登录的班级(未登录时为空)
@@ -624,6 +504,8 @@ model ClientDevice {
autoUpdate Boolean @default(true)
/// 服务端指定的目标版本('' = 不指定,按最新版走)
updateTargetVersion String @default("")
updateMode String @default("idle")
updateNotBefore DateTime?
/// 已下载待安装的版本('' = 无)
pendingVersion String @default("")
/// 最近一次心跳时间(**在线判定看它**)
@@ -1,9 +1,8 @@
/**
* 维护脚本:给"已有数据库"补齐结构性新增列(不依赖安装程序升级)。
*
* 为什么需要它:安装版服务端只在**库为空**时执行随包迁移 SQL(首次启动建表);
* 用安装程序覆盖升级时,升级逻辑会自动补齐新迁移。若像本地联调那样**手工覆盖 dist**
* 部署,就需要显式跑一次本脚本。
* 服务端启动时会自动应用完整迁移。本脚本仅用于排查旧库缺列,
* 不能替代正式迁移(例如移除联动表、创建权限组索引)。
*
* 用法(用安装目录自带的 node 即可,无需 SDK):传入**已编译的 `lib/db.js`**,
* 直接复用服务端自己配置好的 Prisma 客户端(Prisma 7 需要 driver adapter,不能裸 new):
@@ -56,12 +55,6 @@ const COLUMNS = [
sql: `ALTER TABLE "Grade" ADD COLUMN "level" TEXT NOT NULL DEFAULT ''`,
note: '成绩等级文本(percent 下由得分率换算,可手改)',
},
{
table: 'IntegrationDevice',
column: 'lastHeartbeatAt',
sql: `ALTER TABLE "IntegrationDevice" ADD COLUMN "lastHeartbeatAt" DATETIME`,
note: 'ClassHelper 班级端最后一次心跳(在线判定看它)',
},
{
table: 'User',
column: 'phone',
+20
View File
@@ -0,0 +1,20 @@
/** 先清理编译目录,确保已移除的模块不会残留在下一次交付物中。 */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
import { spawnSync } from 'node:child_process';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const require = createRequire(import.meta.url);
fs.rmSync(path.join(root, 'dist'), { recursive: true, force: true });
const result = spawnSync(
process.execPath,
[require.resolve('typescript/bin/tsc'), '-p', 'tsconfig.build.json'],
{
cwd: root,
stdio: 'inherit',
},
);
if (result.error) throw result.error;
process.exitCode = result.status ?? 1;
@@ -1,679 +0,0 @@
#!/usr/bin/env node
/**
* ClassIsland 联动验证(插件侧接口 + 下发链路)。
*
* 覆盖范围:
* 1) 设备令牌鉴权:无令牌 / 错令牌一律 401,令牌作废后立即失效
* 2) 插件上报 → 服务端写库(课表 + 节次时间 + 状态快照)幂等
* 3) 教师下发提醒 → 落库 → 插件 pending 拉到 → ack 后不再补发
* 4) 停用设备后插件上报被 403 拦下
* 5) 课表镜像拉取(mirrorScheduleToClassIsland)返回 ClassIsland 口径的数据
*
* 用法:
* 1) 另开终端启动后端:pnpm dev:server
* 2) 执行:node packages/server/scripts/verify-classisland.mjs
*
* 环境变量:
* VERIFY_BASE_URL 默认 http://127.0.0.1:4000(脚本直连,不受系统代理影响)
*
* 注意:本脚本只操作「新建设备 + 该设备对应班级」的数据,
* 结束时会把新建的设备删除;上报的课表会写进该班(与导入模块语义一致,可被覆盖)。
*/
const BASE_URL = process.env.VERIFY_BASE_URL ?? `http://127.0.0.1:${process.env.PORT ?? 4000}`;
const results = [];
function record(name, ok, detail = '') {
results.push({ name, ok, detail });
console.log(`${ok ? '\u2713' : '\u2717'} ${name}${detail ? ` (${detail})` : ''}`);
}
async function api(path, { method = 'GET', token, deviceToken, body } = {}) {
const headers = { 'Content-Type': 'application/json' };
if (token) headers.Authorization = `Bearer ${token}`;
if (deviceToken) headers['X-ClassIsland-Token'] = deviceToken;
const response = await fetch(`${BASE_URL}/api${path}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
});
const payload = await response.json().catch(() => null);
return { status: response.status, payload };
}
/** 造一份插件会上报的课表(周一/周二,含单双周) */
function sampleSchedule() {
return {
mode: 'merge',
entries: [
{
dayOfWeek: 1,
startTime: '08:00',
endTime: '08:45',
subject: '语文',
teacherName: '王老师',
weekParity: 'ALL',
weekCountDiv: 0,
weekCountDivTotal: 0,
planName: '周一课表',
},
{
dayOfWeek: 1,
startTime: '08:55',
endTime: '09:40',
subject: '数学',
teacherName: '李老师',
weekParity: 'ODD',
weekCountDiv: 1,
weekCountDivTotal: 2,
planName: '周一课表',
},
{
dayOfWeek: 2,
startTime: '08:00',
endTime: '08:45',
subject: '英语',
teacherName: '张老师',
weekParity: 'ALL',
weekCountDiv: 0,
weekCountDivTotal: 0,
planName: '周二课表',
},
],
};
}
function sampleTimeLayout() {
return {
name: 'ClassIsland 验证时间表',
mode: 'replace',
items: [
{ index: 1, name: '第 1 节', startTime: '08:00', endTime: '08:45', type: 'class', skipped: false },
{ index: 2, name: '课间', startTime: '08:45', endTime: '08:55', type: 'break', skipped: false },
{ index: 3, name: '第 2 节', startTime: '08:55', endTime: '09:40', type: 'class', skipped: false },
],
};
}
/** 按候选密码依次登录,返回可用 token(不同环境的默认密码可能不同) */
async function loginWithCandidates(username, passwords) {
for (const password of passwords) {
const result = await api('/auth/login', { method: 'POST', body: { username, password } });
const token = result.payload?.data?.token;
if (token) return token;
}
return null;
}
/**
* 反复「拉取待提醒 → 逐条确认」,直到该设备视角下没有积压。
*
* 为什么验证脚本要做这件事:`GET /integrations/classisland/pending` 是
* 「本班全部未确认且未过期的提醒,按时间升序取前 20 条」。而 `verify:desktop` /
* `verify:web` 等冒烟会**真的往演示班发通知**(AGENTS.md §5 第 38 条),
* 那些条如果没被确认就会一直堆着 —— 攒够 20 条之后,本脚本刚发的提醒会被挤到窗口之外,
* 表现为「待提醒里找不到刚发的那条」,与代码对不对完全无关(2026-10-05 实测踩过:
* 库里积了 45 条历次冒烟残条,本脚本从 42/42 掉到 35/40)。
*
* 这里做的事情与真实插件重连后的行为完全一致(补弹积压并逐条确认),
* 因此不会掩盖任何产品侧问题。可见范围也一致:只处理 `deviceId` 为空的班级广播
* 与本设备自己的推送,别的设备的目标推送取不到、也确认不了。
*/
async function drainPending(deviceToken) {
let total = 0;
for (let round = 0; round < 20; round += 1) {
const pending = await api('/integrations/classisland/pending', { deviceToken });
const items = pending.payload?.data?.notifications ?? [];
if (items.length === 0) break;
for (const item of items) {
await api('/integrations/classisland/ack', { method: 'POST', deviceToken, body: { id: item.id } });
total += 1;
}
}
return total;
}
async function main() {
console.log(`\n=== ClassIsland 联动验证(${BASE_URL})===\n`);
const health = await api('/health');
if (health.status !== 200) {
console.log('后端未启动,请先运行 pnpm dev:server\n');
process.exit(1);
}
const modules = health.payload?.data?.modules ?? [];
record('integrations 模块已挂载', modules.includes('integrations'), modules.join(', '));
if (!modules.includes('integrations')) process.exit(1);
// ---------------------------------------------------------------- 登录
// 演示库里的教师密码由 .env 的 DEFAULT_TEACHER_PASSWORD 决定(种子脚本用它建号),
// 因此这里按候选列表尝试,避免「换了环境就整脚本失败」。
const teacherToken = await loginWithCandidates('teacher1', ['teacher123', '123456']);
record('教师登录 teacher1', Boolean(teacherToken));
if (!teacherToken) process.exit(1);
// 管理员用于取班级码(只有管理员/班主任能看到班级码),学生隔离用例需要它
const adminToken = await loginWithCandidates('admin', ['admin123']);
const classes = await api('/classes', { token: teacherToken });
const target = (classes.payload?.data ?? [])[0];
record('取到可管理的班级', Boolean(target?.id), target ? `${target.name} (${target.id})` : '无');
if (!target?.id) process.exit(1);
// 叫人用例需要一位学生;班级账号用来验证"教室客户端自己选显示位置"
const students = await api(`/classes/${target.id}/students`, { token: teacherToken });
const firstStudent = (students.payload?.data ?? [])[0];
/** 用班级码 + 班级密码登录,拿班级账号 token(教室机器的身份) */
async function classLoginToken() {
if (adminToken) {
const detail = await api(`/classes/${target.id}`, { token: adminToken });
const code = detail.payload?.data?.code;
if (code) {
for (const password of ['123456', 'class123']) {
const result = await api('/auth/class-login', {
method: 'POST',
body: { code, password },
});
const token = result.payload?.data?.token;
if (token) return token;
}
}
}
return null;
}
// ---------------------------------------------------------------- 1. 新建设备
const created = await api('/integrations/devices', {
method: 'POST',
token: teacherToken,
body: { classId: target.id, name: '验证用设备', syncScheduleToServer: true },
});
const deviceToken = created.payload?.data?.token;
const deviceId = created.payload?.data?.device?.id;
record(
'新建设备并返回设备令牌',
created.status === 201 && typeof deviceToken === 'string' && deviceToken.startsWith('chci_'),
`status=${created.status} hint=${created.payload?.data?.device?.tokenHint ?? '-'}`,
);
if (!deviceToken || !deviceId) process.exit(1);
// ---------------------------------------------------------------- 2. 令牌鉴权
const noToken = await api('/integrations/classisland/report', { method: 'POST', body: {} });
record('无令牌上报被拒(401)', noToken.status === 401, `status=${noToken.status}`);
const badToken = await api('/integrations/classisland/report', {
method: 'POST',
deviceToken: 'chci_deadbeef',
body: {},
});
record('错误令牌上报被拒(401)', badToken.status === 401, `status=${badToken.status}`);
// ---------------------------------------------------------------- 3. 上报(状态 + 课表 + 节次)
const reportBody = {
pluginVersion: '1.1.2.0',
classIslandVersion: '2.1.0.0',
state: {
inClass: true,
subject: '语文',
nextSubject: '数学',
timeState: 'OnClass',
periodStart: '08:00',
periodEnd: '08:45',
week: 1,
classPlanLoaded: true,
clientTime: new Date().toISOString(),
},
schedule: sampleSchedule(),
timeLayout: sampleTimeLayout(),
};
const report1 = await api('/integrations/classisland/report', {
method: 'POST',
deviceToken,
body: reportBody,
});
const r1 = report1.payload?.data;
record(
'插件上报课表写入成功',
report1.status === 200 && r1?.scheduleApplied === true && r1.scheduleCreated + r1.scheduleUpdated === 3,
`新增=${r1?.scheduleCreated} 更新=${r1?.scheduleUpdated} 周=${r1?.week}`,
);
record('插件上报节次时间写入成功', r1?.timeLayoutApplied === true, `applied=${r1?.timeLayoutApplied}`);
record('上报回传服务端周次与时间', typeof r1?.serverTime === 'string' && Number.isInteger(r1?.week));
// 幂等:重复上报不应产生重复行
const report2 = await api('/integrations/classisland/report', {
method: 'POST',
deviceToken,
body: reportBody,
});
const r2 = report2.payload?.data;
record(
'重复上报幂等(不新增、只更新)',
r2?.scheduleCreated === 0 && r2?.scheduleUpdated === 3,
`新增=${r2?.scheduleCreated} 更新=${r2?.scheduleUpdated}`,
);
// 设备列表里的状态快照
const devices = await api(`/integrations/devices?classId=${target.id}`, { token: teacherToken });
const listed = (devices.payload?.data ?? []).find((item) => item.id === deviceId);
record(
'设备状态快照已更新(Web 端可展示)',
Boolean(listed?.lastSeenAt) &&
listed?.currentSubject === '语文' &&
listed?.currentTimeState === 'OnClass',
`科目=${listed?.currentSubject} 状态=${listed?.currentTimeState} ClassIsland=${listed?.classIslandVersion}`,
);
// ---------------------------------------------------------------- 4. 下发提醒
// 先确认掉本班的历史积压(历次冒烟留下的未确认提醒),否则 /pending 的前 20 条窗口
// 会被它们占满,下面「插件拉取到待提醒」等用例会拿不到刚发的这条(理由见 drainPending)
const drained = await drainPending(deviceToken);
if (drained > 0) {
console.log(`(已确认本班 ${drained} 条历史积压提醒,避免挤占待提醒窗口)\n`);
}
const notify = await api('/integrations/classisland/notify', {
method: 'POST',
token: teacherToken,
body: {
classId: target.id,
title: '请到讲台领资料',
content: '下课后来讲台领取期中复习资料',
durationSeconds: 12,
speech: true,
},
});
const n1 = notify.payload?.data;
record(
'教师下发提醒(落库 + 标记设备数)',
notify.status === 200 && n1?.targetCount >= 1 && Boolean(n1?.notificationId),
`设备数=${n1?.targetCount} 通知id=${n1?.notificationId ? '有' : '无'}`,
);
const pending = await api('/integrations/classisland/pending', { deviceToken });
const items = pending.payload?.data?.notifications ?? [];
const picked = items.find((item) => item.title === '请到讲台领资料');
record(
'插件拉取到待提醒(离线补齐链路可用)',
pending.status === 200 && Boolean(picked),
`待提醒数=${items.length} 时长=${picked?.durationSeconds}s 朗读=${Boolean(picked?.speechContent)}`,
);
if (picked) {
const ack = await api('/integrations/classisland/ack', {
method: 'POST',
deviceToken,
body: { id: picked.id },
});
record(
'插件确认提醒已弹出',
ack.status === 200 && ack.payload?.data?.acked === true,
`status=${ack.status}`,
);
const pending2 = await api('/integrations/classisland/pending', { deviceToken });
const again = (pending2.payload?.data?.notifications ?? []).some((item) => item.id === picked.id);
record('确认后不再补发(避免重复弹窗)', !again, `仍在待提醒中=${again}`);
}
// ---------------------------------------------------------------- 4.5 其他发布入口也会联动 ClassIsland
// 需求:"在其他页面发通知也可以联动 ClassIsland"。通知发布页 / 叫人走的是各自的接口,
// 这里逐个验证它们真的会生成待弹出提醒(而不是只有联动页那个专用接口才联动)。
const classChannel = await api(`/classes/${target.id}/notification-channel`, { token: teacherToken });
record(
'班级有"通知显示位置"(默认两端都弹)',
classChannel.status === 200 && classChannel.payload?.data?.notificationChannel === 'both',
`channel=${classChannel.payload?.data?.notificationChannel}`,
);
const published = await api('/notifications', {
method: 'POST',
token: teacherToken,
body: { classId: target.id, title: '通知页联动验证', content: '从通知发布页发的通知', priority: 'NORMAL' },
});
const pendingAfterPublish = await api('/integrations/classisland/pending', { deviceToken });
const publishPush = (pendingAfterPublish.payload?.data?.notifications ?? []).find(
(item) => item.title === '通知页联动验证',
);
record(
'通知发布页发的通知也会推送到 ClassIsland',
published.status === 201 && Boolean(publishPush),
`status=${published.status} 待提醒=${(pendingAfterPublish.payload?.data?.notifications ?? []).length}`,
);
// kind 决定插件"上课时段弹不弹":通知类会被暂存,叫人属于主动通知要立刻弹
record(
'通知类推送的 kind=notification(上课时段插件会暂存)',
publishPush?.kind === 'notification',
`kind=${publishPush?.kind}`,
);
if (publishPush) {
await api('/integrations/classisland/ack', {
method: 'POST',
deviceToken,
body: { id: publishPush.id },
});
}
const call = await api('/calls', {
method: 'POST',
token: teacherToken,
body: { classId: target.id, studentId: firstStudent?.id, message: '叫人联动验证' },
});
const pendingAfterCall = await api('/integrations/classisland/pending', { deviceToken });
const callPush = (pendingAfterCall.payload?.data?.notifications ?? []).find(
(item) => item.content === '叫人联动验证',
);
record(
'叫人也会推送到 ClassIsland',
Boolean(firstStudent) && call.status === 201 && Boolean(callPush),
firstStudent ? `status=${call.status}` : '班级里没有学生,跳过',
);
record(
'叫人推送的 kind=call(算主动通知,上课时段也立刻弹)',
callPush?.kind === 'call',
`kind=${callPush?.kind}`,
);
if (callPush) {
await api('/integrations/classisland/ack', {
method: 'POST',
deviceToken,
body: { id: callPush.id },
});
}
// 教室在客户端里选"只在 ClassHelper 客户端显示"后,任何入口都不该再打扰 ClassIsland
const setClient = await api(`/classes/${target.id}/notification-channel`, {
method: 'PATCH',
token: teacherToken,
body: { notificationChannel: 'client' },
});
record(
'可把"通知显示位置"改成只在客户端显示',
setClient.status === 200 && setClient.payload?.data?.notificationChannel === 'client',
`channel=${setClient.payload?.data?.notificationChannel}`,
);
const mutedPublish = await api('/notifications', {
method: 'POST',
token: teacherToken,
body: { classId: target.id, title: '不该上 ClassIsland 的通知', content: '教室选择了只在客户端显示' },
});
const mutedNotify = await api('/integrations/classisland/notify', {
method: 'POST',
token: teacherToken,
body: { classId: target.id, title: '联动页也不该下发', content: '同样被教室的设置拦下' },
});
const pendingMuted = await api('/integrations/classisland/pending', { deviceToken });
const mutedItems = pendingMuted.payload?.data?.notifications ?? [];
record(
'显示位置=client 时通知不再推送 ClassIsland',
mutedPublish.status === 201 && !mutedItems.some((item) => item.title === '不该上 ClassIsland 的通知'),
`待提醒=${mutedItems.length}`,
);
record(
'显示位置=client 时联动页的下发也会被跳过(并说明原因)',
mutedNotify.status === 200 &&
mutedNotify.payload?.data?.skipped === 'channel-client' &&
String(mutedNotify.payload?.message ?? '').includes('只在 ClassHelper 客户端显示'),
`skipped=${mutedNotify.payload?.data?.skipped} message=${mutedNotify.payload?.message}`,
);
// 班级账号(教室机器)自己就能读写这项设置 —— 需求就是"由 ClassIsland 之外的客户端自己选"
const classSessionToken = await classLoginToken();
const readByClass = await api(`/classes/${target.id}/notification-channel`, {
token: classSessionToken,
});
record(
'班级账号可读取通知显示位置',
readByClass.status === 200 && readByClass.payload?.data?.notificationChannel === 'client',
`channel=${readByClass.payload?.data?.notificationChannel}`,
);
const setByClass = await api(`/classes/${target.id}/notification-channel`, {
method: 'PATCH',
token: classSessionToken,
body: { notificationChannel: 'both' },
});
record(
'班级账号可修改通知显示位置(由教室客户端自己选)',
setByClass.status === 200 && setByClass.payload?.data?.notificationChannel === 'both',
`channel=${setByClass.payload?.data?.notificationChannel}`,
);
const badChannel = await api(`/classes/${target.id}/notification-channel`, {
method: 'PATCH',
token: teacherToken,
body: { notificationChannel: 'nope' },
});
record('非法显示位置被拒(422)', badChannel.status === 422, `status=${badChannel.status}`);
// ---------------------------------------------------------------- 5. 课表镜像
//
// 同步方向在 2026-10-06 反转:**服务端 → 教室自动下发**成为主方向(默认开启),
// 「把教室课表传上来」改成 Web 端的一次性人工动作。因此这里先验证"默认就下发",
// 再验证"关掉之后确实不下发"。
const mirrorDefault = await api('/integrations/classisland/class-plan', { deviceToken });
record(
'课表默认由服务端自动下发(新方向:服务端 → 教室)',
mirrorDefault.status === 200 && mirrorDefault.payload?.data?.classPlan?.entries?.length >= 0,
`status=${mirrorDefault.status} data=${mirrorDefault.payload?.data === null ? 'null' : 'object'}`,
);
const disabled = await api(`/integrations/devices/${deviceId}`, {
method: 'PATCH',
token: teacherToken,
body: { mirrorScheduleToClassIsland: false },
});
record(
'关闭「镜像课表到 ClassIsland」',
disabled.status === 200 && disabled.payload?.data?.mirrorScheduleToClassIsland === false,
`status=${disabled.status}`,
);
const mirrorOff = await api('/integrations/classisland/class-plan', { deviceToken });
record(
'关掉镜像后不再下发课表',
mirrorOff.status === 200 &&
(mirrorOff.payload?.data === null || mirrorOff.payload?.data === undefined),
`data=${mirrorOff.payload?.data === null ? 'null' : 'object'}`,
);
const enabled = await api(`/integrations/devices/${deviceId}`, {
method: 'PATCH',
token: teacherToken,
body: { mirrorScheduleToClassIsland: true },
});
record(
'重新打开「镜像课表到 ClassIsland」',
enabled.status === 200 && enabled.payload?.data?.mirrorScheduleToClassIsland === true,
`status=${enabled.status}`,
);
const mirror = await api('/integrations/classisland/class-plan', { deviceToken });
const plan = mirror.payload?.data?.classPlan;
const weekDays = (plan?.entries ?? []).map((item) => item.weekDay);
record(
'拉取课表为 ClassIsland 口径(0=周日 … 6=周六)',
mirror.status === 200 &&
Array.isArray(plan?.entries) &&
plan.entries.length >= 3 &&
weekDays.every((day) => day >= 0 && day <= 6),
`条目=${plan?.entries?.length} weekDay=[${weekDays.join(',')}] 档案名=${plan?.profileName}`,
);
record(
'单双周换算为 WeekCountDiv/Total',
(plan?.entries ?? []).some((item) => item.weekCountDivTotal === 2),
(plan?.entries ?? [])
.map((item) => `${item.subject}:${item.weekCountDiv}/${item.weekCountDivTotal}`)
.join(' '),
);
// ClassInfo.Index 与"第 i 个上课时间点"一一对应,因此镜像条目必须带起止时间,
// 否则插件只能按数组顺序硬排,一旦某天少一节整份课表就错位(这是最容易漏的一处契约)
const timeOk = (plan?.entries ?? []).every(
(item) => /^\d{2}:\d{2}$/.test(item.startTime ?? '') && /^\d{2}:\d{2}$/.test(item.endTime ?? ''),
);
record(
'镜像条目带起止时间(插件据此重建上课时间点)',
(plan?.entries ?? []).length > 0 && timeOk,
(plan?.entries ?? [])
.slice(0, 3)
.map((item) => `${item.subject} ${item.startTime}-${item.endTime}`)
.join(' | '),
);
const classPoints = (plan?.timeLayouts?.[0]?.layouts ?? []).filter((item) => item.timeType === 0);
record(
'镜像时间表含上课时间点(与课表条目对得上)',
classPoints.length > 0 && (plan?.entries ?? []).length >= classPoints.length / 2,
`上课点=${classPoints.length} 条目=${(plan?.entries ?? []).length}`,
);
/* ---------------------------------------------------------------- 5.1 课表同步:幽灵行清理 + 机器码回填 */
// 老师在 Web 端手排的一节课(source=manual):插件同步时**绝不能**删它
const courseList = await api(`/courses?classId=${target.id}`, { token: teacherToken });
const courseId = (courseList.payload?.data ?? [])[0]?.id;
const manualCreated = await api('/schedules', {
method: 'POST',
token: teacherToken,
body: {
classId: target.id,
courseId,
dayOfWeek: 7,
startTime: '21:00',
endTime: '21:45',
weekStart: 1,
weekEnd: 20,
weekParity: 'ALL',
},
});
const manualScheduleId = manualCreated.payload?.data?.id;
record(
'(准备)Web 端手排一节课(source=manual)',
manualCreated.status === 201 && Boolean(manualScheduleId),
`status=${manualCreated.status}`,
);
const entry = (startTime, endTime) => ({
dayOfWeek: 6,
startTime,
endTime,
subject: '语文',
weekParity: 'ALL',
});
/** 该班课表里"周六 19:xx"的行(插件上报写入的那些) */
const listSaturday = async () => {
const list = await api(`/schedules?classId=${target.id}`, { token: teacherToken });
return (list.payload?.data ?? []).filter(
(item) => item.dayOfWeek === 6 && item.startTime.startsWith('19:'),
);
};
// 第一次上报:两节(第二节随后会被"老师在 ClassIsland 里删掉")
const ghostReport = await api('/integrations/classisland/report', {
method: 'POST',
deviceToken,
body: {
deviceKey: 'smoke-machine-01',
schedule: { mode: 'merge', entries: [entry('19:00', '19:45'), entry('19:50', '20:35')] },
},
});
record(
'插件上报两节课(其中一节随后会被删除)',
ghostReport.payload?.data?.scheduleApplied === true,
`status=${ghostReport.status}`,
);
const beforePrune = await listSaturday();
record('上报后两节都在库里', beforePrune.length === 2, `周六 19 点=${beforePrune.length} 节`);
// 第二次上报:只报第二节 → 第一节应当被清理。
// 原先 merge 只 upsert、从不删除,老师删掉的课会永远留在服务端(幽灵课),
// ClassHelper 班级端与 Web 端会一直显示一节实际上已经不上的课。
const pruneReport = await api('/integrations/classisland/report', {
method: 'POST',
deviceToken,
body: {
deviceKey: 'smoke-machine-01',
schedule: { mode: 'merge', entries: [entry('19:50', '20:35')] },
},
});
const afterPrune = await listSaturday();
record(
'插件侧删除的课被同步清理(不再留幽灵课)',
pruneReport.payload?.data?.scheduleApplied === true &&
afterPrune.length === 1 &&
afterPrune[0]?.startTime === '19:50',
`周六 19 点=${afterPrune.map((item) => item.startTime).join(',') || '空'}`,
);
// 只清理"插件同步出来的行":老师手排的课必须活着
const scheduleList = await api(`/schedules?classId=${target.id}`, { token: teacherToken });
const manualAlive = (scheduleList.payload?.data ?? []).some((item) => item.id === manualScheduleId);
record('Web 端手排的课不被插件同步删除', manualAlive, `手排行 id=${manualScheduleId ?? '-'}`);
// 机器码回填:设备列表里不再是 pending-…
const deviceList = await api(`/integrations/devices?classId=${target.id}`, { token: teacherToken });
const backfilledKey =
(deviceList.payload?.data ?? []).find((item) => item.id === deviceId)?.deviceKey ?? '';
record(
'插件上报的机器码已回填到设备记录',
backfilledKey === 'smoke-machine-01',
`deviceKey=${backfilledKey}`,
);
// 清理:把手排的课与本次上报写进去的课都删掉,避免污染演示数据
if (manualScheduleId) {
await api(`/schedules/${manualScheduleId}`, { method: 'DELETE', token: teacherToken });
}
for (const row of await listSaturday()) {
await api(`/schedules/${row.id}`, { method: 'DELETE', token: teacherToken });
}
record('清理:本次验证写入的课表与手排课已删除', (await listSaturday()).length === 0, '周六 19 点已清空');
// ---------------------------------------------------------------- 6. 停用设备
await api(`/integrations/devices/${deviceId}`, {
method: 'PATCH',
token: teacherToken,
body: { enabled: false },
});
const blocked = await api('/integrations/classisland/report', {
method: 'POST',
deviceToken,
body: { state: { inClass: false, clientTime: new Date().toISOString() } },
});
record('停用设备后插件上报被拒(403)', blocked.status === 403, `status=${blocked.status}`);
// ---------------------------------------------------------------- 7. 权限隔离
// 班级码只有管理员/班主任可见,班级密码也是默认值,因此这里按管理员信息补齐
let classCode = target.code ?? null;
if (!classCode && adminToken) {
const all = await api('/classes', { token: adminToken });
classCode = (all.payload?.data ?? []).find((item) => item.id === target.id)?.code ?? null;
}
const studentLogin = await api('/auth/class-login', {
method: 'POST',
body: { code: classCode ?? '', password: '123456' },
});
const studentToken = studentLogin.payload?.data?.token;
if (studentToken) {
const forbidden = await api('/integrations/devices', { token: studentToken });
record('学生无法查看联动设备列表(403)', forbidden.status === 403, `status=${forbidden.status}`);
} else {
record('班级账号登录(跳过学生隔离用例)', false, `status=${studentLogin.status}`);
}
// ---------------------------------------------------------------- 清理
const removed = await api(`/integrations/devices/${deviceId}`, { method: 'DELETE', token: teacherToken });
record('删除验证设备(清理)', removed.status === 200, `status=${removed.status}`);
const failed = results.filter((item) => !item.ok);
console.log(`\n=== 结果:${results.length - failed.length}/${results.length} 通过 ===`);
if (failed.length > 0) {
console.log('失败用例:');
for (const item of failed) console.log(` - ${item.name} (${item.detail})`);
process.exit(1);
}
console.log('ClassIsland 联动链路全部通过。\n');
}
main().catch((error) => {
console.error('验证脚本异常:', error);
process.exit(1);
});
+58 -85
View File
@@ -476,7 +476,11 @@ async function main() {
try {
const { payload, elapsed } = await notificationWait;
record('ClassHelper 班级端 5 秒内收到 notification:new', elapsed < TIME_LIMIT_MS, `${elapsed}ms · ${payload?.title}`);
record(
'ClassHelper 班级端 5 秒内收到 notification:new',
elapsed < TIME_LIMIT_MS,
`${elapsed}ms · ${payload?.title}`,
);
} catch (error) {
record('ClassHelper 班级端 5 秒内收到 notification:new', false, error.message);
}
@@ -534,7 +538,11 @@ async function main() {
try {
const { payload, elapsed } = await homeworkWait;
record('ClassHelper 班级端 5 秒内收到 homework:new', elapsed < TIME_LIMIT_MS, `${elapsed}ms · ${payload?.title}`);
record(
'ClassHelper 班级端 5 秒内收到 homework:new',
elapsed < TIME_LIMIT_MS,
`${elapsed}ms · ${payload?.title}`,
);
} catch (error) {
record('ClassHelper 班级端 5 秒内收到 homework:new', false, error.message);
}
@@ -705,8 +713,8 @@ async function main() {
'管理员设置某班某科的任课老师(PUT /subject-teachers)',
adminAssignSubject.status === 200 &&
(adminAssignSubject.payload?.data ?? []).some(
(item) => item.subjectName === probeSubject &&
item.teacherId === teacher2Login.payload?.data?.user?.id,
(item) =>
item.subjectName === probeSubject && item.teacherId === teacher2Login.payload?.data?.user?.id,
),
`status=${adminAssignSubject.status}`,
);
@@ -1145,11 +1153,7 @@ async function main() {
token: adminToken,
body: { assignments: [{ subjectName: '音乐', teacherId: teacher2Login.payload?.data?.user?.id }] },
});
record(
'管理员分配任课老师成功(200)',
adminAssign.status === 200,
`status=${adminAssign.status}`,
);
record('管理员分配任课老师成功(200)', adminAssign.status === 200, `status=${adminAssign.status}`);
// 解除 = 把该科还回班主任(Course.teacherId 是必填列,不能留空)
const adminUnassign = await api(`/classes/${classId}/subject-teachers`, {
method: 'PUT',
@@ -1183,8 +1187,9 @@ async function main() {
// 新规则:**作业按科目授权**。
// 科任老师只能布置自己任教科目(Course.teacherId)的作业;
// 不指定科目的作业只有班主任与管理员能发 —— 两条都要验到。
const subjectCourse = (await api(`/courses?classId=${subjectClassId}`, { token: adminToken }))
.payload?.data?.find((item) => item.teacherId === teacher2Id);
const subjectCourse = (
await api(`/courses?classId=${subjectClassId}`, { token: adminToken })
).payload?.data?.find((item) => item.teacherId === teacher2Id);
const subjectHomework = await api('/homeworks', {
method: 'POST',
token: subjectClassId ? teacher2Token : teacherToken,
@@ -1215,8 +1220,9 @@ async function main() {
);
// 科任老师改**别人任教科目**的作业同样被拒
if (subjectCourse) {
const otherCourse = (await api(`/courses?classId=${subjectClassId}`, { token: adminToken }))
.payload?.data?.find((item) => item.teacherId !== teacher2Id);
const otherCourse = (
await api(`/courses?classId=${subjectClassId}`, { token: adminToken })
).payload?.data?.find((item) => item.teacherId !== teacher2Id);
// 先确认"别人任教的科目"这个前提存在:缺了它,下面那条用例会因为"没带科目"
// 而被拒(403),看着是绿的,其实没验到"非任教科目"这条规则。
record(
@@ -1355,7 +1361,9 @@ async function main() {
);
}
const badDay = await api(`/notifications/days?classId=${classId}&from=2026-13-45`, { token: teacherToken });
const badDay = await api(`/notifications/days?classId=${classId}&from=2026-13-45`, {
token: teacherToken,
});
record('通知归档接口拒绝非法日期(422)', badDay.status === 422, `status=${badDay.status}`);
// 批量发布通知:一次提交多个班,返回逐班结果
@@ -1545,25 +1553,32 @@ async function main() {
`含 homework:write=${teacher2ResetPermissions.includes('homework:write')}`,
);
// 管理员固定拥有全部权限,不接受分配
// 管理员可以分配权限组,但始终保留两个管理入口
const assignAdmin = await api(`/permissions/users/${adminMember?.id}/groups`, {
method: 'PUT',
token: adminToken,
body: { groupIds: permissionGroupId ? [permissionGroupId] : [] },
});
record(
'管理员不接受权限组分配(PUT /users/:id/groups → 400)',
Boolean(adminMember) &&
assignAdmin.status === 400 &&
String(assignAdmin.payload?.message ?? '').includes('权限组'),
'管理员可以分配权限组(PUT /users/:id/groups → 200)',
Boolean(adminMember) && assignAdmin.status === 200 && assignAdmin.payload?.data?.fixed === false,
`status=${assignAdmin.status} 响应=${assignAdmin.payload?.message ?? ''}`,
);
await api(`/permissions/users/${adminMember?.id}/groups`, {
method: 'PUT',
token: adminToken,
body: { groupIds: [] },
});
// 内置权限组不可删除:先找一个 builtin 的(**演示库当前没有内置组**,此时只报事实、不算失败)
const groupsList = await api('/permissions/groups', { token: adminToken });
const builtinGroup = (groupsList.payload?.data ?? []).find((item) => item.builtin === true) ?? null;
if (builtinGroup) {
const deleteBuiltin = await api(`/permissions/groups/${builtinGroup.id}`, { method: 'DELETE', token: adminToken });
const deleteBuiltin = await api(`/permissions/groups/${builtinGroup.id}`, {
method: 'DELETE',
token: adminToken,
});
record(
'内置权限组不可删除(DELETE /permissions/groups/:id → 400)',
deleteBuiltin.status === 400,
@@ -1607,7 +1622,11 @@ async function main() {
// 心跳不强求权限键(教室端会话权限集为空),但**必须登录**:没有 JWT 一律 401
const heartbeatNoAuth = await api('/clients/heartbeat', { method: 'POST', body: heartbeatBase });
const heartbeat = await api('/clients/heartbeat', { method: 'POST', token: adminToken, body: heartbeatBase });
const heartbeat = await api('/clients/heartbeat', {
method: 'POST',
token: adminToken,
body: heartbeatBase,
});
const heartbeatData = heartbeat.payload?.data;
record(
'客户端心跳 POST /clients/heartbeat(未登录 401 / 登录后 200 且返回 deviceId 与 command 字段)',
@@ -1644,7 +1663,11 @@ async function main() {
const command = await api('/clients/commands', {
method: 'POST',
token: adminToken,
body: { deviceIds: [device?.id ?? heartbeatData?.deviceId ?? 'none'], kind: 'lock', note: 'E2E 远控用例' },
body: {
deviceIds: [device?.id ?? heartbeatData?.deviceId ?? 'none'],
kind: 'lock',
note: 'E2E 远控用例',
},
});
const heartbeatWithCommand = await api('/clients/heartbeat', {
method: 'POST',
@@ -1677,7 +1700,8 @@ async function main() {
);
const devicesAfterAck = await api('/clients/devices', { token: adminToken });
const ackedDevice = (devicesAfterAck.payload?.data ?? []).find((item) => item.deviceKey === deviceKey) ?? null;
const ackedDevice =
(devicesAfterAck.payload?.data ?? []).find((item) => item.deviceKey === deviceKey) ?? null;
record(
'回执后设备不再有待执行命令(pendingCommand 为空)',
Boolean(ackedDevice) && ackedDevice.pendingCommand === null,
@@ -1803,7 +1827,9 @@ async function main() {
});
record(
'开启大模型助手并固定为离线 mock(PUT /ai/settings)',
enableAi.status === 200 && enableAi.payload?.data?.enabled === true && enableAi.payload?.data?.provider === 'mock',
enableAi.status === 200 &&
enableAi.payload?.data?.enabled === true &&
enableAi.payload?.data?.provider === 'mock',
`status=${enableAi.status} enabled=${enableAi.payload?.data?.enabled} provider=${enableAi.payload?.data?.provider}`,
);
@@ -1916,8 +1942,7 @@ async function main() {
const diagnosticsText = JSON.stringify(diagnostics.payload?.data ?? {});
record(
'运行诊断 GET /system/diagnostics(200 且不泄漏 apiKey/password/token/secret)',
diagnostics.status === 200 &&
!/apiKey|password|token|secret/i.test(diagnosticsText),
diagnostics.status === 200 && !/apiKey|password|token|secret/i.test(diagnosticsText),
`status=${diagnostics.status} 字段=${Object.keys(diagnostics.payload?.data ?? {}).join(',')}`,
);
}
@@ -2930,8 +2955,8 @@ async function main() {
body: { username: 'smoke_denied_teacher', name: '越权教师', password: 'smoke123456' },
});
record(
'仅管理员可录入教师(教师读取/新建均 403)',
teacherSeesTeachers.status === 403 && teacherCreatesTeacher.status === 403,
'教师名单只读与管理分离(默认教师可读取,但不能新建)',
teacherSeesTeachers.status === 200 && teacherCreatesTeacher.status === 403,
`列表=${teacherSeesTeachers.status} 新建=${teacherCreatesTeacher.status} message=${teacherCreatesTeacher.payload?.message ?? ''}`,
);
@@ -3187,8 +3212,6 @@ async function main() {
'Notification',
'NotificationRead',
'Grade',
'IntegrationDevice',
'ClassIslandPush',
'PermissionGroup',
'PermissionGroupItem',
'UserPermissionGroup',
@@ -3511,13 +3534,12 @@ async function main() {
// force 只对管理员生效:教师带 force=1 也必须命中缓存(否则任意登录用户都能刷爆匿名限流)
const updateTeacherForced = await api('/update/check?force=1', { token: teacherToken });
record(
'更新检查:教师可查(公开信息),但 force 仅管理员生效',
'更新检查:默认教师可查,强制刷新需要 update:force',
updateTeacherForced.status === 200 &&
updateTeacherForced.payload?.data?.checkedAt === updateData.checkedAt,
`status=${updateTeacherForced.status} 命中缓存=${updateTeacherForced.payload?.data?.checkedAt === updateData.checkedAt}`,
);
/* ---------------------------------------------------------------- 13. 学期周次(仅管理员可写) */
// 需求:「第几周的周次数据可以由 admin 修改,并对所有 ClassIsland 下发修改」。
// 线性推算遇到调休/补课会整体错位,所以支持逐周指定日期区间。
@@ -3624,62 +3646,13 @@ async function main() {
`configured=${termRestored.payload?.data?.configured}`,
);
/* ---------------------------------------------------------------- 14. 课表同步方向反转 */
// 自建一台临时设备(收尾删掉):不依赖演示库里有没有接入过设备
const tempDevice = await api('/integrations/devices', {
method: 'POST',
token: adminToken,
body: { classId, name: 'E2E 课表方向校验设备' },
});
const tempDeviceId = tempDevice.payload?.data?.device?.id;
const retiredIntegration = await api('/integrations/devices', { token: adminToken });
record(
'课表方向:新建设备默认「服务端自动下发、不自动回传」',
tempDevice.status === 201 &&
tempDevice.payload?.data?.device?.syncScheduleToServer === false &&
tempDevice.payload?.data?.device?.mirrorScheduleToClassIsland === true,
`status=${tempDevice.status} syncScheduleToServer=${tempDevice.payload?.data?.device?.syncScheduleToServer} mirrorScheduleToClassIsland=${tempDevice.payload?.data?.device?.mirrorScheduleToClassIsland}`,
'退役联动接口不再提供服务',
retiredIntegration.status === 404,
`status=${retiredIntegration.status}`,
);
if (tempDeviceId) {
const pullRequest = await api(`/integrations/devices/${tempDeviceId}/request-schedule`, {
method: 'POST',
token: adminToken,
});
record(
'从教室机器获取课表:管理员可发起(POST /request-schedule)',
pullRequest.status === 200 && pullRequest.payload?.data?.requested === true,
`status=${pullRequest.status} ${pullRequest.payload?.message ?? ''}`,
);
// 置位后再读设备列表应当看到待办(插件下一次心跳看到就会立刻把课表推上来)
const afterRequest = await api(`/integrations/devices?classId=${classId}`, { token: adminToken });
const requestedDevice = (afterRequest.payload?.data ?? []).find((item) => item.id === tempDeviceId);
record(
'从教室机器获取课表:待办标记已落库(插件下次心跳会照做)',
requestedDevice?.requestScheduleReport === true,
`requestScheduleReport=${requestedDevice?.requestScheduleReport}`,
);
// 教师对**别人班**的设备不能发起
const deniedPull = await api(`/integrations/devices/${tempDeviceId}/request-schedule`, {
method: 'POST',
token: teacher2Token,
});
record(
'从教室机器获取课表:非本班教师被拒绝(403)',
deniedPull.status === 403,
`status=${deniedPull.status}`,
);
// 收尾:删掉临时设备
const removedDevice = await api(`/integrations/devices/${tempDeviceId}`, {
method: 'DELETE',
token: adminToken,
});
record('课表方向用例收尾:临时设备已删除', removedDevice.status === 200, `status=${removedDevice.status}`);
}
socket.close();
// ---------------------------------------------------------------- 汇总
+3
View File
@@ -7,6 +7,7 @@ import { env } from './config/env.js';
import { disconnectPrisma, pingDatabase } from './lib/db.js';
import { ensureInitialAdmin, ensureSchema } from './lib/db-bootstrap.js';
import { logger } from './lib/logger.js';
import { backfillNotificationDates } from './lib/backfill-notification-dates.js';
import { refreshDeveloperMode } from './lib/settings.js';
import { resolveWebDistDir } from './lib/web-static.js';
import { initRealtime } from './realtime/socket.js';
@@ -51,6 +52,8 @@ async function prepareDatabase(): Promise<void> {
}
await prepareDatabase();
const backfilledDates = await backfillNotificationDates();
if (backfilledDates) logger.info(`已补齐 ${backfilledDates} 条历史通知的所属日期`);
// 开发者模式的内存缓存:错误中间件每请求都要问一次,不可能为此查库(见 lib/settings.ts)
await refreshDeveloperMode();
@@ -0,0 +1,24 @@
import { dayKeyLocal } from '@classhelper/shared';
import { prisma } from './db.js';
/** 旧叫人通知没有所属日期;用服务进程的本地日期口径幂等回填,兼容 SQLite 与 MySQL。 */
export async function backfillNotificationDates(): Promise<number> {
let updated = 0;
for (;;) {
const rows = await prisma.notification.findMany({
where: { assignDate: '' },
select: { id: true, createdAt: true },
take: 200,
});
if (!rows.length) return updated;
await prisma.$transaction(
rows.map((row) =>
prisma.notification.update({
where: { id: row.id },
data: { assignDate: dayKeyLocal(row.createdAt) },
}),
),
);
updated += rows.length;
}
}
+17
View File
@@ -90,6 +90,23 @@ async function loadAppliedMigrations(client: {
`CREATE TABLE IF NOT EXISTS "${MIGRATION_LEDGER}" ("name" TEXT NOT NULL PRIMARY KEY, "appliedAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
);
// 开发库/源码部署由 Prisma 管理迁移;覆盖安装时接纳其已完成记录,
// 不能重跑已被后续迁移改过的旧 SQL(例如已移除的 User.classId 索引)。
const prismaLedger = await prisma.$queryRawUnsafe<Array<{ name: string }>>(
`SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_prisma_migrations'`,
);
if (prismaLedger.length > 0) {
const completed = await prisma.$queryRawUnsafe<Array<{ migration_name: string }>>(
`SELECT migration_name FROM "_prisma_migrations" WHERE finished_at IS NOT NULL AND rolled_back_at IS NULL`,
);
for (const row of completed) {
await client.execute({
sql: `INSERT OR IGNORE INTO "${MIGRATION_LEDGER}" ("name") VALUES (?)`,
args: [row.migration_name],
} as never);
}
}
const rows = await prisma.$queryRawUnsafe<Array<{ name: string }>>(
`SELECT name FROM "${MIGRATION_LEDGER}"`,
);
+8 -2
View File
@@ -2,8 +2,14 @@ import type { Response } from 'express';
import type { ApiResponse } from '@classhelper/shared';
/** 成功响应:{ success: true, data, message } */
export function sendOk<T>(res: Response, data: T, message = 'ok', status = 200): void {
const body: ApiResponse<T> = { success: true, data, message };
export function sendOk<T>(
res: Response,
data: T,
message = 'ok',
status = 200,
legacyFields: object = {},
): void {
const body: ApiResponse<T> = { ...legacyFields, success: true, data, message };
res.status(status).json(body);
}
-9
View File
@@ -3,7 +3,6 @@ import type {
ArchivedClassDto,
ArchivedYearDto,
ClassDto,
ClassIslandNotificationChannel,
ClassTeacherBrief,
CourseBrief,
CourseDto,
@@ -191,8 +190,6 @@ export interface ClassLike {
teacherId: string;
/** 本学期教学周数(班主任可调,默认 20) */
termWeeks?: number;
/** 通知显示位置:both / client / classisland(由 ClassHelper 班级端设置) */
notificationChannel?: string | null;
/** 班级端按学号查成绩的开关 */
studentGradeQueryEnabled?: boolean | null;
/** 毕业归档所属届别;null = 在读 */
@@ -209,11 +206,6 @@ export interface ClassLike {
};
}
/** 通知显示位置:库里存字符串,出参收敛成联合类型(非法值一律按默认 both 处理) */
export function toNotificationChannel(value: string | null | undefined): ClassIslandNotificationChannel {
return value === 'client' || value === 'classisland' ? value : 'both';
}
export function toClassDto(item: ClassLike): ClassDto {
return {
id: item.id,
@@ -223,7 +215,6 @@ export function toClassDto(item: ClassLike): ClassDto {
classIndex: item.classIndex ?? null,
teacherId: item.teacherId,
termWeeks: item.termWeeks ?? 20,
notificationChannel: toNotificationChannel(item.notificationChannel),
// 默认开启:老库补列时的默认值也是 true,两边保持一致
studentGradeQueryEnabled: item.studentGradeQueryEnabled ?? true,
archivedYearId: item.archivedYearId ?? null,
+47 -12
View File
@@ -12,13 +12,13 @@ import type { TokenPayload } from './jwt.js';
* 生效权限集合的**唯一加载入口**(权限组功能的全部运行时逻辑都收在这里)。
*
* 语义(与 shared 的 `PERMISSION_DEFAULT_ROLES` 一一对应):
* - `ADMIN`:全集。另外**永远**保留 {@link ADMIN_UNREMOVABLE_PERMISSIONS},避免管理员
* - `ADMIN`:按权限组计算,另外**永远**保留 {@link ADMIN_UNREMOVABLE_PERMISSIONS},避免管理员
* 把自己(或最后一个管理员)锁在权限页之外;
* - `CLASS_DEVICE`(ClassHelper 班级端):**空集,且不受权限组影响** —— 班级端的会话主体是
* 班级而非账号,它的能力由班级维度断言(`canManageSubjectContent(..., { allowClassDevice })`
* 等)决定,给某个班级端"分配权限组"没有意义;
* - 其他账号:**有分组**时取这些组的键并集(因此可以比默认更少 ⇒ 也能用来收回权限);
* **没有任何分组**时回落角色默认模板(逐条镜像权限组上线前各路由的 `requireRole`)。
* **没有任何分组**时使用数据库中可编辑的角色默认组(逐条镜像权限组上线前各路由的 `requireRole`)。
*
* 每次请求实时查询(不缓存):权限改动**立即生效**,代价是每请求多一条 `findMany`
* (账号规模很小,这个代价换"改了立刻生效"是值的)。
@@ -28,10 +28,7 @@ export async function loadEffectivePermissions(user: TokenPayload): Promise<Set<
if (user.classSession || user.role === 'CLASS_DEVICE') return permissions;
if (user.role === 'ADMIN') {
for (const key of PERMISSION_KEYS) permissions.add(key);
return permissions;
}
await ensureDefaultGroups();
const assignments = await prisma.userPermissionGroup.findMany({
where: { userId: user.sub },
@@ -39,7 +36,14 @@ export async function loadEffectivePermissions(user: TokenPayload): Promise<Set<
});
if (assignments.length === 0) {
for (const key of defaultPermissionsForRole(user.role)) permissions.add(key);
const group = await prisma.permissionGroup.findUnique({
where: { defaultRole: user.role },
include: { items: true },
});
for (const key of group ? group.items.map((item) => item.key) : defaultPermissionsForRole(user.role)) {
if ((PERMISSION_KEYS as readonly string[]).includes(key)) permissions.add(key as PermissionKey);
}
if (user.role === 'ADMIN') for (const key of ADMIN_UNREMOVABLE_PERMISSIONS) permissions.add(key);
return permissions;
}
@@ -50,17 +54,48 @@ export async function loadEffectivePermissions(user: TokenPayload): Promise<Set<
if (known.has(item.key)) permissions.add(item.key as PermissionKey);
}
}
if (user.role === 'ADMIN') for (const key of ADMIN_UNREMOVABLE_PERMISSIONS) permissions.add(key);
return permissions;
}
/** 首次升级创建默认组;后续启动保留管理员的编辑结果(包括空权限组)。 */
let defaultGroupsReady: Promise<void> | null = null;
export function ensureDefaultGroups(): Promise<void> {
if (!defaultGroupsReady)
defaultGroupsReady = createDefaultGroups().finally(() => {
defaultGroupsReady = null;
});
return defaultGroupsReady;
}
async function createDefaultGroups(): Promise<void> {
for (const role of ['ADMIN', 'TEACHER'] as const) {
if (await prisma.permissionGroup.findUnique({ where: { defaultRole: role }, select: { id: true } }))
continue;
const baseName = `${role === 'ADMIN' ? '管理员' : '教师'}默认权限`;
let name = baseName;
let suffix = 1;
// 旧库可能已有同名自定义组,保留它并为角色默认组选一个不冲突的名称。
while (await prisma.permissionGroup.findUnique({ where: { name }, select: { id: true } })) {
name = `${baseName}(系统 ${suffix++})`;
}
await prisma.permissionGroup.upsert({
where: { defaultRole: role },
update: {},
create: {
id: `default-permission-${role.toLowerCase()}`,
defaultRole: role,
name,
builtin: true,
description: '未分配其他权限组时自动生效;可调整权限。管理员始终保留权限与系统管理入口。',
items: { create: ROLE_DEFAULT_PERMISSIONS[role].map((key) => ({ key })) },
},
});
}
}
/** 管理员不可被剥夺的权限键(防锁死) */
export const ADMIN_UNREMOVABLE_PERMISSIONS: readonly PermissionKey[] = ['permission:manage', 'system:manage'];
/** 角色默认模板(供权限页展示"没分组时会是什么") */
export function roleDefaultPermissions(role: TokenPayload['role']): readonly PermissionKey[] {
return ROLE_DEFAULT_PERMISSIONS[role];
}
/** 把权限键翻译成中文提示(403 文案与权限页共用) */
export function permissionLabel(key: PermissionKey): string {
return PERMISSION_LABELS[key];
+1 -1
View File
@@ -46,7 +46,7 @@ export const attachmentUrlSchema = z
.max(500)
.refine(
(value) =>
value === '' || value.startsWith('/') || /^https?:\/\//i.test(value),
value === '' || (/^\/(?![\/\\])/.test(value) && !value.includes('\\')) || /^https?:\/\//i.test(value),
{ message: '附件链接需为 http(s):// 地址或站内相对路径' },
)
.nullish();
+11 -4
View File
@@ -50,8 +50,6 @@ export const SNAPSHOT_TABLES = [
'Notification',
'NotificationRead',
'Grade',
'IntegrationDevice',
'ClassIslandPush',
'ClientDevice',
'ClientCommand',
'ClientRelease',
@@ -132,7 +130,11 @@ export function assertValidSnapshot(value: unknown): asserts value is DatabaseSn
}
}
async function setForeignKeys(prisma: PrismaClient, provider: DatabaseProvider, enabled: boolean): Promise<void> {
async function setForeignKeys(
prisma: PrismaClient,
provider: DatabaseProvider,
enabled: boolean,
): Promise<void> {
const sql =
provider === 'mysql'
? `SET FOREIGN_KEY_CHECKS=${enabled ? 1 : 0}`
@@ -164,7 +166,12 @@ export async function restoreSnapshot(
}
}
for (const table of SNAPSHOT_TABLES) {
const rows = snapshot.data[table];
const rows = snapshot.data[table].map((row) => {
if (table !== 'Class' || typeof row !== 'object' || row === null) return row;
const copy = { ...(row as Record<string, unknown>) };
delete copy.notificationChannel;
return copy;
});
for (let index = 0; index < rows.length; index += CHUNK_SIZE) {
await delegates[table].createMany({ data: rows.slice(index, index + CHUNK_SIZE) });
}
+12 -1
View File
@@ -104,6 +104,15 @@ export function requirePermission(...keys: PermissionKey[]): RequestHandler {
};
}
/** 班级端按班级范围开放读取;教师/管理员仍按可编辑的功能权限校验。 */
export function requireStaffPermission(...keys: PermissionKey[]): RequestHandler {
const guard = requirePermission(...keys);
return (req, res, next) => {
if (req.auth?.user.role === 'CLASS_DEVICE') return next();
return guard(req, res, next);
};
}
/**
* 权限守卫(任一满足):只要拥有其中**一个**权限键就放行。
*
@@ -119,7 +128,9 @@ export function requireAnyPermission(...keys: PermissionKey[]): RequestHandler {
const permissions = req.auth.permissions ?? new Set<PermissionKey>();
if (keys.length > 0 && !keys.some((key) => permissions.has(key))) {
const labels = keys.map((key) => `「${PERMISSION_LABELS[key]}」`).join('、');
next(ApiError.forbidden(`当前账号缺少权限(${labels} 中至少需要一项),请联系管理员在「权限组」里分配`));
next(
ApiError.forbidden(`当前账号缺少权限(${labels} 中至少需要一项),请联系管理员在「权限组」里分配`),
);
return;
}
next();
+47 -14
View File
@@ -1,6 +1,12 @@
import { dayKeyLocal, type AiActionKind, type AiAuditDto, type AiInterpretResult, type AiSettingsDto } from '@classhelper/shared';
import {
dayKeyLocal,
type AiActionKind,
type AiAuditDto,
type AiInterpretResult,
type AiSettingsDto,
} from '@classhelper/shared';
import { z } from 'zod';
import { getAccessibleClassIds } from '../../lib/access.js';
import { getAccessibleClassIds, assertClassAccess } from '../../lib/access.js';
import { prisma } from '../../lib/db.js';
import { ApiError } from '../../lib/http.js';
import type { TokenPayload } from '../../lib/jwt.js';
@@ -17,7 +23,7 @@ import type { AiInterpretInput, UpdateAiSettingsInput } from './ai.schemas.js';
* 设计边界(照 approved 计划):
* 1. 模型只输出结构化意图(`{action, params, confidence}`),服务端用**与手动入口同一份 zod**
* 二次校验后返回预览;真正落库由前端确认后调既有端点(`POST /homeworks` 等),
* 于是权限断言、上课时段紧急通知保护、ClassIsland 推送全部自动复用(AGENTS.md §5 第 5/14 条);
* 于是权限断言、上课时段紧急通知保护全部自动复用(AGENTS.md §5 第 5/14 条);
* 2. **密钥只进不出**:`AppSetting` 里存的是 `encryptSecret()` 的密文,任何 GET 都不回传;
* 3. `provider: 'mock'` 用确定性规则离线解析 —— 自动化验收**绝不访问外网**(§5 第 52 条),
* 真实模型走 `provider: 'openai'` 时的 `{baseUrl}/chat/completions`。
@@ -98,6 +104,7 @@ interface AssistantContext {
}
async function resolveContext(user: TokenPayload, classId?: string): Promise<AssistantContext> {
if (classId) await assertClassAccess(user, classId);
const classIds = await getAccessibleClassIds(user);
const classes = await prisma.class.findMany({
where: { id: { in: classIds } },
@@ -201,7 +208,11 @@ async function callOpenAi(
signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
});
} catch (error) {
throw new ApiError(504, 'AI_TIMEOUT', `无法连接大模型服务:${error instanceof Error ? error.message : String(error)}`);
throw new ApiError(
504,
'AI_TIMEOUT',
`无法连接大模型服务:${error instanceof Error ? error.message : String(error)}`,
);
}
if (!response.ok) {
@@ -253,12 +264,13 @@ async function buildPreview(
if (action === 'call_student') {
const studentName = typeof params.studentName === 'string' ? params.studentName : '';
const student = studentName && classId
? await prisma.student.findFirst({
where: { classId, name: studentName },
select: { id: true, name: true },
})
: null;
const student =
studentName && classId
? await prisma.student.findFirst({
where: { classId, name: studentName },
select: { id: true, name: true },
})
: null;
if (!student) warnings.push(studentName ? `没找到学生「${studentName}」` : '没识别出学生姓名');
return {
summary: `叫${student?.name ?? (studentName || '某位同学')}到老师这里`,
@@ -281,7 +293,11 @@ export async function interpret(user: TokenPayload, input: AiInterpretInput): Pr
throw new ApiError(400, 'AI_NOT_CONFIGURED', '助手功能还没开启,请管理员在「大模型设置」里打开');
}
if (settings.provider === 'openai' && (!settings.hasApiKey || !settings.baseUrl)) {
throw new ApiError(400, 'AI_NOT_CONFIGURED', '还没配置大模型服务地址或密钥,请管理员在「大模型设置」里填写');
throw new ApiError(
400,
'AI_NOT_CONFIGURED',
'还没配置大模型服务地址或密钥,请管理员在「大模型设置」里填写',
);
}
const context = await resolveContext(user, input.classId);
@@ -301,7 +317,10 @@ export async function interpret(user: TokenPayload, input: AiInterpretInput): Pr
const warnings: string[] = [];
try {
if (reply.action === 'create_homework') {
const parsed = homeworkParamsSchema.parse({ ...reply.params, classId: reply.params.classId ?? input.classId });
const parsed = homeworkParamsSchema.parse({
...reply.params,
classId: reply.params.classId ?? input.classId,
});
action = 'create_homework';
params = parsed as unknown as Record<string, unknown>;
} else if (reply.action === 'create_notification') {
@@ -312,7 +331,10 @@ export async function interpret(user: TokenPayload, input: AiInterpretInput): Pr
action = 'create_notification';
params = parsed as unknown as Record<string, unknown>;
} else if (reply.action === 'call_student') {
const parsed = callParamsSchema.parse({ ...reply.params, classId: reply.params.classId ?? input.classId });
const parsed = callParamsSchema.parse({
...reply.params,
classId: reply.params.classId ?? input.classId,
});
action = 'call_student';
params = parsed as unknown as Record<string, unknown>;
}
@@ -321,6 +343,16 @@ export async function interpret(user: TokenPayload, input: AiInterpretInput): Pr
logger.warn(`助手参数校验失败:${error instanceof Error ? error.message : String(error)}`);
}
if (typeof params.classId === 'string') {
await assertClassAccess(user, params.classId);
if (typeof params.courseId === 'string') {
const course = await prisma.course.findFirst({
where: { id: params.courseId, classId: params.classId },
select: { id: true },
});
if (!course) throw ApiError.badRequest('科目不属于所选班级');
}
}
const preview = await buildPreview(action, params);
preview.warnings = [...preview.warnings, ...warnings];
if (settings.provider === 'mock') preview.warnings.push('当前是离线示例解析(未配置真实模型),请仔细核对');
@@ -330,7 +362,8 @@ export async function interpret(user: TokenPayload, input: AiInterpretInput): Pr
userId: user.sub,
prompt: input.text,
intent: action,
status: 'pending',
// 审计只记录解析,不代表前端确认后的业务操作已执行。
status: action === 'unknown' ? 'unrecognized' : 'interpreted',
message: preview.summary,
rawReply: JSON.stringify(reply).slice(0, 2000),
},
@@ -16,7 +16,7 @@ import * as authService from './auth.service.js';
const router = Router();
/** POST /api/auth/login - 登录(公开):教师 / 管理员 / 个人学生账号 */
/** POST /api/auth/login - 登录(公开):教师 / 管理员 */
router.post('/login', validate({ body: loginSchema }), async (req, res) => {
const result: LoginResponse = await authService.login(req.body as LoginInput);
sendOk(res, result, '登录成功');
@@ -26,7 +26,7 @@ router.post('/login', validate({ body: loginSchema }), async (req, res) => {
* POST /api/auth/class-login - 班级账号登录(公开,ClassHelper 班级端主入口)
*
* 班级码 + 班级密码 → 以「班级」为主体的 JWT(个人数据按全班读写)。
* 个人学生账号仍可用 /auth/login 登录(向后兼容,客户端已不再展示该入口)。
* 学生仅为名单记录,没有个人登录账号。
*/
router.post('/class-login', validate({ body: classLoginSchema }), async (req, res) => {
const result: LoginResponse = await authService.classLogin(req.body as ClassLoginInput);
@@ -1,4 +1,4 @@
import { SOCKET_EVENTS, buildCallTitle, type NotificationDto } from '@classhelper/shared';
import { SOCKET_EVENTS, buildCallTitle, dayKeyLocal, type NotificationDto } from '@classhelper/shared';
import { assertCanPublishNotification } from '../../lib/access.js';
import { prisma } from '../../lib/db.js';
import { ApiError } from '../../lib/http.js';
@@ -6,7 +6,6 @@ import type { TokenPayload } from '../../lib/jwt.js';
import { logger } from '../../lib/logger.js';
import { toNotificationDto } from '../../lib/mappers.js';
import { emitToClass, emitToSession } from '../../realtime/bus.js';
import { pushToClassIsland, shouldPushToClassIsland } from '../integrations/integrations.service.js';
import type { CreateCallInput } from './calls.schemas.js';
const creatorSelect = { select: { id: true, name: true, username: true } } as const;
@@ -55,6 +54,7 @@ export async function createCall(user: TokenPayload, input: CreateCallInput): Pr
// (不会触发上课时段 409 拦截,但客户端按普通通知排队处理)
priority: input.urgent ? 'URGENT' : 'HIGH',
createdBy: user.sub,
assignDate: dayKeyLocal(new Date()),
},
include: { creator: creatorSelect, reads: true },
});
@@ -65,26 +65,6 @@ export async function createCall(user: TokenPayload, input: CreateCallInput): Pr
// 定向广播给教室机器:会话房间以**班级 id** 为键,叫人消息因此立即展开
emitToSession(created.classId, SOCKET_EVENTS.callNew, dto);
// 叫人同样推到教室的 ClassIsland:老师点名时,教室大屏也弹一条(学生姓名在标题里)。
// 显示位置由班级端决定;推送失败不影响叫人本身。
try {
if (await shouldPushToClassIsland(input.classId)) {
await pushToClassIsland({
classId: input.classId,
title: created.title,
content: created.content,
urgent: input.urgent === true,
// 叫人属于「主动通知」:教室的 ClassIsland 上课时段也要立刻弹
kind: 'call',
createdBy: user.sub,
notificationId: created.id,
teacherName,
});
}
} catch (error) {
logger.warn(`叫人推送 ClassIsland 失败(叫人本身已发出):${String(error)}`);
}
logger.info(`${input.urgent ? '紧急叫人' : '叫人'}:${teacherName} → ${studentName}(${message})`);
return dto;
}
@@ -2,12 +2,7 @@ import { Router } from 'express';
import { sendCreated, sendOk } from '../../lib/http.js';
import { idParamSchema } from '../../lib/schemas.js';
import { authenticate, getAuthUser, requirePermission } from '../../middleware/auth.js';
import {
validate,
validatedBody,
validatedParams,
validatedQuery,
} from '../../middleware/validate.js';
import { validate, validatedBody, validatedParams, validatedQuery } from '../../middleware/validate.js';
import { defineModule } from '../module.types.js';
import {
addStudentSchema,
@@ -19,14 +14,12 @@ import {
promoteClassesSchema,
updateClassAccountSchema,
updateClassSchema,
updateNotificationChannelSchema,
updateStudentGradeQuerySchema,
type AddStudentInput,
type AssignSubjectTeachersInput,
type CreateClassInput,
type UpdateClassAccountInput,
type UpdateClassInput,
type UpdateNotificationChannelInput,
type UpdateStudentGradeQueryInput,
} from './classes.schemas.js';
import * as classService from './classes.service.js';
@@ -73,10 +66,15 @@ router.get('/:id', validate({ params: idParamSchema }), async (req, res) => {
});
/** POST /api/classes - 创建班级(称呼由入学年份 + 班号生成,如「2026级1班」) */
router.post('/', requirePermission('class:manage'), validate({ body: createClassSchema }), async (req, res) => {
const user = getAuthUser(req);
sendCreated(res, await classService.createClass(user, req.body as CreateClassInput), '班级创建成功');
});
router.post(
'/',
requirePermission('class:manage'),
validate({ body: createClassSchema }),
async (req, res) => {
const user = getAuthUser(req);
sendCreated(res, await classService.createClass(user, req.body as CreateClassInput), '班级创建成功');
},
);
/** PATCH /api/classes/:id - 编辑班级(年级 / 届别 / 教学周数),仅管理员 */
router.patch(
@@ -160,55 +158,9 @@ router.put(
},
);
/**
* GET /api/classes/:id/classisland-status - 本班 ClassHelper 班级端 / ClassIsland 联动状态
*
* 教室机器(ClassHelper 班级端)也能读:客户端「设置 → ClassIsland 联动」据此显示状态。
*/
router.get('/:id/classisland-status', validate({ params: idParamSchema }), async (req, res) => {
const user = getAuthUser(req);
const { id } = validatedParams<{ id: string }>(req);
sendOk(res, await classService.getClassIslandStatus(user, id), '获取联动状态成功');
});
/**
* GET /api/classes/:id/notification-channel - 读取"通知显示到哪个端"
*
* 教室的 ClassHelper 班级端登录后会拉这个值,据此决定自己是弹窗/上岛还是静默;
* 教师/管理员也能读(Web 端展示用)。
*/
router.get('/:id/notification-channel', validate({ params: idParamSchema }), async (req, res) => {
const user = getAuthUser(req);
const { id } = validatedParams<{ id: string }>(req);
sendOk(res, await classService.getNotificationChannel(user, id), '获取通知显示位置成功');
});
/**
* PATCH /api/classes/:id/notification-channel - 设置"通知显示到哪个端"
*
* **由教室的 ClassHelper 班级端自己选**,教师/管理员也可改。
*/
router.patch(
'/:id/notification-channel',
validate({ params: idParamSchema, body: updateNotificationChannelSchema }),
async (req, res) => {
const user = getAuthUser(req);
const { id } = validatedParams<{ id: string }>(req);
sendOk(
res,
await classService.updateNotificationChannel(
user,
id,
validatedBody<UpdateNotificationChannelInput>(req),
),
'通知显示位置已更新',
);
},
);
/**
* GET /api/classes/:id/student-grade-query - 本班是否允许班级端按学号查成绩明细
* PATCH 同路径 - 开关它(班级端自己可改,教师/管理员也可改)
* PATCH 同路径 - 教师/管理员按班级管理权限设置,班级端只读
*/
router.get('/:id/student-grade-query', validate({ params: idParamSchema }), async (req, res) => {
const user = getAuthUser(req);
@@ -224,11 +176,7 @@ router.patch(
const { id } = validatedParams<{ id: string }>(req);
sendOk(
res,
await classService.updateStudentGradeQuery(
user,
id,
validatedBody<UpdateStudentGradeQueryInput>(req),
),
await classService.updateStudentGradeQuery(user, id, validatedBody<UpdateStudentGradeQueryInput>(req)),
'成绩查询开关已更新',
);
},
@@ -1,5 +1,5 @@
import { z } from 'zod';
import { CLASSISLAND_NOTIFICATION_CHANNELS, MAX_TERM_WEEK, SUBJECT_CATALOG, isDayKey } from '@classhelper/shared';
import { MAX_TERM_WEEK, SUBJECT_CATALOG, isDayKey } from '@classhelper/shared';
import {
classIndexSchema,
enrollmentYearSchema,
@@ -99,10 +99,7 @@ export const assignSubjectTeachersSchema = z.object({
.trim()
.min(1, '请选择或填写科目')
.max(32)
.refine(
(value) => value.length > 0,
{ message: '科目名不能为空' },
),
.refine((value) => value.length > 0, { message: '科目名不能为空' }),
teacherId: z.string().min(1).nullish(),
}),
)
@@ -114,17 +111,6 @@ export const assignHeadTeacherSchema = z.object({
teacherId: z.string().min(1, '请选择班主任'),
});
/**
* 通知显示位置(both / client / classisland)。
* 由 **ClassHelper 班级端**在设置页里改,教师/管理员也可以在 Web 端改。
*/
export const updateNotificationChannelSchema = z.object({
notificationChannel: z.enum(
CLASSISLAND_NOTIFICATION_CHANNELS as unknown as [string, ...string[]],
{ message: '显示位置只能是 both / client / classisland' },
),
});
/** 班级端按学号查询成绩明细的开关 */
export const updateStudentGradeQuerySchema = z.object({
enabled: z.boolean(),
@@ -138,7 +124,6 @@ export const classStudentParamSchema = z.object({
export type CreateClassInput = z.infer<typeof createClassSchema>;
export type UpdateClassInput = z.infer<typeof updateClassSchema>;
export type UpdateClassAccountInput = z.infer<typeof updateClassAccountSchema>;
export type UpdateNotificationChannelInput = z.infer<typeof updateNotificationChannelSchema>;
export type UpdateStudentGradeQueryInput = z.infer<typeof updateStudentGradeQuerySchema>;
export type AddStudentInput = z.infer<typeof addStudentSchema>;
export type AssignSubjectTeachersInput = z.infer<typeof assignSubjectTeachersSchema>;
@@ -1,10 +1,4 @@
import type {
ClassDetailDto,
ClassDto,
ClassIslandNotificationChannel,
StudentDto,
SubjectTeacherDto,
} from '@classhelper/shared';
import type { ClassDetailDto, ClassDto, StudentDto, SubjectTeacherDto } from '@classhelper/shared';
import { SOCKET_EVENTS, formatClassName } from '@classhelper/shared';
import { env } from '../../config/env.js';
import {
@@ -13,7 +7,6 @@ import {
assertCanManageRoster,
assertClassAccess,
classScopeIdFilter,
isClassDevice,
isStaff,
resolveClassScope,
} from '../../lib/access.js';
@@ -24,23 +17,15 @@ import {
import { prisma } from '../../lib/db.js';
import { ApiError } from '../../lib/http.js';
import type { TokenPayload } from '../../lib/jwt.js';
import {
toClassDto,
toCourseDto,
toNotificationChannel,
toStudentDto,
toTeacherBrief,
} from '../../lib/mappers.js';
import { toClassDto, toCourseDto, toStudentDto, toTeacherBrief } from '../../lib/mappers.js';
import { emitToClass } from '../../realtime/bus.js';
import type {
AddStudentInput,
AssignSubjectTeachersInput,
CreateClassInput,
UpdateClassInput,
UpdateNotificationChannelInput,
UpdateStudentGradeQueryInput,
} from './classes.schemas.js';
import { attachIntegrationFlag } from '../integrations/integrations.service.js';
import { logger } from '../../lib/logger.js';
const countSelect = {
@@ -106,8 +91,7 @@ export async function listClasses(user: TokenPayload, keyword?: string): Promise
orderBy: [{ enrollmentYear: 'desc' }, { classIndex: 'asc' }, { grade: 'asc' }],
});
// 附上「是否已接入 ClassIsland」徽标:Web 端班级列表/课表页据此提示
return attachIntegrationFlag(classes.map((item) => toClassDtoWithAccount(user, item)));
return classes.map((item) => toClassDtoWithAccount(user, item));
}
/** 班级详情:学生名单 + 课程 + 班主任 + 各科任课老师 */
@@ -261,7 +245,10 @@ export async function assignSubjectTeachers(
.teacherId;
const existing = assignment.courseId
? await prisma.course.findUnique({ where: { id: assignment.courseId }, select: { id: true, classId: true } })
? await prisma.course.findUnique({
where: { id: assignment.courseId },
select: { id: true, classId: true },
})
: await prisma.course.findUnique({
where: { classId_name: { classId, name: assignment.subjectName } },
select: { id: true, classId: true },
@@ -481,98 +468,6 @@ export async function removeStudent(user: TokenPayload, classId: string, student
emitToClass(classId, SOCKET_EVENTS.classUpdated, { classId, action: 'updated' });
}
/* ---------------------------------------------------------------- ClassHelper 班级端状态 */
/**
* 本班的 ClassHelper 联动状态(教室机器上的「联动」面板展示)。
*
* 为什么单独开一个接口:设备列表(/integrations/devices)是管理面,只对教师/管理员开放;
* 而教室机器(ClassHelper 班级端)需要知道"本班接没接 ClassIsland、最后什么时候上报的",
* 才能给出准确的提示(例如没接就别选"只在 ClassIsland 上弹")。
*/
export async function getClassIslandStatus(
user: TokenPayload,
classId: string,
): Promise<{
connected: boolean;
deviceName: string | null;
deviceCount: number;
onlineCount: number;
lastSeenAt: string | null;
lastHeartbeatAt: string | null;
pluginVersion: string | null;
classIslandVersion: string | null;
}> {
await assertClassAccess(user, classId);
const devices = await prisma.integrationDevice.findMany({
where: { classId, enabled: true, mode: 'plugin' },
select: {
name: true,
lastSeenAt: true,
lastHeartbeatAt: true,
pluginVersion: true,
classIslandVersion: true,
},
orderBy: { lastHeartbeatAt: 'desc' },
});
const latest = devices[0];
const window = 60_000;
return {
connected: devices.length > 0,
deviceName: latest?.name ?? null,
deviceCount: devices.length,
onlineCount: devices.filter(
(item) => item.lastHeartbeatAt && Date.now() - item.lastHeartbeatAt.getTime() < window,
).length,
lastSeenAt: latest?.lastSeenAt ? latest.lastSeenAt.toISOString() : null,
lastHeartbeatAt: latest?.lastHeartbeatAt ? latest.lastHeartbeatAt.toISOString() : null,
pluginVersion: latest?.pluginVersion ?? null,
classIslandVersion: latest?.classIslandVersion ?? null,
};
}
/* ---------------------------------------------------------------- 班级端设置 */
/**
* 读取班级的通知显示位置(both / client / classisland)。
* 这是**教室机器**要读的值:登录后拉一次,把自己的弹窗行为对齐到同一个选择。
*/
export async function getNotificationChannel(
user: TokenPayload,
classId: string,
): Promise<{ notificationChannel: ClassIslandNotificationChannel }> {
await assertClassAccess(user, classId);
const record = await prisma.class.findUnique({
where: { id: classId },
select: { notificationChannel: true },
});
return { notificationChannel: toNotificationChannel(record?.notificationChannel) };
}
/**
* 设置班级的通知显示位置。
*
* 允许两类人改:**该班的 ClassHelper 班级端**(需求就是"由教室机器自己选")
* 与教师 / 管理员(Web 端也能改,便于老师统一要求)。
*/
export async function updateNotificationChannel(
user: TokenPayload,
classId: string,
input: UpdateNotificationChannelInput,
): Promise<{ notificationChannel: ClassIslandNotificationChannel }> {
await assertClassAccess(user, classId);
if (!isClassDevice(user) && !isStaff(user)) {
throw ApiError.forbidden('只有 ClassHelper 班级端或教师/管理员可以修改通知显示位置');
}
const channel = toNotificationChannel(input.notificationChannel);
await prisma.class.update({ where: { id: classId }, data: { notificationChannel: channel } });
emitToClass(classId, SOCKET_EVENTS.classUpdated, { classId, action: 'updated' });
logger.info(`班级通知显示位置已更新:classId=${classId} channel=${channel} by=${user.sub}`);
return { notificationChannel: channel };
}
/**
* 读取「是否允许 ClassHelper 班级端按学号查询本班学生成绩明细」。
* 班级端设置页用它渲染开关的当前状态。
@@ -595,10 +490,7 @@ export async function getStudentGradeQuery(
* 设置「是否允许 ClassHelper 班级端查看本班成绩与排名」。
*
* **只有教师 / 管理员能改**(需求:「成绩查询由服务端控制,客户端只读」)。
* 原先班级端自己也能改这个开关 —— 教室机器能给自己开成绩查询,等于把
* "学校说不给看"变成了一台机器说了算;而与它同一套模式的「通知显示位置」
* (`Class.notificationChannel`)**仍然由班级端自己改**,那个确实是现场偏好,
* 两者别再按"同一个模式"去理解。关闭后班级端查成绩一律 403,教师端不受影响。
* 关闭后班级端查成绩一律 403,教师端不受影响。
*/
export async function updateStudentGradeQuery(
user: TokenPayload,
@@ -1,7 +1,7 @@
import { Router } from 'express';
import { sendCreated, sendOk } from '../../lib/http.js';
import { idParamSchema } from '../../lib/schemas.js';
import { authenticate, getAuthUser, requirePermission } from '../../middleware/auth.js';
import { authenticate, getAuthUser, requireAnyPermission, requirePermission } from '../../middleware/auth.js';
import { validate, validatedBody, validatedParams, validatedQuery } from '../../middleware/validate.js';
import { defineModule } from '../module.types.js';
import {
@@ -30,7 +30,9 @@ router.use(authenticate());
router.post('/heartbeat', validate({ body: clientHeartbeatSchema }), async (req, res) => {
const user = getAuthUser(req);
const input = validatedBody<ClientHeartbeatInput>(req);
sendOk(res, await clientService.heartbeat(user, input, req.ip ?? ''), '心跳已上报');
const result = await clientService.heartbeat(user, input, req.ip ?? '');
// 1.3.x 旧客户端误读顶层字段,提供兼容别名让它们仍能接收修复版更新。
sendOk(res, result, '心跳已上报', 200, input.agentProtocol === 2 ? {} : result);
});
/** POST /api/clients/commands/:id/ack - 执行回执(同样不挂权限键,靠 deviceKey 归属校验) */
@@ -56,18 +58,26 @@ router.post(
async (req, res) => {
const user = getAuthUser(req);
const input = validatedBody<CreateClientCommandInput>(req);
sendCreated(res, await clientService.createCommands(user, input), '命令已下发,将在这台电脑下次心跳时送达');
sendCreated(
res,
await clientService.createCommands(user, input),
'命令已下发,将在这台电脑下次心跳时送达',
);
},
);
/** GET /api/clients/devices?classId= - Web 端设备列表(版本 / 在线 / 待执行命令) */
router.get(
'/devices',
requirePermission('client:manage'),
requireAnyPermission('client:read', 'client:manage', 'remote:control', 'client:update-push'),
validate({ query: listClientDevicesQuerySchema }),
async (req, res) => {
const query = validatedQuery<ListClientDevicesQuery>(req);
sendOk(res, await clientService.listDevices({ classId: query.classId }), '获取设备列表成功');
sendOk(
res,
await clientService.listDevices(getAuthUser(req), { classId: query.classId }),
'获取设备列表成功',
);
},
);
@@ -90,7 +100,7 @@ router.delete(
validate({ params: idParamSchema }),
async (req, res) => {
const { id } = validatedParams<{ id: string }>(req);
sendOk(res, await clientService.deleteDevice(id), '设备已移除');
sendOk(res, await clientService.deleteDevice(getAuthUser(req), id), '设备已移除');
},
);
@@ -14,10 +14,12 @@ const deviceKeySchema = z.string().trim().min(8, '设备标识不合法').max(80
/** `POST /api/clients/heartbeat`:客户端每 30 秒一次的上报 */
export const clientHeartbeatSchema = z.object({
agentProtocol: z.number().int().min(1).max(2).optional(),
deviceKey: deviceKeySchema,
name: z.string().trim().max(60).optional(),
clientVersion: z.string().trim().max(40).optional(),
platform: z.string().trim().max(40).optional(),
autoUpdate: z.boolean().optional(),
pendingVersion: z.string().trim().max(40).nullable().optional(),
stateNote: z.string().trim().max(120).optional(),
});
@@ -53,6 +55,11 @@ export const pushClientUpdateSchema = z.object({
all: z.boolean().optional(),
version: z.string().trim().max(40).nullable().optional(),
clear: z.boolean().optional(),
mode: z.enum(['idle', 'immediate', 'after-school']).default('idle'),
afterSchoolTime: z
.string()
.regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/, '放学时间应为 HH:mm')
.optional(),
});
export type ClientHeartbeatInput = z.infer<typeof clientHeartbeatSchema>;
@@ -2,6 +2,8 @@ import {
CLIENT_COMMAND_EXPIRE_MS,
CLIENT_COMMAND_LABELS,
CLIENT_ONLINE_WINDOW_MS,
weekParityOf,
type ClientUpdateMode,
type ClientCommandAckRequest,
type ClientCommandDto,
type ClientCommandKind,
@@ -10,18 +12,23 @@ import {
type ClientPushResult,
type ClientTargetResult,
} from '@classhelper/shared';
import { loadTermContext, resolveCurrentWeek } from '../../lib/term.js';
import { resolveClassScope, classScopeWhere } from '../../lib/access.js';
import { prisma } from '../../lib/db.js';
import { ApiError } from '../../lib/http.js';
import type { TokenPayload } from '../../lib/jwt.js';
import { logger } from '../../lib/logger.js';
import * as clientReleases from '../update/client-releases.service.js';
import type { ClientHeartbeatInput, CreateClientCommandInput, PushClientUpdateInput } from './clients.schemas.js';
import type {
ClientHeartbeatInput,
CreateClientCommandInput,
PushClientUpdateInput,
} from './clients.schemas.js';
/**
* ClassHelper 桌面客户端设备的心跳 / 远控命令 / 更新下发。
*
* 范式(AGENTS.md §5 第 67 条):**DB 记状态 + 客户端定时拉取** ——
* 与 `IntegrationDevice.requestScheduleReport` 同一套路,不新增长连接握手。
* 因此本文件里没有任何"推送"动作:所有下发都只是改 `ClientDevice` / `ClientCommand` 的字段,
* 由客户端下一次心跳(30 秒内)带走。
*/
@@ -35,6 +42,8 @@ type DeviceRow = {
platform: string;
autoUpdate: boolean;
updateTargetVersion: string;
updateMode: ClientUpdateMode;
updateNotBefore: Date | null;
pendingVersion: string;
lastHeartbeatAt: Date | null;
lastIp: string;
@@ -131,6 +140,7 @@ export async function heartbeat(
name: input.name?.trim() || '未命名设备',
clientVersion: input.clientVersion?.trim() ?? '',
platform: input.platform?.trim() ?? '',
autoUpdate: input.autoUpdate !== false,
pendingVersion: input.pendingVersion?.trim() ?? '',
stateNote: input.stateNote?.trim() ?? '',
lastHeartbeatAt: now,
@@ -153,7 +163,16 @@ export async function heartbeat(
deviceId: device.id,
serverTime: now.toISOString(),
updateTargetVersion: targetVersion || null,
update,
updateMode: device.updateMode,
updateNotBefore: device.updateNotBefore?.toISOString() ?? null,
// 旧客户端没有时机判断:到放学时间前不提供包,避免它提前安装。
update:
input.agentProtocol !== 2 &&
device.updateMode === 'after-school' &&
device.updateNotBefore &&
now < device.updateNotBefore
? null
: update,
command: command ? toCommandDto(command) : null,
};
}
@@ -187,9 +206,13 @@ export async function ackCommand(
}
/** GET /api/clients/devices - Web 端「客户端设备」列表(含待执行命令) */
export async function listDevices(options: { classId?: string } = {}): Promise<ClientDeviceDto[]> {
export async function listDevices(
user: TokenPayload,
options: { classId?: string } = {},
): Promise<ClientDeviceDto[]> {
const scope = await resolveClassScope(user, options.classId);
const rows = (await prisma.clientDevice.findMany({
where: options.classId ? { classId: options.classId } : {},
where: classScopeWhere(scope),
include: { class: { select: { id: true, name: true } } },
orderBy: [{ lastHeartbeatAt: 'desc' }, { createdAt: 'desc' }],
})) as unknown as DeviceRow[];
@@ -235,6 +258,8 @@ export async function listDevices(options: { classId?: string } = {}): Promise<C
platform: row.platform,
autoUpdate: row.autoUpdate,
updateTargetVersion: row.updateTargetVersion,
updateMode: row.updateMode,
updateNotBefore: row.updateNotBefore?.toISOString() ?? null,
pendingVersion: row.pendingVersion,
lastHeartbeatAt: heartbeat ? heartbeat.toISOString() : null,
lastIp: row.lastIp,
@@ -249,10 +274,11 @@ export async function listDevices(options: { classId?: string } = {}): Promise<C
}
/** 命令去重后的目标设备(保持请求顺序,便于结果一一对应) */
async function findTargetDevices(deviceIds: string[]): Promise<Map<string, DeviceRow>> {
async function findTargetDevices(user: TokenPayload, deviceIds: string[]): Promise<Map<string, DeviceRow>> {
const wanted = [...new Set(deviceIds)];
const scope = classScopeWhere(await resolveClassScope(user));
const rows = (await prisma.clientDevice.findMany({
where: { id: { in: wanted } },
where: { AND: [scope, { id: { in: wanted } }] },
select: { id: true, name: true, deviceKey: true },
})) as unknown as DeviceRow[];
return new Map(rows.map((row) => [row.id, row]));
@@ -268,7 +294,7 @@ export async function createCommands(
user: TokenPayload,
input: CreateClientCommandInput,
): Promise<ClientPushResult> {
const targets = await findTargetDevices(input.deviceIds);
const targets = await findTargetDevices(user, input.deviceIds);
const expiresAt = new Date(Date.now() + CLIENT_COMMAND_EXPIRE_MS);
const note = input.note?.trim() ?? '';
const results: ClientTargetResult[] = [];
@@ -304,12 +330,13 @@ export async function createCommands(
}
/** 更新推送的目标集合:优先设备,其次班级,最后"全部" */
async function resolveUpdateTargets(input: PushClientUpdateInput): Promise<DeviceRow[]> {
async function resolveUpdateTargets(user: TokenPayload, input: PushClientUpdateInput): Promise<DeviceRow[]> {
const scope = classScopeWhere(await resolveClassScope(user));
const deviceIds = [...new Set(input.deviceIds ?? [])];
if (deviceIds.length > 0) {
const rows = (await prisma.clientDevice.findMany({
where: { id: { in: deviceIds } },
select: { id: true, name: true },
where: { AND: [scope, { id: { in: deviceIds } }] },
select: { id: true, name: true, classId: true },
})) as unknown as DeviceRow[];
return rows;
}
@@ -317,13 +344,16 @@ async function resolveUpdateTargets(input: PushClientUpdateInput): Promise<Devic
const classIds = [...new Set(input.classIds ?? [])];
if (classIds.length > 0) {
return (await prisma.clientDevice.findMany({
where: { classId: { in: classIds } },
select: { id: true, name: true },
where: { AND: [scope, { classId: { in: classIds } }] },
select: { id: true, name: true, classId: true },
})) as unknown as DeviceRow[];
}
if (input.all) {
return (await prisma.clientDevice.findMany({ select: { id: true, name: true } })) as unknown as DeviceRow[];
return (await prisma.clientDevice.findMany({
where: scope,
select: { id: true, name: true, classId: true },
})) as unknown as DeviceRow[];
}
throw ApiError.badRequest('请选择要推送的设备、班级,或选择"全部设备"');
@@ -333,8 +363,7 @@ async function resolveUpdateTargets(input: PushClientUpdateInput): Promise<Devic
* POST /api/clients/updates - 统一下发客户端更新
*
* `version` 省略时用服务端缓存里最新的那个版本;`clear: true` 取消下发。
* 只改 `updateTargetVersion`,真正的下载与安装由客户端按自己的空闲判据决定
* (上课时段 / 窗口可见都不装)。
* 保存目标版本和安装策略,下载、安装由客户端在心跳后执行。
*/
export async function pushUpdate(
user: TokenPayload,
@@ -352,14 +381,21 @@ export async function pushUpdate(
if (!info) throw ApiError.badRequest(`服务端缺少 v${target} 的安装包文件,请重新下载或登记`);
}
const devices = await resolveUpdateTargets(input);
const devices = await resolveUpdateTargets(user, input);
if (devices.length === 0) throw ApiError.badRequest('没有匹配到任何客户端设备');
const results: ClientTargetResult[] = [];
for (const device of devices) {
await prisma.clientDevice.update({
where: { id: device.id },
data: { updateTargetVersion: target },
data: {
updateTargetVersion: target,
updateMode: clear ? 'idle' : input.mode,
updateNotBefore:
!clear && input.mode === 'after-school'
? await afterSchoolAt(device.classId, input.afterSchoolTime)
: null,
},
});
results.push({ deviceId: device.id, deviceName: device.name, ok: true });
}
@@ -373,10 +409,36 @@ export async function pushUpdate(
return summary;
}
/** 按当前教学周、单双周与星期计算今天放学时间;未绑定班级使用明确的兜底时间。 */
async function afterSchoolAt(classId: string | null, fallback = '17:00'): Promise<Date> {
const now = new Date();
let end = fallback;
if (classId) {
const week = resolveCurrentWeek(now, await loadTermContext(classId));
const last = await prisma.schedule.findFirst({
where: {
classId,
dayOfWeek: now.getDay() || 7,
weekStart: { lte: week },
weekEnd: { gte: week },
weekParity: { in: ['ALL', weekParityOf(week)] },
},
orderBy: { endTime: 'desc' },
select: { endTime: true },
});
if (last && last.endTime > end) end = last.endTime;
}
const [hours, minutes] = end.split(':').map(Number);
const at = new Date(now);
at.setHours(hours!, minutes!, 0, 0);
return at;
}
/** DELETE /api/clients/devices/:id - 移除一台设备记录(换机 / 旧机器清理) */
export async function deleteDevice(deviceId: string): Promise<{ id: string }> {
const device = await prisma.clientDevice.findUnique({
where: { id: deviceId },
export async function deleteDevice(user: TokenPayload, deviceId: string): Promise<{ id: string }> {
const scope = classScopeWhere(await resolveClassScope(user));
const device = await prisma.clientDevice.findFirst({
where: { AND: [scope, { id: deviceId }] },
select: { id: true, name: true, deviceKey: true },
});
if (!device) throw ApiError.notFound('设备不存在');
@@ -1,7 +1,7 @@
import { Router } from 'express';
import { sendOk } from '../../lib/http.js';
import { resolveCurrentWeek } from '../../lib/term.js';
import { authenticate, getAuthUser } from '../../middleware/auth.js';
import { resolveCurrentWeek, loadTermContext } from '../../lib/term.js';
import { authenticate, getAuthUser, requireStaffPermission } from '../../middleware/auth.js';
import { defineModule } from '../module.types.js';
import * as dashboardService from './dashboard.service.js';
@@ -9,7 +9,7 @@ const router = Router();
router.use(authenticate());
/** GET /api/dashboard/summary - 首页汇总(按角色权限收敛数据范围) */
router.get('/summary', async (req, res) => {
router.get('/summary', requireStaffPermission('dashboard:read'), async (req, res) => {
const user = getAuthUser(req);
sendOk(res, await dashboardService.getDashboardSummary(user), '获取仪表盘数据成功');
});
@@ -21,11 +21,13 @@ router.get('/summary', async (req, res) => {
* 这样周次选择器不会再出现"实际 20 周却给到 30 周"的情况;不带 classId 时退回全局默认值。
* 带 classId 时会先校验班级访问权限(见 resolveTermWeeks)。
*/
router.get('/term', async (req, res) => {
router.get('/term', requireStaffPermission('term:read'), async (req, res) => {
const user = getAuthUser(req);
const classId = typeof req.query.classId === 'string' && req.query.classId ? req.query.classId : undefined;
const maxWeek = await dashboardService.resolveTermWeeks(user, classId);
sendOk(res, { currentWeek: resolveCurrentWeek(), maxWeek }, '获取学期信息成功');
const targetClassId = user.role === 'CLASS_DEVICE' ? (user.classId ?? user.sub) : classId;
const context = await loadTermContext(targetClassId);
sendOk(res, { currentWeek: resolveCurrentWeek(new Date(), context), maxWeek }, '获取学期信息成功');
});
export const dashboardModule = defineModule({
@@ -1,7 +1,12 @@
import { Router } from 'express';
import { sendCreated, sendOk } from '../../lib/http.js';
import { idParamSchema } from '../../lib/schemas.js';
import { authenticate, getAuthUser, requirePermission } from '../../middleware/auth.js';
import {
authenticate,
getAuthUser,
requirePermission,
requireStaffPermission,
} from '../../middleware/auth.js';
import { validate, validatedParams, validatedQuery } from '../../middleware/validate.js';
import { defineModule } from '../module.types.js';
import {
@@ -43,16 +48,13 @@ router.get('/my', async (req, res) => {
*/
router.get(
'/student/:studentNo',
requireStaffPermission('student:grade-query'),
validate({ params: studentGradeParamSchema, query: studentGradeQuerySchema }),
async (req, res) => {
const user = getAuthUser(req);
const { studentNo } = validatedParams<{ studentNo: string }>(req);
const { classId } = validatedQuery<{ classId?: string }>(req);
sendOk(
res,
await gradeService.getStudentGradeDetail(user, studentNo, classId),
'获取学生成绩明细成功',
);
sendOk(res, await gradeService.getStudentGradeDetail(user, studentNo, classId), '获取学生成绩明细成功');
},
);
@@ -74,15 +76,11 @@ router.get(
* **刻意不挂权限键**:ClassHelper 班级端要用它列出可选考试(班级端的有效权限是空集,
* 挂 `grade:read` 会把教室机器挡在门外)。边界在 service 里:`assertClassAccess` + 班级开关。
*/
router.get(
'/exams',
validate({ query: examListQuerySchema }),
async (req, res) => {
const user = getAuthUser(req);
const { classId } = validatedQuery<{ classId: string }>(req);
sendOk(res, await gradeService.listExams(user, classId), '获取考试列表成功');
},
);
router.get('/exams', validate({ query: examListQuerySchema }), async (req, res) => {
const user = getAuthUser(req);
const { classId } = validatedQuery<{ classId: string }>(req);
sendOk(res, await gradeService.listExams(user, classId), '获取考试列表成功');
});
/** PUT /api/grades/exams - 设置"这次考试是否把所有科目相加做总分排名"(教师/管理员) */
router.put(
@@ -106,15 +104,11 @@ router.put(
* 同样不挂权限键(班级端要看),边界在 service 里 —— 与按学号查明细共用
* `canQueryStudentGrades`:班级端受按班开关控制,教师端不受影响。
*/
router.get(
'/ranking',
validate({ query: examRankingQuerySchema }),
async (req, res) => {
const user = getAuthUser(req);
const { classId, examName } = validatedQuery<{ classId: string; examName: string }>(req);
sendOk(res, await gradeService.getExamRanking(user, classId, examName), '获取考试排名成功');
},
);
router.get('/ranking', validate({ query: examRankingQuerySchema }), async (req, res) => {
const user = getAuthUser(req);
const { classId, examName } = validatedQuery<{ classId: string; examName: string }>(req);
sendOk(res, await gradeService.getExamRanking(user, classId, examName), '获取考试排名成功');
});
/** GET /api/grades?classId=&courseId=&studentId=&examName= - 成绩列表(教师) */
router.get(
@@ -134,14 +128,19 @@ router.get(
);
/** POST /api/grades - 录入单条成绩(仅自己任教科目) */
router.post('/', requirePermission('grade:write'), validate({ body: createGradeSchema }), async (req, res) => {
const user = getAuthUser(req);
sendCreated(
res,
await gradeService.createGrade(user, req.body as CreateGradeInput),
'成绩录入成功,已实时推送',
);
});
router.post(
'/',
requirePermission('grade:write'),
validate({ body: createGradeSchema }),
async (req, res) => {
const user = getAuthUser(req);
sendCreated(
res,
await gradeService.createGrade(user, req.body as CreateGradeInput),
'成绩录入成功,已实时推送',
);
},
);
/**
* PATCH /api/grades/levels - 批量修改等级
@@ -287,13 +287,16 @@ export async function updateGradeLevels(
}
await prisma.$transaction(
input.items.map((item) =>
prisma.grade.update({ where: { id: item.id }, data: { level: item.level } }),
),
input.items.map((item) => prisma.grade.update({ where: { id: item.id }, data: { level: item.level } })),
);
const sample = byId.get(input.items[0]!.id);
if (sample) emitToClass(sample.classId, SOCKET_EVENTS.gradeUpdated, { bulk: true, count: input.items.length });
const counts = new Map<string, number>();
for (const item of input.items) {
const classId = byId.get(item.id)!.classId;
counts.set(classId, (counts.get(classId) ?? 0) + 1);
}
for (const [classId, count] of counts)
emitToClass(classId, SOCKET_EVENTS.gradeUpdated, { bulk: true, count });
return { updated: input.items.length };
}
@@ -301,6 +304,7 @@ export async function updateGradeLevels(
const classId = input.classId!;
await assertCanManageSubjectContent(user, classId, input.courseId ?? null, '调整成绩等级');
const levelType = input.levelType!;
if (levelType === 'custom') throw ApiError.badRequest('自定义等级不能由分数推算,请逐条填写等级');
const records = await prisma.grade.findMany({
where: {
classId,
@@ -316,10 +320,7 @@ export async function updateGradeLevels(
where: { id: item.id },
data: {
levelType,
level:
levelType === 'percent'
? gradeLevel(gradePercent(item.score, item.totalScore))
: item.level,
level: gradeLevel(gradePercent(item.score, item.totalScore)),
},
}),
),
@@ -97,7 +97,7 @@ function normalizeTime(value: unknown): string | null {
/**
* `WeekCountDiv` / `WeekCountDivTotal` → 我们课表的 weekParity。
* 口径集中在 `@classhelper/shared` 的 `weekParityFromDiv`(插件上报走同一份实现),
* 口径集中在 `@classhelper/shared` 的 `weekParityFromDiv`,
* 这里只是本模块内的别名,保证"手动导入 JSON"与"插件实时上报"落到库里完全一致。
*/
const resolveParity = weekParityFromDiv;
@@ -294,13 +294,14 @@ export async function importClassPlan(
const classRecord = await prisma.class.findUnique({
where: { id: input.classId },
select: { id: true, teacherId: true },
select: { id: true, teacherId: true, termWeeks: true },
});
if (!classRecord) throw ApiError.notFound('班级不存在');
// 时间配置(导入的时间表)里如果只有部分节次,weekEnd 用默认 20 周
// 导入范围与本班配置的学期长度一致。
const weekStart = input.termStartWeek ?? 1;
const weekEnd = 20;
const weekEnd = classRecord.termWeeks;
if (weekStart > weekEnd) throw ApiError.badRequest('导入起始周不能超出本班学期周数');
const result = await prisma.$transaction(async (tx) => {
// 1) 补建缺失课程(用班主任作为课程任课老师)
@@ -48,23 +48,33 @@ function resolveImportKind(value: unknown): (typeof IMPORT_KINDS)[number] {
* GET /api/imports/template?kind=grades|students|teachers&format=csv|xlsx - 下载导入模板
* 成绩模板:管理员或班主任(空白模板,不含任何业务数据);学生/教师名单模板:仅管理员
*/
router.get('/template', requireAnyPermission('import:students', 'grade:import', 'import:teachers', 'import:schedule', 'import:class-teachers'), (req, res) => {
const kind = resolveImportKind(req.query.kind);
assertImportKindAllowed(kind, getAuthUser(req).role);
const format = req.query.format === 'xlsx' ? 'xlsx' : 'csv';
if (format === 'xlsx') {
const base64 = buildTemplateXlsx(kind);
res.setHeader('content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('content-disposition', `attachment; filename="template-${kind}.xlsx"`);
res.send(Buffer.from(base64, 'base64'));
return;
}
sendOk(
res,
{ kind, format, fileName: `template-${kind}.csv`, content: buildTemplateCsv(kind) },
'模板生成成功',
);
});
router.get(
'/template',
requireAnyPermission(
'import:students',
'grade:import',
'import:teachers',
'import:schedule',
'import:class-teachers',
),
(req, res) => {
const kind = resolveImportKind(req.query.kind);
assertImportKindAllowed(kind, getAuthUser(req).role);
const format = req.query.format === 'xlsx' ? 'xlsx' : 'csv';
if (format === 'xlsx') {
const base64 = buildTemplateXlsx(kind);
res.setHeader('content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('content-disposition', `attachment; filename="template-${kind}.xlsx"`);
res.send(Buffer.from(base64, 'base64'));
return;
}
sendOk(
res,
{ kind, format, fileName: `template-${kind}.csv`, content: buildTemplateCsv(kind) },
'模板生成成功',
);
},
);
/**
* POST /api/imports/table/preview - 上传表格并预览(解析 + 必填列校验 + 建议字段映射)
@@ -72,7 +82,13 @@ router.get('/template', requireAnyPermission('import:students', 'grade:import',
*/
router.post(
'/table/preview',
requireAnyPermission('import:students', 'grade:import', 'import:teachers', 'import:schedule', 'import:class-teachers'),
requireAnyPermission(
'import:students',
'grade:import',
'import:teachers',
'import:schedule',
'import:class-teachers',
),
validate({ body: tableFileSchema }),
(req, res) => {
const input = validatedBody<TableFileInput>(req);
@@ -89,13 +105,19 @@ router.post(
*/
router.post(
'/table/commit',
requireAnyPermission('import:students', 'grade:import', 'import:teachers', 'import:schedule', 'import:class-teachers'),
requireAnyPermission(
'import:students',
'grade:import',
'import:teachers',
'import:schedule',
'import:class-teachers',
),
validate({ body: tableCommitSchema }),
async (req, res) => {
const input = validatedBody<TableCommitInput>(req);
assertImportKindAllowed(input.kind, getAuthUser(req).role);
// 教师名单与班级无关;成绩/学生名单必须带班级,否则拒绝(避免写到"全局")
if (input.kind !== 'teachers' && !input.classId) {
if (input.kind !== 'teachers' && input.kind !== 'classTeachers' && !input.classId) {
throw ApiError.badRequest('请先选择要导入的班级');
}
const result = await commitTable(getAuthUser(req), input);
@@ -334,7 +334,16 @@ export async function commitGrades(user: TokenPayload, input: TableCommitInput):
});
// 学号在库里已归一化为大写,比对前统一一次
const byStudentNo = new Map(students.map((item) => [normalizeStudentNo(item.studentNo), item]));
const byName = new Map(students.map((item) => [item.name.toLowerCase(), item]));
const nameCounts = new Map<string, number>();
for (const item of students) {
const key = item.name.trim().toLowerCase();
nameCounts.set(key, (nameCounts.get(key) ?? 0) + 1);
}
const byName = new Map(
students
.filter((item) => nameCounts.get(item.name.trim().toLowerCase()) === 1)
.map((item) => [item.name.trim().toLowerCase(), item]),
);
const courses = await prisma.course.findMany({
where: { classId },
select: { id: true, name: true, teacherId: true },
@@ -370,9 +379,19 @@ export async function commitGrades(user: TokenPayload, input: TableCommitInput):
errors.push({ row: rowNumber, message: '缺少学生标识(学号与姓名至少填写一个)' });
continue;
}
if (
!byStudentNo.has(normalizeStudentNo(studentNo)) &&
(nameCounts.get(name.trim().toLowerCase()) ?? 0) > 1
) {
errors.push({
row: rowNumber,
message: `该班有 ${nameCounts.get(name.trim().toLowerCase())} 个同名同学「${name}」,请填写正确学号`,
});
continue;
}
const student =
(studentNo ? byStudentNo.get(normalizeStudentNo(studentNo)) : undefined) ??
(name ? byName.get(name.toLowerCase()) : undefined);
(name ? byName.get(name.trim().toLowerCase()) : undefined);
if (!student) {
errors.push({ row: rowNumber, message: `找不到该班学生:${studentNo || name}` });
continue;
@@ -492,7 +511,8 @@ export async function commitStudents(user: TokenPayload, input: TableCommitInput
const classByName = new Map<string, { id: string; name: string }>();
for (const item of allClasses) {
const key = item.name.toLowerCase();
if (classByName.has(key)) classByName.delete(key); // 重名 → 标记为不可用
if (classByName.has(key))
classByName.delete(key); // 重名 → 标记为不可用
else classByName.set(key, item);
}
@@ -555,10 +575,7 @@ export async function commitStudents(user: TokenPayload, input: TableCommitInput
}
if (existing.classId !== classId) {
// 换班要留痕,与手动调班同一种历史
const [from, to] = await Promise.all([
classNameOf(existing.classId),
classNameOf(classId),
]);
const [from, to] = await Promise.all([classNameOf(existing.classId), classNameOf(classId)]);
await prisma.studentClassTransfer.create({
data: {
studentId: existing.id,
@@ -681,7 +698,9 @@ export async function commitTeachers(user: TokenPayload, input: TableCommitInput
errors,
warnings,
};
logger.info(`教师名单导入:模式=${input.mode} 新增=${inserted} 更新=${updated} 跳过=${skipped} 失败=${errors.length}`);
logger.info(
`教师名单导入:模式=${input.mode} 新增=${inserted} 更新=${updated} 跳过=${skipped} 失败=${errors.length}`,
);
return result;
}
@@ -698,7 +717,10 @@ export async function commitTeachers(user: TokenPayload, input: TableCommitInput
* 后面几行指向的还是同一个账号(`useTeacherNo` 打开时按工号匹配,关闭时按姓名唯一匹配),
* 因此"班主任同时是科任老师"只会有一条教师记录,权限在 `resolveClassRole` 里合并。
*/
export async function commitClassTeachers(user: TokenPayload, input: TableCommitInput): Promise<ImportResult> {
export async function commitClassTeachers(
user: TokenPayload,
input: TableCommitInput,
): Promise<ImportResult> {
await assertImportAllowed(user, undefined, 'classTeachers');
const buffer = decodeBase64(input.contentBase64);
const parsed = parseTable(buffer, input.fileName);
@@ -891,12 +913,13 @@ async function classNameOf(classId: string | null): Promise<string> {
return record?.name ?? '';
}
/** 角色列解析:只认「管理员」类词;其余(含空)返回 null 交给调用方取默认值 */
/** 只接受明确的角色值;空值或未识别值保留原角色,避免意外降级。 */
function parseTeacherRole(cell: string): 'TEACHER' | 'ADMIN' | null {
const value = cell.trim().toUpperCase();
if (!value) return null;
if (value === 'ADMIN' || cell.includes('管理员') || value === '管理员') return 'ADMIN';
return 'TEACHER';
if (value === 'TEACHER' || value === '教师' || value === '老师') return 'TEACHER';
return null;
}
/** 班级任课老师的角色列:班主任 / 科任 */
@@ -1,104 +0,0 @@
import crypto from 'node:crypto';
import type { Request, RequestHandler } from 'express';
import { prisma } from '../../lib/db.js';
import { ApiError } from '../../lib/http.js';
/**
* 联动设备的令牌工具。
*
* 为什么不用 JWT:
* - 令牌是「设备级长期凭证」,插件装在教室机器上,长时间无人值守,
* 需要一个"管理员在 Web 端点了重置才失效"的凭证,而不是有固定过期时间的会话;
* - 明文只在创建/重置接口返回一次,服务端只存 sha256 —— 库被读走也无法反推出可用令牌。
*/
export function generateDeviceToken(): string {
// 32 字节随机 -> 64 位十六进制,前缀便于在日志/设置页里一眼认出
return `chci_${crypto.randomBytes(32).toString('hex')}`;
}
export function hashDeviceToken(token: string): string {
return crypto.createHash('sha256').update(token, 'utf8').digest('hex');
}
/** 令牌前缀提示(chci_ + 前 8 位),用于设备列表里人眼识别 */
export function tokenHintOf(token: string): string {
return `${token.slice(0, 13)}…`;
}
/** 从 \`X-ClassIsland-Token\` 或 \`Authorization: Bearer\` 中取出设备令牌 */
export function extractDeviceToken(headerValue: string | undefined, custom: unknown): string | null {
if (typeof custom === 'string' && custom.trim()) return custom.trim();
if (!headerValue) return null;
const [scheme, value] = headerValue.split(' ');
if (!value || scheme.toLowerCase() !== 'bearer') return null;
return value.trim();
}
/** 设备上下文(与 Express.Request.device 的结构一致) */
export interface DeviceContext {
deviceId: string;
classId: string;
name: string;
enabled: boolean;
syncScheduleToServer: boolean;
mirrorScheduleToClassIsland: boolean;
/** 是否有一次待办的「下发课表到教室」(Web 端点按钮时置位,拉取成功即清除) */
mirrorRequested: boolean;
}
/** 插件侧路由统一挂这个中间件:解析设备令牌并回查设备记录 */
export function authenticateDevice(): RequestHandler {
return (req, _res, next) => {
void (async () => {
try {
const token = extractDeviceToken(req.headers.authorization, req.headers['x-classisland-token']);
if (!token) throw ApiError.unauthorized('缺少设备令牌(X-ClassIsland-Token)');
const record = await prisma.integrationDevice.findFirst({
where: { tokenHash: hashDeviceToken(token) },
select: {
id: true,
classId: true,
name: true,
enabled: true,
syncScheduleToServer: true,
mirrorScheduleToClassIsland: true,
requestMirrorSchedule: true,
},
});
if (!record) throw ApiError.unauthorized('设备令牌无效,请在「ClassIsland 联动」里重新生成');
const context: DeviceContext = {
deviceId: record.id,
classId: record.classId,
name: record.name,
enabled: record.enabled,
syncScheduleToServer: record.syncScheduleToServer,
mirrorScheduleToClassIsland: record.mirrorScheduleToClassIsland,
mirrorRequested: record.requestMirrorSchedule === true,
};
req.device = context;
next();
} catch (error) {
next(error);
}
})();
};
}
/** 取出当前设备上下文,未鉴权时抛 401 */
export function getDevice(req: Request): DeviceContext {
const device = req.device;
if (!device) throw ApiError.unauthorized('缺少设备上下文');
return device;
}
/** 设备被管理员停用:插件上报与下发一律拒绝(403 而不是 401,便于插件提示"请管理员开启") */
export function assertDeviceEnabled(device: DeviceContext): void {
if (!device.enabled) {
throw ApiError.forbidden('该设备已在「ClassIsland 联动」中被停用,请联系管理员开启');
}
}
/** 生成的令牌字符串的字面量前缀,供测试与文档引用 */
export const DEVICE_TOKEN_PREFIX = 'chci_';
@@ -1,255 +0,0 @@
import { Router } from 'express';
import { ApiError, sendCreated, sendOk } from '../../lib/http.js';
import { authenticate, getAuthUser, requirePermission } from '../../middleware/auth.js';
import { validate, validatedBody, validatedParams, validatedQuery } from '../../middleware/validate.js';
import { defineModule } from '../module.types.js';
import * as gradeService from '../grades/grades.service.js';
import { studentGradeQuerySchema } from '../grades/grades.schemas.js';
import { authenticateDevice, assertDeviceEnabled, getDevice } from './device-auth.js';
import {
ackNotificationSchema,
classIslandReportSchema,
createDeviceSchema,
deviceIdParamSchema,
listDevicesQuerySchema,
sendNotificationSchema,
updateDeviceSchema,
type ClassIslandReportInput,
type CreateDeviceInput,
type SendNotificationInput,
type UpdateDeviceInput,
} from './integrations.schemas.js';
import * as integrationService from './integrations.service.js';
const router = Router();
/* ================================================================== 插件侧
* 用**设备令牌**鉴权(X-ClassIsland-Token / Authorization: Bearer),不是 JWT 会话。
* 路由放在文件最前面,避免被下面的 authenticate() 拦住;每个路由单独挂 authenticateDevice()。
*/
/** POST /api/integrations/classisland/report - 插件上报当前状态 +(可选)课表 */
router.post(
'/classisland/report',
authenticateDevice(),
validate({ body: classIslandReportSchema }),
async (req, res) => {
const device = getDevice(req);
assertDeviceEnabled(device);
const result = await integrationService.applyReport(device, validatedBody<ClassIslandReportInput>(req));
sendOk(res, result, '上报成功');
},
);
/** GET /api/integrations/classisland/pending - 插件拉取尚未确认的下发提醒(离线补齐) */
router.get('/classisland/pending', authenticateDevice(), async (req, res) => {
const device = getDevice(req);
assertDeviceEnabled(device);
sendOk(res, await integrationService.listPendingNotifications(device), '获取待提醒成功');
});
/** POST /api/integrations/classisland/ack - 插件确认提醒已弹出(之后不再补发) */
router.post(
'/classisland/ack',
authenticateDevice(),
validate({ body: ackNotificationSchema }),
async (req, res) => {
const device = getDevice(req);
assertDeviceEnabled(device);
await integrationService.ackNotification(device, validatedBody<{ id: string }>(req).id);
sendOk(res, { acked: true }, '已确认');
},
);
/** GET /api/integrations/classisland/class-plan - 插件拉取本班课表(镜像回 ClassIsland) */
router.get('/classisland/class-plan', authenticateDevice(), async (req, res) => {
const device = getDevice(req);
assertDeviceEnabled(device);
if (!device.mirrorScheduleToClassIsland) {
sendOk(res, null, '该设备未开启「把班级课表镜像到 ClassIsland」');
return;
}
sendOk(res, await integrationService.pullClassPlanForDevice(device), '获取课表成功');
});
/**
* GET /api/integrations/classisland/student-grades?studentNo= - 班级端按学号查成绩明细
*
* 给"插件形态的 ClassHelper 班级端"留的通道:走设备令牌而不是 JWT。
* 受**同一个班级开关**约束(`Class.studentGradeQueryEnabled`),与桌面客户端走的是同一条 service。
*/
router.get(
'/classisland/student-grades',
authenticateDevice(),
validate({ query: studentGradeQuerySchema }),
async (req, res) => {
const device = getDevice(req);
assertDeviceEnabled(device);
const { studentNo } = validatedQuery<{ studentNo?: string }>(req);
if (!studentNo) throw ApiError.badRequest('请提供学号(studentNo)');
// 设备令牌没有"账号",构造一个等价于 ClassHelper 班级端的会话载荷
const session = {
sub: device.classId,
username: '',
name: '',
role: 'CLASS_DEVICE' as const,
classId: device.classId,
classSession: true,
};
sendOk(
res,
await gradeService.getStudentGradeDetail(session, studentNo, device.classId),
'获取学生成绩明细成功',
);
},
);
/* ================================================================== Web 管理端
* 用 JWT 鉴权;权限与"课表管理 / 发通知"保持一致,由 service 内二次校验班级维度角色。
*/
router.use(authenticate());
/**
* GET /api/integrations/devices?classId= - 联动设备列表(含最后一次上报的状态快照)
*
* 仅管理员/教师可见:设备列表属于管理面,学生也不需要知道教室机器接了哪台设备;
* 教师只能看到自己可访问班级的设备(service 内按 classScope 过滤)。
*/
router.get(
'/devices',
requirePermission('device:manage'),
validate({ query: listDevicesQuerySchema }),
async (req, res) => {
const { classId } = validatedQuery<{ classId?: string }>(req);
sendOk(res, await integrationService.listDevices(getAuthUser(req), classId), '获取设备列表成功');
},
);
/**
* GET /api/integrations/classisland/status - **ClassHelper 班级端在线状态**(教师网页)
*
* 管理员看全部班级;普通教师看自己担任班主任的班级 ∪ 任课的班级。
* 每条含:班级、设备名/设备号、在线/离线、最后在线时间、最后心跳时间。
*/
router.get('/classisland/status', requirePermission('device:manage'), async (req, res) => {
sendOk(res, await integrationService.listClassHelperStatus(getAuthUser(req)), '获取在线状态成功');
});
/** POST /api/integrations/devices - 新建设备并一次性返回明文令牌(管理员或本班班主任) */
router.post(
'/devices',
requirePermission('device:manage'),
validate({ body: createDeviceSchema }),
async (req, res) => {
const result = await integrationService.createDevice(
getAuthUser(req),
validatedBody<CreateDeviceInput>(req),
);
sendCreated(res, result, '设备已创建,请把令牌填入插件设置(只显示这一次)');
},
);
/** PATCH /api/integrations/devices/:id - 改名 / 启停 / 调整同步开关 */
router.patch(
'/devices/:id',
requirePermission('device:manage'),
validate({ params: deviceIdParamSchema, body: updateDeviceSchema }),
async (req, res) => {
const { id } = validatedParams<{ id: string }>(req);
sendOk(
res,
await integrationService.updateDevice(getAuthUser(req), id, validatedBody<UpdateDeviceInput>(req)),
'设备已更新',
);
},
);
/**
* POST /api/integrations/devices/:id/request-schedule - 「从教室机器获取一次课表」
*
* **这是现在取教室课表的唯一入口**(原来的自动回传已默认关闭,见
* `IntegrationDevice.syncScheduleToServer`)。Web 端点击前会弹警告对话框,
* 说明它会用教室机器的课表覆盖本班现有课表。
* 置一个待办标记,插件在下一次心跳看到就立刻把课表推上来。
*/
router.post(
'/devices/:id/request-schedule',
requirePermission('device:manage'),
validate({ params: deviceIdParamSchema }),
async (req, res) => {
const { id } = validatedParams<{ id: string }>(req);
const result = await integrationService.requestScheduleReport(getAuthUser(req), id);
sendOk(res, result, result.nextHeartbeatHint);
},
);
/**
* POST /api/integrations/devices/:id/mirror-schedule - 「下发一次课表到教室」
*
* 与「获取课表」反方向、同样是一次性动作。插件在下一次心跳看到待办就去拉本班课表,
* 并**强制替换**写进 ClassIsland(覆盖老师手排的冲突课表)。
*
* 为什么要做成按钮而不是后台一直同步:插件原先每 15 秒上报一次、每次上报完还顺手镜像一遍,
* 教室课表被反复重写,服务端也每 15 秒 merge + 清理一次幽灵行 —— 老师看到的是
* "课表被反复删改"(2026-10-11 实测)。
*/
router.post(
'/devices/:id/mirror-schedule',
requirePermission('device:manage'),
validate({ params: deviceIdParamSchema }),
async (req, res) => {
const { id } = validatedParams<{ id: string }>(req);
const result = await integrationService.requestMirrorSchedule(getAuthUser(req), id);
sendOk(res, result, result.nextHeartbeatHint);
},
);
/** POST /api/integrations/devices/:id/token - 重置令牌(旧令牌立即失效) */router.post(
'/devices/:id/token',
requirePermission('device:manage'),
validate({ params: deviceIdParamSchema }),
async (req, res) => {
const { id } = validatedParams<{ id: string }>(req);
sendOk(res, await integrationService.resetDeviceToken(getAuthUser(req), id), '令牌已重置');
},
);
/** DELETE /api/integrations/devices/:id - 删除设备 */
router.delete(
'/devices/:id',
requirePermission('device:manage'),
validate({ params: deviceIdParamSchema }),
async (req, res) => {
const { id } = validatedParams<{ id: string }>(req);
await integrationService.deleteDevice(getAuthUser(req), id);
sendOk(res, { id }, '设备已删除');
},
);
/** POST /api/integrations/classisland/notify - 把提醒下发到该班的 ClassIsland 设备 */
router.post(
'/classisland/notify',
requirePermission('classisland:notify'),
validate({ body: sendNotificationSchema }),
async (req, res) => {
const result = await integrationService.sendNotification(
getAuthUser(req),
validatedBody<SendNotificationInput>(req),
);
sendOk(
res,
result,
result.skipped === 'channel-client'
? '该班教室已设置为「只在 ClassHelper 客户端显示」,本次未推送到 ClassIsland'
: result.targetCount === 0
? '已保存提醒,但该班级还没有已接入的 ClassIsland 设备'
: `已下发到 ${result.delivered} 台 ClassIsland 设备`,
);
},
);
export const integrationsModule = defineModule({
name: 'integrations',
basePath: '/integrations',
router,
});
@@ -1,133 +0,0 @@
import { z } from 'zod';
import {
WEEK_PARITY_VALUES,
CLASSISLAND_NOTIFICATION_MAX_DURATION,
CLASSISLAND_NOTIFICATION_DEFAULT_DURATION,
} from '@classhelper/shared';
import { booleanFlagSchema, timeSchema } from '../../lib/schemas.js';
/** 1=周一 … 7=周日 */
const dayOfWeekSchema = z.coerce.number().int().min(1).max(7);
export const integrationModeSchema = z.enum(['plugin', 'import']);
export const weekParitySchema = z.enum(WEEK_PARITY_VALUES as unknown as [string, ...string[]]);
/* ------------------------------------------------------------------ Web 管理端 */
export const listDevicesQuerySchema = z.object({
classId: z.string().min(1).optional(),
});
export const createDeviceSchema = z.object({
classId: z.string().min(1, '请选择班级'),
name: z.string().trim().max(40).optional(),
mode: integrationModeSchema.optional(),
/**
* 是否允许插件把 ClassIsland 的课表**自动**回传到本服务。
* 默认 **false**(课表以服务端为准);要取教室的课表用「从教室机器获取课表」这个手动动作。
*/
syncScheduleToServer: z.boolean().optional(),
/** 是否允许把本班课表镜像回 ClassIsland。默认 **true** —— 这是现在课表同步的主方向。 */
mirrorScheduleToClassIsland: z.boolean().optional(),
});
export const updateDeviceSchema = z.object({
name: z.string().trim().max(40).optional(),
enabled: z.boolean().optional(),
mode: integrationModeSchema.optional(),
syncScheduleToServer: z.boolean().optional(),
mirrorScheduleToClassIsland: z.boolean().optional(),
});
export const deviceIdParamSchema = z.object({ id: z.string().min(1, '缺少设备 id') });
export const sendNotificationSchema = z.object({
classId: z.string().min(1, '请选择班级'),
title: z.string().trim().min(1, '请输入提醒标题').max(120),
content: z.string().trim().min(1, '请输入提醒内容').max(2000),
durationSeconds: z.coerce.number().int().min(1).max(CLASSISLAND_NOTIFICATION_MAX_DURATION).optional(),
speech: booleanFlagSchema,
speechContent: z.string().trim().max(500).optional(),
saveToNotifications: z.boolean().optional(),
priority: z.enum(['LOW', 'NORMAL', 'HIGH', 'URGENT']).optional(),
});
/* ------------------------------------------------------------------ 插件侧(设备令牌鉴权) */
export const reportScheduleEntrySchema = z.object({
dayOfWeek: dayOfWeekSchema,
startTime: timeSchema,
endTime: timeSchema,
subject: z.string().trim().min(1, '科目不能为空').max(40),
teacherName: z.string().trim().max(40).nullish(),
weekParity: weekParitySchema.optional(),
weekCountDiv: z.coerce.number().int().min(0).max(30).optional(),
weekCountDivTotal: z.coerce.number().int().min(0).max(30).optional(),
planName: z.string().trim().max(60).optional(),
});
export const reportTimeLayoutItemSchema = z.object({
index: z.coerce.number().int().min(0).max(200).optional(),
name: z.string().trim().max(40).optional(),
startTime: timeSchema,
endTime: timeSchema,
type: z.enum(['class', 'break', 'divider', 'action']).optional(),
skipped: z.boolean().optional(),
});
export const classIslandReportSchema = z.object({
pluginVersion: z.string().trim().max(40).optional(),
classIslandVersion: z.string().trim().max(40).optional(),
/**
* 插件生成的机器码。设备创建时服务端还不知道它是谁,只能用 `pending-…` 占位,
* 因此插件每次上报都带上它,服务端据此回填,Web 端设备列表才能与教室机器对上
* (见 integrations.service 的 syncDeviceKey)。
*/
deviceKey: z.string().trim().max(64).optional(),
state: z
.object({
inClass: z.boolean().optional(),
subject: z.string().trim().max(40).nullish(),
nextSubject: z.string().trim().max(40).nullish(),
timeState: z.string().trim().max(40).nullish(),
periodStart: timeSchema.nullish(),
periodEnd: timeSchema.nullish(),
week: z.coerce.number().int().min(1).max(60).nullish(),
classPlanLoaded: z.boolean().optional(),
clientTime: z.string().trim().max(40).optional(),
})
.optional(),
schedule: z
.object({
mode: z.enum(['replace', 'merge']).optional(),
entries: z.array(reportScheduleEntrySchema).max(500, '单次上报的课程条目过多'),
})
.nullish(),
timeLayout: z
.object({
name: z.string().trim().max(60).optional(),
mode: z.enum(['replace', 'merge']).optional(),
items: z.array(reportTimeLayoutItemSchema).max(200, '单次上报的节次过多'),
})
.nullish(),
});
/** 插件确认某条提醒已弹出(避免重连后重复补发) */
export const ackNotificationSchema = z.object({
id: z.string().min(1, '缺少提醒 id'),
});
/** 插件上报的默认值集中在这里,避免散落在 service 里 */
export const REPORT_DEFAULTS = {
scheduleMode: 'merge',
timeLayoutMode: 'merge',
timeLayoutName: 'ClassIsland 时间表',
notificationDuration: CLASSISLAND_NOTIFICATION_DEFAULT_DURATION,
} as const;
export type CreateDeviceInput = z.infer<typeof createDeviceSchema>;
export type UpdateDeviceInput = z.infer<typeof updateDeviceSchema>;
export type SendNotificationInput = z.infer<typeof sendNotificationSchema>;
export type ClassIslandReportInput = z.infer<typeof classIslandReportSchema>;
export type ReportScheduleEntry = z.infer<typeof reportScheduleEntrySchema>;
export type ReportTimeLayoutItem = z.infer<typeof reportTimeLayoutItemSchema>;
@@ -1,957 +0,0 @@
import {
CLASS_HELPER_ONLINE_WINDOW_MS,
SOCKET_EVENTS,
weekDivFromParity,
type ClassDto,
type ClassHelperDeviceStatusDto,
type ClassHelperStatusListDto,
type ClassIslandPendingResult,
type ClassIslandPushNotification,
type ClassIslandReportResult,
type ClassIslandScheduleEntry,
type IntegrationDeviceDto,
type IntegrationDeviceTokenDto,
type SendClassIslandNotificationResult,
type TimeLayoutEntry,
type NotificationDto,
} from '@classhelper/shared';
import { assertCanManageSchedule, assertCanPublishNotification, resolveClassScope } from '../../lib/access.js';
import { loadTermContext, resolveCurrentWeek } from '../../lib/term.js';
import { prisma } from '../../lib/db.js';
import { ApiError } from '../../lib/http.js';
import type { TokenPayload } from '../../lib/jwt.js';
import { logger } from '../../lib/logger.js';
import { toNotificationChannel, toNotificationDto } from '../../lib/mappers.js';
import { emitToClass, emitToRooms } from '../../realtime/bus.js';
import { SOCKET_ROOMS } from '@classhelper/shared';
import type { DeviceContext } from './device-auth.js';
import { generateDeviceToken, hashDeviceToken, tokenHintOf } from './device-auth.js';
import type {
ClassIslandReportInput,
CreateDeviceInput,
SendNotificationInput,
UpdateDeviceInput,
} from './integrations.schemas.js';
import { REPORT_DEFAULTS } from './integrations.schemas.js';
import {
applyReportedSchedule,
applyReportedTimeLayout,
toClassIslandWeekDay,
type MirrorClassPlan,
} from './write-back.service.js';
/**
* ClassIsland 联动服务。
*
* 两条链路:
* 1) **ClassHelper → ClassIsland**:教师发通知 → 落库 + Socket.IO 广播 →
* 教室机器上的插件弹出全屏提醒(离线时先落库,插件重连后拉取补发);
* 2) **ClassIsland → ClassHelper**:插件把"当前上什么课 + 全量课表"上报 →
* 本服务按设备令牌解析出所属班级并写库 → 广播 `classisland:state` 给 Web 端实时展示。
*
* 权限口径:
* - 设备管理(创建/重置令牌/启停):与"课表管理"一致(管理员或本班班主任);
* - 下发提醒:与"发通知"一致(管理员 / 班主任 / 科任老师)。
*/
/* ------------------------------------------------------------------ 设备管理(Web 端,JWT 鉴权) */
/**
* 设备记录 -> DTO(tokenHash 永不出库)。
*
* `online` 由**最后一次心跳**(`lastHeartbeatAt`)与共享的
* `CLASS_HELPER_ONLINE_WINDOW_MS`(60 秒)算出,而不是最后一次带状态的上报 ——
* 插件每 60 秒打一次心跳,因此"最近一分钟内有心跳"才是最贴合的口径。
*/
function toDeviceDto(record: {
id: string;
classId: string;
name: string;
deviceKey: string;
mode: string;
enabled: boolean;
syncScheduleToServer: boolean;
mirrorScheduleToClassIsland: boolean;
requestScheduleReport: boolean;
classIslandVersion: string | null;
pluginVersion: string | null;
lastSeenAt: Date | null;
lastHeartbeatAt: Date | null;
classPlanLoaded: boolean;
currentSubject: string | null;
currentTimeState: string | null;
currentPeriodStart: string | null;
currentPeriodEnd: string | null;
nextSubject: string | null;
tokenHint: string;
createdAt: Date;
updatedAt: Date;
class?: { name: string } | null;
}): IntegrationDeviceDto {
const heartbeat = record.lastHeartbeatAt ?? record.lastSeenAt;
return {
id: record.id,
classId: record.classId,
className: record.class?.name ?? null,
name: record.name,
deviceKey: record.deviceKey,
mode: record.mode === 'import' ? 'import' : 'plugin',
enabled: record.enabled,
syncScheduleToServer: record.syncScheduleToServer,
mirrorScheduleToClassIsland: record.mirrorScheduleToClassIsland,
requestScheduleReport: record.requestScheduleReport,
classIslandVersion: record.classIslandVersion,
pluginVersion: record.pluginVersion,
lastSeenAt: record.lastSeenAt ? record.lastSeenAt.toISOString() : null,
lastHeartbeatAt: heartbeat ? heartbeat.toISOString() : null,
online: Boolean(record.enabled && heartbeat && Date.now() - heartbeat.getTime() < CLASS_HELPER_ONLINE_WINDOW_MS),
classPlanLoaded: record.classPlanLoaded,
currentSubject: record.currentSubject,
currentTimeState: record.currentTimeState,
currentPeriodStart: record.currentPeriodStart,
currentPeriodEnd: record.currentPeriodEnd,
nextSubject: record.nextSubject,
tokenHint: record.tokenHint,
createdAt: record.createdAt.toISOString(),
updatedAt: record.updatedAt.toISOString(),
};
}
/**
* GET /api/integrations/classisland/status —— **ClassHelper 班级端在线状态**(教师网页)。
*
* 范围:管理员看全部班级,普通教师看自己担任班主任的班级 ∪ 任课(有 Course)的班级。
* 这是「教师网页可查看班级 ClassHelper 在线状态」这条需求的落点。
*/
export async function listClassHelperStatus(user: TokenPayload): Promise<ClassHelperStatusListDto> {
const scope = await resolveClassScope(user);
const classes = await prisma.class.findMany({
where: {
...(scope.mode === 'all' ? {} : { id: { in: scope.classIds } }),
// 归档班级的班级端已经停用,不列出来
archivedYearId: null,
},
orderBy: [{ enrollmentYear: 'desc' }, { classIndex: 'asc' }],
select: {
id: true,
name: true,
grade: true,
studentGradeQueryEnabled: true,
integrationDevices: {
where: { mode: 'plugin' },
orderBy: [{ lastHeartbeatAt: 'desc' }],
select: {
id: true,
name: true,
deviceKey: true,
enabled: true,
lastSeenAt: true,
lastHeartbeatAt: true,
pluginVersion: true,
classIslandVersion: true,
},
},
},
});
const now = Date.now();
return {
serverTime: new Date().toISOString(),
onlineWindowMs: CLASS_HELPER_ONLINE_WINDOW_MS,
classes: classes.map((item) => {
const devices: ClassHelperDeviceStatusDto[] = item.integrationDevices.map((device) => {
const heartbeat = device.lastHeartbeatAt ?? device.lastSeenAt;
return {
deviceId: device.id,
deviceName: device.name,
deviceKey: device.deviceKey,
enabled: device.enabled,
online: Boolean(device.enabled && heartbeat && now - heartbeat.getTime() < CLASS_HELPER_ONLINE_WINDOW_MS),
lastSeenAt: device.lastSeenAt ? device.lastSeenAt.toISOString() : null,
lastHeartbeatAt: heartbeat ? heartbeat.toISOString() : null,
pluginVersion: device.pluginVersion,
classIslandVersion: device.classIslandVersion,
};
});
return {
classId: item.id,
className: item.name,
grade: item.grade,
devices,
online: devices.some((device) => device.online),
studentGradeQueryEnabled: item.studentGradeQueryEnabled ?? true,
};
}),
};
}
export async function listDevices(user: TokenPayload, classId?: string): Promise<IntegrationDeviceDto[]> {
// 管理员不传 classId 时看全部;教师只看自己可访问的班级
const scope = await resolveClassScope(user, classId);
const records = await prisma.integrationDevice.findMany({
where: scope.mode === 'all' ? {} : { classId: { in: scope.classIds } },
include: { class: { select: { name: true } } },
orderBy: [{ classId: 'asc' }, { createdAt: 'asc' }],
});
return records.map(toDeviceDto);
}
/**
* 新建设备:一次性返回明文令牌。
* deviceKey 由插件上报的机器码决定,但创建时还不知道机器码,
* 因此这里用随机值占位,插件首次上报时按 token 找到记录并回填真实机器码。
*/
export async function createDevice(
user: TokenPayload,
input: CreateDeviceInput,
): Promise<IntegrationDeviceTokenDto> {
await assertCanManageSchedule(user, input.classId);
const classRecord = await prisma.class.findUnique({
where: { id: input.classId },
select: { id: true, name: true },
});
if (!classRecord) throw ApiError.notFound('班级不存在');
const token = generateDeviceToken();
const created = await prisma.integrationDevice.create({
data: {
classId: input.classId,
name: input.name?.trim() || `${classRecord.name} ClassHelper 班级端`,
deviceKey: `pending-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,
mode: input.mode ?? 'plugin',
tokenHash: hashDeviceToken(token),
tokenHint: tokenHintOf(token),
// 同步方向(2026-10-06 起):课表以服务端为准,**服务端 → 教室自动下发**;
// 「把教室课表传上来」改成 Web 端的一次性人工动作,所以默认关掉自动回传。
syncScheduleToServer: input.syncScheduleToServer === true,
mirrorScheduleToClassIsland: input.mirrorScheduleToClassIsland !== false,
},
include: { class: { select: { name: true } } },
});
logger.info(`ClassIsland 联动设备已创建:班级=${classRecord.name} 设备=${created.name}`);
return { device: toDeviceDto(created), token };
}
async function findDeviceOrFail(id: string): Promise<{
id: string;
classId: string;
name: string;
enabled: boolean;
/** 「下发课表到教室」要按它判断这台设备接不接受下发(见 requestMirrorSchedule) */
mirrorScheduleToClassIsland: boolean;
}> {
const record = await prisma.integrationDevice.findUnique({
where: { id },
select: { id: true, classId: true, name: true, enabled: true, mirrorScheduleToClassIsland: true },
});
if (!record) throw ApiError.notFound('设备不存在或已被删除');
return record;
}
export async function updateDevice(
user: TokenPayload,
deviceId: string,
input: UpdateDeviceInput,
): Promise<IntegrationDeviceDto> {
const current = await findDeviceOrFail(deviceId);
await assertCanManageSchedule(user, current.classId);
const updated = await prisma.integrationDevice.update({
where: { id: deviceId },
data: {
...(input.name !== undefined ? { name: input.name.trim() || current.name } : {}),
...(input.enabled !== undefined ? { enabled: input.enabled } : {}),
...(input.mode !== undefined ? { mode: input.mode } : {}),
...(input.syncScheduleToServer !== undefined
? { syncScheduleToServer: input.syncScheduleToServer }
: {}),
...(input.mirrorScheduleToClassIsland !== undefined
? { mirrorScheduleToClassIsland: input.mirrorScheduleToClassIsland }
: {}),
},
include: { class: { select: { name: true } } },
});
logger.info(`ClassIsland 联动设备已更新:${updated.name} enabled=${updated.enabled}`);
return toDeviceDto(updated);
}
/**
* 「**从教室机器获取一次课表**」的待办(Web 端手动动作)。
*
* 为什么是"待办"而不是直接拉:课表由**插件主动上报**,服务端没有反向通道去催它。
* 所以这里只置一个标记,插件在下一次上报(默认 60 秒一次的心跳)看到
* `settings.scheduleRequested = true` 就立刻把当前课表推上来并完成待办。
*
* 它独立于 `syncScheduleToServer`:后者是"允许自动回传",现在默认**关闭**
* (自动回传会在老师手排课之后被教室的旧课表悄悄覆盖);
* 管理员显式点"获取课表"时仍然应当能取到一次。
*/
export async function requestScheduleReport(
user: TokenPayload,
deviceId: string,
): Promise<{ requested: boolean; deviceName: string; nextHeartbeatHint: string }> {
const current = await findDeviceOrFail(deviceId);
await assertCanManageSchedule(user, current.classId);
if (!current.enabled) throw ApiError.badRequest('该设备已停用,请先启用后再获取课表');
await prisma.integrationDevice.update({
where: { id: deviceId },
data: { requestScheduleReport: true },
});
logger.info(`已请求设备上报课表:${current.name}(classId=${current.classId})由 ${user.name} 发起`);
return {
requested: true,
deviceName: current.name,
nextHeartbeatHint: '教室机器会在下一次心跳(约 1 分钟内)把当前课表上报上来',
};
}
/**
* 「**下发一次课表到教室**」的待办(Web 端手动动作)。
*
* 与 `requestScheduleReport` 对称:服务端没有反向通道去催插件,所以只置一个标记,
* 插件在下一次心跳看到 `settings.mirrorRequested = true` 就去拉本班课表、
* **强制替换**写进 ClassIsland(见插件侧 `ClassPlanWriter` 的 force 语义)。
*
* 为什么要改成手动(2026-10-11):插件原先每 15 秒上报一次、每次上报完还顺手镜像一遍
* (插件侧的 `MirrorSchedule` 开关),教室课表被反复重写、服务端也每 15 秒 merge + 清理
* 一次幽灵行 —— 老师看到的是"课表被反复删改"。两个方向现在都只由点击触发。
*/
export async function requestMirrorSchedule(
user: TokenPayload,
deviceId: string,
): Promise<{ requested: boolean; deviceName: string; nextHeartbeatHint: string }> {
const current = await findDeviceOrFail(deviceId);
await assertCanManageSchedule(user, current.classId);
if (!current.enabled) throw ApiError.badRequest('该设备已停用,请先启用后再下发课表');
if (!current.mirrorScheduleToClassIsland) {
throw ApiError.badRequest('这台设备没有开启「允许下发课表」,请先在设备设置里打开');
}
await prisma.integrationDevice.update({
where: { id: deviceId },
data: { requestMirrorSchedule: true },
});
logger.info(`已请求向设备下发课表:${current.name}(classId=${current.classId})由 ${user.name} 发起`);
return {
requested: true,
deviceName: current.name,
nextHeartbeatHint: '教室机器会在下一次心跳(约 1 分钟内)拉取并强制替换教室课表',
};
}
/** 重置令牌:旧令牌立即失效(插件侧需要重新填写) */
export async function resetDeviceToken(
user: TokenPayload, deviceId: string,
): Promise<IntegrationDeviceTokenDto> {
const current = await findDeviceOrFail(deviceId);
await assertCanManageSchedule(user, current.classId);
const token = generateDeviceToken();
const updated = await prisma.integrationDevice.update({
where: { id: deviceId },
data: { tokenHash: hashDeviceToken(token), tokenHint: tokenHintOf(token) },
include: { class: { select: { name: true } } },
});
logger.warn(`ClassIsland 联动设备令牌已重置:${updated.name}(旧令牌立即失效)`);
return { device: toDeviceDto(updated), token };
}
export async function deleteDevice(user: TokenPayload, deviceId: string): Promise<void> {
const current = await findDeviceOrFail(deviceId);
await assertCanManageSchedule(user, current.classId);
await prisma.integrationDevice.delete({ where: { id: deviceId } });
logger.info(`ClassIsland 联动设备已删除:${current.name}`);
}
/* ------------------------------------------------------------------ 提醒下发(Web 端 → ClassIsland) */
function toPushDto(
record: {
id: string;
classId: string;
title: string;
content: string;
durationSeconds: number;
speechContent: string | null;
urgent: boolean;
kind?: string | null;
createdAt: Date;
},
extras: { className?: string | null; teacherName?: string | null } = {},
): ClassIslandPushNotification {
return {
id: record.id,
title: record.title,
content: record.content,
durationSeconds: record.durationSeconds,
speechContent: record.speechContent,
createdAt: record.createdAt.toISOString(),
urgent: record.urgent,
// 老数据(迁移前)kind 为空:按普通通知处理
kind: record.kind === 'call' ? 'call' : 'notification',
classId: record.classId,
className: extras.className ?? null,
teacherName: extras.teacherName ?? null,
};
}
/**
* 下发一条提醒到该班级的 ClassIsland 设备。
*
* - 落库(ClassIslandPush)→ 在线设备通过 Socket.IO 立即收到;离线设备重连后走
* `GET /api/integrations/classisland/pending` 补齐,保证"老师按了发送就一定送到";
* - `saveToNotifications` 默认 true:同时写一条班级通知,ClassHelper 班级端通知中心/灵动岛也能看到,
* 避免"只在 ClassIsland 上弹了一下,事后查无此事"。
*/
export async function sendNotification(
user: TokenPayload,
input: SendNotificationInput,
): Promise<SendClassIslandNotificationResult> {
await assertCanPublishNotification(user, input.classId);
const teacher = await prisma.user.findUnique({
where: { id: user.sub },
select: { name: true, username: true },
});
const teacherName = teacher?.name ?? teacher?.username ?? null;
const priority = input.priority ?? 'NORMAL';
let notificationId: string | null = null;
// 教室在客户端里选了"只在 ClassHelper 客户端显示"时,**任何入口**都不再推 ClassIsland
// (包括这个专门发给 ClassIsland 的入口)—— 规则只有一条,老师不用记"哪个页面有例外"。
// 仍然把通知落库,并把跳过原因回给调用方,由 Web 端提示"不是没送达,是教室没要"。
const allowed = await shouldPushToClassIsland(input.classId);
if (input.saveToNotifications !== false) {
const created = await prisma.notification.create({
data: {
classId: input.classId,
title: input.title,
content: input.content,
priority,
createdBy: user.sub,
},
include: { creator: { select: { id: true, name: true, username: true } }, reads: true },
});
notificationId = created.id;
const dto: NotificationDto = toNotificationDto(created, { withStatus: true });
// ClassHelper 班级端照旧收到通知中心的实时推送
emitToClass(input.classId, SOCKET_EVENTS.notificationNew, dto);
}
if (!allowed) {
logger.info(`ClassIsland 提醒被跳过:班级=${input.classId} 已选择"只在 ClassHelper 客户端显示"`);
return { delivered: 0, targetCount: 0, notificationId, skipped: 'channel-client' };
}
const result = await pushToClassIsland({
classId: input.classId,
title: input.title,
content: input.content,
durationSeconds: input.durationSeconds,
speechContent: input.speech
? input.speechContent?.trim() || `${input.title}。${input.content}`
: null,
urgent: priority === 'URGENT',
createdBy: user.sub,
notificationId,
teacherName,
});
return { ...result, notificationId, skipped: null };
}
/** 推送所需的入参:三个发布入口(联动页 / 通知发布 / 叫人)共用同一套语义 */
export interface PushToClassIslandInput {
classId: string;
title: string;
content: string;
/** 显示时长(秒),留空用默认值 */
durationSeconds?: number;
/** 语音朗读内容;null = 不朗读 */
speechContent?: string | null;
urgent?: boolean;
createdBy?: string | null;
/** 若这次提醒也落了通知中心的库,把通知 id 带上,便于事后追溯 */
notificationId?: string | null;
/** 覆盖落库/广播时附带的教师名(三个入口的取法不同) */
teacherName?: string | null;
/** 提醒类型:notification(默认)/ call(叫人,算「主动通知」) */
kind?: 'notification' | 'call';
}
/**
* 把一条提醒推给某个班的 ClassIsland 设备(落库 + 广播)。
*
* 这是**三个发布入口的唯一共用实现**:
* 1. 联动页的「下发提醒」(sendNotification);
* 2. 通知发布页的 POST /notifications;
* 3. 叫人 POST /calls。
* 因此"换个页面发通知就联动不到 ClassIsland"这类不一致不会再出现。
*
* 调用方负责权限校验与(必要时)显示位置开关判断。
*/
export async function pushToClassIsland(
input: PushToClassIslandInput,
): Promise<{ delivered: number; targetCount: number }> {
const classRecord = await prisma.class.findUnique({
where: { id: input.classId },
select: { id: true, name: true },
});
if (!classRecord) throw ApiError.notFound('班级不存在');
const devices = await prisma.integrationDevice.findMany({
where: { classId: input.classId, enabled: true, mode: 'plugin' },
select: { id: true },
});
// 一个已接入的设备都没有时**不落推送记录**:
// 否则任何"发通知"的动作(通知发布 / 叫人 / 冒烟脚本)都会给该班堆一条待提醒,
// 等这台教室真的装上插件时被一次性补发一堆过期内容。
// 教室机器只是离线(设备存在但没上报)的情况不受影响 —— 那正是"离线补齐"要覆盖的场景。
if (devices.length === 0) {
logger.info(`跳过 ClassIsland 推送:班级=${classRecord.name} 还没有已接入的设备`);
return { delivered: 0, targetCount: 0 };
}
const push = await prisma.classIslandPush.create({
data: {
classId: input.classId,
title: input.title,
content: input.content,
durationSeconds: input.durationSeconds ?? REPORT_DEFAULTS.notificationDuration,
speechContent: input.speechContent ?? null,
urgent: input.urgent === true,
kind: input.kind ?? 'notification',
createdBy: input.createdBy ?? null,
notificationId: input.notificationId ?? null,
// 24 小时未送达/未确认的提醒不再补发,避免学生过几天突然看到旧提醒
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
},
});
emitToClass(input.classId, SOCKET_EVENTS.classislandNotification, {
...toPushDto(push, { className: classRecord.name, teacherName: input.teacherName ?? null }),
targetCount: devices.length,
});
logger.info(
`ClassIsland 提醒下发:班级=${classRecord.name} 设备数=${devices.length} 标题="${input.title}"`,
);
return { delivered: devices.length, targetCount: devices.length };
}
/**
* 班级的通知显示位置(由教室的班级客户端在设置页里选)。
*
* - `client`:教室里选了"只在 ClassHelper 客户端弹",因此**不要**推 ClassIsland;
* - 其余(both / classisland / 非法值)都推 —— 非法值按默认 both 处理,宁可多送一次也不要静默丢提醒。
*/
export async function shouldPushToClassIsland(classId: string): Promise<boolean> {
const record = await prisma.class.findUnique({
where: { id: classId },
select: { notificationChannel: true },
});
return toNotificationChannel(record?.notificationChannel) !== 'client';
}
/* ------------------------------------------------------------------ 插件侧(设备令牌鉴权) */
/**
* 插件上报:状态 + 可选的全量课表/节次时间。
*
* 关键点:**班级由设备令牌决定**,插件无法指定 classId,
* 因此一台被绑定到 A 班的机器不可能把课表写进 B 班。
*/
export async function applyReport(
device: DeviceContext,
input: ClassIslandReportInput,
): Promise<ClassIslandReportResult> {
const now = new Date();
// 周次口径按**本班**算(管理员可以给每个班单独配开学日期与逐周区间)
const week = resolveCurrentWeek(now, await loadTermContext(device.classId));
// 0) 机器码回填(设备创建时只能用 pending-… 占位,首次上报才知道它到底是哪台机器)
if (input.deviceKey) await syncDeviceKey(device, input.deviceKey);
// 1) 状态快照(无论课表是否上报都更新,Web 端据此显示"现在上什么课")
//
// 心跳与"带状态的上报"分开记:`lastHeartbeatAt` 每次上报都刷(在线判定看它),
// `lastSeenAt` 只在确实带了运行状态时刷 —— 这样"连得上但一直没上报状态"的设备
// 不会被误判成一切正常。
const state = input.state;
const currentDevice = await prisma.integrationDevice.findUnique({
where: { id: device.deviceId },
select: { requestScheduleReport: true },
});
const scheduleRequested = currentDevice?.requestScheduleReport === true;
await prisma.integrationDevice.update({
where: { id: device.deviceId },
data: {
lastHeartbeatAt: now,
// 这次真的带了课表上来 → 待办完成
...(input.schedule ? { requestScheduleReport: false } : {}),
...(state ? { lastSeenAt: now } : {}),
...(input.pluginVersion ? { pluginVersion: input.pluginVersion } : {}),
...(input.classIslandVersion ? { classIslandVersion: input.classIslandVersion } : {}),
...(state
? {
classPlanLoaded: state.classPlanLoaded === true,
currentSubject: state.subject ?? null,
currentTimeState: state.timeState ?? null,
currentPeriodStart: state.periodStart ?? null,
currentPeriodEnd: state.periodEnd ?? null,
nextSubject: state.nextSubject ?? null,
}
: {}),
},
select: { id: true },
});
if (state) {
emitToRooms([SOCKET_ROOMS.class(device.classId), SOCKET_ROOMS.teachers], SOCKET_EVENTS.classislandState, {
classId: device.classId,
deviceId: device.deviceId,
deviceName: device.name,
inClass: state.inClass === true,
subject: state.subject ?? null,
nextSubject: state.nextSubject ?? null,
timeState: state.timeState ?? null,
periodStart: state.periodStart ?? null,
periodEnd: state.periodEnd ?? null,
week: state.week ?? week,
classPlanLoaded: state.classPlanLoaded === true,
at: now.toISOString(),
});
}
// 2) 课表写入(受设备开关与班级设置双重约束)
let scheduleApplied = false;
let scheduleCreated = 0;
let scheduleUpdated = 0;
let courses: string[] = [];
if (input.schedule && input.schedule.entries.length > 0) {
if (!device.syncScheduleToServer) {
logger.warn(`ClassIsland 上报课表被忽略:设备「${device.name}」的"回传课表到服务端"开关已关闭`);
} else {
const result = await applyReportedSchedule(
device.classId,
input.schedule.mode ?? REPORT_DEFAULTS.scheduleMode,
input.schedule.entries,
);
scheduleApplied = result.applied;
scheduleCreated = result.created;
scheduleUpdated = result.updated;
courses = result.courses;
if (result.applied) {
emitToClass(device.classId, SOCKET_EVENTS.scheduleUpdated, {
classId: device.classId,
action: 'imported',
});
}
}
}
// 3) 节次时间表写入
let timeLayoutApplied = false;
if (input.timeLayout && input.timeLayout.items.length > 0) {
const result = await applyReportedTimeLayout(
device.classId,
input.timeLayout.name?.trim() || REPORT_DEFAULTS.timeLayoutName,
input.timeLayout.items,
);
timeLayoutApplied = result.applied;
}
// 4) 取出尚未确认的下发提醒(插件刚启动时把漏掉的提醒立刻弹出来)
const pending = await pendingNotificationFor(device.deviceId, device.classId);
return {
scheduleApplied,
scheduleCreated,
scheduleUpdated,
courses,
timeLayoutApplied,
week,
serverTime: now.toISOString(),
settings: {
mirrorScheduleToClassIsland: device.mirrorScheduleToClassIsland,
enabled: device.enabled,
// 「从教室机器取一次课表」的待办:Web 端点过之后置位,插件看到就立刻推一次课表上来。
// 注意它**独立于** syncScheduleToServer —— 后者是"允许自动回传",现在默认关闭,
// 但管理员显式点"获取课表"时仍然应当能取到。
scheduleRequested: scheduleRequested,
// 「下发一次课表到教室」的待办(反方向)。插件看到就去拉本班课表并强制替换,
// 拉取成功时由 `pullClassPlanForDevice` 清除标记 —— 与上面那条对称。
mirrorRequested: device.mirrorRequested,
},
pendingNotification: pending,
};
}
/**
* 把插件上报的机器码回填到设备记录。
*
* `IntegrationDevice` 上有 `@@unique([classId, deviceKey])`,因此要避开两个坑:
* 1) 同一台机器在这个班已有另一条设备记录(例如管理员重复建过设备)时直接写会撞唯一约束 → 500,
* 这里改为记 warning 并保留原值;
* 2) 值没变时不必白写一次库。
*/
async function syncDeviceKey(device: DeviceContext, reportedKey: string): Promise<void> {
const key = reportedKey.trim();
if (!key) return;
const current = await prisma.integrationDevice.findUnique({
where: { id: device.deviceId },
select: { deviceKey: true },
});
if (!current || current.deviceKey === key) return;
const taken = await prisma.integrationDevice.findFirst({
where: { classId: device.classId, deviceKey: key, id: { not: device.deviceId } },
select: { name: true },
});
if (taken) {
logger.warn(
`ClassIsland 上报的机器码「${key}」已被本班设备「${taken.name}」占用,本次不回填(设备=${device.name})`,
);
return;
}
await prisma.integrationDevice.update({ where: { id: device.deviceId }, data: { deviceKey: key } });
logger.info(`ClassIsland 设备机器码已回填:${device.name} -> ${key}`);
}
/** 该设备/该班级最近一条尚未确认、未过期的下发提醒 */
async function pendingNotificationFor(
deviceId: string,
classId: string,
): Promise<ClassIslandPushNotification | null> {
const record = await prisma.classIslandPush.findFirst({
where: {
classId,
ackedAt: null,
expiresAt: { gt: new Date() },
OR: [{ deviceId: null }, { deviceId }],
},
orderBy: { createdAt: 'desc' },
});
if (!record) return null;
return toPushDto(record);
}
/** 插件重连/定时轮询:拉取本班所有未确认的提醒 */
export async function listPendingNotifications(device: DeviceContext): Promise<ClassIslandPendingResult> {
const now = new Date();
const records = await prisma.classIslandPush.findMany({
where: {
classId: device.classId,
ackedAt: null,
expiresAt: { gt: now },
OR: [{ deviceId: null }, { deviceId: device.deviceId }],
},
orderBy: { createdAt: 'asc' },
take: 20,
});
return {
notifications: records.map((item) => toPushDto(item)),
serverTime: now.toISOString(),
week: resolveCurrentWeek(now, await loadTermContext(device.classId)),
};
}
/** 插件确认提醒已弹出(之后不再补发) */
export async function ackNotification(device: DeviceContext, id: string): Promise<void> {
const record = await prisma.classIslandPush.findUnique({
where: { id },
select: { id: true, classId: true, deviceId: true },
});
if (!record) throw ApiError.notFound('提醒不存在');
if (record.classId !== device.classId) throw ApiError.forbidden('该提醒不属于本设备所在班级');
await prisma.classIslandPush.update({
where: { id },
data: { ackedAt: new Date(), ...(record.deviceId ? {} : { deviceId: device.deviceId }) },
});
}
/**
* 插件拉取本班课表(mirrorScheduleToClassIsland 打开时,
* 插件把它转换后覆盖写入 ClassIsland,实现"教师在 Web 端排课 → 教室课表跟着变")。
*/
export async function pullClassPlanForDevice(device: DeviceContext): Promise<{
classPlan: MirrorClassPlan;
week: number;
/** 学期周次区间(管理员逐周配置的);空数组 = 按学期开始日期线性推算 */
weekRanges: Array<{ weekNumber: number; startDate: string; endDate: string }>;
serverTime: string;
}> {
const now = new Date();
// 周次口径按**本班**算:管理员可以给每个班单独配开学日期与逐周区间(调休、错峰开学)
const termContext = await loadTermContext(device.classId);
const week = resolveCurrentWeek(now, termContext);
// 「下发一次课表」的待办到这里就算完成:插件已经来拉了,拿到就会写进 ClassIsland。
// **必须清掉** —— 不清的话每次心跳都会重新下发一遍,又变回"一直下发",
// 而这正是老师反映"课表被反复删改"的源头。
if (device.mirrorRequested) {
await prisma.integrationDevice.update({
where: { id: device.deviceId },
data: { requestMirrorSchedule: false },
});
logger.info(`课表下发待办已完成:${device.name}(classId=${device.classId})`);
}
const classRecord = await prisma.class.findUnique({
where: { id: device.classId },
select: { id: true, name: true, termWeeks: true, termStartDate: true },
});
if (!classRecord) throw ApiError.notFound('班级不存在');
const [schedules, timeLayouts] = await Promise.all([
prisma.schedule.findMany({
where: { classId: device.classId },
include: { course: { select: { id: true, name: true } } },
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
}),
prisma.timeLayout.findMany({
where: { classId: device.classId },
orderBy: { updatedAt: 'desc' },
}),
]);
// 节次时间表:优先用班级里已导入的 ClassIsland 时间表,其次按课表的开始时间合成
const layoutId = `ch-${device.classId}`;
const layoutName = timeLayouts[0]?.name ?? 'ClassHelper时间表';
let layouts: { startTime: string; endTime: string; timeType: number }[] = [];
if (timeLayouts.length > 0 && timeLayouts[0]) {
layouts = parseStoredTimeLayout(timeLayouts[0].items).map((item) => ({
startTime: item.startTime,
endTime: item.endTime,
// 本系统的 class->0(上课)、break->1(课间)、divider->2(分割线)
timeType: item.type === 'break' ? 1 : item.type === 'divider' ? 2 : 0,
}));
} else {
layouts = synthesizeTimeLayout(schedules);
}
const entries = schedules.map((item) => {
const parity = weekDivFromParity((item.weekParity as 'ALL' | 'ODD' | 'EVEN' | null) ?? 'ALL');
return {
weekDay: toClassIslandWeekDay(item.dayOfWeek),
weekCountDiv: parity.weekCountDiv,
weekCountDivTotal: parity.weekCountDivTotal,
subject: item.course?.name ?? '未命名科目',
teacherName: null,
startTime: item.startTime,
endTime: item.endTime,
timeLayoutId: layoutId,
};
});
return {
classPlan: {
entries,
timeLayouts: [{ id: layoutId, name: layoutName, layouts }],
profileName: `ClassHelper-${classRecord.name}`,
// 下发本班实际生效的开学日期(管理员可以为某个班单独配,优先级高于全局 .env)
termStartDate: termContext.termStartDate,
},
week,
weekRanges: termContext.weeks,
serverTime: now.toISOString(),
};
}
/**
* 「课表/周次变了,请重新镜像」的轻量通知。
*
* 插件是**轮询**镜像的(不订阅 Socket.IO),所以这里只做两件事:
* 广播给 Web 端让页面刷新,以及把该班的设备标记为"有新版本"。
* 真正的下发发生在插件下一次拉取课表时 —— 它会把新的开学日期与周次区间一并带走。
*/
export async function notifyScheduleChanged(classId: string): Promise<void> {
emitToRooms([SOCKET_ROOMS.class(classId), SOCKET_ROOMS.teachers], SOCKET_EVENTS.scheduleUpdated, {
classId,
action: 'imported',
});
logger.info(`课表/周次已变更,等待教室机器下次镜像时下发:classId=${classId}`);
}
/** 解析库里存的节次 JSON(容错:坏数据不抛异常,退化为空) */
function parseStoredTimeLayout(raw: string): { startTime: string; endTime: string; type: string }[] {
try {
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed
.map((item) => item as Partial<TimeLayoutEntry>)
.filter(
(item): item is Partial<TimeLayoutEntry> & { startTime: string; endTime: string } =>
typeof item.startTime === 'string' && typeof item.endTime === 'string',
)
.map((item) => ({
startTime: item.startTime,
endTime: item.endTime,
type: typeof item.type === 'string' ? item.type : 'class',
}));
} catch {
return [];
}
}
/**
* 没有导入节次时间表时,用课表里出现过的起止时间合成一份(去重、按时间排序)。
*
* **每节课之间补一个课间**(timeType=1:上一节下课 → 下一节上课),最后一节之后不补(放学)。
* ClassHelper这边的节次时间表与 ClassIsland 档案保持同一口径,镜像过去才不会缺课间。
*/
function synthesizeTimeLayout(
schedules: { startTime: string; endTime: string }[],
): { startTime: string; endTime: string; timeType: number }[] {
const seen = new Map<string, string>();
for (const item of schedules) {
if (!seen.has(item.startTime)) seen.set(item.startTime, item.endTime);
}
const classPoints = [...seen.entries()]
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([startTime, endTime]) => ({ startTime, endTime, timeType: 0 }));
const items: { startTime: string; endTime: string; timeType: number }[] = [];
for (let index = 0; index < classPoints.length; index += 1) {
const point = classPoints[index]!;
items.push(point);
const next = classPoints[index + 1];
if (!next) continue; // 最后一节之后是放学,不插课间
if (next.startTime > point.endTime) {
items.push({ startTime: point.endTime, endTime: next.startTime, timeType: 1 });
}
}
return items;
}
/* ------------------------------------------------------------------ 供仪表盘/统计使用 */
/** 某个班级当前是否已有在线设备(用于 Web 端提示"该班尚未接入 ClassIsland") */
export async function countEnabledDevices(classIds: string[]): Promise<number> {
if (classIds.length === 0) return 0;
return prisma.integrationDevice.count({
where: { classId: { in: classIds }, enabled: true, mode: 'plugin' },
});
}
/** 供 ClassDto 附加"是否已接入 ClassIsland"(Web 端班级列表里显示徽标) */
export async function attachIntegrationFlag(classes: ClassDto[]): Promise<ClassDto[]> {
if (classes.length === 0) return classes;
const ids = classes.map((item) => item.id);
const devices = await prisma.integrationDevice.findMany({
where: { classId: { in: ids }, enabled: true },
select: { classId: true },
});
const connected = new Set(devices.map((item) => item.classId));
return classes.map((item) => ({ ...item, classIslandConnected: connected.has(item.id) }));
}
export type { ClassIslandScheduleEntry };
@@ -1,271 +0,0 @@
import { prisma } from '../../lib/db.js';
import { logger } from '../../lib/logger.js';
import { weekParityFromDiv } from '@classhelper/shared';
import type { ReportScheduleEntry, ReportTimeLayoutItem } from './integrations.schemas.js';
/**
* 插件上报的课表 / 节次时间 → 写入本服务。
*
* 设计要点:
* 1) **复用导入模块的口径**:与 `modules/imports/class-plan.service.ts`、
* `time-layout.service.ts` 完全一致 —— 缺失的科目自动补建课程(任课老师取班主任)、
* merge 按 `星期 + 开始时间 + 单双周` 去重、replace 先清空再写入。
* 这样"插件实时上报"和"手动导入 JSON"落到库里的结果是一样的,不会出现两套语义。
* 2) **幂等**:插件每次上报(启动、课表变化、定时)都会带全量课表,
* 因此 merge 必须是"存在则更新、不存在则新增",重复上报不会产生重复行。
* 3) 整个写入放在一个事务里:解析/校验失败的批次不会留下半截数据。
*/
export interface ScheduleWriteResult {
applied: boolean;
created: number;
updated: number;
/** 被清理掉的旧同步行(老师已在 ClassIsland 里删除的课) */
removed: number;
courses: string[];
weekStart: number;
weekEnd: number;
}
/** 单双周口径:优先用插件显式给的 weekParity,否则从 WeekCountDiv/Total 推导 */
function resolveParity(entry: ReportScheduleEntry): 'ALL' | 'ODD' | 'EVEN' {
if (entry.weekParity === 'ALL' || entry.weekParity === 'ODD' || entry.weekParity === 'EVEN') {
return entry.weekParity;
}
const { weekCountDiv = 0, weekCountDivTotal = 0 } = entry;
return weekParityFromDiv(weekCountDiv, weekCountDivTotal);
}
/**
* 写入课表。classId 由**设备令牌**决定(不接受插件指定),因此插件无法越权写别的班级。
*/
export async function applyReportedSchedule(
classId: string,
mode: 'replace' | 'merge',
entries: ReportScheduleEntry[],
): Promise<ScheduleWriteResult> {
const empty: ScheduleWriteResult = {
applied: false,
created: 0,
updated: 0,
removed: 0,
courses: [],
weekStart: 1,
weekEnd: 20,
};
if (entries.length === 0) return empty;
const classRecord = await prisma.class.findUnique({
where: { id: classId },
select: { id: true, teacherId: true, termWeeks: true },
});
if (!classRecord) {
logger.warn(`ClassIsland 上报:班级不存在,已丢弃本批课表(classId=${classId})`);
return empty;
}
// 起止周次:与导入模块保持一致(weekStart 由班级进度决定,weekEnd 取班级教学周数)
const weekStart = 1;
const weekEnd = classRecord.termWeeks > 0 ? classRecord.termWeeks : 20;
const result = await prisma.$transaction(async (tx) => {
// 1) 补齐缺失的课程(任课老师先用班主任占位,老师可在课表管理里改)
const existingCourses = await tx.course.findMany({
where: { classId },
select: { id: true, name: true },
});
const courseIdByName = new Map(existingCourses.map((item) => [item.name, item.id]));
const createdCourses: string[] = [];
for (const name of new Set(entries.map((item) => item.subject))) {
if (courseIdByName.has(name)) continue;
const created = await tx.course.create({
data: { classId, name, teacherId: classRecord.teacherId },
select: { id: true, name: true },
});
courseIdByName.set(created.name, created.id);
createdCourses.push(created.name);
}
// 2) replace:先清空该班课表(与导入模块的 replace 语义一致)
if (mode === 'replace') {
await tx.schedule.deleteMany({ where: { classId } });
}
// 3) 逐条 upsert:merge 的去重键是「星期 + 开始时间 + 单双周」
let created = 0;
let updated = 0;
/** 本轮上报覆盖到的行 id:不在其中的 classisland 来源行会被清理(见第 4 步) */
const keptIds = new Set<string>();
for (const entry of entries) {
const courseId = courseIdByName.get(entry.subject);
if (!courseId) continue;
const weekParity = resolveParity(entry);
const existing = await tx.schedule.findFirst({
where: { classId, dayOfWeek: entry.dayOfWeek, startTime: entry.startTime, weekParity },
select: { id: true },
});
if (existing) {
await tx.schedule.update({
where: { id: existing.id },
data: {
courseId,
endTime: entry.endTime,
// 不覆盖 weekStart / weekEnd:插件上报契约里没有周次范围,
// 硬写"整学期"会把老师在 Web 端为选修/短期课设的「第 1~10 周」悄悄抹掉。
// 只在新建时给默认值(见下面 create)。
//
// 同样**不要**把 source 改成 'classisland':merge 的去重键是「星期 + 开始时间 + 单双周」,
// 老师在 Web 端手排的同一时间槽会被这里"收养"。一旦收养时改写来源,
// 后续那次"清理插件侧已删除的课"就会把这行老师手排的课一起删掉
// (真机上发生过:种子课表 93 行被删成 91 行,`verify:e2e` 的上课状态用例随之失败)。
// 因此来源只在 create 时确定,update 永远保持原值。
},
});
keptIds.add(existing.id);
updated += 1;
} else {
await tx.schedule.create({
data: {
classId,
courseId,
dayOfWeek: entry.dayOfWeek,
startTime: entry.startTime,
endTime: entry.endTime,
location: null,
weekStart,
weekEnd,
weekParity,
source: 'classisland',
},
});
created += 1;
}
}
// 4) 清理"老师已在 ClassIsland 里删掉"的行。
//
// merge 模式原先只 upsert、从不删除:老师在 ClassIsland 删掉一节,或把 8:00 的课挪到 8:05,
// 服务端那行会永远留着(幽灵课 / 同一天两节重复课)。但也不能照 replace 那样整表清空 ——
// 那会连老师在 Web 端手排的课一起删。
// 因此只清理 `source='classisland'`(即由上报同步产生)且本轮未再出现的行。
let removed = 0;
if (mode === 'merge') {
const synced = await tx.schedule.findMany({
where: { classId, source: 'classisland' },
select: { id: true, dayOfWeek: true, startTime: true, weekParity: true },
});
const stale = synced.filter(
(row) =>
!keptIds.has(row.id) &&
!entries.some(
(entry) =>
entry.dayOfWeek === row.dayOfWeek &&
entry.startTime === row.startTime &&
resolveParity(entry) === row.weekParity,
),
);
if (stale.length > 0) {
await tx.schedule.deleteMany({ where: { id: { in: stale.map((row) => row.id) } } });
removed = stale.length;
}
}
return { created, updated, removed, createdCourses, allCourses: [...courseIdByName.keys()] };
});
logger.info(
`ClassIsland 上报课表:班级=${classId} 模式=${mode} 新增=${result.created} 更新=${result.updated} ` +
`清理=${result.removed} 补建科目=[${result.createdCourses.join(',')}]`,
);
return {
applied: true,
created: result.created,
updated: result.updated,
removed: result.removed,
courses: result.allCourses,
weekStart,
weekEnd,
};
}
/**
* 写入节次时间表(TimeLayout)。
* 与 `modules/imports/time-layout.service.ts` 的口径保持一致:
* 同一班级同名配置整体替换;没有则新建。
* 注意:`action`(ClassIsland TimeType=3,行动)在本系统里没有对应节次类型,
* 写入时降级为 `divider`(不占课时,只做视觉分隔),避免类型校验失败。
*/
export async function applyReportedTimeLayout(
classId: string,
name: string,
items: ReportTimeLayoutItem[],
): Promise<{ applied: boolean; count: number }> {
if (items.length === 0) return { applied: false, count: 0 };
const normalized = items.map((item, index) => ({
index: item.index && item.index > 0 ? item.index : index + 1,
name: item.name?.trim() || `第 ${index + 1} 节`,
startTime: item.startTime,
endTime: item.endTime,
type: item.type === 'action' ? 'divider' : (item.type ?? 'class'),
skipped: item.skipped === true,
}));
const current = await prisma.timeLayout.findFirst({
where: { classId, name },
orderBy: { updatedAt: 'desc' },
select: { id: true },
});
if (current) {
await prisma.timeLayout.update({
where: { id: current.id },
data: { items: JSON.stringify(normalized), source: 'classisland' },
});
} else {
await prisma.timeLayout.create({
data: { classId, name, source: 'classisland', items: JSON.stringify(normalized) },
});
}
logger.info(`ClassIsland 上报节次时间表:班级=${classId} 名称=${name} 共 ${normalized.length} 节`);
return { applied: true, count: normalized.length };
}
/**
* 把本服务的课表转换成 ClassIsland 的档案口径(供插件拉回去镜像)。
*
* 关键换算:
* - 星期:本系统 1=周一…7=周日 → ClassIsland 0=周日、1=周一…6=周六;
* - 节次:ClassIsland 的 Classes[i] 对应 Layouts 里第 i 个 TimeType=0(上课)的点,
* 因此这里必须**按节次顺序**生成 layouts,并把每个 Schedule 归到"开始时间最接近且不晚于它"的节次上;
* - 单双周:ALL→(0,0);ODD→(1,2);EVEN→(2,2),与导入模块的解析互逆。
*/
export interface MirrorClassPlan {
entries: {
weekDay: number;
weekCountDiv: number;
weekCountDivTotal: number;
subject: string;
teacherName: string | null;
/**
* 该课目的起止时间(HH:mm)。插件靠它重建 ClassIsland 的时间表:
* `ClassPlan.Classes[i]` 必须与时间表里第 i 个上课点一一对应,缺了时间就整份错位。
*/
startTime: string;
endTime: string;
timeLayoutId: string;
}[];
timeLayouts: {
id: string;
name: string;
layouts: { startTime: string; endTime: string; timeType: number }[];
}[];
profileName: string;
termStartDate: string;
}
/** 本系统 dayOfWeek(1=周一…7=周日)→ ClassIsland WeekDay(0=周日…6=周六) */
export function toClassIslandWeekDay(dayOfWeek: number): number {
return dayOfWeek % 7;
}
@@ -5,10 +5,7 @@ import { booleanFlagSchema } from '../../lib/schemas.js';
export const notificationPrioritySchema = z.enum(['LOW', 'NORMAL', 'HIGH', 'URGENT']);
/** 本地日期(YYYY-MM-DD):按天归档/筛选用它,不要用 createdAt 的 UTC 切片 */
const dayKeySchema = z
.string()
.trim()
.refine(isDayKey, { message: '日期格式应为 YYYY-MM-DD' });
const dayKeySchema = z.string().trim().refine(isDayKey, { message: '日期格式应为 YYYY-MM-DD' });
export const listNotificationsQuerySchema = z.object({
classId: z.string().min(1).optional(),
@@ -52,14 +49,11 @@ export const notificationScopeQuerySchema = z.object({
/**
* 一次给多个班级发同一条通知(批量发布)。
*
* 上限 50 个班是刻意设的:批量发布是逐班串行落库 + 逐班推 ClassIsland,
* 上限 50 个班是刻意设的:批量发布是逐班串行落库与广播,
* 一次塞几百个班会长时间占住请求,也会把教室大屏刷屏。
*/
export const bulkCreateNotificationSchema = z.object({
classIds: z
.array(z.string().min(1))
.min(1, '请至少选择一个班级')
.max(50, '一次最多发布 50 个班级'),
classIds: z.array(z.string().min(1)).min(1, '请至少选择一个班级').max(50, '一次最多发布 50 个班级'),
title: z.string().trim().min(1, '请输入通知标题').max(120),
content: z.string().min(1, '请输入通知内容').max(5000),
priority: notificationPrioritySchema.optional(),
@@ -23,7 +23,6 @@ import { logger } from '../../lib/logger.js';
import { toNotificationDto } from '../../lib/mappers.js';
import { personalIdWhere, resolvePersonalIds } from '../../lib/session.js';
import { emitToClass } from '../../realtime/bus.js';
import { pushToClassIsland, shouldPushToClassIsland } from '../integrations/integrations.service.js';
import { computeClassStatus } from '../schedules/schedules.service.js';
import type { CreateNotificationInput } from './notifications.schemas.js';
@@ -94,7 +93,9 @@ export async function listNotifications(
take: 200,
});
return notifications.map((item) => toNotificationDto(item, { studentIds: personalIds, withStatus: isStaff }));
return notifications.map((item) =>
toNotificationDto(item, { studentIds: personalIds, withStatus: isStaff }),
);
}
/**
@@ -157,7 +158,7 @@ export async function listNotificationCreators(
/**
* 批量发布通知:一次给多个班级发同一条内容。
*
* 逐班串行调用 `createNotification`(复用同一套权限断言 + 上课保护 + 实时广播 + ClassIsland 推送),
* 逐班串行调用 `createNotification`(复用同一套权限断言 + 上课保护 + 实时广播),
* 某个班失败只记进结果,不影响其他班 —— 前端拿到逐班结果后自己决定怎么展示与重试。
*/
export async function bulkCreateNotifications(
@@ -235,61 +236,18 @@ export async function createNotification(
const dto = toNotificationDto(created, { withStatus: true });
emitToClass(created.classId, SOCKET_EVENTS.notificationNew, dto);
// 同一条通知也推到教室的 ClassIsland 上("老师发通知 → 教室大屏弹出"不该只在联动页生效)。
// 是否真的推送由**教室客户端**在设置页里选的显示位置决定(见 Class.notificationChannel):
// 选了"只弹 ClassHelper 客户端"就不打扰 ClassIsland。
await pushToClassIslandIfEnabled({
classId: created.classId,
title: created.title,
content: created.content,
priority,
createdBy: user.sub,
notificationId: created.id,
teacherName: created.creator?.name ?? created.creator?.username ?? null,
});
return dto;
}
/**
* 通知类发布入口的公共尾巴:按班级的显示位置决定要不要推 ClassIsland。
*
* 推失败**不能**影响通知本身已经发布成功这件事 —— 教室机器离线、插件没装都不该让老师收到 500,
* 因此这里把异常收敛成日志告警。
*/
async function pushToClassIslandIfEnabled(input: {
classId: string;
title: string;
content: string;
priority: string;
createdBy: string;
notificationId: string;
teacherName: string | null;
}): Promise<void> {
try {
if (!(await shouldPushToClassIsland(input.classId))) {
logger.info(`通知未推送 ClassIsland:班级=${input.classId} 已选择"只在 ClassHelper 客户端显示"`);
return;
}
await pushToClassIsland({
classId: input.classId,
title: input.title,
content: input.content,
urgent: input.priority === 'URGENT',
createdBy: input.createdBy,
notificationId: input.notificationId,
teacherName: input.teacherName,
});
} catch (error) {
logger.warn(`通知推送 ClassIsland 失败(通知本身已发布):${String(error)}`);
}
}
export async function deleteNotification(user: TokenPayload, notificationId: string): Promise<void> {
const current = await prisma.notification.findUnique({ where: { id: notificationId } });
if (!current) throw ApiError.notFound('通知不存在');
await assertCanPublishNotification(user, current.classId);
await prisma.notification.delete({ where: { id: notificationId } });
emitToClass(current.classId, SOCKET_EVENTS.notificationDeleted, {
id: notificationId,
classId: current.classId,
});
}
/**
@@ -30,7 +30,7 @@ router.get('/me', async (req, res) => {
/** GET /api/permissions/catalog - 权限键目录(权限页整棵勾选树的唯一来源) */
router.get('/catalog', requirePermission('permission:manage'), async (_req, res) => {
sendOk(res, permissionService.permissionCatalog(), '获取权限目录成功');
sendOk(res, await permissionService.permissionCatalog(), '获取权限目录成功');
});
/** GET /api/permissions/groups - 权限组列表 */
@@ -1,6 +1,5 @@
import {
PERMISSION_CATEGORIES,
PERMISSION_DEFAULT_ROLES,
PERMISSION_KEYS,
PERMISSION_LABELS,
ROLE_DEFAULT_PERMISSIONS,
@@ -18,7 +17,11 @@ import { prisma } from '../../lib/db.js';
import { ApiError } from '../../lib/http.js';
import type { TokenPayload } from '../../lib/jwt.js';
import { logger } from '../../lib/logger.js';
import { ADMIN_UNREMOVABLE_PERMISSIONS, loadEffectivePermissions } from '../../lib/permissions.js';
import {
ADMIN_UNREMOVABLE_PERMISSIONS,
ensureDefaultGroups,
loadEffectivePermissions,
} from '../../lib/permissions.js';
/**
* 权限组服务:组 / 键 / 成员三件事的全部读写都收在这里。
@@ -32,6 +35,7 @@ const GROUP_SELECT = {
name: true,
description: true,
builtin: true,
defaultRole: true,
createdAt: true,
updatedAt: true,
items: { select: { key: true } },
@@ -43,6 +47,7 @@ type GroupRow = {
name: string;
description: string;
builtin: boolean;
defaultRole: string | null;
createdAt: Date;
updatedAt: Date;
items: { key: string }[];
@@ -89,7 +94,11 @@ function toGroupDto(row: GroupRow): PermissionGroupDto {
name: row.name,
description: row.description,
builtin: row.builtin,
keys: row.items.map((item) => item.key).filter(knownKey).sort(byCatalogOrder),
defaultRole: row.defaultRole as UserRole | null,
keys: row.items
.map((item) => item.key)
.filter(knownKey)
.sort(byCatalogOrder),
memberCount: row._count.users,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
@@ -97,8 +106,19 @@ function toGroupDto(row: GroupRow): PermissionGroupDto {
}
/** GET /api/permissions/catalog - 权限键目录(权限页整棵勾选树都按它渲染) */
export function permissionCatalog(): PermissionCatalogDto {
export async function permissionCatalog(): Promise<PermissionCatalogDto> {
await ensureDefaultGroups();
const defaults = await prisma.permissionGroup.findMany({
where: { defaultRole: { not: null } },
include: { items: true },
});
const roles = Object.keys(ROLE_DEFAULT_PERMISSIONS) as UserRole[];
const keysForRole = (role: UserRole): PermissionKey[] => {
const keys =
defaults.find((group) => group.defaultRole === role)?.items.map((item) => item.key) ??
ROLE_DEFAULT_PERMISSIONS[role];
return normalizeKeys(role === 'ADMIN' ? [...keys, ...ADMIN_UNREMOVABLE_PERMISSIONS] : keys);
};
return {
keys: [...PERMISSION_KEYS],
labels: { ...PERMISSION_LABELS },
@@ -107,17 +127,19 @@ export function permissionCatalog(): PermissionCatalogDto {
keys: [...category.keys],
})),
defaultRoles: Object.fromEntries(
PERMISSION_KEYS.map((key) => [key, [...PERMISSION_DEFAULT_ROLES[key]]]),
PERMISSION_KEYS.map((key) => [key, roles.filter((role) => keysForRole(role).includes(key))]),
) as Record<PermissionKey, UserRole[]>,
roleDefaults: Object.fromEntries(
roles.map((role) => [role, [...ROLE_DEFAULT_PERMISSIONS[role]]]),
) as Record<UserRole, PermissionKey[]>,
roleDefaults: Object.fromEntries(roles.map((role) => [role, keysForRole(role)])) as Record<
UserRole,
PermissionKey[]
>,
unremovable: [...ADMIN_UNREMOVABLE_PERMISSIONS],
};
}
/** GET /api/permissions/groups - 权限组列表(内置组排在最前,其余按创建时间) */
export async function listGroups(): Promise<PermissionGroupDto[]> {
await ensureDefaultGroups();
const rows = await prisma.permissionGroup.findMany({
select: GROUP_SELECT,
orderBy: [{ builtin: 'desc' }, { createdAt: 'asc' }],
@@ -201,17 +223,12 @@ export async function deleteGroup(groupId: string): Promise<{ id: string }> {
// 键与成员关系都是 onDelete: Cascade,直接删组即可;
// 组内成员随后"没有任何分组",会回落角色默认模板(不会变成空权限)。
await prisma.permissionGroup.delete({ where: { id: groupId } });
logger.info(
`删除权限组「${current.name}」(原成员 ${current._count.users} 个,已回到角色默认权限)`,
);
logger.info(`删除权限组「${current.name}」(原成员 ${current._count.users} 个,已回到角色默认权限)`);
return { id: groupId };
}
/** 把一行 User(含分组关联)转成权限页用的成员 DTO */
function toMemberDto(
row: MemberRow,
keysOfGroup: Map<string, PermissionKey[]>,
): PermissionMemberDto {
function toMemberDto(row: MemberRow, keysOfGroup: Map<string, PermissionKey[]>): PermissionMemberDto {
const groupIds = row.permissionGroups.map((link) => link.groupId);
const union = new Set<PermissionKey>();
for (const groupId of groupIds) for (const key of keysOfGroup.get(groupId) ?? []) union.add(key);
@@ -231,7 +248,7 @@ function toMemberDto(
role,
groupIds,
permissionCount,
fixed: role === 'ADMIN',
fixed: false,
};
}
@@ -249,11 +266,27 @@ export async function listMembers(): Promise<PermissionMemberDto[]> {
const keysOfGroup = new Map<string, PermissionKey[]>(
groups.map((group) => [
group.id,
group.items.map((item) => item.key).filter(knownKey).sort(byCatalogOrder),
group.items
.map((item) => item.key)
.filter(knownKey)
.sort(byCatalogOrder),
]),
);
return (rows as MemberRow[]).map((row) => toMemberDto(row, keysOfGroup));
return Promise.all(
(rows as MemberRow[]).map(async (row) => ({
...toMemberDto(row, keysOfGroup),
permissionCount: (
await loadEffectivePermissions({
sub: row.id,
role: row.role as UserRole,
username: row.username,
name: row.name,
classId: null,
})
).size,
})),
);
}
/** PUT /api/permissions/users/:id/groups - 整体替换某账号的权限组 */
@@ -265,9 +298,6 @@ export async function assignUserGroups(
if (!user) throw ApiError.notFound('账号不存在');
const row = user as MemberRow;
if (row.role === 'ADMIN') {
throw ApiError.badRequest('管理员固定拥有全部权限,不需要(也不能)分配权限组');
}
if (row.role === 'CLASS_DEVICE') {
throw ApiError.badRequest(
'ClassHelper 班级端账号的能力由"班级内角色"决定(见权限矩阵),不参与权限组分配',
@@ -299,10 +329,24 @@ export async function assignUserGroups(
const keysOfGroup = new Map<string, PermissionKey[]>(
groups.map((group) => [
group.id,
group.items.map((item) => item.key).filter(knownKey).sort(byCatalogOrder),
group.items
.map((item) => item.key)
.filter(knownKey)
.sort(byCatalogOrder),
]),
);
return toMemberDto({ ...row, permissionGroups: groupIds.map((groupId) => ({ groupId })) }, keysOfGroup);
return {
...toMemberDto({ ...row, permissionGroups: groupIds.map((groupId) => ({ groupId })) }, keysOfGroup),
permissionCount: (
await loadEffectivePermissions({
sub: row.id,
role: row.role as UserRole,
username: row.username,
name: row.name,
classId: null,
})
).size,
};
}
/**
@@ -314,7 +358,7 @@ export async function assignUserGroups(
export async function myPermissions(user: TokenPayload): Promise<MyPermissionsDto> {
const permissions = await loadEffectivePermissions(user);
const fromGroups =
user.classSession || user.role === 'CLASS_DEVICE' || user.role === 'ADMIN'
user.classSession || user.role === 'CLASS_DEVICE'
? false
: (await prisma.userPermissionGroup.count({ where: { userId: user.sub } })) > 0;
-2
View File
@@ -10,7 +10,6 @@ import { dashboardModule } from './dashboard/dashboard.module.js';
import { gradesModule } from './grades/grades.module.js';
import { homeworksModule } from './homeworks/homeworks.module.js';
import { importsModule } from './imports/imports.module.js';
import { integrationsModule } from './integrations/integrations.module.js';
import { notificationsModule } from './notifications/notifications.module.js';
import { permissionsModule } from './permissions/permissions.module.js';
import { schedulesModule } from './schedules/schedules.module.js';
@@ -40,7 +39,6 @@ export const apiModules: ApiModule[] = [
permissionsModule,
callsModule,
importsModule,
integrationsModule,
gradesModule,
studentsModule,
systemModule,
@@ -47,7 +47,7 @@ export const createScheduleSchema = z
message: '结束时间必须晚于开始时间',
path: ['endTime'],
})
.refine((data) => (data.weekStart ?? 1) <= (data.weekEnd ?? 20), {
.refine((data) => data.weekEnd === undefined || (data.weekStart ?? 1) <= data.weekEnd, {
message: '起始周次不能大于结束周次',
path: ['weekEnd'],
});
@@ -115,6 +115,10 @@ export async function createSchedule(user: TokenPayload, input: CreateScheduleIn
await assertCanManageSchedule(user, input.classId);
await assertCourseInClass(input.courseId, input.classId);
const weekStart = input.weekStart ?? 1;
const weekEnd = input.weekEnd ?? termWeeks;
if (weekStart > weekEnd) throw ApiError.badRequest('起始周次不能大于结束周次');
const created = await prisma.schedule.create({
data: {
classId: input.classId,
@@ -123,8 +127,8 @@ export async function createSchedule(user: TokenPayload, input: CreateScheduleIn
startTime: input.startTime,
endTime: input.endTime,
location: input.location ?? null,
weekStart: input.weekStart ?? 1,
weekEnd: input.weekEnd ?? termWeeks,
weekStart,
weekEnd,
// 单双周:默认 ALL(每周),与旧数据行为一致
weekParity: input.weekParity ?? 'ALL',
},
@@ -1,7 +1,7 @@
import { Router } from 'express';
import { sendCreated, sendOk } from '../../lib/http.js';
import { idParamSchema } from '../../lib/schemas.js';
import { authenticate, getAuthUser, requirePermission } from '../../middleware/auth.js';
import { authenticate, getAuthUser, requirePermission, requireAnyPermission } from '../../middleware/auth.js';
import { validate, validatedParams, validatedQuery } from '../../middleware/validate.js';
import { defineModule } from '../module.types.js';
import {
@@ -33,7 +33,7 @@ router.use(authenticate());
*/
router.get(
'/',
requirePermission('roster:manage'),
requireAnyPermission('roster:read', 'roster:manage'),
validate({ query: listStudentsQuerySchema }),
async (req, res) => {
const user = getAuthUser(req);
@@ -45,7 +45,7 @@ router.get(
/** GET /api/students/transfers - 调班 / 转出历史(管理员看全部,也可按学生或班级过滤) */
router.get(
'/transfers',
requirePermission('roster:manage'),
requireAnyPermission('roster:read', 'roster:manage'),
validate({ query: listTransfersQuerySchema }),
async (req, res) => {
const user = getAuthUser(req);
@@ -2,6 +2,7 @@ import type { PaginatedResult, StudentDto, StudentTransferDto } from '@classhelp
import { normalizeStudentNo } from '@classhelper/shared';
import {
assertCanManageRoster,
assertClassAccess,
classScopeWhere,
isAdmin,
resolveClassScope,
@@ -33,10 +34,7 @@ import type {
const withClass = { class: { select: { name: true, grade: true } } } as const;
/** 学生名单(按班级权限过滤) */
export async function listStudents(
user: TokenPayload,
options: ListStudentsQuery,
): Promise<StudentDto[]> {
export async function listStudents(user: TokenPayload, options: ListStudentsQuery): Promise<StudentDto[]> {
const scope = await resolveClassScope(user, options.classId);
const students = await prisma.student.findMany({
@@ -178,7 +176,10 @@ export async function transferStudents(
// 注意传的是**调班前**的 movable(classId 还是原班级):历史里的"原班级"要按每条自己的来
const transfers = await recordTransfer(user, movable, null, input.toClassId, mode, input.note ?? '');
notifyClassChange(movable.map((item) => item.classId), input.toClassId);
notifyClassChange(
movable.map((item) => item.classId),
input.toClassId,
);
return { moved: movable.length, transfers };
}
@@ -229,7 +230,10 @@ export async function transferOutStudents(
})),
});
notifyClassChange(pending.map((item) => item.classId), null);
notifyClassChange(
pending.map((item) => item.classId),
null,
);
const created = await prisma.studentClassTransfer.findMany({
where: { studentId: { in: pending.map((item) => item.id) }, mode: 'transfer-out' },
@@ -248,11 +252,20 @@ export async function listTransfers(
throw ApiError.forbidden('查看全部调班历史需要管理员权限');
}
if (options.classId) await assertClassAccess(user, options.classId);
if (options.studentId) {
const student = await prisma.student.findUnique({
where: { id: options.studentId },
select: { classId: true },
});
if (!student) throw ApiError.notFound('学生不存在');
if (student.classId) await assertClassAccess(user, student.classId);
else if (!isAdmin(user)) throw ApiError.forbidden('无权查看未分班学生的调班历史');
}
const where = {
...(options.studentId ? { studentId: options.studentId } : {}),
...(options.classId
? { OR: [{ fromClassId: options.classId }, { toClassId: options.classId }] }
: {}),
...(options.classId ? { OR: [{ fromClassId: options.classId }, { toClassId: options.classId }] } : {}),
};
const page = options.page ?? 1;
@@ -320,7 +333,10 @@ async function recordTransfer(
async function loadClassNames(classIds: (string | null)[]): Promise<Map<string, string>> {
const ids = [...new Set(classIds.filter((id): id is string => Boolean(id)))];
if (ids.length === 0) return new Map();
const classes = await prisma.class.findMany({ where: { id: { in: ids } }, select: { id: true, name: true } });
const classes = await prisma.class.findMany({
where: { id: { in: ids } },
select: { id: true, name: true },
});
return new Map(classes.map((item) => [item.id, item.name]));
}
@@ -1,7 +1,7 @@
import { Router } from 'express';
import { sendCreated, sendOk } from '../../lib/http.js';
import { idParamSchema } from '../../lib/schemas.js';
import { authenticate, requirePermission } from '../../middleware/auth.js';
import { authenticate, requirePermission, requireAnyPermission } from '../../middleware/auth.js';
import { validate, validatedParams, validatedQuery } from '../../middleware/validate.js';
import { defineModule } from '../module.types.js';
import {
@@ -27,7 +27,7 @@ router.use(authenticate());
/** GET /api/teachers?keyword= - 教师列表(教师管理页 + 分配协作教师时使用) */
router.get(
'/',
requirePermission('teacher:manage'),
requireAnyPermission('teacher:read', 'teacher:manage'),
validate({ query: listTeachersQuerySchema }),
async (req, res) => {
const { keyword } = validatedQuery<{ keyword?: string }>(req);
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff. Show more