feat(file): refactor file management module

- add virtual path storage, granular permissions, trash and share features

- secure upload, archive and transfer tasks; add folder size calculation

- split controllers and add async task SSE progress events

- add Flyway migrations and file module tests
This commit is contained in:
Timi
2026-11-24 15:36:17 +08:00
parent 7e7a9cf60c
commit 3b62f795de
69 changed files with 4380 additions and 1438 deletions
@@ -5,6 +5,8 @@ import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.bean.ModuleCode; import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.user.service.PermissionChecker; import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.TimiJava; import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull; import org.springframework.lang.NonNull;
@@ -12,6 +14,8 @@ import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.HandlerInterceptor;
import java.io.IOException;
/// ///
/// CORE 权限注解处理器 /// CORE 权限注解处理器
/// ///
@@ -32,14 +36,28 @@ public class RequireCorePermissionInterceptor implements HandlerInterceptor {
return true; return true;
} }
RequireCorePermission annotation = handlerMethod.getMethodAnnotation(RequireCorePermission.class); RequireCorePermission annotation = handlerMethod.getMethodAnnotation(RequireCorePermission.class);
if (annotation == null) {
annotation = handlerMethod.getBeanType().getAnnotation(RequireCorePermission.class);
}
if (annotation == null || TimiJava.isEmpty(annotation.value())) { if (annotation == null || TimiJava.isEmpty(annotation.value())) {
return true; return true;
} }
String[] permissionCodeList = java.util.Arrays.stream(annotation.value()).map(CorePermissionCode::getValue).toArray(String[]::new); String[] permissionCodeList = java.util.Arrays.stream(annotation.value()).map(CorePermissionCode::getValue).toArray(String[]::new);
if (annotation.mode() == PermissionMatchMode.ANY) { try {
permissionChecker.checkAny(ModuleCode.CORE, permissionCodeList); if (annotation.mode() == PermissionMatchMode.ANY) {
} else { permissionChecker.checkAny(ModuleCode.CORE, permissionCodeList);
permissionChecker.checkAll(ModuleCode.CORE, permissionCodeList); } else {
permissionChecker.checkAll(ModuleCode.CORE, permissionCodeList);
}
} catch (TimiException e) {
if (handlerMethod.hasMethodAnnotation(IgnoreGlobalReturn.class) && !resp.isCommitted()) {
try {
resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
} catch (IOException ignored) {
}
return false;
}
throw e;
} }
return true; return true;
} }
@@ -69,6 +69,11 @@ public enum CorePermissionCode implements BuiltinPermissionCode {
NOTIFY_DELETE("NOTIFY:DELETE", "通知删除", false, true), NOTIFY_DELETE("NOTIFY:DELETE", "通知删除", false, true),
NOTIFY_CANCEL("NOTIFY:CANCEL", "通知取消", false, true), NOTIFY_CANCEL("NOTIFY:CANCEL", "通知取消", false, true),
FILE_READ("FILE:READ", "文件读取", false, true),
FILE_WRITE("FILE:WRITE", "文件写入", false, true),
FILE_DELETE("FILE:DELETE", "文件删除", false, true),
FILE_SHARE("FILE:SHARE", "文件分享", false, true),
USER_ROLE_CREATE("USER_ROLE:CREATE", "用户角色创建", true, true), USER_ROLE_CREATE("USER_ROLE:CREATE", "用户角色创建", true, true),
USER_ROLE_READ("USER_ROLE:READ", "用户角色读取", true, true), USER_ROLE_READ("USER_ROLE:READ", "用户角色读取", true, true),
USER_ROLE_DELETE("USER_ROLE:DELETE", "用户角色删除", true, true); USER_ROLE_DELETE("USER_ROLE:DELETE", "用户角色删除", true, true);
@@ -11,7 +11,6 @@ import com.imyeyu.api.annotation.RequireCorePermissionInterceptor;
import com.imyeyu.api.modules.app.annotation.RequireAppPermissionInterceptor; import com.imyeyu.api.modules.app.annotation.RequireAppPermissionInterceptor;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermissionInterceptor; import com.imyeyu.api.modules.gao.annotation.RequireGaoPermissionInterceptor;
import com.imyeyu.api.modules.journal.util.JournalAPIInterceptor; import com.imyeyu.api.modules.journal.util.JournalAPIInterceptor;
import com.imyeyu.api.modules.system.util.SystemAPIInterceptor;
import com.imyeyu.spring.annotation.RequestBodyValueArgumentResolver; import com.imyeyu.spring.annotation.RequestBodyValueArgumentResolver;
import com.imyeyu.utils.Time; import com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -38,7 +37,6 @@ import java.util.List;
public class WebConfig implements WebMvcConfigurer { public class WebConfig implements WebMvcConfigurer {
private final ObjectMapper jackson; private final ObjectMapper jackson;
private final SystemAPIInterceptor systemAPIInterceptor;
private final JournalAPIInterceptor journalAPIInterceptor; private final JournalAPIInterceptor journalAPIInterceptor;
private final RequestRateLimitInterceptor requestRateLimitInterceptor; private final RequestRateLimitInterceptor requestRateLimitInterceptor;
private final RequireGaoPermissionInterceptor requireGaoPermissionInterceptor; private final RequireGaoPermissionInterceptor requireGaoPermissionInterceptor;
@@ -52,7 +50,6 @@ public class WebConfig implements WebMvcConfigurer {
*/ */
@Override @Override
public void addInterceptors(InterceptorRegistry registry) { public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(systemAPIInterceptor).addPathPatterns(SystemAPIInterceptor.PATH);
registry.addInterceptor(journalAPIInterceptor).addPathPatterns(JournalAPIInterceptor.PATH); registry.addInterceptor(journalAPIInterceptor).addPathPatterns(JournalAPIInterceptor.PATH);
registry.addInterceptor(requireCorePermissionInterceptor).addPathPatterns("/**"); registry.addInterceptor(requireCorePermissionInterceptor).addPathPatterns("/**");
registry.addInterceptor(requireGaoPermissionInterceptor).addPathPatterns("/**"); registry.addInterceptor(requireGaoPermissionInterceptor).addPathPatterns("/**");
@@ -107,7 +107,33 @@ public enum AuditOperation {
GAO_USER_DELETE(Logger.Module.GAO), GAO_USER_DELETE(Logger.Module.GAO),
GAO_STORE_DIARY_DELETE(Logger.Module.GAO), GAO_STORE_DIARY_DELETE(Logger.Module.GAO),
GAO_SALES_ORDER_PAYMENT_REJECT(Logger.Module.GAO), GAO_SALES_ORDER_PAYMENT_REJECT(Logger.Module.GAO),
GAO_SALES_ORDER_PAYMENT_CANCEL(Logger.Module.GAO); GAO_SALES_ORDER_PAYMENT_CANCEL(Logger.Module.GAO),
/// 创建目录
FILE_MKDIR(Logger.Module.SYSTEM),
/// 重命名文件或目录
FILE_RENAME(Logger.Module.SYSTEM),
/// 上传文件(普通上传或分片上传完成)
FILE_UPLOAD(Logger.Module.SYSTEM),
/// 移入回收站
FILE_DELETE(Logger.Module.SYSTEM),
/// 从回收站恢复
FILE_RESTORE(Logger.Module.SYSTEM),
/// 彻底删除回收站文件
FILE_PURGE(Logger.Module.SYSTEM),
/// 创建分享链接
FILE_SHARE_CREATE(Logger.Module.SYSTEM),
/// 撤销分享链接
FILE_SHARE_REVOKE(Logger.Module.SYSTEM),
/// 压缩、解压、复制、移动等归档操作
FILE_ARCHIVE(Logger.Module.SYSTEM);
final Logger.Module module; final Logger.Module module;
} }
@@ -1,19 +0,0 @@
package com.imyeyu.api.modules.system.bean;
import lombok.Data;
/**
* 访问令牌
*
* @author 夜雨
* @since 2026-04-28 14:35
*/
@Data
public class AccessKey {
/** 值 */
private String value;
/** true 为高权限密钥 */
private Boolean highAuthority;
}
@@ -0,0 +1,96 @@
package com.imyeyu.api.modules.system.bean;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Locale;
/**
* 文件内容分类
*
* @author 夜雨
* @version 2026-11-24
*/
public enum FileCategory {
/// 目录
DIRECTORY,
/// 图片
IMAGE,
/// 视频
VIDEO,
/// 音频
AUDIO,
/// 纯文本
TEXT,
/// 代码/标记语言/配置
CODE,
/// 压缩包
ARCHIVE,
/// 文档,例如 PDF、Office 文件
DOCUMENT,
/// 未识别的其他类型
OTHER;
@JsonValue
public String getValue() {
return name().toLowerCase(Locale.ROOT);
}
@JsonCreator
public static FileCategory of(String value) {
if (value != null) {
for (FileCategory category : values()) {
if (category.name().equalsIgnoreCase(value)) {
return category;
}
}
}
return OTHER;
}
public static FileCategory of(String mimeType, String extension, boolean directory) {
if (directory) {
return DIRECTORY;
}
String mime = mimeType == null ? "" : mimeType;
if (mime.startsWith("image/")) {
return IMAGE;
}
if (mime.startsWith("video/")) {
return VIDEO;
}
if (mime.startsWith("audio/")) {
return AUDIO;
}
if (mime.startsWith("text/")) {
return TEXT;
}
if (mime.contains("json") || mime.contains("xml") || mime.contains("javascript")) {
return CODE;
}
if (mime.startsWith("application/zip") || mime.startsWith("application/x-tar") || mime.startsWith("application/gzip")
|| mime.startsWith("application/x-7z") || mime.startsWith("application/vnd.rar")) {
return ARCHIVE;
}
if (mime.startsWith("application/pdf") || mime.contains("word") || mime.contains("excel")
|| mime.contains("powerpoint") || mime.contains("officedocument")) {
return DOCUMENT;
}
String ext = extension == null ? "" : extension.toLowerCase(Locale.ROOT);
return switch (ext) {
case "zip", "tar", "gz", "tgz", "7z", "rar" -> ARCHIVE;
case "java", "js", "ts", "tsx", "jsx", "vue", "py", "go", "rs", "c", "cpp", "h", "cs", "sql", "sh", "bat", "ps1", "json", "xml", "yml", "yaml" -> CODE;
case "md", "txt", "log", "csv" -> TEXT;
default -> OTHER;
};
}
}
@@ -1,50 +0,0 @@
package com.imyeyu.api.modules.system.bean;
import lombok.Data;
import java.util.List;
import java.util.Map;
/**
* 文件同步配置
*
* @author 夜雨
* @since 2024-12-09 14:14
*/
@Data
public class FileSyncConfig {
/** true 为启用同步功能 */
private boolean enable;
/** 轮询同步任务 cron 周期表达式,如果配置已启用但任务无效时自动创建 */
private String cron;
/** 同步任务列表 */
private Map<String, Task> tasks;
/**
* 同步任务
*
* @author 夜雨
* @since 2024-12-09 14:14
*/
@Data
public static class Task {
/** true 为启用此同步任务 */
private boolean enable;
/** true 为使用 MD5 校验,将会大幅增加扫描耗时 */
private boolean useMD5Compare;
/** 任务 cron 周期表达式 */
private String cron;
/** 同步来源文件路径 */
private String source;
/** 同步去向文件路径,不可位于 {@link #source} 内 */
private List<String> targets;
}
}
@@ -0,0 +1,48 @@
package com.imyeyu.api.modules.system.bean;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Locale;
/**
* 文件系统条目类型
*
* @author 夜雨
* @version 2026-11-24
*/
public enum FileType {
/// 普通文件
FILE,
/// 目录
DIRECTORY,
/// 其他类型,例如符号链接、设备文件等
OTHER;
@JsonValue
public String getValue() {
return name().toLowerCase(Locale.ROOT);
}
@JsonCreator
public static FileType of(String value) {
if (value != null) {
for (FileType type : values()) {
if (type.name().equalsIgnoreCase(value)) {
return type;
}
}
}
return OTHER;
}
public static FileType of(boolean file, boolean directory) {
if (file) {
return FILE;
}
return directory ? DIRECTORY : OTHER;
}
}
@@ -1,14 +1,16 @@
package com.imyeyu.api.modules.system.bean; package com.imyeyu.api.modules.system.bean;
import com.imyeyu.api.TimiServerAPI;
import com.imyeyu.api.modules.common.service.SettingService;
import lombok.Data; import lombok.Data;
import lombok.extern.slf4j.Slf4j; import lombok.NoArgsConstructor;
import org.apache.tika.Tika; import org.apache.tika.Tika;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.Serializable; import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.Locale;
/** /**
* 文件属性 * 文件属性
@@ -17,16 +19,16 @@ import java.io.Serializable;
* @version 2022-01-01 23:04 * @version 2022-01-01 23:04
*/ */
@Data @Data
@Slf4j @NoArgsConstructor
public class ServerFile implements Serializable { public class ServerFile implements Serializable {
// ---------- 基本属性 ---------- private static final Tika TIKA = new Tika();
/** 文件名 */ /** 文件名 */
private String name; private String name;
/** 绝对路径(非文件系统绝对路径,仅基于配置路径) */ /** 基于 BASE_PATH 的虚拟路径 */
private String absolutePath; private String path;
/** MimeType */ /** MimeType */
private String mimeType; private String mimeType;
@@ -37,14 +39,30 @@ public class ServerFile implements Serializable {
/** 修改时间 */ /** 修改时间 */
private Long modifiedAt; private Long modifiedAt;
/** 创建时间 */
private Long createdAt;
/** 扩展名(小写,不含点) */
private String extension;
/** 分类 */
private FileCategory category;
/** 文件类型 */
private FileType type;
/** true 为可执行 */
private boolean executable;
/** 文件 ETag(大小-修改时间) */
private String etag;
/** true 为文件 */ /** true 为文件 */
private Boolean file; private Boolean file;
/** true 为文件夹 */ /** true 为文件夹 */
private Boolean directory; private Boolean directory;
// ---------- 权限 ----------
/** true 为可读 */ /** true 为可读 */
private boolean canRead; private boolean canRead;
@@ -57,48 +75,53 @@ public class ServerFile implements Serializable {
/** true 为可预览 */ /** true 为可预览 */
private boolean canPreview; private boolean canPreview;
public ServerFile(File file) { public ServerFile(Path base, Path path) {
name = file.getName(); Path absolute = path.toAbsolutePath().normalize();
absolutePath = file.getAbsolutePath().replaceAll("\\\\", "/"); this.name = path.getFileName() == null ? "/" : path.getFileName().toString();
SettingService settingService = TimiServerAPI.applicationContext.getBean(SettingService.class); String relative = base.toAbsolutePath().normalize().relativize(absolute).toString().replace('\\', '/');
absolutePath = absolutePath.substring(new File(settingService.getSystem(SystemFileSetting.BASE_PATH).asString()).getAbsolutePath().length()); this.path = relative.isEmpty() ? "/" : "/" + relative;
this.file = Files.isRegularFile(absolute, LinkOption.NOFOLLOW_LINKS);
modifiedAt = file.lastModified(); this.directory = Files.isDirectory(absolute, LinkOption.NOFOLLOW_LINKS);
this.file = file.isFile(); this.type = FileType.of(Boolean.TRUE.equals(this.file), Boolean.TRUE.equals(this.directory));
directory = file.isDirectory(); this.canRead = Files.isReadable(absolute);
this.canWrite = Files.isWritable(absolute);
canRead = file.canRead(); this.executable = Files.isExecutable(absolute);
canWrite = file.canWrite(); this.extension = extensionOf(this.name);
isHidden = file.isHidden(); this.category = FileCategory.of(null, this.extension, Boolean.TRUE.equals(this.directory));
try {
// 大小 this.isHidden = Files.isHidden(absolute);
if (this.file) { } catch (IOException e) {
size = file.length(); this.isHidden = false;
}
if (Boolean.TRUE.equals(this.file)) {
try { try {
mimeType = new Tika().detect(file); this.size = Files.size(absolute);
canPreview = switch (mimeType = new Tika().detect(file)) {
case "image/png", "image/jpeg", "video/mp4", "video/quicktime" -> true;
default -> false;
};
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); this.size = 0L;
} }
this.modifiedAt = absolute.toFile().lastModified();
this.mimeType = TIKA.detect(this.name);
this.category = FileCategory.of(this.mimeType, this.extension, false);
this.etag = String.format("\"%x-%x\"", this.size, this.modifiedAt);
this.canPreview = switch (this.mimeType) {
case "image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp",
"video/mp4", "video/quicktime", "video/webm",
"application/pdf", "text/plain" -> true;
default -> false;
};
} else {
this.size = 0L;
this.modifiedAt = absolute.toFile().lastModified();
}
try {
this.createdAt = ((FileTime) Files.getAttribute(absolute, "creationTime", LinkOption.NOFOLLOW_LINKS)).toMillis();
} catch (IOException | RuntimeException e) {
this.createdAt = this.modifiedAt;
} }
} }
/** @return true 为可读 */ private static String extensionOf(String name) {
public boolean canRead() { int dot = name.lastIndexOf('.');
return canRead; return dot > 0 && dot < name.length() - 1 ? name.substring(dot + 1).toLowerCase(Locale.ROOT) : "";
}
/** @return true 为可写 */
public boolean canWrite() {
return canWrite;
}
/** @return true 为可预览 */
public boolean canPreview() {
return false;
} }
} }
@@ -5,7 +5,7 @@ import com.imyeyu.api.modules.common.entity.Setting;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
/// /// 文件模块配置
/// ///
/// @author 夜雨 /// @author 夜雨
/// @since 2026-09-08 17:08 /// @since 2026-09-08 17:08
@@ -13,9 +13,42 @@ import lombok.Getter;
@AllArgsConstructor @AllArgsConstructor
public enum SystemFileSetting implements SettingEnum { public enum SystemFileSetting implements SettingEnum {
BASE_PATH("data/file", Setting.ValueType.STRING); /// 文件存储根目录,相对路径基于进程工作目录,也支持绝对路径
BASE_PATH("data/file", Setting.ValueType.STRING),
/// 回收站目录,相对路径基于 BASE_PATH
TRASH_PATH(".trash", Setting.ValueType.STRING),
/// 回收站文件保留天数,超期后由定时任务清理
TRASH_RETENTION_DAYS("30", Setting.ValueType.INTEGER),
/// 缩略图缓存目录,相对路径基于 BASE_PATH
THUMBNAIL_PATH(".cache/thumbnails", Setting.ValueType.STRING),
/// 搜索接口最多返回的文件数量
SEARCH_MAX_RESULTS("200", Setting.ValueType.INTEGER),
/// 搜索接口最大遍历深度,避免深层目录耗时过长
SEARCH_MAX_DEPTH("32", Setting.ValueType.INTEGER),
/// 搜索接口超时时间,单位秒
SEARCH_TIMEOUT_SECONDS("5", Setting.ValueType.INTEGER),
/// 单个文件上传大小上限,单位字节,默认 4 GiB
UPLOAD_MAX_SIZE("4294967296", Setting.ValueType.BYTE_SIZE),
/// 分片上传的单片大小,单位字节,默认 8 MiB
UPLOAD_CHUNK_SIZE("8388608", Setting.ValueType.BYTE_SIZE),
/// 是否启用文件分享
SHARE_ENABLED("true", Setting.ValueType.BOOLEAN),
/// 分享链接默认有效期,单位天;创建时未指定过期时间则使用该值
SHARE_DEFAULT_EXPIRE_DAYS("7", Setting.ValueType.INTEGER);
/// 默认值
final String defaultValue; final String defaultValue;
/// 配置值类型
final Setting.ValueType valueType; final Setting.ValueType valueType;
} }
@@ -1,19 +0,0 @@
package com.imyeyu.api.modules.system.bean;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
/**
* 上传文件对象
*
* @author 夜雨
* @version 2022-01-13 00:51
*/
@Data
public class TransferFile {
private Long length;
private String name, path;
private MultipartFile file;
}
@@ -1,17 +1,22 @@
package com.imyeyu.api.modules.system.controller; package com.imyeyu.api.modules.system.controller;
import com.imyeyu.api.modules.system.service.AsyncTaskEventService;
import com.imyeyu.api.modules.system.service.AsyncTaskService; import com.imyeyu.api.modules.system.service.AsyncTaskService;
import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask;
import com.imyeyu.api.modules.system.task.async.DebugAsyncTask; import com.imyeyu.api.modules.system.task.async.DebugAsyncTask;
import com.imyeyu.api.modules.system.vo.AsyncTaskView; import com.imyeyu.api.modules.system.vo.AsyncTaskView;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.util.List; import java.util.List;
@@ -28,6 +33,8 @@ import java.util.List;
public class AsyncTaskController { public class AsyncTaskController {
private final AsyncTaskService service; private final AsyncTaskService service;
private final AsyncTaskEventService eventService;
private final UserLoginService userLoginService;
@AOPLog @AOPLog
@PostMapping("/debug") @PostMapping("/debug")
@@ -45,6 +52,21 @@ public class AsyncTaskController {
return service.getAsyncTask(uuid); return service.getAsyncTask(uuid);
} }
/**
* 订阅异步任务状态。
*
* <p>适用于压缩、解压、复制、移动、文件夹大小统计等长耗时文件任务。
* 任务结束后服务端会主动关闭连接;客户端断线后可以回退到 {@code /detail} 轮询。</p>
*
* @param uuid 任务 ID
* @return SSE 事件流
*/
@IgnoreGlobalReturn
@GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter events(@RequestParam("uuid") String uuid) {
return eventService.subscribe(uuid, userLoginService.getRequireLoginUserId());
}
@PostMapping("/list") @PostMapping("/list")
public List<AsyncTaskView> list() { public List<AsyncTaskView> list() {
return service.listAllView(); return service.listAllView();
@@ -0,0 +1,109 @@
package com.imyeyu.api.modules.system.controller;
import com.imyeyu.api.annotation.RequireCorePermission;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.audit.AuditOperation;
import com.imyeyu.api.modules.system.audit.OperationAudit;
import com.imyeyu.api.modules.system.service.AsyncTaskService;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.task.async.FileCopyAsyncTask;
import com.imyeyu.api.modules.system.task.async.FileMoveAsyncTask;
import com.imyeyu.api.modules.system.task.async.FileTarAsyncTask;
import com.imyeyu.api.modules.system.task.async.FileUnTarAsyncTask;
import com.imyeyu.api.modules.system.task.async.FileUnZipAsyncTask;
import com.imyeyu.api.modules.system.task.async.FileZipAsyncTask;
import com.imyeyu.api.modules.system.vo.ArchiveRequest;
import com.imyeyu.api.modules.system.vo.UnarchiveRequest;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 文件压缩、复制、移动接口
*
* @author 夜雨
* @version 2026-11-24
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/file")
public class FileArchiveController {
private final FileStorageService storage;
private final AsyncTaskService asyncTaskService;
private final UserLoginService userLoginService;
private final PermissionChecker permissionChecker;
@AOPLog
@OperationAudit(AuditOperation.FILE_ARCHIVE)
@RequestRateLimit
@RequireCorePermission({CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE})
@PostMapping("/zip")
public String zip(@Valid @RequestBody ArchiveRequest request) {
FileZipAsyncTask task = new FileZipAsyncTask(request.list(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId());
asyncTaskService.addAsyncTask(task);
return task.getId();
}
@AOPLog
@OperationAudit(AuditOperation.FILE_ARCHIVE)
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_WRITE)
@PostMapping("/unzip")
public String unzip(@Valid @RequestBody UnarchiveRequest request) {
FileUnZipAsyncTask task = new FileUnZipAsyncTask(request.file(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId());
asyncTaskService.addAsyncTask(task);
return task.getId();
}
@AOPLog
@OperationAudit(AuditOperation.FILE_ARCHIVE)
@RequestRateLimit
@RequireCorePermission({CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE})
@PostMapping("/tar")
public String tar(@Valid @RequestBody ArchiveRequest request) {
FileTarAsyncTask task = new FileTarAsyncTask(request.list(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId());
asyncTaskService.addAsyncTask(task);
return task.getId();
}
@AOPLog
@OperationAudit(AuditOperation.FILE_ARCHIVE)
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_WRITE)
@PostMapping("/untar")
public String untar(@Valid @RequestBody UnarchiveRequest request) {
FileUnTarAsyncTask task = new FileUnTarAsyncTask(request.file(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId());
asyncTaskService.addAsyncTask(task);
return task.getId();
}
@AOPLog
@OperationAudit(AuditOperation.FILE_ARCHIVE)
@RequestRateLimit
@RequireCorePermission({CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE, CorePermissionCode.FILE_DELETE})
@PostMapping("/cut")
public String cut(@Valid @RequestBody ArchiveRequest request) {
FileMoveAsyncTask task = new FileMoveAsyncTask(request.list(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId());
asyncTaskService.addAsyncTask(task);
return task.getId();
}
@AOPLog
@OperationAudit(AuditOperation.FILE_ARCHIVE)
@RequestRateLimit
@RequireCorePermission({CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE})
@PostMapping("/copy")
public String copy(@Valid @RequestBody ArchiveRequest request) {
FileCopyAsyncTask task = new FileCopyAsyncTask(request.list(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId());
asyncTaskService.addAsyncTask(task);
return task.getId();
}
}
@@ -0,0 +1,53 @@
package com.imyeyu.api.modules.system.controller;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 文件二进制响应异常映射
*
* @author 夜雨
* @version 2026-11-24
*/
final class FileBinaryResponder {
private FileBinaryResponder() {
}
static void serve(HttpServletResponse resp, BinaryAction action) {
try {
action.run();
} catch (TimiException e) {
if (resp.isCommitted()) {
return;
}
int status = switch (e.getCode()) {
case PERMISSION_ERROR -> HttpServletResponse.SC_FORBIDDEN;
case RESULT_NULL -> HttpServletResponse.SC_NOT_FOUND;
case ARG_BAD, ARG_MISS, RESULT_BAD -> HttpServletResponse.SC_BAD_REQUEST;
default -> HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
};
try {
resp.sendError(status, e.getMessage());
} catch (IOException ignored) {
}
} catch (Exception e) {
if (resp.isCommitted()) {
return;
}
try {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件处理失败");
} catch (IOException ignored) {
}
}
}
@FunctionalInterface
interface BinaryAction {
void run();
}
}
@@ -0,0 +1,53 @@
package com.imyeyu.api.modules.system.controller;
import com.imyeyu.api.annotation.RequireCorePermission;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.service.FileContentService;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.spring.annotation.RequestRateLimit;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* 文件内容接口
*
* @author 夜雨
* @version 2026-11-24
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/file")
public class FileContentController {
private final FileContentService contentService;
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_READ)
@IgnoreGlobalReturn
@GetMapping("/read/{*path}")
public void read(HttpServletRequest req, HttpServletResponse resp, @PathVariable("path") String path) {
FileBinaryResponder.serve(resp, () -> contentService.serve(req, resp, path, false));
}
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_READ)
@IgnoreGlobalReturn
@RequestMapping(value = "/download/{*path}", method = {RequestMethod.GET, RequestMethod.HEAD})
public void download(HttpServletRequest req, HttpServletResponse resp, @PathVariable("path") String path) {
FileBinaryResponder.serve(resp, () -> contentService.serve(req, resp, path, true));
}
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_READ)
@IgnoreGlobalReturn
@GetMapping("/preview/{*path}")
public void preview(HttpServletRequest req, HttpServletResponse resp, @PathVariable("path") String path) {
FileBinaryResponder.serve(resp, () -> contentService.preview(req, resp, path));
}
}
@@ -1,453 +1,114 @@
package com.imyeyu.api.modules.system.controller; package com.imyeyu.api.modules.system.controller;
import com.imyeyu.api.modules.common.service.SettingService; import com.imyeyu.api.annotation.RequireCorePermission;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.bean.ServerFile; import com.imyeyu.api.modules.system.bean.ServerFile;
import com.imyeyu.api.modules.system.bean.SystemFileSetting;
import com.imyeyu.api.modules.system.bean.TransferFile;
import com.imyeyu.api.modules.system.service.AsyncTaskService; import com.imyeyu.api.modules.system.service.AsyncTaskService;
import com.imyeyu.api.modules.system.service.FileService; import com.imyeyu.api.modules.system.service.FileService;
import com.imyeyu.api.modules.system.task.async.FileCopyAsyncTask; import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.task.async.FileMoveAsyncTask; import com.imyeyu.api.modules.system.task.async.FileCalcSizeAsyncTask;
import com.imyeyu.api.modules.system.task.async.FileTarAsyncTask; import com.imyeyu.api.modules.system.vo.MkdirRequest;
import com.imyeyu.api.modules.system.task.async.FileUnTarAsyncTask; import com.imyeyu.api.modules.system.vo.PathRequest;
import com.imyeyu.api.modules.system.task.async.FileUnZipAsyncTask; import com.imyeyu.api.modules.system.vo.RenameRequest;
import com.imyeyu.api.modules.system.task.async.FileZipAsyncTask; import com.imyeyu.api.modules.system.vo.SearchRequest;
import com.imyeyu.api.modules.system.util.ResourceHandler; import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.api.modules.system.vo.ListFileToRequest; import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.io.IO;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.network.Network;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.spring.annotation.RequestRateLimit; import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.bean.RequestRange; import jakarta.validation.Valid;
import com.imyeyu.utils.OS;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Cleanup;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.tika.Tika;
import org.jcodec.api.FrameGrab;
import org.jcodec.common.model.Picture;
import org.jcodec.scale.AWTUtil;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* 文件系统接口 * 文件元数据接口
* *
* @author 夜雨 * @author 夜雨
* @version 2022-01-01 20:00 * @version 2022-01-01 20:00
*/ */
@Slf4j
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/system/file") @RequestMapping("/system/file")
public class FileController implements TimiJava, OS.FileSystem { public class FileController {
private final FileService service; private final FileService fileService;
private final SettingService settingService; private final FileStorageService storage;
private final AsyncTaskService asyncTaskService; private final AsyncTaskService asyncTaskService;
private final UserLoginService userLoginService;
private final PermissionChecker permissionChecker;
private final ResourceHandler resourceHandler;
/**
* 文件对象
*
* @param req 请求
* @param resp 返回
* @return 元数据对象
*/
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@GetMapping("/object/**") @RequireCorePermission(CorePermissionCode.FILE_READ)
public ServerFile object(HttpServletRequest req, HttpServletResponse resp) { @GetMapping("/object/{*path}")
String path = req.getServletPath().substring("/system/file/object".length()); public ServerFile object(@PathVariable("path") String path) {
if (TimiJava.isEmpty(path)) { return fileService.object(path);
throw new TimiException(TimiCode.ARG_MISS, "TODO 缺少参数:object");
}
ServerFile file = new ServerFile(new File(path));
service.checkAccessPermission(file.getAbsolutePath());
return file;
} }
/**
* 深度搜索
*
* @param params path: 基本路径, keyword: 关键字
* @return 文件列表
*/
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_READ)
@GetMapping("/list")
public List<ServerFile> list(@RequestParam(defaultValue = "/") String path) {
return fileService.list(path);
}
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_READ)
@PostMapping("/search") @PostMapping("/search")
public List<ServerFile> search(@RequestBody Map<String, String> params) { public FileService.SearchResult search(@Valid @RequestBody SearchRequest request) {
if (TimiJava.isEmpty(params.get("path"))) { return fileService.search(request.path(), request.keyword());
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:path");
}
if (TimiJava.isEmpty(params.get("keyword"))) {
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:keyword");
}
return service.doFilter(service.search(params.get("path"), params.get("keyword")));
} }
/**
* 文件是否存在
*
* @param req 请求
* @param resp 返回
* @return true 为存在
*/
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@GetMapping("/exist/**") @RequireCorePermission(CorePermissionCode.FILE_READ)
public boolean exist(HttpServletRequest req, HttpServletResponse resp) { @GetMapping("/exist")
String path = req.getServletPath().substring("/system/file/exist".length()); public boolean exist(@RequestParam String path) {
if (TimiJava.isEmpty(path)) { return fileService.exists(path);
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:path");
}
return service.canAccess(path) && service.isExist(path);
} }
/**
* 通用资源加载接口
*
* @param req 请求
* @param resp 返回
*/
@AOPLog
@IgnoreGlobalReturn
@GetMapping("/read/**")
public void read(HttpServletRequest req, HttpServletResponse resp) {
try {
String path = req.getServletPath().substring("/system/file/read".length());
path = settingService.getSystem(SystemFileSetting.BASE_PATH).asString() + path;
if (TimiJava.isEmpty(path)) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
service.checkAccessPermission(path);
Path filePath = Paths.get(path);
if (!Files.exists(filePath)) {
log.warn("read a not exist file: {}", path);
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
resp.setContentLengthLong(Files.size(filePath));
String mimeType = new Tika().detect(filePath);
if (TimiJava.isNotEmpty(mimeType)) {
resp.setContentType(mimeType);
}
req.setAttribute(ResourceHandler.ATTR_TYPE, ResourceHandler.Type.FILE);
req.setAttribute(ResourceHandler.ATTR_VALUE, filePath);
resourceHandler.handleRequest(req, resp);
} catch (Exception e) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
/**
* 文件列表
*
* @return 列表
*/
@GetMapping("/list/**")
public List<ServerFile> list(HttpServletRequest req) {
return service.doFilter(service.list(req.getServletPath().substring("/system/file/list".length())));
}
/**
* 预览接口
*
* @param req 请求
* @param resp 返回
*/
@AOPLog
@IgnoreGlobalReturn
@GetMapping("/preview/**")
public void preview(HttpServletRequest req, HttpServletResponse resp) {
resp.setCharacterEncoding(StandardCharsets.UTF_8.toString());
try {
String path = req.getServletPath().substring("/system/file/preview".length());
if (TimiJava.isEmpty(path)) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
File file = new File(settingService.getSystem(SystemFileSetting.BASE_PATH).asString() + path);
if (!file.exists()) {
log.warn("preview a not exist file: {}", path);
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
service.checkAccessPermission(file.getAbsolutePath());
String mimeType = new Tika().detect(file);
switch (mimeType) {
case "image/png", "image/bmp", "image/jpeg" -> {
if (TimiJava.isNotEmpty(mimeType)) {
resp.setContentType(mimeType);
}
Thumbnails.of(file).size(256, 256).toOutputStream(resp.getOutputStream());
}
case "video/mp4", "video/quicktime" -> {
// 视频
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Picture picture = FrameGrab.getFrameAtSec(file, 2);
BufferedImage bi = AWTUtil.toBufferedImage(picture);
ImageIO.write(bi, "png", baos);
Thumbnails.of(IO.toInputStream(baos)).size(256, 256).toOutputStream(resp.getOutputStream());
}
default -> resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
} catch (Exception e) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
/**
* 创建文件夹
*
* @param params path: 路径, name: 名称
* @return true 为成功
*/
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_READ)
@GetMapping("/hash")
public FileService.FileHash hash(@RequestParam String path) {
return fileService.hash(path);
}
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_READ)
@PostMapping("/size")
public String size(@Valid @RequestBody PathRequest request) {
FileCalcSizeAsyncTask task = new FileCalcSizeAsyncTask(
request.path(), storage, permissionChecker, userLoginService.getRequireLoginUserId()
);
asyncTaskService.addAsyncTask(task);
return task.getId();
}
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_WRITE)
@PostMapping("/mkdir") @PostMapping("/mkdir")
public String mkdir(@RequestBody Map<String, String> params) { public ServerFile mkdir(@Valid @RequestBody MkdirRequest request) {
if (TimiJava.isEmpty(params.get("path"))) { return fileService.mkdir(request.path(), request.name());
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:path");
}
if (TimiJava.isEmpty(params.get("name"))) {
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:name");
}
return service.mkdir(params.get("path"), params.get("name")).getAbsolutePath();
} }
/**
* 重命名文件
*
* @param params from: 原文件, to: 目标文件
* @return true 为成功
*/
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_WRITE)
@PostMapping("/rename") @PostMapping("/rename")
public boolean rename(@RequestBody Map<String, String> params) { public ServerFile rename(@Valid @RequestBody RenameRequest request) {
if (TimiJava.isEmpty(params.get("from"))) { return fileService.rename(request.from(), request.to());
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:from");
}
if (TimiJava.isEmpty(params.get("to"))) {
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:to");
}
return service.rename(params.get("from"), params.get("to"));
}
/**
* 压缩 ZIP
*
* @param listFileToRequest 文件列表操作对象
* @return 异步任务 UUID
*/
@AOPLog
@RequestRateLimit
@PostMapping("/zip")
public String zip(@RequestBody ListFileToRequest listFileToRequest) {
if (TimiJava.isEmpty(listFileToRequest.getList())) {
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:list[]");
}
if (TimiJava.isEmpty(listFileToRequest.getTo())) {
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:to");
}
// 异步任务
FileZipAsyncTask task = new FileZipAsyncTask(listFileToRequest.getList(), listFileToRequest.getTo());
asyncTaskService.addAsyncTask(task);
return task.getId();
}
/**
* 解压缩 ZIP
*
* @param params zipFile: 压缩文件, to: 解压到
* @return 异步任务 UUID
*/
@AOPLog
@RequestRateLimit
@PostMapping("/unzip")
public String unzip(@RequestBody Map<String, String> params) {
String zipFilePath = params.get("zipFile");
if (TimiJava.isEmpty(zipFilePath)) {
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:zipFile");
}
File zipFile = new File(zipFilePath);
if (!zipFile.exists()) {
throw new TimiException(TimiCode.ARG_BAD, "文件不存在:" + zipFilePath);
}
if (TimiJava.isEmpty(params.get("to"))) {
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:to");
}
// 异步任务
FileUnZipAsyncTask task = new FileUnZipAsyncTask(zipFile, params.get("to"));
asyncTaskService.addAsyncTask(task);
return task.getId();
}
/**
* 压缩 TAR
*
* @param listFileToRequest 文件列表操作对象
* @return 异步任务 UUID
*/
@AOPLog
@RequestRateLimit
@PostMapping("/tar")
public String tar(@RequestBody ListFileToRequest listFileToRequest) {
FileTarAsyncTask task = new FileTarAsyncTask(listFileToRequest.getList(), listFileToRequest.getTo());
asyncTaskService.addAsyncTask(task);
return task.getId();
}
/**
* 解压缩 TAR
*
* @param params tarFile: 压缩文件, to: 解压到
* @return 异步任务 UUID
*/
@AOPLog
@RequestRateLimit
@PostMapping("/untar")
public String untar(@RequestBody Map<String, String> params) {
// TODO 具名入参
String tarFilePath = params.get("tarFile");
if (TimiJava.isEmpty(tarFilePath)) {
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:tarFile");
}
File tarFile = new File(tarFilePath);
if (!tarFile.exists()) {
throw new TimiException(TimiCode.ARG_BAD, "文件不存在:" + tarFilePath);
}
if (TimiJava.isEmpty(params.get("to"))) {
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:to");
}
FileUnTarAsyncTask task = new FileUnTarAsyncTask(tarFile, params.get("to"));
asyncTaskService.addAsyncTask(task);
return task.getId();
}
/**
* 剪切
*
* @param listFileToRequest 文件列表操作对象
* @return 异步任务 UUID
*/
@AOPLog
@RequestRateLimit
@PostMapping("/cut")
public String cut(@RequestBody ListFileToRequest listFileToRequest) {
FileMoveAsyncTask task = new FileMoveAsyncTask(listFileToRequest.getList(), listFileToRequest.getTo());
asyncTaskService.addAsyncTask(task);
return task.getId();
}
/**
* 复制
*
* @param listFileToRequest 文件列表操作对象
* @return 异步任务 UUID
*/
@AOPLog
@RequestRateLimit
@PostMapping("/copy")
public String copy(@RequestBody ListFileToRequest listFileToRequest) {
FileCopyAsyncTask task = new FileCopyAsyncTask(listFileToRequest.getList(), listFileToRequest.getTo());
asyncTaskService.addAsyncTask(task);
return task.getId();
}
/**
* 上传文件
*
* @param transferFile 文件传输对象
*/
@AOPLog
@RequestRateLimit
@PostMapping("/upload")
public void upload(TransferFile transferFile) {
service.upload(transferFile);
}
/**
* 下载文件
*
* @param resp 返回对象
*/
@AOPLog
@RequestRateLimit
@IgnoreGlobalReturn
@RequestMapping("/download/**")
public void download(HttpServletResponse resp) {
try {
String path = TimiSpring.cutURIStartAt("/system/file/download");
File file = new File(settingService.getSystem(SystemFileSetting.BASE_PATH).asString() + path);
service.checkAccessPermission(file.getAbsolutePath());
String mimeType = new Tika().detect(file);
resp.setContentType(mimeType);
resp.setHeader("Content-Disposition", Network.getFileDownloadHeader(file.getName()));
resp.setHeader("Accept-Ranges", "bytes");
RequestRange range = TimiSpring.getRequestRange(file.length());
if (range == null && resp.isCommitted()) {
return;
}
if (range == null) {
// 完整文件
resp.setContentLengthLong(file.length());
resp.setStatus(HttpServletResponse.SC_OK);
IO.toOutputStream(resp.getOutputStream(), file);
} else {
// 分片文件
resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
resp.setHeader("Content-Range", "bytes %s-%s/%s".formatted(range.getStart(), range.getEnd(), file.length()));
resp.setContentLengthLong(range.getLength());
@Cleanup
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(range.getStart());
IO.toOutputStream(resp.getOutputStream(), raf, range.getStart(), range.getLength());
}
} catch (Exception e) {
log.error("download error", e);
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
/**
* 销毁文件
*
* @param list 服务器文件绝对路径列表
*/
@AOPLog
@RequestRateLimit
@PostMapping("/destroy")
public void destroy(@RequestBody String[] list) {
service.destroy(list);
} }
} }
@@ -0,0 +1,91 @@
package com.imyeyu.api.modules.system.controller;
import com.imyeyu.api.annotation.RequireCorePermission;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.entity.FileShare;
import com.imyeyu.api.modules.system.entity.Logger;
import com.imyeyu.api.modules.system.service.FileContentService;
import com.imyeyu.api.modules.system.service.FileShareService;
import com.imyeyu.api.modules.system.service.LoggerService;
import com.imyeyu.api.modules.system.vo.ShareCreateRequest;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.spring.annotation.RequestRateLimit;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 文件分享接口
*
* @author 夜雨
* @version 2026-11-24
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/file")
public class FileShareController {
private final FileShareService shareService;
private final FileContentService contentService;
private final UserLoginService userLoginService;
private final LoggerService loggerService;
@RequestRateLimit
@RequireCorePermission({CorePermissionCode.FILE_READ, CorePermissionCode.FILE_SHARE})
@PostMapping("/share")
public FileShare share(@Valid @RequestBody ShareCreateRequest request) {
return shareService.create(request.path(), request.password(), request.expiresAt(), request.maxDownloads(), userLoginService.getRequireLoginUserId());
}
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_SHARE)
@GetMapping("/share")
public List<FileShare> shares() {
return shareService.list();
}
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_SHARE)
@DeleteMapping("/share/{id}")
public FileShare revokeShare(@PathVariable String id) {
return shareService.revoke(id);
}
/// 公开分享下载,只校验令牌与密码,不要求登录权限。
@RequestRateLimit
@IgnoreGlobalReturn
@RequestMapping(value = "/share/{token}/download", method = {RequestMethod.GET, RequestMethod.HEAD})
public void downloadShare(@PathVariable String token, @RequestParam(required = false) String password, HttpServletRequest req, HttpServletResponse resp) {
FileBinaryResponder.serve(resp, () -> {
boolean consume = !"HEAD".equalsIgnoreCase(req.getMethod());
FileShare share = shareService.open(token, password, consume);
contentService.serve(req, resp, share.getPath(), true);
loggerService.info(Logger.Module.SYSTEM, "FILE_SHARE_DOWNLOAD",
"shareId=" + share.getId() + ",path=" + share.getPath(),
"token=" + maskToken(token));
});
}
private String maskToken(String token) {
if (token == null || token.length() < 8) {
return "***";
}
return token.substring(0, 8) + "***";
}
}
@@ -0,0 +1,78 @@
package com.imyeyu.api.modules.system.controller;
import com.imyeyu.api.annotation.RequireCorePermission;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.bean.ServerFile;
import com.imyeyu.api.modules.system.entity.FileTrash;
import com.imyeyu.api.modules.system.service.FileTrashService;
import com.imyeyu.api.modules.system.vo.FileListRequest;
import com.imyeyu.api.modules.system.vo.IdRequest;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 文件回收站接口
*
* @author 夜雨
* @version 2026-11-24
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/file")
public class FileTrashController {
private final FileTrashService trashService;
private final UserLoginService userLoginService;
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_DELETE)
@PostMapping("/delete")
public List<FileTrash> delete(@Valid @RequestBody FileListRequest request) {
return trashService.trash(request.list(), userLoginService.getRequireLoginUserId());
}
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_READ)
@GetMapping("/trash")
public List<FileTrash> trash() {
return trashService.list();
}
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_WRITE)
@PostMapping("/trash/restore")
public ServerFile restore(@Valid @RequestBody IdRequest request) {
return trashService.restore(request.id());
}
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_DELETE)
@DeleteMapping("/trash/{id}")
public void purge(@PathVariable String id) {
trashService.purge(id);
}
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_DELETE)
@DeleteMapping("/trash")
public int emptyTrash() {
return trashService.empty();
}
}
@@ -0,0 +1,69 @@
package com.imyeyu.api.modules.system.controller;
import com.imyeyu.api.annotation.RequireCorePermission;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.bean.ServerFile;
import com.imyeyu.api.modules.system.service.FileUploadService;
import com.imyeyu.api.modules.system.vo.UploadCompleteRequest;
import com.imyeyu.api.modules.system.vo.UploadInitRequest;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* 文件上传接口
*
* @author 夜雨
* @version 2026-11-24
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/file")
public class FileUploadController {
private final FileUploadService uploadService;
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_WRITE)
@PostMapping("/upload")
public ServerFile upload(
@RequestParam String path,
@RequestParam String name,
@RequestParam(defaultValue = "false") boolean overwrite,
@RequestPart("file") MultipartFile file
) {
return uploadService.upload(path, name, file, overwrite);
}
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_WRITE)
@PostMapping("/upload/init")
public FileUploadService.UploadInit initUpload(@Valid @RequestBody UploadInitRequest request) {
return uploadService.init(request.path(), request.name(), request.size(), request.sha256());
}
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_WRITE)
@PostMapping("/upload/chunk")
public void uploadChunk(@RequestParam String uploadId, @RequestParam int index, @RequestPart("file") MultipartFile file) {
uploadService.chunk(uploadId, index, file);
}
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.FILE_WRITE)
@PostMapping("/upload/complete")
public ServerFile completeUpload(@Valid @RequestBody UploadCompleteRequest request) {
return uploadService.complete(request.uploadId(), request.sha256());
}
}
@@ -0,0 +1,63 @@
package com.imyeyu.api.modules.system.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.imyeyu.spring.annotation.Entity;
import com.imyeyu.spring.annotation.table.AutoUUID;
import com.imyeyu.spring.annotation.table.Id;
import lombok.Data;
import lombok.ToString;
/// 文件分享
@Data
@Entity
public class FileShare {
@Id
@AutoUUID
private String id;
/// 分享令牌
@ToString.Exclude
private String token;
/// 文件虚拟路径
private String path;
/// 文件名
private String name;
/// 创建人
private String ownerUserId;
/// 密码哈希(salt:hash)
@JsonIgnore
@ToString.Exclude
private String passwordHash;
/// 分享时的文件 SHA-256
private String fileHash;
/// 分享时的文件大小
private long fileSize;
/// 分享时的文件修改时间(epoch millis)
private long fileModifiedAt;
/// 过期时间(epoch millis)
private long expiresAt;
/// 最大下载次数,0 表示不限
private int maxDownloads;
/// 已下载次数
private int downloadCount;
/// 最后访问时间
private long lastAccessAt;
/// 创建时间
private long createdAt;
/// 删除时间(epoch millis),0 表示未删除
private long deletedAt;
}
@@ -0,0 +1,40 @@
package com.imyeyu.api.modules.system.entity;
import com.imyeyu.spring.annotation.Entity;
import com.imyeyu.spring.annotation.table.AutoUUID;
import com.imyeyu.spring.annotation.table.Id;
import lombok.Data;
/// 回收站记录。文件被删除时移动到 `BASE_PATH/.trash/{trashName}`,记录原路径用于恢复。
@Data
@Entity
public class FileTrash {
@Id
@AutoUUID
protected String id;
/// 删除前的虚拟路径
protected String originalPath;
/// 回收站中的目录名(UUID)
protected String trashName;
/// 文件或文件夹名称
protected String name;
/// 文件大小时为字节数,文件夹为 0
protected long size;
/// 是否为文件夹
protected boolean directory;
/// 删除人用户 ID
protected String ownerUserId;
/// 删除时间
protected long deletedAt;
/// 过期时间,超过后由定时任务彻底删除
protected long expiresAt;
}
@@ -0,0 +1,43 @@
package com.imyeyu.api.modules.system.mapper;
import com.imyeyu.api.modules.system.entity.FileShare;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface FileShareMapper extends BaseMapper<FileShare, String> {
@Select("SELECT * FROM file_share WHERE id = #{id}")
FileShare selectRecord(@Param("id") String id);
@Select("SELECT * FROM file_share WHERE token = #{token} AND deleted_at = 0")
FileShare selectActiveByToken(@Param("token") String token);
@Select("SELECT * FROM file_share WHERE deleted_at = 0 ORDER BY created_at DESC")
List<FileShare> listAll();
@Select("SELECT COUNT(*) FROM file_share WHERE token = #{token}")
int countByToken(@Param("token") String token);
@Update("UPDATE file_share SET deleted_at = #{now} WHERE id = #{id} AND deleted_at = 0")
int softDelete(@Param("id") String id, @Param("now") long now);
@Update("""
UPDATE file_share
SET file_hash = #{hash}, file_size = #{size}, file_modified_at = #{modifiedAt}
WHERE id = #{id}
""")
int updateFileMetadata(@Param("id") String id, @Param("hash") String hash, @Param("size") long size, @Param("modifiedAt") long modifiedAt);
@Update("""
UPDATE file_share
SET download_count = download_count + 1, last_access_at = #{now}
WHERE id = #{id}
AND deleted_at = 0
AND (max_downloads = 0 OR download_count < max_downloads)
""")
int incrementDownload(@Param("id") String id, @Param("now") long now);
}
@@ -0,0 +1,24 @@
package com.imyeyu.api.modules.system.mapper;
import com.imyeyu.api.modules.system.entity.FileTrash;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface FileTrashMapper extends BaseMapper<FileTrash, String> {
@Select("SELECT * FROM `file_trash` WHERE `expires_at` > #{now} ORDER BY `deleted_at` DESC")
List<FileTrash> listActive(@Param("now") long now);
@Select("SELECT * FROM `file_trash` WHERE `id` = #{id} AND `expires_at` > #{now}")
FileTrash selectActive(@Param("id") String id, @Param("now") long now);
@Select("SELECT * FROM `file_trash` WHERE `expires_at` <= #{now}")
List<FileTrash> listExpired(@Param("now") long now);
@Delete("DELETE FROM `file_trash` WHERE `id` = #{id}")
int deleteRecord(@Param("id") String id);
}
@@ -0,0 +1,221 @@
package com.imyeyu.api.modules.system.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.system.entity.AsyncTask;
import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask;
import com.imyeyu.api.modules.system.vo.AsyncTaskEvent;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
/**
* 异步任务 SSE 推送。
*
* <p>任务记录仍然是唯一状态源,SSE 只负责把状态变化、日志和最终结果推送给前端。
* 连接断开或任务结束后会取消内部轮询,避免遗留定时任务。</p>
*
* @author 夜雨
* @version 2026-11-24
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class AsyncTaskEventService {
private static final long CONNECTION_TIMEOUT = 30L * 60 * 1000;
private static final long POLL_INTERVAL = 500L;
private static final long HEARTBEAT_INTERVAL = 15L * 1000;
private static final int MESSAGE_LIMIT = 4096;
private static final ObjectMapper MAPPER = new ObjectMapper();
private final AsyncTaskService asyncTaskService;
private final TaskScheduler taskScheduler;
/**
* 订阅异步任务事件。
*
* @param taskId 任务 ID
* @param userId 当前登录用户 ID
* @return SSE 连接
*/
public SseEmitter subscribe(String taskId, String userId) {
AbstractAsyncTask task = asyncTaskService.getAsyncTask(taskId);
checkOwner(task, userId);
SseEmitter emitter = new SseEmitter(CONNECTION_TIMEOUT);
AtomicBoolean finished = new AtomicBoolean();
AtomicReference<ScheduledFuture<?>> futureRef = new AtomicReference<>();
AtomicReference<String> lastPayload = new AtomicReference<>();
AtomicLong lastHeartbeatAt = new AtomicLong(System.currentTimeMillis());
Runnable stopAction = () -> stop(emitter, finished, futureRef);
emitter.onCompletion(stopAction);
emitter.onTimeout(stopAction);
emitter.onError(error -> stopAction.run());
String payload = payload(task);
lastPayload.set(payload);
boolean terminal = terminal(task.getStatus());
if (terminal) {
sendTerminal(emitter, task.getStatus(), payload, finished, futureRef);
return emitter;
}
if (!send(emitter, "snapshot", payload, finished, futureRef)) {
return emitter;
}
ScheduledFuture<?> future;
try {
future = taskScheduler.scheduleAtFixedRate(
() -> tick(taskId, emitter, finished, futureRef, lastPayload, lastHeartbeatAt),
Duration.ofMillis(POLL_INTERVAL)
);
} catch (RuntimeException e) {
log.warn("订阅异步任务 SSE 失败,taskId={}", taskId, e);
sendError(emitter, "任务状态订阅失败", finished, futureRef);
return emitter;
}
futureRef.set(future);
if (finished.get()) {
future.cancel(false);
}
return emitter;
}
private void tick(String taskId, SseEmitter emitter, AtomicBoolean finished,
AtomicReference<ScheduledFuture<?>> futureRef, AtomicReference<String> lastPayload,
AtomicLong lastHeartbeatAt) {
if (finished.get()) {
return;
}
AbstractAsyncTask task;
try {
task = asyncTaskService.getAsyncTask(taskId);
} catch (TimiException e) {
sendError(emitter, "任务不存在或已结束", finished, futureRef);
return;
} catch (RuntimeException e) {
log.warn("读取异步任务状态失败,taskId={}", taskId, e);
sendError(emitter, "读取任务状态失败", finished, futureRef);
return;
}
String payload = payload(task);
if (terminal(task.getStatus())) {
sendTerminal(emitter, task.getStatus(), payload, finished, futureRef);
return;
}
if (!payload.equals(lastPayload.getAndSet(payload))) {
if (!send(emitter, "progress", payload, finished, futureRef)) {
return;
}
lastHeartbeatAt.set(System.currentTimeMillis());
return;
}
long now = System.currentTimeMillis();
if (HEARTBEAT_INTERVAL <= now - lastHeartbeatAt.get()) {
lastHeartbeatAt.set(now);
send(emitter, "heartbeat", "{}", finished, futureRef);
}
}
private void sendTerminal(SseEmitter emitter, AsyncTask.Status status, String payload,
AtomicBoolean finished, AtomicReference<ScheduledFuture<?>> futureRef) {
String event = status == AsyncTask.Status.SUCCESS ? "done" : "error";
if (send(emitter, event, payload, finished, futureRef)) {
stop(emitter, finished, futureRef);
}
}
private void sendError(SseEmitter emitter, String message, AtomicBoolean finished,
AtomicReference<ScheduledFuture<?>> futureRef) {
try {
String payload = MAPPER.writeValueAsString(java.util.Map.of("message", message));
if (send(emitter, "error", payload, finished, futureRef)) {
stop(emitter, finished, futureRef);
}
} catch (JsonProcessingException e) {
stop(emitter, finished, futureRef);
}
}
private boolean send(SseEmitter emitter, String event, String payload, AtomicBoolean finished,
AtomicReference<ScheduledFuture<?>> futureRef) {
if (finished.get()) {
return false;
}
try {
emitter.send(SseEmitter.event().name(event).data(payload));
return true;
} catch (IOException | IllegalStateException e) {
log.debug("异步任务 SSE 发送失败", e);
stop(emitter, finished, futureRef);
return false;
}
}
private void stop(SseEmitter emitter, AtomicBoolean finished, AtomicReference<ScheduledFuture<?>> futureRef) {
if (!finished.compareAndSet(false, true)) {
return;
}
ScheduledFuture<?> future = futureRef.getAndSet(null);
if (future != null) {
future.cancel(false);
}
try {
emitter.complete();
} catch (Exception e) {
log.debug("关闭异步任务 SSE 连接失败", e);
}
}
private void checkOwner(AbstractAsyncTask task, String userId) {
String ownerUserId = task.getOwnerUserId();
if (ownerUserId != null && !ownerUserId.equals(userId)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "无权访问该任务");
}
}
private String payload(AbstractAsyncTask task) {
String message = task.getMessage();
if (message != null && MESSAGE_LIMIT < message.length()) {
message = message.substring(message.length() - MESSAGE_LIMIT);
}
AsyncTaskEvent event = new AsyncTaskEvent(
task.getId(),
task.getName(),
task.getType(),
task.getStatus(),
task.getProgress(),
message,
task.getResult(),
task.getCreatedAt(),
task.getStartAt(),
task.getCompletedAt()
);
try {
return MAPPER.writeValueAsString(event);
} catch (JsonProcessingException e) {
throw new IllegalStateException("异步任务事件序列化失败", e);
}
}
private boolean terminal(AsyncTask.Status status) {
return status == AsyncTask.Status.SUCCESS
|| status == AsyncTask.Status.ERROR
|| status == AsyncTask.Status.INTERRUPT
|| status == AsyncTask.Status.DIED;
}
}
@@ -0,0 +1,132 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.modules.system.util.ResourceHandler;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.network.Network;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.Set;
/// 文件内容服务:负责下载、读取、预览和 HTTP 缓存语义。
@Slf4j
@Service
@RequiredArgsConstructor
public class FileContentService {
private static final Tika TIKA = new Tika();
private static final Set<String> ATTACHMENT_TYPES = Set.of(
"text/html", "application/xhtml+xml", "image/svg+xml",
"application/javascript", "text/javascript", "application/x-javascript"
);
private final FileStorageService storage;
private final ThumbnailService thumbnailService;
private final ResourceHandler resourceHandler;
public ContentInfo info(String virtualPath) {
Path file = storage.resolveExisting(virtualPath);
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.ARG_BAD, "路径不是文件");
}
try {
long size = Files.size(file);
long modifiedAt = Files.getLastModifiedTime(file).toMillis();
String mimeType = TIKA.detect(file);
String etag = "\"%x-%x\"".formatted(size, modifiedAt);
return new ContentInfo(file, mimeType, size, modifiedAt, etag,
ATTACHMENT_TYPES.contains(mimeType));
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "读取文件失败");
}
}
/// 输出原始文件,支持 GET/HEAD/Range/ETag。
public void serve(HttpServletRequest req, HttpServletResponse resp, String virtualPath, boolean attachment) {
ContentInfo info = info(virtualPath);
resp.setHeader("ETag", info.etag());
resp.setDateHeader("Last-Modified", info.modifiedAt());
resp.setHeader("Cache-Control", "private, max-age=0, must-revalidate");
if (notModified(req, info)) {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
resp.setContentType(info.mimeType());
resp.setHeader("X-Content-Type-Options", "nosniff");
if (attachment || info.attachment()) {
try {
resp.setHeader("Content-Disposition", Network.getFileDownloadHeader(info.path().getFileName().toString()));
} catch (java.io.UnsupportedEncodingException e) {
resp.setHeader("Content-Disposition", "attachment");
}
}
req.setAttribute(ResourceHandler.ATTR_TYPE, ResourceHandler.Type.FILE);
req.setAttribute(ResourceHandler.ATTR_VALUE, info.path());
try {
resourceHandler.handleRequest(req, resp);
} catch (Exception e) {
if (!resp.isCommitted()) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
/// 输出预览图。图片/视频走缩略图缓存,PDF/文本直接内联。
public void preview(HttpServletRequest req, HttpServletResponse resp, String virtualPath) {
ContentInfo info = info(virtualPath);
if (info.attachment()) {
throw new TimiException(TimiCode.ARG_BAD, "该文件类型不支持在线预览");
}
resp.setHeader("ETag", info.etag());
resp.setDateHeader("Last-Modified", info.modifiedAt());
if (notModified(req, info)) {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
if (info.mimeType().startsWith("image/") || info.mimeType().startsWith("video/")) {
Path thumbnail = thumbnailService.thumbnail(info.path(), info.mimeType());
try {
resp.setContentType("image/png");
resp.setHeader("X-Content-Type-Options", "nosniff");
resp.setHeader("Cache-Control", "private, max-age=86400");
resp.setContentLengthLong(Files.size(thumbnail));
Files.copy(thumbnail, resp.getOutputStream());
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "生成预览失败");
}
return;
}
if ("application/pdf".equals(info.mimeType()) || "text/plain".equals(info.mimeType())) {
resp.setContentType(info.mimeType());
resp.setHeader("X-Content-Type-Options", "nosniff");
resp.setHeader("Content-Disposition", "inline; filename*=UTF-8''" +
java.net.URLEncoder.encode(info.path().getFileName().toString(), java.nio.charset.StandardCharsets.UTF_8).replace("+", "%20"));
resp.setContentLengthLong(info.size());
try {
Files.copy(info.path(), resp.getOutputStream());
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "读取文件失败");
}
return;
}
throw new TimiException(TimiCode.ARG_BAD, "该文件类型不支持预览");
}
private boolean notModified(HttpServletRequest req, ContentInfo info) {
String ifNoneMatch = req.getHeader("If-None-Match");
return ifNoneMatch != null && ifNoneMatch.contains(info.etag());
}
public record ContentInfo(Path path, String mimeType, long size, long modifiedAt, String etag,
boolean attachment) {
}
}
@@ -1,114 +1,95 @@
package com.imyeyu.api.modules.system.service; package com.imyeyu.api.modules.system.service;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.api.modules.system.bean.ServerFile; import com.imyeyu.api.modules.system.bean.ServerFile;
import com.imyeyu.api.modules.system.bean.TransferFile;
import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
/** /**
* 文件服务 * 文件元数据服务
* *
* @author 夜雨 * @author 夜雨
* @version 2022-01-07 16:03 * @version 2022-01-07 16:03
*/ */
public interface FileService { public interface FileService {
boolean canAccess(String absPath) throws TimiException; /**
* 文件对象
default boolean canAccess(File file) throws TimiException { *
return canAccess(file.getAbsolutePath()); * @param path 虚拟路径
} * @return 文件元数据
*/
void checkAccessPermission(String absPath) throws TimiException; ServerFile object(String path);
default void checkAccessPermission(File file) throws TimiException {
checkAccessPermission(file.getAbsolutePath());
}
List<ServerFile> doFilter(List<ServerFile> list) throws TimiException;
/** /**
* 文件列表 * 文件列表
* *
* @param path 路径 * @param path 虚拟路径
* @return 文件列表 * @return 文件列表
* @throws TimiException 服务异常
*/ */
List<ServerFile> list(String path); List<ServerFile> list(String path);
/**
* 文件是否存在
*
* @param path 路径
* @return true 为存在
* @throws TimiException 服务异常
*/
boolean isExist(String path);
/** /**
* 深度搜索 * 深度搜索
* *
* @param path 基本路径 * @param path 基本路径
* @param keyword 关键字 * @param keyword 关键字
* @return 文件列表 * @return 搜索结果
* @throws TimiException 服务异常
*/ */
List<ServerFile> search(String path, String keyword); SearchResult search(String path, String keyword);
/**
* 文件是否存在
*
* @param path 虚拟路径
* @return true 为存在
*/
boolean exists(String path);
/** /**
* 创建文件夹 * 创建文件夹
* *
* @param path 路径 * @param path 父路径
* @param name 名称 * @param name 文件夹名称
* @return 文件夹 * @return 文件夹
* @throws TimiException 服务异常
*/ */
File mkdir(String path, String name); ServerFile mkdir(String path, String name);
/** /**
* 重命名,如果原文件不存在则修改失败 * 重命名或移动文件
* *
* @param from 原文件 * @param from 原虚拟路径
* @param to 目标文件 * @param to 目标虚拟路径
* @return true 为成功 * @return 目标文件
* @throws TimiException 服务异常
*/ */
boolean rename(String from, String to); ServerFile rename(String from, String to);
/** /**
* 获取文件数据流 * 获取文件数据流
* *
* @param path 绝对路径 * @param path 虚拟路径
* @return 数据流 * @return 数据流
* @throws TimiException 服务异常
*/ */
InputStream getInputStream(String path); InputStream open(String path);
/** /**
* 上传文件 * 获取文件 SHA-256
* *
* @param file 文件传输对象 * @param path 虚拟路径
* @throws TimiException 服务异常 * @return 文件哈希信息
*/ */
void upload(TransferFile file); FileHash hash(String path);
/** /**
* 数据流写入到文件 * 物理删除文件或文件夹
* *
* @param file 文件 * @param paths 虚拟路径列表
* @param is 数据流
* @throws TimiException 服务异常
*/ */
void toFile(File file, InputStream is); void deletePermanently(String... paths);
/** record SearchResult(List<ServerFile> items, boolean truncated, int scanned) {
* 删除文件 }
*
* @param list 列表 record FileHash(String path, long size, String sha256) {
* @throws TimiException 服务异常 }
*/
void destroy(String... list);
} }
@@ -0,0 +1,184 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.modules.system.audit.AuditOperation;
import com.imyeyu.api.modules.system.audit.OperationAudit;
import com.imyeyu.api.modules.system.entity.FileShare;
import com.imyeyu.api.modules.system.mapper.FileShareMapper;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HexFormat;
import java.util.List;
import java.util.UUID;
/// 文件分享服务
@Service
@RequiredArgsConstructor
public class FileShareService {
private static final SecureRandom RANDOM = new SecureRandom();
private static final long DAY_MILLIS = 86_400_000L;
private final FileStorageService storage;
private final FileShareMapper mapper;
@OperationAudit(AuditOperation.FILE_SHARE_CREATE)
public FileShare create(String path, String password, Long expiresAt, Integer maxDownloads, String ownerUserId) {
if (!storage.shareEnabled()) {
throw new TimiException(TimiCode.ARG_BAD, "文件分享未启用");
}
Path file = storage.resolveExisting(path);
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.ARG_BAD, "只能分享文件");
}
long now = System.currentTimeMillis();
long expire = expiresAt == null || expiresAt <= 0
? now + storage.shareDefaultExpireDays() * DAY_MILLIS
: expiresAt;
if (expire <= now) {
throw new TimiException(TimiCode.ARG_BAD, "过期时间必须晚于当前时间");
}
FileShare share = new FileShare();
share.setToken(nextToken());
share.setPath(path);
share.setName(file.getFileName().toString());
share.setOwnerUserId(ownerUserId);
share.setPasswordHash(password == null || password.isBlank() ? null : hashPassword(password));
try {
share.setFileSize(Files.size(file));
share.setFileModifiedAt(Files.getLastModifiedTime(file, LinkOption.NOFOLLOW_LINKS).toMillis());
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "读取分享文件信息失败");
}
share.setFileHash(storage.sha256(file));
share.setExpiresAt(expire);
share.setMaxDownloads(maxDownloads == null ? 0 : Math.max(0, maxDownloads));
share.setDownloadCount(0);
share.setLastAccessAt(0);
share.setCreatedAt(now);
share.setDeletedAt(0);
mapper.insert(share);
return share;
}
public List<FileShare> list() {
return mapper.listAll();
}
@OperationAudit(AuditOperation.FILE_SHARE_REVOKE)
public FileShare revoke(String id) {
FileShare share = mapper.selectRecord(id);
if (share == null || share.getDeletedAt() > 0) {
throw new TimiException(TimiCode.RESULT_NULL, "分享不存在");
}
long now = System.currentTimeMillis();
mapper.softDelete(id, now);
share.setDeletedAt(now);
return share;
}
/// 校验令牌、有效期、下载次数和密码,返回可下载的分享。
public FileShare open(String token, String password) {
return open(token, password, true);
}
/// 校验令牌、有效期、下载次数和密码,返回可下载的分享。
///
/// @param consume 是否消耗一次下载次数,HEAD 请求传 false
public FileShare open(String token, String password, boolean consume) {
FileShare share = mapper.selectActiveByToken(token);
if (share == null) {
throw new TimiException(TimiCode.RESULT_NULL, "分享不存在或已失效");
}
long now = System.currentTimeMillis();
if (share.getExpiresAt() <= now) {
throw new TimiException(TimiCode.RESULT_NULL, "分享已过期");
}
if (share.getMaxDownloads() > 0 && share.getDownloadCount() >= share.getMaxDownloads()) {
throw new TimiException(TimiCode.RESULT_BAD, "分享下载次数已用完");
}
if (share.getPasswordHash() != null && !verifyPassword(password, share.getPasswordHash())) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "分享密码错误");
}
Path file = storage.resolveExisting(share.getPath());
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.RESULT_NULL, "分享文件不存在");
}
try {
long size = Files.size(file);
long modifiedAt = Files.getLastModifiedTime(file, LinkOption.NOFOLLOW_LINKS).toMillis();
if (share.getFileSize() != size || share.getFileModifiedAt() != modifiedAt) {
String hash = storage.sha256(file);
if (share.getFileHash() != null && !share.getFileHash().equals(hash)) {
mapper.softDelete(share.getId(), now);
throw new TimiException(TimiCode.RESULT_NULL, "分享文件已变化");
}
mapper.updateFileMetadata(share.getId(), hash, size, modifiedAt);
share.setFileHash(hash);
share.setFileSize(size);
share.setFileModifiedAt(modifiedAt);
}
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "读取分享文件信息失败");
}
if (consume && mapper.incrementDownload(share.getId(), now) == 0) {
throw new TimiException(TimiCode.RESULT_BAD, "分享下载次数已用完");
}
return share;
}
private String nextToken() {
for (int i = 0; i < 5; i++) {
String token = UUID.randomUUID().toString().replace("-", "");
if (mapper.countByToken(token) == 0) {
return token;
}
}
throw new TimiException(TimiCode.ERROR, "生成分享令牌失败");
}
private static String hashPassword(String password) {
byte[] salt = new byte[16];
RANDOM.nextBytes(salt);
byte[] digest = digest(salt, password);
return HexFormat.of().formatHex(salt) + ":" + HexFormat.of().formatHex(digest);
}
private static boolean verifyPassword(String password, String stored) {
if (password == null) {
return false;
}
String[] parts = stored.split(":", 2);
if (parts.length != 2) {
return false;
}
try {
byte[] salt = HexFormat.of().parseHex(parts[0]);
byte[] expected = HexFormat.of().parseHex(parts[1]);
return MessageDigest.isEqual(expected, digest(salt, password));
} catch (IllegalArgumentException e) {
return false;
}
}
private static byte[] digest(byte[] salt, String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(salt);
md.update(password.getBytes(StandardCharsets.UTF_8));
return md.digest();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,337 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.modules.common.entity.Setting;
import com.imyeyu.api.modules.common.service.SettingService;
import com.imyeyu.api.modules.system.bean.SystemFileSetting;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitialization;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.Locale;
import java.util.Set;
/// 文件存储路径解析器。
///
/// 所有对外接口只接受以 `/` 开头、相对 `BASE_PATH` 的虚拟路径。
/// 该类是唯一允许把虚拟路径转换为真实路径的入口。
@Slf4j
@Service
@RequiredArgsConstructor
@DependsOnDatabaseInitialization
public class FileStorageService {
private static final Set<String> WINDOWS_RESERVED_NAMES = Set.of(
"CON", "PRN", "AUX", "NUL",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
);
private final SettingService settingService;
private volatile Path basePath;
private volatile Path trashPath;
private volatile Path thumbnailPath;
@PostConstruct
private void initialize() {
Path base = Path.of(value(SystemFileSetting.BASE_PATH))
.toAbsolutePath().normalize();
try {
Files.createDirectories(base);
basePath = base.toRealPath();
trashPath = resolveDirectory(value(SystemFileSetting.TRASH_PATH), ".trash");
thumbnailPath = resolveDirectory(value(SystemFileSetting.THUMBNAIL_PATH), ".cache/thumbnails");
if (trashPath.equals(basePath) || thumbnailPath.equals(basePath) || trashPath.equals(thumbnailPath)) {
throw new IllegalStateException("回收站和缩略图目录必须是 BASE_PATH 下的独立目录");
}
Files.createDirectories(trashPath);
Files.createDirectories(thumbnailPath);
log.info("file base path: {}", basePath);
} catch (IOException e) {
throw new IllegalStateException("无法初始化文件存储目录: " + base, e);
}
}
/// 读取系统配置。启动阶段 InitBuiltinSetting 尚未执行时,数据库可能还没有新增配置记录,
/// 此时回退到枚举默认值,避免 FileStorageService 初始化直接失败。
private Setting setting(SystemFileSetting key) {
Setting setting = settingService.getSystem(key);
if (setting != null) {
return setting;
}
Setting fallback = new Setting();
fallback.setCode(key.name());
fallback.setBizType(key.getBizType());
fallback.setValue(key.getDefaultValue());
fallback.setValueType(key.getValueType());
return fallback;
}
/// 读取配置值,空值时回退到枚举默认值。
private String value(SystemFileSetting key) {
String value = setting(key).asString();
return value == null || value.isBlank() ? key.getDefaultValue() : value;
}
private Path resolveDirectory(String value, String fallback) throws IOException {
String path = value == null || value.isBlank() ? fallback : value;
Path directory = Path.of(path);
if (!directory.isAbsolute()) {
directory = basePath.resolve(path);
}
directory = directory.toAbsolutePath().normalize();
if (!directory.startsWith(basePath)) {
throw new IllegalStateException("文件目录必须位于 BASE_PATH 内: " + directory);
}
ensureNoSymbolicLinks(basePath, directory);
Files.createDirectories(directory);
Path real = directory.toRealPath();
if (!real.startsWith(basePath)) {
throw new IllegalStateException("文件目录必须位于 BASE_PATH 内: " + directory);
}
return real;
}
public Path basePath() {
Path path = basePath;
if (path == null) {
throw new IllegalStateException("文件存储尚未初始化");
}
return path;
}
public Path trashPath() {
return trashPath;
}
public Path thumbnailPath() {
return thumbnailPath;
}
public long maxUploadSize() {
return setting(SystemFileSetting.UPLOAD_MAX_SIZE).asLong();
}
public long chunkSize() {
return setting(SystemFileSetting.UPLOAD_CHUNK_SIZE).asLong();
}
public int searchMaxResults() {
return setting(SystemFileSetting.SEARCH_MAX_RESULTS).asInteger();
}
public int searchMaxDepth() {
return setting(SystemFileSetting.SEARCH_MAX_DEPTH).asInteger();
}
public int searchTimeoutSeconds() {
return setting(SystemFileSetting.SEARCH_TIMEOUT_SECONDS).asInteger();
}
public int trashRetentionDays() {
return setting(SystemFileSetting.TRASH_RETENTION_DAYS).asInteger();
}
public boolean shareEnabled() {
return setting(SystemFileSetting.SHARE_ENABLED).asBoolean();
}
public int shareDefaultExpireDays() {
return setting(SystemFileSetting.SHARE_DEFAULT_EXPIRE_DAYS).asInteger();
}
/// 解析虚拟路径。路径必须位于 BASE_PATH 内,且不能经过符号链接。
public Path resolve(String virtualPath) {
return resolve(virtualPath, false);
}
/// 解析虚拟路径并要求目标存在。
public Path resolveExisting(String virtualPath) {
return resolve(virtualPath, true);
}
private Path resolve(String virtualPath, boolean mustExist) {
Path base = basePath();
String value = virtualPath == null ? "" : virtualPath;
if (!value.equals(value.strip())) {
throw new TimiException(TimiCode.ARG_BAD, "路径首尾不能包含空白");
}
if (value.indexOf('\0') >= 0 || value.indexOf('\\') >= 0) {
throw new TimiException(TimiCode.ARG_BAD, "路径不合法");
}
if (!value.isEmpty() && !value.startsWith("/")) {
throw new TimiException(TimiCode.ARG_BAD, "路径必须以 / 开头");
}
String relative = value.replaceFirst("^/+", "");
Path target = base.resolve(relative).normalize();
if (!target.startsWith(base)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "路径越界");
}
if (isInternal(target)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不能访问系统目录");
}
ensureNoSymbolicLinks(base, target);
if (!mustExist) {
return target;
}
if (!Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.RESULT_NULL, "文件或路径不存在");
}
try {
Path real = target.toRealPath();
if (!real.startsWith(base)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "路径越界");
}
return real;
} catch (IOException e) {
throw new TimiException(TimiCode.RESULT_NULL, "文件或路径不存在");
}
}
private void ensureNoSymbolicLinks(Path base, Path target) {
Path current = base;
Path relative = base.relativize(target);
for (Path part : relative) {
current = current.resolve(part);
if (Files.isSymbolicLink(current)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许访问符号链接");
}
}
}
/// 将真实路径转换为虚拟路径。
public String virtualPath(Path path) {
Path absolute = path.toAbsolutePath().normalize();
if (!absolute.startsWith(basePath())) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "路径越界");
}
String relative = basePath().relativize(absolute).toString().replace('\\', '/');
return relative.isEmpty() ? "/" : "/" + relative;
}
/// 解析并校验单个文件名(不是完整路径)。
public void validateFileName(String name) {
if (name == null || name.isBlank()) {
throw new TimiException(TimiCode.ARG_MISS, "缺少文件名称");
}
if (name.length() > 255) {
throw new TimiException(TimiCode.ARG_BAD, "文件名称过长");
}
if (".".equals(name) || "..".equals(name) || name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) {
throw new TimiException(TimiCode.ARG_BAD, "文件名称不合法");
}
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (c < 0x20 || c == 0x7F || "<>:\"|?*".indexOf(c) >= 0) {
throw new TimiException(TimiCode.ARG_BAD, "文件名称不合法");
}
}
if (name.endsWith(".") || name.endsWith(" ")) {
throw new TimiException(TimiCode.ARG_BAD, "文件名称不能以点或空格结尾");
}
String baseName = name;
int dot = name.indexOf('.');
if (dot >= 0) {
baseName = name.substring(0, dot);
}
if (WINDOWS_RESERVED_NAMES.contains(baseName.toUpperCase(Locale.ROOT))) {
throw new TimiException(TimiCode.ARG_BAD, "文件名称不合法");
}
}
/// 在父目录下拼接一个经过校验的文件名。
public Path child(Path parent, String name) {
validateFileName(name);
Path child = parent.resolve(name).normalize();
if (!child.startsWith(basePath())) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "路径越界");
}
if (isInternal(child)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不能访问系统目录");
}
return child;
}
public boolean isRoot(String virtualPath) {
return virtualPath == null || virtualPath.isBlank() || "/".equals(virtualPath);
}
/// 是否为回收站或缩略图缓存等内部目录。
public boolean isInternal(Path path) {
Path absolute = path.toAbsolutePath().normalize();
if (absolute.startsWith(trashPath()) || absolute.startsWith(thumbnailPath())) {
return true;
}
Path cacheRoot = thumbnailPath().getParent();
return cacheRoot != null && !cacheRoot.equals(basePath()) && absolute.startsWith(cacheRoot);
}
public void move(Path source, Path target) throws IOException {
Files.createDirectories(target.getParent());
try {
Files.move(source, target);
} catch (IOException e) {
copyRecursively(source, target);
deleteRecursively(source);
}
}
private void copyRecursively(Path source, Path target) throws IOException {
if (Files.isSymbolicLink(source)) {
throw new IOException("不允许复制符号链接");
}
if (Files.isDirectory(source, LinkOption.NOFOLLOW_LINKS)) {
Files.createDirectories(target);
try (var children = Files.newDirectoryStream(source)) {
for (Path child : children) {
copyRecursively(child, target.resolve(child.getFileName()));
}
}
} else {
Files.copy(source, target);
}
}
public void deleteRecursively(Path path) throws IOException {
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
return;
}
if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
try (var children = Files.newDirectoryStream(path)) {
for (Path child : children) {
deleteRecursively(child);
}
}
}
Files.deleteIfExists(path);
}
/// 流式计算文件 SHA-256。
public String sha256(Path file) {
try (InputStream input = Files.newInputStream(file)) {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] buffer = new byte[64 * 1024];
int read;
while ((read = input.read(buffer)) >= 0) {
digest.update(buffer, 0, read);
}
return HexFormat.of().formatHex(digest.digest());
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "计算文件哈希失败");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,167 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.modules.system.audit.AuditOperation;
import com.imyeyu.api.modules.system.audit.OperationAudit;
import com.imyeyu.api.modules.system.bean.ServerFile;
import com.imyeyu.api.modules.system.entity.FileTrash;
import com.imyeyu.api.modules.system.mapper.FileTrashMapper;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/// 文件回收站。删除操作只移动文件并写入记录,恢复/彻底删除由本服务负责。
@Slf4j
@Service
@RequiredArgsConstructor
public class FileTrashService {
private final FileStorageService storage;
private final FileTrashMapper fileTrashMapper;
/// 将文件移入回收站。
@OperationAudit(AuditOperation.FILE_DELETE)
public List<FileTrash> trash(List<String> paths, String ownerUserId) {
if (paths == null || paths.isEmpty()) {
throw new TimiException(TimiCode.ARG_MISS, "缺少文件列表");
}
long now = System.currentTimeMillis();
long expiresAt = now + storage.trashRetentionDays() * 86_400_000L;
List<FileTrash> result = new ArrayList<>(paths.size());
for (String path : paths) {
if (storage.isRoot(path)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不能删除根目录");
}
Path source = storage.resolveExisting(path);
if (storage.isInternal(source)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不能删除系统目录");
}
String trashName = UUID.randomUUID().toString();
Path item = storage.trashPath().resolve(trashName);
FileTrash record = new FileTrash();
record.setOriginalPath(storage.virtualPath(source));
record.setTrashName(trashName);
record.setName(source.getFileName().toString());
record.setDirectory(Files.isDirectory(source, LinkOption.NOFOLLOW_LINKS));
record.setSize(record.isDirectory() ? 0 : fileSize(source));
record.setOwnerUserId(ownerUserId);
record.setDeletedAt(now);
record.setExpiresAt(expiresAt);
try {
storage.move(source, item);
fileTrashMapper.insert(record);
result.add(record);
} catch (IOException e) {
try {
if (Files.exists(item, LinkOption.NOFOLLOW_LINKS) && !Files.exists(source, LinkOption.NOFOLLOW_LINKS)) {
storage.move(item, source);
}
} catch (IOException ignored) {
log.warn("restore failed after trash error: {}", path, ignored);
}
throw new TimiException(TimiCode.ERROR, "删除失败:" + path);
}
}
return result;
}
public List<FileTrash> list() {
return fileTrashMapper.listActive(System.currentTimeMillis());
}
@OperationAudit(AuditOperation.FILE_RESTORE)
public ServerFile restore(String id) {
FileTrash record = requireActive(id);
Path item = storage.trashPath().resolve(record.getTrashName());
if (!Files.exists(item, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.RESULT_NULL, "回收站文件不存在");
}
String originalPath = record.getOriginalPath();
int slash = originalPath.lastIndexOf('/');
String parentPath = slash <= 0 ? "/" : originalPath.substring(0, slash);
String name = slash < 0 ? originalPath : originalPath.substring(slash + 1);
Path parent = storage.resolve(parentPath);
try {
Files.createDirectories(parent);
Path target = storage.child(parent, name);
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.RESULT_BAD, "原位置已存在同名文件");
}
storage.move(item, target);
fileTrashMapper.deleteRecord(id);
return new ServerFile(storage.basePath(), target);
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "恢复文件失败");
}
}
@OperationAudit(AuditOperation.FILE_PURGE)
public void purge(String id) {
FileTrash record = requireActive(id);
deleteItem(record);
fileTrashMapper.deleteRecord(id);
}
@OperationAudit(AuditOperation.FILE_PURGE)
public int empty() {
List<FileTrash> list = fileTrashMapper.listActive(System.currentTimeMillis());
for (FileTrash record : list) {
try {
deleteItem(record);
fileTrashMapper.deleteRecord(record.getId());
} catch (Exception e) {
log.warn("purge trash failed: {}", record.getId(), e);
}
}
return list.size();
}
/// 每天清理过期回收站。
@Scheduled(cron = "0 30 3 * * ?")
public void cleanupExpired() {
List<FileTrash> list = fileTrashMapper.listExpired(System.currentTimeMillis());
for (FileTrash record : list) {
try {
deleteItem(record);
fileTrashMapper.deleteRecord(record.getId());
} catch (Exception e) {
log.warn("cleanup trash failed: {}", record.getId(), e);
}
}
}
private FileTrash requireActive(String id) {
FileTrash record = fileTrashMapper.selectActive(id, System.currentTimeMillis());
if (record == null) {
throw new TimiException(TimiCode.RESULT_NULL, "回收站记录不存在");
}
return record;
}
private void deleteItem(FileTrash record) {
Path item = storage.trashPath().resolve(record.getTrashName());
try {
storage.deleteRecursively(item);
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "彻底删除失败");
}
}
private long fileSize(Path path) {
try {
return Files.size(path);
} catch (IOException e) {
return 0;
}
}
}
@@ -0,0 +1,265 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.modules.system.audit.AuditOperation;
import com.imyeyu.api.modules.system.audit.OperationAudit;
import com.imyeyu.api.modules.system.bean.ServerFile;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/// 文件上传服务,支持普通上传与分片上传。
@Service
@RequiredArgsConstructor
public class FileUploadService {
private static final long SESSION_TTL_MILLIS = 24 * 60 * 60 * 1000L;
private final FileStorageService storage;
private final Map<String, UploadSession> sessions = new ConcurrentHashMap<>();
@OperationAudit(AuditOperation.FILE_UPLOAD)
public ServerFile upload(String path, String name, MultipartFile file, boolean overwrite) {
if (file == null || file.isEmpty()) {
throw new TimiException(TimiCode.ARG_MISS, "缺少上传文件");
}
if (storage.maxUploadSize() < file.getSize()) {
throw new TimiException(TimiCode.ARG_BAD, "文件超过大小限制");
}
Path parent = requireDirectory(path);
Path target = storage.child(parent, name);
if (!overwrite && Files.exists(target)) {
throw new TimiException(TimiCode.RESULT_BAD, "目标文件已存在");
}
Path temp = parent.resolve(".upload-" + UUID.randomUUID() + ".part");
try {
try (InputStream input = file.getInputStream()) {
Files.copy(input, temp, StandardCopyOption.REPLACE_EXISTING);
}
move(temp, target, overwrite);
setPermissions(target);
return new ServerFile(storage.basePath(), target);
} catch (IOException e) {
deleteQuietly(temp);
throw new TimiException(TimiCode.ERROR, "上传文件失败");
}
}
public UploadInit init(String path, String name, long size, String sha256) {
if (size < 0 || storage.maxUploadSize() < size) {
throw new TimiException(TimiCode.ARG_BAD, "文件超过大小限制");
}
Path parent = requireDirectory(path);
storage.validateFileName(name);
if (Files.exists(parent.resolve(name))) {
throw new TimiException(TimiCode.RESULT_BAD, "目标文件已存在");
}
long chunkSize = storage.chunkSize();
int totalChunks = (int) Math.max(1, (size + chunkSize - 1) / chunkSize);
String id = UUID.randomUUID().toString();
UploadSession session = new UploadSession(id, path, name, size, chunkSize, totalChunks, sha256);
sessions.put(id, session);
try {
Files.createDirectories(session.directory);
} catch (IOException e) {
sessions.remove(id);
throw new TimiException(TimiCode.ERROR, "初始化上传失败");
}
return new UploadInit(id, chunkSize, totalChunks);
}
public void chunk(String uploadId, int index, MultipartFile file) {
UploadSession session = requireSession(uploadId);
if (index < 0 || session.totalChunks <= index) {
throw new TimiException(TimiCode.ARG_BAD, "分片序号不合法");
}
if (file == null || file.isEmpty()) {
throw new TimiException(TimiCode.ARG_MISS, "缺少分片文件");
}
if (session.chunkSize < file.getSize()) {
throw new TimiException(TimiCode.ARG_BAD, "分片大小超出限制");
}
Path target = session.directory.resolve(index + ".part");
try (InputStream input = file.getInputStream()) {
Files.copy(input, target, StandardCopyOption.REPLACE_EXISTING);
session.received.add(index);
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "写入分片失败");
}
}
@OperationAudit(AuditOperation.FILE_UPLOAD)
public ServerFile complete(String uploadId, String sha256) {
UploadSession session = requireSession(uploadId);
if (session.received.size() != session.totalChunks) {
throw new TimiException(TimiCode.RESULT_BAD, "分片不完整");
}
Path parent = requireDirectory(session.path);
Path target = storage.child(parent, session.name);
if (Files.exists(target)) {
throw new TimiException(TimiCode.RESULT_BAD, "目标文件已存在");
}
Path temp = parent.resolve(".upload-" + uploadId + ".part");
try {
try (var output = Files.newOutputStream(temp, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
for (int i = 0; i < session.totalChunks; i++) {
Path part = session.directory.resolve(i + ".part");
if (!Files.isRegularFile(part)) {
throw new TimiException(TimiCode.RESULT_BAD, "分片不完整");
}
Files.copy(part, output);
}
}
if (Files.size(temp) != session.size) {
throw new TimiException(TimiCode.ARG_BAD, "文件大小校验失败");
}
String expected = sha256 != null && !sha256.isBlank() ? sha256 : session.sha256;
if (expected != null && !expected.isBlank() && !expected.equalsIgnoreCase(sha256(temp))) {
throw new TimiException(TimiCode.ARG_BAD, "文件校验失败");
}
move(temp, target, false);
setPermissions(target);
sessions.remove(uploadId);
try {
storage.deleteRecursively(session.directory);
} catch (RuntimeException ignored) {
// 临时分片清理失败不影响上传结果。
}
return new ServerFile(storage.basePath(), target);
} catch (IOException e) {
deleteQuietly(temp);
throw new TimiException(TimiCode.ERROR, "合并分片失败");
} catch (RuntimeException e) {
deleteQuietly(temp);
throw e;
}
}
/// 清理超过 24 小时未活动的分片上传会话。
@Scheduled(cron = "0 0 * * * ?")
public void cleanupExpiredSessions() {
long now = System.currentTimeMillis();
sessions.forEach((id, session) -> {
if (now - session.lastAccessAt < SESSION_TTL_MILLIS) {
return;
}
if (!sessions.remove(id, session)) {
return;
}
try {
storage.deleteRecursively(session.directory);
} catch (IOException | RuntimeException ignored) {
// 临时目录清理失败不影响后续会话。
}
});
}
private Path requireDirectory(String path) {
Path directory = storage.resolveExisting(path);
if (!Files.isDirectory(directory)) {
throw new TimiException(TimiCode.ARG_BAD, "目标路径不是文件夹");
}
return directory;
}
private UploadSession requireSession(String id) {
UploadSession session = sessions.get(id);
if (session == null) {
throw new TimiException(TimiCode.RESULT_NULL, "上传任务不存在");
}
session.lastAccessAt = System.currentTimeMillis();
return session;
}
private void move(Path source, Path target, boolean overwrite) throws IOException {
if (overwrite) {
try {
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (java.nio.file.AtomicMoveNotSupportedException e) {
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
}
return;
}
try {
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
} catch (java.nio.file.AtomicMoveNotSupportedException e) {
Files.move(source, target);
}
}
private void setPermissions(Path path) {
try {
Files.setPosixFilePermissions(path, java.nio.file.attribute.PosixFilePermissions.fromString("rw-r--r--"));
} catch (UnsupportedOperationException | IOException ignored) {
// Windows 文件系统不支持 POSIX 权限,保留默认权限。
}
}
private String sha256(Path path) throws IOException {
try (InputStream input = Files.newInputStream(path)) {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] buffer = new byte[64 * 1024];
int length;
while ((length = input.read(buffer)) >= 0) {
digest.update(buffer, 0, length);
}
StringBuilder result = new StringBuilder();
for (byte b : digest.digest()) {
result.append(Character.forDigit((b >> 4) & 0xF, 16));
result.append(Character.forDigit(b & 0xF, 16));
}
return result.toString();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
private void deleteQuietly(Path path) {
try {
Files.deleteIfExists(path);
} catch (IOException ignored) {
}
}
public record UploadInit(String uploadId, long chunkSize, int totalChunks) {
}
private static final class UploadSession {
private final String id;
private final String path;
private final String name;
private final long size;
private final long chunkSize;
private final int totalChunks;
private final String sha256;
private final Path directory;
private final Set<Integer> received = ConcurrentHashMap.newKeySet();
private volatile long lastAccessAt = System.currentTimeMillis();
private UploadSession(String id, String path, String name, long size, long chunkSize, int totalChunks, String sha256) {
this.id = id;
this.path = path;
this.name = name;
this.size = size;
this.chunkSize = chunkSize;
this.totalChunks = totalChunks;
this.sha256 = sha256;
this.directory = Path.of(System.getProperty("java.io.tmpdir"), "timi-file-upload", id);
}
}
}
@@ -0,0 +1,100 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import lombok.RequiredArgsConstructor;
import net.coobird.thumbnailator.Thumbnails;
import org.jcodec.api.FrameGrab;
import org.jcodec.common.model.Picture;
import org.jcodec.scale.AWTUtil;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
/// 缩略图缓存服务。
@Service
@RequiredArgsConstructor
public class ThumbnailService {
private static final int SIZE = 256;
private static final long MAX_PIXELS = 50_000_000L;
private final FileStorageService storage;
public Path thumbnail(Path source, String mimeType) {
try {
long modifiedAt = Files.getLastModifiedTime(source).toMillis();
long size = Files.size(source);
String key = sha256(source.toAbsolutePath() + "|" + modifiedAt + "|" + size + "|" + SIZE);
Path target = storage.thumbnailPath().resolve(key + ".png");
if (Files.isRegularFile(target)) {
return target;
}
Files.createDirectories(target.getParent());
if (mimeType.startsWith("video/")) {
Picture picture;
try {
picture = FrameGrab.getFrameAtSec(source.toFile(), 0);
} catch (Exception e) {
picture = FrameGrab.getFrameAtSec(source.toFile(), 1);
}
BufferedImage image = AWTUtil.toBufferedImage(picture);
ImageIO.write(image, "png", target.toFile());
} else {
validatePixelCount(source);
Thumbnails.of(source.toFile()).size(SIZE, SIZE).outputFormat("png").toFile(target.toFile());
}
return target;
} catch (TimiException e) {
throw e;
} catch (Exception e) {
throw new TimiException(TimiCode.ERROR, "生成缩略图失败");
}
}
/// 在完整解码前检查图片像素数,避免超大图片耗尽内存。
private void validatePixelCount(Path source) throws IOException {
try (ImageInputStream input = ImageIO.createImageInputStream(source.toFile())) {
if (input == null) {
throw new IOException("无法读取图片");
}
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
if (!readers.hasNext()) {
throw new IOException("不支持的图片格式");
}
ImageReader reader = readers.next();
try {
reader.setInput(input, true, true);
long pixels = (long) reader.getWidth(0) * reader.getHeight(0);
if (MAX_PIXELS < pixels) {
throw new TimiException(TimiCode.ARG_BAD, "图片像素过大");
}
} finally {
reader.dispose();
}
}
}
private String sha256(String value) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(java.nio.charset.StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder(digest.length * 2);
for (byte b : digest) {
result.append(Character.forDigit((b >> 4) & 0xF, 16));
result.append(Character.forDigit(b & 0xF, 16));
}
return result.toString();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}
@@ -40,6 +40,9 @@ public abstract class AbstractAsyncTask extends AsyncTask {
/** 日志缓冲 */ /** 日志缓冲 */
final StringBuilder logBuffer = new StringBuilder(); final StringBuilder logBuffer = new StringBuilder();
/** 暂停/中断检查节流计数 */
private int pauseCheckCount;
/// 任务持久化回调 /// 任务持久化回调
private Consumer<AbstractAsyncTask> persistenceCallback = task -> { private Consumer<AbstractAsyncTask> persistenceCallback = task -> {
}; };
@@ -203,11 +206,19 @@ public abstract class AbstractAsyncTask extends AsyncTask {
/** 在耗时任务中执行此方法可受 {@link #isPause()} 和 {@link #isInterrupt()} 控制暂停或中断 */ /** 在耗时任务中执行此方法可受 {@link #isPause()} 和 {@link #isInterrupt()} 控制暂停或中断 */
protected void pauseInterruptHandle() throws InterruptedException { protected void pauseInterruptHandle() throws InterruptedException {
Thread.sleep(700); // 每处理 64 项检查一次,避免每个文件固定休眠 700ms;暂停后恢复时立即重新检查。
if (++pauseCheckCount % 64 != 0 && !isPause() && !isInterrupt()) {
return;
}
if (isPause()) { if (isPause()) {
// 暂停 // 暂停
synchronized (pauseLocker) { synchronized (pauseLocker) {
pauseLocker.wait(); while (isPause() && !isInterrupt()) {
pauseLocker.wait();
}
}
if (isInterrupt()) {
throw TimiCode.ERROR_SERVICE_OFF.toException();
} }
setStatus(AsyncTask.Status.RUNNING); setStatus(AsyncTask.Status.RUNNING);
} }
@@ -144,7 +144,7 @@ public class AsyncTaskServiceImplement implements AsyncTaskService {
task.setMessage(task.getLogContent()); task.setMessage(task.getLogContent());
return task; return task;
} }
throw new TimiException(TimiCode.RESULT_NULL, "TODO not found task"); throw new TimiException(TimiCode.RESULT_NULL, "任务不存在");
} }
@Override @Override
@@ -1,266 +1,233 @@
package com.imyeyu.api.modules.system.service.implement; package com.imyeyu.api.modules.system.service.implement;
import com.imyeyu.api.modules.common.service.SettingService; import com.imyeyu.api.modules.system.audit.AuditOperation;
import com.imyeyu.api.modules.system.audit.OperationAudit;
import com.imyeyu.api.modules.system.bean.ServerFile; import com.imyeyu.api.modules.system.bean.ServerFile;
import com.imyeyu.api.modules.system.bean.SystemFileSetting;
import com.imyeyu.api.modules.system.bean.TransferFile;
import com.imyeyu.api.modules.system.service.AsyncTaskService;
import com.imyeyu.api.modules.system.service.FileService; import com.imyeyu.api.modules.system.service.FileService;
import com.imyeyu.api.modules.system.util.SystemAPIInterceptor; import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.io.IO;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode; import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException; import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.utils.Decoder;
import com.imyeyu.utils.OS;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.naming.NoPermissionException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayDeque; import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Deque; import java.util.Comparator;
import java.util.List; import java.util.List;
/** /**
* 文件服务,不可直接使用入参路径 * 文件元数据服务实现
* *
* @author 夜雨 * @author 夜雨
* @version 2022-01-07 16:05 * @version 2022-01-07 16:05
*/ */
@Slf4j
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class FileServiceImplement implements TimiJava, FileService { public class FileServiceImplement implements FileService {
/** private static final Comparator<Path> FILE_COMPARATOR = (left, right) -> {
* boolean leftDirectory = Files.isDirectory(left, LinkOption.NOFOLLOW_LINKS);
* boolean rightDirectory = Files.isDirectory(right, LinkOption.NOFOLLOW_LINKS);
* @author 夜雨 if (leftDirectory != rightDirectory) {
* @since 2025-03-31 14:50 return leftDirectory ? -1 : 1;
*/ }
@Data return left.getFileName().toString().compareToIgnoreCase(right.getFileName().toString());
public static class FilterOption { };
List<String> allow; private final FileStorageService storage;
List<String> exclude;
}
private final SettingService settingService;
private final AsyncTaskService asyncTaskService;
private final SystemAPIInterceptor interceptor;
private final ScheduledTaskRegistrar scheduledTaskRegistrar;
private FilterOption option;
@PostConstruct
private void fileSyncPostConstruct() {
// FileSyncConfig config = settingService.fromYaml(SettingKey.SYSTEM_FILE_SYNC, FileSyncConfig.class);
// if (config.isEnable()) {
// scheduledTaskRegistrar.scheduleCronTask(new CronTask(() -> {
// Map<String, FileSyncConfig.Task> tasks = config.getTasks();
// configTask: for (Map.Entry<String, FileSyncConfig.Task> item : tasks.entrySet()) {
// if (item.getValue().isEnable()) {
// List<AbstractAsyncTask> runningTaskList = asyncTaskService.listAll();
// for (int i = 0; i < runningTaskList.size(); i++) {
// AbstractAsyncTask runningTask = runningTaskList.get(i);
// if (runningTask.getType() == AsyncTask.Type.FILE_SYNC && runningTask.getName().equals(item.getKey())) {
// continue configTask;
// }
// }
// FileSyncTask task = new FileSyncTask(item.getKey(), item.getValue());
// asyncTaskService.addAsyncTask(task);
// }
// }
// }, config.getCron()));
// }
}
@PostConstruct
private void fileFilterPostConstruct() {
// option = settingService.fromYaml(SettingKey.SYSTEM_FILE_FILTER, FilterOption.class);
}
@Override @Override
public boolean canAccess(String path) { public ServerFile object(String path) {
if (interceptor.isHighAuthorityKey()) { Path file = storage.resolveExisting(path);
return true; return new ServerFile(storage.basePath(), file);
}
for (String allow : option.allow) {
if (!path.startsWith(allow)) {
return false;
}
}
for (String exclude : option.exclude) {
if (path.startsWith(exclude)) {
return false;
}
}
return true;
}
@Override
public void checkAccessPermission(String path) {
if (canAccess(path)) {
return;
}
throw new TimiException(TimiCode.PERMISSION_ERROR, "TODO invalid permission");
}
@Override
public List<ServerFile> doFilter(List<ServerFile> list) {
list.removeIf(item -> !canAccess(item.getAbsolutePath()));
return list;
} }
@Override @Override
public List<ServerFile> list(String path) { public List<ServerFile> list(String path) {
File file = new File(getPath(path)); Path directory = storage.resolveExisting(path);
if (file.exists()) { if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) {
List<ServerFile> result = new ArrayList<>(); throw new TimiException(TimiCode.ARG_BAD, "路径不是文件夹");
File[] files = file.listFiles();
if (files != null) {
List<File> list = new ArrayList<>(List.of(files));
list.sort(OS.FileSystem.COMPARATOR_FILE_NAME);
for (int i = 0; i < list.size(); i++) {
result.add(new ServerFile(list.get(i)));
}
}
return result;
} else {
throw new TimiException(TimiCode.RESULT_NULL, "文件或路径不存在");
} }
} try (var children = Files.list(directory)) {
return children.filter(child -> !storage.isInternal(child))
@Override .filter(child -> !Files.isSymbolicLink(child))
public boolean isExist(String path) { .sorted(FILE_COMPARATOR)
return new File(getPath(path)).exists(); .map(child -> new ServerFile(storage.basePath(), child))
} .toList();
@Override
public List<ServerFile> search(String path, String keyword) {
File file = new File(getPath(path));
if (file.exists()) {
List<ServerFile> result = new ArrayList<>();
// 右进左出文件夹队列,非递归深度栈遍历
Deque<File> directoryQueue = new ArrayDeque<>();
directoryQueue.addLast(file);
deque: while (!directoryQueue.isEmpty()) {
File directory = directoryQueue.pollFirst();
File[] files = directory.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].getName().contains(keyword)) {
result.add(new ServerFile(files[i]));
if (100 < result.size()) {
break deque;
}
}
if (files[i].isDirectory()) {
directoryQueue.addLast(files[i]);
}
}
}
}
return result;
} else {
throw new TimiException(TimiCode.RESULT_NULL, "文件或路径不存在");
}
}
@Override
public File mkdir(String path, String name) {
String uri = IO.fitPath(getPath(path)) + name;
try {
return IO.dir(uri);
} catch (NoPermissionException e) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "权限错误");
}
}
@Override
public boolean rename(String from, String to) {
File source = new File(getPath(from));
checkAccessPermission(source.getAbsolutePath());
if (source.exists()) {
return source.renameTo(new File(getPath(to)));
}
return false;
}
@Override
public InputStream getInputStream(String path) {
try {
return IO.getInputStream(getPath(path));
} catch (FileNotFoundException e) {
throw new TimiException(TimiCode.RESULT_NULL, "找不到文件");
}
}
@Override
public void upload(TransferFile file) {
String path = getPath(Decoder.url(file.getPath()));
if (file.getName() == null) {
throw new TimiException(TimiCode.ARG_MISS, "缺少参数:name");
}
String fileName = Decoder.url(file.getName());
if (!OS.isValidFileName(path)) {
throw new TimiException(TimiCode.ARG_BAD, "路径名称不合法:" + path);
}
if (!OS.isValidFileName(fileName)) {
throw new TimiException(TimiCode.ARG_BAD, "文件名称不合法:" + fileName);
}
if (file.getLength() == file.getFile().getSize()) {
try {
toFile(new File(path + fileName), file.getFile().getInputStream());
} catch (IOException e) {
log.error("get request input stream error", e);
throw new TimiException(TimiCode.ARG_BAD, "获取文件输入流失败");
}
} else {
log.error("request submit request size: {}, receive request size: {}", file.getLength(), file.getFile().getSize());
throw new TimiException(TimiCode.ERROR, "不完整上传文件,已忽略");
}
}
@Override
public void toFile(File file, InputStream is) {
try {
IO.toFile(file, is);
} catch (IOException e) { } catch (IOException e) {
throw new TimiException(TimiCode.ERROR); throw new TimiException(TimiCode.ERROR, "读取文件夹失败");
} catch (NoPermissionException e) {
throw new TimiException(TimiCode.PERMISSION_ERROR);
} }
} }
@Override @Override
public void destroy(String... list) { public SearchResult search(String path, String keyword) {
for (int i = 0; i < list.length; i++) { if (keyword == null || keyword.isBlank()) {
File file = new File(list[i]); throw new TimiException(TimiCode.ARG_MISS, "缺少参数:keyword");
if (canAccess(file) && file.exists() && file.canWrite()) { }
IO.destroy(file); Path start = storage.resolveExisting(path);
int maxResults = storage.searchMaxResults();
int maxDepth = storage.searchMaxDepth();
long deadline = System.nanoTime() + storage.searchTimeoutSeconds() * 1_000_000_000L;
List<ServerFile> result = new ArrayList<>();
int[] scanned = {0};
boolean[] truncated = {false};
try {
Files.walkFileTree(start, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (Files.isSymbolicLink(dir)) {
return FileVisitResult.SKIP_SUBTREE;
}
if (storage.isInternal(dir)) {
return FileVisitResult.SKIP_SUBTREE;
}
if (start.relativize(dir).getNameCount() > maxDepth) {
truncated[0] = true;
return FileVisitResult.SKIP_SUBTREE;
}
return check();
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
scanned[0]++;
if (Files.isSymbolicLink(file)) {
return check();
}
if (file.getFileName().toString().toLowerCase().contains(keyword.toLowerCase())) {
result.add(new ServerFile(storage.basePath(), file));
}
return check();
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
return check();
}
private FileVisitResult check() {
if (maxResults <= result.size()) {
truncated[0] = true;
return FileVisitResult.TERMINATE;
}
if (deadline < System.nanoTime()) {
truncated[0] = true;
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "搜索文件失败");
}
return new SearchResult(List.copyOf(result), truncated[0], scanned[0]);
}
@Override
public boolean exists(String path) {
try {
storage.resolveExisting(path);
return true;
} catch (TimiException e) {
if (e.getCode() == TimiCode.RESULT_NULL) {
return false;
} }
throw e;
} }
} }
private String getPath(String path) { @Override
String basePath = settingService.getSystem(SystemFileSetting.BASE_PATH).asString(); @OperationAudit(AuditOperation.FILE_MKDIR)
if (TimiJava.isEmpty(path)) { public ServerFile mkdir(String path, String name) {
return basePath; Path parent = storage.resolveExisting(path);
if (!Files.isDirectory(parent, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.ARG_BAD, "父路径不是文件夹");
}
Path target = storage.child(parent, name);
try {
Files.createDirectory(target);
return new ServerFile(storage.basePath(), target);
} catch (java.nio.file.FileAlreadyExistsException e) {
throw new TimiException(TimiCode.RESULT_BAD, "文件夹已存在");
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "创建文件夹失败");
}
}
@Override
@OperationAudit(AuditOperation.FILE_RENAME)
public ServerFile rename(String from, String to) {
Path source = storage.resolveExisting(from);
if (storage.isRoot(from)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不能重命名根目录");
}
Path target = storage.resolve(to);
if (target.startsWith(source)) {
throw new TimiException(TimiCode.ARG_BAD, "不能移动到自身内部");
}
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.RESULT_BAD, "目标文件已存在");
}
if (!Files.isDirectory(target.getParent(), LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.ARG_BAD, "目标父路径不存在");
}
try {
Files.move(source, target);
return new ServerFile(storage.basePath(), target);
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "重命名失败");
}
}
@Override
public InputStream open(String path) {
Path file = storage.resolveExisting(path);
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.ARG_BAD, "路径不是文件");
}
try {
return Files.newInputStream(file);
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "读取文件失败");
}
}
@Override
public FileHash hash(String path) {
Path file = storage.resolveExisting(path);
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.ARG_BAD, "路径不是文件");
}
try {
return new FileHash(storage.virtualPath(file), Files.size(file), storage.sha256(file));
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "读取文件失败");
}
}
@Override
@OperationAudit(AuditOperation.FILE_PURGE)
public void deletePermanently(String... paths) {
if (paths == null || paths.length == 0) {
throw new TimiException(TimiCode.ARG_MISS, "缺少文件列表");
}
for (String path : paths) {
if (storage.isRoot(path)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不能删除根目录");
}
Path file = storage.resolveExisting(path);
try {
storage.deleteRecursively(file);
} catch (IOException e) {
throw new TimiException(TimiCode.ERROR, "删除失败:" + path);
}
} }
return basePath + path;
} }
} }
@@ -1,54 +1,118 @@
package com.imyeyu.api.modules.system.task.async; package com.imyeyu.api.modules.system.task.async;
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Level;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.entity.AsyncTask; import com.imyeyu.api.modules.system.entity.AsyncTask;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask;
import com.imyeyu.api.modules.system.vo.FileSizeResult;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import java.io.File; import java.io.IOException;
import java.util.ArrayDeque; import java.nio.file.FileVisitResult;
import java.util.Deque; import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.atomic.AtomicLong;
/** /**
* 计算文件夹大小(无法计算进度) * 统计文件夹大小。
*
* <p>使用虚拟路径遍历,不跟随符号链接,并跳过回收站、缩略图等内部目录。
* 由于目录总大小在遍历完成前无法预知,进度保持为不确定状态,结果通过任务 result 返回。</p>
* *
* @author 夜雨 * @author 夜雨
* @version 2022-08-21 21:36 * @version 2026-11-24
*/ */
public class FileCalcSizeAsyncTask extends AbstractAsyncTask { public class FileCalcSizeAsyncTask extends AbstractAsyncTask {
private final File file; private static final ObjectMapper MAPPER = new ObjectMapper();
public FileCalcSizeAsyncTask(File file) { private final String path;
this.file = file; private final FileStorageService storage;
type = AsyncTask.Type.FILE_CALC_SIZE; private final PermissionChecker permissionChecker;
private final String ownerUserId;
public FileCalcSizeAsyncTask(String path, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) {
this.path = path;
this.storage = storage;
this.permissionChecker = permissionChecker;
this.ownerUserId = ownerUserId;
this.type = AsyncTask.Type.FILE_CALC_SIZE;
this.name = "计算文件夹大小 " + path;
}
private void pause() {
try {
pauseInterruptHandle();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new TimiException(TimiCode.ERROR_SERVICE_OFF, "任务已中断");
}
} }
@Override @Override
protected void run() throws InterruptedException { protected void run() throws Exception {
long total = 0; FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_READ);
if (file != null && file.exists() && file.isDirectory()) { Path root = storage.resolveExisting(path);
// 左出右进,文件夹队列 if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) {
Deque<File> deque = new ArrayDeque<>(); throw new TimiException(TimiCode.ARG_BAD, "只能统计文件夹大小");
deque.addLast(file);
while (!deque.isEmpty()) {
File poll = deque.pollFirst();
pauseInterruptHandle();
if (poll.isDirectory()) {
File[] files = poll.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
deque.addLast(files[i]);
}
}
} else {
total += poll.length();
log(Level.INFO, String.valueOf(total));
}
}
} }
progress = 1;
long startAt = System.currentTimeMillis();
AtomicLong bytes = new AtomicLong();
AtomicLong files = new AtomicLong();
AtomicLong directories = new AtomicLong();
AtomicLong failed = new AtomicLong();
Files.walkFileTree(root, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
pause();
if (!dir.equals(root) && storage.isInternal(dir)) {
return FileVisitResult.SKIP_SUBTREE;
}
directories.incrementAndGet();
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
pause();
if (Files.isSymbolicLink(file)) {
return FileVisitResult.CONTINUE;
}
if (attrs.isRegularFile()) {
bytes.addAndGet(attrs.size());
files.incrementAndGet();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
failed.incrementAndGet();
log(Level.WARN, "跳过无法访问的文件:" + file + "," + e.getMessage());
return FileVisitResult.CONTINUE;
}
});
FileSizeResult result = new FileSizeResult(
path,
bytes.get(),
files.get(),
directories.get(),
failed.get(),
System.currentTimeMillis() - startAt
);
updateResult(MAPPER.writeValueAsString(result));
log(Level.INFO, "文件夹大小统计完成:" + result);
} }
} }
@@ -1,16 +1,18 @@
package com.imyeyu.api.modules.system.task.async; package com.imyeyu.api.modules.system.task.async;
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Level;
import com.imyeyu.io.IO; import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.entity.AsyncTask; import com.imyeyu.api.modules.system.entity.AsyncTask;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import java.io.File;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.StandardCopyOption; import java.nio.file.LinkOption;
import java.util.HashMap; import java.nio.file.Path;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* 文件复制 * 文件复制
@@ -22,51 +24,48 @@ public class FileCopyAsyncTask extends AbstractAsyncTask {
private final String to; private final String to;
private final List<String> fromList; private final List<String> fromList;
private final FileStorageService storage;
private final PermissionChecker permissionChecker;
public FileCopyAsyncTask(List<String> fromList, String to) { public FileCopyAsyncTask(List<String> fromList, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) {
this.fromList = fromList; this.fromList = fromList;
this.to = to; this.to = to;
this.storage = storage;
this.permissionChecker = permissionChecker;
this.ownerUserId = ownerUserId;
type = AsyncTask.Type.FILE_COPY; type = AsyncTask.Type.FILE_COPY;
} }
@Override @Override
protected void run() throws Exception { protected void run() throws Exception {
// 准备文件 Map<文件, 深度路径>,深度路径含文件名 FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE);
Map<File, String> fromList = new HashMap<>(); Path destination = FileTaskSupport.targetDirectory(storage, to);
File file; List<Path> sources = FileTaskSupport.sources(storage, fromList);
for (int i = 0; i < this.fromList.size(); i++) { for (Path source : sources) {
pauseInterruptHandle(); FileTaskSupport.ensureNotNested(source, destination);
file = new File(this.fromList.get(i));
if (file.exists()) {
if (file.isFile()) {
fromList.put(file, file.getName());
} else {
String basePath = file.getParentFile().getAbsolutePath();
List<File> files = IO.listFile(file);
for (int j = 0; j < files.size(); j++) {
fromList.put(files.get(j), files.get(j).getAbsolutePath().substring(basePath.length()));
}
}
}
} }
// 复制文件 List<FileTaskSupport.Entry> entries = FileTaskSupport.collect(sources, null);
int total = fromList.size(); int total = entries.size();
int i = 0; int index = 0;
for (Map.Entry<File, String> item : fromList.entrySet()) { for (FileTaskSupport.Entry entry : entries) {
pauseInterruptHandle(); pauseInterruptHandle();
log(Level.INFO, item.getKey().getName()); Path target = destination.resolve(entry.name()).normalize();
// 执行复制 if (!target.startsWith(destination)) {
{ throw new TimiException(TimiCode.PERMISSION_ERROR, "目标路径越界");
File toFile = new File(IO.fitPath(to) + item.getValue());
IO.dir(toFile.getParent());
Files.copy(item.getKey().toPath(), toFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} }
log(Level.INFO, entry.name());
// 更新进度 if (entry.directory()) {
progress = 1D * ++i / total; Files.createDirectories(target);
} else {
Files.createDirectories(target.getParent());
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.RESULT_BAD, "目标已存在:" + entry.name());
}
Files.copy(entry.path(), target);
}
progress = 1D * ++index / total;
} }
progress = 1; progress = 1;
} }
@@ -1,16 +1,18 @@
package com.imyeyu.api.modules.system.task.async; package com.imyeyu.api.modules.system.task.async;
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Level;
import com.imyeyu.io.IO; import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.entity.AsyncTask;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.bean.timi.TimiCode; import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException; import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.api.modules.system.entity.AsyncTask;
import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask;
import java.io.File; import java.nio.file.Files;
import java.util.HashMap; import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* 文件批量移动异步任务 * 文件批量移动异步任务
@@ -22,64 +24,42 @@ public class FileMoveAsyncTask extends AbstractAsyncTask {
private final String to; private final String to;
private final List<String> fromList; private final List<String> fromList;
private final FileStorageService storage;
private final PermissionChecker permissionChecker;
public FileMoveAsyncTask(List<String> fromList, String to) { public FileMoveAsyncTask(List<String> fromList, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) {
this.fromList = fromList; this.fromList = fromList;
this.to = to; this.to = to;
this.storage = storage;
this.permissionChecker = permissionChecker;
this.ownerUserId = ownerUserId;
type = AsyncTask.Type.FILE_MOVE; type = AsyncTask.Type.FILE_MOVE;
} }
@Override @Override
protected void run() throws Exception { protected void run() throws Exception {
// 准备文件 Map<文件, 深度路径>,深度路径含文件名 FileTaskSupport.require(permissionChecker, ownerUserId,
Map<File, String> fromList = new HashMap<>(); CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE, CorePermissionCode.FILE_DELETE);
File file; Path destination = FileTaskSupport.targetDirectory(storage, to);
for (int i = 0; i < this.fromList.size(); i++) { List<Path> sources = FileTaskSupport.sources(storage, fromList);
int total = sources.size();
int index = 0;
for (Path source : sources) {
pauseInterruptHandle(); pauseInterruptHandle();
file = new File(this.fromList.get(i)); FileTaskSupport.ensureNotNested(source, destination);
if (file.exists()) { Path target = destination.resolve(source.getFileName()).normalize();
if (file.isFile()) { if (target.equals(source)) {
fromList.put(file, file.getName()); throw new TimiException(TimiCode.ARG_BAD, "源路径与目标路径相同");
} else {
String basePath = file.getParentFile().getAbsolutePath();
List<File> files = IO.listFile(file);
for (int j = 0; j < files.size(); j++) {
fromList.put(files.get(j), files.get(j).getAbsolutePath().substring(basePath.length()));
}
}
} }
} if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
// 移动文件 throw new TimiException(TimiCode.RESULT_BAD, "目标已存在:" + storage.virtualPath(target));
int total = fromList.size();
int i = 0;
for (Map.Entry<File, String> item : fromList.entrySet()) {
pauseInterruptHandle();
log(Level.INFO, item.getKey().getName());
// 执行移动
{
File toFile = new File(IO.fitPath(to) + item.getValue());
IO.dir(toFile.getParent());
if (!item.getKey().renameTo(toFile)) {
throw new TimiException(TimiCode.ERROR, "移动失败:" + item.getKey().getAbsolutePath() + " -> " + toFile.getAbsolutePath());
}
} }
log(Level.INFO, storage.virtualPath(source));
// 更新进度 storage.move(source, target);
progress = 1D * ++i / total; progress = 1D * ++index / total;
} }
progress = 1; progress = 1;
// 删除已移动文件夹
for (int j = 0; j < this.fromList.size(); j++) {
pauseInterruptHandle();
file = new File(this.fromList.get(j));
if (file.exists()) {
IO.destroy(file);
}
}
} }
} }
@@ -1,150 +0,0 @@
package com.imyeyu.api.modules.system.task.async;
import ch.qos.logback.classic.Level;
import com.imyeyu.io.IO;
import com.imyeyu.io.TreeFile;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.api.modules.system.bean.FileSyncConfig;
import com.imyeyu.api.modules.system.entity.AsyncTask;
import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 文件同步任务
*
* @author 夜雨
* @version 2024-06-16 08:36
*/
public class FileSyncTask extends AbstractAsyncTask {
private final FileSyncConfig.Task config;
public FileSyncTask(String name, FileSyncConfig.Task config) {
this.config = config;
super.name = name;
isPeriodical = true;
cron = config.getCron();
type = AsyncTask.Type.FILE_SYNC;
List<String> targetList = config.getTargets();
String sourceAbsPath = new File(config.getSource()).getAbsolutePath();
for (int i = 0; i < targetList.size(); i++) {
File target = new File(targetList.get(i));
if (target.getAbsolutePath().startsWith(sourceAbsPath)) {
throw new TimiException(TimiCode.ERROR, "invalid target:%s that is in source:%s".formatted(target.getAbsolutePath(), sourceAbsPath));
}
}
}
@Override
protected void run() throws Exception {
// 扫描
setStatus(AsyncTask.Status.RUNNING);
log(Level.INFO, "building file tree");
// Map<目标, 来源>
Map<File, File> copyMap = new HashMap<>();
List<File> mkdirList = new ArrayList<>();
List<File> destoryList = new ArrayList<>();
List<String> targetList = config.getTargets();
List<TreeFile> targetTreeFileList = new ArrayList<>();
for (int i = 0; i < targetList.size(); i++) {
targetTreeFileList.add(new TreeFile(targetList.get(i)));
}
{
log(Level.INFO, "scanning path:%s".formatted(new File(config.getSource()).getAbsolutePath()));
TreeFile sourceTreeFile = new TreeFile(config.getSource());
sourceTreeFile.foreach((relPath, sourceFile) -> {
for (int i = 0; i < targetTreeFileList.size(); i++) {
// pauseInterruptHandle();
File targetFile = new File(IO.fitPath(targetTreeFileList.get(i).getAbsolutePath()) + relPath);
if (sourceFile.isFile()) {
if (!targetFile.exists() || targetFile.length() != sourceFile.length()) {
// 复制
if (config.isUseMD5Compare() && !IO.md5(targetFile).equals(IO.md5(sourceFile))) {
copyMap.put(targetFile, sourceFile);
} else {
copyMap.put(targetFile, sourceFile);
}
}
} else {
if (!targetFile.exists()) {
// 新建文件夹
mkdirList.add(targetFile);
}
}
}
});
// 删除
for (int i = 0; i < targetTreeFileList.size(); i++) {
TreeFile targetTreeFile = targetTreeFileList.get(i);
targetTreeFile.foreach((relPath, targetFile) -> {
// pauseInterruptHandle();
File sourceFile = new File(IO.fitPath(config.getSource()) + relPath);
if (!sourceFile.exists()) {
destoryList.add(targetFile);
}
});
}
}
// 执行
{
// 10% 进度用于操作创建文件夹和删除文件
int easyActionTTL = mkdirList.size() + destoryList.size();
int easyAction = 0;
for (int j = 0; j < mkdirList.size(); j++) {
pauseInterruptHandle();
log(Level.INFO, "making dir:%s".formatted(mkdirList.get(j).getAbsolutePath()));
IO.dir(mkdirList.get(j).getAbsolutePath());
progress = 1D * ++easyAction / easyActionTTL * .1;
}
for (int j = 0; j < destoryList.size(); j++) {
pauseInterruptHandle();
log(Level.INFO, "destroying file:%s".formatted(destoryList.get(j).getAbsolutePath()));
IO.destroy(destoryList.get(j));
progress = 1D * ++easyAction / easyActionTTL * .1;
}
progress = .1;
// 复制文件
long copySizeTTL = 0;
long copySize = 0;
List<File> copyList = new ArrayList<>(copyMap.values());
for (int i = 0; i < copyList.size(); i++) {
copySizeTTL += copyList.get(i).length();
}
for (Map.Entry<File, File> item : copyMap.entrySet()) {
pauseInterruptHandle();
log(Level.INFO, "copping file:%s to %s".formatted(item.getValue().getAbsolutePath(), item.getKey().getAbsolutePath()));
final long fileSize = item.getValue().length();
final long finalCopySize = copySize;
final long finalCopySizeTTL = copySizeTTL;
IO.copy(item.getValue(), item.getKey().getParentFile().getAbsolutePath(), new IO.OnWriteCallback() {
@Override
public boolean handler(long total, long now) {
progress = .1 + (1D * finalCopySize + total) / finalCopySizeTTL * .9;
return true;
}
});
copySize += fileSize;
}
}
progress = 1;
log(Level.INFO, "synced");
synchronized (this) {
wait(3000);
}
}
}
@@ -1,23 +1,26 @@
package com.imyeyu.api.modules.system.task.async; package com.imyeyu.api.modules.system.task.async;
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Level;
import com.imyeyu.io.IO; import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.entity.AsyncTask; import com.imyeyu.api.modules.system.entity.AsyncTask;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.File; import java.io.OutputStream;
import java.io.FileOutputStream; import java.nio.file.Files;
import java.util.HashMap; import java.nio.file.Path;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Locale;
/** /**
* 压缩 TAR * 压缩 TAR
* // TODO 可选是否压缩
* *
* @author 夜雨 * @author 夜雨
* @version 2022-08-16 16:54 * @version 2022-08-16 16:54
@@ -26,70 +29,66 @@ public class FileTarAsyncTask extends AbstractAsyncTask {
private final String to; private final String to;
private final List<String> fromList; private final List<String> fromList;
private final FileStorageService storage;
private final PermissionChecker permissionChecker;
public FileTarAsyncTask(List<String> fromList, String to) { public FileTarAsyncTask(List<String> fromList, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) {
this.fromList = fromList; this.fromList = fromList;
this.to = to; this.to = to;
this.storage = storage;
this.permissionChecker = permissionChecker;
this.ownerUserId = ownerUserId;
type = AsyncTask.Type.FILE_TAR; type = AsyncTask.Type.FILE_TAR;
} }
@Override @Override
protected void run() throws Exception { protected void run() throws Exception {
// 准备文件 Map<文件, 深度路径>,深度路径含文件名 FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE);
Map<File, String> fromList = new HashMap<>(); Path target = FileTaskSupport.targetFile(storage, to);
File file; List<Path> sources = FileTaskSupport.sources(storage, fromList);
for (int i = 0; i < this.fromList.size(); i++) { if (sources.stream().anyMatch(source -> source.equals(target))) {
pauseInterruptHandle(); throw new TimiException(TimiCode.ARG_BAD, "压缩目标不能是源文件");
file = new File(this.fromList.get(i));
if (file.exists()) {
if (file.isFile()) {
fromList.put(file, file.getName());
} else {
String basePath = file.getParentFile().getAbsolutePath();
List<File> files = IO.listFile(file);
for (int j = 0; j < files.size(); j++) {
fromList.put(files.get(j), files.get(j).getAbsolutePath().substring(basePath.length()));
}
}
}
} }
if (sources.stream().anyMatch(source -> target.startsWith(source))) {
// 压缩文件 throw new TimiException(TimiCode.ARG_BAD, "压缩目标不能位于源目录内");
int total = fromList.size(); }
int i = 0; FileTaskSupport.ensureParent(target);
List<FileTaskSupport.Entry> entries = FileTaskSupport.collect(sources, target);
FileOutputStream fos = new FileOutputStream(to); Path temporary = FileTaskSupport.temporarySibling(target);
BufferedOutputStream bos = new BufferedOutputStream(fos);
GzipCompressorOutputStream gcos = new GzipCompressorOutputStream(bos);
TarArchiveOutputStream taos = new TarArchiveOutputStream(gcos);
try { try {
String lower = to.toLowerCase(Locale.ROOT);
boolean gzip = lower.endsWith(".gz") || lower.endsWith(".tgz");
try (OutputStream fileOutput = new BufferedOutputStream(Files.newOutputStream(temporary), 64 * 1024);
OutputStream archiveOutput = gzip ? new GzipCompressorOutputStream(fileOutput) : fileOutput;
TarArchiveOutputStream tar = new TarArchiveOutputStream(archiveOutput)) {
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
tar.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
int total = entries.size();
int index = 0;
for (FileTaskSupport.Entry entry : entries) {
pauseInterruptHandle();
TarArchiveEntry tarEntry; log(Level.INFO, entry.name());
for (Map.Entry<File, String> item : fromList.entrySet()) { if (entry.directory()) {
pauseInterruptHandle(); TarArchiveEntry tarEntry = new TarArchiveEntry(entry.name() + "/");
tarEntry.setSize(0);
log(Level.INFO, item.getKey().getName()); tar.putArchiveEntry(tarEntry);
// 执行压缩 } else {
{ TarArchiveEntry tarEntry = new TarArchiveEntry(entry.path().toFile(), entry.name());
tarEntry = new TarArchiveEntry(item.getKey(), item.getValue()); tarEntry.setSize(Files.size(entry.path()));
taos.putArchiveEntry(tarEntry); tar.putArchiveEntry(tarEntry);
taos.write(IO.toBytes(item.getKey())); Files.copy(entry.path(), tar);
taos.closeArchiveEntry(); }
tar.closeArchiveEntry();
progress = 1D * ++index / total;
} }
// 更新进度
progress = 1D * ++i / total;
} }
FileTaskSupport.replace(temporary, target);
progress = 1; progress = 1;
} catch (Exception e) {
} finally { FileTaskSupport.deleteQuietly(temporary);
taos.finish(); throw e;
taos.close();
gcos.close();
bos.close();
fos.close();
} }
} }
} }
@@ -0,0 +1,191 @@
package com.imyeyu.api.modules.system.task.async;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/// 文件异步任务的公共路径、权限与归档辅助方法。
final class FileTaskSupport {
private FileTaskSupport() {
}
/// 异步任务执行前按创建人复核权限,避免任务创建后权限被撤销仍继续执行。
static void require(PermissionChecker permissionChecker, String userId, CorePermissionCode... codes) {
if (userId == null || userId.isBlank()) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "任务缺少创建人");
}
Set<String> codeSet = permissionChecker.codeSet(userId);
for (CorePermissionCode code : codes) {
if (!codeSet.contains(ModuleCode.CORE.name() + ":" + code.getValue())) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "权限不足:" + code.getValue());
}
}
}
/// 解析并去重源路径,父目录已包含时跳过其子路径。
static List<Path> sources(FileStorageService storage, List<String> virtualPaths) {
List<Path> resolved = new ArrayList<>();
for (String virtualPath : virtualPaths) {
if (storage.isRoot(virtualPath)) {
throw new TimiException(TimiCode.ARG_BAD, "不能操作根目录");
}
resolved.add(storage.resolveExisting(virtualPath));
}
resolved.sort(Comparator.comparingInt(Path::getNameCount));
List<Path> result = new ArrayList<>();
for (Path path : resolved) {
boolean nested = result.stream().anyMatch(parent -> path.startsWith(parent) && !path.equals(parent));
if (!nested) {
result.add(path);
}
}
return result;
}
/// 解析并创建目标目录。
static Path targetDirectory(FileStorageService storage, String virtualPath) throws IOException {
Path target = storage.resolve(virtualPath);
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS) && !Files.isDirectory(target, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.ARG_BAD, "目标不是目录");
}
Files.createDirectories(target);
return target;
}
/// 解析目标文件,不创建目标本身或父目录。
static Path targetFile(FileStorageService storage, String virtualPath) throws IOException {
Path target = storage.resolve(virtualPath);
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS) && Files.isDirectory(target, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.ARG_BAD, "目标不是文件");
}
if (target.getParent() == null) {
throw new TimiException(TimiCode.ARG_BAD, "目标路径不合法");
}
return target;
}
/// 创建目标文件的父目录。
static void ensureParent(Path target) throws IOException {
Path parent = target.getParent();
if (parent == null) {
throw new TimiException(TimiCode.ARG_BAD, "目标路径不合法");
}
Files.createDirectories(parent);
}
/// 防止把目录复制/移动到自身内部。
static void ensureNotNested(Path source, Path destination) {
if (destination.equals(source) || destination.startsWith(source)) {
throw new TimiException(TimiCode.ARG_BAD, "目标不能位于源目录内");
}
}
/// 收集源文件与空目录,保留源名称作为归档/复制后的第一层路径。
static List<Entry> collect(List<Path> sources, Path exclude) throws IOException {
List<Entry> entries = new ArrayList<>();
Set<String> names = new HashSet<>();
for (Path source : sources) {
if (Files.isSymbolicLink(source)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许操作符号链接");
}
String rootName = source.getFileName() == null ? "" : source.getFileName().toString();
if (rootName.isEmpty()) {
throw new TimiException(TimiCode.ARG_BAD, "源路径不合法");
}
if (Files.isDirectory(source, LinkOption.NOFOLLOW_LINKS)) {
Files.walkFileTree(source, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (Files.isSymbolicLink(dir)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许归档符号链接");
}
String relative = source.relativize(dir).toString().replace('\\', '/');
String name = relative.isEmpty() ? rootName : rootName + "/" + relative;
add(entries, names, new Entry(dir, name, true));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (Files.isSymbolicLink(file)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许归档符号链接");
}
String relative = source.relativize(file).toString().replace('\\', '/');
add(entries, names, new Entry(file, rootName + "/" + relative, false));
return FileVisitResult.CONTINUE;
}
});
} else {
add(entries, names, new Entry(source, rootName, false));
}
}
if (exclude != null) {
Path excluded = exclude.toAbsolutePath().normalize();
entries.removeIf(entry -> entry.path().toAbsolutePath().normalize().equals(excluded));
}
return entries;
}
private static void add(List<Entry> entries, Set<String> names, Entry entry) {
if (!names.add(entry.name())) {
throw new TimiException(TimiCode.ARG_BAD, "源文件名称重复:" + entry.name());
}
entries.add(entry);
}
/// 防止解压时通过已存在的符号链接目录逃逸。
static void ensureNoSymlink(Path root, Path target) {
Path current = root;
for (Path part : root.relativize(target)) {
current = current.resolve(part);
if (Files.isSymbolicLink(current)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许通过符号链接写入");
}
}
}
/// 在目标文件同目录创建临时文件,成功后原子替换目标。
static Path temporarySibling(Path target) throws IOException {
return Files.createTempFile(target.getParent(), ".timi-archive-", ".part");
}
static void replace(Path temporary, Path target) throws IOException {
try {
Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING);
}
}
static void deleteQuietly(Path path) {
if (path == null) {
return;
}
try {
Files.deleteIfExists(path);
} catch (IOException ignored) {
}
}
record Entry(Path path, String name, boolean directory) {
}
}
@@ -1,17 +1,25 @@
package com.imyeyu.api.modules.system.task.async; package com.imyeyu.api.modules.system.task.async;
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Level;
import com.imyeyu.io.IO; import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.entity.AsyncTask; import com.imyeyu.api.modules.system.entity.AsyncTask;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask;
import org.apache.commons.compress.archivers.ArchiveEntry; import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import java.io.File; import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
/** /**
* 解压 TAR * 解压 TAR
@@ -21,91 +29,119 @@ import java.io.IOException;
*/ */
public class FileUnTarAsyncTask extends AbstractAsyncTask { public class FileUnTarAsyncTask extends AbstractAsyncTask {
private final File tarFile; private static final int MAX_ENTRIES = 100_000;
private final String unTarTo; private static final long MAX_RATIO = 1_000;
private static final long MIN_RATIO_SIZE = 10L * 1024 * 1024;
public FileUnTarAsyncTask(File tarFile, String unTarTo) { private final String from;
this.tarFile = tarFile; private final String to;
this.unTarTo = unTarTo; private final FileStorageService storage;
private final PermissionChecker permissionChecker;
public FileUnTarAsyncTask(String from, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) {
this.from = from;
this.to = to;
this.storage = storage;
this.permissionChecker = permissionChecker;
this.ownerUserId = ownerUserId;
type = AsyncTask.Type.FILE_UNTAR; type = AsyncTask.Type.FILE_UNTAR;
} }
@Override @Override
protected void run() throws Exception { protected void run() throws Exception {
int total = getTotal(); FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_WRITE);
Path tarPath = storage.resolveExisting(from);
// 解压 if (!Files.isRegularFile(tarPath, LinkOption.NOFOLLOW_LINKS)) {
FileInputStream fis = new FileInputStream(tarFile); throw new TimiException(TimiCode.ARG_BAD, "压缩文件不存在");
GzipCompressorInputStream gcis = null;
TarArchiveInputStream tais;
if (tarFile.getName().endsWith("gz")) {
gcis = new GzipCompressorInputStream(fis);
tais = new TarArchiveInputStream(gcis);
} else {
tais = new TarArchiveInputStream(fis);
} }
try { Path destination = FileTaskSupport.targetDirectory(storage, to);
TarArchiveEntry entry; long maxTotal = storage.maxUploadSize();
int i = 0;
while ((entry = (TarArchiveEntry) tais.getNextEntry()) != null) {
pauseInterruptHandle();
String path = IO.fitPath(unTarTo) + entry.getName();
log(Level.INFO, path);
// 执行解压
if (entry.isDirectory()) {
IO.dir(path);
} else {
IO.toFile(IO.file(path), tais);
// 更新进度(total 只包含文件)
progress = 1D * ++i / total;
}
}
progress = 1;
} finally {
tais.close();
if (gcis != null) {
gcis.close();
}
fis.close();
}
}
private int getTotal() throws IOException, InterruptedException {
int total = 0; int total = 0;
{ long declaredSize = 0;
// 统计文件数量 try (TarArchiveInputStream tar = new TarArchiveInputStream(open(tarPath))) {
FileInputStream fis = new FileInputStream(tarFile); TarArchiveEntry entry;
GzipCompressorInputStream gcis = null; int entryCount = 0;
TarArchiveInputStream tais; while ((entry = tar.getNextTarEntry()) != null) {
if (tarFile.getName().endsWith("gz")) { if (++entryCount > MAX_ENTRIES) {
gcis = new GzipCompressorInputStream(fis); throw new TimiException(TimiCode.ARG_BAD, "压缩包条目过多");
tais = new TarArchiveInputStream(gcis); }
} else { if (entry.isSymbolicLink() || entry.isLink()) {
tais = new TarArchiveInputStream(fis); throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许解压链接文件");
} }
if (!entry.isDirectory()) {
try { ++total;
ArchiveEntry entry; declaredSize += Math.max(0, entry.getSize());
while ((entry = tais.getNextEntry()) != null) { if (declaredSize > maxTotal) {
pauseInterruptHandle(); throw new TimiException(TimiCode.ARG_BAD, "解压后大小超过限制");
if (!entry.isDirectory()) {
++total;
} }
} }
} finally {
tais.close();
if (gcis != null) {
gcis.close();
}
fis.close();
} }
} }
return total; if (declaredSize > MIN_RATIO_SIZE && Files.size(tarPath) > 0
&& declaredSize / Files.size(tarPath) > MAX_RATIO) {
throw new TimiException(TimiCode.ARG_BAD, "压缩比异常");
}
long totalWritten = 0;
int index = 0;
try (TarArchiveInputStream tar = new TarArchiveInputStream(open(tarPath))) {
TarArchiveEntry entry;
while ((entry = tar.getNextTarEntry()) != null) {
pauseInterruptHandle();
if (entry.isSymbolicLink() || entry.isLink()) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许解压链接文件");
}
Path target = target(destination, entry.getName());
log(Level.INFO, entry.getName());
if (entry.isDirectory()) {
Files.createDirectories(target);
} else {
Files.createDirectories(target.getParent());
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.RESULT_BAD, "目标已存在:" + entry.getName());
}
try (OutputStream output = Files.newOutputStream(target, StandardOpenOption.CREATE_NEW)) {
byte[] buffer = new byte[64 * 1024];
int length;
while ((length = tar.read(buffer)) != -1) {
totalWritten += length;
if (totalWritten > maxTotal) {
throw new TimiException(TimiCode.ARG_BAD, "解压后大小超过限制");
}
output.write(buffer, 0, length);
}
} catch (Exception e) {
Files.deleteIfExists(target);
throw e;
}
progress = 1D * ++index / total;
}
}
}
progress = 1;
}
private InputStream open(Path path) throws IOException {
BufferedInputStream input = new BufferedInputStream(Files.newInputStream(path));
input.mark(2);
int first = input.read();
int second = input.read();
input.reset();
return first == 0x1f && second == 0x8b ? new GzipCompressorInputStream(input) : input;
}
private Path target(Path destination, String name) {
if (name == null || name.isBlank() || name.indexOf('\\') >= 0 || name.startsWith("/")) {
throw new TimiException(TimiCode.ARG_BAD, "压缩包路径不合法");
}
Path target = destination.resolve(name).normalize();
if (!target.startsWith(destination)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "压缩包路径越界");
}
FileTaskSupport.ensureNoSymlink(destination, target);
return target;
} }
} }
@@ -1,19 +1,24 @@
package com.imyeyu.api.modules.system.task.async; package com.imyeyu.api.modules.system.task.async;
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Level;
import com.imyeyu.io.IO; import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.java.TimiJava;
import com.imyeyu.api.modules.system.entity.AsyncTask; import com.imyeyu.api.modules.system.entity.AsyncTask;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream; import java.io.InputStream;
import java.util.Enumeration; import java.io.OutputStream;
import java.util.zip.ZipEntry; import java.nio.file.Files;
import java.util.zip.ZipFile; import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
import java.util.List;
/** /**
* 解压缩 ZIP * 解压缩 ZIP
@@ -21,73 +26,105 @@ import java.util.zip.ZipFile;
* @author 夜雨 * @author 夜雨
* @version 2022-08-15 16:58 * @version 2022-08-15 16:58
*/ */
public class FileUnZipAsyncTask extends AbstractAsyncTask implements TimiJava { public class FileUnZipAsyncTask extends AbstractAsyncTask {
private final File zipFile; private static final int MAX_ENTRIES = 100_000;
private final String unZipTo; private static final long MAX_RATIO = 1_000;
private static final long MIN_RATIO_SIZE = 10L * 1024 * 1024;
public FileUnZipAsyncTask(File zipFile, String unZipTo) { private final String from;
this.zipFile = zipFile; private final String to;
this.unZipTo = unZipTo; private final FileStorageService storage;
private final PermissionChecker permissionChecker;
public FileUnZipAsyncTask(String from, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) {
this.from = from;
this.to = to;
this.storage = storage;
this.permissionChecker = permissionChecker;
this.ownerUserId = ownerUserId;
type = AsyncTask.Type.FILE_UNZIP; type = AsyncTask.Type.FILE_UNZIP;
} }
@Override @Override
@SuppressWarnings("unchecked")
protected void run() throws Exception { protected void run() throws Exception {
ZipFile zip = new ZipFile(zipFile); FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_WRITE);
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries(); Path zipPath = storage.resolveExisting(from);
if (!Files.isRegularFile(zipPath, LinkOption.NOFOLLOW_LINKS)) {
// 统计数量 throw new TimiException(TimiCode.ARG_BAD, "压缩文件不存在");
int total = 0;
while (entries.hasMoreElements()) {
if (!entries.nextElement().isDirectory()) {
++total;
}
} }
Path destination = FileTaskSupport.targetDirectory(storage, to);
long maxTotal = storage.maxUploadSize();
long totalWritten = 0;
// 解压 try (ZipFile zip = new ZipFile(zipPath.toFile())) {
ZipEntry entry; List<ZipArchiveEntry> entries = Collections.list(zip.getEntries());
if (entries.size() > MAX_ENTRIES) {
InputStream is; throw new TimiException(TimiCode.ARG_BAD, "压缩包条目过多");
FileOutputStream fos; }
BufferedInputStream bis; long declaredSize = 0;
BufferedOutputStream bos; for (ZipArchiveEntry entry : entries) {
entries = (Enumeration<ZipEntry>) zip.entries(); if (entry.getSize() > 0) {
for (int i = 0; entries.hasMoreElements(); i++) { declaredSize += entry.getSize();
pauseInterruptHandle(); if (declaredSize > maxTotal) {
throw new TimiException(TimiCode.ARG_BAD, "解压后大小超过限制");
entry = entries.nextElement(); }
String path = IO.fitPath(unZipTo) + entry.getName(); if (entry.getSize() > MIN_RATIO_SIZE && entry.getCompressedSize() > 0
&& entry.getSize() / entry.getCompressedSize() > MAX_RATIO) {
log(Level.INFO, path); throw new TimiException(TimiCode.ARG_BAD, "压缩比异常");
// 执行解压 }
{
File entryFile = IO.file(path);
is = zip.getInputStream(entry);
bis = new BufferedInputStream(is);
fos = new FileOutputStream(entryFile);
bos = new BufferedOutputStream(fos);
int l;
byte[] buffer = new byte[4096];
while ((l = bis.read(buffer)) != -1) {
bos.write(buffer, 0, l);
} }
} }
bos.flush(); int total = entries.size();
bos.close(); int index = 0;
fos.close(); for (ZipArchiveEntry entry : entries) {
bis.close(); pauseInterruptHandle();
is.close();
progress = 1D * i / total; if (entry.isUnixSymlink()) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许解压符号链接");
}
Path target = target(destination, entry.getName());
log(Level.INFO, entry.getName());
if (entry.isDirectory()) {
Files.createDirectories(target);
} else {
Files.createDirectories(target.getParent());
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
throw new TimiException(TimiCode.RESULT_BAD, "目标已存在:" + entry.getName());
}
try (InputStream input = zip.getInputStream(entry);
OutputStream output = Files.newOutputStream(target, StandardOpenOption.CREATE_NEW)) {
byte[] buffer = new byte[64 * 1024];
int length;
while ((length = input.read(buffer)) != -1) {
totalWritten += length;
if (totalWritten > maxTotal) {
throw new TimiException(TimiCode.ARG_BAD, "解压后大小超过限制");
}
output.write(buffer, 0, length);
}
} catch (Exception e) {
Files.deleteIfExists(target);
throw e;
}
}
progress = 1D * ++index / total;
}
} }
zip.close();
progress = 1; progress = 1;
} }
private Path target(Path destination, String name) {
if (name == null || name.isBlank() || name.indexOf('\\') >= 0 || name.startsWith("/")) {
throw new TimiException(TimiCode.ARG_BAD, "压缩包路径不合法");
}
Path target = destination.resolve(name).normalize();
if (!target.startsWith(destination)) {
throw new TimiException(TimiCode.PERMISSION_ERROR, "压缩包路径越界");
}
FileTaskSupport.ensureNoSymlink(destination, target);
return target;
}
} }
@@ -1,19 +1,19 @@
package com.imyeyu.api.modules.system.task.async; package com.imyeyu.api.modules.system.task.async;
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Level;
import com.imyeyu.io.IO; import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.entity.AsyncTask; import com.imyeyu.api.modules.system.entity.AsyncTask;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import java.io.BufferedInputStream; import java.io.BufferedOutputStream;
import java.io.File; import java.io.InputStream;
import java.io.FileInputStream; import java.nio.file.Files;
import java.io.FileOutputStream; import java.nio.file.Path;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
@@ -27,90 +27,57 @@ public class FileZipAsyncTask extends AbstractAsyncTask {
private final String to; private final String to;
private final List<String> fromList; private final List<String> fromList;
private final FileStorageService storage;
private final PermissionChecker permissionChecker;
public FileZipAsyncTask(List<String> fromList, String to) { public FileZipAsyncTask(List<String> fromList, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) {
this.fromList = fromList; this.fromList = fromList;
this.to = to; this.to = to;
this.storage = storage;
this.permissionChecker = permissionChecker;
this.ownerUserId = ownerUserId;
type = AsyncTask.Type.FILE_ZIP; type = AsyncTask.Type.FILE_ZIP;
} }
@Override @Override
protected void run() throws Exception { protected void run() throws Exception {
// 准备文件 Map<文件, 深度路径>,深度路径含文件名 FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE);
Map<File, String> fromList = new HashMap<>(); Path target = FileTaskSupport.targetFile(storage, to);
File file; List<Path> sources = FileTaskSupport.sources(storage, fromList);
for (int i = 0; i < this.fromList.size(); i++) { if (sources.stream().anyMatch(source -> source.equals(target))) {
pauseInterruptHandle(); throw new TimiException(TimiCode.ARG_BAD, "压缩目标不能是源文件");
file = new File(this.fromList.get(i));
if (file.exists()) {
if (file.isFile()) {
fromList.put(file, file.getName());
} else {
String basePath = file.getParentFile().getAbsolutePath();
List<File> files = IO.listFile(file);
for (int j = 0; j < files.size(); j++) {
fromList.put(files.get(j), files.get(j).getAbsolutePath().substring(basePath.length()));
}
}
}
} }
// 压缩文件 if (sources.stream().anyMatch(source -> target.startsWith(source))) {
int total = fromList.size(); throw new TimiException(TimiCode.ARG_BAD, "压缩目标不能位于源目录内");
int i = 0; }
FileTaskSupport.ensureParent(target);
ZipOutputStream zos = null; List<FileTaskSupport.Entry> entries = FileTaskSupport.collect(sources, target);
CheckedOutputStream cos = null; Path temporary = FileTaskSupport.temporarySibling(target);
FileOutputStream fos = null;
try { try {
File zipFile = IO.file(to); try (ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temporary), 64 * 1024))) {
int total = entries.size();
int index = 0;
for (FileTaskSupport.Entry entry : entries) {
pauseInterruptHandle();
fos = new FileOutputStream(zipFile); log(Level.INFO, entry.name());
cos = new CheckedOutputStream(fos, new CRC32()); ZipEntry zipEntry = new ZipEntry(entry.directory() ? entry.name() + "/" : entry.name());
zos = new ZipOutputStream(cos); zip.putNextEntry(zipEntry);
if (!entry.directory()) {
for (Map.Entry<File, String> item : fromList.entrySet()) { try (InputStream input = Files.newInputStream(entry.path())) {
pauseInterruptHandle(); input.transferTo(zip);
}
log(Level.INFO, item.getKey().getName());
// 执行压缩
{
ZipEntry entry = new ZipEntry(item.getValue());
zos.putNextEntry(entry);
FileInputStream fis = new FileInputStream(item.getKey());
BufferedInputStream bis = new BufferedInputStream(fis);
int l;
byte[] buffer = new byte[4096];
while ((l = bis.read(buffer)) != -1) {
zos.write(buffer, 0, l);
} }
zip.closeEntry();
bis.close(); progress = 1D * ++index / total;
fis.close();
zos.closeEntry();
} }
// 更新进度
progress = 1D * ++i / total;
} }
FileTaskSupport.replace(temporary, target);
progress = 1; progress = 1;
} catch (Exception e) {
} finally { FileTaskSupport.deleteQuietly(temporary);
if (zos != null) { throw e;
zos.flush();
zos.close();
}
if (cos != null) {
cos.flush();
cos.close();
}
if (fos != null) {
fos.flush();
fos.close();
}
} }
} }
} }
@@ -1,64 +0,0 @@
package com.imyeyu.api.modules.system.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.common.entity.Setting;
import com.imyeyu.api.modules.common.service.SettingService;
import com.imyeyu.api.modules.system.bean.AccessKey;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.TimiSpring;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 夜雨
* @version 2023-11-23 17:09
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class SystemAPIInterceptor implements HandlerInterceptor {
public static final String PATH = "/system/**";
private static final String HIGH_AUTHORITY = "SYSTEM_API_HIGH_AUTHORITY_KEY";
private final ObjectMapper jackson;
private final SettingService settingService;
private final Map<String, Boolean> keyMap = new HashMap<>();
@PostConstruct
private void postConstruct() throws JsonProcessingException {
// List<AccessKey> list = jackson.readValue(settingService.getSystem(Setting.Module.System.API_KEY).asString(), new TypeReference<>() {});
// for (AccessKey key : list) {
// keyMap.put(key.getValue(), key.getHighAuthority());
// }
}
public boolean preHandle(@NonNull HttpServletRequest req, @NonNull HttpServletResponse resp, @NonNull Object handler) {
// String key = TimiSpring.getKey();
// if (keyMap.containsKey(key)) {
// TimiSpring.setRequestAttr(HIGH_AUTHORITY, keyMap.get(key));
// return true;
// }
// throw new TimiException(TimiCode.PERMISSION_ERROR, "TODO invalid key");
return true;
}
public boolean isHighAuthorityKey() {
// return TimiSpring.getRequestAttr(HIGH_AUTHORITY, Boolean.class);
return true;
}
}
@@ -0,0 +1,9 @@
package com.imyeyu.api.modules.system.vo;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;
public record ArchiveRequest(@NotEmpty List<@NotBlank String> list, @NotBlank String to) {
}
@@ -0,0 +1,33 @@
package com.imyeyu.api.modules.system.vo;
import com.imyeyu.api.modules.system.entity.AsyncTask;
/**
* 异步任务 SSE 事件快照。
*
* @param id 任务 ID
* @param name 任务名称
* @param type 任务类型
* @param status 当前状态
* @param progress 进度,-1 表示无法计算进度
* @param message 最近日志
* @param result 任务结果(通常为 JSON 字符串)
* @param createdAt 创建时间
* @param startAt 开始时间
* @param completedAt 完成时间
* @author 夜雨
* @version 2026-11-24
*/
public record AsyncTaskEvent(
String id,
String name,
AsyncTask.Type type,
AsyncTask.Status status,
double progress,
String message,
String result,
long createdAt,
long startAt,
long completedAt
) {
}
@@ -0,0 +1,9 @@
package com.imyeyu.api.modules.system.vo;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;
public record FileListRequest(@NotEmpty List<@NotBlank String> list) {
}
@@ -0,0 +1,23 @@
package com.imyeyu.api.modules.system.vo;
/**
* 文件夹大小统计结果。
*
* @param path 统计的虚拟路径
* @param bytes 文件总字节数
* @param files 文件数量
* @param directories 目录数量(包含被统计的根目录)
* @param failed 无法访问而跳过的条目数量
* @param durationMillis 统计耗时(毫秒)
* @author 夜雨
* @version 2026-11-24
*/
public record FileSizeResult(
String path,
long bytes,
long files,
long directories,
long failed,
long durationMillis
) {
}
@@ -0,0 +1,7 @@
package com.imyeyu.api.modules.system.vo;
import jakarta.validation.constraints.NotBlank;
/// 通用 ID 请求
public record IdRequest(@NotBlank String id) {
}
@@ -0,0 +1,6 @@
package com.imyeyu.api.modules.system.vo;
import jakarta.validation.constraints.NotBlank;
public record MkdirRequest(@NotBlank String path, @NotBlank String name) {
}
@@ -0,0 +1,6 @@
package com.imyeyu.api.modules.system.vo;
import jakarta.validation.constraints.NotBlank;
public record PathRequest(@NotBlank String path) {
}
@@ -0,0 +1,6 @@
package com.imyeyu.api.modules.system.vo;
import jakarta.validation.constraints.NotBlank;
public record RenameRequest(@NotBlank String from, @NotBlank String to) {
}
@@ -0,0 +1,6 @@
package com.imyeyu.api.modules.system.vo;
import jakarta.validation.constraints.NotBlank;
public record SearchRequest(@NotBlank String path, @NotBlank String keyword) {
}
@@ -0,0 +1,6 @@
package com.imyeyu.api.modules.system.vo;
import jakarta.validation.constraints.NotBlank;
public record ShareCreateRequest(@NotBlank String path, String password, Long expiresAt, Integer maxDownloads) {
}
@@ -0,0 +1,6 @@
package com.imyeyu.api.modules.system.vo;
import jakarta.validation.constraints.NotBlank;
public record UnarchiveRequest(@NotBlank String file, @NotBlank String to) {
}
@@ -0,0 +1,6 @@
package com.imyeyu.api.modules.system.vo;
import jakarta.validation.constraints.NotBlank;
public record UploadCompleteRequest(@NotBlank String uploadId, String sha256) {
}
@@ -0,0 +1,7 @@
package com.imyeyu.api.modules.system.vo;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.PositiveOrZero;
public record UploadInitRequest(@NotBlank String path, @NotBlank String name, @PositiveOrZero long size, String sha256) {
}
@@ -0,0 +1,15 @@
CREATE TABLE `file_trash`
(
`id` VARCHAR(36) NOT NULL COMMENT '主键',
`original_path` VARCHAR(4096) NOT NULL COMMENT '删除前的虚拟路径',
`trash_name` VARCHAR(64) NOT NULL COMMENT '回收站目录名',
`name` VARCHAR(255) NOT NULL COMMENT '文件或文件夹名称',
`size` BIGINT NOT NULL DEFAULT 0 COMMENT '文件大小,文件夹为 0',
`directory` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否为文件夹',
`owner_user_id` VARCHAR(36) NULL COMMENT '删除人用户 ID',
`deleted_at` BIGINT NOT NULL COMMENT '删除时间',
`expires_at` BIGINT NOT NULL COMMENT '过期时间',
PRIMARY KEY (`id`),
KEY `idx_file_trash_expires_at` (`expires_at`),
KEY `idx_file_trash_deleted_at` (`deleted_at`)
) COMMENT = '文件回收站';
@@ -0,0 +1,24 @@
CREATE TABLE `file_share`
(
`id` varchar(36) NOT NULL COMMENT '主键',
`token` varchar(64) NOT NULL COMMENT '分享令牌',
`path` varchar(4096) NOT NULL COMMENT '文件虚拟路径',
`name` varchar(255) NOT NULL COMMENT '文件名',
`owner_user_id` varchar(36) NULL COMMENT '创建人',
`password_hash` varchar(255) NULL COMMENT '密码哈希',
`file_hash` varchar(64) NULL COMMENT '文件 SHA-256',
`file_size` bigint NOT NULL DEFAULT 0 COMMENT '分享时文件大小',
`file_modified_at` bigint NOT NULL DEFAULT 0 COMMENT '分享时文件修改时间',
`expires_at` bigint NOT NULL COMMENT '过期时间',
`max_downloads` int NOT NULL DEFAULT 0 COMMENT '最大下载次数,0 不限',
`download_count` int NOT NULL DEFAULT 0 COMMENT '已下载次数',
`last_access_at` bigint NOT NULL DEFAULT 0 COMMENT '最后访问时间',
`created_at` bigint NOT NULL COMMENT '创建时间',
`deleted_at` bigint NOT NULL DEFAULT 0 COMMENT '删除时间,0 未删除',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_file_share_token` (`token`),
KEY `idx_file_share_owner` (`owner_user_id`),
KEY `idx_file_share_expires` (`expires_at`),
KEY `idx_file_share_deleted` (`deleted_at`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4 COMMENT = '文件分享';
@@ -0,0 +1,94 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.modules.system.util.ResourceHandler;
import com.imyeyu.java.bean.timi.TimiException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/// 文件内容服务测试。
class FileContentServiceTest {
@TempDir
Path temp;
private FileContentService service;
private ResourceHandler resourceHandler;
@BeforeEach
void setUp() throws IOException {
FileStorageService storage = FileTestSupport.storage(temp, Map.of());
resourceHandler = mock(ResourceHandler.class);
service = new FileContentService(storage, mock(ThumbnailService.class), resourceHandler);
}
@Test
void detectsMimeTypeAndDangerousAttachment() throws IOException {
Files.writeString(temp.resolve("a.txt"), "hello", StandardCharsets.UTF_8);
Files.writeString(temp.resolve("a.html"), "<script>alert(1)</script>", StandardCharsets.UTF_8);
FileContentService.ContentInfo text = service.info("/a.txt");
assertEquals("text/plain", text.mimeType());
assertFalse(text.attachment());
assertNotNull(text.etag());
FileContentService.ContentInfo html = service.info("/a.html");
assertEquals("text/html", html.mimeType());
assertTrue(html.attachment());
}
@Test
void rejectsDangerousPreview() throws IOException {
Files.writeString(temp.resolve("a.html"), "<script>alert(1)</script>", StandardCharsets.UTF_8);
assertThrows(TimiException.class, () -> service.preview(new MockHttpServletRequest(),
new MockHttpServletResponse(), "/a.html"));
}
@Test
void servesNotModified() throws Exception {
Files.writeString(temp.resolve("a.txt"), "hello", StandardCharsets.UTF_8);
FileContentService.ContentInfo info = service.info("/a.txt");
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/system/file/read/a.txt");
req.addHeader("If-None-Match", info.etag());
MockHttpServletResponse resp = new MockHttpServletResponse();
service.serve(req, resp, "/a.txt", false);
assertEquals(304, resp.getStatus());
verify(resourceHandler, org.mockito.Mockito.never()).handleRequest(req, resp);
}
@Test
void servesWithCacheHeaders() throws Exception {
Files.writeString(temp.resolve("a.txt"), "hello", StandardCharsets.UTF_8);
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/system/file/read/a.txt");
MockHttpServletResponse resp = new MockHttpServletResponse();
service.serve(req, resp, "/a.txt", false);
assertEquals("text/plain", resp.getContentType());
assertNotNull(resp.getHeader("ETag"));
assertEquals("nosniff", resp.getHeader("X-Content-Type-Options"));
assertEquals("private, max-age=0, must-revalidate", resp.getHeader("Cache-Control"));
verify(resourceHandler).handleRequest(req, resp);
}
}
@@ -0,0 +1,102 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.modules.system.bean.ServerFile;
import com.imyeyu.api.modules.system.service.implement.FileServiceImplement;
import com.imyeyu.java.bean.timi.TimiException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/// 文件元数据服务测试。
class FileServiceImplementTest {
@TempDir
Path temp;
private FileStorageService storage;
private FileServiceImplement service;
@BeforeEach
void setUp() throws IOException {
storage = FileTestSupport.storage(temp, Map.of(
"SEARCH_MAX_RESULTS", "200",
"SEARCH_MAX_DEPTH", "32",
"SEARCH_TIMEOUT_SECONDS", "5"
));
service = new FileServiceImplement(storage);
}
@Test
void listsDirectoriesFirstAndHidesInternalDirectories() throws IOException {
Files.createDirectories(temp.resolve("b"));
Files.writeString(temp.resolve("a.txt"), "a");
Files.createDirectories(temp.resolve(".trash"));
List<ServerFile> list = service.list("/");
assertEquals(2, list.size());
assertTrue(Boolean.TRUE.equals(list.get(0).getDirectory()));
assertEquals("b", list.get(0).getName());
assertEquals("a.txt", list.get(1).getName());
assertFalse(list.stream().anyMatch(item -> ".trash".equals(item.getName())));
}
@Test
void createsAndRejectsDuplicateDirectory() {
ServerFile directory = service.mkdir("/", "new");
assertTrue(Boolean.TRUE.equals(directory.getDirectory()));
assertEquals("/new", directory.getPath());
assertThrows(TimiException.class, () -> service.mkdir("/", "new"));
assertThrows(TimiException.class, () -> service.mkdir("/", "../escape"));
}
@Test
void renamesFileWithoutOverwrite() throws IOException {
Files.writeString(temp.resolve("a.txt"), "a");
Files.writeString(temp.resolve("b.txt"), "b");
ServerFile renamed = service.rename("/a.txt", "/c.txt");
assertEquals("/c.txt", renamed.getPath());
assertTrue(Files.exists(temp.resolve("c.txt")));
assertFalse(Files.exists(temp.resolve("a.txt")));
assertThrows(TimiException.class, () -> service.rename("/c.txt", "/b.txt"));
assertThrows(TimiException.class, () -> service.rename("/", "/root"));
}
@Test
void searchesByKeyword() throws IOException {
Files.writeString(temp.resolve("Report.txt"), "a");
Files.createDirectories(temp.resolve("sub"));
Files.writeString(temp.resolve("sub/report-2026.txt"), "b");
FileService.SearchResult result = service.search("/", "report");
assertEquals(2, result.items().size());
assertFalse(result.truncated());
assertTrue(result.scanned() >= 2);
}
@Test
void opensOnlyRegularFilesAndDeletesRecursively() throws IOException {
Files.createDirectories(temp.resolve("dir/sub"));
Files.writeString(temp.resolve("dir/sub/a.txt"), "a");
assertThrows(TimiException.class, () -> service.open("/dir"));
try (var input = service.open("/dir/sub/a.txt")) {
assertEquals('a', input.read());
}
service.deletePermanently("/dir");
assertFalse(Files.exists(temp.resolve("dir")));
assertThrows(TimiException.class, () -> service.deletePermanently("/"));
}
}
@@ -0,0 +1,105 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.modules.system.entity.FileShare;
import com.imyeyu.api.modules.system.mapper.FileShareMapper;
import com.imyeyu.java.bean.timi.TimiException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/// 文件分享服务测试。
class FileShareServiceTest {
@TempDir
Path temp;
private FileStorageService storage;
private FileShareMapper mapper;
private FileShareService service;
@BeforeEach
void setUp() throws IOException {
storage = FileTestSupport.storage(temp, Map.of(
"SHARE_ENABLED", "true",
"SHARE_DEFAULT_EXPIRE_DAYS", "7"
));
mapper = mock(FileShareMapper.class);
service = new FileShareService(storage, mapper);
when(mapper.countByToken(anyString())).thenReturn(0);
}
@Test
void createsAndVerifiesPasswordProtectedShare() throws IOException {
Files.writeString(temp.resolve("a.txt"), "hello");
FileShare share = service.create("/a.txt", "secret", null, 2, "user-1");
assertNotNull(share.getToken());
assertEquals(0L, share.getDeletedAt());
assertNotNull(share.getPasswordHash());
assertNotNull(share.getFileHash());
when(mapper.selectActiveByToken(share.getToken())).thenReturn(share);
when(mapper.incrementDownload(eq(share.getId()), anyLong())).thenReturn(1);
assertThrows(TimiException.class, () -> service.open(share.getToken(), "wrong"));
assertEquals(share, service.open(share.getToken(), "secret"));
}
@Test
void rejectsExpiredAndExhaustedShare() throws IOException {
Files.writeString(temp.resolve("a.txt"), "hello");
FileShare expired = service.create("/a.txt", null, null, 0, "user-1");
expired.setExpiresAt(System.currentTimeMillis() - 1);
when(mapper.selectActiveByToken(expired.getToken())).thenReturn(expired);
assertThrows(TimiException.class, () -> service.open(expired.getToken(), null));
FileShare exhausted = service.create("/a.txt", null, null, 1, "user-1");
exhausted.setDownloadCount(1);
when(mapper.selectActiveByToken(exhausted.getToken())).thenReturn(exhausted);
assertThrows(TimiException.class, () -> service.open(exhausted.getToken(), null));
}
@Test
void rejectsDirectoryShare() {
assertThrows(TimiException.class, () -> service.create("/", null, null, 0, "user-1"));
}
@Test
void headDoesNotConsumeDownload() throws IOException {
Files.writeString(temp.resolve("a.txt"), "hello");
FileShare share = service.create("/a.txt", "secret", null, 2, "user-1");
when(mapper.selectActiveByToken(share.getToken())).thenReturn(share);
service.open(share.getToken(), "secret", false);
verify(mapper, never()).incrementDownload(anyString(), anyLong());
}
@Test
void rejectsAndInvalidatesChangedFile() throws IOException {
Path file = temp.resolve("a.txt");
Files.writeString(file, "hello");
FileShare share = service.create("/a.txt", null, null, 0, "user-1");
Files.writeString(file, "world");
Files.setLastModifiedTime(file, java.nio.file.attribute.FileTime.fromMillis(share.getFileModifiedAt() + 1000));
when(mapper.selectActiveByToken(share.getToken())).thenReturn(share);
assertThrows(TimiException.class, () -> service.open(share.getToken(), null));
verify(mapper).softDelete(eq(share.getId()), anyLong());
}
}
@@ -0,0 +1,104 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.bean.SettingEnum;
import com.imyeyu.api.modules.common.entity.Setting;
import com.imyeyu.api.modules.common.service.SettingService;
import com.imyeyu.api.modules.system.bean.SystemFileSetting;
import com.imyeyu.java.bean.timi.TimiException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.test.util.ReflectionTestUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.abort;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/// 文件存储路径安全测试。
class FileStorageServiceTest {
@TempDir
Path temp;
private FileStorageService storage;
@BeforeEach
void setUp() throws IOException {
storage = FileTestSupport.storage(temp, Map.of());
}
@Test
void initializesWithMissingOptionalSettings() throws Exception {
SettingService settingService = mock(SettingService.class);
when(settingService.getSystem(any())).thenAnswer(invocation -> {
SettingEnum key = invocation.getArgument(0);
if (key == SystemFileSetting.BASE_PATH) {
Setting base = new Setting();
base.setValue(temp.toString());
return base;
}
return null;
});
FileStorageService service = new FileStorageService(settingService);
ReflectionTestUtils.invokeMethod(service, "initialize");
assertEquals(temp.toRealPath(), service.basePath());
assertTrue(Files.isDirectory(temp.resolve(".trash")));
assertTrue(Files.isDirectory(temp.resolve(".cache/thumbnails")));
}
@Test
void resolvesVirtualPath() {
assertEquals(storage.basePath().resolve("a/b.txt"), storage.resolve("/a/b.txt"));
assertEquals("/a/b.txt", storage.virtualPath(storage.basePath().resolve("a/b.txt")));
assertEquals("/", storage.virtualPath(storage.basePath()));
}
@Test
void rejectsTraversalAndRelativePaths() {
assertThrows(TimiException.class, () -> storage.resolve("/../escape.txt"));
assertThrows(TimiException.class, () -> storage.resolve("a.txt"));
assertThrows(TimiException.class, () -> storage.resolve("/a\\b.txt"));
}
@Test
void rejectsInternalDirectories() {
assertThrows(TimiException.class, () -> storage.resolve("/.trash/a.txt"));
assertThrows(TimiException.class, () -> storage.resolve("/.cache/thumbnails/a.png"));
}
@Test
void validatesFileNames() {
storage.validateFileName("报告 2026.pdf");
storage.validateFileName("a.txt");
assertThrows(TimiException.class, () -> storage.validateFileName(".."));
assertThrows(TimiException.class, () -> storage.validateFileName("a/b.txt"));
assertThrows(TimiException.class, () -> storage.validateFileName("CON.txt"));
assertThrows(TimiException.class, () -> storage.validateFileName("a:b.txt"));
assertThrows(TimiException.class, () -> storage.validateFileName("a."));
}
@Test
void rejectsSymbolicLinks() throws IOException {
Path outside = temp.resolve("outside");
Files.createDirectories(outside);
Path link = temp.resolve("link");
try {
Files.createSymbolicLink(link, outside);
} catch (IOException | UnsupportedOperationException e) {
abort("当前环境不支持符号链接");
}
assertThrows(TimiException.class, () -> storage.resolve("/link/file.txt"));
}
}
@@ -0,0 +1,61 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.bean.SettingEnum;
import com.imyeyu.api.modules.common.entity.Setting;
import com.imyeyu.api.modules.common.service.SettingService;
import org.springframework.test.util.ReflectionTestUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/// 文件模块测试用存储环境。
public final class FileTestSupport {
private FileTestSupport() {
}
public static FileStorageService storage(Path base, Map<String, String> values) throws IOException {
Path realBase = base.toRealPath();
Map<String, String> settings = new HashMap<>(values);
settings.putIfAbsent("BASE_PATH", realBase.toString());
settings.putIfAbsent("TRASH_PATH", ".trash");
settings.putIfAbsent("THUMBNAIL_PATH", ".cache/thumbnails");
settings.putIfAbsent("TRASH_RETENTION_DAYS", "30");
settings.putIfAbsent("SEARCH_MAX_RESULTS", "200");
settings.putIfAbsent("SEARCH_MAX_DEPTH", "32");
settings.putIfAbsent("SEARCH_TIMEOUT_SECONDS", "5");
settings.putIfAbsent("UPLOAD_MAX_SIZE", String.valueOf(1024L * 1024 * 1024));
settings.putIfAbsent("UPLOAD_CHUNK_SIZE", String.valueOf(8L * 1024 * 1024));
settings.putIfAbsent("SHARE_ENABLED", "true");
settings.putIfAbsent("SHARE_DEFAULT_EXPIRE_DAYS", "7");
SettingService settingService = mock(SettingService.class);
when(settingService.getSystem(any())).thenAnswer(invocation -> {
SettingEnum key = invocation.getArgument(0);
String value = settings.get(key.name());
if (value == null) {
return null;
}
Setting setting = new Setting();
setting.setValue(value);
return setting;
});
FileStorageService storage = new FileStorageService(settingService);
ReflectionTestUtils.setField(storage, "basePath", realBase);
Path trash = realBase.resolve(".trash");
Path thumbnail = realBase.resolve(".cache/thumbnails");
Files.createDirectories(trash);
Files.createDirectories(thumbnail);
ReflectionTestUtils.setField(storage, "trashPath", trash);
ReflectionTestUtils.setField(storage, "thumbnailPath", thumbnail);
return storage;
}
}
@@ -0,0 +1,67 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.modules.system.entity.FileTrash;
import com.imyeyu.api.modules.system.mapper.FileTrashMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/// 回收站服务测试。
class FileTrashServiceTest {
@TempDir
Path temp;
private FileStorageService storage;
private FileTrashMapper mapper;
private FileTrashService service;
@BeforeEach
void setUp() throws IOException {
storage = FileTestSupport.storage(temp, Map.of("TRASH_RETENTION_DAYS", "30"));
mapper = mock(FileTrashMapper.class);
service = new FileTrashService(storage, mapper);
}
@Test
void movesFileToTrashAndRestoresIt() throws IOException {
Files.writeString(temp.resolve("a.txt"), "hello");
List<FileTrash> records = service.trash(List.of("/a.txt"), "user-1");
assertEquals(1, records.size());
assertFalse(Files.exists(temp.resolve("a.txt")));
FileTrash record = records.getFirst();
record.setId("trash-1");
assertTrue(Files.exists(storage.trashPath().resolve(record.getTrashName())));
when(mapper.selectActive(eq("trash-1"), anyLong())).thenReturn(record);
var restored = service.restore("trash-1");
assertEquals("/a.txt", restored.getPath());
assertEquals("hello", Files.readString(temp.resolve("a.txt")));
}
@Test
void purgesTrashItem() throws IOException {
Files.writeString(temp.resolve("a.txt"), "hello");
FileTrash record = service.trash(List.of("/a.txt"), "user-1").getFirst();
record.setId("trash-2");
when(mapper.selectActive(eq("trash-2"), anyLong())).thenReturn(record);
service.purge("trash-2");
assertFalse(Files.exists(storage.trashPath().resolve(record.getTrashName())));
}
}
@@ -0,0 +1,113 @@
package com.imyeyu.api.modules.system.service;
import com.imyeyu.api.modules.system.bean.ServerFile;
import com.imyeyu.java.bean.timi.TimiException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
/// 文件上传服务测试。
class FileUploadServiceTest {
@TempDir
Path temp;
private FileUploadService service;
@BeforeEach
void setUp() throws IOException {
FileStorageService storage = FileTestSupport.storage(temp, Map.of(
"UPLOAD_MAX_SIZE", "1048576",
"UPLOAD_CHUNK_SIZE", "4"
));
service = new FileUploadService(storage);
}
@Test
void uploadsAndRejectsDuplicate() {
MockMultipartFile file = new MockMultipartFile("file", "a.txt", "text/plain",
"hello".getBytes(StandardCharsets.UTF_8));
ServerFile result = service.upload("/", "a.txt", file, false);
assertEquals("/a.txt", result.getPath());
assertThrows(TimiException.class, () -> service.upload("/", "a.txt", file, false));
assertThrows(TimiException.class, () -> service.upload("/", "../escape.txt", file, false));
}
@Test
void completesChunkedUpload() throws IOException {
FileUploadService.UploadInit init = service.init("/", "b.txt", 10, null);
assertEquals(3, init.totalChunks());
service.chunk(init.uploadId(), 0, chunk("0123"));
service.chunk(init.uploadId(), 1, chunk("4567"));
service.chunk(init.uploadId(), 2, chunk("89"));
ServerFile result = service.complete(init.uploadId(), null);
assertEquals("/b.txt", result.getPath());
assertEquals("0123456789", Files.readString(temp.resolve("b.txt")));
}
@Test
void rejectsWrongSizeAndCleansMergedTemp() throws IOException {
FileUploadService.UploadInit init = service.init("/", "short.txt", 7, null);
service.chunk(init.uploadId(), 0, chunk("0123"));
service.chunk(init.uploadId(), 1, chunk("45"));
assertThrows(TimiException.class, () -> service.complete(init.uploadId(), null));
assertEquals(0, uploadTempCount());
}
@Test
void rejectsChecksumAndCleansMergedTemp() throws IOException {
FileUploadService.UploadInit init = service.init("/", "checksum.txt", 4, "deadbeef");
service.chunk(init.uploadId(), 0, chunk("0123"));
assertThrows(TimiException.class, () -> service.complete(init.uploadId(), null));
assertEquals(0, uploadTempCount());
}
@Test
void rejectsOversizedChunk() {
FileUploadService.UploadInit init = service.init("/", "chunk.txt", 4, null);
assertThrows(TimiException.class, () -> service.chunk(init.uploadId(), 0, chunk("01234")));
}
@Test
@SuppressWarnings("unchecked")
void cleansExpiredSessions() throws IOException {
FileUploadService.UploadInit init = service.init("/", "c.txt", 4, null);
Map<String, Object> sessions = (Map<String, Object>) ReflectionTestUtils.getField(service, "sessions");
Object session = sessions.get(init.uploadId());
Path directory = (Path) ReflectionTestUtils.getField(session, "directory");
ReflectionTestUtils.setField(session, "lastAccessAt", 0L);
service.cleanupExpiredSessions();
assertFalse(sessions.containsKey(init.uploadId()));
assertFalse(Files.exists(directory));
}
private long uploadTempCount() throws IOException {
try (var files = Files.list(temp)) {
return files.filter(path -> path.getFileName().toString().startsWith(".upload-")).count();
}
}
private MockMultipartFile chunk(String value) {
return new MockMultipartFile("file", "chunk", "application/octet-stream",
value.getBytes(StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,90 @@
package com.imyeyu.api.modules.system.task.async;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.service.FileTestSupport;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.bean.timi.TimiException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class FileArchiveTaskTest {
@TempDir
Path temp;
private FileStorageService storage;
private PermissionChecker permissionChecker;
@BeforeEach
void setUp() throws Exception {
storage = FileTestSupport.storage(temp, java.util.Map.of());
permissionChecker = mock(PermissionChecker.class);
when(permissionChecker.codeSet("user")).thenReturn(Set.of(
"CORE:FILE:READ",
"CORE:FILE:WRITE",
"CORE:FILE:DELETE"
));
}
@Test
void zipThenUnzipRoundTrip() throws Exception {
Files.createDirectories(temp.resolve("src/empty"));
Files.createDirectories(temp.resolve("src/sub"));
Files.writeString(temp.resolve("src/a.txt"), "hello");
Files.writeString(temp.resolve("src/sub/b.txt"), "world");
new FileZipAsyncTask(List.of("/src"), "/src.zip", storage, permissionChecker, "user").run();
assertTrue(Files.isRegularFile(temp.resolve("src.zip")));
assertTrue(Files.size(temp.resolve("src.zip")) > 0);
new FileUnZipAsyncTask("/src.zip", "/out", storage, permissionChecker, "user").run();
assertEquals("hello", Files.readString(temp.resolve("out/src/a.txt")));
assertEquals("world", Files.readString(temp.resolve("out/src/sub/b.txt")));
assertTrue(Files.isDirectory(temp.resolve("out/src/empty")));
}
@Test
void zipRejectsTargetInsideSource() throws Exception {
Files.createDirectories(temp.resolve("src"));
Files.writeString(temp.resolve("src/a.txt"), "hello");
FileZipAsyncTask task = new FileZipAsyncTask(List.of("/src"), "/src/out.zip", storage, permissionChecker, "user");
assertThrows(TimiException.class, task::run);
assertFalse(Files.exists(temp.resolve("src/out.zip")));
}
@Test
void unzipRejectsTraversal() throws Exception {
Path zip = temp.resolve("bad.zip");
try (OutputStream output = Files.newOutputStream(zip);
ZipOutputStream zipOutput = new ZipOutputStream(output)) {
zipOutput.putNextEntry(new ZipEntry("../evil.txt"));
zipOutput.write("evil".getBytes(java.nio.charset.StandardCharsets.UTF_8));
zipOutput.closeEntry();
}
FileUnZipAsyncTask task = new FileUnZipAsyncTask("/bad.zip", "/out", storage, permissionChecker, "user");
assertThrows(TimiException.class, task::run);
assertFalse(Files.exists(temp.resolve("evil.txt")));
}
}
@@ -0,0 +1,65 @@
package com.imyeyu.api.modules.system.task.async;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.service.FileTestSupport;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.bean.timi.TimiException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class FileCalcSizeAsyncTaskTest {
@TempDir
Path temp;
@Test
void countsFilesAndSkipsInternalDirectories() throws Exception {
Files.createDirectories(temp.resolve("data/sub"));
Files.writeString(temp.resolve("data/a.txt"), "abc");
Files.writeString(temp.resolve("data/sub/b.txt"), "12345");
Files.createDirectories(temp.resolve(".trash"));
Files.writeString(temp.resolve(".trash/ignored.txt"), "must not count");
FileStorageService storage = FileTestSupport.storage(temp, Map.of());
PermissionChecker checker = mock(PermissionChecker.class);
when(checker.codeSet("user")).thenReturn(Set.of("CORE:FILE:READ"));
FileCalcSizeAsyncTask task = new FileCalcSizeAsyncTask("/", storage, checker, "user");
task.run();
JsonNode result = new ObjectMapper().readTree(task.getResult());
assertEquals(8, result.get("bytes").asLong());
assertEquals(2, result.get("files").asLong());
assertTrue(result.get("directories").asLong() >= 3);
assertEquals(0, result.get("failed").asLong());
}
@Test
void rejectsFilesAndMissingPermission() throws Exception {
Files.writeString(temp.resolve("a.txt"), "abc");
FileStorageService storage = FileTestSupport.storage(temp, Map.of());
PermissionChecker checker = mock(PermissionChecker.class);
when(checker.codeSet("user")).thenReturn(Set.of("CORE:FILE:READ"));
FileCalcSizeAsyncTask fileTask = new FileCalcSizeAsyncTask("/a.txt", storage, checker, "user");
assertThrows(TimiException.class, fileTask::run);
PermissionChecker noPermission = mock(PermissionChecker.class);
when(noPermission.codeSet("user")).thenReturn(Set.of());
FileCalcSizeAsyncTask deniedTask = new FileCalcSizeAsyncTask("/", storage, noPermission, "user");
assertThrows(TimiException.class, deniedTask::run);
}
}
@@ -0,0 +1,84 @@
package com.imyeyu.api.modules.system.task.async;
import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.modules.system.service.FileStorageService;
import com.imyeyu.api.modules.system.service.FileTestSupport;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.bean.timi.TimiException;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/// 异步任务公共辅助测试。
class FileTaskSupportTest {
@TempDir
Path temp;
@Test
void collectsEmptyDirectories() throws IOException {
FileStorageService storage = FileTestSupport.storage(temp, Map.of());
Files.createDirectories(temp.resolve("a/b"));
List<Path> sources = FileTaskSupport.sources(storage, List.of("/a"));
List<FileTaskSupport.Entry> entries = FileTaskSupport.collect(sources, null);
assertEquals(2, entries.size());
assertTrue(entries.stream().anyMatch(entry -> entry.name().equals("a") && entry.directory()));
assertTrue(entries.stream().anyMatch(entry -> entry.name().equals("a/b") && entry.directory()));
}
@Test
void rejectsNestedDestination() throws IOException {
FileStorageService storage = FileTestSupport.storage(temp, Map.of());
Files.createDirectories(temp.resolve("a"));
Path source = storage.resolveExisting("/a");
Path destination = storage.resolve("/a/out");
assertThrows(TimiException.class, () -> FileTaskSupport.ensureNotNested(source, destination));
}
@Test
void requiresEveryPermission() {
PermissionChecker checker = mock(PermissionChecker.class);
when(checker.codeSet("u")).thenReturn(Set.of("CORE:FILE:READ"));
assertDoesNotThrow(() -> FileTaskSupport.require(checker, "u", CorePermissionCode.FILE_READ));
assertThrows(TimiException.class, () -> FileTaskSupport.require(checker, "u",
CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE));
assertThrows(TimiException.class, () -> FileTaskSupport.require(checker, " ", CorePermissionCode.FILE_READ));
}
@Test
void rejectsSymlinkSources() throws IOException {
FileStorageService storage = FileTestSupport.storage(temp, Map.of());
Path outside = temp.resolve("outside");
Files.createDirectories(outside);
Files.createDirectories(temp.resolve("a"));
Path link = temp.resolve("a/link");
try {
Files.createSymbolicLink(link, outside);
} catch (UnsupportedOperationException | IOException e) {
Assumptions.assumeTrue(false, "当前文件系统不支持符号链接");
return;
}
List<Path> sources = FileTaskSupport.sources(storage, List.of("/a"));
assertThrows(TimiException.class, () -> FileTaskSupport.collect(sources, null));
}
}