Files
no-copy/src/main/java/ru/soune/nocopy/service/file/FileUploadServiceImpl.java
T

737 lines
27 KiB
Java
Raw Normal View History

2025-12-17 13:41:05 +07:00
package ru.soune.nocopy.service.file;
2025-12-15 19:49:09 +07:00
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
2025-12-17 01:19:48 +07:00
import org.springframework.beans.factory.annotation.Autowired;
2025-12-15 19:49:09 +07:00
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
2025-12-17 13:41:05 +07:00
import ru.soune.nocopy.dto.file.UploadProgressResponse;
2026-01-19 15:49:27 +07:00
import ru.soune.nocopy.entity.file.FileEntity;
import ru.soune.nocopy.entity.file.FileStatus;
2025-12-17 13:41:05 +07:00
import ru.soune.nocopy.entity.file.FileUploadSession;
import ru.soune.nocopy.entity.file.UploadStatus;
import ru.soune.nocopy.exception.ChunkSizeExceededException;
2026-01-19 15:49:27 +07:00
import ru.soune.nocopy.exception.DuplicateImageException;
2025-12-17 13:41:05 +07:00
import ru.soune.nocopy.exception.FileUploadException;
import ru.soune.nocopy.exception.UploadSessionNotFoundException;
2026-01-19 15:49:27 +07:00
import ru.soune.nocopy.repository.FileEntityRepository;
2025-12-17 13:41:05 +07:00
import ru.soune.nocopy.repository.FileUploadSessionRepository;
2026-01-19 15:49:27 +07:00
import ru.soune.nocopy.repository.SimilarImageProjection;
import ru.soune.nocopy.service.FileSimilarityService;
import ru.soune.nocopy.service.ImageHashService;
2025-12-15 19:49:09 +07:00
import java.io.*;
2025-12-16 03:44:59 +07:00
import java.nio.file.*;
import java.nio.file.attribute.PosixFilePermission;
2025-12-15 19:49:09 +07:00
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
2026-01-19 15:49:27 +07:00
import java.util.*;
2025-12-16 03:44:59 +07:00
import java.util.concurrent.CompletableFuture;
2025-12-15 19:49:09 +07:00
import java.util.stream.Stream;
@Slf4j
@Service
@RequiredArgsConstructor
public class FileUploadServiceImpl implements FileUploadService {
private final FileUploadSessionRepository sessionRepository;
@Value("${file.storage.base-path}")
private String basePath;
@Value("${file.storage.chunk-size}")
private int chunkSize;
@Value("${file.storage.max-file-size}")
private long maxFileSize;
2025-12-16 03:44:59 +07:00
@Value("${file.storage.max-retry-attempts:3}")
private int maxRetryAttempts;
@Value("${file.storage.chunk-timeout-ms:300000}") // 5 минут
private long chunkTimeoutMs;
@Value("${file.storage.session-expiry-hours:24}")
private int sessionExpiryHours;
private Path storageRoot;
2026-01-19 15:49:27 +07:00
@Autowired
private ImageHashService imageHashService;
@Autowired
private FileSimilarityService fileSimilarityService;
@Autowired
private FileEntityRepository fileEntityRepository;
2025-12-17 01:19:48 +07:00
@Autowired
private FileEntityService fileEntityService;
2025-12-15 19:49:09 +07:00
@PostConstruct
public void init() {
try {
2025-12-16 03:44:59 +07:00
storageRoot = Paths.get(basePath).toAbsolutePath().normalize();
log.info("Initializing file storage at: {}", storageRoot);
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
createDirectoryIfNotExists(storageRoot);
createDirectoryIfNotExists(storageRoot.resolve("temp"));
createDirectoryIfNotExists(storageRoot.resolve("uploads"));
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
if (!System.getProperty("os.name").toLowerCase().contains("win")) {
setDirectoryPermissions(storageRoot);
2025-12-15 19:49:09 +07:00
}
2025-12-16 03:44:59 +07:00
log.info("File storage initialized successfully");
2025-12-15 19:49:09 +07:00
} catch (IOException e) {
2025-12-16 03:44:59 +07:00
log.error("Failed to initialize file storage at: {}", basePath, e);
throw new RuntimeException("Storage initialization failed", e);
2025-12-15 19:49:09 +07:00
}
}
@Override
@Transactional
public FileUploadSession initUpload(Long userId, String fileName,
2025-12-16 14:27:03 +07:00
String fileType, String extension, long fileSize) {
2025-12-16 03:44:59 +07:00
log.info("Initializing upload for user {}: {} ({} bytes, type: {})",
userId, fileName, fileSize, fileType);
2025-12-15 19:49:09 +07:00
if (fileSize > maxFileSize) {
throw new FileUploadException(
String.format("File size %d exceeds maximum allowed size %d",
fileSize, maxFileSize));
}
2025-12-16 03:44:59 +07:00
if (fileSize <= 0) {
throw new FileUploadException("File size must be positive");
}
2025-12-15 19:49:09 +07:00
int totalChunks = (int) Math.ceil((double) fileSize / chunkSize);
2025-12-16 03:44:59 +07:00
log.debug("File will be split into {} chunks (chunk size: {} bytes)",
totalChunks, chunkSize);
2026-01-08 12:59:30 +07:00
Long chunkSize = totalChunks == 1 ? fileSize : 1000000L;
2025-12-15 19:49:09 +07:00
FileUploadSession session = FileUploadSession.builder()
.userId(userId)
2025-12-16 14:27:03 +07:00
.extension(extension)
2025-12-15 19:49:09 +07:00
.fileName(fileName)
.fileType(fileType)
2025-12-24 13:58:46 +07:00
.chunkSize(chunkSize)
2025-12-15 19:49:09 +07:00
.fileSize(fileSize)
.totalChunks(totalChunks)
.chunksUploaded(0)
.status(UploadStatus.INITIATED)
2025-12-16 03:44:59 +07:00
.expiresAt(LocalDateTime.now().plusHours(sessionExpiryHours))
.retryCount(0)
2025-12-15 19:49:09 +07:00
.build();
2025-12-16 03:44:59 +07:00
FileUploadSession savedSession = sessionRepository.save(session);
log.info("Upload session created: {} for file: {}",
savedSession.getUploadId(), fileName);
return savedSession;
2025-12-15 19:49:09 +07:00
}
@Override
@Transactional
public UploadProgressResponse uploadChunk(String uploadId, Integer chunkNumber,
MultipartFile chunkFile) {
FileUploadSession session = sessionRepository.findById(uploadId)
.orElseThrow(() -> new UploadSessionNotFoundException(uploadId));
2025-12-16 03:44:59 +07:00
validateSession(session);
if (session.getExpiresAt().isBefore(LocalDateTime.now())) {
handleExpiredSession(session);
throw new FileUploadException("Upload session expired");
}
if (chunkNumber < 0 || chunkNumber >= session.getTotalChunks()) {
throw new FileUploadException(
2025-12-25 13:04:49 +07:00
String.format("Invalid chunk number %d. Expected number: %d",
2025-12-16 03:44:59 +07:00
chunkNumber, session.getTotalChunks() - 1));
2025-12-15 19:49:09 +07:00
}
2025-12-24 13:58:46 +07:00
if (chunkNumber == 0 && chunkFile.getSize() > chunkSize || chunkNumber + 1 == (session.getTotalChunks())
&& chunkFile.getSize() > chunkSize) {
throw new ChunkSizeExceededException(chunkFile.getSize(), chunkSize);
}
if (chunkNumber > 0 && chunkNumber + 1 < session.getTotalChunks() && chunkFile.getSize() != chunkSize) {
2025-12-15 19:49:09 +07:00
throw new ChunkSizeExceededException(chunkFile.getSize(), chunkSize);
}
2025-12-16 03:44:59 +07:00
return processChunk(session, chunkNumber, chunkFile);
}
2025-12-15 19:49:09 +07:00
2025-12-25 15:27:45 +07:00
@Override
@Transactional
public void handleExpiredSession(FileUploadSession session) {
session.setStatus(UploadStatus.FAILED);
session.setLastError("Upload session expired");
sessionRepository.save(session);
CompletableFuture.runAsync(() -> cleanupSessionFiles(session));
}
@Async("fileUploadTaskExecutor")
@Transactional
2026-01-19 15:49:27 +07:00
public void assembleFileAsync(FileUploadSession session) throws DuplicateImageException {
2025-12-25 15:27:45 +07:00
try {
assembleFile(session);
log.info("File assembly completed successfully for session: {}",
session.getUploadId());
2026-01-19 15:49:27 +07:00
} catch (DuplicateImageException e) {
throw new DuplicateImageException("DUBL", e.duplicateFileId(), e.userId());
2025-12-25 15:27:45 +07:00
} catch (Exception e) {
log.error("Failed to assemble file for session {}: {}",
session.getUploadId(), e.getMessage(), e);
handleAssemblyFailure(session, e);
}
}
@Override
@Transactional
public void cancelUpload(String uploadId) {
FileUploadSession session = sessionRepository.findById(uploadId)
.orElseThrow(() -> new UploadSessionNotFoundException(uploadId));
if (session.getStatus() == UploadStatus.COMPLETED || session.getStatus() == UploadStatus.CANCELLED) {
throw new FileUploadException("Cannot cancel completed or cancelled upload");
}
session.setStatus(UploadStatus.CANCELLED);
sessionRepository.save(session);
CompletableFuture.runAsync(() -> cleanupSessionFiles(session));
log.info("Upload cancelled: {}", uploadId);
}
@Override
public UploadProgressResponse getUploadProgress(String uploadId) {
FileUploadSession session = sessionRepository.findById(uploadId)
.orElseThrow(() -> new UploadSessionNotFoundException(uploadId));
return UploadProgressResponse.fromSession(session);
}
2025-12-16 03:44:59 +07:00
private void validateSession(FileUploadSession session) {
UploadStatus status = session.getStatus();
if (status == UploadStatus.FAILED) {
if (session.getRetryCount() >= maxRetryAttempts) {
throw new FileUploadException(
"Upload failed after maximum retry attempts");
}
session.setStatus(UploadStatus.UPLOADING);
session.setRetryCount(session.getRetryCount() + 1);
sessionRepository.save(session);
log.info("Retrying failed upload session: {}, attempt: {}",
session.getUploadId(), session.getRetryCount());
}
if (status == UploadStatus.COMPLETED) {
throw new FileUploadException("Upload already completed");
}
if (status == UploadStatus.CANCELLED) {
throw new FileUploadException("Upload was cancelled");
}
if (status == UploadStatus.INITIATED) {
session.setStatus(UploadStatus.UPLOADING);
sessionRepository.save(session);
}
}
2026-01-19 15:49:27 +07:00
@Async("fileUploadTaskExecutor")
@Transactional
public void completeFileProcessingAsync(FileUploadSession session) {
try {
Path filePath = Paths.get(session.getFilePath());
String checksum = calculateChecksum(filePath);
FileEntity fileEntity = FileEntity.builder()
.userId(session.getUserId())
.originalFileName(session.getFileName())
.storedFileName(filePath.getFileName().toString())
.filePath(session.getFilePath())
.fileSize(session.getFileSize())
.mimeType(session.getFileType())
.fileExtension(session.getExtension())
.checksum(checksum)
.uploadSessionId(session.getUploadId())
.status(FileStatus.ACTIVE)
.build();
FileEntity saved = fileEntityRepository.save(fileEntity);
Map<String, Integer> hash = imageHashService.calculateHash(filePath);
imageHashService.create(saved, hash);
cleanupSessionFiles(session);
log.info("File processing completed for session: {}", session.getUploadId());
} catch (Exception e) {
log.error("Failed to complete file processing for session {}: {}",
session.getUploadId(), e.getMessage(), e);
}
}
private UploadProgressResponse processChunk(FileUploadSession session, Integer chunkNumber, MultipartFile chunkFile) {
2025-12-16 03:44:59 +07:00
String chunkPath = null;
try {
if (session.getChunkPaths().containsKey(chunkNumber)) {
return handleExistingChunk(session, chunkNumber, chunkFile);
}
chunkPath = saveChunkWithIntegrityCheck(session, chunkNumber, chunkFile);
2025-12-15 19:49:09 +07:00
session.getChunkPaths().put(chunkNumber, chunkPath);
session.setChunksUploaded(session.getChunksUploaded() + 1);
2025-12-16 03:44:59 +07:00
session.setStatus(UploadStatus.UPLOADING);
2025-12-25 15:27:45 +07:00
session.setExpiresAt(LocalDateTime.now().plusMinutes(1));
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
log.debug("Chunk {} saved successfully. Uploaded: {}/{}",
2025-12-15 19:49:09 +07:00
chunkNumber, session.getChunksUploaded(), session.getTotalChunks());
2026-01-19 15:49:27 +07:00
boolean isLastChunk = session.getChunksUploaded().equals(session.getTotalChunks());
if (isLastChunk) {
2025-12-16 03:44:59 +07:00
log.info("All chunks uploaded for session {}. Starting assembly...",
session.getUploadId());
2026-01-19 15:49:27 +07:00
String finalFilePath = assembleFileSynchronously(session);
if (session.getFileType().startsWith("image")) {
checkForDuplicatesSynchronously(finalFilePath);
}
session.setStatus(UploadStatus.COMPLETED);
session.setFilePath(finalFilePath);
completeFileProcessingAsync(session);
2025-12-15 19:49:09 +07:00
} else {
sessionRepository.save(session);
}
return UploadProgressResponse.fromSession(session);
2026-01-19 15:49:27 +07:00
} catch (DuplicateImageException e) {
if (chunkPath != null) {
cleanupFailedChunk(chunkPath);
}
log.warn("Duplicate image found for session {}: {}",
session.getUploadId(), e.getMessage());
session.setStatus(UploadStatus.FAILED);
session.setLastError(e.getMessage());
sessionRepository.save(session);
throw e;
2025-12-16 03:44:59 +07:00
} catch (Exception e) {
if (chunkPath != null) {
cleanupFailedChunk(chunkPath);
}
log.error("Failed to process chunk {} for session {}: {}",
chunkNumber, session.getUploadId(), e.getMessage(), e);
2025-12-15 19:49:09 +07:00
session.setStatus(UploadStatus.FAILED);
2025-12-16 03:44:59 +07:00
session.setLastError(e.getMessage());
2025-12-15 19:49:09 +07:00
sessionRepository.save(session);
2025-12-16 03:44:59 +07:00
throw new FileUploadException("Failed to upload chunk: " + e.getMessage(), e);
2025-12-15 19:49:09 +07:00
}
}
2026-01-19 15:49:27 +07:00
private String assembleFileSynchronously(FileUploadSession session) throws IOException {
Path finalFilePath = prepareFinalFile(session);
validateAllChunksExist(session);
mergeChunksToFile(session, finalFilePath);
validateFinalFile(session, finalFilePath);
return finalFilePath.toString();
}
private void checkForDuplicatesSynchronously(String filePath)
throws IOException {
Path path = Paths.get(filePath);
Map<String, Integer> hash = imageHashService.calculateHash(path);
List<SimilarImageProjection> duplicates = fileSimilarityService.findDuplicatedByHash(
hash.get("hi"), hash.get("low"));
if (!duplicates.isEmpty()) {
2026-01-24 12:23:05 +07:00
throw new DuplicateImageException("Duplicate", duplicates.get(0).getId(),
2026-01-19 15:49:27 +07:00
duplicates.get(0).getUserId());
}
}
2025-12-16 03:44:59 +07:00
private UploadProgressResponse handleExistingChunk(FileUploadSession session,
Integer chunkNumber,
MultipartFile chunkFile) throws IOException {
String existingPath = session.getChunkPaths().get(chunkNumber);
Path chunkPath = Paths.get(existingPath);
if (!Files.exists(chunkPath)) {
session.getChunkPaths().remove(chunkNumber);
session.setChunksUploaded(session.getChunksUploaded() - 1);
sessionRepository.save(session);
2026-01-19 15:49:27 +07:00
2025-12-16 03:44:59 +07:00
return processChunk(session, chunkNumber, chunkFile);
}
long existingSize = Files.size(chunkPath);
2026-01-19 15:49:27 +07:00
2025-12-16 03:44:59 +07:00
if (existingSize != chunkFile.getSize()) {
Files.deleteIfExists(chunkPath);
session.getChunkPaths().remove(chunkNumber);
session.setChunksUploaded(session.getChunksUploaded() - 1);
sessionRepository.save(session);
2026-01-19 15:49:27 +07:00
2025-12-16 03:44:59 +07:00
return processChunk(session, chunkNumber, chunkFile);
}
return UploadProgressResponse.fromSession(session);
}
private String saveChunkWithIntegrityCheck(FileUploadSession session,
Integer chunkNumber,
MultipartFile chunkFile) throws IOException {
2025-12-15 19:49:09 +07:00
Long userId = session.getUserId();
String uploadId = session.getUploadId();
2025-12-16 03:44:59 +07:00
Path chunkDir = getChunkDirectory(userId, uploadId);
2025-12-15 19:49:09 +07:00
Files.createDirectories(chunkDir);
2025-12-16 03:44:59 +07:00
String tempFileName = String.format("chunk_%04d.%s.tmp",
chunkNumber, UUID.randomUUID());
String finalFileName = String.format("chunk_%04d.tmp", chunkNumber);
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
Path tempPath = chunkDir.resolve(tempFileName);
Path finalPath = chunkDir.resolve(finalFileName);
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
try {
chunkFile.transferTo(tempPath.toFile());
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
long savedSize = Files.size(tempPath);
long uploadedSize = chunkFile.getSize();
if (uploadedSize > 0 && savedSize != uploadedSize) {
throw new IOException(
String.format("Size mismatch: saved %d, uploaded %d",
savedSize, uploadedSize));
2025-12-15 19:49:09 +07:00
}
2025-12-16 03:44:59 +07:00
Files.move(tempPath, finalPath, StandardCopyOption.ATOMIC_MOVE);
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
log.debug("Chunk {} saved successfully: {} bytes",
chunkNumber, savedSize);
return finalPath.toString();
} finally {
Files.deleteIfExists(tempPath);
2025-12-15 19:49:09 +07:00
}
2025-12-16 03:44:59 +07:00
}
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
private void cleanupFailedChunk(String chunkPath) {
try {
Files.deleteIfExists(Paths.get(chunkPath));
log.debug("Cleaned up failed chunk: {}", chunkPath);
} catch (IOException e) {
log.warn("Failed to cleanup chunk: {}", chunkPath, e);
}
2025-12-15 19:49:09 +07:00
}
private void assembleFile(FileUploadSession session) throws IOException {
2025-12-16 03:44:59 +07:00
log.info("Starting file assembly for session: {} ({})",
session.getUploadId(), session.getFileName());
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
Path finalFilePath = null;
String checksum;
2025-12-15 19:49:09 +07:00
try {
2025-12-16 03:44:59 +07:00
finalFilePath = prepareFinalFile(session);
2025-12-17 01:19:48 +07:00
log.info("Final file path: {}", finalFilePath);
2025-12-16 03:44:59 +07:00
validateAllChunksExist(session);
mergeChunksToFile(session, finalFilePath);
validateFinalFile(session, finalFilePath);
2025-12-17 01:19:48 +07:00
checksum = calculateChecksum(finalFilePath);
log.debug("File checksum calculated: {}", checksum);
session.setFilePath(finalFilePath.toString());
session.setChecksum(checksum);
session.setStatus(UploadStatus.COMPLETED);
session.setCompletedAt(LocalDateTime.now());
sessionRepository.save(session);
log.info("Upload session updated to COMPLETED: {}", session.getUploadId());
try {
fileEntityService.createFromUploadSession(session, checksum);
log.info("FileEntity successfully created for session: {}",
session.getUploadId());
2026-01-19 15:49:27 +07:00
} catch (DuplicateImageException e) {
throw new DuplicateImageException("Duplicate", e.duplicateFileId(), e.userId());
2025-12-17 01:19:48 +07:00
} catch (Exception e) {
log.error("Failed to create FileEntity for session {} (file uploaded, but metadata not saved): {}",
session.getUploadId(), e.getMessage());
}
2025-12-16 03:44:59 +07:00
cleanupSessionFiles(session);
2025-12-17 01:19:48 +07:00
log.info("File assembly completed successfully: {} -> {} ({} bytes)",
2025-12-16 03:44:59 +07:00
session.getFileName(), finalFilePath, session.getFileSize());
} catch (Exception e) {
2025-12-17 01:19:48 +07:00
log.error("File assembly failed for session {}: {}",
session.getUploadId(), e.getMessage(), e);
2025-12-16 03:44:59 +07:00
if (finalFilePath != null) {
2025-12-17 01:19:48 +07:00
try {
Files.deleteIfExists(finalFilePath);
log.debug("Cleaned up partial file: {}", finalFilePath);
} catch (IOException ioException) {
log.warn("Failed to cleanup partial file: {}", finalFilePath, ioException);
}
2025-12-16 03:44:59 +07:00
}
2025-12-17 01:19:48 +07:00
session.setStatus(UploadStatus.FAILED);
session.setLastError(e.getMessage());
sessionRepository.save(session);
throw new IOException("File assembly failed: " + e.getMessage(), e);
2025-12-16 03:44:59 +07:00
}
}
private Path prepareFinalFile(FileUploadSession session) throws IOException {
Path userUploadsDir = storageRoot.resolve("uploads")
.resolve(String.valueOf(session.getUserId()))
.resolve(extractCategory(session.getFileType()));
Files.createDirectories(userUploadsDir);
2025-12-16 14:27:03 +07:00
String safeFileName = generateUniqueFileName(session.getFileName(), session.getExtension());
2025-12-16 03:44:59 +07:00
Path finalPath = userUploadsDir.resolve(safeFileName);
if (Files.exists(finalPath)) {
throw new IOException("File already exists: " + finalPath);
2025-12-15 19:49:09 +07:00
}
2025-12-16 03:44:59 +07:00
return finalPath;
}
2025-12-16 14:27:03 +07:00
private String generateUniqueFileName(String originalName, String extension) {
int dotIndex = originalName.lastIndexOf('.');
log.info("dotIndex: {}", dotIndex);
log.info("originalName: {}", originalName);
String nameWithoutExtension;
if (dotIndex > 0) {
nameWithoutExtension = originalName.substring(0, dotIndex)
.replaceAll("[^a-zA-Z0-9\\-_]", "_");
} else {
nameWithoutExtension = originalName.replaceAll("[^a-zA-Z0-9\\-_]", "_");
}
2025-12-16 03:44:59 +07:00
String timestamp = String.valueOf(System.currentTimeMillis());
String uuid = UUID.randomUUID().toString().substring(0, 8);
2025-12-16 14:27:03 +07:00
return String.format("%s_%s_%s.%s",
nameWithoutExtension, timestamp, uuid, extension);
2025-12-16 03:44:59 +07:00
}
private void validateAllChunksExist(FileUploadSession session) throws IOException {
Path chunkDir = getChunkDirectory(session.getUserId(), session.getUploadId());
for (int i = 0; i < session.getTotalChunks(); i++) {
Path chunkPath = chunkDir.resolve(String.format("chunk_%04d.tmp", i));
if (!Files.exists(chunkPath)) {
throw new IOException("Missing chunk: " + chunkPath.getFileName());
}
if (Files.size(chunkPath) == 0) {
throw new IOException("Empty chunk: " + chunkPath.getFileName());
}
}
}
private void mergeChunksToFile(FileUploadSession session, Path finalPath)
throws IOException {
Path chunkDir = getChunkDirectory(session.getUserId(), session.getUploadId());
2025-12-16 14:27:03 +07:00
byte[] buffer = new byte[8192];
2025-12-16 03:44:59 +07:00
try (BufferedOutputStream outputStream = new BufferedOutputStream(
Files.newOutputStream(finalPath, StandardOpenOption.CREATE_NEW))) {
long totalWritten = 0;
for (int i = 0; i < session.getTotalChunks(); i++) {
Path chunkPath = chunkDir.resolve(String.format("chunk_%04d.tmp", i));
try (BufferedInputStream inputStream = new BufferedInputStream(
Files.newInputStream(chunkPath))) {
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
totalWritten += bytesRead;
}
}
if (log.isDebugEnabled()) {
log.debug("Processed chunk {}: {} bytes (total: {})",
i, Files.size(chunkPath), totalWritten);
}
}
outputStream.flush();
log.info("Total bytes written to final file: {}", totalWritten);
}
}
private void validateFinalFile(FileUploadSession session, Path finalPath)
throws IOException {
long actualSize = Files.size(finalPath);
if (actualSize != session.getFileSize()) {
throw new IOException(
String.format("File size mismatch: expected %d, got %d",
session.getFileSize(), actualSize));
}
String checksum = calculateChecksum(finalPath);
log.debug("Final file checksum: {}", checksum);
}
private void cleanupSessionFiles(FileUploadSession session) {
2025-12-15 19:49:09 +07:00
try {
2025-12-16 03:44:59 +07:00
Path chunkDir = getChunkDirectory(session.getUserId(), session.getUploadId());
if (Files.exists(chunkDir)) {
deleteDirectoryRecursively(chunkDir);
log.info("Cleaned up temp directory for session: {}",
session.getUploadId());
}
2025-12-15 19:49:09 +07:00
} catch (IOException e) {
2025-12-16 03:44:59 +07:00
log.warn("Failed to cleanup temp files for session {}: {}",
session.getUploadId(), e.getMessage());
2025-12-15 19:49:09 +07:00
}
}
2025-12-16 03:44:59 +07:00
private void deleteDirectoryRecursively(Path directory) throws IOException {
try (Stream<Path> walk = Files.walk(directory)) {
walk.sorted(Comparator.reverseOrder())
.forEach(path -> {
try {
Files.deleteIfExists(path);
} catch (IOException e) {
log.warn("Failed to delete: {}", path, e);
}
});
}
}
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
private void handleAssemblyFailure(FileUploadSession session, Exception e) {
session.setStatus(UploadStatus.FAILED);
session.setLastError(e.getMessage());
2025-12-16 03:44:59 +07:00
sessionRepository.save(session);
}
private Path getChunkDirectory(Long userId, String uploadId) {
return storageRoot.resolve("temp")
.resolve("user")
.resolve(String.valueOf(userId))
.resolve(uploadId);
2025-12-15 19:49:09 +07:00
}
private String extractCategory(String fileType) {
2025-12-16 03:44:59 +07:00
if (fileType == null) {
return "other";
}
String lowerType = fileType.toLowerCase();
2025-12-16 14:27:03 +07:00
if (lowerType.startsWith("image")) {
2025-12-15 19:49:09 +07:00
return "images";
2025-12-16 14:27:03 +07:00
} else if (lowerType.startsWith("video")) {
2025-12-15 19:49:09 +07:00
return "videos";
2025-12-16 14:27:03 +07:00
} else if (lowerType.startsWith("audio")) {
2025-12-15 19:49:09 +07:00
return "audio";
2025-12-16 14:27:03 +07:00
} else if (lowerType.contains("document")) {
2025-12-15 19:49:09 +07:00
return "documents";
} else {
return "other";
}
}
2025-12-16 03:44:59 +07:00
private String calculateChecksum(Path filePath) {
2025-12-15 19:49:09 +07:00
try {
2025-12-16 03:44:59 +07:00
MessageDigest md = MessageDigest.getInstance("SHA-256");
2025-12-15 19:49:09 +07:00
byte[] buffer = new byte[8192];
try (InputStream inputStream = Files.newInputStream(filePath)) {
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
md.update(buffer, 0, bytesRead);
}
}
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b));
}
return sb.toString();
2025-12-16 03:44:59 +07:00
} catch (NoSuchAlgorithmException | IOException e) {
log.warn("Failed to calculate checksum for file: {}", filePath, e);
2025-12-15 19:49:09 +07:00
return "N/A";
}
}
2025-12-16 03:44:59 +07:00
private void createDirectoryIfNotExists(Path directory) throws IOException {
if (!Files.exists(directory)) {
Files.createDirectories(directory);
log.debug("Created directory: {}", directory);
2025-12-15 19:49:09 +07:00
}
}
2025-12-16 03:44:59 +07:00
private void setDirectoryPermissions(Path directory) throws IOException {
try {
Set<PosixFilePermission> permissions = new HashSet<>();
permissions.add(PosixFilePermission.OWNER_READ);
permissions.add(PosixFilePermission.OWNER_WRITE);
permissions.add(PosixFilePermission.OWNER_EXECUTE);
permissions.add(PosixFilePermission.GROUP_READ);
permissions.add(PosixFilePermission.GROUP_EXECUTE);
permissions.add(PosixFilePermission.OTHERS_READ);
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
Files.setPosixFilePermissions(directory, permissions);
log.debug("Set permissions for directory: {}", directory);
2025-12-15 19:49:09 +07:00
2025-12-16 03:44:59 +07:00
} catch (UnsupportedOperationException e) {
log.debug("Posix permissions not supported on this system");
}
2025-12-15 19:49:09 +07:00
}
2025-12-16 03:44:59 +07:00
}