diff --git a/booklore-api/src/main/java/org/booklore/controller/BookController.java b/booklore-api/src/main/java/org/booklore/controller/BookController.java index 95baf077e..ba24bfa7b 100644 --- a/booklore-api/src/main/java/org/booklore/controller/BookController.java +++ b/booklore-api/src/main/java/org/booklore/controller/BookController.java @@ -7,18 +7,20 @@ import org.booklore.model.dto.BookRecommendation; import org.booklore.model.dto.BookViewerSettings; import org.booklore.model.dto.request.AttachBookFileRequest; import org.booklore.model.dto.request.CreatePhysicalBookRequest; +import org.booklore.model.dto.request.DuplicateDetectionRequest; import org.booklore.model.dto.request.PersonalRatingUpdateRequest; import org.booklore.model.dto.request.ReadProgressRequest; import org.booklore.model.dto.request.ReadStatusUpdateRequest; import org.booklore.model.dto.request.ShelvesAssignmentRequest; import org.booklore.model.dto.response.BookDeletionResponse; import org.booklore.model.dto.response.BookStatusUpdateResponse; -import org.booklore.model.dto.response.BookSyncResponse; +import org.booklore.model.dto.response.DuplicateGroup; import org.booklore.model.dto.response.PersonalRatingUpdateResponse; import org.booklore.model.enums.ResetProgressType; import org.booklore.service.book.BookFileAttachmentService; import org.booklore.service.book.BookService; import org.booklore.service.book.BookUpdateService; +import org.booklore.service.book.DuplicateDetectionService; import org.booklore.service.book.PhysicalBookService; import org.booklore.service.metadata.BookMetadataService; import org.booklore.service.progress.ReadingProgressService; @@ -35,13 +37,10 @@ import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; import lombok.AllArgsConstructor; import org.springframework.core.io.Resource; -import org.springframework.http.CacheControl; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import java.time.Instant; import java.util.List; import java.util.Set; @@ -58,35 +57,15 @@ public class BookController { private final BookMetadataService bookMetadataService; private final ReadingProgressService readingProgressService; private final PhysicalBookService physicalBookService; + private final DuplicateDetectionService duplicateDetectionService; - @Operation(summary = "Get all books", description = "Retrieve a list of all books. Optionally include descriptions. Supports ETag-based conditional requests.") - @ApiResponses({ - @ApiResponse(responseCode = "200", description = "List of books returned successfully"), - @ApiResponse(responseCode = "304", description = "Not modified — client cache is still valid") - }) + @Operation(summary = "Get all books", description = "Retrieve a list of all books. Optionally include descriptions.") + @ApiResponse(responseCode = "200", description = "List of books returned successfully") @GetMapping public ResponseEntity> getBooks( - @Parameter(description = "Include book descriptions in the response") - @RequestParam(required = false, defaultValue = "false") boolean withDescription, - @RequestHeader(value = "If-None-Match", required = false) String ifNoneMatch) { - String etag = bookService.computeBooksETag(withDescription); - if (etag.equals(ifNoneMatch)) { - return ResponseEntity.status(HttpStatus.NOT_MODIFIED).eTag(etag).build(); - } - return ResponseEntity.ok() - .eTag(etag) - .cacheControl(CacheControl.noCache().cachePrivate()) - .body(bookService.getBookDTOs(withDescription)); - } - - @Operation(summary = "Get book changes since timestamp", description = "Returns books added/modified since the given timestamp and IDs of deleted books. Used for delta synchronization.") - @ApiResponse(responseCode = "200", description = "Delta sync response returned successfully") - @GetMapping("/delta") - public ResponseEntity getBooksDelta( - @Parameter(description = "Timestamp to fetch changes since (ISO-8601 instant)") @RequestParam Instant since, @Parameter(description = "Include book descriptions in the response") @RequestParam(required = false, defaultValue = "false") boolean withDescription) { - return ResponseEntity.ok(bookService.getBooksDelta(since, withDescription)); + return ResponseEntity.ok(bookService.getBookDTOs(withDescription)); } @Operation(summary = "Get a book by ID", description = "Retrieve details of a specific book by its ID.") @@ -288,6 +267,15 @@ public class BookController { return ResponseEntity.ok(updatedBooks); } + @Operation(summary = "Find duplicate books", description = "Detect potential duplicate books in a library using configurable matching strategies.") + @ApiResponse(responseCode = "200", description = "Duplicate groups returned successfully") + @PostMapping("/duplicates") + @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") + public ResponseEntity> findDuplicates( + @Parameter(description = "Duplicate detection configuration") @RequestBody @Valid DuplicateDetectionRequest request) { + return ResponseEntity.ok(duplicateDetectionService.findDuplicates(request)); + } + @Operation(summary = "Attach book files", description = "Attach book files from single-file source books to a target book as alternative formats.") @ApiResponses({ @ApiResponse(responseCode = "200", description = "Book files attached successfully"), diff --git a/booklore-api/src/main/java/org/booklore/model/dto/request/DuplicateDetectionRequest.java b/booklore-api/src/main/java/org/booklore/model/dto/request/DuplicateDetectionRequest.java new file mode 100644 index 000000000..a55106bb8 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/request/DuplicateDetectionRequest.java @@ -0,0 +1,12 @@ +package org.booklore.model.dto.request; + +import jakarta.validation.constraints.NotNull; + +public record DuplicateDetectionRequest( + @NotNull Long libraryId, + boolean matchByIsbn, + boolean matchByExternalId, + boolean matchByTitleAuthor, + boolean matchByDirectory, + boolean matchByFilename +) {} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/response/BookSyncResponse.java b/booklore-api/src/main/java/org/booklore/model/dto/response/BookSyncResponse.java deleted file mode 100644 index 75a4a1949..000000000 --- a/booklore-api/src/main/java/org/booklore/model/dto/response/BookSyncResponse.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.booklore.model.dto.response; - -import com.fasterxml.jackson.annotation.JsonInclude; -import org.booklore.model.dto.Book; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@Builder -@NoArgsConstructor -@AllArgsConstructor -@JsonInclude(JsonInclude.Include.NON_NULL) -public class BookSyncResponse { - private List books; - private List deletedIds; - private String syncTimestamp; - private long totalBookCount; -} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/response/DuplicateGroup.java b/booklore-api/src/main/java/org/booklore/model/dto/response/DuplicateGroup.java new file mode 100644 index 000000000..2c2982e49 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/response/DuplicateGroup.java @@ -0,0 +1,11 @@ +package org.booklore.model.dto.response; + +import org.booklore.model.dto.Book; + +import java.util.List; + +public record DuplicateGroup( + Long suggestedTargetBookId, + String matchReason, + List books +) {} diff --git a/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java b/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java index 3e8653d2d..791dc5173 100644 --- a/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java +++ b/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java @@ -33,5 +33,6 @@ public enum AuditAction { OPDS_USER_UPDATED, NAMING_PATTERN_CHANGED, LOGIN_RATE_LIMITED, - REFRESH_RATE_LIMITED + REFRESH_RATE_LIMITED, + DUPLICATE_BOOKS_MERGED } diff --git a/booklore-api/src/main/java/org/booklore/repository/BookRepository.java b/booklore-api/src/main/java/org/booklore/repository/BookRepository.java index 6cb42c8fb..08ffb61be 100644 --- a/booklore-api/src/main/java/org/booklore/repository/BookRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/BookRepository.java @@ -66,6 +66,17 @@ public interface BookRepository extends JpaRepository, JpaSpec @Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)") List findAllByLibraryIdWithFiles(@Param("libraryId") Long libraryId); + @Query(""" + SELECT DISTINCT b FROM BookEntity b + LEFT JOIN FETCH b.metadata m + LEFT JOIN FETCH m.authors + LEFT JOIN FETCH b.bookFiles + LEFT JOIN FETCH b.libraryPath + WHERE b.library.id = :libraryId + AND (b.deleted IS NULL OR b.deleted = false) + """) + List findAllForDuplicateDetection(@Param("libraryId") Long libraryId); + @EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "shelves", "libraryPath", "bookFiles"}) @Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)") List findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection libraryIds); @@ -118,29 +129,6 @@ public interface BookRepository extends JpaRepository, JpaSpec @Query("SELECT COUNT(b) FROM BookEntity b WHERE b.deleted = TRUE") long countAllSoftDeleted(); - @Query("SELECT COUNT(b), MAX(COALESCE(b.metadataUpdatedAt, b.addedOn)), MAX(b.addedOn) " + - "FROM BookEntity b WHERE b.deleted IS NULL OR b.deleted = false") - Object[] getBookStats(); - - @Query("SELECT COUNT(b), MAX(COALESCE(b.metadataUpdatedAt, b.addedOn)), MAX(b.addedOn) " + - "FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)") - Object[] getBookStatsByLibraryIds(@Param("libraryIds") Set libraryIds); - - @Query("SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) " + - "AND (b.addedOn > :since OR b.metadataUpdatedAt > :since)") - Set findBookIdsModifiedSince(@Param("since") Instant since); - - @Query("SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) " + - "AND (b.addedOn > :since OR b.metadataUpdatedAt > :since) AND b.library.id IN :libraryIds") - Set findBookIdsModifiedSinceByLibraryIds(@Param("since") Instant since, @Param("libraryIds") Set libraryIds); - - @Query("SELECT b.id FROM BookEntity b WHERE b.deleted = true AND b.deletedAt > :since") - List findDeletedBookIdsSince(@Param("since") Instant since); - - @Query("SELECT b.id FROM BookEntity b WHERE b.deleted = true AND b.deletedAt > :since " + - "AND b.library.id IN :libraryIds") - List findDeletedBookIdsSinceByLibraryIds(@Param("since") Instant since, @Param("libraryIds") Set libraryIds); - @Query(value = """ SELECT b.* FROM book b diff --git a/booklore-api/src/main/java/org/booklore/repository/UserBookProgressRepository.java b/booklore-api/src/main/java/org/booklore/repository/UserBookProgressRepository.java index a81836bad..a4c28c2ae 100644 --- a/booklore-api/src/main/java/org/booklore/repository/UserBookProgressRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/UserBookProgressRepository.java @@ -21,14 +21,6 @@ public interface UserBookProgressRepository extends JpaRepository findByUserIdAndBookIdIn(Long userId, Set bookIds); - @Query("SELECT MAX(COALESCE(ubp.lastReadTime, ubp.readStatusModifiedTime)) " + - "FROM UserBookProgressEntity ubp WHERE ubp.user.id = :userId") - Instant getMaxProgressTimestamp(@Param("userId") Long userId); - - @Query("SELECT ubp.book.id FROM UserBookProgressEntity ubp WHERE ubp.user.id = :userId " + - "AND (ubp.lastReadTime > :since OR ubp.readStatusModifiedTime > :since)") - Set findBookIdsWithProgressChangedSince(@Param("userId") Long userId, @Param("since") Instant since); - @Query(""" SELECT ubp FROM UserBookProgressEntity ubp WHERE ubp.user.id = :userId diff --git a/booklore-api/src/main/java/org/booklore/service/book/BookFileAttachmentService.java b/booklore-api/src/main/java/org/booklore/service/book/BookFileAttachmentService.java index 46c120f3a..774d7f376 100644 --- a/booklore-api/src/main/java/org/booklore/service/book/BookFileAttachmentService.java +++ b/booklore-api/src/main/java/org/booklore/service/book/BookFileAttachmentService.java @@ -76,7 +76,6 @@ public class BookFileAttachmentService { throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " must be in the same library as target"); } - // Validate source has exactly 1 book format file List sourceBookFiles = sourceBook.getBookFiles().stream() .filter(BookFileEntity::isBookFormat) .collect(Collectors.toList()); @@ -85,23 +84,17 @@ public class BookFileAttachmentService { throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " has no book format files to attach"); } - if (sourceBookFiles.size() > 1) { - throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " has multiple book format files. Only single-file books can be attached."); - } + for (BookFileEntity fileToMove : sourceBookFiles) { + if (fileToMove.isFolderBased()) { + throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " contains a folder-based audiobook. Folder-based books cannot be attached."); + } - BookFileEntity fileToMove = sourceBookFiles.get(0); - - // Validate not folder-based - if (fileToMove.isFolderBased()) { - throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " is a folder-based audiobook. Folder-based books cannot be attached."); - } - - // Validate source file exists - Path sourceFilePath = fileToMove.getFullFilePath(); - if (!Files.exists(sourceFilePath)) { - throw ApiError.GENERIC_BAD_REQUEST.createException( - "Source file not found at expected location: " + sourceFilePath + - ". The file may have been moved, deleted, or the database record is out of sync."); + Path sourceFilePath = fileToMove.getFullFilePath(); + if (!Files.exists(sourceFilePath)) { + throw ApiError.GENERIC_BAD_REQUEST.createException( + "Source file not found at expected location: " + sourceFilePath + + ". The file may have been moved, deleted, or the database record is out of sync."); + } } } @@ -228,70 +221,61 @@ public class BookFileAttachmentService { // Process each source book for (BookEntity sourceBook : sourceBooks) { - BookFileEntity fileToMove = sourceBook.getBookFiles().stream() + List filesToMove = sourceBook.getBookFiles().stream() .filter(BookFileEntity::isBookFormat) - .findFirst() - .orElseThrow(); // Already validated above + .toList(); - Path sourceFilePath = fileToMove.getFullFilePath(); - Path sourceDirectory = sourceFilePath.getParent(); + Set sourceDirectories = new HashSet<>(); - // Unregister source directory from monitoring to prevent spurious DELETE events - if (sourceDirectory != null) { - try { - monitoringRegistrationService.unregisterSpecificPath(sourceDirectory); - } catch (Exception ex) { - log.warn("Failed to unregister source directory from monitoring: {}", sourceDirectory, ex); + for (BookFileEntity fileToMove : filesToMove) { + Path sourceFilePath = fileToMove.getFullFilePath(); + Path sourceDirectory = sourceFilePath.getParent(); + + if (sourceDirectory != null && sourceDirectories.add(sourceDirectory)) { + try { + monitoringRegistrationService.unregisterSpecificPath(sourceDirectory); + } catch (Exception ex) { + log.warn("Failed to unregister source directory from monitoring: {}", sourceDirectory, ex); + } + pathsToReregister.add(sourceDirectory); } - pathsToReregister.add(sourceDirectory); + + String extension = getFileExtension(fileToMove.getFileName()).toLowerCase(); + + int existingCount = extensionCounts.getOrDefault(extension, 0); + String newFileName; + if (extension.isEmpty()) { + newFileName = existingCount > 0 + ? baseFileName + "_" + existingCount + : baseFileName; + } else { + newFileName = existingCount > 0 + ? baseFileName + "_" + existingCount + "." + extension + : baseFileName + "." + extension; + } + extensionCounts.merge(extension, 1, Integer::sum); + + newFileName = resolveFilenameConflict(targetDirectory, newFileName); + + Path destinationPath = targetDirectory.resolve(newFileName); + try { + Files.move(sourceFilePath, destinationPath); + log.info("Moved file from {} to {}", sourceFilePath, destinationPath); + } catch (IOException e) { + log.error("Failed to move file from {} to {}", sourceFilePath, destinationPath, e); + throw ApiError.INTERNAL_SERVER_ERROR.createException("Failed to move file: " + e.getMessage()); + } + + fileToMove.setFileSubPath(targetFileSubPath); + fileToMove.setFileName(newFileName); + + sourceBook.getBookFiles().remove(fileToMove); + fileToMove.setBook(targetBook); + targetBook.getBookFiles().add(fileToMove); } - // Generate new filename using the base name determined earlier (from pattern or actual primary file) - String extension = getFileExtension(fileToMove.getFileName()).toLowerCase(); + sourceDirectoriesToCleanup.addAll(sourceDirectories); - // Handle same-extension conflicts by adding suffix (_1, _2, etc.) - int existingCount = extensionCounts.getOrDefault(extension, 0); - String newFileName; - if (extension.isEmpty()) { - // File has no extension - newFileName = existingCount > 0 - ? baseFileName + "_" + existingCount - : baseFileName; - } else { - newFileName = existingCount > 0 - ? baseFileName + "_" + existingCount + "." + extension - : baseFileName + "." + extension; - } - extensionCounts.merge(extension, 1, Integer::sum); - - // Final conflict check against filesystem (in case of external files) - newFileName = resolveFilenameConflict(targetDirectory, newFileName); - - // Move the physical file - Path destinationPath = targetDirectory.resolve(newFileName); - try { - Files.move(sourceFilePath, destinationPath); - log.info("Moved file from {} to {}", sourceFilePath, destinationPath); - } catch (IOException e) { - log.error("Failed to move file from {} to {}", sourceFilePath, destinationPath, e); - throw ApiError.INTERNAL_SERVER_ERROR.createException("Failed to move file: " + e.getMessage()); - } - - // Update file entity with new path info - properly manage bidirectional relationship - fileToMove.setFileSubPath(targetFileSubPath); - fileToMove.setFileName(newFileName); - - // Remove from source book's collection and add to target's collection - sourceBook.getBookFiles().remove(fileToMove); - fileToMove.setBook(targetBook); - targetBook.getBookFiles().add(fileToMove); - - // Track source directory for cleanup - if (sourceDirectory != null) { - sourceDirectoriesToCleanup.add(sourceDirectory); - } - - // Track source book for deletion if requested if (deleteSourceBooks) { long remainingBookFiles = sourceBook.getBookFiles().stream() .filter(BookFileEntity::isBookFormat) diff --git a/booklore-api/src/main/java/org/booklore/service/book/BookService.java b/booklore-api/src/main/java/org/booklore/service/book/BookService.java index a529623a8..d180339fd 100644 --- a/booklore-api/src/main/java/org/booklore/service/book/BookService.java +++ b/booklore-api/src/main/java/org/booklore/service/book/BookService.java @@ -7,7 +7,6 @@ import org.booklore.model.dto.*; import org.booklore.model.dto.request.ReadProgressRequest; import org.booklore.model.dto.response.BookDeletionResponse; import org.booklore.model.dto.response.BookStatusUpdateResponse; -import org.booklore.model.dto.response.BookSyncResponse; import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.LibraryPathEntity; @@ -42,8 +41,6 @@ import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.sql.Timestamp; -import java.time.Instant; import java.util.*; import java.util.stream.Collectors; import org.booklore.model.enums.AuditAction; @@ -105,110 +102,6 @@ public class BookService { return books; } - public String computeBooksETag(boolean includeDescription) { - BookLoreUser user = authenticationService.getAuthenticatedUser(); - boolean isAdmin = user.getPermissions().isAdmin(); - - Object[] row = extractStatsRow(isAdmin - ? bookRepository.getBookStats() - : bookRepository.getBookStatsByLibraryIds(getUserLibraryIds(user))); - - long count = ((Number) row[0]).longValue(); - long maxBookTs = toEpochMilli(row[1]); - long maxAddedTs = toEpochMilli(row[2]); - long maxProgressTs = toEpochMilli(userBookProgressRepository.getMaxProgressTimestamp(user.getId())); - - return "\"" + count + "-" + maxBookTs + "-" + maxAddedTs + "-" + maxProgressTs - + "-" + includeDescription + "\""; - } - - public BookSyncResponse getBooksDelta(Instant since, boolean includeDescription) { - BookLoreUser user = authenticationService.getAuthenticatedUser(); - boolean isAdmin = user.getPermissions().isAdmin(); - Set libraryIds = isAdmin ? null : getUserLibraryIds(user); - - // Find book IDs modified since the given timestamp - Set modifiedBookIds = isAdmin - ? bookRepository.findBookIdsModifiedSince(since) - : bookRepository.findBookIdsModifiedSinceByLibraryIds(since, libraryIds); - - // Find book IDs with progress changes - Set progressChangedIds = userBookProgressRepository.findBookIdsWithProgressChangedSince(user.getId(), since); - - // Combine all changed IDs - Set allChangedIds = new HashSet<>(modifiedBookIds); - allChangedIds.addAll(progressChangedIds); - - // Find deleted book IDs - List deletedIds = isAdmin - ? bookRepository.findDeletedBookIdsSince(since) - : bookRepository.findDeletedBookIdsSinceByLibraryIds(since, libraryIds); - - // Fetch and enrich changed books - List changedBooks = List.of(); - if (!allChangedIds.isEmpty()) { - List bookEntities = bookQueryService.findAllWithMetadataByIds(allChangedIds); - if (!isAdmin) { - // Content restriction is handled by BookQueryService for non-admin users, - // but since we're using findAllWithMetadataByIds directly, filter by library - bookEntities = bookEntities.stream() - .filter(b -> libraryIds.contains(b.getLibrary().getId())) - .collect(Collectors.toList()); - } - changedBooks = enrichBookEntities(bookEntities, user, includeDescription); - } - - // Get total book count for client to detect full-sync needs - Object[] row = extractStatsRow(isAdmin - ? bookRepository.getBookStats() - : bookRepository.getBookStatsByLibraryIds(libraryIds)); - long totalCount = ((Number) row[0]).longValue(); - - return BookSyncResponse.builder() - .books(changedBooks) - .deletedIds(deletedIds) - .syncTimestamp(Instant.now().toString()) - .totalBookCount(totalCount) - .build(); - } - - private List enrichBookEntities(List bookEntities, BookLoreUser user, boolean includeDescription) { - // Map entities through the same DTO pipeline as full fetch (includes field stripping) - List books = bookQueryService.mapEntitiesToDto(bookEntities, includeDescription, user.getId()); - - Set bookIds = books.stream().map(Book::getId).collect(Collectors.toSet()); - Map progressMap = - readingProgressService.fetchUserProgress(user.getId(), bookIds); - Map fileProgressMap = - readingProgressService.fetchUserFileProgress(user.getId(), bookIds); - - books.forEach(book -> { - readingProgressService.enrichBookWithProgress( - book, - progressMap.get(book.getId()), - fileProgressMap.get(book.getId()) - ); - Set filtered = filterShelvesByUserId(book.getShelves(), user.getId()); - book.setShelves(!includeDescription && filtered != null && filtered.isEmpty() ? null : filtered); - }); - - return books; - } - - private long toEpochMilli(Object value) { - if (value == null) return 0; - if (value instanceof Instant inst) return inst.toEpochMilli(); - if (value instanceof Timestamp ts) return ts.toInstant().toEpochMilli(); - return 0; - } - - private Object[] extractStatsRow(Object[] result) { - if (result.length > 0 && result[0] instanceof Object[]) { - return (Object[]) result[0]; - } - return result; - } - private Set getUserLibraryIds(BookLoreUser user) { return user.getAssignedLibraries().stream() .map(Library::getId) diff --git a/booklore-api/src/main/java/org/booklore/service/book/DuplicateDetectionService.java b/booklore-api/src/main/java/org/booklore/service/book/DuplicateDetectionService.java new file mode 100644 index 000000000..3dc6888ec --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/service/book/DuplicateDetectionService.java @@ -0,0 +1,332 @@ +package org.booklore.service.book; + +import org.booklore.mapper.BookMapper; +import org.booklore.model.dto.Book; +import org.booklore.model.dto.request.DuplicateDetectionRequest; +import org.booklore.model.dto.response.DuplicateGroup; +import org.booklore.model.entity.AuthorEntity; +import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; +import org.booklore.model.entity.BookMetadataEntity; +import org.booklore.model.enums.BookFileType; +import org.booklore.repository.BookRepository; +import org.booklore.util.BookUtils; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; +import java.util.stream.Collectors; + +@RequiredArgsConstructor +@Service +public class DuplicateDetectionService { + + private static final List DEFAULT_FORMAT_PRIORITY = List.of( + BookFileType.EPUB, BookFileType.PDF, BookFileType.AZW3, + BookFileType.MOBI, BookFileType.FB2, BookFileType.CBX, BookFileType.AUDIOBOOK + ); + + private final BookRepository bookRepository; + private final BookMapper bookMapper; + + @Transactional(readOnly = true) + public List findDuplicates(DuplicateDetectionRequest request) { + List books = bookRepository.findAllForDuplicateDetection(request.libraryId()); + if (books.size() < 2) { + return List.of(); + } + + List formatPriority = books.getFirst().getLibrary() != null + ? books.getFirst().getLibrary().getFormatPriority() + : null; + if (formatPriority == null || formatPriority.isEmpty()) { + formatPriority = DEFAULT_FORMAT_PRIORITY; + } + + Set alreadyGrouped = new HashSet<>(); + List groups = new ArrayList<>(); + + if (request.matchByIsbn()) { + groups.addAll(findByIsbn(books, alreadyGrouped, formatPriority)); + } + if (request.matchByExternalId()) { + groups.addAll(findByExternalId(books, alreadyGrouped, formatPriority)); + } + if (request.matchByTitleAuthor()) { + groups.addAll(findByTitleAuthor(books, alreadyGrouped, formatPriority)); + } + if (request.matchByDirectory()) { + groups.addAll(findByDirectory(books, alreadyGrouped, formatPriority)); + } + if (request.matchByFilename()) { + groups.addAll(findByFilename(books, alreadyGrouped, formatPriority)); + } + + return groups; + } + + private List findByIsbn(List books, Set alreadyGrouped, List formatPriority) { + Map> isbnGroups = new HashMap<>(); + + for (BookEntity book : books) { + if (alreadyGrouped.contains(book.getId())) continue; + BookMetadataEntity meta = book.getMetadata(); + if (meta == null) continue; + + String isbn13 = meta.getIsbn13(); + if (isbn13 == null && meta.getIsbn10() != null) { + isbn13 = BookUtils.isbn10To13(meta.getIsbn10()); + } + if (isbn13 != null && !isbn13.isBlank()) { + isbnGroups.computeIfAbsent(isbn13.trim(), k -> new ArrayList<>()).add(book); + } + } + + return buildGroups(isbnGroups, "ISBN", alreadyGrouped, formatPriority); + } + + private List findByExternalId(List books, Set alreadyGrouped, List formatPriority) { + Map parent = new HashMap<>(); + Map bookMap = new HashMap<>(); + + List candidates = books.stream() + .filter(b -> !alreadyGrouped.contains(b.getId())) + .filter(b -> b.getMetadata() != null) + .toList(); + + for (BookEntity book : candidates) { + bookMap.put(book.getId(), book); + parent.put(book.getId(), book.getId()); + } + + Map idToBook = new HashMap<>(); + for (BookEntity book : candidates) { + BookMetadataEntity meta = book.getMetadata(); + List externalIds = extractExternalIds(meta); + for (String extId : externalIds) { + if (idToBook.containsKey(extId)) { + union(parent, book.getId(), idToBook.get(extId)); + } else { + idToBook.put(extId, book.getId()); + } + } + } + + Map> groups = new HashMap<>(); + for (BookEntity book : candidates) { + Long root = find(parent, book.getId()); + groups.computeIfAbsent(root, k -> new ArrayList<>()).add(book); + } + + List result = new ArrayList<>(); + for (List group : groups.values()) { + if (group.size() < 2) continue; + group.forEach(b -> alreadyGrouped.add(b.getId())); + result.add(toDuplicateGroup(group, "EXTERNAL_ID", formatPriority)); + } + return result; + } + + private List extractExternalIds(BookMetadataEntity meta) { + List ids = new ArrayList<>(); + addIfPresent(ids, "goodreads:", meta.getGoodreadsId()); + addIfPresent(ids, "hardcover:", meta.getHardcoverId()); + addIfPresent(ids, "google:", meta.getGoogleId()); + addIfPresent(ids, "asin:", meta.getAsin()); + addIfPresent(ids, "audible:", meta.getAudibleId()); + addIfPresent(ids, "comicvine:", meta.getComicvineId()); + return ids; + } + + private void addIfPresent(List list, String prefix, String value) { + if (value != null && !value.isBlank()) { + list.add(prefix + value.trim()); + } + } + + private Long find(Map parent, Long x) { + while (!parent.get(x).equals(x)) { + parent.put(x, parent.get(parent.get(x))); + x = parent.get(x); + } + return x; + } + + private void union(Map parent, Long a, Long b) { + Long rootA = find(parent, a); + Long rootB = find(parent, b); + if (!rootA.equals(rootB)) { + parent.put(rootA, rootB); + } + } + + private List findByTitleAuthor(List books, Set alreadyGrouped, List formatPriority) { + Map> titleGroups = new HashMap<>(); + + for (BookEntity book : books) { + if (alreadyGrouped.contains(book.getId())) continue; + BookMetadataEntity meta = book.getMetadata(); + if (meta == null || meta.getTitle() == null || meta.getTitle().isBlank()) continue; + + String normalizedTitle = BookUtils.normalizeForSearch(meta.getTitle()); + if (normalizedTitle != null && !normalizedTitle.isBlank()) { + titleGroups.computeIfAbsent(normalizedTitle, k -> new ArrayList<>()).add(book); + } + } + + List result = new ArrayList<>(); + for (List group : titleGroups.values()) { + if (group.size() < 2) continue; + + List withAuthors = group.stream() + .filter(b -> b.getMetadata().getAuthors() != null && !b.getMetadata().getAuthors().isEmpty()) + .toList(); + + if (withAuthors.size() < 2) continue; + + Map> normalizedAuthors = new HashMap<>(); + for (BookEntity book : withAuthors) { + Set names = book.getMetadata().getAuthors().stream() + .map(AuthorEntity::getName) + .filter(Objects::nonNull) + .map(BookUtils::normalizeForSearch) + .collect(Collectors.toSet()); + normalizedAuthors.put(book.getId(), names); + } + + Map parent = new HashMap<>(); + for (BookEntity book : withAuthors) { + parent.put(book.getId(), book.getId()); + } + + for (int i = 0; i < withAuthors.size(); i++) { + for (int j = i + 1; j < withAuthors.size(); j++) { + Set authorsI = normalizedAuthors.get(withAuthors.get(i).getId()); + Set authorsJ = normalizedAuthors.get(withAuthors.get(j).getId()); + boolean overlap = authorsI.stream().anyMatch(authorsJ::contains); + if (overlap) { + union(parent, withAuthors.get(i).getId(), withAuthors.get(j).getId()); + } + } + } + + Map> subGroups = new HashMap<>(); + for (BookEntity book : withAuthors) { + Long root = find(parent, book.getId()); + subGroups.computeIfAbsent(root, k -> new ArrayList<>()).add(book); + } + + for (List subGroup : subGroups.values()) { + if (subGroup.size() < 2) continue; + subGroup.forEach(b -> alreadyGrouped.add(b.getId())); + result.add(toDuplicateGroup(subGroup, "TITLE_AUTHOR", formatPriority)); + } + } + + return result; + } + + private List findByDirectory(List books, Set alreadyGrouped, List formatPriority) { + Map> dirGroups = new HashMap<>(); + + for (BookEntity book : books) { + if (alreadyGrouped.contains(book.getId())) continue; + if (book.getLibraryPath() == null) continue; + + List bookFiles = book.getBookFiles(); + if (bookFiles == null || bookFiles.isEmpty()) continue; + + BookFileEntity primary = bookFiles.stream() + .filter(BookFileEntity::isBookFormat) + .findFirst() + .orElse(null); + if (primary == null) continue; + + String subPath = primary.getFileSubPath(); + if (subPath == null || subPath.isBlank()) continue; + + String key = book.getLibraryPath().getId() + ":" + subPath; + dirGroups.computeIfAbsent(key, k -> new ArrayList<>()).add(book); + } + + return buildGroups(dirGroups, "DIRECTORY", alreadyGrouped, formatPriority); + } + + private List findByFilename(List books, Set alreadyGrouped, List formatPriority) { + Map> nameGroups = new HashMap<>(); + + for (BookEntity book : books) { + if (alreadyGrouped.contains(book.getId())) continue; + + List bookFiles = book.getBookFiles(); + if (bookFiles == null || bookFiles.isEmpty()) continue; + + BookFileEntity primary = bookFiles.stream() + .filter(BookFileEntity::isBookFormat) + .findFirst() + .orElse(null); + if (primary == null || primary.getFileName() == null) continue; + + String fileName = primary.getFileName(); + int dotIdx = fileName.lastIndexOf('.'); + String baseName = dotIdx > 0 ? fileName.substring(0, dotIdx) : fileName; + + String normalized = baseName.toLowerCase() + .replaceAll("[_\\-]", " ") + .replaceAll("[^a-z0-9\\s]", "") + .replaceAll("\\s+", " ") + .trim(); + + if (!normalized.isBlank()) { + nameGroups.computeIfAbsent(normalized, k -> new ArrayList<>()).add(book); + } + } + + return buildGroups(nameGroups, "FILENAME", alreadyGrouped, formatPriority); + } + + private List buildGroups(Map> groupMap, String reason, + Set alreadyGrouped, List formatPriority) { + List result = new ArrayList<>(); + for (List group : groupMap.values()) { + if (group.size() < 2) continue; + group.forEach(b -> alreadyGrouped.add(b.getId())); + result.add(toDuplicateGroup(group, reason, formatPriority)); + } + return result; + } + + private DuplicateGroup toDuplicateGroup(List entities, String reason, List formatPriority) { + BookEntity suggested = entities.stream() + .max(Comparator + .comparingInt((BookEntity b) -> formatPriorityScore(b, formatPriority)) + .thenComparingLong(b -> b.getBookFiles() == null ? 0 : + b.getBookFiles().stream().filter(BookFileEntity::isBookFormat).count()) + .thenComparing(b -> b.getMetadataMatchScore() != null ? b.getMetadataMatchScore() : 0f) + .thenComparing(BookEntity::getId, Comparator.reverseOrder())) + .orElse(entities.getFirst()); + + List books = entities.stream() + .map(bookMapper::toBook) + .toList(); + + return new DuplicateGroup(suggested.getId(), reason, books); + } + + private int formatPriorityScore(BookEntity book, List formatPriority) { + if (book.getBookFiles() == null) { + return 0; + } + int bestScore = 0; + for (BookFileEntity file : book.getBookFiles()) { + if (!file.isBookFormat() || file.getBookType() == null) continue; + int index = formatPriority.indexOf(file.getBookType()); + if (index >= 0) { + int score = formatPriority.size() - index; + bestScore = Math.max(bestScore, score); + } + } + return bestScore; + } +} diff --git a/booklore-api/src/main/java/org/booklore/service/library/BookDeletionService.java b/booklore-api/src/main/java/org/booklore/service/library/BookDeletionService.java index b8051a922..ee9b42680 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/BookDeletionService.java +++ b/booklore-api/src/main/java/org/booklore/service/library/BookDeletionService.java @@ -3,6 +3,8 @@ package org.booklore.service.library; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.LibraryEntity; +import org.booklore.model.enums.BookFileType; import org.booklore.model.websocket.Topic; import org.booklore.repository.BookAdditionalFileRepository; import org.booklore.repository.BookRepository; @@ -94,6 +96,53 @@ public class BookDeletionService { if (bookIds.size() > 1) log.info("Books removed: {}", bookIds); } + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void purgeDisallowedFormats(LibraryEntity libraryEntity) { + List allowedFormats = libraryEntity.getAllowedFormats(); + if (allowedFormats == null || allowedFormats.isEmpty()) { + return; + } + + Set allowed = EnumSet.copyOf(allowedFormats); + List allBookFiles = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId()); + + List disallowedFiles = allBookFiles.stream() + .filter(BookFileEntity::isBook) + .filter(bf -> !allowed.contains(bf.getBookType())) + .toList(); + + if (disallowedFiles.isEmpty()) { + return; + } + + Set affectedBookIds = disallowedFiles.stream() + .map(bf -> bf.getBook().getId()) + .collect(Collectors.toSet()); + + Map remainingCounts = allBookFiles.stream() + .filter(BookFileEntity::isBook) + .filter(bf -> allowed.contains(bf.getBookType())) + .filter(bf -> affectedBookIds.contains(bf.getBook().getId())) + .collect(Collectors.groupingBy(bf -> bf.getBook().getId(), Collectors.counting())); + + List booksToDelete = affectedBookIds.stream() + .filter(bookId -> remainingCounts.getOrDefault(bookId, 0L) == 0) + .toList(); + + bookAdditionalFileRepository.deleteAll(disallowedFiles); + entityManager.flush(); + entityManager.clear(); + + if (!booksToDelete.isEmpty()) { + log.info("Deleting {} books with no remaining files of allowed formats in library: {}", + booksToDelete.size(), libraryEntity.getName()); + deleteRemovedBooks(booksToDelete); + } + + log.info("Purged {} book files of disallowed formats from library: {}", + disallowedFiles.size(), libraryEntity.getName()); + } + private boolean tryPromoteAlternativeFormatToBook(BookEntity book, List libraryFiles) { Set existingFileNames = libraryFiles.stream() .map(LibraryFile::getFileName) diff --git a/booklore-api/src/main/java/org/booklore/service/library/BookGroupingService.java b/booklore-api/src/main/java/org/booklore/service/library/BookGroupingService.java index eaa82158d..85ba83ccd 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/BookGroupingService.java +++ b/booklore-api/src/main/java/org/booklore/service/library/BookGroupingService.java @@ -138,20 +138,23 @@ public class BookGroupingService { .filter(BookEntity::hasFiles) .toList(); - if (booksWithFiles.size() == 1) { - BookEntity book = booksWithFiles.get(0); - log.debug("BOOK_PER_FOLDER: Attaching '{}' to single book in folder: '{}'", - file.getFileName(), book.getPrimaryBookFile().getFileName()); - return book; + if (booksWithFiles.isEmpty()) { + return null; } - if (booksWithFiles.isEmpty()) { + if (booksWithFiles.size() == 1) { + BookEntity book = booksWithFiles.get(0); + if (isFileNameCompatible(file, book)) { + log.debug("BOOK_PER_FOLDER: Attaching '{}' to single book in folder: '{}'", + file.getFileName(), book.getPrimaryBookFile().getFileName()); + return book; + } return null; } log.warn("BOOK_PER_FOLDER: Multiple books ({}) in folder '{}', using filename match", booksWithFiles.size(), file.getFileSubPath()); - return findExactMatch(file, booksWithFiles); + return findBestMatch(file, booksWithFiles); } private BookEntity findMatchAutoDetect(LibraryFile file, List booksInDirectory) { @@ -165,11 +168,18 @@ public class BookGroupingService { if (booksWithFiles.size() == 1) { BookEntity book = booksWithFiles.get(0); - log.debug("AUTO_DETECT: Single book in folder '{}', attaching '{}' to '{}'", - file.getFileSubPath(), file.getFileName(), book.getPrimaryBookFile().getFileName()); - return book; + if (isFileNameCompatible(file, book)) { + log.debug("AUTO_DETECT: Single book in folder '{}', attaching '{}' to '{}'", + file.getFileSubPath(), file.getFileName(), book.getPrimaryBookFile().getFileName()); + return book; + } + return null; } + return findBestMatch(file, booksWithFiles); + } + + private BookEntity findBestMatch(LibraryFile file, List booksWithFiles) { String fileGroupingKey = BookFileGroupingUtils.extractGroupingKey(file.getFileName()); BookEntity bestMatch = null; double bestSimilarity = 0; @@ -190,12 +200,25 @@ public class BookGroupingService { } if (bestMatch != null) { - log.debug("AUTO_DETECT: Fuzzy matched '{}' to '{}' (similarity: {})", + log.debug("Fuzzy matched '{}' to '{}' (similarity: {})", file.getFileName(), bestMatch.getPrimaryBookFile().getFileName(), bestSimilarity); } return bestMatch; } + private boolean isFileNameCompatible(LibraryFile file, BookEntity book) { + BookFileEntity primaryFile = book.getPrimaryBookFile(); + if (primaryFile == null) { + return false; + } + String fileKey = BookFileGroupingUtils.extractGroupingKey(file.getFileName()); + String bookKey = BookFileGroupingUtils.extractGroupingKey(primaryFile.getFileName()); + if (fileKey.equals(bookKey)) { + return true; + } + return BookFileGroupingUtils.calculateSimilarity(fileKey, bookKey) >= 0.85; + } + private BookEntity findExactMatch(LibraryFile file, List books) { String fileKey = BookFileGroupingUtils.extractGroupingKey(file.getFileName()); diff --git a/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java b/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java index 94f65aac1..22228209a 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java +++ b/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java @@ -32,15 +32,19 @@ public class LibraryFileHelper { private static final int MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK = 2; - public List getLibraryFiles(LibraryEntity libraryEntity) throws IOException { + public List getAllLibraryFiles(LibraryEntity libraryEntity) throws IOException { List allFiles = new ArrayList<>(); for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) { allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity)); } - return filterByAllowedFormats(allFiles, libraryEntity.getAllowedFormats()); + return allFiles; } - private List filterByAllowedFormats(List files, List allowedFormats) { + public List getLibraryFiles(LibraryEntity libraryEntity) throws IOException { + return filterByAllowedFormats(getAllLibraryFiles(libraryEntity), libraryEntity.getAllowedFormats()); + } + + List filterByAllowedFormats(List files, List allowedFormats) { if (allowedFormats == null || allowedFormats.isEmpty()) { return files; } diff --git a/booklore-api/src/main/java/org/booklore/service/library/LibraryProcessingService.java b/booklore-api/src/main/java/org/booklore/service/library/LibraryProcessingService.java index 12f458408..1c7b64540 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/LibraryProcessingService.java +++ b/booklore-api/src/main/java/org/booklore/service/library/LibraryProcessingService.java @@ -74,10 +74,12 @@ public class LibraryProcessingService { validateLibraryPathsAccessible(libraryEntity); - List libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity); + List allLibraryFiles = libraryFileHelper.getAllLibraryFiles(libraryEntity); + List filteredFiles = libraryFileHelper.filterByAllowedFormats( + allLibraryFiles, libraryEntity.getAllowedFormats()); int existingBookCount = libraryEntity.getBookEntities().size(); - if (existingBookCount > 0 && libraryFiles.isEmpty()) { + if (existingBookCount > 0 && allLibraryFiles.isEmpty()) { String paths = libraryEntity.getLibraryPaths().stream() .map(LibraryPathEntity::getPath) .collect(Collectors.joining(", ")); @@ -86,23 +88,24 @@ public class LibraryProcessingService { throw ApiError.LIBRARY_PATH_NOT_ACCESSIBLE.createException(paths); } - List additionalFileIds = detectDeletedAdditionalFiles(libraryFiles, libraryEntity); + List additionalFileIds = detectDeletedAdditionalFiles(allLibraryFiles, libraryEntity); if (!additionalFileIds.isEmpty()) { log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName()); bookDeletionService.deleteRemovedAdditionalFiles(additionalFileIds); } - List bookIds = detectDeletedBookIds(libraryFiles, libraryEntity); + List bookIds = detectDeletedBookIds(allLibraryFiles, libraryEntity); if (!bookIds.isEmpty()) { log.info("Detected {} removed books in library: {}", bookIds.size(), libraryEntity.getName()); - bookDeletionService.processDeletedLibraryFiles(bookIds, libraryFiles); + bookDeletionService.processDeletedLibraryFiles(bookIds, allLibraryFiles); } - bookRestorationService.restoreDeletedBooks(libraryFiles); + bookRestorationService.restoreDeletedBooks(allLibraryFiles); + bookDeletionService.purgeDisallowedFormats(libraryEntity); entityManager.clear(); // Re-fetch library entity to get fresh state after entity manager was cleared libraryEntity = libraryRepository.findById(context.getLibraryId()) .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(context.getLibraryId())); - List newFiles = detectNewBookPaths(libraryFiles, libraryEntity); + List newFiles = detectNewBookPaths(filteredFiles, libraryEntity); // Use BookGroupingService to determine what to attach vs create new BookGroupingService.GroupingResult groupingResult = bookGroupingService.groupForRescan(newFiles, libraryEntity); diff --git a/booklore-api/src/test/java/org/booklore/service/book/DuplicateDetectionServiceTest.java b/booklore-api/src/test/java/org/booklore/service/book/DuplicateDetectionServiceTest.java new file mode 100644 index 000000000..14a5585f7 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/book/DuplicateDetectionServiceTest.java @@ -0,0 +1,964 @@ +package org.booklore.service.book; + +import org.booklore.mapper.BookMapper; +import org.booklore.model.dto.Book; +import org.booklore.model.dto.request.DuplicateDetectionRequest; +import org.booklore.model.dto.response.DuplicateGroup; +import org.booklore.model.entity.*; +import org.booklore.model.enums.BookFileType; +import org.booklore.repository.BookRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +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.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class DuplicateDetectionServiceTest { + + @Mock + private BookRepository bookRepository; + + @Mock + private BookMapper bookMapper; + + @InjectMocks + private DuplicateDetectionService service; + + private static final Long LIBRARY_ID = 1L; + private long nextBookId = 1L; + + private LibraryEntity library; + + @BeforeEach + void setUp() { + library = LibraryEntity.builder().id(LIBRARY_ID).name("Test Library").build(); + nextBookId = 1L; + lenient().when(bookMapper.toBook(any(BookEntity.class))).thenAnswer(inv -> { + BookEntity entity = inv.getArgument(0); + return Book.builder().id(entity.getId()).build(); + }); + } + + // ── Helper methods ────────────────────────────────────────── + + private BookEntity createBook(BookFileType fileType, String title, String authorName) { + long id = nextBookId++; + BookFileEntity file = BookFileEntity.builder() + .id(id * 100) + .fileName("book" + id + "." + fileType.getExtensions().iterator().next()) + .fileSubPath("books") + .isBookFormat(true) + .bookType(fileType) + .build(); + + Set authors = new HashSet<>(); + if (authorName != null) { + authors.add(AuthorEntity.builder().id(id * 10).name(authorName).build()); + } + + BookMetadataEntity metadata = BookMetadataEntity.builder() + .bookId(id) + .title(title) + .authors(authors) + .build(); + + BookEntity book = BookEntity.builder() + .id(id) + .library(library) + .metadata(metadata) + .bookFiles(new ArrayList<>(List.of(file))) + .build(); + + file.setBook(book); + return book; + } + + private BookEntity createBookWithIsbn(BookFileType fileType, String title, String authorName, + String isbn13, String isbn10) { + BookEntity book = createBook(fileType, title, authorName); + book.getMetadata().setIsbn13(isbn13); + book.getMetadata().setIsbn10(isbn10); + return book; + } + + private DuplicateDetectionRequest allSignals() { + return new DuplicateDetectionRequest(LIBRARY_ID, true, true, true, true, true); + } + + private DuplicateDetectionRequest onlyIsbn() { + return new DuplicateDetectionRequest(LIBRARY_ID, true, false, false, false, false); + } + + private DuplicateDetectionRequest onlyExternalId() { + return new DuplicateDetectionRequest(LIBRARY_ID, false, true, false, false, false); + } + + private DuplicateDetectionRequest onlyTitleAuthor() { + return new DuplicateDetectionRequest(LIBRARY_ID, false, false, true, false, false); + } + + private DuplicateDetectionRequest onlyDirectory() { + return new DuplicateDetectionRequest(LIBRARY_ID, false, false, false, true, false); + } + + private DuplicateDetectionRequest onlyFilename() { + return new DuplicateDetectionRequest(LIBRARY_ID, false, false, false, false, true); + } + + private void stubBooks(BookEntity... books) { + when(bookRepository.findAllForDuplicateDetection(LIBRARY_ID)).thenReturn(List.of(books)); + } + + // ── General tests ─────────────────────────────────────────── + + @Nested + class General { + + @Test + void returnsEmptyWhenLessThanTwoBooks() { + BookEntity single = createBook(BookFileType.EPUB, "Solo Book", "Author"); + stubBooks(single); + + List result = service.findDuplicates(allSignals()); + + assertThat(result).isEmpty(); + } + + @Test + void returnsEmptyWhenNoBooksInLibrary() { + when(bookRepository.findAllForDuplicateDetection(LIBRARY_ID)).thenReturn(List.of()); + + List result = service.findDuplicates(allSignals()); + + assertThat(result).isEmpty(); + } + + @Test + void returnsEmptyWhenNoSignalsEnabled() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "Same", "Author", "9781234567890", null); + BookEntity book2 = createBookWithIsbn(BookFileType.MOBI, "Same", "Author", "9781234567890", null); + stubBooks(book1, book2); + + DuplicateDetectionRequest noSignals = new DuplicateDetectionRequest(LIBRARY_ID, false, false, false, false, false); + List result = service.findDuplicates(noSignals); + + assertThat(result).isEmpty(); + } + + @Test + void returnsEmptyWhenNoDuplicatesExist() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book A", "Author X"); + BookEntity book2 = createBook(BookFileType.MOBI, "Book B", "Author Y"); + stubBooks(book1, book2); + + List result = service.findDuplicates(allSignals()); + + assertThat(result).isEmpty(); + } + } + + // ── ISBN matching ─────────────────────────────────────────── + + @Nested + class IsbnMatching { + + @Test + void groupsBooksWithSameIsbn13() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "Book", "Author", "9781234567890", null); + BookEntity book2 = createBookWithIsbn(BookFileType.MOBI, "Book", "Author", "9781234567890", null); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyIsbn()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().matchReason()).isEqualTo("ISBN"); + assertThat(result.getFirst().books()).hasSize(2); + } + + @Test + void convertsIsbn10ToIsbn13ForMatching() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "Book", "Author", "9780306406157", null); + BookEntity book2 = createBookWithIsbn(BookFileType.MOBI, "Book", "Author", null, "0306406152"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyIsbn()); + + assertThat(result).hasSize(1); + } + + @Test + void doesNotGroupDifferentIsbns() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "Book A", "Author", "9781234567890", null); + BookEntity book2 = createBookWithIsbn(BookFileType.MOBI, "Book B", "Author", "9780987654321", null); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyIsbn()); + + assertThat(result).isEmpty(); + } + + @Test + void skipsBooksWithNullMetadata() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "Book", "Author", "9781234567890", null); + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.setMetadata(null); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyIsbn()); + + assertThat(result).isEmpty(); + } + + @Test + void skipsBooksWithBlankIsbn() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "Book", "Author", " ", null); + BookEntity book2 = createBookWithIsbn(BookFileType.MOBI, "Book", "Author", " ", null); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyIsbn()); + + assertThat(result).isEmpty(); + } + + @Test + void trimsIsbnBeforeGrouping() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "Book", "Author", "9781234567890 ", null); + BookEntity book2 = createBookWithIsbn(BookFileType.MOBI, "Book", "Author", " 9781234567890", null); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyIsbn()); + + assertThat(result).hasSize(1); + } + } + + // ── External ID matching ──────────────────────────────────── + + @Nested + class ExternalIdMatching { + + @Test + void groupsBooksWithSameGoodreadsId() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book A", "Author"); + book1.getMetadata().setGoodreadsId("12345"); + BookEntity book2 = createBook(BookFileType.MOBI, "Book B", "Author"); + book2.getMetadata().setGoodreadsId("12345"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyExternalId()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().matchReason()).isEqualTo("EXTERNAL_ID"); + } + + @Test + void groupsBooksWithSameAsin() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book A", "Author"); + book1.getMetadata().setAsin("B0ABCDEFGH"); + BookEntity book2 = createBook(BookFileType.MOBI, "Book B", "Author"); + book2.getMetadata().setAsin("B0ABCDEFGH"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyExternalId()); + + assertThat(result).hasSize(1); + } + + @Test + void unionFindGroupsTransitively() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.getMetadata().setGoodreadsId("111"); + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.getMetadata().setGoodreadsId("111"); + book2.getMetadata().setAsin("ASIN1"); + BookEntity book3 = createBook(BookFileType.PDF, "Book", "Author"); + book3.getMetadata().setAsin("ASIN1"); + stubBooks(book1, book2, book3); + + List result = service.findDuplicates(onlyExternalId()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().books()).hasSize(3); + } + + @Test + void doesNotGroupBooksWithDifferentExternalIds() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book A", "Author"); + book1.getMetadata().setGoodreadsId("111"); + BookEntity book2 = createBook(BookFileType.MOBI, "Book B", "Author"); + book2.getMetadata().setGoodreadsId("222"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyExternalId()); + + assertThat(result).isEmpty(); + } + + @Test + void skipsBooksWithNoExternalIds() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book A", "Author"); + BookEntity book2 = createBook(BookFileType.MOBI, "Book B", "Author"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyExternalId()); + + assertThat(result).isEmpty(); + } + + @Test + void trimsExternalIdsBeforeGrouping() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book A", "Author"); + book1.getMetadata().setHardcoverId(" abc "); + BookEntity book2 = createBook(BookFileType.MOBI, "Book B", "Author"); + book2.getMetadata().setHardcoverId("abc"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyExternalId()); + + assertThat(result).hasSize(1); + } + + @Test + void matchesAcrossDifferentIdTypes() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book A", "Author"); + book1.getMetadata().setGoodreadsId("shared-id"); + BookEntity book2 = createBook(BookFileType.MOBI, "Book B", "Author"); + book2.getMetadata().setGoodreadsId("shared-id"); + book2.getMetadata().setAudibleId("aud-123"); + BookEntity book3 = createBook(BookFileType.PDF, "Book C", "Author"); + book3.getMetadata().setAudibleId("aud-123"); + stubBooks(book1, book2, book3); + + List result = service.findDuplicates(onlyExternalId()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().books()).hasSize(3); + } + } + + // ── Title + Author matching ───────────────────────────────── + + @Nested + class TitleAuthorMatching { + + @Test + void groupsBooksWithSameTitleAndAuthor() { + BookEntity book1 = createBook(BookFileType.EPUB, "The Great Gatsby", "F. Scott Fitzgerald"); + BookEntity book2 = createBook(BookFileType.MOBI, "The Great Gatsby", "F. Scott Fitzgerald"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().matchReason()).isEqualTo("TITLE_AUTHOR"); + } + + @Test + void matchesCaseInsensitive() { + BookEntity book1 = createBook(BookFileType.EPUB, "THE GREAT GATSBY", "F. SCOTT FITZGERALD"); + BookEntity book2 = createBook(BookFileType.MOBI, "the great gatsby", "f. scott fitzgerald"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + } + + @Test + void doesNotGroupSameTitleDifferentAuthors() { + BookEntity book1 = createBook(BookFileType.EPUB, "Introduction", "Alice Smith"); + BookEntity book2 = createBook(BookFileType.MOBI, "Introduction", "Bob Jones"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).isEmpty(); + } + + @Test + void skipsBooksWithNoAuthors() { + BookEntity book1 = createBook(BookFileType.EPUB, "Orphan Book", null); + book1.getMetadata().setAuthors(new HashSet<>()); + BookEntity book2 = createBook(BookFileType.MOBI, "Orphan Book", null); + book2.getMetadata().setAuthors(new HashSet<>()); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).isEmpty(); + } + + @Test + void skipsBooksWithNullTitle() { + BookEntity book1 = createBook(BookFileType.EPUB, null, "Author"); + BookEntity book2 = createBook(BookFileType.MOBI, null, "Author"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).isEmpty(); + } + + @Test + void skipsBooksWithBlankTitle() { + BookEntity book1 = createBook(BookFileType.EPUB, " ", "Author"); + BookEntity book2 = createBook(BookFileType.MOBI, " ", "Author"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).isEmpty(); + } + + @Test + void groupsByOverlappingAuthors() { + BookEntity book1 = createBook(BookFileType.EPUB, "Collab Work", "Author A"); + book1.getMetadata().getAuthors().add(AuthorEntity.builder().id(90L).name("Author B").build()); + + BookEntity book2 = createBook(BookFileType.MOBI, "Collab Work", "Author B"); + book2.getMetadata().getAuthors().add(AuthorEntity.builder().id(91L).name("Author C").build()); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + } + + @Test + void requiresAtLeastTwoBooksWithAuthorsInTitleGroup() { + BookEntity book1 = createBook(BookFileType.EPUB, "Solo Title", "Author A"); + BookEntity book2 = createBook(BookFileType.MOBI, "Solo Title", null); + book2.getMetadata().setAuthors(new HashSet<>()); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).isEmpty(); + } + } + + // ── Directory matching ────────────────────────────────────── + + @Nested + class DirectoryMatching { + + @Test + void groupsBooksInSameDirectory() { + LibraryPathEntity path = LibraryPathEntity.builder().id(10L).build(); + + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.setLibraryPath(path); + book1.getBookFiles().getFirst().setFileSubPath("fiction/scifi"); + + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.setLibraryPath(path); + book2.getBookFiles().getFirst().setFileSubPath("fiction/scifi"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyDirectory()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().matchReason()).isEqualTo("DIRECTORY"); + } + + @Test + void doesNotGroupBooksInDifferentDirectories() { + LibraryPathEntity path = LibraryPathEntity.builder().id(10L).build(); + + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.setLibraryPath(path); + book1.getBookFiles().getFirst().setFileSubPath("fiction"); + + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.setLibraryPath(path); + book2.getBookFiles().getFirst().setFileSubPath("nonfiction"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyDirectory()); + + assertThat(result).isEmpty(); + } + + @Test + void doesNotGroupBooksFromDifferentLibraryPaths() { + LibraryPathEntity path1 = LibraryPathEntity.builder().id(10L).build(); + LibraryPathEntity path2 = LibraryPathEntity.builder().id(20L).build(); + + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.setLibraryPath(path1); + book1.getBookFiles().getFirst().setFileSubPath("shared"); + + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.setLibraryPath(path2); + book2.getBookFiles().getFirst().setFileSubPath("shared"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyDirectory()); + + assertThat(result).isEmpty(); + } + + @Test + void skipsBooksWithNullLibraryPath() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.setLibraryPath(null); + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.setLibraryPath(null); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyDirectory()); + + assertThat(result).isEmpty(); + } + + @Test + void skipsBooksWithBlankFileSubPath() { + LibraryPathEntity path = LibraryPathEntity.builder().id(10L).build(); + + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.setLibraryPath(path); + book1.getBookFiles().getFirst().setFileSubPath(" "); + + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.setLibraryPath(path); + book2.getBookFiles().getFirst().setFileSubPath(" "); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyDirectory()); + + assertThat(result).isEmpty(); + } + } + + // ── Filename matching ─────────────────────────────────────── + + @Nested + class FilenameMatching { + + @Test + void groupsBooksWithSameBaseFilename() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.getBookFiles().getFirst().setFileName("my_book.epub"); + + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.getBookFiles().getFirst().setFileName("my_book.mobi"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyFilename()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().matchReason()).isEqualTo("FILENAME"); + } + + @Test + void normalizesUnderscoresHyphensCaseForMatching() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.getBookFiles().getFirst().setFileName("My-Book_Title.epub"); + + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.getBookFiles().getFirst().setFileName("my book title.mobi"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyFilename()); + + assertThat(result).hasSize(1); + } + + @Test + void stripsPunctuationForMatching() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.getBookFiles().getFirst().setFileName("book!@#title.epub"); + + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.getBookFiles().getFirst().setFileName("booktitle.mobi"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyFilename()); + + assertThat(result).hasSize(1); + } + + @Test + void doesNotGroupDifferentFilenames() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.getBookFiles().getFirst().setFileName("alpha.epub"); + + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.getBookFiles().getFirst().setFileName("beta.mobi"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyFilename()); + + assertThat(result).isEmpty(); + } + + @Test + void skipsBooksWithNoBookFiles() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.setBookFiles(new ArrayList<>()); + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.setBookFiles(new ArrayList<>()); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyFilename()); + + assertThat(result).isEmpty(); + } + + @Test + void skipsBooksWithNullBookFiles() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.setBookFiles(null); + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.setBookFiles(null); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyFilename()); + + assertThat(result).isEmpty(); + } + } + + // ── Strategy ordering (already-grouped exclusion) ─────────── + + @Nested + class StrategyOrdering { + + @Test + void higherConfidenceStrategyPreventsLowerFromRegrouping() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "Same Title", "Same Author", "9781234567890", null); + book1.getMetadata().setGoodreadsId("gr1"); + BookEntity book2 = createBookWithIsbn(BookFileType.MOBI, "Same Title", "Same Author", "9781234567890", null); + book2.getMetadata().setGoodreadsId("gr1"); + stubBooks(book1, book2); + + List result = service.findDuplicates(allSignals()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().matchReason()).isEqualTo("ISBN"); + } + + @Test + void booksGroupedByIsbnNotRegroupedByTitleAuthor() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "The Book", "Author", "9781234567890", null); + BookEntity book2 = createBookWithIsbn(BookFileType.MOBI, "The Book", "Author", "9781234567890", null); + BookEntity book3 = createBook(BookFileType.PDF, "The Book", "Author"); + BookEntity book4 = createBook(BookFileType.AZW3, "The Book", "Author"); + stubBooks(book1, book2, book3, book4); + + List result = service.findDuplicates(allSignals()); + + assertThat(result).hasSize(2); + + DuplicateGroup isbnGroup = result.stream() + .filter(g -> g.matchReason().equals("ISBN")).findFirst().orElseThrow(); + DuplicateGroup titleGroup = result.stream() + .filter(g -> g.matchReason().equals("TITLE_AUTHOR")).findFirst().orElseThrow(); + + assertThat(isbnGroup.books()).hasSize(2); + assertThat(titleGroup.books()).hasSize(2); + + Set isbnBookIds = new HashSet<>(); + isbnGroup.books().forEach(b -> isbnBookIds.add(b.getId())); + assertThat(isbnBookIds).containsExactlyInAnyOrder(book1.getId(), book2.getId()); + + Set titleBookIds = new HashSet<>(); + titleGroup.books().forEach(b -> titleBookIds.add(b.getId())); + assertThat(titleBookIds).containsExactlyInAnyOrder(book3.getId(), book4.getId()); + } + + @Test + void multipleStrategiesCreateSeparateGroups() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "Book A", "Author A", "9781234567890", null); + BookEntity book2 = createBookWithIsbn(BookFileType.MOBI, "Book A", "Author A", "9781234567890", null); + + BookEntity book3 = createBook(BookFileType.EPUB, "Book B", "Author B"); + BookEntity book4 = createBook(BookFileType.MOBI, "Book B", "Author B"); + stubBooks(book1, book2, book3, book4); + + List result = service.findDuplicates(allSignals()); + + assertThat(result).hasSize(2); + } + } + + // ── Target selection ──────────────────────────────────────── + + @Nested + class TargetSelection { + + @Test + void defaultPriorityPrefersEpubOverMobi() { + BookEntity mobi = createBook(BookFileType.MOBI, "Book", "Author"); + BookEntity epub = createBook(BookFileType.EPUB, "Book", "Author"); + stubBooks(mobi, epub); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(epub.getId()); + } + + @Test + void defaultPriorityPrefersEpubOverPdf() { + BookEntity pdf = createBook(BookFileType.PDF, "Book", "Author"); + BookEntity epub = createBook(BookFileType.EPUB, "Book", "Author"); + stubBooks(pdf, epub); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(epub.getId()); + } + + @Test + void defaultPriorityPrefersPdfOverMobi() { + BookEntity mobi = createBook(BookFileType.MOBI, "Book", "Author"); + BookEntity pdf = createBook(BookFileType.PDF, "Book", "Author"); + stubBooks(mobi, pdf); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(pdf.getId()); + } + + @Test + void defaultPriorityPrefersAzw3OverMobi() { + BookEntity mobi = createBook(BookFileType.MOBI, "Book", "Author"); + BookEntity azw3 = createBook(BookFileType.AZW3, "Book", "Author"); + stubBooks(mobi, azw3); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(azw3.getId()); + } + + @Test + void usesLibraryFormatPriorityWhenConfigured() { + library.setFormatPriority(List.of(BookFileType.MOBI, BookFileType.EPUB)); + + BookEntity epub = createBook(BookFileType.EPUB, "Book", "Author"); + BookEntity mobi = createBook(BookFileType.MOBI, "Book", "Author"); + stubBooks(epub, mobi); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(mobi.getId()); + } + + @Test + void fallsBackToDefaultWhenLibraryPriorityEmpty() { + library.setFormatPriority(new ArrayList<>()); + + BookEntity mobi = createBook(BookFileType.MOBI, "Book", "Author"); + BookEntity epub = createBook(BookFileType.EPUB, "Book", "Author"); + stubBooks(mobi, epub); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(epub.getId()); + } + + @Test + void fallsBackToDefaultWhenLibraryPriorityNull() { + library.setFormatPriority(null); + + BookEntity mobi = createBook(BookFileType.MOBI, "Book", "Author"); + BookEntity epub = createBook(BookFileType.EPUB, "Book", "Author"); + stubBooks(mobi, epub); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(epub.getId()); + } + + @Test + void tiebreaksByFileCountWhenFormatPriorityEqual() { + BookEntity singleFile = createBook(BookFileType.EPUB, "Book", "Author"); + + BookEntity multiFile = createBook(BookFileType.EPUB, "Book", "Author"); + BookFileEntity extraFile = BookFileEntity.builder() + .id(999L) + .fileName("extra.pdf") + .fileSubPath("books") + .isBookFormat(true) + .bookType(BookFileType.PDF) + .book(multiFile) + .build(); + multiFile.getBookFiles().add(extraFile); + stubBooks(singleFile, multiFile); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(multiFile.getId()); + } + + @Test + void tiebreaksByMetadataMatchScoreWhenFileCountEqual() { + BookEntity lowScore = createBook(BookFileType.EPUB, "Book", "Author"); + lowScore.setMetadataMatchScore(0.5f); + + BookEntity highScore = createBook(BookFileType.EPUB, "Book", "Author"); + highScore.setMetadataMatchScore(0.9f); + stubBooks(lowScore, highScore); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(highScore.getId()); + } + + @Test + void handlesNullMetadataMatchScoreGracefully() { + BookEntity nullScore = createBook(BookFileType.EPUB, "Book", "Author"); + nullScore.setMetadataMatchScore(null); + + BookEntity withScore = createBook(BookFileType.EPUB, "Book", "Author"); + withScore.setMetadataMatchScore(0.8f); + stubBooks(nullScore, withScore); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(withScore.getId()); + } + + @Test + void handlesNullLibraryOnBookGracefully() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.setLibrary(null); + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.setLibrary(null); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(book1.getId()); + } + } + + // ── Edge cases ────────────────────────────────────────────── + + @Nested + class EdgeCases { + + @Test + void singletonGroupsAreFiltered() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "Unique A", "Author", "9781111111111", null); + BookEntity book2 = createBookWithIsbn(BookFileType.MOBI, "Unique B", "Author", "9782222222222", null); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyIsbn()); + + assertThat(result).isEmpty(); + } + + @Test + void booksWithOnlyNonBookFilesAreSkippedInFilenameMatch() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.getBookFiles().getFirst().setBookFormat(false); + + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.getBookFiles().getFirst().setBookFormat(false); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyFilename()); + + assertThat(result).isEmpty(); + } + + @Test + void handlesLargeGroupCorrectly() { + List books = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + BookEntity book = createBookWithIsbn(BookFileType.EPUB, "Popular Book", "Author", + "9781234567890", null); + books.add(book); + } + when(bookRepository.findAllForDuplicateDetection(LIBRARY_ID)).thenReturn(books); + + List result = service.findDuplicates(onlyIsbn()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().books()).hasSize(10); + } + + @Test + void bookWithNullBookTypeGetsZeroFormatScore() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.getBookFiles().getFirst().setBookType(null); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().suggestedTargetBookId()).isEqualTo(book1.getId()); + } + + @Test + void handlesFilenameWithNoExtension() { + BookEntity book1 = createBook(BookFileType.EPUB, "Book", "Author"); + book1.getBookFiles().getFirst().setFileName("mybook"); + + BookEntity book2 = createBook(BookFileType.MOBI, "Book", "Author"); + book2.getBookFiles().getFirst().setFileName("mybook"); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyFilename()); + + assertThat(result).hasSize(1); + } + + @Test + void threeBooksInTitleAuthorGroupWithPartialAuthorOverlap() { + BookEntity book1 = createBook(BookFileType.EPUB, "Shared Title", "Author A"); + book1.getMetadata().getAuthors().add(AuthorEntity.builder().id(80L).name("Author B").build()); + + BookEntity book2 = createBook(BookFileType.MOBI, "Shared Title", "Author B"); + book2.getMetadata().getAuthors().add(AuthorEntity.builder().id(81L).name("Author C").build()); + + BookEntity book3 = createBook(BookFileType.PDF, "Shared Title", "Author C"); + stubBooks(book1, book2, book3); + + List result = service.findDuplicates(onlyTitleAuthor()); + + assertThat(result).hasSize(1); + assertThat(result.getFirst().books()).hasSize(3); + } + + @Test + void duplicateGroupContainsCorrectBookDtos() { + BookEntity book1 = createBookWithIsbn(BookFileType.EPUB, "Book", "Author", "9781234567890", null); + BookEntity book2 = createBookWithIsbn(BookFileType.MOBI, "Book", "Author", "9781234567890", null); + stubBooks(book1, book2); + + List result = service.findDuplicates(onlyIsbn()); + + assertThat(result).hasSize(1); + Set bookIds = new HashSet<>(); + for (Book b : result.getFirst().books()) { + bookIds.add(b.getId()); + } + assertThat(bookIds).containsExactlyInAnyOrder(book1.getId(), book2.getId()); + } + } +} diff --git a/booklore-api/src/test/java/org/booklore/service/library/LibraryProcessingServiceRegressionTest.java b/booklore-api/src/test/java/org/booklore/service/library/LibraryProcessingServiceRegressionTest.java index 25bcd29f1..a1e01c4c9 100644 --- a/booklore-api/src/test/java/org/booklore/service/library/LibraryProcessingServiceRegressionTest.java +++ b/booklore-api/src/test/java/org/booklore/service/library/LibraryProcessingServiceRegressionTest.java @@ -89,13 +89,14 @@ class LibraryProcessingServiceRegressionTest { libraryEntity.setBookEntities(List.of(filelessBook)); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of( + when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of( LibraryFile.builder() .libraryPathEntity(pathEntity) .fileName("other.epub") .fileSubPath("") .build() )); + when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class))) .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); diff --git a/booklore-api/src/test/java/org/booklore/service/library/LibraryProcessingServiceTest.java b/booklore-api/src/test/java/org/booklore/service/library/LibraryProcessingServiceTest.java index 1f8b54825..04b08a8aa 100644 --- a/booklore-api/src/test/java/org/booklore/service/library/LibraryProcessingServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/service/library/LibraryProcessingServiceTest.java @@ -356,7 +356,8 @@ class LibraryProcessingServiceTest { .fileName("book.epub") .build(); - when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(epubOnDisk)); + when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(epubOnDisk)); + when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(List.of(epub, pdf, image)); when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity))) .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); @@ -422,7 +423,7 @@ class LibraryProcessingServiceTest { libraryEntity.setBookEntities(List.of(existingBook)); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList()); + when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList()); RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build(); @@ -467,7 +468,8 @@ class LibraryProcessingServiceTest { .build(); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk)); + when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk)); + when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity))) .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); @@ -496,7 +498,8 @@ class LibraryProcessingServiceTest { libraryEntity.setBookEntities(Collections.emptyList()); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList()); + when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList()); + when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity))) .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); @@ -551,7 +554,8 @@ class LibraryProcessingServiceTest { when(libraryRepository.findById(libraryId)) .thenReturn(Optional.of(libraryEntity)) .thenReturn(Optional.of(freshLibraryEntity)); // Second call returns fresh entity - when(libraryFileHelper.getLibraryFiles(any(LibraryEntity.class))).thenReturn(List.of(fileOnDisk)); + when(libraryFileHelper.getAllLibraryFiles(any(LibraryEntity.class))).thenReturn(List.of(fileOnDisk)); + when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class))) .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); diff --git a/booklore-ui/package-lock.json b/booklore-ui/package-lock.json index 7387d3276..f7e0bb0b7 100644 --- a/booklore-ui/package-lock.json +++ b/booklore-ui/package-lock.json @@ -29,7 +29,6 @@ "chartjs-chart-matrix": "^3.0.0", "chartjs-plugin-datalabels": "^2.2.0", "date-fns": "^4.1.0", - "idb": "^8.0.3", "jwt-decode": "^4.0.0", "ng-lazyload-image": "^9.1.3", "ng2-charts": "^8.0.0", @@ -7316,12 +7315,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/idb": { - "version": "8.0.3", - "resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz", - "integrity": "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==", - "license": "ISC" - }, "node_modules/ignore": { "version": "7.0.5", "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", diff --git a/booklore-ui/package.json b/booklore-ui/package.json index 6e38c9888..c09913950 100644 --- a/booklore-ui/package.json +++ b/booklore-ui/package.json @@ -33,7 +33,6 @@ "chartjs-chart-matrix": "^3.0.0", "chartjs-plugin-datalabels": "^2.2.0", "date-fns": "^4.1.0", - "idb": "^8.0.3", "jwt-decode": "^4.0.0", "ng-lazyload-image": "^9.1.3", "ng2-charts": "^8.0.0", diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts b/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts index 341fbd2ff..8b8923f7e 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts @@ -17,6 +17,7 @@ import {Book} from '../../model/book.model'; import {AdditionalFileUploaderComponent} from '../additional-file-uploader/additional-file-uploader.component'; import {BookFileAttacherComponent} from '../book-file-attacher/book-file-attacher.component'; import {AddPhysicalBookDialogComponent} from '../add-physical-book-dialog/add-physical-book-dialog.component'; +import {DuplicateMergerComponent} from '../duplicate-merger/duplicate-merger.component'; @Injectable({providedIn: 'root'}) export class BookDialogHelperService { @@ -165,6 +166,16 @@ export class BookDialogHelperService { }); } + openDuplicateMergerDialog(libraryId: number): DynamicDialogRef | null { + return this.openDialog(DuplicateMergerComponent, { + showHeader: false, + styleClass: `${DialogSize.XL} ${DialogStyle.MINIMAL}`, + data: { + libraryId: libraryId, + }, + }); + } + openAddPhysicalBookDialog(libraryId?: number): DynamicDialogRef | null { return this.openDialog(AddPhysicalBookDialogComponent, { showHeader: false, diff --git a/booklore-ui/src/app/features/book/components/duplicate-merger/duplicate-merger.component.html b/booklore-ui/src/app/features/book/components/duplicate-merger/duplicate-merger.component.html new file mode 100644 index 000000000..4cfde0149 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/duplicate-merger/duplicate-merger.component.html @@ -0,0 +1,215 @@ + +
+
+
+ +
+
+

{{ t('title') }}

+

{{ t('description') }}

+
+ + +
+ +
+ +
+ + +
+ + +
+ + + @if (showAdvanced) { +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ } +
+ + +
+
+ + +
+
+
+ + + +
+ @if (activeGroups.length > 0) { + + + } +
+
+ + + @if (isMerging) { + + } + + + @if (hasScanned && activeGroups.length > 0) { +
+ + {{ t('helpText') }} +
+ } + + +
+ @if (isScanning) { +
+ +

{{ t('scanning') }}

+
+ } @else if (!hasScanned) { +
+ +

{{ t('scanPrompt') }}

+
+ } @else if (activeGroups.length === 0 && groups.length === 0) { +
+ +

{{ t('noDuplicates') }}

+
+ } @else if (activeGroups.length === 0 && groups.length > 0) { +
+ +

{{ t('allMerged') }}

+
+ } @else { +
+ @for (group of pagedGroups; track group.suggestedTargetBookId) { +
+
+ {{ t('groupLabel', { index: pageFirst + $index + 1 }) }} + +
+ + + + +
+
+
+ @for (book of group.books; track book.id) { +
+ +
+
{{ book.metadata?.title || ('book.fileAttacher.unknownTitle' | transloco) }}
+ @if (book.metadata?.authors?.length) { +
{{ book.metadata?.authors?.join(', ') }}
+ } +
+ @for (format of getBookFormats(book); track format) { + {{ format }} + } + @if (getFileCount(book) > 1) { + {{ t('fileCount', { count: getFileCount(book) }) }} + } +
+
+
+ + + @if (book.id === group.selectedTargetBookId) { + {{ t('target') }} + } +
+
+ } +
+
+ } +
+ + @if (activeGroups.length > pageSize) { + + + } + } +
+
+
+
diff --git a/booklore-ui/src/app/features/book/components/duplicate-merger/duplicate-merger.component.scss b/booklore-ui/src/app/features/book/components/duplicate-merger/duplicate-merger.component.scss new file mode 100644 index 000000000..900cbfcc3 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/duplicate-merger/duplicate-merger.component.scss @@ -0,0 +1,308 @@ +@use '../../../../shared/styles/panel-shared' as panel; + +.duplicate-merger-container { + display: flex; + flex-direction: column; + height: 100%; +} + +.panel-header { + @include panel.panel-header; + flex-shrink: 0; +} + +.dialog-content { + flex: 1; + overflow-y: auto; + min-height: 0; + padding: 1.5rem; + background: var(--card-background); + border: 1px solid var(--border-color); + border-top: none; + border-radius: 0 0 10px 10px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08); + display: flex; + flex-direction: column; + gap: 1rem; +} + +.preset-section { + display: flex; + align-items: center; +} + +.advanced-section { + .advanced-toggle { + display: flex; + align-items: center; + gap: 0.5rem; + background: none; + border: none; + color: var(--p-text-muted-color); + font-size: 0.875rem; + font-weight: 500; + cursor: pointer; + padding: 0.25rem 0; + + &:hover { + color: var(--p-text-color); + } + + i { + font-size: 0.75rem; + } + } + + .signal-checkboxes { + display: flex; + flex-wrap: wrap; + gap: 0.75rem 1.5rem; + padding: 0.75rem 0 0 0; + } + + .signal-checkbox { + display: flex; + align-items: center; + gap: 0.5rem; + + label { + font-size: 0.875rem; + cursor: pointer; + user-select: none; + } + } +} + +.action-bar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + padding: 0.75rem 0; + border-top: 1px solid var(--border-color); + border-bottom: 1px solid var(--border-color); + + .action-bar-left { + display: flex; + align-items: center; + gap: 0.75rem; + } + + .action-bar-right { + display: flex; + align-items: center; + gap: 1rem; + } + + .delete-option { + display: flex; + align-items: center; + gap: 0.5rem; + + label { + font-size: 0.875rem; + cursor: pointer; + user-select: none; + white-space: nowrap; + } + } +} + +.results-area { + flex: 1; + min-height: 0; + overflow-y: auto; +} + +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 3rem 1rem; + color: var(--p-text-muted-color); + gap: 0.75rem; + + i { + font-size: 2.5rem; + } + + p { + margin: 0; + font-size: 0.9375rem; + } +} + +.groups-list { + display: flex; + flex-direction: column; + gap: 0.75rem; +} + +.duplicate-group { + border: 1px solid var(--border-color); + border-radius: 8px; + overflow: hidden; + + .group-header { + display: flex; + align-items: center; + gap: 0.75rem; + padding: 0.5rem 0.75rem; + border-bottom: 1px solid var(--border-color); + + .group-label { + font-weight: 600; + font-size: 0.8125rem; + color: var(--p-text-muted-color); + } + + .group-actions { + margin-left: auto; + display: flex; + gap: 0.5rem; + } + } + + .group-books { + display: flex; + flex-direction: column; + } +} + +.book-row { + display: flex; + align-items: center; + gap: 0.75rem; + padding: 0.625rem 0.75rem; + cursor: pointer; + transition: background-color 0.1s; + + &:not(:last-child) { + border-bottom: 1px solid var(--border-color); + } + + &:hover { + background: var(--p-content-hover-background); + } + + &.selected-target { + background: var(--p-highlight-background); + } + + .book-cover { + width: 36px; + height: 52px; + flex-shrink: 0; + border-radius: 3px; + object-fit: cover; + background: var(--p-surface-200); + } + + .book-info { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 0.0625rem; + + .book-title { + font-weight: 600; + font-size: 0.875rem; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .book-authors { + font-size: 0.8125rem; + color: var(--p-text-muted-color); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .book-formats { + display: flex; + flex-wrap: wrap; + gap: 0.25rem; + margin-top: 0.125rem; + + .format-badge { + display: inline-block; + font-size: 0.625rem; + font-weight: 700; + padding: 0.0625rem 0.3125rem; + border-radius: 3px; + background: var(--p-primary-100); + color: var(--p-primary-700); + text-transform: uppercase; + letter-spacing: 0.02em; + } + + .file-count { + font-size: 0.75rem; + color: var(--p-text-muted-color); + } + } + } + + .book-select { + display: flex; + align-items: center; + gap: 0.375rem; + flex-shrink: 0; + + .target-label { + font-size: 0.6875rem; + color: var(--p-primary-color); + text-transform: uppercase; + font-weight: 700; + letter-spacing: 0.03em; + } + } +} + +.help-text { + display: flex; + align-items: flex-start; + gap: 0.5rem; + padding: 0.625rem 0.75rem; + font-size: 0.8125rem; + color: var(--p-text-muted-color); + background: var(--p-content-hover-background); + border-radius: 6px; + line-height: 1.4; + + i { + flex-shrink: 0; + margin-top: 0.125rem; + font-size: 0.875rem; + } +} + +:host-context(.p-dark) { + .book-row .book-cover { + background: var(--p-surface-700); + } + + .book-row .book-formats .format-badge { + background: rgba(var(--p-primary-500-rgb, 99, 102, 241), 0.15); + color: var(--p-primary-400); + } +} + +@media (max-width: 640px) { + .action-bar { + flex-direction: column; + align-items: stretch; + + .action-bar-right { + flex-wrap: wrap; + } + } + + .duplicate-group .group-header { + flex-wrap: wrap; + } +} diff --git a/booklore-ui/src/app/features/book/components/duplicate-merger/duplicate-merger.component.ts b/booklore-ui/src/app/features/book/components/duplicate-merger/duplicate-merger.component.ts new file mode 100644 index 000000000..1bd60e1c8 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/duplicate-merger/duplicate-merger.component.ts @@ -0,0 +1,312 @@ +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {FormsModule} from '@angular/forms'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {Button} from 'primeng/button'; +import {Checkbox} from 'primeng/checkbox'; +import {RadioButton} from 'primeng/radiobutton'; +import {SelectButton} from 'primeng/selectbutton'; +import {ProgressBar} from 'primeng/progressbar'; +import {Tag} from 'primeng/tag'; +import {Paginator} from 'primeng/paginator'; +import {Subject, takeUntil} from 'rxjs'; +import {BookFileService} from '../../service/book-file.service'; +import {Book, DuplicateDetectionRequest, DuplicateGroup} from '../../model/book.model'; +import {MessageService} from 'primeng/api'; +import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco'; +import {UrlHelperService} from '../../../../shared/service/url-helper.service'; + +type PresetMode = 'strict' | 'balanced' | 'aggressive' | 'custom'; + +interface DisplayGroup extends DuplicateGroup { + selectedTargetBookId: number; + dismissed: boolean; +} + +@Component({ + selector: 'app-duplicate-merger', + standalone: true, + imports: [ + FormsModule, + Button, + Checkbox, + RadioButton, + SelectButton, + ProgressBar, + Tag, + Paginator, + TranslocoDirective, + TranslocoPipe, + ], + templateUrl: './duplicate-merger.component.html', + styleUrls: ['./duplicate-merger.component.scss'] +}) +export class DuplicateMergerComponent implements OnInit, OnDestroy { + libraryId!: number; + presetMode: PresetMode = 'balanced'; + showAdvanced = false; + + matchByIsbn = true; + matchByExternalId = true; + matchByTitleAuthor = true; + matchByDirectory = false; + matchByFilename = false; + + isScanning = false; + isMerging = false; + hasScanned = false; + deleteSourceBooks = true; + mergeProgress = 0; + mergeTotal = 0; + + groups: DisplayGroup[] = []; + presetOptions: { label: string; value: PresetMode }[] = []; + + pageFirst = 0; + pageSize = 20; + + private destroy$ = new Subject(); + private readonly bookFileService = inject(BookFileService); + private readonly messageService = inject(MessageService); + private readonly dialogRef = inject(DynamicDialogRef); + private readonly config = inject(DynamicDialogConfig); + private readonly t = inject(TranslocoService); + readonly urlHelper = inject(UrlHelperService); + + ngOnInit(): void { + this.libraryId = this.config.data.libraryId; + this.presetOptions = [ + {label: this.t.translate('book.duplicateMerger.presetStrict'), value: 'strict'}, + {label: this.t.translate('book.duplicateMerger.presetBalanced'), value: 'balanced'}, + {label: this.t.translate('book.duplicateMerger.presetAggressive'), value: 'aggressive'}, + {label: this.t.translate('book.duplicateMerger.presetCustom'), value: 'custom'}, + ]; + this.applyPreset('balanced'); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + onPresetChange(): void { + if (this.presetMode !== 'custom') { + this.applyPreset(this.presetMode); + } + } + + onSignalToggle(): void { + this.presetMode = 'custom'; + } + + applyPreset(mode: PresetMode): void { + switch (mode) { + case 'strict': + this.matchByIsbn = true; + this.matchByExternalId = true; + this.matchByTitleAuthor = false; + this.matchByDirectory = false; + this.matchByFilename = false; + break; + case 'balanced': + this.matchByIsbn = true; + this.matchByExternalId = true; + this.matchByTitleAuthor = true; + this.matchByDirectory = false; + this.matchByFilename = false; + break; + case 'aggressive': + this.matchByIsbn = true; + this.matchByExternalId = true; + this.matchByTitleAuthor = true; + this.matchByDirectory = true; + this.matchByFilename = true; + break; + } + } + + scan(): void { + this.isScanning = true; + this.hasScanned = false; + this.groups = []; + this.pageFirst = 0; + + const request: DuplicateDetectionRequest = { + libraryId: this.libraryId, + matchByIsbn: this.matchByIsbn, + matchByExternalId: this.matchByExternalId, + matchByTitleAuthor: this.matchByTitleAuthor, + matchByDirectory: this.matchByDirectory, + matchByFilename: this.matchByFilename, + }; + + this.bookFileService.findDuplicates(request).pipe( + takeUntil(this.destroy$) + ).subscribe({ + next: (groups) => { + this.groups = groups.map(g => ({ + ...g, + selectedTargetBookId: g.suggestedTargetBookId, + dismissed: false, + })); + this.isScanning = false; + this.hasScanned = true; + }, + error: (err) => { + this.isScanning = false; + this.hasScanned = true; + this.messageService.add({ + severity: 'error', + summary: this.t.translate('book.duplicateMerger.toast.scanFailedSummary'), + detail: err?.error?.message || this.t.translate('book.duplicateMerger.toast.scanFailedDetail'), + }); + } + }); + } + + get activeGroups(): DisplayGroup[] { + return this.groups.filter(g => !g.dismissed); + } + + get pagedGroups(): DisplayGroup[] { + return this.activeGroups.slice(this.pageFirst, this.pageFirst + this.pageSize); + } + + get canScan(): boolean { + return !this.isScanning && !this.isMerging && + (this.matchByIsbn || this.matchByExternalId || this.matchByTitleAuthor || + this.matchByDirectory || this.matchByFilename); + } + + onPageChange(event: any): void { + this.pageFirst = event.first; + this.pageSize = event.rows; + } + + getBookFormats(book: Book): string[] { + const formats: string[] = []; + if (book.primaryFile?.bookType) { + formats.push(book.primaryFile.bookType); + } + if (book.alternativeFormats) { + for (const alt of book.alternativeFormats) { + if (alt.bookType) { + formats.push(alt.bookType); + } + } + } + return formats; + } + + getFileCount(book: Book): number { + let count = book.primaryFile ? 1 : 0; + count += book.alternativeFormats?.length ?? 0; + return count; + } + + getMatchReasonLabel(reason: string): string { + return this.t.translate(`book.duplicateMerger.reason.${reason}`); + } + + getMatchReasonSeverity(reason: string): "success" | "info" | "warn" | "danger" | "secondary" | "contrast" { + switch (reason) { + case 'ISBN': + case 'EXTERNAL_ID': + return 'success'; + case 'TITLE_AUTHOR': + return 'info'; + case 'DIRECTORY': + return 'warn'; + case 'FILENAME': + return 'secondary'; + default: + return 'info'; + } + } + + dismissGroup(group: DisplayGroup): void { + group.dismissed = true; + if (this.pagedGroups.length === 0 && this.pageFirst > 0) { + this.pageFirst = Math.max(0, this.pageFirst - this.pageSize); + } + } + + async mergeGroup(group: DisplayGroup): Promise { + const targetId = group.selectedTargetBookId; + const sourceIds = group.books + .filter(b => b.id !== targetId) + .map(b => b.id); + + if (sourceIds.length === 0) return; + + group.dismissed = true; + try { + await this.bookFileService.attachBookFiles(targetId, sourceIds, this.deleteSourceBooks) + .pipe(takeUntil(this.destroy$)) + .toPromise(); + } catch { + group.dismissed = false; + this.messageService.add({ + severity: 'error', + summary: this.t.translate('book.duplicateMerger.toast.mergeFailedSummary'), + detail: this.t.translate('book.duplicateMerger.toast.mergeFailedDetail'), + }); + } + } + + async mergeAll(): Promise { + const toMerge = this.activeGroups; + if (toMerge.length === 0) return; + + this.isMerging = true; + this.mergeTotal = toMerge.length; + this.mergeProgress = 0; + + let successCount = 0; + let failCount = 0; + + for (const group of toMerge) { + const targetId = group.selectedTargetBookId; + const sourceIds = group.books + .filter(b => b.id !== targetId) + .map(b => b.id); + + if (sourceIds.length === 0) { + group.dismissed = true; + this.mergeProgress++; + continue; + } + + try { + await this.bookFileService.attachBookFiles(targetId, sourceIds, this.deleteSourceBooks) + .pipe(takeUntil(this.destroy$)) + .toPromise(); + group.dismissed = true; + successCount++; + } catch { + failCount++; + } + this.mergeProgress++; + } + + this.isMerging = false; + + if (successCount > 0) { + this.messageService.add({ + severity: 'success', + summary: this.t.translate('book.duplicateMerger.toast.mergeSuccessSummary'), + detail: this.t.translate('book.duplicateMerger.toast.mergeSuccessDetail', {count: successCount}), + }); + } + if (failCount > 0) { + this.messageService.add({ + severity: 'error', + summary: this.t.translate('book.duplicateMerger.toast.mergeFailedSummary'), + detail: this.t.translate('book.duplicateMerger.toast.mergePartialDetail', {success: successCount, failed: failCount}), + }); + } + } + + closeDialog(): void { + this.dialogRef.close(); + } +} diff --git a/booklore-ui/src/app/features/book/model/book.model.ts b/booklore-ui/src/app/features/book/model/book.model.ts index c762e86b6..766f2516a 100644 --- a/booklore-ui/src/app/features/book/model/book.model.ts +++ b/booklore-ui/src/app/features/book/model/book.model.ts @@ -381,13 +381,6 @@ export interface BookDeletionResponse { failedFileDeletions: number[]; } -export interface BookSyncResponse { - books: Book[]; - deletedIds: number[]; - syncTimestamp: string; - totalBookCount: number; -} - export enum ReadStatus { UNREAD = 'UNREAD', READING = 'READING', @@ -424,3 +417,18 @@ export interface PersonalRatingUpdateResponse { bookId: number; personalRating?: number; } + +export interface DuplicateDetectionRequest { + libraryId: number; + matchByIsbn: boolean; + matchByExternalId: boolean; + matchByTitleAuthor: boolean; + matchByDirectory: boolean; + matchByFilename: boolean; +} + +export interface DuplicateGroup { + suggestedTargetBookId: number; + matchReason: string; + books: Book[]; +} diff --git a/booklore-ui/src/app/features/book/service/book-cache.service.ts b/booklore-ui/src/app/features/book/service/book-cache.service.ts deleted file mode 100644 index 4be97d982..000000000 --- a/booklore-ui/src/app/features/book/service/book-cache.service.ts +++ /dev/null @@ -1,76 +0,0 @@ -import {Injectable} from '@angular/core'; -import {openDB, IDBPDatabase} from 'idb'; -import {Book} from '../model/book.model'; - -const DB_NAME = 'booklore-books'; -const DB_VERSION = 1; -const BOOKS_STORE = 'books'; -const META_STORE = 'meta'; - -@Injectable({ - providedIn: 'root', -}) -export class BookCacheService { - - private dbPromise: Promise = openDB(DB_NAME, DB_VERSION, { - upgrade(db) { - if (!db.objectStoreNames.contains(BOOKS_STORE)) { - db.createObjectStore(BOOKS_STORE, {keyPath: 'id'}); - } - if (!db.objectStoreNames.contains(META_STORE)) { - db.createObjectStore(META_STORE); - } - }, - }); - - async getAll(): Promise { - const db = await this.dbPromise; - return db.getAll(BOOKS_STORE); - } - - async putAll(books: Book[]): Promise { - const db = await this.dbPromise; - const tx = db.transaction(BOOKS_STORE, 'readwrite'); - for (const book of books) { - tx.store.put(book); - } - await tx.done; - } - - async put(book: Book): Promise { - const db = await this.dbPromise; - await db.put(BOOKS_STORE, book); - } - - async delete(id: number): Promise { - const db = await this.dbPromise; - await db.delete(BOOKS_STORE, id); - } - - async deleteMany(ids: number[]): Promise { - const db = await this.dbPromise; - const tx = db.transaction(BOOKS_STORE, 'readwrite'); - for (const id of ids) { - tx.store.delete(id); - } - await tx.done; - } - - async getSyncTimestamp(): Promise { - const db = await this.dbPromise; - return (await db.get(META_STORE, 'syncTimestamp')) ?? null; - } - - async setSyncTimestamp(ts: string): Promise { - const db = await this.dbPromise; - await db.put(META_STORE, ts, 'syncTimestamp'); - } - - async clear(): Promise { - const db = await this.dbPromise; - const tx = db.transaction([BOOKS_STORE, META_STORE], 'readwrite'); - tx.objectStore(BOOKS_STORE).clear(); - tx.objectStore(META_STORE).clear(); - await tx.done; - } -} diff --git a/booklore-ui/src/app/features/book/service/book-file.service.ts b/booklore-ui/src/app/features/book/service/book-file.service.ts index 66c98dd1d..6284d1ca7 100644 --- a/booklore-ui/src/app/features/book/service/book-file.service.ts +++ b/booklore-ui/src/app/features/book/service/book-file.service.ts @@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core'; import {Observable, throwError} from 'rxjs'; import {HttpClient} from '@angular/common/http'; import {catchError, tap} from 'rxjs/operators'; -import {AdditionalFile, AdditionalFileType, Book} from '../model/book.model'; +import {AdditionalFile, AdditionalFileType, Book, DuplicateDetectionRequest, DuplicateGroup} from '../model/book.model'; import {API_CONFIG} from '../../../core/config/api-config'; import {MessageService} from 'primeng/api'; import {FileDownloadService} from '../../../shared/service/file-download.service'; @@ -208,6 +208,10 @@ export class BookFileService { this.fileDownloadService.downloadFile(downloadUrl, additionalFile?.fileName ?? 'file'); } + findDuplicates(request: DuplicateDetectionRequest): Observable { + return this.http.post(`${this.url}/duplicates`, request); + } + attachBookFiles(targetBookId: number, sourceBookIds: number[], deleteSourceBooks: boolean): Observable { return this.http.post(`${this.url}/${targetBookId}/attach-file`, { sourceBookIds, diff --git a/booklore-ui/src/app/features/book/service/book-socket.service.ts b/booklore-ui/src/app/features/book/service/book-socket.service.ts index 9890ce651..eb1deca33 100644 --- a/booklore-ui/src/app/features/book/service/book-socket.service.ts +++ b/booklore-ui/src/app/features/book/service/book-socket.service.ts @@ -1,6 +1,5 @@ import {inject, Injectable} from '@angular/core'; import {BookStateService} from './book-state.service'; -import {BookCacheService} from './book-cache.service'; import {Book, BookMetadata} from '../model/book.model'; @Injectable({ @@ -8,7 +7,6 @@ import {Book, BookMetadata} from '../model/book.model'; }) export class BookSocketService { private bookStateService = inject(BookStateService); - private bookCacheService = inject(BookCacheService); handleNewlyCreatedBook(book: Book): void { const currentState = this.bookStateService.getCurrentBookState(); @@ -20,14 +18,12 @@ export class BookSocketService { updatedBooks.push(book); } this.bookStateService.updateBookState({...currentState, books: updatedBooks}); - this.bookCacheService.put(book); } handleRemovedBookIds(removedBookIds: number[]): void { const currentState = this.bookStateService.getCurrentBookState(); const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.includes(book.id)); this.bookStateService.updateBookState({...currentState, books: filteredBooks}); - this.bookCacheService.deleteMany(removedBookIds); } handleBookUpdate(updatedBook: Book): void { @@ -36,7 +32,6 @@ export class BookSocketService { book.id === updatedBook.id ? updatedBook : book ); this.bookStateService.updateBookState({...currentState, books: updatedBooks}); - this.bookCacheService.put(updatedBook); } handleMultipleBookUpdates(updatedBooks: Book[]): void { @@ -50,7 +45,6 @@ export class BookSocketService { ); this.bookStateService.updateBookState({...currentState, books: mergedBooks}); - this.bookCacheService.putAll(updatedBooks); } handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata): void { @@ -59,30 +53,18 @@ export class BookSocketService { return book.id === bookId ? {...book, metadata: updatedMetadata} : book; }); this.bookStateService.updateBookState({...currentState, books: updatedBooks}); - - // Mirror metadata update to cache - const updatedBook = updatedBooks.find(b => b.id === bookId); - if (updatedBook) { - this.bookCacheService.put(updatedBook); - } } handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void { if (!patches || patches.length === 0) return; const currentState = this.bookStateService.getCurrentBookState(); const books = currentState.books || []; - const patchedBooks: Book[] = []; patches.forEach(p => { const index = books.findIndex(b => b.id === p.id); if (index !== -1 && books[index].metadata) { books[index].metadata.coverUpdatedOn = p.coverUpdatedOn; - patchedBooks.push(books[index]); } }); this.bookStateService.updateBookState({...currentState, books}); - if (patchedBooks.length > 0) { - this.bookCacheService.putAll(patchedBooks); - } } } - diff --git a/booklore-ui/src/app/features/book/service/book.service.ts b/booklore-ui/src/app/features/book/service/book.service.ts index a47463996..04d4717b9 100644 --- a/booklore-ui/src/app/features/book/service/book.service.ts +++ b/booklore-ui/src/app/features/book/service/book.service.ts @@ -1,8 +1,8 @@ import {inject, Injectable} from '@angular/core'; -import {first, from, Observable, of, throwError} from 'rxjs'; +import {first, Observable, of, throwError} from 'rxjs'; import {HttpClient, HttpParams} from '@angular/common/http'; -import {catchError, distinctUntilChanged, filter, finalize, map, shareReplay, switchMap, tap} from 'rxjs/operators'; -import {Book, BookDeletionResponse, BookRecommendation, BookSetting, BookStatusUpdateResponse, BookSyncResponse, BookType, CreatePhysicalBookRequest, PersonalRatingUpdateResponse, ReadStatus} from '../model/book.model'; +import {catchError, distinctUntilChanged, filter, finalize, map, shareReplay, tap} from 'rxjs/operators'; +import {Book, BookDeletionResponse, BookRecommendation, BookSetting, BookStatusUpdateResponse, BookType, CreatePhysicalBookRequest, PersonalRatingUpdateResponse, ReadStatus} from '../model/book.model'; import {BookState} from '../model/state/book-state.model'; import {API_CONFIG} from '../../../core/config/api-config'; import {MessageService} from 'primeng/api'; @@ -12,7 +12,6 @@ import {Router} from '@angular/router'; import {BookStateService} from './book-state.service'; import {BookSocketService} from './book-socket.service'; import {BookPatchService} from './book-patch.service'; -import {BookCacheService} from './book-cache.service'; import {TranslocoService} from '@jsverse/transloco'; @Injectable({ @@ -29,7 +28,6 @@ export class BookService { private bookStateService = inject(BookStateService); private bookSocketService = inject(BookSocketService); private bookPatchService = inject(BookPatchService); - private bookCacheService = inject(BookCacheService); private readonly t = inject(TranslocoService); private loading$: Observable | null = null; @@ -41,7 +39,6 @@ export class BookService { if (token === null) { this.bookStateService.resetBookState(); this.loading$ = null; - this.bookCacheService.clear(); } else { const current = this.bookStateService.getCurrentBookState(); if (current.loaded && !current.books) { @@ -61,7 +58,7 @@ export class BookService { bookState$ = this.bookStateService.bookState$.pipe( tap(state => { if (!state.loaded && !state.error && !this.loading$) { - this.loading$ = this.fetchBooksWithCache().pipe( + this.loading$ = this.fetchBooks().pipe( shareReplay(1), finalize(() => (this.loading$ = null)) ); @@ -74,52 +71,14 @@ export class BookService { return this.bookStateService.getCurrentBookState(); } - private fetchBooksWithCache(): Observable { - return from(this.bookCacheService.getAll()).pipe( - switchMap(cachedBooks => from(this.bookCacheService.getSyncTimestamp()).pipe( - map(syncTs => ({cachedBooks, syncTs})) - )), - switchMap(({cachedBooks, syncTs}) => { - if (cachedBooks.length > 0 && syncTs) { - this.bookStateService.updateBookState({ - books: cachedBooks, - loaded: true, - error: null, - }); - - this.deltaSync(syncTs); - return of(cachedBooks); - } - return this.fetchBooksFullAndCache(); - }), - catchError(error => { - return this.fetchBooksFullAndCache().pipe( - catchError(fetchError => { - const curr = this.bookStateService.getCurrentBookState(); - this.bookStateService.updateBookState({ - books: curr.books, - loaded: true, - error: fetchError.message, - }); - throw fetchError; - }) - ); - }) - ); - } - - private fetchBooksFullAndCache(): Observable { - return this.http.get(this.url, {observe: 'response'}).pipe( - map(response => { - const bookList = response.body || []; + private fetchBooks(): Observable { + return this.http.get(this.url).pipe( + map(bookList => { this.bookStateService.updateBookState({ books: bookList, loaded: true, error: null, }); - const serverDate = response.headers.get('Date'); - const syncTs = serverDate ? new Date(serverDate).toISOString() : new Date().toISOString(); - this.writeBooksToCache(bookList, syncTs); return bookList; }), catchError(error => { @@ -134,72 +93,14 @@ export class BookService { ); } - private deltaSync(syncTs: string): void { - const params = new HttpParams().set('since', syncTs); - this.http.get(`${this.url}/delta`, {params}).pipe( - tap(delta => { - const currentState = this.bookStateService.getCurrentBookState(); - let books = [...(currentState.books || [])]; - - if (delta.deletedIds?.length) { - const deletedSet = new Set(delta.deletedIds); - books = books.filter(b => !deletedSet.has(b.id)); - this.bookCacheService.deleteMany(delta.deletedIds); - } - - if (delta.books?.length) { - const updatedMap = new Map(delta.books.map(b => [b.id, b])); - books = books.map(b => updatedMap.get(b.id) ?? b); - const existingIds = new Set(books.map(b => b.id)); - for (const book of delta.books) { - if (!existingIds.has(book.id)) { - books.push(book); - } - } - this.bookCacheService.putAll(delta.books); - } - - if (delta.totalBookCount !== books.length) { - this.refreshBooks(); - return; - } - - this.bookStateService.updateBookState({ - books, - loaded: true, - error: null, - }); - - if (delta.syncTimestamp) { - this.bookCacheService.setSyncTimestamp(delta.syncTimestamp); - } - }), - catchError(() => { - this.refreshBooks(); - return of(null); - }) - ).subscribe(); - } - - private writeBooksToCache(books: Book[], syncTimestamp: string): void { - this.bookCacheService.clear().then(() => { - this.bookCacheService.putAll(books); - this.bookCacheService.setSyncTimestamp(syncTimestamp); - }); - } - refreshBooks(): void { - this.http.get(this.url, {observe: 'response'}).pipe( - tap(response => { - const bookList = response.body || []; + this.http.get(this.url).pipe( + tap(bookList => { this.bookStateService.updateBookState({ books: bookList, loaded: true, error: null, }); - const serverDate = response.headers.get('Date'); - const syncTs = serverDate ? new Date(serverDate).toISOString() : new Date().toISOString(); - this.writeBooksToCache(bookList, syncTs); }), catchError(error => { this.bookStateService.updateBookState({ diff --git a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts index c6f0fc9d3..a737a310d 100644 --- a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts +++ b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts @@ -111,6 +111,13 @@ export class LibraryShelfMenuService { }).subscribe(); } }, + { + label: this.t.translate('book.shelfMenuService.library.findDuplicates'), + icon: 'pi pi-copy', + command: () => { + this.bookDialogHelperService.openDuplicateMergerDialog(entity?.id as number); + } + }, { separator: true }, diff --git a/booklore-ui/src/app/features/book/service/library.service.ts b/booklore-ui/src/app/features/book/service/library.service.ts index b842dbc8c..9e045a844 100644 --- a/booklore-ui/src/app/features/book/service/library.service.ts +++ b/booklore-ui/src/app/features/book/service/library.service.ts @@ -100,6 +100,7 @@ export class LibraryService { const curr = this.libraryStateSubject.value; const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated]; this.libraryStateSubject.next({...curr, libraries: list}); + this.bookService.refreshBooks(); return updated; }) ); diff --git a/booklore-ui/src/app/features/library-creator/library-creator.component.ts b/booklore-ui/src/app/features/library-creator/library-creator.component.ts index f33e76b9b..59931c167 100644 --- a/booklore-ui/src/app/features/library-creator/library-creator.component.ts +++ b/booklore-ui/src/app/features/library-creator/library-creator.component.ts @@ -241,7 +241,9 @@ export class LibraryCreatorComponent implements OnInit { }; if (this.mode === 'edit') { - this.libraryService.updateLibrary(library, this.library?.id).subscribe({ + this.libraryService.updateLibrary(library, this.library?.id).pipe( + switchMap(() => this.libraryService.refreshLibrary(this.library!.id!)) + ).subscribe({ next: () => { this.messageService.add({severity: 'success', summary: this.t.translate('libraryCreator.creator.toast.updatedSummary'), detail: this.t.translate('libraryCreator.creator.toast.updatedDetail')}); this.dynamicDialogRef.close(); diff --git a/booklore-ui/src/i18n/en/book.json b/booklore-ui/src/i18n/en/book.json index 7c6babb4e..f23624dc4 100644 --- a/booklore-ui/src/i18n/en/book.json +++ b/booklore-ui/src/i18n/en/book.json @@ -262,6 +262,7 @@ "rescanLibrary": "Re-scan Library", "customFetchMetadata": "Custom Fetch Metadata", "autoFetchMetadata": "Auto Fetch Metadata", + "findDuplicates": "Find Duplicates", "deleteLibrary": "Delete Library" }, "shelf": { @@ -771,5 +772,48 @@ "deselectAll": "Deselect all books", "deleteSelected": "Delete selected books" } + }, + "duplicateMerger": { + "title": "Find Duplicates", + "description": "Detect and merge duplicate books in this library", + "presetStrict": "Strict", + "presetBalanced": "Balanced", + "presetAggressive": "Aggressive", + "presetCustom": "Custom", + "advanced": "Advanced", + "signalIsbn": "ISBN", + "signalExternalId": "External ID", + "signalTitleAuthor": "Title + Author", + "signalDirectory": "Same Directory", + "signalFilename": "Filename", + "scan": "Scan", + "scanning": "Scanning for duplicates...", + "scanPrompt": "Select a detection mode and click Scan to find duplicates.", + "noDuplicates": "No duplicates found.", + "allMerged": "All duplicate groups have been processed.", + "deleteSource": "Delete source books", + "mergeAll": "Merge All ({{ count }})", + "merge": "Merge", + "dismiss": "Dismiss", + "target": "Target", + "helpText": "Each group contains books that appear to be duplicates. Select the target book (the one to keep), then click Merge. The other books' files will be attached to the target as alternative formats.", + "groupLabel": "Group {{ index }}", + "fileCount": "{{ count }} files", + "reason": { + "ISBN": "ISBN Match", + "EXTERNAL_ID": "External ID Match", + "TITLE_AUTHOR": "Title + Author", + "DIRECTORY": "Same Directory", + "FILENAME": "Filename Match" + }, + "toast": { + "scanFailedSummary": "Scan Failed", + "scanFailedDetail": "Could not scan for duplicates.", + "mergeSuccessSummary": "Merge Complete", + "mergeSuccessDetail": "Successfully merged {{ count }} group(s).", + "mergeFailedSummary": "Merge Failed", + "mergeFailedDetail": "Could not merge this group.", + "mergePartialDetail": "{{ success }} merged, {{ failed }} failed." + } } } diff --git a/booklore-ui/src/i18n/es/book.json b/booklore-ui/src/i18n/es/book.json index 67b83f02c..0c732c4fc 100644 --- a/booklore-ui/src/i18n/es/book.json +++ b/booklore-ui/src/i18n/es/book.json @@ -262,6 +262,7 @@ "rescanLibrary": "Re-escanear biblioteca", "customFetchMetadata": "Obtención personalizada de metadatos", "autoFetchMetadata": "Obtener metadatos automáticamente", + "findDuplicates": "Buscar duplicados", "deleteLibrary": "Eliminar biblioteca" }, "shelf": { @@ -771,5 +772,48 @@ "deselectAll": "Deseleccionar todos los libros", "deleteSelected": "Eliminar libros seleccionados" } + }, + "duplicateMerger": { + "title": "Buscar duplicados", + "description": "Detectar y fusionar libros duplicados en esta biblioteca", + "presetStrict": "Estricto", + "presetBalanced": "Equilibrado", + "presetAggressive": "Agresivo", + "presetCustom": "Personalizado", + "advanced": "Avanzado", + "signalIsbn": "ISBN", + "signalExternalId": "ID externo", + "signalTitleAuthor": "Título + Autor", + "signalDirectory": "Mismo directorio", + "signalFilename": "Nombre de archivo", + "scan": "Escanear", + "scanning": "Buscando duplicados...", + "scanPrompt": "Seleccione un modo de detección y haga clic en Escanear para buscar duplicados.", + "noDuplicates": "No se encontraron duplicados.", + "allMerged": "Todos los grupos duplicados han sido procesados.", + "deleteSource": "Eliminar libros de origen", + "mergeAll": "Fusionar todo ({{ count }})", + "merge": "Fusionar", + "dismiss": "Descartar", + "target": "Destino", + "helpText": "Cada grupo contiene libros que parecen ser duplicados. Seleccione el libro destino (el que se conserva) y haga clic en Fusionar. Los archivos de los otros libros se adjuntarán al destino como formatos alternativos.", + "groupLabel": "Grupo {{ index }}", + "fileCount": "{{ count }} archivos", + "reason": { + "ISBN": "Coincidencia ISBN", + "EXTERNAL_ID": "Coincidencia ID externo", + "TITLE_AUTHOR": "Título + Autor", + "DIRECTORY": "Mismo directorio", + "FILENAME": "Coincidencia de nombre" + }, + "toast": { + "scanFailedSummary": "Error de escaneo", + "scanFailedDetail": "No se pudieron buscar duplicados.", + "mergeSuccessSummary": "Fusión completada", + "mergeSuccessDetail": "Se fusionaron {{ count }} grupo(s) correctamente.", + "mergeFailedSummary": "Error de fusión", + "mergeFailedDetail": "No se pudo fusionar este grupo.", + "mergePartialDetail": "{{ success }} fusionados, {{ failed }} fallidos." + } } }