feat(course-resources): add resource management, visibility and learning progress
parent
60f6a76729
commit
2993a792d3
@ -0,0 +1,79 @@
|
|||||||
|
package com.sztzjy.linkCommerce.controller.common;
|
||||||
|
|
||||||
|
import com.sztzjy.linkCommerce.config.security.JwtUser;
|
||||||
|
import com.sztzjy.linkCommerce.config.security.TokenProvider;
|
||||||
|
import com.sztzjy.linkCommerce.service.CourseResourceService;
|
||||||
|
import com.sztzjy.linkCommerce.util.ResultEntity;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("api/course-resources")
|
||||||
|
public class CourseResourceController {
|
||||||
|
private final CourseResourceService service;
|
||||||
|
public CourseResourceController(CourseResourceService service) { this.service = service; }
|
||||||
|
|
||||||
|
@GetMapping("/management")
|
||||||
|
public ResultEntity<Map<String, Object>> management(HttpServletRequest request) { return ok(service.management(user(request))); }
|
||||||
|
|
||||||
|
@PostMapping("/nodes")
|
||||||
|
public ResultEntity<Long> create(@RequestBody NodeInput input, HttpServletRequest request) {
|
||||||
|
return ok(service.createNode(user(request), input.parentId, input.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/nodes/{id}")
|
||||||
|
public ResultEntity<Void> rename(@PathVariable long id, @RequestBody NodeInput input, HttpServletRequest request) {
|
||||||
|
service.renameNode(user(request), id, input.name); return ok(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/nodes/{id}/move")
|
||||||
|
public ResultEntity<Void> move(@PathVariable long id, @RequestBody MoveInput input, HttpServletRequest request) {
|
||||||
|
service.moveNode(user(request), id, input.direction); return ok(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/nodes/{id}")
|
||||||
|
public ResultEntity<Void> deleteNode(@PathVariable long id, HttpServletRequest request) {
|
||||||
|
service.deleteNode(user(request), id); return ok(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/nodes/{id}/files")
|
||||||
|
public ResultEntity<Map<String, Object>> upload(@PathVariable long id, @RequestPart("file") MultipartFile file, HttpServletRequest request) {
|
||||||
|
return ok(service.upload(user(request), id, file));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/files/{id}")
|
||||||
|
public ResultEntity<Void> deleteFile(@PathVariable long id, HttpServletRequest request) {
|
||||||
|
service.deleteFile(user(request), id); return ok(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/files/{id}/content")
|
||||||
|
public ResponseEntity<Resource> content(@PathVariable long id, @RequestParam(defaultValue = "false") boolean preview, HttpServletRequest request) throws IOException {
|
||||||
|
return service.content(user(request), id, preview);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/visibility")
|
||||||
|
public ResultEntity<Void> visibility(@RequestBody List<Map<String, Object>> changes, HttpServletRequest request) {
|
||||||
|
service.saveVisibility(user(request), changes); return ok(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/student")
|
||||||
|
public ResultEntity<Map<String, Object>> student(HttpServletRequest request) { return ok(service.student(user(request))); }
|
||||||
|
|
||||||
|
@PostMapping("/files/{id}/learned")
|
||||||
|
public ResultEntity<Void> learned(@PathVariable long id, HttpServletRequest request) {
|
||||||
|
service.markLearned(user(request), id); return ok(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private JwtUser user(HttpServletRequest request) { return TokenProvider.getJWTUser(request); }
|
||||||
|
private <T> ResultEntity<T> ok(T data) { return new ResultEntity<>(HttpStatus.OK, "操作成功", data); }
|
||||||
|
public static class NodeInput { public Long parentId; public String name; }
|
||||||
|
public static class MoveInput { public int direction; }
|
||||||
|
}
|
||||||
@ -0,0 +1,385 @@
|
|||||||
|
package com.sztzjy.linkCommerce.service;
|
||||||
|
|
||||||
|
import com.sztzjy.linkCommerce.config.security.JwtUser;
|
||||||
|
import com.sztzjy.linkCommerce.util.file.IFileUtil;
|
||||||
|
import com.sztzjy.linkCommerce.util.pdfUtils.PDFConvertUtil;
|
||||||
|
import org.springframework.core.io.ByteArrayResource;
|
||||||
|
import org.springframework.core.io.FileSystemResource;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.http.ContentDisposition;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||||
|
import org.springframework.jdbc.support.KeyHolder;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.Timestamp;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class CourseResourceService {
|
||||||
|
private final JdbcTemplate jdbc;
|
||||||
|
private final IFileUtil files;
|
||||||
|
private final StudentTeachingClassResolver classResolver;
|
||||||
|
private static final Set<String> OFFICE = new HashSet<>(Arrays.asList("doc", "docx", "xls", "xlsx", "ppt", "pptx"));
|
||||||
|
private static final Set<String> SUPPORTED = new HashSet<>(Arrays.asList(
|
||||||
|
"pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "png", "jpg", "jpeg", "gif", "webp", "bmp",
|
||||||
|
"mp4", "webm", "ogg", "mp3", "wav", "txt", "csv", "zip", "rar", "7z"));
|
||||||
|
|
||||||
|
public CourseResourceService(JdbcTemplate jdbc, IFileUtil files, StudentTeachingClassResolver classResolver) {
|
||||||
|
this.jdbc = jdbc;
|
||||||
|
this.files = files;
|
||||||
|
this.classResolver = classResolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> management(JwtUser user) {
|
||||||
|
String owner = managerOwner(user);
|
||||||
|
List<Map<String, Object>> nodes = nodes(owner);
|
||||||
|
List<Map<String, Object>> resources = resources(owner);
|
||||||
|
decorateNodes(nodes, resources, owner);
|
||||||
|
return map("nodes", nodes, "classes", owner.isEmpty() ? Collections.emptyList() : teacherClasses(user),
|
||||||
|
"permissions", owner.isEmpty() ? Collections.emptyList() : permissions(owner));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Map<String, Object>> teacherClasses(JwtUser user) {
|
||||||
|
requireRole(user, 3);
|
||||||
|
// 即使是教师管理员,这里也只允许配置本人创建的教学班。
|
||||||
|
return jdbc.query("select school_class_id id,class_name name from school_class where school_id=? and created_by=? " +
|
||||||
|
"and (status is null or status=1) and (class_type is null or class_type='TEACHING') order by create_time desc",
|
||||||
|
(rs, i) -> map("id", rs.getString("id"), "name", rs.getString("name")), user.getSchoolId(), user.getUserId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public long createNode(JwtUser user, Long parentId, String name) {
|
||||||
|
String owner = managerOwner(user);
|
||||||
|
String cleanName = nodeName(name);
|
||||||
|
Map<String, Object> parent = parentId == null ? null : readableNode(owner, parentId);
|
||||||
|
if (parent != null && integer(parent, "depth") >= 3) throw new IllegalArgumentException("最多支持三级目录");
|
||||||
|
// 教师可在内置目录下扩充,管理员不能在教师目录下新增。
|
||||||
|
List<Map<String, Object>> siblings = siblings(parentId, owner, true);
|
||||||
|
int order = siblings.stream().mapToInt(n -> integer(n, "sortOrder")).max().orElse(0) + 1;
|
||||||
|
boolean defaultOpen = !owner.isEmpty() || (parent == null ? siblings.isEmpty() : Boolean.TRUE.equals(parent.get("defaultOpen")));
|
||||||
|
KeyHolder key = new GeneratedKeyHolder();
|
||||||
|
jdbc.update(connection -> {
|
||||||
|
PreparedStatement statement = connection.prepareStatement(
|
||||||
|
"insert into course_resource_node(parent_id,owner_id,name,depth,sort_order,default_open) values(?,?,?,?,?,?)", new String[]{"id"});
|
||||||
|
statement.setObject(1, parentId);
|
||||||
|
statement.setString(2, owner);
|
||||||
|
statement.setString(3, cleanName);
|
||||||
|
statement.setInt(4, parent == null ? 1 : integer(parent, "depth") + 1);
|
||||||
|
statement.setInt(5, order);
|
||||||
|
statement.setBoolean(6, defaultOpen);
|
||||||
|
return statement;
|
||||||
|
}, key);
|
||||||
|
return Objects.requireNonNull(key.getKey()).longValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void renameNode(JwtUser user, long id, String name) {
|
||||||
|
String owner = managerOwner(user);
|
||||||
|
requireOwned(readableNode(owner, id), owner);
|
||||||
|
jdbc.update("update course_resource_node set name=? where id=? and owner_id=?", nodeName(name), id, owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void moveNode(JwtUser user, long id, int direction) {
|
||||||
|
if (direction != -1 && direction != 1) throw new IllegalArgumentException("移动方向无效");
|
||||||
|
String owner = managerOwner(user);
|
||||||
|
Map<String, Object> node = readableNode(owner, id);
|
||||||
|
requireOwned(node, owner);
|
||||||
|
List<Map<String, Object>> siblings = siblings(nullableId(node.get("parentId")), owner, true);
|
||||||
|
for (int i = 0; i < siblings.size(); i++) {
|
||||||
|
if (longValue(siblings.get(i).get("id")) != id) continue;
|
||||||
|
int target = i + direction;
|
||||||
|
if (target < 0 || target >= siblings.size()) return;
|
||||||
|
Collections.swap(siblings, i, target);
|
||||||
|
for (int index = 0; index < siblings.size(); index++) {
|
||||||
|
jdbc.update("update course_resource_node set sort_order=? where id=? and owner_id=?", index + 1, siblings.get(index).get("id"), owner);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteNode(JwtUser user, long id) {
|
||||||
|
String owner = managerOwner(user);
|
||||||
|
requireOwned(readableNode(owner, id), owner);
|
||||||
|
// 外键级联删除全部后代、资源、开放配置和学习记录,包括挂在内置目录下的教师内容。
|
||||||
|
jdbc.update("delete from course_resource_node where id=? and owner_id=?", id, owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Map<String, Object> upload(JwtUser user, long nodeId, MultipartFile file) {
|
||||||
|
String owner = managerOwner(user);
|
||||||
|
readableNode(owner, nodeId);
|
||||||
|
if (file == null || file.isEmpty()) throw new IllegalArgumentException("请选择资源文件");
|
||||||
|
String name = Optional.ofNullable(file.getOriginalFilename()).orElse("").replace('\\', '_').replace('/', '_');
|
||||||
|
if (name.isEmpty() || name.length() > 255 || !SUPPORTED.contains(extension(name))) {
|
||||||
|
throw new IllegalArgumentException("支持PDF、Office文档、图片、音视频、文本和压缩文件");
|
||||||
|
}
|
||||||
|
String path = files.upload(file);
|
||||||
|
try {
|
||||||
|
KeyHolder key = new GeneratedKeyHolder();
|
||||||
|
jdbc.update(connection -> {
|
||||||
|
PreparedStatement statement = connection.prepareStatement(
|
||||||
|
"insert into course_resource_file(node_id,owner_id,uploader_name,name,storage_path,size) values(?,?,?,?,?,?)", new String[]{"id"});
|
||||||
|
statement.setLong(1, nodeId);
|
||||||
|
statement.setString(2, owner);
|
||||||
|
statement.setString(3, Optional.ofNullable(user.getName()).orElse(user.getUsername()));
|
||||||
|
statement.setString(4, name);
|
||||||
|
statement.setString(5, path);
|
||||||
|
statement.setLong(6, file.getSize());
|
||||||
|
return statement;
|
||||||
|
}, key);
|
||||||
|
return map("id", Objects.requireNonNull(key.getKey()).longValue(), "name", name);
|
||||||
|
} catch (RuntimeException error) {
|
||||||
|
files.remove(path);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteFile(JwtUser user, long id) {
|
||||||
|
String owner = managerOwner(user);
|
||||||
|
requireOwned(resource(id), owner);
|
||||||
|
jdbc.update("delete from course_resource_file where id=? and owner_id=?", id, owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void saveVisibility(JwtUser user, List<Map<String, Object>> changes) {
|
||||||
|
requireRole(user, 3);
|
||||||
|
String teacherId = managerOwner(user);
|
||||||
|
Set<String> classIds = teacherClasses(user).stream().map(n -> text(n.get("id"))).collect(Collectors.toSet());
|
||||||
|
Map<Long, Map<String, Object>> accessible = index(nodes(teacherId));
|
||||||
|
if (changes == null) throw new IllegalArgumentException("缺少可见范围设置");
|
||||||
|
// 先校验整批数据,禁止跨教师或跨班级配置。
|
||||||
|
for (Map<String, Object> change : changes) {
|
||||||
|
if (!accessible.containsKey(longValue(change.get("nodeId"))) || !classIds.contains(text(change.get("classId")))) {
|
||||||
|
throw new AccessDeniedException("只能设置本人目录与班级的可见范围");
|
||||||
|
}
|
||||||
|
if (!(change.get("visible") instanceof Boolean)) throw new IllegalArgumentException("可见范围格式错误");
|
||||||
|
}
|
||||||
|
for (Map<String, Object> change : changes) {
|
||||||
|
long nodeId = longValue(change.get("nodeId"));
|
||||||
|
String classId = text(change.get("classId"));
|
||||||
|
boolean visible = Boolean.TRUE.equals(change.get("visible"));
|
||||||
|
jdbc.update("insert into course_resource_visibility(teacher_id,node_id,class_id,visible,opened_at) values(?,?,?,?,current_timestamp(3)) " +
|
||||||
|
"on duplicate key update opened_at=case when visible=false and ?=true then current_timestamp(3) else opened_at end,visible=?",
|
||||||
|
teacherId, nodeId, classId, visible, visible, visible);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> student(JwtUser user) {
|
||||||
|
requireRole(user, 4);
|
||||||
|
Map<String, Object> context = studentContext(user);
|
||||||
|
String teacher = text(context.get("teacherId"));
|
||||||
|
String classId = text(context.get("classId"));
|
||||||
|
List<Map<String, Object>> allNodes = nodes(teacher);
|
||||||
|
Map<Long, Map<String, Object>> indexed = index(allNodes);
|
||||||
|
Map<Long, Map<String, Object>> rules = new HashMap<>();
|
||||||
|
for (Map<String, Object> permission : permissions(teacher)) {
|
||||||
|
if (classId.equals(permission.get("classId"))) rules.put(longValue(permission.get("nodeId")), permission);
|
||||||
|
}
|
||||||
|
List<Map<String, Object>> visibleNodes = allNodes.stream()
|
||||||
|
.filter(n -> effectiveVisible(n, indexed, rules)).collect(Collectors.toList());
|
||||||
|
Set<Long> visibleIds = index(visibleNodes).keySet();
|
||||||
|
List<Map<String, Object>> visibleFiles = resources(teacher).stream()
|
||||||
|
.filter(f -> visibleIds.contains(longValue(f.get("nodeId")))).collect(Collectors.toList());
|
||||||
|
Set<Long> learned = new HashSet<>(jdbc.query("select file_id from course_resource_learning where student_id=? and class_id=?",
|
||||||
|
(rs, i) -> rs.getLong(1), user.getUserId(), classId));
|
||||||
|
for (Map<String, Object> file : visibleFiles) {
|
||||||
|
Timestamp latest = (Timestamp) file.get("createdAt");
|
||||||
|
Map<String, Object> node = indexed.get(longValue(file.get("nodeId")));
|
||||||
|
while (node != null) {
|
||||||
|
Map<String, Object> rule = rules.get(longValue(node.get("id")));
|
||||||
|
if (rule != null && ((Timestamp) rule.get("openedAt")).after(latest)) latest = (Timestamp) rule.get("openedAt");
|
||||||
|
node = indexed.get(longValue(node.get("parentId")));
|
||||||
|
}
|
||||||
|
file.put("updatedAt", latest);
|
||||||
|
file.put("learned", learned.contains(longValue(file.get("id"))));
|
||||||
|
}
|
||||||
|
decorateNodes(visibleNodes, visibleFiles, null);
|
||||||
|
return map("available", !visibleFiles.isEmpty(), "nodes", visibleNodes, "total", visibleFiles.size(),
|
||||||
|
"learnedCount", visibleFiles.stream().filter(f -> Boolean.TRUE.equals(f.get("learned"))).count());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void markLearned(JwtUser user, long id) {
|
||||||
|
requireRole(user, 4);
|
||||||
|
if (user.isDemoMode()) throw new AccessDeniedException("演示模式不能保存学习记录");
|
||||||
|
accessibleResource(user, id);
|
||||||
|
Map<String, Object> context = studentContext(user);
|
||||||
|
jdbc.update("insert ignore into course_resource_learning(student_id,class_id,file_id) values(?,?,?)", user.getUserId(), context.get("classId"), id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ResponseEntity<Resource> content(JwtUser user, long id, boolean preview) throws IOException {
|
||||||
|
Map<String, Object> resource = accessibleResource(user, id);
|
||||||
|
Path path = Paths.get(files.getFullPath(text(resource.get("storagePath"))));
|
||||||
|
if (!Files.isRegularFile(path)) throw new IllegalArgumentException("资源文件不存在");
|
||||||
|
String name = text(resource.get("name"));
|
||||||
|
String ext = extension(name);
|
||||||
|
Resource body;
|
||||||
|
String type;
|
||||||
|
if (preview && OFFICE.contains(ext)) {
|
||||||
|
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||||
|
try (InputStream input = Files.newInputStream(path)) {
|
||||||
|
if (!PDFConvertUtil.convertToPDFByFileNameSuffix(name, input, output)) throw new IllegalArgumentException("文档预览生成失败,请下载后查看");
|
||||||
|
}
|
||||||
|
body = new ByteArrayResource(output.toByteArray());
|
||||||
|
type = "application/pdf";
|
||||||
|
name += ".pdf";
|
||||||
|
} else {
|
||||||
|
body = new FileSystemResource(path);
|
||||||
|
type = preview ? mediaType(ext) : "application/octet-stream";
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok().contentType(MediaType.parseMediaType(type))
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, (preview ? ContentDisposition.inline() : ContentDisposition.attachment())
|
||||||
|
.filename(name, StandardCharsets.UTF_8).build().toString())
|
||||||
|
.header(HttpHeaders.CACHE_CONTROL, "private, no-store")
|
||||||
|
.header("X-Content-Type-Options", "nosniff").body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> accessibleResource(JwtUser user, long id) {
|
||||||
|
if (user != null && user.getRoleId() == 4) {
|
||||||
|
@SuppressWarnings("unchecked") List<Map<String, Object>> nodes = (List<Map<String, Object>>) student(user).get("nodes");
|
||||||
|
boolean found = nodes.stream().anyMatch(n -> {
|
||||||
|
@SuppressWarnings("unchecked") List<Map<String, Object>> resources = (List<Map<String, Object>>) n.get("files");
|
||||||
|
return resources.stream().anyMatch(f -> longValue(f.get("id")) == id);
|
||||||
|
});
|
||||||
|
if (!found) throw new AccessDeniedException("该资源未向当前班级开放");
|
||||||
|
} else {
|
||||||
|
String owner = managerOwner(user);
|
||||||
|
Map<String, Object> resource = resource(id);
|
||||||
|
if (!text(resource.get("ownerId")).isEmpty() && !owner.equals(resource.get("ownerId"))) throw new AccessDeniedException("无权访问该资源");
|
||||||
|
readableNode(owner, longValue(resource.get("nodeId")));
|
||||||
|
}
|
||||||
|
return resource(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> studentContext(JwtUser student) {
|
||||||
|
String classId = classResolver.resolveRequired(student);
|
||||||
|
List<Map<String, Object>> rows = jdbc.query("select created_by from school_class where school_class_id=? and school_id=? " +
|
||||||
|
"and (status is null or status=1) and (class_type is null or class_type='TEACHING')",
|
||||||
|
(rs, i) -> map("classId", classId, "teacherId", rs.getString("created_by")), classId, student.getSchoolId());
|
||||||
|
if (rows.isEmpty() || text(rows.get(0).get("teacherId")).isEmpty()) throw new AccessDeniedException("当前教学班没有所属教师");
|
||||||
|
return rows.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean effectiveVisible(Map<String, Object> node, Map<Long, Map<String, Object>> nodes, Map<Long, Map<String, Object>> rules) {
|
||||||
|
while (node != null) {
|
||||||
|
Map<String, Object> rule = rules.get(longValue(node.get("id")));
|
||||||
|
if (rule == null ? !Boolean.TRUE.equals(node.get("defaultOpen")) : !Boolean.TRUE.equals(rule.get("visible"))) return false;
|
||||||
|
node = nodes.get(longValue(node.get("parentId")));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Map<String, Object>> nodes(String owner) {
|
||||||
|
return jdbc.query("select * from course_resource_node where owner_id='' or owner_id=? order by depth,case when owner_id='' then 0 else 1 end,sort_order,id",
|
||||||
|
(rs, i) -> map("id", rs.getLong("id"), "parentId", rs.getLong("parent_id"), "ownerId", rs.getString("owner_id"),
|
||||||
|
"name", rs.getString("name"), "depth", rs.getInt("depth"), "sortOrder", rs.getInt("sort_order"),
|
||||||
|
"defaultOpen", rs.getBoolean("default_open"), "createdAt", rs.getTimestamp("created_at")), owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Map<String, Object>> resources(String owner) {
|
||||||
|
return jdbc.query("select id,node_id,owner_id,uploader_name,name,size,created_at from course_resource_file where owner_id='' or owner_id=? order by created_at desc,id desc",
|
||||||
|
(rs, i) -> map("id", rs.getLong("id"), "nodeId", rs.getLong("node_id"), "ownerId", rs.getString("owner_id"),
|
||||||
|
"name", rs.getString("name"), "size", rs.getLong("size"), "uploaderName", rs.getString("uploader_name"),
|
||||||
|
"createdAt", rs.getTimestamp("created_at")), owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Map<String, Object>> permissions(String owner) {
|
||||||
|
return jdbc.query("select node_id,class_id,visible,opened_at from course_resource_visibility where teacher_id=?",
|
||||||
|
(rs, i) -> map("nodeId", rs.getLong("node_id"), "classId", rs.getString("class_id"),
|
||||||
|
"visible", rs.getBoolean("visible"), "openedAt", rs.getTimestamp("opened_at")), owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Map<String, Object>> siblings(Long parentId, String owner, boolean lock) {
|
||||||
|
return jdbc.query("select id,sort_order from course_resource_node where coalesce(parent_id,0)=? and owner_id=? order by sort_order,id" + (lock ? " for update" : ""),
|
||||||
|
(rs, i) -> map("id", rs.getLong("id"), "sortOrder", rs.getInt("sort_order")), parentId == null ? 0L : parentId, owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> readableNode(String owner, long id) {
|
||||||
|
Map<String, Object> node = index(nodes(owner)).get(id);
|
||||||
|
if (node == null) throw new AccessDeniedException("目录不存在或无权访问");
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> resource(long id) {
|
||||||
|
List<Map<String, Object>> rows = jdbc.query("select * from course_resource_file where id=?",
|
||||||
|
(rs, i) -> map("id", rs.getLong("id"), "nodeId", rs.getLong("node_id"), "ownerId", rs.getString("owner_id"),
|
||||||
|
"name", rs.getString("name"), "storagePath", rs.getString("storage_path")), id);
|
||||||
|
if (rows.isEmpty()) throw new IllegalArgumentException("资源不存在");
|
||||||
|
return rows.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void decorateNodes(List<Map<String, Object>> nodes, List<Map<String, Object>> resources, String owner) {
|
||||||
|
for (Map<String, Object> resource : resources) resource.put("editable", owner != null && owner.equals(resource.get("ownerId")));
|
||||||
|
for (Map<String, Object> node : nodes) {
|
||||||
|
node.put("editable", owner != null && owner.equals(node.get("ownerId")));
|
||||||
|
node.put("files", resources.stream().filter(f -> Objects.equals(f.get("nodeId"), node.get("id"))).collect(Collectors.toList()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void requireOwned(Map<String, Object> item, String owner) {
|
||||||
|
if (!owner.equals(item.get("ownerId"))) throw new AccessDeniedException("只能修改或删除自己的数据");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String managerOwner(JwtUser user) {
|
||||||
|
if (user == null) throw new AccessDeniedException("请先登录");
|
||||||
|
if (user.getRoleId() == 1) return "";
|
||||||
|
requireRole(user, 3);
|
||||||
|
if (text(user.getUserId()).isEmpty()) throw new AccessDeniedException("教师身份无效");
|
||||||
|
return user.getUserId();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void requireRole(JwtUser user, int role) {
|
||||||
|
if (user == null || user.getRoleId() != role) throw new AccessDeniedException("无权进行此操作");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String nodeName(String name) {
|
||||||
|
if (name == null || name.trim().isEmpty() || name.trim().length() > 200) throw new IllegalArgumentException("目录名称须为1至200个字符");
|
||||||
|
return name.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<Long, Map<String, Object>> index(List<Map<String, Object>> nodes) {
|
||||||
|
Map<Long, Map<String, Object>> indexed = new LinkedHashMap<>();
|
||||||
|
for (Map<String, Object> node : nodes) indexed.put(longValue(node.get("id")), node);
|
||||||
|
return indexed;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String extension(String name) { return name.substring(name.lastIndexOf('.') + 1).toLowerCase(Locale.ROOT); }
|
||||||
|
private static String mediaType(String ext) {
|
||||||
|
if ("pdf".equals(ext)) return "application/pdf";
|
||||||
|
if (Arrays.asList("jpg", "jpeg").contains(ext)) return "image/jpeg";
|
||||||
|
if (Arrays.asList("png", "gif", "webp", "bmp").contains(ext)) return "image/" + ext;
|
||||||
|
if (Arrays.asList("mp4", "webm").contains(ext)) return "video/" + ext;
|
||||||
|
if ("mp3".equals(ext)) return "audio/mpeg";
|
||||||
|
if (Arrays.asList("wav", "ogg").contains(ext)) return "audio/" + ext;
|
||||||
|
if (Arrays.asList("txt", "csv").contains(ext)) return "text/plain;charset=UTF-8";
|
||||||
|
throw new IllegalArgumentException("此格式请下载后查看");
|
||||||
|
}
|
||||||
|
private static String text(Object value) { return value == null ? "" : String.valueOf(value); }
|
||||||
|
private static long longValue(Object value) { return value == null ? 0 : Long.parseLong(String.valueOf(value)); }
|
||||||
|
private static Long nullableId(Object value) { return longValue(value) == 0 ? null : longValue(value); }
|
||||||
|
private static int integer(Map<String, Object> value, String key) { return ((Number) value.get(key)).intValue(); }
|
||||||
|
private static Map<String, Object> map(Object... values) {
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
for (int i = 0; i < values.length; i += 2) result.put(String.valueOf(values[i]), values[i + 1]);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,176 @@
|
|||||||
|
package com.sztzjy.linkCommerce.service;
|
||||||
|
|
||||||
|
import com.sztzjy.linkCommerce.config.security.JwtUser;
|
||||||
|
import com.sztzjy.linkCommerce.util.file.IFileUtil;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||||
|
import org.springframework.mock.web.MockMultipartFile;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.sql.Timestamp;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
class CourseResourceServiceTest {
|
||||||
|
private JdbcTemplate jdbc;
|
||||||
|
private CourseResourceService service;
|
||||||
|
private IFileUtil files;
|
||||||
|
private StudentTeachingClassResolver resolver;
|
||||||
|
private final JwtUser admin = user(1, "admin");
|
||||||
|
private final JwtUser teacher = user(3, "teacher-a");
|
||||||
|
private final JwtUser other = user(3, "teacher-b");
|
||||||
|
private final JwtUser student = user(4, "student-a");
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setup() throws Exception {
|
||||||
|
DriverManagerDataSource dataSource = new DriverManagerDataSource("jdbc:h2:mem:" + UUID.randomUUID() + ";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1", "sa", "");
|
||||||
|
jdbc = new JdbcTemplate(dataSource);
|
||||||
|
String schema = new String(Files.readAllBytes(Paths.get("docs/sql/2026-10-29-course-resources.sql")), StandardCharsets.UTF_8)
|
||||||
|
.replaceAll("ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", "");
|
||||||
|
for (String statement : schema.split(";")) if (!statement.trim().isEmpty()) jdbc.execute(statement);
|
||||||
|
jdbc.execute("create table school_class(school_class_id varchar(64),class_name varchar(100),school_id varchar(64),created_by varchar(64),status int,class_type varchar(16),create_time timestamp)");
|
||||||
|
jdbc.update("insert into school_class values('class-a','甲班','school','teacher-a',1,'TEACHING',now()),('class-a2','甲二班','school','teacher-a',1,'TEACHING',now()),('class-b','乙班','school','teacher-b',1,'TEACHING',now())");
|
||||||
|
files = mock(IFileUtil.class);
|
||||||
|
when(files.upload(any(org.springframework.web.multipart.MultipartFile.class))).thenReturn("course-resources/example.pdf");
|
||||||
|
resolver = mock(StudentTeachingClassResolver.class);
|
||||||
|
when(resolver.resolveRequired(student)).thenReturn("class-a");
|
||||||
|
service = new CourseResourceService(jdbc, files, resolver);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void teachersCanExtendBuiltinsButCannotModifyBuiltinsOrEachOther() {
|
||||||
|
long builtin = service.createNode(admin, null, "内置章");
|
||||||
|
long custom = service.createNode(teacher, builtin, "教师节");
|
||||||
|
long ownFile = upload(teacher, builtin, "教师资料.pdf");
|
||||||
|
long builtinFile = upload(admin, builtin, "内置资料.pdf");
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.renameNode(teacher, builtin, "篡改"));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.deleteNode(teacher, builtin));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.moveNode(teacher, builtin, 1));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.deleteFile(teacher, builtinFile));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.deleteFile(admin, ownFile));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.deleteNode(admin, custom));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.createNode(other, custom, "越权"));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.deleteFile(other, ownFile));
|
||||||
|
assertEquals(1, nodes(other).size());
|
||||||
|
assertEquals(1, node(other, builtin).get("files") instanceof List ? ((List<?>) node(other, builtin).get("files")).size() : 0);
|
||||||
|
service.renameNode(teacher, custom, "教师重命名");
|
||||||
|
service.deleteFile(teacher, ownFile);
|
||||||
|
assertEquals(0, count("course_resource_file", "id=" + ownFile));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void adminDeletionCascadesAcrossAllTeachersAndLearningRecords() {
|
||||||
|
long builtin = service.createNode(admin, null, "内置章");
|
||||||
|
long child = service.createNode(admin, builtin, "内置节");
|
||||||
|
long teacherChild = service.createNode(teacher, child, "教师知识点");
|
||||||
|
long otherChild = service.createNode(other, builtin, "其他教师节");
|
||||||
|
long file = upload(teacher, teacherChild, "教师资料.pdf");
|
||||||
|
upload(other, otherChild, "其他教师.pdf");
|
||||||
|
upload(admin, child, "公共.pdf");
|
||||||
|
service.saveVisibility(teacher, Collections.singletonList(rule(child, "class-a", true)));
|
||||||
|
service.markLearned(student, file);
|
||||||
|
service.deleteNode(admin, builtin);
|
||||||
|
assertEquals(0, count("course_resource_node", "1=1"));
|
||||||
|
assertEquals(0, count("course_resource_file", "1=1"));
|
||||||
|
assertEquals(0, count("course_resource_visibility", "1=1"));
|
||||||
|
assertEquals(0, count("course_resource_learning", "1=1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void defaultFirstChapterAndTeacherDirectoriesAreVisibleWithParentGating() {
|
||||||
|
long first = service.createNode(admin, null, "第一章");
|
||||||
|
long firstChild = service.createNode(admin, first, "第一章节");
|
||||||
|
long second = service.createNode(admin, null, "第二章");
|
||||||
|
long own = service.createNode(teacher, null, "教师章");
|
||||||
|
long nestedOwn = service.createNode(teacher, second, "教师节");
|
||||||
|
long a = upload(admin, firstChild, "公开.pdf");
|
||||||
|
long b = upload(admin, second, "未开放.pdf");
|
||||||
|
long c = upload(teacher, own, "教师.pdf");
|
||||||
|
long d = upload(teacher, nestedOwn, "受父级控制.pdf");
|
||||||
|
assertTrue(Boolean.TRUE.equals(node(teacher, own).get("defaultOpen")));
|
||||||
|
assertTrue(Boolean.TRUE.equals(node(teacher, nestedOwn).get("defaultOpen")));
|
||||||
|
assertEquals(new HashSet<>(Arrays.asList(a, c)), studentFiles());
|
||||||
|
service.saveVisibility(teacher, Collections.singletonList(rule(second, "class-a", true)));
|
||||||
|
assertEquals(new HashSet<>(Arrays.asList(a, b, c, d)), studentFiles());
|
||||||
|
service.saveVisibility(teacher, Arrays.asList(rule(first, "class-a", false), rule(second, "class-a", false), rule(own, "class-a", false)));
|
||||||
|
assertEquals(false, service.student(student).get("available"));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.markLearned(student, a));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void visibilityAndLearningAreIsolatedByTeacherClassAndCurrentAvailability() throws Exception {
|
||||||
|
long first = service.createNode(admin, null, "第一章");
|
||||||
|
long file = upload(admin, first, "内置.pdf");
|
||||||
|
assertEquals(2, service.teacherClasses(teacher).size());
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.saveVisibility(teacher, Collections.singletonList(rule(first, "class-b", true))));
|
||||||
|
service.markLearned(student, file);
|
||||||
|
service.markLearned(student, file);
|
||||||
|
assertEquals(1L, service.student(student).get("learnedCount"));
|
||||||
|
assertEquals(1, count("course_resource_learning", "1=1"));
|
||||||
|
when(resolver.resolveRequired(student)).thenReturn("class-a2");
|
||||||
|
assertEquals(0L, service.student(student).get("learnedCount"));
|
||||||
|
when(resolver.resolveRequired(student)).thenReturn("class-a");
|
||||||
|
service.saveVisibility(teacher, Collections.singletonList(rule(first, "class-a", false)));
|
||||||
|
assertEquals(0L, service.student(student).get("learnedCount"));
|
||||||
|
Timestamp old = new Timestamp(System.currentTimeMillis() - 86400000);
|
||||||
|
jdbc.update("update course_resource_file set created_at=? where id=?", old, file);
|
||||||
|
service.saveVisibility(teacher, Collections.singletonList(rule(first, "class-a", true)));
|
||||||
|
@SuppressWarnings("unchecked") List<Map<String, Object>> n = (List<Map<String, Object>>) service.student(student).get("nodes");
|
||||||
|
@SuppressWarnings("unchecked") List<Map<String, Object>> f = (List<Map<String, Object>>) n.get(0).get("files");
|
||||||
|
assertTrue(((Timestamp) f.get(0).get("updatedAt")).after(old));
|
||||||
|
assertEquals(1L, service.student(student).get("learnedCount"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void movementIsRestrictedToOwnedSiblingsAndDirectoryDepthIsLimited() {
|
||||||
|
long root = service.createNode(admin, null, "内置章");
|
||||||
|
long a = service.createNode(teacher, root, "甲节");
|
||||||
|
long b = service.createNode(teacher, root, "乙节");
|
||||||
|
long c = service.createNode(teacher, a, "知识点");
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.createNode(teacher, c, "第四级"));
|
||||||
|
service.moveNode(teacher, b, -1);
|
||||||
|
List<Long> order = jdbc.query("select id from course_resource_node where parent_id=? and owner_id=? order by sort_order,id", (rs, i) -> rs.getLong(1), root, "teacher-a");
|
||||||
|
assertEquals(Arrays.asList(b, a), order);
|
||||||
|
assertEquals(a, ((Number) node(teacher, c).get("parentId")).longValue());
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.management(student));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.management(user(2, "school-admin")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fileContentEnforcesVisibilityAndOwnershipBeforeReadingStorage() throws Exception {
|
||||||
|
long node = service.createNode(admin, null, "内置章");
|
||||||
|
long file = upload(teacher, node, "教师.pdf");
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.content(other, file, false));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.content(admin, file, false));
|
||||||
|
service.saveVisibility(teacher, Collections.singletonList(rule(node, "class-a", false)));
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.content(student, file, true));
|
||||||
|
verify(files, never()).getFullPath(anyString());
|
||||||
|
student.setDemoMode(true);
|
||||||
|
assertThrows(AccessDeniedException.class, () -> service.markLearned(student, file));
|
||||||
|
}
|
||||||
|
|
||||||
|
private long upload(JwtUser owner, long node, String name) {
|
||||||
|
return ((Number) service.upload(owner, node, new MockMultipartFile("file", name, "application/pdf", new byte[]{1})).get("id")).longValue();
|
||||||
|
}
|
||||||
|
@SuppressWarnings("unchecked") private List<Map<String, Object>> nodes(JwtUser owner) { return (List<Map<String, Object>>) service.management(owner).get("nodes"); }
|
||||||
|
private Map<String, Object> node(JwtUser owner, long id) { return nodes(owner).stream().filter(n -> ((Number) n.get("id")).longValue() == id).findFirst().get(); }
|
||||||
|
@SuppressWarnings("unchecked") private Set<Long> studentFiles() {
|
||||||
|
List<Map<String, Object>> nodes = (List<Map<String, Object>>) service.student(student).get("nodes");
|
||||||
|
Set<Long> ids = new HashSet<>();
|
||||||
|
nodes.forEach(n -> ((List<Map<String, Object>>) n.get("files")).forEach(f -> ids.add(((Number) f.get("id")).longValue())));
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
private int count(String table, String where) { return jdbc.queryForObject("select count(*) from " + table + " where " + where, Integer.class); }
|
||||||
|
private static JwtUser user(int role, String id) { JwtUser user = new JwtUser(); user.setRoleId(role); user.setUserId(id); user.setSchoolId("school"); user.setName(id); return user; }
|
||||||
|
private static Map<String, Object> rule(long node, String schoolClass, boolean visible) {
|
||||||
|
Map<String, Object> rule = new HashMap<>(); rule.put("nodeId", node); rule.put("classId", schoolClass); rule.put("visible", visible); return rule;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue