资源分类整改

This commit is contained in:
none 2023-03-08 17:20:39 +08:00
parent e8455a3a58
commit 64309a078a
22 changed files with 372 additions and 188 deletions

View File

@ -6,7 +6,6 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import xyz.playedu.api.PlayEduBackendThreadLocal; import xyz.playedu.api.PlayEduBackendThreadLocal;
import xyz.playedu.api.constant.BPermissionConstant; import xyz.playedu.api.constant.BPermissionConstant;
import xyz.playedu.api.constant.BackendConstant;
import xyz.playedu.api.domain.ResourceCategory; import xyz.playedu.api.domain.ResourceCategory;
import xyz.playedu.api.event.ResourceCategoryDestroyEvent; import xyz.playedu.api.event.ResourceCategoryDestroyEvent;
import xyz.playedu.api.exception.NotFoundException; import xyz.playedu.api.exception.NotFoundException;
@ -15,10 +14,8 @@ import xyz.playedu.api.request.backend.ResourceCategoryRequest;
import xyz.playedu.api.service.ResourceCategoryService; import xyz.playedu.api.service.ResourceCategoryService;
import xyz.playedu.api.types.JsonResponse; import xyz.playedu.api.types.JsonResponse;
import java.util.Arrays; import java.util.*;
import java.util.Date; import java.util.stream.Collectors;
import java.util.HashMap;
import java.util.List;
/** /**
* @Author 杭州白书科技有限公司 * @Author 杭州白书科技有限公司
@ -29,62 +26,59 @@ import java.util.List;
public class ResourceCategoryController { public class ResourceCategoryController {
@Autowired @Autowired
private ResourceCategoryService resourceCategoryService; private ResourceCategoryService categoryService;
@Autowired @Autowired
private ApplicationContext ctx; private ApplicationContext ctx;
@GetMapping("/index") @GetMapping("/index")
public JsonResponse index(@RequestParam(name = "type") String type) { public JsonResponse index() {
List<ResourceCategory> categories = resourceCategoryService.getByType(type); Map<Integer, List<ResourceCategory>> categories = categoryService.all().stream().collect(Collectors.groupingBy(ResourceCategory::getParentId));
HashMap<String, Object> data = new HashMap<>(); HashMap<String, Object> data = new HashMap<>();
data.put("data", categories); data.put("categories", categories);
return JsonResponse.data(data); return JsonResponse.data(data);
} }
@BackendPermissionMiddleware(slug = BPermissionConstant.RESOURCE_CATEGORY)
@GetMapping("/create") @GetMapping("/create")
public JsonResponse create() { public JsonResponse create() {
Map<Integer, List<ResourceCategory>> categories = categoryService.all().stream().collect(Collectors.groupingBy(ResourceCategory::getParentId));
HashMap<String, Object> data = new HashMap<>(); HashMap<String, Object> data = new HashMap<>();
data.put("types", BackendConstant.RESOURCE_TYPE_WHITELIST); data.put("categories", categories);
return JsonResponse.data(data); return JsonResponse.data(data);
} }
@BackendPermissionMiddleware(slug = BPermissionConstant.RESOURCE_CATEGORY) @BackendPermissionMiddleware(slug = BPermissionConstant.RESOURCE_CATEGORY)
@PostMapping("/create") @PostMapping("/create")
public JsonResponse store(@RequestBody @Validated ResourceCategoryRequest req) { public JsonResponse store(@RequestBody @Validated ResourceCategoryRequest req) throws NotFoundException {
if (!Arrays.asList(BackendConstant.RESOURCE_TYPE_WHITELIST).contains(req.getType())) { categoryService.create(req.getName(), req.getParentId(), req.getSort());
return JsonResponse.error("资源类型不支持");
}
resourceCategoryService.create(req.getType(), req.getSort(), req.getName());
return JsonResponse.success(); return JsonResponse.success();
} }
@BackendPermissionMiddleware(slug = BPermissionConstant.RESOURCE_CATEGORY) @BackendPermissionMiddleware(slug = BPermissionConstant.RESOURCE_CATEGORY)
@GetMapping("/{id}") @GetMapping("/{id}")
public JsonResponse edit(@PathVariable(name = "id") Integer id) throws NotFoundException { public JsonResponse edit(@PathVariable Integer id) throws NotFoundException {
ResourceCategory category = resourceCategoryService.findOrFail(id); ResourceCategory category = categoryService.findOrFail(id);
return JsonResponse.data(category); return JsonResponse.data(category);
} }
@BackendPermissionMiddleware(slug = BPermissionConstant.RESOURCE_CATEGORY) @BackendPermissionMiddleware(slug = BPermissionConstant.RESOURCE_CATEGORY)
@PutMapping("/{id}") @PutMapping("/{id}")
public JsonResponse update(@PathVariable(name = "id") Integer id, @RequestBody @Validated ResourceCategoryRequest req) throws NotFoundException { public JsonResponse update(@PathVariable Integer id, @RequestBody ResourceCategoryRequest req) throws NotFoundException {
if (!Arrays.asList(BackendConstant.RESOURCE_TYPE_WHITELIST).contains(req.getType())) { ResourceCategory category = categoryService.findOrFail(id);
return JsonResponse.error("资源类型不支持"); categoryService.update(category, req.getName(), req.getParentId(), req.getSort());
}
ResourceCategory category = resourceCategoryService.findOrFail(id);
resourceCategoryService.update(category, req.getSort(), req.getName());
return JsonResponse.success(); return JsonResponse.success();
} }
@BackendPermissionMiddleware(slug = BPermissionConstant.RESOURCE_CATEGORY) @BackendPermissionMiddleware(slug = BPermissionConstant.RESOURCE_CATEGORY)
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public JsonResponse destroy(@PathVariable(name = "id") Integer id) { public JsonResponse destroy(@PathVariable Integer id) throws NotFoundException {
resourceCategoryService.removeById(id); ResourceCategory category = categoryService.findOrFail(id);
ctx.publishEvent(new ResourceCategoryDestroyEvent(this, PlayEduBackendThreadLocal.getAdminUserID(), id, new Date())); categoryService.deleteById(category.getId());
ctx.publishEvent(new ResourceCategoryDestroyEvent(this, PlayEduBackendThreadLocal.getAdminUserID(), category.getId(), new Date()));
return JsonResponse.success(); return JsonResponse.success();
} }

View File

@ -1,19 +1,14 @@
package xyz.playedu.api.controller.backend; package xyz.playedu.api.controller.backend;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import xyz.playedu.api.constant.BackendConstant; import xyz.playedu.api.constant.BackendConstant;
import xyz.playedu.api.domain.Resource; import xyz.playedu.api.domain.Resource;
import xyz.playedu.api.domain.ResourceCategory;
import xyz.playedu.api.domain.ResourceVideo; import xyz.playedu.api.domain.ResourceVideo;
import xyz.playedu.api.exception.NotFoundException; import xyz.playedu.api.exception.NotFoundException;
import xyz.playedu.api.request.backend.ResourceRequest;
import xyz.playedu.api.service.MinioService; import xyz.playedu.api.service.MinioService;
import xyz.playedu.api.service.ResourceCategoryService;
import xyz.playedu.api.service.ResourceService; import xyz.playedu.api.service.ResourceService;
import xyz.playedu.api.service.ResourceVideoService; import xyz.playedu.api.service.ResourceVideoService;
import xyz.playedu.api.types.JsonResponse; import xyz.playedu.api.types.JsonResponse;
@ -28,7 +23,6 @@ import java.util.stream.Collectors;
* @create 2023/2/23 10:50 * @create 2023/2/23 10:50
*/ */
@RestController @RestController
@Slf4j
@RequestMapping("/backend/v1/resource") @RequestMapping("/backend/v1/resource")
public class ResourceController { public class ResourceController {
@ -38,9 +32,6 @@ public class ResourceController {
@Autowired @Autowired
private ResourceVideoService resourceVideoService; private ResourceVideoService resourceVideoService;
@Autowired
private ResourceCategoryService categoryService;
@Autowired @Autowired
private MinioService minioService; private MinioService minioService;
@ -61,7 +52,6 @@ public class ResourceController {
ResourcePaginateFilter filter = new ResourcePaginateFilter(); ResourcePaginateFilter filter = new ResourcePaginateFilter();
filter.setSortAlgo(sortAlgo); filter.setSortAlgo(sortAlgo);
filter.setSortField(sortField); filter.setSortField(sortField);
filter.setType(type);
if (name != null && name.length() > 0) { if (name != null && name.length() > 0) {
filter.setName(name); filter.setName(name);
} }
@ -84,60 +74,6 @@ public class ResourceController {
return JsonResponse.data(data); return JsonResponse.data(data);
} }
@GetMapping("/create")
public JsonResponse create(@RequestParam(name = "type") String type) {
List<ResourceCategory> categories = categoryService.getByType(type);
HashMap<String, Object> data = new HashMap<>();
data.put("categories", categories);
return JsonResponse.data(data);
}
@PostMapping("/create")
@Transactional
public JsonResponse store(@RequestBody @Validated ResourceRequest req) {
String disk = req.getDisk();
if (!Arrays.asList(BackendConstant.RESOURCE_DISK_WHITELIST).contains(disk)) {
return JsonResponse.error("存储磁盘参数错误");
}
String extension = req.getExtension().toLowerCase();
String type = BackendConstant.RESOURCE_EXT_2_TYPE.get(extension);
if (type == null) {
return JsonResponse.error("格式不支持");
}
// 如果是视频则必须传递duration参数
Integer duration = req.getDuration();
String poster = req.getPoster();
boolean isVideoType = BackendConstant.RESOURCE_TYPE_VIDEO.equals(type);
if (isVideoType) {
if (duration == null || duration == 0) {
return JsonResponse.error("duration参数必须存在且大于0");
}
if (poster == null || poster.trim().length() == 0) {
return JsonResponse.error("poster参数值不能为空");
}
}
Resource res = resourceService.create(
req.getCategoryId(),
type, req.getName(),
extension,
req.getSize(),
disk,
req.getFileId(),
req.getPath(),
req.getUrl()
);
if (isVideoType) {
resourceVideoService.create(res.getId(), duration, poster);
}
return JsonResponse.data(res);
}
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
@Transactional @Transactional
public JsonResponse destroy(@PathVariable(name = "id") Integer id) throws NotFoundException { public JsonResponse destroy(@PathVariable(name = "id") Integer id) throws NotFoundException {

View File

@ -11,12 +11,12 @@ import xyz.playedu.api.domain.Resource;
import xyz.playedu.api.exception.ServiceException; import xyz.playedu.api.exception.ServiceException;
import xyz.playedu.api.request.backend.UploadVideoMergeRequest; import xyz.playedu.api.request.backend.UploadVideoMergeRequest;
import xyz.playedu.api.service.MinioService; import xyz.playedu.api.service.MinioService;
import xyz.playedu.api.service.ResourceCategoryService;
import xyz.playedu.api.service.ResourceService; import xyz.playedu.api.service.ResourceService;
import xyz.playedu.api.service.UploadService; import xyz.playedu.api.service.UploadService;
import xyz.playedu.api.types.JsonResponse; import xyz.playedu.api.types.JsonResponse;
import xyz.playedu.api.util.HelperUtil; import xyz.playedu.api.util.HelperUtil;
import java.util.HashMap; import java.util.HashMap;
/** /**
@ -27,9 +27,6 @@ import java.util.HashMap;
@Slf4j @Slf4j
@RequestMapping("/backend/v1/upload") @RequestMapping("/backend/v1/upload")
public class UploadController { public class UploadController {
@Autowired
private ResourceCategoryService resourceCategoryService;
@Autowired @Autowired
private MinioService minioService; private MinioService minioService;
@ -40,9 +37,9 @@ public class UploadController {
private ResourceService resourceService; private ResourceService resourceService;
@PostMapping("/file") @PostMapping("/file")
public JsonResponse image(@RequestParam HashMap<String, Object> params, MultipartFile file) throws ServiceException { public JsonResponse file(@RequestParam HashMap<String, Object> params, MultipartFile file) throws ServiceException {
Integer cid = MapUtils.getInteger(params, "category_id"); String categoryIds = MapUtils.getString(params, "category_ids");
Resource res = uploadService.storeMinio(file, cid); Resource res = uploadService.storeMinio(file, categoryIds);
return JsonResponse.data(res); return JsonResponse.data(res);
} }
@ -85,21 +82,16 @@ public class UploadController {
@PostMapping("/minio/merge-video") @PostMapping("/minio/merge-video")
public JsonResponse minioMergeVideo(@RequestBody @Validated UploadVideoMergeRequest req) throws ServiceException { public JsonResponse minioMergeVideo(@RequestBody @Validated UploadVideoMergeRequest req) throws ServiceException {
Integer cid = req.getCategoryId();
String type = BackendConstant.RESOURCE_EXT_2_TYPE.get(req.getExtension()); String type = BackendConstant.RESOURCE_EXT_2_TYPE.get(req.getExtension());
if (type == null) { if (type == null) {
return JsonResponse.error("当前格式不支持上传"); return JsonResponse.error("当前格式不支持上传");
} }
if (cid != null && resourceCategoryService.find(cid, type) == null) {
return JsonResponse.error("资源分类不存在");
}
// 合并视频文件 // 合并视频文件
String url = minioService.merge(req.getFilename(), req.getUploadId()); String url = minioService.merge(req.getFilename(), req.getUploadId());
// 视频素材保存 // 视频素材保存
Resource videoResource = resourceService.create( Resource videoResource = resourceService.create(
cid, req.getCategoryIds(),
type, type,
req.getOriginalFilename(), req.getOriginalFilename(),
req.getExtension(), req.getExtension(),
@ -110,7 +102,7 @@ public class UploadController {
url url
); );
// 视频封面素材保存 // 视频封面素材保存
Resource posterResource = uploadService.storeBase64Image(req.getPoster(), 0); Resource posterResource = uploadService.storeBase64Image(req.getPoster(), null);
// 视频的封面素材改为[隐藏 && 属于视频的子素材] // 视频的封面素材改为[隐藏 && 属于视频的子素材]
resourceService.changeParentId(posterResource.getId(), videoResource.getId()); resourceService.changeParentId(posterResource.getId(), videoResource.getId());
// 视频信息 // 视频信息

View File

@ -8,7 +8,6 @@ import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data; import lombok.Data;
@ -29,12 +28,6 @@ public class Resource implements Serializable {
*/ */
private String type; private String type;
/**
* 分类id
*/
@JsonProperty("category_id")
private Integer categoryId;
/** /**
* 资源名 * 资源名
*/ */
@ -71,22 +64,16 @@ public class Resource implements Serializable {
*/ */
private String url; private String url;
/**
*
*/
@JsonProperty("created_at") @JsonProperty("created_at")
private Date createdAt; private Date createdAt;
/**
* 所属素材
*/
@JsonProperty("parent_id") @JsonProperty("parent_id")
private Integer parentId; private Integer parentId;
/** /**
* 隐藏[0:,1:] * 隐藏[0:,1:]
*/ */
@JsonIgnore @JsonProperty("is_hidden")
private Integer isHidden; private Integer isHidden;
@TableField(exist = false) @TableField(exist = false)
@ -106,7 +93,6 @@ public class Resource implements Serializable {
Resource other = (Resource) that; Resource other = (Resource) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType())) && (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))
&& (this.getCategoryId() == null ? other.getCategoryId() == null : this.getCategoryId().equals(other.getCategoryId()))
&& (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
&& (this.getExtension() == null ? other.getExtension() == null : this.getExtension().equals(other.getExtension())) && (this.getExtension() == null ? other.getExtension() == null : this.getExtension().equals(other.getExtension()))
&& (this.getSize() == null ? other.getSize() == null : this.getSize().equals(other.getSize())) && (this.getSize() == null ? other.getSize() == null : this.getSize().equals(other.getSize()))
@ -125,7 +111,6 @@ public class Resource implements Serializable {
int result = 1; int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getType() == null) ? 0 : getType().hashCode()); result = prime * result + ((getType() == null) ? 0 : getType().hashCode());
result = prime * result + ((getCategoryId() == null) ? 0 : getCategoryId().hashCode());
result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((getExtension() == null) ? 0 : getExtension().hashCode()); result = prime * result + ((getExtension() == null) ? 0 : getExtension().hashCode());
result = prime * result + ((getSize() == null) ? 0 : getSize().hashCode()); result = prime * result + ((getSize() == null) ? 0 : getSize().hashCode());
@ -147,7 +132,6 @@ public class Resource implements Serializable {
sb.append("Hash = ").append(hashCode()); sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id); sb.append(", id=").append(id);
sb.append(", type=").append(type); sb.append(", type=").append(type);
sb.append(", categoryId=").append(categoryId);
sb.append(", name=").append(name); sb.append(", name=").append(name);
sb.append(", extension=").append(extension); sb.append(", extension=").append(extension);
sb.append(", size=").append(size); sb.append(", size=").append(size);

View File

@ -8,6 +8,7 @@ import java.io.Serializable;
import java.util.Date; import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data; import lombok.Data;
/** /**
@ -24,9 +25,16 @@ public class ResourceCategory implements Serializable {
private Integer id; private Integer id;
/** /**
* 资源类别 *
*/ */
private String type; @JsonProperty("parent_id")
private Integer parentId;
/**
*
*/
@JsonProperty("parent_chain")
private String parentChain;
/** /**
* 分类名 * 分类名
@ -66,7 +74,8 @@ public class ResourceCategory implements Serializable {
} }
ResourceCategory other = (ResourceCategory) that; ResourceCategory other = (ResourceCategory) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType())) && (this.getParentId() == null ? other.getParentId() == null : this.getParentId().equals(other.getParentId()))
&& (this.getParentChain() == null ? other.getParentChain() == null : this.getParentChain().equals(other.getParentChain()))
&& (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
&& (this.getSort() == null ? other.getSort() == null : this.getSort().equals(other.getSort())) && (this.getSort() == null ? other.getSort() == null : this.getSort().equals(other.getSort()))
&& (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt())) && (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()))
@ -78,7 +87,8 @@ public class ResourceCategory implements Serializable {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getType() == null) ? 0 : getType().hashCode()); result = prime * result + ((getParentId() == null) ? 0 : getParentId().hashCode());
result = prime * result + ((getParentChain() == null) ? 0 : getParentChain().hashCode());
result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((getSort() == null) ? 0 : getSort().hashCode()); result = prime * result + ((getSort() == null) ? 0 : getSort().hashCode());
result = prime * result + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode()); result = prime * result + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode());
@ -93,7 +103,8 @@ public class ResourceCategory implements Serializable {
sb.append(" ["); sb.append(" [");
sb.append("Hash = ").append(hashCode()); sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id); sb.append(", id=").append(id);
sb.append(", type=").append(type); sb.append(", parentId=").append(parentId);
sb.append(", parentChain=").append(parentChain);
sb.append(", name=").append(name); sb.append(", name=").append(name);
sb.append(", sort=").append(sort); sb.append(", sort=").append(sort);
sb.append(", createdAt=").append(createdAt); sb.append(", createdAt=").append(createdAt);

View File

@ -0,0 +1,65 @@
package xyz.playedu.api.domain;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import lombok.Data;
/**
*
* @TableName resource_category
*/
@TableName(value ="resource_category")
@Data
public class ResourceCategoryRelation implements Serializable {
/**
*
*/
private Integer cid;
/**
*
*/
private Integer rid;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
ResourceCategoryRelation other = (ResourceCategoryRelation) that;
return (this.getCid() == null ? other.getCid() == null : this.getCid().equals(other.getCid()))
&& (this.getRid() == null ? other.getRid() == null : this.getRid().equals(other.getRid()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getCid() == null) ? 0 : getCid().hashCode());
result = prime * result + ((getRid() == null) ? 0 : getRid().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", cid=").append(cid);
sb.append(", rid=").append(rid);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}

View File

@ -7,7 +7,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/** /**
* @author tengteng * @author tengteng
* @description 针对表resource_categories的数据库操作Mapper * @description 针对表resource_categories的数据库操作Mapper
* @createDate 2023-02-23 09:50:18 * @createDate 2023-03-08 16:50:54
* @Entity xyz.playedu.api.domain.ResourceCategory * @Entity xyz.playedu.api.domain.ResourceCategory
*/ */
@Mapper @Mapper

View File

@ -0,0 +1,20 @@
package xyz.playedu.api.mapper;
import org.apache.ibatis.annotations.Mapper;
import xyz.playedu.api.domain.ResourceCategoryRelation;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @author tengteng
* @description 针对表resource_category的数据库操作Mapper
* @createDate 2023-03-08 16:54:56
* @Entity xyz.playedu.api.domain.ResourceCategoryRelation
*/
@Mapper
public interface ResourceCategoryRelationMapper extends BaseMapper<ResourceCategoryRelation> {
}

View File

@ -7,7 +7,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/** /**
* @author tengteng * @author tengteng
* @description 针对表resources的数据库操作Mapper * @description 针对表resources的数据库操作Mapper
* @createDate 2023-03-08 13:43:00 * @createDate 2023-03-08 16:55:59
* @Entity xyz.playedu.api.domain.Resource * @Entity xyz.playedu.api.domain.Resource
*/ */
@Mapper @Mapper

View File

@ -1,5 +1,7 @@
package xyz.playedu.api.request.backend; package xyz.playedu.api.request.backend;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import lombok.Data; import lombok.Data;
import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Length;
@ -11,14 +13,16 @@ import org.hibernate.validator.constraints.Length;
@Data @Data
public class ResourceCategoryRequest { public class ResourceCategoryRequest {
@NotNull(message = "资源类型不能为空") @NotNull(message = "name参数不存在")
private String type; @NotBlank(message = "请输入分类名")
@Length(min = 1, max = 20, message = "分类名长度在1-20个字符之间")
@NotNull(message = "分类名不能为空")
@Length(min = 1, max = 12, message = "分类名长度在1-12个字符之间")
private String name; private String name;
@NotNull(message = "请输入排序值") @JsonProperty("parent_id")
@NotNull(message = "parent_id参数不存在")
private Integer parentId;
@NotNull(message = "sort参数不存在")
private Integer sort; private Integer sort;
} }

View File

@ -32,7 +32,8 @@ public class UploadVideoMergeRequest {
@NotBlank(message = "请输入extension") @NotBlank(message = "请输入extension")
private String extension; private String extension;
private Integer categoryId; @JsonProperty("category_ids")
private String categoryIds;
@NotNull(message = "请上传视频封面") @NotNull(message = "请上传视频封面")
private String poster; private String poster;

View File

@ -13,14 +13,20 @@ import java.util.List;
*/ */
public interface ResourceCategoryService extends IService<ResourceCategory> { public interface ResourceCategoryService extends IService<ResourceCategory> {
List<ResourceCategory> getByType(String type); List<ResourceCategory> listByParentId(Integer id);
void create(String type, Integer sort, String name); List<ResourceCategory> all();
ResourceCategory findOrFail(Integer id) throws NotFoundException; ResourceCategory findOrFail(Integer id) throws NotFoundException;
ResourceCategory find(Integer id, String type); void deleteById(Integer id) throws NotFoundException;
void update(ResourceCategory category, Integer sort, String name); void update(ResourceCategory category, String name, Integer parentId, Integer sort) throws NotFoundException;
void create(String name, Integer parentId, Integer sort) throws NotFoundException;
String childrenParentChain(ResourceCategory category);
String compParentChain(Integer parentId) throws NotFoundException;
} }

View File

@ -6,6 +6,8 @@ import xyz.playedu.api.exception.NotFoundException;
import xyz.playedu.api.types.paginate.PaginationResult; import xyz.playedu.api.types.paginate.PaginationResult;
import xyz.playedu.api.types.paginate.ResourcePaginateFilter; import xyz.playedu.api.types.paginate.ResourcePaginateFilter;
import java.util.List;
/** /**
* @author tengteng * @author tengteng
* @description 针对表resources的数据库操作Service * @description 针对表resources的数据库操作Service
@ -15,7 +17,7 @@ public interface ResourceService extends IService<Resource> {
PaginationResult<Resource> paginate(int page, int size, ResourcePaginateFilter filter); PaginationResult<Resource> paginate(int page, int size, ResourcePaginateFilter filter);
Resource create(Integer categoryId, String type, String filename, String ext, Long size, String disk, String fileId, String path, String url); Resource create(String categoryIds, String type, String filename, String ext, Long size, String disk, String fileId, String path, String url);
Resource findOrFail(Integer id) throws NotFoundException; Resource findOrFail(Integer id) throws NotFoundException;

View File

@ -9,7 +9,7 @@ import xyz.playedu.api.exception.ServiceException;
* @create 2023/3/8 14:02 * @create 2023/3/8 14:02
*/ */
public interface UploadService { public interface UploadService {
Resource storeMinio(MultipartFile file, Integer categoryId) throws ServiceException; Resource storeMinio(MultipartFile file, String categoryIds) throws ServiceException;
Resource storeBase64Image(String content,Integer categoryId) throws ServiceException; Resource storeBase64Image(String content, String categoryIds) throws ServiceException;
} }

View File

@ -1,12 +1,14 @@
package xyz.playedu.api.service.impl; package xyz.playedu.api.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import xyz.playedu.api.domain.ResourceCategory; import xyz.playedu.api.domain.ResourceCategory;
import xyz.playedu.api.exception.NotFoundException; import xyz.playedu.api.exception.NotFoundException;
import xyz.playedu.api.service.ResourceCategoryService; import xyz.playedu.api.service.ResourceCategoryService;
import xyz.playedu.api.mapper.ResourceCategoryMapper; import xyz.playedu.api.mapper.ResourceCategoryMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -18,27 +20,20 @@ import java.util.List;
@Service @Service
public class ResourceCategoryServiceImpl extends ServiceImpl<ResourceCategoryMapper, ResourceCategory> public class ResourceCategoryServiceImpl extends ServiceImpl<ResourceCategoryMapper, ResourceCategory>
implements ResourceCategoryService { implements ResourceCategoryService {
@Override @Override
public List<ResourceCategory> getByType(String type) { public List<ResourceCategory> listByParentId(Integer id) {
return list(query().getWrapper().eq("type", type).orderByAsc("sort")); return list(query().getWrapper().eq("parent_id", id).orderByAsc("sort"));
} }
@Override @Override
public void create(String type, Integer sort, String name) { public List<ResourceCategory> all() {
ResourceCategory category = new ResourceCategory(); return list(query().getWrapper().orderByAsc("sort"));
category.setType(type);
category.setSort(sort);
category.setName(name);
category.setCreatedAt(new Date());
category.setUpdatedAt(new Date());
save(category);
} }
@Override @Override
public ResourceCategory findOrFail(Integer id) throws NotFoundException { public ResourceCategory findOrFail(Integer id) throws NotFoundException {
ResourceCategory category = getOne(query().getWrapper().eq("id", id)); ResourceCategory category = getById(id);
if (category == null) { if (category == null) {
throw new NotFoundException("分类不存在"); throw new NotFoundException("分类不存在");
} }
@ -46,18 +41,120 @@ public class ResourceCategoryServiceImpl extends ServiceImpl<ResourceCategoryMap
} }
@Override @Override
public void update(ResourceCategory category, Integer sort, String name) { @Transactional
ResourceCategory newCategory = new ResourceCategory(); public void deleteById(Integer id) throws NotFoundException {
newCategory.setId(category.getId()); ResourceCategory category = findOrFail(id);
newCategory.setSort(sort); //更新parent_chain
newCategory.setName(name); updateParentChain(category.getParentChain(), childrenParentChain(category));
updateById(newCategory); //删除记录
removeById(category.getId());
} }
@Override @Override
public ResourceCategory find(Integer id, String type) { @Transactional
return getOne(query().getWrapper().eq("id", id).eq("type", type)); public void update(ResourceCategory category, String name, Integer parentId, Integer sort) throws NotFoundException {
String childrenChainPrefix = childrenParentChain(category);
ResourceCategory data = new ResourceCategory();
data.setId(category.getId());
if (!category.getName().equals(name)) {
data.setName(name);
}
if (!category.getParentId().equals(parentId)) {
data.setParentId(parentId);
if (parentId.equals(0)) {
data.setParentChain("");
} else {
ResourceCategory parentResourceCategory = findOrFail(parentId);
data.setParentChain(childrenParentChain(parentResourceCategory));
}
}
if (!category.getSort().equals(sort)) {
data.setSort(sort);
}
//提交更换
updateById(data);
category = getById(category.getId());
updateParentChain(childrenParentChain(category), childrenChainPrefix);
} }
private void updateParentChain(String newChildrenPC, String oldChildrenPC) {
List<ResourceCategory> children = list(query().getWrapper().like("parent_chain", oldChildrenPC + "%"));
if (children.size() == 0) {
return;
}
ArrayList<ResourceCategory> updateRows = new ArrayList<>();
for (ResourceCategory tmpResourceCategory : children) {
ResourceCategory tmpUpdateResourceCategory = new ResourceCategory();
tmpUpdateResourceCategory.setId(tmpResourceCategory.getId());
// parentChain计算
String pc = newChildrenPC;
if (!tmpResourceCategory.getParentChain().equals(oldChildrenPC)) {
pc = tmpResourceCategory.getParentChain().replaceFirst(oldChildrenPC + ",", newChildrenPC.length() == 0 ? newChildrenPC : newChildrenPC + ',');
}
tmpUpdateResourceCategory.setParentChain(pc);
// parentId计算
int parentId = 0;
if (pc != null && pc.length() > 0) {
String[] parentIds = pc.split(",");
parentId = Integer.parseInt(parentIds[parentIds.length - 1]);
}
tmpUpdateResourceCategory.setParentId(parentId);
updateRows.add(tmpUpdateResourceCategory);
}
updateBatchById(updateRows);
}
@Override
public void create(String name, Integer parentId, Integer sort) throws NotFoundException {
String parentChain = "";
if (parentId != 0) {
parentChain = compParentChain(parentId);
}
ResourceCategory category = new ResourceCategory();
category.setName(name);
category.setParentId(parentId);
category.setParentChain(parentChain);
category.setSort(sort);
category.setCreatedAt(new Date());
category.setUpdatedAt(new Date());
save(category);
}
@Override
public String childrenParentChain(ResourceCategory category) {
String prefix = category.getId() + "";
if (category.getParentChain() != null && category.getParentChain().length() > 0) {
prefix = category.getParentChain() + "," + prefix;
}
return prefix;
}
@Override
public String compParentChain(Integer parentId) throws NotFoundException {
String parentChain = "";
if (parentId != 0) {
ResourceCategory parentResourceCategory = getById(parentId);
if (parentResourceCategory == null) {
throw new NotFoundException("父级分类不存在");
}
String pc = parentResourceCategory.getParentChain();
parentChain = pc == null || pc.length() == 0 ? parentId + "" : pc + "," + parentId;
}
return parentChain;
}
} }

View File

@ -5,18 +5,23 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import xyz.playedu.api.domain.Resource; import xyz.playedu.api.domain.Resource;
import xyz.playedu.api.domain.ResourceCategoryRelation;
import xyz.playedu.api.exception.NotFoundException; import xyz.playedu.api.exception.NotFoundException;
import xyz.playedu.api.service.ResourceService; import xyz.playedu.api.service.ResourceService;
import xyz.playedu.api.mapper.ResourceMapper; import xyz.playedu.api.mapper.ResourceMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import xyz.playedu.api.service.ResourceVideoService; import xyz.playedu.api.service.ResourceVideoService;
import xyz.playedu.api.service.internal.ResourceCategoryRelationService;
import xyz.playedu.api.types.paginate.PaginationResult; import xyz.playedu.api.types.paginate.PaginationResult;
import xyz.playedu.api.types.paginate.ResourcePaginateFilter; import xyz.playedu.api.types.paginate.ResourcePaginateFilter;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List;
/** /**
* @author tengteng * @author tengteng
@ -29,6 +34,9 @@ public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> i
@Autowired @Autowired
private ResourceVideoService resourceVideoService; private ResourceVideoService resourceVideoService;
@Autowired
private ResourceCategoryRelationService relationService;
@Override @Override
public PaginationResult<Resource> paginate(int page, int size, ResourcePaginateFilter filter) { public PaginationResult<Resource> paginate(int page, int size, ResourcePaginateFilter filter) {
QueryWrapper<Resource> wrapper = query().getWrapper().eq("is_hidden", 0); QueryWrapper<Resource> wrapper = query().getWrapper().eq("is_hidden", 0);
@ -46,7 +54,7 @@ public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> i
wrapper.eq("type", filter.getType()); wrapper.eq("type", filter.getType());
} }
if (filter.getCategoryIds() != null && filter.getCategoryIds().length > 0) { if (filter.getCategoryIds() != null && filter.getCategoryIds().length > 0) {
wrapper.in("category_id", Arrays.asList(filter.getCategoryIds())); // todo 资源分类过滤
} }
String sortFiled = filter.getSortField(); String sortFiled = filter.getSortField();
@ -74,10 +82,10 @@ public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> i
} }
@Override @Override
public Resource create(Integer categoryId, String type, String filename, String ext, Long size, String disk, String fileId, String path, String url) { @Transactional
public Resource create(String categoryIds, String type, String filename, String ext, Long size, String disk, String fileId, String path, String url) {
Resource resource = new Resource(); Resource resource = new Resource();
resource.setType(type); resource.setType(type);
resource.setCategoryId(categoryId);
resource.setName(filename); resource.setName(filename);
resource.setExtension(ext); resource.setExtension(ext);
resource.setSize(size); resource.setSize(size);
@ -87,6 +95,21 @@ public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> i
resource.setUrl(url); resource.setUrl(url);
resource.setCreatedAt(new Date()); resource.setCreatedAt(new Date());
save(resource); save(resource);
if (categoryIds != null && categoryIds.trim().length() > 0) {
String[] idArray = categoryIds.split(",");
List<ResourceCategoryRelation> relations = new ArrayList<>();
for (int i = 0; i < idArray.length; i++) {
String tmpId = idArray[i];
relations.add(new ResourceCategoryRelation() {{
setCid(Integer.valueOf(tmpId));
setRid(resource.getId());
}});
}
relationService.saveBatch(relations);
}
return resource; return resource;
} }

View File

@ -13,6 +13,8 @@ import xyz.playedu.api.service.UploadService;
import xyz.playedu.api.util.Base64Util; import xyz.playedu.api.util.Base64Util;
import xyz.playedu.api.util.HelperUtil; import xyz.playedu.api.util.HelperUtil;
import java.util.List;
/** /**
* @Author 杭州白书科技有限公司 * @Author 杭州白书科技有限公司
* @create 2023/3/8 14:02 * @create 2023/3/8 14:02
@ -20,9 +22,6 @@ import xyz.playedu.api.util.HelperUtil;
@Service @Service
public class UploadServiceImpl implements UploadService { public class UploadServiceImpl implements UploadService {
@Autowired
private ResourceCategoryService resourceCategoryService;
@Autowired @Autowired
private ResourceService resourceService; private ResourceService resourceService;
@ -30,7 +29,7 @@ public class UploadServiceImpl implements UploadService {
private MinioService minioService; private MinioService minioService;
@Override @Override
public Resource storeMinio(MultipartFile file, Integer cid) throws ServiceException { public Resource storeMinio(MultipartFile file, String categoryIds) throws ServiceException {
if (file == null || file.isEmpty() || file.getOriginalFilename() == null) { if (file == null || file.isEmpty() || file.getOriginalFilename() == null) {
throw new ServiceException("请上传文件"); throw new ServiceException("请上传文件");
} }
@ -50,11 +49,6 @@ public class UploadServiceImpl implements UploadService {
throw new ServiceException("格式不支持"); throw new ServiceException("格式不支持");
} }
// 分类校验
if (cid != null && !cid.equals(0) && resourceCategoryService.find(cid, type) == null) {
throw new ServiceException("分类不存在");
}
// 上传原文件的文件名 // 上传原文件的文件名
String oFilename = filename.replaceAll("." + ext, ""); String oFilename = filename.replaceAll("." + ext, "");
// 自定义新的存储文件名 // 自定义新的存储文件名
@ -64,17 +58,22 @@ public class UploadServiceImpl implements UploadService {
// 保存文件 // 保存文件
String url = minioService.saveFile(file, savePath, contentType); String url = minioService.saveFile(file, savePath, contentType);
// 上传记录 // 上传记录
return resourceService.create(cid, type, oFilename, ext, file.getSize(), BackendConstant.STORAGE_DRIVER_MINIO, "", savePath, url); return resourceService.create(categoryIds, type, oFilename, ext, file.getSize(), BackendConstant.STORAGE_DRIVER_MINIO, "", savePath, url);
} }
@Override @Override
public Resource storeBase64Image(String content, Integer categoryId) throws ServiceException { public Resource storeBase64Image(String content, String categoryIds) throws ServiceException {
// data:image/jpeg;base64, // data:image/jpeg;base64,
String[] base64Rows = content.split(","); String[] base64Rows = content.split(",");
// 解析出content-type
String contentType = base64Rows[0].replaceAll("data:", "").replaceAll(";base64", "").toLowerCase(); String contentType = base64Rows[0].replaceAll("data:", "").replaceAll(";base64", "").toLowerCase();
// 解析出文件格式
String ext = contentType.replaceAll("image/", ""); String ext = contentType.replaceAll("image/", "");
// 通过文件格式解析资源类型
String type = BackendConstant.RESOURCE_EXT_2_TYPE.get(ext); String type = BackendConstant.RESOURCE_EXT_2_TYPE.get(ext);
// 通过资源类型获取安全的content-type
String safeContentType = BackendConstant.RESOURCE_EXT_2_CONTENT_TYPE.get(ext); String safeContentType = BackendConstant.RESOURCE_EXT_2_CONTENT_TYPE.get(ext);
// 资源类型必须存在 && 安全的 content-type 必须存在 且与解析出来的 content-type 一致
if (type == null || safeContentType == null || !safeContentType.equals(contentType)) { if (type == null || safeContentType == null || !safeContentType.equals(contentType)) {
throw new ServiceException("格式不支持"); throw new ServiceException("格式不支持");
} }
@ -86,6 +85,6 @@ public class UploadServiceImpl implements UploadService {
// 保存文件 // 保存文件
String url = minioService.saveBytes(binary, savePath, contentType); String url = minioService.saveBytes(binary, savePath, contentType);
// 上传记录 // 上传记录
return resourceService.create(categoryId, type, filename, ext, (long) binary.length, BackendConstant.STORAGE_DRIVER_MINIO, "", savePath, url); return resourceService.create(categoryIds, type, filename, ext, (long) binary.length, BackendConstant.STORAGE_DRIVER_MINIO, "", savePath, url);
} }
} }

View File

@ -0,0 +1,22 @@
package xyz.playedu.api.service.impl.internal;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xyz.playedu.api.domain.ResourceCategoryRelation;
import xyz.playedu.api.service.internal.ResourceCategoryRelationService;
import xyz.playedu.api.mapper.ResourceCategoryRelationMapper;
import org.springframework.stereotype.Service;
/**
* @author tengteng
* @description 针对表resource_category的数据库操作Service实现
* @createDate 2023-03-08 16:54:56
*/
@Service
public class ResourceCategoryRelationServiceImpl extends ServiceImpl<ResourceCategoryRelationMapper, ResourceCategoryRelation>
implements ResourceCategoryRelationService{
}

View File

@ -0,0 +1,13 @@
package xyz.playedu.api.service.internal;
import xyz.playedu.api.domain.ResourceCategoryRelation;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author tengteng
* @description 针对表resource_category的数据库操作Service
* @createDate 2023-03-08 16:54:56
*/
public interface ResourceCategoryRelationService extends IService<ResourceCategoryRelation> {
}

View File

@ -6,7 +6,8 @@
<resultMap id="BaseResultMap" type="xyz.playedu.api.domain.ResourceCategory"> <resultMap id="BaseResultMap" type="xyz.playedu.api.domain.ResourceCategory">
<id property="id" column="id" jdbcType="INTEGER"/> <id property="id" column="id" jdbcType="INTEGER"/>
<result property="type" column="type" jdbcType="VARCHAR"/> <result property="parentId" column="parent_id" jdbcType="INTEGER"/>
<result property="parentChain" column="parent_chain" jdbcType="VARCHAR"/>
<result property="name" column="name" jdbcType="VARCHAR"/> <result property="name" column="name" jdbcType="VARCHAR"/>
<result property="sort" column="sort" jdbcType="INTEGER"/> <result property="sort" column="sort" jdbcType="INTEGER"/>
<result property="createdAt" column="created_at" jdbcType="TIMESTAMP"/> <result property="createdAt" column="created_at" jdbcType="TIMESTAMP"/>
@ -14,7 +15,8 @@
</resultMap> </resultMap>
<sql id="Base_Column_List"> <sql id="Base_Column_List">
id,type,name, id,parent_id,parent_chain,
sort,created_at,updated_at name,sort,created_at,
updated_at
</sql> </sql>
</mapper> </mapper>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xyz.playedu.api.mapper.ResourceCategoryRelationMapper">
<resultMap id="BaseResultMap" type="xyz.playedu.api.domain.ResourceCategoryRelation">
<result property="cid" column="cid" jdbcType="INTEGER"/>
<result property="rid" column="rid" jdbcType="INTEGER"/>
</resultMap>
<sql id="Base_Column_List">
cid,rid
</sql>
</mapper>

View File

@ -7,7 +7,6 @@
<resultMap id="BaseResultMap" type="xyz.playedu.api.domain.Resource"> <resultMap id="BaseResultMap" type="xyz.playedu.api.domain.Resource">
<id property="id" column="id" jdbcType="INTEGER"/> <id property="id" column="id" jdbcType="INTEGER"/>
<result property="type" column="type" jdbcType="VARCHAR"/> <result property="type" column="type" jdbcType="VARCHAR"/>
<result property="categoryId" column="category_id" jdbcType="INTEGER"/>
<result property="name" column="name" jdbcType="VARCHAR"/> <result property="name" column="name" jdbcType="VARCHAR"/>
<result property="extension" column="extension" jdbcType="VARCHAR"/> <result property="extension" column="extension" jdbcType="VARCHAR"/>
<result property="size" column="size" jdbcType="BIGINT"/> <result property="size" column="size" jdbcType="BIGINT"/>
@ -21,10 +20,9 @@
</resultMap> </resultMap>
<sql id="Base_Column_List"> <sql id="Base_Column_List">
id,type,category_id, id,type,name,
name,extension,size, extension,size,disk,
disk,file_id,path, file_id,path,url,
url,created_at,parent_id, created_at,parent_id,is_hidden
is_hidden
</sql> </sql>
</mapper> </mapper>