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;
}));
}
}
@@ -51,7 +51,7 @@
[dropdown]="true"
[showClear]="true"
[placeholder]="t('searchPlaceholder')"
class="full-width"
fluid
[disabled]="isAttaching">
<ng-template let-book pTemplate="item">
<div class="book-suggestion">
@@ -9,7 +9,7 @@ import { filter, take } from 'rxjs/operators';
import { BookService } from '../../service/book.service';
import { BookFileService } from '../../service/book-file.service';
import { Book } from '../../model/book.model';
import { MessageService } from 'primeng/api';
import {MessageService, PrimeTemplate} from 'primeng/api';
import { TranslocoDirective, TranslocoPipe, TranslocoService } from '@jsverse/transloco';
import { AppSettingsService } from '../../../../shared/service/app-settings.service';
@@ -23,6 +23,7 @@ import { AppSettingsService } from '../../../../shared/service/app-settings.serv
Checkbox,
TranslocoDirective,
TranslocoPipe,
PrimeTemplate,
],
templateUrl: './book-file-attacher.component.html',
styleUrls: ['./book-file-attacher.component.scss']
@@ -441,3 +441,8 @@ export interface DuplicateGroup {
matchReason: string;
books: Book[];
}
export interface DetachBookFileResponse {
sourceBook: Book;
newBook: Book;
}
@@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core';
import {Observable, throwError} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {catchError, tap} from 'rxjs/operators';
import {AdditionalFile, AdditionalFileType, Book, DuplicateDetectionRequest, DuplicateGroup} from '../model/book.model';
import {AdditionalFile, AdditionalFileType, Book, DetachBookFileResponse, DuplicateDetectionRequest, DuplicateGroup} from '../model/book.model';
import {API_CONFIG} from '../../../core/config/api-config';
import {MessageService} from 'primeng/api';
import {FileDownloadService} from '../../../shared/service/file-download.service';
@@ -208,6 +208,37 @@ export class BookFileService {
this.fileDownloadService.downloadFile(downloadUrl, additionalFile?.fileName ?? 'file');
}
detachBookFile(bookId: number, fileId: number, copyMetadata: boolean): Observable<DetachBookFileResponse> {
return this.http.post<DetachBookFileResponse>(`${this.url}/${bookId}/files/${fileId}/detach`, { copyMetadata }).pipe(
tap(response => {
const currentState = this.bookStateService.getCurrentBookState();
let updatedBooks = (currentState.books || []).map(book =>
book.id === bookId ? response.sourceBook : book
);
updatedBooks = [...updatedBooks, response.newBook];
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
this.messageService.add({
severity: 'success',
summary: this.t.translate('metadata.viewer.toast.detachFileSuccessSummary'),
detail: this.t.translate('metadata.viewer.toast.detachFileSuccessDetail')
});
}),
catchError(error => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('metadata.viewer.toast.detachFileErrorSummary'),
detail: error?.error?.message || error?.message || this.t.translate('metadata.viewer.toast.detachFileErrorDetail')
});
return throwError(() => error);
})
);
}
findDuplicates(request: DuplicateDetectionRequest): Observable<DuplicateGroup[]> {
return this.http.post<DuplicateGroup[]>(`${this.url}/duplicates`, request);
}
@@ -194,6 +194,17 @@
tooltipPosition="top"
(onClick)="download(book)">
</p-button>
@if (canDetach(book)) {
<p-button
icon="pi pi-external-link"
size="small"
text
severity="warn"
[pTooltip]="t('detachTooltip')"
tooltipPosition="top"
(onClick)="detachFile(book, book.primaryFile!.id, book.primaryFile!.fileName || 'file')">
</p-button>
}
<p-button
icon="pi pi-trash"
size="small"
@@ -271,6 +282,17 @@
tooltipPosition="top"
(onClick)="downloadAdditionalFile(book, format.id)">
</p-button>
@if (canDetach(book)) {
<p-button
icon="pi pi-external-link"
size="small"
text
severity="warn"
[pTooltip]="t('detachTooltip')"
tooltipPosition="top"
(onClick)="detachFile(book, format.id, format.fileName || 'file')">
</p-button>
}
<p-button
icon="pi pi-trash"
size="small"
@@ -307,6 +329,17 @@
tooltipPosition="top"
(onClick)="downloadAdditionalFile(book, file.id)">
</p-button>
@if (canDetach(book)) {
<p-button
icon="pi pi-external-link"
size="small"
text
severity="warn"
[pTooltip]="t('detachTooltip')"
tooltipPosition="top"
(onClick)="detachFile(book, file.id, file.fileName || 'file')">
</p-button>
}
<p-button
icon="pi pi-trash"
size="small"
@@ -47,6 +47,12 @@ export interface DeleteSupplementaryFileEvent {
fileName: string;
}
export interface DetachBookFileEvent {
book: Book;
fileId: number;
fileName: string;
}
@Component({
selector: 'app-metadata-tabs',
standalone: true,
@@ -84,6 +90,7 @@ export class MetadataTabsComponent {
@Output() downloadAllFiles = new EventEmitter<DownloadAllFilesEvent>();
@Output() deleteBookFile = new EventEmitter<DeleteBookFileEvent>();
@Output() deleteSupplementaryFile = new EventEmitter<DeleteSupplementaryFileEvent>();
@Output() detachBookFile = new EventEmitter<DetachBookFileEvent>();
get defaultTabValue(): string {
return this.bookInSeries && this.bookInSeries.length > 1 ? 'series' : 'similar';
@@ -114,6 +121,17 @@ export class MetadataTabsComponent {
this.deleteSupplementaryFile.emit({ bookId, fileId, fileName });
}
detachFile(book: Book, fileId: number, fileName: string): void {
this.detachBookFile.emit({ book, fileId, fileName });
}
canDetach(book: Book): boolean {
const totalFiles = (book.primaryFile ? 1 : 0)
+ (book.alternativeFormats?.length ?? 0)
+ (book.supplementaryFiles?.length ?? 0);
return totalFiles > 1;
}
hasMultipleFiles(book: Book): boolean {
const primaryCount = book.primaryFile ? 1 : 0;
const altCount = book.alternativeFormats?.length ?? 0;
@@ -1012,8 +1012,42 @@
(downloadFile)="onDownloadFile($event)"
(downloadAllFiles)="onDownloadAllFiles($event)"
(deleteBookFile)="onDeleteBookFile($event)"
(deleteSupplementaryFile)="onDeleteSupplementaryFile($event)">
(deleteSupplementaryFile)="onDeleteSupplementaryFile($event)"
(detachBookFile)="onDetachBookFile($event)">
</app-metadata-tabs>
<p-dialog
[header]="t('confirm.detachFileHeader')"
[(visible)]="showDetachDialog"
[modal]="true"
[closable]="true"
[style]="{ width: '450px' }"
[breakpoints]="{ '575px': '95vw' }">
<div class="detach-dialog-content">
<p>{{ t('confirm.detachFileMessage', { fileName: detachFileName }) }}</p>
<div class="detach-dialog-option">
<p-checkbox
[(ngModel)]="detachCopyMetadata"
[binary]="true"
inputId="copyMetadata">
</p-checkbox>
<label for="copyMetadata">{{ t('confirm.detachFileCopyMetadata') }}</label>
</div>
</div>
<ng-template #footer>
<p-button
[label]="'common.cancel' | transloco"
severity="secondary"
(onClick)="showDetachDialog = false">
</p-button>
<p-button
[label]="t('confirm.detachFileBtn')"
severity="warn"
icon="pi pi-external-link"
(onClick)="confirmDetach()">
</p-button>
</ng-template>
</p-dialog>
</div>
} @else {
<div class="loading-state" *transloco="let t; prefix: 'metadata.viewer'">
@@ -1184,3 +1184,15 @@
font-size: 0.8rem;
font-variant-numeric: tabular-nums;
}
.detach-dialog-content {
display: flex;
flex-direction: column;
gap: 1rem;
.detach-dialog-option {
display: flex;
align-items: center;
gap: 0.5rem;
}
}
@@ -33,9 +33,11 @@ import {AGE_RATING_OPTIONS, CONTENT_RATING_LABELS, fileSizeRanges, matchScoreRan
import {BookNavigationService} from '../../../../book/service/book-navigation.service';
import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host.service';
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
import {DeleteBookFileEvent, DeleteSupplementaryFileEvent, DownloadAdditionalFileEvent, DownloadAllFilesEvent, DownloadEvent, MetadataTabsComponent, ReadEvent} from './metadata-tabs/metadata-tabs.component';
import {DeleteBookFileEvent, DeleteSupplementaryFileEvent, DetachBookFileEvent, DownloadAdditionalFileEvent, DownloadAllFilesEvent, DownloadEvent, MetadataTabsComponent, ReadEvent} from './metadata-tabs/metadata-tabs.component';
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
import {AuthorService} from '../../../../author-browser/service/author.service';
import {Dialog} from 'primeng/dialog';
import {Checkbox} from 'primeng/checkbox';
@Component({
@@ -43,7 +45,7 @@ import {AuthorService} from '../../../../author-browser/service/author.service';
standalone: true,
templateUrl: './metadata-viewer.component.html',
styleUrl: './metadata-viewer.component.scss',
imports: [Button, AsyncPipe, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, ProgressBar, Menu, DatePicker, ProgressSpinner, TieredMenu, Image, TagComponent, MetadataTabsComponent, TranslocoDirective, TranslocoPipe]
imports: [Button, AsyncPipe, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, ProgressBar, Menu, DatePicker, ProgressSpinner, TieredMenu, Image, TagComponent, MetadataTabsComponent, TranslocoDirective, TranslocoPipe, Dialog, Checkbox]
})
export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChecked {
@Input() book$!: Observable<Book | null>;
@@ -85,6 +87,11 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
selectedReadStatus: ReadStatus = ReadStatus.UNREAD;
isEditingDateFinished = false;
editDateFinished: Date | null = null;
showDetachDialog = false;
detachCopyMetadata = true;
private detachBookId = 0;
private detachFileId = 0;
detachFileName = '';
readStatusOptions: { value: ReadStatus, labelKey: string }[] = [
{value: ReadStatus.UNREAD, labelKey: 'metadata.viewer.readStatusUnread'},
@@ -537,6 +544,19 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
this.deleteAdditionalFile(event.bookId, event.fileId, event.fileName);
}
onDetachBookFile(event: DetachBookFileEvent): void {
this.detachBookId = event.book.id;
this.detachFileId = event.fileId;
this.detachFileName = event.fileName;
this.detachCopyMetadata = true;
this.showDetachDialog = true;
}
confirmDetach(): void {
this.showDetachDialog = false;
this.bookFileService.detachBookFile(this.detachBookId, this.detachFileId, this.detachCopyMetadata).subscribe();
}
deleteAdditionalFile(bookId: number, fileId: number, fileName: string) {
this.confirmationService.confirm({
message: this.t.translate('metadata.viewer.confirm.deleteSupplementaryMessage', { fileName }),
+9
View File
@@ -220,6 +220,7 @@
"playTooltip": "Play",
"downloadTooltip": "Download",
"deleteTooltip": "Delete",
"detachTooltip": "Detach",
"downloadAllTooltip": "Download all files as a ZIP archive",
"physicalBookHint": "You can upload a digital copy or add metadata manually."
},
@@ -355,6 +356,10 @@
"deleteFormatSuccessDetail": "Book format \"{{ fileName }}\" deleted successfully",
"deleteFormatErrorSummary": "Error",
"deleteFormatErrorDetail": "Failed to delete book format: {{ error }}",
"detachFileSuccessSummary": "File Detached",
"detachFileSuccessDetail": "The file has been detached and a new book has been created.",
"detachFileErrorSummary": "Detach Failed",
"detachFileErrorDetail": "Failed to detach file.",
"dateUpdatedSummary": "Date Updated",
"dateUpdatedDetail": "Book finish date has been updated.",
"dateUpdateFailedSummary": "Update Failed",
@@ -372,6 +377,10 @@
"deleteAltFormatMessage": "Are you sure you want to delete \"{{ fileName }}\"?\n\nThis file will be permanently removed from your filesystem.",
"deleteAltFormatHeader": "Delete Book Format",
"deleteFileBtn": "Delete File",
"detachFileHeader": "Detach File",
"detachFileMessage": "This will detach \"{{ fileName }}\" from this book and create a new standalone book for it. The file will not be deleted.",
"detachFileCopyMetadata": "Copy metadata to new book",
"detachFileBtn": "Detach",
"deleteBookMessage": "Are you sure you want to delete \"{{ title }}\"?\n\nThis will permanently remove the book record from your library.\n\nThis action cannot be undone.",
"deleteBookAllFilesMessage": "Are you sure you want to delete \"{{ title }}\"?\n\nThis will permanently remove the book record AND all associated files from your filesystem.\n\nThis action cannot be undone.",
"deleteEverythingBtn": "Delete Everything"
+9
View File
@@ -220,6 +220,7 @@
"playTooltip": "Reproducir",
"downloadTooltip": "Descargar",
"deleteTooltip": "Eliminar",
"detachTooltip": "Separar",
"downloadAllTooltip": "Descargar todos los archivos como archivo ZIP",
"physicalBookHint": "Puede subir una copia digital o agregar metadatos manualmente."
},
@@ -355,6 +356,10 @@
"deleteFormatSuccessDetail": "Formato de libro \"{{ fileName }}\" eliminado correctamente",
"deleteFormatErrorSummary": "Error",
"deleteFormatErrorDetail": "Error al eliminar formato de libro: {{ error }}",
"detachFileSuccessSummary": "Archivo separado",
"detachFileSuccessDetail": "El archivo se ha separado y se ha creado un nuevo libro.",
"detachFileErrorSummary": "Error al separar",
"detachFileErrorDetail": "No se pudo separar el archivo.",
"dateUpdatedSummary": "Fecha actualizada",
"dateUpdatedDetail": "La fecha de finalización del libro se ha actualizado.",
"dateUpdateFailedSummary": "Actualización fallida",
@@ -372,6 +377,10 @@
"deleteAltFormatMessage": "¿Estás seguro de que deseas eliminar \"{{ fileName }}\"?\n\nEste archivo será eliminado permanentemente de tu sistema de archivos.",
"deleteAltFormatHeader": "Eliminar formato del libro",
"deleteFileBtn": "Eliminar archivo",
"detachFileHeader": "Separar archivo",
"detachFileMessage": "Esto separará \"{{ fileName }}\" de este libro y creará un nuevo libro independiente. El archivo no será eliminado.",
"detachFileCopyMetadata": "Copiar metadatos al nuevo libro",
"detachFileBtn": "Separar",
"deleteBookMessage": "¿Estás seguro de que deseas eliminar \"{{ title }}\"?\n\nEsto eliminará permanentemente el registro del libro de tu biblioteca.\n\nEsta acción no se puede deshacer.",
"deleteBookAllFilesMessage": "¿Estás seguro de que deseas eliminar \"{{ title }}\"?\n\nEsto eliminará permanentemente el registro del libro Y todos los archivos asociados de tu sistema de archivos.\n\nEsta acción no se puede deshacer.",
"deleteEverythingBtn": "Eliminar todo"