fix attach file without move when source/target have different library paths (#2999)
This commit is contained in:
@@ -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<Book> attachBookFiles(
|
||||
public ResponseEntity<AttachBookFileResponse> 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()));
|
||||
|
||||
@@ -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<Long> deletedSourceBookIds) {}
|
||||
+27
-10
@@ -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<Long> sourceBookIds, boolean moveFiles) {
|
||||
public AttachBookFileResponse attachBookFiles(Long targetBookId, List<Long> 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<Long> 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<BookEntity> sourceBooks) {
|
||||
private List<Long> attachWithoutFileMove(BookEntity targetBook, List<BookEntity> sourceBooks) {
|
||||
List<Long> sourceBooksToDeleteIds = new ArrayList<>();
|
||||
|
||||
for (BookEntity sourceBook : sourceBooks) {
|
||||
@@ -140,10 +149,12 @@ public class BookFileAttachmentService {
|
||||
List<BookEntity> booksToDelete = bookRepository.findAllById(sourceBooksToDeleteIds);
|
||||
bookRepository.deleteAll(booksToDelete);
|
||||
}
|
||||
|
||||
return sourceBooksToDeleteIds;
|
||||
}
|
||||
|
||||
private void attachWithFileMove(BookEntity targetBook, List<BookEntity> sourceBooks,
|
||||
BookFileEntity targetPrimaryFile) {
|
||||
private List<Long> 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());
|
||||
@@ -306,6 +317,10 @@ public class BookFileAttachmentService {
|
||||
}
|
||||
}
|
||||
|
||||
List<Long> 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)) {
|
||||
|
||||
+58
-5
@@ -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 {
|
||||
|
||||
@@ -212,17 +212,17 @@ export class BookFileService {
|
||||
return this.http.post<DuplicateGroup[]>(`${this.url}/duplicates`, request);
|
||||
}
|
||||
|
||||
attachBookFiles(targetBookId: number, sourceBookIds: number[], moveFiles: boolean): Observable<Book> {
|
||||
return this.http.post<Book>(`${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,
|
||||
|
||||
Reference in New Issue
Block a user