add detach book file feature and fix attach not respecting move preference (#3024)

This commit is contained in:
ACX
2026-02-26 08:16:12 -07:00
committed by GitHub
parent 073bc1045e
commit 3e374a197f
19 changed files with 751 additions and 40 deletions
@@ -2,7 +2,10 @@ package org.booklore.controller;
import org.booklore.config.security.annotation.CheckBookAccess;
import org.booklore.model.dto.BookFile;
import org.booklore.model.dto.request.DetachBookFileRequest;
import org.booklore.model.dto.response.DetachBookFileResponse;
import org.booklore.model.enums.BookFileType;
import org.booklore.service.book.BookFileDetachmentService;
import org.booklore.service.file.AdditionalFileService;
import org.booklore.service.upload.FileUploadService;
import lombok.AllArgsConstructor;
@@ -22,6 +25,7 @@ public class AdditionalFileController {
private final AdditionalFileService additionalFileService;
private final FileUploadService fileUploadService;
private final BookFileDetachmentService bookFileDetachmentService;
@GetMapping
@CheckBookAccess(bookIdParam = "bookId")
@@ -69,4 +73,14 @@ public class AdditionalFileController {
additionalFileService.deleteAdditionalFile(fileId);
return ResponseEntity.noContent().build();
}
@PostMapping("/{fileId}/detach")
@CheckBookAccess(bookIdParam = "bookId")
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<DetachBookFileResponse> detachFile(
@PathVariable Long bookId,
@PathVariable Long fileId,
@RequestBody DetachBookFileRequest request) {
return ResponseEntity.ok(bookFileDetachmentService.detachBookFile(bookId, fileId, request.copyMetadata()));
}
}
@@ -0,0 +1,3 @@
package org.booklore.model.dto.request;
public record DetachBookFileRequest(boolean copyMetadata) {}
@@ -0,0 +1,5 @@
package org.booklore.model.dto.response;
import org.booklore.model.dto.Book;
public record DetachBookFileResponse(Book sourceBook, Book newBook) {}
@@ -35,6 +35,7 @@ public enum AuditAction {
LOGIN_RATE_LIMITED,
REFRESH_RATE_LIMITED,
DUPLICATE_BOOKS_MERGED,
BOOK_FILE_DETACHED,
AUTHOR_METADATA_UPDATED,
AUTHOR_DELETED
}
@@ -50,13 +50,11 @@ public class BookFileAttachmentService {
BookEntity targetBook = bookRepository.findByIdWithBookFiles(targetBookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(targetBookId));
// Validate and deduplicate source book IDs
Set<Long> uniqueSourceBookIds = new LinkedHashSet<>(sourceBookIds); // Preserves order, removes duplicates
Set<Long> uniqueSourceBookIds = new LinkedHashSet<>(sourceBookIds);
if (uniqueSourceBookIds.contains(targetBookId)) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Cannot attach a book to itself");
}
// Load all source books upfront to avoid Hibernate auto-flush issues when loading inside loop
List<BookEntity> sourceBooks = new ArrayList<>();
for (Long sourceBookId : uniqueSourceBookIds) {
BookEntity sourceBook = bookRepository.findByIdWithBookFiles(sourceBookId)
@@ -64,17 +62,12 @@ public class BookFileAttachmentService {
sourceBooks.add(sourceBook);
}
// === VALIDATION PHASE - Do all validation BEFORE any file operations ===
// Validate target has a primary file
BookFileEntity targetPrimaryFile = targetBook.getBookFiles().stream()
.filter(BookFileEntity::isBookFormat)
.findFirst()
.orElseThrow(() -> ApiError.GENERIC_BAD_REQUEST.createException("Target book has no primary file"));
// Validate all source books upfront
for (BookEntity sourceBook : sourceBooks) {
// Validate same library
if (!targetBook.getLibrary().getId().equals(sourceBook.getLibrary().getId())) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " must be in the same library as target");
}
@@ -101,14 +94,6 @@ public class BookFileAttachmentService {
}
}
if (!moveFiles) {
boolean hasPathMismatch = sourceBooks.stream()
.anyMatch(source -> !source.getLibraryPath().getId().equals(targetBook.getLibraryPath().getId()));
if (hasPathMismatch) {
moveFiles = true;
}
}
List<Long> deletedSourceBookIds;
if (moveFiles) {
deletedSourceBookIds = attachWithFileMove(targetBook, sourceBooks, targetPrimaryFile);
@@ -121,22 +106,42 @@ public class BookFileAttachmentService {
private List<Long> attachWithoutFileMove(BookEntity targetBook, List<BookEntity> sourceBooks) {
List<Long> sourceBooksToDeleteIds = new ArrayList<>();
Path targetLibraryRoot = Paths.get(targetBook.getLibraryPath().getPath()).toAbsolutePath().normalize();
for (BookEntity sourceBook : sourceBooks) {
List<Long> bookFileIds = sourceBook.getBookFiles().stream()
boolean sameLibraryPath = sourceBook.getLibraryPath().getId().equals(targetBook.getLibraryPath().getId());
List<BookFileEntity> bookFormatFiles = 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();
if (!bookFormatFiles.isEmpty()) {
if (sameLibraryPath) {
List<Long> bookFileIds = bookFormatFiles.stream()
.map(BookFileEntity::getId)
.toList();
entityManager.createQuery(
"UPDATE BookFileEntity bf SET bf.book.id = :targetId WHERE bf.id IN :fileIds")
.setParameter("targetId", targetBook.getId())
.setParameter("fileIds", bookFileIds)
.executeUpdate();
} else {
Path sourceLibraryRoot = Paths.get(sourceBook.getLibraryPath().getPath()).toAbsolutePath().normalize();
for (BookFileEntity file : bookFormatFiles) {
Path fileDir = sourceLibraryRoot.resolve(file.getFileSubPath()).normalize();
String newSubPath = fileDir.equals(targetLibraryRoot)
? ""
: targetLibraryRoot.relativize(fileDir).toString();
entityManager.createQuery(
"UPDATE BookFileEntity bf SET bf.book.id = :targetId, bf.fileSubPath = :subPath WHERE bf.id = :fileId")
.setParameter("targetId", targetBook.getId())
.setParameter("subPath", newSubPath)
.setParameter("fileId", file.getId())
.executeUpdate();
}
}
}
long remainingBookFiles = sourceBook.getBookFiles().size() - bookFileIds.size();
long remainingBookFiles = sourceBook.getBookFiles().size() - bookFormatFiles.size();
if (remainingBookFiles == 0) {
sourceBooksToDeleteIds.add(sourceBook.getId());
}
@@ -373,7 +378,6 @@ public class BookFileAttachmentService {
return originalFileName;
}
// Extract base name and extension
String baseName;
String extension;
int lastDotIndex = originalFileName.lastIndexOf('.');
@@ -385,7 +389,6 @@ public class BookFileAttachmentService {
extension = "";
}
// Try with incrementing suffix
int counter = 1;
String newFileName;
do {
@@ -0,0 +1,222 @@
package org.booklore.service.book;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.config.security.service.AuthenticationService;
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.DetachBookFileResponse;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.BookMetadataEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.model.entity.UserBookFileProgressEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.AuditAction;
import org.booklore.repository.BookRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.booklore.service.audit.AuditService;
import org.booklore.service.metadata.BookCoverService;
import org.booklore.service.progress.ReadingProgressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Slf4j
@RequiredArgsConstructor
@Service
public class BookFileDetachmentService {
private final BookRepository bookRepository;
private final UserBookProgressRepository userBookProgressRepository;
private final AuthenticationService authenticationService;
private final ReadingProgressService readingProgressService;
private final BookMapper bookMapper;
private final BookService bookService;
private final AuditService auditService;
private final BookCoverService bookCoverService;
@Transactional
public DetachBookFileResponse detachBookFile(Long bookId, Long fileId, boolean copyMetadata) {
BookEntity sourceBook = bookRepository.findByIdWithBookFiles(bookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
BookFileEntity targetFile = sourceBook.getBookFiles().stream()
.filter(f -> f.getId().equals(fileId))
.findFirst()
.orElseThrow(() -> ApiError.GENERIC_BAD_REQUEST.createException("File not found on this book"));
if (sourceBook.getBookFiles().size() <= 1) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Cannot detach the only file from a book");
}
if (targetFile.isBookFormat()) {
long bookFormatCount = sourceBook.getBookFiles().stream()
.filter(BookFileEntity::isBookFormat)
.count();
if (bookFormatCount == 1) {
boolean hasSupplementaryOnly = sourceBook.getBookFiles().stream()
.anyMatch(f -> !f.isBookFormat());
if (hasSupplementaryOnly) {
throw ApiError.GENERIC_BAD_REQUEST.createException(
"Cannot detach the only book format file. The book would be left with only supplementary files.");
}
}
}
Path fileDiskPath = targetFile.getFullFilePath();
LibraryPathEntity newLibraryPath = resolveLibraryPath(sourceBook, fileDiskPath);
String newFileSubPath = computeFileSubPath(newLibraryPath, fileDiskPath);
BookEntity newBook = BookEntity.builder()
.library(sourceBook.getLibrary())
.libraryPath(newLibraryPath)
.addedOn(Instant.now())
.build();
BookMetadataEntity newMetadata;
if (copyMetadata) {
newMetadata = copyMetadataFrom(sourceBook.getMetadata());
} else {
newMetadata = BookMetadataEntity.builder().build();
String title = deriveTitle(targetFile.getFileName());
newMetadata.setTitle(title);
}
newMetadata.setBook(newBook);
newBook.setMetadata(newMetadata);
sourceBook.getBookFiles().remove(targetFile);
targetFile.setFileSubPath(newFileSubPath);
targetFile.setBook(newBook);
newBook = bookRepository.saveAndFlush(newBook);
try {
bookCoverService.regenerateCover(newBook.getId());
} catch (Exception e) {
log.warn("Failed to generate cover for detached book {}: {}", newBook.getId(), e.getMessage());
}
auditService.log(AuditAction.BOOK_FILE_DETACHED, "Book", bookId,
"Detached file '" + targetFile.getFileName() + "' from book " + bookId + " to new book " + newBook.getId());
Book sourceBookDto = getUpdatedBook(sourceBook.getId());
Book newBookDto = getUpdatedBook(newBook.getId());
return new DetachBookFileResponse(sourceBookDto, newBookDto);
}
private BookMetadataEntity copyMetadataFrom(BookMetadataEntity source) {
if (source == null) {
return BookMetadataEntity.builder().build();
}
BookMetadataEntity copy = BookMetadataEntity.builder().build();
copy.setTitle(source.getTitle());
copy.setSubtitle(source.getSubtitle());
copy.setPublisher(source.getPublisher());
copy.setPublishedDate(source.getPublishedDate());
copy.setDescription(source.getDescription());
copy.setSeriesName(source.getSeriesName());
copy.setSeriesNumber(source.getSeriesNumber());
copy.setSeriesTotal(source.getSeriesTotal());
copy.setIsbn13(source.getIsbn13());
copy.setIsbn10(source.getIsbn10());
copy.setPageCount(source.getPageCount());
copy.setLanguage(source.getLanguage());
copy.setRating(source.getRating());
copy.setReviewCount(source.getReviewCount());
copy.setAmazonRating(source.getAmazonRating());
copy.setAmazonReviewCount(source.getAmazonReviewCount());
copy.setGoodreadsRating(source.getGoodreadsRating());
copy.setGoodreadsReviewCount(source.getGoodreadsReviewCount());
copy.setHardcoverRating(source.getHardcoverRating());
copy.setHardcoverReviewCount(source.getHardcoverReviewCount());
copy.setLubimyczytacRating(source.getLubimyczytacRating());
copy.setRanobedbRating(source.getRanobedbRating());
copy.setAudibleRating(source.getAudibleRating());
copy.setAudibleReviewCount(source.getAudibleReviewCount());
copy.setAsin(source.getAsin());
copy.setGoodreadsId(source.getGoodreadsId());
copy.setHardcoverId(source.getHardcoverId());
copy.setHardcoverBookId(source.getHardcoverBookId());
copy.setGoogleId(source.getGoogleId());
copy.setComicvineId(source.getComicvineId());
copy.setLubimyczytacId(source.getLubimyczytacId());
copy.setRanobedbId(source.getRanobedbId());
copy.setAudibleId(source.getAudibleId());
copy.setNarrator(source.getNarrator());
copy.setAbridged(source.getAbridged());
copy.setAgeRating(source.getAgeRating());
copy.setContentRating(source.getContentRating());
if (source.getAuthors() != null) {
copy.setAuthors(new HashSet<>(source.getAuthors()));
}
if (source.getCategories() != null) {
copy.setCategories(new HashSet<>(source.getCategories()));
}
if (source.getMoods() != null) {
copy.setMoods(new HashSet<>(source.getMoods()));
}
if (source.getTags() != null) {
copy.setTags(new HashSet<>(source.getTags()));
}
return copy;
}
private String deriveTitle(String fileName) {
if (fileName == null || fileName.isBlank()) {
return "Untitled";
}
int lastDot = fileName.lastIndexOf('.');
return lastDot > 0 ? fileName.substring(0, lastDot) : fileName;
}
private LibraryPathEntity resolveLibraryPath(BookEntity sourceBook, Path fileDiskPath) {
Path normalizedFilePath = fileDiskPath.toAbsolutePath().normalize();
return sourceBook.getLibrary().getLibraryPaths().stream()
.map(lp -> Map.entry(lp, Paths.get(lp.getPath()).toAbsolutePath().normalize()))
.filter(entry -> normalizedFilePath.startsWith(entry.getValue()))
.max(Comparator.comparingInt(entry -> entry.getValue().getNameCount()))
.map(Map.Entry::getKey)
.orElse(sourceBook.getLibraryPath());
}
private String computeFileSubPath(LibraryPathEntity libraryPath, Path fileDiskPath) {
Path libraryRoot = Paths.get(libraryPath.getPath()).toAbsolutePath().normalize();
Path fileDir = fileDiskPath.toAbsolutePath().normalize().getParent();
if (fileDir == null || fileDir.equals(libraryRoot)) {
return "";
}
return libraryRoot.relativize(fileDir).toString();
}
private Book getUpdatedBook(Long bookId) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookEntity refreshedBook = bookRepository.findByIdWithBookFiles(bookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookId)
.orElse(new UserBookProgressEntity());
UserBookFileProgressEntity fileProgress = readingProgressService
.fetchUserFileProgress(user.getId(), Set.of(bookId))
.get(bookId);
Book book = bookMapper.toBook(refreshedBook);
book.setShelves(bookService.filterShelvesByUserId(book.getShelves(), user.getId()));
readingProgressService.enrichBookWithProgress(book, userProgress, fileProgress);
return book;
}
}
@@ -797,8 +797,8 @@ class BookFileAttachmentServiceTest {
}
@Test
@DisplayName("Auto-upgrades to file move when source and target have different library paths")
void attachBookFiles_differentLibraryPaths_autoUpgradesToFileMove() throws IOException {
@DisplayName("Attach without move keeps file in place and recalculates fileSubPath for different library paths")
void attachBookFiles_differentLibraryPaths_noMoveRecalculatesSubPath() throws IOException {
LibraryPathEntity otherLibraryPath = LibraryPathEntity.builder()
.id(2L)
.library(library)
@@ -830,17 +830,20 @@ class BookFileAttachmentServiceTest {
Files.createDirectories(sourceDir);
Files.createFile(sourceDir.resolve("source.pdf"));
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.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");
assertTrue(Files.exists(sourceDir.resolve("source.pdf")),
"Source file should remain at original location");
verify(entityManager).createQuery(contains("bf.fileSubPath"));
assertEquals(List.of(2L), result.deletedSourceBookIds());
}
@@ -0,0 +1,288 @@
package org.booklore.service.book;
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.dto.response.DetachBookFileResponse;
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.audit.AuditService;
import org.booklore.service.metadata.BookCoverService;
import org.booklore.service.progress.ReadingProgressService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class BookFileDetachmentServiceTest {
@Mock private BookRepository bookRepository;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private AuthenticationService authenticationService;
@Mock private ReadingProgressService readingProgressService;
@Mock private BookMapper bookMapper;
@Mock private BookService bookService;
@Mock private AuditService auditService;
@Mock private BookCoverService bookCoverService;
@InjectMocks
private BookFileDetachmentService service;
private LibraryEntity library;
private LibraryPathEntity libraryPath;
@BeforeEach
void setUp() {
library = LibraryEntity.builder()
.id(1L)
.name("Test Library")
.build();
libraryPath = LibraryPathEntity.builder()
.id(1L)
.library(library)
.path("/tmp/test-library")
.build();
library.setLibraryPaths(new ArrayList<>(List.of(libraryPath)));
}
private BookEntity createBook(Long id) {
BookEntity book = BookEntity.builder()
.id(id)
.library(library)
.libraryPath(libraryPath)
.build();
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(book)
.title("Test Book " + id)
.build();
book.setMetadata(metadata);
return book;
}
private BookFileEntity createBookFile(Long id, BookEntity book, boolean isBookFormat, BookFileType type) {
BookFileEntity file = BookFileEntity.builder()
.id(id)
.book(book)
.fileName("file-" + id + "." + type.name().toLowerCase())
.fileSubPath("")
.isBookFormat(isBookFormat)
.bookType(type)
.build();
return file;
}
private void setupMocksForGetUpdatedBook() {
BookLoreUser user = new BookLoreUser();
user.setId(1L);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(userBookProgressRepository.findByUserIdAndBookId(anyLong(), anyLong()))
.thenReturn(Optional.of(new UserBookProgressEntity()));
when(readingProgressService.fetchUserFileProgress(anyLong(), anySet()))
.thenReturn(new HashMap<>());
when(bookMapper.toBook(any(BookEntity.class))).thenReturn(Book.builder().build());
}
@Test
void detachAlternativeFormat_withCopyMetadata() {
BookEntity book = createBook(1L);
BookFileEntity primaryFile = createBookFile(10L, book, true, BookFileType.EPUB);
BookFileEntity altFile = createBookFile(11L, book, true, BookFileType.PDF);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.saveAndFlush(any(BookEntity.class))).thenAnswer(inv -> {
BookEntity saved = inv.getArgument(0);
saved.setId(2L);
return saved;
});
setupMocksForGetUpdatedBook();
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(createBook(2L)));
DetachBookFileResponse response = service.detachBookFile(1L, 11L, true);
assertThat(response).isNotNull();
assertThat(book.getBookFiles()).hasSize(1);
assertThat(book.getBookFiles().getFirst().getId()).isEqualTo(10L);
verify(auditService).log(eq(org.booklore.model.enums.AuditAction.BOOK_FILE_DETACHED), anyString(), eq(1L), anyString());
verify(bookRepository).saveAndFlush(argThat(newBook -> {
assertThat(newBook.getBookFiles()).hasSize(1);
assertThat(newBook.getMetadata().getTitle()).isEqualTo("Test Book 1");
return true;
}));
}
@Test
void detachAlternativeFormat_withoutCopyMetadata() {
BookEntity book = createBook(1L);
createBookFile(10L, book, true, BookFileType.EPUB);
createBookFile(11L, book, true, BookFileType.PDF);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.saveAndFlush(any(BookEntity.class))).thenAnswer(inv -> {
BookEntity saved = inv.getArgument(0);
saved.setId(2L);
return saved;
});
setupMocksForGetUpdatedBook();
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(createBook(2L)));
service.detachBookFile(1L, 11L, false);
verify(bookRepository).saveAndFlush(argThat(newBook -> {
assertThat(newBook.getMetadata().getTitle()).isEqualTo("file-11");
return true;
}));
}
@Test
void detachSupplementaryFile() {
BookEntity book = createBook(1L);
createBookFile(10L, book, true, BookFileType.EPUB);
BookFileEntity suppFile = createBookFile(11L, book, false, BookFileType.PDF);
suppFile.setFileName("notes.txt");
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.saveAndFlush(any(BookEntity.class))).thenAnswer(inv -> {
BookEntity saved = inv.getArgument(0);
saved.setId(2L);
return saved;
});
setupMocksForGetUpdatedBook();
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(createBook(2L)));
service.detachBookFile(1L, 11L, false);
assertThat(book.getBookFiles()).hasSize(1);
verify(bookRepository).saveAndFlush(argThat(newBook -> {
assertThat(newBook.getBookFiles()).hasSize(1);
assertThat(newBook.getBookFiles().getFirst().getFileName()).isEqualTo("notes.txt");
return true;
}));
}
@Test
void detachPrimaryFile_alternativeGetsPromoted() {
BookEntity book = createBook(1L);
BookFileEntity primaryFile = createBookFile(10L, book, true, BookFileType.EPUB);
createBookFile(11L, book, true, BookFileType.PDF);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.saveAndFlush(any(BookEntity.class))).thenAnswer(inv -> {
BookEntity saved = inv.getArgument(0);
saved.setId(2L);
return saved;
});
setupMocksForGetUpdatedBook();
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(createBook(2L)));
service.detachBookFile(1L, 10L, false);
assertThat(book.getBookFiles()).hasSize(1);
assertThat(book.getBookFiles().getFirst().getId()).isEqualTo(11L);
assertThat(book.getBookFiles().getFirst().isBookFormat()).isTrue();
}
@Test
void rejectDetach_onlyOneFile() {
BookEntity book = createBook(1L);
BookFileEntity file = createBookFile(10L, book, true, BookFileType.EPUB);
assertThat(book.getBookFiles()).hasSize(1);
assertThat(file.isBookFormat()).isTrue();
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
assertThatThrownBy(() -> service.detachBookFile(1L, 10L, false))
.isInstanceOf(APIException.class)
.hasMessageContaining("Cannot detach the only file");
}
@Test
void rejectDetach_fileNotOnBook() {
BookEntity book = createBook(1L);
createBookFile(10L, book, true, BookFileType.EPUB);
createBookFile(11L, book, true, BookFileType.PDF);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
assertThatThrownBy(() -> service.detachBookFile(1L, 99L, false))
.isInstanceOf(APIException.class)
.hasMessageContaining("File not found on this book");
}
@Test
void rejectDetach_bookNotFound() {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.detachBookFile(1L, 10L, false))
.isInstanceOf(APIException.class)
.hasMessageContaining("Book not found");
}
@Test
void rejectDetach_onlyBookFormatWithSupplementary() {
BookEntity book = createBook(1L);
createBookFile(10L, book, true, BookFileType.EPUB);
createBookFile(11L, book, false, BookFileType.PDF);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
assertThatThrownBy(() -> service.detachBookFile(1L, 10L, false))
.isInstanceOf(APIException.class)
.hasMessageContaining("only book format file");
}
@Test
void detachFile_resolvesCorrectLibraryPath() {
LibraryPathEntity libraryPath2 = LibraryPathEntity.builder()
.id(2L)
.library(library)
.path("/tmp/test-library/folder-2")
.build();
library.getLibraryPaths().add(libraryPath2);
BookEntity book = createBook(1L);
BookFileEntity primaryFile = createBookFile(10L, book, true, BookFileType.EPUB);
BookFileEntity altFile = createBookFile(11L, book, true, BookFileType.PDF);
altFile.setFileSubPath("folder-2");
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.saveAndFlush(any(BookEntity.class))).thenAnswer(inv -> {
BookEntity saved = inv.getArgument(0);
saved.setId(2L);
return saved;
});
setupMocksForGetUpdatedBook();
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(createBook(2L)));
service.detachBookFile(1L, 11L, false);
verify(bookRepository).saveAndFlush(argThat(newBook -> {
assertThat(newBook.getLibraryPath().getId()).isEqualTo(2L);
assertThat(newBook.getBookFiles().getFirst().getFileSubPath()).isEmpty();
return true;
}));
}
}