diff --git a/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/collection/CollectionUtils.java b/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/collection/CollectionUtils.java index ed58c4f16..aa523b94d 100644 --- a/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/collection/CollectionUtils.java +++ b/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/collection/CollectionUtils.java @@ -11,6 +11,7 @@ import java.util.function.*; import java.util.stream.Collectors; import java.util.stream.Stream; +import static cn.hutool.core.convert.Convert.toCollection; import static java.util.Arrays.asList; /** @@ -335,4 +336,17 @@ public class CollectionUtils { return list.stream().filter(Objects::nonNull).flatMap(Collection::stream).collect(Collectors.toList()); } + /** + * 转换为 LinkedHashSet + * + * @param 元素类型 + * @param elementType 集合中元素类型 + * @param value 被转换的值 + * @return {@link LinkedHashSet} + */ + @SuppressWarnings("unchecked") + public static LinkedHashSet toLinkedHashSet(Class elementType, Object value) { + return (LinkedHashSet) toCollection(LinkedHashSet.class, elementType, value); + } + } \ No newline at end of file diff --git a/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/io/FileUtils.java b/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/io/FileUtils.java index 2f870d738..63732f1b3 100644 --- a/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/io/FileUtils.java +++ b/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/io/FileUtils.java @@ -1,14 +1,9 @@ package cn.iocoder.yudao.framework.common.util.io; -import cn.hutool.core.io.FileTypeUtil; import cn.hutool.core.io.FileUtil; -import cn.hutool.core.io.file.FileNameUtil; import cn.hutool.core.util.IdUtil; -import cn.hutool.core.util.StrUtil; -import cn.hutool.crypto.digest.DigestUtil; import lombok.SneakyThrows; -import java.io.ByteArrayInputStream; import java.io.File; /** @@ -63,22 +58,4 @@ public class FileUtils { return file; } - /** - * 生成文件路径 - * - * @param content 文件内容 - * @param originalName 原始文件名 - * @return path,唯一不可重复 - */ - public static String generatePath(byte[] content, String originalName) { - String sha256Hex = DigestUtil.sha256Hex(content); - // 情况一:如果存在 name,则优先使用 name 的后缀 - if (StrUtil.isNotBlank(originalName)) { - String extName = FileNameUtil.extName(originalName); - return StrUtil.isBlank(extName) ? sha256Hex : sha256Hex + "." + extName; - } - // 情况二:基于 content 计算 - return sha256Hex + '.' + FileTypeUtil.getType(new ByteArrayInputStream(content)); - } - } diff --git a/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/config/YudaoRedisMQConsumerAutoConfiguration.java b/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/config/YudaoRedisMQConsumerAutoConfiguration.java index d02e84b14..c9ab3e541 100644 --- a/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/config/YudaoRedisMQConsumerAutoConfiguration.java +++ b/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/config/YudaoRedisMQConsumerAutoConfiguration.java @@ -6,6 +6,7 @@ import cn.hutool.system.SystemUtil; import cn.iocoder.yudao.framework.common.enums.DocumentEnum; import cn.iocoder.yudao.framework.mq.redis.core.RedisMQTemplate; import cn.iocoder.yudao.framework.mq.redis.core.job.RedisPendingMessageResendJob; +import cn.iocoder.yudao.framework.mq.redis.core.job.RedisStreamMessageCleanupJob; import cn.iocoder.yudao.framework.mq.redis.core.pubsub.AbstractRedisChannelMessageListener; import cn.iocoder.yudao.framework.mq.redis.core.stream.AbstractRedisStreamMessageListener; import cn.iocoder.yudao.framework.redis.config.YudaoRedisAutoConfiguration; @@ -73,6 +74,17 @@ public class YudaoRedisMQConsumerAutoConfiguration { return new RedisPendingMessageResendJob(listeners, redisTemplate, groupName, redissonClient); } + /** + * 创建 Redis Stream 消息清理任务 + */ + @Bean + @ConditionalOnBean(AbstractRedisStreamMessageListener.class) + public RedisStreamMessageCleanupJob redisStreamMessageCleanupJob(List> listeners, + RedisMQTemplate redisTemplate, + RedissonClient redissonClient) { + return new RedisStreamMessageCleanupJob(listeners, redisTemplate, redissonClient); + } + /** * 创建 Redis Stream 集群消费的容器 * diff --git a/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/core/job/RedisPendingMessageResendJob.java b/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/core/job/RedisPendingMessageResendJob.java index b84f17c15..cb4e3991f 100644 --- a/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/core/job/RedisPendingMessageResendJob.java +++ b/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/core/job/RedisPendingMessageResendJob.java @@ -23,13 +23,13 @@ import java.util.Objects; @AllArgsConstructor public class RedisPendingMessageResendJob { - private static final String LOCK_KEY = "redis:pending:msg:lock"; + private static final String LOCK_KEY = "redis:stream:pending-message-resend:lock"; /** * 消息超时时间,默认 5 分钟 * * 1. 超时的消息才会被重新投递 - * 2. 由于定时任务 1 分钟一次,消息超时后不会被立即重投,极端情况下消息5分钟过期后,再等 1 分钟才会被扫瞄到 + * 2. 由于定时任务 1 分钟一次,消息超时后不会被立即重投,极端情况下消息 5 分钟过期后,再等 1 分钟才会被扫瞄到 */ private static final int EXPIRE_TIME = 5 * 60; @@ -39,7 +39,7 @@ public class RedisPendingMessageResendJob { private final RedissonClient redissonClient; /** - * 一分钟执行一次,这里选择每分钟的35秒执行,是为了避免整点任务过多的问题 + * 一分钟执行一次,这里选择每分钟的 35 秒执行,是为了避免整点任务过多的问题 */ @Scheduled(cron = "35 * * * * ?") public void messageResend() { diff --git a/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/core/job/RedisStreamMessageCleanupJob.java b/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/core/job/RedisStreamMessageCleanupJob.java new file mode 100644 index 000000000..19da84594 --- /dev/null +++ b/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/core/job/RedisStreamMessageCleanupJob.java @@ -0,0 +1,72 @@ +package cn.iocoder.yudao.framework.mq.redis.core.job; + +import cn.iocoder.yudao.framework.mq.redis.core.RedisMQTemplate; +import cn.iocoder.yudao.framework.mq.redis.core.stream.AbstractRedisStreamMessageListener; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.redisson.api.RLock; +import org.redisson.api.RedissonClient; +import org.springframework.data.redis.core.StreamOperations; +import org.springframework.scheduling.annotation.Scheduled; + +import java.util.List; + +/** + * Redis Stream 消息清理任务 + * 用于定期清理已消费的消息,防止内存占用过大 + * + * @see 记一次 redis stream 数据类型内存不释放问题 + * + * @author 芋道源码 + */ +@Slf4j +@AllArgsConstructor +public class RedisStreamMessageCleanupJob { + + private static final String LOCK_KEY = "redis:stream:message-cleanup:lock"; + + /** + * 保留的消息数量,默认保留最近 10000 条消息 + */ + private static final long MAX_COUNT = 10000; + + private final List> listeners; + private final RedisMQTemplate redisTemplate; + private final RedissonClient redissonClient; + + /** + * 每小时执行一次清理任务 + */ + @Scheduled(cron = "0 0 * * * ?") + public void cleanup() { + RLock lock = redissonClient.getLock(LOCK_KEY); + // 尝试加锁 + if (lock.tryLock()) { + try { + execute(); + } catch (Exception ex) { + log.error("[cleanup][执行异常]", ex); + } finally { + lock.unlock(); + } + } + } + + /** + * 执行清理逻辑 + */ + private void execute() { + StreamOperations ops = redisTemplate.getRedisTemplate().opsForStream(); + listeners.forEach(listener -> { + try { + // 使用 XTRIM 命令清理消息,只保留最近的 MAX_LEN 条消息 + Long trimCount = ops.trim(listener.getStreamKey(), MAX_COUNT, true); + if (trimCount != null && trimCount > 0) { + log.info("[execute][Stream({}) 清理消息数量({})]", listener.getStreamKey(), trimCount); + } + } catch (Exception ex) { + log.error("[execute][Stream({}) 清理异常]", listener.getStreamKey(), ex); + } + }); + } +} \ No newline at end of file diff --git a/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/core/filter/TokenAuthenticationFilter.java b/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/core/filter/TokenAuthenticationFilter.java index 2bf0f87dc..071e1a0cd 100644 --- a/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/core/filter/TokenAuthenticationFilter.java +++ b/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/core/filter/TokenAuthenticationFilter.java @@ -13,16 +13,15 @@ import cn.iocoder.yudao.framework.web.core.handler.GlobalExceptionHandler; import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils; import cn.iocoder.yudao.module.system.api.oauth2.OAuth2TokenApi; import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenCheckRespDTO; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; -import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.filter.OncePerRequestFilter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; @@ -129,15 +128,24 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter { .setTenantId(WebFrameworkUtils.getTenantId(request)); } - @SneakyThrows private LoginUser buildLoginUserByHeader(HttpServletRequest request) { String loginUserStr = request.getHeader(SecurityFrameworkUtils.LOGIN_USER_HEADER); if (StrUtil.isEmpty(loginUserStr)) { return null; } try { - loginUserStr = URLDecoder.decode(loginUserStr, StandardCharsets.UTF_8.name()); // 解码,解决中文乱码问题 - return JsonUtils.parseObject(loginUserStr, LoginUser.class); + loginUserStr = URLDecoder.decode(loginUserStr, StandardCharsets.UTF_8); // 解码,解决中文乱码问题 + LoginUser loginUser = JsonUtils.parseObject(loginUserStr, LoginUser.class); + // 用户类型不匹配,无权限 + // 注意:只有 /admin-api/* 和 /app-api/* 有 userType,才需要比对用户类型 + // 类似 WebSocket 的 /ws/* 连接地址,是不需要比对用户类型的 + Integer userType = WebFrameworkUtils.getLoginUserType(request); + if (userType != null + && loginUser != null + && ObjectUtil.notEqual(loginUser.getUserType(), userType)) { + throw new AccessDeniedException("错误的用户类型"); + } + return loginUser; } catch (Exception ex) { log.error("[buildLoginUserByHeader][解析 LoginUser({}) 发生异常]", loginUserStr, ex); ; throw ex; diff --git a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/framework/flowable/core/candidate/strategy/form/BpmTaskCandidateFormUserStrategy.java b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/framework/flowable/core/candidate/strategy/form/BpmTaskCandidateFormUserStrategy.java index 2d315979a..6298c3259 100644 --- a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/framework/flowable/core/candidate/strategy/form/BpmTaskCandidateFormUserStrategy.java +++ b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/framework/flowable/core/candidate/strategy/form/BpmTaskCandidateFormUserStrategy.java @@ -1,7 +1,7 @@ package cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.strategy.form; -import cn.hutool.core.convert.Convert; import cn.hutool.core.lang.Assert; +import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.BpmTaskCandidateStrategy; import cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.strategy.user.BpmTaskCandidateUserStrategy; import cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmTaskCandidateStrategyEnum; @@ -33,7 +33,7 @@ public class BpmTaskCandidateFormUserStrategy implements BpmTaskCandidateStrateg @Override public Set calculateUsersByTask(DelegateExecution execution, String param) { Object result = execution.getVariable(param); - return Convert.toSet(Long.class, result); + return CollectionUtils.toLinkedHashSet(Long.class, result); } @Override @@ -41,7 +41,7 @@ public class BpmTaskCandidateFormUserStrategy implements BpmTaskCandidateStrateg String param, Long startUserId, String processDefinitionId, Map processVariables) { Object result = processVariables == null ? null : processVariables.get(param); - return Convert.toSet(Long.class, result); + return CollectionUtils.toLinkedHashSet(Long.class, result); } } diff --git a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/framework/flowable/core/candidate/strategy/other/BpmTaskCandidateExpressionStrategy.java b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/framework/flowable/core/candidate/strategy/other/BpmTaskCandidateExpressionStrategy.java index c008c1cb6..64ca9e853 100644 --- a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/framework/flowable/core/candidate/strategy/other/BpmTaskCandidateExpressionStrategy.java +++ b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/framework/flowable/core/candidate/strategy/other/BpmTaskCandidateExpressionStrategy.java @@ -1,6 +1,6 @@ package cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.strategy.other; -import cn.hutool.core.convert.Convert; +import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.BpmTaskCandidateStrategy; import cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmTaskCandidateStrategyEnum; import cn.iocoder.yudao.module.bpm.framework.flowable.core.util.FlowableUtils; @@ -37,7 +37,7 @@ public class BpmTaskCandidateExpressionStrategy implements BpmTaskCandidateStrat @Override public Set calculateUsersByTask(DelegateExecution execution, String param) { Object result = FlowableUtils.getExpressionValue(execution, param); - return Convert.toSet(Long.class, result); + return CollectionUtils.toLinkedHashSet(Long.class, result); } @Override @@ -46,7 +46,7 @@ public class BpmTaskCandidateExpressionStrategy implements BpmTaskCandidateStrat Map variables = processVariables == null ? new HashMap<>() : processVariables; try { Object result = FlowableUtils.getExpressionValue(variables, param); - return Convert.toSet(Long.class, result); + return CollectionUtils.toLinkedHashSet(Long.class, result); } catch (FlowableException ex) { // 预测未运行的节点时候,表达式如果包含 execution 或者不存在的流程变量会抛异常, log.warn("[calculateUsersByActivity][表达式({}) 变量({}) 解析报错", param, variables, ex); diff --git a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/task/BpmTaskServiceImpl.java b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/task/BpmTaskServiceImpl.java index 64358dd06..67bc7de1b 100644 --- a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/task/BpmTaskServiceImpl.java +++ b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/task/BpmTaskServiceImpl.java @@ -873,12 +873,14 @@ public class BpmTaskServiceImpl implements BpmTaskService { List returnUserTaskList = BpmnModelUtils.iteratorFindChildUserTasks(targetElement, runTaskKeyList, null, null); List returnTaskKeyList = convertList(returnUserTaskList, UserTask::getId); + List runExecutionIds = new ArrayList<>(); // 2. 给当前要被退回的 task 数组,设置退回意见 taskList.forEach(task -> { // 需要排除掉,不需要设置退回意见的任务 if (!returnTaskKeyList.contains(task.getTaskDefinitionKey())) { return; } + runExecutionIds.add(task.getExecutionId()); // 判断是否分配给自己任务,因为会签任务,一个节点会有多个任务 if (isAssignUserTask(userId, task)) { // 情况一:自己的任务,进行 RETURN 标记 @@ -898,7 +900,6 @@ public class BpmTaskServiceImpl implements BpmTaskService { // 4. 执行驳回 // 使用 moveExecutionsToSingleActivityId 替换 moveActivityIdsToSingleActivityId 原因: // 当多实例任务回退的时候有问题。相关 issue: https://github.com/flowable/flowable-engine/issues/3944 - List runExecutionIds = convertList(taskList, Task::getExecutionId); runtimeService.createChangeActivityStateBuilder() .processInstanceId(currentTask.getProcessInstanceId()) .moveExecutionsToSingleActivityId(runExecutionIds, reqVO.getTargetTaskDefinitionKey()) diff --git a/yudao-module-infra/yudao-module-infra-api/src/main/java/cn/iocoder/yudao/module/infra/api/file/FileApi.java b/yudao-module-infra/yudao-module-infra-api/src/main/java/cn/iocoder/yudao/module/infra/api/file/FileApi.java index 9828721a4..9c6f0f4a3 100644 --- a/yudao-module-infra/yudao-module-infra-api/src/main/java/cn/iocoder/yudao/module/infra/api/file/FileApi.java +++ b/yudao-module-infra/yudao-module-infra-api/src/main/java/cn/iocoder/yudao/module/infra/api/file/FileApi.java @@ -3,14 +3,13 @@ package cn.iocoder.yudao.module.infra.api.file; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.module.infra.api.file.dto.FileCreateReqDTO; import cn.iocoder.yudao.module.infra.enums.ApiConstants; -import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotEmpty; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; - -import javax.validation.Valid; @FeignClient(name = ApiConstants.NAME) // TODO 芋艿:fallbackFactory = @Tag(name = "RPC 服务 - 文件") @@ -25,32 +24,32 @@ public interface FileApi { * @return 文件路径 */ default String createFile(byte[] content) { - return createFile(null, null, content); + return createFile(content, null, null, null); } /** * 保存文件,并返回文件的访问路径 * - * @param path 文件路径 * @param content 文件内容 + * @param name 文件名称,允许空 * @return 文件路径 */ - default String createFile(String path, byte[] content) { - return createFile(null, path, content); + default String createFile(byte[] content, String name) { + return createFile(content, name, null, null); } /** * 保存文件,并返回文件的访问路径 * - * @param name 原文件名称 - * @param path 文件路径 * @param content 文件内容 + * @param name 文件名称,允许空 + * @param directory 目录,允许空 + * @param type 文件的 MIME 类型,允许空 * @return 文件路径 */ - default String createFile(@RequestParam("name") String name, - @RequestParam("path") String path, - @RequestParam("content") byte[] content) { - return createFile(new FileCreateReqDTO().setName(name).setPath(path).setContent(content)).getCheckedData(); + default String createFile(@NotEmpty(message = "文件内容不能为空") byte[] content, + String name, String directory, String type) { + return createFile(new FileCreateReqDTO().setName(name).setDirectory(directory).setType(type).setContent(content)).getCheckedData(); } @PostMapping(PREFIX + "/create") diff --git a/yudao-module-infra/yudao-module-infra-api/src/main/java/cn/iocoder/yudao/module/infra/api/file/dto/FileCreateReqDTO.java b/yudao-module-infra/yudao-module-infra-api/src/main/java/cn/iocoder/yudao/module/infra/api/file/dto/FileCreateReqDTO.java index 1f554e653..731ca7c86 100644 --- a/yudao-module-infra/yudao-module-infra-api/src/main/java/cn/iocoder/yudao/module/infra/api/file/dto/FileCreateReqDTO.java +++ b/yudao-module-infra/yudao-module-infra-api/src/main/java/cn/iocoder/yudao/module/infra/api/file/dto/FileCreateReqDTO.java @@ -12,8 +12,11 @@ public class FileCreateReqDTO { @Schema(description = "原文件名称", example = "xxx.png") private String name; - @Schema(description = "文件路径", example = "xxx.png") - private String path; + @Schema(description = "文件目录", example = "xxx") + private String directory; + + @Schema(description = "文件的 MIME 类型", example = "image/png") + private String type; @Schema(description = "文件内容", requiredMode = Schema.RequiredMode.REQUIRED) @NotEmpty(message = "文件内容不能为空") diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/api/file/FileApiImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/api/file/FileApiImpl.java index 32f7aab88..d7232685b 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/api/file/FileApiImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/api/file/FileApiImpl.java @@ -19,8 +19,8 @@ public class FileApiImpl implements FileApi { @Override public CommonResult createFile(FileCreateReqDTO createReqDTO) { - return success(fileService.createFile(createReqDTO.getName(), createReqDTO.getPath(), - createReqDTO.getContent())); + return success(fileService.createFile(createReqDTO.getContent(), createReqDTO.getName(), + createReqDTO.getDirectory(), createReqDTO.getType())); } } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/FileController.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/FileController.java index db137d5ed..5260ad85d 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/FileController.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/FileController.java @@ -11,6 +11,7 @@ import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileDO; import cn.iocoder.yudao.module.infra.service.file.FileService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.tags.Tag; import javax.annotation.Resource; import javax.annotation.security.PermitAll; @@ -41,14 +42,21 @@ public class FileController { @Operation(summary = "上传文件", description = "模式一:后端上传文件") public CommonResult uploadFile(FileUploadReqVO uploadReqVO) throws Exception { MultipartFile file = uploadReqVO.getFile(); - String path = uploadReqVO.getPath(); - return success(fileService.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream()))); + byte[] content = IoUtil.readBytes(file.getInputStream()); + return success(fileService.createFile(content, file.getOriginalFilename(), + uploadReqVO.getDirectory(), file.getContentType())); } @GetMapping("/presigned-url") @Operation(summary = "获取文件预签名地址", description = "模式二:前端上传文件:用于前端直接上传七牛、阿里云 OSS 等文件存储器") - public CommonResult getFilePresignedUrl(@RequestParam("path") String path) throws Exception { - return success(fileService.getFilePresignedUrl(path)); + @Parameters({ + @Parameter(name = "name", description = "文件名称", required = true), + @Parameter(name = "directory", description = "文件目录") + }) + public CommonResult getFilePresignedUrl( + @RequestParam("name") String name, + @RequestParam(value = "directory", required = false) String directory) { + return success(fileService.getFilePresignedUrl(name, directory)); } @PostMapping("/create") diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/vo/file/FilePresignedUrlRespVO.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/vo/file/FilePresignedUrlRespVO.java index 926133ebc..72be6ae26 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/vo/file/FilePresignedUrlRespVO.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/vo/file/FilePresignedUrlRespVO.java @@ -14,7 +14,8 @@ public class FilePresignedUrlRespVO { @Schema(description = "配置编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "11") private Long configId; - @Schema(description = "文件上传 URL", requiredMode = Schema.RequiredMode.REQUIRED, example = "https://s3.cn-south-1.qiniucs.com/ruoyi-vue-pro/758d3a5387507358c7236de4c8f96de1c7f5097ff6a7722b34772fb7b76b140f.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=3TvrJ70gl2Gt6IBe7_IZT1F6i_k0iMuRtyEv4EyS%2F20240217%2Fcn-south-1%2Fs3%2Faws4_request&X-Amz-Date=20240217T123222Z&X-Amz-Expires=600&X-Amz-SignedHeaders=host&X-Amz-Signature=a29f33770ab79bf523ccd4034d0752ac545f3c2a3b17baa1eb4e280cfdccfda5") + @Schema(description = "文件上传 URL", requiredMode = Schema.RequiredMode.REQUIRED, + example = "https://s3.cn-south-1.qiniucs.com/ruoyi-vue-pro/758d3a5387507358c7236de4c8f96de1c7f5097ff6a7722b34772fb7b76b140f.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=3TvrJ70gl2Gt6IBe7_IZT1F6i_k0iMuRtyEv4EyS%2F20240217%2Fcn-south-1%2Fs3%2Faws4_request&X-Amz-Date=20240217T123222Z&X-Amz-Expires=600&X-Amz-SignedHeaders=host&X-Amz-Signature=a29f33770ab79bf523ccd4034d0752ac545f3c2a3b17baa1eb4e280cfdccfda5") private String uploadUrl; /** @@ -26,4 +27,12 @@ public class FilePresignedUrlRespVO { example = "https://test.yudao.iocoder.cn/758d3a5387507358c7236de4c8f96de1c7f5097ff6a7722b34772fb7b76b140f.png") private String url; + /** + * 为什么要返回 path 字段? + * + * 前端上传完文件后,需要调用 createFile 记录下 path 路径 + */ + @Schema(description = "文件路径", requiredMode = Schema.RequiredMode.REQUIRED, example = "xxx.png") + private String path; + } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/vo/file/FileUploadReqVO.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/vo/file/FileUploadReqVO.java index b60b9a180..918ea8902 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/vo/file/FileUploadReqVO.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/file/vo/file/FileUploadReqVO.java @@ -14,7 +14,7 @@ public class FileUploadReqVO { @NotNull(message = "文件附件不能为空") private MultipartFile file; - @Schema(description = "文件附件", example = "yudaoyuanma.png") - private String path; + @Schema(description = "文件目录", example = "XXX/YYY") + private String directory; } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/app/file/AppFileController.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/app/file/AppFileController.java index 0c568e529..47dcde7cf 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/app/file/AppFileController.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/app/file/AppFileController.java @@ -7,6 +7,8 @@ import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.FilePresigned import cn.iocoder.yudao.module.infra.controller.app.file.vo.AppFileUploadReqVO; import cn.iocoder.yudao.module.infra.service.file.FileService; import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.annotation.Validated; @@ -34,15 +36,21 @@ public class AppFileController { @PermitAll public CommonResult uploadFile(AppFileUploadReqVO uploadReqVO) throws Exception { MultipartFile file = uploadReqVO.getFile(); - String path = uploadReqVO.getPath(); - return success(fileService.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream()))); + byte[] content = IoUtil.readBytes(file.getInputStream()); + return success(fileService.createFile(content, file.getOriginalFilename(), + uploadReqVO.getDirectory(), file.getContentType())); } @GetMapping("/presigned-url") @Operation(summary = "获取文件预签名地址", description = "模式二:前端上传文件:用于前端直接上传七牛、阿里云 OSS 等文件存储器") - @PermitAll - public CommonResult getFilePresignedUrl(@RequestParam("path") String path) throws Exception { - return success(fileService.getFilePresignedUrl(path)); + @Parameters({ + @Parameter(name = "name", description = "文件名称", required = true), + @Parameter(name = "directory", description = "文件目录") + }) + public CommonResult getFilePresignedUrl( + @RequestParam("name") String name, + @RequestParam(value = "directory", required = false) String directory) { + return success(fileService.getFilePresignedUrl(name, directory)); } @PostMapping("/create") diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/app/file/vo/AppFileUploadReqVO.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/app/file/vo/AppFileUploadReqVO.java index 04666c14f..c27465222 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/app/file/vo/AppFileUploadReqVO.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/app/file/vo/AppFileUploadReqVO.java @@ -14,7 +14,7 @@ public class AppFileUploadReqVO { @NotNull(message = "文件附件不能为空") private MultipartFile file; - @Schema(description = "文件附件", example = "yudaoyuanma.png") - private String path; + @Schema(description = "文件目录", example = "XXX/YYY") + private String directory; } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/enums/codegen/CodegenFrontTypeEnum.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/enums/codegen/CodegenFrontTypeEnum.java index 1b6bb41ab..db4326f91 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/enums/codegen/CodegenFrontTypeEnum.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/enums/codegen/CodegenFrontTypeEnum.java @@ -13,9 +13,14 @@ import lombok.Getter; public enum CodegenFrontTypeEnum { VUE2_ELEMENT_UI(10), // Vue2 Element UI 标准模版 + VUE3_ELEMENT_PLUS(20), // Vue3 Element Plus 标准模版 + VUE3_VBEN2_ANTD_SCHEMA(30), // Vue3 VBEN2 + ANTD + Schema 模版 + VUE3_VBEN5_ANTD_SCHEMA(40), // Vue3 VBEN5 + ANTD + schema 模版 + + VUE3_VBEN5_ANTD_GENERAL(41), // Vue3 VBEN5 + ANTD 标准模版 ; /** diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/ftp/FtpFileClient.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/ftp/FtpFileClient.java index 062d83818..4207eb7e1 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/ftp/FtpFileClient.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/ftp/FtpFileClient.java @@ -26,12 +26,6 @@ public class FtpFileClient extends AbstractFileClient { @Override protected void doInit() { - // 把配置的 \ 替换成 /, 如果路径配置 \a\test, 替换成 /a/test, 替换方法已经处理 null 情况 - config.setBasePath(StrUtil.replace(config.getBasePath(), StrUtil.BACKSLASH, StrUtil.SLASH)); - // ftp的路径是 / 结尾 - if (!config.getBasePath().endsWith(StrUtil.SLASH)) { - config.setBasePath(config.getBasePath() + StrUtil.SLASH); - } // 初始化 Ftp 对象 this.ftp = new Ftp(config.getHost(), config.getPort(), config.getUsername(), config.getPassword(), CharsetUtil.CHARSET_UTF_8, null, null, FtpMode.valueOf(config.getMode())); @@ -43,8 +37,8 @@ public class FtpFileClient extends AbstractFileClient { String filePath = getFilePath(path); String fileName = FileUtil.getName(filePath); String dir = StrUtil.removeSuffix(filePath, fileName); - ftp.reconnectIfTimeout(); - boolean success = ftp.upload(dir, fileName, new ByteArrayInputStream(content)); + reconnectIfTimeout(); + boolean success = ftp.upload(dir, fileName, new ByteArrayInputStream(content)); // 不需要主动创建目录,ftp 内部已经处理(见源码) if (!success) { throw new FtpException(StrUtil.format("上传文件到目标目录 ({}) 失败", filePath)); } @@ -55,7 +49,7 @@ public class FtpFileClient extends AbstractFileClient { @Override public void delete(String path) { String filePath = getFilePath(path); - ftp.reconnectIfTimeout(); + reconnectIfTimeout(); ftp.delFile(filePath); } @@ -65,13 +59,17 @@ public class FtpFileClient extends AbstractFileClient { String fileName = FileUtil.getName(filePath); String dir = StrUtil.removeSuffix(filePath, fileName); ByteArrayOutputStream out = new ByteArrayOutputStream(); - ftp.reconnectIfTimeout(); + reconnectIfTimeout(); ftp.download(dir, fileName, out); return out.toByteArray(); } private String getFilePath(String path) { - return config.getBasePath() + path; + return config.getBasePath() + StrUtil.SLASH + path; + } + + private synchronized void reconnectIfTimeout() { + ftp.reconnectIfTimeout(); } } \ No newline at end of file diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/local/LocalFileClient.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/local/LocalFileClient.java index a9196903e..7fa2a7ea9 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/local/LocalFileClient.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/local/LocalFileClient.java @@ -18,10 +18,6 @@ public class LocalFileClient extends AbstractFileClient { @Override protected void doInit() { - // 补全风格。例如说 Linux 是 /,Windows 是 \ - if (!config.getBasePath().endsWith(File.separator)) { - config.setBasePath(config.getBasePath() + File.separator); - } } @Override @@ -46,7 +42,7 @@ public class LocalFileClient extends AbstractFileClient { } private String getFilePath(String path) { - return config.getBasePath() + path; + return config.getBasePath() + File.separator + path; } } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/s3/S3FileClient.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/s3/S3FileClient.java index d74d80560..a33f0d738 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/s3/S3FileClient.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/s3/S3FileClient.java @@ -46,7 +46,9 @@ public class S3FileClient extends AbstractFileClient { AwsBasicCredentials.create(config.getAccessKey(), config.getAccessSecret())); URI endpoint = URI.create(buildEndpoint()); S3Configuration serviceConfiguration = S3Configuration.builder() // Path-style 访问 - .pathStyleAccessEnabled(Boolean.TRUE.equals(config.getEnablePathStyleAccess())).build(); + .pathStyleAccessEnabled(Boolean.TRUE.equals(config.getEnablePathStyleAccess())) + .chunkedEncodingEnabled(false) // 禁用分块编码,参见 https://t.zsxq.com/kBy57 + .build(); client = S3Client.builder() .credentialsProvider(credentialsProvider) .region(region) diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/sftp/SftpFileClient.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/sftp/SftpFileClient.java index 3ebe78215..000cbd10b 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/sftp/SftpFileClient.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/client/sftp/SftpFileClient.java @@ -22,10 +22,6 @@ public class SftpFileClient extends AbstractFileClient { @Override protected void doInit() { - // 补全风格。例如说 Linux 是 /,Windows 是 \ - if (!config.getBasePath().endsWith(File.separator)) { - config.setBasePath(config.getBasePath() + File.separator); - } // 初始化 Ftp 对象 this.sftp = new Sftp(config.getHost(), config.getPort(), config.getUsername(), config.getPassword()); } @@ -35,6 +31,8 @@ public class SftpFileClient extends AbstractFileClient { // 执行写入 String filePath = getFilePath(path); File file = FileUtils.createTempFile(content); + reconnectIfTimeout(); + sftp.mkDirs(FileUtil.getParent(filePath, 1)); // 需要创建父目录,不然会报错 sftp.upload(filePath, file); // 拼接返回路径 return super.formatFileUrl(config.getDomain(), path); @@ -43,6 +41,7 @@ public class SftpFileClient extends AbstractFileClient { @Override public void delete(String path) { String filePath = getFilePath(path); + reconnectIfTimeout(); sftp.delFile(filePath); } @@ -50,12 +49,17 @@ public class SftpFileClient extends AbstractFileClient { public byte[] getContent(String path) { String filePath = getFilePath(path); File destFile = FileUtils.createTempFile(); + reconnectIfTimeout(); sftp.download(filePath, destFile); return FileUtil.readBytes(destFile); } private String getFilePath(String path) { - return config.getBasePath() + path; + return config.getBasePath() + File.separator + path; + } + + private synchronized void reconnectIfTimeout() { + sftp.reconnectIfTimeout(); } } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/utils/FileTypeUtils.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/utils/FileTypeUtils.java index 7a3e5748a..a53f7058d 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/utils/FileTypeUtils.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/file/core/utils/FileTypeUtils.java @@ -5,7 +5,10 @@ import cn.hutool.core.util.StrUtil; import cn.iocoder.yudao.framework.common.util.http.HttpUtils; import com.alibaba.ttl.TransmittableThreadLocal; import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; import org.apache.tika.Tika; +import org.apache.tika.mime.MimeTypeException; +import org.apache.tika.mime.MimeTypes; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -15,12 +18,13 @@ import java.io.IOException; * * @author 芋道源码 */ +@Slf4j public class FileTypeUtils { private static final ThreadLocal TIKA = TransmittableThreadLocal.withInitial(Tika::new); /** - * 获得文件的 mineType,对于doc,jar等文件会有误差 + * 获得文件的 mineType,对于 doc,jar 等文件会有误差 * * @param data 文件内容 * @return mineType 无法识别时会返回“application/octet-stream” @@ -31,7 +35,7 @@ public class FileTypeUtils { } /** - * 已知文件名,获取文件类型,在某些情况下比通过字节数组准确,例如使用jar文件时,通过名字更为准确 + * 已知文件名,获取文件类型,在某些情况下比通过字节数组准确,例如使用 jar 文件时,通过名字更为准确 * * @param name 文件名 * @return mineType 无法识别时会返回“application/octet-stream” @@ -51,6 +55,23 @@ public class FileTypeUtils { return TIKA.get().detect(data, name); } + /** + * 根据 mineType 获得文件后缀 + * + * 注意:如果获取不到,或者发生异常,都返回 null + * + * @param mineType 类型 + * @return 后缀,例如说 .pdf + */ + public static String getExtension(String mineType) { + try { + return MimeTypes.getDefaultMimeTypes().forName(mineType).getExtension(); + } catch (MimeTypeException e) { + log.warn("[getExtension][获取文件后缀({}) 失败]", mineType, e); + return null; + } + } + /** * 返回附件 * diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/inner/CodegenEngine.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/inner/CodegenEngine.java index 30b6081b0..cb645f42b 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/inner/CodegenEngine.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/inner/CodegenEngine.java @@ -163,6 +163,25 @@ public class CodegenEngine { vue3FilePath("views/${table.moduleName}/${table.businessName}/modules/${subSimpleClassName_strikeCase}-list.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN5_ANTD_SCHEMA.getType(), vue3Vben5AntdSchemaTemplatePath("views/modules/list_sub_erp.vue"), // 特殊:主子表专属逻辑 vue3FilePath("views/${table.moduleName}/${table.businessName}/modules/${subSimpleClassName_strikeCase}-list.vue")) + // VUE3_VBEN5_ANTD + .put(CodegenFrontTypeEnum.VUE3_VBEN5_ANTD_GENERAL.getType(), vue3Vben5AntdGeneralTemplatePath("views/data.ts"), + vue3FilePath("views/${table.moduleName}/${table.businessName}/data.ts")) + .put(CodegenFrontTypeEnum.VUE3_VBEN5_ANTD_GENERAL.getType(), vue3Vben5AntdGeneralTemplatePath("views/index.vue"), + vue3FilePath("views/${table.moduleName}/${table.businessName}/index.vue")) + .put(CodegenFrontTypeEnum.VUE3_VBEN5_ANTD_GENERAL.getType(), vue3Vben5AntdGeneralTemplatePath("views/form.vue"), + vue3FilePath("views/${table.moduleName}/${table.businessName}/modules/form.vue")) + .put(CodegenFrontTypeEnum.VUE3_VBEN5_ANTD_GENERAL.getType(), vue3Vben5AntdGeneralTemplatePath("api/api.ts"), + vue3FilePath("api/${table.moduleName}/${table.businessName}/index.ts")) + .put(CodegenFrontTypeEnum.VUE3_VBEN5_ANTD_GENERAL.getType(), vue3Vben5AntdGeneralTemplatePath("views/modules/form_sub_normal.vue"), // 特殊:主子表专属逻辑 + vue3FilePath("views/${table.moduleName}/${table.businessName}/modules/${subSimpleClassName_strikeCase}-form.vue")) + .put(CodegenFrontTypeEnum.VUE3_VBEN5_ANTD_GENERAL.getType(), vue3Vben5AntdGeneralTemplatePath("views/modules/form_sub_inner.vue"), // 特殊:主子表专属逻辑 + vue3FilePath("views/${table.moduleName}/${table.businessName}/modules/${subSimpleClassName_strikeCase}-form.vue")) + .put(CodegenFrontTypeEnum.VUE3_VBEN5_ANTD_GENERAL.getType(), vue3Vben5AntdGeneralTemplatePath("views/modules/form_sub_erp.vue"), // 特殊:主子表专属逻辑 + vue3FilePath("views/${table.moduleName}/${table.businessName}/modules/${subSimpleClassName_strikeCase}-form.vue")) + .put(CodegenFrontTypeEnum.VUE3_VBEN5_ANTD_GENERAL.getType(), vue3Vben5AntdGeneralTemplatePath("views/modules/list_sub_inner.vue"), // 特殊:主子表专属逻辑 + vue3FilePath("views/${table.moduleName}/${table.businessName}/modules/${subSimpleClassName_strikeCase}-list.vue")) + .put(CodegenFrontTypeEnum.VUE3_VBEN5_ANTD_GENERAL.getType(), vue3Vben5AntdGeneralTemplatePath("views/modules/list_sub_erp.vue"), // 特殊:主子表专属逻辑 + vue3FilePath("views/${table.moduleName}/${table.businessName}/modules/${subSimpleClassName_strikeCase}-list.vue")) .build(); @Resource diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileService.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileService.java index 3ca9a2419..247fe5f62 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileService.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileService.java @@ -5,6 +5,7 @@ import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.FileCreateReq import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.FilePageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.FilePresignedUrlRespVO; import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileDO; +import jakarta.validation.constraints.NotEmpty; /** * 文件 Service 接口 @@ -24,12 +25,24 @@ public interface FileService { /** * 保存文件,并返回文件的访问路径 * - * @param name 文件名称 - * @param path 文件路径 * @param content 文件内容 + * @param name 文件名称,允许空 + * @param directory 目录,允许空 + * @param type 文件的 MIME 类型,允许空 * @return 文件路径 */ - String createFile(String name, String path, byte[] content); + String createFile(@NotEmpty(message = "文件内容不能为空") byte[] content, + String name, String directory, String type); + + /** + * 生成文件预签名地址信息 + * + * @param name 文件名 + * @param directory 目录 + * @return 预签名地址信息 + */ + FilePresignedUrlRespVO getFilePresignedUrl(@NotEmpty(message = "文件名不能为空") String name, + String directory); /** * 创建文件 @@ -55,12 +68,4 @@ public interface FileService { */ byte[] getFileContent(Long configId, String path) throws Exception; - /** - * 生成文件预签名地址信息 - * - * @param path 文件路径 - * @return 预签名地址信息 - */ - FilePresignedUrlRespVO getFilePresignedUrl(String path) throws Exception; - } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java index 4835dcd8f..4a0faadaa 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java @@ -1,9 +1,11 @@ package cn.iocoder.yudao.module.infra.service.file; +import cn.hutool.core.date.LocalDateTimeUtil; +import cn.hutool.core.io.FileUtil; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.StrUtil; +import cn.hutool.crypto.digest.DigestUtil; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.io.FileUtils; import cn.iocoder.yudao.framework.common.util.object.BeanUtils; import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.FileCreateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.FilePageReqVO; @@ -13,11 +15,12 @@ import cn.iocoder.yudao.module.infra.dal.mysql.file.FileMapper; import cn.iocoder.yudao.module.infra.framework.file.core.client.FileClient; import cn.iocoder.yudao.module.infra.framework.file.core.client.s3.FilePresignedUrlRespDTO; import cn.iocoder.yudao.module.infra.framework.file.core.utils.FileTypeUtils; +import com.google.common.annotations.VisibleForTesting; +import jakarta.annotation.Resource; import lombok.SneakyThrows; import org.springframework.stereotype.Service; -import javax.annotation.Resource; - +import static cn.hutool.core.date.DatePattern.PURE_DATE_PATTERN; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_NOT_EXISTS; @@ -29,6 +32,20 @@ import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_NOT_EX @Service public class FileServiceImpl implements FileService { + /** + * 上传文件的前缀,是否包含日期(yyyyMMdd) + * + * 目的:按照日期,进行分目录 + */ + static boolean PATH_PREFIX_DATE_ENABLE = true; + /** + * 上传文件的后缀,是否包含时间戳 + * + * 目的:保证文件的唯一性,避免覆盖 + * 定制:可按需调整成 UUID、或者其他方式 + */ + static boolean PATH_SUFFIX_TIMESTAMP_ENABLE = true; + @Resource private FileConfigService fileConfigService; @@ -42,34 +59,82 @@ public class FileServiceImpl implements FileService { @Override @SneakyThrows - public String createFile(String name, String path, byte[] content) { - // 计算默认的 path 名 - String type = FileTypeUtils.getMineType(content, name); - if (StrUtil.isEmpty(path)) { - path = FileUtils.generatePath(content, name); + public String createFile(byte[] content, String name, String directory, String type) { + // 1.1 处理 type 为空的情况 + if (StrUtil.isEmpty(type)) { + type = FileTypeUtils.getMineType(content, name); } - // 如果 name 为空,则使用 path 填充 + // 1.2 处理 name 为空的情况 if (StrUtil.isEmpty(name)) { - name = path; + name = DigestUtil.sha256Hex(content); + } + if (StrUtil.isEmpty(FileUtil.extName(name))) { + // 如果 name 没有后缀 type,则补充后缀 + String extension = FileTypeUtils.getExtension(type); + if (StrUtil.isNotEmpty(extension)) { + name = name + extension; + } } - // 上传到文件存储器 + // 2.1 生成上传的 path,需要保证唯一 + String path = generateUploadPath(name, directory); + // 2.2 上传到文件存储器 FileClient client = fileConfigService.getMasterFileClient(); Assert.notNull(client, "客户端(master) 不能为空"); String url = client.upload(content, path, type); - // 保存到数据库 - FileDO file = new FileDO(); - file.setConfigId(client.getId()); - file.setName(name); - file.setPath(path); - file.setUrl(url); - file.setType(type); - file.setSize(content.length); - fileMapper.insert(file); + // 3. 保存到数据库 + fileMapper.insert(new FileDO().setConfigId(client.getId()) + .setName(name).setPath(path).setUrl(url) + .setType(type).setSize(content.length)); return url; } + @VisibleForTesting + String generateUploadPath(String name, String directory) { + // 1. 生成前缀、后缀 + String prefix = null; + if (PATH_PREFIX_DATE_ENABLE) { + prefix = LocalDateTimeUtil.format(LocalDateTimeUtil.now(), PURE_DATE_PATTERN); + } + String suffix = null; + if (PATH_SUFFIX_TIMESTAMP_ENABLE) { + suffix = String.valueOf(System.currentTimeMillis()); + } + + // 2.1 先拼接 suffix 后缀 + if (StrUtil.isNotEmpty(suffix)) { + String ext = FileUtil.extName(name); + if (StrUtil.isNotEmpty(ext)) { + name = FileUtil.mainName(name) + StrUtil.C_UNDERLINE + suffix + StrUtil.DOT + ext; + } else { + name = name + StrUtil.C_UNDERLINE + suffix; + } + } + // 2.2 再拼接 prefix 前缀 + if (StrUtil.isNotEmpty(prefix)) { + name = prefix + StrUtil.SLASH + name; + } + // 2.3 最后拼接 directory 目录 + if (StrUtil.isNotEmpty(directory)) { + name = directory + StrUtil.SLASH + name; + } + return name; + } + + @Override + @SneakyThrows + public FilePresignedUrlRespVO getFilePresignedUrl(String name, String directory) { + // 1. 生成上传的 path,需要保证唯一 + String path = generateUploadPath(name, directory); + + // 2. 获取文件预签名地址 + FileClient fileClient = fileConfigService.getMasterFileClient(); + FilePresignedUrlRespDTO presignedObjectUrl = fileClient.getPresignedObjectUrl(path); + return BeanUtils.toBean(presignedObjectUrl, FilePresignedUrlRespVO.class, + object -> object.setConfigId(fileClient.getId()).setPath(path)); + } + @Override public Long createFile(FileCreateReqVO createReqVO) { FileDO file = BeanUtils.toBean(createReqVO, FileDO.class); @@ -106,12 +171,4 @@ public class FileServiceImpl implements FileService { return client.getContent(path); } - @Override - public FilePresignedUrlRespVO getFilePresignedUrl(String path) throws Exception { - FileClient fileClient = fileConfigService.getMasterFileClient(); - FilePresignedUrlRespDTO presignedObjectUrl = fileClient.getPresignedObjectUrl(path); - return BeanUtils.toBean(presignedObjectUrl, FilePresignedUrlRespVO.class, - object -> object.setConfigId(fileClient.getId())); - } - } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/vue3_vben5_antd/general/index.vue.vm b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/vue3_vben5_antd/general/index.vue.vm deleted file mode 100644 index e69de29bb..000000000 diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/vue3_vben5_antd/general/views/data.ts.vm b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/vue3_vben5_antd/general/views/data.ts.vm new file mode 100644 index 000000000..9f356f684 --- /dev/null +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/vue3_vben5_antd/general/views/data.ts.vm @@ -0,0 +1,349 @@ +import type { VxeTableGridOptions } from '@vben/plugins/vxe-table'; +import type { VbenFormSchema } from '#/adapter/form'; +import type { OnActionClickFn } from '#/adapter/vxe-table'; +import type { ${simpleClassName}Api } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}'; + +import { z } from '#/adapter/form'; +#if(${table.templateType} == 2)## 树表需要导入这些 +import { get${simpleClassName}List } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}'; +import { handleTree } from '#/utils/tree'; +#end +import { DICT_TYPE, getDictOptions } from '#/utils/dict'; +import { getRangePickerDefaultProps } from '#/utils/date'; +import { useAccess } from '@vben/access'; + +const { hasAccessByCodes } = useAccess(); + +/** 列表的搜索表单 */ +export function useGridFormSchema(): VbenFormSchema[] { + return [ +#foreach($column in $columns) +#if ($column.listOperation) + #set ($dictType = $column.dictType) + #set ($javaType = $column.javaType) + #set ($javaField = $column.javaField) + #set ($comment = $column.columnComment) + #if ($javaType == "Integer" || $javaType == "Long" || $javaType == "Byte" || $javaType == "Short") + #set ($dictMethod = "number") + #elseif ($javaType == "String") + #set ($dictMethod = "string") + #elseif ($javaType == "Boolean") + #set ($dictMethod = "boolean") + #end + { + fieldName: '${javaField}', + label: '${comment}', + #if ($column.htmlType == "input" || $column.htmlType == "textarea" || $column.htmlType == "editor") + component: 'Input', + componentProps: { + allowClear: true, + placeholder: '请输入${comment}', + }, + #elseif ($column.htmlType == "select" || $column.htmlType == "radio") + component: 'Select', + componentProps: { + allowClear: true, + #if ("" != $dictType)## 设置了 dictType 数据字典的情况 + options: getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod'), + #else## 未设置 dictType 数据字典的情况 + options: [], + #end + placeholder: '请选择${comment}', + }, + #elseif($column.htmlType == "datetime") + component: 'RangePicker', + componentProps: { + ...getRangePickerDefaultProps(), + allowClear: true, + }, + #end + }, +#end +#end + ]; +} + +/** 列表的字段 */ +export function useGridColumns( + onActionClick?: OnActionClickFn<${simpleClassName}Api.${simpleClassName}>, +): VxeTableGridOptions<${simpleClassName}Api.${simpleClassName}>['columns'] { + return [ +#if ($table.templateType == 12) ## 内嵌情况 + { type: 'expand', width: 80, slots: { content: 'expand_content' } }, +#end +#foreach($column in $columns) +#if ($column.listOperationResult) + #set ($dictType = $column.dictType) + #set ($javaField = $column.javaField) + #set ($comment = $column.columnComment) + { + field: '${javaField}', + title: '${comment}', + minWidth: 120, + #if ($column.javaType == "LocalDateTime")## 时间类型 + formatter: 'formatDateTime', + #elseif("" != $dictType)## 数据字典 + cellRender: { + name: 'CellDict', + props: { type: DICT_TYPE.$dictType.toUpperCase() }, + }, + #end + #if (${table.templateType} == 2 && $column.id == $treeNameColumn.id)## 树表特有:标记树节点列 + treeNode: true, + #end + }, +#end +#end + { + field: 'operation', + title: '操作', + minWidth: 200, + align: 'center', + fixed: 'right', + headerAlign: 'center', + showOverflow: false, + cellRender: { + attrs: { + nameField: '${columns[0].javaField}', + nameTitle: '${table.classComment}', + onClick: onActionClick, + }, + name: 'CellOperation', + options: [ +#if (${table.templateType} == 2)## 树表特有操作 + { + code: 'append', + text: '新增下级', + show: hasAccessByCodes(['${table.moduleName}:${simpleClassName_strikeCase}:create']), + }, +#end + { + code: 'edit', + show: hasAccessByCodes(['${table.moduleName}:${simpleClassName_strikeCase}:update']), + }, + { + code: 'delete', + show: hasAccessByCodes(['${table.moduleName}:${simpleClassName_strikeCase}:delete']), +#if (${table.templateType} == 2)## 树表禁止删除带有子节点的数据 + disabled: (row: ${simpleClassName}Api.${simpleClassName}) => { + return !!(row.children && row.children.length > 0); + }, +#end + }, + ], + }, + }, + ]; +} + +## 标准模式和内嵌模式时,主子关系一对一则生成表单schema,一对多则生成列表schema(内嵌模式时表单schema也要生成)。erp 模式时都生成 +## 特殊:主子表专属逻辑 +#foreach ($subTable in $subTables) + #set ($index = $foreach.count - 1) + #set ($subColumns = $subColumnsList.get($index))##当前字段数组 + #set ($subSimpleClassName = $subSimpleClassNames.get($index)) + #set ($subJoinColumn = $subJoinColumns.get($index))##当前 join 字段 + #set ($subSimpleClassName_strikeCase = $subSimpleClassName_strikeCases.get($index)) +// ==================== 子表($subTable.classComment) ==================== + +#if ($table.templateType == 11) ## erp 情况 +/** 列表的搜索表单 */ +export function use${subSimpleClassName}GridFormSchema(): VbenFormSchema[] { + return [ + #foreach($column in $subColumns) + #if ($column.listOperation) + #set ($dictType = $column.dictType) + #set ($javaType = $column.javaType) + #set ($javaField = $column.javaField) + #set ($comment = $column.columnComment) + #if ($javaType == "Integer" || $javaType == "Long" || $javaType == "Byte" || $javaType == "Short") + #set ($dictMethod = "number") + #elseif ($javaType == "String") + #set ($dictMethod = "string") + #elseif ($javaType == "Boolean") + #set ($dictMethod = "boolean") + #end + { + fieldName: '${javaField}', + label: '${comment}', + #if ($column.htmlType == "input" || $column.htmlType == "textarea" || $column.htmlType == "editor") + component: 'Input', + componentProps: { + allowClear: true, + placeholder: '请输入${comment}', + }, + #elseif ($column.htmlType == "select" || $column.htmlType == "radio") + component: 'Select', + componentProps: { + allowClear: true, + #if ("" != $dictType)## 设置了 dictType 数据字典的情况 + options: getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod'), + #else## 未设置 dictType 数据字典的情况 + options: [], + #end + placeholder: '请选择${comment}', + }, + #elseif($column.htmlType == "datetime") + component: 'RangePicker', + componentProps: { + ...getRangePickerDefaultProps(), + allowClear: true, + }, + #end + }, + #end + #end + ]; +} + +/** 列表的字段 */ +export function use${subSimpleClassName}GridColumns( + onActionClick?: OnActionClickFn<${simpleClassName}Api.${subSimpleClassName}>, +): VxeTableGridOptions<${simpleClassName}Api.${subSimpleClassName}>['columns'] { + return [ + #foreach($column in $subColumns) + #if ($column.listOperationResult) + #set ($dictType = $column.dictType) + #set ($javaField = $column.javaField) + #set ($comment = $column.columnComment) + { + field: '${javaField}', + title: '${comment}', + minWidth: 120, + #if ($column.javaType == "LocalDateTime")## 时间类型 + formatter: 'formatDateTime', + #elseif("" != $dictType)## 数据字典 + cellRender: { + name: 'CellDict', + props: { type: DICT_TYPE.$dictType.toUpperCase() }, + }, + #end + }, + #end + #end + { + field: 'operation', + title: '操作', + minWidth: 200, + align: 'center', + fixed: 'right', + headerAlign: 'center', + showOverflow: false, + cellRender: { + attrs: { + nameField: '${columns[0].javaField}', + nameTitle: '${subTable.classComment}', + onClick: onActionClick, + }, + name: 'CellOperation', + options: [ + { + code: 'edit', + show: hasAccessByCodes(['${table.moduleName}:${simpleClassName_strikeCase}:update']), + }, + { + code: 'delete', + show: hasAccessByCodes(['${table.moduleName}:${simpleClassName_strikeCase}:delete']), + }, + ], + }, + }, + ]; +} + +#else + #if ($subTable.subJoinMany) ## 一对多 + /** 新增/修改列表的字段 */ + export function use${subSimpleClassName}GridEditColumns( + onActionClick?: OnActionClickFn<${simpleClassName}Api.${subSimpleClassName}>, + ): VxeTableGridOptions<${simpleClassName}Api.${subSimpleClassName}>['columns'] { + return [ + #foreach($column in $subColumns) + #if ($column.createOperation || $column.updateOperation) + #if (!$column.primaryKey && $column.listOperationResult && $column.id != $subJoinColumn.id) ## 特殊:忽略主子表的 join 字段,不用填写 + #set ($dictType = $column.dictType) + #set ($javaField = $column.javaField) + #set ($comment = $column.columnComment) + #if ($javaType == "Integer" || $javaType == "Long" || $javaType == "Byte" || $javaType == "Short") + #set ($dictMethod = "number") + #elseif ($javaType == "String") + #set ($dictMethod = "string") + #elseif ($javaType == "Boolean") + #set ($dictMethod = "boolean") + #end + { + field: '${javaField}', + title: '${comment}', + minWidth: 120, + slots: { default: '${javaField}' }, + #if ($column.htmlType == "select" || $column.htmlType == "checkbox" || $column.htmlType == "radio") + #if ("" != $dictType)## 有数据字典 + params: { + options: getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod'), + }, + #else + params: { + options: [], + }, + #end + #end + }, + #end + #end + #end + { + field: 'operation', + title: '操作', + minWidth: 60, + align: 'center', + fixed: 'right', + headerAlign: 'center', + showOverflow: false, + cellRender: { + attrs: { + nameField: '${columns[0].javaField}', + nameTitle: '${table.classComment}', + onClick: onActionClick, + }, + name: 'CellOperation', + options: [ + { + code: 'delete', + show: hasAccessByCodes(['${table.moduleName}:${simpleClassName_strikeCase}:delete']), + }, + ], + }, + }, + ]; + } + #end + #if ($table.templateType == 12) ## 内嵌情况 + /** 列表的字段 */ + export function use${subSimpleClassName}GridColumns(): VxeTableGridOptions<${simpleClassName}Api.${subSimpleClassName}>['columns'] { + return [ + #foreach($column in $subColumns) + #if ($column.listOperationResult) + #set ($dictType = $column.dictType) + #set ($javaField = $column.javaField) + #set ($comment = $column.columnComment) + { + field: '${javaField}', + title: '${comment}', + minWidth: 120, + #if ($column.javaType == "LocalDateTime")## 时间类型 + formatter: 'formatDateTime', + #elseif("" != $dictType)## 数据字典 + cellRender: { + name: 'CellDict', + props: { type: DICT_TYPE.$dictType.toUpperCase() }, + }, + #end + }, + #end + #end + ]; + } + + #end +#end +#end \ No newline at end of file diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/vue3_vben5_antd/general/views/form.vue.vm b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/vue3_vben5_antd/general/views/form.vue.vm new file mode 100644 index 000000000..281df2479 --- /dev/null +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/vue3_vben5_antd/general/views/form.vue.vm @@ -0,0 +1,313 @@ + + +