Add duplicate book detection/merge and fix format-related data loss (#2820)
* Add duplicate book detection and merge feature * Remove delta sync, ETag, and IndexedDB caching --------- Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
@@ -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<List<Book>> 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<BookSyncResponse> 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<List<DuplicateGroup>> 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"),
|
||||
|
||||
+12
@@ -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
|
||||
) {}
|
||||
@@ -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<Book> books;
|
||||
private List<Long> deletedIds;
|
||||
private String syncTimestamp;
|
||||
private long totalBookCount;
|
||||
}
|
||||
@@ -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<Book> books
|
||||
) {}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -66,6 +66,17 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> 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<BookEntity> 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<BookEntity> findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
|
||||
@@ -118,29 +129,6 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, 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<Long> 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<Long> 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<Long> findBookIdsModifiedSinceByLibraryIds(@Param("since") Instant since, @Param("libraryIds") Set<Long> libraryIds);
|
||||
|
||||
@Query("SELECT b.id FROM BookEntity b WHERE b.deleted = true AND b.deletedAt > :since")
|
||||
List<Long> 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<Long> findDeletedBookIdsSinceByLibraryIds(@Param("since") Instant since, @Param("libraryIds") Set<Long> libraryIds);
|
||||
|
||||
@Query(value = """
|
||||
SELECT b.*
|
||||
FROM book b
|
||||
|
||||
@@ -21,14 +21,6 @@ public interface UserBookProgressRepository extends JpaRepository<UserBookProgre
|
||||
|
||||
List<UserBookProgressEntity> findByUserIdAndBookIdIn(Long userId, Set<Long> 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<Long> findBookIdsWithProgressChangedSince(@Param("userId") Long userId, @Param("since") Instant since);
|
||||
|
||||
@Query("""
|
||||
SELECT ubp FROM UserBookProgressEntity ubp
|
||||
WHERE ubp.user.id = :userId
|
||||
|
||||
+58
-74
@@ -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<BookFileEntity> 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<BookFileEntity> filesToMove = sourceBook.getBookFiles().stream()
|
||||
.filter(BookFileEntity::isBookFormat)
|
||||
.findFirst()
|
||||
.orElseThrow(); // Already validated above
|
||||
.toList();
|
||||
|
||||
Path sourceFilePath = fileToMove.getFullFilePath();
|
||||
Path sourceDirectory = sourceFilePath.getParent();
|
||||
Set<Path> 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)
|
||||
|
||||
@@ -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<Long> libraryIds = isAdmin ? null : getUserLibraryIds(user);
|
||||
|
||||
// Find book IDs modified since the given timestamp
|
||||
Set<Long> modifiedBookIds = isAdmin
|
||||
? bookRepository.findBookIdsModifiedSince(since)
|
||||
: bookRepository.findBookIdsModifiedSinceByLibraryIds(since, libraryIds);
|
||||
|
||||
// Find book IDs with progress changes
|
||||
Set<Long> progressChangedIds = userBookProgressRepository.findBookIdsWithProgressChangedSince(user.getId(), since);
|
||||
|
||||
// Combine all changed IDs
|
||||
Set<Long> allChangedIds = new HashSet<>(modifiedBookIds);
|
||||
allChangedIds.addAll(progressChangedIds);
|
||||
|
||||
// Find deleted book IDs
|
||||
List<Long> deletedIds = isAdmin
|
||||
? bookRepository.findDeletedBookIdsSince(since)
|
||||
: bookRepository.findDeletedBookIdsSinceByLibraryIds(since, libraryIds);
|
||||
|
||||
// Fetch and enrich changed books
|
||||
List<Book> changedBooks = List.of();
|
||||
if (!allChangedIds.isEmpty()) {
|
||||
List<BookEntity> 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<Book> enrichBookEntities(List<BookEntity> bookEntities, BookLoreUser user, boolean includeDescription) {
|
||||
// Map entities through the same DTO pipeline as full fetch (includes field stripping)
|
||||
List<Book> books = bookQueryService.mapEntitiesToDto(bookEntities, includeDescription, user.getId());
|
||||
|
||||
Set<Long> bookIds = books.stream().map(Book::getId).collect(Collectors.toSet());
|
||||
Map<Long, UserBookProgressEntity> progressMap =
|
||||
readingProgressService.fetchUserProgress(user.getId(), bookIds);
|
||||
Map<Long, UserBookFileProgressEntity> fileProgressMap =
|
||||
readingProgressService.fetchUserFileProgress(user.getId(), bookIds);
|
||||
|
||||
books.forEach(book -> {
|
||||
readingProgressService.enrichBookWithProgress(
|
||||
book,
|
||||
progressMap.get(book.getId()),
|
||||
fileProgressMap.get(book.getId())
|
||||
);
|
||||
Set<Shelf> 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<Long> getUserLibraryIds(BookLoreUser user) {
|
||||
return user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
|
||||
@@ -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<BookFileType> 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<DuplicateGroup> findDuplicates(DuplicateDetectionRequest request) {
|
||||
List<BookEntity> books = bookRepository.findAllForDuplicateDetection(request.libraryId());
|
||||
if (books.size() < 2) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<BookFileType> formatPriority = books.getFirst().getLibrary() != null
|
||||
? books.getFirst().getLibrary().getFormatPriority()
|
||||
: null;
|
||||
if (formatPriority == null || formatPriority.isEmpty()) {
|
||||
formatPriority = DEFAULT_FORMAT_PRIORITY;
|
||||
}
|
||||
|
||||
Set<Long> alreadyGrouped = new HashSet<>();
|
||||
List<DuplicateGroup> 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<DuplicateGroup> findByIsbn(List<BookEntity> books, Set<Long> alreadyGrouped, List<BookFileType> formatPriority) {
|
||||
Map<String, List<BookEntity>> 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<DuplicateGroup> findByExternalId(List<BookEntity> books, Set<Long> alreadyGrouped, List<BookFileType> formatPriority) {
|
||||
Map<Long, Long> parent = new HashMap<>();
|
||||
Map<Long, BookEntity> bookMap = new HashMap<>();
|
||||
|
||||
List<BookEntity> 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<String, Long> idToBook = new HashMap<>();
|
||||
for (BookEntity book : candidates) {
|
||||
BookMetadataEntity meta = book.getMetadata();
|
||||
List<String> 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<Long, List<BookEntity>> groups = new HashMap<>();
|
||||
for (BookEntity book : candidates) {
|
||||
Long root = find(parent, book.getId());
|
||||
groups.computeIfAbsent(root, k -> new ArrayList<>()).add(book);
|
||||
}
|
||||
|
||||
List<DuplicateGroup> result = new ArrayList<>();
|
||||
for (List<BookEntity> 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<String> extractExternalIds(BookMetadataEntity meta) {
|
||||
List<String> 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<String> list, String prefix, String value) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
list.add(prefix + value.trim());
|
||||
}
|
||||
}
|
||||
|
||||
private Long find(Map<Long, Long> 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<Long, Long> 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<DuplicateGroup> findByTitleAuthor(List<BookEntity> books, Set<Long> alreadyGrouped, List<BookFileType> formatPriority) {
|
||||
Map<String, List<BookEntity>> 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<DuplicateGroup> result = new ArrayList<>();
|
||||
for (List<BookEntity> group : titleGroups.values()) {
|
||||
if (group.size() < 2) continue;
|
||||
|
||||
List<BookEntity> withAuthors = group.stream()
|
||||
.filter(b -> b.getMetadata().getAuthors() != null && !b.getMetadata().getAuthors().isEmpty())
|
||||
.toList();
|
||||
|
||||
if (withAuthors.size() < 2) continue;
|
||||
|
||||
Map<Long, Set<String>> normalizedAuthors = new HashMap<>();
|
||||
for (BookEntity book : withAuthors) {
|
||||
Set<String> names = book.getMetadata().getAuthors().stream()
|
||||
.map(AuthorEntity::getName)
|
||||
.filter(Objects::nonNull)
|
||||
.map(BookUtils::normalizeForSearch)
|
||||
.collect(Collectors.toSet());
|
||||
normalizedAuthors.put(book.getId(), names);
|
||||
}
|
||||
|
||||
Map<Long, Long> 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<String> authorsI = normalizedAuthors.get(withAuthors.get(i).getId());
|
||||
Set<String> 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<Long, List<BookEntity>> subGroups = new HashMap<>();
|
||||
for (BookEntity book : withAuthors) {
|
||||
Long root = find(parent, book.getId());
|
||||
subGroups.computeIfAbsent(root, k -> new ArrayList<>()).add(book);
|
||||
}
|
||||
|
||||
for (List<BookEntity> 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<DuplicateGroup> findByDirectory(List<BookEntity> books, Set<Long> alreadyGrouped, List<BookFileType> formatPriority) {
|
||||
Map<String, List<BookEntity>> dirGroups = new HashMap<>();
|
||||
|
||||
for (BookEntity book : books) {
|
||||
if (alreadyGrouped.contains(book.getId())) continue;
|
||||
if (book.getLibraryPath() == null) continue;
|
||||
|
||||
List<BookFileEntity> 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<DuplicateGroup> findByFilename(List<BookEntity> books, Set<Long> alreadyGrouped, List<BookFileType> formatPriority) {
|
||||
Map<String, List<BookEntity>> nameGroups = new HashMap<>();
|
||||
|
||||
for (BookEntity book : books) {
|
||||
if (alreadyGrouped.contains(book.getId())) continue;
|
||||
|
||||
List<BookFileEntity> 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<DuplicateGroup> buildGroups(Map<String, List<BookEntity>> groupMap, String reason,
|
||||
Set<Long> alreadyGrouped, List<BookFileType> formatPriority) {
|
||||
List<DuplicateGroup> result = new ArrayList<>();
|
||||
for (List<BookEntity> 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<BookEntity> entities, String reason, List<BookFileType> 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<Book> books = entities.stream()
|
||||
.map(bookMapper::toBook)
|
||||
.toList();
|
||||
|
||||
return new DuplicateGroup(suggested.getId(), reason, books);
|
||||
}
|
||||
|
||||
private int formatPriorityScore(BookEntity book, List<BookFileType> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<BookFileType> allowedFormats = libraryEntity.getAllowedFormats();
|
||||
if (allowedFormats == null || allowedFormats.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Set<BookFileType> allowed = EnumSet.copyOf(allowedFormats);
|
||||
List<BookFileEntity> allBookFiles = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId());
|
||||
|
||||
List<BookFileEntity> disallowedFiles = allBookFiles.stream()
|
||||
.filter(BookFileEntity::isBook)
|
||||
.filter(bf -> !allowed.contains(bf.getBookType()))
|
||||
.toList();
|
||||
|
||||
if (disallowedFiles.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Set<Long> affectedBookIds = disallowedFiles.stream()
|
||||
.map(bf -> bf.getBook().getId())
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
Map<Long, Long> 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<Long> 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<LibraryFile> libraryFiles) {
|
||||
Set<String> existingFileNames = libraryFiles.stream()
|
||||
.map(LibraryFile::getFileName)
|
||||
|
||||
@@ -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<BookEntity> 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<BookEntity> 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<BookEntity> books) {
|
||||
String fileKey = BookFileGroupingUtils.extractGroupingKey(file.getFileName());
|
||||
|
||||
|
||||
@@ -32,15 +32,19 @@ public class LibraryFileHelper {
|
||||
|
||||
private static final int MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK = 2;
|
||||
|
||||
public List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity) throws IOException {
|
||||
public List<LibraryFile> getAllLibraryFiles(LibraryEntity libraryEntity) throws IOException {
|
||||
List<LibraryFile> allFiles = new ArrayList<>();
|
||||
for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
|
||||
allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity));
|
||||
}
|
||||
return filterByAllowedFormats(allFiles, libraryEntity.getAllowedFormats());
|
||||
return allFiles;
|
||||
}
|
||||
|
||||
private List<LibraryFile> filterByAllowedFormats(List<LibraryFile> files, List<BookFileType> allowedFormats) {
|
||||
public List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity) throws IOException {
|
||||
return filterByAllowedFormats(getAllLibraryFiles(libraryEntity), libraryEntity.getAllowedFormats());
|
||||
}
|
||||
|
||||
List<LibraryFile> filterByAllowedFormats(List<LibraryFile> files, List<BookFileType> allowedFormats) {
|
||||
if (allowedFormats == null || allowedFormats.isEmpty()) {
|
||||
return files;
|
||||
}
|
||||
|
||||
+10
-7
@@ -74,10 +74,12 @@ public class LibraryProcessingService {
|
||||
|
||||
validateLibraryPathsAccessible(libraryEntity);
|
||||
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity);
|
||||
List<LibraryFile> allLibraryFiles = libraryFileHelper.getAllLibraryFiles(libraryEntity);
|
||||
List<LibraryFile> 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<Long> additionalFileIds = detectDeletedAdditionalFiles(libraryFiles, libraryEntity);
|
||||
List<Long> additionalFileIds = detectDeletedAdditionalFiles(allLibraryFiles, libraryEntity);
|
||||
if (!additionalFileIds.isEmpty()) {
|
||||
log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName());
|
||||
bookDeletionService.deleteRemovedAdditionalFiles(additionalFileIds);
|
||||
}
|
||||
List<Long> bookIds = detectDeletedBookIds(libraryFiles, libraryEntity);
|
||||
List<Long> 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<LibraryFile> newFiles = detectNewBookPaths(libraryFiles, libraryEntity);
|
||||
List<LibraryFile> newFiles = detectNewBookPaths(filteredFiles, libraryEntity);
|
||||
|
||||
// Use BookGroupingService to determine what to attach vs create new
|
||||
BookGroupingService.GroupingResult groupingResult = bookGroupingService.groupForRescan(newFiles, libraryEntity);
|
||||
|
||||
+964
@@ -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<AuthorEntity> 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<DuplicateGroup> result = service.findDuplicates(allSignals());
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptyWhenNoBooksInLibrary() {
|
||||
when(bookRepository.findAllForDuplicateDetection(LIBRARY_ID)).thenReturn(List.of());
|
||||
|
||||
List<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<Long> isbnBookIds = new HashSet<>();
|
||||
isbnGroup.books().forEach(b -> isbnBookIds.add(b.getId()));
|
||||
assertThat(isbnBookIds).containsExactlyInAnyOrder(book1.getId(), book2.getId());
|
||||
|
||||
Set<Long> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> result = service.findDuplicates(onlyFilename());
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlesLargeGroupCorrectly() {
|
||||
List<BookEntity> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> 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<DuplicateGroup> result = service.findDuplicates(onlyIsbn());
|
||||
|
||||
assertThat(result).hasSize(1);
|
||||
Set<Long> bookIds = new HashSet<>();
|
||||
for (Book b : result.getFirst().books()) {
|
||||
bookIds.add(b.getId());
|
||||
}
|
||||
assertThat(bookIds).containsExactlyInAnyOrder(book1.getId(), book2.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -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()));
|
||||
|
||||
+9
-5
@@ -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()));
|
||||
|
||||
Reference in New Issue
Block a user