diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/FileMoveController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/FileMoveController.java index a59f5eda3..b04621d5c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/FileMoveController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/FileMoveController.java @@ -18,7 +18,7 @@ public class FileMoveController { @PostMapping("/move") public ResponseEntity moveFiles(@RequestBody FileMoveRequest request) { - fileMoveService.moveFiles(request); + fileMoveService.bulkMoveFiles(request); return ResponseEntity.ok().build(); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/FileMoveResult.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/FileMoveResult.java new file mode 100644 index 000000000..edc4d7d71 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/FileMoveResult.java @@ -0,0 +1,12 @@ +package com.adityachandel.booklore.model.dto; + +import lombok.Builder; +import lombok.Data; + +@Builder +@Data +public class FileMoveResult { + private boolean moved; + private String newFileName; + private String newFileSubPath; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FileMoveRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FileMoveRequest.java index 52a4d5e3c..2e3d2233c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FileMoveRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FileMoveRequest.java @@ -14,5 +14,6 @@ public class FileMoveRequest { public static class Move { private Long bookId; private Long targetLibraryId; + private Long targetLibraryPathId; } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java index 83c7676e8..521e7aa25 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java @@ -27,7 +27,7 @@ public class LibraryEntity { @Convert(converter = SortConverter.class) private Sort sort; - @OneToMany(mappedBy = "library", cascade = CascadeType.MERGE, orphanRemoval = true) + @OneToMany(mappedBy = "library", orphanRemoval = true) private List bookEntities; @OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java index 66c7faf6f..51fc827fe 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java @@ -7,6 +7,7 @@ import lombok.Getter; @AllArgsConstructor public enum Topic { BOOK_ADD("/queue/book-add"), + BOOK_UPDATE("/queue/book-update"), BOOKS_REMOVE("/queue/books-remove"), BOOK_METADATA_UPDATE("/queue/book-metadata-update"), BOOK_METADATA_BATCH_UPDATE("/queue/book-metadata-batch-update"), diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java index b41065f30..c9f00190a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java @@ -1,11 +1,13 @@ package com.adityachandel.booklore.repository; import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; import jakarta.transaction.Transactional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.*; import org.springframework.data.repository.query.Param; +import org.springframework.security.core.parameters.P; import org.springframework.stereotype.Repository; import java.time.Instant; @@ -112,39 +114,24 @@ public interface BookRepository extends JpaRepository, JpaSpec """) Page searchByMetadata(@Param("text") String text, Pageable pageable); - @Query(value = """ - SELECT DISTINCT b FROM BookEntity b - LEFT JOIN b.metadata m - LEFT JOIN m.authors a - WHERE (b.deleted IS NULL OR b.deleted = false) - AND b.library.id IN :libraryIds - AND ( - LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%')) - OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%')) - OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%')) - ) - """, - countQuery = """ - SELECT COUNT(DISTINCT b.id) FROM BookEntity b - LEFT JOIN b.metadata m - LEFT JOIN m.authors a - WHERE (b.deleted IS NULL OR b.deleted = false) - AND b.library.id IN :libraryIds - AND ( - LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%')) - OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%')) - OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%')) - ) - """) - Page searchByMetadataAndLibraryIds(@Param("text") String text, @Param("libraryIds") Collection libraryIds, Pageable pageable); - @Modifying @Transactional @Query("DELETE FROM BookEntity b WHERE b.deletedAt IS NOT NULL AND b.deletedAt < :cutoff") int deleteAllByDeletedAtBefore(Instant cutoff); @Modifying - @Transactional - @Query("UPDATE BookEntity b SET b.library.id = :libraryId WHERE b.id = :bookId") - void updateLibraryId(@Param("bookId") Long bookId, @Param("libraryId") Long libraryId); + @Query(""" + UPDATE BookEntity b + SET b.fileSubPath = :fileSubPath, + b.fileName = :fileName, + b.library.id = :libraryId, + b.libraryPath = :libraryPath + WHERE b.id = :bookId + """) + void updateFileAndLibrary( + @Param("bookId") Long bookId, + @Param("fileSubPath") String fileSubPath, + @Param("fileName") String fileName, + @Param("libraryId") Long libraryId, + @Param("libraryPath") LibraryPathEntity libraryPath); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveHelper.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveHelper.java new file mode 100644 index 000000000..14bc7af31 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveHelper.java @@ -0,0 +1,145 @@ +package com.adityachandel.booklore.service.file; + +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.service.appsettings.AppSettingService; +import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; +import com.adityachandel.booklore.util.PathPatternResolver; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +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.HashSet; +import java.util.Set; + +@Slf4j +@Component +@AllArgsConstructor +public class FileMoveHelper { + + private final MonitoringRegistrationService monitoringRegistrationService; + private final AppSettingService appSettingService; + + 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); + } + + public String extractSubPath(Path filePath, LibraryPathEntity libraryPathEntity) { + Path libraryRoot = Paths.get(libraryPathEntity.getPath()).toAbsolutePath().normalize(); + Path parentDir = filePath.getParent().toAbsolutePath().normalize(); + Path relativeSubPath = libraryRoot.relativize(parentDir); + return relativeSubPath.toString().replace('\\', '/'); + } + + public void unregisterLibrary(Long libraryId) { + monitoringRegistrationService.unregisterLibrary(libraryId); + } + + public void registerLibraryPaths(Long libraryId, Path libraryRoot) { + monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot); + } + + 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()); + } + if (pattern.endsWith("/") || pattern.endsWith("\\")) { + pattern += "{currentFilename}"; + } + return pattern; + } + + public Path generateNewFilePath(BookEntity book, LibraryPathEntity libraryPathEntity, String pattern) { + String newRelativePathStr = PathPatternResolver.resolvePattern(book, pattern); + if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) { + newRelativePathStr = newRelativePathStr.substring(1); + } + String path = libraryPathEntity.getPath(); + return Paths.get(path, newRelativePathStr); + } + + public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set libraryRoots) throws IOException { + Set ignoredFilenames = Set.of(".DS_Store", "Thumbs.db"); + currentDir = currentDir.toAbsolutePath().normalize(); + Set normalizedRoots = new HashSet<>(); + for (Path root : libraryRoots) { + normalizedRoots.add(root.toAbsolutePath().normalize()); + } + while (currentDir != null) { + if (isLibraryRoot(currentDir, normalizedRoots)) { + 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 { + break; + } + } + } + + private boolean isLibraryRoot(Path currentDir, Set 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 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); + } + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java index d078b08de..89e9740f5 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java @@ -1,182 +1,155 @@ package com.adityachandel.booklore.service.file; import com.adityachandel.booklore.mapper.BookMapper; -import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.mapper.LibraryMapper; +import com.adityachandel.booklore.model.dto.FileMoveResult; import com.adityachandel.booklore.model.dto.request.FileMoveRequest; 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.websocket.Topic; import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.BookQueryService; +import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.service.NotificationService; -import com.adityachandel.booklore.util.PathPatternResolver; +import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; +import jakarta.persistence.EntityManager; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; -import static com.adityachandel.booklore.model.enums.PermissionType.ADMIN; -import static com.adityachandel.booklore.model.enums.PermissionType.MANIPULATE_LIBRARY; - -@Slf4j -@Service @AllArgsConstructor +@Service +@Slf4j public class FileMoveService { - private static final int BATCH_SIZE = 100; - - private final BookQueryService bookQueryService; private final BookRepository bookRepository; + private final LibraryRepository libraryRepository; + private final FileMoveHelper fileMoveHelper; + private final MonitoringRegistrationService monitoringRegistrationService; + private final LibraryMapper libraryMapper; private final BookMapper bookMapper; private final NotificationService notificationService; - private final UnifiedFileMoveService unifiedFileMoveService; + private final EntityManager entityManager; + @Transactional - public void moveFiles(FileMoveRequest request) { - List bookIds = request.getBookIds().stream().toList(); - List moves = request.getMoves() != null ? request.getMoves() : List.of(); + public void bulkMoveFiles(FileMoveRequest request) { + List moves = request.getMoves(); + Set targetLibraryIds = moves.stream().map(FileMoveRequest.Move::getTargetLibraryId).collect(Collectors.toSet()); + Set sourceLibraryIds = new HashSet<>(); + monitoringRegistrationService.unregisterLibraries(targetLibraryIds); - log.info("Moving {} books with {} specific moves in batches of {}", bookIds.size(), moves.size(), BATCH_SIZE); + for (FileMoveRequest.Move move : moves) { + Long bookId = move.getBookId(); + Long targetLibraryId = move.getTargetLibraryId(); + Long targetLibraryPathId = move.getTargetLibraryPathId(); - Map bookToTargetLibraryMap = moves.stream() - .collect(Collectors.toMap( - FileMoveRequest.Move::getBookId, - FileMoveRequest.Move::getTargetLibraryId - )); - - Map> libraryRemovals = new HashMap<>(); - Map> libraryAdditions = new HashMap<>(); - List allUpdatedBooks = new ArrayList<>(); - int totalProcessed = 0; - int offset = 0; - - while (offset < bookIds.size()) { - log.info("Processing batch {}/{}", (offset / BATCH_SIZE) + 1, (bookIds.size() + BATCH_SIZE - 1) / BATCH_SIZE); - - List batchBookIds = bookIds.subList(offset, Math.min(offset + BATCH_SIZE, bookIds.size())); - Set batchBookIdSet = new HashSet<>(batchBookIds); - - List batchBooks = bookQueryService.findWithMetadataByIdsWithPagination(batchBookIdSet, offset, BATCH_SIZE); - - if (batchBooks.isEmpty()) { - log.info("No more books at offset {}", offset); - break; - } - - List batchUpdatedBooks = processBookChunk(batchBooks, bookToTargetLibraryMap, libraryRemovals, libraryAdditions); - 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); - sendCrossLibraryMoveNotifications(libraryRemovals, libraryAdditions); - - } - - public String generatePathFromPattern(BookEntity book, String pattern) { - return PathPatternResolver.resolvePattern(book, pattern); - } - - private List processBookChunk(List books, Map bookToTargetLibraryMap, Map> libraryRemovals, Map> libraryAdditions) { - List updatedBooks = new ArrayList<>(); - - Map originalLibraryIds = new HashMap<>(); - for (BookEntity book : books) { - if (book.getLibraryPath() != null && book.getLibraryPath().getLibrary() != null) { - originalLibraryIds.put(book.getId(), book.getLibraryPath().getLibrary().getId()); - } - } - - unifiedFileMoveService.moveBatchBookFiles(books, bookToTargetLibraryMap, new UnifiedFileMoveService.BatchMoveCallback() { - @Override - public void onBookMoved(BookEntity book) { - Long targetLibraryId = bookToTargetLibraryMap.get(book.getId()); - Long originalSourceLibraryId = originalLibraryIds.get(book.getId()); - - log.debug("Processing moved book {}: targetLibraryId={}, originalSourceLibraryId={}", book.getId(), targetLibraryId, originalSourceLibraryId); - - if (targetLibraryId != null && originalSourceLibraryId != null && !targetLibraryId.equals(originalSourceLibraryId)) { - log.info("Cross-library move detected for book {}: {} -> {}", book.getId(), originalSourceLibraryId, targetLibraryId); - - Book bookDtoForRemoval = bookMapper.toBookWithDescription(book, false); - bookDtoForRemoval.setLibraryId(originalSourceLibraryId); - libraryRemovals.computeIfAbsent(originalSourceLibraryId, k -> new ArrayList<>()).add(bookDtoForRemoval); - log.debug("Added book {} to removal list for library {}", book.getId(), originalSourceLibraryId); - - bookRepository.updateLibraryId(book.getId(), targetLibraryId); - log.debug("Updated library_id for book {} to {}", book.getId(), targetLibraryId); - - BookEntity savedBook = bookRepository.saveAndFlush(book); - - Book updatedBookDto = bookMapper.toBookWithDescription(savedBook, false); - updatedBookDto.setLibraryId(targetLibraryId); - libraryAdditions.computeIfAbsent(targetLibraryId, k -> new ArrayList<>()).add(updatedBookDto); - log.debug("Added book {} to addition list for library {} with libraryId {}", book.getId(), targetLibraryId, updatedBookDto.getLibraryId()); - - updatedBooks.add(updatedBookDto); - } else { - log.debug("Same library move for book {} or no target specified. Target: {}, Original: {}", book.getId(), targetLibraryId, originalSourceLibraryId); - BookEntity savedBook = bookRepository.save(book); - updatedBooks.add(bookMapper.toBook(savedBook)); - } - } - - @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); - } - }); - - log.info("Processed {} books, {} library removals tracked, {} library additions tracked", updatedBooks.size(), libraryRemovals.size(), libraryAdditions.size()); - - return updatedBooks; - } - - private void sendUpdateNotifications(List updatedBooks) { - if (!updatedBooks.isEmpty()) { - notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_UPDATE, updatedBooks); - } - } - - private void sendCrossLibraryMoveNotifications(Map> libraryRemovals, Map> libraryAdditions) { - log.info("Sending cross-library move notifications: {} removals, {} additions", - libraryRemovals.size(), libraryAdditions.size()); - - for (Map.Entry> entry : libraryRemovals.entrySet()) { - List removedBookIds = entry.getValue().stream() - .map(Book::getId) - .collect(Collectors.toList()); - - log.info("Notifying removal of {} books from library {}: {}", removedBookIds.size(), entry.getKey(), removedBookIds); try { - notificationService.sendMessageToPermissions(Topic.BOOKS_REMOVE, removedBookIds, Set.of(ADMIN, MANIPULATE_LIBRARY)); - log.info("Successfully sent removal notification for library {}", entry.getKey()); - } catch (Exception e) { - log.error("Failed to send removal notification for library {}: {}", entry.getKey(), e.getMessage(), e); - } - } - - for (Map.Entry> entry : libraryAdditions.entrySet()) { - List addedBooks = entry.getValue(); - - log.info("Notifying addition of {} books to library {}", addedBooks.size(), entry.getKey()); - try { - for (Book book : addedBooks) { - log.debug("Sending BOOK_ADD notification for book {} to library {}", book.getId(), entry.getKey()); - notificationService.sendMessageToPermissions(Topic.BOOK_ADD, book, Set.of(ADMIN, MANIPULATE_LIBRARY)); + Optional optionalBook = bookRepository.findById(bookId); + Optional optionalLibrary = libraryRepository.findById(targetLibraryId); + if (optionalBook.isEmpty() || optionalLibrary.isEmpty()) { + continue; } - log.info("Successfully sent {} addition notifications for library {}", addedBooks.size(), entry.getKey()); + BookEntity bookEntity = optionalBook.get(); + LibraryEntity targetLibrary = optionalLibrary.get(); + + Optional optionalLibraryPathEntity = targetLibrary.getLibraryPaths().stream().filter(l -> Objects.equals(l.getId(), targetLibraryPathId)).findFirst(); + if (optionalLibraryPathEntity.isEmpty()) { + continue; + } + LibraryPathEntity libraryPathEntity = optionalLibraryPathEntity.get(); + + LibraryEntity sourceLibrary = bookEntity.getLibrary(); + if (sourceLibrary.getId().equals(targetLibrary.getId())) { + continue; + } + if (!sourceLibraryIds.contains(sourceLibrary.getId())) { + monitoringRegistrationService.unregisterLibraries(Collections.singleton(sourceLibrary.getId())); + sourceLibraryIds.add(sourceLibrary.getId()); + } + Path currentFilePath = bookEntity.getFullFilePath(); + String pattern = fileMoveHelper.getFileNamingPattern(targetLibrary); + Path newFilePath = fileMoveHelper.generateNewFilePath(bookEntity, libraryPathEntity, pattern); + if (currentFilePath.equals(newFilePath)) { + continue; + } + fileMoveHelper.moveFile(currentFilePath, newFilePath); + + String newFileName = newFilePath.getFileName().toString(); + String newFileSubPath = fileMoveHelper.extractSubPath(newFilePath, libraryPathEntity); + bookRepository.updateFileAndLibrary(bookEntity.getId(), newFileSubPath, newFileName, targetLibrary.getId(), libraryPathEntity); + + Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize(); + fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot)); + + entityManager.clear(); + + BookEntity fresh = bookRepository.findById(bookId).orElseThrow(); + + notificationService.sendMessage(Topic.BOOK_UPDATE, bookMapper.toBookWithDescription(fresh, false)); + } catch (Exception e) { - log.error("Failed to send addition notifications for library {}: {}", entry.getKey(), e.getMessage(), e); + log.error("Error moving file for book ID {}: {}", bookId, e.getMessage(), e); } } + + for (Long libraryId : targetLibraryIds) { + Optional optionalLibrary = libraryRepository.findById(libraryId); + optionalLibrary.ifPresent(library -> { + monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)); + }); + } + for (Long libraryId : sourceLibraryIds) { + Optional optionalLibrary = libraryRepository.findById(libraryId); + optionalLibrary.ifPresent(library -> { + monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)); + }); + } + } + + @Transactional + public FileMoveResult moveSingleFile(BookEntity bookEntity) { + + Long libraryId = bookEntity.getLibraryPath().getLibrary().getId(); + Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize(); + + try { + String pattern = fileMoveHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary()); + Path currentFilePath = bookEntity.getFullFilePath(); + Path expectedFilePath = fileMoveHelper.generateNewFilePath(bookEntity, bookEntity.getLibraryPath(), pattern); + + if (currentFilePath.equals(expectedFilePath)) { + return FileMoveResult.builder().moved(false).build(); + } + + log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, expectedFilePath); + + fileMoveHelper.unregisterLibrary(libraryId); + + fileMoveHelper.moveFile(currentFilePath, expectedFilePath); + + fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot)); + + String newFileName = expectedFilePath.getFileName().toString(); + String newFileSubPath = fileMoveHelper.extractSubPath(expectedFilePath, bookEntity.getLibraryPath()); + + return FileMoveResult.builder() + .moved(true) + .newFileName(newFileName) + .newFileSubPath(newFileSubPath) + .build(); + } catch (Exception e) { + log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e); + } finally { + fileMoveHelper.registerLibraryPaths(libraryId, libraryRoot); + } + + return FileMoveResult.builder().moved(false).build(); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMovingHelper.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMovingHelper.java index c8616fb34..2fcd23297 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMovingHelper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMovingHelper.java @@ -1,12 +1,7 @@ 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.model.entity.LibraryPathEntity; -import com.adityachandel.booklore.repository.BookAdditionalFileRepository; -import com.adityachandel.booklore.repository.LibraryPathRepository; import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.util.PathPatternResolver; import lombok.AllArgsConstructor; @@ -14,51 +9,17 @@ 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; - private final LibraryPathRepository libraryPathRepository; - /** - * 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()) { @@ -73,340 +34,14 @@ public class FileMovingHelper { 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 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 libraryRoots) throws IOException { - Set ignoredFilenames = Set.of(".DS_Store", "Thumbs.db"); - currentDir = currentDir.toAbsolutePath().normalize(); - - Set 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; - } - } - } - - /** - * Moves a book file to a different library with the target library's naming pattern - */ - public boolean moveBookFileToLibrary(BookEntity book, LibraryEntity targetLibrary) throws IOException { - if (!hasRequiredPathComponents(book)) { - log.error("Missing required path components for book id {}. Cannot move to different library.", book.getId()); - return false; - } - - Path oldFilePath = book.getFullFilePath(); - String pattern = getFileNamingPattern(targetLibrary); - - // Generate new file path in target library - Path newFilePath = generateNewFilePathForLibrary(book, targetLibrary, pattern); - - if (oldFilePath.equals(newFilePath)) { - log.debug("Source and destination paths are identical for book id {}. Skipping cross-library move.", book.getId()); - return false; - } - - moveBookFileAndUpdatePathsForLibrary(book, oldFilePath, newFilePath, targetLibrary); - return true; - } - - /** - * Generates the new file path for a book in a different library - */ - public Path generateNewFilePathForLibrary(BookEntity book, LibraryEntity targetLibrary, String pattern) { - String newRelativePathStr = PathPatternResolver.resolvePattern(book, pattern); - if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) { - newRelativePathStr = newRelativePathStr.substring(1); - } - - Path targetLibraryRoot = getLibraryRootPath(targetLibrary); - return targetLibraryRoot.resolve(newRelativePathStr).normalize(); - } - - /** - * Gets the root path for a library (uses the first library path) - */ - private Path getLibraryRootPath(LibraryEntity library) { - if (library.getLibraryPaths() == null || library.getLibraryPaths().isEmpty()) { - throw new RuntimeException("Library " + library.getName() + " has no paths configured"); - } - return Paths.get(library.getLibraryPaths().getFirst().getPath()).toAbsolutePath().normalize(); - } - - 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 moveBookFileAndUpdatePathsForLibrary(BookEntity book, Path oldFilePath, Path newFilePath, LibraryEntity targetLibrary) throws IOException { - moveFile(oldFilePath, newFilePath); - updateBookPathsForLibrary(book, newFilePath, targetLibrary); - - // Clean up empty directories in source library - // IMPORTANT: We need to collect ALL library roots to avoid deleting any library root directory - try { - Set allLibraryRoots = getAllLibraryRoots(); - deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), allLibraryRoots); - } catch (IOException e) { - log.warn("Failed to clean up empty directories after moving book ID {}: {}", book.getId(), e.getMessage()); - } - } - - /** - * Gets all library root paths from all libraries to ensure we never delete any library root - */ - private Set getAllLibraryRoots() { - Set allRoots = new HashSet<>(); - try { - // Get all libraries and collect their root paths - libraryPathRepository.findAll().forEach(libraryPath -> { - try { - Path rootPath = Paths.get(libraryPath.getPath()).toAbsolutePath().normalize(); - allRoots.add(rootPath); - log.debug("Added library root to protection list: {}", rootPath); - } catch (Exception e) { - log.warn("Failed to process library path {}: {}", libraryPath.getPath(), e.getMessage()); - } - }); - } catch (Exception e) { - log.error("Failed to collect all library roots: {}", e.getMessage()); - } - return allRoots; - } - - private void updateBookPathsForLibrary(BookEntity book, Path newFilePath, LibraryEntity targetLibrary) { - String newFileName = newFilePath.getFileName().toString(); - Path targetLibraryRoot = getLibraryRootPath(targetLibrary); - Path newRelativeSubPath = targetLibraryRoot.relativize(newFilePath.getParent()); - String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/'); - - // Find or create the appropriate LibraryPathEntity for the target library - String targetLibraryPath = targetLibrary.getLibraryPaths().getFirst().getPath(); - LibraryPathEntity targetLibraryPathEntity = libraryPathRepository - .findByLibraryIdAndPath(targetLibrary.getId(), targetLibraryPath) - .orElseThrow(() -> new RuntimeException("LibraryPath not found for library " + targetLibrary.getId() + " and path " + targetLibraryPath)); - - // Update only the path-related fields, avoid touching library entity relationships - // that might trigger cascade operations - book.setLibraryPath(targetLibraryPathEntity); // This should update library_path_id - book.setFileSubPath(newFileSubPath); - book.setFileName(newFileName); - - // DO NOT set book.setLibrary(targetLibrary) to avoid cascade issues - log.debug("Updated book {} path references: libraryPathId={}, newPath={}", - book.getId(), targetLibraryPathEntity.getId(), newFilePath); - } - - private void moveAdditionalFile(BookEntity book, BookAdditionalFileEntity additionalFile, String pattern, Map 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 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 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 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); - } + 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); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/MonitoredFileOperationService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/MonitoredFileOperationService.java deleted file mode 100644 index ccff11ec5..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/MonitoredFileOperationService.java +++ /dev/null @@ -1,147 +0,0 @@ -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 the return type of the operation - */ - public void executeWithMonitoringSuspended(Path sourcePath, Path targetPath, Long libraryId, Supplier 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 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.debug("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 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 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"); - } -} - diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/UnifiedFileMoveService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/UnifiedFileMoveService.java deleted file mode 100644 index 878125a34..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/UnifiedFileMoveService.java +++ /dev/null @@ -1,264 +0,0 @@ -package com.adityachandel.booklore.service.file; - -import com.adityachandel.booklore.model.entity.BookEntity; -import com.adityachandel.booklore.model.entity.LibraryEntity; -import com.adityachandel.booklore.repository.LibraryRepository; -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; - private final LibraryRepository libraryRepository; - - /** - * 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(); - Path expectedFilePath = fileMovingHelper.generateNewFilePath(bookEntity, pattern); - - // Check if current path differs from expected 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); - - Long libraryId = bookEntity.getLibraryPath().getLibrary().getId(); - Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()) - .toAbsolutePath().normalize(); - - // unregister the entire library to suppress all watch events during the move - monitoringRegistrationService.unregisterLibrary(libraryId); - - try { - monitoredFileOperationService.executeWithMonitoringSuspended( - currentFilePath, expectedFilePath, libraryId, () -> { - try { - boolean moved = fileMovingHelper.moveBookFileIfNeeded(bookEntity, pattern); - if (moved) { - log.info("Successfully moved file for book ID {} from {} to {}", - 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); - } - } - ); - } finally { - // re-register all folders under the library after the move - monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot); - } - } - - /** - * Moves multiple book files in batches with cross-library support and library-level monitoring protection. - * Used for bulk file operations where many files need to be moved, potentially across libraries. - */ - public void moveBatchBookFiles(List books, Map bookToTargetLibraryMap, BatchMoveCallback callback) { - if (books.isEmpty()) { - log.debug("No books to move"); - return; - } - - Set allLibraryIds = new HashSet<>(); - Map> 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; - - // Source library - Long sourceLibraryId = book.getLibraryPath().getLibrary().getId(); - Path sourceLibraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize(); - libraryToRootsMap.computeIfAbsent(sourceLibraryId, k -> new HashSet<>()).add(sourceLibraryRoot); - allLibraryIds.add(sourceLibraryId); - - // Target library (if different) - Long targetLibraryId = bookToTargetLibraryMap.get(book.getId()); - if (targetLibraryId != null && !targetLibraryId.equals(sourceLibraryId)) { - LibraryEntity targetLibrary = libraryRepository.findById(targetLibraryId).orElse(null); - if (targetLibrary != null && targetLibrary.getLibraryPaths() != null && !targetLibrary.getLibraryPaths().isEmpty()) { - Path targetLibraryRoot = Paths.get(targetLibrary.getLibraryPaths().getFirst().getPath()).toAbsolutePath().normalize(); - libraryToRootsMap.computeIfAbsent(targetLibraryId, k -> new HashSet<>()).add(targetLibraryRoot); - allLibraryIds.add(targetLibraryId); - } - } - } - - // Unregister all affected libraries for batch operation - unregisterLibrariesBatch(libraryToRootsMap); - - try { - // Small delay to let any pending file watcher events settle - try { - Thread.sleep(500); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - log.warn("Interrupted during pre-move delay"); - } - - // Process each book - for (BookEntity book : books) { - if (book.getMetadata() == null) continue; - 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 { - Long targetLibraryId = bookToTargetLibraryMap.get(book.getId()); - boolean moved = false; - - if (targetLibraryId != null && !targetLibraryId.equals(book.getLibraryPath().getLibrary().getId())) { - // Cross-library move - LibraryEntity targetLibrary = libraryRepository.findById(targetLibraryId).orElse(null); - if (targetLibrary != null) { - moved = fileMovingHelper.moveBookFileToLibrary(book, targetLibrary); - if (moved) { - log.debug("Book {} moved to library {} successfully", book.getId(), targetLibraryId); - } - } else { - log.error("Target library {} not found for book {}", targetLibraryId, book.getId()); - callback.onBookMoveFailed(book, new RuntimeException("Target library not found")); - continue; - } - } else { - // Same library move (existing functionality) - String pattern = fileMovingHelper.getFileNamingPattern(book.getLibraryPath().getLibrary()); - moved = fileMovingHelper.moveBookFileIfNeeded(book, pattern); - if (moved) { - log.debug("Book {} moved within library successfully", book.getId()); - } - } - - if (moved) { - callback.onBookMoved(book); - - // Move additional files if any - if (book.getAdditionalFiles() != null && !book.getAdditionalFiles().isEmpty()) { - String pattern = fileMovingHelper.getFileNamingPattern(book.getLibraryPath().getLibrary()); - fileMovingHelper.moveAdditionalFiles(book, pattern); - } - } - } catch (IOException e) { - log.error("Move failed for book {}: {}", book.getId(), e.getMessage(), e); - callback.onBookMoveFailed(book, e); - } - } - - // Longer delay to let filesystem operations settle before re-registering monitoring - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - log.warn("Interrupted during batch move delay"); - } - - } finally { - // Re-register all affected libraries - registerLibrariesBatch(libraryToRootsMap); - } - } - - // Overloaded method for backward compatibility with same-library moves - public void moveBatchBookFiles(List books, BatchMoveCallback callback) { - moveBatchBookFiles(books, new HashMap<>(), callback); - } - - private void unregisterLibrariesBatch(Map> libraryToRootsMap) { - log.debug("Unregistering {} libraries for batch move", libraryToRootsMap.size()); - - for (Map.Entry> entry : libraryToRootsMap.entrySet()) { - Long libraryId = entry.getKey(); - try { - monitoringRegistrationService.unregisterLibrary(libraryId); - log.debug("Unregistered library {}", libraryId); - } catch (Exception e) { - log.warn("Failed to unregister library {}: {}", libraryId, e.getMessage()); - } - } - } - - private void registerLibrariesBatch(Map> libraryToRootsMap) { - log.debug("Re-registering {} libraries after batch move", libraryToRootsMap.size()); - - for (Map.Entry> entry : libraryToRootsMap.entrySet()) { - Long libraryId = entry.getKey(); - Set libraryRoots = entry.getValue(); - - // Verify library still exists before re-registering - try { - LibraryEntity library = libraryRepository.findById(libraryId).orElse(null); - if (library == null) { - log.warn("Library {} no longer exists, skipping re-registration", libraryId); - continue; - } - - for (Path libraryRoot : libraryRoots) { - if (Files.exists(libraryRoot) && Files.isDirectory(libraryRoot)) { - try { - monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot); - log.debug("Re-registered library {} at {}", libraryId, libraryRoot); - } catch (Exception e) { - log.warn("Failed to re-register library {} at {}: {}", libraryId, libraryRoot, e.getMessage()); - } - } else { - log.debug("Library root {} no longer exists or is not a directory, skipping re-registration", libraryRoot); - } - } - } catch (Exception e) { - log.error("Error verifying library {} during re-registration: {}", libraryId, e.getMessage()); - } - } - } - - /** - * Callback interface for batch move operations - */ - public interface BatchMoveCallback { - void onBookMoved(BookEntity book); - - void onBookMoveFailed(BookEntity book, Exception error); - } -} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java index cf070fe19..5cc26f600 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java @@ -4,6 +4,7 @@ import com.adityachandel.booklore.model.MetadataClearFlags; import com.adityachandel.booklore.model.MetadataUpdateContext; import com.adityachandel.booklore.model.MetadataUpdateWrapper; import com.adityachandel.booklore.model.dto.BookMetadata; +import com.adityachandel.booklore.model.dto.FileMoveResult; import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.enums.BookFileType; @@ -15,7 +16,7 @@ import com.adityachandel.booklore.repository.MoodRepository; import com.adityachandel.booklore.repository.TagRepository; 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.file.FileMoveService; import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory; import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.MetadataChangeDetector; @@ -52,7 +53,7 @@ public class BookMetadataUpdater { private final AppSettingService appSettingService; private final MetadataWriterFactory metadataWriterFactory; private final BookReviewUpdateService bookReviewUpdateService; - private final UnifiedFileMoveService unifiedFileMoveService; + private final FileMoveService fileMoveService; @Transactional public void setBookMetadata(MetadataUpdateContext context) { @@ -117,34 +118,13 @@ public class BookMetadataUpdater { metadataWriterFactory.getWriter(bookType).ifPresent(writer -> { try { String thumbnailUrl = updateThumbnail ? 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, 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()); - } - + String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); bookEntity.setCurrentHash(newHash); } catch (Exception e) { log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage()); @@ -156,14 +136,18 @@ public class BookMetadataUpdater { boolean moveFilesToLibraryPattern = settings.isMoveFilesToLibraryPattern(); if (moveFilesToLibraryPattern) { try { - unifiedFileMoveService.moveSingleBookFile(bookEntity); + BookEntity book = metadata.getBook(); + FileMoveResult result = fileMoveService.moveSingleFile(book); + if (result.isMoved()) { + book.setFileName(result.getNewFileName()); + book.setFileSubPath(result.getNewFileSubPath()); + } } 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, MetadataReplaceMode replaceMode) { handleFieldUpdate(e.getTitleLocked(), clear.isTitle(), m.getTitle(), v -> e.setTitle(nullIfBlank(v)), e::getTitle, replaceMode); handleFieldUpdate(e.getSubtitleLocked(), clear.isSubtitle(), m.getSubtitle(), v -> e.setSubtitle(nullIfBlank(v)), e::getSubtitle, replaceMode); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java index c9b0a994a..0c8ea6fc9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java @@ -1,20 +1,13 @@ package com.adityachandel.booklore.service.metadata; +import com.adityachandel.booklore.model.dto.FileMoveResult; import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; -import com.adityachandel.booklore.model.entity.AuthorEntity; -import com.adityachandel.booklore.model.entity.BookMetadataEntity; -import com.adityachandel.booklore.model.entity.CategoryEntity; -import com.adityachandel.booklore.model.entity.MoodEntity; -import com.adityachandel.booklore.model.entity.TagEntity; +import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.MergeMetadataType; -import com.adityachandel.booklore.repository.AuthorRepository; -import com.adityachandel.booklore.repository.BookMetadataRepository; -import com.adityachandel.booklore.repository.CategoryRepository; -import com.adityachandel.booklore.repository.MoodRepository; -import com.adityachandel.booklore.repository.TagRepository; +import com.adityachandel.booklore.repository.*; import com.adityachandel.booklore.service.appsettings.AppSettingService; -import com.adityachandel.booklore.service.file.UnifiedFileMoveService; +import com.adityachandel.booklore.service.file.FileMoveService; import com.adityachandel.booklore.service.metadata.writer.MetadataWriter; import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory; import lombok.RequiredArgsConstructor; @@ -38,7 +31,8 @@ public class MetadataManagementService { private final BookMetadataRepository bookMetadataRepository; private final AppSettingService appSettingService; private final MetadataWriterFactory metadataWriterFactory; - private final UnifiedFileMoveService unifiedFileMoveService; + private final FileMoveService fileMoveService; + private final BookRepository bookRepository; @Transactional @@ -70,7 +64,13 @@ public class MetadataManagementService { }); if (moveFile) { - unifiedFileMoveService.moveSingleBookFile(metadata.getBook()); + BookEntity book = metadata.getBook(); + FileMoveResult result = fileMoveService.moveSingleFile(book); + if (result.isMoved()) { + book.setFileName(result.getNewFileName()); + book.setFileSubPath(result.getNewFileSubPath()); + bookRepository.saveAndFlush(book); + } } } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataRefreshService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataRefreshService.java index 6526b86f6..b321cdf8e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataRefreshService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataRefreshService.java @@ -282,7 +282,7 @@ public class MetadataRefreshService { .build()) .updateThumbnail(replaceCover) .mergeCategories(mergeCategories) - .replaceMode(MetadataReplaceMode.REPLACE_ALL) + .replaceMode(MetadataReplaceMode.REPLACE_MISSING) .build(); bookMetadataUpdater.setBookMetadata(context); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java index 951f54bcf..57c83e807 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java @@ -1,11 +1,14 @@ package com.adityachandel.booklore.service.monitoring; +import com.adityachandel.booklore.model.dto.Library; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Collection; +import java.util.Map; @Slf4j @Service @@ -14,55 +17,26 @@ 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 registerLibrary(Library library) { + monitoringService.registerLibrary(library); + } + 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; @@ -78,4 +52,18 @@ public class MonitoringRegistrationService { log.error("Failed to register library paths for libraryId {} at {}", libraryId, libraryRoot, e); } } + + public void registerLibraries(Map libraries) { + if (libraries == null || libraries.isEmpty()) { + return; + } + libraries.forEach(this::registerLibraryPaths); + } + + public void unregisterLibraries(Collection libraryIds) { + if (libraryIds == null || libraryIds.isEmpty()) { + return; + } + libraryIds.forEach(this::unregisterLibrary); + } } \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceTest.java deleted file mode 100644 index 483fe90a1..000000000 --- a/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceTest.java +++ /dev/null @@ -1,406 +0,0 @@ -package com.adityachandel.booklore; - -import com.adityachandel.booklore.model.entity.AuthorEntity; -import com.adityachandel.booklore.model.entity.BookEntity; -import com.adityachandel.booklore.model.entity.BookMetadataEntity; -import com.adityachandel.booklore.service.BookQueryService; -import com.adityachandel.booklore.service.file.FileMoveService; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -@ExtendWith(MockitoExtension.class) -class FileMoveServiceTest { - - @Mock - private BookQueryService bookQueryService; - - @InjectMocks - private FileMoveService fileMoveService; - - @Test - void testGeneratePathWithAllFieldsPresent() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Dune") - .authors(new HashSet<>(List.of(new AuthorEntity(1L, "Frank Herbert", new ArrayList<>()))) - ) - .publishedDate(LocalDate.of(1965, 8, 1)) - .seriesName("Dune Saga") - .seriesNumber(1.0F) - .language("English") - .publisher("Chilton Books") - .isbn13("9780441172719") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("Dune.epub") - .build(); - - String pattern = "/{series}/{seriesIndex} - {title} by {authors} ({year})"; - String result = fileMoveService.generatePathFromPattern(book, pattern); - - assertThat(result).isEqualTo("/Dune Saga/1 - Dune by Frank Herbert (1965).epub"); - } - - @Test - void testGeneratePathWithMissingMetadata() { - BookMetadataEntity metadata = BookMetadataEntity.builder().build(); - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("unknown.pdf") - .build(); - - String result = fileMoveService.generatePathFromPattern( - book, - "/{title}_{authors}_{year}_{series}_{seriesIndex}_{language}_{publisher}_{isbn}" - ); - assertThat(result).isEqualTo("/Untitled_______.pdf"); - } - - @Test - void testGeneratePathWithMultipleAuthors() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Good Omens") - .authors(new HashSet<>(List.of( - new AuthorEntity(1L, "Neil Gaiman", new ArrayList<>()), - new AuthorEntity(2L, "Terry Pratchett", new ArrayList<>()) - ))) - .publishedDate(LocalDate.of(1990, 5, 1)) - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("goodomens.mobi") - .build(); - - String pattern = "/{title} - {authors} ({year})"; - String result = fileMoveService.generatePathFromPattern(book, pattern); - - assertThat(result) - .isIn( - "/Good Omens - Neil Gaiman, Terry Pratchett (1990).mobi", - "/Good Omens - Terry Pratchett, Neil Gaiman (1990).mobi" - ); - } - - @Test - void testGeneratePathWithNoExtension() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("The Nameless Book") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("namelessbook") - .build(); - - String result = fileMoveService.generatePathFromPattern(book, "/{title}"); - assertThat(result).isEqualTo("/The Nameless Book"); - } - - @Test - void testGeneratePathWithIsbn10Fallback() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Test Book") - .isbn10("1234567890") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("testbook.pdf") - .build(); - - String result = fileMoveService.generatePathFromPattern(book, "/{isbn}"); - assertThat(result).isEqualTo("/1234567890.pdf"); - } - - @Test - void testGeneratePathWithEmptyFileName() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("No File") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName(null) - .build(); - - String result = fileMoveService.generatePathFromPattern(book, "/{title}"); - assertThat(result).isEqualTo("/No File"); - } - - @Test - void testGeneratePathWithEmptyPattern() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Empty Pattern Book") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("empty.txt") - .build(); - - String result = fileMoveService.generatePathFromPattern(book, ""); - assertThat(result).isEqualTo("empty.txt"); - } - - @Test - void testGeneratePathWithEmptyFileNameString() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Ghost File") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("") - .build(); - - String result = fileMoveService.generatePathFromPattern(book, "/{title}"); - assertThat(result).isEqualTo("/Ghost File"); - } - - @Test - void testGeneratePathWithUnknownPlaceholder() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Weird Format") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("weird.pdf") - .build(); - - String pattern = "/{title}/{unknown}"; - String result = fileMoveService.generatePathFromPattern(book, pattern); - - assertThat(result).isEqualTo("/Weird Format/{unknown}.pdf"); - } - - @Test - void testGeneratePathWithDotOnlyFilename() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Dotfile") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName(".gitignore") - .build(); - - String result = fileMoveService.generatePathFromPattern(book, "/{title}"); - assertThat(result).isEqualTo("/Dotfile.gitignore"); - } - - @Test - void testGeneratePathWithOptionalBlockIncluded() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Book Title") - .seriesName("Series") - .seriesNumber(3.5F) - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("book.pdf") - .build(); - - String pattern = "<{series}/><{seriesIndex}. >{title}"; - String result = fileMoveService.generatePathFromPattern(book, pattern); - - assertThat(result).isEqualTo("Series/3.5. Book Title.pdf"); - } - - @Test - void testGeneratePathWithOptionalBlockExcluded() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Book Title") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("book.pdf") - .build(); - - String pattern = "<{series}/><{seriesIndex}. >{title}"; - String result = fileMoveService.generatePathFromPattern(book, pattern); - - assertThat(result).isEqualTo("Book Title.pdf"); - } - - @Test - void testOptionalBlockWithPartialMissingData() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Solo") - .seriesName("Lone") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("solo.pdf") - .build(); - - String pattern = "<{series}/><{seriesIndex}. >{title}"; - String result = fileMoveService.generatePathFromPattern(book, pattern); - - assertThat(result).isEqualTo("Lone/Solo.pdf"); - } - - @Test - void testPatternWithMultipleOptionalBlocks() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Layered") - .seriesName("Stack") - .seriesNumber(3F) - .language("English") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("layered.epub") - .build(); - - String pattern = "<{series}/><{seriesIndex}. ><{language}/>{title}"; - String result = fileMoveService.generatePathFromPattern(book, pattern); - - assertThat(result).isEqualTo("Stack/3. English/Layered.epub"); - } - - @Test - void testIllegalCharactersAreRemoved() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Inva|id:Name*?") - .authors(new HashSet<>(List.of(new AuthorEntity(1L, "Au", new ArrayList<>())))) - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("bad?.pdf") - .build(); - - String pattern = "/{title}_{authors}"; - String result = fileMoveService.generatePathFromPattern(book, pattern); - - assertThat(result).isEqualTo("/InvaidName_Author.pdf"); - } - - @Test - void testControlCharactersAreStripped() { - String titleWithControlChars = "Bad\u0000Name\u0007Here"; - - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title(titleWithControlChars) - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("control.epub") - .build(); - - String result = fileMoveService.generatePathFromPattern(book, "/{title}"); - assertThat(result).isEqualTo("/BadNameHere.epub"); - } - - @Test - void testWhitespaceIsCollapsed() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title(" Too Many Spaces ") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("space.mobi") - .build(); - - String result = fileMoveService.generatePathFromPattern(book, "/{title}"); - assertThat(result).isEqualTo("/Too Many Spaces.mobi"); - } - - @Test - void testUnknownPlaceholdersAreUnchanged() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Valid Book") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("valid.pdf") - .build(); - - String pattern = "/{title}/{foo}/{bar}"; - String result = fileMoveService.generatePathFromPattern(book, pattern); - - assertThat(result).isEqualTo("/Valid Book/{foo}/{bar}.pdf"); - } - - @Test - void testEmptyOptionalBlockIsIgnored() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("Optional") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("opt.epub") - .build(); - - String result = fileMoveService.generatePathFromPattern(book, "<>"); - assertThat(result).isEqualTo("opt.epub"); - } - - @Test - void testUnicodeCharactersArePreservedAndSanitized() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("𝔘𝔫𝔦𝔠𝔬𝔡𝔢 – 漢字 – हिंदी") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("unicode.azw3") - .build(); - - String result = fileMoveService.generatePathFromPattern(book, "/{title}"); - assertThat(result).isEqualTo("/𝔘𝔫𝔦𝔠𝔬𝔡𝔢 – 漢字 – हिंदी.azw3"); - } - - @Test - void testOptionalBlockDoesNotLeakSurroundingChars() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("LeakTest") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName("leaky.fb2") - .build(); - - String pattern = "<({series}) >{title}"; - String result = fileMoveService.generatePathFromPattern(book, pattern); - - assertThat(result).isEqualTo("LeakTest.fb2"); - } - - @Test - void testExtensionWithDotOnly() { - BookMetadataEntity metadata = BookMetadataEntity.builder() - .title("DotDot") - .build(); - - BookEntity book = BookEntity.builder() - .metadata(metadata) - .fileName(".") - .build(); - - String result = fileMoveService.generatePathFromPattern(book, "/{title}"); - assertThat(result).isEqualTo("/DotDot"); - } -} \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceTest.java deleted file mode 100644 index 5507d9cb0..000000000 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceTest.java +++ /dev/null @@ -1,380 +0,0 @@ -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.Map; -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 bookIds = Set.of(1L, 2L); - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(bookIds); - request.setMoves(List.of()); - - List batchBooks = List.of(bookEntity1, bookEntity2); - when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100)) - .thenReturn(batchBooks); - - when(bookRepository.save(bookEntity1)).thenReturn(bookEntity1); - when(bookRepository.save(bookEntity2)).thenReturn(bookEntity2); - when(bookMapper.toBook(bookEntity1)).thenReturn(book1); - when(bookMapper.toBook(bookEntity2)).thenReturn(book2); - - doAnswer(invocation -> { - UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(2); - callback.onBookMoved(bookEntity1); - callback.onBookMoved(bookEntity2); - return null; - }).when(unifiedFileMoveService).moveBatchBookFiles(eq(batchBooks), eq(Map.of()), any()); - - // When - fileMoveService.moveFiles(request); - - // Then - verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 0, 100); - verify(unifiedFileMoveService).moveBatchBookFiles(eq(batchBooks), eq(Map.of()), 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 bookIds = IntStream.rangeClosed(1, 150) - .mapToObj(i -> (long) i) - .collect(Collectors.toSet()); - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(bookIds); - request.setMoves(List.of()); - - // Create subset for first batch (first 100 items) - Set firstBatchIds = IntStream.rangeClosed(1, 100) - .mapToObj(i -> (long) i) - .collect(Collectors.toSet()); - - // Create subset for second batch (remaining 50 items) - Set secondBatchIds = IntStream.rangeClosed(101, 150) - .mapToObj(i -> (long) i) - .collect(Collectors.toSet()); - - // First batch - when(bookQueryService.findWithMetadataByIdsWithPagination(firstBatchIds, 0, 100)) - .thenReturn(List.of(bookEntity1)); - // Second batch - when(bookQueryService.findWithMetadataByIdsWithPagination(secondBatchIds, 100, 100)) - .thenReturn(List.of(bookEntity2)); - - when(book1.getId()).thenReturn(1L); - when(book2.getId()).thenReturn(2L); - when(bookRepository.save(bookEntity1)).thenReturn(bookEntity1); - when(bookRepository.save(bookEntity2)).thenReturn(bookEntity2); - when(bookMapper.toBook(bookEntity1)).thenReturn(book1); - when(bookMapper.toBook(bookEntity2)).thenReturn(book2); - - doAnswer(invocation -> { - UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(2); - List books = invocation.getArgument(0); - for (BookEntity book : books) { - callback.onBookMoved(book); - } - return null; - }).when(unifiedFileMoveService).moveBatchBookFiles(any(), eq(Map.of()), any()); - - // When - fileMoveService.moveFiles(request); - - // Then - verify(bookQueryService).findWithMetadataByIdsWithPagination(firstBatchIds, 0, 100); - verify(bookQueryService).findWithMetadataByIdsWithPagination(secondBatchIds, 100, 100); - verify(unifiedFileMoveService, times(2)).moveBatchBookFiles(any(), eq(Map.of()), 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 bookIds = Set.of(1L, 2L); - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(bookIds); - request.setMoves(List.of()); - - 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(), any()); - verify(bookRepository, never()).save(any()); - verify(notificationService, never()).sendMessage(any(), any()); - } - - @Test - void moveFiles_WhenMoveFailsForSomeBooks_ShouldThrowException() { - // Given - Set bookIds = Set.of(1L, 2L); - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(bookIds); - request.setMoves(List.of()); - - List batchBooks = List.of(bookEntity1, bookEntity2); - when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100)) - .thenReturn(batchBooks); - - when(bookRepository.save(bookEntity1)).thenReturn(bookEntity1); - when(bookMapper.toBook(bookEntity1)).thenReturn(book1); - - RuntimeException moveException = new RuntimeException("File move failed"); - doAnswer(invocation -> { - UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(2); - callback.onBookMoved(bookEntity1); - callback.onBookMoveFailed(bookEntity2, moveException); - return null; - }).when(unifiedFileMoveService).moveBatchBookFiles(eq(batchBooks), eq(Map.of()), any()); - - // 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 bookIds = Set.of(); - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(bookIds); - request.setMoves(List.of()); - - // 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(), any()); - verify(notificationService, never()).sendMessage(any(), any()); - } - - @Test - void moveFiles_WhenPartialBatch_ShouldProcessCorrectly() { - // Given - Set bookIds = Set.of(1L); - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(bookIds); - request.setMoves(List.of()); - - when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100)) - .thenReturn(List.of(bookEntity1)); - - when(book1.getId()).thenReturn(1L); - when(bookRepository.save(bookEntity1)).thenReturn(bookEntity1); - when(bookMapper.toBook(bookEntity1)).thenReturn(book1); - - doAnswer(invocation -> { - UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(2); - callback.onBookMoved(bookEntity1); - return null; - }).when(unifiedFileMoveService).moveBatchBookFiles(eq(List.of(bookEntity1)), eq(Map.of()), any()); - - // When - fileMoveService.moveFiles(request); - - // Then - verify(bookQueryService).findWithMetadataByIdsWithPagination(bookIds, 0, 100); - verify(unifiedFileMoveService).moveBatchBookFiles(eq(List.of(bookEntity1)), eq(Map.of()), 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 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 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 bookIds = Set.of(1L, 2L); - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(bookIds); - request.setMoves(List.of()); - - when(bookQueryService.findWithMetadataByIdsWithPagination(bookIds, 0, 100)) - .thenReturn(List.of(bookEntity1, bookEntity2)); - - when(bookRepository.save(bookEntity1)).thenReturn(bookEntity1); - when(bookRepository.save(bookEntity2)).thenReturn(bookEntity2); - when(bookMapper.toBook(bookEntity1)).thenReturn(book1); - when(bookMapper.toBook(bookEntity2)).thenReturn(book2); - - doAnswer(invocation -> { - UnifiedFileMoveService.BatchMoveCallback callback = invocation.getArgument(2); - callback.onBookMoved(bookEntity1); - callback.onBookMoved(bookEntity2); - return null; - }).when(unifiedFileMoveService).moveBatchBookFiles(any(), eq(Map.of()), any()); - - // When - fileMoveService.moveFiles(request); - - // Then - ArgumentCaptor> booksCaptor = ArgumentCaptor.forClass(List.class); - verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), booksCaptor.capture()); - - List sentBooks = booksCaptor.getValue(); - assertEquals(2, sentBooks.size()); - assertTrue(sentBooks.contains(book1)); - assertTrue(sentBooks.contains(book2)); - } - - @Test - void moveFiles_WhenNoBooksMoved_ShouldNotSendNotification() { - // Given - Set bookIds = Set.of(1L, 2L); - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(bookIds); - request.setMoves(List.of()); - - 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(2); - callback.onBookMoveFailed(bookEntity1, moveException); - return null; - }).when(unifiedFileMoveService).moveBatchBookFiles(any(), eq(Map.of()), any()); - - // When & Then - assertThrows(RuntimeException.class, () -> { - fileMoveService.moveFiles(request); - }); - - verify(notificationService, never()).sendMessage(any(), any()); - } -} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMovingHelperTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMovingHelperTest.java deleted file mode 100644 index c781666f3..000000000 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMovingHelperTest.java +++ /dev/null @@ -1,306 +0,0 @@ -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 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 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 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 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 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 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 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()); - } - } -} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/MonitoredFileOperationServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/MonitoredFileOperationServiceTest.java deleted file mode 100644 index 50b84ad15..000000000 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/MonitoredFileOperationServiceTest.java +++ /dev/null @@ -1,208 +0,0 @@ -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 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 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 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 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 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 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 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 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)); - } -} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/UnifiedFileMoveServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/UnifiedFileMoveServiceTest.java deleted file mode 100644 index 8c9c89a05..000000000 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/UnifiedFileMoveServiceTest.java +++ /dev/null @@ -1,213 +0,0 @@ -package com.adityachandel.booklore.service.file; - -import com.adityachandel.booklore.model.entity.*; -import com.adityachandel.booklore.repository.LibraryRepository; -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.junit.jupiter.MockitoExtension; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.Optional; - -import static java.util.Collections.singletonList; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) -class UnifiedFileMoveServiceTest { - - @Mock - FileMovingHelper fileMovingHelper; - - @Mock - MonitoredFileOperationService monitoredFileOperationService; - - @Mock - MonitoringRegistrationService monitoringRegistrationService; - - @Mock - LibraryRepository libraryRepository; - - @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(); - 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 { - when(libraryRepository.findById(10L)).thenReturn(Optional.of(library)); - - 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 { - when(libraryRepository.findById(10L)).thenReturn(Optional.of(library)); - - 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()); - } -} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/MetadataManagementServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/MetadataManagementServiceTest.java index 12beba457..139a01770 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/MetadataManagementServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/MetadataManagementServiceTest.java @@ -4,7 +4,6 @@ import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.enums.MergeMetadataType; import com.adityachandel.booklore.repository.*; import com.adityachandel.booklore.service.appsettings.AppSettingService; -import com.adityachandel.booklore.service.file.UnifiedFileMoveService; import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory; import com.adityachandel.booklore.model.dto.settings.AppSettings; import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; @@ -44,8 +43,6 @@ class MetadataManagementServiceTest { AppSettingService appSettingService; @Mock MetadataWriterFactory metadataWriterFactory; - @Mock - UnifiedFileMoveService unifiedFileMoveService; @InjectMocks MetadataManagementService service; diff --git a/booklore-ui/src/app/app.component.ts b/booklore-ui/src/app/app.component.ts index a9e95ec45..8c5adc028 100644 --- a/booklore-ui/src/app/app.component.ts +++ b/booklore-ui/src/app/app.component.ts @@ -55,6 +55,11 @@ export class AppComponent implements OnInit, OnDestroy { this.bookService.handleNewlyCreatedBook(JSON.parse(msg.body)) ) ); + this.subscriptions.push( + this.rxStompService.watch('/user/queue/book-update').subscribe(msg => + this.bookService.handleBookUpdate(JSON.parse(msg.body)) + ) + ); this.subscriptions.push( this.rxStompService.watch('/user/queue/books-remove').subscribe(msg => this.bookService.handleRemovedBookIds(JSON.parse(msg.body)) diff --git a/booklore-ui/src/app/features/book/components/book-browser/BookDialogHelperService.ts b/booklore-ui/src/app/features/book/components/book-browser/BookDialogHelperService.ts index c3b0920f8..b6dd59972 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/BookDialogHelperService.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/BookDialogHelperService.ts @@ -100,10 +100,10 @@ export class BookDialogHelperService { closeOnEscape: false, dismissableMask: false, style: { - width: '85vw', - height: '80vh', - maxHeight: '95vh', - maxWidth: '97.5vw' + width: '95vw', + maxWidth: '97.5vw', + height: '90vh', + maxHeight: '95vh' }, data: { bookIds: selectedBooks diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html index ee1c7e18f..efe02579c 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html @@ -515,7 +515,7 @@
-
+
diff --git a/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.html b/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.html index 614ce5cab..7efcf4d2b 100644 --- a/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.html +++ b/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.html @@ -17,32 +17,15 @@
- +
-

- - Writes metadata directly into the original file. A backup of the metadata and/or cover is created only if enabled below. Proceed with caution, restoration may fail if the file is moved or renamed. -

-
-
- -
-
-
- - - -

- Converts CBR and CB7 files to CBZ format when updating metadata. If disabled, edits to CBR/CB7 files will not be written to the original file. + Write metadata directly into the original file. (Only Epub and PDF formats are currently supported.)

diff --git a/booklore-ui/src/app/shared/components/file-mover/file-mover-component.html b/booklore-ui/src/app/shared/components/file-mover/file-mover-component.html index c5fed30cc..068ad15fd 100644 --- a/booklore-ui/src/app/shared/components/file-mover/file-mover-component.html +++ b/booklore-ui/src/app/shared/components/file-mover/file-mover-component.html @@ -66,33 +66,50 @@ size="small" appendTo="body" > + @if (defaultAvailableLibraryPaths.length > 0) { + + }
-
+
- ID + ID Current Path - Target Library + Target Library + Library Sub Path New Path - + - {{ preview.bookId }} - -

- {{ preview.currentLibraryName }}/{{ preview.relativeOriginalPath }} -

+ {{ preview.bookId }} + +
+ {{ preview.currentLibraryName }}/{{ preview.relativeOriginalPath }} +
- + - → - -

- {{ preview.targetLibraryName }}/{{ preview.relativeNewPath }} -

+ + @if (preview.availableLibraryPaths.length > 0) { + + } @else { +
No paths configured
+ } - + → + +
+ {{ preview.targetLibraryName }}/{{ preview.relativeNewPath }} +
+ + @if (preview.isMoved) { } diff --git a/booklore-ui/src/app/shared/components/file-mover/file-mover-component.ts b/booklore-ui/src/app/shared/components/file-mover/file-mover-component.ts index 6543574b8..0302dda84 100644 --- a/booklore-ui/src/app/shared/components/file-mover/file-mover-component.ts +++ b/booklore-ui/src/app/shared/components/file-mover/file-mover-component.ts @@ -14,6 +14,7 @@ import {FileMoveRequest, FileOperationsService} from '../../service/file-operati import {LibraryService} from "../../../features/book/service/library.service"; import {AppSettingsService} from '../../service/app-settings.service'; import {Select} from 'primeng/select'; +import {Library, LibraryPath} from '../../../features/book/model/library.model'; interface FilePreview { bookId: number; @@ -21,8 +22,12 @@ interface FilePreview { relativeOriginalPath: string; currentLibraryId: number | null; currentLibraryName: string; + currentLibraryPath: string; targetLibraryId: number | null; targetLibraryName: string; + targetLibraryPath: string; + targetLibraryPathId: number | null; + availableLibraryPaths: LibraryPath[]; newPath: string; relativeNewPath: string; isMoved?: boolean; @@ -54,13 +59,15 @@ export class FileMoverComponent implements OnDestroy { }[] = []; defaultMovePattern = ''; loading = false; - patternsCollapsed = false; + patternsCollapsed = true; bookIds: Set = new Set(); books: Book[] = []; availableLibraries: { id: number | null; name: string }[] = []; filePreviews: FilePreview[] = []; defaultTargetLibraryId: number | null = null; + defaultTargetLibraryPathId: number | null = null; + defaultAvailableLibraryPaths: LibraryPath[] = []; constructor() { this.bookIds = new Set(this.config.data?.bookIds ?? []); @@ -152,9 +159,13 @@ export class FileMoverComponent implements OnDestroy { const currentLibraryId = book.libraryId ?? book.libraryPath?.id ?? (book as any).library?.id ?? null; const currentLibraryName = this.getLibraryNameById(currentLibraryId); + const currentLibraryPath = this.getLibraryPathById(currentLibraryId); const targetLibraryId = currentLibraryId; const targetLibraryName = currentLibraryName; + const availableLibraryPaths = this.getLibraryPathsById(targetLibraryId); + const targetLibraryPathId = availableLibraryPaths.length > 0 ? availableLibraryPaths[0].id ?? null : null; + const targetLibraryPath = availableLibraryPaths.length > 0 ? availableLibraryPaths[0].path : ''; const preview: FilePreview = { bookId: book.id, @@ -162,8 +173,12 @@ export class FileMoverComponent implements OnDestroy { relativeOriginalPath, currentLibraryId, currentLibraryName, + currentLibraryPath, targetLibraryId, targetLibraryName, + targetLibraryPath, + targetLibraryPathId, + availableLibraryPaths, newPath: '', relativeNewPath: '' }; @@ -174,10 +189,30 @@ export class FileMoverComponent implements OnDestroy { } onDefaultLibraryChange(): void { + this.defaultAvailableLibraryPaths = this.getLibraryPathsById(this.defaultTargetLibraryId); + this.defaultTargetLibraryPathId = this.defaultAvailableLibraryPaths.length > 0 ? this.defaultAvailableLibraryPaths[0].id ?? null : null; + this.filePreviews.forEach(preview => { if (!preview.isMoved) { preview.targetLibraryId = this.defaultTargetLibraryId; preview.targetLibraryName = this.getLibraryNameById(this.defaultTargetLibraryId); + preview.availableLibraryPaths = this.defaultAvailableLibraryPaths; + preview.targetLibraryPathId = this.defaultTargetLibraryPathId; + preview.targetLibraryPath = this.defaultAvailableLibraryPaths.find(p => p.id === this.defaultTargetLibraryPathId)?.path || ''; + + const book = this.books.find(b => b.id === preview.bookId); + if (book) { + this.updatePreviewPaths(preview, book); + } + } + }); + } + + onDefaultLibraryPathChange(): void { + this.filePreviews.forEach(preview => { + if (!preview.isMoved && preview.targetLibraryId === this.defaultTargetLibraryId) { + preview.targetLibraryPathId = this.defaultTargetLibraryPathId; + preview.targetLibraryPath = this.defaultAvailableLibraryPaths.find(p => p.id === this.defaultTargetLibraryPathId)?.path || ''; const book = this.books.find(b => b.id === preview.bookId); if (book) { @@ -189,6 +224,20 @@ export class FileMoverComponent implements OnDestroy { onLibraryChange(preview: FilePreview): void { preview.targetLibraryName = this.getLibraryNameById(preview.targetLibraryId); + preview.availableLibraryPaths = this.getLibraryPathsById(preview.targetLibraryId); + preview.targetLibraryPathId = preview.availableLibraryPaths.length > 0 ? preview.availableLibraryPaths[0].id ?? null : null; + preview.targetLibraryPath = preview.availableLibraryPaths.length > 0 ? preview.availableLibraryPaths[0].path : ''; + + const book = this.books.find(b => b.id === preview.bookId); + if (book) { + this.updatePreviewPaths(preview, book); + } + } + + onLibraryPathChange(preview: FilePreview): void { + const selectedPath = preview.availableLibraryPaths.find(p => p.id === preview.targetLibraryPathId); + preview.targetLibraryPath = selectedPath?.path || ''; + const book = this.books.find(b => b.id === preview.bookId); if (book) { this.updatePreviewPaths(preview, book); @@ -199,9 +248,7 @@ export class FileMoverComponent implements OnDestroy { const meta = book.metadata!; const fileName = book.fileName ?? ''; const extension = fileName.match(/\.[^.]+$/)?.[0] ?? ''; - - const libraryPattern = this.libraryPatterns.find(p => p.libraryId === preview.targetLibraryId); - const pattern = libraryPattern?.pattern || this.defaultMovePattern; + const pattern = this.getPatternForLibrary(preview.targetLibraryId); const values: Record = { authors: this.sanitize(meta.authors?.join(', ') || 'Unknown Author'), @@ -239,13 +286,40 @@ export class FileMoverComponent implements OnDestroy { preview.newPath = this.getFullPath(preview.targetLibraryId, newPath); } + private getPatternForLibrary(libraryId: number | null): string { + if (libraryId === null) { + return this.defaultMovePattern; + } + + const libraries = this.libraryService.getLibrariesFromState(); + const library = libraries.find((lib: Library) => lib.id === libraryId); + + return library?.fileNamingPattern || this.defaultMovePattern; + } + private getLibraryNameById(libraryId: number | null): string { if (libraryId === null) return 'Unknown Library'; return this.availableLibraries.find(lib => lib.id === libraryId)?.name || 'Unknown Library'; } + private getLibraryPathsById(libraryId: number | null): LibraryPath[] { + if (libraryId === null) return []; + + const libraries = this.libraryService.getLibrariesFromState(); + const library = libraries.find((lib: Library) => lib.id === libraryId); + return library?.paths || []; + } + + private getLibraryPathById(libraryId: number | null): string { + const paths = this.getLibraryPathsById(libraryId); + return paths.map((p: LibraryPath) => p.path).join(', '); + } + private getFullPath(libraryId: number | null, relativePath: string): string { - const libraryPath = libraryId ? this.libraryService.getLibraryPathById(libraryId)?.replace(/\/+$/g, '') : ''; + if (!libraryId) return relativePath; + + const paths = this.getLibraryPathsById(libraryId); + const libraryPath = paths.length > 0 ? paths[0].path.replace(/\/+$/g, '') : ''; return libraryPath ? `${libraryPath}/${relativePath}`.replace(/\/\/+/g, '/') : relativePath; } @@ -282,7 +356,8 @@ export class FileMoverComponent implements OnDestroy { bookIds: [...this.bookIds], moves: this.filePreviews.map(preview => ({ bookId: preview.bookId, - targetLibraryId: preview.targetLibraryId + targetLibraryId: preview.targetLibraryId, + targetLibraryPathId: preview.targetLibraryPathId })) }; @@ -318,4 +393,8 @@ export class FileMoverComponent implements OnDestroy { togglePatternsCollapsed(): void { this.patternsCollapsed = !this.patternsCollapsed; } + + trackByBookId(index: number, preview: FilePreview): number { + return preview.bookId; + } } diff --git a/booklore-ui/src/app/shared/service/file-operations-service.ts b/booklore-ui/src/app/shared/service/file-operations-service.ts index f86c7dec4..5d1d75324 100644 --- a/booklore-ui/src/app/shared/service/file-operations-service.ts +++ b/booklore-ui/src/app/shared/service/file-operations-service.ts @@ -8,6 +8,7 @@ export interface FileMoveRequest { moves: { bookId: number; targetLibraryId: number | null; + targetLibraryPathId: number | null; }[]; }