Allow duplicate files both within the same library and across different libraries (#1632)
This commit is contained in:
@@ -1,15 +0,0 @@
|
||||
package com.adityachandel.booklore.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
@Builder
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class DuplicateFileInfo {
|
||||
private final Long bookId;
|
||||
private final String fileName;
|
||||
private final String fullPath;
|
||||
private final String hash;
|
||||
}
|
||||
@@ -14,6 +14,4 @@ import lombok.ToString;
|
||||
public class FileProcessResult {
|
||||
private final Book book;
|
||||
private final FileProcessStatus status;
|
||||
@Builder.Default
|
||||
private final DuplicateFileInfo duplicate = null;
|
||||
}
|
||||
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Setter
|
||||
@Getter
|
||||
@Builder
|
||||
public class DuplicateFileNotification {
|
||||
private long libraryId;
|
||||
private String libraryName;
|
||||
private long fileId;
|
||||
private String fileName;
|
||||
private String fullPath;
|
||||
private String hash;
|
||||
private Instant timestamp;
|
||||
}
|
||||
-1
@@ -2,6 +2,5 @@ package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum FileProcessStatus {
|
||||
NEW,
|
||||
DUPLICATE,
|
||||
UPDATED
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ public enum Topic {
|
||||
BOOK_METADATA_BATCH_UPDATE("/queue/book-metadata-batch-update"),
|
||||
BOOK_METADATA_BATCH_PROGRESS("/queue/book-metadata-batch-progress"),
|
||||
BOOKDROP_FILE("/queue/bookdrop-file"),
|
||||
DUPLICATE_FILE("/queue/duplicate-file"),
|
||||
LOG("/queue/log"),
|
||||
TASK_PROGRESS("/queue/task-progress");
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.*;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.security.core.parameters.P;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.Instant;
|
||||
@@ -24,8 +23,6 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
|
||||
Optional<BookEntity> findByCurrentHash(String currentHash);
|
||||
|
||||
Optional<BookEntity> findByCurrentHashAndDeletedTrue(String currentHash);
|
||||
|
||||
@Query("SELECT b.id FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
Set<Long> findBookIdsByLibraryId(@Param("libraryId") long libraryId);
|
||||
|
||||
@@ -43,10 +40,6 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> findAllWithMetadata();
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
|
||||
@Query(value = "SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
||||
Page<BookEntity> findAllWithMetadata(Pageable pageable);
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> bookIds);
|
||||
|
||||
+2
-95
@@ -1,7 +1,6 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.DuplicateFileInfo;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
@@ -13,15 +12,11 @@ import com.adityachandel.booklore.service.book.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.file.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
@Slf4j
|
||||
public abstract class AbstractFileProcessor implements BookFileProcessor {
|
||||
@@ -32,8 +27,6 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
|
||||
protected final BookMapper bookMapper;
|
||||
protected final MetadataMatchService metadataMatchService;
|
||||
protected final FileService fileService;
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
|
||||
protected AbstractFileProcessor(BookRepository bookRepository,
|
||||
@@ -54,95 +47,9 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
|
||||
@Override
|
||||
public FileProcessResult processFile(LibraryFile libraryFile) {
|
||||
Path path = libraryFile.getFullPath();
|
||||
String fileName = path.getFileName().toString();
|
||||
String hash = FileFingerprint.generateHash(path);
|
||||
|
||||
Optional<Book> duplicate = fileService.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash);
|
||||
|
||||
if (duplicate.isPresent()) {
|
||||
return handleDuplicate(duplicate.get(), libraryFile, hash);
|
||||
}
|
||||
|
||||
Long libraryId = libraryFile.getLibraryEntity().getId();
|
||||
return bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
|
||||
.map(bookMapper::toBook)
|
||||
.map(b -> new FileProcessResult(b, FileProcessStatus.DUPLICATE, createDuplicateInfo(b, libraryFile, hash)))
|
||||
.orElseGet(() -> {
|
||||
Book book = createAndMapBook(libraryFile, hash);
|
||||
return new FileProcessResult(book, FileProcessStatus.NEW, null);
|
||||
});
|
||||
}
|
||||
|
||||
private FileProcessResult handleDuplicate(Book bookDto, LibraryFile libraryFile, String hash) {
|
||||
return bookRepository.findById(bookDto.getId())
|
||||
.map(entity -> {
|
||||
boolean sameHash = Objects.equals(entity.getCurrentHash(), hash);
|
||||
boolean sameFileName = Objects.equals(entity.getFileName(), libraryFile.getFileName());
|
||||
boolean sameSubPath = Objects.equals(entity.getFileSubPath(), libraryFile.getFileSubPath());
|
||||
boolean sameLibraryPath = Objects.equals(entity.getLibraryPath(), libraryFile.getLibraryPathEntity());
|
||||
|
||||
if (sameHash && sameFileName && sameSubPath && sameLibraryPath) {
|
||||
return new FileProcessResult(
|
||||
bookDto,
|
||||
FileProcessStatus.DUPLICATE,
|
||||
createDuplicateInfo(bookDto, libraryFile, hash)
|
||||
);
|
||||
}
|
||||
|
||||
boolean folderChanged = !sameSubPath;
|
||||
boolean updated = false;
|
||||
|
||||
if (!sameSubPath) {
|
||||
entity.setFileSubPath(libraryFile.getFileSubPath());
|
||||
updated = true;
|
||||
}
|
||||
|
||||
if (!sameFileName) {
|
||||
entity.setFileName(libraryFile.getFileName());
|
||||
updated = true;
|
||||
}
|
||||
|
||||
if (!sameLibraryPath) {
|
||||
entity.setLibraryPath(libraryFile.getLibraryPathEntity());
|
||||
entity.setLibrary(libraryFile.getLibraryEntity());
|
||||
updated = true;
|
||||
}
|
||||
|
||||
entity.setCurrentHash(hash);
|
||||
|
||||
/*if (folderChanged) {
|
||||
log.info("Duplicate file found in different folder: bookId={} oldSubPath='{}' newSubPath='{}'",
|
||||
entity.getId(),
|
||||
bookDto.getFileSubPath(),
|
||||
libraryFile.getFileSubPath());
|
||||
}*/
|
||||
|
||||
DuplicateFileInfo dupeInfo = createDuplicateInfo(bookMapper.toBook(entity), libraryFile, hash);
|
||||
|
||||
if (updated) {
|
||||
/*log.info("Duplicate file updated: bookId={} fileName='{}' libraryId={} subPath='{}'",
|
||||
entity.getId(),
|
||||
entity.getFileName(),
|
||||
entity.getLibraryPath().getLibrary().getId(),
|
||||
entity.getFileSubPath());*/
|
||||
entityManager.flush();
|
||||
entityManager.detach(entity);
|
||||
return new FileProcessResult(bookMapper.toBook(entity), FileProcessStatus.UPDATED, dupeInfo);
|
||||
} else {
|
||||
entityManager.detach(entity);
|
||||
return new FileProcessResult(bookMapper.toBook(entity), FileProcessStatus.DUPLICATE, dupeInfo);
|
||||
}
|
||||
})
|
||||
.orElse(new FileProcessResult(bookDto, FileProcessStatus.DUPLICATE, null));
|
||||
}
|
||||
|
||||
private DuplicateFileInfo createDuplicateInfo(Book book, LibraryFile libraryFile, String hash) {
|
||||
return new DuplicateFileInfo(
|
||||
book.getId(),
|
||||
libraryFile.getFileName(),
|
||||
libraryFile.getFullPath().toString(),
|
||||
hash
|
||||
);
|
||||
Book book = createAndMapBook(libraryFile, hash);
|
||||
return new FileProcessResult(book, FileProcessStatus.NEW);
|
||||
}
|
||||
|
||||
private Book createAndMapBook(LibraryFile libraryFile, String hash) {
|
||||
|
||||
+2
-27
@@ -1,14 +1,10 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.DuplicateFileInfo;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.DuplicateFileNotification;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.FileProcessStatus;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||
@@ -18,7 +14,6 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@AllArgsConstructor
|
||||
@@ -44,28 +39,8 @@ public class FileAsBookProcessor implements LibraryFileProcessor {
|
||||
FileProcessResult result = processLibraryFile(libraryFile);
|
||||
|
||||
if (result != null) {
|
||||
if (result.getDuplicate() != null) {
|
||||
DuplicateFileInfo dupe = result.getDuplicate();
|
||||
|
||||
DuplicateFileNotification notification = DuplicateFileNotification.builder()
|
||||
.libraryId(libraryEntity.getId())
|
||||
.libraryName(libraryEntity.getName())
|
||||
.fileId(dupe.getBookId())
|
||||
.fileName(dupe.getFileName())
|
||||
.fullPath(dupe.getFullPath())
|
||||
.hash(dupe.getHash())
|
||||
.timestamp(Instant.now())
|
||||
.build();
|
||||
|
||||
log.info("Duplicate file detected: {}", notification);
|
||||
|
||||
notificationService.sendMessage(Topic.DUPLICATE_FILE, notification);
|
||||
}
|
||||
|
||||
if (result.getStatus() != FileProcessStatus.DUPLICATE) {
|
||||
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
|
||||
log.info("Processed file: {}", libraryFile.getFileName());
|
||||
}
|
||||
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
|
||||
log.info("Processed file: {}", libraryFile.getFileName());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-5
@@ -55,11 +55,6 @@ public class BookFilePersistenceService {
|
||||
notificationService.sendMessageToPermissions(Topic.BOOK_ADD, bookMapper.toBookWithDescription(book, false), Set.of(ADMIN, MANIPULATE_LIBRARY));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<BookEntity> findByHash(String hash) {
|
||||
return bookRepository.findByCurrentHash(hash);
|
||||
}
|
||||
|
||||
String findMatchingLibraryPath(LibraryEntity libraryEntity, Path filePath) {
|
||||
return libraryEntity.getLibraryPaths().stream()
|
||||
.map(lp -> Paths.get(lp.getPath()).toAbsolutePath().normalize())
|
||||
|
||||
+1
-8
@@ -36,16 +36,9 @@ public class BookFileTransactionalHandler {
|
||||
private final LibraryRepository libraryRepository;
|
||||
|
||||
@Transactional()
|
||||
public void handleNewBookFile(long libraryId, Path path, String currentHash) {
|
||||
public void handleNewBookFile(long libraryId, Path path) {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
|
||||
Optional<BookEntity> existingOpt = bookFilePersistenceService.findByHash(currentHash);
|
||||
if (existingOpt.isPresent()) {
|
||||
BookEntity existingBook = existingOpt.get();
|
||||
bookFilePersistenceService.updatePathIfChanged(existingBook, libraryEntity, path, currentHash);
|
||||
return;
|
||||
}
|
||||
|
||||
String filePath = path.toString();
|
||||
String fileName = path.getFileName().toString();
|
||||
String libraryPath = bookFilePersistenceService.findMatchingLibraryPath(libraryEntity, path);
|
||||
|
||||
+2
-4
@@ -118,8 +118,7 @@ public class LibraryFileEventProcessor {
|
||||
|
||||
private void handleFileCreate(LibraryEntity library, Path path) {
|
||||
log.info("[FILE_CREATE] '{}'", path);
|
||||
String hash = FileFingerprint.generateHash(path);
|
||||
bookFileTransactionalHandler.handleNewBookFile(library.getId(), path, hash);
|
||||
bookFileTransactionalHandler.handleNewBookFile(library.getId(), path);
|
||||
}
|
||||
|
||||
private void handleFileDelete(LibraryEntity library, Path path) {
|
||||
@@ -153,8 +152,7 @@ public class LibraryFileEventProcessor {
|
||||
.filter(p -> isBookFile(p.getFileName().toString()))
|
||||
.forEach(p -> {
|
||||
try {
|
||||
String hash = FileFingerprint.generateHash(p);
|
||||
bookFileTransactionalHandler.handleNewBookFile(library.getId(), p, hash);
|
||||
bookFileTransactionalHandler.handleNewBookFile(library.getId(), p);
|
||||
} catch (Exception e) {
|
||||
log.warn("[ERROR] Processing file '{}': {}", p, e.getMessage());
|
||||
}
|
||||
|
||||
@@ -2,18 +2,9 @@ package com.adityachandel.booklore.util;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
@@ -32,15 +23,11 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -50,9 +37,6 @@ import java.util.stream.Stream;
|
||||
public class FileService {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final BookRepository bookRepository;
|
||||
private final BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
private final BookMapper bookMapper;
|
||||
|
||||
// @formatter:off
|
||||
private static final String IMAGES_DIR = "images";
|
||||
@@ -373,59 +357,6 @@ public class FileService {
|
||||
// UTILITY METHODS
|
||||
// ========================================
|
||||
|
||||
@Transactional
|
||||
public Optional<Book> checkForDuplicateAndUpdateMetadataIfNeeded(LibraryFile libraryFile, String hash) {
|
||||
if (StringUtils.isBlank(hash)) {
|
||||
log.warn("Skipping file due to missing hash: {}", libraryFile.getFullPath());
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
// First check for soft-deleted books with the same hash
|
||||
Optional<BookEntity> softDeletedBook = bookRepository.findByCurrentHashAndDeletedTrue(hash);
|
||||
if (softDeletedBook.isPresent()) {
|
||||
BookEntity book = softDeletedBook.get();
|
||||
log.info("Found soft-deleted book with same hash, undeleting: bookId={} file='{}'",
|
||||
book.getId(), libraryFile.getFileName());
|
||||
|
||||
// Undelete the book
|
||||
book.setDeleted(false);
|
||||
book.setDeletedAt(null);
|
||||
|
||||
// Update file information
|
||||
book.setFileName(libraryFile.getFileName());
|
||||
book.setFileSubPath(libraryFile.getFileSubPath());
|
||||
book.setLibraryPath(libraryFile.getLibraryPathEntity());
|
||||
book.setLibrary(libraryFile.getLibraryEntity());
|
||||
|
||||
return Optional.of(bookMapper.toBook(book));
|
||||
}
|
||||
|
||||
Optional<BookEntity> existingByHash = bookRepository.findByCurrentHash(hash);
|
||||
if (existingByHash.isPresent()) {
|
||||
BookEntity book = existingByHash.get();
|
||||
String fileName = libraryFile.getFullPath().getFileName().toString();
|
||||
if (!book.getFileName().equals(fileName)) {
|
||||
book.setFileName(fileName);
|
||||
}
|
||||
if (!Objects.equals(book.getLibraryPath().getId(), libraryFile.getLibraryPathEntity().getId())) {
|
||||
book.setLibraryPath(libraryFile.getLibraryPathEntity());
|
||||
book.setFileSubPath(libraryFile.getFileSubPath());
|
||||
}
|
||||
return Optional.of(bookMapper.toBook(book));
|
||||
}
|
||||
Optional<BookAdditionalFileEntity> existingAdditionalFile = bookAdditionalFileRepository.findByAltFormatCurrentHash(hash);
|
||||
if (existingAdditionalFile.isPresent()) {
|
||||
BookAdditionalFileEntity additionalFile = existingAdditionalFile.get();
|
||||
BookEntity book = additionalFile.getBook();
|
||||
|
||||
// Additional file might have a different name or path, so there is no need
|
||||
// to update the file name or library path here
|
||||
return Optional.of(bookMapper.toBook(book));
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public static String truncate(String input, int maxLength) {
|
||||
if (input == null) return null;
|
||||
if (maxLength <= 0) return "";
|
||||
|
||||
Reference in New Issue
Block a user