Add moveFiles option to attach/merge and per-book delete in duplicate merger (#2833)
* Add moveFiles option to attach/merge and per-book delete in duplicate merger * Remove single-format restriction from attach-to-book action
This commit is contained in:
@@ -288,6 +288,6 @@ public class BookController {
|
||||
public ResponseEntity<Book> attachBookFiles(
|
||||
@Parameter(description = "ID of the target book to attach the files to") @PathVariable Long targetBookId,
|
||||
@Parameter(description = "Request containing source book IDs and delete option") @RequestBody @Valid AttachBookFileRequest request) {
|
||||
return ResponseEntity.ok(bookFileAttachmentService.attachBookFiles(targetBookId, request.getSourceBookIds(), request.isDeleteSourceBooks()));
|
||||
return ResponseEntity.ok(bookFileAttachmentService.attachBookFiles(targetBookId, request.getSourceBookIds(), request.isMoveFiles()));
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -11,5 +11,5 @@ public class AttachBookFileRequest {
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
private List<Long> sourceBookIds;
|
||||
private boolean deleteSourceBooks;
|
||||
private boolean moveFiles;
|
||||
}
|
||||
|
||||
+51
-38
@@ -16,6 +16,7 @@ import org.booklore.service.file.FileMoveHelper;
|
||||
import org.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import org.booklore.service.progress.ReadingProgressService;
|
||||
import org.booklore.util.PathPatternResolver;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -41,9 +42,10 @@ public class BookFileAttachmentService {
|
||||
private final FileMoveHelper fileMoveHelper;
|
||||
private final BookMapper bookMapper;
|
||||
private final BookService bookService;
|
||||
private final EntityManager entityManager;
|
||||
|
||||
@Transactional
|
||||
public Book attachBookFiles(Long targetBookId, List<Long> sourceBookIds, boolean deleteSourceBooks) {
|
||||
public Book attachBookFiles(Long targetBookId, List<Long> sourceBookIds, boolean moveFiles) {
|
||||
BookEntity targetBook = bookRepository.findByIdWithBookFiles(targetBookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(targetBookId));
|
||||
|
||||
@@ -98,50 +100,83 @@ public class BookFileAttachmentService {
|
||||
}
|
||||
}
|
||||
|
||||
// === SETUP PHASE - Calculate paths and naming ===
|
||||
if (moveFiles) {
|
||||
attachWithFileMove(targetBook, sourceBooks, targetPrimaryFile);
|
||||
} else {
|
||||
attachWithoutFileMove(targetBook, sourceBooks);
|
||||
}
|
||||
|
||||
// Get file naming pattern and determine if primary file is at pattern location
|
||||
// Return updated target book
|
||||
return getUpdatedBook(targetBookId);
|
||||
}
|
||||
|
||||
private void attachWithoutFileMove(BookEntity targetBook, List<BookEntity> sourceBooks) {
|
||||
List<Long> sourceBooksToDeleteIds = new ArrayList<>();
|
||||
|
||||
for (BookEntity sourceBook : sourceBooks) {
|
||||
List<Long> bookFileIds = sourceBook.getBookFiles().stream()
|
||||
.filter(BookFileEntity::isBookFormat)
|
||||
.map(BookFileEntity::getId)
|
||||
.toList();
|
||||
|
||||
if (!bookFileIds.isEmpty()) {
|
||||
entityManager.createQuery(
|
||||
"UPDATE BookFileEntity bf SET bf.book.id = :targetId WHERE bf.id IN :fileIds")
|
||||
.setParameter("targetId", targetBook.getId())
|
||||
.setParameter("fileIds", bookFileIds)
|
||||
.executeUpdate();
|
||||
}
|
||||
|
||||
long remainingBookFiles = sourceBook.getBookFiles().size() - bookFileIds.size();
|
||||
if (remainingBookFiles == 0) {
|
||||
sourceBooksToDeleteIds.add(sourceBook.getId());
|
||||
}
|
||||
}
|
||||
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
if (!sourceBooksToDeleteIds.isEmpty()) {
|
||||
List<BookEntity> booksToDelete = bookRepository.findAllById(sourceBooksToDeleteIds);
|
||||
bookRepository.deleteAll(booksToDelete);
|
||||
}
|
||||
}
|
||||
|
||||
private void attachWithFileMove(BookEntity targetBook, List<BookEntity> sourceBooks,
|
||||
BookFileEntity targetPrimaryFile) {
|
||||
String fileNamingPattern = fileMoveHelper.getFileNamingPattern(targetBook.getLibrary());
|
||||
String patternResolvedPath = PathPatternResolver.resolvePattern(targetBook, targetPrimaryFile, fileNamingPattern);
|
||||
Path libraryRootPath = Paths.get(targetBook.getLibraryPath().getPath());
|
||||
Path patternFullPath = libraryRootPath.resolve(patternResolvedPath);
|
||||
|
||||
// Check if primary file is at the pattern location
|
||||
Path actualPrimaryFilePath = targetPrimaryFile.getFullFilePath();
|
||||
boolean primaryFileAtPatternLocation = Files.exists(patternFullPath) &&
|
||||
patternFullPath.normalize().equals(actualPrimaryFilePath.normalize());
|
||||
|
||||
// Determine target directory - use pattern directory, fallback to library root if pattern has no directory
|
||||
Path targetDirectory = patternFullPath.getParent();
|
||||
if (targetDirectory == null) {
|
||||
// Pattern resolved to just a filename with no directory structure
|
||||
targetDirectory = libraryRootPath;
|
||||
}
|
||||
String targetFileSubPath = libraryRootPath.equals(targetDirectory)
|
||||
? ""
|
||||
: libraryRootPath.relativize(targetDirectory).toString();
|
||||
|
||||
// Use pattern-resolved filename (without extension) as base
|
||||
String patternFileName = Paths.get(patternResolvedPath).getFileName().toString();
|
||||
int lastDot = patternFileName.lastIndexOf('.');
|
||||
String baseFileName = lastDot > 0 ? patternFileName.substring(0, lastDot) : patternFileName;
|
||||
|
||||
// Validate target primary file exists (if not at pattern location)
|
||||
if (!primaryFileAtPatternLocation && !Files.exists(actualPrimaryFilePath)) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException(
|
||||
"Target book's primary file not found at expected location: " + actualPrimaryFilePath +
|
||||
". Please ensure the target book's files exist before attaching files.");
|
||||
}
|
||||
|
||||
// === FILE OPERATION PHASE - All file operations inside try-finally for monitoring cleanup ===
|
||||
|
||||
Long libraryId = targetBook.getLibrary().getId();
|
||||
List<BookEntity> sourceBooksToDelete = new ArrayList<>();
|
||||
List<Path> sourceDirectoriesToCleanup = new ArrayList<>();
|
||||
Set<Path> pathsToReregister = new HashSet<>();
|
||||
|
||||
try {
|
||||
// Unregister target directory from monitoring
|
||||
try {
|
||||
monitoringRegistrationService.unregisterSpecificPath(targetDirectory);
|
||||
} catch (Exception ex) {
|
||||
@@ -149,11 +184,9 @@ public class BookFileAttachmentService {
|
||||
}
|
||||
pathsToReregister.add(targetDirectory);
|
||||
|
||||
// If primary file is NOT at pattern location, move all existing target book files there first
|
||||
if (!primaryFileAtPatternLocation) {
|
||||
log.info("Primary file not at pattern location, organizing target book files first");
|
||||
|
||||
// Unregister source directories for existing files
|
||||
for (BookFileEntity existingFile : targetBook.getBookFiles()) {
|
||||
Path currentPath = existingFile.getFullFilePath();
|
||||
if (Files.exists(currentPath)) {
|
||||
@@ -170,14 +203,12 @@ public class BookFileAttachmentService {
|
||||
}
|
||||
}
|
||||
|
||||
// Create target directory if needed
|
||||
try {
|
||||
Files.createDirectories(targetDirectory);
|
||||
} catch (IOException e) {
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("Failed to create target directory: " + e.getMessage());
|
||||
}
|
||||
|
||||
// Move all existing target book files to pattern location
|
||||
for (BookFileEntity existingFile : targetBook.getBookFiles()) {
|
||||
Path currentPath = existingFile.getFullFilePath();
|
||||
if (!Files.exists(currentPath)) {
|
||||
@@ -185,11 +216,8 @@ public class BookFileAttachmentService {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Generate pattern-resolved filename for this file
|
||||
String resolvedPath = PathPatternResolver.resolvePattern(targetBook, existingFile, fileNamingPattern);
|
||||
String newFileName = Paths.get(resolvedPath).getFileName().toString();
|
||||
|
||||
// Resolve conflicts if file already exists at destination
|
||||
newFileName = resolveFilenameConflict(targetDirectory, newFileName);
|
||||
Path destinationPath = targetDirectory.resolve(newFileName);
|
||||
|
||||
@@ -197,8 +225,6 @@ public class BookFileAttachmentService {
|
||||
try {
|
||||
Files.move(currentPath, destinationPath);
|
||||
log.info("Organized file from {} to {}", currentPath, destinationPath);
|
||||
|
||||
// Update database record
|
||||
existingFile.setFileSubPath(targetFileSubPath);
|
||||
existingFile.setFileName(newFileName);
|
||||
} catch (IOException e) {
|
||||
@@ -209,8 +235,6 @@ public class BookFileAttachmentService {
|
||||
}
|
||||
}
|
||||
|
||||
// Track extension counts for handling same-extension conflicts
|
||||
// Initialize with existing extensions in target book
|
||||
Map<String, Integer> extensionCounts = new HashMap<>();
|
||||
for (BookFileEntity existingFile : targetBook.getBookFiles()) {
|
||||
if (existingFile.isBookFormat()) {
|
||||
@@ -219,7 +243,6 @@ public class BookFileAttachmentService {
|
||||
}
|
||||
}
|
||||
|
||||
// Process each source book
|
||||
for (BookEntity sourceBook : sourceBooks) {
|
||||
List<BookFileEntity> filesToMove = sourceBook.getBookFiles().stream()
|
||||
.filter(BookFileEntity::isBookFormat)
|
||||
@@ -241,7 +264,6 @@ public class BookFileAttachmentService {
|
||||
}
|
||||
|
||||
String extension = getFileExtension(fileToMove.getFileName()).toLowerCase();
|
||||
|
||||
int existingCount = extensionCounts.getOrDefault(extension, 0);
|
||||
String newFileName;
|
||||
if (extension.isEmpty()) {
|
||||
@@ -276,23 +298,18 @@ public class BookFileAttachmentService {
|
||||
|
||||
sourceDirectoriesToCleanup.addAll(sourceDirectories);
|
||||
|
||||
if (deleteSourceBooks) {
|
||||
long remainingBookFiles = sourceBook.getBookFiles().stream()
|
||||
.filter(BookFileEntity::isBookFormat)
|
||||
.count();
|
||||
|
||||
if (remainingBookFiles == 0) {
|
||||
sourceBooksToDelete.add(sourceBook);
|
||||
}
|
||||
long remainingBookFiles = sourceBook.getBookFiles().stream()
|
||||
.filter(BookFileEntity::isBookFormat)
|
||||
.count();
|
||||
if (remainingBookFiles == 0) {
|
||||
sourceBooksToDelete.add(sourceBook);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete source books after all files are moved
|
||||
if (!sourceBooksToDelete.isEmpty()) {
|
||||
bookRepository.deleteAll(sourceBooksToDelete);
|
||||
}
|
||||
|
||||
// Cleanup empty source directories
|
||||
Set<Path> libraryRoots = targetBook.getLibrary().getLibraryPaths().stream()
|
||||
.map(LibraryPathEntity::getPath)
|
||||
.map(Paths::get)
|
||||
@@ -303,7 +320,6 @@ public class BookFileAttachmentService {
|
||||
bookService.deleteEmptyParentDirsUpToLibraryFolders(sourceDir, libraryRoots);
|
||||
}
|
||||
} finally {
|
||||
// Re-register paths for monitoring (only if they still exist)
|
||||
for (Path path : pathsToReregister) {
|
||||
if (Files.exists(path) && Files.isDirectory(path)) {
|
||||
try {
|
||||
@@ -314,9 +330,6 @@ public class BookFileAttachmentService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return updated target book
|
||||
return getUpdatedBook(targetBookId);
|
||||
}
|
||||
|
||||
private Book getUpdatedBook(Long bookId) {
|
||||
|
||||
+824
@@ -0,0 +1,824 @@
|
||||
package org.booklore.service.book;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.Query;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.APIException;
|
||||
import org.booklore.mapper.BookMapper;
|
||||
import org.booklore.model.dto.Book;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.*;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.UserBookProgressRepository;
|
||||
import org.booklore.service.file.FileMoveHelper;
|
||||
import org.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import org.booklore.service.progress.ReadingProgressService;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BookFileAttachmentServiceTest {
|
||||
|
||||
@Mock private BookRepository bookRepository;
|
||||
@Mock private UserBookProgressRepository userBookProgressRepository;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private ReadingProgressService readingProgressService;
|
||||
@Mock private MonitoringRegistrationService monitoringRegistrationService;
|
||||
@Mock private FileMoveHelper fileMoveHelper;
|
||||
@Mock private BookMapper bookMapper;
|
||||
@Mock private BookService bookService;
|
||||
@Mock private EntityManager entityManager;
|
||||
|
||||
@InjectMocks
|
||||
private BookFileAttachmentService service;
|
||||
|
||||
@TempDir
|
||||
Path rawTempDir;
|
||||
|
||||
private Path tempDir;
|
||||
private LibraryEntity library;
|
||||
private LibraryPathEntity libraryPath;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
tempDir = rawTempDir.toRealPath();
|
||||
|
||||
library = LibraryEntity.builder()
|
||||
.id(1L)
|
||||
.name("Test Library")
|
||||
.build();
|
||||
|
||||
libraryPath = LibraryPathEntity.builder()
|
||||
.id(1L)
|
||||
.library(library)
|
||||
.path(tempDir.toString())
|
||||
.build();
|
||||
|
||||
library.setLibraryPaths(List.of(libraryPath));
|
||||
}
|
||||
|
||||
private BookEntity createBook(Long id) {
|
||||
BookEntity book = BookEntity.builder()
|
||||
.id(id)
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.build();
|
||||
book.setBookFiles(new ArrayList<>());
|
||||
return book;
|
||||
}
|
||||
|
||||
private BookFileEntity createBookFile(Long id, BookEntity book, String fileName, String subPath,
|
||||
boolean isBookFormat, boolean folderBased) throws IOException {
|
||||
BookFileEntity file = BookFileEntity.builder()
|
||||
.id(id)
|
||||
.book(book)
|
||||
.fileName(fileName)
|
||||
.fileSubPath(subPath)
|
||||
.isBookFormat(isBookFormat)
|
||||
.folderBased(folderBased)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Path dir = tempDir.resolve(subPath);
|
||||
Files.createDirectories(dir);
|
||||
Files.createFile(dir.resolve(fileName));
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
private BookFileEntity createBookFileNoPhysicalFile(Long id, BookEntity book, String fileName,
|
||||
String subPath, boolean isBookFormat) {
|
||||
BookFileEntity file = BookFileEntity.builder()
|
||||
.id(id)
|
||||
.book(book)
|
||||
.fileName(fileName)
|
||||
.fileSubPath(subPath)
|
||||
.isBookFormat(isBookFormat)
|
||||
.folderBased(false)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
return file;
|
||||
}
|
||||
|
||||
private void setupGetUpdatedBookMocks(Long bookId, BookEntity bookEntity) {
|
||||
BookLoreUser user = BookLoreUser.builder().id(1L).username("testuser").build();
|
||||
lenient().when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
lenient().when(bookRepository.findByIdWithBookFiles(bookId))
|
||||
.thenReturn(Optional.of(bookEntity));
|
||||
lenient().when(userBookProgressRepository.findByUserIdAndBookId(1L, bookId))
|
||||
.thenReturn(Optional.empty());
|
||||
lenient().when(readingProgressService.fetchUserFileProgress(eq(1L), anySet()))
|
||||
.thenReturn(Map.of());
|
||||
Book dto = Book.builder().id(bookId).build();
|
||||
lenient().when(bookMapper.toBook(bookEntity)).thenReturn(dto);
|
||||
lenient().when(bookService.filterShelvesByUserId(any(), eq(1L))).thenReturn(Set.of());
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Validation: Target Book")
|
||||
class TargetBookValidation {
|
||||
|
||||
@Test
|
||||
@DisplayName("Throws when target book does not exist")
|
||||
void attachBookFiles_targetNotFound_throws() {
|
||||
when(bookRepository.findByIdWithBookFiles(999L)).thenReturn(Optional.empty());
|
||||
|
||||
APIException ex = assertThrows(APIException.class,
|
||||
() -> service.attachBookFiles(999L, List.of(2L), false));
|
||||
assertTrue(ex.getMessage().contains("999"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Throws when target book has no book format files")
|
||||
void attachBookFiles_targetNoPrimaryFile_throws() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "notes.txt", "sub", false, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "book.epub", "sub2", true, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
APIException ex = assertThrows(APIException.class,
|
||||
() -> service.attachBookFiles(1L, List.of(2L), false));
|
||||
assertTrue(ex.getMessage().contains("no primary file"));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Validation: Source Books")
|
||||
class SourceBookValidation {
|
||||
|
||||
@Test
|
||||
@DisplayName("Throws when attaching a book to itself")
|
||||
void attachBookFiles_selfAttach_throws() {
|
||||
BookEntity target = createBook(1L);
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
|
||||
APIException ex = assertThrows(APIException.class,
|
||||
() -> service.attachBookFiles(1L, List.of(1L), false));
|
||||
assertTrue(ex.getMessage().contains("Cannot attach a book to itself"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Throws when source book does not exist")
|
||||
void attachBookFiles_sourceNotFound_throws() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(999L)).thenReturn(Optional.empty());
|
||||
|
||||
APIException ex = assertThrows(APIException.class,
|
||||
() -> service.attachBookFiles(1L, List.of(999L), false));
|
||||
assertTrue(ex.getMessage().contains("999"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Throws when source book is in a different library")
|
||||
void attachBookFiles_differentLibrary_throws() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
LibraryEntity otherLibrary = LibraryEntity.builder().id(2L).name("Other").build();
|
||||
BookEntity source = BookEntity.builder()
|
||||
.id(2L)
|
||||
.library(otherLibrary)
|
||||
.libraryPath(libraryPath)
|
||||
.bookFiles(new ArrayList<>())
|
||||
.build();
|
||||
createBookFile(20L, source, "source.epub", "sub2", true, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
APIException ex = assertThrows(APIException.class,
|
||||
() -> service.attachBookFiles(1L, List.of(2L), false));
|
||||
assertTrue(ex.getMessage().contains("same library"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Throws when source book has no book format files")
|
||||
void attachBookFiles_sourceNoBookFiles_throws() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "notes.txt", "sub2", false, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
APIException ex = assertThrows(APIException.class,
|
||||
() -> service.attachBookFiles(1L, List.of(2L), false));
|
||||
assertTrue(ex.getMessage().contains("no book format files"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Throws when source book contains folder-based audiobook")
|
||||
void attachBookFiles_folderBasedSource_throws() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "audiobook", "sub2", true, true);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
APIException ex = assertThrows(APIException.class,
|
||||
() -> service.attachBookFiles(1L, List.of(2L), false));
|
||||
assertTrue(ex.getMessage().contains("folder-based"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Throws when source file does not exist on disk")
|
||||
void attachBookFiles_sourceFileMissing_throws() {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFileNoPhysicalFile(10L, target, "target.epub", "sub", true);
|
||||
// Create the target file physically so target validation passes
|
||||
try {
|
||||
Files.createDirectories(tempDir.resolve("sub"));
|
||||
Files.createFile(tempDir.resolve("sub/target.epub"));
|
||||
} catch (IOException e) {
|
||||
fail("Setup failed");
|
||||
}
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFileNoPhysicalFile(20L, source, "missing.epub", "sub2", true);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
APIException ex = assertThrows(APIException.class,
|
||||
() -> service.attachBookFiles(1L, List.of(2L), false));
|
||||
assertTrue(ex.getMessage().contains("Source file not found"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Deduplicates source book IDs")
|
||||
void attachBookFiles_duplicateSourceIds_deduplicates() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.epub", "sub2", true, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
Query mockQuery = mock(Query.class);
|
||||
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
|
||||
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
|
||||
when(mockQuery.executeUpdate()).thenReturn(1);
|
||||
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L, 2L, 2L), false);
|
||||
|
||||
// findByIdWithBookFiles for source should be called only once (deduplicated)
|
||||
verify(bookRepository, times(1)).findByIdWithBookFiles(2L);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Attach Without File Move")
|
||||
class AttachWithoutFileMove {
|
||||
|
||||
@Test
|
||||
@DisplayName("Reassigns book files via JPQL and deletes source book")
|
||||
void attachWithoutFileMove_singleSource_reassignsAndDeletes() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.epub", "sub2", true, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
Query mockQuery = mock(Query.class);
|
||||
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
|
||||
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
|
||||
when(mockQuery.executeUpdate()).thenReturn(1);
|
||||
|
||||
when(bookRepository.findAllById(List.of(2L))).thenReturn(List.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
|
||||
Book result = service.attachBookFiles(1L, List.of(2L), false);
|
||||
|
||||
assertNotNull(result);
|
||||
verify(entityManager).createQuery(contains("UPDATE BookFileEntity"));
|
||||
verify(entityManager).flush();
|
||||
verify(entityManager).clear();
|
||||
verify(bookRepository).deleteAll(List.of(source));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Handles multiple source books")
|
||||
void attachWithoutFileMove_multipleSources_reassignsAll() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
BookEntity source1 = createBook(2L);
|
||||
createBookFile(20L, source1, "source1.epub", "sub2", true, false);
|
||||
|
||||
BookEntity source2 = createBook(3L);
|
||||
createBookFile(30L, source2, "source2.epub", "sub3", true, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source1));
|
||||
when(bookRepository.findByIdWithBookFiles(3L)).thenReturn(Optional.of(source2));
|
||||
|
||||
Query mockQuery = mock(Query.class);
|
||||
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
|
||||
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
|
||||
when(mockQuery.executeUpdate()).thenReturn(1);
|
||||
|
||||
when(bookRepository.findAllById(anyList())).thenReturn(List.of(source1, source2));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L, 3L), false);
|
||||
|
||||
verify(entityManager, times(2)).createQuery(contains("UPDATE BookFileEntity"));
|
||||
verify(bookRepository).deleteAll(anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Does not delete source book if it has remaining non-book files")
|
||||
void attachWithoutFileMove_sourceHasRemainingFiles_noDelete() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.epub", "sub2", true, false);
|
||||
createBookFile(21L, source, "cover.jpg", "sub2", false, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
Query mockQuery = mock(Query.class);
|
||||
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
|
||||
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
|
||||
when(mockQuery.executeUpdate()).thenReturn(1);
|
||||
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), false);
|
||||
|
||||
verify(bookRepository, never()).deleteAll(anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Does not physically move files")
|
||||
void attachWithoutFileMove_filesStayInPlace() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
Path sourceFile = createBookFile(20L, source, "source.epub", "sub2", true, false)
|
||||
.getFullFilePath();
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
Query mockQuery = mock(Query.class);
|
||||
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
|
||||
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
|
||||
when(mockQuery.executeUpdate()).thenReturn(1);
|
||||
|
||||
when(bookRepository.findAllById(List.of(2L))).thenReturn(List.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), false);
|
||||
|
||||
assertTrue(Files.exists(sourceFile), "Source file should remain at original location");
|
||||
}
|
||||
}
|
||||
|
||||
private void setupFileMoveStubs(BookEntity target, String pattern) {
|
||||
lenient().when(fileMoveHelper.getFileNamingPattern(target.getLibrary())).thenReturn(pattern);
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Attach With File Move")
|
||||
class AttachWithFileMove {
|
||||
|
||||
@Test
|
||||
@DisplayName("Moves source file to target directory and renames")
|
||||
void attachWithFileMove_singleSource_movesFile() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "target_dir", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.pdf", "source_dir", true, false);
|
||||
source.getBookFiles().getFirst().setBookType(BookFileType.PDF);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "target_dir/{title}");
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), true);
|
||||
|
||||
assertFalse(Files.exists(tempDir.resolve("source_dir/source.pdf")), "Source file should no longer be at original location");
|
||||
assertTrue(Files.exists(tempDir.resolve("target_dir/target.pdf")),
|
||||
"Source file should be moved to target directory with base name");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Adds suffix when same extension already exists")
|
||||
void attachWithFileMove_sameExtension_addsSuffix() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "target_dir", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.epub", "source_dir", true, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "target_dir/{title}");
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), true);
|
||||
|
||||
Path movedFile = tempDir.resolve("target_dir/target_1.epub");
|
||||
assertTrue(Files.exists(movedFile), "Source file should be moved with _1 suffix");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Organizes target files when primary not at pattern location")
|
||||
void attachWithFileMove_primaryNotAtPattern_organizesFirst() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
target.setMetadata(BookMetadataEntity.builder().bookId(1L).title("new_name").build());
|
||||
createBookFile(10L, target, "old_name.epub", "old_dir", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.pdf", "source_dir", true, false);
|
||||
source.getBookFiles().getFirst().setBookType(BookFileType.PDF);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "new_dir/{title}");
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), true);
|
||||
|
||||
assertTrue(Files.exists(tempDir.resolve("new_dir/new_name.epub")),
|
||||
"Target file should be organized to pattern location");
|
||||
assertTrue(Files.exists(tempDir.resolve("new_dir/new_name.pdf")),
|
||||
"Source file should be moved to new target directory");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Skips organizing if primary file is already at pattern location")
|
||||
void attachWithFileMove_primaryAtPattern_skipsOrganization() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "target_dir", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.pdf", "source_dir", true, false);
|
||||
source.getBookFiles().getFirst().setBookType(BookFileType.PDF);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "target_dir/{title}");
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), true);
|
||||
|
||||
assertTrue(Files.exists(tempDir.resolve("target_dir/target.epub")),
|
||||
"Target file should remain at pattern location");
|
||||
assertTrue(Files.exists(tempDir.resolve("target_dir/target.pdf")),
|
||||
"Source file should be moved to target directory");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Deletes source book when all book files are moved")
|
||||
void attachWithFileMove_allFilesMoved_deletesSourceBook() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "target_dir", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.pdf", "source_dir", true, false);
|
||||
source.getBookFiles().getFirst().setBookType(BookFileType.PDF);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "target_dir/{title}");
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), true);
|
||||
|
||||
verify(bookRepository).deleteAll(anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Throws when target primary file missing and not at pattern")
|
||||
void attachWithFileMove_targetPrimaryMissing_throws() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
target.setMetadata(BookMetadataEntity.builder().bookId(1L).title("other").build());
|
||||
createBookFileNoPhysicalFile(10L, target, "missing.epub", "sub", true);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.epub", "sub2", true, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
setupFileMoveStubs(target, "other_dir/{title}");
|
||||
|
||||
APIException ex = assertThrows(APIException.class,
|
||||
() -> service.attachBookFiles(1L, List.of(2L), true));
|
||||
assertTrue(ex.getMessage().contains("primary file not found"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Re-registers monitoring paths in finally block")
|
||||
void attachWithFileMove_reregistersMonitoring() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "target_dir", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.pdf", "source_dir", true, false);
|
||||
source.getBookFiles().getFirst().setBookType(BookFileType.PDF);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "target_dir/{title}");
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), true);
|
||||
|
||||
verify(monitoringRegistrationService, atLeastOnce()).registerSpecificPath(any(Path.class), eq(1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Monitoring unregister failure does not block operation")
|
||||
void attachWithFileMove_monitoringFailure_continues() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "target_dir", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.pdf", "source_dir", true, false);
|
||||
source.getBookFiles().getFirst().setBookType(BookFileType.PDF);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "target_dir/{title}");
|
||||
|
||||
doThrow(new RuntimeException("monitoring error"))
|
||||
.when(monitoringRegistrationService).unregisterSpecificPath(any(Path.class));
|
||||
|
||||
assertDoesNotThrow(() -> service.attachBookFiles(1L, List.of(2L), true));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Cleans up empty source directories")
|
||||
void attachWithFileMove_cleansUpEmptyDirs() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "target_dir", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.pdf", "source_dir", true, false);
|
||||
source.getBookFiles().getFirst().setBookType(BookFileType.PDF);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "target_dir/{title}");
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), true);
|
||||
|
||||
verify(bookService, atLeastOnce()).deleteEmptyParentDirsUpToLibraryFolders(any(Path.class), anySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Handles multiple source books with different extensions")
|
||||
void attachWithFileMove_multipleSourcesDifferentExtensions() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "target_dir", true, false);
|
||||
|
||||
BookEntity source1 = createBook(2L);
|
||||
createBookFile(20L, source1, "source1.pdf", "source_dir1", true, false);
|
||||
source1.getBookFiles().getFirst().setBookType(BookFileType.PDF);
|
||||
|
||||
BookEntity source2 = createBook(3L);
|
||||
createBookFile(30L, source2, "source2.mobi", "source_dir2", true, false);
|
||||
source2.getBookFiles().getFirst().setBookType(BookFileType.MOBI);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source1));
|
||||
when(bookRepository.findByIdWithBookFiles(3L)).thenReturn(Optional.of(source2));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "target_dir/{title}");
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L, 3L), true);
|
||||
|
||||
assertTrue(Files.exists(tempDir.resolve("target_dir/target.pdf")));
|
||||
assertTrue(Files.exists(tempDir.resolve("target_dir/target.mobi")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Handles multiple source books with same extension using incrementing suffix")
|
||||
void attachWithFileMove_multipleSourcesSameExtension_incrementsSuffix() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "target_dir", true, false);
|
||||
|
||||
BookEntity source1 = createBook(2L);
|
||||
createBookFile(20L, source1, "source1.epub", "source_dir1", true, false);
|
||||
|
||||
BookEntity source2 = createBook(3L);
|
||||
createBookFile(30L, source2, "source2.epub", "source_dir2", true, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source1));
|
||||
when(bookRepository.findByIdWithBookFiles(3L)).thenReturn(Optional.of(source2));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "target_dir/{title}");
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L, 3L), true);
|
||||
|
||||
assertTrue(Files.exists(tempDir.resolve("target_dir/target.epub")), "Original target file stays");
|
||||
assertTrue(Files.exists(tempDir.resolve("target_dir/target_1.epub")), "First source gets _1 suffix");
|
||||
assertTrue(Files.exists(tempDir.resolve("target_dir/target_2.epub")), "Second source gets _2 suffix");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Result Enrichment")
|
||||
class ResultEnrichment {
|
||||
|
||||
@Test
|
||||
@DisplayName("Returns enriched Book DTO with progress and shelves")
|
||||
void getUpdatedBook_returnsEnrichedDto() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.epub", "sub2", true, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
Query mockQuery = mock(Query.class);
|
||||
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
|
||||
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
|
||||
when(mockQuery.executeUpdate()).thenReturn(1);
|
||||
when(bookRepository.findAllById(List.of(2L))).thenReturn(List.of(source));
|
||||
|
||||
BookLoreUser user = BookLoreUser.builder().id(1L).username("testuser").build();
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(userBookProgressRepository.findByUserIdAndBookId(1L, 1L))
|
||||
.thenReturn(Optional.empty());
|
||||
when(readingProgressService.fetchUserFileProgress(eq(1L), anySet()))
|
||||
.thenReturn(Map.of());
|
||||
|
||||
Book dto = Book.builder().id(1L).build();
|
||||
when(bookMapper.toBook(target)).thenReturn(dto);
|
||||
when(bookService.filterShelvesByUserId(any(), eq(1L))).thenReturn(Set.of());
|
||||
|
||||
Book result = service.attachBookFiles(1L, List.of(2L), false);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1L, result.getId());
|
||||
verify(readingProgressService).enrichBookWithProgress(eq(dto), any(), any());
|
||||
verify(bookService).filterShelvesByUserId(any(), eq(1L));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Edge Cases")
|
||||
class EdgeCases {
|
||||
|
||||
@Test
|
||||
@DisplayName("Source book with mixed book and non-book files: only book files reassigned")
|
||||
void attachWithoutFileMove_mixedFiles_onlyBookFormatReassigned() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.epub", "sub2", true, false);
|
||||
createBookFile(21L, source, "cover.jpg", "sub2", false, false);
|
||||
createBookFile(22L, source, "metadata.xml", "sub2", false, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
Query mockQuery = mock(Query.class);
|
||||
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
|
||||
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
|
||||
when(mockQuery.executeUpdate()).thenReturn(1);
|
||||
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), false);
|
||||
|
||||
// Should not delete source since it has remaining non-book files
|
||||
verify(bookRepository, never()).deleteAll(anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Source book with multiple book format files: all reassigned")
|
||||
void attachWithoutFileMove_multipleBookFiles_allReassigned() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "sub", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.epub", "sub2", true, false);
|
||||
createBookFile(21L, source, "source.pdf", "sub2", true, false);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
Query mockQuery = mock(Query.class);
|
||||
when(entityManager.createQuery(anyString())).thenReturn(mockQuery);
|
||||
when(mockQuery.setParameter(anyString(), any())).thenReturn(mockQuery);
|
||||
when(mockQuery.executeUpdate()).thenReturn(1);
|
||||
|
||||
when(bookRepository.findAllById(List.of(2L))).thenReturn(List.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), false);
|
||||
|
||||
verify(entityManager).createQuery(contains("UPDATE BookFileEntity"));
|
||||
verify(bookRepository).deleteAll(List.of(source));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Empty source book IDs list after filtering self-references")
|
||||
void attachBookFiles_emptySourceAfterFilter_noopValidation() {
|
||||
BookEntity target = createBook(1L);
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
|
||||
APIException ex = assertThrows(APIException.class,
|
||||
() -> service.attachBookFiles(1L, List.of(1L), false));
|
||||
assertTrue(ex.getMessage().contains("Cannot attach a book to itself"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pattern resolves to file at library root (no subdirectory)")
|
||||
void attachWithFileMove_patternAtLibraryRoot() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
createBookFile(20L, source, "source.pdf", "source_dir", true, false);
|
||||
source.getBookFiles().getFirst().setBookType(BookFileType.PDF);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "{title}");
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), true);
|
||||
|
||||
assertTrue(Files.exists(tempDir.resolve("target.pdf")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("File without extension handled correctly")
|
||||
void attachWithFileMove_fileWithoutExtension() throws IOException {
|
||||
BookEntity target = createBook(1L);
|
||||
createBookFile(10L, target, "target.epub", "target_dir", true, false);
|
||||
|
||||
BookEntity source = createBook(2L);
|
||||
BookFileEntity sourceFile = BookFileEntity.builder()
|
||||
.id(20L)
|
||||
.book(source)
|
||||
.fileName("noextension")
|
||||
.fileSubPath("source_dir")
|
||||
.isBookFormat(true)
|
||||
.folderBased(false)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
Files.createDirectories(tempDir.resolve("source_dir"));
|
||||
Files.createFile(tempDir.resolve("source_dir/noextension"));
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
setupGetUpdatedBookMocks(1L, target);
|
||||
setupFileMoveStubs(target, "target_dir/{title}");
|
||||
|
||||
service.attachBookFiles(1L, List.of(2L), true);
|
||||
|
||||
assertTrue(Files.exists(tempDir.resolve("target_dir/target")),
|
||||
"File without extension should use base name");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -915,11 +915,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
}
|
||||
|
||||
attachFilesToBook(): void {
|
||||
// Get selected books that are single-file books (no alternative formats)
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedBookIds = Array.from(this.selectedBooks);
|
||||
const sourceBooks = (currentState.books || []).filter(book =>
|
||||
selectedBookIds.includes(book.id) && !book.alternativeFormats?.length
|
||||
selectedBookIds.includes(book.id)
|
||||
);
|
||||
|
||||
if (sourceBooks.length === 0) {
|
||||
@@ -957,14 +956,13 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedBookIds = Array.from(this.selectedBooks);
|
||||
const eligibleBooks = (currentState.books || []).filter(book =>
|
||||
selectedBookIds.includes(book.id) && !book.alternativeFormats?.length
|
||||
const selectedBooks = (currentState.books || []).filter(book =>
|
||||
selectedBookIds.includes(book.id)
|
||||
);
|
||||
|
||||
if (eligibleBooks.length === 0) return false;
|
||||
if (selectedBooks.length === 0) return false;
|
||||
|
||||
// Check if all eligible books are from the same library
|
||||
const libraryIds = new Set(eligibleBooks.map(b => b.libraryId));
|
||||
const libraryIds = new Set(selectedBooks.map(b => b.libraryId));
|
||||
return libraryIds.size === 1;
|
||||
}
|
||||
|
||||
|
||||
+9
-9
@@ -70,16 +70,16 @@
|
||||
</p-autocomplete>
|
||||
</div>
|
||||
|
||||
<!-- Delete Source Book(s) Option -->
|
||||
<!-- Options -->
|
||||
<div class="delete-option">
|
||||
<p-checkbox
|
||||
[(ngModel)]="deleteSourceBooks"
|
||||
[(ngModel)]="moveFiles"
|
||||
[binary]="true"
|
||||
inputId="deleteSourceBooks"
|
||||
inputId="moveFiles"
|
||||
[disabled]="isAttaching">
|
||||
</p-checkbox>
|
||||
<label for="deleteSourceBooks" class="delete-label">
|
||||
{{ isBulkMode ? t('deleteSourceBulk') : t('deleteSource') }}
|
||||
<label for="moveFiles" class="delete-label">
|
||||
{{ t('moveFilesLabel') }}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
@@ -87,12 +87,12 @@
|
||||
<div class="warning-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<div class="warning-text">
|
||||
<p>{{ isBulkMode ? t('warningMoveBulk') : t('warningMove') }}</p>
|
||||
@if (deleteSourceBooks) {
|
||||
<p>{{ isBulkMode ? t('warningDeleteBulk') : t('warningDelete') }}</p>
|
||||
@if (moveFiles) {
|
||||
<p>{{ isBulkMode ? t('warningMoveBulk') : t('warningMove') }}</p>
|
||||
} @else {
|
||||
<p>{{ isBulkMode ? t('warningKeepBulk') : t('warningKeep') }}</p>
|
||||
<p>{{ isBulkMode ? t('warningNoMoveBulk') : t('warningNoMove') }}</p>
|
||||
}
|
||||
<p>{{ isBulkMode ? t('warningDeleteBulk') : t('warningDelete') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+13
-3
@@ -11,6 +11,7 @@ import { BookFileService } from '../../service/book-file.service';
|
||||
import { Book } from '../../model/book.model';
|
||||
import { MessageService } from 'primeng/api';
|
||||
import { TranslocoDirective, TranslocoPipe, TranslocoService } from '@jsverse/transloco';
|
||||
import { AppSettingsService } from '../../../../shared/service/app-settings.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-file-attacher',
|
||||
@@ -29,7 +30,7 @@ import { TranslocoDirective, TranslocoPipe, TranslocoService } from '@jsverse/tr
|
||||
export class BookFileAttacherComponent implements OnInit, OnDestroy {
|
||||
sourceBooks: Book[] = [];
|
||||
targetBook: Book | null = null;
|
||||
deleteSourceBooks = true;
|
||||
moveFiles = false;
|
||||
isAttaching = false;
|
||||
searchQuery = '';
|
||||
filteredBooks: Book[] = [];
|
||||
@@ -38,6 +39,7 @@ export class BookFileAttacherComponent implements OnInit, OnDestroy {
|
||||
private allBooks: Book[] = [];
|
||||
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly appSettingsService = inject(AppSettingsService);
|
||||
|
||||
constructor(
|
||||
private dialogRef: DynamicDialogRef,
|
||||
@@ -60,6 +62,14 @@ export class BookFileAttacherComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
this.appSettingsService.appSettings$.pipe(
|
||||
filter(settings => !!settings),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(settings => {
|
||||
this.moveFiles = settings!.metadataPersistenceSettings?.moveFilesToLibraryPattern ?? false;
|
||||
});
|
||||
|
||||
// Get the library ID from first source book (all should be same library)
|
||||
const libraryId = this.sourceBooks[0].libraryId;
|
||||
const sourceBookIds = new Set(this.sourceBooks.map(b => b.id));
|
||||
@@ -136,12 +146,12 @@ export class BookFileAttacherComponent implements OnInit, OnDestroy {
|
||||
this.bookFileService.attachBookFiles(
|
||||
this.targetBook.id,
|
||||
sourceBookIds,
|
||||
this.deleteSourceBooks
|
||||
this.moveFiles
|
||||
).pipe(
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe({
|
||||
next: () => {
|
||||
this.dialogRef.close({ success: true, deletedSourceBooks: this.deleteSourceBooks });
|
||||
this.dialogRef.close({ success: true });
|
||||
},
|
||||
error: () => {
|
||||
this.isAttaching = false;
|
||||
|
||||
+37
-4
@@ -78,12 +78,12 @@
|
||||
<div class="action-bar-right">
|
||||
<div class="delete-option">
|
||||
<p-checkbox
|
||||
[(ngModel)]="deleteSourceBooks"
|
||||
[(ngModel)]="moveFiles"
|
||||
[binary]="true"
|
||||
inputId="deleteSource"
|
||||
inputId="moveFiles"
|
||||
[disabled]="isMerging">
|
||||
</p-checkbox>
|
||||
<label for="deleteSource">{{ t('deleteSource') }}</label>
|
||||
<label for="moveFiles">{{ 'book.fileAttacher.moveFilesLabel' | transloco }}</label>
|
||||
</div>
|
||||
@if (activeGroups.length > 0) {
|
||||
<p-button
|
||||
@@ -140,6 +140,9 @@
|
||||
<div class="group-header">
|
||||
<span class="group-label">{{ t('groupLabel', { index: pageFirst + $index + 1 }) }}</span>
|
||||
<p-tag [value]="getMatchReasonLabel(group.matchReason)" [severity]="getMatchReasonSeverity(group.matchReason)"></p-tag>
|
||||
@if (hasSameFormatConflict(group)) {
|
||||
<p-tag [value]="t('sameFormatWarning')" severity="warn" icon="pi pi-exclamation-triangle"></p-tag>
|
||||
}
|
||||
<div class="group-actions">
|
||||
<p-button
|
||||
[label]="t('merge')"
|
||||
@@ -149,6 +152,17 @@
|
||||
(click)="mergeGroup(group)"
|
||||
[disabled]="isMerging">
|
||||
</p-button>
|
||||
@if (getDeleteSelectedCount(group) > 0) {
|
||||
<p-button
|
||||
[label]="t('deleteSelected', { count: getDeleteSelectedCount(group) })"
|
||||
icon="pi pi-trash"
|
||||
size="small"
|
||||
severity="danger"
|
||||
[outlined]="true"
|
||||
(click)="deleteGroup(group)"
|
||||
[disabled]="isMerging">
|
||||
</p-button>
|
||||
}
|
||||
<p-button
|
||||
[label]="t('dismiss')"
|
||||
icon="pi pi-times"
|
||||
@@ -162,7 +176,16 @@
|
||||
</div>
|
||||
<div class="group-books">
|
||||
@for (book of group.books; track book.id) {
|
||||
<div class="book-row" [class.selected-target]="book.id === group.selectedTargetBookId" (click)="group.selectedTargetBookId = book.id">
|
||||
<div class="book-row" [class.selected-target]="book.id === group.selectedTargetBookId" [class.marked-for-deletion]="group.selectedForDeletion.has(book.id)">
|
||||
@if (book.id !== group.selectedTargetBookId) {
|
||||
<p-checkbox
|
||||
[binary]="true"
|
||||
[ngModel]="group.selectedForDeletion.has(book.id)"
|
||||
(onChange)="toggleDeleteSelection(group, book.id)"
|
||||
[disabled]="isMerging"
|
||||
class="delete-checkbox">
|
||||
</p-checkbox>
|
||||
}
|
||||
<img class="book-cover"
|
||||
[src]="urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn)"
|
||||
[alt]="book.metadata?.title || ''"
|
||||
@@ -179,13 +202,23 @@
|
||||
@if (getFileCount(book) > 1) {
|
||||
<span class="file-count">{{ t('fileCount', { count: getFileCount(book) }) }}</span>
|
||||
}
|
||||
@if (book.primaryFile?.fileSizeKb) {
|
||||
<span class="file-detail">{{ formatFileSize(book.primaryFile?.fileSizeKb) }}</span>
|
||||
}
|
||||
</div>
|
||||
@if (book.primaryFile?.fileName) {
|
||||
<div class="book-file-path" [title]="getBookFilePath(book)">
|
||||
<i class="pi pi-file"></i>
|
||||
{{ getBookFilePath(book) }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="book-select">
|
||||
<p-radioButton
|
||||
[name]="'target-' + group.suggestedTargetBookId"
|
||||
[value]="book.id"
|
||||
[(ngModel)]="group.selectedTargetBookId"
|
||||
(onClick)="onTargetChange(group)"
|
||||
[disabled]="isMerging">
|
||||
</p-radioButton>
|
||||
@if (book.id === group.selectedTargetBookId) {
|
||||
|
||||
+30
@@ -190,6 +190,14 @@
|
||||
background: var(--p-highlight-background);
|
||||
}
|
||||
|
||||
&.marked-for-deletion {
|
||||
background: color-mix(in srgb, var(--p-red-500) 8%, transparent);
|
||||
}
|
||||
|
||||
.delete-checkbox {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.book-cover {
|
||||
width: 36px;
|
||||
height: 52px;
|
||||
@@ -244,6 +252,28 @@
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-text-muted-color);
|
||||
}
|
||||
|
||||
.file-detail {
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-text-muted-color);
|
||||
}
|
||||
}
|
||||
|
||||
.book-file-path {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-text-muted-color);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
margin-top: 0.125rem;
|
||||
|
||||
i {
|
||||
font-size: 0.6875rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+90
-5
@@ -8,18 +8,21 @@ import {SelectButton} from 'primeng/selectbutton';
|
||||
import {ProgressBar} from 'primeng/progressbar';
|
||||
import {Tag} from 'primeng/tag';
|
||||
import {Paginator} from 'primeng/paginator';
|
||||
import {Subject, takeUntil} from 'rxjs';
|
||||
import {filter, Subject, take, takeUntil} from 'rxjs';
|
||||
import {BookFileService} from '../../service/book-file.service';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {Book, DuplicateDetectionRequest, DuplicateGroup} from '../../model/book.model';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
|
||||
type PresetMode = 'strict' | 'balanced' | 'aggressive' | 'custom';
|
||||
|
||||
interface DisplayGroup extends DuplicateGroup {
|
||||
selectedTargetBookId: number;
|
||||
dismissed: boolean;
|
||||
selectedForDeletion: Set<number>;
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -54,7 +57,7 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
|
||||
isScanning = false;
|
||||
isMerging = false;
|
||||
hasScanned = false;
|
||||
deleteSourceBooks = true;
|
||||
moveFiles = false;
|
||||
mergeProgress = 0;
|
||||
mergeTotal = 0;
|
||||
|
||||
@@ -66,14 +69,26 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
private readonly bookFileService = inject(BookFileService);
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly confirmationService = inject(ConfirmationService);
|
||||
private readonly dialogRef = inject(DynamicDialogRef);
|
||||
private readonly config = inject(DynamicDialogConfig);
|
||||
private readonly t = inject(TranslocoService);
|
||||
readonly urlHelper = inject(UrlHelperService);
|
||||
private readonly appSettingsService = inject(AppSettingsService);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.libraryId = this.config.data.libraryId;
|
||||
|
||||
this.appSettingsService.appSettings$.pipe(
|
||||
filter(settings => !!settings),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(settings => {
|
||||
this.moveFiles = settings!.metadataPersistenceSettings?.moveFilesToLibraryPattern ?? false;
|
||||
});
|
||||
|
||||
this.presetOptions = [
|
||||
{label: this.t.translate('book.duplicateMerger.presetStrict'), value: 'strict'},
|
||||
{label: this.t.translate('book.duplicateMerger.presetBalanced'), value: 'balanced'},
|
||||
@@ -147,6 +162,7 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
|
||||
...g,
|
||||
selectedTargetBookId: g.suggestedTargetBookId,
|
||||
dismissed: false,
|
||||
selectedForDeletion: new Set<number>(),
|
||||
}));
|
||||
this.isScanning = false;
|
||||
this.hasScanned = true;
|
||||
@@ -207,6 +223,32 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
|
||||
return this.t.translate(`book.duplicateMerger.reason.${reason}`);
|
||||
}
|
||||
|
||||
hasSameFormatConflict(group: DisplayGroup): boolean {
|
||||
const formats = new Set<string>();
|
||||
for (const book of group.books) {
|
||||
if (book.primaryFile?.bookType) {
|
||||
if (formats.has(book.primaryFile.bookType)) return true;
|
||||
formats.add(book.primaryFile.bookType);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
getBookFilePath(book: Book): string {
|
||||
const subPath = book.primaryFile?.fileSubPath;
|
||||
const fileName = book.primaryFile?.fileName || '';
|
||||
if (subPath) return `${subPath}/${fileName}`;
|
||||
return fileName;
|
||||
}
|
||||
|
||||
formatFileSize(sizeKb?: number): string {
|
||||
if (!sizeKb) return '';
|
||||
if (sizeKb < 1024) return `${sizeKb} KB`;
|
||||
const sizeMb = sizeKb / 1024;
|
||||
if (sizeMb < 1024) return `${sizeMb.toFixed(1)} MB`;
|
||||
return `${(sizeMb / 1024).toFixed(2)} GB`;
|
||||
}
|
||||
|
||||
getMatchReasonSeverity(reason: string): "success" | "info" | "warn" | "danger" | "secondary" | "contrast" {
|
||||
switch (reason) {
|
||||
case 'ISBN':
|
||||
@@ -223,6 +265,22 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
onTargetChange(group: DisplayGroup): void {
|
||||
group.selectedForDeletion.delete(group.selectedTargetBookId);
|
||||
}
|
||||
|
||||
toggleDeleteSelection(group: DisplayGroup, bookId: number): void {
|
||||
if (group.selectedForDeletion.has(bookId)) {
|
||||
group.selectedForDeletion.delete(bookId);
|
||||
} else {
|
||||
group.selectedForDeletion.add(bookId);
|
||||
}
|
||||
}
|
||||
|
||||
getDeleteSelectedCount(group: DisplayGroup): number {
|
||||
return group.selectedForDeletion.size;
|
||||
}
|
||||
|
||||
dismissGroup(group: DisplayGroup): void {
|
||||
group.dismissed = true;
|
||||
if (this.pagedGroups.length === 0 && this.pageFirst > 0) {
|
||||
@@ -240,7 +298,7 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
|
||||
|
||||
group.dismissed = true;
|
||||
try {
|
||||
await this.bookFileService.attachBookFiles(targetId, sourceIds, this.deleteSourceBooks)
|
||||
await this.bookFileService.attachBookFiles(targetId, sourceIds, this.moveFiles)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.toPromise();
|
||||
} catch {
|
||||
@@ -277,7 +335,7 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
try {
|
||||
await this.bookFileService.attachBookFiles(targetId, sourceIds, this.deleteSourceBooks)
|
||||
await this.bookFileService.attachBookFiles(targetId, sourceIds, this.moveFiles)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.toPromise();
|
||||
group.dismissed = true;
|
||||
@@ -306,6 +364,33 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
deleteGroup(group: DisplayGroup): void {
|
||||
const idsToDelete = Array.from(group.selectedForDeletion);
|
||||
if (idsToDelete.length === 0) return;
|
||||
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.duplicateMerger.confirm.deleteMessage', {count: idsToDelete.length}),
|
||||
header: this.t.translate('book.duplicateMerger.confirm.deleteHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.no'),
|
||||
acceptButtonProps: {severity: 'danger'},
|
||||
accept: () => {
|
||||
this.bookService.deleteBooks(new Set(idsToDelete)).pipe(
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe({
|
||||
next: () => {
|
||||
group.books = group.books.filter(b => !group.selectedForDeletion.has(b.id));
|
||||
group.selectedForDeletion.clear();
|
||||
if (group.books.length <= 1) {
|
||||
group.dismissed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
closeDialog(): void {
|
||||
this.dialogRef.close();
|
||||
}
|
||||
|
||||
@@ -212,21 +212,17 @@ export class BookFileService {
|
||||
return this.http.post<DuplicateGroup[]>(`${this.url}/duplicates`, request);
|
||||
}
|
||||
|
||||
attachBookFiles(targetBookId: number, sourceBookIds: number[], deleteSourceBooks: boolean): Observable<Book> {
|
||||
attachBookFiles(targetBookId: number, sourceBookIds: number[], moveFiles: boolean): Observable<Book> {
|
||||
return this.http.post<Book>(`${this.url}/${targetBookId}/attach-file`, {
|
||||
sourceBookIds,
|
||||
deleteSourceBooks
|
||||
moveFiles
|
||||
}).pipe(
|
||||
tap(updatedBook => {
|
||||
const currentState = this.bookStateService.getCurrentBookState();
|
||||
const sourceIdSet = new Set(sourceBookIds);
|
||||
let updatedBooks = (currentState.books || []).map(book =>
|
||||
book.id === targetBookId ? updatedBook : book
|
||||
);
|
||||
|
||||
if (deleteSourceBooks) {
|
||||
const sourceIdSet = new Set(sourceBookIds);
|
||||
updatedBooks = updatedBooks.filter(book => !sourceIdSet.has(book.id));
|
||||
}
|
||||
).filter(book => !sourceIdSet.has(book.id));
|
||||
|
||||
this.bookStateService.updateBookState({
|
||||
...currentState,
|
||||
|
||||
@@ -691,14 +691,13 @@
|
||||
"unknownTitle": "Unknown Title",
|
||||
"selectTargetBook": "Select Target Book",
|
||||
"searchPlaceholder": "Search for a book in the same library...",
|
||||
"deleteSource": "Delete source book after attachment",
|
||||
"deleteSourceBulk": "Delete source books after attachment",
|
||||
"warningMove": "This will move the file from the source book to the target book as alternative format.",
|
||||
"warningMoveBulk": "This will move the files from the selected books to the target book as alternative formats.",
|
||||
"warningDelete": "The source book record will be deleted (file will be preserved in target book).",
|
||||
"warningDeleteBulk": "The source book records will be deleted (files will be preserved in target book).",
|
||||
"warningKeep": "The source book record will remain but will have no readable files.",
|
||||
"warningKeepBulk": "The source book records will remain but will have no readable files.",
|
||||
"moveFilesLabel": "Move files to target book's directory",
|
||||
"warningMove": "The source file will be moved to the target book's directory and renamed to match.",
|
||||
"warningMoveBulk": "The source files will be moved to the target book's directory and renamed to match.",
|
||||
"warningNoMove": "The source file will stay in its original location on disk.",
|
||||
"warningNoMoveBulk": "The source files will stay in their original locations on disk.",
|
||||
"warningDelete": "The source book record will be removed (files are preserved in target book).",
|
||||
"warningDeleteBulk": "The source book records will be removed (files are preserved in target book).",
|
||||
"attachFile": "Attach File",
|
||||
"attachFilesBulk": "Attach Files",
|
||||
"unknownFile": "Unknown file",
|
||||
@@ -791,12 +790,13 @@
|
||||
"scanPrompt": "Select a detection mode and click Scan to find duplicates.",
|
||||
"noDuplicates": "No duplicates found.",
|
||||
"allMerged": "All duplicate groups have been processed.",
|
||||
"deleteSource": "Delete source books",
|
||||
"mergeAll": "Merge All ({{ count }})",
|
||||
"merge": "Merge",
|
||||
"deleteSelected": "Delete ({{ count }})",
|
||||
"dismiss": "Dismiss",
|
||||
"target": "Target",
|
||||
"helpText": "Each group contains books that appear to be duplicates. Select the target book (the one to keep), then click Merge. The other books' files will be attached to the target as alternative formats.",
|
||||
"sameFormatWarning": "Same format",
|
||||
"helpText": "Each group contains books that appear to be duplicates. Select the target book (the one to keep), then click Merge to combine files. To delete specific duplicates, check the ones you want to remove and click Delete.",
|
||||
"groupLabel": "Group {{ index }}",
|
||||
"fileCount": "{{ count }} files",
|
||||
"reason": {
|
||||
@@ -806,6 +806,10 @@
|
||||
"DIRECTORY": "Same Directory",
|
||||
"FILENAME": "Filename Match"
|
||||
},
|
||||
"confirm": {
|
||||
"deleteHeader": "Confirm Deletion",
|
||||
"deleteMessage": "This will permanently delete {{ count }} book(s) and their files from disk. This cannot be undone."
|
||||
},
|
||||
"toast": {
|
||||
"scanFailedSummary": "Scan Failed",
|
||||
"scanFailedDetail": "Could not scan for duplicates.",
|
||||
|
||||
@@ -691,14 +691,13 @@
|
||||
"unknownTitle": "Titulo desconocido",
|
||||
"selectTargetBook": "Seleccionar libro de destino",
|
||||
"searchPlaceholder": "Buscar un libro en la misma biblioteca...",
|
||||
"deleteSource": "Eliminar libro de origen tras adjuntar",
|
||||
"deleteSourceBulk": "Eliminar libros de origen tras adjuntar",
|
||||
"warningMove": "Esto moverá el archivo del libro de origen al libro de destino como formato alternativo.",
|
||||
"warningMoveBulk": "Esto moverá los archivos de los libros seleccionados al libro de destino como formatos alternativos.",
|
||||
"warningDelete": "El registro del libro de origen será eliminado (el archivo se conservará en el libro de destino).",
|
||||
"warningDeleteBulk": "Los registros de los libros de origen serán eliminados (los archivos se conservarán en el libro de destino).",
|
||||
"warningKeep": "El registro del libro de origen permanecerá, pero no tendrá archivos legibles.",
|
||||
"warningKeepBulk": "Los registros de los libros de origen permanecerán, pero no tendrán archivos legibles.",
|
||||
"moveFilesLabel": "Mover archivos al directorio del libro de destino",
|
||||
"warningMove": "El archivo de origen se moverá al directorio del libro de destino y se renombrará.",
|
||||
"warningMoveBulk": "Los archivos de origen se moverán al directorio del libro de destino y se renombrarán.",
|
||||
"warningNoMove": "El archivo de origen permanecerá en su ubicación original en disco.",
|
||||
"warningNoMoveBulk": "Los archivos de origen permanecerán en sus ubicaciones originales en disco.",
|
||||
"warningDelete": "El registro del libro de origen será eliminado (los archivos se conservan en el libro de destino).",
|
||||
"warningDeleteBulk": "Los registros de los libros de origen serán eliminados (los archivos se conservan en el libro de destino).",
|
||||
"attachFile": "Adjuntar archivo",
|
||||
"attachFilesBulk": "Adjuntar archivos",
|
||||
"unknownFile": "Archivo desconocido",
|
||||
@@ -791,12 +790,13 @@
|
||||
"scanPrompt": "Seleccione un modo de detección y haga clic en Escanear para buscar duplicados.",
|
||||
"noDuplicates": "No se encontraron duplicados.",
|
||||
"allMerged": "Todos los grupos duplicados han sido procesados.",
|
||||
"deleteSource": "Eliminar libros de origen",
|
||||
"mergeAll": "Fusionar todo ({{ count }})",
|
||||
"merge": "Fusionar",
|
||||
"deleteSelected": "Eliminar ({{ count }})",
|
||||
"dismiss": "Descartar",
|
||||
"target": "Destino",
|
||||
"helpText": "Cada grupo contiene libros que parecen ser duplicados. Seleccione el libro destino (el que se conserva) y haga clic en Fusionar. Los archivos de los otros libros se adjuntarán al destino como formatos alternativos.",
|
||||
"sameFormatWarning": "Mismo formato",
|
||||
"helpText": "Cada grupo contiene libros que parecen ser duplicados. Seleccione el libro destino (el que se conserva) y haga clic en Fusionar para combinar archivos. Para eliminar duplicados específicos, marque los que desea eliminar y haga clic en Eliminar.",
|
||||
"groupLabel": "Grupo {{ index }}",
|
||||
"fileCount": "{{ count }} archivos",
|
||||
"reason": {
|
||||
@@ -806,6 +806,10 @@
|
||||
"DIRECTORY": "Mismo directorio",
|
||||
"FILENAME": "Coincidencia de nombre"
|
||||
},
|
||||
"confirm": {
|
||||
"deleteHeader": "Confirmar eliminación",
|
||||
"deleteMessage": "Esto eliminará permanentemente {{ count }} libro(s) y sus archivos del disco. Esta acción no se puede deshacer."
|
||||
},
|
||||
"toast": {
|
||||
"scanFailedSummary": "Error de escaneo",
|
||||
"scanFailedDetail": "No se pudieron buscar duplicados.",
|
||||
|
||||
Reference in New Issue
Block a user