直播观看与录像链路真实验证通过,前端 UI 全面重做,分角色控制台
- 修复: LiveKit 回环候选生效(宿主机浏览器可直连推流) - 修复: 回放预签名 URL 403(公开端点直接签名,SignedHeaders=host) - 修复: 录像探针补 fileSize/durationSeconds - 修复: 家长录像列表被权限过滤误伤为 0 条;教师/家长列表按角色精确隔离 - 修复: 巡课静音失效(LiveKit attach 强制 unmute,静音时不挂载音轨) - 修复: 教室页自动请求摄像头/麦克风权限,分辨率失败自动降级 - 新增: 浏览器端到端验证脚本 scripts/e2e-browser.mjs(9 项断言全过: 教师推流/家长观看含音频电平实测/巡课默认静音/Egress 录像双轨齐全/ DPlayer 回放/录像权限隔离) - 新增: /parent/today 家长今日课程表、网站 Logo 上传与公开读取 - UI 重做: 虎牙风直播播放器 + DPlayer 回放播放器(视觉统一) - 分角色控制台: 管理端 /admin(16 模块)、教师端 /teacher、家长端 /parent - 直播/录像列表返回班级、课程、教师名称与在线人数 - 18088 本地预览改为 Vite 热更新,README/实现状态文档同步更新 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
1 parent
0afc29d431
commit
ed55053b10
66 files changed
+7048
-1028
No files matched your search
@@ -6,6 +6,8 @@ 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 com.xh.xunke.user.UserAccount;
|
||||
import com.xh.xunke.user.UserRepository;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -13,8 +15,13 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class CourseService {
|
||||
@@ -22,12 +29,15 @@ public class CourseService {
|
||||
private final PeriodRepository periods;
|
||||
private final TimetableRepository timetable;
|
||||
private final SchoolService schools;
|
||||
private final UserRepository users;
|
||||
|
||||
public CourseService(CourseRepository courses, PeriodRepository periods, TimetableRepository timetable, SchoolService schools) {
|
||||
public CourseService(CourseRepository courses, PeriodRepository periods, TimetableRepository timetable,
|
||||
SchoolService schools, UserRepository users) {
|
||||
this.courses = courses;
|
||||
this.periods = periods;
|
||||
this.timetable = timetable;
|
||||
this.schools = schools;
|
||||
this.users = users;
|
||||
}
|
||||
|
||||
public record CourseRequest(@NotNull Long classId, @NotNull Long teacherId, @NotBlank String name,
|
||||
@@ -191,6 +201,35 @@ public class CourseService {
|
||||
return saved;
|
||||
}
|
||||
|
||||
/** 家长今日课程表:按绑定班级汇总今天的课节,带时间与名称。 */
|
||||
public List<Map<String, Object>> todayViews(List<Long> classIds) {
|
||||
ZoneId zone = ZoneId.of("Asia/Shanghai");
|
||||
LocalTime now = LocalTime.now(zone);
|
||||
DateTimeFormatter hm = DateTimeFormatter.ofPattern("HH:mm");
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
for (Long classId : classIds) {
|
||||
for (TimetableEntry entry : today(classId)) {
|
||||
Period period = periods.findById(entry.getPeriodId()).orElse(null);
|
||||
if (period == null) {
|
||||
continue;
|
||||
}
|
||||
Course course = courses.findById(entry.getCourseId()).orElse(null);
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("classId", classId);
|
||||
row.put("className", schools.className(classId));
|
||||
row.put("courseName", course == null ? "课程" : course.getName());
|
||||
row.put("teacherName", users.findById(entry.getTeacherId()).map(UserAccount::getDisplayName).orElse("教师"));
|
||||
row.put("startTime", period.getStartTime().format(hm));
|
||||
row.put("endTime", period.getEndTime().format(hm));
|
||||
row.put("phase", now.isBefore(period.getStartTime()) ? "later" : now.isAfter(period.getEndTime()) ? "done" : "now");
|
||||
rows.add(row);
|
||||
}
|
||||
}
|
||||
rows.sort(Comparator.comparing((Map<String, Object> row) -> String.valueOf(row.get("startTime")))
|
||||
.thenComparing(row -> String.valueOf(row.get("className"))));
|
||||
return rows;
|
||||
}
|
||||
|
||||
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"));
|
||||
|
||||
@@ -56,6 +56,22 @@ public class LiveKitGateway {
|
||||
}
|
||||
}
|
||||
|
||||
public void removeParticipantsWithPrefix(String room, String prefix) {
|
||||
try {
|
||||
var response = api.getRoom().listParticipants(room).execute();
|
||||
if (!response.isSuccessful() || response.body() == null) {
|
||||
return;
|
||||
}
|
||||
for (var participant : response.body()) {
|
||||
if (participant.getIdentity().startsWith(prefix)) {
|
||||
api.getRoom().removeParticipant(room, participant.getIdentity()).execute();
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.warn("移出直播参与者失败");
|
||||
}
|
||||
}
|
||||
|
||||
public String startEgress(String room, String objectKey) {
|
||||
try {
|
||||
LivekitEgress.S3Upload s3 = LivekitEgress.S3Upload.newBuilder()
|
||||
|
||||
@@ -16,6 +16,10 @@ public interface LiveSessionRepository extends JpaRepository<LiveSession, Long>
|
||||
|
||||
Page<LiveSession> findByStatus(String status, Pageable pageable);
|
||||
|
||||
List<LiveSession> findByTeacherId(Long teacherId);
|
||||
|
||||
Page<LiveSession> findByClassIdInAndStatus(List<Long> classIds, String status, Pageable pageable);
|
||||
|
||||
List<LiveSession> findByStatusIn(List<String> statuses);
|
||||
|
||||
long countByStatus(String status);
|
||||
|
||||
@@ -15,12 +15,15 @@ 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 com.xh.xunke.user.UserAccount;
|
||||
import com.xh.xunke.user.UserRepository;
|
||||
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.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -38,11 +41,12 @@ public class LiveSessionService {
|
||||
private final AccessGuard guard;
|
||||
private final StringRedisTemplate redis;
|
||||
private final CourseService courseService;
|
||||
private final UserRepository users;
|
||||
|
||||
public LiveSessionService(LiveSessionRepository sessions, CourseRepository courses, SchoolRepository schools,
|
||||
SchoolService schoolService, BindingService bindings, LiveKitGateway liveKit,
|
||||
RecordingService recordings, SettingsService settings, AccessGuard guard,
|
||||
StringRedisTemplate redis, CourseService courseService) {
|
||||
StringRedisTemplate redis, CourseService courseService, UserRepository users) {
|
||||
this.sessions = sessions;
|
||||
this.courses = courses;
|
||||
this.schools = schools;
|
||||
@@ -54,6 +58,7 @@ public class LiveSessionService {
|
||||
this.guard = guard;
|
||||
this.redis = redis;
|
||||
this.courseService = courseService;
|
||||
this.users = users;
|
||||
}
|
||||
|
||||
public record StartRequest(@NotNull Long classId, @NotNull Long courseId, String videoDevice, String audioDevice) {
|
||||
@@ -91,7 +96,7 @@ public class LiveSessionService {
|
||||
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);
|
||||
String token = liveKit.token(publishIdentity(me), me.displayName(), session.getRoomName(), true);
|
||||
return Map.of("session", session, "url", settings.text("site.name.zh", "XH巡课") == null ? "" : liveUrl(),
|
||||
"livekitUrl", liveUrl(), "token", token);
|
||||
}
|
||||
@@ -139,7 +144,8 @@ public class LiveSessionService {
|
||||
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);
|
||||
String identity = canPublish ? publishIdentity(me) : subscribeIdentity(me);
|
||||
String token = liveKit.token(identity, me.displayName(), session.getRoomName(), canPublish);
|
||||
return new TokenView(liveUrl(), token, session.getRoomName(), kind.name(), session.getId());
|
||||
}
|
||||
|
||||
@@ -156,31 +162,66 @@ public class LiveSessionService {
|
||||
return count;
|
||||
}
|
||||
|
||||
public PagePayload<LiveSession> list(UserPrincipal me, String status, int page, int size) {
|
||||
public PagePayload<Map<String, Object>> 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))
|
||||
.map(this::sessionView)
|
||||
.toList();
|
||||
return new PagePayload<>(allowed, allowed.size(), result.getNumber(), result.getSize());
|
||||
}
|
||||
// 教师:只看到自己任教班级的直播
|
||||
if (me.canTeach() && !me.superAdmin() && !me.schoolStaff()) {
|
||||
List<Long> classIds = schoolService.teacherClassIds(me.id());
|
||||
var result = classIds.isEmpty()
|
||||
? org.springframework.data.domain.Page.<LiveSession>empty(Pages.of(page, size))
|
||||
: sessions.findByClassIdInAndStatus(classIds, wanted, Pages.of(page, size));
|
||||
return new PagePayload<>(result.getContent().stream().map(this::sessionView).toList(),
|
||||
result.getTotalElements(), 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());
|
||||
return new PagePayload<>(result.getContent().stream().map(this::sessionView).toList(),
|
||||
result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
public LiveSession get(UserPrincipal me, Long id) {
|
||||
public Map<String, Object> 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;
|
||||
return sessionView(session);
|
||||
}
|
||||
|
||||
private Map<String, Object> sessionView(LiveSession session) {
|
||||
Map<String, Object> view = new LinkedHashMap<>();
|
||||
view.put("id", session.getId());
|
||||
view.put("schoolId", session.getSchoolId());
|
||||
view.put("classId", session.getClassId());
|
||||
view.put("courseId", session.getCourseId());
|
||||
view.put("teacherId", session.getTeacherId());
|
||||
view.put("roomName", session.getRoomName());
|
||||
view.put("status", session.getStatus());
|
||||
view.put("startedAt", session.getStartedAt());
|
||||
view.put("endedAt", session.getEndedAt());
|
||||
view.put("endReason", session.getEndReason());
|
||||
view.put("viewerPeak", session.getViewerPeak());
|
||||
view.put("recordEnabled", session.isRecordEnabled());
|
||||
view.put("createdAt", session.getCreatedAt());
|
||||
view.put("className", schoolService.className(session.getClassId()));
|
||||
view.put("schoolName", schoolService.schoolName(session.getSchoolId()));
|
||||
view.put("courseName", courses.findById(session.getCourseId()).map(Course::getName).orElse("课程"));
|
||||
view.put("teacherName", users.findById(session.getTeacherId()).map(UserAccount::getDisplayName).orElse("教师"));
|
||||
view.put("viewers", countViewers(session.getId()));
|
||||
return view;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@@ -252,4 +293,12 @@ public class LiveSessionService {
|
||||
private String liveUrl() {
|
||||
return System.getenv().getOrDefault("LIVEKIT_PUBLIC_URL", "ws://localhost:7880");
|
||||
}
|
||||
|
||||
private String publishIdentity(UserPrincipal me) {
|
||||
return "u-" + me.id();
|
||||
}
|
||||
|
||||
private String subscribeIdentity(UserPrincipal me) {
|
||||
return "u-" + me.id() + "-watch-" + Long.toHexString(System.nanoTime());
|
||||
}
|
||||
}
|
||||
@@ -133,10 +133,13 @@ public class NotificationService {
|
||||
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()));
|
||||
boolean authenticate = settings.getUsername() != null && !settings.getUsername().isBlank();
|
||||
if (authenticate) {
|
||||
sender.setUsername(settings.getUsername());
|
||||
sender.setPassword(cipher.decrypt(settings.getPasswordCipher()));
|
||||
}
|
||||
Properties mailProps = sender.getJavaMailProperties();
|
||||
mailProps.put("mail.smtp.auth", "true");
|
||||
mailProps.put("mail.smtp.auth", Boolean.toString(authenticate));
|
||||
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");
|
||||
|
||||
@@ -32,7 +32,7 @@ public class MediaProbe {
|
||||
try {
|
||||
String url = storage.presignInternal(recording.getObjectKey(), 10);
|
||||
Process process = new ProcessBuilder(props.getFfprobePath(), "-v", "error", "-show_streams",
|
||||
"-print_format", "json", url)
|
||||
"-show_format", "-print_format", "json", url)
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
boolean finished = process.waitFor(20, TimeUnit.SECONDS);
|
||||
@@ -48,6 +48,13 @@ public class MediaProbe {
|
||||
ProbeParser.Result result = ProbeParser.parse(output);
|
||||
recording.setHasVideo(result.video());
|
||||
recording.setHasAudio(result.audio());
|
||||
if (result.durationSeconds() > 0) {
|
||||
recording.setDurationSeconds(result.durationSeconds());
|
||||
}
|
||||
Long size = storage.size(recording.getObjectKey());
|
||||
if (size != null) {
|
||||
recording.setFileSize(size);
|
||||
}
|
||||
if (result.video() && result.audio()) {
|
||||
recording.setStatus("COMPLETED");
|
||||
recording.setErrorMessage(null);
|
||||
|
||||
@@ -2,16 +2,21 @@ package com.xh.xunke.recording;
|
||||
|
||||
import com.xh.xunke.config.AppProperties;
|
||||
import io.minio.BucketExistsArgs;
|
||||
import io.minio.GetObjectArgs;
|
||||
import io.minio.GetObjectResponse;
|
||||
import io.minio.GetPresignedObjectUrlArgs;
|
||||
import io.minio.MakeBucketArgs;
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.PutObjectArgs;
|
||||
import io.minio.RemoveObjectArgs;
|
||||
import io.minio.StatObjectArgs;
|
||||
import io.minio.StatObjectResponse;
|
||||
import io.minio.http.Method;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Component
|
||||
@@ -48,6 +53,8 @@ public class ObjectStorage {
|
||||
}
|
||||
|
||||
public String presignPlayback(String key, int minutes) {
|
||||
// 用浏览器可达的公开端点直接签名。客户端已显式设置 region,签名过程不会访问服务器,
|
||||
// 因此容器内也能为 localhost:9000 生成有效链接。
|
||||
return sign(browser, key, minutes);
|
||||
}
|
||||
|
||||
@@ -55,6 +62,46 @@ public class ObjectStorage {
|
||||
return sign(internal, key, minutes);
|
||||
}
|
||||
|
||||
public Long size(String key) {
|
||||
try {
|
||||
return internal.statObject(StatObjectArgs.builder().bucket(props.getMinioBucket()).object(key).build()).size();
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void put(String key, String contentType, InputStream data) {
|
||||
try {
|
||||
internal.putObject(PutObjectArgs.builder()
|
||||
.bucket(props.getMinioBucket())
|
||||
.object(key)
|
||||
.contentType(contentType)
|
||||
.stream(data, -1, 10485760)
|
||||
.build());
|
||||
} catch (Exception ex) {
|
||||
throw new com.xh.xunke.common.BizException(com.xh.xunke.common.ErrorCode.UPSTREAM, "对象上传失败");
|
||||
}
|
||||
}
|
||||
|
||||
public record StoredObject(InputStream stream, String contentType, long size) {
|
||||
}
|
||||
|
||||
public StoredObject get(String key) {
|
||||
try {
|
||||
GetObjectResponse response = internal.getObject(GetObjectArgs.builder()
|
||||
.bucket(props.getMinioBucket())
|
||||
.object(key)
|
||||
.build());
|
||||
StatObjectResponse stat = internal.statObject(StatObjectArgs.builder()
|
||||
.bucket(props.getMinioBucket())
|
||||
.object(key)
|
||||
.build());
|
||||
return new StoredObject(response, response.headers().get("Content-Type"), stat.size());
|
||||
} catch (Exception ex) {
|
||||
throw new com.xh.xunke.common.BizException(com.xh.xunke.common.ErrorCode.NOT_FOUND, "对象不存在");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean exists(String key) {
|
||||
try {
|
||||
internal.statObject(StatObjectArgs.builder().bucket(props.getMinioBucket()).object(key).build());
|
||||
@@ -88,6 +135,7 @@ public class ObjectStorage {
|
||||
private static MinioClient client(String endpoint, AppProperties props) {
|
||||
return MinioClient.builder()
|
||||
.endpoint(endpoint)
|
||||
.region("us-east-1")
|
||||
.credentials(props.getMinioAccess(), props.getMinioSecret())
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -9,12 +9,13 @@ public final class ProbeParser {
|
||||
private ProbeParser() {
|
||||
}
|
||||
|
||||
public record Result(boolean video, boolean audio) {
|
||||
public record Result(boolean video, boolean audio, int durationSeconds) {
|
||||
}
|
||||
|
||||
public static Result parse(String body) {
|
||||
try {
|
||||
JsonNode streams = JSON.readTree(body).path("streams");
|
||||
JsonNode json = JSON.readTree(body);
|
||||
JsonNode streams = json.path("streams");
|
||||
boolean video = false;
|
||||
boolean audio = false;
|
||||
if (streams.isArray()) {
|
||||
@@ -27,9 +28,10 @@ public final class ProbeParser {
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Result(video, audio);
|
||||
double duration = json.path("format").path("duration").asDouble(0);
|
||||
return new Result(video, audio, (int) Math.round(duration));
|
||||
} catch (Exception ex) {
|
||||
return new Result(false, false);
|
||||
return new Result(false, false, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,10 @@ public interface RecordingRepository extends JpaRepository<Recording, Long> {
|
||||
|
||||
Page<Recording> findByClassId(Long classId, Pageable pageable);
|
||||
|
||||
Page<Recording> findByClassIdIn(List<Long> classIds, Pageable pageable);
|
||||
|
||||
Page<Recording> findBySessionIdIn(List<Long> sessionIds, Pageable pageable);
|
||||
|
||||
List<Recording> findByStatusAndEndedAtBefore(String status, Instant endedBefore);
|
||||
|
||||
long countByStatus(String status);
|
||||
|
||||
@@ -5,18 +5,26 @@ 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.course.Course;
|
||||
import com.xh.xunke.course.CourseRepository;
|
||||
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.school.SchoolService;
|
||||
import com.xh.xunke.security.UserPrincipal;
|
||||
import com.xh.xunke.user.UserAccount;
|
||||
import com.xh.xunke.user.UserRepository;
|
||||
import livekit.LivekitWebhook;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class RecordingService {
|
||||
@@ -28,10 +36,14 @@ public class RecordingService {
|
||||
private final SchoolRepository schools;
|
||||
private final AppProperties props;
|
||||
private final MediaProbe mediaProbe;
|
||||
private final SchoolService schoolService;
|
||||
private final CourseRepository courses;
|
||||
private final UserRepository users;
|
||||
|
||||
public RecordingService(RecordingRepository recordings, LiveSessionRepository sessions, LiveKitGateway liveKit,
|
||||
ObjectStorage storage, BindingService bindings, SchoolRepository schools, AppProperties props,
|
||||
MediaProbe mediaProbe) {
|
||||
MediaProbe mediaProbe, SchoolService schoolService, CourseRepository courses,
|
||||
UserRepository users) {
|
||||
this.recordings = recordings;
|
||||
this.sessions = sessions;
|
||||
this.liveKit = liveKit;
|
||||
@@ -40,6 +52,9 @@ public class RecordingService {
|
||||
this.schools = schools;
|
||||
this.props = props;
|
||||
this.mediaProbe = mediaProbe;
|
||||
this.schoolService = schoolService;
|
||||
this.courses = courses;
|
||||
this.users = users;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@@ -103,17 +118,67 @@ public class RecordingService {
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
public PagePayload<Map<String, Object>> list(UserPrincipal me, Long classId, int page, int size) {
|
||||
// 管理员/巡课:全站或本校范围
|
||||
if (me.superAdmin() || me.schoolStaff()) {
|
||||
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)));
|
||||
return mapped(result);
|
||||
}
|
||||
return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
// 教师:只看到自己发起的直播的录像
|
||||
if (me.canTeach()) {
|
||||
List<Long> sessionIds = sessions.findByTeacherId(me.id()).stream().map(LiveSession::getId).toList();
|
||||
var result = sessionIds.isEmpty()
|
||||
? org.springframework.data.domain.Page.<Recording>empty(Pages.of(page, size))
|
||||
: recordings.findBySessionIdIn(sessionIds, Pages.of(page, size));
|
||||
return mapped(result);
|
||||
}
|
||||
// 家长:只看到绑定班级且回放授权的录像,跨班级请求直接拒绝
|
||||
List<Long> classIds = bindings.replayClassIds(me.id());
|
||||
org.springframework.data.domain.Page<Recording> result;
|
||||
if (classIds.isEmpty()) {
|
||||
result = org.springframework.data.domain.Page.<Recording>empty(Pages.of(page, size));
|
||||
} else if (classId != null) {
|
||||
result = classIds.contains(classId)
|
||||
? recordings.findByClassId(classId, Pages.of(page, size))
|
||||
: org.springframework.data.domain.Page.<Recording>empty(Pages.of(page, size));
|
||||
} else {
|
||||
result = recordings.findByClassIdIn(classIds, Pages.of(page, size));
|
||||
}
|
||||
return mapped(result);
|
||||
}
|
||||
|
||||
private PagePayload<Map<String, Object>> mapped(org.springframework.data.domain.Page<Recording> result) {
|
||||
return new PagePayload<>(result.getContent().stream().map(this::recordingView).toList(),
|
||||
result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
private Map<String, Object> recordingView(Recording recording) {
|
||||
Map<String, Object> view = new LinkedHashMap<>();
|
||||
view.put("id", recording.getId());
|
||||
view.put("sessionId", recording.getSessionId());
|
||||
view.put("schoolId", recording.getSchoolId());
|
||||
view.put("classId", recording.getClassId());
|
||||
view.put("status", recording.getStatus());
|
||||
view.put("fileSize", recording.getFileSize());
|
||||
view.put("durationSeconds", recording.getDurationSeconds());
|
||||
view.put("hasVideo", recording.getHasVideo());
|
||||
view.put("hasAudio", recording.getHasAudio());
|
||||
view.put("errorMessage", recording.getErrorMessage());
|
||||
view.put("retryCount", recording.getRetryCount());
|
||||
view.put("startedAt", recording.getStartedAt());
|
||||
view.put("endedAt", recording.getEndedAt());
|
||||
view.put("createdAt", recording.getCreatedAt());
|
||||
view.put("className", schoolService.className(recording.getClassId()));
|
||||
view.put("schoolName", schoolService.schoolName(recording.getSchoolId()));
|
||||
sessions.findById(recording.getSessionId()).ifPresent(session -> {
|
||||
view.put("courseId", session.getCourseId());
|
||||
view.put("teacherId", session.getTeacherId());
|
||||
view.put("courseName", courses.findById(session.getCourseId()).map(Course::getName).orElse("课程"));
|
||||
view.put("teacherName", users.findById(session.getTeacherId()).map(UserAccount::getDisplayName).orElse("教师"));
|
||||
});
|
||||
return view;
|
||||
}
|
||||
|
||||
public String playback(UserPrincipal me, Long id) {
|
||||
|
||||
@@ -9,12 +9,16 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface BindingRepository extends JpaRepository<ParentBinding, Long> {
|
||||
Page<ParentBinding> findBySchoolId(Long schoolId, Pageable pageable);
|
||||
|
||||
Page<ParentBinding> findBySchoolIdAndStatus(Long schoolId, String status, Pageable pageable);
|
||||
|
||||
Page<ParentBinding> findByStatus(String status, Pageable pageable);
|
||||
|
||||
List<ParentBinding> findByParentId(Long parentId);
|
||||
|
||||
List<ParentBinding> findByParentIdAndStatusAndReplayGranted(Long parentId, String status, boolean replayGranted);
|
||||
|
||||
Optional<ParentBinding> findByParentIdAndClassIdAndStatus(Long parentId, Long classId, String status);
|
||||
|
||||
List<ParentBinding> findByClassIdAndStatusAndLiveGranted(Long classId, String status, boolean liveGranted);
|
||||
|
||||
@@ -79,9 +79,11 @@ public class BindingService {
|
||||
return new PagePayload<>(mine, mine.size(), 0, mine.size());
|
||||
}
|
||||
Long schoolId = me.superAdmin() ? null : me.schoolId();
|
||||
String wanted = status == null || status.isBlank() ? null : status;
|
||||
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));
|
||||
? (wanted == null ? bindings.findAll(Pages.of(page, size)) : bindings.findByStatus(wanted, Pages.of(page, size)))
|
||||
: (wanted == null ? bindings.findBySchoolId(schoolId, Pages.of(page, size))
|
||||
: bindings.findBySchoolIdAndStatus(schoolId, wanted, Pages.of(page, size)));
|
||||
return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
@@ -125,7 +127,7 @@ public class BindingService {
|
||||
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()));
|
||||
.ifPresent(session -> liveKit.removeParticipantsWithPrefix(session.getRoomName(), "u-" + binding.getParentId()));
|
||||
return binding;
|
||||
}
|
||||
|
||||
@@ -135,6 +137,14 @@ public class BindingService {
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
/** 家长已通过审核且被授予回放权限的班级。 */
|
||||
public List<Long> replayClassIds(Long parentId) {
|
||||
return bindings.findByParentIdAndStatusAndReplayGranted(parentId, "APPROVED", true).stream()
|
||||
.map(ParentBinding::getClassId)
|
||||
.distinct()
|
||||
.toList();
|
||||
}
|
||||
|
||||
private void syncGrant(ParentBinding binding) {
|
||||
String parent = String.valueOf(binding.getParentId());
|
||||
if (binding.isLiveGranted()) {
|
||||
|
||||
@@ -66,6 +66,30 @@ public class SchoolService {
|
||||
public record StudentRequest(@NotNull Long classId, @NotBlank String name, @NotBlank String studentNo) {
|
||||
}
|
||||
|
||||
public String className(Long classId) {
|
||||
return classes.findById(classId).map(ClassRoom::getName).orElse("班级 " + classId);
|
||||
}
|
||||
|
||||
public String schoolName(Long schoolId) {
|
||||
return schools.findById(schoolId).map(School::getName).orElse("");
|
||||
}
|
||||
|
||||
public String studentName(Long classId, Long studentId) {
|
||||
return students.findByClassId(classId).stream()
|
||||
.filter(student -> student.getId().equals(studentId))
|
||||
.map(Student::getName)
|
||||
.findFirst()
|
||||
.orElse("");
|
||||
}
|
||||
|
||||
/** 教师任教的班级 ID(用于直播/录像列表按教师范围过滤)。 */
|
||||
public List<Long> teacherClassIds(Long teacherId) {
|
||||
return classTeachers.findByTeacherId(teacherId).stream()
|
||||
.map(ClassTeacher::getClassId)
|
||||
.distinct()
|
||||
.toList();
|
||||
}
|
||||
|
||||
public PagePayload<School> listSchools(UserPrincipal me, String q, int page, int size) {
|
||||
if (!me.superAdmin()) {
|
||||
if (me.schoolId() == null) {
|
||||
|
||||
@@ -55,6 +55,9 @@ public class SettingsService {
|
||||
public Map<String, Object> publicSite() {
|
||||
Map<String, Object> site = new LinkedHashMap<>();
|
||||
byPrefix("site.").forEach(site::put);
|
||||
if (!text("site.logo.key", "").isBlank()) {
|
||||
site.put("site.logo.url", "/api/public/site-logo");
|
||||
}
|
||||
site.put("registrationEnabled", flag("reg.enabled", true));
|
||||
site.put("emailVerify", flag("reg.emailVerify", false));
|
||||
site.put("smsVerify", flag("reg.smsVerify", false));
|
||||
|
||||
@@ -41,9 +41,10 @@ public class UserAdminService {
|
||||
|
||||
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);
|
||||
RoleName parsedRole = role == null || role.isBlank() ? null : RoleName.valueOf(role);
|
||||
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();
|
||||
var result = users.search(schoolId, parsed, q == null || q.isBlank() ? null : q, parsedRole, Pages.of(page, size));
|
||||
var views = result.getContent().stream().map(this::view).toList();
|
||||
return new PagePayload<>(views, result.getTotalElements(), result.getNumber(), result.getSize());
|
||||
}
|
||||
|
||||
|
||||
@@ -25,9 +25,11 @@ public interface UserRepository extends JpaRepository<UserAccount, Long> {
|
||||
|
||||
@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);
|
||||
+ "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), '%')))) "
|
||||
+ "and (:role is null or exists (select r.id.userId from UserRole r "
|
||||
+ "where r.id.userId = u.id and r.id.role = :role))")
|
||||
Page<UserAccount> search(Long schoolId, UserStatus status, String q, RoleName role, Pageable pageable);
|
||||
|
||||
long countBySchoolId(Long schoolId);
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ package com.xh.xunke.web;
|
||||
|
||||
import com.xh.xunke.audit.AuditService;
|
||||
import com.xh.xunke.common.ApiResponse;
|
||||
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;
|
||||
@@ -52,9 +54,11 @@ import java.lang.management.ManagementFactory;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.io.InputStream;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
@@ -342,21 +346,21 @@ public class ResourceController {
|
||||
}
|
||||
|
||||
@GetMapping("/live/sessions")
|
||||
public ApiResponse<PagePayload<LiveSession>> lives(@RequestParam(required = false) String status,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
public ApiResponse<PagePayload<Map<String, Object>>> 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) {
|
||||
public ApiResponse<Map<String, Object>> 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) {
|
||||
public ApiResponse<PagePayload<Map<String, Object>>> 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));
|
||||
}
|
||||
|
||||
@@ -435,7 +439,36 @@ public class ResourceController {
|
||||
@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()));
|
||||
var enriched = new LinkedHashMap<String, Object>();
|
||||
var bindingRows = new ArrayList<Map<String, Object>>();
|
||||
for (ParentBinding binding : mine.items()) {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("id", binding.getId());
|
||||
row.put("classId", binding.getClassId());
|
||||
row.put("status", binding.getStatus());
|
||||
row.put("liveGranted", binding.isLiveGranted());
|
||||
row.put("replayGranted", binding.isReplayGranted());
|
||||
row.put("relationship", binding.getRelationship());
|
||||
row.put("reviewNote", binding.getReviewNote());
|
||||
row.put("createdAt", binding.getCreatedAt());
|
||||
row.put("className", schools.className(binding.getClassId()));
|
||||
row.put("schoolName", schools.schoolName(binding.getSchoolId()));
|
||||
row.put("studentName", schools.studentName(binding.getClassId(), binding.getStudentId()));
|
||||
bindingRows.add(row);
|
||||
}
|
||||
enriched.put("bindings", new PagePayload<>(bindingRows, bindingRows.size(), 0, bindingRows.size()));
|
||||
enriched.put("lives", live.list(me(), "LIVE", 0, 20));
|
||||
return ApiResponse.ok(enriched);
|
||||
}
|
||||
|
||||
@GetMapping("/parent/today")
|
||||
public ApiResponse<List<Map<String, Object>>> parentToday() {
|
||||
List<Long> classIds = bindings.list(me(), null, 0, 50).items().stream()
|
||||
.filter(binding -> "APPROVED".equals(binding.getStatus()))
|
||||
.map(ParentBinding::getClassId)
|
||||
.distinct()
|
||||
.toList();
|
||||
return ApiResponse.ok(courses.todayViews(classIds));
|
||||
}
|
||||
|
||||
@GetMapping("/admin/settings")
|
||||
@@ -568,6 +601,44 @@ public class ResourceController {
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@PostMapping("/admin/site-logo")
|
||||
public ApiResponse<Map<String, String>> siteLogo(@RequestParam("file") org.springframework.web.multipart.MultipartFile file) {
|
||||
String contentType = file.getContentType();
|
||||
if (contentType == null || !List.of("image/png", "image/jpeg", "image/webp").contains(contentType)) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "只支持 PNG / JPG / WebP 图片");
|
||||
}
|
||||
if (file.getSize() > 2 * 1024 * 1024) {
|
||||
throw new BizException(ErrorCode.VALIDATION, "图片不能超过 2MB");
|
||||
}
|
||||
String ext = contentType.equals("image/png") ? "png" : contentType.equals("image/webp") ? "webp" : "jpg";
|
||||
String key = "site/logo-" + System.currentTimeMillis() + "." + ext;
|
||||
try (InputStream in = file.getInputStream()) {
|
||||
storage.put(key, contentType, in);
|
||||
} catch (Exception ex) {
|
||||
throw new BizException(ErrorCode.UPSTREAM, "Logo 上传失败");
|
||||
}
|
||||
settings.update(Map.of("site.logo.key", key));
|
||||
return ApiResponse.ok(Map.of("url", "/api/public/site-logo?v=" + System.currentTimeMillis()));
|
||||
}
|
||||
|
||||
@GetMapping("/public/site-logo")
|
||||
public org.springframework.http.ResponseEntity<byte[]> siteLogoImage() {
|
||||
String key = settings.text("site.logo.key", "");
|
||||
if (key.isBlank()) {
|
||||
return org.springframework.http.ResponseEntity.notFound().build();
|
||||
}
|
||||
ObjectStorage.StoredObject object = storage.get(key);
|
||||
try (InputStream in = object.stream()) {
|
||||
byte[] bytes = in.readAllBytes();
|
||||
return org.springframework.http.ResponseEntity.ok()
|
||||
.contentType(org.springframework.http.MediaType.parseMediaType(object.contentType()))
|
||||
.cacheControl(org.springframework.http.CacheControl.maxAge(java.time.Duration.ofHours(1)).cachePublic())
|
||||
.body(bytes);
|
||||
} catch (Exception ex) {
|
||||
throw new BizException(ErrorCode.UPSTREAM, "Logo 读取失败");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean liveKitUp() {
|
||||
return liveKit.reachable();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user