把 XH巡课 的当前可运行版本放进仓库,方便后续继续改并同步。
This commit is contained in:
commit
6e5107f1b6
134 files changed
+11284
No files matched your search
@@ -0,0 +1,14 @@
|
||||
---
|
||||
description: Spring Boot、数据库与 API 规范
|
||||
globs: backend/**/*.{java,yml,sql}
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# 后端
|
||||
|
||||
- Java 21,Spring Boot 3.5。公共响应使用 `ApiResponse`。业务错误抛 `BizException`。
|
||||
- DTO 使用 Jakarta Validation。列表接口必须分页,每页最多 100 条。
|
||||
- 写操作放在事务里。只读查询不要把大文件读进内存。
|
||||
- Flyway 是唯一建表方式。`ddl-auto` 保持 `validate`。新表要有外键、唯一约束和查询索引。
|
||||
- 学校数据默认按 `schoolId` 隔离。超级管理员除外。
|
||||
- 日志里不写密码、验证码、令牌、密钥和完整手机号。
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
description: Vue 3、TypeScript 与界面规范
|
||||
globs: frontend/**/*.{vue,ts,css}
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# 前端
|
||||
|
||||
- 使用 `<script setup lang="ts">`。路由懒加载。站点名称、颜色、注册开关来自 `useSiteStore`。
|
||||
- 摄像头和麦克风是两个独立列表,禁止合并成一个设备框。
|
||||
- 进入教室页不得自动打开摄像头或麦克风,必须由教师点击授权。
|
||||
- 离开直播页时断开 Room、停止轨道并关闭 AudioContext。
|
||||
- 接口错误、空数据和加载中都要有可见状态。
|
||||
- 家长页优先手机宽度,教师页按钮适合触摸,后台页优先信息密度。
|
||||
- 主题色默认 `#1677ff`,并支持深色模式。
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
description: XH巡课架构、代码规范与虚拟 Java 环境
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# XH巡课核心规则
|
||||
|
||||
- 项目是校园直播、巡课、回放的前后端分离网站。默认名称「XH巡课」,页面名称只读站点配置。
|
||||
- 技术栈:Vue 3 + TypeScript + Vite;Java 21 + Spring Boot 3.5;PostgreSQL、Redis、LiveKit、MinIO。
|
||||
- **禁止在宿主机安装 JDK 或修改系统 PATH。** Java 只存在于 Docker 镜像中。编译和测试用 `scripts/mvn.ps1`,运行用 `docker compose`。
|
||||
- 分层:Controller 只做入参和响应,业务在 Service,数据访问在 Repository。
|
||||
- 新功能必须接到现有权限模型。注册账号只能是家长,不能自动获得直播权限。
|
||||
- 关键业务数据进 PostgreSQL。Redis 只放验证码、刷新令牌、限流、短缓存和在线状态。
|
||||
- 不要提交密钥。本地口令只写在 `.env.example`,并标明必须更换。
|
||||
- 完成一个模块后更新 `docs/IMPLEMENTATION_STATUS.md`。未跑通的功能不能标成完成。
|
||||
- 改代码前先看真实文件。不要覆盖无关改动,不要删用户数据。
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
description: 隐私、权限与数据安全规范
|
||||
globs: backend/**/security/**,backend/**/user/**,backend/**/binding/**,frontend/src/stores/auth.ts,frontend/src/api/**,docker-compose.yml,.env.example
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# 安全
|
||||
|
||||
- 家长必须通过学生信息核对和管理员审核,直播与回放分开授权,可撤销。
|
||||
- 播放令牌短时有效。撤销授权后立刻拒绝新令牌,并把该身份移出 LiveKit 房间。
|
||||
- 密码用 BCrypt。SMTP 和短信密钥用 AES-GCM 后入库,接口不回传明文。
|
||||
- 登录、验证码和注册要限流。关闭注册时,接口和页面一起生效。
|
||||
- 生产环境若仍使用示例口令或模拟短信,必须拒绝启动或拒绝发送。
|
||||
- 课堂涉及未成年人:不采集隐藏录像,不对学生做自动识别或纪律评分。
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
description: 直播、录像与媒体性能规范
|
||||
globs: backend/**/live/**,backend/**/recording/**,frontend/src/composables/**,frontend/src/views/teacher/**,frontend/src/views/parent/**,frontend/src/views/inspect/**,deploy/**
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# 直播与录像
|
||||
|
||||
- 教师浏览器用 WebRTC 推到 LiveKit。家长只订阅,不与教师建点对点上传。
|
||||
- 房间名必须包含学校、班级和会话,不能复用到其他班级。
|
||||
- 发布成功并调用 ack 之后,会话才能变成 LIVE。
|
||||
- 切换设备用轨道替换,先停旧轨道再释放,不能叠两条音轨。
|
||||
- 录像走 LiveKit Egress 到 MinIO,后端不转发整段视频。回放用短时预签名地址。
|
||||
- 巡课墙默认静音,只在选中的一间教室开声音。
|
||||
- 没有实测数据时,不能宣称支持 300 路并发观看。
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
description: 测试、验收与性能测量规范
|
||||
globs: backend/src/test/**,frontend/src/**/*.spec.ts,scripts/**,docs/TEST_REPORT.md
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# 测试
|
||||
|
||||
- 权限、注册关闭、班级隔离、直播状态机、录像探针解析必须有自动化测试。
|
||||
- 后端测试在 Docker 里的 Maven 中运行,不依赖宿主机 Java。
|
||||
- 集成测试使用 Compose 里的 PostgreSQL 和 Redis,不改用内存库冒充。
|
||||
- 失败的测试要修代码或修测试数据,不能删断言。
|
||||
- 模拟短信、无摄像头和未跑的压力场景必须在 `docs/TEST_REPORT.md` 标明。
|
||||
- 性能优化前后保留同口径的测量结果。
|
||||
@@ -0,0 +1,16 @@
|
||||
# 本地示例。生产环境必须全部更换,并把 APP_PROD_GUARD 设为 true。
|
||||
DB_USER=xuenke
|
||||
DB_PASSWORD=xuenke
|
||||
JWT_SECRET=dev-only-change-this-jwt-secret-32b
|
||||
APP_ENCRYPTION_KEY=dev-only-change-this-encryption-key!!
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=ChangeMe_Admin_2026!
|
||||
LIVEKIT_API_KEY=devkey
|
||||
LIVEKIT_API_SECRET=devsecret_change_me_32_characters
|
||||
LIVEKIT_URL=ws://livekit:7880
|
||||
LIVEKIT_PUBLIC_URL=ws://localhost:7880
|
||||
MINIO_ACCESS_KEY=xuenke
|
||||
MINIO_SECRET_KEY=xuenke-minio-secret
|
||||
MINIO_BUCKET=xuenke-recordings
|
||||
APP_PROD_GUARD=false
|
||||
CORS_ORIGINS=http://localhost:5173,http://localhost,http://localhost:8088,http://localhost:18088
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
.env
|
||||
.env.local
|
||||
deploy/runtime/
|
||||
backend/target/
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/coverage/
|
||||
*.log
|
||||
.idea/
|
||||
.vscode/
|
||||
*.iml
|
||||
.toolchain/
|
||||
@@ -0,0 +1,26 @@
|
||||
# XH巡课
|
||||
|
||||
校园课堂直播、巡课和回放。Java 只在 Docker 里编译和运行,不要在 Windows 上安装 JDK。
|
||||
|
||||
## 本地命令
|
||||
|
||||
```powershell
|
||||
copy .env.example .env
|
||||
.\scripts\mvn.ps1 test
|
||||
cd frontend
|
||||
npm install
|
||||
npm test
|
||||
npm run dev
|
||||
```
|
||||
|
||||
前端开发服务器是 `http://localhost:5173`,接口代理到 `http://localhost:8080`。
|
||||
|
||||
完整堆栈:
|
||||
|
||||
```powershell
|
||||
docker compose --env-file .env up --build
|
||||
```
|
||||
|
||||
网站入口是 `http://localhost:8088`。初始管理员来自 `.env` 的 `ADMIN_USERNAME` 和 `ADMIN_PASSWORD`,示例口令只能用于本机。
|
||||
|
||||
浏览器要访问摄像头,请使用 `localhost`。跨公网观看 WebRTC 时,还要把 LiveKit 的节点 IP 和 TURN 配到学校网络,不能只打开 HTTPS。
|
||||
@@ -0,0 +1,17 @@
|
||||
FROM maven:3.9.11-eclipse-temurin-21 AS build
|
||||
WORKDIR /src
|
||||
COPY pom.xml .
|
||||
COPY src ./src
|
||||
RUN mvn -B -DskipTests package
|
||||
|
||||
FROM eclipse-temurin:21-jdk-jammy
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ffmpeg curl \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& useradd --system --uid 10001 app
|
||||
WORKDIR /app
|
||||
COPY --from=build /src/target/xuenke-*.jar /app/app.jar
|
||||
USER app
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=15s --timeout=3s --retries=12 CMD curl -fsS http://localhost:8080/actuator/health/liveness || exit 1
|
||||
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.5.16</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
<groupId>com.xh</groupId>
|
||||
<artifactId>xuenke</artifactId>
|
||||
<version>0.1.0</version>
|
||||
<name>xuenke</name>
|
||||
<description>XH巡课</description>
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
<jjwt.version>0.12.6</jjwt.version>
|
||||
<livekit.version>0.17.0</livekit.version>
|
||||
<minio.version>8.5.17</minio.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-websocket</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-mail</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-database-postgresql</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.livekit</groupId>
|
||||
<artifactId>livekit-server</artifactId>
|
||||
<version>${livekit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.minio</groupId>
|
||||
<artifactId>minio</artifactId>
|
||||
<version>${minio.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.xh.xunke;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@SpringBootApplication
|
||||
@ConfigurationPropertiesScan
|
||||
@EnableScheduling
|
||||
public class XunkeApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(XunkeApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.xh.xunke.audit;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "audit_logs")
|
||||
public class AuditLog {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private Long actorId;
|
||||
@Column(length = 64)
|
||||
private String actorName;
|
||||
@Column(nullable = false, length = 64)
|
||||
private String action;
|
||||
@Column(length = 64)
|
||||
private String resourceType;
|
||||
@Column(length = 64)
|
||||
private String resourceId;
|
||||
@Column(length = 1000)
|
||||
private String detail;
|
||||
@Column(length = 64)
|
||||
private String ip;
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@PrePersist
|
||||
void onCreate() {
|
||||
createdAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.xh.xunke.audit;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface AuditLogRepository extends JpaRepository<AuditLog, Long> {
|
||||
Page<AuditLog> findAllByOrderByIdDesc(Pageable pageable);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.xh.xunke.audit;
|
||||
|
||||
import com.xh.xunke.common.ClientInfo;
|
||||
import com.xh.xunke.security.UserPrincipal;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class AuditService {
|
||||
private final AuditLogRepository audits;
|
||||
private final LoginLogRepository logins;
|
||||
|
||||
public AuditService(AuditLogRepository audits, LoginLogRepository logins) {
|
||||
this.audits = audits;
|
||||
this.logins = logins;
|
||||
}
|
||||
|
||||
public void record(UserPrincipal actor, String action, String type, String resourceId, String detail, ClientInfo client) {
|
||||
AuditLog log = new AuditLog();
|
||||
if (actor != null) {
|
||||
log.setActorId(actor.id());
|
||||
log.setActorName(actor.username());
|
||||
}
|
||||
log.setAction(action);
|
||||
log.setResourceType(type);
|
||||
log.setResourceId(resourceId);
|
||||
log.setDetail(trim(detail));
|
||||
if (client != null) {
|
||||
log.setIp(client.ip());
|
||||
}
|
||||
audits.save(log);
|
||||
}
|
||||
|
||||
public void login(Long userId, String username, boolean success, String reason, ClientInfo client) {
|
||||
LoginLog log = new LoginLog();
|
||||
log.setUserId(userId);
|
||||
log.setUsername(username == null ? "" : username.substring(0, Math.min(64, username.length())));
|
||||
log.setSuccess(success);
|
||||
log.setReason(trim(reason));
|
||||
if (client != null) {
|
||||
log.setIp(client.ip());
|
||||
log.setUserAgent(client.userAgent());
|
||||
}
|
||||
logins.save(log);
|
||||
}
|
||||
|
||||
public Page<AuditLog> audits(Pageable pageable) {
|
||||
return audits.findAllByOrderByIdDesc(pageable);
|
||||
}
|
||||
|
||||
public Page<LoginLog> logins(Pageable pageable) {
|
||||
return logins.findAllByOrderByIdDesc(pageable);
|
||||
}
|
||||
|
||||
private String trim(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return value.length() <= 1000 ? value : value.substring(0, 1000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.xh.xunke.audit;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "login_logs")
|
||||
public class LoginLog {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private Long userId;
|
||||
@Column(nullable = false, length = 64)
|
||||
private String username;
|
||||
@Column(nullable = false)
|
||||
private boolean success;
|
||||
@Column(length = 64)
|
||||
private String ip;
|
||||
@Column(length = 255)
|
||||
private String userAgent;
|
||||
@Column(length = 128)
|
||||
private String reason;
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@PrePersist
|
||||
void onCreate() {
|
||||
createdAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.xh.xunke.audit;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface LoginLogRepository extends JpaRepository<LoginLog, Long> {
|
||||
Page<LoginLog> findAllByOrderByIdDesc(Pageable pageable);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.xh.xunke.common;
|
||||
|
||||
public record ApiResponse<T>(boolean success, String code, String message, T data) {
|
||||
public static <T> ApiResponse<T> ok(T data) {
|
||||
return new ApiResponse<>(true, "OK", "ok", data);
|
||||
}
|
||||
|
||||
public static ApiResponse<Void> ok() {
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> fail(String code, String message) {
|
||||
return new ApiResponse<>(false, code, message, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.xh.xunke.common;
|
||||
|
||||
public class BizException extends RuntimeException {
|
||||
private final ErrorCode errorCode;
|
||||
|
||||
public BizException(ErrorCode errorCode, String message) {
|
||||
super(message);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public ErrorCode errorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.xh.xunke.common;
|
||||
|
||||
import com.xh.xunke.security.RateLimitFilter;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
public record ClientInfo(String ip, String userAgent) {
|
||||
public static ClientInfo from(HttpServletRequest request) {
|
||||
String agent = request.getHeader("User-Agent");
|
||||
if (agent != null && agent.length() > 255) {
|
||||
agent = agent.substring(0, 255);
|
||||
}
|
||||
return new ClientInfo(RateLimitFilter.clientIp(request), agent);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.xh.xunke.common;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public enum ErrorCode {
|
||||
VALIDATION(HttpStatus.BAD_REQUEST),
|
||||
UNAUTHORIZED(HttpStatus.UNAUTHORIZED),
|
||||
FORBIDDEN(HttpStatus.FORBIDDEN),
|
||||
NOT_FOUND(HttpStatus.NOT_FOUND),
|
||||
CONFLICT(HttpStatus.CONFLICT),
|
||||
REGISTRATION_CLOSED(HttpStatus.FORBIDDEN),
|
||||
RATE_LIMIT(HttpStatus.TOO_MANY_REQUESTS),
|
||||
STATE(HttpStatus.CONFLICT),
|
||||
UPSTREAM(HttpStatus.BAD_GATEWAY);
|
||||
|
||||
private final HttpStatus status;
|
||||
|
||||
ErrorCode(HttpStatus status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public HttpStatus status() {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.xh.xunke.common;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(BizException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> biz(BizException ex) {
|
||||
return ResponseEntity.status(ex.errorCode().status())
|
||||
.body(ApiResponse.fail(ex.errorCode().name(), ex.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> invalid(MethodArgumentNotValidException ex) {
|
||||
String message = ex.getBindingResult().getFieldErrors().stream()
|
||||
.map(err -> err.getField() + " " + err.getDefaultMessage())
|
||||
.findFirst()
|
||||
.orElse("参数不正确");
|
||||
return ResponseEntity.badRequest().body(ApiResponse.fail(ErrorCode.VALIDATION.name(), message));
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> constraint(ConstraintViolationException ex) {
|
||||
return ResponseEntity.badRequest().body(ApiResponse.fail(ErrorCode.VALIDATION.name(), "参数不正确"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> denied(AccessDeniedException ex) {
|
||||
return ResponseEntity.status(403).body(ApiResponse.fail(ErrorCode.FORBIDDEN.name(), "没有权限"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(DataIntegrityViolationException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> conflict(DataIntegrityViolationException ex) {
|
||||
return ResponseEntity.status(409).body(ApiResponse.fail(ErrorCode.CONFLICT.name(), "数据冲突或仍被引用"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ApiResponse<Void>> unknown(Exception ex, HttpServletRequest request) {
|
||||
log.error("未处理异常 {} {}", request.getMethod(), request.getRequestURI(), ex);
|
||||
return ResponseEntity.status(500).body(ApiResponse.fail("INTERNAL", "服务器内部错误"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.xh.xunke.common;
|
||||
|
||||
public final class Masks {
|
||||
private Masks() {
|
||||
}
|
||||
|
||||
public static String phone(String phone) {
|
||||
if (phone == null || phone.length() < 7) {
|
||||
return "***";
|
||||
}
|
||||
return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
|
||||
}
|
||||
|
||||
public static String email(String email) {
|
||||
if (email == null || !email.contains("@")) {
|
||||
return "***";
|
||||
}
|
||||
int at = email.indexOf('@');
|
||||
String name = email.substring(0, at);
|
||||
String head = name.length() <= 1 ? "*" : name.substring(0, 1);
|
||||
return head + "***" + email.substring(at);
|
||||
}
|
||||
|
||||
public static String account(String value) {
|
||||
if (value != null && value.contains("@")) {
|
||||
return email(value);
|
||||
}
|
||||
if (value != null && value.chars().allMatch(Character::isDigit)) {
|
||||
return phone(value);
|
||||
}
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.xh.xunke.common;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record PagePayload<T>(List<T> items, long total, int page, int size) {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.xh.xunke.common;
|
||||
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
public final class Pages {
|
||||
private Pages() {
|
||||
}
|
||||
|
||||
public static Pageable of(int page, int size) {
|
||||
int safePage = Math.max(page, 0);
|
||||
int safeSize = Math.min(Math.max(size, 1), 100);
|
||||
return PageRequest.of(safePage, safeSize, Sort.by(Sort.Direction.DESC, "id"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.xh.xunke.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "app")
|
||||
public class AppProperties {
|
||||
private String jwtSecret;
|
||||
private int jwtAccessMinutes = 15;
|
||||
private int jwtRefreshDays = 7;
|
||||
private String encryptionKey;
|
||||
private String adminUsername;
|
||||
private String adminPassword;
|
||||
private String adminDisplayName = "系统管理员";
|
||||
private String livekitUrl;
|
||||
private String livekitKey;
|
||||
private String livekitSecret;
|
||||
private String minioEndpoint;
|
||||
private String minioPublicEndpoint;
|
||||
private String minioAccess;
|
||||
private String minioSecret;
|
||||
private String minioBucket;
|
||||
private String corsOrigins = "http://localhost:5173";
|
||||
private boolean prodGuard;
|
||||
private String ffprobePath = "ffprobe";
|
||||
private boolean cookieSecure;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.xh.xunke.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
public class AsyncConfig {
|
||||
@Bean(name = "mediaExecutor")
|
||||
public Executor mediaExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setThreadNamePrefix("media-");
|
||||
executor.setCorePoolSize(2);
|
||||
executor.setMaxPoolSize(8);
|
||||
executor.setQueueCapacity(100);
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.xh.xunke.config;
|
||||
|
||||
import com.xh.xunke.live.LiveStatusSocket;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocket;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSocket
|
||||
public class LiveSocketConfig implements WebSocketConfigurer {
|
||||
private final LiveStatusSocket socket;
|
||||
private final AppProperties props;
|
||||
|
||||
public LiveSocketConfig(LiveStatusSocket socket, AppProperties props) {
|
||||
this.socket = socket;
|
||||
this.props = props;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
||||
String[] origins = java.util.Arrays.stream(props.getCorsOrigins().split(","))
|
||||
.map(String::trim).filter(item -> !item.isEmpty()).toArray(String[]::new);
|
||||
registry.addHandler(socket, "/ws/events").setAllowedOrigins(origins);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.xh.xunke.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xh.xunke.common.ApiResponse;
|
||||
import com.xh.xunke.security.JwtAuthFilter;
|
||||
import com.xh.xunke.security.RateLimitFilter;
|
||||
import com.xh.xunke.security.StaffApiFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@EnableMethodSecurity
|
||||
public class SecurityConfig {
|
||||
private final JwtAuthFilter jwtAuthFilter;
|
||||
private final RateLimitFilter rateLimitFilter;
|
||||
private final AppProperties props;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public SecurityConfig(JwtAuthFilter jwtAuthFilter, RateLimitFilter rateLimitFilter,
|
||||
AppProperties props, ObjectMapper objectMapper) {
|
||||
this.jwtAuthFilter = jwtAuthFilter;
|
||||
this.rateLimitFilter = rateLimitFilter;
|
||||
this.props = props;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder(12);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http.csrf(AbstractHttpConfigurer::disable)
|
||||
.cors(Customizer.withDefaults())
|
||||
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.exceptionHandling(e -> e
|
||||
.authenticationEntryPoint((req, res, ex) -> write(res, 401, "UNAUTHORIZED", "请先登录"))
|
||||
.accessDeniedHandler((req, res, ex) -> write(res, 403, "FORBIDDEN", "没有权限")))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/actuator/health", "/actuator/health/**").permitAll()
|
||||
.requestMatchers(HttpMethod.POST,
|
||||
"/api/auth/login", "/api/auth/register", "/api/auth/email-code",
|
||||
"/api/auth/sms-code", "/api/auth/forgot-password", "/api/auth/reset-password",
|
||||
"/api/auth/refresh").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/auth/logout").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/public/**").permitAll()
|
||||
.requestMatchers("/ws/**").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/internal/livekit/webhook").permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.addFilterBefore(rateLimitFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(new StaffApiFilter(objectMapper), JwtAuthFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
config.setAllowedOrigins(Arrays.stream(props.getCorsOrigins().split(","))
|
||||
.map(String::trim).filter(s -> !s.isEmpty()).toList());
|
||||
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
|
||||
config.setAllowedHeaders(List.of("*"));
|
||||
config.setAllowCredentials(true);
|
||||
config.setMaxAge(3600L);
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
return source;
|
||||
}
|
||||
|
||||
private void write(jakarta.servlet.http.HttpServletResponse res, int status, String code, String message)
|
||||
throws java.io.IOException {
|
||||
res.setStatus(status);
|
||||
res.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
res.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
objectMapper.writeValue(res.getWriter(), ApiResponse.fail(code, message));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.xh.xunke.course;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "courses")
|
||||
public class Course {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long schoolId;
|
||||
@Column(nullable = false)
|
||||
private Long classId;
|
||||
@Column(nullable = false)
|
||||
private Long teacherId;
|
||||
@Column(nullable = false, length = 128)
|
||||
private String name;
|
||||
@Column(nullable = false)
|
||||
private boolean allowLive = true;
|
||||
@Column(nullable = false)
|
||||
private boolean allowRecord = true;
|
||||
@Column(length = 500)
|
||||
private String description;
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@PrePersist
|
||||
void onCreate() {
|
||||
createdAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.xh.xunke.course;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
public interface CourseRepository extends JpaRepository<Course, Long> {
|
||||
Page<Course> findBySchoolId(Long schoolId, Pageable pageable);
|
||||
|
||||
List<Course> findByClassId(Long classId);
|
||||
}
|
||||
|
||||
interface TimetableRepository extends JpaRepository<TimetableEntry, Long> {
|
||||
List<TimetableEntry> findByClassIdAndWeekday(Long classId, int weekday);
|
||||
|
||||
List<TimetableEntry> findBySchoolIdAndWeekday(Long schoolId, int weekday);
|
||||
|
||||
List<TimetableEntry> findByClassIdAndLessonDate(Long classId, LocalDate lessonDate);
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package com.xh.xunke.course;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import com.xh.xunke.common.PagePayload;
|
||||
import com.xh.xunke.common.Pages;
|
||||
import com.xh.xunke.school.SchoolService;
|
||||
import com.xh.xunke.security.UserPrincipal;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class CourseService {
|
||||
private final CourseRepository courses;
|
||||
private final PeriodRepository periods;
|
||||
private final TimetableRepository timetable;
|
||||
private final SchoolService schools;
|
||||
|
||||
public CourseService(CourseRepository courses, PeriodRepository periods, TimetableRepository timetable, SchoolService schools) {
|
||||
this.courses = courses;
|
||||
this.periods = periods;
|
||||
this.timetable = timetable;
|
||||
this.schools = schools;
|
||||
}
|
||||
|
||||
public record CourseRequest(@NotNull Long classId, @NotNull Long teacherId, @NotBlank String name,
|
||||
Boolean allowLive, Boolean allowRecord, String description) {
|
||||
}
|
||||
|
||||
public record PeriodRequest(@NotNull Long schoolId, @NotBlank String name, @NotBlank String startTime,
|
||||
@NotBlank String endTime, Integer sortOrder) {
|
||||
}
|
||||
|
||||
public record TimetableRequest(@NotNull Long classId, @NotNull Long courseId, @NotNull Long periodId,
|
||||
@NotNull Integer weekday, String lessonDate, String status, String note) {
|
||||
}
|
||||
|
||||
public PagePayload<Course> list(UserPrincipal me, int page, int size) {
|
||||
if (!me.superAdmin() && me.schoolId() == null) {
|
||||
return new PagePayload<>(java.util.List.of(), 0, page, size);
|
||||
}
|
||||
Long schoolId = me.superAdmin() ? null : me.schoolId();
|
||||
var result = schoolId == null ? courses.findAll(Pages.of(page, size)) : courses.findBySchoolId(schoolId, Pages.of(page, size));
|
||||
return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
public boolean shouldAutoStop(Long classId, Long courseId) {
|
||||
java.time.ZoneId zone = java.time.ZoneId.of("Asia/Shanghai");
|
||||
java.time.LocalTime now = java.time.LocalTime.now(zone);
|
||||
int weekday = java.time.LocalDate.now(zone).getDayOfWeek().getValue();
|
||||
for (TimetableEntry entry : timetable.findByClassIdAndWeekday(classId, weekday)) {
|
||||
if (!entry.getCourseId().equals(courseId) || "CANCELLED".equals(entry.getStatus())) {
|
||||
continue;
|
||||
}
|
||||
Period period = periods.findById(entry.getPeriodId()).orElse(null);
|
||||
if (period != null && now.isAfter(period.getEndTime())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Course create(UserPrincipal me, CourseRequest request) {
|
||||
var room = schools.requireClass(me, request.classId());
|
||||
if (!schools.teaches(room.getId(), request.teacherId()) && !me.superAdmin()) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "教师尚未分配到该班级");
|
||||
}
|
||||
Course course = new Course();
|
||||
course.setSchoolId(room.getSchoolId());
|
||||
course.setClassId(room.getId());
|
||||
course.setTeacherId(request.teacherId());
|
||||
course.setName(request.name().trim());
|
||||
course.setAllowLive(request.allowLive() == null || request.allowLive());
|
||||
course.setAllowRecord(request.allowRecord() == null || request.allowRecord());
|
||||
course.setDescription(request.description());
|
||||
return courses.save(course);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Course update(UserPrincipal me, Long id, CourseRequest request) {
|
||||
Course course = require(me, id);
|
||||
course.setName(request.name().trim());
|
||||
course.setTeacherId(request.teacherId());
|
||||
if (request.allowLive() != null) {
|
||||
course.setAllowLive(request.allowLive());
|
||||
}
|
||||
if (request.allowRecord() != null) {
|
||||
course.setAllowRecord(request.allowRecord());
|
||||
}
|
||||
course.setDescription(request.description());
|
||||
return courses.save(course);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void delete(UserPrincipal me, Long id) {
|
||||
courses.delete(require(me, id));
|
||||
}
|
||||
|
||||
public List<Period> periods(UserPrincipal me, Long schoolId) {
|
||||
Long scoped = me.superAdmin() ? schoolId : me.schoolId();
|
||||
if (scoped == null) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "请选择学校");
|
||||
}
|
||||
return periods.findBySchoolIdOrderBySortOrderAsc(scoped);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Period savePeriod(UserPrincipal me, PeriodRequest request, Long id) {
|
||||
Long schoolId = me.superAdmin() ? request.schoolId() : me.schoolId();
|
||||
Period period = id == null ? new Period() : periods.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "节次不存在"));
|
||||
if (id != null && !period.getSchoolId().equals(schoolId) && !me.superAdmin()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不能修改其他学校的节次");
|
||||
}
|
||||
period.setSchoolId(schoolId);
|
||||
period.setName(request.name().trim());
|
||||
period.setStartTime(LocalTime.parse(request.startTime()));
|
||||
period.setEndTime(LocalTime.parse(request.endTime()));
|
||||
period.setSortOrder(request.sortOrder() == null ? 0 : request.sortOrder());
|
||||
return periods.save(period);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deletePeriod(UserPrincipal me, Long id) {
|
||||
Period period = periods.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "节次不存在"));
|
||||
if (!me.superAdmin() && !period.getSchoolId().equals(me.schoolId())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不能删除其他学校的节次");
|
||||
}
|
||||
periods.delete(period);
|
||||
}
|
||||
|
||||
public List<TimetableEntry> week(UserPrincipal me, Long classId, Integer weekday) {
|
||||
schools.requireClass(me, classId);
|
||||
if (weekday == null) {
|
||||
List<TimetableEntry> all = new ArrayList<>();
|
||||
for (int day = 1; day <= 7; day++) {
|
||||
all.addAll(timetable.findByClassIdAndWeekday(classId, day));
|
||||
}
|
||||
return all;
|
||||
}
|
||||
return timetable.findByClassIdAndWeekday(classId, weekday);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public TimetableEntry saveEntry(UserPrincipal me, TimetableRequest request, Long id) {
|
||||
var room = schools.requireClass(me, request.classId());
|
||||
Course course = courses.findById(request.courseId()).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "课程不存在"));
|
||||
if (!course.getClassId().equals(room.getId())) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "课程不属于该班级");
|
||||
}
|
||||
if (request.weekday() < 1 || request.weekday() > 7) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "星期必须是 1 到 7");
|
||||
}
|
||||
TimetableEntry entry = id == null ? new TimetableEntry() : timetable.findById(id).orElseThrow();
|
||||
entry.setSchoolId(room.getSchoolId());
|
||||
entry.setClassId(room.getId());
|
||||
entry.setCourseId(course.getId());
|
||||
entry.setTeacherId(course.getTeacherId());
|
||||
entry.setPeriodId(request.periodId());
|
||||
entry.setWeekday(request.weekday());
|
||||
entry.setLessonDate(request.lessonDate() == null || request.lessonDate().isBlank() ? null : LocalDate.parse(request.lessonDate()));
|
||||
entry.setStatus(request.status() == null ? "ACTIVE" : request.status());
|
||||
entry.setNote(request.note());
|
||||
return timetable.save(entry);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<TimetableEntry> importCsv(UserPrincipal me, String csv) {
|
||||
List<TimetableEntry> saved = new ArrayList<>();
|
||||
String[] lines = csv.split("\\R");
|
||||
for (int i = 1; i < lines.length; i++) {
|
||||
if (lines[i].isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String[] cols = lines[i].split(",", -1);
|
||||
if (cols.length < 5) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "第 " + (i + 1) + " 行格式不正确");
|
||||
}
|
||||
TimetableRequest request = new TimetableRequest(Long.parseLong(cols[0].trim()), Long.parseLong(cols[1].trim()),
|
||||
Long.parseLong(cols[2].trim()), Integer.parseInt(cols[3].trim()), cols.length > 4 ? empty(cols[4]) : null,
|
||||
cols.length > 5 && !cols[5].isBlank() ? cols[5].trim() : "ACTIVE", cols.length > 6 ? empty(cols[6]) : null);
|
||||
saved.add(saveEntry(me, request, null));
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
public List<TimetableEntry> today(Long classId) {
|
||||
int weekday = LocalDate.now(java.time.ZoneId.of("Asia/Shanghai")).getDayOfWeek().getValue();
|
||||
LocalDate today = LocalDate.now(java.time.ZoneId.of("Asia/Shanghai"));
|
||||
List<TimetableEntry> entries = new ArrayList<>(timetable.findByClassIdAndWeekday(classId, weekday));
|
||||
entries.addAll(timetable.findByClassIdAndLessonDate(classId, today));
|
||||
return entries.stream().filter(entry -> !"CANCELLED".equals(entry.getStatus())).toList();
|
||||
}
|
||||
|
||||
private Course require(UserPrincipal me, Long id) {
|
||||
Course course = courses.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "课程不存在"));
|
||||
schools.requireClass(me, course.getClassId());
|
||||
return course;
|
||||
}
|
||||
|
||||
private String empty(String value) {
|
||||
String trimmed = value == null ? null : value.trim();
|
||||
return trimmed == null || trimmed.isEmpty() ? null : trimmed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.xh.xunke.course;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "periods")
|
||||
public class Period {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long schoolId;
|
||||
@Column(nullable = false, length = 32)
|
||||
private String name;
|
||||
@Column(nullable = false)
|
||||
private LocalTime startTime;
|
||||
@Column(nullable = false)
|
||||
private LocalTime endTime;
|
||||
@Column(nullable = false)
|
||||
private int sortOrder;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.xh.xunke.course;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PeriodRepository extends JpaRepository<Period, Long> {
|
||||
List<Period> findBySchoolIdOrderBySortOrderAsc(Long schoolId);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.xh.xunke.course;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "timetable_entries")
|
||||
public class TimetableEntry {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long schoolId;
|
||||
@Column(nullable = false)
|
||||
private Long classId;
|
||||
@Column(nullable = false)
|
||||
private Long courseId;
|
||||
@Column(nullable = false)
|
||||
private Long teacherId;
|
||||
@Column(nullable = false)
|
||||
private Long periodId;
|
||||
@Column(nullable = false)
|
||||
private int weekday;
|
||||
@Column(nullable = false, length = 20)
|
||||
private String status = "ACTIVE";
|
||||
private LocalDate lessonDate;
|
||||
@Column(length = 255)
|
||||
private String note;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.xh.xunke.inspection;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "inspection_records")
|
||||
public class InspectionRecord {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long schoolId;
|
||||
@Column(nullable = false)
|
||||
private Long classId;
|
||||
private Long courseId;
|
||||
private Long teacherId;
|
||||
@Column(nullable = false)
|
||||
private Long inspectorId;
|
||||
private Long sessionId;
|
||||
@Column(nullable = false)
|
||||
private Instant inspectedAt;
|
||||
@Column(length = 2000)
|
||||
private String situation;
|
||||
@Column(length = 2000)
|
||||
private String disciplineNote;
|
||||
@Column(length = 2000)
|
||||
private String remark;
|
||||
@Column(length = 2000)
|
||||
private String followUp;
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@PrePersist
|
||||
void onCreate() {
|
||||
if (inspectedAt == null) {
|
||||
inspectedAt = Instant.now();
|
||||
}
|
||||
createdAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.xh.xunke.inspection;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface InspectionRepository extends JpaRepository<InspectionRecord, Long> {
|
||||
Page<InspectionRecord> findBySchoolId(Long schoolId, Pageable pageable);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.xh.xunke.live;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
|
||||
public final class LiveAuthorization {
|
||||
public enum Kind { PUBLISH, SUBSCRIBE }
|
||||
|
||||
private LiveAuthorization() {
|
||||
}
|
||||
|
||||
public static Kind decide(boolean wantPublish, String status, boolean teacherOfSession,
|
||||
boolean schoolStaff, boolean parentLive) {
|
||||
boolean open = "LIVE".equals(status) || (wantPublish && "PREPARING".equals(status));
|
||||
if (!open) {
|
||||
throw new BizException(ErrorCode.STATE, "课堂未在直播");
|
||||
}
|
||||
if (wantPublish) {
|
||||
if (!teacherOfSession) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "只有本课教师可以推流");
|
||||
}
|
||||
return Kind.PUBLISH;
|
||||
}
|
||||
if (schoolStaff || parentLive) {
|
||||
return Kind.SUBSCRIBE;
|
||||
}
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "没有该班级的观看权限");
|
||||
}
|
||||
|
||||
public static String roomName(long schoolId, long classId, String unique) {
|
||||
return "xh-" + schoolId + "-" + classId + "-" + unique;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.xh.xunke.live;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import com.xh.xunke.config.AppProperties;
|
||||
import io.livekit.server.AccessToken;
|
||||
import io.livekit.server.CanPublish;
|
||||
import io.livekit.server.CanPublishData;
|
||||
import io.livekit.server.CanSubscribe;
|
||||
import io.livekit.server.LiveKitAPI;
|
||||
import io.livekit.server.RoomJoin;
|
||||
import io.livekit.server.RoomName;
|
||||
import io.livekit.server.WebhookReceiver;
|
||||
import livekit.LivekitEgress;
|
||||
import livekit.LivekitWebhook;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class LiveKitGateway {
|
||||
private static final Logger log = LoggerFactory.getLogger(LiveKitGateway.class);
|
||||
private final AppProperties props;
|
||||
private final LiveKitAPI api;
|
||||
private final WebhookReceiver receiver;
|
||||
|
||||
public LiveKitGateway(AppProperties props) {
|
||||
this.props = props;
|
||||
this.api = LiveKitAPI.createClient(props.getLivekitUrl(), props.getLivekitKey(), props.getLivekitSecret());
|
||||
this.receiver = new WebhookReceiver(props.getLivekitKey(), props.getLivekitSecret());
|
||||
}
|
||||
|
||||
public String token(String identity, String name, String room, boolean publish) {
|
||||
AccessToken token = new AccessToken(props.getLivekitKey(), props.getLivekitSecret());
|
||||
token.setIdentity(identity);
|
||||
token.setName(name);
|
||||
token.setTtl(publish ? 10 * 60 * 1000L : 5 * 60 * 1000L);
|
||||
token.addGrants(new RoomJoin(true), new RoomName(room), new CanPublish(publish),
|
||||
new CanSubscribe(true), new CanPublishData(publish));
|
||||
return token.toJwt();
|
||||
}
|
||||
|
||||
public void deleteRoom(String room) {
|
||||
try {
|
||||
api.getRoom().deleteRoom(room).execute();
|
||||
} catch (Exception ex) {
|
||||
log.warn("关闭 LiveKit 房间失败");
|
||||
}
|
||||
}
|
||||
|
||||
public void removeParticipant(String room, String identity) {
|
||||
try {
|
||||
api.getRoom().removeParticipant(room, identity).execute();
|
||||
} catch (Exception ex) {
|
||||
log.warn("移出直播参与者失败");
|
||||
}
|
||||
}
|
||||
|
||||
public String startEgress(String room, String objectKey) {
|
||||
try {
|
||||
LivekitEgress.S3Upload s3 = LivekitEgress.S3Upload.newBuilder()
|
||||
.setAccessKey(props.getMinioAccess())
|
||||
.setSecret(props.getMinioSecret())
|
||||
.setRegion("us-east-1")
|
||||
.setEndpoint(props.getMinioEndpoint())
|
||||
.setBucket(props.getMinioBucket())
|
||||
.setForcePathStyle(true)
|
||||
.build();
|
||||
LivekitEgress.EncodedFileOutput output = LivekitEgress.EncodedFileOutput.newBuilder()
|
||||
.setFileType(LivekitEgress.EncodedFileType.MP4)
|
||||
.setFilepath(objectKey)
|
||||
.setS3(s3)
|
||||
.build();
|
||||
var response = api.getEgress().startRoomCompositeEgress(room, output, "speaker",
|
||||
LivekitEgress.EncodingOptionsPreset.H264_720P_30).execute();
|
||||
if (!response.isSuccessful() || response.body() == null) {
|
||||
throw new BizException(ErrorCode.UPSTREAM, "录像任务启动失败");
|
||||
}
|
||||
return response.body().getEgressId();
|
||||
} catch (BizException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
log.warn("启动录像失败");
|
||||
throw new BizException(ErrorCode.UPSTREAM, "录像服务不可用");
|
||||
}
|
||||
}
|
||||
|
||||
public void stopEgress(String egressId) {
|
||||
if (egressId == null || egressId.isBlank()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
api.getEgress().stopEgress(egressId).execute();
|
||||
} catch (Exception ex) {
|
||||
log.warn("停止录像失败");
|
||||
}
|
||||
}
|
||||
|
||||
public LivekitWebhook.WebhookEvent receive(String body, String authorization) {
|
||||
try {
|
||||
return receiver.receive(body, authorization);
|
||||
} catch (Exception ex) {
|
||||
throw new BizException(ErrorCode.UNAUTHORIZED, "直播回调校验失败");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean reachable() {
|
||||
try {
|
||||
var response = api.getRoom().listRooms().execute();
|
||||
return response.isSuccessful();
|
||||
} catch (Exception ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.xh.xunke.live;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "live_sessions")
|
||||
public class LiveSession {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long schoolId;
|
||||
@Column(nullable = false)
|
||||
private Long classId;
|
||||
@Column(nullable = false)
|
||||
private Long courseId;
|
||||
@Column(nullable = false)
|
||||
private Long teacherId;
|
||||
@Column(nullable = false, unique = true, length = 160)
|
||||
private String roomName;
|
||||
@Column(nullable = false, length = 20)
|
||||
private String status;
|
||||
private Instant startedAt;
|
||||
private Instant endedAt;
|
||||
@Column(length = 32)
|
||||
private String endReason;
|
||||
private String videoDevice;
|
||||
private String audioDevice;
|
||||
@Column(nullable = false)
|
||||
private int viewerPeak;
|
||||
@Column(nullable = false)
|
||||
private boolean recordEnabled = true;
|
||||
private Instant lastHeartbeatAt;
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@PrePersist
|
||||
void onCreate() {
|
||||
createdAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.xh.xunke.live;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface LiveSessionRepository extends JpaRepository<LiveSession, Long> {
|
||||
Optional<LiveSession> findByClassIdAndStatusIn(Long classId, List<String> statuses);
|
||||
|
||||
Page<LiveSession> findBySchoolIdAndStatus(Long schoolId, String status, Pageable pageable);
|
||||
|
||||
Page<LiveSession> findByStatus(String status, Pageable pageable);
|
||||
|
||||
List<LiveSession> findByStatusIn(List<String> statuses);
|
||||
|
||||
long countByStatus(String status);
|
||||
|
||||
long countByStatusAndSchoolId(String status, Long schoolId);
|
||||
|
||||
@Query("select s from LiveSession s where s.startedAt >= :start and (:schoolId is null or s.schoolId = :schoolId)")
|
||||
List<LiveSession> startedSince(Instant start, Long schoolId);
|
||||
|
||||
List<LiveSession> findByTeacherIdAndStatusIn(Long teacherId, List<String> statuses);
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package com.xh.xunke.live;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import com.xh.xunke.common.PagePayload;
|
||||
import com.xh.xunke.common.Pages;
|
||||
import com.xh.xunke.course.Course;
|
||||
import com.xh.xunke.course.CourseRepository;
|
||||
import com.xh.xunke.course.CourseService;
|
||||
import com.xh.xunke.recording.RecordingService;
|
||||
import com.xh.xunke.school.BindingService;
|
||||
import com.xh.xunke.school.School;
|
||||
import com.xh.xunke.school.SchoolRepository;
|
||||
import com.xh.xunke.school.SchoolService;
|
||||
import com.xh.xunke.security.AccessGuard;
|
||||
import com.xh.xunke.security.UserPrincipal;
|
||||
import com.xh.xunke.settings.SettingsService;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class LiveSessionService {
|
||||
private final LiveSessionRepository sessions;
|
||||
private final CourseRepository courses;
|
||||
private final SchoolRepository schools;
|
||||
private final SchoolService schoolService;
|
||||
private final BindingService bindings;
|
||||
private final LiveKitGateway liveKit;
|
||||
private final RecordingService recordings;
|
||||
private final SettingsService settings;
|
||||
private final AccessGuard guard;
|
||||
private final StringRedisTemplate redis;
|
||||
private final CourseService courseService;
|
||||
|
||||
public LiveSessionService(LiveSessionRepository sessions, CourseRepository courses, SchoolRepository schools,
|
||||
SchoolService schoolService, BindingService bindings, LiveKitGateway liveKit,
|
||||
RecordingService recordings, SettingsService settings, AccessGuard guard,
|
||||
StringRedisTemplate redis, CourseService courseService) {
|
||||
this.sessions = sessions;
|
||||
this.courses = courses;
|
||||
this.schools = schools;
|
||||
this.schoolService = schoolService;
|
||||
this.bindings = bindings;
|
||||
this.liveKit = liveKit;
|
||||
this.recordings = recordings;
|
||||
this.settings = settings;
|
||||
this.guard = guard;
|
||||
this.redis = redis;
|
||||
this.courseService = courseService;
|
||||
}
|
||||
|
||||
public record StartRequest(@NotNull Long classId, @NotNull Long courseId, String videoDevice, String audioDevice) {
|
||||
}
|
||||
|
||||
public record TokenView(String url, String token, String roomName, String role, Long sessionId) {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Map<String, Object> start(UserPrincipal me, StartRequest request) {
|
||||
if (!schoolService.teaches(request.classId(), me.id()) && !me.superAdmin()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "你不是该班级的任课教师");
|
||||
}
|
||||
var room = schoolService.requireClass(me.superAdmin() ? me : me, request.classId());
|
||||
School school = schools.findById(room.getSchoolId()).orElseThrow();
|
||||
if (!"ACTIVE".equals(school.getStatus()) || !school.isLiveEnabled()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "学校未开放直播");
|
||||
}
|
||||
Course course = courses.findById(request.courseId()).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "课程不存在"));
|
||||
if (!course.getClassId().equals(room.getId()) || !course.isAllowLive()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "该课程不允许直播");
|
||||
}
|
||||
if (sessions.findByClassIdAndStatusIn(room.getId(), List.of("PREPARING", "LIVE")).isPresent()) {
|
||||
throw new BizException(ErrorCode.CONFLICT, "该班级已有进行中的直播");
|
||||
}
|
||||
LiveSession session = new LiveSession();
|
||||
session.setSchoolId(school.getId());
|
||||
session.setClassId(room.getId());
|
||||
session.setCourseId(course.getId());
|
||||
session.setTeacherId(me.id());
|
||||
session.setRoomName(LiveAuthorization.roomName(school.getId(), room.getId(), UUID.randomUUID().toString()));
|
||||
session.setStatus("PREPARING");
|
||||
session.setVideoDevice(request.videoDevice());
|
||||
session.setAudioDevice(request.audioDevice());
|
||||
session.setRecordEnabled(course.isAllowRecord() && school.isRecordEnabled());
|
||||
session.setLastHeartbeatAt(Instant.now());
|
||||
sessions.save(session);
|
||||
String token = liveKit.token("u-" + me.id(), me.displayName(), session.getRoomName(), true);
|
||||
return Map.of("session", session, "url", settings.text("site.name.zh", "XH巡课") == null ? "" : liveUrl(),
|
||||
"livekitUrl", liveUrl(), "token", token);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LiveSession ack(UserPrincipal me, Long id) {
|
||||
LiveSession session = requireTeacherSession(me, id);
|
||||
if (!"PREPARING".equals(session.getStatus())) {
|
||||
throw new BizException(ErrorCode.STATE, "直播状态不允许确认推流");
|
||||
}
|
||||
session.setStatus("LIVE");
|
||||
session.setStartedAt(Instant.now());
|
||||
session.setLastHeartbeatAt(Instant.now());
|
||||
sessions.save(session);
|
||||
if (session.isRecordEnabled()) {
|
||||
recordings.begin(session);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LiveSession heartbeat(UserPrincipal me, Long id) {
|
||||
LiveSession session = requireTeacherSession(me, id);
|
||||
session.setLastHeartbeatAt(Instant.now());
|
||||
return sessions.save(session);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LiveSession stop(UserPrincipal me, Long id, String reason) {
|
||||
LiveSession session = sessions.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "直播不存在"));
|
||||
boolean teacher = session.getTeacherId().equals(me.id());
|
||||
if (!teacher) {
|
||||
guard.checkSchool(me, session.getSchoolId());
|
||||
if (!me.schoolStaff() && !me.superAdmin()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不能结束这场直播");
|
||||
}
|
||||
}
|
||||
return finish(session, reason == null ? "MANUAL" : reason);
|
||||
}
|
||||
|
||||
public TokenView token(UserPrincipal me, Long id, boolean publish) {
|
||||
LiveSession session = sessions.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "直播不存在"));
|
||||
boolean teacher = session.getTeacherId().equals(me.id()) && schoolService.teaches(session.getClassId(), me.id());
|
||||
boolean staff = me.superAdmin() || (me.schoolStaff() && session.getSchoolId().equals(me.schoolId()));
|
||||
boolean parentLive = bindings.parentCan(me.id(), session.getClassId(), false);
|
||||
LiveAuthorization.Kind kind = LiveAuthorization.decide(publish, session.getStatus(), teacher, staff, parentLive);
|
||||
boolean canPublish = kind == LiveAuthorization.Kind.PUBLISH;
|
||||
String token = liveKit.token("u-" + me.id(), me.displayName(), session.getRoomName(), canPublish);
|
||||
return new TokenView(liveUrl(), token, session.getRoomName(), kind.name(), session.getId());
|
||||
}
|
||||
|
||||
public int touchViewer(UserPrincipal me, Long id) {
|
||||
LiveSession session = sessions.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "直播不存在"));
|
||||
token(me, id, false);
|
||||
String key = "viewers:" + id;
|
||||
redis.opsForHash().put(key, String.valueOf(me.id()), String.valueOf(Instant.now().getEpochSecond()));
|
||||
int count = countViewers(id);
|
||||
if (count > session.getViewerPeak()) {
|
||||
session.setViewerPeak(count);
|
||||
sessions.save(session);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
public PagePayload<LiveSession> list(UserPrincipal me, String status, int page, int size) {
|
||||
String wanted = status == null ? "LIVE" : status;
|
||||
if (!me.superAdmin() && !me.schoolStaff() && !me.canTeach()) {
|
||||
var result = sessions.findByStatus(wanted, Pages.of(page, size));
|
||||
var allowed = result.getContent().stream()
|
||||
.filter(session -> bindings.parentCan(me.id(), session.getClassId(), false))
|
||||
.toList();
|
||||
return new PagePayload<>(allowed, allowed.size(), result.getNumber(), result.getSize());
|
||||
}
|
||||
if (!me.superAdmin() && me.schoolId() == null) {
|
||||
return new PagePayload<>(java.util.List.of(), 0, page, size);
|
||||
}
|
||||
var result = me.superAdmin()
|
||||
? sessions.findByStatus(wanted, Pages.of(page, size))
|
||||
: sessions.findBySchoolIdAndStatus(me.schoolId(), wanted, Pages.of(page, size));
|
||||
return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
public LiveSession get(UserPrincipal me, Long id) {
|
||||
LiveSession session = sessions.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "直播不存在"));
|
||||
if (!me.superAdmin() && !session.getSchoolId().equals(me.schoolId()) && !bindings.parentCan(me.id(), session.getClassId(), false)
|
||||
&& !session.getTeacherId().equals(me.id())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不能查看该直播");
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void sweep() {
|
||||
Instant now = Instant.now();
|
||||
int disconnect = settings.integer("live.disconnectSeconds", 60);
|
||||
int prepare = settings.integer("live.prepareTimeoutSeconds", 120);
|
||||
int maxMinutes = settings.integer("live.maxMinutes", 120);
|
||||
for (LiveSession session : sessions.findByStatusIn(List.of("PREPARING", "LIVE"))) {
|
||||
if ("PREPARING".equals(session.getStatus()) && session.getCreatedAt().plusSeconds(prepare).isBefore(now)) {
|
||||
finish(session, "PREPARE_TIMEOUT");
|
||||
continue;
|
||||
}
|
||||
if ("LIVE".equals(session.getStatus())) {
|
||||
Instant beat = session.getLastHeartbeatAt() == null ? session.getStartedAt() : session.getLastHeartbeatAt();
|
||||
if (beat != null && beat.plusSeconds(disconnect).isBefore(now)) {
|
||||
finish(session, "DISCONNECT");
|
||||
continue;
|
||||
}
|
||||
if (session.getStartedAt() != null && session.getStartedAt().plusSeconds(maxMinutes * 60L).isBefore(now)) {
|
||||
finish(session, "MAX_DURATION");
|
||||
continue;
|
||||
}
|
||||
if (courseService.shouldAutoStop(session.getClassId(), session.getCourseId())) {
|
||||
finish(session, "COURSE_END");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int countViewers(Long sessionId) {
|
||||
Map<Object, Object> viewers = redis.opsForHash().entries("viewers:" + sessionId);
|
||||
long now = Instant.now().getEpochSecond();
|
||||
int count = 0;
|
||||
for (var entry : viewers.entrySet()) {
|
||||
long seen = Long.parseLong(String.valueOf(entry.getValue()));
|
||||
if (now - seen <= 40) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
public long liveCount(Long schoolId) {
|
||||
return schoolId == null ? sessions.countByStatus("LIVE") : sessions.countByStatusAndSchoolId("LIVE", schoolId);
|
||||
}
|
||||
|
||||
private LiveSession requireTeacherSession(UserPrincipal me, Long id) {
|
||||
LiveSession session = sessions.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "直播不存在"));
|
||||
if (!session.getTeacherId().equals(me.id()) && !me.superAdmin()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不是这场直播的教师");
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
private LiveSession finish(LiveSession session, String reason) {
|
||||
if ("ENDED".equals(session.getStatus()) || "FORCED_STOP".equals(session.getStatus())) {
|
||||
return session;
|
||||
}
|
||||
session.setStatus("ADMIN".equals(reason) || "FORCED".equals(reason) ? "FORCED_STOP" : "ENDED");
|
||||
session.setEndReason(reason);
|
||||
session.setEndedAt(Instant.now());
|
||||
sessions.save(session);
|
||||
recordings.finish(session);
|
||||
liveKit.deleteRoom(session.getRoomName());
|
||||
return session;
|
||||
}
|
||||
|
||||
private String liveUrl() {
|
||||
return System.getenv().getOrDefault("LIVEKIT_PUBLIC_URL", "ws://localhost:7880");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.xh.xunke.live;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xh.xunke.security.JwtService;
|
||||
import com.xh.xunke.user.UserRepository;
|
||||
import com.xh.xunke.user.UserStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.CloseStatus;
|
||||
import org.springframework.web.socket.TextMessage;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Component
|
||||
public class LiveStatusSocket extends TextWebSocketHandler {
|
||||
private final JwtService jwtService;
|
||||
private final UserRepository users;
|
||||
private final LiveSessionRepository sessions;
|
||||
private final ObjectMapper json;
|
||||
private final Set<WebSocketSession> clients = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public LiveStatusSocket(JwtService jwtService, UserRepository users, LiveSessionRepository sessions, ObjectMapper json) {
|
||||
this.jwtService = jwtService;
|
||||
this.users = users;
|
||||
this.sessions = sessions;
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
|
||||
String query = session.getUri() == null ? "" : String.valueOf(session.getUri().getQuery());
|
||||
String token = query.replaceFirst(".*token=", "").split("&")[0];
|
||||
io.jsonwebtoken.Claims claims;
|
||||
try {
|
||||
claims = jwtService.parse(token);
|
||||
} catch (RuntimeException ex) {
|
||||
session.close(CloseStatus.NOT_ACCEPTABLE);
|
||||
return;
|
||||
}
|
||||
var user = users.findById(Long.parseLong(claims.getSubject())).orElse(null);
|
||||
Integer version = claims.get("tv", Integer.class);
|
||||
if (user == null || user.getStatus() != UserStatus.ACTIVE || version == null || version != user.getTokenVersion()) {
|
||||
session.close(CloseStatus.NOT_ACCEPTABLE);
|
||||
return;
|
||||
}
|
||||
clients.add(session);
|
||||
sendSnapshot(session);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
|
||||
sendSnapshot(session);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
|
||||
clients.remove(session);
|
||||
}
|
||||
|
||||
private void sendSnapshot(WebSocketSession session) throws Exception {
|
||||
long live = sessions.countByStatus("LIVE");
|
||||
session.sendMessage(new TextMessage(json.writeValueAsString(Map.of("type", "status", "liveNow", live))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.xh.xunke.notify;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class AliyunSigner {
|
||||
private AliyunSigner() {
|
||||
}
|
||||
|
||||
public static String sign(Map<String, String> params, String accessKeySecret) {
|
||||
String canonical = params.entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.map(entry -> encode(entry.getKey()) + "=" + encode(entry.getValue()))
|
||||
.collect(Collectors.joining("&"));
|
||||
String toSign = "GET&" + encode("/") + "&" + encode(canonical);
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA1");
|
||||
mac.init(new SecretKeySpec((accessKeySecret + "&").getBytes(StandardCharsets.UTF_8), "HmacSHA1"));
|
||||
return Base64.getEncoder().encodeToString(mac.doFinal(toSign.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException("阿里云签名失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
static String encode(String value) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
|
||||
for (byte b : bytes) {
|
||||
int c = b & 0xff;
|
||||
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|
||||
|| c == '-' || c == '_' || c == '.' || c == '~') {
|
||||
out.append((char) c);
|
||||
} else {
|
||||
out.append('%');
|
||||
out.append(Character.toUpperCase(Character.forDigit(c >> 4, 16)));
|
||||
out.append(Character.toUpperCase(Character.forDigit(c & 0xf, 16)));
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.xh.xunke.notify;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "notification_logs")
|
||||
public class NotificationLog {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false, length = 16)
|
||||
private String channel;
|
||||
@Column(nullable = false, length = 128)
|
||||
private String targetMask;
|
||||
@Column(length = 64)
|
||||
private String templateCode;
|
||||
@Column(nullable = false)
|
||||
private boolean success;
|
||||
@Column(length = 500)
|
||||
private String errorMessage;
|
||||
@Column(nullable = false)
|
||||
private boolean simulated;
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@PrePersist
|
||||
void onCreate() {
|
||||
createdAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
package com.xh.xunke.notify;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import com.xh.xunke.common.Masks;
|
||||
import com.xh.xunke.common.PagePayload;
|
||||
import com.xh.xunke.common.Pages;
|
||||
import com.xh.xunke.config.AppProperties;
|
||||
import com.xh.xunke.security.SecretCipher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
@Service
|
||||
public class NotificationService {
|
||||
private static final Logger log = LoggerFactory.getLogger(NotificationService.class);
|
||||
private static final DateTimeFormatter ALIYUN_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
|
||||
.withZone(ZoneOffset.UTC);
|
||||
private final SmtpRepository smtpRepository;
|
||||
private final SmsRepository smsRepository;
|
||||
private final TemplateRepository templates;
|
||||
private final NotificationLogRepository logs;
|
||||
private final SecretCipher cipher;
|
||||
private final StringRedisTemplate redis;
|
||||
private final AppProperties props;
|
||||
private final ObjectMapper json;
|
||||
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
|
||||
|
||||
public NotificationService(SmtpRepository smtpRepository, SmsRepository smsRepository,
|
||||
TemplateRepository templates, NotificationLogRepository logs,
|
||||
SecretCipher cipher, StringRedisTemplate redis, AppProperties props, ObjectMapper json) {
|
||||
this.smtpRepository = smtpRepository;
|
||||
this.smsRepository = smsRepository;
|
||||
this.templates = templates;
|
||||
this.logs = logs;
|
||||
this.cipher = cipher;
|
||||
this.redis = redis;
|
||||
this.props = props;
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
public record CodeSend(boolean simulated, String debugCode) {
|
||||
}
|
||||
|
||||
public CodeSend sendVerification(String channel, String target, String purpose) {
|
||||
String lockKey = "code:lock:" + purpose + ":" + target;
|
||||
Boolean first = redis.opsForValue().setIfAbsent(lockKey, "1", Duration.ofSeconds(60));
|
||||
if (!Boolean.TRUE.equals(first)) {
|
||||
throw new BizException(ErrorCode.RATE_LIMIT, "验证码发送过于频繁");
|
||||
}
|
||||
String code = String.format("%06d", ThreadLocalRandom.current().nextInt(1_000_000));
|
||||
String codeKey = codeKey(purpose, target);
|
||||
redis.opsForValue().set(codeKey, code, Duration.ofMinutes(5));
|
||||
try {
|
||||
boolean simulated = "sms".equals(channel)
|
||||
? sendSms(target, "验证码 " + code, "REGISTER_CODE", Map.of("code", code))
|
||||
: sendMail(target, purpose.equals("RESET") ? "RESET_CODE" : "REGISTER_CODE", Map.of("code", code));
|
||||
return new CodeSend(simulated, simulated && !props.isProdGuard() ? code : null);
|
||||
} catch (RuntimeException ex) {
|
||||
redis.delete(lockKey);
|
||||
redis.delete(codeKey);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean verify(String purpose, String target, String code) {
|
||||
if (code == null || target == null) {
|
||||
return false;
|
||||
}
|
||||
String key = codeKey(purpose, target);
|
||||
String expected = redis.opsForValue().get(key);
|
||||
if (expected == null) {
|
||||
return false;
|
||||
}
|
||||
boolean matches = MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), code.getBytes(StandardCharsets.UTF_8));
|
||||
if (matches) {
|
||||
redis.delete(key);
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
|
||||
public void notify(String channel, String target, String templateCode, Map<String, String> vars) {
|
||||
try {
|
||||
if ("sms".equals(channel)) {
|
||||
sendSms(target, render(templateBody(templateCode), vars), templateCode, vars);
|
||||
} else if (target != null && !target.isBlank()) {
|
||||
sendMail(target, templateCode, vars);
|
||||
}
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn("通知发送失败 template={} reason={}", templateCode, ex.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean sendMail(String to, String templateCode, Map<String, String> vars) {
|
||||
SmtpSettings settings = smtpRepository.findById((short) 1).orElseThrow();
|
||||
NotificationTemplate template = templates.findById(templateCode).orElse(null);
|
||||
String subject = template == null ? "XH巡课通知" : render(template.getSubject(), vars);
|
||||
String body = template == null ? render("验证码 {{code}}", vars) : render(template.getBody(), vars);
|
||||
if (!settings.isEnabled()) {
|
||||
if (props.isProdGuard()) {
|
||||
failLog("mail", to, templateCode, false, "邮件服务未启用");
|
||||
throw new BizException(ErrorCode.UPSTREAM, "邮件服务未启用");
|
||||
}
|
||||
log.info("模拟邮件已接收 target={}", Masks.email(to));
|
||||
okLog("mail", to, templateCode, true);
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
JavaMailSenderImpl sender = new JavaMailSenderImpl();
|
||||
sender.setHost(settings.getHost());
|
||||
sender.setPort(settings.getPort() == null ? 465 : settings.getPort());
|
||||
sender.setUsername(settings.getUsername());
|
||||
sender.setPassword(cipher.decrypt(settings.getPasswordCipher()));
|
||||
Properties mailProps = sender.getJavaMailProperties();
|
||||
mailProps.put("mail.smtp.auth", "true");
|
||||
mailProps.put("mail.smtp.ssl.enable", Boolean.toString(settings.isSslEnabled()));
|
||||
mailProps.put("mail.smtp.starttls.enable", Boolean.toString(settings.isStarttls()));
|
||||
mailProps.put("mail.smtp.connectiontimeout", "5000");
|
||||
mailProps.put("mail.smtp.timeout", "5000");
|
||||
SimpleMailMessage message = new SimpleMailMessage();
|
||||
message.setFrom(settings.getFromName() == null ? settings.getFromAddress()
|
||||
: settings.getFromName() + " <" + settings.getFromAddress() + ">");
|
||||
message.setTo(to);
|
||||
message.setSubject(subject);
|
||||
message.setText(body);
|
||||
sender.send(message);
|
||||
okLog("mail", to, templateCode, false);
|
||||
return false;
|
||||
} catch (RuntimeException ex) {
|
||||
failLog("mail", to, templateCode, false, "发送失败");
|
||||
throw new BizException(ErrorCode.UPSTREAM, "邮件发送失败");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean sendSms(String phone, String text, String templateCode, Map<String, String> vars) {
|
||||
SmsSettings settings = smsRepository.findById((short) 1).orElseThrow();
|
||||
if (!settings.isEnabled()) {
|
||||
if (props.isProdGuard()) {
|
||||
throw new BizException(ErrorCode.UPSTREAM, "短信服务未启用");
|
||||
}
|
||||
log.info("模拟短信已接收 target={}", Masks.phone(phone));
|
||||
okLog("sms", phone, templateCode, true);
|
||||
return true;
|
||||
}
|
||||
if (props.isProdGuard() && "simulated".equals(settings.getProvider())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "生产环境不能使用模拟短信");
|
||||
}
|
||||
try {
|
||||
switch (settings.getProvider()) {
|
||||
case "aliyun" -> sendAliyun(settings, phone, vars.getOrDefault("code", text));
|
||||
case "tencent" -> sendTencent(settings, phone, vars.getOrDefault("code", text));
|
||||
case "http" -> sendCustom(settings, phone, vars.getOrDefault("code", text));
|
||||
case "simulated" -> log.info("模拟短信已接收 target={}", Masks.phone(phone));
|
||||
default -> throw new BizException(ErrorCode.VALIDATION, "未知短信服务商");
|
||||
}
|
||||
boolean simulated = "simulated".equals(settings.getProvider());
|
||||
okLog("sms", phone, templateCode, simulated);
|
||||
return simulated;
|
||||
} catch (BizException ex) {
|
||||
failLog("sms", phone, templateCode, false, ex.getMessage());
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
failLog("sms", phone, templateCode, false, "发送失败");
|
||||
throw new BizException(ErrorCode.UPSTREAM, "短信发送失败");
|
||||
}
|
||||
}
|
||||
|
||||
public void testMail(String to) {
|
||||
sendMail(to, "REGISTER_CODE", Map.of("code", "000000"));
|
||||
}
|
||||
|
||||
public void testSms(String phone) {
|
||||
sendSms(phone, "000000", "REGISTER_CODE", Map.of("code", "000000"));
|
||||
}
|
||||
|
||||
public SmtpSettings smtp() {
|
||||
return smtpRepository.findById((short) 1).orElseThrow();
|
||||
}
|
||||
|
||||
public SmsSettings sms() {
|
||||
return smsRepository.findById((short) 1).orElseThrow();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SmtpSettings saveSmtp(SmtpSettings incoming, String plainPassword) {
|
||||
SmtpSettings current = smtp();
|
||||
current.setHost(incoming.getHost());
|
||||
current.setPort(incoming.getPort());
|
||||
current.setUsername(incoming.getUsername());
|
||||
current.setSslEnabled(incoming.isSslEnabled());
|
||||
current.setStarttls(incoming.isStarttls());
|
||||
current.setFromAddress(incoming.getFromAddress());
|
||||
current.setFromName(incoming.getFromName());
|
||||
current.setEnabled(incoming.isEnabled());
|
||||
if (plainPassword != null && !plainPassword.isBlank()) {
|
||||
current.setPasswordCipher(cipher.encrypt(plainPassword));
|
||||
}
|
||||
return smtpRepository.save(current);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SmsSettings saveSms(SmsSettings incoming, String accessKey, String secret) {
|
||||
SmsSettings current = sms();
|
||||
current.setProvider(incoming.getProvider());
|
||||
current.setApiUrl(incoming.getApiUrl());
|
||||
current.setSignName(incoming.getSignName());
|
||||
current.setTemplateId(incoming.getTemplateId());
|
||||
current.setRegion(incoming.getRegion());
|
||||
current.setSdkAppId(incoming.getSdkAppId());
|
||||
current.setEnabled(incoming.isEnabled());
|
||||
if (accessKey != null && !accessKey.isBlank()) {
|
||||
current.setAccessKeyCipher(cipher.encrypt(accessKey));
|
||||
}
|
||||
if (secret != null && !secret.isBlank()) {
|
||||
current.setSecretCipher(cipher.encrypt(secret));
|
||||
}
|
||||
return smsRepository.save(current);
|
||||
}
|
||||
|
||||
public List<NotificationTemplate> listTemplates() {
|
||||
return templates.findAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public NotificationTemplate saveTemplate(NotificationTemplate incoming) {
|
||||
NotificationTemplate current = templates.findById(incoming.getCode()).orElse(incoming);
|
||||
current.setCode(incoming.getCode());
|
||||
current.setChannel(incoming.getChannel());
|
||||
current.setSubject(incoming.getSubject());
|
||||
current.setBody(incoming.getBody());
|
||||
current.setUpdatedAt(Instant.now());
|
||||
return templates.save(current);
|
||||
}
|
||||
|
||||
public PagePayload<NotificationLog> logs(int page, int size) {
|
||||
var result = logs.findAllByOrderByIdDesc(Pages.of(page, size));
|
||||
return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
private void sendAliyun(SmsSettings settings, String phone, String code) throws Exception {
|
||||
String accessKey = required(cipher.decrypt(settings.getAccessKeyCipher()), "短信 AccessKey");
|
||||
String secret = required(cipher.decrypt(settings.getSecretCipher()), "短信密钥");
|
||||
Map<String, String> params = new TreeMap<>();
|
||||
params.put("AccessKeyId", accessKey);
|
||||
params.put("Action", "SendSms");
|
||||
params.put("Format", "JSON");
|
||||
params.put("PhoneNumbers", phone);
|
||||
params.put("RegionId", settings.getRegion() == null ? "cn-hangzhou" : settings.getRegion());
|
||||
params.put("SignName", required(settings.getSignName(), "短信签名"));
|
||||
params.put("SignatureMethod", "HMAC-SHA1");
|
||||
params.put("SignatureNonce", UUID.randomUUID().toString());
|
||||
params.put("SignatureVersion", "1.0");
|
||||
params.put("TemplateCode", required(settings.getTemplateId(), "短信模板"));
|
||||
params.put("TemplateParam", json.writeValueAsString(Map.of("code", code)));
|
||||
params.put("Timestamp", ALIYUN_TIME.format(Instant.now()));
|
||||
params.put("Version", "2017-05-25");
|
||||
params.put("Signature", AliyunSigner.sign(params, secret));
|
||||
String query = params.entrySet().stream()
|
||||
.map(entry -> url(entry.getKey()) + "=" + url(entry.getValue()))
|
||||
.reduce((a, b) -> a + "&" + b).orElse("");
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create("https://dysmsapi.aliyuncs.com/?" + query))
|
||||
.timeout(Duration.ofSeconds(8)).GET().build();
|
||||
HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() >= 300 || response.body() == null || !response.body().contains("\"Code\":\"OK\"")) {
|
||||
throw new BizException(ErrorCode.UPSTREAM, "阿里云短信发送失败");
|
||||
}
|
||||
}
|
||||
|
||||
private void sendTencent(SmsSettings settings, String phone, String code) throws Exception {
|
||||
String secretId = required(cipher.decrypt(settings.getAccessKeyCipher()), "短信 SecretId");
|
||||
String secretKey = required(cipher.decrypt(settings.getSecretCipher()), "短信 SecretKey");
|
||||
String region = settings.getRegion() == null ? "ap-guangzhou" : settings.getRegion();
|
||||
String number = phone.startsWith("+") ? phone : "+86" + phone;
|
||||
String payload = json.writeValueAsString(new LinkedHashMap<>(Map.of(
|
||||
"PhoneNumberSet", List.of(number),
|
||||
"SmsSdkAppId", required(settings.getSdkAppId(), "SdkAppId"),
|
||||
"SignName", required(settings.getSignName(), "短信签名"),
|
||||
"TemplateId", required(settings.getTemplateId(), "短信模板"),
|
||||
"TemplateParamSet", List.of(code))));
|
||||
long now = Instant.now().getEpochSecond();
|
||||
TencentSmsSigner.Signed signed = TencentSmsSigner.sign(secretId, secretKey, region, payload, now);
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create("https://sms.tencentcloudapi.com"))
|
||||
.timeout(Duration.ofSeconds(8))
|
||||
.header("Authorization", signed.authorization())
|
||||
.header("Content-Type", "application/json; charset=utf-8")
|
||||
.header("Host", "sms.tencentcloudapi.com")
|
||||
.header("X-TC-Action", "SendSms")
|
||||
.header("X-TC-Timestamp", signed.timestamp())
|
||||
.header("X-TC-Version", "2021-01-11")
|
||||
.header("X-TC-Region", region)
|
||||
.POST(HttpRequest.BodyPublishers.ofString(payload))
|
||||
.build();
|
||||
HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() >= 300 || response.body() == null || response.body().contains("Error")) {
|
||||
throw new BizException(ErrorCode.UPSTREAM, "腾讯云短信发送失败");
|
||||
}
|
||||
}
|
||||
|
||||
private void sendCustom(SmsSettings settings, String phone, String code) throws Exception {
|
||||
String secret = cipher.decrypt(settings.getSecretCipher());
|
||||
String payload = json.writeValueAsString(Map.of(
|
||||
"phone", phone,
|
||||
"sign", settings.getSignName() == null ? "" : settings.getSignName(),
|
||||
"templateId", settings.getTemplateId() == null ? "" : settings.getTemplateId(),
|
||||
"params", Map.of("code", code)));
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(required(settings.getApiUrl(), "短信接口地址")))
|
||||
.timeout(Duration.ofSeconds(8))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(payload));
|
||||
if (secret != null && !secret.isBlank()) {
|
||||
builder.header("Authorization", "Bearer " + secret);
|
||||
}
|
||||
HttpResponse<String> response = http.send(builder.build(), HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() >= 300) {
|
||||
throw new BizException(ErrorCode.UPSTREAM, "自定义短信接口发送失败");
|
||||
}
|
||||
}
|
||||
|
||||
private String templateBody(String code) {
|
||||
return templates.findById(code).map(NotificationTemplate::getBody).orElse("{{code}}");
|
||||
}
|
||||
|
||||
static String render(String template, Map<String, String> vars) {
|
||||
if (template == null) {
|
||||
return "";
|
||||
}
|
||||
String rendered = template;
|
||||
for (var entry : vars.entrySet()) {
|
||||
rendered = rendered.replace("{{" + entry.getKey() + "}}", escape(entry.getValue()));
|
||||
}
|
||||
return rendered;
|
||||
}
|
||||
|
||||
private static String escape(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
return value.replace("&", "&").replace("<", "<").replace(">", ">");
|
||||
}
|
||||
|
||||
private void okLog(String channel, String target, String template, boolean simulated) {
|
||||
writeLog(channel, target, template, true, null, simulated);
|
||||
}
|
||||
|
||||
private void failLog(String channel, String target, String template, boolean simulated, String error) {
|
||||
writeLog(channel, target, template, false, error, simulated);
|
||||
}
|
||||
|
||||
private void writeLog(String channel, String target, String template, boolean success, String error, boolean simulated) {
|
||||
NotificationLog row = new NotificationLog();
|
||||
row.setChannel(channel);
|
||||
row.setTargetMask(target != null && target.contains("@") ? Masks.email(target) : Masks.phone(target));
|
||||
row.setTemplateCode(template);
|
||||
row.setSuccess(success);
|
||||
row.setErrorMessage(error);
|
||||
row.setSimulated(simulated);
|
||||
logs.save(row);
|
||||
}
|
||||
|
||||
private static String required(String value, String label) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new BizException(ErrorCode.VALIDATION, label + "未配置");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String codeKey(String purpose, String target) {
|
||||
return "code:" + purpose + ":" + target;
|
||||
}
|
||||
|
||||
private static String url(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.xh.xunke.notify;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "notification_templates")
|
||||
public class NotificationTemplate {
|
||||
@Id
|
||||
@Column(length = 64)
|
||||
private String code;
|
||||
@Column(nullable = false, length = 16)
|
||||
private String channel;
|
||||
private String subject;
|
||||
@Column(nullable = false)
|
||||
private String body;
|
||||
@Column(nullable = false)
|
||||
private Instant updatedAt = Instant.now();
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.xh.xunke.notify;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
interface SmtpRepository extends JpaRepository<SmtpSettings, Short> {
|
||||
}
|
||||
|
||||
interface SmsRepository extends JpaRepository<SmsSettings, Short> {
|
||||
}
|
||||
|
||||
interface TemplateRepository extends JpaRepository<NotificationTemplate, String> {
|
||||
}
|
||||
|
||||
interface NotificationLogRepository extends JpaRepository<NotificationLog, Long> {
|
||||
Page<NotificationLog> findAllByOrderByIdDesc(Pageable pageable);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.xh.xunke.notify;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "sms_settings")
|
||||
public class SmsSettings {
|
||||
@Id
|
||||
private Short id = 1;
|
||||
@Column(nullable = false, length = 32)
|
||||
private String provider = "simulated";
|
||||
private String apiUrl;
|
||||
private String accessKeyCipher;
|
||||
private String secretCipher;
|
||||
private String signName;
|
||||
private String templateId;
|
||||
private String region;
|
||||
private String sdkAppId;
|
||||
@Column(nullable = false)
|
||||
private boolean enabled;
|
||||
@Column(nullable = false)
|
||||
private Instant updatedAt = Instant.now();
|
||||
|
||||
@PrePersist
|
||||
@PreUpdate
|
||||
void touch() {
|
||||
updatedAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.xh.xunke.notify;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "smtp_settings")
|
||||
public class SmtpSettings {
|
||||
@Id
|
||||
private Short id = 1;
|
||||
private String host;
|
||||
private Integer port;
|
||||
private String username;
|
||||
private String passwordCipher;
|
||||
@Column(nullable = false)
|
||||
private boolean sslEnabled = true;
|
||||
@Column(nullable = false)
|
||||
private boolean starttls = true;
|
||||
private String fromAddress;
|
||||
private String fromName;
|
||||
@Column(nullable = false)
|
||||
private boolean enabled;
|
||||
@Column(nullable = false)
|
||||
private Instant updatedAt = Instant.now();
|
||||
|
||||
@PrePersist
|
||||
@PreUpdate
|
||||
void touch() {
|
||||
updatedAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.xh.xunke.notify;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
|
||||
public final class TencentSmsSigner {
|
||||
private TencentSmsSigner() {
|
||||
}
|
||||
|
||||
public record Signed(String authorization, String timestamp) {
|
||||
}
|
||||
|
||||
public static Signed sign(String secretId, String secretKey, String region, String payload, long epochSeconds) {
|
||||
try {
|
||||
String timestamp = Long.toString(epochSeconds);
|
||||
String date = java.time.Instant.ofEpochSecond(epochSeconds)
|
||||
.atZone(java.time.ZoneOffset.UTC).toLocalDate().toString();
|
||||
String hashedPayload = sha256(payload);
|
||||
String canonical = "POST\n/\n\ncontent-type:application/json; charset=utf-8\nhost:sms.tencentcloudapi.com\n\n"
|
||||
+ "content-type;host\n" + hashedPayload;
|
||||
String credentialScope = date + "/sms/tc3_request";
|
||||
String toSign = "TC3-HMAC-SHA256\n" + timestamp + "\n" + credentialScope + "\n" + sha256(canonical);
|
||||
byte[] secretDate = hmac(("TC3" + secretKey).getBytes(StandardCharsets.UTF_8), date);
|
||||
byte[] secretService = hmac(secretDate, "sms");
|
||||
byte[] secretSigning = hmac(secretService, "tc3_request");
|
||||
String signature = HexFormat.of().formatHex(hmac(secretSigning, toSign));
|
||||
String authorization = "TC3-HMAC-SHA256 Credential=" + secretId + "/" + credentialScope
|
||||
+ ", SignedHeaders=content-type;host, Signature=" + signature;
|
||||
return new Signed(authorization, timestamp);
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException("腾讯云签名失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static String sha256(String value) throws Exception {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
private static byte[] hmac(byte[] key, String value) throws Exception {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key, "HmacSHA256"));
|
||||
return mac.doFinal(value.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.xh.xunke.recording;
|
||||
|
||||
import com.xh.xunke.config.AppProperties;
|
||||
import io.minio.BucketExistsArgs;
|
||||
import io.minio.GetPresignedObjectUrlArgs;
|
||||
import io.minio.MakeBucketArgs;
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.RemoveObjectArgs;
|
||||
import io.minio.StatObjectArgs;
|
||||
import io.minio.http.Method;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Component
|
||||
public class ObjectStorage {
|
||||
private static final Logger log = LoggerFactory.getLogger(ObjectStorage.class);
|
||||
private final AppProperties props;
|
||||
private final MinioClient internal;
|
||||
private final MinioClient browser;
|
||||
|
||||
public ObjectStorage(AppProperties props) {
|
||||
this.props = props;
|
||||
this.internal = client(props.getMinioEndpoint(), props);
|
||||
this.browser = client(props.getMinioPublicEndpoint(), props);
|
||||
}
|
||||
|
||||
public void ensureBucket() {
|
||||
try {
|
||||
String bucket = props.getMinioBucket();
|
||||
if (!internal.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) {
|
||||
internal.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.warn("对象存储暂不可用,登录和课程查询不受影响");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean reachable() {
|
||||
try {
|
||||
internal.bucketExists(BucketExistsArgs.builder().bucket(props.getMinioBucket()).build());
|
||||
return true;
|
||||
} catch (Exception ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public String presignPlayback(String key, int minutes) {
|
||||
return sign(browser, key, minutes);
|
||||
}
|
||||
|
||||
public String presignInternal(String key, int minutes) {
|
||||
return sign(internal, key, minutes);
|
||||
}
|
||||
|
||||
public boolean exists(String key) {
|
||||
try {
|
||||
internal.statObject(StatObjectArgs.builder().bucket(props.getMinioBucket()).object(key).build());
|
||||
return true;
|
||||
} catch (Exception ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(String key) {
|
||||
try {
|
||||
internal.removeObject(RemoveObjectArgs.builder().bucket(props.getMinioBucket()).object(key).build());
|
||||
} catch (Exception ex) {
|
||||
log.warn("删除录像对象失败");
|
||||
}
|
||||
}
|
||||
|
||||
private String sign(MinioClient client, String key, int minutes) {
|
||||
try {
|
||||
return client.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
|
||||
.method(Method.GET)
|
||||
.bucket(props.getMinioBucket())
|
||||
.object(key)
|
||||
.expiry(minutes, TimeUnit.MINUTES)
|
||||
.build());
|
||||
} catch (Exception ex) {
|
||||
throw new com.xh.xunke.common.BizException(com.xh.xunke.common.ErrorCode.UPSTREAM, "无法生成回放地址");
|
||||
}
|
||||
}
|
||||
|
||||
private static MinioClient client(String endpoint, AppProperties props) {
|
||||
return MinioClient.builder()
|
||||
.endpoint(endpoint)
|
||||
.credentials(props.getMinioAccess(), props.getMinioSecret())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.xh.xunke.recording;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public final class ProbeParser {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
private ProbeParser() {
|
||||
}
|
||||
|
||||
public record Result(boolean video, boolean audio) {
|
||||
}
|
||||
|
||||
public static Result parse(String body) {
|
||||
try {
|
||||
JsonNode streams = JSON.readTree(body).path("streams");
|
||||
boolean video = false;
|
||||
boolean audio = false;
|
||||
if (streams.isArray()) {
|
||||
for (JsonNode stream : streams) {
|
||||
String type = stream.path("codec_type").asText("");
|
||||
if ("video".equals(type)) {
|
||||
video = true;
|
||||
} else if ("audio".equals(type)) {
|
||||
audio = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Result(video, audio);
|
||||
} catch (Exception ex) {
|
||||
return new Result(false, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.xh.xunke.recording;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "recordings")
|
||||
public class Recording {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long sessionId;
|
||||
@Column(nullable = false)
|
||||
private Long schoolId;
|
||||
@Column(nullable = false)
|
||||
private Long classId;
|
||||
private String egressId;
|
||||
@Column(nullable = false, length = 32)
|
||||
private String status;
|
||||
private String bucket;
|
||||
private String objectKey;
|
||||
private Long fileSize;
|
||||
private Integer durationSeconds;
|
||||
private Boolean hasVideo;
|
||||
private Boolean hasAudio;
|
||||
@Column(length = 1000)
|
||||
private String errorMessage;
|
||||
@Column(nullable = false)
|
||||
private int retryCount;
|
||||
private Instant startedAt;
|
||||
private Instant endedAt;
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
@Column(nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
@PrePersist
|
||||
void onCreate() {
|
||||
Instant now = Instant.now();
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
void onUpdate() {
|
||||
updatedAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.xh.xunke.recording;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface RecordingRepository extends JpaRepository<Recording, Long> {
|
||||
Optional<Recording> findFirstBySessionIdOrderByIdDesc(Long sessionId);
|
||||
|
||||
Page<Recording> findBySchoolId(Long schoolId, Pageable pageable);
|
||||
|
||||
Page<Recording> findByClassId(Long classId, Pageable pageable);
|
||||
|
||||
List<Recording> findByStatusAndEndedAtBefore(String status, Instant endedBefore);
|
||||
|
||||
long countByStatus(String status);
|
||||
|
||||
@Query("select coalesce(sum(r.fileSize), 0) from Recording r where r.status = 'COMPLETED' and (:schoolId is null or r.schoolId = :schoolId)")
|
||||
long sumSize(Long schoolId);
|
||||
|
||||
long countByStatusAndSchoolId(String status, Long schoolId);
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package com.xh.xunke.recording;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import com.xh.xunke.common.PagePayload;
|
||||
import com.xh.xunke.common.Pages;
|
||||
import com.xh.xunke.config.AppProperties;
|
||||
import com.xh.xunke.live.LiveKitGateway;
|
||||
import com.xh.xunke.live.LiveSession;
|
||||
import com.xh.xunke.live.LiveSessionRepository;
|
||||
import com.xh.xunke.school.BindingService;
|
||||
import com.xh.xunke.school.SchoolRepository;
|
||||
import com.xh.xunke.security.UserPrincipal;
|
||||
import livekit.LivekitWebhook;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
public class RecordingService {
|
||||
private static final Logger log = LoggerFactory.getLogger(RecordingService.class);
|
||||
private final RecordingRepository recordings;
|
||||
private final LiveSessionRepository sessions;
|
||||
private final LiveKitGateway liveKit;
|
||||
private final ObjectStorage storage;
|
||||
private final BindingService bindings;
|
||||
private final SchoolRepository schools;
|
||||
private final AppProperties props;
|
||||
|
||||
public RecordingService(RecordingRepository recordings, LiveSessionRepository sessions, LiveKitGateway liveKit,
|
||||
ObjectStorage storage, BindingService bindings, SchoolRepository schools, AppProperties props) {
|
||||
this.recordings = recordings;
|
||||
this.sessions = sessions;
|
||||
this.liveKit = liveKit;
|
||||
this.storage = storage;
|
||||
this.bindings = bindings;
|
||||
this.schools = schools;
|
||||
this.props = props;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Recording begin(LiveSession session) {
|
||||
Recording recording = new Recording();
|
||||
recording.setSessionId(session.getId());
|
||||
recording.setSchoolId(session.getSchoolId());
|
||||
recording.setClassId(session.getClassId());
|
||||
recording.setStatus("PENDING");
|
||||
recording.setBucket(props.getMinioBucket());
|
||||
recording.setObjectKey("recordings/" + session.getSchoolId() + "/" + session.getClassId()
|
||||
+ "/" + session.getId() + ".mp4");
|
||||
recording.setStartedAt(Instant.now());
|
||||
recordings.save(recording);
|
||||
try {
|
||||
String egressId = liveKit.startEgress(session.getRoomName(), recording.getObjectKey());
|
||||
recording.setEgressId(egressId);
|
||||
recording.setStatus("RECORDING");
|
||||
} catch (RuntimeException ex) {
|
||||
recording.setStatus("FAILED");
|
||||
recording.setErrorMessage("录像服务启动失败");
|
||||
}
|
||||
return recordings.save(recording);
|
||||
}
|
||||
|
||||
public void finish(LiveSession session) {
|
||||
recordings.findFirstBySessionIdOrderByIdDesc(session.getId()).ifPresent(recording -> {
|
||||
if ("RECORDING".equals(recording.getStatus()) || "PENDING".equals(recording.getStatus())) {
|
||||
liveKit.stopEgress(recording.getEgressId());
|
||||
recording.setStatus("PROCESSING");
|
||||
recording.setEndedAt(Instant.now());
|
||||
recordings.save(recording);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void onWebhook(String body, String authorization) {
|
||||
LivekitWebhook.WebhookEvent event = liveKit.receive(body, authorization);
|
||||
if (event.getEgressInfo() == null || event.getEgressInfo().getEgressId().isBlank()) {
|
||||
return;
|
||||
}
|
||||
String egressId = event.getEgressInfo().getEgressId();
|
||||
recordings.findAll().stream()
|
||||
.filter(item -> egressId.equals(item.getEgressId()))
|
||||
.findFirst()
|
||||
.ifPresent(recording -> {
|
||||
String name = event.getEvent();
|
||||
if ("egress_ended".equals(name) || "egress_complete".equals(name) || name.contains("ended")) {
|
||||
recording.setStatus("PROCESSING");
|
||||
recording.setEndedAt(Instant.now());
|
||||
if (event.getEgressInfo().getFileResultsCount() > 0) {
|
||||
recording.setFileSize(event.getEgressInfo().getFileResults(0).getSize());
|
||||
recording.setDurationSeconds((int) event.getEgressInfo().getFileResults(0).getDuration());
|
||||
}
|
||||
recordings.save(recording);
|
||||
probeLater(recording.getId());
|
||||
} else if (name.contains("failed") || name.contains("aborted")) {
|
||||
recording.setStatus("FAILED");
|
||||
recording.setErrorMessage("录像任务失败");
|
||||
recording.setEndedAt(Instant.now());
|
||||
recordings.save(recording);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Async("mediaExecutor")
|
||||
public void probeLater(Long recordingId) {
|
||||
Recording recording = recordings.findById(recordingId).orElse(null);
|
||||
if (recording == null || recording.getObjectKey() == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String url = storage.presignInternal(recording.getObjectKey(), 10);
|
||||
Process process = new ProcessBuilder(props.getFfprobePath(), "-v", "error", "-show_streams",
|
||||
"-print_format", "json", url)
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
boolean finished = process.waitFor(20, TimeUnit.SECONDS);
|
||||
String output;
|
||||
try (InputStream in = process.getInputStream()) {
|
||||
output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
if (!finished) {
|
||||
process.destroyForcibly();
|
||||
markFailed(recording, "探针超时");
|
||||
return;
|
||||
}
|
||||
ProbeParser.Result result = ProbeParser.parse(output);
|
||||
recording.setHasVideo(result.video());
|
||||
recording.setHasAudio(result.audio());
|
||||
if (result.video() && result.audio()) {
|
||||
recording.setStatus("COMPLETED");
|
||||
recording.setErrorMessage(null);
|
||||
} else {
|
||||
recording.setStatus("FAILED");
|
||||
recording.setErrorMessage(result.video() ? "录像缺少音轨" : "录像缺少视频轨");
|
||||
}
|
||||
recordings.save(recording);
|
||||
} catch (Exception ex) {
|
||||
log.warn("录像探针失败");
|
||||
markFailed(recording, "无法检查录像文件");
|
||||
}
|
||||
}
|
||||
|
||||
public PagePayload<Recording> list(UserPrincipal me, Long classId, int page, int size) {
|
||||
var result = classId != null
|
||||
? recordings.findByClassId(classId, Pages.of(page, size))
|
||||
: (me.superAdmin() ? recordings.findAll(Pages.of(page, size)) : recordings.findBySchoolId(me.schoolId(), Pages.of(page, size)));
|
||||
if (!me.superAdmin() && !me.schoolStaff() && me.schoolId() == null) {
|
||||
var allowed = result.getContent().stream()
|
||||
.filter(item -> bindings.parentCan(me.id(), item.getClassId(), true))
|
||||
.toList();
|
||||
return new PagePayload<>(allowed, allowed.size(), page, size);
|
||||
}
|
||||
return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
public String playback(UserPrincipal me, Long id) {
|
||||
Recording recording = recordings.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "录像不存在"));
|
||||
if (!"COMPLETED".equals(recording.getStatus())) {
|
||||
throw new BizException(ErrorCode.STATE, "录像尚未完成");
|
||||
}
|
||||
boolean staff = me.superAdmin() || (me.schoolStaff() && recording.getSchoolId().equals(me.schoolId()));
|
||||
boolean parent = bindings.parentCan(me.id(), recording.getClassId(), true);
|
||||
if (!staff && !parent && !canTeacher(me, recording)) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "没有该录像的观看权限");
|
||||
}
|
||||
return storage.presignPlayback(recording.getObjectKey(), 10);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void delete(UserPrincipal me, Long id) {
|
||||
Recording recording = recordings.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "录像不存在"));
|
||||
if (!me.superAdmin() && !(me.schoolStaff() && recording.getSchoolId().equals(me.schoolId()))) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不能删除该录像");
|
||||
}
|
||||
storage.delete(recording.getObjectKey());
|
||||
recordings.delete(recording);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Recording retry(UserPrincipal me, Long id) {
|
||||
Recording recording = recordings.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "录像不存在"));
|
||||
if (!me.superAdmin() && !(me.schoolStaff() && recording.getSchoolId().equals(me.schoolId()))) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不能重试该录像");
|
||||
}
|
||||
LiveSession session = sessions.findById(recording.getSessionId()).orElseThrow();
|
||||
if ("LIVE".equals(session.getStatus())) {
|
||||
recording.setRetryCount(recording.getRetryCount() + 1);
|
||||
recording.setStatus("PENDING");
|
||||
recording.setErrorMessage(null);
|
||||
recordings.save(recording);
|
||||
String egressId = liveKit.startEgress(session.getRoomName(), recording.getObjectKey());
|
||||
recording.setEgressId(egressId);
|
||||
recording.setStatus("RECORDING");
|
||||
return recordings.save(recording);
|
||||
}
|
||||
if (storage.exists(recording.getObjectKey())) {
|
||||
probeLater(recording.getId());
|
||||
recording.setStatus("PROCESSING");
|
||||
return recordings.save(recording);
|
||||
}
|
||||
throw new BizException(ErrorCode.STATE, "直播已结束且没有可重试的文件");
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void cleanup() {
|
||||
schools.findAll().forEach(school -> {
|
||||
Instant deadline = Instant.now().minus(school.getRetentionDays(), ChronoUnit.DAYS);
|
||||
recordings.findByStatusAndEndedAtBefore("COMPLETED", deadline).stream()
|
||||
.filter(item -> item.getSchoolId().equals(school.getId()))
|
||||
.forEach(item -> {
|
||||
storage.delete(item.getObjectKey());
|
||||
recordings.delete(item);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public long storedBytes(Long schoolId) {
|
||||
return recordings.sumSize(schoolId);
|
||||
}
|
||||
|
||||
public long failedCount(Long schoolId) {
|
||||
return schoolId == null ? recordings.countByStatus("FAILED") : recordings.countByStatusAndSchoolId("FAILED", schoolId);
|
||||
}
|
||||
|
||||
public long completedCount(Long schoolId) {
|
||||
return schoolId == null ? recordings.countByStatus("COMPLETED") : recordings.countByStatusAndSchoolId("COMPLETED", schoolId);
|
||||
}
|
||||
|
||||
private boolean canTeacher(UserPrincipal me, Recording recording) {
|
||||
return sessions.findById(recording.getSessionId()).map(session -> session.getTeacherId().equals(me.id())).orElse(false);
|
||||
}
|
||||
|
||||
private void markFailed(Recording recording, String reason) {
|
||||
recording.setStatus("FAILED");
|
||||
recording.setErrorMessage(reason);
|
||||
recordings.save(recording);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.xh.xunke.school;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface BindingRepository extends JpaRepository<ParentBinding, Long> {
|
||||
Page<ParentBinding> findBySchoolIdAndStatus(Long schoolId, String status, Pageable pageable);
|
||||
|
||||
Page<ParentBinding> findByStatus(String status, Pageable pageable);
|
||||
|
||||
List<ParentBinding> findByParentId(Long parentId);
|
||||
|
||||
Optional<ParentBinding> findByParentIdAndClassIdAndStatus(Long parentId, Long classId, String status);
|
||||
|
||||
List<ParentBinding> findByClassIdAndStatusAndLiveGranted(Long classId, String status, boolean liveGranted);
|
||||
|
||||
@Query("select count(distinct b.parentId) from ParentBinding b where b.status = 'APPROVED' and (:schoolId is null or b.schoolId = :schoolId)")
|
||||
long countApprovedParents(Long schoolId);
|
||||
|
||||
boolean existsByParentIdAndStudentIdAndStatusIn(Long parentId, Long studentId, List<String> statuses);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.xh.xunke.school;
|
||||
|
||||
public final class BindingRules {
|
||||
private BindingRules() {
|
||||
}
|
||||
|
||||
public static boolean canWatch(String status, boolean granted) {
|
||||
return "APPROVED".equals(status) && granted;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.xh.xunke.school;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import com.xh.xunke.live.LiveKitGateway;
|
||||
import com.xh.xunke.live.LiveSessionRepository;
|
||||
import com.xh.xunke.common.PagePayload;
|
||||
import com.xh.xunke.common.Pages;
|
||||
import com.xh.xunke.security.AccessGuard;
|
||||
import com.xh.xunke.security.UserPrincipal;
|
||||
import com.xh.xunke.user.RoleName;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class BindingService {
|
||||
private final BindingRepository bindings;
|
||||
private final StudentRepository students;
|
||||
private final ClassRoomRepository classes;
|
||||
private final AccessGuard guard;
|
||||
private final StringRedisTemplate redis;
|
||||
private final LiveSessionRepository sessions;
|
||||
private final LiveKitGateway liveKit;
|
||||
|
||||
public BindingService(BindingRepository bindings, StudentRepository students, ClassRoomRepository classes,
|
||||
AccessGuard guard, StringRedisTemplate redis, LiveSessionRepository sessions,
|
||||
LiveKitGateway liveKit) {
|
||||
this.bindings = bindings;
|
||||
this.students = students;
|
||||
this.classes = classes;
|
||||
this.guard = guard;
|
||||
this.redis = redis;
|
||||
this.sessions = sessions;
|
||||
this.liveKit = liveKit;
|
||||
}
|
||||
|
||||
public record BindRequest(@NotNull Long classId, @NotBlank String studentNo, @NotBlank String studentName,
|
||||
@NotBlank String relationship, boolean requestLive, boolean requestReplay) {
|
||||
}
|
||||
|
||||
public record ReviewRequest(boolean approve, boolean liveGranted, boolean replayGranted, String note) {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ParentBinding request(UserPrincipal me, BindRequest request) {
|
||||
if (!me.has(RoleName.PARENT) && !me.superAdmin()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "只有家长可以申请绑定");
|
||||
}
|
||||
ClassRoom room = classes.findById(request.classId()).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "班级不存在"));
|
||||
Student student = students.findBySchoolIdAndStudentNo(room.getSchoolId(), request.studentNo().trim())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "学生信息不匹配"));
|
||||
if (!student.getClassId().equals(room.getId()) || !student.getName().equals(request.studentName().trim())) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "学生姓名或班级不匹配");
|
||||
}
|
||||
if (bindings.existsByParentIdAndStudentIdAndStatusIn(me.id(), student.getId(), List.of("PENDING", "APPROVED"))) {
|
||||
throw new BizException(ErrorCode.CONFLICT, "已有待审核或已通过的绑定");
|
||||
}
|
||||
ParentBinding binding = new ParentBinding();
|
||||
binding.setParentId(me.id());
|
||||
binding.setStudentId(student.getId());
|
||||
binding.setClassId(room.getId());
|
||||
binding.setSchoolId(room.getSchoolId());
|
||||
binding.setRelationship(request.relationship().trim());
|
||||
binding.setLiveGranted(false);
|
||||
binding.setReplayGranted(false);
|
||||
binding.setStatus("PENDING");
|
||||
return bindings.save(binding);
|
||||
}
|
||||
|
||||
public PagePayload<ParentBinding> list(UserPrincipal me, String status, int page, int size) {
|
||||
if (me.has(RoleName.PARENT) && !me.schoolStaff() && !me.superAdmin()) {
|
||||
var mine = bindings.findByParentId(me.id());
|
||||
return new PagePayload<>(mine, mine.size(), 0, mine.size());
|
||||
}
|
||||
Long schoolId = me.superAdmin() ? null : me.schoolId();
|
||||
var result = schoolId == null
|
||||
? (status == null ? bindings.findAll(Pages.of(page, size)) : bindings.findByStatus(status, Pages.of(page, size)))
|
||||
: bindings.findBySchoolIdAndStatus(schoolId, status == null ? "PENDING" : status, Pages.of(page, size));
|
||||
return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ParentBinding review(UserPrincipal me, Long id, ReviewRequest request) {
|
||||
ParentBinding binding = bindings.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "绑定申请不存在"));
|
||||
guard.checkSchool(me, binding.getSchoolId());
|
||||
if (!"PENDING".equals(binding.getStatus())) {
|
||||
throw new BizException(ErrorCode.STATE, "该申请已处理");
|
||||
}
|
||||
binding.setReviewerId(me.id());
|
||||
binding.setReviewedAt(Instant.now());
|
||||
binding.setReviewNote(request.note());
|
||||
if (!request.approve()) {
|
||||
binding.setStatus("REJECTED");
|
||||
binding.setLiveGranted(false);
|
||||
binding.setReplayGranted(false);
|
||||
return bindings.save(binding);
|
||||
}
|
||||
binding.setStatus("APPROVED");
|
||||
binding.setLiveGranted(request.liveGranted());
|
||||
binding.setReplayGranted(request.replayGranted());
|
||||
bindings.save(binding);
|
||||
syncGrant(binding);
|
||||
return binding;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ParentBinding revoke(UserPrincipal me, Long id) {
|
||||
ParentBinding binding = bindings.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "绑定不存在"));
|
||||
if (!me.superAdmin() && !me.schoolStaff() && !binding.getParentId().equals(me.id())) {
|
||||
guard.checkSchool(me, binding.getSchoolId());
|
||||
}
|
||||
if (me.has(RoleName.PARENT) && !binding.getParentId().equals(me.id()) && !me.schoolStaff() && !me.superAdmin()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不能撤销他人的绑定");
|
||||
}
|
||||
binding.setStatus("REVOKED");
|
||||
binding.setLiveGranted(false);
|
||||
binding.setReplayGranted(false);
|
||||
bindings.save(binding);
|
||||
redis.opsForSet().remove(liveKey(binding.getClassId()), String.valueOf(binding.getParentId()));
|
||||
redis.opsForSet().remove(replayKey(binding.getClassId()), String.valueOf(binding.getParentId()));
|
||||
sessions.findByClassIdAndStatusIn(binding.getClassId(), java.util.List.of("PREPARING", "LIVE"))
|
||||
.ifPresent(session -> liveKit.removeParticipant(session.getRoomName(), "u-" + binding.getParentId()));
|
||||
return binding;
|
||||
}
|
||||
|
||||
public boolean parentCan(Long parentId, Long classId, boolean replay) {
|
||||
return bindings.findByParentIdAndClassIdAndStatus(parentId, classId, "APPROVED")
|
||||
.map(binding -> BindingRules.canWatch(binding.getStatus(), replay ? binding.isReplayGranted() : binding.isLiveGranted()))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
private void syncGrant(ParentBinding binding) {
|
||||
String parent = String.valueOf(binding.getParentId());
|
||||
if (binding.isLiveGranted()) {
|
||||
redis.opsForSet().add(liveKey(binding.getClassId()), parent);
|
||||
}
|
||||
if (binding.isReplayGranted()) {
|
||||
redis.opsForSet().add(replayKey(binding.getClassId()), parent);
|
||||
}
|
||||
}
|
||||
|
||||
private String liveKey(Long classId) {
|
||||
return "grant:live:" + classId;
|
||||
}
|
||||
|
||||
private String replayKey(Long classId) {
|
||||
return "grant:replay:" + classId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.xh.xunke.school;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "classes")
|
||||
public class ClassRoom {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long schoolId;
|
||||
@Column(nullable = false)
|
||||
private Long gradeId;
|
||||
@Column(nullable = false, length = 64)
|
||||
private String name;
|
||||
private Long headTeacherId;
|
||||
@Column(nullable = false, length = 20)
|
||||
private String status = "ACTIVE";
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
@Column(nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
@PrePersist
|
||||
void onCreate() {
|
||||
Instant now = Instant.now();
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
void onUpdate() {
|
||||
updatedAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.xh.xunke.school;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "class_teachers")
|
||||
public class ClassTeacher {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long classId;
|
||||
@Column(nullable = false)
|
||||
private Long teacherId;
|
||||
@Column(length = 64)
|
||||
private String subject;
|
||||
@Column(name = "is_head", nullable = false)
|
||||
private boolean head;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.xh.xunke.school;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "grades")
|
||||
public class Grade {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long schoolId;
|
||||
@Column(nullable = false, length = 64)
|
||||
private String name;
|
||||
@Column(nullable = false)
|
||||
private int sortOrder;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.xh.xunke.school;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "parent_bindings")
|
||||
public class ParentBinding {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long parentId;
|
||||
@Column(nullable = false)
|
||||
private Long studentId;
|
||||
@Column(nullable = false)
|
||||
private Long classId;
|
||||
@Column(nullable = false)
|
||||
private Long schoolId;
|
||||
@Column(nullable = false, length = 32)
|
||||
private String relationship;
|
||||
@Column(nullable = false)
|
||||
private boolean liveGranted;
|
||||
@Column(nullable = false)
|
||||
private boolean replayGranted;
|
||||
@Column(nullable = false, length = 20)
|
||||
private String status;
|
||||
@Column(length = 500)
|
||||
private String reviewNote;
|
||||
private Long reviewerId;
|
||||
private Instant reviewedAt;
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
@Column(nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
@PrePersist
|
||||
void onCreate() {
|
||||
Instant now = Instant.now();
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
void onUpdate() {
|
||||
updatedAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.xh.xunke.school;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "schools")
|
||||
public class School {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false, length = 128)
|
||||
private String name;
|
||||
@Column(nullable = false, unique = true, length = 32)
|
||||
private String code;
|
||||
private String logoUrl;
|
||||
@Column(nullable = false, length = 20)
|
||||
private String status = "ACTIVE";
|
||||
private String address;
|
||||
private String contactName;
|
||||
private String contactPhone;
|
||||
@Column(nullable = false)
|
||||
private boolean liveEnabled = true;
|
||||
@Column(nullable = false)
|
||||
private boolean recordEnabled = true;
|
||||
@Column(nullable = false)
|
||||
private boolean teacherPublic = true;
|
||||
@Column(nullable = false)
|
||||
private int retentionDays = 30;
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
@Column(nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
@PrePersist
|
||||
void onCreate() {
|
||||
Instant now = Instant.now();
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
void onUpdate() {
|
||||
updatedAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.xh.xunke.school;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface SchoolRepository extends JpaRepository<School, Long> {
|
||||
Page<School> findByNameContainingIgnoreCase(String name, Pageable pageable);
|
||||
|
||||
boolean existsByCode(String code);
|
||||
}
|
||||
|
||||
interface GradeRepository extends JpaRepository<Grade, Long> {
|
||||
List<Grade> findBySchoolIdOrderBySortOrderAsc(Long schoolId);
|
||||
}
|
||||
|
||||
interface ClassRoomRepository extends JpaRepository<ClassRoom, Long> {
|
||||
Page<ClassRoom> findBySchoolId(Long schoolId, Pageable pageable);
|
||||
|
||||
List<ClassRoom> findBySchoolIdAndGradeId(Long schoolId, Long gradeId);
|
||||
|
||||
long countBySchoolId(Long schoolId);
|
||||
}
|
||||
|
||||
interface ClassTeacherRepository extends JpaRepository<ClassTeacher, Long> {
|
||||
List<ClassTeacher> findByClassId(Long classId);
|
||||
|
||||
List<ClassTeacher> findByTeacherId(Long teacherId);
|
||||
|
||||
Optional<ClassTeacher> findByClassIdAndTeacherId(Long classId, Long teacherId);
|
||||
|
||||
void deleteByClassIdAndTeacherId(Long classId, Long teacherId);
|
||||
}
|
||||
|
||||
interface StudentRepository extends JpaRepository<Student, Long> {
|
||||
Page<Student> findByClassId(Long classId, Pageable pageable);
|
||||
|
||||
Optional<Student> findBySchoolIdAndStudentNo(Long schoolId, String studentNo);
|
||||
|
||||
List<Student> findByClassId(Long classId);
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
package com.xh.xunke.school;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import com.xh.xunke.course.Period;
|
||||
import com.xh.xunke.course.PeriodRepository;
|
||||
import com.xh.xunke.common.PagePayload;
|
||||
import com.xh.xunke.common.Pages;
|
||||
import com.xh.xunke.security.AccessGuard;
|
||||
import com.xh.xunke.security.UserPrincipal;
|
||||
import com.xh.xunke.user.RoleName;
|
||||
import com.xh.xunke.user.UserAccount;
|
||||
import com.xh.xunke.user.UserRepository;
|
||||
import com.xh.xunke.user.UserRoleRepository;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class SchoolService {
|
||||
private final SchoolRepository schools;
|
||||
private final GradeRepository grades;
|
||||
private final ClassRoomRepository classes;
|
||||
private final ClassTeacherRepository classTeachers;
|
||||
private final StudentRepository students;
|
||||
private final UserRepository users;
|
||||
private final UserRoleRepository roles;
|
||||
private final AccessGuard guard;
|
||||
private final PeriodRepository periods;
|
||||
|
||||
public SchoolService(SchoolRepository schools, GradeRepository grades, ClassRoomRepository classes,
|
||||
ClassTeacherRepository classTeachers, StudentRepository students,
|
||||
UserRepository users, UserRoleRepository roles, AccessGuard guard, PeriodRepository periods) {
|
||||
this.schools = schools;
|
||||
this.grades = grades;
|
||||
this.classes = classes;
|
||||
this.classTeachers = classTeachers;
|
||||
this.students = students;
|
||||
this.users = users;
|
||||
this.roles = roles;
|
||||
this.guard = guard;
|
||||
this.periods = periods;
|
||||
}
|
||||
|
||||
public record SchoolRequest(@NotBlank String name, @NotBlank String code, String logoUrl, String address,
|
||||
String contactName, String contactPhone, Boolean liveEnabled, Boolean recordEnabled,
|
||||
Boolean teacherPublic, Integer retentionDays) {
|
||||
}
|
||||
|
||||
public record GradeRequest(@NotNull Long schoolId, @NotBlank String name, Integer sortOrder) {
|
||||
}
|
||||
|
||||
public record ClassRequest(@NotNull Long schoolId, @NotNull Long gradeId, @NotBlank String name, Long headTeacherId) {
|
||||
}
|
||||
|
||||
public record TeacherAssign(@NotNull Long teacherId, String subject, boolean head) {
|
||||
}
|
||||
|
||||
public record StudentRequest(@NotNull Long classId, @NotBlank String name, @NotBlank String studentNo) {
|
||||
}
|
||||
|
||||
public PagePayload<School> listSchools(UserPrincipal me, String q, int page, int size) {
|
||||
if (!me.superAdmin()) {
|
||||
if (me.schoolId() == null) {
|
||||
return new PagePayload<>(List.of(), 0, 0, size);
|
||||
}
|
||||
School school = schools.findById(me.schoolId()).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "学校不存在"));
|
||||
return new PagePayload<>(List.of(school), 1, 0, 1);
|
||||
}
|
||||
var result = schools.findByNameContainingIgnoreCase(q == null ? "" : q, Pages.of(page, size));
|
||||
return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public School createSchool(UserPrincipal me, SchoolRequest request) {
|
||||
if (!me.superAdmin()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "只有超级管理员可以创建学校");
|
||||
}
|
||||
if (schools.existsByCode(request.code())) {
|
||||
throw new BizException(ErrorCode.CONFLICT, "学校编码已存在");
|
||||
}
|
||||
School school = new School();
|
||||
apply(school, request);
|
||||
schools.save(school);
|
||||
String[][] defaults = {
|
||||
{"第1节", "08:00", "08:40"}, {"第2节", "08:50", "09:30"}, {"第3节", "09:50", "10:30"},
|
||||
{"第4节", "10:40", "11:20"}, {"第5节", "14:00", "14:40"}, {"第6节", "14:50", "15:30"},
|
||||
{"第7节", "15:50", "16:30"}, {"第8节", "16:40", "17:20"}
|
||||
};
|
||||
for (int i = 0; i < defaults.length; i++) {
|
||||
Period period = new Period();
|
||||
period.setSchoolId(school.getId());
|
||||
period.setName(defaults[i][0]);
|
||||
period.setStartTime(LocalTime.parse(defaults[i][1]));
|
||||
period.setEndTime(LocalTime.parse(defaults[i][2]));
|
||||
period.setSortOrder(i + 1);
|
||||
periods.save(period);
|
||||
}
|
||||
return school;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public School updateSchool(UserPrincipal me, Long id, SchoolRequest request) {
|
||||
School school = schools.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "学校不存在"));
|
||||
guard.checkSchool(me, school.getId());
|
||||
if (!school.getCode().equals(request.code()) && schools.existsByCode(request.code())) {
|
||||
throw new BizException(ErrorCode.CONFLICT, "学校编码已存在");
|
||||
}
|
||||
apply(school, request);
|
||||
return schools.save(school);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateSchoolStatus(UserPrincipal me, Long id, String status) {
|
||||
School school = schools.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "学校不存在"));
|
||||
guard.checkSchool(me, school.getId());
|
||||
if (!"ACTIVE".equals(status) && !"DISABLED".equals(status)) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "状态不正确");
|
||||
}
|
||||
school.setStatus(status);
|
||||
schools.save(school);
|
||||
}
|
||||
|
||||
public List<Grade> grades(UserPrincipal me, Long schoolId) {
|
||||
Long scoped = guard.requiredSchool(me, schoolId);
|
||||
return grades.findBySchoolIdOrderBySortOrderAsc(scoped);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Grade createGrade(UserPrincipal me, GradeRequest request) {
|
||||
Long schoolId = guard.requiredSchool(me, request.schoolId());
|
||||
Grade grade = new Grade();
|
||||
grade.setSchoolId(schoolId);
|
||||
grade.setName(request.name().trim());
|
||||
grade.setSortOrder(request.sortOrder() == null ? 0 : request.sortOrder());
|
||||
return grades.save(grade);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Grade updateGrade(UserPrincipal me, Long id, GradeRequest request) {
|
||||
Grade grade = grades.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "年级不存在"));
|
||||
guard.checkSchool(me, grade.getSchoolId());
|
||||
grade.setName(request.name().trim());
|
||||
grade.setSortOrder(request.sortOrder() == null ? grade.getSortOrder() : request.sortOrder());
|
||||
return grades.save(grade);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteGrade(UserPrincipal me, Long id) {
|
||||
Grade grade = grades.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "年级不存在"));
|
||||
guard.checkSchool(me, grade.getSchoolId());
|
||||
if (!classes.findBySchoolIdAndGradeId(grade.getSchoolId(), id).isEmpty()) {
|
||||
throw new BizException(ErrorCode.CONFLICT, "年级下仍有班级");
|
||||
}
|
||||
grades.delete(grade);
|
||||
}
|
||||
|
||||
public PagePayload<ClassRoom> classes(UserPrincipal me, Long schoolId, int page, int size) {
|
||||
Long scoped = me.superAdmin() ? schoolId : me.schoolId();
|
||||
var result = scoped == null
|
||||
? classes.findAll(Pages.of(page, size))
|
||||
: classes.findBySchoolId(scoped, Pages.of(page, size));
|
||||
return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ClassRoom createClass(UserPrincipal me, ClassRequest request) {
|
||||
Long schoolId = guard.requiredSchool(me, request.schoolId());
|
||||
Grade grade = grades.findById(request.gradeId()).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "年级不存在"));
|
||||
if (!grade.getSchoolId().equals(schoolId)) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "年级不属于该学校");
|
||||
}
|
||||
ClassRoom room = new ClassRoom();
|
||||
room.setSchoolId(schoolId);
|
||||
room.setGradeId(grade.getId());
|
||||
room.setName(request.name().trim());
|
||||
room.setHeadTeacherId(request.headTeacherId());
|
||||
room.setStatus("ACTIVE");
|
||||
return classes.save(room);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ClassRoom updateClass(UserPrincipal me, Long id, ClassRequest request) {
|
||||
ClassRoom room = requireClass(me, id);
|
||||
room.setName(request.name().trim());
|
||||
room.setGradeId(request.gradeId());
|
||||
room.setHeadTeacherId(request.headTeacherId());
|
||||
return classes.save(room);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteClass(UserPrincipal me, Long id) {
|
||||
ClassRoom room = requireClass(me, id);
|
||||
classes.delete(room);
|
||||
}
|
||||
|
||||
public List<ClassTeacher> teachersOf(UserPrincipal me, Long classId) {
|
||||
requireClass(me, classId);
|
||||
return classTeachers.findByClassId(classId);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ClassTeacher assignTeacher(UserPrincipal me, Long classId, TeacherAssign request) {
|
||||
ClassRoom room = requireClass(me, classId);
|
||||
UserAccount teacher = users.findById(request.teacherId())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "教师不存在"));
|
||||
boolean isTeacher = roles.findByIdUserId(teacher.getId()).stream().anyMatch(role -> role.role() == RoleName.TEACHER);
|
||||
if (!isTeacher) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "该账号不是教师");
|
||||
}
|
||||
guard.checkSchool(me, teacher.getSchoolId());
|
||||
ClassTeacher link = classTeachers.findByClassIdAndTeacherId(classId, teacher.getId()).orElseGet(ClassTeacher::new);
|
||||
link.setClassId(classId);
|
||||
link.setTeacherId(teacher.getId());
|
||||
link.setSubject(request.subject());
|
||||
link.setHead(request.head());
|
||||
classTeachers.save(link);
|
||||
if (request.head()) {
|
||||
room.setHeadTeacherId(teacher.getId());
|
||||
classes.save(room);
|
||||
}
|
||||
return link;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void removeTeacher(UserPrincipal me, Long classId, Long teacherId) {
|
||||
requireClass(me, classId);
|
||||
classTeachers.deleteByClassIdAndTeacherId(classId, teacherId);
|
||||
}
|
||||
|
||||
public PagePayload<Student> students(UserPrincipal me, Long classId, int page, int size) {
|
||||
requireClass(me, classId);
|
||||
var result = students.findByClassId(classId, Pages.of(page, size));
|
||||
return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Student createStudent(UserPrincipal me, StudentRequest request) {
|
||||
ClassRoom room = requireClass(me, request.classId());
|
||||
if (students.findBySchoolIdAndStudentNo(room.getSchoolId(), request.studentNo()).isPresent()) {
|
||||
throw new BizException(ErrorCode.CONFLICT, "学号已存在");
|
||||
}
|
||||
Student student = new Student();
|
||||
student.setSchoolId(room.getSchoolId());
|
||||
student.setClassId(room.getId());
|
||||
student.setName(request.name().trim());
|
||||
student.setStudentNo(request.studentNo().trim());
|
||||
return students.save(student);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteStudent(UserPrincipal me, Long id) {
|
||||
Student student = students.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "学生不存在"));
|
||||
guard.checkSchool(me, student.getSchoolId());
|
||||
students.delete(student);
|
||||
}
|
||||
|
||||
public ClassRoom requireClass(UserPrincipal me, Long classId) {
|
||||
ClassRoom room = classes.findById(classId).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "班级不存在"));
|
||||
guard.checkSchool(me, room.getSchoolId());
|
||||
return room;
|
||||
}
|
||||
|
||||
public School requireSchool(Long id) {
|
||||
return schools.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "学校不存在"));
|
||||
}
|
||||
|
||||
public boolean teaches(Long classId, Long teacherId) {
|
||||
return classTeachers.findByClassIdAndTeacherId(classId, teacherId).isPresent();
|
||||
}
|
||||
|
||||
public long countClasses(Long schoolId) {
|
||||
return schoolId == null ? classes.count() : classes.countBySchoolId(schoolId);
|
||||
}
|
||||
|
||||
private void apply(School school, SchoolRequest request) {
|
||||
school.setName(request.name().trim());
|
||||
school.setCode(request.code().trim());
|
||||
school.setLogoUrl(request.logoUrl());
|
||||
school.setAddress(request.address());
|
||||
school.setContactName(request.contactName());
|
||||
school.setContactPhone(request.contactPhone());
|
||||
if (request.liveEnabled() != null) {
|
||||
school.setLiveEnabled(request.liveEnabled());
|
||||
}
|
||||
if (request.recordEnabled() != null) {
|
||||
school.setRecordEnabled(request.recordEnabled());
|
||||
}
|
||||
if (request.teacherPublic() != null) {
|
||||
school.setTeacherPublic(request.teacherPublic());
|
||||
}
|
||||
if (request.retentionDays() != null) {
|
||||
school.setRetentionDays(Math.max(1, request.retentionDays()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.xh.xunke.school;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "students")
|
||||
public class Student {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private Long schoolId;
|
||||
@Column(nullable = false)
|
||||
private Long classId;
|
||||
@Column(nullable = false, length = 64)
|
||||
private String name;
|
||||
@Column(nullable = false, length = 32)
|
||||
private String studentNo;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.xh.xunke.security;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class AccessGuard {
|
||||
public void checkSchool(UserPrincipal me, Long schoolId) {
|
||||
if (me.superAdmin()) {
|
||||
return;
|
||||
}
|
||||
if (schoolId == null || me.schoolId() == null || !schoolId.equals(me.schoolId())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不能访问其他学校的数据");
|
||||
}
|
||||
}
|
||||
|
||||
public Long requiredSchool(UserPrincipal me, Long requested) {
|
||||
if (me.superAdmin()) {
|
||||
if (requested == null) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "请选择学校");
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
if (me.schoolId() == null) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "账号未绑定学校");
|
||||
}
|
||||
if (requested != null && !requested.equals(me.schoolId())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不能访问其他学校的数据");
|
||||
}
|
||||
return me.schoolId();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.xh.xunke.security;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
public final class AuthCookies {
|
||||
public static final String REFRESH = "xh_refresh";
|
||||
public static final String CLIENT_HEADER = "X-XH-Request";
|
||||
|
||||
private AuthCookies() {
|
||||
}
|
||||
|
||||
public static void requireClientHeader(HttpServletRequest request) {
|
||||
if (!"1".equals(request.getHeader(CLIENT_HEADER))) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "缺少安全请求头");
|
||||
}
|
||||
}
|
||||
|
||||
public static void setRefresh(HttpServletResponse response, String token, int days, boolean secure) {
|
||||
ResponseCookie cookie = ResponseCookie.from(REFRESH, token)
|
||||
.httpOnly(true)
|
||||
.secure(secure)
|
||||
.sameSite("Strict")
|
||||
.path("/api/auth")
|
||||
.maxAge(Duration.ofDays(days))
|
||||
.build();
|
||||
response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
|
||||
}
|
||||
|
||||
public static void clear(HttpServletResponse response, boolean secure) {
|
||||
ResponseCookie cookie = ResponseCookie.from(REFRESH, "")
|
||||
.httpOnly(true)
|
||||
.secure(secure)
|
||||
.sameSite("Strict")
|
||||
.path("/api/auth")
|
||||
.maxAge(0)
|
||||
.build();
|
||||
response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.xh.xunke.security;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
public final class CurrentUsers {
|
||||
private CurrentUsers() {
|
||||
}
|
||||
|
||||
public static UserPrincipal get() {
|
||||
var auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (auth == null || !(auth.getPrincipal() instanceof UserPrincipal principal)) {
|
||||
throw new BizException(ErrorCode.UNAUTHORIZED, "请先登录");
|
||||
}
|
||||
return principal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.xh.xunke.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xh.xunke.common.ApiResponse;
|
||||
import com.xh.xunke.user.RoleName;
|
||||
import com.xh.xunke.user.UserAccount;
|
||||
import com.xh.xunke.user.UserRepository;
|
||||
import com.xh.xunke.user.UserRoleRepository;
|
||||
import com.xh.xunke.user.UserStatus;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class JwtAuthFilter extends OncePerRequestFilter {
|
||||
private final JwtService jwtService;
|
||||
private final UserRepository users;
|
||||
private final UserRoleRepository roles;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public JwtAuthFilter(JwtService jwtService, UserRepository users, UserRoleRepository roles, ObjectMapper objectMapper) {
|
||||
this.jwtService = jwtService;
|
||||
this.users = users;
|
||||
this.roles = roles;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
|
||||
if (header == null || !header.startsWith("Bearer ")) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Claims claims = jwtService.parse(header.substring(7).trim());
|
||||
long userId = Long.parseLong(claims.getSubject());
|
||||
Integer version = claims.get("tv", Integer.class);
|
||||
UserAccount user = users.findById(userId).orElse(null);
|
||||
if (user == null || user.getStatus() != UserStatus.ACTIVE || version == null
|
||||
|| version != user.getTokenVersion()) {
|
||||
write(response, "登录已失效");
|
||||
return;
|
||||
}
|
||||
Set<RoleName> roleNames = roles.findByIdUserId(userId).stream()
|
||||
.map(role -> role.role())
|
||||
.collect(Collectors.toSet());
|
||||
UserPrincipal principal = new UserPrincipal(user.getId(), user.getUsername(), user.getDisplayName(),
|
||||
user.getSchoolId(), roleNames, user.getTokenVersion());
|
||||
var authentication = new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
chain.doFilter(request, response);
|
||||
} catch (JwtException | IllegalArgumentException ex) {
|
||||
SecurityContextHolder.clearContext();
|
||||
write(response, "登录已过期");
|
||||
}
|
||||
}
|
||||
|
||||
private void write(HttpServletResponse response, String message) throws IOException {
|
||||
response.setStatus(401);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
objectMapper.writeValue(response.getWriter(), ApiResponse.fail("UNAUTHORIZED", message));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.xh.xunke.security;
|
||||
|
||||
import com.xh.xunke.config.AppProperties;
|
||||
import com.xh.xunke.user.RoleName;
|
||||
import com.xh.xunke.user.UserAccount;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Date;
|
||||
import java.util.Set;
|
||||
|
||||
@Component
|
||||
public class JwtService {
|
||||
private final AppProperties props;
|
||||
private final SecretKey key;
|
||||
|
||||
public JwtService(AppProperties props) {
|
||||
this.props = props;
|
||||
byte[] bytes = props.getJwtSecret().getBytes(StandardCharsets.UTF_8);
|
||||
if (bytes.length < 32) {
|
||||
throw new IllegalStateException("JWT_SECRET 至少需要 32 字节");
|
||||
}
|
||||
this.key = Keys.hmacShaKeyFor(bytes);
|
||||
}
|
||||
|
||||
public String accessToken(UserAccount user, Set<RoleName> roles) {
|
||||
Instant now = Instant.now();
|
||||
return Jwts.builder()
|
||||
.subject(String.valueOf(user.getId()))
|
||||
.claim("username", user.getUsername())
|
||||
.claim("name", user.getDisplayName())
|
||||
.claim("roles", roles.stream().map(Enum::name).sorted().toList())
|
||||
.claim("tv", user.getTokenVersion())
|
||||
.claim("schoolId", user.getSchoolId())
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(now.plus(props.getJwtAccessMinutes(), ChronoUnit.MINUTES)))
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public Claims parse(String token) {
|
||||
return Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload();
|
||||
}
|
||||
|
||||
public int accessSeconds() {
|
||||
return props.getJwtAccessMinutes() * 60;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.xh.xunke.security;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import com.xh.xunke.settings.SettingsService;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
@Component
|
||||
public class PasswordPolicy {
|
||||
private static final Set<String> WEAK = Set.of("password", "12345678", "admin123", "qwertyui", "changeme");
|
||||
private final SettingsService settings;
|
||||
|
||||
public PasswordPolicy(SettingsService settings) {
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
public void check(String password) {
|
||||
checkRaw(password, settings.integer("sec.password.min", 8), settings.flag("sec.password.mix", true));
|
||||
}
|
||||
|
||||
public static void checkRaw(String password, int min, boolean mix) {
|
||||
if (password == null || password.length() < min || password.length() > 72) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "密码长度需在 " + min + " 到 72 之间");
|
||||
}
|
||||
if (WEAK.contains(password.toLowerCase(Locale.ROOT))) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "密码过于常见");
|
||||
}
|
||||
if (mix) {
|
||||
boolean letter = password.chars().anyMatch(Character::isLetter);
|
||||
boolean digit = password.chars().anyMatch(Character::isDigit);
|
||||
if (!letter || !digit) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "密码需要同时包含字母和数字");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.xh.xunke.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xh.xunke.common.ApiResponse;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
|
||||
@Component
|
||||
public class RateLimitFilter extends OncePerRequestFilter {
|
||||
private final StringRedisTemplate redis;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public RateLimitFilter(StringRedisTemplate redis, ObjectMapper objectMapper) {
|
||||
this.redis = redis;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
String path = request.getRequestURI();
|
||||
int limit = limitFor(path);
|
||||
if (limit < 0) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
String ip = clientIp(request);
|
||||
String key = "rl:" + path + ":" + ip;
|
||||
try {
|
||||
Long count = redis.opsForValue().increment(key);
|
||||
if (count != null && count == 1L) {
|
||||
redis.expire(key, Duration.ofMinutes(1));
|
||||
}
|
||||
if (count != null && count > limit) {
|
||||
response.setStatus(429);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
objectMapper.writeValue(response.getWriter(), ApiResponse.fail("RATE_LIMIT", "请求过于频繁,请稍后再试"));
|
||||
return;
|
||||
}
|
||||
} catch (RuntimeException ex) {
|
||||
if (path.startsWith("/api/auth")) {
|
||||
response.setStatus(503);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
objectMapper.writeValue(response.getWriter(), ApiResponse.fail("UPSTREAM", "安全校验暂不可用"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private int limitFor(String path) {
|
||||
if (path.equals("/api/auth/login") || path.equals("/api/auth/register")
|
||||
|| path.equals("/api/auth/forgot-password") || path.equals("/api/auth/reset-password")) {
|
||||
return 20;
|
||||
}
|
||||
if (path.equals("/api/auth/email-code") || path.equals("/api/auth/sms-code")) {
|
||||
return 5;
|
||||
}
|
||||
if (path.startsWith("/api/")) {
|
||||
return 300;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static String clientIp(HttpServletRequest request) {
|
||||
String forwarded = request.getHeader("X-Forwarded-For");
|
||||
if (forwarded != null && !forwarded.isBlank()) {
|
||||
return forwarded.split(",")[0].trim();
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.xh.xunke.security;
|
||||
|
||||
import com.xh.xunke.config.AppProperties;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
@Component
|
||||
public class SecretCipher {
|
||||
private static final int IV_LENGTH = 12;
|
||||
private final byte[] key;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
@Autowired
|
||||
public SecretCipher(AppProperties props) {
|
||||
this(props.getEncryptionKey());
|
||||
}
|
||||
|
||||
public SecretCipher(String secret) {
|
||||
try {
|
||||
this.key = MessageDigest.getInstance("SHA-256")
|
||||
.digest(secret.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException("无法初始化加密", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public String encrypt(String plain) {
|
||||
if (plain == null || plain.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
byte[] iv = new byte[IV_LENGTH];
|
||||
random.nextBytes(iv);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, iv));
|
||||
byte[] encrypted = cipher.doFinal(plain.getBytes(StandardCharsets.UTF_8));
|
||||
ByteBuffer buffer = ByteBuffer.allocate(iv.length + encrypted.length);
|
||||
buffer.put(iv);
|
||||
buffer.put(encrypted);
|
||||
return Base64.getEncoder().encodeToString(buffer.array());
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException("加密失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public String decrypt(String encoded) {
|
||||
if (encoded == null || encoded.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
byte[] all = Base64.getDecoder().decode(encoded);
|
||||
ByteBuffer buffer = ByteBuffer.wrap(all);
|
||||
byte[] iv = new byte[IV_LENGTH];
|
||||
buffer.get(iv);
|
||||
byte[] encrypted = new byte[buffer.remaining()];
|
||||
buffer.get(encrypted);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, iv));
|
||||
return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8);
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException("解密失败", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.xh.xunke.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xh.xunke.common.ApiResponse;
|
||||
import com.xh.xunke.user.RoleName;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
public class StaffApiFilter extends OncePerRequestFilter {
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public StaffApiFilter(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
String path = request.getRequestURI();
|
||||
if (!path.startsWith("/api/") || path.startsWith("/api/auth") || path.startsWith("/api/public")
|
||||
|| path.startsWith("/api/internal")) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null || !(authentication.getPrincipal() instanceof UserPrincipal me)) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
if (!allowed(me, request.getMethod(), path)) {
|
||||
response.setStatus(403);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
objectMapper.writeValue(response.getWriter(), ApiResponse.fail("FORBIDDEN", "没有权限"));
|
||||
return;
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
static boolean allowed(UserPrincipal me, String method, String path) {
|
||||
boolean read = "GET".equals(method) || "HEAD".equals(method);
|
||||
boolean admin = me.superAdmin() || me.has(RoleName.SCHOOL_ADMIN);
|
||||
boolean inspector = me.has(RoleName.INSPECTOR);
|
||||
boolean teacher = me.canTeach();
|
||||
if (path.startsWith("/api/admin") || path.equals("/api/dashboard") || path.startsWith("/api/users")) {
|
||||
return admin || (read && inspector && (path.equals("/api/dashboard") || path.equals("/api/admin/status")));
|
||||
}
|
||||
if (path.startsWith("/api/inspections")) {
|
||||
return admin || inspector;
|
||||
}
|
||||
if (path.startsWith("/api/schools") || path.startsWith("/api/grades") || path.startsWith("/api/classes")
|
||||
|| path.startsWith("/api/students") || path.startsWith("/api/courses") || path.startsWith("/api/periods")
|
||||
|| path.startsWith("/api/timetable")) {
|
||||
return read ? admin || inspector || teacher : admin;
|
||||
}
|
||||
if (path.contains("/force-stop") || path.equals("/api/recordings/usage") || path.matches(".*/recordings/\\d+/retry")) {
|
||||
return admin;
|
||||
}
|
||||
if ("DELETE".equals(method) && path.startsWith("/api/recordings")) {
|
||||
return admin;
|
||||
}
|
||||
if (path.startsWith("/api/bindings") && path.contains("/review")) {
|
||||
return admin;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.xh.xunke.security;
|
||||
|
||||
import com.xh.xunke.user.RoleName;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
|
||||
public record UserPrincipal(
|
||||
Long id,
|
||||
String username,
|
||||
String displayName,
|
||||
Long schoolId,
|
||||
Set<RoleName> roles,
|
||||
int tokenVersion
|
||||
) implements UserDetails {
|
||||
public boolean has(RoleName role) {
|
||||
return roles.contains(role);
|
||||
}
|
||||
|
||||
public boolean superAdmin() {
|
||||
return has(RoleName.SUPER_ADMIN);
|
||||
}
|
||||
|
||||
public boolean schoolStaff() {
|
||||
return has(RoleName.SUPER_ADMIN) || has(RoleName.SCHOOL_ADMIN) || has(RoleName.INSPECTOR);
|
||||
}
|
||||
|
||||
public boolean canTeach() {
|
||||
return has(RoleName.TEACHER) || has(RoleName.SCHOOL_ADMIN) || has(RoleName.SUPER_ADMIN);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return roles.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role.name())).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.xh.xunke.settings;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface SettingRepository extends JpaRepository<SystemSetting, String> {
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.xh.xunke.settings;
|
||||
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class SettingsService {
|
||||
private final SettingRepository repository;
|
||||
private final StringRedisTemplate redis;
|
||||
private final Map<String, String> cache = new ConcurrentHashMap<>();
|
||||
private volatile String loadedVersion = "";
|
||||
|
||||
public SettingsService(SettingRepository repository, StringRedisTemplate redis) {
|
||||
this.repository = repository;
|
||||
this.redis = redis;
|
||||
}
|
||||
|
||||
public String text(String key, String fallback) {
|
||||
refresh();
|
||||
return cache.getOrDefault(key, fallback);
|
||||
}
|
||||
|
||||
public boolean flag(String key, boolean fallback) {
|
||||
String value = text(key, null);
|
||||
if (value == null) {
|
||||
return fallback;
|
||||
}
|
||||
return "true".equalsIgnoreCase(value) || "1".equals(value);
|
||||
}
|
||||
|
||||
public int integer(String key, int fallback) {
|
||||
try {
|
||||
return Integer.parseInt(text(key, Integer.toString(fallback)));
|
||||
} catch (NumberFormatException ex) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, String> byPrefix(String prefix) {
|
||||
refresh();
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
cache.forEach((key, value) -> {
|
||||
if (key.startsWith(prefix)) {
|
||||
result.put(key, value);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
public Map<String, Object> publicSite() {
|
||||
Map<String, Object> site = new LinkedHashMap<>();
|
||||
byPrefix("site.").forEach(site::put);
|
||||
site.put("registrationEnabled", flag("reg.enabled", true));
|
||||
site.put("emailVerify", flag("reg.emailVerify", false));
|
||||
site.put("smsVerify", flag("reg.smsVerify", false));
|
||||
site.put("requireApproval", flag("reg.requireApproval", true));
|
||||
site.put("allowUsername", flag("reg.allowUsername", true));
|
||||
site.put("allowEmail", flag("reg.allowEmail", true));
|
||||
site.put("allowPhone", flag("reg.allowPhone", true));
|
||||
site.put("passwordMin", integer("sec.password.min", 8));
|
||||
site.put("passwordMix", flag("sec.password.mix", true));
|
||||
return site;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void update(Map<String, String> values) {
|
||||
values.forEach((key, value) -> {
|
||||
if (key == null || !key.matches("[a-z0-9.]+") || value == null) {
|
||||
return;
|
||||
}
|
||||
repository.save(new SystemSetting(key, value));
|
||||
});
|
||||
redis.opsForValue().increment("settings:ver");
|
||||
loadedVersion = "";
|
||||
}
|
||||
|
||||
private void refresh() {
|
||||
String version;
|
||||
try {
|
||||
version = redis.opsForValue().get("settings:ver");
|
||||
} catch (RuntimeException ex) {
|
||||
version = loadedVersion;
|
||||
}
|
||||
if (version == null) {
|
||||
version = "0";
|
||||
}
|
||||
if (version.equals(loadedVersion) && !cache.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
synchronized (this) {
|
||||
cache.clear();
|
||||
repository.findAll().forEach(item -> cache.put(item.getSettingKey(), item.getSettingValue()));
|
||||
loadedVersion = version;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.xh.xunke.settings;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "system_settings")
|
||||
public class SystemSetting {
|
||||
@Id
|
||||
@Column(length = 128)
|
||||
private String settingKey;
|
||||
@Column(nullable = false)
|
||||
private String settingValue;
|
||||
@Column(nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
public SystemSetting(String settingKey, String settingValue) {
|
||||
this.settingKey = settingKey;
|
||||
this.settingValue = settingValue;
|
||||
this.updatedAt = Instant.now();
|
||||
}
|
||||
|
||||
@PrePersist
|
||||
@PreUpdate
|
||||
void touch() {
|
||||
updatedAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.xh.xunke.system;
|
||||
|
||||
import com.xh.xunke.config.AppProperties;
|
||||
import com.xh.xunke.live.LiveSessionService;
|
||||
import com.xh.xunke.recording.ObjectStorage;
|
||||
import com.xh.xunke.recording.RecordingService;
|
||||
import com.xh.xunke.security.PasswordPolicy;
|
||||
import com.xh.xunke.user.RoleName;
|
||||
import com.xh.xunke.user.UserAccount;
|
||||
import com.xh.xunke.user.UserRepository;
|
||||
import com.xh.xunke.user.UserRole;
|
||||
import com.xh.xunke.user.UserRoleRepository;
|
||||
import com.xh.xunke.user.UserStatus;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class MaintenanceJobs implements ApplicationRunner {
|
||||
private static final Logger log = LoggerFactory.getLogger(MaintenanceJobs.class);
|
||||
private final AppProperties props;
|
||||
private final UserRepository users;
|
||||
private final UserRoleRepository roles;
|
||||
private final PasswordEncoder encoder;
|
||||
private final ObjectStorage storage;
|
||||
private final LiveSessionService live;
|
||||
private final RecordingService recordings;
|
||||
|
||||
public MaintenanceJobs(AppProperties props, UserRepository users, UserRoleRepository roles, PasswordEncoder encoder,
|
||||
ObjectStorage storage, LiveSessionService live, RecordingService recordings) {
|
||||
this.props = props;
|
||||
this.users = users;
|
||||
this.roles = roles;
|
||||
this.encoder = encoder;
|
||||
this.storage = storage;
|
||||
this.live = live;
|
||||
this.recordings = recordings;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
guardProductionSecrets();
|
||||
if (!roles.existsByIdRole(RoleName.SUPER_ADMIN)) {
|
||||
PasswordPolicy.checkRaw(props.getAdminPassword(), 8, true);
|
||||
UserAccount admin = new UserAccount();
|
||||
admin.setUsername(props.getAdminUsername());
|
||||
admin.setDisplayName(props.getAdminDisplayName());
|
||||
admin.setPasswordHash(encoder.encode(props.getAdminPassword()));
|
||||
admin.setStatus(UserStatus.ACTIVE);
|
||||
users.save(admin);
|
||||
roles.save(new UserRole(admin.getId(), RoleName.SUPER_ADMIN));
|
||||
log.info("已创建初始超级管理员 {}", admin.getUsername());
|
||||
}
|
||||
storage.ensureBucket();
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 15000)
|
||||
public void sweepLive() {
|
||||
try {
|
||||
live.sweep();
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn("直播巡检失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Scheduled(cron = "0 30 2 * * *")
|
||||
public void cleanupRecordings() {
|
||||
try {
|
||||
recordings.cleanup();
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn("录像清理失败");
|
||||
}
|
||||
}
|
||||
|
||||
private void guardProductionSecrets() {
|
||||
if (!props.isProdGuard()) {
|
||||
return;
|
||||
}
|
||||
String blob = props.getAdminPassword() + props.getJwtSecret() + props.getEncryptionKey() + props.getLivekitSecret();
|
||||
if (blob.contains("ChangeMe") || blob.contains("dev-only") || blob.contains("devsecret")) {
|
||||
throw new IllegalStateException("生产环境仍在使用示例密钥,已拒绝启动");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.xh.xunke.user;
|
||||
|
||||
import com.xh.xunke.common.ApiResponse;
|
||||
import com.xh.xunke.common.ClientInfo;
|
||||
import com.xh.xunke.config.AppProperties;
|
||||
import com.xh.xunke.security.AuthCookies;
|
||||
import com.xh.xunke.security.CurrentUsers;
|
||||
import com.xh.xunke.settings.SettingsService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
public class AuthController {
|
||||
private final AuthService auth;
|
||||
private final SettingsService settings;
|
||||
private final AppProperties props;
|
||||
|
||||
public AuthController(AuthService auth, SettingsService settings, AppProperties props) {
|
||||
this.auth = auth;
|
||||
this.settings = settings;
|
||||
this.props = props;
|
||||
}
|
||||
|
||||
@GetMapping("/public/site")
|
||||
public ApiResponse<Map<String, Object>> site() {
|
||||
return ApiResponse.ok(settings.publicSite());
|
||||
}
|
||||
|
||||
@PostMapping("/auth/register")
|
||||
public ApiResponse<AuthService.RegisterResult> register(@Valid @RequestBody AuthService.RegisterRequest request) {
|
||||
return ApiResponse.ok(auth.register(request));
|
||||
}
|
||||
|
||||
@PostMapping("/auth/login")
|
||||
public ApiResponse<AuthService.TokenResult> login(@Valid @RequestBody AuthService.LoginRequest request,
|
||||
HttpServletRequest http, HttpServletResponse response) {
|
||||
AuthService.TokenResult result = auth.login(request, ClientInfo.from(http));
|
||||
AuthCookies.setRefresh(response, result.refreshToken(), props.getJwtRefreshDays(), secure(http));
|
||||
return ApiResponse.ok(withoutRefresh(result));
|
||||
}
|
||||
|
||||
@PostMapping("/auth/refresh")
|
||||
public ApiResponse<AuthService.TokenResult> refresh(HttpServletRequest http, HttpServletResponse response) {
|
||||
AuthCookies.requireClientHeader(http);
|
||||
String refresh = readCookie(http);
|
||||
AuthService.TokenResult result = auth.refresh(refresh);
|
||||
AuthCookies.setRefresh(response, result.refreshToken(), props.getJwtRefreshDays(), secure(http));
|
||||
return ApiResponse.ok(withoutRefresh(result));
|
||||
}
|
||||
|
||||
@PostMapping("/auth/logout")
|
||||
public ApiResponse<Void> logout(HttpServletRequest http, HttpServletResponse response) {
|
||||
AuthCookies.requireClientHeader(http);
|
||||
auth.logout(readCookie(http));
|
||||
AuthCookies.clear(response, secure(http));
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@PostMapping("/auth/email-code")
|
||||
public ApiResponse<NotificationView> emailCode(@Valid @RequestBody AuthService.CodeRequest request) {
|
||||
return ApiResponse.ok(view(auth.sendCode("mail", request)));
|
||||
}
|
||||
|
||||
@PostMapping("/auth/sms-code")
|
||||
public ApiResponse<NotificationView> smsCode(@Valid @RequestBody AuthService.CodeRequest request) {
|
||||
return ApiResponse.ok(view(auth.sendCode("sms", request)));
|
||||
}
|
||||
|
||||
@PostMapping("/auth/forgot-password")
|
||||
public ApiResponse<NotificationView> forgot(@Valid @RequestBody AuthService.CodeRequest request) {
|
||||
String channel = request.target().contains("@") ? "mail" : "sms";
|
||||
return ApiResponse.ok(view(auth.sendCode(channel, new AuthService.CodeRequest(request.target(), "RESET"))));
|
||||
}
|
||||
|
||||
@PostMapping("/auth/reset-password")
|
||||
public ApiResponse<Void> reset(@Valid @RequestBody AuthService.ResetRequest request) {
|
||||
auth.resetPassword(request);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/auth/me")
|
||||
public ApiResponse<AuthService.UserView> me() {
|
||||
return ApiResponse.ok(auth.me(CurrentUsers.get().id()));
|
||||
}
|
||||
|
||||
@PutMapping("/auth/password")
|
||||
public ApiResponse<Void> password(@Valid @RequestBody AuthService.PasswordChange request) {
|
||||
auth.changePassword(CurrentUsers.get().id(), request);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
private NotificationView view(com.xh.xunke.notify.NotificationService.CodeSend send) {
|
||||
return new NotificationView(send.simulated(), send.debugCode());
|
||||
}
|
||||
|
||||
private AuthService.TokenResult withoutRefresh(AuthService.TokenResult result) {
|
||||
return new AuthService.TokenResult(result.accessToken(), result.expiresIn(), null, result.user(), false, null);
|
||||
}
|
||||
|
||||
private boolean secure(HttpServletRequest request) {
|
||||
return props.isCookieSecure() || request.isSecure();
|
||||
}
|
||||
|
||||
private String readCookie(HttpServletRequest request) {
|
||||
if (request.getCookies() == null) {
|
||||
return null;
|
||||
}
|
||||
for (var cookie : request.getCookies()) {
|
||||
if (AuthCookies.REFRESH.equals(cookie.getName())) {
|
||||
return cookie.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public record NotificationView(boolean simulated, String debugCode) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package com.xh.xunke.user;
|
||||
|
||||
import com.xh.xunke.audit.AuditService;
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ClientInfo;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import com.xh.xunke.config.AppProperties;
|
||||
import com.xh.xunke.notify.NotificationService;
|
||||
import com.xh.xunke.security.JwtService;
|
||||
import com.xh.xunke.security.PasswordPolicy;
|
||||
import com.xh.xunke.settings.SettingsService;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class AuthService {
|
||||
private final UserRepository users;
|
||||
private final UserRoleRepository roles;
|
||||
private final PasswordEncoder encoder;
|
||||
private final JwtService jwt;
|
||||
private final SettingsService settings;
|
||||
private final NotificationService notifications;
|
||||
private final AuditService audit;
|
||||
private final StringRedisTemplate redis;
|
||||
private final AppProperties props;
|
||||
private final PasswordPolicy passwords;
|
||||
private final String dummyHash;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
public AuthService(UserRepository users, UserRoleRepository roles, PasswordEncoder encoder, JwtService jwt,
|
||||
SettingsService settings, NotificationService notifications, AuditService audit,
|
||||
StringRedisTemplate redis, AppProperties props, PasswordPolicy passwords) {
|
||||
this.users = users;
|
||||
this.roles = roles;
|
||||
this.encoder = encoder;
|
||||
this.jwt = jwt;
|
||||
this.settings = settings;
|
||||
this.notifications = notifications;
|
||||
this.audit = audit;
|
||||
this.redis = redis;
|
||||
this.props = props;
|
||||
this.passwords = passwords;
|
||||
this.dummyHash = encoder.encode("timing-placeholder");
|
||||
}
|
||||
|
||||
public record RegisterRequest(@NotBlank String username, @NotBlank String password, String email, String phone,
|
||||
@NotBlank String displayName, String emailCode, String smsCode) {
|
||||
}
|
||||
|
||||
public record LoginRequest(@NotBlank String account, @NotBlank String password) {
|
||||
}
|
||||
|
||||
public record CodeRequest(@NotBlank String target, @NotBlank String purpose) {
|
||||
}
|
||||
|
||||
public record ResetRequest(@NotBlank String target, @NotBlank String code, @NotBlank String password) {
|
||||
}
|
||||
|
||||
public record PasswordChange(@NotBlank String oldPassword, @NotBlank String newPassword) {
|
||||
}
|
||||
|
||||
public record UserView(Long id, String username, String displayName, Long schoolId, String status, Set<String> roles) {
|
||||
}
|
||||
|
||||
public record TokenResult(String accessToken, int expiresIn, String refreshToken, UserView user,
|
||||
boolean simulated, String debugCode) {
|
||||
}
|
||||
|
||||
public record RegisterResult(Long id, String status, boolean simulated, String debugCode) {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public RegisterResult register(RegisterRequest request) {
|
||||
RegistrationPolicy.assertOpen(settings.flag("reg.enabled", true));
|
||||
if (!settings.flag("reg.allowUsername", true)) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "当前不允许用户名注册");
|
||||
}
|
||||
String email = blankToNull(request.email());
|
||||
String phone = blankToNull(request.phone());
|
||||
if (email == null && phone == null) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "请填写邮箱或手机号");
|
||||
}
|
||||
if (email != null && !settings.flag("reg.allowEmail", true)) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "当前不允许邮箱注册");
|
||||
}
|
||||
if (phone != null && !settings.flag("reg.allowPhone", true)) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "当前不允许手机号注册");
|
||||
}
|
||||
passwords.check(request.password());
|
||||
boolean emailVerify = settings.flag("reg.emailVerify", false);
|
||||
boolean smsVerify = settings.flag("reg.smsVerify", false);
|
||||
boolean simulated = false;
|
||||
String debugCode = null;
|
||||
if (emailVerify) {
|
||||
if (email == null || !notifications.verify("REGISTER", email, request.emailCode())) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "邮箱验证码不正确");
|
||||
}
|
||||
}
|
||||
if (smsVerify) {
|
||||
if (phone == null || !notifications.verify("REGISTER", phone, request.smsCode())) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "短信验证码不正确");
|
||||
}
|
||||
}
|
||||
if (users.existsByUsername(request.username())
|
||||
|| (email != null && users.existsByEmailIgnoreCase(email))
|
||||
|| (phone != null && users.existsByPhone(phone))) {
|
||||
throw new BizException(ErrorCode.CONFLICT, "账号已存在");
|
||||
}
|
||||
UserAccount user = new UserAccount();
|
||||
user.setUsername(request.username().trim());
|
||||
user.setEmail(email);
|
||||
user.setPhone(phone);
|
||||
user.setPasswordHash(encoder.encode(request.password()));
|
||||
user.setDisplayName(request.displayName().trim());
|
||||
user.setStatus(RegistrationPolicy.initialStatus(settings.flag("reg.requireApproval", true)));
|
||||
user.setEmailVerified(!emailVerify || email != null);
|
||||
user.setPhoneVerified(!smsVerify || phone != null);
|
||||
users.save(user);
|
||||
for (RoleName role : RegistrationPolicy.publicRoles()) {
|
||||
roles.save(new UserRole(user.getId(), role));
|
||||
}
|
||||
return new RegisterResult(user.getId(), user.getStatus().name(), simulated, debugCode);
|
||||
}
|
||||
|
||||
public NotificationService.CodeSend sendCode(String channel, CodeRequest request) {
|
||||
String purpose = "RESET".equals(request.purpose()) ? "RESET" : "REGISTER";
|
||||
if ("RESET".equals(purpose) && findAccount(request.target()) == null) {
|
||||
return new NotificationService.CodeSend(false, null);
|
||||
}
|
||||
return notifications.sendVerification(channel, request.target().trim(), purpose);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public TokenResult login(LoginRequest request, ClientInfo client) {
|
||||
String account = request.account().trim();
|
||||
UserAccount user = findAccount(account);
|
||||
if (user == null) {
|
||||
encoder.matches(request.password(), dummyHash);
|
||||
audit.login(null, account, false, "not-found", client);
|
||||
throw new BizException(ErrorCode.UNAUTHORIZED, "账号或密码错误");
|
||||
}
|
||||
if (user.getLockedUntil() != null && user.getLockedUntil().isAfter(Instant.now())) {
|
||||
audit.login(user.getId(), user.getUsername(), false, "locked", client);
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "账号已锁定,请稍后再试");
|
||||
}
|
||||
if (!encoder.matches(request.password(), user.getPasswordHash())) {
|
||||
int fails = user.getFailedLogins() + 1;
|
||||
user.setFailedLogins(fails);
|
||||
int max = settings.integer("sec.login.maxFail", 5);
|
||||
if (fails >= max) {
|
||||
user.setLockedUntil(Instant.now().plus(Duration.ofMinutes(settings.integer("sec.login.lockMinutes", 15))));
|
||||
user.setFailedLogins(0);
|
||||
}
|
||||
users.save(user);
|
||||
audit.login(user.getId(), user.getUsername(), false, "bad-password", client);
|
||||
throw new BizException(ErrorCode.UNAUTHORIZED, "账号或密码错误");
|
||||
}
|
||||
if (user.getStatus() == UserStatus.DISABLED) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "账号已禁用");
|
||||
}
|
||||
if (user.getStatus() == UserStatus.PENDING) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "账号待审核");
|
||||
}
|
||||
if (user.getStatus() == UserStatus.REJECTED) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "账号未通过审核");
|
||||
}
|
||||
if (settings.flag("reg.emailVerify", false) && user.getEmail() != null && !user.isEmailVerified()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "邮箱尚未验证");
|
||||
}
|
||||
if (settings.flag("reg.smsVerify", false) && user.getPhone() != null && !user.isPhoneVerified()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "手机号尚未验证");
|
||||
}
|
||||
user.setFailedLogins(0);
|
||||
user.setLockedUntil(null);
|
||||
users.save(user);
|
||||
audit.login(user.getId(), user.getUsername(), true, null, client);
|
||||
return issue(user);
|
||||
}
|
||||
|
||||
public TokenResult refresh(String refreshToken) {
|
||||
if (refreshToken == null || refreshToken.isBlank()) {
|
||||
throw new BizException(ErrorCode.UNAUTHORIZED, "请先登录");
|
||||
}
|
||||
String raw = redis.opsForValue().get(refreshKey(refreshToken));
|
||||
if (raw == null || !raw.contains(":")) {
|
||||
throw new BizException(ErrorCode.UNAUTHORIZED, "登录已过期");
|
||||
}
|
||||
String[] parts = raw.split(":");
|
||||
UserAccount user = users.findById(Long.parseLong(parts[0]))
|
||||
.orElseThrow(() -> new BizException(ErrorCode.UNAUTHORIZED, "登录已过期"));
|
||||
if (user.getStatus() != UserStatus.ACTIVE || user.getTokenVersion() != Integer.parseInt(parts[1])) {
|
||||
redis.delete(refreshKey(refreshToken));
|
||||
throw new BizException(ErrorCode.UNAUTHORIZED, "登录已失效");
|
||||
}
|
||||
redis.delete(refreshKey(refreshToken));
|
||||
return issue(user);
|
||||
}
|
||||
|
||||
public void logout(String refreshToken) {
|
||||
if (refreshToken != null) {
|
||||
redis.delete(refreshKey(refreshToken));
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void resetPassword(ResetRequest request) {
|
||||
UserAccount user = findAccount(request.target().trim());
|
||||
if (user == null || !notifications.verify("RESET", request.target().trim(), request.code())) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "验证码不正确");
|
||||
}
|
||||
passwords.check(request.password());
|
||||
user.setPasswordHash(encoder.encode(request.password()));
|
||||
user.setTokenVersion(user.getTokenVersion() + 1);
|
||||
user.setFailedLogins(0);
|
||||
user.setLockedUntil(null);
|
||||
users.save(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void changePassword(Long userId, PasswordChange request) {
|
||||
UserAccount user = users.findById(userId).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "用户不存在"));
|
||||
if (!encoder.matches(request.oldPassword(), user.getPasswordHash())) {
|
||||
throw new BizException(ErrorCode.UNAUTHORIZED, "原密码不正确");
|
||||
}
|
||||
passwords.check(request.newPassword());
|
||||
user.setPasswordHash(encoder.encode(request.newPassword()));
|
||||
user.setTokenVersion(user.getTokenVersion() + 1);
|
||||
users.save(user);
|
||||
}
|
||||
|
||||
public UserView me(Long userId) {
|
||||
UserAccount user = users.findById(userId).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "用户不存在"));
|
||||
return view(user);
|
||||
}
|
||||
|
||||
private TokenResult issue(UserAccount user) {
|
||||
Set<RoleName> roleNames = roles.findByIdUserId(user.getId()).stream().map(UserRole::role).collect(Collectors.toSet());
|
||||
String refresh = randomToken();
|
||||
redis.opsForValue().set(refreshKey(refresh), user.getId() + ":" + user.getTokenVersion(),
|
||||
Duration.ofDays(props.getJwtRefreshDays()));
|
||||
return new TokenResult(jwt.accessToken(user, roleNames), jwt.accessSeconds(), refresh, view(user), false, null);
|
||||
}
|
||||
|
||||
private UserView view(UserAccount user) {
|
||||
Set<String> roleNames = roles.findByIdUserId(user.getId()).stream()
|
||||
.map(role -> role.role().name()).collect(Collectors.toSet());
|
||||
return new UserView(user.getId(), user.getUsername(), user.getDisplayName(), user.getSchoolId(),
|
||||
user.getStatus().name(), roleNames);
|
||||
}
|
||||
|
||||
private UserAccount findAccount(String account) {
|
||||
return users.findByUsername(account)
|
||||
.or(() -> users.findByEmailIgnoreCase(account))
|
||||
.or(() -> users.findByPhone(account))
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private String blankToNull(String value) {
|
||||
return value == null || value.isBlank() ? null : value.trim();
|
||||
}
|
||||
|
||||
private String randomToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
private String refreshKey(String token) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.UTF_8));
|
||||
return "refresh:" + HexFormat.of().formatHex(digest);
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.xh.xunke.user;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public final class RegistrationPolicy {
|
||||
private RegistrationPolicy() {
|
||||
}
|
||||
|
||||
public static void assertOpen(boolean enabled) {
|
||||
if (!enabled) {
|
||||
throw new BizException(ErrorCode.REGISTRATION_CLOSED, "注册已关闭");
|
||||
}
|
||||
}
|
||||
|
||||
public static UserStatus initialStatus(boolean requireApproval) {
|
||||
return requireApproval ? UserStatus.PENDING : UserStatus.ACTIVE;
|
||||
}
|
||||
|
||||
public static Set<RoleName> publicRoles() {
|
||||
return Set.of(RoleName.PARENT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.xh.xunke.user;
|
||||
|
||||
public enum RoleName {
|
||||
SUPER_ADMIN,
|
||||
SCHOOL_ADMIN,
|
||||
TEACHER,
|
||||
INSPECTOR,
|
||||
PARENT
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.xh.xunke.user;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserAccount {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@Column(nullable = false, unique = true, length = 64)
|
||||
private String username;
|
||||
@Column(unique = true)
|
||||
private String email;
|
||||
@Column(unique = true, length = 20)
|
||||
private String phone;
|
||||
@Column(nullable = false, length = 100)
|
||||
private String passwordHash;
|
||||
@Column(nullable = false, length = 64)
|
||||
private String displayName;
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 20)
|
||||
private UserStatus status;
|
||||
@Column(nullable = false)
|
||||
private boolean emailVerified;
|
||||
@Column(nullable = false)
|
||||
private boolean phoneVerified;
|
||||
private Long schoolId;
|
||||
@Column(nullable = false)
|
||||
private int tokenVersion;
|
||||
@Column(nullable = false)
|
||||
private int failedLogins;
|
||||
private Instant lockedUntil;
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
@Column(nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
@PrePersist
|
||||
void onCreate() {
|
||||
Instant now = Instant.now();
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
void onUpdate() {
|
||||
updatedAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.xh.xunke.user;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.common.ErrorCode;
|
||||
import com.xh.xunke.common.PagePayload;
|
||||
import com.xh.xunke.common.Pages;
|
||||
import com.xh.xunke.security.AccessGuard;
|
||||
import com.xh.xunke.security.PasswordPolicy;
|
||||
import com.xh.xunke.security.UserPrincipal;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class UserAdminService {
|
||||
private final UserRepository users;
|
||||
private final UserRoleRepository roles;
|
||||
private final PasswordEncoder encoder;
|
||||
private final PasswordPolicy passwords;
|
||||
private final AccessGuard guard;
|
||||
|
||||
public UserAdminService(UserRepository users, UserRoleRepository roles, PasswordEncoder encoder,
|
||||
PasswordPolicy passwords, AccessGuard guard) {
|
||||
this.users = users;
|
||||
this.roles = roles;
|
||||
this.encoder = encoder;
|
||||
this.passwords = passwords;
|
||||
this.guard = guard;
|
||||
}
|
||||
|
||||
public record CreateUser(@NotBlank String username, @NotBlank String password, @NotBlank String displayName,
|
||||
String email, String phone, @NotBlank String role, Long schoolId) {
|
||||
}
|
||||
|
||||
public record ReviewUser(boolean approve, String note) {
|
||||
}
|
||||
|
||||
public PagePayload<AuthService.UserView> list(UserPrincipal me, String role, String status, String q, int page, int size) {
|
||||
UserStatus parsed = status == null || status.isBlank() ? null : UserStatus.valueOf(status);
|
||||
Long schoolId = me.superAdmin() ? null : me.schoolId();
|
||||
var result = users.search(schoolId, parsed, q == null || q.isBlank() ? null : q, Pages.of(page, size));
|
||||
var views = result.getContent().stream().map(this::view).filter(item -> role == null || role.isBlank() || item.roles().contains(role)).toList();
|
||||
return new PagePayload<>(views, result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthService.UserView create(UserPrincipal me, CreateUser request) {
|
||||
RoleName role = RoleName.valueOf(request.role());
|
||||
if (role == RoleName.SUPER_ADMIN) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不能创建超级管理员");
|
||||
}
|
||||
if (!me.superAdmin() && role == RoleName.SCHOOL_ADMIN) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "只有超级管理员可以创建学校管理员");
|
||||
}
|
||||
Long schoolId = guard.requiredSchool(me, request.schoolId());
|
||||
if (users.existsByUsername(request.username())) {
|
||||
throw new BizException(ErrorCode.CONFLICT, "用户名已存在");
|
||||
}
|
||||
passwords.check(request.password());
|
||||
UserAccount user = new UserAccount();
|
||||
user.setUsername(request.username().trim());
|
||||
user.setDisplayName(request.displayName().trim());
|
||||
user.setEmail(blank(request.email()));
|
||||
user.setPhone(blank(request.phone()));
|
||||
user.setPasswordHash(encoder.encode(request.password()));
|
||||
user.setStatus(UserStatus.ACTIVE);
|
||||
user.setSchoolId(schoolId);
|
||||
user.setEmailVerified(user.getEmail() != null);
|
||||
user.setPhoneVerified(user.getPhone() != null);
|
||||
users.save(user);
|
||||
roles.save(new UserRole(user.getId(), role));
|
||||
return view(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthService.UserView review(UserPrincipal me, Long id, ReviewUser request) {
|
||||
UserAccount user = require(me, id);
|
||||
if (user.getStatus() != UserStatus.PENDING) {
|
||||
throw new BizException(ErrorCode.STATE, "账号不在待审核状态");
|
||||
}
|
||||
user.setStatus(request.approve() ? UserStatus.ACTIVE : UserStatus.REJECTED);
|
||||
users.save(user);
|
||||
return view(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthService.UserView status(UserPrincipal me, Long id, String status) {
|
||||
UserAccount user = require(me, id);
|
||||
UserStatus next = UserStatus.valueOf(status);
|
||||
if (next != UserStatus.ACTIVE && next != UserStatus.DISABLED) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "只能启用或禁用");
|
||||
}
|
||||
user.setStatus(next);
|
||||
user.setTokenVersion(user.getTokenVersion() + 1);
|
||||
users.save(user);
|
||||
return view(user);
|
||||
}
|
||||
|
||||
private UserAccount require(UserPrincipal me, Long id) {
|
||||
UserAccount user = users.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "用户不存在"));
|
||||
if (user.getSchoolId() != null) {
|
||||
guard.checkSchool(me, user.getSchoolId());
|
||||
} else if (!me.superAdmin()) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "不能管理该账号");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
private AuthService.UserView view(UserAccount user) {
|
||||
Set<String> roleNames = roles.findByIdUserId(user.getId()).stream().map(role -> role.role().name()).collect(Collectors.toSet());
|
||||
return new AuthService.UserView(user.getId(), user.getUsername(), user.getDisplayName(), user.getSchoolId(),
|
||||
user.getStatus().name(), roleNames);
|
||||
}
|
||||
|
||||
private String blank(String value) {
|
||||
return value == null || value.isBlank() ? null : value.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.xh.xunke.user;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserRepository extends JpaRepository<UserAccount, Long> {
|
||||
Optional<UserAccount> findByUsername(String username);
|
||||
|
||||
Optional<UserAccount> findByEmailIgnoreCase(String email);
|
||||
|
||||
Optional<UserAccount> findByPhone(String phone);
|
||||
|
||||
boolean existsByUsername(String username);
|
||||
|
||||
boolean existsByEmailIgnoreCase(String email);
|
||||
|
||||
boolean existsByPhone(String phone);
|
||||
|
||||
Page<UserAccount> findBySchoolId(Long schoolId, Pageable pageable);
|
||||
|
||||
@Query("select u from UserAccount u where (:schoolId is null or u.schoolId = :schoolId) "
|
||||
+ "and (:status is null or u.status = :status) "
|
||||
+ "and (:q is null or lower(u.username) like lower(concat('%', cast(:q as string), '%')) "
|
||||
+ "or lower(u.displayName) like lower(concat('%', cast(:q as string), '%')))")
|
||||
Page<UserAccount> search(Long schoolId, UserStatus status, String q, Pageable pageable);
|
||||
|
||||
long countBySchoolId(Long schoolId);
|
||||
|
||||
@Query("select count(distinct u.id) from UserAccount u, UserRole r where r.id.userId = u.id and r.id.role = :role "
|
||||
+ "and (:schoolId is null or u.schoolId = :schoolId)")
|
||||
long countByRole(RoleName role, Long schoolId);
|
||||
|
||||
java.util.List<UserAccount> findByIdIn(Collection<Long> ids);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.xh.xunke.user;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Embeddable;
|
||||
import jakarta.persistence.EmbeddedId;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "user_roles")
|
||||
public class UserRole {
|
||||
@EmbeddedId
|
||||
private Key id;
|
||||
|
||||
public UserRole(Long userId, RoleName role) {
|
||||
this.id = new Key(userId, role);
|
||||
}
|
||||
|
||||
public RoleName role() {
|
||||
return id.getRole();
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
@Embeddable
|
||||
public static class Key implements Serializable {
|
||||
private Long userId;
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 32)
|
||||
private RoleName role;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.xh.xunke.user;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
public interface UserRoleRepository extends JpaRepository<UserRole, UserRole.Key> {
|
||||
List<UserRole> findByIdUserId(Long userId);
|
||||
|
||||
List<UserRole> findByIdUserIdIn(Collection<Long> userIds);
|
||||
|
||||
boolean existsByIdRole(RoleName role);
|
||||
|
||||
void deleteByIdUserId(Long userId);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.xh.xunke.user;
|
||||
|
||||
public enum UserStatus {
|
||||
PENDING,
|
||||
ACTIVE,
|
||||
DISABLED,
|
||||
REJECTED
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
package com.xh.xunke.web;
|
||||
|
||||
import com.xh.xunke.audit.AuditService;
|
||||
import com.xh.xunke.common.ApiResponse;
|
||||
import com.xh.xunke.common.PagePayload;
|
||||
import com.xh.xunke.common.Pages;
|
||||
import com.xh.xunke.course.Course;
|
||||
import com.xh.xunke.course.CourseService;
|
||||
import com.xh.xunke.course.Period;
|
||||
import com.xh.xunke.course.TimetableEntry;
|
||||
import com.xh.xunke.inspection.InspectionRecord;
|
||||
import com.xh.xunke.inspection.InspectionRepository;
|
||||
import com.xh.xunke.live.LiveKitGateway;
|
||||
import com.xh.xunke.live.LiveSession;
|
||||
import com.xh.xunke.live.LiveSessionRepository;
|
||||
import com.xh.xunke.live.LiveSessionService;
|
||||
import com.xh.xunke.notify.NotificationService;
|
||||
import com.xh.xunke.notify.NotificationTemplate;
|
||||
import com.xh.xunke.notify.SmsSettings;
|
||||
import com.xh.xunke.notify.SmtpSettings;
|
||||
import com.xh.xunke.recording.ObjectStorage;
|
||||
import com.xh.xunke.recording.Recording;
|
||||
import com.xh.xunke.recording.RecordingService;
|
||||
import com.xh.xunke.school.BindingRepository;
|
||||
import com.xh.xunke.school.BindingService;
|
||||
import com.xh.xunke.school.ClassRoom;
|
||||
import com.xh.xunke.school.ClassTeacher;
|
||||
import com.xh.xunke.school.Grade;
|
||||
import com.xh.xunke.school.ParentBinding;
|
||||
import com.xh.xunke.school.School;
|
||||
import com.xh.xunke.school.SchoolService;
|
||||
import com.xh.xunke.school.Student;
|
||||
import com.xh.xunke.security.CurrentUsers;
|
||||
import com.xh.xunke.security.UserPrincipal;
|
||||
import com.xh.xunke.settings.SettingsService;
|
||||
import com.xh.xunke.user.AuthService;
|
||||
import com.xh.xunke.user.UserAdminService;
|
||||
import com.xh.xunke.user.UserRepository;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
public class ResourceController {
|
||||
private final SchoolService schools;
|
||||
private final BindingService bindings;
|
||||
private final CourseService courses;
|
||||
private final LiveSessionService live;
|
||||
private final RecordingService recordings;
|
||||
private final UserAdminService userAdmin;
|
||||
private final UserRepository users;
|
||||
private final InspectionRepository inspections;
|
||||
private final SettingsService settings;
|
||||
private final NotificationService notifications;
|
||||
private final ObjectStorage storage;
|
||||
private final LiveSessionRepository sessions;
|
||||
private final LiveKitGateway liveKit;
|
||||
private final BindingRepository bindingRepository;
|
||||
private final AuditService audit;
|
||||
|
||||
public ResourceController(SchoolService schools, BindingService bindings, CourseService courses,
|
||||
LiveSessionService live, RecordingService recordings, UserAdminService userAdmin,
|
||||
UserRepository users, InspectionRepository inspections, SettingsService settings,
|
||||
NotificationService notifications, ObjectStorage storage, LiveSessionRepository sessions,
|
||||
LiveKitGateway liveKit, BindingRepository bindingRepository, AuditService audit) {
|
||||
this.schools = schools;
|
||||
this.bindings = bindings;
|
||||
this.courses = courses;
|
||||
this.live = live;
|
||||
this.recordings = recordings;
|
||||
this.userAdmin = userAdmin;
|
||||
this.users = users;
|
||||
this.inspections = inspections;
|
||||
this.settings = settings;
|
||||
this.notifications = notifications;
|
||||
this.storage = storage;
|
||||
this.sessions = sessions;
|
||||
this.liveKit = liveKit;
|
||||
this.bindingRepository = bindingRepository;
|
||||
this.audit = audit;
|
||||
}
|
||||
|
||||
@GetMapping("/schools")
|
||||
public ApiResponse<PagePayload<School>> schools(@RequestParam(required = false) String q,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ApiResponse.ok(schools.listSchools(me(), q, page, size));
|
||||
}
|
||||
|
||||
@PostMapping("/schools")
|
||||
public ApiResponse<School> createSchool(@Valid @RequestBody SchoolService.SchoolRequest request) {
|
||||
return ApiResponse.ok(schools.createSchool(me(), request));
|
||||
}
|
||||
|
||||
@PutMapping("/schools/{id}")
|
||||
public ApiResponse<School> updateSchool(@PathVariable Long id, @Valid @RequestBody SchoolService.SchoolRequest request) {
|
||||
return ApiResponse.ok(schools.updateSchool(me(), id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/schools/{id}/status")
|
||||
public ApiResponse<Void> schoolStatus(@PathVariable Long id, @RequestBody Map<String, String> body) {
|
||||
schools.updateSchoolStatus(me(), id, body.get("status"));
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/grades")
|
||||
public ApiResponse<List<Grade>> grades(@RequestParam(required = false) Long schoolId) {
|
||||
return ApiResponse.ok(schools.grades(me(), schoolId));
|
||||
}
|
||||
|
||||
@PostMapping("/grades")
|
||||
public ApiResponse<Grade> createGrade(@Valid @RequestBody SchoolService.GradeRequest request) {
|
||||
return ApiResponse.ok(schools.createGrade(me(), request));
|
||||
}
|
||||
|
||||
@PutMapping("/grades/{id}")
|
||||
public ApiResponse<Grade> updateGrade(@PathVariable Long id, @Valid @RequestBody SchoolService.GradeRequest request) {
|
||||
return ApiResponse.ok(schools.updateGrade(me(), id, request));
|
||||
}
|
||||
|
||||
@DeleteMapping("/grades/{id}")
|
||||
public ApiResponse<Void> deleteGrade(@PathVariable Long id) {
|
||||
schools.deleteGrade(me(), id);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/classes")
|
||||
public ApiResponse<PagePayload<ClassRoom>> classes(@RequestParam(required = false) Long schoolId,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ApiResponse.ok(schools.classes(me(), schoolId, page, size));
|
||||
}
|
||||
|
||||
@PostMapping("/classes")
|
||||
public ApiResponse<ClassRoom> createClass(@Valid @RequestBody SchoolService.ClassRequest request) {
|
||||
return ApiResponse.ok(schools.createClass(me(), request));
|
||||
}
|
||||
|
||||
@PutMapping("/classes/{id}")
|
||||
public ApiResponse<ClassRoom> updateClass(@PathVariable Long id, @Valid @RequestBody SchoolService.ClassRequest request) {
|
||||
return ApiResponse.ok(schools.updateClass(me(), id, request));
|
||||
}
|
||||
|
||||
@DeleteMapping("/classes/{id}")
|
||||
public ApiResponse<Void> deleteClass(@PathVariable Long id) {
|
||||
schools.deleteClass(me(), id);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/classes/{id}/teachers")
|
||||
public ApiResponse<List<ClassTeacher>> classTeachers(@PathVariable Long id) {
|
||||
return ApiResponse.ok(schools.teachersOf(me(), id));
|
||||
}
|
||||
|
||||
@PostMapping("/classes/{id}/teachers")
|
||||
public ApiResponse<ClassTeacher> assignTeacher(@PathVariable Long id, @Valid @RequestBody SchoolService.TeacherAssign request) {
|
||||
return ApiResponse.ok(schools.assignTeacher(me(), id, request));
|
||||
}
|
||||
|
||||
@DeleteMapping("/classes/{id}/teachers/{teacherId}")
|
||||
public ApiResponse<Void> removeTeacher(@PathVariable Long id, @PathVariable Long teacherId) {
|
||||
schools.removeTeacher(me(), id, teacherId);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/students")
|
||||
public ApiResponse<PagePayload<Student>> students(@RequestParam Long classId,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ApiResponse.ok(schools.students(me(), classId, page, size));
|
||||
}
|
||||
|
||||
@PostMapping("/students")
|
||||
public ApiResponse<Student> createStudent(@Valid @RequestBody SchoolService.StudentRequest request) {
|
||||
return ApiResponse.ok(schools.createStudent(me(), request));
|
||||
}
|
||||
|
||||
@DeleteMapping("/students/{id}")
|
||||
public ApiResponse<Void> deleteStudent(@PathVariable Long id) {
|
||||
schools.deleteStudent(me(), id);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/users")
|
||||
public ApiResponse<PagePayload<AuthService.UserView>> users(@RequestParam(required = false) String role,
|
||||
@RequestParam(required = false) String status,
|
||||
@RequestParam(required = false) String q,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ApiResponse.ok(userAdmin.list(me(), role, status, q, page, size));
|
||||
}
|
||||
|
||||
@PostMapping("/users")
|
||||
public ApiResponse<AuthService.UserView> createUser(@Valid @RequestBody UserAdminService.CreateUser request) {
|
||||
return ApiResponse.ok(userAdmin.create(me(), request));
|
||||
}
|
||||
|
||||
@PostMapping("/users/{id}/review")
|
||||
public ApiResponse<AuthService.UserView> reviewUser(@PathVariable Long id, @RequestBody UserAdminService.ReviewUser request) {
|
||||
return ApiResponse.ok(userAdmin.review(me(), id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/users/{id}/status")
|
||||
public ApiResponse<AuthService.UserView> userStatus(@PathVariable Long id, @RequestBody Map<String, String> body) {
|
||||
return ApiResponse.ok(userAdmin.status(me(), id, body.get("status")));
|
||||
}
|
||||
|
||||
@PostMapping("/bindings")
|
||||
public ApiResponse<ParentBinding> bind(@Valid @RequestBody BindingService.BindRequest request) {
|
||||
return ApiResponse.ok(bindings.request(me(), request));
|
||||
}
|
||||
|
||||
@GetMapping("/bindings")
|
||||
public ApiResponse<PagePayload<ParentBinding>> bindings(@RequestParam(required = false) String status,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ApiResponse.ok(bindings.list(me(), status, page, size));
|
||||
}
|
||||
|
||||
@PostMapping("/bindings/{id}/review")
|
||||
public ApiResponse<ParentBinding> reviewBinding(@PathVariable Long id, @RequestBody BindingService.ReviewRequest request) {
|
||||
return ApiResponse.ok(bindings.review(me(), id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/bindings/{id}/revoke")
|
||||
public ApiResponse<ParentBinding> revokeBinding(@PathVariable Long id) {
|
||||
return ApiResponse.ok(bindings.revoke(me(), id));
|
||||
}
|
||||
|
||||
@GetMapping("/courses")
|
||||
public ApiResponse<PagePayload<Course>> courses(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) {
|
||||
return ApiResponse.ok(courses.list(me(), page, size));
|
||||
}
|
||||
|
||||
@PostMapping("/courses")
|
||||
public ApiResponse<Course> createCourse(@Valid @RequestBody CourseService.CourseRequest request) {
|
||||
return ApiResponse.ok(courses.create(me(), request));
|
||||
}
|
||||
|
||||
@PutMapping("/courses/{id}")
|
||||
public ApiResponse<Course> updateCourse(@PathVariable Long id, @Valid @RequestBody CourseService.CourseRequest request) {
|
||||
return ApiResponse.ok(courses.update(me(), id, request));
|
||||
}
|
||||
|
||||
@DeleteMapping("/courses/{id}")
|
||||
public ApiResponse<Void> deleteCourse(@PathVariable Long id) {
|
||||
courses.delete(me(), id);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/periods")
|
||||
public ApiResponse<List<Period>> periods(@RequestParam(required = false) Long schoolId) {
|
||||
return ApiResponse.ok(courses.periods(me(), schoolId));
|
||||
}
|
||||
|
||||
@PostMapping("/periods")
|
||||
public ApiResponse<Period> createPeriod(@Valid @RequestBody CourseService.PeriodRequest request) {
|
||||
return ApiResponse.ok(courses.savePeriod(me(), request, null));
|
||||
}
|
||||
|
||||
@PutMapping("/periods/{id}")
|
||||
public ApiResponse<Period> updatePeriod(@PathVariable Long id, @Valid @RequestBody CourseService.PeriodRequest request) {
|
||||
return ApiResponse.ok(courses.savePeriod(me(), request, id));
|
||||
}
|
||||
|
||||
@DeleteMapping("/periods/{id}")
|
||||
public ApiResponse<Void> deletePeriod(@PathVariable Long id) {
|
||||
courses.deletePeriod(me(), id);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/timetable")
|
||||
public ApiResponse<List<TimetableEntry>> timetable(@RequestParam Long classId, @RequestParam(required = false) Integer weekday) {
|
||||
return ApiResponse.ok(courses.week(me(), classId, weekday));
|
||||
}
|
||||
|
||||
@PostMapping("/timetable")
|
||||
public ApiResponse<TimetableEntry> createTimetable(@Valid @RequestBody CourseService.TimetableRequest request) {
|
||||
return ApiResponse.ok(courses.saveEntry(me(), request, null));
|
||||
}
|
||||
|
||||
@PutMapping("/timetable/{id}")
|
||||
public ApiResponse<TimetableEntry> updateTimetable(@PathVariable Long id, @Valid @RequestBody CourseService.TimetableRequest request) {
|
||||
return ApiResponse.ok(courses.saveEntry(me(), request, id));
|
||||
}
|
||||
|
||||
@PostMapping("/timetable/import")
|
||||
public ApiResponse<List<TimetableEntry>> importTimetable(@RequestBody Map<String, String> body) {
|
||||
return ApiResponse.ok(courses.importCsv(me(), body.getOrDefault("csv", "")));
|
||||
}
|
||||
|
||||
@PostMapping("/live/sessions")
|
||||
public ApiResponse<Map<String, Object>> startLive(@Valid @RequestBody LiveSessionService.StartRequest request) {
|
||||
return ApiResponse.ok(live.start(me(), request));
|
||||
}
|
||||
|
||||
@PostMapping("/live/sessions/{id}/ack")
|
||||
public ApiResponse<LiveSession> ack(@PathVariable Long id) {
|
||||
return ApiResponse.ok(live.ack(me(), id));
|
||||
}
|
||||
|
||||
@PostMapping("/live/sessions/{id}/heartbeat")
|
||||
public ApiResponse<LiveSession> heartbeat(@PathVariable Long id) {
|
||||
return ApiResponse.ok(live.heartbeat(me(), id));
|
||||
}
|
||||
|
||||
@PostMapping("/live/sessions/{id}/stop")
|
||||
public ApiResponse<LiveSession> stop(@PathVariable Long id, @RequestBody(required = false) Map<String, String> body) {
|
||||
return ApiResponse.ok(live.stop(me(), id, body == null ? "MANUAL" : body.getOrDefault("reason", "MANUAL")));
|
||||
}
|
||||
|
||||
@PostMapping("/live/sessions/{id}/force-stop")
|
||||
public ApiResponse<LiveSession> forceStop(@PathVariable Long id) {
|
||||
return ApiResponse.ok(live.stop(me(), id, "FORCED"));
|
||||
}
|
||||
|
||||
@PostMapping("/live/sessions/{id}/token")
|
||||
public ApiResponse<LiveSessionService.TokenView> token(@PathVariable Long id, @RequestBody Map<String, Boolean> body) {
|
||||
return ApiResponse.ok(live.token(me(), id, Boolean.TRUE.equals(body.get("publish"))));
|
||||
}
|
||||
|
||||
@PostMapping("/live/sessions/{id}/view")
|
||||
public ApiResponse<Map<String, Integer>> view(@PathVariable Long id) {
|
||||
return ApiResponse.ok(Map.of("viewers", live.touchViewer(me(), id)));
|
||||
}
|
||||
|
||||
@GetMapping("/live/sessions")
|
||||
public ApiResponse<PagePayload<LiveSession>> lives(@RequestParam(required = false) String status,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ApiResponse.ok(live.list(me(), status, page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/live/sessions/{id}")
|
||||
public ApiResponse<LiveSession> live(@PathVariable Long id) {
|
||||
return ApiResponse.ok(live.get(me(), id));
|
||||
}
|
||||
|
||||
@GetMapping("/recordings")
|
||||
public ApiResponse<PagePayload<Recording>> recordings(@RequestParam(required = false) Long classId,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ApiResponse.ok(recordings.list(me(), classId, page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/recordings/{id}/playback")
|
||||
public ApiResponse<Map<String, String>> playback(@PathVariable Long id) {
|
||||
return ApiResponse.ok(Map.of("url", recordings.playback(me(), id)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/recordings/{id}")
|
||||
public ApiResponse<Void> deleteRecording(@PathVariable Long id) {
|
||||
recordings.delete(me(), id);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@PostMapping("/recordings/{id}/retry")
|
||||
public ApiResponse<Recording> retryRecording(@PathVariable Long id) {
|
||||
return ApiResponse.ok(recordings.retry(me(), id));
|
||||
}
|
||||
|
||||
@GetMapping("/recordings/usage")
|
||||
public ApiResponse<Map<String, Long>> usage() {
|
||||
Long schoolId = me().superAdmin() ? null : me().schoolId();
|
||||
return ApiResponse.ok(Map.of("bytes", recordings.storedBytes(schoolId), "failed", recordings.failedCount(schoolId)));
|
||||
}
|
||||
|
||||
@GetMapping("/inspections")
|
||||
public ApiResponse<PagePayload<InspectionRecord>> inspections(@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
var result = me().superAdmin()
|
||||
? inspections.findAll(Pages.of(page, size))
|
||||
: inspections.findBySchoolId(me().schoolId(), Pages.of(page, size));
|
||||
return ApiResponse.ok(new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize()));
|
||||
}
|
||||
|
||||
@PostMapping("/inspections")
|
||||
public ApiResponse<InspectionRecord> createInspection(@RequestBody InspectionRecord request) {
|
||||
request.setId(null);
|
||||
request.setInspectorId(me().id());
|
||||
if (!me().superAdmin()) {
|
||||
request.setSchoolId(me().schoolId());
|
||||
}
|
||||
if (request.getInspectedAt() == null) {
|
||||
request.setInspectedAt(Instant.now());
|
||||
}
|
||||
return ApiResponse.ok(inspections.save(request));
|
||||
}
|
||||
|
||||
@GetMapping("/dashboard")
|
||||
public ApiResponse<Map<String, Object>> dashboard() {
|
||||
UserPrincipal me = me();
|
||||
Long schoolId = me.superAdmin() ? null : me.schoolId();
|
||||
Instant start = LocalDate.now(ZoneId.of("Asia/Shanghai")).atStartOfDay(ZoneId.of("Asia/Shanghai")).toInstant();
|
||||
var today = liveToday(schoolId, start);
|
||||
Map<String, Object> stats = new LinkedHashMap<>();
|
||||
stats.put("users", schoolId == null ? users.count() : users.countBySchoolId(schoolId));
|
||||
stats.put("parents", bindingRepository.countApprovedParents(schoolId));
|
||||
stats.put("teachers", users.countByRole(com.xh.xunke.user.RoleName.TEACHER, schoolId));
|
||||
stats.put("classes", schools.countClasses(schoolId));
|
||||
stats.put("liveNow", live.liveCount(schoolId));
|
||||
stats.put("viewersNow", sessions.findByStatusIn(java.util.List.of("LIVE")).stream()
|
||||
.filter(session -> schoolId == null || schoolId.equals(session.getSchoolId()))
|
||||
.mapToInt(session -> live.countViewers(session.getId()))
|
||||
.sum());
|
||||
stats.put("liveToday", today.count());
|
||||
stats.put("liveMinutesToday", today.minutes());
|
||||
stats.put("recordings", recordings.completedCount(schoolId));
|
||||
stats.put("storageBytes", recordings.storedBytes(schoolId));
|
||||
return ApiResponse.ok(stats);
|
||||
}
|
||||
|
||||
@GetMapping("/parent/home")
|
||||
public ApiResponse<Map<String, Object>> parentHome() {
|
||||
var mine = bindings.list(me(), null, 0, 50);
|
||||
return ApiResponse.ok(Map.of("bindings", mine.items(), "lives", live.list(me(), "LIVE", 0, 20).items()));
|
||||
}
|
||||
|
||||
@GetMapping("/admin/settings")
|
||||
public ApiResponse<Map<String, String>> allSettings() {
|
||||
return ApiResponse.ok(settings.byPrefix(""));
|
||||
}
|
||||
|
||||
@PutMapping("/admin/settings")
|
||||
public ApiResponse<Void> updateSettings(@RequestBody Map<String, String> body) {
|
||||
settings.update(body);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/admin/smtp")
|
||||
public ApiResponse<Map<String, Object>> smtp() {
|
||||
SmtpSettings row = notifications.smtp();
|
||||
Map<String, Object> view = new LinkedHashMap<>();
|
||||
view.put("host", row.getHost());
|
||||
view.put("port", row.getPort());
|
||||
view.put("username", row.getUsername());
|
||||
view.put("passwordSet", row.getPasswordCipher() != null);
|
||||
view.put("sslEnabled", row.isSslEnabled());
|
||||
view.put("starttls", row.isStarttls());
|
||||
view.put("fromAddress", row.getFromAddress());
|
||||
view.put("fromName", row.getFromName());
|
||||
view.put("enabled", row.isEnabled());
|
||||
return ApiResponse.ok(view);
|
||||
}
|
||||
|
||||
@PutMapping("/admin/smtp")
|
||||
public ApiResponse<Void> saveSmtp(@RequestBody SmtpBody body) {
|
||||
SmtpSettings row = new SmtpSettings();
|
||||
row.setHost(body.host());
|
||||
row.setPort(body.port());
|
||||
row.setUsername(body.username());
|
||||
row.setSslEnabled(body.sslEnabled());
|
||||
row.setStarttls(body.starttls());
|
||||
row.setFromAddress(body.fromAddress());
|
||||
row.setFromName(body.fromName());
|
||||
row.setEnabled(body.enabled());
|
||||
notifications.saveSmtp(row, body.password());
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@PostMapping("/admin/smtp/test")
|
||||
public ApiResponse<Void> testSmtp(@RequestBody Map<String, String> body) {
|
||||
notifications.testMail(body.get("to"));
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/admin/sms")
|
||||
public ApiResponse<Map<String, Object>> sms() {
|
||||
SmsSettings row = notifications.sms();
|
||||
Map<String, Object> view = new LinkedHashMap<>();
|
||||
view.put("provider", row.getProvider());
|
||||
view.put("apiUrl", row.getApiUrl());
|
||||
view.put("signName", row.getSignName());
|
||||
view.put("templateId", row.getTemplateId());
|
||||
view.put("region", row.getRegion());
|
||||
view.put("sdkAppId", row.getSdkAppId());
|
||||
view.put("enabled", row.isEnabled());
|
||||
view.put("accessKeySet", row.getAccessKeyCipher() != null);
|
||||
view.put("secretSet", row.getSecretCipher() != null);
|
||||
return ApiResponse.ok(view);
|
||||
}
|
||||
|
||||
@PutMapping("/admin/sms")
|
||||
public ApiResponse<Void> saveSms(@RequestBody SmsBody body) {
|
||||
SmsSettings row = new SmsSettings();
|
||||
row.setProvider(body.provider());
|
||||
row.setApiUrl(body.apiUrl());
|
||||
row.setSignName(body.signName());
|
||||
row.setTemplateId(body.templateId());
|
||||
row.setRegion(body.region());
|
||||
row.setSdkAppId(body.sdkAppId());
|
||||
row.setEnabled(body.enabled());
|
||||
notifications.saveSms(row, body.accessKey(), body.secret());
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@PostMapping("/admin/sms/test")
|
||||
public ApiResponse<Void> testSms(@RequestBody Map<String, String> body) {
|
||||
notifications.testSms(body.get("phone"));
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/admin/templates")
|
||||
public ApiResponse<List<NotificationTemplate>> templates() {
|
||||
return ApiResponse.ok(notifications.listTemplates());
|
||||
}
|
||||
|
||||
@PutMapping("/admin/templates")
|
||||
public ApiResponse<NotificationTemplate> saveTemplate(@RequestBody NotificationTemplate template) {
|
||||
return ApiResponse.ok(notifications.saveTemplate(template));
|
||||
}
|
||||
|
||||
@GetMapping("/admin/notifications")
|
||||
public ApiResponse<?> notificationLogs(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) {
|
||||
return ApiResponse.ok(notifications.logs(page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/admin/status")
|
||||
public ApiResponse<Map<String, Object>> status() {
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
Map<String, Object> status = new LinkedHashMap<>();
|
||||
status.put("livekit", liveKitUp());
|
||||
status.put("storage", storage.reachable());
|
||||
status.put("heapUsed", runtime.totalMemory() - runtime.freeMemory());
|
||||
status.put("heapMax", runtime.maxMemory());
|
||||
status.put("uptimeSeconds", ManagementFactory.getRuntimeMXBean().getUptime() / 1000);
|
||||
status.put("failedRecordings", recordings.failedCount(me().superAdmin() ? null : me().schoolId()));
|
||||
return ApiResponse.ok(status);
|
||||
}
|
||||
|
||||
@GetMapping("/admin/audits")
|
||||
public ApiResponse<?> audits(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) {
|
||||
var result = audit.audits(Pages.of(page, size));
|
||||
return ApiResponse.ok(new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize()));
|
||||
}
|
||||
|
||||
@GetMapping("/admin/login-logs")
|
||||
public ApiResponse<?> loginLogs(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) {
|
||||
var result = audit.logins(Pages.of(page, size));
|
||||
return ApiResponse.ok(new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize()));
|
||||
}
|
||||
|
||||
@PostMapping("/internal/livekit/webhook")
|
||||
public ApiResponse<Void> webhook(@RequestBody String body, jakarta.servlet.http.HttpServletRequest request) {
|
||||
recordings.onWebhook(body, request.getHeader("Authorization"));
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
private boolean liveKitUp() {
|
||||
return liveKit.reachable();
|
||||
}
|
||||
|
||||
private Today liveToday(Long schoolId, Instant start) {
|
||||
var rows = sessions.startedSince(start, schoolId);
|
||||
long minutes = rows.stream().mapToLong(session -> {
|
||||
if (session.getStartedAt() == null) {
|
||||
return 0;
|
||||
}
|
||||
Instant end = session.getEndedAt() == null ? Instant.now() : session.getEndedAt();
|
||||
return Math.max(0, java.time.Duration.between(session.getStartedAt(), end).toMinutes());
|
||||
}).sum();
|
||||
return new Today(rows.size(), minutes);
|
||||
}
|
||||
|
||||
private UserPrincipal me() {
|
||||
return CurrentUsers.get();
|
||||
}
|
||||
|
||||
private record Today(long count, long minutes) {
|
||||
}
|
||||
|
||||
public record SmtpBody(String host, Integer port, String username, String password, boolean sslEnabled,
|
||||
boolean starttls, String fromAddress, String fromName, boolean enabled) {
|
||||
}
|
||||
|
||||
public record SmsBody(@NotBlank String provider, String apiUrl, String accessKey, String secret, String signName,
|
||||
String templateId, String region, String sdkAppId, boolean enabled) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
server:
|
||||
port: ${SERVER_PORT:8080}
|
||||
forward-headers-strategy: framework
|
||||
shutdown: graceful
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: xuenke
|
||||
datasource:
|
||||
url: ${DB_URL:jdbc:postgresql://postgres:5432/xuenke}
|
||||
username: ${DB_USER:xuenke}
|
||||
password: ${DB_PASSWORD:xuenke}
|
||||
hikari:
|
||||
maximum-pool-size: ${DB_POOL:20}
|
||||
minimum-idle: 2
|
||||
connection-timeout: 5000
|
||||
jpa:
|
||||
open-in-view: false
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
properties:
|
||||
hibernate.jdbc.time_zone: UTC
|
||||
flyway:
|
||||
enabled: true
|
||||
data:
|
||||
redis:
|
||||
host: ${REDIS_HOST:redis}
|
||||
port: ${REDIS_PORT:6379}
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 2MB
|
||||
max-request-size: 2MB
|
||||
jackson:
|
||||
serialization:
|
||||
write-dates-as-timestamps: false
|
||||
|
||||
app:
|
||||
jwt-secret: ${JWT_SECRET:dev-only-change-this-jwt-secret-32b}
|
||||
jwt-access-minutes: 15
|
||||
jwt-refresh-days: 7
|
||||
encryption-key: ${APP_ENCRYPTION_KEY:dev-only-change-this-encryption-key!!}
|
||||
admin-username: ${ADMIN_USERNAME:admin}
|
||||
admin-password: ${ADMIN_PASSWORD:ChangeMe_Admin_2026!}
|
||||
admin-display-name: ${ADMIN_DISPLAY_NAME:系统管理员}
|
||||
livekit-url: ${LIVEKIT_URL:ws://localhost:7880}
|
||||
livekit-key: ${LIVEKIT_API_KEY:devkey}
|
||||
livekit-secret: ${LIVEKIT_API_SECRET:devsecret_change_me_32_characters}
|
||||
minio-endpoint: ${MINIO_ENDPOINT:http://minio:9000}
|
||||
minio-public-endpoint: ${MINIO_PUBLIC_ENDPOINT:http://localhost:9000}
|
||||
minio-access: ${MINIO_ACCESS_KEY:xuenke}
|
||||
minio-secret: ${MINIO_SECRET_KEY:xuenke-minio-secret}
|
||||
minio-bucket: ${MINIO_BUCKET:xuenke-recordings}
|
||||
cors-origins: ${CORS_ORIGINS:http://localhost:5173,http://localhost,http://localhost:8088}
|
||||
prod-guard: ${APP_PROD_GUARD:false}
|
||||
ffprobe-path: ${FFPROBE_PATH:ffprobe}
|
||||
cookie-secure: ${COOKIE_SECURE:false}
|
||||
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: health,info
|
||||
endpoint:
|
||||
health:
|
||||
probes:
|
||||
enabled: true
|
||||
show-details: never
|
||||
@@ -0,0 +1,288 @@
|
||||
CREATE TABLE schools (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
code VARCHAR(32) NOT NULL UNIQUE,
|
||||
logo_url TEXT,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
|
||||
address VARCHAR(255),
|
||||
contact_name VARCHAR(64),
|
||||
contact_phone VARCHAR(32),
|
||||
live_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
record_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
teacher_public BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
retention_days INT NOT NULL DEFAULT 30,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username VARCHAR(64) NOT NULL UNIQUE,
|
||||
email VARCHAR(255) UNIQUE,
|
||||
phone VARCHAR(20) UNIQUE,
|
||||
password_hash VARCHAR(100) NOT NULL,
|
||||
display_name VARCHAR(64) NOT NULL,
|
||||
status VARCHAR(20) NOT NULL,
|
||||
email_verified BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
phone_verified BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
school_id BIGINT REFERENCES schools (id),
|
||||
token_version INT NOT NULL DEFAULT 0,
|
||||
failed_logins INT NOT NULL DEFAULT 0,
|
||||
locked_until TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX idx_users_school ON users (school_id);
|
||||
CREATE INDEX idx_users_status ON users (status);
|
||||
|
||||
CREATE TABLE user_roles (
|
||||
user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
role VARCHAR(32) NOT NULL,
|
||||
PRIMARY KEY (user_id, role)
|
||||
);
|
||||
|
||||
CREATE TABLE grades (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
school_id BIGINT NOT NULL REFERENCES schools (id),
|
||||
name VARCHAR(64) NOT NULL,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
UNIQUE (school_id, name)
|
||||
);
|
||||
CREATE INDEX idx_grades_school ON grades (school_id);
|
||||
|
||||
CREATE TABLE classes (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
school_id BIGINT NOT NULL REFERENCES schools (id),
|
||||
grade_id BIGINT NOT NULL REFERENCES grades (id),
|
||||
name VARCHAR(64) NOT NULL,
|
||||
head_teacher_id BIGINT REFERENCES users (id),
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (school_id, grade_id, name)
|
||||
);
|
||||
CREATE INDEX idx_classes_school ON classes (school_id);
|
||||
CREATE INDEX idx_classes_grade ON classes (grade_id);
|
||||
|
||||
CREATE TABLE class_teachers (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
class_id BIGINT NOT NULL REFERENCES classes (id) ON DELETE CASCADE,
|
||||
teacher_id BIGINT NOT NULL REFERENCES users (id),
|
||||
subject VARCHAR(64),
|
||||
is_head BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
UNIQUE (class_id, teacher_id)
|
||||
);
|
||||
CREATE INDEX idx_class_teachers_teacher ON class_teachers (teacher_id);
|
||||
|
||||
CREATE TABLE students (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
school_id BIGINT NOT NULL REFERENCES schools (id),
|
||||
class_id BIGINT NOT NULL REFERENCES classes (id),
|
||||
name VARCHAR(64) NOT NULL,
|
||||
student_no VARCHAR(32) NOT NULL,
|
||||
UNIQUE (school_id, student_no)
|
||||
);
|
||||
CREATE INDEX idx_students_class ON students (class_id);
|
||||
|
||||
CREATE TABLE parent_bindings (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
parent_id BIGINT NOT NULL REFERENCES users (id),
|
||||
student_id BIGINT NOT NULL REFERENCES students (id),
|
||||
class_id BIGINT NOT NULL REFERENCES classes (id),
|
||||
school_id BIGINT NOT NULL REFERENCES schools (id),
|
||||
relationship VARCHAR(32) NOT NULL,
|
||||
live_granted BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
replay_granted BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
status VARCHAR(20) NOT NULL,
|
||||
review_note VARCHAR(500),
|
||||
reviewer_id BIGINT REFERENCES users (id),
|
||||
reviewed_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE UNIQUE INDEX uq_binding_open ON parent_bindings (parent_id, student_id)
|
||||
WHERE status IN ('PENDING', 'APPROVED');
|
||||
CREATE INDEX idx_bindings_parent ON parent_bindings (parent_id, status);
|
||||
CREATE INDEX idx_bindings_class ON parent_bindings (class_id, status);
|
||||
|
||||
CREATE TABLE courses (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
school_id BIGINT NOT NULL REFERENCES schools (id),
|
||||
class_id BIGINT NOT NULL REFERENCES classes (id),
|
||||
teacher_id BIGINT NOT NULL REFERENCES users (id),
|
||||
name VARCHAR(128) NOT NULL,
|
||||
allow_live BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
allow_record BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
description VARCHAR(500),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX idx_courses_class ON courses (class_id);
|
||||
|
||||
CREATE TABLE periods (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
school_id BIGINT NOT NULL REFERENCES schools (id),
|
||||
name VARCHAR(32) NOT NULL,
|
||||
start_time TIME NOT NULL,
|
||||
end_time TIME NOT NULL,
|
||||
sort_order INT NOT NULL,
|
||||
UNIQUE (school_id, name)
|
||||
);
|
||||
CREATE INDEX idx_periods_school ON periods (school_id);
|
||||
|
||||
CREATE TABLE timetable_entries (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
school_id BIGINT NOT NULL REFERENCES schools (id),
|
||||
class_id BIGINT NOT NULL REFERENCES classes (id),
|
||||
course_id BIGINT NOT NULL REFERENCES courses (id),
|
||||
teacher_id BIGINT NOT NULL REFERENCES users (id),
|
||||
period_id BIGINT NOT NULL REFERENCES periods (id),
|
||||
weekday INT NOT NULL CHECK (weekday BETWEEN 1 AND 7),
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
|
||||
lesson_date DATE,
|
||||
note VARCHAR(255)
|
||||
);
|
||||
CREATE UNIQUE INDEX uq_timetable_weekly ON timetable_entries (class_id, weekday, period_id)
|
||||
WHERE lesson_date IS NULL AND status <> 'CANCELLED';
|
||||
CREATE INDEX idx_timetable_class ON timetable_entries (class_id, weekday);
|
||||
|
||||
CREATE TABLE live_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
school_id BIGINT NOT NULL REFERENCES schools (id),
|
||||
class_id BIGINT NOT NULL REFERENCES classes (id),
|
||||
course_id BIGINT NOT NULL REFERENCES courses (id),
|
||||
teacher_id BIGINT NOT NULL REFERENCES users (id),
|
||||
room_name VARCHAR(160) NOT NULL UNIQUE,
|
||||
status VARCHAR(20) NOT NULL,
|
||||
started_at TIMESTAMPTZ,
|
||||
ended_at TIMESTAMPTZ,
|
||||
end_reason VARCHAR(32),
|
||||
video_device VARCHAR(255),
|
||||
audio_device VARCHAR(255),
|
||||
viewer_peak INT NOT NULL DEFAULT 0,
|
||||
record_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
last_heartbeat_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE UNIQUE INDEX uq_live_class ON live_sessions (class_id)
|
||||
WHERE status IN ('PREPARING', 'LIVE');
|
||||
CREATE INDEX idx_live_school_status ON live_sessions (school_id, status);
|
||||
CREATE INDEX idx_live_started ON live_sessions (started_at);
|
||||
|
||||
CREATE TABLE recordings (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
session_id BIGINT NOT NULL REFERENCES live_sessions (id),
|
||||
school_id BIGINT NOT NULL,
|
||||
class_id BIGINT NOT NULL,
|
||||
egress_id VARCHAR(128),
|
||||
status VARCHAR(32) NOT NULL,
|
||||
bucket VARCHAR(128),
|
||||
object_key VARCHAR(512),
|
||||
file_size BIGINT,
|
||||
duration_seconds INT,
|
||||
has_video BOOLEAN,
|
||||
has_audio BOOLEAN,
|
||||
error_message VARCHAR(1000),
|
||||
retry_count INT NOT NULL DEFAULT 0,
|
||||
started_at TIMESTAMPTZ,
|
||||
ended_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX idx_recordings_session ON recordings (session_id);
|
||||
CREATE INDEX idx_recordings_class ON recordings (class_id, status);
|
||||
|
||||
CREATE TABLE inspection_records (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
school_id BIGINT NOT NULL REFERENCES schools (id),
|
||||
class_id BIGINT NOT NULL REFERENCES classes (id),
|
||||
course_id BIGINT REFERENCES courses (id),
|
||||
teacher_id BIGINT REFERENCES users (id),
|
||||
inspector_id BIGINT NOT NULL REFERENCES users (id),
|
||||
session_id BIGINT REFERENCES live_sessions (id),
|
||||
inspected_at TIMESTAMPTZ NOT NULL,
|
||||
situation VARCHAR(2000),
|
||||
discipline_note VARCHAR(2000),
|
||||
remark VARCHAR(2000),
|
||||
follow_up VARCHAR(2000),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX idx_inspections_school ON inspection_records (school_id, inspected_at);
|
||||
|
||||
CREATE TABLE system_settings (
|
||||
setting_key VARCHAR(128) PRIMARY KEY,
|
||||
setting_value TEXT NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE smtp_settings (
|
||||
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||||
host VARCHAR(255),
|
||||
port INT,
|
||||
username VARCHAR(255),
|
||||
password_cipher TEXT,
|
||||
ssl_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
starttls BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
from_address VARCHAR(255),
|
||||
from_name VARCHAR(128),
|
||||
enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE sms_settings (
|
||||
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||||
provider VARCHAR(32) NOT NULL DEFAULT 'simulated',
|
||||
api_url VARCHAR(500),
|
||||
access_key_cipher TEXT,
|
||||
secret_cipher TEXT,
|
||||
sign_name VARCHAR(64),
|
||||
template_id VARCHAR(128),
|
||||
region VARCHAR(64),
|
||||
sdk_app_id VARCHAR(64),
|
||||
enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE notification_templates (
|
||||
code VARCHAR(64) PRIMARY KEY,
|
||||
channel VARCHAR(16) NOT NULL,
|
||||
subject VARCHAR(255),
|
||||
body TEXT NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE notification_logs (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
channel VARCHAR(16) NOT NULL,
|
||||
target_mask VARCHAR(128) NOT NULL,
|
||||
template_code VARCHAR(64),
|
||||
success BOOLEAN NOT NULL,
|
||||
error_message VARCHAR(500),
|
||||
simulated BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX idx_notification_logs_created ON notification_logs (created_at);
|
||||
|
||||
CREATE TABLE login_logs (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT,
|
||||
username VARCHAR(64) NOT NULL,
|
||||
success BOOLEAN NOT NULL,
|
||||
ip VARCHAR(64),
|
||||
user_agent VARCHAR(255),
|
||||
reason VARCHAR(128),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX idx_login_logs_created ON login_logs (created_at);
|
||||
|
||||
CREATE TABLE audit_logs (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
actor_id BIGINT,
|
||||
actor_name VARCHAR(64),
|
||||
action VARCHAR(64) NOT NULL,
|
||||
resource_type VARCHAR(64),
|
||||
resource_id VARCHAR(64),
|
||||
detail VARCHAR(1000),
|
||||
ip VARCHAR(64),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX idx_audit_created ON audit_logs (created_at);
|
||||
@@ -0,0 +1,43 @@
|
||||
INSERT INTO system_settings (setting_key, setting_value) VALUES
|
||||
('site.name.zh', 'XH巡课'),
|
||||
('site.name.en', 'XH Classroom Monitor'),
|
||||
('site.logo', ''),
|
||||
('site.favicon', ''),
|
||||
('site.intro', '面向学校的课堂直播、巡课与课程回放系统。观看权限只发给经过审核的家长和教职工。'),
|
||||
('site.title', 'XH巡课'),
|
||||
('site.seo.description', 'XH巡课是校园课堂直播与回放系统。'),
|
||||
('site.seo.keywords', '巡课,课堂直播,课程回放'),
|
||||
('site.seo.robots', 'noindex,nofollow'),
|
||||
('site.announcement', ''),
|
||||
('site.footer', '课堂画面只对获得授权的家长和教职工开放'),
|
||||
('site.contact', ''),
|
||||
('site.theme.color', '#1677ff'),
|
||||
('site.theme.mode', 'light'),
|
||||
('site.terms', '使用本系统前,学校应完成告知并取得适用的授权。教师主动开启采集,可随时停止。系统不进行隐蔽录像。'),
|
||||
('site.privacy', '课堂音视频属于敏感信息。家长只能查看已审核班级的直播或回放。录像按学校设定的期限保存,到期删除。系统不对未成年学生做自动身份识别或纪律评分。'),
|
||||
('reg.enabled', 'true'),
|
||||
('reg.emailVerify', 'false'),
|
||||
('reg.smsVerify', 'false'),
|
||||
('reg.requireApproval', 'true'),
|
||||
('reg.allowUsername', 'true'),
|
||||
('reg.allowEmail', 'true'),
|
||||
('reg.allowPhone', 'true'),
|
||||
('sec.password.min', '8'),
|
||||
('sec.password.mix', 'true'),
|
||||
('sec.login.maxFail', '5'),
|
||||
('sec.login.lockMinutes', '15'),
|
||||
('live.maxMinutes', '120'),
|
||||
('live.disconnectSeconds', '60'),
|
||||
('live.prepareTimeoutSeconds', '120'),
|
||||
('recording.retentionDays', '30');
|
||||
|
||||
INSERT INTO smtp_settings (id, enabled) VALUES (1, FALSE);
|
||||
INSERT INTO sms_settings (id, provider, enabled) VALUES (1, 'simulated', FALSE);
|
||||
|
||||
INSERT INTO notification_templates (code, channel, subject, body) VALUES
|
||||
('REGISTER_CODE', 'mail', '注册验证码', '你的注册验证码是 {{code}},5 分钟内有效。'),
|
||||
('RESET_CODE', 'mail', '重置密码验证码', '你的重置验证码是 {{code}},5 分钟内有效。'),
|
||||
('ACCOUNT_REVIEW', 'mail', '账号审核结果', '{{name}},你的账号审核结果:{{result}}。'),
|
||||
('BINDING_RESULT', 'mail', '班级绑定结果', '{{name}},班级绑定审核结果:{{result}}。'),
|
||||
('LIVE_STARTED', 'mail', '课程开始直播', '{{className}} 的 {{courseName}} 已开始直播。'),
|
||||
('RECORDING_READY', 'mail', '课程回放已生成', '{{courseName}} 的回放已可观看。');
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.xh.xunke.security;
|
||||
|
||||
import com.xh.xunke.common.BizException;
|
||||
import com.xh.xunke.live.LiveAuthorization;
|
||||
import com.xh.xunke.recording.ProbeParser;
|
||||
import com.xh.xunke.school.BindingRules;
|
||||
import com.xh.xunke.user.RegistrationPolicy;
|
||||
import com.xh.xunke.user.RoleName;
|
||||
import com.xh.xunke.user.UserStatus;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class PolicyTest {
|
||||
@Test
|
||||
void passwordMustMixLettersAndDigits() {
|
||||
PasswordPolicy.checkRaw("abc12345", 8, true);
|
||||
assertThatThrownBy(() -> PasswordPolicy.checkRaw("abcdefgh", 8, true)).isInstanceOf(BizException.class);
|
||||
assertThatThrownBy(() -> PasswordPolicy.checkRaw("12345678", 8, true)).isInstanceOf(BizException.class);
|
||||
assertThatThrownBy(() -> PasswordPolicy.checkRaw("short1", 8, true)).isInstanceOf(BizException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publicRegistrationIsParentAndCanBeClosed() {
|
||||
assertThat(RegistrationPolicy.publicRoles()).containsExactly(RoleName.PARENT);
|
||||
assertThat(RegistrationPolicy.initialStatus(true)).isEqualTo(UserStatus.PENDING);
|
||||
assertThat(RegistrationPolicy.initialStatus(false)).isEqualTo(UserStatus.ACTIVE);
|
||||
assertThatThrownBy(() -> RegistrationPolicy.assertOpen(false)).isInstanceOf(BizException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void liveRoomsStayIsolatedAndParentsCannotPublish() {
|
||||
assertThat(LiveAuthorization.roomName(1, 2, "a")).isNotEqualTo(LiveAuthorization.roomName(1, 3, "a"));
|
||||
assertThat(LiveAuthorization.decide(true, "PREPARING", true, false, false))
|
||||
.isEqualTo(LiveAuthorization.Kind.PUBLISH);
|
||||
assertThat(LiveAuthorization.decide(false, "LIVE", false, false, true))
|
||||
.isEqualTo(LiveAuthorization.Kind.SUBSCRIBE);
|
||||
assertThatThrownBy(() -> LiveAuthorization.decide(true, "LIVE", false, true, true))
|
||||
.isInstanceOf(BizException.class);
|
||||
assertThatThrownBy(() -> LiveAuthorization.decide(false, "LIVE", false, false, false))
|
||||
.isInstanceOf(BizException.class);
|
||||
assertThatThrownBy(() -> LiveAuthorization.decide(false, "ENDED", true, true, true))
|
||||
.isInstanceOf(BizException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void replayAndLiveGrantsAreIndependent() {
|
||||
assertThat(BindingRules.canWatch("APPROVED", true)).isTrue();
|
||||
assertThat(BindingRules.canWatch("APPROVED", false)).isFalse();
|
||||
assertThat(BindingRules.canWatch("PENDING", true)).isFalse();
|
||||
assertThat(BindingRules.canWatch("REVOKED", true)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void probeRequiresBothAudioAndVideo() {
|
||||
String json = "{\"streams\":[{\"codec_type\":\"video\"},{\"codec_type\":\"audio\"}]}";
|
||||
assertThat(ProbeParser.parse(json).video()).isTrue();
|
||||
assertThat(ProbeParser.parse(json).audio()).isTrue();
|
||||
assertThat(ProbeParser.parse("{\"streams\":[{\"codec_type\":\"video\"}]}").audio()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void parentsCannotManageTheSchool() {
|
||||
var parent = new UserPrincipal(1L, "parent", "家长", null, Set.of(RoleName.PARENT), 0);
|
||||
var admin = new UserPrincipal(2L, "admin", "管理员", null, Set.of(RoleName.SUPER_ADMIN), 0);
|
||||
assertThat(StaffApiFilter.allowed(parent, "POST", "/api/schools")).isFalse();
|
||||
assertThat(StaffApiFilter.allowed(parent, "GET", "/api/dashboard")).isFalse();
|
||||
assertThat(StaffApiFilter.allowed(parent, "GET", "/api/parent/home")).isTrue();
|
||||
assertThat(StaffApiFilter.allowed(admin, "POST", "/api/schools")).isTrue();
|
||||
assertThat(StaffApiFilter.allowed(admin, "GET", "/api/admin/audits")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretsRoundTrip() {
|
||||
SecretCipher cipher = new SecretCipher("test-key");
|
||||
String encrypted = cipher.encrypt("smtp-secret");
|
||||
assertThat(encrypted).doesNotContain("smtp-secret");
|
||||
assertThat(cipher.decrypt(encrypted)).isEqualTo("smtp-secret");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
log_level: info
|
||||
api_key: devkey
|
||||
api_secret: devsecret_change_me_32_characters
|
||||
ws_url: ws://livekit:7880
|
||||
insecure: true
|
||||
redis:
|
||||
address: redis:6379
|
||||
@@ -0,0 +1,16 @@
|
||||
port: 7880
|
||||
bind_addresses:
|
||||
- ""
|
||||
rtc:
|
||||
tcp_port: 7881
|
||||
port_range_start: 50000
|
||||
port_range_end: 50100
|
||||
use_external_ip: false
|
||||
redis:
|
||||
address: redis:6379
|
||||
keys:
|
||||
devkey: devsecret_change_me_32_characters
|
||||
webhook:
|
||||
api_key: devkey
|
||||
urls:
|
||||
- http://backend:8080/api/internal/livekit/webhook
|
||||
@@ -0,0 +1,108 @@
|
||||
name: xuenke
|
||||
|
||||
x-logging: &logging
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_USER: ${DB_USER:-xuenke}
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-xuenke}
|
||||
POSTGRES_DB: xuenke
|
||||
volumes:
|
||||
- pg-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USER:-xuenke}"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
logging: *logging
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
command: ["redis-server", "--appendonly", "yes"]
|
||||
volumes:
|
||||
- redis-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
logging: *logging
|
||||
|
||||
minio:
|
||||
image: alpine/minio:RELEASE.2025-10-15T17-29-55Z
|
||||
command: server /data --console-address ":9001"
|
||||
user: "0:0"
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ACCESS_KEY:-xuenke}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_SECRET_KEY:-xuenke-minio-secret}
|
||||
ports:
|
||||
- "9000:9000"
|
||||
- "9001:9001"
|
||||
volumes:
|
||||
- minio-data:/data
|
||||
logging: *logging
|
||||
|
||||
livekit:
|
||||
image: livekit/livekit-server:v1.13.11
|
||||
command: --config /etc/livekit.yaml
|
||||
volumes:
|
||||
- ./deploy/livekit.yaml:/etc/livekit.yaml:ro
|
||||
ports:
|
||||
- "7880:7880"
|
||||
- "7881:7881"
|
||||
- "50000-50100:50000-50100/udp"
|
||||
depends_on:
|
||||
redis:
|
||||
condition: service_healthy
|
||||
logging: *logging
|
||||
|
||||
egress:
|
||||
image: livekit/egress:v1.13.0
|
||||
environment:
|
||||
EGRESS_CONFIG_FILE: /etc/egress.yaml
|
||||
volumes:
|
||||
- ./deploy/egress.yaml:/etc/egress.yaml:ro
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
depends_on:
|
||||
- livekit
|
||||
- redis
|
||||
- minio
|
||||
logging: *logging
|
||||
|
||||
backend:
|
||||
build: ./backend
|
||||
env_file: .env
|
||||
environment:
|
||||
DB_URL: jdbc:postgresql://postgres:5432/xuenke
|
||||
REDIS_HOST: redis
|
||||
MINIO_ENDPOINT: http://minio:9000
|
||||
MINIO_PUBLIC_ENDPOINT: http://localhost:9000
|
||||
LIVEKIT_URL: ws://livekit:7880
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "8080:8080"
|
||||
logging: *logging
|
||||
|
||||
web:
|
||||
build: ./frontend
|
||||
depends_on:
|
||||
- backend
|
||||
ports:
|
||||
- "18088:80"
|
||||
logging: *logging
|
||||
|
||||
volumes:
|
||||
pg-data:
|
||||
redis-data:
|
||||
minio-data:
|
||||
@@ -0,0 +1,14 @@
|
||||
# 架构
|
||||
|
||||
教师浏览器分别采集摄像头和麦克风,经 WebRTC 推到 LiveKit 房间。房间名是 `xh-{学校}-{班级}-{会话}`。后端在确认音视频发布后把会话标为 LIVE,家长只拿订阅令牌。录像由 LiveKit Egress 直接写入 MinIO,后端只保存元数据和短时播放地址。
|
||||
|
||||
## 运行单元
|
||||
|
||||
- `frontend`:Vue 3、Vite、Element Plus、LiveKit Client。
|
||||
- `backend`:Spring Boot 3.5.16。Controller 只接收请求,规则在 Service。
|
||||
- PostgreSQL:用户、学校、授权、课程、直播和录像元数据。
|
||||
- Redis:验证码、刷新令牌、限流、设置版本和观看心跳。
|
||||
- LiveKit / Egress:实时分发和合成录像。
|
||||
- MinIO:私有录像文件。
|
||||
|
||||
Java 工具链是 Docker 镜像 `maven:3.9.11-eclipse-temurin-21` 和 `eclipse-temurin:21-jre`,不进入宿主机 PATH。
|
||||
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user