package com.custom.webui.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.custom.webui.config.props.RagProperties; import com.custom.webui.config.props.StorageProperties; import com.custom.webui.security.CurrentUser; import com.custom.webui.dto.resp.FileDTO; import com.custom.webui.dto.resp.OcrResultDTO; import com.custom.webui.entity.RagCollection; import com.custom.webui.entity.UploadFile; import com.custom.webui.exception.BusinessException; import com.custom.webui.entity.KbCategory; import com.custom.webui.mapper.KbCategoryMapper; import com.custom.webui.mapper.RagCollectionMapper; import com.custom.webui.mapper.UploadFileMapper; import com.custom.webui.service.FileService; import com.custom.webui.service.CategoryService; import com.custom.webui.service.RagProxyService; import com.custom.webui.util.StoragePathUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; 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.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.UUID; /** * 文件与知识库服务实现。 * *
安全设计(重点): *
归类失败**不抛异常**:文件已经上传成功,因为分类参数有问题 * 就把整个上传判为失败,用户会以为文件丢了。改为记日志 + 文件保持未分类, * 用户可以在界面上重新归类。 */ private void applyCategory(Long userId, FileDTO uploaded, Long categoryId) { if (uploaded == null || uploaded.getId() == null || categoryId == null) { return; } try { categoryService.assignFile(userId, uploaded.getId(), categoryId); uploaded.setCategoryId(categoryId); } catch (Exception e) { log.warn("上传后归类失败,文件保持未分类 fileId={} categoryId={} err={}", uploaded.getId(), categoryId, e.getMessage()); uploaded.setCategoryId(null); } } /** * 上传后自动向量化。 * *
失败不抛异常,而是把原因写进返回的 {@code ingestMessage}。
* 理由:文件已经成功落盘并入库(元数据),此时因为 embedding 服务不可用
* 或代理问题把整个上传判为失败,会让用户以为文件丢了 —— 而实际上文件好好的,
* 只是暂时没向量化,修好环境后点一次「向量化」即可。
*/
private FileDTO tryAutoIngest(Long userId, FileDTO uploaded) {
if (uploaded == null || uploaded.getId() == null) {
return uploaded;
}
try {
log.info("上传后自动向量化 fileId={} name={}", uploaded.getId(), uploaded.getFilename());
return ingest(userId, uploaded.getId());
} catch (Exception e) {
log.warn("自动向量化失败,文件已保存,可稍后手动重试 fileId={} err={}",
uploaded.getId(), e.getMessage());
uploaded.setIngested(false);
uploaded.setIngestMessage("自动向量化失败:" + e.getMessage()
+ "(文件已保存,可稍后点「向量化」重试)");
return uploaded;
}
}
/** 校验当前登录者是否为管理员,否则 403 */
private void requireAdmin() {
if (!CurrentUser.isAdmin()) {
throw BusinessException.forbidden("只有管理员可以维护全局知识库");
}
}
/**
* 上传文件的共用实现。
*
* @param isGlobal true 表示全局知识库(仅管理员可传入)
*/
private FileDTO saveUpload(Long userId, Long chatId, MultipartFile file, boolean isGlobal) {
if (file == null || file.isEmpty()) {
throw BusinessException.badRequest("上传文件为空");
}
if (file.getSize() > storageProperties.getMaxFileSize()) {
throw BusinessException.badRequest(
"文件超过大小限制 " + (storageProperties.getMaxFileSize() / 1024 / 1024) + "MB");
}
// 原始文件名可能包含路径,先剥掉目录部分
String originalName = sanitizeFilename(file.getOriginalFilename());
String extension = extractExtension(originalName);
if (!storageProperties.getAllowedExtensions().contains(extension)) {
throw BusinessException.badRequest(
"不支持的文件类型 ." + extension + ",允许的类型: "
+ String.join(", ", storageProperties.getAllowedExtensions()));
}
// 存储名完全由服务端生成:UUID + 已校验的扩展名
String storedName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
String dateDir = LocalDate.now().format(DATE_DIR_FORMAT);
Path root = storageRoot();
Path targetDir = root.resolve(dateDir).normalize();
// 防御符号链接:确保目标目录确实在存储根目录之下
if (!targetDir.startsWith(root)) {
throw BusinessException.badRequest("非法的存储路径");
}
try {
Files.createDirectories(targetDir);
Path targetFile = targetDir.resolve(storedName).normalize();
if (!targetFile.startsWith(root)) {
throw BusinessException.badRequest("非法的存储路径");
}
try (var in = file.getInputStream()) {
// 已存在同名(UUID 冲突概率极低)则覆盖;REPLACE_EXISTING 也避免重复上传报错
Files.copy(in, targetFile, StandardCopyOption.REPLACE_EXISTING);
}
UploadFile entity = new UploadFile();
entity.setUserId(userId);
entity.setChatId(chatId);
entity.setFilename(originalName);
entity.setSavePath(targetFile.toString());
entity.setFileSize(file.getSize());
entity.setMimeType(file.getContentType());
entity.setIsGlobal(isGlobal);
entity.setCreatedAt(LocalDateTime.now());
uploadFileMapper.insert(entity);
log.info("文件上传成功 userId={} fileId={} name={} size={}B chatId={} 全局={}",
userId, entity.getId(), originalName, file.getSize(), chatId, isGlobal);
return toDto(entity, null);
} catch (IOException e) {
log.error("文件写入失败 name={}", originalName, e);
throw BusinessException.serverError("文件保存失败: " + e.getMessage());
}
}
// ============================================================
// 查询
// ============================================================
@Override
public List 刻意不加 {@code @Transactional}:向量化是一次可能持续数分钟的
* 外部 HTTP 调用。若把它包在事务里,一个数据库连接会被占住直到调用结束,
* 并发十几个文档入库就能耗尽连接池,让整个系统不可用。
* 这里改为「短事务分步提交」:
* 即便存储名由 UUID 生成(用户文件名不参与落盘路径),
* 这里的净化依然必要 —— 原始名会入库并回显到前端,
* 未净化的名字可能被用来做 XSS 或误导用户(如伪装成 .exe)。
*/
private String sanitizeFilename(String raw) {
if (raw == null || raw.isBlank()) {
return "unnamed";
}
// 去掉任何目录成分:同时处理 Unix 与 Windows 分隔符
String name = raw.replace('\\', '/');
int slash = name.lastIndexOf('/');
if (slash >= 0) {
name = name.substring(slash + 1);
}
// 剔除控制字符
name = name.replaceAll("[\\p{Cntrl}]", "");
// 剔除会干扰展示的引号与尖括号
name = name.replaceAll("[<>\"']", "");
name = name.trim();
if (name.isEmpty() || ".".equals(name) || "..".equals(name)) {
return "unnamed";
}
return name.length() > 255 ? name.substring(0, 255) : name;
}
/** 提取小写扩展名;无扩展名返回空串 */
private String extractExtension(String filename) {
int dot = filename.lastIndexOf('.');
if (dot < 0 || dot == filename.length() - 1) {
return "";
}
return filename.substring(dot + 1).toLowerCase(Locale.ROOT);
}
/** 配置的存储根目录(绝对路径),供路径兜底使用 */
private Path storageRoot() {
return Paths.get(storageProperties.getLocation()).toAbsolutePath().normalize();
}
/** 集合名:确定性生成,保证同一文件重复入库时幂等 */
private String buildCollectionName(UploadFile file) {
// 集合名用确定性规则生成(而非随机名),使重复入库幂等、不产生重复集合。
// 全局文件用 global_ 前缀,运维在 Chroma 里一眼能分辨归属。
if (Boolean.TRUE.equals(file.getIsGlobal())) {
return "global_file_" + file.getId();
}
return "user_" + file.getUserId() + "_file_" + file.getId();
}
/** 不存在则插入 pending 记录,存在则重置为 pending */
private void upsertPending(Long userId, Long fileId, String collectionName) {
RagCollection existing = findCollectionRecord(fileId, collectionName);
if (existing == null) {
RagCollection record = new RagCollection();
record.setUserId(userId);
record.setFileId(fileId);
record.setCollectionName(collectionName);
record.setChunkCount(0);
record.setStatus(RagCollection.STATUS_PENDING);
record.setCreatedAt(LocalDateTime.now());
ragCollectionMapper.insert(record);
} else {
RagCollection patch = new RagCollection();
patch.setId(existing.getId());
patch.setStatus(RagCollection.STATUS_PENDING);
patch.setMessage(null);
ragCollectionMapper.updateById(patch);
}
}
private RagCollection findCollectionRecord(Long fileId, String collectionName) {
return ragCollectionMapper.selectOne(
Wrappers.
*
*/
@Override
public FileDTO ingest(Long userId, Long fileId) {
UploadFile file = requireManageableFile(userId, fileId);
if (!ragProperties.isEnabled()) {
throw BusinessException.badRequest("RAG 功能已在配置中关闭(webui.rag.enabled=false)");
}
Path path = StoragePathUtil.resolve(storageRoot(), file.getSavePath());
if (!Files.exists(path)) {
throw BusinessException.badRequest("文件在磁盘上不存在,可能已被清理: " + file.getFilename());
}
// 集合名规则:user_{userId}_file_{fileId}
// 用确定性命名而非随机名,使得重复入库可以幂等覆盖,不会产生重复集合。
String collectionName = buildCollectionName(file);
// 步骤 1:先写 pending 记录
upsertPending(userId, fileId, collectionName);
try {
// 步骤 2:无事务地调用 Python 服务
RagProxyService.IngestResult result =
ragProxyService.ingest(path, collectionName, userId);
// 步骤 3:写回成功状态
RagCollection record = findCollectionRecord(fileId, collectionName);
if (record != null) {
RagCollection patch = new RagCollection();
patch.setId(record.getId());
patch.setChunkCount(result.chunkCount());
patch.setStatus(RagCollection.STATUS_READY);
patch.setMessage(result.message());
ragCollectionMapper.updateById(patch);
}
log.info("向量化入库成功 fileId={} collection={} chunks={}",
fileId, result.collectionName(), result.chunkCount());
return toDto(file, findCollectionRecord(fileId, collectionName));
} catch (Exception e) {
log.error("向量化入库失败 fileId={} collection={}", fileId, collectionName, e);
RagCollection record = findCollectionRecord(fileId, collectionName);
if (record != null) {
RagCollection patch = new RagCollection();
patch.setId(record.getId());
patch.setStatus(RagCollection.STATUS_FAILED);
patch.setMessage(abbreviate(e.getMessage(), 500));
ragCollectionMapper.updateById(patch);
}
throw e instanceof BusinessException be
? be
: BusinessException.serverError("向量化失败: " + e.getMessage());
}
}
// ============================================================
// 文本读取
// ============================================================
@Override
public OcrResultDTO recognizeImage(Long userId, Long fileId) {
UploadFile file = requireManageableFile(userId, fileId);
Path path = StoragePathUtil.resolve(storageRoot(), file.getSavePath());
if (!Files.exists(path)) {
throw BusinessException.badRequest("图片在磁盘上不存在: " + file.getFilename());
}
OcrResultDTO result = ragProxyService.recognizeImage(path);
// 以用户上传时的原始文件名为准,OCR 服务返回的是磁盘存储名
result.setFilename(file.getFilename());
return result;
}
@Override
public org.springframework.core.io.Resource loadAsResource(Long userId, Long fileId) {
UploadFile file = requireManageableFile(userId, fileId);
Path path = StoragePathUtil.resolve(storageRoot(), file.getSavePath());
if (!Files.exists(path)) {
throw BusinessException.notFound("文件在磁盘上不存在,可能已被清理");
}
try {
return new org.springframework.core.io.FileSystemResource(path);
} catch (Exception e) {
throw BusinessException.serverError("读取文件失败: " + e.getMessage());
}
}
@Override
public String readTextContent(UploadFile file) {
String extension = extractExtension(file.getFilename());
// 只直接读取纯文本类,pdf/docx 必须走 Python 解析服务
List