From a8c356297c547ebc30ffcf21f24fefc44b2db4b8 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Wed, 25 Feb 2026 16:17:34 -0700 Subject: [PATCH] fix attach file without move when source/target have different library paths (#2999) --- .../booklore/controller/BookController.java | 3 +- .../dto/response/AttachBookFileResponse.java | 7 +++ .../book/BookFileAttachmentService.java | 37 ++++++++--- .../book/BookFileAttachmentServiceTest.java | 63 +++++++++++++++++-- .../book/service/book-file.service.ts | 12 ++-- 5 files changed, 100 insertions(+), 22 deletions(-) create mode 100644 booklore-api/src/main/java/org/booklore/model/dto/response/AttachBookFileResponse.java diff --git a/booklore-api/src/main/java/org/booklore/controller/BookController.java b/booklore-api/src/main/java/org/booklore/controller/BookController.java index 556208484..f547602c2 100644 --- a/booklore-api/src/main/java/org/booklore/controller/BookController.java +++ b/booklore-api/src/main/java/org/booklore/controller/BookController.java @@ -12,6 +12,7 @@ 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.AttachBookFileResponse; import org.booklore.model.dto.response.BookDeletionResponse; import org.booklore.model.dto.response.BookStatusUpdateResponse; import org.booklore.model.dto.response.DuplicateGroup; @@ -285,7 +286,7 @@ public class BookController { }) @PostMapping("/{targetBookId}/attach-file") @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") - public ResponseEntity attachBookFiles( + public ResponseEntity 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.isMoveFiles())); diff --git a/booklore-api/src/main/java/org/booklore/model/dto/response/AttachBookFileResponse.java b/booklore-api/src/main/java/org/booklore/model/dto/response/AttachBookFileResponse.java new file mode 100644 index 000000000..ee0a0c145 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/response/AttachBookFileResponse.java @@ -0,0 +1,7 @@ +package org.booklore.model.dto.response; + +import org.booklore.model.dto.Book; + +import java.util.List; + +public record AttachBookFileResponse(Book updatedBook, List deletedSourceBookIds) {} diff --git a/booklore-api/src/main/java/org/booklore/service/book/BookFileAttachmentService.java b/booklore-api/src/main/java/org/booklore/service/book/BookFileAttachmentService.java index 7eb8642b7..e2b418847 100644 --- a/booklore-api/src/main/java/org/booklore/service/book/BookFileAttachmentService.java +++ b/booklore-api/src/main/java/org/booklore/service/book/BookFileAttachmentService.java @@ -5,6 +5,7 @@ import org.booklore.exception.ApiError; import org.booklore.mapper.BookMapper; import org.booklore.model.dto.Book; import org.booklore.model.dto.BookLoreUser; +import org.booklore.model.dto.response.AttachBookFileResponse; import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.LibraryPathEntity; @@ -45,7 +46,7 @@ public class BookFileAttachmentService { private final EntityManager entityManager; @Transactional - public Book attachBookFiles(Long targetBookId, List sourceBookIds, boolean moveFiles) { + public AttachBookFileResponse attachBookFiles(Long targetBookId, List sourceBookIds, boolean moveFiles) { BookEntity targetBook = bookRepository.findByIdWithBookFiles(targetBookId) .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(targetBookId)); @@ -100,17 +101,25 @@ public class BookFileAttachmentService { } } - if (moveFiles) { - attachWithFileMove(targetBook, sourceBooks, targetPrimaryFile); - } else { - attachWithoutFileMove(targetBook, sourceBooks); + if (!moveFiles) { + boolean hasPathMismatch = sourceBooks.stream() + .anyMatch(source -> !source.getLibraryPath().getId().equals(targetBook.getLibraryPath().getId())); + if (hasPathMismatch) { + moveFiles = true; + } } - // Return updated target book - return getUpdatedBook(targetBookId); + List deletedSourceBookIds; + if (moveFiles) { + deletedSourceBookIds = attachWithFileMove(targetBook, sourceBooks, targetPrimaryFile); + } else { + deletedSourceBookIds = attachWithoutFileMove(targetBook, sourceBooks); + } + + return new AttachBookFileResponse(getUpdatedBook(targetBookId), deletedSourceBookIds); } - private void attachWithoutFileMove(BookEntity targetBook, List sourceBooks) { + private List attachWithoutFileMove(BookEntity targetBook, List sourceBooks) { List sourceBooksToDeleteIds = new ArrayList<>(); for (BookEntity sourceBook : sourceBooks) { @@ -140,10 +149,12 @@ public class BookFileAttachmentService { List booksToDelete = bookRepository.findAllById(sourceBooksToDeleteIds); bookRepository.deleteAll(booksToDelete); } + + return sourceBooksToDeleteIds; } - private void attachWithFileMove(BookEntity targetBook, List sourceBooks, - BookFileEntity targetPrimaryFile) { + private List attachWithFileMove(BookEntity targetBook, List sourceBooks, + BookFileEntity targetPrimaryFile) { String fileNamingPattern = fileMoveHelper.getFileNamingPattern(targetBook.getLibrary()); String patternResolvedPath = PathPatternResolver.resolvePattern(targetBook, targetPrimaryFile, fileNamingPattern); Path libraryRootPath = Paths.get(targetBook.getLibraryPath().getPath()); @@ -306,6 +317,10 @@ public class BookFileAttachmentService { } } + List deletedSourceBookIds = sourceBooksToDelete.stream() + .map(BookEntity::getId) + .toList(); + if (!sourceBooksToDelete.isEmpty()) { bookRepository.deleteAll(sourceBooksToDelete); } @@ -319,6 +334,8 @@ public class BookFileAttachmentService { for (Path sourceDir : sourceDirectoriesToCleanup) { bookService.deleteEmptyParentDirsUpToLibraryFolders(sourceDir, libraryRoots); } + + return deletedSourceBookIds; } finally { for (Path path : pathsToReregister) { if (Files.exists(path) && Files.isDirectory(path)) { diff --git a/booklore-api/src/test/java/org/booklore/service/book/BookFileAttachmentServiceTest.java b/booklore-api/src/test/java/org/booklore/service/book/BookFileAttachmentServiceTest.java index bd01ebb94..aab70dbff 100644 --- a/booklore-api/src/test/java/org/booklore/service/book/BookFileAttachmentServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/service/book/BookFileAttachmentServiceTest.java @@ -7,6 +7,7 @@ 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.dto.response.AttachBookFileResponse; import org.booklore.model.entity.*; import org.booklore.model.enums.BookFileType; import org.booklore.repository.BookRepository; @@ -68,7 +69,7 @@ class BookFileAttachmentServiceTest { .path(tempDir.toString()) .build(); - library.setLibraryPaths(List.of(libraryPath)); + library.setLibraryPaths(new ArrayList<>(List.of(libraryPath))); } private BookEntity createBook(Long id) { @@ -320,9 +321,11 @@ class BookFileAttachmentServiceTest { when(bookRepository.findAllById(List.of(2L))).thenReturn(List.of(source)); setupGetUpdatedBookMocks(1L, target); - Book result = service.attachBookFiles(1L, List.of(2L), false); + AttachBookFileResponse result = service.attachBookFiles(1L, List.of(2L), false); assertNotNull(result); + assertNotNull(result.updatedBook()); + assertEquals(List.of(2L), result.deletedSourceBookIds()); verify(entityManager).createQuery(contains("UPDATE BookFileEntity")); verify(entityManager).flush(); verify(entityManager).clear(); @@ -693,10 +696,11 @@ class BookFileAttachmentServiceTest { when(bookMapper.toBook(target)).thenReturn(dto); when(bookService.filterShelvesByUserId(any(), eq(1L))).thenReturn(Set.of()); - Book result = service.attachBookFiles(1L, List.of(2L), false); + AttachBookFileResponse result = service.attachBookFiles(1L, List.of(2L), false); assertNotNull(result); - assertEquals(1L, result.getId()); + assertEquals(1L, result.updatedBook().getId()); + assertEquals(List.of(2L), result.deletedSourceBookIds()); verify(readingProgressService).enrichBookWithProgress(eq(dto), any(), any()); verify(bookService).filterShelvesByUserId(any(), eq(1L)); } @@ -727,10 +731,11 @@ class BookFileAttachmentServiceTest { setupGetUpdatedBookMocks(1L, target); - service.attachBookFiles(1L, List.of(2L), false); + AttachBookFileResponse result = service.attachBookFiles(1L, List.of(2L), false); // Should not delete source since it has remaining non-book files verify(bookRepository, never()).deleteAll(anyList()); + assertTrue(result.deletedSourceBookIds().isEmpty()); } @Test @@ -791,6 +796,54 @@ class BookFileAttachmentServiceTest { assertTrue(Files.exists(tempDir.resolve("target.pdf"))); } + @Test + @DisplayName("Auto-upgrades to file move when source and target have different library paths") + void attachBookFiles_differentLibraryPaths_autoUpgradesToFileMove() throws IOException { + LibraryPathEntity otherLibraryPath = LibraryPathEntity.builder() + .id(2L) + .library(library) + .path(tempDir.resolve("other_root").toString()) + .build(); + library.setLibraryPaths(new ArrayList<>(List.of(libraryPath, otherLibraryPath))); + + Files.createDirectories(tempDir.resolve("other_root")); + + BookEntity target = createBook(1L); + createBookFile(10L, target, "target.epub", "target_dir", true, false); + + BookEntity source = BookEntity.builder() + .id(2L) + .library(library) + .libraryPath(otherLibraryPath) + .build(); + source.setBookFiles(new ArrayList<>()); + BookFileEntity sourceFile = BookFileEntity.builder() + .id(20L) + .book(source) + .fileName("source.pdf") + .fileSubPath("source_dir") + .isBookFormat(true) + .folderBased(false) + .bookType(BookFileType.PDF) + .build(); + Path sourceDir = tempDir.resolve("other_root/source_dir"); + Files.createDirectories(sourceDir); + Files.createFile(sourceDir.resolve("source.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}"); + + AttachBookFileResponse result = service.attachBookFiles(1L, List.of(2L), false); + + assertFalse(Files.exists(sourceDir.resolve("source.pdf")), + "Source file should be moved (auto-upgraded to file move)"); + assertTrue(Files.exists(tempDir.resolve("target_dir/target.pdf")), + "Source file should be at target directory"); + assertEquals(List.of(2L), result.deletedSourceBookIds()); + } + @Test @DisplayName("File without extension handled correctly") void attachWithFileMove_fileWithoutExtension() throws IOException { diff --git a/booklore-ui/src/app/features/book/service/book-file.service.ts b/booklore-ui/src/app/features/book/service/book-file.service.ts index 9ba3bc9cd..3daba36d0 100644 --- a/booklore-ui/src/app/features/book/service/book-file.service.ts +++ b/booklore-ui/src/app/features/book/service/book-file.service.ts @@ -212,17 +212,17 @@ export class BookFileService { return this.http.post(`${this.url}/duplicates`, request); } - attachBookFiles(targetBookId: number, sourceBookIds: number[], moveFiles: boolean): Observable { - return this.http.post(`${this.url}/${targetBookId}/attach-file`, { + attachBookFiles(targetBookId: number, sourceBookIds: number[], moveFiles: boolean): Observable<{updatedBook: Book, deletedSourceBookIds: number[]}> { + return this.http.post<{updatedBook: Book, deletedSourceBookIds: number[]}>(`${this.url}/${targetBookId}/attach-file`, { sourceBookIds, moveFiles }).pipe( - tap(updatedBook => { + tap(response => { const currentState = this.bookStateService.getCurrentBookState(); - const sourceIdSet = new Set(sourceBookIds); + const deletedIdSet = new Set(response.deletedSourceBookIds); let updatedBooks = (currentState.books || []).map(book => - book.id === targetBookId ? updatedBook : book - ).filter(book => !sourceIdSet.has(book.id)); + book.id === targetBookId ? response.updatedBook : book + ).filter(book => !deletedIdSet.has(book.id)); this.bookStateService.updateBookState({ ...currentState,