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:
ACX
2026-02-20 16:09:45 -07:00
committed by GitHub
co-authored by acx10
parent 9ace45a8ea
commit 2223b18d0f
33 changed files with 2491 additions and 509 deletions
@@ -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"),
@@ -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
@@ -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;
}
@@ -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);