Add auto-move option on metadata update and simplify file monitoring (#1137)

- Introduce option to automatically move books when their metadata is updated
- Simplify the file monitoring workflow for improved reliability and clarity
This commit is contained in:
Aditya Chandel
2025-09-12 11:59:36 -06:00
committed by GitHub
parent 7adc2b3f57
commit 6ea2eb58bc
47 changed files with 3749 additions and 2942 deletions
@@ -22,11 +22,12 @@ public class FileUploadController {
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canUpload()")
@PostMapping(value = "/upload", consumes = "multipart/form-data")
public ResponseEntity<Book> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("pathId") long pathId) throws IOException {
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("pathId") long pathId) throws IOException {
if (file.isEmpty()) {
throw new IllegalArgumentException("Uploaded file is missing.");
}
return ResponseEntity.ok(fileUploadService.uploadFile(file, libraryId, pathId));
fileUploadService.uploadFile(file, libraryId, pathId);
return ResponseEntity.noContent().build();
}
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canUpload()")
@@ -14,4 +14,5 @@ public class MetadataPersistenceSettings {
private boolean convertCbrCb7ToCbz;
private boolean backupMetadata;
private boolean backupCover;
private boolean moveFilesToLibraryPattern;
}
@@ -22,6 +22,8 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
Optional<BookEntity> findByCurrentHash(String currentHash);
Optional<BookEntity> findByCurrentHashAndDeletedTrue(String currentHash);
@Query("SELECT b.id FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
Set<Long> findBookIdsByLibraryId(@Param("libraryId") long libraryId);
@@ -47,6 +49,10 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> bookIds);
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findWithMetadataByIdsWithPagination(@Param("bookIds") Set<Long> bookIds, Pageable pageable);
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadataByLibraryId(@Param("libraryId") Long libraryId);
@@ -32,3 +32,4 @@ public interface BookdropFileRepository extends JpaRepository<BookdropFileEntity
@Query("SELECT f.id FROM BookdropFileEntity f WHERE f.id NOT IN :excludedIds")
List<Long> findAllExcludingIdsFlat(@Param("excludedIds") List<Long> excludedIds);
}
@@ -1,15 +1,11 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.AdditionalFileMapper;
import com.adityachandel.booklore.model.dto.AdditionalFile;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
@@ -19,19 +15,11 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Slf4j
@@ -41,7 +29,7 @@ public class AdditionalFileService {
private final BookAdditionalFileRepository additionalFileRepository;
private final AdditionalFileMapper additionalFileMapper;
private final MonitoringProtectionService monitoringProtectionService;
private final MonitoringRegistrationService monitoringRegistrationService;
public List<AdditionalFile> getAdditionalFilesByBookId(Long bookId) {
List<BookAdditionalFileEntity> entities = additionalFileRepository.findByBookId(bookId);
@@ -61,21 +49,18 @@ public class AdditionalFileService {
}
BookAdditionalFileEntity file = fileOpt.get();
monitoringProtectionService.executeWithProtection(() -> {
try {
// Delete physical file
Files.deleteIfExists(file.getFullFilePath());
log.info("Deleted additional file: {}", file.getFullFilePath());
// Delete database record
additionalFileRepository.delete(file);
} catch (IOException e) {
log.warn("Failed to delete physical file: {}", file.getFullFilePath(), e);
// Still delete the database record even if file deletion fails
additionalFileRepository.delete(file);
}
}, "additional file deletion");
try {
monitoringRegistrationService.unregisterSpecificPath(file.getFullFilePath().getParent());
Files.deleteIfExists(file.getFullFilePath());
log.info("Deleted additional file: {}", file.getFullFilePath());
additionalFileRepository.delete(file);
} catch (IOException e) {
log.warn("Failed to delete physical file: {}", file.getFullFilePath(), e);
additionalFileRepository.delete(file);
}
}
public ResponseEntity<Resource> downloadAdditionalFile(Long fileId) throws IOException {
@@ -98,5 +83,4 @@ public class AdditionalFileService {
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
.body(resource);
}
}
@@ -5,6 +5,8 @@ import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.repository.BookRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
@@ -114,6 +116,11 @@ public class BookQueryService {
return bookRepository.findAllWithMetadataByIds(bookIds);
}
public List<BookEntity> findWithMetadataByIdsWithPagination(Set<Long> bookIds, int offset, int limit) {
Pageable pageable = PageRequest.of(offset / limit, limit);
return bookRepository.findWithMetadataByIdsWithPagination(bookIds, pageable);
}
public List<BookEntity> getAllFullBookEntities() {
return bookRepository.findAllFullBooks();
}
@@ -15,7 +15,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.model.enums.ResetProgressType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
@@ -59,7 +59,7 @@ public class BookService {
private final BookQueryService bookQueryService;
private final UserProgressService userProgressService;
private final BookDownloadService bookDownloadService;
private final MonitoringProtectionService monitoringProtectionService;
private final MonitoringRegistrationService monitoringRegistrationService;
private void setBookProgress(Book book, UserBookProgressEntity progress) {
@@ -468,8 +468,7 @@ public class BookService {
if (Files.exists(coverPath)) {
return new UrlResource(coverPath.toUri());
} else {
Path defaultCover = Paths.get("static/images/missing-cover.jpg");
return new UrlResource(defaultCover.toUri());
return new ClassPathResource("static/images/missing-cover.jpg");
}
} catch (MalformedURLException e) {
throw new RuntimeException("Failed to load book cover for bookId=" + bookId, e);
@@ -504,35 +503,33 @@ public class BookService {
public ResponseEntity<BookDeletionResponse> deleteBooks(Set<Long> ids) {
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(ids);
List<Long> failedFileDeletions = new ArrayList<>();
for (BookEntity book : books) {
Path fullFilePath = book.getFullFilePath();
try {
if (Files.exists(fullFilePath)) {
monitoringRegistrationService.unregisterSpecificPath(fullFilePath.getParent());
Files.delete(fullFilePath);
log.info("Deleted book file: {}", fullFilePath);
return monitoringProtectionService.executeWithProtection(() -> {
for (BookEntity book : books) {
Path fullFilePath = book.getFullFilePath();
try {
if (Files.exists(fullFilePath)) {
Files.delete(fullFilePath);
log.info("Deleted book file: {}", fullFilePath);
Set<Path> libraryRoots = book.getLibrary().getLibraryPaths().stream()
.map(LibraryPathEntity::getPath)
.map(Paths::get)
.map(Path::normalize)
.collect(Collectors.toSet());
Set<Path> libraryRoots = book.getLibrary().getLibraryPaths().stream()
.map(LibraryPathEntity::getPath)
.map(Paths::get)
.map(Path::normalize)
.collect(Collectors.toSet());
deleteEmptyParentDirsUpToLibraryFolders(fullFilePath.getParent(), libraryRoots);
}
} catch (IOException e) {
log.warn("Failed to delete book file: {}", fullFilePath, e);
failedFileDeletions.add(book.getId());
deleteEmptyParentDirsUpToLibraryFolders(fullFilePath.getParent(), libraryRoots);
}
} catch (IOException e) {
log.warn("Failed to delete book file: {}", fullFilePath, e);
failedFileDeletions.add(book.getId());
}
}
bookRepository.deleteAll(books);
BookDeletionResponse response = new BookDeletionResponse(ids, failedFileDeletions);
return failedFileDeletions.isEmpty()
? ResponseEntity.ok(response)
: ResponseEntity.status(HttpStatus.MULTI_STATUS).body(response);
}, "book deletion");
bookRepository.deleteAll(books);
BookDeletionResponse response = new BookDeletionResponse(ids, failedFileDeletions);
return failedFileDeletions.isEmpty()
? ResponseEntity.ok(response)
: ResponseEntity.status(HttpStatus.MULTI_STATUS).body(response);
}
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
@@ -186,6 +186,7 @@ public class SettingPersistenceHelper {
.convertCbrCb7ToCbz(false)
.backupMetadata(false)
.backupCover(false)
.moveFilesToLibraryPattern(false)
.build();
}
@@ -4,7 +4,6 @@ import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookdropFileMapper;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.BookdropFile;
import com.adityachandel.booklore.model.dto.BookdropFileNotification;
@@ -23,17 +22,14 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.BookdropFileRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.file.FileMovingHelper;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.util.PathPatternResolver;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
@@ -45,6 +41,7 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
@@ -63,7 +60,6 @@ public class BookDropService {
private final BookdropFileRepository bookdropFileRepository;
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final MonitoringProtectionService monitoringProtectionService;
private final BookdropMonitoringService bookdropMonitoringService;
private final NotificationService notificationService;
private final MetadataRefreshService metadataRefreshService;
@@ -72,7 +68,9 @@ public class BookDropService {
private final AppProperties appProperties;
private final BookdropFileMapper mapper;
private final ObjectMapper objectMapper;
AppSettingService appSettingService;
private final FileMovingHelper fileMovingHelper;
private static final int CHUNK_SIZE = 100;
public BookdropFileNotification getFileNotificationSummary() {
long pendingCount = bookdropFileRepository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW);
@@ -88,140 +86,169 @@ public class BookDropService {
}
}
public BookdropFinalizeResult finalizeImport(BookdropFinalizeRequest request) {
return monitoringProtectionService.executeWithProtection(() -> {
try {
bookdropMonitoringService.pauseMonitoring();
BookdropFinalizeResult results = BookdropFinalizeResult.builder()
.processedAt(Instant.now())
.build();
Long defaultLibraryId = request.getDefaultLibraryId();
Long defaultPathId = request.getDefaultPathId();
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.collect(Collectors.toMap(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId, Function.identity()));
final int CHUNK_SIZE = 100;
AtomicInteger failedCount = new AtomicInteger();
AtomicInteger totalFilesProcessed = new AtomicInteger();
log.info("Starting finalizeImport: selectAll={}, provided file count={}, defaultLibraryId={}, defaultPathId={}",
request.getSelectAll(), metadataById.size(), defaultLibraryId, defaultPathId);
if (Boolean.TRUE.equals(request.getSelectAll())) {
List<Long> excludedIds = Optional.ofNullable(request.getExcludedIds()).orElse(List.of());
List<Long> allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds);
log.info("SelectAll: Total files to finalize (after exclusions): {}, Excluded IDs: {}", allIds.size(), excludedIds);
for (int i = 0; i < allIds.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, allIds.size());
List<Long> chunk = allIds.subList(i, end);
log.info("Processing chunk {}/{} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) allIds.size() / CHUNK_SIZE), chunk.size(), chunk);
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunk);
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
for (Long id : chunk) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.warn("File ID {} missing in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
}
} else {
List<Long> ids = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.map(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId)
.toList();
log.info("Processing {} manually selected files in chunks of {}. File IDs: {}", ids.size(), CHUNK_SIZE, ids);
for (int i = 0; i < ids.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, ids.size());
List<Long> chunkIds = ids.subList(i, end);
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunkIds);
log.info("Processing chunk {} of {} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) ids.size() / CHUNK_SIZE), chunkFiles.size(), chunkIds);
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream()
.collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
for (Long id : chunkIds) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.error("File ID {} not found in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
}
}
results.setTotalFiles(totalFilesProcessed.get());
results.setFailed(failedCount.get());
results.setSuccessfullyImported(totalFilesProcessed.get() - failedCount.get());
log.info("Finalization complete. Success: {}, Failed: {}, Total processed: {}",
results.getSuccessfullyImported(),
results.getFailed(),
results.getTotalFiles());
return results;
} finally {
bookdropMonitoringService.resumeMonitoring();
}
}, "bookdrop finalize import");
public Resource getBookdropCover(long bookdropId) {
String coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropId + ".jpg").toString();
File coverFile = new File(coverPath);
if (coverFile.exists() && coverFile.isFile()) {
return new PathResource(coverFile.toPath());
} else {
return null;
}
}
private void processFile(
BookdropFileEntity fileEntity,
BookdropFinalizeRequest.BookdropFinalizeFile fileReq,
Long defaultLibraryId,
Long defaultPathId,
BookdropFinalizeResult results,
AtomicInteger failedCount
) {
public BookdropFinalizeResult finalizeImport(BookdropFinalizeRequest request) {
try {
Long libraryId;
Long pathId;
BookMetadata metadata;
bookdropMonitoringService.pauseMonitoring();
return processFinalizationRequest(request);
} finally {
bookdropMonitoringService.resumeMonitoring();
log.info("Bookdrop monitoring resumed");
}
}
if (fileReq != null) {
libraryId = fileReq.getLibraryId() != null ? fileReq.getLibraryId() : defaultLibraryId;
pathId = fileReq.getPathId() != null ? fileReq.getPathId() : defaultPathId;
metadata = fileReq.getMetadata();
log.debug("Processing fileId={}, fileName={} with provided metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
} else {
if (defaultLibraryId == null || defaultPathId == null) {
log.warn("Missing default metadata for fileId={}", fileEntity.getId());
throw ApiError.GENERIC_BAD_REQUEST.createException("Missing metadata and defaults for fileId=" + fileEntity.getId());
}
public void discardSelectedFiles(boolean selectAll, List<Long> excludedIds, List<Long> selectedIds) {
bookdropMonitoringService.pauseMonitoring();
Path bookdropPath = Path.of(appProperties.getBookdropFolder());
metadata = fileEntity.getFetchedMetadata() != null
? objectMapper.readValue(fileEntity.getFetchedMetadata(), BookMetadata.class)
: objectMapper.readValue(fileEntity.getOriginalMetadata(), BookMetadata.class);
AtomicInteger deletedFiles = new AtomicInteger();
AtomicInteger deletedDirs = new AtomicInteger();
AtomicInteger deletedCovers = new AtomicInteger();
libraryId = defaultLibraryId;
pathId = defaultPathId;
log.debug("Processing fileId={}, fileName={} with default metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
try {
if (!Files.exists(bookdropPath)) {
log.info("Bookdrop folder does not exist: {}", bookdropPath);
return;
}
BookdropFileResult result = moveFile(libraryId, pathId, metadata, fileEntity);
List<BookdropFileEntity> filesToDelete = getFilesToDelete(selectAll, excludedIds, selectedIds);
deleteFilesAndCovers(filesToDelete, deletedFiles, deletedCovers);
deleteEmptyDirectories(bookdropPath, deletedDirs);
bookdropFileRepository.deleteAllById(filesToDelete.stream().map(BookdropFileEntity::getId).toList());
log.info("Deleted {} bookdrop DB entries", filesToDelete.size());
bookdropNotificationService.sendBookdropFileSummaryNotification();
log.info("Bookdrop cleanup summary: deleted {} files, {} folders, {} DB entries, {} covers",
deletedFiles.get(), deletedDirs.get(), filesToDelete.size(), deletedCovers.get());
} finally {
bookdropMonitoringService.resumeMonitoring();
log.info("Bookdrop monitoring resumed after cleanup (library monitoring unaffected)");
}
}
private BookdropFinalizeResult processFinalizationRequest(BookdropFinalizeRequest request) {
BookdropFinalizeResult results = BookdropFinalizeResult.builder()
.processedAt(Instant.now())
.build();
Long defaultLibraryId = request.getDefaultLibraryId();
Long defaultPathId = request.getDefaultPathId();
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById = getMetadataMap(request);
AtomicInteger failedCount = new AtomicInteger();
AtomicInteger totalFilesProcessed = new AtomicInteger();
log.info("Starting finalizeImport: selectAll={}, provided file count={}, defaultLibraryId={}, defaultPathId={}", request.getSelectAll(), metadataById.size(), defaultLibraryId, defaultPathId);
if (Boolean.TRUE.equals(request.getSelectAll())) {
processAllFiles(request, metadataById, defaultLibraryId, defaultPathId, results, failedCount, totalFilesProcessed);
} else {
processSelectedFiles(request, metadataById, defaultLibraryId, defaultPathId, results, failedCount, totalFilesProcessed);
}
updateFinalResults(results, totalFilesProcessed, failedCount);
return results;
}
private Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> getMetadataMap(BookdropFinalizeRequest request) {
return Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.collect(Collectors.toMap(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId, Function.identity()));
}
private void processAllFiles(BookdropFinalizeRequest request,
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById,
Long defaultLibraryId,
Long defaultPathId,
BookdropFinalizeResult results,
AtomicInteger failedCount,
AtomicInteger totalFilesProcessed) {
List<Long> excludedIds = Optional.ofNullable(request.getExcludedIds()).orElse(List.of());
List<Long> allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds);
log.info("SelectAll: Total files to finalize (after exclusions): {}, Excluded IDs: {}", allIds.size(), excludedIds);
processFileChunks(allIds, metadataById, defaultLibraryId, defaultPathId, results, failedCount, totalFilesProcessed);
}
private void processSelectedFiles(BookdropFinalizeRequest request,
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById,
Long defaultLibraryId,
Long defaultPathId,
BookdropFinalizeResult results,
AtomicInteger failedCount,
AtomicInteger totalFilesProcessed) {
List<Long> ids = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.map(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId)
.toList();
log.info("Processing {} manually selected files in chunks of {}. File IDs: {}", ids.size(), CHUNK_SIZE, ids);
processFileChunks(ids, metadataById, defaultLibraryId, defaultPathId, results, failedCount, totalFilesProcessed);
}
private void processFileChunks(List<Long> ids,
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById,
Long defaultLibraryId,
Long defaultPathId,
BookdropFinalizeResult results,
AtomicInteger failedCount,
AtomicInteger totalFilesProcessed) {
for (int i = 0; i < ids.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, ids.size());
List<Long> chunk = ids.subList(i, end);
log.info("Processing chunk {}/{} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) ids.size() / CHUNK_SIZE), chunk.size(), chunk);
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunk);
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
for (Long id : chunk) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.warn("File ID {} missing in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
}
}
private void updateFinalResults(BookdropFinalizeResult results, AtomicInteger totalFilesProcessed, AtomicInteger failedCount) {
results.setTotalFiles(totalFilesProcessed.get());
results.setFailed(failedCount.get());
results.setSuccessfullyImported(totalFilesProcessed.get() - failedCount.get());
log.info("Finalization complete. Success: {}, Failed: {}, Total processed: {}",
results.getSuccessfullyImported(),
results.getFailed(),
results.getTotalFiles());
}
private void processFile(BookdropFileEntity fileEntity,
BookdropFinalizeRequest.BookdropFinalizeFile fileReq,
Long defaultLibraryId,
Long defaultPathId,
BookdropFinalizeResult results,
AtomicInteger failedCount) {
try {
FileProcessingContext context = prepareFileProcessingContext(fileEntity, fileReq, defaultLibraryId, defaultPathId);
BookdropFileResult result = moveFile(context.libraryId, context.pathId, context.metadata, fileEntity);
results.getResults().add(result);
if (!result.isSuccess()) {
@@ -239,7 +266,38 @@ public class BookDropService {
}
}
private BookdropFileResult moveFile(long libraryId, long pathId, BookMetadata metadata, BookdropFileEntity bookdropFile) throws Exception {
private FileProcessingContext prepareFileProcessingContext(BookdropFileEntity fileEntity,
BookdropFinalizeRequest.BookdropFinalizeFile fileReq,
Long defaultLibraryId,
Long defaultPathId) throws Exception {
Long libraryId;
Long pathId;
BookMetadata metadata;
if (fileReq != null) {
libraryId = fileReq.getLibraryId() != null ? fileReq.getLibraryId() : defaultLibraryId;
pathId = fileReq.getPathId() != null ? fileReq.getPathId() : defaultPathId;
metadata = fileReq.getMetadata();
log.debug("Processing fileId={}, fileName={} with provided metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
} else {
if (defaultLibraryId == null || defaultPathId == null) {
log.warn("Missing default metadata for fileId={}", fileEntity.getId());
throw ApiError.GENERIC_BAD_REQUEST.createException("Missing metadata and defaults for fileId=" + fileEntity.getId());
}
metadata = fileEntity.getFetchedMetadata() != null
? objectMapper.readValue(fileEntity.getFetchedMetadata(), BookMetadata.class)
: objectMapper.readValue(fileEntity.getOriginalMetadata(), BookMetadata.class);
libraryId = defaultLibraryId;
pathId = defaultPathId;
log.debug("Processing fileId={}, fileName={} with default metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
}
return new FileProcessingContext(libraryId, pathId, metadata);
}
private BookdropFileResult moveFile(long libraryId, long pathId, BookMetadata metadata, BookdropFileEntity bookdropFile) {
LibraryEntity library = libraryRepository.findById(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
@@ -248,22 +306,12 @@ public class BookDropService {
.findFirst()
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
String filePattern = library.getFileNamingPattern();
if (filePattern == null || filePattern.isBlank()) {
filePattern = appSettingService.getAppSettings().getUploadPattern();
}
if (filePattern.endsWith("/") || filePattern.endsWith("\\")) {
filePattern += "{currentFilename}";
}
String relativePath = PathPatternResolver.resolvePattern(metadata, filePattern, FilenameUtils.getName(bookdropFile.getFilePath()));
String filePattern = fileMovingHelper.getFileNamingPattern(library);
Path source = Path.of(bookdropFile.getFilePath());
Path target = Paths.get(path.getPath(), relativePath);
Path target = fileMovingHelper.generateNewFilePath(path.getPath(), metadata, filePattern, bookdropFile.getFilePath());
File targetFile = target.toFile();
log.debug("Preparing to move file id={}, name={}, source={}, target={}, library={}, path={}",
bookdropFile.getId(), bookdropFile.getFileName(), source, target, library.getName(), path.getPath());
log.debug("Preparing to move file id={}, name={}, source={}, target={}, library={}, path={}", bookdropFile.getId(), bookdropFile.getFileName(), source, target, library.getName(), path.getPath());
if (!Files.exists(source)) {
bookdropFileRepository.deleteById(bookdropFile.getId());
@@ -277,64 +325,93 @@ public class BookDropService {
return failureResult(targetFile.getName(), "File already exists in the library '" + library.getName() + "'");
}
return monitoringProtectionService.executeWithProtection(() -> {
try {
Files.createDirectories(target.getParent());
Files.move(source, target);
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
FileProcessResult fileProcessResult = processFile(targetFile.getName(), library, path, targetFile,
BookFileExtension.fromFileName(bookdropFile.getFileName())
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
.getType());
BookEntity bookEntity = bookRepository.findById(fileProcessResult.getBook().getId())
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getStatus());
metadataRefreshService.updateBookMetadata(bookEntity, metadata, metadata.getThumbnailUrl() != null, false);
bookdropFileRepository.deleteById(bookdropFile.getId());
bookdropNotificationService.sendBookdropFileSummaryNotification();
File cachedCover = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFile.getId() + ".jpg").toFile();
if (cachedCover.exists()) {
boolean deleted = cachedCover.delete();
log.debug("Deleted cached cover image for bookdropId={}: {}", bookdropFile.getId(), deleted);
}
log.info("File import completed: id={}, name={}, library={}, path={}", bookdropFile.getId(), targetFile.getName(), library.getName(), path.getPath());
return BookdropFileResult.builder()
.fileName(targetFile.getName())
.message("File successfully imported into the '" + library.getName() + "' library from the Bookdrop folder")
.success(true)
.build();
} catch (Exception e) {
log.error("Failed to move file id={}, name={} from '{}' to '{}': {}", bookdropFile.getId(), bookdropFile.getFileName(), source, target, e.getMessage(), e);
try {
if (Files.exists(target)) {
Files.deleteIfExists(target);
log.info("Cleaned up partially created target file: {}", target);
}
} catch (Exception cleanupException) {
log.warn("Failed to cleanup target file after move error: {}", target, cleanupException);
}
return failureResult(bookdropFile.getFileName(), "Failed to move file: " + e.getMessage());
}
}, "bookdrop file move");
return performFileMove(bookdropFile, source, target, library, path, metadata);
}
private BookdropFileResult failureResult(String fileName, String message) {
private BookdropFileResult performFileMove(BookdropFileEntity bookdropFile, Path source, Path target,
LibraryEntity library, LibraryPathEntity path, BookMetadata metadata) {
Path tempPath = null;
try {
tempPath = Files.createTempFile("bookdrop-finalize-", bookdropFile.getFileName());
Files.copy(source, tempPath, StandardCopyOption.REPLACE_EXISTING);
Files.createDirectories(target.getParent());
Files.move(tempPath, target, StandardCopyOption.REPLACE_EXISTING);
Files.deleteIfExists(source);
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
return processMovedFile(bookdropFile, target.toFile(), library, path, metadata);
} catch (Exception e) {
log.error("Failed to move file id={}, name={} from '{}' to '{}': {}", bookdropFile.getId(), bookdropFile.getFileName(), source, target, e.getMessage(), e);
cleanupFailedMove(target);
return failureResult(bookdropFile.getFileName(), "Failed to move file: " + e.getMessage());
} finally {
cleanupTempFile(tempPath);
}
}
private BookdropFileResult processMovedFile(BookdropFileEntity bookdropFile,
File targetFile,
LibraryEntity library,
LibraryPathEntity path,
BookMetadata metadata) throws Exception {
FileProcessResult fileProcessResult = processFileInLibrary(targetFile.getName(), library, path, targetFile,
BookFileExtension.fromFileName(bookdropFile.getFileName())
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
.getType());
BookEntity bookEntity = bookRepository.findById(fileProcessResult.getBook().getId())
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getBook());
metadataRefreshService.updateBookMetadata(bookEntity, metadata, metadata.getThumbnailUrl() != null, false);
cleanupBookdropData(bookdropFile);
log.info("File import completed: id={}, name={}, library={}, path={}", bookdropFile.getId(), targetFile.getName(), library.getName(), path.getPath());
return BookdropFileResult.builder()
.fileName(fileName)
.message(message)
.success(false)
.fileName(targetFile.getName())
.message("File successfully imported into the '" + library.getName() + "' library from the Bookdrop folder")
.success(true)
.build();
}
private FileProcessResult processFile(String fileName, LibraryEntity library, LibraryPathEntity path, File file, BookFileType type) {
private void cleanupBookdropData(BookdropFileEntity bookdropFile) {
bookdropFileRepository.deleteById(bookdropFile.getId());
bookdropNotificationService.sendBookdropFileSummaryNotification();
File cachedCover = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFile.getId() + ".jpg").toFile();
if (cachedCover.exists()) {
boolean deleted = cachedCover.delete();
log.debug("Deleted cached cover image for bookdropId={}: {}", bookdropFile.getId(), deleted);
}
}
private void cleanupFailedMove(Path target) {
try {
if (Files.exists(target)) {
Files.deleteIfExists(target);
log.info("Cleaned up partially created target file: {}", target);
}
} catch (Exception cleanupException) {
log.warn("Failed to cleanup target file after move error: {}", target, cleanupException);
}
}
private void cleanupTempFile(Path tempPath) {
if (tempPath != null) {
try {
Files.deleteIfExists(tempPath);
} catch (Exception e) {
log.warn("Failed to cleanup temp file: {}", tempPath, e);
}
}
}
private FileProcessResult processFileInLibrary(String fileName, LibraryEntity library, LibraryPathEntity path, File file, BookFileType type) {
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(library)
.libraryPathEntity(path)
@@ -347,87 +424,67 @@ public class BookDropService {
return processor.processFile(libraryFile);
}
public void discardSelectedFiles(boolean selectAll, List<Long> excludedIds, List<Long> selectedIds) {
bookdropMonitoringService.pauseMonitoring();
Path bookdropPath = Path.of(appProperties.getBookdropFolder());
AtomicInteger deletedFiles = new AtomicInteger();
AtomicInteger deletedDirs = new AtomicInteger();
AtomicInteger deletedCovers = new AtomicInteger();
try {
if (!Files.exists(bookdropPath)) {
log.info("Bookdrop folder does not exist: {}", bookdropPath);
return;
}
List<BookdropFileEntity> filesToDelete;
if (selectAll) {
filesToDelete = bookdropFileRepository.findAll().stream()
.filter(f -> excludedIds == null || !excludedIds.contains(f.getId()))
.toList();
log.info("Discarding all files except excluded IDs: {}", excludedIds);
} else {
filesToDelete = bookdropFileRepository.findAllById(selectedIds == null ? List.of() : selectedIds);
log.info("Discarding selected files: {}", selectedIds);
}
for (BookdropFileEntity entity : filesToDelete) {
try {
Path filePath = Path.of(entity.getFilePath());
if (Files.exists(filePath) && Files.isRegularFile(filePath) && Files.deleteIfExists(filePath)) {
deletedFiles.incrementAndGet();
log.debug("Deleted file from disk: id={}, path={}", entity.getId(), filePath);
}
Path coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", entity.getId() + ".jpg");
if (Files.exists(coverPath) && Files.deleteIfExists(coverPath)) {
deletedCovers.incrementAndGet();
log.debug("Deleted cover image: id={}, path={}", entity.getId(), coverPath);
}
} catch (IOException e) {
log.warn("Failed to delete file or cover for bookdropId={}: {}", entity.getId(), e.getMessage());
}
}
bookdropFileRepository.deleteAllById(filesToDelete.stream().map(BookdropFileEntity::getId).toList());
log.info("Deleted {} bookdrop DB entries", filesToDelete.size());
try (Stream<Path> paths = Files.walk(bookdropPath)) {
paths.sorted(Comparator.reverseOrder())
.filter(p -> !p.equals(bookdropPath) && Files.isDirectory(p))
.forEach(p -> {
try (Stream<Path> subPaths = Files.list(p)) {
if (subPaths.findAny().isEmpty()) {
Files.deleteIfExists(p);
deletedDirs.incrementAndGet();
log.debug("Deleted empty directory: {}", p);
}
} catch (IOException e) {
log.warn("Failed to delete folder: {}", p, e);
}
});
} catch (IOException e) {
log.warn("Failed to scan bookdrop folder for empty directories", e);
}
bookdropNotificationService.sendBookdropFileSummaryNotification();
log.info("Bookdrop cleanup summary: deleted {} files, {} folders, {} DB entries, {} covers",
deletedFiles.get(), deletedDirs.get(), filesToDelete.size(), deletedCovers.get());
} finally {
bookdropMonitoringService.resumeMonitoring();
log.info("Bookdrop monitoring resumed after cleanup");
}
}
public Resource getBookdropCover(long bookdropId) {
String coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropId + ".jpg").toString();
File coverFile = new File(coverPath);
if (coverFile.exists() && coverFile.isFile()) {
return new PathResource(coverFile.toPath());
private List<BookdropFileEntity> getFilesToDelete(boolean selectAll, List<Long> excludedIds, List<Long> selectedIds) {
if (selectAll) {
List<BookdropFileEntity> filesToDelete = bookdropFileRepository.findAll().stream()
.filter(f -> excludedIds == null || !excludedIds.contains(f.getId()))
.toList();
log.info("Discarding all files except excluded IDs: {}", excludedIds);
return filesToDelete;
} else {
return null;
List<BookdropFileEntity> filesToDelete = bookdropFileRepository.findAllById(selectedIds == null ? List.of() : selectedIds);
log.info("Discarding selected files: {}", selectedIds);
return filesToDelete;
}
}
}
private void deleteFilesAndCovers(List<BookdropFileEntity> filesToDelete, AtomicInteger deletedFiles, AtomicInteger deletedCovers) {
for (BookdropFileEntity entity : filesToDelete) {
try {
Path filePath = Path.of(entity.getFilePath());
if (Files.exists(filePath) && Files.isRegularFile(filePath) && Files.deleteIfExists(filePath)) {
deletedFiles.incrementAndGet();
log.debug("Deleted file from disk: id={}, path={}", entity.getId(), filePath);
}
Path coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", entity.getId() + ".jpg");
if (Files.exists(coverPath) && Files.deleteIfExists(coverPath)) {
deletedCovers.incrementAndGet();
log.debug("Deleted cover image: id={}, path={}", entity.getId(), coverPath);
}
} catch (IOException e) {
log.warn("Failed to delete file or cover for bookdropId={}: {}", entity.getId(), e.getMessage());
}
}
}
private void deleteEmptyDirectories(Path bookdropPath, AtomicInteger deletedDirs) {
try (Stream<Path> paths = Files.walk(bookdropPath)) {
paths.sorted(Comparator.reverseOrder())
.filter(p -> !p.equals(bookdropPath) && Files.isDirectory(p))
.forEach(p -> {
try (Stream<Path> subPaths = Files.list(p)) {
if (subPaths.findAny().isEmpty()) {
Files.deleteIfExists(p);
deletedDirs.incrementAndGet();
log.debug("Deleted empty directory: {}", p);
}
} catch (IOException e) {
log.warn("Failed to delete folder: {}", p, e);
}
});
} catch (IOException e) {
log.warn("Failed to scan bookdrop folder for empty directories", e);
}
}
private BookdropFileResult failureResult(String fileName, String message) {
return BookdropFileResult.builder()
.fileName(fileName)
.message(message)
.success(false)
.build();
}
private record FileProcessingContext(Long libraryId, Long pathId, BookMetadata metadata) {
}
}
@@ -93,8 +93,7 @@ public class BookdropMonitoringService {
try {
watchKey = bookdrop.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
StandardWatchEventKinds.ENTRY_DELETE);
paused = false;
log.info("Bookdrop monitoring resumed.");
} catch (IOException e) {
@@ -3,172 +3,86 @@ package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.library.LibraryService;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.PathPatternResolver;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Slf4j
@Service
@AllArgsConstructor
public class FileMoveService {
private static final int BATCH_SIZE = 100;
private final BookQueryService bookQueryService;
private final BookRepository bookRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final BookMapper bookMapper;
private final NotificationService notificationService;
private final LibraryService libraryService;
private final MonitoringProtectionService monitoringProtectionService;
private final AppSettingService appSettingService;
private final UnifiedFileMoveService unifiedFileMoveService;
public void moveFiles(FileMoveRequest request) {
Set<Long> bookIds = request.getBookIds();
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
String defaultPattern = appSettingService.getAppSettings().getUploadPattern();
log.info("Moving {} books in batches of {}", bookIds.size(), BATCH_SIZE);
log.info("Starting file move for {} books", books.size());
List<Book> allUpdatedBooks = new ArrayList<>();
int totalProcessed = 0;
int offset = 0;
Set<Long> libraryIds = new HashSet<>();
while (offset < bookIds.size()) {
log.info("Processing batch {}/{}", (offset / BATCH_SIZE) + 1, (bookIds.size() + BATCH_SIZE - 1) / BATCH_SIZE);
List<BookEntity> batchBooks = bookQueryService.findWithMetadataByIdsWithPagination(bookIds, offset, BATCH_SIZE);
if (batchBooks.isEmpty()) {
log.info("No more books at offset {}", offset);
break;
}
List<Book> batchUpdatedBooks = processBookChunk(batchBooks);
allUpdatedBooks.addAll(batchUpdatedBooks);
totalProcessed += batchBooks.size();
offset += BATCH_SIZE;
log.info("Processed {}/{} books", totalProcessed, bookIds.size());
}
log.info("Move completed: {} books processed, {} updated", totalProcessed, allUpdatedBooks.size());
sendUpdateNotifications(allUpdatedBooks);
}
public String generatePathFromPattern(BookEntity book, String pattern) {
return PathPatternResolver.resolvePattern(book, pattern);
}
private List<Book> processBookChunk(List<BookEntity> books) {
List<Book> updatedBooks = new ArrayList<>();
monitoringProtectionService.executeWithProtection(() -> {
for (BookEntity book : books) {
processBookMove(book, defaultPattern, updatedBooks, libraryIds);
unifiedFileMoveService.moveBatchBookFiles(books, new UnifiedFileMoveService.BatchMoveCallback() {
@Override
public void onBookMoved(BookEntity book) {
bookRepository.save(book);
updatedBooks.add(bookMapper.toBook(book));
}
log.info("Completed file move for {} books.", books.size());
sendUpdateNotifications(updatedBooks);
}, "file move operations");
// Trigger library rescan immediately after file operations complete
if (!libraryIds.isEmpty()) {
rescanLibraries(libraryIds);
}
}
private void processBookMove(BookEntity book, String defaultPattern, List<Book> updatedBooks, Set<Long> libraryIds) {
if (book.getMetadata() == null) return;
String pattern = getFileNamingPattern(book, defaultPattern);
if (pattern == null) return;
if (!hasRequiredPathComponents(book)) return;
Path oldFilePath = book.getFullFilePath();
if (!Files.exists(oldFilePath)) {
log.warn("File does not exist for book id {}: {}", book.getId(), oldFilePath);
return;
}
log.info("Processing book id {}: '{}'", book.getId(), book.getMetadata().getTitle());
Path newFilePath = generateNewFilePath(book, pattern);
if (oldFilePath.equals(newFilePath)) {
log.info("Source and destination paths are identical for book id {}. Skipping.", book.getId());
return;
}
try {
moveFileAndUpdateBook(book, oldFilePath, newFilePath, updatedBooks, libraryIds);
// Move additional files if present
if (book.getAdditionalFiles() != null && !book.getAdditionalFiles().isEmpty()) {
moveAdditionalFiles(book, pattern);
@Override
public void onBookMoveFailed(BookEntity book, Exception error) {
log.error("Move failed for book {}: {}", book.getId(), error.getMessage(), error);
throw new RuntimeException("File move failed for book id " + book.getId(), error);
}
} catch (IOException e) {
log.error("Failed to move file for book id {}: {}", book.getId(), e.getMessage(), e);
}
}
});
private String getFileNamingPattern(BookEntity book, String defaultPattern) {
if (book.getLibraryPath() == null || book.getLibraryPath().getLibrary() == null) {
log.error("Book id {} has no library associated. Skipping.", book.getId());
return null;
}
LibraryEntity library = book.getLibraryPath().getLibrary();
String pattern = library.getFileNamingPattern();
if (pattern == null || pattern.trim().isEmpty()) {
pattern = defaultPattern;
log.info("Using default pattern for library {} as no custom pattern is set", library.getName());
}
if (pattern == null || pattern.trim().isEmpty()) {
log.error("No file naming pattern available for book id {}. Skipping.", book.getId());
return null;
}
return pattern;
}
private boolean hasRequiredPathComponents(BookEntity book) {
if (book.getLibraryPath() == null || book.getLibraryPath().getPath() == null ||
book.getFileSubPath() == null || book.getFileName() == null) {
log.error("Missing required path components for book id {}. Skipping.", book.getId());
return false;
}
return true;
}
private Path generateNewFilePath(BookEntity book, String pattern) {
String newRelativePathStr = generatePathFromPattern(book, pattern);
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
newRelativePathStr = newRelativePathStr.substring(1);
}
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
return libraryRoot.resolve(newRelativePathStr).normalize();
}
private void moveFileAndUpdateBook(BookEntity book, Path oldFilePath, Path newFilePath,
List<Book> updatedBooks, Set<Long> libraryIds) throws IOException {
if (newFilePath.getParent() != null) {
Files.createDirectories(newFilePath.getParent());
}
log.info("Moving file from {} to {}", oldFilePath, newFilePath);
Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING);
updateBookPaths(book, newFilePath);
bookRepository.save(book);
updatedBooks.add(bookMapper.toBook(book));
log.info("Updated book id {} with new path", book.getId());
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), Set.of(libraryRoot));
if (book.getLibraryPath().getLibrary().getId() != null) {
libraryIds.add(book.getLibraryPath().getLibrary().getId());
}
}
private void updateBookPaths(BookEntity book, Path newFilePath) {
String newFileName = newFilePath.getFileName().toString();
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent());
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
book.setFileSubPath(newFileSubPath);
book.setFileName(newFileName);
return updatedBooks;
}
private void sendUpdateNotifications(List<Book> updatedBooks) {
@@ -176,169 +90,4 @@ public class FileMoveService {
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_UPDATE, updatedBooks);
}
}
private void rescanLibraries(Set<Long> libraryIds) {
for (Long libraryId : libraryIds) {
try {
libraryService.rescanLibrary(libraryId);
log.info("Rescanned library id {} after file move", libraryId);
} catch (Exception e) {
log.error("Failed to rescan library id {}: {}", libraryId, e.getMessage(), e);
}
}
}
public String generatePathFromPattern(BookEntity book, String pattern) {
return PathPatternResolver.resolvePattern(book, pattern);
}
private void moveAdditionalFiles(BookEntity book, String pattern) throws IOException {
Map<String, Integer> fileNameCounter = new HashMap<>();
for (BookAdditionalFileEntity additionalFile : book.getAdditionalFiles()) {
Path oldAdditionalFilePath = additionalFile.getFullFilePath();
if (!Files.exists(oldAdditionalFilePath)) {
log.warn("Additional file does not exist for book id {}: {}", book.getId(), oldAdditionalFilePath);
continue;
}
String newRelativePathStr = PathPatternResolver.resolvePattern(book.getMetadata(), pattern, additionalFile.getFileName());
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
newRelativePathStr = newRelativePathStr.substring(1);
}
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
Path newAdditionalFilePath = libraryRoot.resolve(newRelativePathStr).normalize();
// Check for filename uniqueness and add index if necessary
newAdditionalFilePath = ensureUniqueFilePath(newAdditionalFilePath, fileNameCounter);
if (oldAdditionalFilePath.equals(newAdditionalFilePath)) {
log.debug("Source and destination paths are identical for additional file id {}. Skipping.", additionalFile.getId());
continue;
}
// Create parent directories if needed
if (newAdditionalFilePath.getParent() != null) {
Files.createDirectories(newAdditionalFilePath.getParent());
}
log.info("Moving additional file from {} to {}", oldAdditionalFilePath, newAdditionalFilePath);
Files.move(oldAdditionalFilePath, newAdditionalFilePath, StandardCopyOption.REPLACE_EXISTING);
// Update additional file paths
updateAdditionalFilePaths(additionalFile, newAdditionalFilePath, libraryRoot);
bookAdditionalFileRepository.save(additionalFile);
log.info("Updated additional file id {} with new path", additionalFile.getId());
}
}
private Path ensureUniqueFilePath(Path filePath, Map<String, Integer> fileNameCounter) {
String fileName = filePath.getFileName().toString();
String baseName = fileName;
String extension = "";
int lastDot = fileName.lastIndexOf(".");
if (lastDot >= 0 && lastDot < fileName.length() - 1) {
baseName = fileName.substring(0, lastDot);
extension = fileName.substring(lastDot);
}
String fileKey = filePath.toString().toLowerCase();
Integer count = fileNameCounter.get(fileKey);
if (count == null) {
fileNameCounter.put(fileKey, 1);
return filePath;
} else {
// File name already exists, add index
count++;
fileNameCounter.put(fileKey, count);
String newFileName = baseName + "_" + count + extension;
return filePath.getParent().resolve(newFileName);
}
}
private void updateAdditionalFilePaths(BookAdditionalFileEntity additionalFile, Path newFilePath, Path libraryRoot) {
String newFileName = newFilePath.getFileName().toString();
Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent());
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
additionalFile.setFileSubPath(newFileSubPath);
additionalFile.setFileName(newFileName);
}
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
currentDir = currentDir.toAbsolutePath().normalize();
Set<Path> normalizedRoots = new HashSet<>();
for (Path root : libraryRoots) {
normalizedRoots.add(root.toAbsolutePath().normalize());
}
while (currentDir != null) {
if (isLibraryRoot(currentDir, normalizedRoots)) {
log.debug("Reached library root: {}. Stopping cleanup.", currentDir);
break;
}
File[] files = currentDir.toFile().listFiles();
if (files == null) {
log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir);
break;
}
if (hasOnlyIgnoredFiles(files, ignoredFilenames)) {
deleteIgnoredFilesAndDirectory(files, currentDir);
currentDir = currentDir.getParent();
} else {
log.debug("Directory {} contains important files. Stopping cleanup.", currentDir);
break;
}
}
}
private boolean isLibraryRoot(Path currentDir, Set<Path> normalizedRoots) {
for (Path root : normalizedRoots) {
try {
if (Files.isSameFile(root, currentDir)) {
return true;
}
} catch (IOException e) {
log.warn("Failed to compare paths: {} and {}", root, currentDir);
}
}
return false;
}
private boolean hasOnlyIgnoredFiles(File[] files, Set<String> ignoredFilenames) {
for (File file : files) {
if (!ignoredFilenames.contains(file.getName())) {
return false;
}
}
return true;
}
private void deleteIgnoredFilesAndDirectory(File[] files, Path currentDir) {
for (File file : files) {
try {
Files.delete(file.toPath());
log.info("Deleted ignored file: {}", file.getAbsolutePath());
} catch (IOException e) {
log.warn("Failed to delete ignored file: {}", file.getAbsolutePath());
}
}
try {
Files.delete(currentDir);
log.info("Deleted empty directory: {}", currentDir);
} catch (IOException e) {
log.warn("Failed to delete directory: {}", currentDir, e);
}
}
}
@@ -0,0 +1,303 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.PathPatternResolver;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Slf4j
@Component
@AllArgsConstructor
public class FileMovingHelper {
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final AppSettingService appSettingService;
/**
* Generates the new file path based on the library's file naming pattern
*/
public Path generateNewFilePath(BookEntity book, String pattern) {
String newRelativePathStr = PathPatternResolver.resolvePattern(book, pattern);
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
newRelativePathStr = newRelativePathStr.substring(1);
}
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
return libraryRoot.resolve(newRelativePathStr).normalize();
}
/**
* Generates the new file path based on metadata and file naming pattern
*/
public Path generateNewFilePath(String libraryRootPath, BookMetadata metadata, String pattern, String fileName) {
String relativePath = PathPatternResolver.resolvePattern(metadata, pattern, FilenameUtils.getName(fileName));
return Paths.get(libraryRootPath, relativePath);
}
/**
* Gets the file naming pattern for a library, falling back to default if not set,
* and finally to {currentFilename} if no patterns are available
*/
public String getFileNamingPattern(LibraryEntity library) {
String pattern = library.getFileNamingPattern();
if (pattern == null || pattern.trim().isEmpty()) {
try {
pattern = appSettingService.getAppSettings().getUploadPattern();
log.debug("Using default pattern for library {} as no custom pattern is set", library.getName());
} catch (Exception e) {
log.warn("Failed to get default upload pattern for library {}: {}", library.getName(), e.getMessage());
}
}
if (pattern == null || pattern.trim().isEmpty()) {
pattern = "{currentFilename}";
log.info("No file naming pattern available for library {}. Using fallback pattern: {currentFilename}", library.getName());
}
// Ensure pattern ends with filename placeholder if it ends with separator
if (pattern.endsWith("/") || pattern.endsWith("\\")) {
pattern += "{currentFilename}";
}
return pattern;
}
/**
* Checks if a book has all required path components for file operations
*/
public boolean hasRequiredPathComponents(BookEntity book) {
if (book.getLibraryPath() == null || book.getLibraryPath().getPath() == null ||
book.getFileSubPath() == null || book.getFileName() == null) {
log.error("Missing required path components for book id {}. Skipping.", book.getId());
return false;
}
return true;
}
/**
* Moves a book file if the current path differs from the expected pattern
*/
public boolean moveBookFileIfNeeded(BookEntity book, String pattern) throws IOException {
Path oldFilePath = book.getFullFilePath();
Path newFilePath = generateNewFilePath(book, pattern);
if (oldFilePath.equals(newFilePath)) {
log.debug("Source and destination paths are identical for book id {}. Skipping.", book.getId());
return false;
}
moveBookFileAndUpdatePaths(book, oldFilePath, newFilePath);
return true;
}
/**
* Moves a file from source to target path, creating directories as needed
*/
public void moveFile(Path source, Path target) throws IOException {
if (target.getParent() != null) {
Files.createDirectories(target.getParent());
}
log.info("Moving file from {} to {}", source, target);
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
}
/**
* Updates book entity paths after a file move
*/
public void updateBookPaths(BookEntity book, Path newFilePath) {
String newFileName = newFilePath.getFileName().toString();
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent());
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
book.setFileSubPath(newFileSubPath);
book.setFileName(newFileName);
}
/**
* Moves additional files for a book based on the file naming pattern
*/
public void moveAdditionalFiles(BookEntity book, String pattern) throws IOException {
Map<String, Integer> fileNameCounter = new HashMap<>();
for (BookAdditionalFileEntity additionalFile : book.getAdditionalFiles()) {
moveAdditionalFile(book, additionalFile, pattern, fileNameCounter);
}
}
/**
* Deletes empty parent directories up to library roots
*/
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
currentDir = currentDir.toAbsolutePath().normalize();
Set<Path> normalizedRoots = new HashSet<>();
for (Path root : libraryRoots) {
normalizedRoots.add(root.toAbsolutePath().normalize());
}
while (currentDir != null) {
if (isLibraryRoot(currentDir, normalizedRoots)) {
log.debug("Reached library root: {}. Stopping cleanup.", currentDir);
break;
}
File[] files = currentDir.toFile().listFiles();
if (files == null) {
log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir);
break;
}
if (hasOnlyIgnoredFiles(files, ignoredFilenames)) {
deleteIgnoredFilesAndDirectory(files, currentDir);
currentDir = currentDir.getParent();
} else {
log.debug("Directory {} contains important files. Stopping cleanup.", currentDir);
break;
}
}
}
private void moveBookFileAndUpdatePaths(BookEntity book, Path oldFilePath, Path newFilePath) throws IOException {
moveFile(oldFilePath, newFilePath);
updateBookPaths(book, newFilePath);
// Clean up empty directories
try {
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), Set.of(libraryRoot));
} catch (IOException e) {
log.warn("Failed to clean up empty directories after moving book ID {}: {}", book.getId(), e.getMessage());
}
}
private void moveAdditionalFile(BookEntity book, BookAdditionalFileEntity additionalFile, String pattern, Map<String, Integer> fileNameCounter) throws IOException {
Path oldAdditionalFilePath = additionalFile.getFullFilePath();
if (!Files.exists(oldAdditionalFilePath)) {
log.warn("Additional file does not exist for book id {}: {}", book.getId(), oldAdditionalFilePath);
return;
}
Path newAdditionalFilePath = generateAdditionalFilePath(book, additionalFile, pattern);
newAdditionalFilePath = ensureUniqueFilePath(newAdditionalFilePath, fileNameCounter);
if (oldAdditionalFilePath.equals(newAdditionalFilePath)) {
log.debug("Source and destination paths are identical for additional file id {}. Skipping.", additionalFile.getId());
return;
}
moveFile(oldAdditionalFilePath, newAdditionalFilePath);
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
updateAdditionalFilePaths(additionalFile, newAdditionalFilePath, libraryRoot);
bookAdditionalFileRepository.save(additionalFile);
log.info("Updated additional file id {} with new path", additionalFile.getId());
}
private Path generateAdditionalFilePath(BookEntity book, BookAdditionalFileEntity additionalFile, String pattern) {
String newRelativePathStr = PathPatternResolver.resolvePattern(book.getMetadata(), pattern, additionalFile.getFileName());
// Fall back to the filename when resolver returns null/empty to avoid NPEs in callers/tests
if (newRelativePathStr == null || newRelativePathStr.trim().isEmpty()) {
newRelativePathStr = additionalFile.getFileName() != null ? additionalFile.getFileName() : "";
}
if (!newRelativePathStr.isEmpty() && (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\"))) {
newRelativePathStr = newRelativePathStr.substring(1);
}
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
return libraryRoot.resolve(newRelativePathStr).normalize();
}
private Path ensureUniqueFilePath(Path filePath, Map<String, Integer> fileNameCounter) {
String fileName = filePath.getFileName().toString();
String baseName = fileName;
String extension = "";
int lastDot = fileName.lastIndexOf(".");
if (lastDot >= 0 && lastDot < fileName.length() - 1) {
baseName = fileName.substring(0, lastDot);
extension = fileName.substring(lastDot);
}
String fileKey = filePath.toString().toLowerCase();
Integer count = fileNameCounter.get(fileKey);
if (count == null) {
fileNameCounter.put(fileKey, 1);
return filePath;
} else {
count++;
fileNameCounter.put(fileKey, count);
String newFileName = baseName + "_" + count + extension;
return filePath.getParent().resolve(newFileName);
}
}
private void updateAdditionalFilePaths(BookAdditionalFileEntity additionalFile, Path newFilePath, Path libraryRoot) {
String newFileName = newFilePath.getFileName().toString();
Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent());
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
additionalFile.setFileSubPath(newFileSubPath);
additionalFile.setFileName(newFileName);
}
private boolean isLibraryRoot(Path currentDir, Set<Path> normalizedRoots) {
for (Path root : normalizedRoots) {
try {
if (Files.isSameFile(root, currentDir)) {
return true;
}
} catch (IOException e) {
log.warn("Failed to compare paths: {} and {}", root, currentDir);
}
}
return false;
}
private boolean hasOnlyIgnoredFiles(File[] files, Set<String> ignoredFilenames) {
for (File file : files) {
if (!ignoredFilenames.contains(file.getName())) {
return false;
}
}
return true;
}
private void deleteIgnoredFilesAndDirectory(File[] files, Path currentDir) {
for (File file : files) {
try {
Files.delete(file.toPath());
log.info("Deleted ignored file: {}", file.getAbsolutePath());
} catch (IOException e) {
log.warn("Failed to delete ignored file: {}", file.getAbsolutePath());
}
}
try {
Files.delete(currentDir);
log.info("Deleted empty directory: {}", currentDir);
} catch (IOException e) {
log.warn("Failed to delete directory: {}", currentDir, e);
}
}
}
@@ -0,0 +1,147 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* Service responsible for executing file operations while temporarily disabling monitoring
* on specific paths to prevent event loops and race conditions during file system operations.
*
* This service provides targeted path protection by unregistering only the directories
* involved in the operation rather than pausing all monitoring, ensuring minimal
* disruption to the monitoring system.
*/
@Slf4j
@Component
@AllArgsConstructor
public class MonitoredFileOperationService {
private final MonitoringRegistrationService monitoringRegistrationService;
/**
* Executes a file operation with targeted path protection to prevent monitoring conflicts.
*
* This method temporarily unregisters monitoring for only the specific directories involved
* in the operation (source and target) rather than pausing all monitoring. This approach
* minimizes the impact on the monitoring system while preventing event loops that could
* occur when the monitoring service detects changes from our own file operations.
*
* The process follows these steps:
* 1. Identify source and target directories
* 2. Temporarily unregister monitoring for these specific paths
* 3. Execute the file operation
* 4. Wait for filesystem operations to settle
* 5. Re-register paths and scan for new directory structures
*
* @param sourcePath the source file path for the operation
* @param targetPath the target file path for the operation
* @param libraryId the library ID used for re-registration of monitoring
* @param operation the file operation to execute (supplied as a lambda)
* @param <T> the return type of the operation
*/
public <T> void executeWithMonitoringSuspended(Path sourcePath, Path targetPath, Long libraryId, Supplier<T> operation) {
// Extract parent directories since we monitor directories, not individual files
Path sourceDir = sourcePath.getParent();
Path targetDir = targetPath.getParent();
// Track which paths we unregister so we can restore them later
Set<Path> unregisteredPaths = new HashSet<>();
try {
// Unregister source directory to prevent detection of file removal events
if (monitoringRegistrationService.isPathMonitored(sourceDir)) {
monitoringRegistrationService.unregisterSpecificPath(sourceDir);
unregisteredPaths.add(sourceDir);
log.debug("Temporarily unregistered source directory to prevent monitoring conflicts: {}", sourceDir);
}
// Unregister target directory if it's different from source and already exists
// This prevents detection of file creation events during the operation
if (!sourceDir.equals(targetDir) && Files.exists(targetDir) && monitoringRegistrationService.isPathMonitored(targetDir)) {
monitoringRegistrationService.unregisterSpecificPath(targetDir);
unregisteredPaths.add(targetDir);
log.info("Temporarily unregistered target directory to prevent monitoring conflicts: {}", targetDir);
}
log.debug("Protected {} directory paths from monitoring during file operation", unregisteredPaths.size());
// Execute the actual file operation (move, copy, delete, etc.)
T result = operation.get();
// Allow filesystem operations to complete and settle before re-enabling monitoring
// This prevents race conditions where monitoring might restart before the operation is fully complete
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Thread interrupted while waiting for filesystem operations to settle");
}
} finally {
// Always restore monitoring, even if the operation failed
reregisterPathsAfterMove(unregisteredPaths, libraryId, targetDir);
}
}
/**
* Restores monitoring registration for paths after a file operation and discovers new directories.
*
* This method handles the cleanup phase by:
* 1. Re-registering previously monitored paths that still exist
* 2. Registering new directory structures created by the operation
* 3. Ensuring comprehensive monitoring coverage after the operation
*
* @param unregisteredPaths the set of paths that were temporarily unregistered
* @param libraryId the library ID to use for new registrations
* @param targetDir the target directory where new structures might have been created
*/
private void reregisterPathsAfterMove(Set<Path> unregisteredPaths, Long libraryId, Path targetDir) {
// Restore monitoring for original paths that still exist after the operation
for (Path path : unregisteredPaths) {
if (Files.exists(path) && Files.isDirectory(path)) {
monitoringRegistrationService.registerSpecificPath(path, libraryId);
log.debug("Restored monitoring for existing path: {}", path);
} else {
log.info("Path no longer exists after operation, skipping re-registration: {}", path);
}
}
// Register monitoring for new directory structures created at the target location
if (Files.exists(targetDir) && Files.isDirectory(targetDir)) {
// Register the target directory itself if it wasn't previously monitored
if (!monitoringRegistrationService.isPathMonitored(targetDir)) {
monitoringRegistrationService.registerSpecificPath(targetDir, libraryId);
log.debug("Registered new target directory for monitoring: {}", targetDir);
}
// Discover and register any new subdirectories created during the operation
// This ensures complete monitoring coverage for complex directory structures
try (Stream<Path> stream = Files.walk(targetDir)) {
stream.filter(Files::isDirectory)
.filter(Files::exists)
.filter(path -> !path.equals(targetDir)) // Skip the parent directory itself
.forEach(path -> {
if (!monitoringRegistrationService.isPathMonitored(path)) {
monitoringRegistrationService.registerSpecificPath(path, libraryId);
log.info("Registered new subdirectory for monitoring: {}", path);
}
});
} catch (IOException e) {
log.warn("Failed to scan and register new subdirectories at: {}", targetDir, e);
}
}
log.debug("Completed restoration of monitoring after file operation");
}
}
@@ -0,0 +1,184 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
@Slf4j
@Service
@AllArgsConstructor
public class UnifiedFileMoveService {
private final FileMovingHelper fileMovingHelper;
private final MonitoredFileOperationService monitoredFileOperationService;
private final MonitoringRegistrationService monitoringRegistrationService;
/**
* Moves a single book file to match the library's file naming pattern.
* Used for metadata updates where one file needs to be moved.
*/
public void moveSingleBookFile(BookEntity bookEntity) {
if (bookEntity.getLibraryPath() == null || bookEntity.getLibraryPath().getLibrary() == null) {
log.debug("Book ID {} has no library associated. Skipping file move.", bookEntity.getId());
return;
}
String pattern = fileMovingHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary());
if (!fileMovingHelper.hasRequiredPathComponents(bookEntity)) {
log.debug("Missing required path components for book ID {}. Skipping file move.", bookEntity.getId());
return;
}
Path currentFilePath = bookEntity.getFullFilePath();
if (!Files.exists(currentFilePath)) {
log.warn("File does not exist for book ID {}: {}. Skipping file move.", bookEntity.getId(), currentFilePath);
return;
}
// Check if current path differs from expected pattern
Path expectedFilePath = fileMovingHelper.generateNewFilePath(bookEntity, pattern);
if (currentFilePath.equals(expectedFilePath)) {
log.debug("File for book ID {} is already in the correct location according to library pattern. No move needed.", bookEntity.getId());
return;
}
log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, expectedFilePath);
// For single file moves, use targeted path protection
monitoredFileOperationService.executeWithMonitoringSuspended(currentFilePath, expectedFilePath, bookEntity.getLibraryPath().getLibrary().getId(), () -> {
try {
boolean moved = fileMovingHelper.moveBookFileIfNeeded(bookEntity, pattern);
if (moved) {
log.info("Successfully moved file for book ID {} from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, bookEntity.getFullFilePath());
}
return moved;
} catch (IOException e) {
log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
throw new RuntimeException("File move failed", e);
}
});
}
/**
* Moves multiple book files in batches with library-level monitoring protection.
* Used for bulk file operations where many files need to be moved.
*/
public void moveBatchBookFiles(List<BookEntity> books, BatchMoveCallback callback) {
if (books.isEmpty()) {
log.debug("No books to move");
return;
}
Set<Long> libraryIds = new HashSet<>();
Map<Long, Set<Path>> libraryToRootsMap = new HashMap<>();
// Collect library information for monitoring protection
for (BookEntity book : books) {
if (book.getMetadata() == null) continue;
if (!fileMovingHelper.hasRequiredPathComponents(book)) continue;
Path oldFilePath = book.getFullFilePath();
if (!Files.exists(oldFilePath)) continue;
Long libraryId = book.getLibraryPath().getLibrary().getId();
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
libraryToRootsMap.computeIfAbsent(libraryId, k -> new HashSet<>()).add(libraryRoot);
libraryIds.add(libraryId);
}
// Unregister libraries for batch operation
unregisterLibrariesBatch(libraryToRootsMap);
try {
// Process each book
for (BookEntity book : books) {
if (book.getMetadata() == null) continue;
String pattern = fileMovingHelper.getFileNamingPattern(book.getLibraryPath().getLibrary());
if (!fileMovingHelper.hasRequiredPathComponents(book)) continue;
Path oldFilePath = book.getFullFilePath();
if (!Files.exists(oldFilePath)) {
log.warn("File not found for book {}: {}", book.getId(), oldFilePath);
continue;
}
log.debug("Moving book {}: '{}'", book.getId(), book.getMetadata().getTitle());
try {
boolean moved = fileMovingHelper.moveBookFileIfNeeded(book, pattern);
if (moved) {
log.debug("Book {} moved successfully", book.getId());
callback.onBookMoved(book);
}
// Move additional files if any
if (book.getAdditionalFiles() != null && !book.getAdditionalFiles().isEmpty()) {
fileMovingHelper.moveAdditionalFiles(book, pattern);
}
} catch (IOException e) {
log.error("Move failed for book {}: {}", book.getId(), e.getMessage(), e);
callback.onBookMoveFailed(book, e);
}
}
// Small delay to let filesystem operations settle
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted during batch move delay");
}
} finally {
// Re-register libraries
registerLibrariesBatch(libraryToRootsMap);
}
}
private void unregisterLibrariesBatch(Map<Long, Set<Path>> libraryToRootsMap) {
log.debug("Unregistering {} libraries for batch move", libraryToRootsMap.size());
for (Map.Entry<Long, Set<Path>> entry : libraryToRootsMap.entrySet()) {
Long libraryId = entry.getKey();
monitoringRegistrationService.unregisterLibrary(libraryId);
log.debug("Unregistered library {}", libraryId);
}
}
private void registerLibrariesBatch(Map<Long, Set<Path>> libraryToRootsMap) {
log.debug("Re-registering {} libraries after batch move", libraryToRootsMap.size());
for (Map.Entry<Long, Set<Path>> entry : libraryToRootsMap.entrySet()) {
Long libraryId = entry.getKey();
Set<Path> libraryRoots = entry.getValue();
for (Path libraryRoot : libraryRoots) {
if (Files.exists(libraryRoot) && Files.isDirectory(libraryRoot)) {
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
log.debug("Re-registered library {} at {}", libraryId, libraryRoot);
}
}
}
}
/**
* Callback interface for batch move operations
*/
public interface BatchMoveCallback {
void onBookMoved(BookEntity book);
void onBookMoveFailed(BookEntity book, Exception error);
}
}
@@ -104,6 +104,7 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
if (!sameLibraryPath) {
entity.setLibraryPath(libraryFile.getLibraryPathEntity());
entity.setLibrary(libraryFile.getLibraryEntity());
updated = true;
}
@@ -13,6 +13,7 @@ import com.adityachandel.booklore.repository.AuthorRepository;
import com.adityachandel.booklore.repository.CategoryRepository;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.file.UnifiedFileMoveService;
import com.adityachandel.booklore.service.metadata.backuprestore.MetadataBackupRestore;
import com.adityachandel.booklore.service.metadata.backuprestore.MetadataBackupRestoreFactory;
import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory;
@@ -49,6 +50,7 @@ public class BookMetadataUpdater {
private final MetadataWriterFactory metadataWriterFactory;
private final MetadataBackupRestoreFactory metadataBackupRestoreFactory;
private final BookReviewUpdateService bookReviewUpdateService;
private final UnifiedFileMoveService unifiedFileMoveService;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void setBookMetadata(BookEntity bookEntity, MetadataUpdateWrapper wrapper, boolean setThumbnail, boolean mergeCategories) {
@@ -109,45 +111,55 @@ public class BookMetadataUpdater {
log.info("CBX metadata writing disabled for book ID {}", bookId);
} else {
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
try {
String thumbnailUrl = setThumbnail ? newMetadata.getThumbnailUrl() : null;
try {
String thumbnailUrl = setThumbnail ? newMetadata.getThumbnailUrl() : null;
if ((StringUtils.hasText(thumbnailUrl) && isLocalOrPrivateUrl(thumbnailUrl) || Boolean.TRUE.equals(metadata.getCoverLocked()))) {
log.debug("Blocked local/private thumbnail URL: {}", thumbnailUrl);
thumbnailUrl = null;
}
File file = new File(bookEntity.getFullFilePath().toUri());
writer.writeMetadataToFile(file, metadata, thumbnailUrl, false, clearFlags);
String newHash = "";
// Special handling: If original file was .cbr or .cb7 and now .cbz exists, update to .cbz
File resultingFile = file;
if (!file.exists()) {
// Replace last extension .cbr or .cb7 (case-insensitive) with .cbz
String cbzName = file.getName().replaceFirst("(?i)\\.(cbr|cb7)$", ".cbz");
File cbzFile = new File(file.getParentFile(), cbzName);
if (cbzFile.exists()) {
bookEntity.setFileName(cbzName);
resultingFile = cbzFile;
if ((StringUtils.hasText(thumbnailUrl) && isLocalOrPrivateUrl(thumbnailUrl) || Boolean.TRUE.equals(metadata.getCoverLocked()))) {
log.debug("Blocked local/private thumbnail URL: {}", thumbnailUrl);
thumbnailUrl = null;
}
bookEntity.setFileSizeKb(resultingFile.length() / 1024);
log.info("Converted to CBZ: {} -> {}", file.getAbsolutePath(), resultingFile.getAbsolutePath());
newHash = FileFingerprint.generateHash(resultingFile.toPath());
} else {
newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
File file = new File(bookEntity.getFullFilePath().toUri());
writer.writeMetadataToFile(file, metadata, thumbnailUrl, false, clearFlags);
String newHash;
// Special handling: If original file was .cbr or .cb7 and now .cbz exists, update to .cbz
File resultingFile = file;
if (!file.exists()) {
// Replace last extension .cbr or .cb7 (case-insensitive) with .cbz
String cbzName = file.getName().replaceFirst("(?i)\\.(cbr|cb7)$", ".cbz");
File cbzFile = new File(file.getParentFile(), cbzName);
if (cbzFile.exists()) {
bookEntity.setFileName(cbzName);
resultingFile = cbzFile;
}
bookEntity.setFileSizeKb(resultingFile.length() / 1024);
log.info("Converted to CBZ: {} -> {}", file.getAbsolutePath(), resultingFile.getAbsolutePath());
newHash = FileFingerprint.generateHash(resultingFile.toPath());
} else {
newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
}
bookEntity.setCurrentHash(newHash);
} catch (Exception e) {
log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage());
}
bookEntity.setCurrentHash(newHash);
} catch (Exception e) {
log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage());
}
});
}
});
}
}
boolean moveFilesToLibraryPattern = settings.isMoveFilesToLibraryPattern();
if (moveFilesToLibraryPattern) {
try {
unifiedFileMoveService.moveSingleBookFile(bookEntity);
} catch (Exception e) {
log.warn("Failed to move files for book ID {} after metadata update: {}", bookId, e.getMessage());
}
}
}
private void updateBasicFields(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear) {
handleFieldUpdate(e.getTitleLocked(), clear.isTitle(), m.getTitle(), v -> e.setTitle(nullIfBlank(v)));
handleFieldUpdate(e.getSubtitleLocked(), clear.isSubtitle(), m.getSubtitle(), v -> e.setSubtitle(nullIfBlank(v)));
@@ -1,124 +0,0 @@
package com.adityachandel.booklore.service.monitoring;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.function.Supplier;
/**
* Thread-safe service for managing monitoring protection during file operations.
*
* This service prevents race conditions where file operations are detected as
* "missing files" by the monitoring system, which could lead to data loss.
*
* The service ensures:
* - Thread-safe pause/resume operations
* - Monitoring always resumes even on exceptions
* - Protection against concurrent operations interfering with each other
*/
@Slf4j
@Service
@AllArgsConstructor
public class MonitoringProtectionService {
private final MonitoringService monitoringService;
// Synchronization lock to prevent race conditions in pause/resume logic
private static final Object monitoringLock = new Object();
/**
* Executes an operation with monitoring protection.
*
* @param operation The operation to execute while monitoring is paused
* @param operationName Name for logging purposes
* @param <T> Return type of the operation
* @return Result of the operation
*/
public <T> T executeWithProtection(Supplier<T> operation, String operationName) {
boolean didPause = pauseMonitoringSafely();
try {
log.debug("Executing {} with monitoring protection (paused: {})", operationName, didPause);
return operation.get();
} finally {
resumeMonitoringSafely(didPause, operationName);
}
}
/**
* Executes a void operation with monitoring protection.
*
* @param operation The operation to execute while monitoring is paused
* @param operationName Name for logging purposes
*/
public void executeWithProtection(Runnable operation, String operationName) {
executeWithProtection(() -> {
operation.run();
return null;
}, operationName);
}
/**
* Thread-safe pause of monitoring service.
*
* @return true if monitoring was paused by this call, false if already paused
*/
private boolean pauseMonitoringSafely() {
synchronized (monitoringLock) {
if (!monitoringService.isPaused()) {
monitoringService.pauseMonitoring();
log.debug("Monitoring paused for file operations");
return true;
}
log.debug("Monitoring already paused by another operation");
return false;
}
}
/**
* Thread-safe resume of monitoring service with a 5-second delay.
* The delay is critical to prevent race conditions where file operations
* are still settling when monitoring resumes.
*
* @param didPause true if this operation paused monitoring
* @param operationName name of the operation for logging
*/
private void resumeMonitoringSafely(boolean didPause, String operationName) {
if (!didPause) {
log.debug("Monitoring was not paused by {} - no resume needed", operationName);
return;
}
// Use virtual thread for delayed resume to avoid blocking
Thread.startVirtualThread(() -> {
try {
Thread.sleep(5_000); // Critical 5-second delay for filesystem operations to settle
synchronized (monitoringLock) {
// Double-check that monitoring is still paused before resuming
if (monitoringService.isPaused()) {
monitoringService.resumeMonitoring();
log.debug("Monitoring resumed after {} completed with 5s delay", operationName);
} else {
log.warn("Monitoring was already resumed by another thread during {}", operationName);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while delaying resume of monitoring after {}", operationName);
}
});
}
/**
* Checks if monitoring is currently paused.
*
* @return true if monitoring is paused
*/
public boolean isMonitoringPaused() {
synchronized (monitoringLock) {
return monitoringService.isPaused();
}
}
}
@@ -0,0 +1,81 @@
package com.adityachandel.booklore.service.monitoring;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.nio.file.Files;
import java.nio.file.Path;
@Slf4j
@Service
@AllArgsConstructor
public class MonitoringRegistrationService {
private final MonitoringService monitoringService;
/**
* Checks if a specific path is currently being monitored.
*
* @param path the path to check
* @return true if the path is monitored
*/
public boolean isPathMonitored(Path path) {
return monitoringService.isPathMonitored(path);
}
/**
* Unregisters a specific path from monitoring without affecting other paths.
* This is more efficient than pausing all monitoring for single path operations.
*
* @param path the path to unregister
*/
public void unregisterSpecificPath(Path path) {
monitoringService.unregisterPath(path);
}
/**
* Registers a specific path for monitoring.
*
* @param path the path to register
* @param libraryId the library ID associated with this path
*/
public void registerSpecificPath(Path path, Long libraryId) {
monitoringService.registerPath(path, libraryId);
}
/**
* Unregisters an entire library from monitoring.
* This is more efficient for batch operations than unregistering individual paths.
*
* @param libraryId the library ID to unregister
*/
public void unregisterLibrary(Long libraryId) {
monitoringService.unregisterLibrary(libraryId);
}
/**
* Re-registers an entire library for monitoring after batch operations.
* Since MonitoringService.registerLibrary() requires a Library object,
* this method will register individual paths under the library instead.
*
* @param libraryId the library ID to register
* @param libraryRoot the root path of the library
*/
public void registerLibraryPaths(Long libraryId, Path libraryRoot) {
if (!Files.exists(libraryRoot) || !Files.isDirectory(libraryRoot)) {
return;
}
try {
monitoringService.registerPath(libraryRoot, libraryId);
try (var stream = Files.walk(libraryRoot)) {
stream.filter(Files::isDirectory)
.filter(path -> !path.equals(libraryRoot))
.forEach(path -> monitoringService.registerPath(path, libraryId));
}
} catch (Exception e) {
log.error("Failed to register library paths for libraryId {} at {}", libraryId, libraryRoot, e);
}
}
}
@@ -29,14 +29,11 @@ public class MonitoringService {
private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
private final Set<Path> monitoredPaths = ConcurrentHashMap.newKeySet();
private final Map<Path, WatchKey> registeredWatchKeys = new ConcurrentHashMap<>();
private final Map<Path, Long> pathToLibraryIdMap = new ConcurrentHashMap<>();
private final Map<Long, Boolean> libraryWatchStatusMap = new ConcurrentHashMap<>();
private final Map<Path, WatchKey> registeredWatchKeys = new ConcurrentHashMap<>();
private final Map<Long, List<Path>> libraryIdToPaths = new ConcurrentHashMap<>();
private int pauseCount = 0;
private final Object pauseLock = new Object();
public MonitoringService(LibraryFileEventProcessor libraryFileEventProcessor, WatchService watchService, MonitoringTask monitoringTask) {
this.libraryFileEventProcessor = libraryFileEventProcessor;
this.watchService = watchService;
@@ -60,60 +57,6 @@ public class MonitoringService {
}
}
public synchronized void pauseMonitoring() {
pauseCount++;
if (pauseCount == 1) {
int count = 0;
for (Path path : new HashSet<>(monitoredPaths)) {
unregisterPath(path, false);
count++;
}
log.info("Monitoring paused ({} paths unregistered, pauseCount={})", count, pauseCount);
} else {
log.info("Monitoring pause requested (pauseCount={})", pauseCount);
}
}
public synchronized void resumeMonitoring() {
if (pauseCount == 0) {
log.warn("resumeMonitoring() called but monitoring is not paused");
return;
}
pauseCount--;
if (pauseCount == 0) {
libraryIdToPaths.forEach((libraryId, rootPaths) -> {
for (Path rootPath : rootPaths) {
if (Files.exists(rootPath)) {
try (Stream<Path> stream = Files.walk(rootPath)) {
stream.filter(Files::isDirectory).forEach(path -> {
if (Files.exists(path)) {
registerPath(path, libraryId);
}
});
} catch (IOException e) {
log.warn("Failed to walk path during resume: {}", rootPath, e);
}
} else {
log.debug("Skipping registration of non-existent path during resume: {}", rootPath);
}
}
});
synchronized (pauseLock) {
pauseLock.notifyAll();
}
log.info("Monitoring resumed");
} else {
log.info("Monitoring resume requested (pauseCount={}), monitoring still paused", pauseCount);
}
}
public synchronized boolean isPaused() {
return pauseCount > 0;
}
public void registerLibraries(List<Library> libraries) {
libraries.forEach(lib -> libraryWatchStatusMap.put(lib.getId(), lib.isWatch()));
libraries.stream().filter(Library::isWatch).forEach(this::registerLibrary);
@@ -159,19 +102,7 @@ public class MonitoringService {
libraryWatchStatusMap.put(libraryId, false);
libraryIdToPaths.remove(libraryId);
log.info("Unregistered library {} from monitoring", libraryId);
}
public void unregisterLibraries(Set<Long> libraryIds) {
libraryIds.forEach(this::unregisterLibrary);
}
public boolean isLibraryWatched(Long libraryId) {
return libraryWatchStatusMap.getOrDefault(libraryId, false);
}
public boolean isRelevantBookFile(Path path) {
return BookFileExtension.fromFileName(path.getFileName().toString()).isPresent();
log.debug("Unregistered library {} from monitoring", libraryId);
}
public synchronized boolean registerPath(Path path, Long libraryId) {
@@ -201,11 +132,21 @@ public class MonitoringService {
if (key != null) key.cancel();
pathToLibraryIdMap.remove(path);
if (logUnregister) {
log.info("Unregistered path: {}", path);
log.debug("Unregistered path: {}", path);
}
}
}
private void unregisterSubPaths(Path deletedPath) {
Set<Path> toRemove = monitoredPaths.stream()
.filter(p -> p.startsWith(deletedPath))
.collect(Collectors.toSet());
for (Path path : toRemove) {
unregisterPath(path);
}
}
@EventListener
public void handleFileChangeEvent(FileChangeEvent event) {
Path fullPath = event.getFilePath();
@@ -220,26 +161,8 @@ public class MonitoringService {
boolean isRelevantFile = isRelevantBookFile(fullPath);
if (!(isDir || isRelevantFile)) return;
if (isDir && kind == StandardWatchEventKinds.ENTRY_CREATE) {
Long parentLibraryId = pathToLibraryIdMap.get(event.getWatchedFolder());
if (parentLibraryId != null) {
try (Stream<Path> stream = Files.walk(fullPath)) {
stream.filter(Files::isDirectory).forEach(path -> registerPath(path, parentLibraryId));
} catch (IOException e) {
log.warn("Failed to register nested paths: {}", fullPath, e);
}
}
}
if (isDir && kind == StandardWatchEventKinds.ENTRY_DELETE) {
unregisterSubPaths(fullPath);
}
if (!eventQueue.offer(event)) {
log.warn("Event queue full, dropping: {}", fullPath);
} else {
log.debug("Queued: {} [{}]", fullPath, kind.name());
}
handleDirectoryEvents(event, fullPath, kind, isDir);
queueEvent(event, fullPath, kind);
}
@EventListener
@@ -258,15 +181,8 @@ public class MonitoringService {
singleThreadExecutor.submit(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
synchronized (pauseLock) {
while (isPaused()) {
pauseLock.wait();
}
}
FileChangeEvent event = eventQueue.take();
processFileChangeEvent(event);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
@@ -284,9 +200,7 @@ public class MonitoringService {
if (libraryId != null) {
try {
libraryFileEventProcessor.processFile(
event.getEventKind(), libraryId, watchedFolder.toString(), filePath.toString()
);
libraryFileEventProcessor.processFile(event.getEventKind(), libraryId, watchedFolder.toString(), filePath.toString());
} catch (InvalidDataAccessApiUsageException e) {
log.debug("InvalidDataAccessApiUsageException for libraryId={}", libraryId);
}
@@ -295,13 +209,36 @@ public class MonitoringService {
}
}
private void unregisterSubPaths(Path deletedPath) {
Set<Path> toRemove = monitoredPaths.stream()
.filter(p -> p.startsWith(deletedPath))
.collect(Collectors.toSet());
private void handleDirectoryEvents(FileChangeEvent event, Path fullPath, WatchEvent.Kind<?> kind, boolean isDir) {
if (isDir && kind == StandardWatchEventKinds.ENTRY_CREATE) {
Long parentLibraryId = pathToLibraryIdMap.get(event.getWatchedFolder());
if (parentLibraryId != null) {
try (Stream<Path> stream = Files.walk(fullPath)) {
stream.filter(Files::isDirectory).forEach(path -> registerPath(path, parentLibraryId));
} catch (IOException e) {
log.warn("Failed to register nested paths: {}", fullPath, e);
}
}
}
for (Path path : toRemove) {
unregisterPath(path);
if (isDir && kind == StandardWatchEventKinds.ENTRY_DELETE) {
unregisterSubPaths(fullPath);
}
}
}
private void queueEvent(FileChangeEvent event, Path fullPath, WatchEvent.Kind<?> kind) {
if (!eventQueue.offer(event)) {
log.warn("Event queue full, dropping: {}", fullPath);
} else {
log.debug("Queued: {} [{}]", fullPath, kind.name());
}
}
public boolean isRelevantBookFile(Path path) {
return BookFileExtension.fromFileName(path.getFileName().toString()).isPresent();
}
public boolean isPathMonitored(Path path) {
return monitoredPaths.contains(path.toAbsolutePath().normalize());
}
}
@@ -3,50 +3,36 @@ package com.adityachandel.booklore.service.upload;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.AdditionalFileMapper;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.AdditionalFile;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.FileProcessStatus;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.file.FileMovingHelper;
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.util.PathPatternResolver;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.GroupPrincipal;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
@RequiredArgsConstructor
@@ -54,202 +40,190 @@ import java.util.Optional;
@Slf4j
public class FileUploadService {
private static final String UPLOAD_TEMP_PREFIX = "upload-";
private static final String BOOKDROP_TEMP_PREFIX = "bookdrop-";
private static final long BYTES_TO_KB_DIVISOR = 1024L;
private static final long MB_TO_BYTES_MULTIPLIER = 1024L * 1024L;
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final BookAdditionalFileRepository additionalFileRepository;
private final BookFileProcessorRegistry processorRegistry;
private final NotificationService notificationService;
private final AppSettingService appSettingService;
private final AppProperties appProperties;
private final PdfMetadataExtractor pdfMetadataExtractor;
private final EpubMetadataExtractor epubMetadataExtractor;
private final AdditionalFileMapper additionalFileMapper;
private final MonitoringService monitoringService;
private final FileMovingHelper fileMovingHelper;
@Value("${PUID:${USER_ID:0}}")
private String userId;
@Value("${PGID:${GROUP_ID:0}}")
private String groupId;
public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException {
public void uploadFile(MultipartFile file, long libraryId, long pathId) {
validateFile(file);
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
LibraryPathEntity libraryPathEntity = libraryEntity.getLibraryPaths()
.stream()
.filter(p -> p.getId() == pathId)
.findFirst()
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
Path tempPath = Files.createTempFile("upload-", Objects.requireNonNull(file.getOriginalFilename()));
FileProcessResult result;
boolean wePaused = false;
if (!monitoringService.isPaused()) {
monitoringService.pauseMonitoring();
wePaused = true;
}
final LibraryEntity libraryEntity = findLibraryById(libraryId);
final LibraryPathEntity libraryPathEntity = findLibraryPathById(libraryEntity, pathId);
final String originalFileName = getValidatedFileName(file);
Path tempPath = null;
try {
tempPath = createTempFile(UPLOAD_TEMP_PREFIX, originalFileName);
file.transferTo(tempPath);
setTemporaryFileOwnership(tempPath);
BookFileExtension fileExt = BookFileExtension.fromFileName(file.getOriginalFilename()).orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"));
BookMetadata metadata = extractMetadata(fileExt, tempPath.toFile());
String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
if (uploadPattern.endsWith("/") || uploadPattern.endsWith("\\")) {
uploadPattern += "{currentFilename}";
}
String relativePath = PathPatternResolver.resolvePattern(metadata, uploadPattern, file.getOriginalFilename());
Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
File finalFile = finalPath.toFile();
final BookFileExtension fileExtension = getFileExtension(originalFileName);
final BookMetadata metadata = extractMetadata(fileExtension, tempPath.toFile());
final String uploadPattern = fileMovingHelper.getFileNamingPattern(libraryEntity);
if (finalFile.exists()) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
final String relativePath = PathPatternResolver.resolvePattern(metadata, uploadPattern, originalFileName);
final Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
Files.createDirectories(finalPath.getParent());
Files.move(tempPath, finalPath);
validateFinalPath(finalPath);
moveFileToFinalLocation(tempPath, finalPath);
log.info("File uploaded to final location: {}", finalPath);
result = processFile(finalFile.getName(), libraryEntity, libraryPathEntity, finalFile, fileExt.getType());
if (result != null && result.getStatus() != FileProcessStatus.DUPLICATE) {
notificationService.sendMessage(Topic.BOOK_ADD, result.getBook());
}
return result.getBook();
} catch (IOException e) {
log.error("Failed to upload file: {}", originalFileName, e);
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
} finally {
Files.deleteIfExists(tempPath);
if (wePaused) {
Thread.startVirtualThread(() -> {
try {
Thread.sleep(5_000);
monitoringService.resumeMonitoring();
log.info("Monitoring resumed after 5s delay");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while delaying resume of monitoring");
}
});
}
cleanupTempFile(tempPath);
}
}
@Transactional
public AdditionalFile uploadAdditionalFile(Long bookId, MultipartFile file, AdditionalFileType additionalFileType, String description) throws IOException {
Optional<BookEntity> bookOpt = bookRepository.findById(bookId);
if (bookOpt.isEmpty()) {
throw new IllegalArgumentException("Book not found with id: " + bookId);
}
BookEntity book = bookOpt.get();
String originalFileName = file.getOriginalFilename();
if (originalFileName == null) {
throw new IllegalArgumentException("File must have a name");
}
Path tempPath = Files.createTempFile("upload-", Objects.requireNonNull(file.getOriginalFilename()));
boolean wePaused = false;
if (!monitoringService.isPaused()) {
monitoringService.pauseMonitoring();
wePaused = true;
}
final BookEntity book = findBookById(bookId);
final String originalFileName = getValidatedFileName(file);
Path tempPath = null;
try {
tempPath = createTempFile(UPLOAD_TEMP_PREFIX, originalFileName);
file.transferTo(tempPath);
setTemporaryFileOwnership(tempPath);
final String fileHash = FileFingerprint.generateHash(tempPath);
validateAlternativeFormatDuplicate(additionalFileType, fileHash);
// Check for duplicates by hash, but only for alternative formats
String fileHash = FileFingerprint.generateHash(tempPath);
if (additionalFileType == AdditionalFileType.ALTERNATIVE_FORMAT) {
Optional<BookAdditionalFileEntity> existingAltFormat = additionalFileRepository.findByAltFormatCurrentHash(fileHash);
if (existingAltFormat.isPresent()) {
throw new IllegalArgumentException("Alternative format file already exists with same content");
}
}
// Store file in same directory as the book
Path finalPath = Paths.get(book.getLibraryPath().getPath(), book.getFileSubPath(), originalFileName);
File finalFile = finalPath.toFile();
if (finalFile.exists()) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
Files.createDirectories(finalPath.getParent());
Files.move(tempPath, finalPath);
final Path finalPath = buildAdditionalFilePath(book, originalFileName);
validateFinalPath(finalPath);
moveFileToFinalLocation(tempPath, finalPath);
log.info("Additional file uploaded to final location: {}", finalPath);
// Create entity
BookAdditionalFileEntity entity = BookAdditionalFileEntity.builder()
.book(book)
.fileName(originalFileName)
.fileSubPath(book.getFileSubPath())
.additionalFileType(additionalFileType)
.fileSizeKb(file.getSize() / 1024)
.initialHash(fileHash)
.currentHash(fileHash)
.description(description)
.addedOn(Instant.now())
.build();
final BookAdditionalFileEntity entity = createAdditionalFileEntity(book, originalFileName, additionalFileType, file.getSize(), fileHash, description);
final BookAdditionalFileEntity savedEntity = additionalFileRepository.save(entity);
entity = additionalFileRepository.save(entity);
return additionalFileMapper.toAdditionalFile(savedEntity);
return additionalFileMapper.toAdditionalFile(entity);
} catch (IOException e) {
log.error("Failed to upload additional file for book {}: {}", bookId, originalFileName, e);
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
} finally {
Files.deleteIfExists(tempPath);
if (wePaused) {
Thread.startVirtualThread(() -> {
try {
Thread.sleep(5_000);
monitoringService.resumeMonitoring();
log.info("Monitoring resumed after 5s delay");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while delaying resume of monitoring");
}
});
}
cleanupTempFile(tempPath);
}
}
public Book uploadFileBookDrop(MultipartFile file) throws IOException {
validateFile(file);
Path dropFolder = Paths.get(appProperties.getBookdropFolder());
final Path dropFolder = Paths.get(appProperties.getBookdropFolder());
Files.createDirectories(dropFolder);
String originalFilename = Objects.requireNonNull(file.getOriginalFilename());
Path tempPath = Files.createTempFile("bookdrop-", originalFilename);
final String originalFilename = getValidatedFileName(file);
Path tempPath = null;
try {
tempPath = createTempFile(BOOKDROP_TEMP_PREFIX, originalFilename);
file.transferTo(tempPath);
setTemporaryFileOwnership(tempPath);
Path finalPath = dropFolder.resolve(originalFilename);
if (Files.exists(finalPath)) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
final Path finalPath = dropFolder.resolve(originalFilename);
validateFinalPath(finalPath);
Files.move(tempPath, finalPath);
log.info("File moved to book-drop folder: {}", finalPath);
return null;
} finally {
Files.deleteIfExists(tempPath);
cleanupTempFile(tempPath);
}
}
private LibraryEntity findLibraryById(long libraryId) {
return libraryRepository.findById(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
}
private LibraryPathEntity findLibraryPathById(LibraryEntity libraryEntity, long pathId) {
return libraryEntity.getLibraryPaths()
.stream()
.filter(p -> p.getId() == pathId)
.findFirst()
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryEntity.getId()));
}
private BookEntity findBookById(Long bookId) {
return bookRepository.findById(bookId)
.orElseThrow(() -> new IllegalArgumentException("Book not found with id: " + bookId));
}
private String getValidatedFileName(MultipartFile file) {
final String originalFileName = file.getOriginalFilename();
if (originalFileName == null) {
throw new IllegalArgumentException("File must have a name");
}
return originalFileName;
}
private BookFileExtension getFileExtension(String fileName) {
return BookFileExtension.fromFileName(fileName)
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"));
}
private Path createTempFile(String prefix, String fileName) throws IOException {
return Files.createTempFile(prefix, fileName);
}
private void validateFinalPath(Path finalPath) {
if (Files.exists(finalPath)) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
}
private void moveFileToFinalLocation(Path sourcePath, Path targetPath) throws IOException {
Files.createDirectories(targetPath.getParent());
Files.move(sourcePath, targetPath);
}
private void validateAlternativeFormatDuplicate(AdditionalFileType additionalFileType, String fileHash) {
if (additionalFileType == AdditionalFileType.ALTERNATIVE_FORMAT) {
final Optional<BookAdditionalFileEntity> existingAltFormat = additionalFileRepository.findByAltFormatCurrentHash(fileHash);
if (existingAltFormat.isPresent()) {
throw new IllegalArgumentException("Alternative format file already exists with same content");
}
}
}
private Path buildAdditionalFilePath(BookEntity book, String fileName) {
return Paths.get(book.getLibraryPath().getPath(), book.getFileSubPath(), fileName);
}
private BookAdditionalFileEntity createAdditionalFileEntity(BookEntity book, String fileName, AdditionalFileType additionalFileType, long fileSize, String fileHash, String description) {
return BookAdditionalFileEntity.builder()
.book(book)
.fileName(fileName)
.fileSubPath(book.getFileSubPath())
.additionalFileType(additionalFileType)
.fileSizeKb(fileSize / BYTES_TO_KB_DIVISOR)
.initialHash(fileHash)
.currentHash(fileHash)
.description(description)
.addedOn(Instant.now())
.build();
}
private void cleanupTempFile(Path tempPath) {
if (tempPath != null) {
try {
Files.deleteIfExists(tempPath);
} catch (IOException e) {
log.warn("Failed to cleanup temp file: {}", tempPath, e);
}
}
}
@@ -262,41 +236,14 @@ public class FileUploadService {
}
private void validateFile(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
final String originalFilename = file.getOriginalFilename();
if (originalFilename == null || BookFileExtension.fromFileName(originalFilename).isEmpty()) {
throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension");
}
int maxSizeMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
if (file.getSize() > maxSizeMb * 1024L * 1024L) {
final int maxSizeMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
if (file.getSize() > maxSizeMb * MB_TO_BYTES_MULTIPLIER) {
throw ApiError.FILE_TOO_LARGE.createException(maxSizeMb);
}
}
private void setTemporaryFileOwnership(Path tempPath) throws IOException {
UserPrincipalLookupService lookupService = FileSystems.getDefault()
.getUserPrincipalLookupService();
if (!userId.equals("0")) {
UserPrincipal user = lookupService.lookupPrincipalByName(userId);
Files.getFileAttributeView(tempPath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setOwner(user);
}
if (!groupId.equals("0")) {
GroupPrincipal group = lookupService.lookupPrincipalByGroupName(groupId);
Files.getFileAttributeView(tempPath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setGroup(group);
}
}
private FileProcessResult processFile(String fileName, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile, BookFileType type) {
String subPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), storageFile.toPath());
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileSubPath(subPath)
.bookFileType(type)
.fileName(fileName)
.build();
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type);
return processor.processFile(libraryFile);
}
}
@@ -208,11 +208,22 @@ public class FileService {
if (!folder.exists() && !folder.mkdirs()) {
throw new IOException("Failed to create directory: " + folder.getAbsolutePath());
}
BufferedImage rgbImage = new BufferedImage(
coverImage.getWidth(),
coverImage.getHeight(),
BufferedImage.TYPE_INT_RGB
);
Graphics2D g = rgbImage.createGraphics();
g.drawImage(coverImage, 0, 0, Color.WHITE, null);
g.dispose();
File originalFile = new File(folder, COVER_FILENAME);
boolean originalSaved = ImageIO.write(coverImage, IMAGE_FORMAT, originalFile);
BufferedImage thumb = resizeImage(coverImage, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
boolean originalSaved = ImageIO.write(rgbImage, IMAGE_FORMAT, originalFile);
BufferedImage thumb = resizeImage(rgbImage, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
File thumbnailFile = new File(folder, THUMBNAIL_FILENAME);
boolean thumbnailSaved = ImageIO.write(thumb, IMAGE_FORMAT, thumbnailFile);
return originalSaved && thumbnailSaved;
}
@@ -336,6 +347,27 @@ public class FileService {
log.warn("Skipping file due to missing hash: {}", libraryFile.getFullPath());
return Optional.empty();
}
// First check for soft-deleted books with the same hash
Optional<BookEntity> softDeletedBook = bookRepository.findByCurrentHashAndDeletedTrue(hash);
if (softDeletedBook.isPresent()) {
BookEntity book = softDeletedBook.get();
log.info("Found soft-deleted book with same hash, undeleting: bookId={} file='{}'",
book.getId(), libraryFile.getFileName());
// Undelete the book
book.setDeleted(false);
book.setDeletedAt(null);
// Update file information
book.setFileName(libraryFile.getFileName());
book.setFileSubPath(libraryFile.getFileSubPath());
book.setLibraryPath(libraryFile.getLibraryPathEntity());
book.setLibrary(libraryFile.getLibraryEntity());
return Optional.of(bookMapper.toBook(book));
}
Optional<BookEntity> existingByHash = bookRepository.findByCurrentHash(hash);
if (existingByHash.isPresent()) {
BookEntity book = existingByHash.get();
@@ -7,7 +7,7 @@ import com.adityachandel.booklore.service.BookDownloadService;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.BookService;
import com.adityachandel.booklore.service.UserProgressService;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.util.FileService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -49,7 +49,7 @@ class BookServiceDeleteTests {
BookQueryService bookQueryService = Mockito.mock(BookQueryService.class);
UserProgressService userProgressService = Mockito.mock(UserProgressService.class);
BookDownloadService bookDownloadService = Mockito.mock(BookDownloadService.class);
MonitoringProtectionService monitoringProtectionService = Mockito.mock(MonitoringProtectionService.class);
MonitoringRegistrationService monitoringRegistrationService = Mockito.mock(MonitoringRegistrationService.class);
bookService = new BookService(
bookRepository,
@@ -66,7 +66,7 @@ class BookServiceDeleteTests {
bookQueryService,
userProgressService,
bookDownloadService,
monitoringProtectionService
monitoringRegistrationService
);
}
@@ -1,792 +0,0 @@
package com.adityachandel.booklore;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.file.FileMoveService;
import com.adityachandel.booklore.service.library.LibraryService;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class FileMoveServiceMoveFilesTest {
@Mock
private BookQueryService bookQueryService;
@Mock
private BookRepository bookRepository;
@Mock
private BookAdditionalFileRepository bookAdditionalFileRepository;
@Mock
private BookMapper bookMapper;
@Mock
private NotificationService notificationService;
@Mock
private MonitoringProtectionService monitoringProtectionService;
@Mock
private AppSettingService appSettingService;
@Mock
private LibraryService libraryService;
@InjectMocks
private FileMoveService fileMoveService;
@TempDir
Path tempLibraryRoot;
@BeforeEach
void setUp() {
// Configure the mock to actually execute the Runnable for all tests
doAnswer(invocation -> {
Runnable runnable = invocation.getArgument(0);
runnable.run();
return null;
}).when(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("file move operations"));
}
private BookEntity createBookWithFile(Path libraryRoot, String fileSubPath, String fileName) throws IOException {
LibraryEntity library = LibraryEntity.builder()
.id(42L)
.name("Test Library")
.fileNamingPattern(null)
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(libraryRoot.toString())
.library(library)
.build();
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Test Book")
.authors(new HashSet<>(List.of(new AuthorEntity(1L, "Author Name", new ArrayList<>())))
)
.publishedDate(LocalDate.of(2020, 1, 1))
.build();
BookEntity book = BookEntity.builder()
.id(1L)
.fileName(fileName)
.fileSubPath(fileSubPath)
.metadata(metadata)
.libraryPath(libraryPathEntity)
.build();
Path oldFilePath = book.getFullFilePath();
Files.createDirectories(oldFilePath.getParent());
Files.createFile(oldFilePath);
return book;
}
private BookAdditionalFileEntity createAdditionalFile(BookEntity book, Long id, String fileName,
String fileSubPath, AdditionalFileType type,
boolean createActualFile) throws IOException {
BookAdditionalFileEntity additionalFile = BookAdditionalFileEntity.builder()
.id(id)
.book(book)
.fileName(fileName)
.fileSubPath(fileSubPath)
.additionalFileType(type)
.build();
if (createActualFile) {
Path filePath = Paths.get(book.getLibraryPath().getPath())
.resolve(fileSubPath)
.resolve(fileName);
Files.createDirectories(filePath.getParent());
Files.createFile(filePath);
}
return additionalFile;
}
@Test
void testMoveFiles_skipsNonexistentFile() {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("NoFile")
.build();
LibraryEntity library = LibraryEntity.builder()
.id(43L)
.name("Test Library")
.fileNamingPattern("Moved/{title}")
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString())
.library(library)
.build();
BookEntity book = BookEntity.builder()
.id(2L)
.fileName("nofile.epub")
.fileSubPath("subfolder")
.metadata(metadata)
.libraryPath(libraryPathEntity)
.build();
when(bookQueryService.findAllWithMetadataByIds(Set.of(2L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(2L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("NoFile.epub");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("No file should be created for nonexistent source")
.isFalse();
}
@Test
void testMoveFiles_skipsBookWithoutLibraryPath() throws IOException {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("MissingLibrary")
.build();
BookEntity book = BookEntity.builder()
.id(3L)
.fileName("missinglibrary.epub")
.fileSubPath("subfolder")
.metadata(metadata)
.libraryPath(null)
.build();
Path fakeOldFile = tempLibraryRoot.resolve("subfolder").resolve("missinglibrary.epub");
Files.createDirectories(fakeOldFile.getParent());
Files.createFile(fakeOldFile);
when(bookQueryService.findAllWithMetadataByIds(Set.of(3L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(3L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("MissingLibrary.epub");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("File should not be moved if library path is missing")
.isFalse();
assertThat(Files.exists(fakeOldFile))
.withFailMessage("Original file should remain when library path is missing")
.isTrue();
Files.deleteIfExists(fakeOldFile);
}
@Test
void testMoveFiles_skipsBookWithNullFileName() throws IOException {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("NullFileName")
.build();
LibraryEntity library = LibraryEntity.builder()
.id(46L)
.name("Test Library")
.fileNamingPattern("Moved/{title}")
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString())
.library(library)
.build();
BookEntity book = BookEntity.builder()
.id(10L)
.fileName(null)
.fileSubPath("folder")
.metadata(metadata)
.libraryPath(libraryPathEntity)
.build();
when(bookQueryService.findAllWithMetadataByIds(Set.of(10L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(10L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("NullFileName");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("File should not be moved if filename is null")
.isFalse();
}
@Test
void testMoveFiles_skipsBookWithEmptyFileName() throws IOException {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("EmptyFileName")
.build();
LibraryEntity library = LibraryEntity.builder()
.id(47L)
.name("Test Library")
.fileNamingPattern("Moved/{title}")
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString())
.library(library)
.build();
BookEntity book = BookEntity.builder()
.id(11L)
.fileName("")
.fileSubPath("folder")
.metadata(metadata)
.libraryPath(libraryPathEntity)
.build();
when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(11L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("EmptyFileName");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("File should not be moved if filename is empty")
.isFalse();
}
@Test
void testMoveFiles_skipsBookWithNullFileSubPath() throws IOException {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("NullSubPath")
.build();
LibraryEntity library = LibraryEntity.builder()
.id(48L)
.name("Test Library")
.fileNamingPattern("Moved/{title}")
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString())
.library(library)
.build();
BookEntity book = BookEntity.builder()
.id(12L)
.fileName("file.epub")
.fileSubPath(null)
.metadata(metadata)
.libraryPath(libraryPathEntity)
.build();
Path oldFile = tempLibraryRoot.resolve("file.epub");
Files.createFile(oldFile);
when(bookQueryService.findAllWithMetadataByIds(Set.of(12L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(12L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("NullSubPath.epub");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("File should not be moved if fileSubPath is null")
.isFalse();
Files.deleteIfExists(oldFile);
}
@Test
void testMoveFiles_skipsBookWithNullMetadata() throws IOException {
LibraryEntity library = LibraryEntity.builder()
.id(49L)
.name("Test Library")
.fileNamingPattern("Moved/{title}")
.build();
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString())
.library(library)
.build();
BookEntity book = BookEntity.builder()
.id(13L)
.fileName("file.epub")
.fileSubPath("folder")
.metadata(null)
.libraryPath(libraryPathEntity)
.build();
Path oldFile = tempLibraryRoot.resolve("folder").resolve("file.epub");
Files.createDirectories(oldFile.getParent());
Files.createFile(oldFile);
when(bookQueryService.findAllWithMetadataByIds(Set.of(13L))).thenReturn(List.of(book));
AppSettings appSettings = new AppSettings();
appSettings.setUploadPattern("Moved/{title}");
when(appSettingService.getAppSettings()).thenReturn(appSettings);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(Set.of(13L));
fileMoveService.moveFiles(request);
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve(".epub");
assertThat(Files.exists(expectedNewPath))
.withFailMessage("File should not be moved if metadata is null")
.isFalse();
Files.deleteIfExists(oldFile);
}
@Test
void testMoveFiles_successfulMove() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
Path oldFilePath = book.getFullFilePath();
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
Path newPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub");
assertThat(Files.exists(newPath)).isTrue();
assertThat(Files.exists(oldFilePath)).isFalse();
verify(bookRepository).save(book);
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), anyList());
// Verify monitoring protection was applied correctly
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("file move operations"));
// Note: Library rescan now happens asynchronously with 8-second delay
// We can't verify it immediately in the test, but the operation is scheduled
}
@Test
void testMoveFiles_usesDefaultPatternWhenLibraryPatternEmpty() throws IOException {
LibraryEntity lib = LibraryEntity.builder()
.id(99L).name("Lib").fileNamingPattern(" ").build();
LibraryPathEntity lp = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString()).library(lib).build();
BookMetadataEntity meta = BookMetadataEntity.builder()
.title("DFT").build();
BookEntity book = BookEntity.builder()
.id(55L).fileSubPath("old").fileName("a.epub")
.libraryPath(lp).metadata(meta).build();
Path old = book.getFullFilePath();
Files.createDirectories(old.getParent());
Files.createFile(old);
when(bookQueryService.findAllWithMetadataByIds(Set.of(55L))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("DEF/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(55L));
fileMoveService.moveFiles(req);
Path moved = tempLibraryRoot.resolve("DEF").resolve("DFT.epub");
assertThat(Files.exists(moved)).isTrue();
verify(bookRepository).save(book);
}
@Test
void testMoveFiles_deletesEmptyParentDirectories() throws IOException {
LibraryEntity library = LibraryEntity.builder()
.id(100L).name("Lib").fileNamingPattern(null).build();
LibraryPathEntity lp = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString()).library(library).build();
BookMetadataEntity meta = BookMetadataEntity.builder()
.title("Nested").build();
BookEntity book = BookEntity.builder()
.id(101L).fileSubPath("a/b/c").fileName("nested.epub")
.libraryPath(lp).metadata(meta).build();
Path old = book.getFullFilePath();
Files.createDirectories(old.getParent());
Files.createFile(old);
when(bookQueryService.findAllWithMetadataByIds(Set.of(101L))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("Z/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build());
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(101L));
fileMoveService.moveFiles(req);
Path newPath = tempLibraryRoot.resolve("Z").resolve("Nested.epub");
assertThat(Files.exists(newPath)).isTrue();
assertThat(Files.notExists(tempLibraryRoot.resolve("a"))).isTrue();
}
@Test
void testMoveFiles_overwritesExistingDestination() throws IOException {
LibraryEntity library = LibraryEntity.builder()
.id(102L).name("Lib").fileNamingPattern(null).build();
LibraryPathEntity lp = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString()).library(library).build();
BookMetadataEntity meta = BookMetadataEntity.builder()
.title("Overwrite").build();
BookEntity book = BookEntity.builder()
.id(103L).fileSubPath("sub").fileName("file.epub")
.libraryPath(lp).metadata(meta).build();
Path old = book.getFullFilePath();
Files.createDirectories(old.getParent());
Files.write(old, "SRC".getBytes());
Path destDir = tempLibraryRoot.resolve("DEST");
Files.createDirectories(destDir);
Path dest = destDir.resolve("Overwrite.epub");
Files.write(dest, "OLD".getBytes());
when(bookQueryService.findAllWithMetadataByIds(Set.of(103L))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("DEST/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build());
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(103L));
fileMoveService.moveFiles(req);
assertThat(Files.exists(dest)).isTrue();
String content = Files.readString(dest);
assertThat(content).isEqualTo("SRC");
}
@Test
void testMoveFiles_usesLibraryPatternWhenSet() throws IOException {
LibraryEntity library = LibraryEntity.builder()
.id(104L).name("Lib").fileNamingPattern("LIBY/{title}").build();
LibraryPathEntity lp = LibraryPathEntity.builder()
.path(tempLibraryRoot.toString()).library(library).build();
BookMetadataEntity meta = BookMetadataEntity.builder()
.title("LibTest").build();
BookEntity book = BookEntity.builder()
.id(105L).fileSubPath("x").fileName("file.epub")
.libraryPath(lp).metadata(meta).build();
Path old = book.getFullFilePath();
Files.createDirectories(old.getParent());
Files.createFile(old);
when(bookQueryService.findAllWithMetadataByIds(Set.of(105L))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("DEFAULT/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build());
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(105L));
fileMoveService.moveFiles(req);
Path newPath = tempLibraryRoot.resolve("LIBY").resolve("LibTest.epub");
assertThat(Files.exists(newPath)).isTrue();
}
@Test
void testMoveFiles_skipsWhenDestinationSameAsSource() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
Path oldFilePath = book.getFullFilePath();
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId())))
.thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("sub/mybook.epub");
when(appSettingService.getAppSettings()).thenReturn(settings);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
assertThat(Files.exists(oldFilePath)).isTrue();
verify(bookRepository, never()).save(any());
verify(notificationService, never()).sendMessage(any(), anyList());
verify(libraryService, never()).rescanLibrary(anyLong());
}
@Test
void testMoveFiles_executesWithMonitoringProtection() {
when(bookQueryService.findAllWithMetadataByIds(anySet())).thenReturn(List.of());
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(999L));
fileMoveService.moveFiles(req);
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("file move operations"));
}
@Test
void testMoveFiles_movesAdditionalFiles() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
// Create additional files
BookAdditionalFileEntity additionalFile1 = createAdditionalFile(book, 1L, "mybook.pdf", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
BookAdditionalFileEntity additionalFile2 = createAdditionalFile(book, 2L, "mybook_notes.txt", "sub",
AdditionalFileType.SUPPLEMENTARY, true);
List<BookAdditionalFileEntity> additionalFiles = List.of(additionalFile1, additionalFile2);
book.setAdditionalFiles(additionalFiles);
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify main book moved
Path newBookPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub");
assertThat(Files.exists(newBookPath)).isTrue();
// Verify additional files moved
Path newAdditionalPath1 = tempLibraryRoot.resolve("X").resolve("Test Book.pdf");
Path newAdditionalPath2 = tempLibraryRoot.resolve("X").resolve("Test Book.txt");
assertThat(Files.exists(newAdditionalPath1)).isTrue();
assertThat(Files.exists(newAdditionalPath2)).isTrue();
// Verify database updated
verify(bookAdditionalFileRepository, times(2)).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_handlesUniqueNamesForAdditionalFiles() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
// Create additional files that will result in same name after pattern resolution
BookAdditionalFileEntity additionalFile1 = createAdditionalFile(book, 1L, "version1.pdf", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
BookAdditionalFileEntity additionalFile2 = createAdditionalFile(book, 2L, "version2.pdf", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
List<BookAdditionalFileEntity> additionalFiles = List.of(additionalFile1, additionalFile2);
book.setAdditionalFiles(additionalFiles);
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify files moved with unique names
Path newAdditionalPath1 = tempLibraryRoot.resolve("X").resolve("Test Book.pdf");
Path newAdditionalPath2 = tempLibraryRoot.resolve("X").resolve("Test Book_2.pdf");
assertThat(Files.exists(newAdditionalPath1)).isTrue();
assertThat(Files.exists(newAdditionalPath2)).isTrue();
verify(bookAdditionalFileRepository, times(2)).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_skipsNonexistentAdditionalFiles() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
// Create additional file entity without actual file
BookAdditionalFileEntity additionalFile = createAdditionalFile(book, 1L, "nonexistent.pdf", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, false);
book.setAdditionalFiles(List.of(additionalFile));
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify main book moved
Path newBookPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub");
assertThat(Files.exists(newBookPath)).isTrue();
// Verify nonexistent additional file not saved
verify(bookAdditionalFileRepository, never()).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_handlesEmptyAdditionalFilesList() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
book.setAdditionalFiles(new ArrayList<>());
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify main book moved
Path newBookPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub");
assertThat(Files.exists(newBookPath)).isTrue();
// Verify no additional file operations
verify(bookAdditionalFileRepository, never()).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_handlesNullAdditionalFilesList() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
book.setAdditionalFiles(null);
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify main book moved
Path newBookPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub");
assertThat(Files.exists(newBookPath)).isTrue();
// Verify no additional file operations
verify(bookAdditionalFileRepository, never()).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_additionalFileWithDifferentExtensions() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
// Create additional files with different extensions
BookAdditionalFileEntity additionalFile1 = createAdditionalFile(book, 1L, "mybook.pdf", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
BookAdditionalFileEntity additionalFile2 = createAdditionalFile(book, 2L, "mybook.mobi", "sub",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
BookAdditionalFileEntity additionalFile3 = createAdditionalFile(book, 3L, "cover.jpg", "sub",
AdditionalFileType.SUPPLEMENTARY, true);
List<BookAdditionalFileEntity> additionalFiles = List.of(additionalFile1, additionalFile2, additionalFile3);
book.setAdditionalFiles(additionalFiles);
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("Library/{authors}/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
Book dto = Book.builder().id(book.getId()).build();
when(bookMapper.toBook(book)).thenReturn(dto);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify all files moved with correct extensions
Path basePath = tempLibraryRoot.resolve("Library").resolve("Author Name");
assertThat(Files.exists(basePath.resolve("Test Book.epub"))).isTrue();
assertThat(Files.exists(basePath.resolve("Test Book.pdf"))).isTrue();
assertThat(Files.exists(basePath.resolve("Test Book.mobi"))).isTrue();
assertThat(Files.exists(basePath.resolve("Test Book.jpg"))).isTrue();
verify(bookAdditionalFileRepository, times(3)).save(any(BookAdditionalFileEntity.class));
}
@Test
void testMoveFiles_skipsSamePathAdditionalFiles() throws IOException {
BookEntity book = createBookWithFile(tempLibraryRoot, "X", "Test Book.epub");
// Create additional file that will resolve to same path
BookAdditionalFileEntity additionalFile = createAdditionalFile(book, 1L, "Test Book.pdf", "X",
AdditionalFileType.ALTERNATIVE_FORMAT, true);
book.setAdditionalFiles(List.of(additionalFile));
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
AppSettings settings = new AppSettings();
settings.setUploadPattern("X/{title}");
when(appSettingService.getAppSettings()).thenReturn(settings);
FileMoveRequest req = new FileMoveRequest();
req.setBookIds(Set.of(book.getId()));
fileMoveService.moveFiles(req);
// Verify files still exist at original location
Path additionalFilePath = tempLibraryRoot.resolve("X").resolve("Test Book.pdf");
assertThat(Files.exists(additionalFilePath)).isTrue();
// Verify no save called for additional file (skipped)
verify(bookAdditionalFileRepository, never()).save(any(BookAdditionalFileEntity.class));
}
}
@@ -90,7 +90,7 @@ class FileMoveServiceTest {
.isIn(
"/Good Omens - Neil Gaiman, Terry Pratchett (1990).mobi",
"/Good Omens - Terry Pratchett, Neil Gaiman (1990).mobi"
); // Set order is non-deterministic
);
}
@Test
@@ -162,7 +162,7 @@ class FileMoveServiceTest {
BookEntity book = BookEntity.builder()
.metadata(metadata)
.fileName("") // explicitly empty
.fileName("")
.build();
String result = fileMoveService.generatePathFromPattern(book, "/{title}");
@@ -1,29 +1,36 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.mapper.AdditionalFileMapper;
import com.adityachandel.booklore.model.dto.AdditionalFile;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@@ -36,7 +43,7 @@ class AdditionalFileServiceTest {
private AdditionalFileMapper additionalFileMapper;
@Mock
private MonitoringProtectionService monitoringProtectionService;
private MonitoringRegistrationService monitoringRegistrationService;
@InjectMocks
private AdditionalFileService additionalFileService;
@@ -44,146 +51,243 @@ class AdditionalFileServiceTest {
@TempDir
Path tempDir;
@BeforeEach
void setUp() {
// Configure mock to execute the Runnable for file operations (lenient for tests that don't use it)
lenient().doAnswer(invocation -> {
Runnable runnable = invocation.getArgument(0);
runnable.run();
return null;
}).when(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
}
private BookAdditionalFileEntity fileEntity;
private AdditionalFile additionalFile;
private BookEntity bookEntity;
private LibraryPathEntity libraryPathEntity;
@Test
void deleteAdditionalFile_success() throws IOException {
// Arrange
@BeforeEach
void setUp() throws IOException {
Path testFile = tempDir.resolve("test-file.pdf");
Files.createFile(testFile);
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
libraryPathEntity = new LibraryPathEntity();
libraryPathEntity.setId(1L);
libraryPathEntity.setPath(tempDir.toString());
BookEntity book = new BookEntity();
book.setLibraryPath(libraryPath);
bookEntity = new BookEntity();
bookEntity.setId(100L);
bookEntity.setLibraryPath(libraryPathEntity);
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
.id(1L)
.fileName("test-file.pdf")
.fileSubPath("")
.additionalFileType(AdditionalFileType.ALTERNATIVE_FORMAT)
.book(book)
.build();
fileEntity = new BookAdditionalFileEntity();
fileEntity.setId(1L);
fileEntity.setBook(bookEntity);
fileEntity.setFileName("test-file.pdf");
fileEntity.setFileSubPath(".");
fileEntity.setAdditionalFileType(AdditionalFileType.ALTERNATIVE_FORMAT);
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
// Act
additionalFileService.deleteAdditionalFile(1L);
// Assert
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
verify(additionalFileRepository).delete(fileEntity);
assertThat(Files.exists(testFile)).isFalse();
additionalFile = mock(AdditionalFile.class);
}
@Test
void deleteAdditionalFile_fileNotFound() {
// Arrange
when(additionalFileRepository.findById(1L)).thenReturn(Optional.empty());
void getAdditionalFilesByBookId_WhenFilesExist_ShouldReturnMappedFiles() {
Long bookId = 100L;
List<BookAdditionalFileEntity> entities = List.of(fileEntity);
List<AdditionalFile> expectedFiles = List.of(additionalFile);
// Act & Assert
assertThatThrownBy(() -> additionalFileService.deleteAdditionalFile(1L))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Additional file not found with id: 1");
when(additionalFileRepository.findByBookId(bookId)).thenReturn(entities);
when(additionalFileMapper.toAdditionalFiles(entities)).thenReturn(expectedFiles);
verify(monitoringProtectionService, never()).executeWithProtection(any(Runnable.class), any());
List<AdditionalFile> result = additionalFileService.getAdditionalFilesByBookId(bookId);
assertEquals(expectedFiles, result);
verify(additionalFileRepository).findByBookId(bookId);
verify(additionalFileMapper).toAdditionalFiles(entities);
}
@Test
void deleteAdditionalFile_physicalFileNotExists() {
// Arrange
Path nonExistentFile = tempDir.resolve("non-existent.pdf");
void getAdditionalFilesByBookId_WhenNoFilesExist_ShouldReturnEmptyList() {
Long bookId = 100L;
List<BookAdditionalFileEntity> entities = Collections.emptyList();
List<AdditionalFile> expectedFiles = Collections.emptyList();
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
when(additionalFileRepository.findByBookId(bookId)).thenReturn(entities);
when(additionalFileMapper.toAdditionalFiles(entities)).thenReturn(expectedFiles);
BookEntity book = new BookEntity();
book.setLibraryPath(libraryPath);
List<AdditionalFile> result = additionalFileService.getAdditionalFilesByBookId(bookId);
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
.id(1L)
.fileName("non-existent.pdf")
.fileSubPath("")
.additionalFileType(AdditionalFileType.ALTERNATIVE_FORMAT)
.book(book)
.build();
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
// Act
additionalFileService.deleteAdditionalFile(1L);
// Assert
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
verify(additionalFileRepository).delete(fileEntity);
assertTrue(result.isEmpty());
verify(additionalFileRepository).findByBookId(bookId);
verify(additionalFileMapper).toAdditionalFiles(entities);
}
@Test
void deleteAdditionalFile_ioExceptionDuringDeletion() throws IOException {
// This test verifies that DB record is still deleted even if file deletion fails
// Arrange
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath("/invalid/path");
void getAdditionalFilesByBookIdAndType_WhenFilesExist_ShouldReturnMappedFiles() {
Long bookId = 100L;
AdditionalFileType type = AdditionalFileType.ALTERNATIVE_FORMAT;
List<BookAdditionalFileEntity> entities = List.of(fileEntity);
List<AdditionalFile> expectedFiles = List.of(additionalFile);
BookEntity book = new BookEntity();
book.setLibraryPath(libraryPath);
when(additionalFileRepository.findByBookIdAndAdditionalFileType(bookId, type)).thenReturn(entities);
when(additionalFileMapper.toAdditionalFiles(entities)).thenReturn(expectedFiles);
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
.id(1L)
.fileName("test-file.pdf")
.fileSubPath("")
.additionalFileType(AdditionalFileType.ALTERNATIVE_FORMAT)
.book(book)
.build();
List<AdditionalFile> result = additionalFileService.getAdditionalFilesByBookIdAndType(bookId, type);
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
// Act
additionalFileService.deleteAdditionalFile(1L);
// Assert - DB record should still be deleted even if file deletion fails
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
verify(additionalFileRepository).delete(fileEntity);
assertEquals(expectedFiles, result);
verify(additionalFileRepository).findByBookIdAndAdditionalFileType(bookId, type);
verify(additionalFileMapper).toAdditionalFiles(entities);
}
@Test
void deleteAdditionalFile_withMonitoringProtection() {
// Arrange
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
void getAdditionalFilesByBookIdAndType_WhenNoFilesExist_ShouldReturnEmptyList() {
Long bookId = 100L;
AdditionalFileType type = AdditionalFileType.SUPPLEMENTARY;
List<BookAdditionalFileEntity> entities = Collections.emptyList();
List<AdditionalFile> expectedFiles = Collections.emptyList();
BookEntity book = new BookEntity();
book.setLibraryPath(libraryPath);
when(additionalFileRepository.findByBookIdAndAdditionalFileType(bookId, type)).thenReturn(entities);
when(additionalFileMapper.toAdditionalFiles(entities)).thenReturn(expectedFiles);
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
.id(1L)
.fileName("test-file.pdf")
.fileSubPath("subfolder")
.additionalFileType(AdditionalFileType.SUPPLEMENTARY)
.book(book)
.build();
List<AdditionalFile> result = additionalFileService.getAdditionalFilesByBookIdAndType(bookId, type);
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
assertTrue(result.isEmpty());
verify(additionalFileRepository).findByBookIdAndAdditionalFileType(bookId, type);
verify(additionalFileMapper).toAdditionalFiles(entities);
}
// Act
additionalFileService.deleteAdditionalFile(1L);
@Test
void deleteAdditionalFile_WhenFileNotFound_ShouldThrowException() {
Long fileId = 1L;
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.empty());
// Assert - Verify monitoring protection was used
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
// Verify the operation name is correct for logging/tracking
verify(monitoringProtectionService).executeWithProtection(
any(Runnable.class),
eq("additional file deletion")
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> additionalFileService.deleteAdditionalFile(fileId)
);
assertEquals("Additional file not found with id: 1", exception.getMessage());
verify(additionalFileRepository).findById(fileId);
verify(additionalFileRepository, never()).delete(any());
verify(monitoringRegistrationService, never()).unregisterSpecificPath(any());
}
}
@Test
void deleteAdditionalFile_WhenFileExists_ShouldDeleteSuccessfully() throws IOException {
Long fileId = 1L;
Path parentPath = fileEntity.getFullFilePath().getParent();
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(fileEntity));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.deleteIfExists(fileEntity.getFullFilePath())).thenReturn(true);
additionalFileService.deleteAdditionalFile(fileId);
verify(additionalFileRepository).findById(fileId);
verify(monitoringRegistrationService).unregisterSpecificPath(parentPath);
filesMock.verify(() -> Files.deleteIfExists(fileEntity.getFullFilePath()));
verify(additionalFileRepository).delete(fileEntity);
}
}
@Test
void deleteAdditionalFile_WhenIOExceptionOccurs_ShouldStillDeleteFromRepository() throws IOException {
Long fileId = 1L;
Path parentPath = fileEntity.getFullFilePath().getParent();
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(fileEntity));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.deleteIfExists(fileEntity.getFullFilePath())).thenThrow(new IOException("File access error"));
additionalFileService.deleteAdditionalFile(fileId);
verify(additionalFileRepository).findById(fileId);
verify(monitoringRegistrationService).unregisterSpecificPath(parentPath);
filesMock.verify(() -> Files.deleteIfExists(fileEntity.getFullFilePath()));
verify(additionalFileRepository).delete(fileEntity);
}
}
@Test
void deleteAdditionalFile_WhenEntityRelationshipsMissing_ShouldThrowIllegalStateException() {
Long fileId = 1L;
BookAdditionalFileEntity invalidEntity = new BookAdditionalFileEntity();
invalidEntity.setId(fileId);
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(invalidEntity));
assertThrows(
IllegalStateException.class,
() -> additionalFileService.deleteAdditionalFile(fileId)
);
verify(additionalFileRepository).findById(fileId);
verify(additionalFileRepository, never()).delete(any());
verify(monitoringRegistrationService, never()).unregisterSpecificPath(any());
}
@Test
void downloadAdditionalFile_WhenFileNotFound_ShouldReturnNotFound() throws IOException {
Long fileId = 1L;
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.empty());
ResponseEntity<Resource> result = additionalFileService.downloadAdditionalFile(fileId);
assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
assertNull(result.getBody());
verify(additionalFileRepository).findById(fileId);
}
@Test
void downloadAdditionalFile_WhenPhysicalFileNotExists_ShouldReturnNotFound() throws IOException {
Long fileId = 1L;
BookAdditionalFileEntity entityWithNonExistentFile = new BookAdditionalFileEntity();
entityWithNonExistentFile.setId(fileId);
entityWithNonExistentFile.setBook(bookEntity);
entityWithNonExistentFile.setFileName("non-existent.pdf");
entityWithNonExistentFile.setFileSubPath(".");
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(entityWithNonExistentFile));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
Path actualPath = entityWithNonExistentFile.getFullFilePath();
filesMock.when(() -> Files.exists(actualPath)).thenReturn(false);
ResponseEntity<Resource> result = additionalFileService.downloadAdditionalFile(fileId);
assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
assertNull(result.getBody());
verify(additionalFileRepository).findById(fileId);
filesMock.verify(() -> Files.exists(actualPath));
}
}
@Test
void downloadAdditionalFile_WhenFileExists_ShouldReturnFileResource() throws IOException {
Long fileId = 1L;
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(fileEntity));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(fileEntity.getFullFilePath())).thenReturn(true);
ResponseEntity<Resource> result = additionalFileService.downloadAdditionalFile(fileId);
assertEquals(HttpStatus.OK, result.getStatusCode());
assertNotNull(result.getBody());
assertTrue(result.getHeaders().containsKey(HttpHeaders.CONTENT_DISPOSITION));
assertTrue(result.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION).contains("test-file.pdf"));
assertEquals(MediaType.APPLICATION_OCTET_STREAM, result.getHeaders().getContentType());
verify(additionalFileRepository).findById(fileId);
filesMock.verify(() -> Files.exists(fileEntity.getFullFilePath()));
}
}
@Test
void downloadAdditionalFile_WhenEntityRelationshipsMissing_ShouldThrowIllegalStateException() throws IOException {
Long fileId = 1L;
BookAdditionalFileEntity invalidEntity = new BookAdditionalFileEntity();
invalidEntity.setId(fileId);
when(additionalFileRepository.findById(fileId)).thenReturn(Optional.of(invalidEntity));
assertThrows(
IllegalStateException.class,
() -> additionalFileService.downloadAdditionalFile(fileId)
);
verify(additionalFileRepository).findById(fileId);
}
}
@@ -1,275 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.response.BookDeletionResponse;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.FileService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class BookServiceDeleteBooksTest {
@Mock private BookRepository bookRepository;
@Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
@Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
@Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
@Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
@Mock private ShelfRepository shelfRepository;
@Mock private FileService fileService;
@Mock private BookMapper bookMapper;
@Mock private UserRepository userRepository;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private AuthenticationService authenticationService;
@Mock private BookQueryService bookQueryService;
@Mock private UserProgressService userProgressService;
@Mock private BookDownloadService bookDownloadService;
@Mock private MonitoringProtectionService monitoringProtectionService;
private BookService bookService;
@TempDir
Path tempDir;
@BeforeEach
void setUp() {
bookService = new BookService(
bookRepository,
pdfViewerPreferencesRepository,
epubViewerPreferencesRepository,
cbxViewerPreferencesRepository,
newPdfViewerPreferencesRepository,
shelfRepository,
fileService,
bookMapper,
userRepository,
userBookProgressRepository,
authenticationService,
bookQueryService,
userProgressService,
bookDownloadService,
monitoringProtectionService
);
// Configure mock to execute the Supplier for file operations
when(monitoringProtectionService.executeWithProtection(any(Supplier.class), eq("book deletion")))
.thenAnswer(invocation -> {
Supplier<?> supplier = invocation.getArgument(0);
return supplier.get();
});
}
private LibraryEntity createTestLibrary() {
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
LibraryEntity library = new LibraryEntity();
library.setId(1L);
library.setName("Test Library");
library.setLibraryPaths(List.of(libraryPath));
return library;
}
private LibraryPathEntity createTestLibraryPath() {
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
return libraryPath;
}
@Test
void deleteBooks_successfulDeletion() throws IOException {
// Arrange
Path testFile1 = tempDir.resolve("book1.epub");
Path testFile2 = tempDir.resolve("book2.pdf");
Files.createFile(testFile1);
Files.createFile(testFile2);
LibraryEntity library = createTestLibrary();
LibraryPathEntity libraryPath = createTestLibraryPath();
BookEntity book1 = BookEntity.builder()
.id(1L)
.fileName("book1.epub")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
BookEntity book2 = BookEntity.builder()
.id(2L)
.fileName("book2.pdf")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
List<BookEntity> books = List.of(book1, book2);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L))).thenReturn(books);
// Act
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of(1L, 2L));
// Assert
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
BookDeletionResponse deletionResponse = response.getBody();
assertThat(deletionResponse).isNotNull();
assertThat(deletionResponse.getDeleted()).containsExactlyInAnyOrder(1L, 2L);
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty();
// Verify monitoring protection was used
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
// Verify books were deleted from database
verify(bookRepository).deleteAll(books);
// Verify files were deleted
assertThat(Files.exists(testFile1)).isFalse();
assertThat(Files.exists(testFile2)).isFalse();
}
@Test
void deleteBooks_fileNotFound() {
// Arrange
Path nonExistentFile = tempDir.resolve("non-existent.epub");
LibraryEntity library = createTestLibrary();
LibraryPathEntity libraryPath = createTestLibraryPath();
BookEntity book = BookEntity.builder()
.id(1L)
.fileName("non-existent.epub")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
// Act
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of(1L));
// Assert
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
BookDeletionResponse deletionResponse = response.getBody();
assertThat(deletionResponse).isNotNull();
assertThat(deletionResponse.getDeleted()).containsExactly(1L);
// File doesn't exist, so no deletion failure is recorded
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty();
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
verify(bookRepository).deleteAll(List.of(book));
}
@Test
void deleteBooks_partialFailure() throws IOException {
// Arrange
Path existingFile = tempDir.resolve("existing.epub");
Files.createFile(existingFile);
LibraryEntity library = createTestLibrary();
LibraryPathEntity libraryPath = createTestLibraryPath();
BookEntity existingBook = BookEntity.builder()
.id(1L)
.fileName("existing.epub")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
BookEntity missingBook = BookEntity.builder()
.id(2L)
.fileName("missing.epub")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
List<BookEntity> books = List.of(existingBook, missingBook);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L))).thenReturn(books);
// Act
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of(1L, 2L));
// Assert
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
BookDeletionResponse deletionResponse = response.getBody();
assertThat(deletionResponse).isNotNull();
assertThat(deletionResponse.getDeleted()).containsExactlyInAnyOrder(1L, 2L);
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty(); // Missing file is not considered a failure
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
verify(bookRepository).deleteAll(books);
// Existing file should be deleted
assertThat(Files.exists(existingFile)).isFalse();
}
@Test
void deleteBooks_emptySet() {
// Act
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of());
// Assert
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
BookDeletionResponse deletionResponse = response.getBody();
assertThat(deletionResponse).isNotNull();
assertThat(deletionResponse.getDeleted()).isEmpty();
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty();
// Should still use monitoring protection even for empty operations
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
verify(bookRepository).deleteAll(List.of());
}
@Test
void deleteBooks_verifyMonitoringProtectionUsage() {
// Arrange
LibraryEntity library = createTestLibrary();
LibraryPathEntity libraryPath = createTestLibraryPath();
BookEntity book = BookEntity.builder()
.id(1L)
.fileName("test.epub")
.fileSubPath("")
.libraryPath(libraryPath)
.library(library)
.build();
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
// Act
bookService.deleteBooks(Set.of(1L));
// Assert - Verify monitoring protection is called with correct parameters
verify(monitoringProtectionService).executeWithProtection(
any(Supplier.class),
eq("book deletion")
);
}
}
@@ -1,276 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class MonitoringProtectionConcurrentTest {
@Mock
private MonitoringService monitoringService;
private MonitoringProtectionService monitoringProtectionService;
@BeforeEach
void setUp() {
monitoringProtectionService = new MonitoringProtectionService(monitoringService);
}
@Test
void concurrentOperations_properSynchronization() throws InterruptedException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false, true, true, true, true);
AtomicInteger operationCount = new AtomicInteger(0);
AtomicInteger pauseCount = new AtomicInteger(0);
AtomicInteger resumeCount = new AtomicInteger(0);
// Track pause/resume calls
doAnswer(invocation -> {
pauseCount.incrementAndGet();
return null;
}).when(monitoringService).pauseMonitoring();
doAnswer(invocation -> {
resumeCount.incrementAndGet();
return null;
}).when(monitoringService).resumeMonitoring();
int numberOfThreads = 10;
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
// Act - Run multiple concurrent operations
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < numberOfThreads; i++) {
final int operationId = i;
Future<?> future = executor.submit(() -> {
try {
monitoringProtectionService.executeWithProtection(() -> {
operationCount.incrementAndGet();
// Simulate some work
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "concurrent test operation " + operationId);
} finally {
latch.countDown();
}
});
futures.add(future);
}
// Wait for all operations to complete
boolean completed = latch.await(30, TimeUnit.SECONDS);
executor.shutdown();
// Assert
assertThat(completed).isTrue();
assertThat(operationCount.get()).isEqualTo(numberOfThreads);
// Verify monitoring was paused at least once (may be fewer due to synchronization)
assertThat(pauseCount.get()).isGreaterThan(0);
// Wait a bit for resume calls (they happen with delay in virtual threads)
Thread.sleep(6000);
assertThat(resumeCount.get()).isGreaterThan(0);
// All futures should complete successfully
for (Future<?> future : futures) {
assertThat(future.isDone()).isTrue();
}
}
@Test
void concurrentOperations_onlyOnePausesMonitoring() throws InterruptedException {
// Arrange - First call returns false (not paused), subsequent return true (already paused)
when(monitoringService.isPaused()).thenReturn(false).thenReturn(true);
AtomicInteger pauseCallCount = new AtomicInteger(0);
doAnswer(invocation -> {
pauseCallCount.incrementAndGet();
return null;
}).when(monitoringService).pauseMonitoring();
int numberOfThreads = 5;
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch finishLatch = new CountDownLatch(numberOfThreads);
// Act - Start all threads at the same time to maximize contention
for (int i = 0; i < numberOfThreads; i++) {
executor.submit(() -> {
try {
startLatch.await(); // Wait for signal to start
monitoringProtectionService.executeWithProtection(() -> {
// Simulate work
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "sync test");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
finishLatch.countDown();
}
});
}
startLatch.countDown(); // Start all threads
boolean completed = finishLatch.await(10, TimeUnit.SECONDS);
executor.shutdown();
// Assert
assertThat(completed).isTrue();
// Only one thread should have actually called pauseMonitoring due to synchronization
assertThat(pauseCallCount.get()).isEqualTo(1);
}
@Test
void concurrentOperations_withExceptions() throws InterruptedException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false, true, true);
AtomicInteger successCount = new AtomicInteger(0);
AtomicInteger exceptionCount = new AtomicInteger(0);
AtomicInteger resumeCount = new AtomicInteger(0);
doAnswer(invocation -> {
resumeCount.incrementAndGet();
return null;
}).when(monitoringService).resumeMonitoring();
int numberOfThreads = 8;
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
// Act - Half the operations throw exceptions
for (int i = 0; i < numberOfThreads; i++) {
final int operationId = i;
executor.submit(() -> {
try {
monitoringProtectionService.executeWithProtection(() -> {
if (operationId % 2 == 0) {
successCount.incrementAndGet();
} else {
exceptionCount.incrementAndGet();
throw new RuntimeException("Test exception " + operationId);
}
}, "exception test " + operationId);
} catch (RuntimeException e) {
// Expected for half the operations
} finally {
latch.countDown();
}
});
}
boolean completed = latch.await(10, TimeUnit.SECONDS);
executor.shutdown();
// Assert
assertThat(completed).isTrue();
assertThat(successCount.get()).isEqualTo(numberOfThreads / 2);
assertThat(exceptionCount.get()).isEqualTo(numberOfThreads / 2);
// Wait for resume calls (delayed)
Thread.sleep(6000);
// Even with exceptions, monitoring should still be resumed
assertThat(resumeCount.get()).isGreaterThan(0);
}
@Test
void concurrentOperations_supplierReturnValues() throws InterruptedException, ExecutionException, TimeoutException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false, true, true, true);
int numberOfThreads = 6;
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
// Act - Use Supplier version to test return values
List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < numberOfThreads; i++) {
final int operationId = i;
Future<String> future = executor.submit(() ->
monitoringProtectionService.executeWithProtection(() -> {
try {
Thread.sleep(50); // Simulate work
return "Result-" + operationId;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return "Interrupted-" + operationId;
}
}, "supplier test " + operationId)
);
futures.add(future);
}
// Assert
List<String> results = new ArrayList<>();
for (Future<String> future : futures) {
String result = future.get(10, TimeUnit.SECONDS);
results.add(result);
}
executor.shutdown();
assertThat(results).hasSize(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
assertThat(results).contains("Result-" + i);
}
}
@Test
void stressTest_manyQuickOperations() throws InterruptedException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false).thenReturn(true);
AtomicInteger completedOperations = new AtomicInteger(0);
int numberOfOperations = 100;
ExecutorService executor = Executors.newFixedThreadPool(20);
CountDownLatch latch = new CountDownLatch(numberOfOperations);
// Act - Many quick operations to test lock contention
for (int i = 0; i < numberOfOperations; i++) {
executor.submit(() -> {
try {
monitoringProtectionService.executeWithProtection(() -> {
completedOperations.incrementAndGet();
// Very quick operation
}, "stress test");
} finally {
latch.countDown();
}
});
}
boolean completed = latch.await(30, TimeUnit.SECONDS);
executor.shutdown();
// Assert
assertThat(completed).isTrue();
assertThat(completedOperations.get()).isEqualTo(numberOfOperations);
// Should only pause once due to synchronization, even with many operations
verify(monitoringService, times(1)).pauseMonitoring();
}
}
@@ -1,100 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.*;
/**
* Integration test to verify that critical file operations properly use monitoring protection
* to prevent race conditions that can cause data loss.
*
* This addresses the race condition bug where monitoring would detect file operations
* as "missing files" and delete them before the operations completed.
*/
@ExtendWith(MockitoExtension.class)
class MonitoringProtectionIntegrationTest {
@Mock
private MonitoringService monitoringService;
@Test
void testMonitoringProtectionPattern_PauseAndResumeSequence() {
// Given - monitoring service that reports not paused initially
when(monitoringService.isPaused()).thenReturn(false);
// When - simulating the monitoring protection pattern used in file operations
boolean didPause = pauseMonitoringIfNeeded();
try {
// Critical file operation would happen here
// (simulated - actual file operations tested in integration tests)
} finally {
resumeMonitoringImmediately(didPause);
}
// Then - verify the correct sequence occurred
verify(monitoringService).isPaused(); // Check current state
verify(monitoringService).pauseMonitoring(); // Pause before operation
verify(monitoringService).resumeMonitoring(); // Resume after operation
}
@Test
void testMonitoringProtectionPattern_AlreadyPaused() {
// Given - monitoring service that reports already paused
when(monitoringService.isPaused()).thenReturn(true);
// When - simulating the monitoring protection pattern
boolean didPause = pauseMonitoringIfNeeded();
try {
// Critical file operation would happen here
} finally {
resumeMonitoringImmediately(didPause);
}
// Then - verify no additional pause/resume calls were made
verify(monitoringService).isPaused(); // Check current state
verify(monitoringService, never()).pauseMonitoring(); // Should not pause again
verify(monitoringService, never()).resumeMonitoring(); // Should not resume what we didn't pause
}
@Test
void testMonitoringProtectionPattern_ExceptionHandling() {
// Given - monitoring service that reports not paused initially
when(monitoringService.isPaused()).thenReturn(false);
// When - simulating the monitoring protection pattern with exception
boolean didPause = pauseMonitoringIfNeeded();
try {
// Simulate a critical file operation that throws an exception
throw new RuntimeException("File operation failed");
} catch (RuntimeException e) {
// Exception handling would occur here in real code
} finally {
resumeMonitoringImmediately(didPause);
}
// Then - verify monitoring was still resumed despite the exception
verify(monitoringService).isPaused();
verify(monitoringService).pauseMonitoring();
verify(monitoringService).resumeMonitoring(); // Critical: must resume even on failure
}
// Helper methods that mirror the actual implementation pattern
private boolean pauseMonitoringIfNeeded() {
if (!monitoringService.isPaused()) {
monitoringService.pauseMonitoring();
return true;
}
return false;
}
private void resumeMonitoringImmediately(boolean didPause) {
if (didPause) {
monitoringService.resumeMonitoring();
}
}
}
@@ -1,232 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
/**
* Integration test that simulates the actual race condition scenario:
* File operations happening while monitoring service detects "missing" files.
*
* This test verifies that MonitoringProtectionService prevents the race condition
* that was causing data loss in the original bug.
*/
@ExtendWith(MockitoExtension.class)
class MonitoringProtectionRaceConditionTest {
@TempDir
Path tempDir;
@Mock
private MonitoringService monitoringService;
private MonitoringProtectionService monitoringProtectionService;
@BeforeEach
void setUp() {
monitoringProtectionService = new MonitoringProtectionService(monitoringService);
}
@Test
void raceConditionPrevention_fileMoveDuringMonitoring() throws InterruptedException, IOException, ExecutionException, TimeoutException {
// Arrange
Path sourceFile = tempDir.resolve("source.txt");
Path targetFile = tempDir.resolve("target.txt");
Files.write(sourceFile, "test content".getBytes());
AtomicBoolean fileOperationCompleted = new AtomicBoolean(false);
AtomicBoolean monitoringDetectedMissingFile = new AtomicBoolean(false);
AtomicBoolean raceConditionOccurred = new AtomicBoolean(false);
// Configure mock behavior - monitoring is paused during file operations
when(monitoringService.isPaused()).thenAnswer(invocation -> {
// isPaused() should return true when monitoring is paused (during file operations)
// We start unpaused, then get paused during the operation, then unpaused after
return !fileOperationCompleted.get(); // true when operation is running = paused
});
// Start aggressive monitoring that looks for the file
ExecutorService monitoringExecutor = Executors.newSingleThreadExecutor();
Future<?> monitoringTask = monitoringExecutor.submit(() -> {
while (!fileOperationCompleted.get()) {
if (!monitoringService.isPaused() && !Files.exists(sourceFile)) {
monitoringDetectedMissingFile.set(true);
if (!fileOperationCompleted.get()) {
// This would be where the monitoring service deletes the "missing" file
raceConditionOccurred.set(true);
break;
}
}
try {
Thread.sleep(1); // Very aggressive checking
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
});
// Act - Perform file operation with protection
monitoringProtectionService.executeWithProtection(() -> {
try {
// Simulate the file operation that was causing issues
Thread.sleep(100); // Simulate some processing time
Files.move(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
Thread.sleep(100); // Simulate more processing time
fileOperationCompleted.set(true);
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}, "race condition test");
// Wait for monitoring task to complete
monitoringTask.get(10, TimeUnit.SECONDS);
monitoringExecutor.shutdown();
// Assert
assertThat(Files.exists(targetFile)).isTrue();
assertThat(Files.exists(sourceFile)).isFalse();
assertThat(fileOperationCompleted.get()).isTrue();
// The critical assertion: monitoring should not have detected a missing file during the operation
assertThat(raceConditionOccurred.get())
.withFailMessage("Race condition occurred! Monitoring detected missing file during protected operation")
.isFalse();
}
@Test
void raceConditionPrevention_multipleConcurrentFileOperations() throws InterruptedException, IOException, ExecutionException, TimeoutException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false).thenReturn(true);
// Multiple file operations that could interfere with each other
int numberOfOperations = 10;
List<Path> sourceFiles = new ArrayList<>();
List<Path> targetFiles = new ArrayList<>();
for (int i = 0; i < numberOfOperations; i++) {
Path source = tempDir.resolve("source_" + i + ".txt");
Path target = tempDir.resolve("target_" + i + ".txt");
Files.write(source, ("content " + i).getBytes());
sourceFiles.add(source);
targetFiles.add(target);
}
AtomicInteger completedOperations = new AtomicInteger(0);
AtomicInteger raceConditionCount = new AtomicInteger(0);
// Start monitoring that checks for missing files
ExecutorService monitoringExecutor = Executors.newSingleThreadExecutor();
Future<?> monitoringTask = monitoringExecutor.submit(() -> {
while (completedOperations.get() < numberOfOperations) {
if (!monitoringService.isPaused()) {
// Check for any missing source files
for (int i = 0; i < numberOfOperations; i++) {
Path source = sourceFiles.get(i);
Path target = targetFiles.get(i);
// If source is gone but target doesn't exist, it's a race condition
if (!Files.exists(source) && !Files.exists(target)) {
raceConditionCount.incrementAndGet();
}
}
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
});
// Act - Perform multiple concurrent file operations
ExecutorService operationExecutor = Executors.newFixedThreadPool(5);
CountDownLatch latch = new CountDownLatch(numberOfOperations);
for (int i = 0; i < numberOfOperations; i++) {
final int operationIndex = i;
operationExecutor.submit(() -> {
try {
monitoringProtectionService.executeWithProtection(() -> {
try {
Thread.sleep(50); // Simulate processing
Files.move(sourceFiles.get(operationIndex),
targetFiles.get(operationIndex),
StandardCopyOption.REPLACE_EXISTING);
completedOperations.incrementAndGet();
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}, "concurrent operation " + operationIndex);
} finally {
latch.countDown();
}
});
}
// Wait for all operations to complete
boolean allCompleted = latch.await(30, TimeUnit.SECONDS);
monitoringTask.get(5, TimeUnit.SECONDS);
operationExecutor.shutdown();
monitoringExecutor.shutdown();
// Assert
assertThat(allCompleted).isTrue();
assertThat(completedOperations.get()).isEqualTo(numberOfOperations);
// All target files should exist
for (Path target : targetFiles) {
assertThat(Files.exists(target)).isTrue();
}
// No source files should exist
for (Path source : sourceFiles) {
assertThat(Files.exists(source)).isFalse();
}
// Critical assertion: no race conditions should have occurred
assertThat(raceConditionCount.get())
.withFailMessage("Race conditions detected during concurrent operations")
.isEqualTo(0);
}
@Test
void monitoringResumesAfterDelay() throws InterruptedException {
// Arrange
when(monitoringService.isPaused()).thenReturn(false, true);
// Act - Perform operation with protection
monitoringProtectionService.executeWithProtection(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "delay test");
// Wait for monitoring to resume (should happen after 5 seconds)
Thread.sleep(6000);
// Assert - Verify monitoring service methods were called
verify(monitoringService).pauseMonitoring();
verify(monitoringService).resumeMonitoring();
}
}
@@ -0,0 +1,421 @@
package com.adityachandel.booklore.service.bookdrop;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.mapper.BookdropFileMapper;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.BookdropFile;
import com.adityachandel.booklore.model.dto.BookdropFileNotification;
import com.adityachandel.booklore.model.dto.request.BookdropFinalizeRequest;
import com.adityachandel.booklore.model.dto.response.BookdropFinalizeResult;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.BookdropFileRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.file.FileMovingHelper;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Ignore;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class BookDropServiceTest {
@Mock
private BookdropFileRepository bookdropFileRepository;
@Mock
private LibraryRepository libraryRepository;
@Mock
private BookRepository bookRepository;
@Mock
private BookdropMonitoringService bookdropMonitoringService;
@Mock
private NotificationService notificationService;
@Mock
private MetadataRefreshService metadataRefreshService;
@Mock
private BookdropNotificationService bookdropNotificationService;
@Mock
private BookFileProcessorRegistry processorRegistry;
@Mock
private AppProperties appProperties;
@Mock
private BookdropFileMapper mapper;
@Mock
private ObjectMapper objectMapper;
@Mock
private FileMovingHelper fileMovingHelper;
@InjectMocks
private BookDropService bookDropService;
@TempDir
Path tempDir;
private BookdropFileEntity bookdropFileEntity;
private LibraryEntity libraryEntity;
private LibraryPathEntity libraryPathEntity;
private BookdropFile bookdropFile;
@BeforeEach
void setUp() throws IOException {
libraryPathEntity = new LibraryPathEntity();
libraryPathEntity.setId(1L);
libraryPathEntity.setPath(tempDir.toString());
libraryEntity = new LibraryEntity();
libraryEntity.setId(1L);
libraryEntity.setName("Test Library");
libraryEntity.setLibraryPaths(List.of(libraryPathEntity));
bookdropFileEntity = new BookdropFileEntity();
bookdropFileEntity.setId(1L);
bookdropFileEntity.setFileName("test-book.pdf");
bookdropFileEntity.setFilePath(tempDir.resolve("test-book.pdf").toString());
bookdropFileEntity.setStatus(BookdropFileEntity.Status.PENDING_REVIEW);
bookdropFileEntity.setOriginalMetadata("{\"title\":\"Test Book\"}");
bookdropFileEntity.setFetchedMetadata(null);
bookdropFile = new BookdropFile();
bookdropFile.setId(1L);
bookdropFile.setFileName("test-book.pdf");
Files.createFile(tempDir.resolve("test-book.pdf"));
}
@Test
void getFileNotificationSummary_ShouldReturnCorrectCounts() {
when(bookdropFileRepository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW)).thenReturn(5L);
when(bookdropFileRepository.count()).thenReturn(10L);
BookdropFileNotification result = bookDropService.getFileNotificationSummary();
assertEquals(5, result.getPendingCount());
assertEquals(10, result.getTotalCount());
assertNotNull(result.getLastUpdatedAt());
verify(bookdropFileRepository).countByStatus(BookdropFileEntity.Status.PENDING_REVIEW);
verify(bookdropFileRepository).count();
}
@Test
void getFilesByStatus_WhenStatusIsPending_ShouldReturnPendingFiles() {
Pageable pageable = PageRequest.of(0, 10);
Page<BookdropFileEntity> entityPage = new PageImpl<>(List.of(bookdropFileEntity));
Page<BookdropFile> expectedPage = new PageImpl<>(List.of(bookdropFile));
when(bookdropFileRepository.findAllByStatus(BookdropFileEntity.Status.PENDING_REVIEW, pageable))
.thenReturn(entityPage);
when(mapper.toDto(bookdropFileEntity)).thenReturn(bookdropFile);
Page<BookdropFile> result = bookDropService.getFilesByStatus("pending", pageable);
assertEquals(1, result.getContent().size());
assertEquals(bookdropFile, result.getContent().get(0));
verify(bookdropFileRepository).findAllByStatus(BookdropFileEntity.Status.PENDING_REVIEW, pageable);
verify(mapper).toDto(bookdropFileEntity);
}
@Test
void getFilesByStatus_WhenStatusIsNotPending_ShouldReturnAllFiles() {
Pageable pageable = PageRequest.of(0, 10);
Page<BookdropFileEntity> entityPage = new PageImpl<>(List.of(bookdropFileEntity));
when(bookdropFileRepository.findAll(pageable)).thenReturn(entityPage);
when(mapper.toDto(bookdropFileEntity)).thenReturn(bookdropFile);
Page<BookdropFile> result = bookDropService.getFilesByStatus("all", pageable);
assertEquals(1, result.getContent().size());
verify(bookdropFileRepository).findAll(pageable);
verify(mapper).toDto(bookdropFileEntity);
}
@Test
void getBookdropCover_WhenCoverExists_ShouldReturnResource() throws IOException {
long bookdropId = 1L;
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
Path coverPath = tempDir.resolve("bookdrop_temp").resolve("1.jpg");
Files.createDirectories(coverPath.getParent());
Files.createFile(coverPath);
Resource result = bookDropService.getBookdropCover(bookdropId);
assertNotNull(result);
assertTrue(result.exists());
}
@Test
void getBookdropCover_WhenCoverDoesNotExist_ShouldReturnNull() {
long bookdropId = 999L;
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
Resource result = bookDropService.getBookdropCover(bookdropId);
assertNull(result);
}
@Test
void finalizeImport_ShouldPauseAndResumeMonitoring() {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(false);
request.setFiles(List.of());
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
assertNotNull(result);
assertNotNull(result.getProcessedAt());
verify(bookdropMonitoringService).pauseMonitoring();
verify(bookdropMonitoringService).resumeMonitoring();
}
@Test
@Disabled
void finalizeImport_WhenSelectAllTrue_ShouldProcessAllFiles() throws Exception {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(true);
request.setDefaultLibraryId(1L);
request.setDefaultPathId(1L);
request.setExcludedIds(List.of());
BookMetadata metadata = new BookMetadata();
metadata.setTitle("Test Book");
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("moved-book.pdf"));
BookFileProcessor processor = mock(BookFileProcessor.class);
when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor);
Book book = Book.builder()
.id(1L)
.title("Test Book")
.build();
FileProcessResult processResult = FileProcessResult.builder()
.book(book)
.build();
when(processor.processFile(any())).thenReturn(processResult);
BookEntity bookEntity = new BookEntity();
bookEntity.setId(1L);
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.createTempFile(anyString(), anyString())).thenReturn(tempDir.resolve("temp-file"));
filesMock.when(() -> Files.copy(any(Path.class), any(Path.class), any())).thenReturn(1024L);
filesMock.when(() -> Files.createDirectories(any(Path.class))).thenReturn(tempDir);
filesMock.when(() -> Files.move(any(Path.class), any(Path.class), any())).thenReturn(tempDir);
filesMock.when(() -> Files.deleteIfExists(any(Path.class))).thenReturn(true);
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
assertNotNull(result);
assertEquals(1, result.getTotalFiles());
assertEquals(1, result.getSuccessfullyImported());
assertEquals(0, result.getFailed());
}
}
@Test
void finalizeImport_WhenLibraryNotFound_ShouldFail() throws Exception {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(true);
request.setDefaultLibraryId(999L);
request.setDefaultPathId(1L);
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(999L)).thenReturn(Optional.empty());
BookMetadata metadata = new BookMetadata();
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
assertNotNull(result);
assertEquals(1, result.getTotalFiles());
assertEquals(0, result.getSuccessfullyImported());
assertEquals(1, result.getFailed());
}
}
@Test
void discardSelectedFiles_WhenSelectAllTrue_ShouldDeleteAllExceptExcluded() throws IOException {
List<Long> excludedIds = List.of(2L);
BookdropFileEntity fileToDelete = new BookdropFileEntity();
fileToDelete.setId(1L);
fileToDelete.setFilePath(tempDir.resolve("file-to-delete.pdf").toString());
Files.createFile(tempDir.resolve("file-to-delete.pdf"));
when(bookdropFileRepository.findAll()).thenReturn(List.of(fileToDelete));
when(appProperties.getBookdropFolder()).thenReturn(tempDir.toString());
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.walk(any(Path.class))).thenReturn(java.util.stream.Stream.of(tempDir));
filesMock.when(() -> Files.isDirectory(any(Path.class))).thenReturn(false);
filesMock.when(() -> Files.isRegularFile(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.deleteIfExists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.list(any(Path.class))).thenReturn(java.util.stream.Stream.empty());
bookDropService.discardSelectedFiles(true, excludedIds, null);
verify(bookdropFileRepository).findAll();
verify(bookdropFileRepository).deleteAllById(List.of(1L));
verify(bookdropNotificationService).sendBookdropFileSummaryNotification();
verify(bookdropMonitoringService).pauseMonitoring();
verify(bookdropMonitoringService).resumeMonitoring();
}
}
@Test
void discardSelectedFiles_WhenSelectAllFalse_ShouldDeleteOnlySelected() throws IOException {
List<Long> selectedIds = List.of(1L);
when(bookdropFileRepository.findAllById(selectedIds)).thenReturn(List.of(bookdropFileEntity));
when(appProperties.getBookdropFolder()).thenReturn(tempDir.toString());
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.walk(any(Path.class))).thenReturn(java.util.stream.Stream.of(tempDir));
filesMock.when(() -> Files.isDirectory(any(Path.class))).thenReturn(false);
filesMock.when(() -> Files.isRegularFile(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.deleteIfExists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.list(any(Path.class))).thenReturn(java.util.stream.Stream.empty());
bookDropService.discardSelectedFiles(false, null, selectedIds);
verify(bookdropFileRepository).findAllById(selectedIds);
verify(bookdropFileRepository).deleteAllById(List.of(1L));
verify(bookdropNotificationService).sendBookdropFileSummaryNotification();
}
}
@Test
void discardSelectedFiles_WhenBookdropFolderDoesNotExist_ShouldHandleGracefully() {
when(appProperties.getBookdropFolder()).thenReturn("/non-existent-path");
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(false);
bookDropService.discardSelectedFiles(true, null, null);
verify(bookdropMonitoringService).pauseMonitoring();
verify(bookdropMonitoringService).resumeMonitoring();
}
}
@Test
void finalizeImport_WhenSourceFileDoesNotExist_ShouldDeleteFromDB() throws Exception {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(true);
request.setDefaultLibraryId(1L);
request.setDefaultPathId(1L);
BookdropFileEntity missingFileEntity = new BookdropFileEntity();
missingFileEntity.setId(2L);
missingFileEntity.setFileName("missing-file.pdf");
missingFileEntity.setFilePath("/non-existent/missing-file.pdf");
missingFileEntity.setOriginalMetadata("{\"title\":\"Missing Book\"}");
missingFileEntity.setFetchedMetadata(null);
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(2L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(missingFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
BookMetadata metadata = new BookMetadata();
metadata.setTitle("Missing Book");
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("target-file.pdf"));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(Path.of("/non-existent/missing-file.pdf"))).thenReturn(false);
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
verify(bookdropFileRepository).deleteById(2L);
verify(bookdropNotificationService).sendBookdropFileSummaryNotification();
assertNotNull(result);
assertEquals(1, result.getTotalFiles());
assertEquals(0, result.getSuccessfullyImported());
assertEquals(1, result.getFailed());
}
}
@Test
void finalizeImport_WhenIOExceptionDuringMove_ShouldHandleGracefully() throws Exception {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(true);
request.setDefaultLibraryId(1L);
request.setDefaultPathId(1L);
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
BookMetadata metadata = new BookMetadata();
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("target-file.pdf"));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.createTempFile(anyString(), anyString()))
.thenThrow(new IOException("Disk full"));
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
assertNotNull(result);
assertEquals(1, result.getTotalFiles());
assertEquals(0, result.getSuccessfullyImported());
assertEquals(1, result.getFailed());
}
}
}
@@ -0,0 +1,362 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.util.PathPatternResolver;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class FileMoveServiceTest {
@Mock
private BookQueryService bookQueryService;
@Mock
private BookRepository bookRepository;
@Mock
private BookMapper bookMapper;
@Mock
private NotificationService notificationService;
@Mock
private UnifiedFileMoveService unifiedFileMoveService;
@InjectMocks
private FileMoveService fileMoveService;
private BookEntity bookEntity1;
private BookEntity bookEntity2;
private Book book1;
private Book book2;
@BeforeEach
void setUp() {
// Setup BookMetadataEntity for book1
BookMetadataEntity metadata1 = new BookMetadataEntity();
metadata1.setTitle("Test Book 1");
bookEntity1 = new BookEntity();
bookEntity1.setId(1L);
bookEntity1.setMetadata(metadata1);
metadata1.setBook(bookEntity1);
// Setup BookMetadataEntity for book2
BookMetadataEntity metadata2 = new BookMetadataEntity();
metadata2.setTitle("Test Book 2");
bookEntity2 = new BookEntity();
bookEntity2.setId(2L);
bookEntity2.setMetadata(metadata2);
metadata2.setBook(bookEntity2);
book1 = mock(Book.class);
book2 = mock(Book.class);
}
@Test
void moveFiles_WhenSingleBatch_ShouldProcessAllBooks() {
// Given
Set<Long> bookIds = Set.of(1L, 2L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
List<BookEntity> batchBooks = List.of(bookEntity1, bookEntity2);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(batchBooks);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 100, 100))
.thenReturn(List.of());
when(bookMapper.toBook(bookEntity1)).thenReturn(book1);
when(bookMapper.toBook(bookEntity2)).thenReturn(book2);
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
callback.onBookMoved(bookEntity1);
callback.onBookMoved(bookEntity2);
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(eq(batchBooks), any());
// When
fileMoveService.moveFiles(request);
// Then
verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 0, 100);
verify(unifiedFileMoveService).moveBatchBookFiles(eq(batchBooks), any());
verify(bookRepository).save(bookEntity1);
verify(bookRepository).save(bookEntity2);
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), eq(List.of(book1, book2)));
}
@Test
void moveFiles_WhenMultipleBatches_ShouldProcessAllBatches() {
// Given - create >100 ids so service iterates multiple batches
Set<Long> bookIds = IntStream.rangeClosed(1, 150)
.mapToObj(i -> (long) i)
.collect(Collectors.toSet());
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
// First batch
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(List.of(bookEntity1));
// Second batch
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 100, 100))
.thenReturn(List.of(bookEntity2));
// Third batch - empty
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 200, 100))
.thenReturn(List.of());
when(book1.getId()).thenReturn(1L);
when(book2.getId()).thenReturn(2L);
when(bookMapper.toBook(bookEntity1)).thenReturn(book1);
when(bookMapper.toBook(bookEntity2)).thenReturn(book2);
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
List<BookEntity> books = invocation.getArgument(0);
for (BookEntity book : books) {
callback.onBookMoved(book);
}
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(any(), any());
// When
fileMoveService.moveFiles(request);
// Then
verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 0, 100);
verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 100, 100);
verify(unifiedFileMoveService, times(2)).moveBatchBookFiles(any(), any());
verify(bookRepository).save(bookEntity1);
verify(bookRepository).save(bookEntity2);
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), eq(List.of(book1, book2)));
}
@Test
void moveFiles_WhenNoBooksFound_ShouldNotProcessAnything() {
// Given
Set<Long> bookIds = Set.of(1L, 2L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(List.of());
// When
fileMoveService.moveFiles(request);
// Then
verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 0, 100);
verify(unifiedFileMoveService, never()).moveBatchBookFiles(any(), any());
verify(bookRepository, never()).save(any());
verify(notificationService, never()).sendMessage(any(), any());
}
@Test
void moveFiles_WhenMoveFailsForSomeBooks_ShouldThrowException() {
// Given
Set<Long> bookIds = Set.of(1L, 2L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
List<BookEntity> batchBooks = List.of(bookEntity1, bookEntity2);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(batchBooks);
RuntimeException moveException = new RuntimeException("File move failed");
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
callback.onBookMoved(bookEntity1);
callback.onBookMoveFailed(bookEntity2, moveException);
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(eq(batchBooks), any());
when(bookMapper.toBook(bookEntity1)).thenReturn(book1);
// When & Then
RuntimeException exception = assertThrows(RuntimeException.class, () -> {
fileMoveService.moveFiles(request);
});
assertEquals("File move failed for book id 2", exception.getMessage());
assertEquals(moveException, exception.getCause());
verify(bookRepository).save(bookEntity1);
verify(bookRepository, never()).save(bookEntity2);
}
@Test
void moveFiles_WhenEmptyBookIds_ShouldCompleteWithoutProcessing() {
// Given
Set<Long> bookIds = Set.of();
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
// When
fileMoveService.moveFiles(request);
// Then: service should not call pagination when bookIds is empty
verify(bookQueryService, never()).findWithMetadataByIdsWithPagination(anySet(), anyInt(), anyInt());
verify(unifiedFileMoveService, never()).moveBatchBookFiles(any(), any());
verify(notificationService, never()).sendMessage(any(), any());
}
@Test
void moveFiles_WhenPartialBatch_ShouldProcessCorrectly() {
// Given
Set<Long> bookIds = Set.of(1L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(List.of(bookEntity1));
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 100, 100))
.thenReturn(List.of());
when(book1.getId()).thenReturn(1L);
when(bookMapper.toBook(bookEntity1)).thenReturn(book1);
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
callback.onBookMoved(bookEntity1);
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(any(), any());
// When
fileMoveService.moveFiles(request);
// Then
verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 0, 100);
verify(unifiedFileMoveService).moveBatchBookFiles(eq(List.of(bookEntity1)), any());
verify(bookRepository).save(bookEntity1);
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), eq(List.of(book1)));
}
@Test
void generatePathFromPattern_ShouldDelegateToPathPatternResolver() {
// Given
String pattern = "{author}/{title}";
String expectedPath = "John Doe/Test Book";
try (MockedStatic<PathPatternResolver> mockedResolver = mockStatic(PathPatternResolver.class)) {
mockedResolver.when(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern))
.thenReturn(expectedPath);
// When
String result = fileMoveService.generatePathFromPattern(bookEntity1, pattern);
// Then
assertEquals(expectedPath, result);
mockedResolver.verify(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern));
}
}
@Test
void generatePathFromPattern_WithDifferentPatterns_ShouldReturnCorrectPaths() {
// Given
String pattern1 = "{title}";
String pattern2 = "{author}/{series}/{title}";
String expectedPath1 = "Test Book 1";
String expectedPath2 = "Author/Series/Test Book 1";
try (MockedStatic<PathPatternResolver> mockedResolver = mockStatic(PathPatternResolver.class)) {
mockedResolver.when(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern1))
.thenReturn(expectedPath1);
mockedResolver.when(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern2))
.thenReturn(expectedPath2);
// When
String result1 = fileMoveService.generatePathFromPattern(bookEntity1, pattern1);
String result2 = fileMoveService.generatePathFromPattern(bookEntity1, pattern2);
// Then
assertEquals(expectedPath1, result1);
assertEquals(expectedPath2, result2);
mockedResolver.verify(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern1));
mockedResolver.verify(() -> PathPatternResolver.resolvePattern(bookEntity1, pattern2));
}
}
@Test
void moveFiles_ShouldSendNotificationWithAllUpdatedBooks() {
// Given
Set<Long> bookIds = Set.of(1L, 2L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(List.of(bookEntity1, bookEntity2));
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 100, 100))
.thenReturn(List.of());
when(bookMapper.toBook(bookEntity1)).thenReturn(book1);
when(bookMapper.toBook(bookEntity2)).thenReturn(book2);
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
callback.onBookMoved(bookEntity1);
callback.onBookMoved(bookEntity2);
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(any(), any());
// When
fileMoveService.moveFiles(request);
// Then
ArgumentCaptor<List<Book>> booksCaptor = ArgumentCaptor.forClass(List.class);
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), booksCaptor.capture());
List<Book> sentBooks = booksCaptor.getValue();
assertEquals(2, sentBooks.size());
assertTrue(sentBooks.contains(book1));
assertTrue(sentBooks.contains(book2));
}
@Test
void moveFiles_WhenNoBooksMoved_ShouldNotSendNotification() {
// Given
Set<Long> bookIds = Set.of(1L, 2L);
FileMoveRequest request = new FileMoveRequest();
request.setBookIds(bookIds);
when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100))
.thenReturn(List.of(bookEntity1, bookEntity2));
RuntimeException moveException = new RuntimeException("All moves failed");
doAnswer(invocation -> {
UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(1);
callback.onBookMoveFailed(bookEntity1, moveException);
return null;
}).when(unifiedFileMoveService).moveBatchBookFiles(any(), any());
// When & Then
assertThrows(RuntimeException.class, () -> {
fileMoveService.moveFiles(request);
});
verify(notificationService, never()).sendMessage(any(), any());
}
}
@@ -0,0 +1,306 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.PathPatternResolver;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class FileMovingHelperTest {
@Mock
BookAdditionalFileRepository additionalFileRepository;
@Mock
AppSettingService appSettingService;
@InjectMocks
FileMovingHelper helper;
@TempDir
Path tmp;
LibraryEntity library;
LibraryPathEntity libraryPath;
BookEntity book;
@BeforeEach
void init() {
library = new LibraryEntity();
library.setId(11L);
library.setName("lib");
libraryPath = new LibraryPathEntity();
libraryPath.setId(22L);
libraryPath.setPath(tmp.toString());
library.setLibraryPaths(List.of(libraryPath));
book = new BookEntity();
book.setId(101L);
BookMetadataEntity metaEntity = new BookMetadataEntity();
metaEntity.setTitle("Title");
book.setMetadata(metaEntity);
metaEntity.setBook(book);
book.setLibraryPath(libraryPath);
}
@Test
void generateNewFilePath_fromBook_usesResolvedPattern() {
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book), eq("{pattern}")))
.thenReturn("some/sub/path/book.pdf");
Path result = helper.generateNewFilePath(book, "{pattern}");
assertTrue(result.toAbsolutePath().toString().contains("some/sub/path/book.pdf"));
}
}
@Test
void generateNewFilePath_fromMetadata_usesResolvedPattern() {
BookMetadata metadata = new BookMetadata();
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(metadata), eq("{p}"), eq("orig.pdf")))
.thenReturn("meta/path/orig.pdf");
Path result = helper.generateNewFilePath(tmp.toString(), metadata, "{p}", "orig.pdf");
assertTrue(result.toString().endsWith("meta/path/orig.pdf"));
}
}
@Test
void getFileNamingPattern_prefersLibrary_thenApp_thenFallback() {
library.setFileNamingPattern("LIB_PATTERN/{currentFilename}");
String p1 = helper.getFileNamingPattern(library);
assertEquals("LIB_PATTERN/{currentFilename}", p1);
library.setFileNamingPattern(null);
AppSettings settings = new AppSettings();
settings.setUploadPattern("APP_PATTERN/{currentFilename}");
when(appSettingService.getAppSettings()).thenReturn(settings);
String p2 = helper.getFileNamingPattern(library);
assertEquals("APP_PATTERN/{currentFilename}", p2);
settings.setUploadPattern(null);
when(appSettingService.getAppSettings()).thenReturn(settings);
String p3 = helper.getFileNamingPattern(library);
assertEquals("{currentFilename}", p3);
}
@Test
void hasRequiredPathComponents_returnsFalseWhenMissing() {
BookEntity b = new BookEntity();
b.setId(1L);
b.setFileName("f");
b.setFileSubPath("s");
assertFalse(helper.hasRequiredPathComponents(b));
book.setFileSubPath("s");
book.setFileName(null);
assertFalse(helper.hasRequiredPathComponents(book));
book.setFileName("file.pdf");
assertTrue(helper.hasRequiredPathComponents(book));
}
@Test
void moveBookFileIfNeeded_noOpWhenPathsEqual() throws IOException {
book.setFileSubPath("same");
book.setFileName("file.pdf");
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book), anyString()))
.thenReturn("same/file.pdf");
boolean changed = helper.moveBookFileIfNeeded(book, "{p}");
assertFalse(changed);
}
}
@Test
void moveBookFileIfNeeded_movesAndUpdatesPaths() throws Exception {
book.setFileSubPath("olddir");
book.setFileName("file.pdf");
Path oldDir = tmp.resolve("olddir");
Files.createDirectories(oldDir);
Path oldFile = oldDir.resolve("file.pdf");
Files.createFile(oldFile);
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book), anyString()))
.thenReturn("newdir/file.pdf");
boolean moved = helper.moveBookFileIfNeeded(book, "{p}");
assertTrue(moved);
Path newFile = tmp.resolve("newdir").resolve("file.pdf");
assertTrue(Files.exists(newFile));
assertEquals("newdir", book.getFileSubPath());
assertEquals("file.pdf", book.getFileName());
assertFalse(Files.exists(oldFile));
}
}
@Test
void moveAdditionalFiles_movesFilesAndSaves() throws Exception {
book.setFileSubPath(".");
book.setFileName("book.pdf");
BookAdditionalFileEntity add = new BookAdditionalFileEntity();
add.setId(555L);
add.setFileSubPath("oldsub");
add.setFileName("add.pdf");
add.setBook(book);
book.setAdditionalFiles(List.of(add));
Path oldDir = tmp.resolve("oldsub");
Files.createDirectories(oldDir);
Path oldFile = oldDir.resolve("add.pdf");
Files.createFile(oldFile);
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book.getMetadata()), anyString(), eq("add.pdf")))
.thenReturn("additional/newadd.pdf");
helper.moveAdditionalFiles(book, "{pattern}");
Path newFile = tmp.resolve("additional").resolve("newadd.pdf");
assertTrue(Files.exists(newFile));
verify(additionalFileRepository).save(add);
assertEquals("newadd.pdf", add.getFileName());
}
}
@Test
void generateNewFilePath_trimsLeadingSeparator() {
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book), eq("{pattern}")))
.thenReturn("/leading/path/book.pdf");
Path result = helper.generateNewFilePath(book, "{pattern}");
assertTrue(result.toString().endsWith("leading/path/book.pdf"));
assertFalse(result.toString().contains("//"));
}
}
@Test
void getFileNamingPattern_appendsFilename_whenEndsWithSeparator() {
library.setFileNamingPattern("SOME/PATTERN/");
String pattern = helper.getFileNamingPattern(library);
assertTrue(pattern.endsWith("{currentFilename}"));
assertEquals("SOME/PATTERN/{currentFilename}", pattern);
}
@Test
void moveFile_createsParentDirectories_and_movesFile() throws Exception {
Path srcDir = tmp.resolve("srcdir");
Files.createDirectories(srcDir);
Path src = srcDir.resolve("file.txt");
Files.writeString(src, "hello");
Path target = tmp.resolve("nested").resolve("deep").resolve("file.txt");
assertFalse(Files.exists(target.getParent()));
helper.moveFile(src, target);
assertTrue(Files.exists(target));
assertFalse(Files.exists(src));
assertTrue(Files.exists(target.getParent()));
}
@Test
void deleteEmptyParentDirsUpToLibraryFolders_deletesIgnoredFilesAndDirs() throws Exception {
Path libRoot = tmp.resolve("libroot");
Path dir1 = libRoot.resolve("dir1");
Path dir2 = dir1.resolve("dir2");
Files.createDirectories(dir2);
Files.writeString(dir2.resolve(".DS_Store"), "");
Files.writeString(dir1.resolve(".DS_Store"), "");
assertTrue(Files.exists(dir2));
assertTrue(Files.exists(dir1));
assertTrue(Files.exists(libRoot) || Files.createDirectories(libRoot) != null);
helper.deleteEmptyParentDirsUpToLibraryFolders(dir2, Set.of(libRoot));
assertFalse(Files.exists(dir2));
assertFalse(Files.exists(dir1));
assertTrue(Files.exists(libRoot));
}
@Test
void deleteEmptyParentDirsUpToLibraryFolders_stopsWhenNonIgnoredPresent() throws Exception {
Path libRoot = tmp.resolve("libroot2");
Path dir = libRoot.resolve("keepdir");
Files.createDirectories(dir);
Files.writeString(dir.resolve("keep.txt"), "keep");
helper.deleteEmptyParentDirsUpToLibraryFolders(dir, Set.of(libRoot));
assertTrue(Files.exists(dir));
}
@Test
void moveAdditionalFiles_handles_duplicate_target_names_and_saves() throws Exception {
book.setFileSubPath(".");
book.setFileName("book.pdf");
BookAdditionalFileEntity a1 = new BookAdditionalFileEntity();
a1.setId(1L);
a1.setFileSubPath("oldsub");
a1.setFileName("add.pdf");
a1.setBook(book);
BookAdditionalFileEntity a2 = new BookAdditionalFileEntity();
a2.setId(2L);
a2.setFileSubPath("oldsub");
a2.setFileName("add_2.pdf");
a2.setBook(book);
book.setAdditionalFiles(List.of(a1, a2));
Path oldDir = tmp.resolve("oldsub");
Files.createDirectories(oldDir);
Files.writeString(oldDir.resolve("add.pdf"), "one");
Files.writeString(oldDir.resolve("add_2.pdf"), "two");
try (MockedStatic<PathPatternResolver> ms = mockStatic(PathPatternResolver.class)) {
ms.when(() -> PathPatternResolver.resolvePattern(eq(book.getMetadata()), anyString(), eq("add.pdf")))
.thenReturn("additional/add.pdf");
ms.when(() -> PathPatternResolver.resolvePattern(eq(book.getMetadata()), anyString(), eq("add_2.pdf")))
.thenReturn("additional/add.pdf");
helper.moveAdditionalFiles(book, "{pattern}");
Path first = tmp.resolve("additional").resolve("add.pdf");
Path second = tmp.resolve("additional").resolve("add_2.pdf");
assertTrue(Files.exists(first));
assertTrue(Files.exists(second));
verify(additionalFileRepository, atLeastOnce()).save(any(BookAdditionalFileEntity.class));
assertTrue(a1.getFileName().equals("add.pdf") || a1.getFileName().equals("add_2.pdf"));
assertTrue(a2.getFileName().equals("add.pdf") || a2.getFileName().equals("add_2.pdf"));
assertNotEquals(a1.getFileName(), a2.getFileName());
}
}
}
@@ -0,0 +1,208 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class MonitoredFileOperationServiceTest {
@Mock
MonitoringRegistrationService monitoringRegistrationService;
@InjectMocks
MonitoredFileOperationService service;
@TempDir
Path tmp;
Path sourceDir;
Path targetDir;
Path sourceFile;
Path targetFile;
final Long libraryId = 42L;
@BeforeEach
void init() throws IOException {
sourceDir = tmp.resolve("source");
Files.createDirectories(sourceDir);
sourceFile = sourceDir.resolve("file.txt");
Files.writeString(sourceFile, "data");
targetDir = tmp.resolve("target");
targetFile = targetDir.resolve("file.txt");
}
@Test
void executeWithMonitoringSuspended_unregistersAndReregisters_whenDifferentPaths() {
Supplier<String> operation = () -> {
try {
Files.createDirectories(targetDir);
Files.createDirectories(targetDir.resolve("sub"));
Files.writeString(targetFile, "moved");
} catch (IOException e) {
throw new RuntimeException(e);
}
return "ok";
};
when(monitoringRegistrationService.isPathMonitored(any()))
.thenAnswer(invocation -> {
Path p = invocation.getArgument(0);
return p.equals(sourceDir);
});
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation);
verify(monitoringRegistrationService).isPathMonitored(eq(sourceDir));
verify(monitoringRegistrationService).unregisterSpecificPath(eq(sourceDir));
verify(monitoringRegistrationService).registerSpecificPath(eq(sourceDir), eq(libraryId));
verify(monitoringRegistrationService).registerSpecificPath(eq(targetDir), eq(libraryId));
verify(monitoringRegistrationService).registerSpecificPath(eq(targetDir.resolve("sub")), eq(libraryId));
}
@Test
void executeWithMonitoringSuspended_skipsDoubleUnregister_whenSamePaths() {
Path src = sourceDir.resolve("a.txt");
Path tgt = sourceDir.resolve("b.txt");
when(monitoringRegistrationService.isPathMonitored(eq(sourceDir))).thenReturn(true);
Supplier<Boolean> operation = () -> {
try {
Files.writeString(tgt, "x");
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
};
service.executeWithMonitoringSuspended(src, tgt, libraryId, operation);
verify(monitoringRegistrationService).unregisterSpecificPath(eq(sourceDir));
verify(monitoringRegistrationService, never()).unregisterSpecificPath(eq(targetDir));
verify(monitoringRegistrationService).registerSpecificPath(eq(sourceDir), eq(libraryId));
}
@Test
void executeWithMonitoringSuspended_reRegistersEvenIfOperationThrows() {
when(monitoringRegistrationService.isPathMonitored(eq(sourceDir))).thenReturn(true);
Supplier<Void> operation = () -> {
throw new IllegalStateException("boom");
};
IllegalStateException ex = assertThrows(IllegalStateException.class, () ->
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation)
);
assertEquals("boom", ex.getMessage());
verify(monitoringRegistrationService).unregisterSpecificPath(eq(sourceDir));
verify(monitoringRegistrationService).registerSpecificPath(eq(sourceDir), eq(libraryId));
}
@Test
void reregister_handlesFilesWalkIOException_gracefully() throws Exception {
Supplier<String> operation = () -> {
try {
Files.createDirectories(targetDir);
Files.writeString(targetFile, "moved");
} catch (IOException e) {
throw new RuntimeException(e);
}
return "ok";
};
when(monitoringRegistrationService.isPathMonitored(any()))
.thenAnswer(invocation -> false);
try (MockedStatic<Files> filesMock = mockStatic(Files.class, invocation -> invocation.callRealMethod())) {
filesMock.when(() -> Files.exists(any(Path.class))).thenCallRealMethod();
filesMock.when(() -> Files.isDirectory(any(Path.class))).thenCallRealMethod();
filesMock.when(() -> Files.walk(eq(targetDir))).thenThrow(new IOException("walk fail"));
assertDoesNotThrow(() ->
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation)
);
verify(monitoringRegistrationService).registerSpecificPath(eq(targetDir), eq(libraryId));
}
}
@Test
void executeWithMonitoringSuspended_skipsReregister_whenSourceRemovedByOperation() {
when(monitoringRegistrationService.isPathMonitored(eq(sourceDir))).thenReturn(true);
Supplier<String> operation = () -> {
try {
Files.deleteIfExists(sourceFile);
Files.deleteIfExists(sourceDir);
} catch (IOException e) {
throw new RuntimeException(e);
}
return "done";
};
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation);
verify(monitoringRegistrationService).unregisterSpecificPath(eq(sourceDir));
verify(monitoringRegistrationService, never()).registerSpecificPath(eq(sourceDir), eq(libraryId));
}
@Test
void noUnregisters_whenNothingMonitored() {
Supplier<String> operation = () -> {
try {
Files.createDirectories(targetDir);
Files.writeString(targetFile, "ok");
} catch (IOException e) {
throw new RuntimeException(e);
}
return "ok";
};
when(monitoringRegistrationService.isPathMonitored(any())).thenReturn(false);
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation);
verify(monitoringRegistrationService, never()).unregisterSpecificPath(any());
verify(monitoringRegistrationService).registerSpecificPath(eq(targetDir), eq(libraryId));
}
@Test
void targetAlreadyMonitored_doesNotReRegister() throws Exception {
Files.createDirectories(targetDir);
when(monitoringRegistrationService.isPathMonitored(eq(sourceDir))).thenReturn(true);
when(monitoringRegistrationService.isPathMonitored(eq(targetDir))).thenReturn(true);
Supplier<String> operation = () -> {
try {
Files.writeString(targetFile, "x");
} catch (IOException e) {
throw new RuntimeException(e);
}
return "done";
};
service.executeWithMonitoringSuspended(sourceFile, targetFile, libraryId, operation);
verify(monitoringRegistrationService).unregisterSpecificPath(eq(sourceDir));
verify(monitoringRegistrationService).unregisterSpecificPath(eq(targetDir));
verify(monitoringRegistrationService).registerSpecificPath(eq(targetDir), eq(libraryId));
}
}
@@ -0,0 +1,210 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static java.util.Collections.singletonList;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class UnifiedFileMoveServiceTest {
@Mock
FileMovingHelper fileMovingHelper;
@Mock
MonitoredFileOperationService monitoredFileOperationService;
@Mock
MonitoringRegistrationService monitoringRegistrationService;
@InjectMocks
UnifiedFileMoveService service;
@TempDir
Path tmp;
LibraryEntity library;
LibraryPathEntity libraryPath;
@BeforeEach
void setup() {
library = new LibraryEntity();
library.setId(10L);
library.setName("lib");
libraryPath = new LibraryPathEntity();
libraryPath.setId(20L);
libraryPath.setPath(tmp.toString());
libraryPath.setLibrary(library);
library.setLibraryPaths(singletonList(libraryPath));
}
@Test
void moveSingleBookFile_skipsWhenNoLibrary() {
BookEntity book = new BookEntity();
// no libraryPath set
service.moveSingleBookFile(book);
verifyNoInteractions(monitoredFileOperationService);
verifyNoInteractions(fileMovingHelper);
}
@Test
void moveSingleBookFile_skipsWhenFileMissing() throws Exception {
BookEntity book = new BookEntity();
book.setId(1L);
book.setLibraryPath(libraryPath);
book.setFileSubPath(".");
book.setFileName("missing.pdf");
when(fileMovingHelper.getFileNamingPattern(any())).thenReturn("{currentFilename}");
service.moveSingleBookFile(book);
verifyNoInteractions(monitoredFileOperationService);
}
@Test
void moveSingleBookFile_executesMoveWhenNeeded() throws Exception {
BookEntity book = new BookEntity();
book.setId(2L);
book.setLibraryPath(libraryPath);
book.setFileSubPath(".");
book.setFileName("book.pdf");
Path src = tmp.resolve("book.pdf");
Files.writeString(src, "data");
Path expected = tmp.resolve("moved").resolve("book.pdf");
when(fileMovingHelper.getFileNamingPattern(library)).thenReturn("{currentFilename}");
when(fileMovingHelper.generateNewFilePath(eq(book), anyString())).thenReturn(expected);
when(fileMovingHelper.hasRequiredPathComponents(eq(book))).thenReturn(true);
doAnswer(invocation -> {
java.util.function.Supplier<?> supplier = invocation.getArgument(3);
supplier.get();
return null;
}).when(monitoredFileOperationService).executeWithMonitoringSuspended(any(), any(), anyLong(), any());
when(fileMovingHelper.moveBookFileIfNeeded(eq(book), anyString())).thenAnswer(inv -> {
book.setFileSubPath("moved");
book.setFileName("book.pdf");
return true;
});
Path actualSrc = book.getFullFilePath();
service.moveSingleBookFile(book);
verify(monitoredFileOperationService).executeWithMonitoringSuspended(eq(actualSrc), eq(expected), eq(10L), any());
verify(fileMovingHelper).moveBookFileIfNeeded(eq(book), anyString());
assertEquals("moved", book.getFileSubPath());
}
@Test
void moveBatchBookFiles_movesBooks_and_callsCallback_and_reRegistersLibraries() throws Exception {
BookEntity b1 = new BookEntity();
b1.setId(11L);
b1.setLibraryPath(libraryPath);
b1.setFileSubPath(".");
b1.setFileName("a.pdf");
BookMetadataEntity m1 = new BookMetadataEntity();
m1.setTitle("A");
b1.setMetadata(m1);
m1.setBook(b1);
BookEntity b2 = new BookEntity();
b2.setId(12L);
b2.setLibraryPath(libraryPath);
b2.setFileSubPath(".");
b2.setFileName("b.pdf");
BookMetadataEntity m2 = new BookMetadataEntity();
m2.setTitle("B");
b2.setMetadata(m2);
m2.setBook(b2);
Path p1 = tmp.resolve("a.pdf");
Path p2 = tmp.resolve("b.pdf");
Files.writeString(p1, "1");
Files.writeString(p2, "2");
when(fileMovingHelper.getFileNamingPattern(library)).thenReturn("{currentFilename}");
when(fileMovingHelper.hasRequiredPathComponents(eq(b1))).thenReturn(true);
when(fileMovingHelper.hasRequiredPathComponents(eq(b2))).thenReturn(true);
when(fileMovingHelper.moveBookFileIfNeeded(eq(b1), anyString())).thenAnswer(inv -> {
b1.setFileSubPath("moved");
return true;
});
when(fileMovingHelper.moveBookFileIfNeeded(eq(b2), anyString())).thenReturn(false);
BookAdditionalFileEntity add = new BookAdditionalFileEntity();
add.setId(100L);
add.setBook(b1);
add.setFileSubPath(".");
add.setFileName("extra.pdf");
b1.setAdditionalFiles(List.of(add));
doNothing().when(fileMovingHelper).moveAdditionalFiles(eq(b1), anyString());
UnifiedFileMoveService.BatchMoveCallback cb = mock(UnifiedFileMoveService.BatchMoveCallback.class);
service.moveBatchBookFiles(List.of(b1, b2), cb);
verify(monitoringRegistrationService).unregisterLibrary(eq(10L));
verify(fileMovingHelper).moveBookFileIfNeeded(eq(b1), anyString());
verify(fileMovingHelper).moveBookFileIfNeeded(eq(b2), anyString());
verify(cb).onBookMoved(eq(b1));
verify(cb, never()).onBookMoved(eq(b2));
verify(fileMovingHelper).moveAdditionalFiles(eq(b1), anyString());
verify(monitoringRegistrationService).registerLibraryPaths(eq(10L), any());
}
@Test
void moveBatchBookFiles_callsOnBookMoveFailed_onIOException() throws Exception {
BookEntity b = new BookEntity();
b.setId(21L);
b.setLibraryPath(libraryPath);
b.setFileSubPath(".");
b.setFileName("c.pdf");
BookMetadataEntity m = new BookMetadataEntity();
m.setTitle("C");
b.setMetadata(m);
m.setBook(b);
Path p = tmp.resolve("c.pdf");
Files.writeString(p, "c");
when(fileMovingHelper.getFileNamingPattern(library)).thenReturn("{currentFilename}");
when(fileMovingHelper.hasRequiredPathComponents(eq(b))).thenReturn(true);
when(fileMovingHelper.moveBookFileIfNeeded(eq(b), anyString())).thenThrow(new IOException("disk"));
UnifiedFileMoveService.BatchMoveCallback cb = mock(UnifiedFileMoveService.BatchMoveCallback.class);
service.moveBatchBookFiles(List.of(b), cb);
verify(cb).onBookMoveFailed(eq(b), any(IOException.class));
verify(monitoringRegistrationService).unregisterLibrary(eq(10L));
verify(monitoringRegistrationService).registerLibraryPaths(eq(10L), any());
}
}
@@ -0,0 +1,140 @@
package com.adityachandel.booklore.service.monitoring;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class MonitoringRegistrationServiceTest {
@Mock
MonitoringService monitoringService;
@InjectMocks
MonitoringRegistrationService registrationService;
@TempDir
Path tmp;
Path root;
Path sub1;
Path sub2;
@BeforeEach
void setupFs() throws IOException {
root = tmp.resolve("libroot");
sub1 = root.resolve("a");
sub2 = root.resolve("a").resolve("b");
Files.createDirectories(sub2);
}
@Test
void isPathMonitored_delegatesToMonitoringService() {
when(monitoringService.isPathMonitored(root)).thenReturn(true);
assertTrue(registrationService.isPathMonitored(root));
verify(monitoringService).isPathMonitored(root);
}
@Test
void unregisterSpecificPath_delegates() {
registrationService.unregisterSpecificPath(root);
verify(monitoringService).unregisterPath(root);
}
@Test
void registerSpecificPath_delegates() {
registrationService.registerSpecificPath(root, 123L);
verify(monitoringService).registerPath(root, 123L);
}
@Test
void unregisterLibrary_delegates() {
registrationService.unregisterLibrary(99L);
verify(monitoringService).unregisterLibrary(99L);
}
@Test
void registerLibraryPaths_noopWhenMissingOrNotDirectory() throws IOException {
Path missing = tmp.resolve("does-not-exist");
registrationService.registerLibraryPaths(7L, missing);
verifyNoInteractions(monitoringService);
Path file = tmp.resolve("afile.txt");
Files.writeString(file, "x");
registrationService.registerLibraryPaths(7L, file);
verifyNoInteractions(monitoringService);
}
@Test
void registerLibraryPaths_registersRootAndAllSubdirs() {
registrationService.registerLibraryPaths(42L, root);
verify(monitoringService).registerPath(root, 42L);
// subdirs a and a/b should be registered as well
verify(monitoringService).registerPath(sub1, 42L);
verify(monitoringService).registerPath(sub2, 42L);
ArgumentCaptor<Path> capt = ArgumentCaptor.forClass(Path.class);
verify(monitoringService, atLeast(3)).registerPath(capt.capture(), eq(42L));
List<Path> registered = capt.getAllValues();
assertTrue(registered.contains(root));
assertTrue(registered.contains(sub1));
assertTrue(registered.contains(sub2));
}
@Test
void registerLibraryPaths_handlesMonitoringServiceExceptionGracefully() {
doThrow(new RuntimeException("boom")).when(monitoringService).registerPath(eq(root), eq(55L));
assertDoesNotThrow(() -> registrationService.registerLibraryPaths(55L, root));
verify(monitoringService).registerPath(root, 55L);
}
@Test
void registerLibraryPaths_partialFailureStops() {
doAnswer(invocation -> {
Path p = invocation.getArgument(0);
Long id = invocation.getArgument(1);
if (id != null && id.equals(42L) && p.getFileName() != null && "a".equals(p.getFileName().toString())) {
throw new RuntimeException("fail-sub1");
}
return null;
}).when(monitoringService).registerPath(any(Path.class), anyLong());
registrationService.registerLibraryPaths(42L, root);
verify(monitoringService).registerPath(root, 42L);
verify(monitoringService).registerPath(argThat(p -> p.getFileName() != null && "a".equals(p.getFileName().toString())), eq(42L));
verify(monitoringService, never()).registerPath(argThat(p -> p.getFileName() != null && "b".equals(p.getFileName().toString())), eq(42L));
}
@Test
void registerLibraryPaths_onlyRegistersDirectories() throws IOException {
Path fileInRoot = root.resolve("file.txt");
Files.createDirectories(root);
Files.writeString(fileInRoot, "content");
registrationService.registerLibraryPaths(100L, root);
verify(monitoringService).registerPath(root, 100L);
verify(monitoringService).registerPath(sub1, 100L);
verify(monitoringService).registerPath(sub2, 100L);
verify(monitoringService, never()).registerPath(eq(fileInRoot), anyLong());
}
}
@@ -0,0 +1,288 @@
package com.adityachandel.booklore.service.monitoring;
import com.adityachandel.booklore.model.dto.Library;
import com.adityachandel.booklore.model.dto.LibraryPath;
import com.adityachandel.booklore.service.watcher.LibraryFileEventProcessor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import java.lang.reflect.Field;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class MonitoringServiceTest {
@TempDir
Path tmp;
MonitoringService service;
LibraryFileEventProcessor processor;
MonitoringTask monitoringTask;
WatchService watchService;
@BeforeEach
void setup() throws Exception {
processor = mock(LibraryFileEventProcessor.class);
monitoringTask = mock(MonitoringTask.class);
watchService = FileSystems.getDefault().newWatchService();
service = Mockito.spy(new MonitoringService(processor, watchService, monitoringTask));
}
@AfterEach
void teardown() throws Exception {
try {
service.stopMonitoring();
} catch (Exception ignored) {}
try { watchService.close(); } catch (Exception ignored) {}
}
@Test
void registerLibrary_registersAllDirectoriesUnderLibraryPath() throws Exception {
Path root = tmp.resolve("libroot");
Path a = root.resolve("a");
Path b = a.resolve("b");
Files.createDirectories(b);
Library lib = mock(Library.class);
LibraryPath lp = mock(LibraryPath.class);
when(lp.getPath()).thenReturn(root.toString());
when(lib.getPaths()).thenReturn(List.of(lp));
when(lib.getId()).thenReturn(7L);
when(lib.getName()).thenReturn("my-lib");
when(lib.isWatch()).thenReturn(true);
doReturn(true).when(service).registerPath(any(Path.class), eq(7L));
service.registerLibrary(lib);
Files.walk(root).filter(Files::isDirectory).forEach(path ->
verify(service).registerPath(eq(path), eq(7L))
);
}
@Test
void unregisterLibrary_removesRegisteredPathsAndUpdatesMaps() throws Exception {
Path root = tmp.resolve("libroot2");
Files.createDirectories(root);
Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap");
pathToLibraryField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
map.put(root, 99L);
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
monitored.add(root);
Field registeredKeysField = MonitoringService.class.getDeclaredField("registeredWatchKeys");
registeredKeysField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,WatchKey> keys = (Map<Path,WatchKey>) registeredKeysField.get(service);
WatchKey mockKey = mock(WatchKey.class);
keys.put(root, mockKey);
service.unregisterLibrary(99L);
assertFalse(monitored.contains(root), "monitoredPaths should no longer contain root");
assertFalse(map.containsKey(root), "pathToLibraryIdMap should no longer contain root");
assertFalse(keys.containsKey(root), "registeredWatchKeys should no longer contain root");
verify(mockKey).cancel();
}
@Test
void handleFileChangeEvent_createDirectory_registersNestedPaths() throws Exception {
Path watched = tmp.resolve("watched");
Files.createDirectories(watched);
Path newDir = watched.resolve("newdir");
Files.createDirectories(newDir);
Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap");
pathToLibraryField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
map.put(watched, 5L);
doReturn(true).when(service).registerPath(any(Path.class), eq(5L));
FileChangeEvent ev = mock(FileChangeEvent.class);
when(ev.getFilePath()).thenReturn(newDir);
doReturn(StandardWatchEventKinds.ENTRY_CREATE).when(ev).getEventKind();
when(ev.getWatchedFolder()).thenReturn(watched);
service.handleFileChangeEvent(ev);
Files.walk(newDir).filter(Files::isDirectory).forEach(p -> verify(service).registerPath(eq(p), eq(5L)));
}
@Test
void backgroundProcessor_processesQueuedEvents_and_callsProcessor() throws Exception {
Path watched = tmp.resolve("wf");
Files.createDirectories(watched);
Path file = watched.resolve("book.pdf");
Files.writeString(file, "x");
Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap");
pathToLibraryField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
map.put(watched, 123L);
java.lang.reflect.Method startMethod = MonitoringService.class.getDeclaredMethod("startProcessingThread");
startMethod.setAccessible(true);
startMethod.invoke(service);
FileChangeEvent ev = mock(FileChangeEvent.class);
when(ev.getFilePath()).thenReturn(file);
doReturn(StandardWatchEventKinds.ENTRY_CREATE).when(ev).getEventKind();
when(ev.getWatchedFolder()).thenReturn(watched);
service.handleFileChangeEvent(ev);
verify(processor, timeout(2_000)).processFile(eq(StandardWatchEventKinds.ENTRY_CREATE), eq(123L), eq(watched.toString()), eq(file.toString()));
}
@Test
void handleWatchKeyInvalidation_removesInvalidPath_and_cancelsKey() throws Exception {
Path invalid = tmp.resolve("inv");
Files.createDirectories(invalid);
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
monitored.add(invalid);
Field registeredKeysField = MonitoringService.class.getDeclaredField("registeredWatchKeys");
registeredKeysField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,WatchKey> keys = (Map<Path,WatchKey>) registeredKeysField.get(service);
WatchKey wk = mock(WatchKey.class);
keys.put(invalid, wk);
WatchKeyInvalidatedEvent ev = mock(WatchKeyInvalidatedEvent.class);
when(ev.getInvalidPath()).thenReturn(invalid);
service.handleWatchKeyInvalidation(ev);
assertFalse(monitored.contains(invalid));
assertFalse(keys.containsKey(invalid));
verify(wk).cancel();
}
@Test
void isRelevantBookFile_detectsBookExtensions() {
Path pdf = Paths.get("somebook.pdf");
Path txt = Paths.get("notes.txt");
assertTrue(service.isRelevantBookFile(pdf));
assertFalse(service.isRelevantBookFile(txt));
}
@Test
void handleFileChangeEvent_ignoresIrrelevantNonBookFile() throws Exception {
Path watched = tmp.resolve("watched-ignore");
Files.createDirectories(watched);
Path file = watched.resolve("notes.txt");
Files.writeString(file, "notes");
Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap");
pathToLibraryField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
map.put(watched, 11L);
java.lang.reflect.Method startMethod = MonitoringService.class.getDeclaredMethod("startProcessingThread");
startMethod.setAccessible(true);
startMethod.invoke(service);
FileChangeEvent ev = mock(FileChangeEvent.class);
when(ev.getFilePath()).thenReturn(file);
doReturn(StandardWatchEventKinds.ENTRY_CREATE).when(ev).getEventKind();
when(ev.getWatchedFolder()).thenReturn(watched);
service.handleFileChangeEvent(ev);
verify(processor, timeout(500).times(0)).processFile(any(), anyLong(), anyString(), anyString());
}
@Test
void handleFileChangeEvent_deleteDirectory_unregistersSubPaths() throws Exception {
Path watched = tmp.resolve("watched-del");
Path a = watched.resolve("a");
Path b = a.resolve("b");
Files.createDirectories(b);
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
monitored.add(watched);
monitored.add(a);
monitored.add(b);
FileChangeEvent ev = mock(FileChangeEvent.class);
when(ev.getFilePath()).thenReturn(a);
doReturn(StandardWatchEventKinds.ENTRY_DELETE).when(ev).getEventKind();
when(ev.getWatchedFolder()).thenReturn(watched);
service.handleFileChangeEvent(ev);
assertFalse(monitored.contains(a));
assertFalse(monitored.contains(b));
assertTrue(monitored.contains(watched));
}
@Test
void isPathMonitored_handlesNonNormalizedPaths() throws Exception {
Path root = tmp.resolve("libroot-norm");
Path sub = root.resolve("subdir");
Files.createDirectories(sub);
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
monitored.add(sub.toAbsolutePath().normalize());
Path nonNormalized = root.resolve("subdir/../subdir/.");
assertTrue(service.isPathMonitored(nonNormalized));
}
@Test
void registerPath_successful_updatesInternalMapsAndSets() throws Exception {
Path dir = tmp.resolve("regdir");
Files.createDirectories(dir);
boolean registered = service.registerPath(dir, 55L);
assertTrue(registered);
Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap");
pathToLibraryField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
assertEquals(55L, map.get(dir));
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
assertTrue(monitored.contains(dir));
Field keysField = MonitoringService.class.getDeclaredField("registeredWatchKeys");
keysField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path, WatchKey> keys = (Map<Path, WatchKey>) keysField.get(service);
assertTrue(keys.containsKey(dir));
}
}
@@ -3,32 +3,29 @@ package com.adityachandel.booklore.service.upload;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.AdditionalFileMapperImpl;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.mapper.AdditionalFileMapper;
import com.adityachandel.booklore.model.dto.AdditionalFile;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.FileProcessStatus;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.file.FileMovingHelper;
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@@ -39,7 +36,7 @@ import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
class FileUploadServiceTest {
@@ -54,17 +51,15 @@ class FileUploadServiceTest {
@Mock
BookAdditionalFileRepository bookAdditionalFileRepository;
@Mock
BookFileProcessorRegistry processorRegistry;
@Mock
NotificationService notificationService;
@Mock
AppSettingService appSettingService;
@Mock
PdfMetadataExtractor pdfMetadataExtractor;
@Mock
EpubMetadataExtractor epubMetadataExtractor;
@Mock
MonitoringService monitoringService;
FileMovingHelper fileMovingHelper;
@Mock
AdditionalFileMapper additionalFileMapper;
AppProperties appProperties;
FileUploadService service;
@@ -80,17 +75,11 @@ class FileUploadServiceTest {
settings.setUploadPattern("{currentFilename}");
when(appSettingService.getAppSettings()).thenReturn(settings);
var additionalFilesMapper = new AdditionalFileMapperImpl();
service = new FileUploadService(
libraryRepository, bookRepository, bookAdditionalFileRepository,
processorRegistry, notificationService,
appSettingService, appProperties, pdfMetadataExtractor,
epubMetadataExtractor, additionalFilesMapper, monitoringService
epubMetadataExtractor, additionalFileMapper, fileMovingHelper
);
ReflectionTestUtils.setField(service, "userId", "0");
ReflectionTestUtils.setField(service, "groupId", "0");
}
@Test
@@ -185,6 +174,7 @@ class FileUploadServiceTest {
path.setPath(tempDir.toString());
lib.setLibraryPaths(List.of(path));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(lib));
when(fileMovingHelper.getFileNamingPattern(lib)).thenReturn("{currentFilename}");
assertThatExceptionOfType(APIException.class)
.isThrownBy(() -> service.uploadFile(file, 1L, 1L))
@@ -206,22 +196,76 @@ class FileUploadServiceTest {
path.setPath(tempDir.toString());
lib.setLibraryPaths(List.of(path));
when(libraryRepository.findById(7L)).thenReturn(Optional.of(lib));
when(fileMovingHelper.getFileNamingPattern(lib)).thenReturn("{currentFilename}");
BookFileProcessor proc = mock(BookFileProcessor.class);
FileProcessResult fileProcessResult = FileProcessResult.builder()
.book(Book.builder().build())
.status(FileProcessStatus.NEW)
.build();
service.uploadFile(file, 7L, 2L);
when(processorRegistry.getProcessorOrThrow(BookFileType.CBX)).thenReturn(proc);
when(proc.processFile(any())).thenReturn(fileProcessResult);
Book result = service.uploadFile(file, 7L, 2L);
assertThat(result).isSameAs(fileProcessResult.getBook());
Path moved = tempDir.resolve("book.cbz");
assertThat(Files.exists(moved)).isTrue();
verify(notificationService).sendMessage(eq(Topic.BOOK_ADD), same(fileProcessResult.getBook()));
verifyNoInteractions(pdfMetadataExtractor, epubMetadataExtractor);
}
@Test
void uploadAdditionalFile_successful_and_saves_entity() throws Exception {
long bookId = 5L;
MockMultipartFile file = new MockMultipartFile("file", "add.pdf", "application/pdf", "payload".getBytes());
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setId(1L);
libPath.setPath(tempDir.toString());
BookEntity book = new BookEntity();
book.setId(bookId);
book.setLibraryPath(libPath);
book.setFileSubPath(".");
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
try (MockedStatic<FileFingerprint> fp = mockStatic(FileFingerprint.class)) {
fp.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash-123");
when(bookAdditionalFileRepository.findByAltFormatCurrentHash("hash-123")).thenReturn(Optional.empty());
when(bookAdditionalFileRepository.save(any(BookAdditionalFileEntity.class))).thenAnswer(inv -> {
BookAdditionalFileEntity e = inv.getArgument(0);
e.setId(99L);
return e;
});
AdditionalFile dto = mock(AdditionalFile.class);
when(additionalFileMapper.toAdditionalFile(any(BookAdditionalFileEntity.class))).thenReturn(dto);
AdditionalFile result = service.uploadAdditionalFile(bookId, file, AdditionalFileType.ALTERNATIVE_FORMAT, "desc");
assertThat(result).isEqualTo(dto);
verify(bookAdditionalFileRepository).save(any(BookAdditionalFileEntity.class));
verify(additionalFileMapper).toAdditionalFile(any(BookAdditionalFileEntity.class));
}
}
@Test
void uploadAdditionalFile_duplicate_alternative_format_throws() {
long bookId = 6L;
MockMultipartFile file = new MockMultipartFile("file", "alt.pdf", "application/pdf", "payload".getBytes());
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setId(2L);
libPath.setPath(tempDir.toString());
BookEntity book = new BookEntity();
book.setId(bookId);
book.setLibraryPath(libPath);
book.setFileSubPath(".");
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
try (MockedStatic<FileFingerprint> fp = mockStatic(FileFingerprint.class)) {
fp.when(() -> FileFingerprint.generateHash(any())).thenReturn("dup-hash");
BookAdditionalFileEntity existing = new BookAdditionalFileEntity();
existing.setId(1L);
when(bookAdditionalFileRepository.findByAltFormatCurrentHash("dup-hash")).thenReturn(Optional.of(existing));
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> service.uploadAdditionalFile(bookId, file, AdditionalFileType.ALTERNATIVE_FORMAT, null));
}
}
}