|
|
@@ -6,7 +6,10 @@ import cn.hutool.core.util.StrUtil;
|
|
|
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
|
|
import com.zsjz.ai.common.context.CaseContextHolder;
|
|
|
import com.zsjz.ai.common.exception.ServerException;
|
|
|
+import com.zsjz.ai.common.model.dm.entity.FileInfo;
|
|
|
import com.zsjz.ai.common.utils.Json;
|
|
|
+import com.zsjz.ai.common.utils.WorkspacePathGuard;
|
|
|
+import com.zsjz.ai.module.dm.mapper.FileInfoMapper;
|
|
|
import com.zsjz.ai.module.document.ExtractionResult;
|
|
|
import com.zsjz.ai.module.document.TextExtractor;
|
|
|
import lombok.RequiredArgsConstructor;
|
|
|
@@ -17,11 +20,12 @@ import org.springframework.stereotype.Service;
|
|
|
import org.springframework.web.multipart.MultipartFile;
|
|
|
|
|
|
import java.io.File;
|
|
|
-import java.io.Writer;
|
|
|
+import java.io.IOException;
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
import java.nio.file.Files;
|
|
|
import java.nio.file.Path;
|
|
|
import java.nio.file.Paths;
|
|
|
+import java.nio.file.StandardCopyOption;
|
|
|
import java.time.LocalDateTime;
|
|
|
import java.util.ArrayList;
|
|
|
import java.util.LinkedHashMap;
|
|
|
@@ -58,31 +62,36 @@ public class ChatAttachmentService {
|
|
|
|
|
|
private final TextExtractor textExtractor;
|
|
|
|
|
|
+ /** 案件库(DuckDB)里的已上传文件表:@ 引用已上传文件的数据源 */
|
|
|
+ private final FileInfoMapper fileInfoMapper;
|
|
|
+
|
|
|
private final ChatAttachmentProperties props;
|
|
|
|
|
|
private final Tika tika = new Tika();
|
|
|
|
|
|
- /** 上传响应 */
|
|
|
- public record AttachmentVO(Long id, String name, long size, String kind,
|
|
|
+ /**
|
|
|
+ * 上传响应。id 用字符串回传:雪花 ID 超出 JS Number 安全整数,前端必须按字符串透传。
|
|
|
+ */
|
|
|
+ public record AttachmentVO(String id, String name, long size, String kind,
|
|
|
int rows, int chars, boolean truncated, int indexedChunks, String status) {
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 输入框 @ 可引用的已上传文件(当前案件 file_info 的根记录)。
|
|
|
+ *
|
|
|
+ * @param pickable 能否在对话中引用;false 时 {@code reason} 说明原因
|
|
|
+ */
|
|
|
+ public record ChatFileVO(String id, String name, String type, long size,
|
|
|
+ String createTime, boolean pickable, String reason) {
|
|
|
+ }
|
|
|
+
|
|
|
// ==================== 上传 ====================
|
|
|
|
|
|
/**
|
|
|
* 上传并按路由提取。UNSUPPORTED 直接 400(不落盘),FAILED 落盘登记但状态失败可重传。
|
|
|
*/
|
|
|
public AttachmentVO upload(MultipartFile file, Long userId, Long caseId, Long sessionId) {
|
|
|
- // caseId 来自请求参数,必须与当前打开案件一致;附件行/落盘目录/向量表名都以它为准
|
|
|
- Long openCaseId = CaseContextHolder.currentCaseId();
|
|
|
- if (openCaseId == null) {
|
|
|
- throw new ServerException(400, "请先打开案件后再上传附件");
|
|
|
- }
|
|
|
- if (caseId == null) {
|
|
|
- caseId = openCaseId;
|
|
|
- } else if (!openCaseId.equals(caseId)) {
|
|
|
- throw new ServerException(409, "案件上下文不一致,请重新打开案件后再上传附件");
|
|
|
- }
|
|
|
+ Long openCaseId = requireOpenCase(caseId);
|
|
|
if (!props.isEnabled()) {
|
|
|
throw new ServerException(400, "附件功能未启用");
|
|
|
}
|
|
|
@@ -90,17 +99,166 @@ public class ChatAttachmentService {
|
|
|
throw new ServerException(400, "附件为空");
|
|
|
}
|
|
|
String safeName = sanitizeFileName(file.getOriginalFilename());
|
|
|
- String suffix = AttachmentContentRouter.suffixOf(safeName);
|
|
|
- if (!props.effectiveSuffixes().contains(suffix)) {
|
|
|
- throw new ServerException(400, "不支持的文件类型: " + suffix
|
|
|
+ if (!props.effectiveSuffixes().contains(AttachmentContentRouter.suffixOf(safeName))) {
|
|
|
+ throw new ServerException(400, "不支持的文件类型: " + AttachmentContentRouter.suffixOf(safeName)
|
|
|
+ "(支持文档、表格、图片与音视频,压缩包/加密文件不支持)");
|
|
|
}
|
|
|
long size = file.getSize();
|
|
|
String mime = detectMime(file, safeName);
|
|
|
+ AttachmentContentRouter.Kind kind = requireKind(safeName, mime);
|
|
|
+ requireSize(kind, size, safeName);
|
|
|
+
|
|
|
+ // 落盘(三层隔离路径):{root}/chat-attachments/{userId}/{caseId}/{sessionId}/{雪花}_{safeName}
|
|
|
+ Path dir = baseDir(userId, openCaseId, sessionId);
|
|
|
+ Path target = allocate(dir, safeName);
|
|
|
+ try {
|
|
|
+ Files.createDirectories(dir);
|
|
|
+ file.transferTo(target);
|
|
|
+ } catch (Exception e) {
|
|
|
+ throw new ServerException(500, "附件保存失败: " + e.getMessage());
|
|
|
+ }
|
|
|
+ return register(userId, openCaseId, sessionId, target, safeName, mime, kind, size);
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== @ 引用已上传文件 ====================
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 列出当前案件已上传的文件({@code file_info} 根记录,按上传时间倒序),供输入框 @ 选择。
|
|
|
+ *
|
|
|
+ * <p>只有保留原件的文件可引用:非表格类文件上传时没有落盘(只留 file_ai_profile 的文本样本),
|
|
|
+ * 无法重新解析,这里标记 {@code pickable=false} 并给出原因,前端置灰展示。
|
|
|
+ */
|
|
|
+ public List<ChatFileVO> listCaseFiles(String keyword, int limit) {
|
|
|
+ Long caseId = CaseContextHolder.currentCaseId();
|
|
|
+ if (caseId == null) {
|
|
|
+ throw new ServerException(400, "请先打开案件后再查看已上传文件");
|
|
|
+ }
|
|
|
+ int size = Math.min(Math.max(limit, 1), 200);
|
|
|
+ List<FileInfo> rows = fileInfoMapper.selectList(Wrappers.<FileInfo>lambdaQuery()
|
|
|
+ .eq(FileInfo::getPid, 0L)
|
|
|
+ .like(StrUtil.isNotBlank(keyword), FileInfo::getFileName, StrUtil.trim(keyword))
|
|
|
+ .orderByDesc(FileInfo::getCreateDateTime)
|
|
|
+ .last("limit " + size));
|
|
|
+ List<ChatFileVO> out = new ArrayList<>(rows.size());
|
|
|
+ for (FileInfo row : rows) {
|
|
|
+ out.add(toChatFileVO(caseId, row));
|
|
|
+ }
|
|
|
+ return out;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 把已上传文件({@code file_info})登记为对话附件:复制原件到附件目录,然后走与上传完全相同的
|
|
|
+ * 提取流程(表格扫描 / 文档 OCR / 音视频转写 / 内联或 RAG)。
|
|
|
+ *
|
|
|
+ * <p><b>复制而不是引用原件</b>:附件孤儿清理会删除 {@code file_path} 指向的文件,
|
|
|
+ * 直接引用案件上传目录会在清理时把用户导入的原始表格一起删掉。
|
|
|
+ */
|
|
|
+ public AttachmentVO attachExisting(Long userId, Long caseId, Long sessionId, String fileId) {
|
|
|
+ Long openCaseId = requireOpenCase(caseId);
|
|
|
+ if (!props.isEnabled()) {
|
|
|
+ throw new ServerException(400, "附件功能未启用");
|
|
|
+ }
|
|
|
+ FileInfo info = loadFileInfo(fileId);
|
|
|
+ String safeName = sanitizeFileName(info.getFileName());
|
|
|
+ if (StrUtil.isBlank(info.getFilePath())) {
|
|
|
+ throw new ServerException(400, "该文件未保留原件,无法在对话中引用(只有表格类文件上传时会落盘): " + safeName);
|
|
|
+ }
|
|
|
+ Path source = WorkspacePathGuard.requireInsideWorkspace(openCaseId, info.getFilePath());
|
|
|
+ if (!Files.isRegularFile(source)) {
|
|
|
+ throw new ServerException(400, "文件原件已被清理: " + safeName);
|
|
|
+ }
|
|
|
+ if (!props.effectiveSuffixes().contains(AttachmentContentRouter.suffixOf(safeName))) {
|
|
|
+ throw new ServerException(400, "该文件类型不能在对话中引用: " + safeName);
|
|
|
+ }
|
|
|
+ String mime = detectMime(source);
|
|
|
+ AttachmentContentRouter.Kind kind = requireKind(safeName, mime);
|
|
|
+ long size;
|
|
|
+ try {
|
|
|
+ size = Files.size(source);
|
|
|
+ } catch (IOException e) {
|
|
|
+ throw new ServerException(500, "读取文件失败: " + e.getMessage());
|
|
|
+ }
|
|
|
+ requireSize(kind, size, safeName);
|
|
|
+
|
|
|
+ Path dir = baseDir(userId, openCaseId, sessionId);
|
|
|
+ Path target = allocate(dir, safeName);
|
|
|
+ try {
|
|
|
+ Files.createDirectories(dir);
|
|
|
+ Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
|
|
|
+ } catch (IOException e) {
|
|
|
+ throw new ServerException(500, "附件保存失败: " + e.getMessage());
|
|
|
+ }
|
|
|
+ return register(userId, openCaseId, sessionId, target, safeName, mime, kind, size);
|
|
|
+ }
|
|
|
+
|
|
|
+ private FileInfo loadFileInfo(String fileId) {
|
|
|
+ if (StrUtil.isBlank(fileId)) {
|
|
|
+ throw new ServerException(400, "缺少文件 ID");
|
|
|
+ }
|
|
|
+ long id;
|
|
|
+ try {
|
|
|
+ id = Long.parseLong(fileId.trim());
|
|
|
+ } catch (NumberFormatException e) {
|
|
|
+ throw new ServerException(400, "文件 ID 非法: " + fileId);
|
|
|
+ }
|
|
|
+ FileInfo info = fileInfoMapper.selectById(id);
|
|
|
+ if (info == null) {
|
|
|
+ throw new ServerException(404, "文件不存在或已删除: " + fileId);
|
|
|
+ }
|
|
|
+ return info;
|
|
|
+ }
|
|
|
+
|
|
|
+ private ChatFileVO toChatFileVO(Long caseId, FileInfo row) {
|
|
|
+ String name = StrUtil.blankToDefault(row.getFileName(), "未命名文件");
|
|
|
+ String type = StrUtil.blankToDefault(row.getFileType(), AttachmentContentRouter.suffixOf(name));
|
|
|
+ long size = row.getFileSize() == null ? 0 : row.getFileSize();
|
|
|
+ String reason;
|
|
|
+ if (StrUtil.isBlank(row.getFilePath())) {
|
|
|
+ reason = "未保留原件(仅表格类文件上传时落盘)";
|
|
|
+ } else if (!props.effectiveSuffixes().contains(AttachmentContentRouter.suffixOf(name))) {
|
|
|
+ reason = "该类型不能在对话中引用";
|
|
|
+ } else {
|
|
|
+ try {
|
|
|
+ Path path = WorkspacePathGuard.requireInsideWorkspace(caseId, row.getFilePath());
|
|
|
+ if (!Files.isRegularFile(path)) {
|
|
|
+ reason = "原件已被清理";
|
|
|
+ } else {
|
|
|
+ size = Files.size(path);
|
|
|
+ reason = null;
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ reason = "原件不可读或已被清理";
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return new ChatFileVO(String.valueOf(row.getId()), name, type, size,
|
|
|
+ row.getCreateDateTime() == null ? null : row.getCreateDateTime().toString(),
|
|
|
+ reason == null, reason);
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 当前案件必须已打开,且与请求里的 caseId 一致(附件行/落盘目录/向量表名都以它为准) */
|
|
|
+ private Long requireOpenCase(Long caseId) {
|
|
|
+ Long openCaseId = CaseContextHolder.currentCaseId();
|
|
|
+ if (openCaseId == null) {
|
|
|
+ throw new ServerException(400, "请先打开案件后再操作附件");
|
|
|
+ }
|
|
|
+ if (caseId == null) {
|
|
|
+ return openCaseId;
|
|
|
+ }
|
|
|
+ if (!openCaseId.equals(caseId)) {
|
|
|
+ throw new ServerException(409, "案件上下文不一致,请重新打开案件后再操作附件");
|
|
|
+ }
|
|
|
+ return openCaseId;
|
|
|
+ }
|
|
|
+
|
|
|
+ private AttachmentContentRouter.Kind requireKind(String safeName, String mime) {
|
|
|
AttachmentContentRouter.Kind kind = AttachmentContentRouter.route(safeName, mime);
|
|
|
if (kind == AttachmentContentRouter.Kind.UNSUPPORTED) {
|
|
|
throw new ServerException(400, "该文件类型暂不支持解析: " + safeName + "(压缩包/加密文件不支持)");
|
|
|
}
|
|
|
+ return kind;
|
|
|
+ }
|
|
|
+
|
|
|
+ private void requireSize(AttachmentContentRouter.Kind kind, long size, String safeName) {
|
|
|
long limitMb = switch (kind) {
|
|
|
case TABLE -> props.getMaxSheetMb();
|
|
|
case IMAGE -> props.getMaxImageMb();
|
|
|
@@ -110,20 +268,21 @@ public class ChatAttachmentService {
|
|
|
if (size > limitMb * 1024 * 1024) {
|
|
|
throw new ServerException(400, "文件超过大小上限(" + limitMb + "MB): " + safeName);
|
|
|
}
|
|
|
+ }
|
|
|
|
|
|
- // 落盘(三层隔离路径):{root}/chat-attachments/{userId}/{caseId}/{sessionId}/{雪花}_{safeName}
|
|
|
- Path dir = baseDir(userId, caseId, sessionId);
|
|
|
+ private Path allocate(Path dir, String safeName) {
|
|
|
Path target = dir.resolve(IdUtil.getSnowflakeNextId() + "_" + safeName).normalize();
|
|
|
if (!target.startsWith(dir)) {
|
|
|
throw new ServerException(400, "非法文件名: " + safeName);
|
|
|
}
|
|
|
- try {
|
|
|
- Files.createDirectories(dir);
|
|
|
- file.transferTo(target);
|
|
|
- } catch (Exception e) {
|
|
|
- throw new ServerException(500, "附件保存失败: " + e.getMessage());
|
|
|
- }
|
|
|
+ return target;
|
|
|
+ }
|
|
|
|
|
|
+ /**
|
|
|
+ * 落盘后的统一登记:建行 → 按类型提取 → 入库。上传与 @ 引用共用,保证两条入口口径一致。
|
|
|
+ */
|
|
|
+ private AttachmentVO register(Long userId, Long caseId, Long sessionId, Path target,
|
|
|
+ String safeName, String mime, AttachmentContentRouter.Kind kind, long size) {
|
|
|
ChatAttachment att = new ChatAttachment();
|
|
|
att.setId(IdUtil.getSnowflakeNextId());
|
|
|
att.setUserId(userId);
|
|
|
@@ -400,7 +559,9 @@ public class ChatAttachmentService {
|
|
|
continue;
|
|
|
}
|
|
|
Map<String, Object> m = new LinkedHashMap<>();
|
|
|
- m.put("id", att.getId());
|
|
|
+ // id 同样按字符串写进消息元数据:前端 regenerate 会把它原样回传为 attachmentIds,
|
|
|
+ // Long 经 JS Number 会被抹掉末位,回传后就变成「附件不存在」
|
|
|
+ m.put("id", String.valueOf(att.getId()));
|
|
|
m.put("name", att.getFileName());
|
|
|
m.put("size", att.getSizeBytes());
|
|
|
m.put("kind", att.getKind());
|
|
|
@@ -486,7 +647,7 @@ public class ChatAttachmentService {
|
|
|
// ==================== 内部 ====================
|
|
|
|
|
|
private static AttachmentVO toVO(ChatAttachment att) {
|
|
|
- return new AttachmentVO(att.getId(), att.getFileName(),
|
|
|
+ return new AttachmentVO(String.valueOf(att.getId()), att.getFileName(),
|
|
|
att.getSizeBytes() == null ? 0 : att.getSizeBytes(), att.getKind(),
|
|
|
att.getRowCount() == null ? 0 : att.getRowCount(),
|
|
|
att.getCharCount() == null ? 0 : att.getCharCount(),
|
|
|
@@ -522,6 +683,15 @@ public class ChatAttachmentService {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /** @ 引用已上传文件时按路径探测 MIME(原型是磁盘上的案件上传文件,不是 multipart) */
|
|
|
+ private String detectMime(Path file) {
|
|
|
+ try {
|
|
|
+ return tika.detect(file);
|
|
|
+ } catch (Exception e) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
/** 供 Controller 用的 VO 序列化(前端 chips 展示) */
|
|
|
public static String toJson(AttachmentVO vo) {
|
|
|
return Json.toStr(vo);
|