261001_01_ENH: 문자 템플릿 JPG 첨부 및 MMS 발송 파일 경로 처리
This commit is contained in:
@@ -235,7 +235,8 @@ public class TSendEntity {
|
|||||||
|
|
||||||
Short sendTy = tmplat.getTmplatTy().getCode();
|
Short sendTy = tmplat.getTmplatTy().getCode();
|
||||||
if(SMS_TYPE_CODE_LIST.contains(sendTy)){
|
if(SMS_TYPE_CODE_LIST.contains(sendTy)){
|
||||||
sendTy = determineSms(msgTitle, msgBody).getCode();
|
sendTy = tmplat.getAtchFl() != null && !tmplat.getAtchFl().isBlank()
|
||||||
|
? SendType.LMS_MMS.getCode() : determineSms(msgTitle, msgBody).getCode();
|
||||||
}
|
}
|
||||||
|
|
||||||
return TSendEntity.builder()
|
return TSendEntity.builder()
|
||||||
@@ -270,4 +271,27 @@ public class TSendEntity {
|
|||||||
.regDt(regDt)
|
.regDt(regDt)
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void prepareAttachmentPathForSend() {
|
||||||
|
if (atchFl == null || atchFl.isBlank() || !SMS_TYPE_CODE_LIST.contains(sendTy)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (tmplatIdx == null || tmplatIdx <= 0) {
|
||||||
|
throw new IllegalStateException("MMS attachment requires tmplatIdx.");
|
||||||
|
}
|
||||||
|
|
||||||
|
String prefix = tmplatIdx + "/";
|
||||||
|
String[] fileNames = atchFl.split("\\|", -1);
|
||||||
|
for (int i = 0; i < fileNames.length; i++) {
|
||||||
|
String fileName = fileNames[i];
|
||||||
|
if (fileName.startsWith(prefix)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (fileName.isBlank() || fileName.indexOf('/') >= 0 || fileName.indexOf('\\') >= 0) {
|
||||||
|
throw new IllegalStateException("Invalid MMS attachment file name.");
|
||||||
|
}
|
||||||
|
fileNames[i] = prefix + fileName;
|
||||||
|
}
|
||||||
|
atchFl = String.join("|", fileNames);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -198,6 +198,7 @@ public abstract class AbstractSendService {
|
|||||||
)
|
)
|
||||||
));
|
));
|
||||||
|
|
||||||
|
sendInfo.get(0).prepareAttachmentPathForSend();
|
||||||
sendRepository.save(sendInfo.get(0));
|
sendRepository.save(sendInfo.get(0));
|
||||||
sendRepository.flush();
|
sendRepository.flush();
|
||||||
|
|
||||||
@@ -391,6 +392,9 @@ public abstract class AbstractSendService {
|
|||||||
|
|
||||||
private SendType resolveSendType(TemplateDto tmplat, String msgTitle, String msgBody) {
|
private SendType resolveSendType(TemplateDto tmplat, String msgTitle, String msgBody) {
|
||||||
if (NotihubConst.SMS_TYPE_CODE_LIST.contains(tmplat.getTmplatTy().getCode())) {
|
if (NotihubConst.SMS_TYPE_CODE_LIST.contains(tmplat.getTmplatTy().getCode())) {
|
||||||
|
if (tmplat.getAtchFl() != null && !tmplat.getAtchFl().isBlank()) {
|
||||||
|
return SendType.LMS_MMS;
|
||||||
|
}
|
||||||
return determineSms(msgTitle, msgBody);
|
return determineSms(msgTitle, msgBody);
|
||||||
}
|
}
|
||||||
return tmplat.getTmplatTy();
|
return tmplat.getTmplatTy();
|
||||||
@@ -434,6 +438,7 @@ public abstract class AbstractSendService {
|
|||||||
List<TSendEntity> sub = entityList.subList(i, end);
|
List<TSendEntity> sub = entityList.subList(i, end);
|
||||||
//sendRepository.saveAll(sub);
|
//sendRepository.saveAll(sub);
|
||||||
//sendRepository.flush();
|
//sendRepository.flush();
|
||||||
|
sub.forEach(TSendEntity::prepareAttachmentPathForSend);
|
||||||
sendBulkJdbcWriter.bulkInsert(sub);
|
sendBulkJdbcWriter.bulkInsert(sub);
|
||||||
|
|
||||||
afterPersistSendEntities(sub);
|
afterPersistSendEntities(sub);
|
||||||
|
|||||||
@@ -0,0 +1,417 @@
|
|||||||
|
package com.kri.notihub.server.service;
|
||||||
|
|
||||||
|
import com.kri.common.feature.web.BusinessException;
|
||||||
|
import com.kri.notihub.server.dto.email.EmailAttachmentDto;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.AtomicMoveNotSupportedException;
|
||||||
|
import java.nio.file.DirectoryStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.MediaTypeFactory;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
public abstract class AbstractTemplateAttachmentService {
|
||||||
|
|
||||||
|
private static final String DELIMITER = "|";
|
||||||
|
private static final Pattern DELIMITER_PATTERN = Pattern.compile("\\|");
|
||||||
|
private static final Pattern INVALID_FILE_NAME = Pattern.compile("[<>:\"/\\\\|?*\\p{Cntrl}]");
|
||||||
|
private static final int ATCH_FL_MAX_LENGTH = 1000;
|
||||||
|
|
||||||
|
private final Path uploadBaseDir;
|
||||||
|
private final int maxFileCount;
|
||||||
|
private final long maxFileSize;
|
||||||
|
|
||||||
|
protected AbstractTemplateAttachmentService(
|
||||||
|
String uploadBaseDir,
|
||||||
|
int maxFileCount,
|
||||||
|
long maxFileSize
|
||||||
|
) {
|
||||||
|
this.uploadBaseDir = Paths.get(uploadBaseDir).toAbsolutePath().normalize();
|
||||||
|
this.maxFileCount = maxFileCount;
|
||||||
|
this.maxFileSize = maxFileSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String create(long tmplatIdx, List<MultipartFile> files) {
|
||||||
|
return patch(tmplatIdx, null, files, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String patch(
|
||||||
|
long tmplatIdx,
|
||||||
|
String currentAtchFl,
|
||||||
|
List<MultipartFile> files,
|
||||||
|
List<String> deleteFileNames
|
||||||
|
) {
|
||||||
|
List<String> currentFileNames = parse(currentAtchFl);
|
||||||
|
List<ValidatedFile> uploadFiles = validateFiles(files);
|
||||||
|
Set<String> deleteKeys = validateDeleteFileNames(currentFileNames, deleteFileNames);
|
||||||
|
|
||||||
|
if (uploadFiles.isEmpty() && deleteKeys.isEmpty()) {
|
||||||
|
return currentFileNames.isEmpty() ? null : join(currentFileNames);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, String> currentByKey = indexByNormalizedName(currentFileNames);
|
||||||
|
for (ValidatedFile upload : uploadFiles) {
|
||||||
|
String key = normalizeKey(upload.fileName());
|
||||||
|
if (currentByKey.containsKey(key) && !deleteKeys.contains(key)) {
|
||||||
|
throw BusinessException.badRequest(errorCode("ATTACHMENT_ALREADY_EXISTS"),
|
||||||
|
"기존 첨부파일과 같은 이름을 추가하려면 삭제 목록에도 포함해야 합니다.")
|
||||||
|
.with("fileName", upload.fileName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> finalFileNames = new ArrayList<>();
|
||||||
|
for (String currentFileName : currentFileNames) {
|
||||||
|
if (!deleteKeys.contains(normalizeKey(currentFileName))) {
|
||||||
|
finalFileNames.add(currentFileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
uploadFiles.stream().map(ValidatedFile::fileName).forEach(finalFileNames::add);
|
||||||
|
validateFinalFileNames(finalFileNames);
|
||||||
|
|
||||||
|
applyFileChanges(tmplatIdx, currentFileNames, finalFileNames, uploadFiles);
|
||||||
|
return finalFileNames.isEmpty() ? null : join(finalFileNames);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<EmailAttachmentDto> load(long tmplatIdx, String atchFl) {
|
||||||
|
List<String> fileNames = parse(atchFl);
|
||||||
|
if (fileNames.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<EmailAttachmentDto> attachments = new ArrayList<>(fileNames.size());
|
||||||
|
|
||||||
|
for (String fileName : fileNames) {
|
||||||
|
attachments.add(readAttachment(tmplatIdx, fileName));
|
||||||
|
}
|
||||||
|
|
||||||
|
return attachments;
|
||||||
|
}
|
||||||
|
|
||||||
|
public EmailAttachmentDto download(long tmplatIdx, String atchFl, String requestedFileName) {
|
||||||
|
String validatedFileName = validateStoredFileName(
|
||||||
|
requestedFileName == null ? null : requestedFileName.trim()
|
||||||
|
);
|
||||||
|
String requestedKey = normalizeKey(validatedFileName);
|
||||||
|
|
||||||
|
String storedFileName = parse(atchFl).stream()
|
||||||
|
.filter(fileName -> normalizeKey(fileName).equals(requestedKey))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() ->
|
||||||
|
BusinessException.notFound(errorCode("ATTACHMENT_NOT_FOUND"), "첨부파일을 찾을 수 없습니다.")
|
||||||
|
.with("tmplatIdx", tmplatIdx)
|
||||||
|
.with("fileName", validatedFileName)
|
||||||
|
);
|
||||||
|
|
||||||
|
return readAttachment(tmplatIdx, storedFileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> parse(String atchFl) {
|
||||||
|
if (atchFl == null || atchFl.isBlank()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
return DELIMITER_PATTERN.splitAsStream(atchFl)
|
||||||
|
.map(String::trim)
|
||||||
|
.filter(value -> !value.isEmpty())
|
||||||
|
.map(this::validateStoredFileName)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<ValidatedFile> validateFiles(List<MultipartFile> files) {
|
||||||
|
if (files == null || files.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
if (files.size() > maxFileCount) {
|
||||||
|
throw BusinessException.badRequest(errorCode("ATTACHMENT_COUNT_EXCEEDED"),
|
||||||
|
"첨부파일은 최대 " + maxFileCount + "개까지 등록할 수 있습니다.")
|
||||||
|
.with("maxFileCount", maxFileCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<ValidatedFile> result = new ArrayList<>(files.size());
|
||||||
|
Set<String> duplicateCheck = new LinkedHashSet<>();
|
||||||
|
for (MultipartFile file : files) {
|
||||||
|
if (file == null || file.isEmpty()) {
|
||||||
|
throw BusinessException.badRequest(errorCode("EMPTY_ATTACHMENT"), "빈 첨부파일은 등록할 수 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
String fileName = validateUploadFileName(file.getOriginalFilename());
|
||||||
|
validateFileSize(fileName, file.getSize());
|
||||||
|
validateUploadFile(fileName, file);
|
||||||
|
|
||||||
|
if (!duplicateCheck.add(normalizeKey(fileName))) {
|
||||||
|
throw BusinessException.badRequest(errorCode("DUPLICATE_ATTACHMENT"),
|
||||||
|
"동일한 이름의 첨부파일을 중복 등록할 수 없습니다.")
|
||||||
|
.with("fileName", fileName);
|
||||||
|
}
|
||||||
|
result.add(new ValidatedFile(fileName, file));
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> validateDeleteFileNames(
|
||||||
|
List<String> currentFileNames,
|
||||||
|
List<String> deleteFileNames
|
||||||
|
) {
|
||||||
|
if (deleteFileNames == null || deleteFileNames.isEmpty()) {
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, String> currentByKey = indexByNormalizedName(currentFileNames);
|
||||||
|
Set<String> deleteKeys = new LinkedHashSet<>();
|
||||||
|
for (String value : deleteFileNames) {
|
||||||
|
String fileName = validateStoredFileName(value == null ? null : value.trim());
|
||||||
|
String key = normalizeKey(fileName);
|
||||||
|
if (!deleteKeys.add(key)) {
|
||||||
|
throw BusinessException.badRequest(errorCode("DUPLICATE_ATTACHMENT_DELETE"),
|
||||||
|
"동일한 첨부파일을 삭제 목록에 중복 지정할 수 없습니다.")
|
||||||
|
.with("fileName", fileName);
|
||||||
|
}
|
||||||
|
if (!currentByKey.containsKey(key)) {
|
||||||
|
throw BusinessException.badRequest(errorCode("ATTACHMENT_NOT_FOUND"),
|
||||||
|
"삭제할 첨부파일이 현재 템플릿에 존재하지 않습니다.")
|
||||||
|
.with("fileName", fileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return deleteKeys;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateFinalFileNames(List<String> fileNames) {
|
||||||
|
if (fileNames.size() > maxFileCount) {
|
||||||
|
throw BusinessException.badRequest(errorCode("ATTACHMENT_COUNT_EXCEEDED"),
|
||||||
|
"첨부파일은 최대 " + maxFileCount + "개까지 등록할 수 있습니다.")
|
||||||
|
.with("maxFileCount", maxFileCount)
|
||||||
|
.with("fileCount", fileNames.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
String joined = join(fileNames);
|
||||||
|
if (joined.length() > ATCH_FL_MAX_LENGTH) {
|
||||||
|
throw BusinessException.badRequest(errorCode("ATTACHMENT_NAMES_TOO_LONG"),
|
||||||
|
"첨부파일명 전체 길이는 " + ATCH_FL_MAX_LENGTH + "자를 초과할 수 없습니다.")
|
||||||
|
.with("maxLength", ATCH_FL_MAX_LENGTH);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void applyFileChanges(
|
||||||
|
long tmplatIdx,
|
||||||
|
List<String> currentFileNames,
|
||||||
|
List<String> finalFileNames,
|
||||||
|
List<ValidatedFile> uploadFiles
|
||||||
|
) {
|
||||||
|
Path templateDir = getTemplateDir(tmplatIdx);
|
||||||
|
Path stagingDir = null;
|
||||||
|
Path backupDir = null;
|
||||||
|
boolean installed = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
Files.createDirectories(uploadBaseDir);
|
||||||
|
stagingDir = Files.createTempDirectory(uploadBaseDir, "." + tmplatIdx + "-staging-");
|
||||||
|
|
||||||
|
Set<String> uploadKeys = uploadFiles.stream()
|
||||||
|
.map(ValidatedFile::fileName)
|
||||||
|
.map(this::normalizeKey)
|
||||||
|
.collect(java.util.stream.Collectors.toSet());
|
||||||
|
|
||||||
|
Map<String, String> currentByKey = indexByNormalizedName(currentFileNames);
|
||||||
|
for (String finalFileName : finalFileNames) {
|
||||||
|
if (uploadKeys.contains(normalizeKey(finalFileName))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String storedName = currentByKey.get(normalizeKey(finalFileName));
|
||||||
|
Path source = resolveFile(templateDir, storedName);
|
||||||
|
if (!Files.isRegularFile(source)) {
|
||||||
|
throw new IllegalStateException("기존 이메일 첨부파일을 찾을 수 없습니다: " + storedName);
|
||||||
|
}
|
||||||
|
Files.copy(source, resolveFile(stagingDir, storedName));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (ValidatedFile upload : uploadFiles) {
|
||||||
|
Path target = resolveFile(stagingDir, upload.fileName());
|
||||||
|
try (InputStream input = upload.file().getInputStream()) {
|
||||||
|
Files.copy(input, target, StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Files.exists(templateDir)) {
|
||||||
|
backupDir = Files.createTempDirectory(uploadBaseDir, "." + tmplatIdx + "-backup-");
|
||||||
|
Files.delete(backupDir);
|
||||||
|
moveDirectory(templateDir, backupDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (finalFileNames.isEmpty()) {
|
||||||
|
deleteFlatDirectory(stagingDir);
|
||||||
|
stagingDir = null;
|
||||||
|
} else {
|
||||||
|
moveDirectory(stagingDir, templateDir);
|
||||||
|
stagingDir = null;
|
||||||
|
installed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (backupDir != null) {
|
||||||
|
deleteFlatDirectory(backupDir);
|
||||||
|
backupDir = null;
|
||||||
|
}
|
||||||
|
} catch (IOException | RuntimeException e) {
|
||||||
|
try {
|
||||||
|
if (installed && Files.exists(templateDir)) {
|
||||||
|
deleteFlatDirectory(templateDir);
|
||||||
|
}
|
||||||
|
if (backupDir != null && Files.exists(backupDir)) {
|
||||||
|
moveDirectory(backupDir, templateDir);
|
||||||
|
backupDir = null;
|
||||||
|
}
|
||||||
|
if (stagingDir != null && Files.exists(stagingDir)) {
|
||||||
|
deleteFlatDirectory(stagingDir);
|
||||||
|
}
|
||||||
|
} catch (IOException rollbackError) {
|
||||||
|
e.addSuppressed(rollbackError);
|
||||||
|
}
|
||||||
|
throw new IllegalStateException("이메일 첨부파일 변경에 실패했습니다.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, String> indexByNormalizedName(List<String> fileNames) {
|
||||||
|
Map<String, String> result = new LinkedHashMap<>();
|
||||||
|
for (String fileName : fileNames) {
|
||||||
|
String validated = validateStoredFileName(fileName);
|
||||||
|
String previous = result.put(normalizeKey(validated), validated);
|
||||||
|
if (previous != null) {
|
||||||
|
throw new IllegalStateException("중복된 첨부파일명이 저장되어 있습니다: " + fileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String validateUploadFileName(String originalFileName) {
|
||||||
|
if (originalFileName == null || originalFileName.isBlank()) {
|
||||||
|
throw BusinessException.badRequest(errorCode("INVALID_ATTACHMENT_NAME"), "첨부파일명이 필요합니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
String normalized = originalFileName.replace('\\', '/');
|
||||||
|
String fileName = normalized.substring(normalized.lastIndexOf('/') + 1).trim();
|
||||||
|
return validateStoredFileName(fileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String validateStoredFileName(String fileName) {
|
||||||
|
if (fileName == null || fileName.isBlank()
|
||||||
|
|| ".".equals(fileName) || "..".equals(fileName)
|
||||||
|
|| fileName.endsWith(".") || fileName.endsWith(" ")
|
||||||
|
|| INVALID_FILE_NAME.matcher(fileName).find()) {
|
||||||
|
throw BusinessException.badRequest(errorCode("INVALID_ATTACHMENT_NAME"), "유효하지 않은 첨부파일명입니다.")
|
||||||
|
.with("fileName", fileName);
|
||||||
|
}
|
||||||
|
return fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateFileSize(String fileName, long fileSize) {
|
||||||
|
if (fileSize <= 0) {
|
||||||
|
throw BusinessException.badRequest(errorCode("EMPTY_ATTACHMENT"), "빈 첨부파일은 등록할 수 없습니다.")
|
||||||
|
.with("fileName", fileName);
|
||||||
|
}
|
||||||
|
if (fileSize > maxFileSize) {
|
||||||
|
throw BusinessException.badRequest(errorCode("ATTACHMENT_SIZE_EXCEEDED"),
|
||||||
|
"첨부파일 크기는 " + maxFileSize + "바이트 이하여야 합니다.")
|
||||||
|
.with("fileName", fileName)
|
||||||
|
.with("fileSize", fileSize)
|
||||||
|
.with("maxFileSize", maxFileSize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private EmailAttachmentDto readAttachment(long tmplatIdx, String fileName) {
|
||||||
|
Path path = resolveFile(getTemplateDir(tmplatIdx), validateStoredFileName(fileName));
|
||||||
|
try {
|
||||||
|
if (!Files.isRegularFile(path)) {
|
||||||
|
throw new IllegalStateException("첨부파일을 찾을 수 없습니다: " + fileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
long fileSize = Files.size(path);
|
||||||
|
validateFileSize(fileName, fileSize);
|
||||||
|
validateStoredFile(fileName, path);
|
||||||
|
|
||||||
|
String contentType = MediaTypeFactory.getMediaType(fileName)
|
||||||
|
.map(MediaType::toString)
|
||||||
|
.orElse(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
||||||
|
|
||||||
|
return new EmailAttachmentDto(fileName, contentType, Files.readAllBytes(path));
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalStateException("첨부파일을 읽는 데 실패했습니다: " + fileName, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path getTemplateDir(long tmplatIdx) {
|
||||||
|
if (tmplatIdx <= 0) {
|
||||||
|
throw new IllegalArgumentException("tmplatIdx must be positive.");
|
||||||
|
}
|
||||||
|
Path templateDir = uploadBaseDir.resolve(Long.toString(tmplatIdx)).normalize();
|
||||||
|
if (!templateDir.startsWith(uploadBaseDir)) {
|
||||||
|
throw new IllegalArgumentException("Invalid template attachment directory.");
|
||||||
|
}
|
||||||
|
return templateDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path resolveFile(Path directory, String fileName) {
|
||||||
|
Path path = directory.resolve(fileName).normalize();
|
||||||
|
if (!path.startsWith(directory)) {
|
||||||
|
throw new IllegalArgumentException("Invalid email attachment path.");
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void moveDirectory(Path source, Path target) throws IOException {
|
||||||
|
try {
|
||||||
|
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
|
||||||
|
} catch (AtomicMoveNotSupportedException e) {
|
||||||
|
Files.move(source, target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void deleteFlatDirectory(Path directory) throws IOException {
|
||||||
|
if (!Files.exists(directory)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
|
||||||
|
for (Path path : stream) {
|
||||||
|
if (!Files.isRegularFile(path)) {
|
||||||
|
throw new IOException("Unexpected directory entry: " + path);
|
||||||
|
}
|
||||||
|
Files.deleteIfExists(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Files.deleteIfExists(directory);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeKey(String fileName) {
|
||||||
|
return fileName.toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String join(List<String> fileNames) {
|
||||||
|
return String.join(DELIMITER, fileNames);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void validateUploadFile(String fileName, MultipartFile file) {
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void validateStoredFile(String fileName, Path path) throws IOException {
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String errorCode(String code) {
|
||||||
|
return code.replace("ATTACHMENT", attachmentChannel() + "_ATTACHMENT");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract String attachmentChannel();
|
||||||
|
|
||||||
|
private record ValidatedFile(String fileName, MultipartFile file) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,406 +1,21 @@
|
|||||||
package com.kri.notihub.server.service;
|
package com.kri.notihub.server.service;
|
||||||
|
|
||||||
import com.kri.common.feature.web.BusinessException;
|
|
||||||
import com.kri.notihub.server.dto.email.EmailAttachmentDto;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.nio.file.AtomicMoveNotSupportedException;
|
|
||||||
import java.nio.file.DirectoryStream;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.LinkedHashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.MediaTypeFactory;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class EmailAttachmentService {
|
public class EmailAttachmentService extends AbstractTemplateAttachmentService {
|
||||||
|
|
||||||
private static final String DELIMITER = "|";
|
|
||||||
private static final Pattern DELIMITER_PATTERN = Pattern.compile("\\|");
|
|
||||||
private static final Pattern INVALID_FILE_NAME = Pattern.compile("[<>:\"/\\\\|?*\\p{Cntrl}]");
|
|
||||||
private static final int ATCH_FL_MAX_LENGTH = 1000;
|
|
||||||
|
|
||||||
private final Path uploadBaseDir;
|
|
||||||
private final int maxFileCount;
|
|
||||||
private final long maxFileSize;
|
|
||||||
|
|
||||||
public EmailAttachmentService(
|
public EmailAttachmentService(
|
||||||
@Value("${kri.email-attachment.upload-base-dir}") String uploadBaseDir,
|
@Value("${kri.email-attachment.upload-base-dir}") String uploadBaseDir,
|
||||||
@Value("${kri.email-attachment.max-file-count:5}") int maxFileCount,
|
@Value("${kri.email-attachment.max-file-count:5}") int maxFileCount,
|
||||||
@Value("${kri.email-attachment.max-file-size:1000000}") long maxFileSize
|
@Value("${kri.email-attachment.max-file-size:1000000}") long maxFileSize
|
||||||
) {
|
) {
|
||||||
this.uploadBaseDir = Paths.get(uploadBaseDir).toAbsolutePath().normalize();
|
super(uploadBaseDir, maxFileCount, maxFileSize);
|
||||||
this.maxFileCount = maxFileCount;
|
|
||||||
this.maxFileSize = maxFileSize;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String create(long tmplatIdx, List<MultipartFile> files) {
|
@Override
|
||||||
return patch(tmplatIdx, null, files, null);
|
protected String attachmentChannel() {
|
||||||
}
|
return "EMAIL";
|
||||||
|
|
||||||
public String patch(
|
|
||||||
long tmplatIdx,
|
|
||||||
String currentAtchFl,
|
|
||||||
List<MultipartFile> files,
|
|
||||||
List<String> deleteFileNames
|
|
||||||
) {
|
|
||||||
List<String> currentFileNames = parse(currentAtchFl);
|
|
||||||
List<ValidatedFile> uploadFiles = validateFiles(files);
|
|
||||||
Set<String> deleteKeys = validateDeleteFileNames(currentFileNames, deleteFileNames);
|
|
||||||
|
|
||||||
if (uploadFiles.isEmpty() && deleteKeys.isEmpty()) {
|
|
||||||
return currentFileNames.isEmpty() ? null : join(currentFileNames);
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, String> currentByKey = indexByNormalizedName(currentFileNames);
|
|
||||||
for (ValidatedFile upload : uploadFiles) {
|
|
||||||
String key = normalizeKey(upload.fileName());
|
|
||||||
if (currentByKey.containsKey(key) && !deleteKeys.contains(key)) {
|
|
||||||
throw BusinessException.badRequest("EMAIL_ATTACHMENT_ALREADY_EXISTS",
|
|
||||||
"기존 첨부파일과 같은 이름을 추가하려면 삭제 목록에도 포함해야 합니다.")
|
|
||||||
.with("fileName", upload.fileName());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
List<String> finalFileNames = new ArrayList<>();
|
|
||||||
for (String currentFileName : currentFileNames) {
|
|
||||||
if (!deleteKeys.contains(normalizeKey(currentFileName))) {
|
|
||||||
finalFileNames.add(currentFileName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
uploadFiles.stream().map(ValidatedFile::fileName).forEach(finalFileNames::add);
|
|
||||||
validateFinalFileNames(finalFileNames);
|
|
||||||
|
|
||||||
applyFileChanges(tmplatIdx, currentFileNames, finalFileNames, uploadFiles);
|
|
||||||
return finalFileNames.isEmpty() ? null : join(finalFileNames);
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<EmailAttachmentDto> load(long tmplatIdx, String atchFl) {
|
|
||||||
List<String> fileNames = parse(atchFl);
|
|
||||||
if (fileNames.isEmpty()) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
List<EmailAttachmentDto> attachments = new ArrayList<>(fileNames.size());
|
|
||||||
|
|
||||||
for (String fileName : fileNames) {
|
|
||||||
attachments.add(readAttachment(tmplatIdx, fileName));
|
|
||||||
}
|
|
||||||
|
|
||||||
return attachments;
|
|
||||||
}
|
|
||||||
|
|
||||||
public EmailAttachmentDto download(long tmplatIdx, String atchFl, String requestedFileName) {
|
|
||||||
String validatedFileName = validateStoredFileName(
|
|
||||||
requestedFileName == null ? null : requestedFileName.trim()
|
|
||||||
);
|
|
||||||
String requestedKey = normalizeKey(validatedFileName);
|
|
||||||
|
|
||||||
String storedFileName = parse(atchFl).stream()
|
|
||||||
.filter(fileName -> normalizeKey(fileName).equals(requestedKey))
|
|
||||||
.findFirst()
|
|
||||||
.orElseThrow(() ->
|
|
||||||
BusinessException.notFound("EMAIL_ATTACHMENT_NOT_FOUND", "첨부파일을 찾을 수 없습니다.")
|
|
||||||
.with("tmplatIdx", tmplatIdx)
|
|
||||||
.with("fileName", validatedFileName)
|
|
||||||
);
|
|
||||||
|
|
||||||
return readAttachment(tmplatIdx, storedFileName);
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<String> parse(String atchFl) {
|
|
||||||
if (atchFl == null || atchFl.isBlank()) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
return DELIMITER_PATTERN.splitAsStream(atchFl)
|
|
||||||
.map(String::trim)
|
|
||||||
.filter(value -> !value.isEmpty())
|
|
||||||
.map(this::validateStoredFileName)
|
|
||||||
.toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<ValidatedFile> validateFiles(List<MultipartFile> files) {
|
|
||||||
if (files == null || files.isEmpty()) {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
if (files.size() > maxFileCount) {
|
|
||||||
throw BusinessException.badRequest("EMAIL_ATTACHMENT_COUNT_EXCEEDED",
|
|
||||||
"첨부파일은 최대 " + maxFileCount + "개까지 등록할 수 있습니다.")
|
|
||||||
.with("maxFileCount", maxFileCount);
|
|
||||||
}
|
|
||||||
|
|
||||||
List<ValidatedFile> result = new ArrayList<>(files.size());
|
|
||||||
Set<String> duplicateCheck = new LinkedHashSet<>();
|
|
||||||
for (MultipartFile file : files) {
|
|
||||||
if (file == null || file.isEmpty()) {
|
|
||||||
throw BusinessException.badRequest("EMPTY_EMAIL_ATTACHMENT", "빈 첨부파일은 등록할 수 없습니다.");
|
|
||||||
}
|
|
||||||
|
|
||||||
String fileName = validateUploadFileName(file.getOriginalFilename());
|
|
||||||
validateFileSize(fileName, file.getSize());
|
|
||||||
|
|
||||||
if (!duplicateCheck.add(normalizeKey(fileName))) {
|
|
||||||
throw BusinessException.badRequest("DUPLICATE_EMAIL_ATTACHMENT",
|
|
||||||
"동일한 이름의 첨부파일을 중복 등록할 수 없습니다.")
|
|
||||||
.with("fileName", fileName);
|
|
||||||
}
|
|
||||||
result.add(new ValidatedFile(fileName, file));
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Set<String> validateDeleteFileNames(
|
|
||||||
List<String> currentFileNames,
|
|
||||||
List<String> deleteFileNames
|
|
||||||
) {
|
|
||||||
if (deleteFileNames == null || deleteFileNames.isEmpty()) {
|
|
||||||
return Set.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, String> currentByKey = indexByNormalizedName(currentFileNames);
|
|
||||||
Set<String> deleteKeys = new LinkedHashSet<>();
|
|
||||||
for (String value : deleteFileNames) {
|
|
||||||
String fileName = validateStoredFileName(value == null ? null : value.trim());
|
|
||||||
String key = normalizeKey(fileName);
|
|
||||||
if (!deleteKeys.add(key)) {
|
|
||||||
throw BusinessException.badRequest("DUPLICATE_EMAIL_ATTACHMENT_DELETE",
|
|
||||||
"동일한 첨부파일을 삭제 목록에 중복 지정할 수 없습니다.")
|
|
||||||
.with("fileName", fileName);
|
|
||||||
}
|
|
||||||
if (!currentByKey.containsKey(key)) {
|
|
||||||
throw BusinessException.badRequest("EMAIL_ATTACHMENT_NOT_FOUND",
|
|
||||||
"삭제할 첨부파일이 현재 템플릿에 존재하지 않습니다.")
|
|
||||||
.with("fileName", fileName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return deleteKeys;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void validateFinalFileNames(List<String> fileNames) {
|
|
||||||
if (fileNames.size() > maxFileCount) {
|
|
||||||
throw BusinessException.badRequest("EMAIL_ATTACHMENT_COUNT_EXCEEDED",
|
|
||||||
"첨부파일은 최대 " + maxFileCount + "개까지 등록할 수 있습니다.")
|
|
||||||
.with("maxFileCount", maxFileCount)
|
|
||||||
.with("fileCount", fileNames.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
String joined = join(fileNames);
|
|
||||||
if (joined.length() > ATCH_FL_MAX_LENGTH) {
|
|
||||||
throw BusinessException.badRequest("EMAIL_ATTACHMENT_NAMES_TOO_LONG",
|
|
||||||
"첨부파일명 전체 길이는 " + ATCH_FL_MAX_LENGTH + "자를 초과할 수 없습니다.")
|
|
||||||
.with("maxLength", ATCH_FL_MAX_LENGTH);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applyFileChanges(
|
|
||||||
long tmplatIdx,
|
|
||||||
List<String> currentFileNames,
|
|
||||||
List<String> finalFileNames,
|
|
||||||
List<ValidatedFile> uploadFiles
|
|
||||||
) {
|
|
||||||
Path templateDir = getTemplateDir(tmplatIdx);
|
|
||||||
Path stagingDir = null;
|
|
||||||
Path backupDir = null;
|
|
||||||
boolean installed = false;
|
|
||||||
|
|
||||||
try {
|
|
||||||
Files.createDirectories(uploadBaseDir);
|
|
||||||
stagingDir = Files.createTempDirectory(uploadBaseDir, "." + tmplatIdx + "-staging-");
|
|
||||||
|
|
||||||
Set<String> uploadKeys = uploadFiles.stream()
|
|
||||||
.map(ValidatedFile::fileName)
|
|
||||||
.map(this::normalizeKey)
|
|
||||||
.collect(java.util.stream.Collectors.toSet());
|
|
||||||
|
|
||||||
Map<String, String> currentByKey = indexByNormalizedName(currentFileNames);
|
|
||||||
for (String finalFileName : finalFileNames) {
|
|
||||||
if (uploadKeys.contains(normalizeKey(finalFileName))) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String storedName = currentByKey.get(normalizeKey(finalFileName));
|
|
||||||
Path source = resolveFile(templateDir, storedName);
|
|
||||||
if (!Files.isRegularFile(source)) {
|
|
||||||
throw new IllegalStateException("기존 이메일 첨부파일을 찾을 수 없습니다: " + storedName);
|
|
||||||
}
|
|
||||||
Files.copy(source, resolveFile(stagingDir, storedName));
|
|
||||||
}
|
|
||||||
|
|
||||||
for (ValidatedFile upload : uploadFiles) {
|
|
||||||
Path target = resolveFile(stagingDir, upload.fileName());
|
|
||||||
try (InputStream input = upload.file().getInputStream()) {
|
|
||||||
Files.copy(input, target, StandardCopyOption.REPLACE_EXISTING);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Files.exists(templateDir)) {
|
|
||||||
backupDir = Files.createTempDirectory(uploadBaseDir, "." + tmplatIdx + "-backup-");
|
|
||||||
Files.delete(backupDir);
|
|
||||||
moveDirectory(templateDir, backupDir);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (finalFileNames.isEmpty()) {
|
|
||||||
deleteFlatDirectory(stagingDir);
|
|
||||||
stagingDir = null;
|
|
||||||
} else {
|
|
||||||
moveDirectory(stagingDir, templateDir);
|
|
||||||
stagingDir = null;
|
|
||||||
installed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (backupDir != null) {
|
|
||||||
deleteFlatDirectory(backupDir);
|
|
||||||
backupDir = null;
|
|
||||||
}
|
|
||||||
} catch (IOException | RuntimeException e) {
|
|
||||||
try {
|
|
||||||
if (installed && Files.exists(templateDir)) {
|
|
||||||
deleteFlatDirectory(templateDir);
|
|
||||||
}
|
|
||||||
if (backupDir != null && Files.exists(backupDir)) {
|
|
||||||
moveDirectory(backupDir, templateDir);
|
|
||||||
backupDir = null;
|
|
||||||
}
|
|
||||||
if (stagingDir != null && Files.exists(stagingDir)) {
|
|
||||||
deleteFlatDirectory(stagingDir);
|
|
||||||
}
|
|
||||||
} catch (IOException rollbackError) {
|
|
||||||
e.addSuppressed(rollbackError);
|
|
||||||
}
|
|
||||||
throw new IllegalStateException("이메일 첨부파일 변경에 실패했습니다.", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, String> indexByNormalizedName(List<String> fileNames) {
|
|
||||||
Map<String, String> result = new LinkedHashMap<>();
|
|
||||||
for (String fileName : fileNames) {
|
|
||||||
String validated = validateStoredFileName(fileName);
|
|
||||||
String previous = result.put(normalizeKey(validated), validated);
|
|
||||||
if (previous != null) {
|
|
||||||
throw new IllegalStateException("중복된 이메일 첨부파일명이 저장되어 있습니다: " + fileName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String validateUploadFileName(String originalFileName) {
|
|
||||||
if (originalFileName == null || originalFileName.isBlank()) {
|
|
||||||
throw BusinessException.badRequest("INVALID_EMAIL_ATTACHMENT_NAME", "첨부파일명이 필요합니다.");
|
|
||||||
}
|
|
||||||
|
|
||||||
String normalized = originalFileName.replace('\\', '/');
|
|
||||||
String fileName = normalized.substring(normalized.lastIndexOf('/') + 1).trim();
|
|
||||||
return validateStoredFileName(fileName);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String validateStoredFileName(String fileName) {
|
|
||||||
if (fileName == null || fileName.isBlank()
|
|
||||||
|| ".".equals(fileName) || "..".equals(fileName)
|
|
||||||
|| fileName.endsWith(".") || fileName.endsWith(" ")
|
|
||||||
|| INVALID_FILE_NAME.matcher(fileName).find()) {
|
|
||||||
throw BusinessException.badRequest("INVALID_EMAIL_ATTACHMENT_NAME", "유효하지 않은 첨부파일명입니다.")
|
|
||||||
.with("fileName", fileName);
|
|
||||||
}
|
|
||||||
return fileName;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void validateFileSize(String fileName, long fileSize) {
|
|
||||||
if (fileSize <= 0) {
|
|
||||||
throw BusinessException.badRequest("EMPTY_EMAIL_ATTACHMENT", "빈 첨부파일은 등록할 수 없습니다.")
|
|
||||||
.with("fileName", fileName);
|
|
||||||
}
|
|
||||||
if (fileSize >= maxFileSize) {
|
|
||||||
throw BusinessException.badRequest("EMAIL_ATTACHMENT_SIZE_EXCEEDED",
|
|
||||||
"첨부파일 크기는 " + maxFileSize + "바이트 미만이어야 합니다.")
|
|
||||||
.with("fileName", fileName)
|
|
||||||
.with("fileSize", fileSize)
|
|
||||||
.with("maxFileSize", maxFileSize);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private EmailAttachmentDto readAttachment(long tmplatIdx, String fileName) {
|
|
||||||
Path path = resolveFile(getTemplateDir(tmplatIdx), validateStoredFileName(fileName));
|
|
||||||
try {
|
|
||||||
if (!Files.isRegularFile(path)) {
|
|
||||||
throw new IllegalStateException("이메일 첨부파일을 찾을 수 없습니다: " + fileName);
|
|
||||||
}
|
|
||||||
|
|
||||||
long fileSize = Files.size(path);
|
|
||||||
validateFileSize(fileName, fileSize);
|
|
||||||
|
|
||||||
String contentType = MediaTypeFactory.getMediaType(fileName)
|
|
||||||
.map(MediaType::toString)
|
|
||||||
.orElse(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
|
||||||
|
|
||||||
return new EmailAttachmentDto(fileName, contentType, Files.readAllBytes(path));
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new IllegalStateException("이메일 첨부파일을 읽는 데 실패했습니다: " + fileName, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path getTemplateDir(long tmplatIdx) {
|
|
||||||
if (tmplatIdx <= 0) {
|
|
||||||
throw new IllegalArgumentException("tmplatIdx must be positive.");
|
|
||||||
}
|
|
||||||
Path templateDir = uploadBaseDir.resolve(Long.toString(tmplatIdx)).normalize();
|
|
||||||
if (!templateDir.startsWith(uploadBaseDir)) {
|
|
||||||
throw new IllegalArgumentException("Invalid template attachment directory.");
|
|
||||||
}
|
|
||||||
return templateDir;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path resolveFile(Path directory, String fileName) {
|
|
||||||
Path path = directory.resolve(fileName).normalize();
|
|
||||||
if (!path.startsWith(directory)) {
|
|
||||||
throw new IllegalArgumentException("Invalid email attachment path.");
|
|
||||||
}
|
|
||||||
return path;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void moveDirectory(Path source, Path target) throws IOException {
|
|
||||||
try {
|
|
||||||
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
|
|
||||||
} catch (AtomicMoveNotSupportedException e) {
|
|
||||||
Files.move(source, target);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void deleteFlatDirectory(Path directory) throws IOException {
|
|
||||||
if (!Files.exists(directory)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
|
|
||||||
for (Path path : stream) {
|
|
||||||
if (!Files.isRegularFile(path)) {
|
|
||||||
throw new IOException("Unexpected directory entry: " + path);
|
|
||||||
}
|
|
||||||
Files.deleteIfExists(path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Files.deleteIfExists(directory);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String normalizeKey(String fileName) {
|
|
||||||
return fileName.toLowerCase(Locale.ROOT);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String join(List<String> fileNames) {
|
|
||||||
return String.join(DELIMITER, fileNames);
|
|
||||||
}
|
|
||||||
|
|
||||||
private record ValidatedFile(String fileName, MultipartFile file) {
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package com.kri.notihub.server.service;
|
||||||
|
|
||||||
|
import com.kri.common.feature.web.BusinessException;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
import javax.imageio.ImageReader;
|
||||||
|
import javax.imageio.stream.ImageInputStream;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class MmsAttachmentService extends AbstractTemplateAttachmentService {
|
||||||
|
|
||||||
|
private static final String JPEG_CONTENT_TYPE = "image/jpeg";
|
||||||
|
private static final long MAX_DECODED_PIXELS = 20_000_000;
|
||||||
|
|
||||||
|
public MmsAttachmentService(
|
||||||
|
@Value("${kri.mms-attachment.upload-base-dir}") String uploadBaseDir,
|
||||||
|
@Value("${kri.mms-attachment.accept-type}") String acceptType,
|
||||||
|
@Value("${kri.mms-attachment.max-file-count}") int maxFileCount,
|
||||||
|
@Value("${kri.mms-attachment.max-file-size}") long maxFileSize
|
||||||
|
) {
|
||||||
|
super(uploadBaseDir, maxFileCount, maxFileSize);
|
||||||
|
if (!JPEG_CONTENT_TYPE.equalsIgnoreCase(acceptType)) {
|
||||||
|
throw new IllegalArgumentException("MMS attachment accept-type must be image/jpeg.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void validateUploadFile(String fileName, MultipartFile file) {
|
||||||
|
validateNameAndContentType(fileName, file.getContentType());
|
||||||
|
try (InputStream input = file.getInputStream()) {
|
||||||
|
validateJpeg(input);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw BusinessException.badRequest("INVALID_MMS_ATTACHMENT", "JPG 첨부파일을 읽을 수 없습니다.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void validateStoredFile(String fileName, Path path) throws IOException {
|
||||||
|
validateNameAndContentType(fileName, JPEG_CONTENT_TYPE);
|
||||||
|
try (InputStream input = Files.newInputStream(path)) {
|
||||||
|
validateJpeg(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateNameAndContentType(String fileName, String contentType) {
|
||||||
|
if (!fileName.toLowerCase(java.util.Locale.ROOT).endsWith(".jpg")
|
||||||
|
|| !JPEG_CONTENT_TYPE.equalsIgnoreCase(contentType)) {
|
||||||
|
throw BusinessException.badRequest("INVALID_MMS_ATTACHMENT_TYPE",
|
||||||
|
"JPG(image/jpeg) 첨부파일만 등록할 수 있습니다.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String attachmentChannel() {
|
||||||
|
return "MMS";
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateJpeg(InputStream input) throws IOException {
|
||||||
|
try (ImageInputStream imageInput = ImageIO.createImageInputStream(input)) {
|
||||||
|
if (imageInput == null) {
|
||||||
|
throw invalidJpeg();
|
||||||
|
}
|
||||||
|
Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInput);
|
||||||
|
if (!readers.hasNext()) {
|
||||||
|
throw invalidJpeg();
|
||||||
|
}
|
||||||
|
ImageReader reader = readers.next();
|
||||||
|
try {
|
||||||
|
if (!"JPEG".equalsIgnoreCase(reader.getFormatName())) {
|
||||||
|
throw invalidJpeg();
|
||||||
|
}
|
||||||
|
reader.setInput(imageInput);
|
||||||
|
long pixels = (long) reader.getWidth(0) * reader.getHeight(0);
|
||||||
|
if (pixels <= 0 || pixels > MAX_DECODED_PIXELS || reader.read(0) == null) {
|
||||||
|
throw invalidJpeg();
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw invalidJpeg();
|
||||||
|
} finally {
|
||||||
|
reader.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BusinessException invalidJpeg() {
|
||||||
|
return BusinessException.badRequest("INVALID_MMS_ATTACHMENT_TYPE",
|
||||||
|
"올바른 JPG 이미지 파일이 아닙니다.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,7 +19,6 @@ import com.kri.notihub.server.persistence.repository.TemplateEventLogRepository;
|
|||||||
import com.kri.notihub.server.persistence.repository.TemplateRepository;
|
import com.kri.notihub.server.persistence.repository.TemplateRepository;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.log4j.Log4j2;
|
import lombok.extern.log4j.Log4j2;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -35,6 +34,7 @@ public class TemplateService {
|
|||||||
private final TemplateEventLogRepository templateEventLogRepository;
|
private final TemplateEventLogRepository templateEventLogRepository;
|
||||||
private final FileService fileService;
|
private final FileService fileService;
|
||||||
private final EmailAttachmentService emailAttachmentService;
|
private final EmailAttachmentService emailAttachmentService;
|
||||||
|
private final MmsAttachmentService mmsAttachmentService;
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public TemplateDto createTemplate(
|
public TemplateDto createTemplate(
|
||||||
@@ -43,14 +43,17 @@ public class TemplateService {
|
|||||||
List<MultipartFile> files,
|
List<MultipartFile> files,
|
||||||
String regUser
|
String regUser
|
||||||
) {
|
) {
|
||||||
if (hasAttachments(files) && template.getTmplatTy() != SendType.EMAIL) {
|
if (hasAttachments(files) && !supportsAttachments(template.getTmplatTy())) {
|
||||||
throw BusinessException.badRequest("EMAIL_ATTACHMENT_ONLY",
|
throw BusinessException.badRequest("EMAIL_ATTACHMENT_ONLY",
|
||||||
"첨부파일은 이메일 템플릿에만 등록할 수 있습니다.");
|
"첨부파일은 이메일 또는 문자 템플릿에만 등록할 수 있습니다.");
|
||||||
}
|
}
|
||||||
|
|
||||||
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
|
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
|
||||||
validateBySendType(template);
|
validateBySendType(template);
|
||||||
TemplateContentSanitizer.sanitizeAndNormalizeInPlace(template);
|
TemplateContentSanitizer.sanitizeAndNormalizeInPlace(template);
|
||||||
|
if (hasAttachments(files) && template.getTmplatTy() == SendType.SMS) {
|
||||||
|
template.setTmplatTy(SendType.LMS_MMS);
|
||||||
|
}
|
||||||
|
|
||||||
TTmplatEntity entity = TTmplatEntity.create(itrntPrjctCd, template, regUser, now);
|
TTmplatEntity entity = TTmplatEntity.create(itrntPrjctCd, template, regUser, now);
|
||||||
entity.setAtchFl(null);
|
entity.setAtchFl(null);
|
||||||
@@ -64,7 +67,8 @@ public class TemplateService {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
if (hasAttachments(files)) {
|
if (hasAttachments(files)) {
|
||||||
entity.setAtchFl(emailAttachmentService.create(entity.getTmplatIdx(), files));
|
entity.setAtchFl(attachmentService(template.getTmplatTy())
|
||||||
|
.create(entity.getTmplatIdx(), files));
|
||||||
}
|
}
|
||||||
templateRepository.save(entity);
|
templateRepository.save(entity);
|
||||||
|
|
||||||
@@ -102,12 +106,13 @@ public class TemplateService {
|
|||||||
.with("tmplatIdx", tmplatIdx)
|
.with("tmplatIdx", tmplatIdx)
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!Objects.equals(entity.getTmplatTy(), SendType.EMAIL.getCode())) {
|
SendType type = SendType.fromCode(entity.getTmplatTy());
|
||||||
|
if (!supportsAttachments(type)) {
|
||||||
throw BusinessException.badRequest("EMAIL_ATTACHMENT_ONLY",
|
throw BusinessException.badRequest("EMAIL_ATTACHMENT_ONLY",
|
||||||
"이메일 템플릿의 첨부파일만 다운로드할 수 있습니다.");
|
"이메일 또는 문자 템플릿의 첨부파일만 다운로드할 수 있습니다.");
|
||||||
}
|
}
|
||||||
|
|
||||||
return emailAttachmentService.download(tmplatIdx, entity.getAtchFl(), fileName);
|
return attachmentService(type).download(tmplatIdx, entity.getAtchFl(), fileName);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@@ -133,9 +138,16 @@ public class TemplateService {
|
|||||||
validateBySendType(template);
|
validateBySendType(template);
|
||||||
|
|
||||||
boolean attachmentChanged = hasAttachments(files) || hasDeleteFileNames(deleteFileNames);
|
boolean attachmentChanged = hasAttachments(files) || hasDeleteFileNames(deleteFileNames);
|
||||||
if (attachmentChanged && template.getTmplatTy() != SendType.EMAIL) {
|
if (attachmentChanged && !supportsAttachments(template.getTmplatTy())) {
|
||||||
throw BusinessException.badRequest("EMAIL_ATTACHMENT_ONLY",
|
throw BusinessException.badRequest("EMAIL_ATTACHMENT_ONLY",
|
||||||
"첨부파일은 이메일 템플릿에만 등록할 수 있습니다.");
|
"첨부파일은 이메일 또는 문자 템플릿에만 등록할 수 있습니다.");
|
||||||
|
}
|
||||||
|
SendType previousType = SendType.fromCode(entity.getTmplatTy());
|
||||||
|
if (entity.getAtchFl() != null && !entity.getAtchFl().isBlank()
|
||||||
|
&& (!supportsAttachments(template.getTmplatTy())
|
||||||
|
|| (previousType == SendType.EMAIL) != (template.getTmplatTy() == SendType.EMAIL))) {
|
||||||
|
throw BusinessException.badRequest("ATTACHMENT_TYPE_CHANGE",
|
||||||
|
"첨부파일을 모두 삭제한 뒤 템플릿 타입을 변경할 수 있습니다.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (template.getTmplatTy() == SendType.EMAIL) {
|
if (template.getTmplatTy() == SendType.EMAIL) {
|
||||||
@@ -148,12 +160,17 @@ public class TemplateService {
|
|||||||
|
|
||||||
//제목, 본문 정규화
|
//제목, 본문 정규화
|
||||||
TemplateContentSanitizer.sanitizeAndNormalizeInPlace(template);
|
TemplateContentSanitizer.sanitizeAndNormalizeInPlace(template);
|
||||||
|
if (template.getTmplatTy() == SendType.SMS
|
||||||
|
&& (hasAttachments(files) || (previousType != SendType.EMAIL
|
||||||
|
&& entity.getAtchFl() != null && !entity.getAtchFl().isBlank()))) {
|
||||||
|
template.setTmplatTy(SendType.LMS_MMS);
|
||||||
|
}
|
||||||
|
|
||||||
TemplateBasicDto before = TemplateDto.from(entity);
|
TemplateBasicDto before = TemplateDto.from(entity);
|
||||||
|
|
||||||
entity.updateFrom(template, modUser, now);
|
entity.updateFrom(template, modUser, now);
|
||||||
if (attachmentChanged) {
|
if (attachmentChanged) {
|
||||||
entity.setAtchFl(emailAttachmentService.patch(
|
entity.setAtchFl(attachmentService(template.getTmplatTy()).patch(
|
||||||
tmplatIdx,
|
tmplatIdx,
|
||||||
entity.getAtchFl(),
|
entity.getAtchFl(),
|
||||||
files,
|
files,
|
||||||
@@ -161,6 +178,12 @@ public class TemplateService {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (template.getTmplatTy() == SendType.LMS_MMS
|
||||||
|
&& (entity.getAtchFl() == null || entity.getAtchFl().isBlank())) {
|
||||||
|
entity.setTmplatTy(TemplateContentSanitizer.determineSms(
|
||||||
|
entity.getTmplatTitle(), entity.getTmplatBody()).getCode());
|
||||||
|
}
|
||||||
|
|
||||||
templateRepository.save(entity);
|
templateRepository.save(entity);
|
||||||
|
|
||||||
TemplateDto after = TemplateDto.from(entity);
|
TemplateDto after = TemplateDto.from(entity);
|
||||||
@@ -214,6 +237,14 @@ public class TemplateService {
|
|||||||
return deleteFileNames != null && !deleteFileNames.isEmpty();
|
return deleteFileNames != null && !deleteFileNames.isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean supportsAttachments(SendType type) {
|
||||||
|
return type == SendType.EMAIL || type == SendType.SMS || type == SendType.LMS_MMS;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AbstractTemplateAttachmentService attachmentService(SendType type) {
|
||||||
|
return type == SendType.EMAIL ? emailAttachmentService : mmsAttachmentService;
|
||||||
|
}
|
||||||
|
|
||||||
private void validateBySendType(TemplateBasicDto template) {
|
private void validateBySendType(TemplateBasicDto template) {
|
||||||
//공통 검증
|
//공통 검증
|
||||||
if (template.getTmplatPurpose() == null) {
|
if (template.getTmplatPurpose() == null) {
|
||||||
|
|||||||
@@ -105,10 +105,16 @@ kri:
|
|||||||
temp-cleanup-cron: "0 0 0 * * *" # 매일 00:00(초 분 시 일 월 요일)
|
temp-cleanup-cron: "0 0 0 * * *" # 매일 00:00(초 분 시 일 월 요일)
|
||||||
|
|
||||||
email-attachment:
|
email-attachment:
|
||||||
upload-base-dir: ${NOTIHUB_EMAIL_ATTACHMENT_DIR:./upload-file/email-attachment}
|
upload-base-dir: ./upload-file/email-attachment
|
||||||
max-file-count: 5
|
max-file-count: 5
|
||||||
max-file-size: 1000000
|
max-file-size: 1000000
|
||||||
|
|
||||||
|
mms-attachment:
|
||||||
|
upload-base-dir: ./upload-file/mms-attachment
|
||||||
|
accept-type: image/jpeg
|
||||||
|
max-file-count: 3
|
||||||
|
max-file-size: 61440
|
||||||
|
|
||||||
qr:
|
qr:
|
||||||
public-base-url: https://short-url.kric.com/api/v1/qr
|
public-base-url: https://short-url.kric.com/api/v1/qr
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user