Merge branch 'susu' into dev
This commit is contained in:
@@ -7,8 +7,7 @@ import lombok.RequiredArgsConstructor;
|
||||
@RequiredArgsConstructor
|
||||
public enum FileStorageType {
|
||||
LOCAL("로컬 스토리지"),
|
||||
S3("AWS S3 스토리지"),
|
||||
SFTP("SFTP");
|
||||
S3("AWS S3 스토리지");
|
||||
private final String desc;
|
||||
private String name;
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ public enum FileUploadType {
|
||||
// URI og:image 용 이미지 파일
|
||||
OG_IMAGE(Set.of(FileStorageType.LOCAL), "/ogImage", Set.of(AcceptableFileType.IMAGE)),
|
||||
// WEB Editor 이미지 파일
|
||||
EDITOR_IMAGE(Set.of(FileStorageType.SFTP,FileStorageType.LOCAL), "/editorImage", Set.of(AcceptableFileType.IMAGE)),
|
||||
EDITOR_IMAGE(Set.of(FileStorageType.LOCAL), "/editorImage", Set.of(AcceptableFileType.IMAGE)),
|
||||
|
||||
PUBLIC(
|
||||
Set.of(FileStorageType.LOCAL),
|
||||
@@ -43,7 +43,6 @@ public enum FileUploadType {
|
||||
AcceptableFileType.ZIP)),
|
||||
NOTICE(
|
||||
Set.of(
|
||||
FileStorageType.SFTP,
|
||||
FileStorageType.LOCAL
|
||||
),
|
||||
"/notice",
|
||||
@@ -58,14 +57,14 @@ public enum FileUploadType {
|
||||
AcceptableFileType.PDF,
|
||||
AcceptableFileType.ZIP)),
|
||||
INCOME(
|
||||
Set.of(FileStorageType.SFTP,FileStorageType.LOCAL),
|
||||
Set.of(FileStorageType.LOCAL),
|
||||
"/income",
|
||||
Set.of(
|
||||
AcceptableFileType.IMAGE
|
||||
)
|
||||
),
|
||||
EXPENSE(
|
||||
Set.of(FileStorageType.SFTP,FileStorageType.LOCAL),
|
||||
Set.of(FileStorageType.LOCAL),
|
||||
"/expense",
|
||||
Set.of(
|
||||
AcceptableFileType.IMAGE
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
package app.module.core.config.application.util;
|
||||
|
||||
import app.module.core.usecase.file.getFile.adapters.persistence.GetFileMapper;
|
||||
import app.module.core.usecase.file.getFile.ports.application.domain.GetFile;
|
||||
import app.module.core.usecase.file.saveToStorage.ports.application.strategy.SftpConnector;
|
||||
import app.module.core.usecase.file.updateFile.adapters.persistence.UpdateFileMapper;
|
||||
import app.module.core.usecase.file.updateFile.ports.application.domain.UploadFileDto;
|
||||
import com.jcraft.jsch.ChannelSftp;
|
||||
import com.jcraft.jsch.JSchException;
|
||||
import com.jcraft.jsch.SftpException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.file.Paths;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class SftpFileDeleteUtil {
|
||||
|
||||
private final SftpConnector sftpConnector;
|
||||
private final GetFileMapper getFileMapper;
|
||||
private final UpdateFileMapper updateFileMapper;
|
||||
|
||||
@Value("${path.upload.sftp.public}")
|
||||
private String publicPath;
|
||||
|
||||
/**
|
||||
* SFTP 서버에서 파일을 삭제하는 공통 메서드
|
||||
* @param deleteFile 삭제할 파일 정보
|
||||
* @throws JSchException SFTP 연결 오류
|
||||
* @throws SftpException SFTP 작업 오류
|
||||
*/
|
||||
public void deleteRealFile(UploadFileDto deleteFile) throws JSchException, SftpException {
|
||||
if (deleteFile == null || deleteFile.getPath() == null || deleteFile.getName() == null) {
|
||||
log.error("Invalid file information: {}", deleteFile);
|
||||
throw new IllegalArgumentException("Invalid file information");
|
||||
}
|
||||
|
||||
// 경로 검증 및 생성
|
||||
String filePath = constructSafeFilePath(deleteFile.getPath(), deleteFile.getName());
|
||||
log.info("Attempting to delete file from SFTP: {}", filePath);
|
||||
|
||||
// SFTP 연결 확인 및 재연결
|
||||
if (!sftpConnector.isConnected()) {
|
||||
log.warn("SFTP connection lost, attempting to reconnect");
|
||||
sftpConnector.connect();
|
||||
}
|
||||
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
|
||||
if (channelSftp == null) {
|
||||
log.error("SFTP channel is not initialized");
|
||||
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
|
||||
}
|
||||
|
||||
// 파일 삭제
|
||||
try {
|
||||
channelSftp.stat(filePath); // 파일 존재 여부 확인
|
||||
channelSftp.rm(filePath);
|
||||
log.info("File deleted successfully from SFTP: {}", filePath);
|
||||
} catch (SftpException e) {
|
||||
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
|
||||
log.warn("File does not exist on SFTP: {}", filePath);
|
||||
} else {
|
||||
log.error("Failed to delete file from SFTP: {}, error: {}", filePath, e.getMessage(), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteRealFile(Long deleteFileId) throws JSchException, SftpException {
|
||||
GetFile deleteFile = getFileMapper.findById(deleteFileId).orElseThrow();
|
||||
updateFileMapper.deleteReceiptFile(deleteFileId,CommonUtil.getLoginUsername());
|
||||
|
||||
if (deleteFile == null || deleteFile.getPath() == null || deleteFile.getName() == null) {
|
||||
log.error("Invalid file information: {}", deleteFile);
|
||||
throw new IllegalArgumentException("Invalid file information");
|
||||
}
|
||||
|
||||
// 경로 검증 및 생성
|
||||
String filePath = constructSafeFilePath(deleteFile.getPath(), deleteFile.getName());
|
||||
log.info("Attempting to delete file from SFTP: {}", filePath);
|
||||
|
||||
// SFTP 연결 확인 및 재연결
|
||||
if (!sftpConnector.isConnected()) {
|
||||
log.warn("SFTP connection lost, attempting to reconnect");
|
||||
sftpConnector.connect();
|
||||
}
|
||||
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
|
||||
if (channelSftp == null) {
|
||||
log.error("SFTP channel is not initialized");
|
||||
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
|
||||
}
|
||||
|
||||
// 파일 삭제
|
||||
try {
|
||||
channelSftp.stat(filePath); // 파일 존재 여부 확인
|
||||
channelSftp.rm(filePath);
|
||||
log.info("File deleted successfully from SFTP: {}", filePath);
|
||||
} catch (SftpException e) {
|
||||
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
|
||||
log.warn("File does not exist on SFTP: {}", filePath);
|
||||
} else {
|
||||
log.error("Failed to delete file from SFTP: {}, error: {}", filePath, e.getMessage(), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 경로 조작 방지를 위해 안전한 파일 경로 생성
|
||||
*/
|
||||
private String constructSafeFilePath(String subPath, String fileName) {
|
||||
// 경로 및 파일 이름 정규화
|
||||
String normalizedSubPath = Paths.get(subPath).normalize().toString().replace("\\", "/");
|
||||
String normalizedFileName = Paths.get(fileName).getFileName().toString();
|
||||
String safePath = CommonUtil.removeLastChar(publicPath, "/") + "/" + normalizedSubPath + "/" + normalizedFileName;
|
||||
|
||||
// 경로가 publicPath로 시작하는지 검증
|
||||
if (!safePath.startsWith(publicPath)) {
|
||||
log.error("Invalid file path detected: {}", safePath);
|
||||
throw new IllegalArgumentException("Invalid file path: " + safePath);
|
||||
}
|
||||
|
||||
return safePath;
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
package app.module.core.config.application.util;
|
||||
|
||||
import app.module.core.usecase.file.getFile.ports.application.domain.GetFile;
|
||||
import app.module.core.usecase.file.saveToStorage.ports.application.strategy.SftpConnector;
|
||||
import com.jcraft.jsch.ChannelSftp;
|
||||
import com.jcraft.jsch.JSchException;
|
||||
import com.jcraft.jsch.SftpException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class SftpFileDownloader {
|
||||
private final SftpConnector sftpConnector;
|
||||
private final AESEncryptUtil encryptUtil;
|
||||
|
||||
@Value("${path.upload.sftp.public}")
|
||||
private String publicPath;
|
||||
|
||||
@Value("${file.download.base-path:/tmp/downloads}")
|
||||
private String defaultDownloadBasePath;
|
||||
|
||||
public void downloadFile(GetFile file) throws JSchException, SftpException, IOException {
|
||||
// SFTP 연결 확인 및 재연결
|
||||
if (!sftpConnector.isConnected()) {
|
||||
log.info("SFTP connection lost, attempting to reconnect");
|
||||
sftpConnector.connect();
|
||||
}
|
||||
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
|
||||
if (channelSftp == null) {
|
||||
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
// 원격 파일 경로 (암호화된 파일명 사용)
|
||||
String remoteFilePath = CommonUtil.removeLastChar(publicPath, "/") + file.getPath() + "/" +"encrypted_"+ file.getName();
|
||||
log.info("Remote file path: {}", remoteFilePath);
|
||||
|
||||
// 다운로드 경로 정규화
|
||||
String basePath = CommonUtil.normalizePath(defaultDownloadBasePath);
|
||||
log.info("Base path: {}", basePath);
|
||||
String localEncryptedFilePath = basePath + File.separator + "encrypted_" + file.getOriginName();
|
||||
String localDecryptedFilePath = basePath + File.separator + file.getOriginName();
|
||||
log.info("Local encrypted file path: {}", localEncryptedFilePath);
|
||||
log.info("Local decrypted file path: {}", localDecryptedFilePath);
|
||||
|
||||
// 로컬 디렉토리 생성
|
||||
File localDir = new File(localEncryptedFilePath).getParentFile();
|
||||
CommonUtil.createDirectories(localDir);
|
||||
|
||||
// 원격 파일 존재 여부 확인 (디버깅 용)
|
||||
try {
|
||||
channelSftp.lstat(remoteFilePath);
|
||||
log.info("Remote file exists: {}", remoteFilePath);
|
||||
} catch (SftpException e) {
|
||||
log.error("Remote file does not exist: {}", remoteFilePath, e);
|
||||
throw new SftpException(ChannelSftp.SSH_FX_NO_SUCH_FILE, "Remote file does not exist: " + remoteFilePath);
|
||||
}
|
||||
|
||||
// 암호화된 파일 다운로드
|
||||
try (FileOutputStream fos = new FileOutputStream(localEncryptedFilePath)) {
|
||||
channelSftp.get(remoteFilePath, fos);
|
||||
log.info("File downloaded to: {}", localEncryptedFilePath);
|
||||
}
|
||||
|
||||
// 파일 복호화
|
||||
try {
|
||||
byte[] encryptedContent = Files.readAllBytes(Paths.get(localEncryptedFilePath));
|
||||
byte[] decryptedContent = encryptUtil.decryptAesCbc(encryptedContent);
|
||||
Files.write(Paths.get(localDecryptedFilePath), decryptedContent);
|
||||
log.info("File decrypted and saved to: {}", localDecryptedFilePath);
|
||||
file.setLocalPath(localDecryptedFilePath);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to decrypt file: {}", file.getOriginName(), e);
|
||||
throw new IOException("Failed to decrypt file", e);
|
||||
} finally {
|
||||
// 암호화된 임시 파일 삭제
|
||||
Files.deleteIfExists(Paths.get(localEncryptedFilePath));
|
||||
log.info("Temporary encrypted file deleted: {}", localEncryptedFilePath);
|
||||
}
|
||||
|
||||
} catch (SftpException e) {
|
||||
log.error("Failed to download file: {} (Error: {})", file.getOriginName(), e.getMessage());
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
log.error("IO error during file download or decryption: {}", file.getOriginName(), e);
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("Unexpected error during file download: {}", file.getOriginName(), e);
|
||||
throw new RuntimeException("Unexpected error during file download", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package app.module.core.usecase.file.downloadFile.adapters;
|
||||
|
||||
import app.module.core.config.application.util.SftpFileDownloader;
|
||||
import app.module.core.usecase.file.getFile.ports.GetFilePortIn;
|
||||
import app.module.core.usecase.file.getFile.ports.application.domain.GetFile;
|
||||
import app.module.core.usecase.file.getFile.ports.application.domain.GetFileCmd;
|
||||
import com.jcraft.jsch.JSchException;
|
||||
import com.jcraft.jsch.SftpException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
class DownloadFileController {
|
||||
private final GetFilePortIn getFilePortIn;
|
||||
private final SftpFileDownloader sftpFileDownloader;
|
||||
|
||||
@GetMapping(path = "/api/file/download/{fileId}")
|
||||
ResponseEntity<?> downloadFile(@PathVariable Long fileId) throws JSchException, SftpException, IOException {
|
||||
GetFile file = getFilePortIn.operate(new GetFileCmd(fileId)).orElseThrow(() -> new IllegalArgumentException("File not found: " + fileId));
|
||||
|
||||
// SFTP에서 파일 다운로드
|
||||
sftpFileDownloader.downloadFile(file);
|
||||
|
||||
// 로컬 파일 경로
|
||||
File downloadedFile = new File(file.getLocalPath());
|
||||
if (!downloadedFile.exists()) {
|
||||
throw new IllegalStateException("파일 다운로드에 실패하였습니다.");
|
||||
}
|
||||
|
||||
|
||||
String encodedFileName = URLEncoder.encode(file.getOriginName(), StandardCharsets.UTF_8)
|
||||
.replace("+", "%20");
|
||||
// HTTP 헤더 설정
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName);
|
||||
headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
|
||||
headers.add(HttpHeaders.PRAGMA, "no-cache");
|
||||
headers.add(HttpHeaders.EXPIRES, "0");
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.headers(headers)
|
||||
.contentLength(downloadedFile.length())
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.body(new FileSystemResource(downloadedFile));
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package app.module.core.usecase.file.saveToStorage.ports.application.strategy;
|
||||
|
||||
import com.jcraft.jsch.ChannelSftp;
|
||||
import com.jcraft.jsch.JSch;
|
||||
import com.jcraft.jsch.JSchException;
|
||||
import com.jcraft.jsch.Session;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class SftpConnector {
|
||||
@Value("${file.upload.sftp.ip}")
|
||||
private String host;
|
||||
@Value("${file.upload.sftp.id}")
|
||||
private String id;
|
||||
@Value("${file.upload.sftp.password}")
|
||||
private String password;
|
||||
|
||||
@Value("${file.upload.sftp.port}")
|
||||
private int port;
|
||||
|
||||
private Session session;
|
||||
private ChannelSftp channelSftp;
|
||||
|
||||
public void connect() throws JSchException {
|
||||
|
||||
if (host == null || id == null || password == null) {
|
||||
throw new IllegalStateException("SFTP configuration is incomplete: host=" + host + ", id=" + id + ", password=" + (password != null ? "****" : null));
|
||||
}
|
||||
|
||||
try {
|
||||
JSch jsch = new JSch();
|
||||
// 세션 설정
|
||||
session = jsch.getSession(id, host, port);
|
||||
session.setPassword(password);
|
||||
// 호스트 키 검증 비활성화 (개발 환경에서만 사용, 프로덕션에서는 적절히 설정)
|
||||
session.setConfig("StrictHostKeyChecking", "no");
|
||||
// 연결
|
||||
session.connect();
|
||||
|
||||
// SFTP 채널 열기
|
||||
channelSftp = (ChannelSftp) session.openChannel("sftp");
|
||||
channelSftp.connect();
|
||||
log.info("SFTP connection established successfully");
|
||||
}catch (JSchException e){
|
||||
log.error("Failed to connect to SFTP server", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
if (channelSftp != null && channelSftp.isConnected()) {
|
||||
channelSftp.disconnect();
|
||||
log.info("SFTP channel disconnected");
|
||||
}
|
||||
if (session != null && session.isConnected()) {
|
||||
session.disconnect();
|
||||
log.info("SFTP channel disconnected");
|
||||
}
|
||||
}
|
||||
public boolean isConnected() {
|
||||
return channelSftp != null && channelSftp.isConnected() && session != null && session.isConnected();
|
||||
}
|
||||
|
||||
// ChannelSftp 객체 반환
|
||||
public ChannelSftp getChannelSftp() {
|
||||
return channelSftp;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package app.module.core.usecase.file.saveToStorage.ports.application.strategy;
|
||||
|
||||
import app.module.core.config.application.enums.FileStorageType;
|
||||
import app.module.core.config.application.util.AESEncryptUtil;
|
||||
import app.module.core.config.application.util.CommonUtil;
|
||||
import com.jcraft.jsch.ChannelSftp;
|
||||
import com.jcraft.jsch.JSchException;
|
||||
import com.jcraft.jsch.SftpException;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class SftpStorageFileUploadStrategy implements FileUploadStrategy {
|
||||
@Value("${path.upload.sftp.public}")
|
||||
private String publicPath;
|
||||
|
||||
private final SftpConnector sftpConnector;
|
||||
private final AESEncryptUtil aesEncryptUtil;
|
||||
|
||||
@PostConstruct
|
||||
public void initialize() throws Exception {
|
||||
log.info("FileIoService - initialize : path.upload.public is {}", publicPath);
|
||||
|
||||
try {
|
||||
// SFTP 연결 초기화
|
||||
sftpConnector.connect();
|
||||
// 원격 디렉토리 생성
|
||||
createRemoteDirectories(publicPath);
|
||||
} catch (JSchException | SftpException e) {
|
||||
throw new IOException("Could not initialize SFTP connection or directories", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void createRemoteDirectories(String path) throws SftpException {
|
||||
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
|
||||
if (channelSftp != null) {
|
||||
String[] folders = path.split("/");
|
||||
String currentPath = "";
|
||||
for (String folder : folders) {
|
||||
if (!folder.isEmpty()) {
|
||||
currentPath += "/" + folder;
|
||||
try {
|
||||
channelSftp.cd(currentPath);
|
||||
} catch (SftpException e) {
|
||||
channelSftp.mkdir(currentPath);
|
||||
channelSftp.cd(currentPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileStorageType getStorageType() {
|
||||
return FileStorageType.SFTP;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void operate(MultipartFile multipartFile, String createSubPath, String createFilename) throws IOException {
|
||||
if (multipartFile == null || multipartFile.isEmpty()) {
|
||||
throw new IllegalArgumentException("파일이 비어 있거나 null입니다.");
|
||||
}
|
||||
|
||||
// 경로 조작 방지를 위해 subPath와 filename 유효성 검사
|
||||
if (createSubPath == null || createSubPath.contains("..") || createFilename == null || createFilename.contains("..")) {
|
||||
throw new IllegalArgumentException("잘못된 파일 경로 또는 이름입니다.");
|
||||
}
|
||||
|
||||
// 메모리 내에서 파일 암호화
|
||||
byte[] encryptedContent;
|
||||
try {
|
||||
byte[] fileContent = multipartFile.getBytes(); // 파일을 메모리로 직접 읽음
|
||||
encryptedContent = aesEncryptUtil.encryptAesCbc(fileContent); // 암호화
|
||||
} catch (Exception e) {
|
||||
log.error("파일 암호화 실패: {}", createFilename, e);
|
||||
throw new IOException("파일 암호화에 실패했습니다.", e);
|
||||
}
|
||||
|
||||
// SFTP 경로 생성
|
||||
String remotePath = CommonUtil.removeLastChar(publicPath, "/") + createSubPath;
|
||||
String remoteFilePath = remotePath + "/encrypted_" + createFilename;
|
||||
|
||||
// SFTP 업로드
|
||||
try {
|
||||
// 연결 상태 확인 및 재연결 (최대 3회 시도)
|
||||
int retryCount = 0;
|
||||
while (!sftpConnector.isConnected() && retryCount < 3) {
|
||||
log.warn("SFTP 연결이 끊겼습니다. 재연결 시도 {}회", retryCount + 1);
|
||||
sftpConnector.connect();
|
||||
retryCount++;
|
||||
}
|
||||
if (!sftpConnector.isConnected()) {
|
||||
throw new IOException("SFTP 서버에 연결할 수 없습니다.");
|
||||
}
|
||||
|
||||
createRemoteDirectories(remotePath);
|
||||
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
|
||||
if (channelSftp == null) {
|
||||
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP 채널이 초기화되지 않았습니다.");
|
||||
}
|
||||
|
||||
// 암호화된 내용을 SFTP에 직접 업로드
|
||||
try (ByteArrayInputStream encryptedInputStream = new ByteArrayInputStream(encryptedContent)) {
|
||||
channelSftp.put(encryptedInputStream, remoteFilePath);
|
||||
channelSftp.chmod(0644, remoteFilePath); // 파일 권한 설정
|
||||
log.info("암호화된 파일이 SFTP에 업로드되었습니다: {}", remoteFilePath);
|
||||
}
|
||||
} catch (SftpException | JSchException e) {
|
||||
log.error("SFTP 업로드 실패: {}", remoteFilePath, e);
|
||||
throw new IOException("SFTP에 파일 업로드 실패", e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void cleanup() {
|
||||
sftpConnector.disconnect();
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package app.module.core.usecase.file.updateFile.adapters.persistence;
|
||||
|
||||
import app.module.core.config.application.annotation.DeleteCommand;
|
||||
import app.module.core.config.application.util.AuditUtil;
|
||||
import app.module.core.config.application.util.SftpFileDeleteUtil;
|
||||
import app.module.core.usecase.file.updateFile.ports.UpdateFilePortOut;
|
||||
import app.module.core.usecase.file.updateFile.ports.application.domain.UpdateFileCmd;
|
||||
import app.module.core.usecase.file.updateFile.ports.application.domain.UpdateUploadFileParam;
|
||||
@@ -18,7 +17,6 @@ import java.util.List;
|
||||
@RequiredArgsConstructor
|
||||
class UpdateFileDao implements UpdateFilePortOut {
|
||||
private final UpdateFileMapper mapper;
|
||||
private final SftpFileDeleteUtil sftpFileDeleteUtil;
|
||||
|
||||
@Override
|
||||
@DeleteCommand
|
||||
@@ -30,18 +28,6 @@ class UpdateFileDao implements UpdateFilePortOut {
|
||||
command.getType().getName()
|
||||
)));
|
||||
|
||||
/* for (UploadFileDto file : deletedFileList) {
|
||||
try {
|
||||
sftpFileDeleteUtil.deleteRealFile(file);
|
||||
} catch (JSchException | SftpException e) {
|
||||
log.error("Failed to delete file from SFTP for mapping ID {}: {}", file.getId(), e.getMessage(), e);
|
||||
throw new RuntimeException("Failed to delete file from SFTP", e);
|
||||
} catch (Exception e) {
|
||||
log.error("Unexpected error while deleting file for mapping ID {}: {}", file.getId(), e.getMessage(), e);
|
||||
throw new RuntimeException("Unexpected error while deleting file", e);
|
||||
}
|
||||
}*/
|
||||
|
||||
if (!deletedFileList.isEmpty()) {
|
||||
mapper.deleteFile(
|
||||
AuditUtil.delete(new UpdateUploadFileParam(
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package app.module.core.usecase.file.url.strategy;
|
||||
|
||||
import app.module.core.config.application.enums.FileStorageType;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class SftpFileUrlStrategy implements FileUrlStrategy {
|
||||
|
||||
@Override
|
||||
public FileStorageType getStorageType() {
|
||||
return FileStorageType.SFTP;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getInlineURL(String subPath, String filename) {
|
||||
return String.format("/content-disposition/inline%s/%s", subPath, filename);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAttachmentURL(Long fileId) {
|
||||
return String.format("/content-disposition/attachment/%s", fileId);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package app.module.core.usecase.getAttachment.adapters.web;
|
||||
|
||||
import app.module.core.config.application.enums.FileStorageType;
|
||||
import app.module.core.config.application.util.SftpFileDownloader;
|
||||
import app.module.core.usecase.file.getFile.ports.GetFilePortIn;
|
||||
import app.module.core.usecase.file.getFile.ports.application.domain.GetFile;
|
||||
import app.module.core.usecase.file.getFile.ports.application.domain.GetFileCmd;
|
||||
@@ -33,7 +32,6 @@ import java.nio.file.Paths;
|
||||
class GetAttachmentController {
|
||||
|
||||
private final GetFilePortIn getFilePortIn;
|
||||
private final SftpFileDownloader sftpFileDownloader;
|
||||
|
||||
@Value("${path.upload.public}")
|
||||
private String publicPath;
|
||||
@@ -109,25 +107,6 @@ class GetAttachmentController {
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.body(s3Resource);
|
||||
|
||||
case SFTP:
|
||||
try {
|
||||
sftpFileDownloader.downloadFile(getFile);
|
||||
} catch (JSchException | SftpException | IOException e) {
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body("SFTP 파일 다운로드에 실패했습니다 " + e.getMessage());
|
||||
}
|
||||
File downloadedFile = new File(getFile.getLocalPath());
|
||||
if (!downloadedFile.exists()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body("다운로드된 파일을 찾을 수 없습니다 " + getFile.getLocalPath());
|
||||
}
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.headers(headers)
|
||||
.contentLength(downloadedFile.length())
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.body(new FileSystemResource(downloadedFile));
|
||||
|
||||
default:
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body("지원되지 않는 저장소 타입입니다: " + uploadStorageType);
|
||||
|
||||
Reference in New Issue
Block a user