167 lines
5.9 KiB
Java
167 lines
5.9 KiB
Java
package com.kri.contact.server.service;
|
|
|
|
import com.kri.common.file.FileUtil;
|
|
import com.kri.common.web.BusinessException;
|
|
import org.jsoup.Jsoup;
|
|
import org.jsoup.nodes.Document;
|
|
import org.jsoup.nodes.Element;
|
|
import org.jsoup.select.Elements;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.web.multipart.MultipartFile;
|
|
|
|
import java.io.IOException;
|
|
import java.nio.file.*;
|
|
import java.util.*;
|
|
|
|
@Service
|
|
public class FileService {
|
|
private static final Logger log = LoggerFactory.getLogger(FileService.class);
|
|
private final Path uploadBaseDir; // ex) /data/upload-file/contact-senario
|
|
private final String publicBaseUrlPrefix; // ex) /upload-file/contact-senario
|
|
|
|
public FileService(
|
|
@Value("${kri.contact-senario.upload-base-dir}") String uploadBaseDir,
|
|
@Value("${kri.contact-senario.public-base-url}") String publicBaseUrlPrefix
|
|
) {
|
|
this.uploadBaseDir = Paths.get(uploadBaseDir).toAbsolutePath().normalize();
|
|
this.publicBaseUrlPrefix = publicBaseUrlPrefix.endsWith("/")
|
|
? publicBaseUrlPrefix.substring(0, publicBaseUrlPrefix.length() - 1)
|
|
: publicBaseUrlPrefix;
|
|
}
|
|
|
|
/**
|
|
* Temp에 파일 저장 후, public URL 반환
|
|
*/
|
|
public String storeTempFile(String prjctCd, MultipartFile file) {
|
|
try {
|
|
String original = Optional.ofNullable(file.getOriginalFilename()).orElse("file");
|
|
String ext = "";
|
|
|
|
int dot = original.lastIndexOf('.');
|
|
if (dot > 0 && dot < original.length() - 1) {
|
|
ext = original.substring(dot);
|
|
}
|
|
|
|
String newName = UUID.randomUUID().toString().replace("-", "") + ext;
|
|
|
|
Path tempDir = getTempDir(prjctCd);
|
|
Files.createDirectories(tempDir);
|
|
|
|
Path target = tempDir.resolve(newName);
|
|
file.transferTo(target.toFile());
|
|
|
|
// 브라우저에서 사용할 URL
|
|
return publicBaseUrlPrefix + "/" + prjctCd + "/Temp/" + newName;
|
|
} catch (IOException e) {
|
|
throw new RuntimeException("파일 저장 실패", e);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 컨택 시나리오 저장 시:
|
|
* 1) HTML 내 Temp 이미지 -> Asset으로 이동 & src 수정
|
|
* 2) Asset 디렉토리에서 더 이상 사용되지 않는 파일 삭제
|
|
* 3) 정리된 HTML 반환
|
|
*/
|
|
public String syncOnSave(String prjctCd, String rawHtml) {
|
|
if (rawHtml == null) rawHtml = "";
|
|
|
|
String returnHtml = rawHtml;
|
|
try{
|
|
|
|
|
|
// body fragment로 파싱 (KriEditor가 body 없이 <p>...</p> 형태 저장하므로)
|
|
Document doc = Jsoup.parseBodyFragment(rawHtml);
|
|
Elements imgs = doc.select("img[src]");
|
|
|
|
Set<String> assetFileNamesToKeep = new HashSet<>();
|
|
|
|
for (Element img : imgs) {
|
|
String src = img.attr("src");
|
|
if (src == null || src.isBlank()) continue;
|
|
if (!src.contains("/" + prjctCd + "/")) continue;
|
|
|
|
if (src.contains("/" + prjctCd + "/Temp/")) {
|
|
// Temp → Asset 이동
|
|
String fileName = FileUtil.extractFileNameFromPath(src);
|
|
moveTempToAsset(prjctCd, fileName);
|
|
|
|
String assetSrc = src.replace("/Temp/", "/Asset/");
|
|
img.attr("src", assetSrc);
|
|
|
|
assetFileNamesToKeep.add(fileName);
|
|
} else if (src.contains("/" + prjctCd + "/Asset/")) {
|
|
String fileName = FileUtil.extractFileNameFromPath(src);
|
|
assetFileNamesToKeep.add(fileName);
|
|
}
|
|
}
|
|
|
|
// Asset 디렉토리 정리 (본문에 없는 파일 삭제)
|
|
cleanupAssetDir(prjctCd, assetFileNamesToKeep);
|
|
|
|
// body 안의 HTML만 반환 (불필요한 <html><body> wrapper 제거)
|
|
returnHtml = doc.body().html();
|
|
}
|
|
catch (IOException e) {
|
|
log.warn("temp 파일 이동 실패: {}", rawHtml, e);
|
|
}
|
|
|
|
return returnHtml;
|
|
}
|
|
|
|
/***************************private************************************/
|
|
private String normalizeBaseUrl(String url) {
|
|
if (url.endsWith("/")) {
|
|
return url.substring(0, url.length() - 1);
|
|
}
|
|
return url;
|
|
}
|
|
|
|
private Path getTempDir(String prjctCd) {
|
|
return uploadBaseDir.resolve(prjctCd).resolve("Temp");
|
|
}
|
|
|
|
private Path getAssetDir(String prjctCd) {
|
|
return uploadBaseDir.resolve(prjctCd).resolve("Asset");
|
|
}
|
|
|
|
private void moveTempToAsset(String prjctCd, String fileName) throws IOException {
|
|
if (fileName == null || fileName.isBlank()) return;
|
|
|
|
Path tempDir = getTempDir(prjctCd);
|
|
Path assetDir = getAssetDir(prjctCd);
|
|
Files.createDirectories(assetDir);
|
|
|
|
Path source = tempDir.resolve(fileName).normalize();
|
|
Path target = assetDir.resolve(fileName).normalize();
|
|
|
|
if (!source.startsWith(tempDir) || !target.startsWith(assetDir)) {
|
|
// 안전 체크
|
|
return;
|
|
}
|
|
if (!Files.exists(source)) {
|
|
return;
|
|
}
|
|
|
|
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
|
|
}
|
|
|
|
private void cleanupAssetDir(String prjctCd, Set<String> keepFileNames) throws IOException {
|
|
Path assetDir = getAssetDir(prjctCd);
|
|
if (!Files.exists(assetDir)) return;
|
|
|
|
try (DirectoryStream<Path> stream = Files.newDirectoryStream(assetDir)) {
|
|
for (Path path : stream) {
|
|
if (!Files.isRegularFile(path)) continue;
|
|
String fileName = path.getFileName().toString();
|
|
if (!keepFileNames.contains(fileName)) {
|
|
Files.deleteIfExists(path);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|