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.ReadProgressRequest;
|
||||||
import org.booklore.model.dto.request.ReadStatusUpdateRequest;
|
import org.booklore.model.dto.request.ReadStatusUpdateRequest;
|
||||||
import org.booklore.model.dto.request.ShelvesAssignmentRequest;
|
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.BookDeletionResponse;
|
||||||
import org.booklore.model.dto.response.BookStatusUpdateResponse;
|
import org.booklore.model.dto.response.BookStatusUpdateResponse;
|
||||||
import org.booklore.model.dto.response.DuplicateGroup;
|
import org.booklore.model.dto.response.DuplicateGroup;
|
||||||
@@ -285,7 +286,7 @@ public class BookController {
|
|||||||
})
|
})
|
||||||
@PostMapping("/{targetBookId}/attach-file")
|
@PostMapping("/{targetBookId}/attach-file")
|
||||||
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
|
@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 = "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) {
|
@Parameter(description = "Request containing source book IDs and delete option") @RequestBody @Valid AttachBookFileRequest request) {
|
||||||
return ResponseEntity.ok(bookFileAttachmentService.attachBookFiles(targetBookId, request.getSourceBookIds(), request.isMoveFiles()));
|
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.mapper.BookMapper;
|
||||||
import org.booklore.model.dto.Book;
|
import org.booklore.model.dto.Book;
|
||||||
import org.booklore.model.dto.BookLoreUser;
|
import org.booklore.model.dto.BookLoreUser;
|
||||||
|
import org.booklore.model.dto.response.AttachBookFileResponse;
|
||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
import org.booklore.model.entity.BookFileEntity;
|
import org.booklore.model.entity.BookFileEntity;
|
||||||
import org.booklore.model.entity.LibraryPathEntity;
|
import org.booklore.model.entity.LibraryPathEntity;
|
||||||
@@ -45,7 +46,7 @@ public class BookFileAttachmentService {
|
|||||||
private final EntityManager entityManager;
|
private final EntityManager entityManager;
|
||||||
|
|
||||||
@Transactional
|
@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)
|
BookEntity targetBook = bookRepository.findByIdWithBookFiles(targetBookId)
|
||||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(targetBookId));
|
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(targetBookId));
|
||||||
|
|
||||||
@@ -100,17 +101,25 @@ public class BookFileAttachmentService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (moveFiles) {
|
if (!moveFiles) {
|
||||||
attachWithFileMove(targetBook, sourceBooks, targetPrimaryFile);
|
boolean hasPathMismatch = sourceBooks.stream()
|
||||||
} else {
|
.anyMatch(source -> !source.getLibraryPath().getId().equals(targetBook.getLibraryPath().getId()));
|
||||||
attachWithoutFileMove(targetBook, sourceBooks);
|
if (hasPathMismatch) {
|
||||||
|
moveFiles = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return updated target book
|
List<Long> deletedSourceBookIds;
|
||||||
return getUpdatedBook(targetBookId);
|
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<>();
|
List<Long> sourceBooksToDeleteIds = new ArrayList<>();
|
||||||
|
|
||||||
for (BookEntity sourceBook : sourceBooks) {
|
for (BookEntity sourceBook : sourceBooks) {
|
||||||
@@ -140,10 +149,12 @@ public class BookFileAttachmentService {
|
|||||||
List<BookEntity> booksToDelete = bookRepository.findAllById(sourceBooksToDeleteIds);
|
List<BookEntity> booksToDelete = bookRepository.findAllById(sourceBooksToDeleteIds);
|
||||||
bookRepository.deleteAll(booksToDelete);
|
bookRepository.deleteAll(booksToDelete);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return sourceBooksToDeleteIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void attachWithFileMove(BookEntity targetBook, List<BookEntity> sourceBooks,
|
private List<Long> attachWithFileMove(BookEntity targetBook, List<BookEntity> sourceBooks,
|
||||||
BookFileEntity targetPrimaryFile) {
|
BookFileEntity targetPrimaryFile) {
|
||||||
String fileNamingPattern = fileMoveHelper.getFileNamingPattern(targetBook.getLibrary());
|
String fileNamingPattern = fileMoveHelper.getFileNamingPattern(targetBook.getLibrary());
|
||||||
String patternResolvedPath = PathPatternResolver.resolvePattern(targetBook, targetPrimaryFile, fileNamingPattern);
|
String patternResolvedPath = PathPatternResolver.resolvePattern(targetBook, targetPrimaryFile, fileNamingPattern);
|
||||||
Path libraryRootPath = Paths.get(targetBook.getLibraryPath().getPath());
|
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()) {
|
if (!sourceBooksToDelete.isEmpty()) {
|
||||||
bookRepository.deleteAll(sourceBooksToDelete);
|
bookRepository.deleteAll(sourceBooksToDelete);
|
||||||
}
|
}
|
||||||
@@ -319,6 +334,8 @@ public class BookFileAttachmentService {
|
|||||||
for (Path sourceDir : sourceDirectoriesToCleanup) {
|
for (Path sourceDir : sourceDirectoriesToCleanup) {
|
||||||
bookService.deleteEmptyParentDirsUpToLibraryFolders(sourceDir, libraryRoots);
|
bookService.deleteEmptyParentDirsUpToLibraryFolders(sourceDir, libraryRoots);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return deletedSourceBookIds;
|
||||||
} finally {
|
} finally {
|
||||||
for (Path path : pathsToReregister) {
|
for (Path path : pathsToReregister) {
|
||||||
if (Files.exists(path) && Files.isDirectory(path)) {
|
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.mapper.BookMapper;
|
||||||
import org.booklore.model.dto.Book;
|
import org.booklore.model.dto.Book;
|
||||||
import org.booklore.model.dto.BookLoreUser;
|
import org.booklore.model.dto.BookLoreUser;
|
||||||
|
import org.booklore.model.dto.response.AttachBookFileResponse;
|
||||||
import org.booklore.model.entity.*;
|
import org.booklore.model.entity.*;
|
||||||
import org.booklore.model.enums.BookFileType;
|
import org.booklore.model.enums.BookFileType;
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
@@ -68,7 +69,7 @@ class BookFileAttachmentServiceTest {
|
|||||||
.path(tempDir.toString())
|
.path(tempDir.toString())
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
library.setLibraryPaths(List.of(libraryPath));
|
library.setLibraryPaths(new ArrayList<>(List.of(libraryPath)));
|
||||||
}
|
}
|
||||||
|
|
||||||
private BookEntity createBook(Long id) {
|
private BookEntity createBook(Long id) {
|
||||||
@@ -320,9 +321,11 @@ class BookFileAttachmentServiceTest {
|
|||||||
when(bookRepository.findAllById(List.of(2L))).thenReturn(List.of(source));
|
when(bookRepository.findAllById(List.of(2L))).thenReturn(List.of(source));
|
||||||
setupGetUpdatedBookMocks(1L, target);
|
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);
|
||||||
|
assertNotNull(result.updatedBook());
|
||||||
|
assertEquals(List.of(2L), result.deletedSourceBookIds());
|
||||||
verify(entityManager).createQuery(contains("UPDATE BookFileEntity"));
|
verify(entityManager).createQuery(contains("UPDATE BookFileEntity"));
|
||||||
verify(entityManager).flush();
|
verify(entityManager).flush();
|
||||||
verify(entityManager).clear();
|
verify(entityManager).clear();
|
||||||
@@ -693,10 +696,11 @@ class BookFileAttachmentServiceTest {
|
|||||||
when(bookMapper.toBook(target)).thenReturn(dto);
|
when(bookMapper.toBook(target)).thenReturn(dto);
|
||||||
when(bookService.filterShelvesByUserId(any(), eq(1L))).thenReturn(Set.of());
|
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);
|
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(readingProgressService).enrichBookWithProgress(eq(dto), any(), any());
|
||||||
verify(bookService).filterShelvesByUserId(any(), eq(1L));
|
verify(bookService).filterShelvesByUserId(any(), eq(1L));
|
||||||
}
|
}
|
||||||
@@ -727,10 +731,11 @@ class BookFileAttachmentServiceTest {
|
|||||||
|
|
||||||
setupGetUpdatedBookMocks(1L, target);
|
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
|
// Should not delete source since it has remaining non-book files
|
||||||
verify(bookRepository, never()).deleteAll(anyList());
|
verify(bookRepository, never()).deleteAll(anyList());
|
||||||
|
assertTrue(result.deletedSourceBookIds().isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -791,6 +796,54 @@ class BookFileAttachmentServiceTest {
|
|||||||
assertTrue(Files.exists(tempDir.resolve("target.pdf")));
|
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
|
@Test
|
||||||
@DisplayName("File without extension handled correctly")
|
@DisplayName("File without extension handled correctly")
|
||||||
void attachWithFileMove_fileWithoutExtension() throws IOException {
|
void attachWithFileMove_fileWithoutExtension() throws IOException {
|
||||||
|
|||||||
@@ -212,17 +212,17 @@ export class BookFileService {
|
|||||||
return this.http.post<DuplicateGroup[]>(`${this.url}/duplicates`, request);
|
return this.http.post<DuplicateGroup[]>(`${this.url}/duplicates`, request);
|
||||||
}
|
}
|
||||||
|
|
||||||
attachBookFiles(targetBookId: number, sourceBookIds: number[], moveFiles: boolean): Observable<Book> {
|
attachBookFiles(targetBookId: number, sourceBookIds: number[], moveFiles: boolean): Observable<{updatedBook: Book, deletedSourceBookIds: number[]}> {
|
||||||
return this.http.post<Book>(`${this.url}/${targetBookId}/attach-file`, {
|
return this.http.post<{updatedBook: Book, deletedSourceBookIds: number[]}>(`${this.url}/${targetBookId}/attach-file`, {
|
||||||
sourceBookIds,
|
sourceBookIds,
|
||||||
moveFiles
|
moveFiles
|
||||||
}).pipe(
|
}).pipe(
|
||||||
tap(updatedBook => {
|
tap(response => {
|
||||||
const currentState = this.bookStateService.getCurrentBookState();
|
const currentState = this.bookStateService.getCurrentBookState();
|
||||||
const sourceIdSet = new Set(sourceBookIds);
|
const deletedIdSet = new Set(response.deletedSourceBookIds);
|
||||||
let updatedBooks = (currentState.books || []).map(book =>
|
let updatedBooks = (currentState.books || []).map(book =>
|
||||||
book.id === targetBookId ? updatedBook : book
|
book.id === targetBookId ? response.updatedBook : book
|
||||||
).filter(book => !sourceIdSet.has(book.id));
|
).filter(book => !deletedIdSet.has(book.id));
|
||||||
|
|
||||||
this.bookStateService.updateBookState({
|
this.bookStateService.updateBookState({
|
||||||
...currentState,
|
...currentState,
|
||||||
|
|||||||
Reference in New Issue
Block a user