From bf1957847c87c8af59801f294c4388fa253afd0c Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Mon, 9 Mar 2026 14:42:44 -0600 Subject: [PATCH] Scanner organization modes (#3203) * Add BOOK_PER_FILE and BOOK_PER_FOLDER organization modes for library scanning * Filter temp/partial files, support .ignore directories, and skip zero-byte files during scanning * Replace event-based monitoring with WatchService, add pending deletion pool and move detection * Fix folder-based audiobook grouping, improve series detection, and add tests * Add unit tests for BookFileTransactionalHandler, BookFilePersistenceService, and LibraryFileEventProcessor --- .gitignore | 1 + .../org/booklore/config/MonitoringConfig.java | 25 - .../dto/request/CreateLibraryRequest.java | 2 + .../model/enums/LibraryOrganizationMode.java | 2 + .../booklore/repository/BookRepository.java | 18 +- .../service/library/BookGroupingService.java | 179 ++++- .../service/library/FileAsBookProcessor.java | 19 +- .../service/library/LibraryFileHelper.java | 113 ++- .../service/library/LibraryService.java | 18 +- .../monitoring/DirectoryCreateEvent.java | 16 - .../service/monitoring/FileChangeEvent.java | 22 - .../monitoring/LibraryWatchService.java | 288 +++++++ .../MonitoringRegistrationService.java | 37 +- .../service/monitoring/MonitoringService.java | 301 ------- .../service/monitoring/MonitoringTask.java | 56 -- .../monitoring/WatchKeyInvalidatedEvent.java | 16 - .../watcher/BookFilePersistenceService.java | 54 +- .../watcher/BookFileTransactionalHandler.java | 160 +++- .../watcher/LibraryFileEventProcessor.java | 424 +++++++--- .../service/watcher/PendingDeletionPool.java | 305 ++++++++ .../java/org/booklore/util/FileUtils.java | 41 +- ...0__Add_book_per_file_organization_mode.sql | 1 + .../library/BookGroupingServiceTest.java | 733 ++++++++++++++++++ .../library/FileAsBookProcessorTest.java | 6 + .../library/LibraryFileHelperTest.java | 352 ++++++++- .../library/LibraryServiceIconTest.java | 4 +- .../monitoring/LibraryWatchServiceTest.java | 153 ++++ .../MonitoringRegistrationServiceTest.java | 76 +- .../monitoring/MonitoringServiceTest.java | 286 ------- .../BookFilePersistenceServiceTest.java | 432 +++++++++++ .../BookFileTransactionalHandlerTest.java | 623 +++++++++++++++ .../LibraryFileEventProcessorTest.java | 405 ++++++++++ .../watcher/PendingDeletionPoolTest.java | 226 ++++++ .../java/org/booklore/util/FileUtilsTest.java | 57 +- .../app/features/book/model/library.model.ts | 3 + .../library-creator.component.html | 19 + .../library-creator.component.ts | 25 +- booklore-ui/src/i18n/en/library-creator.json | 5 + booklore-ui/src/i18n/es/library-creator.json | 5 + 39 files changed, 4533 insertions(+), 975 deletions(-) delete mode 100644 booklore-api/src/main/java/org/booklore/config/MonitoringConfig.java delete mode 100644 booklore-api/src/main/java/org/booklore/service/monitoring/DirectoryCreateEvent.java delete mode 100644 booklore-api/src/main/java/org/booklore/service/monitoring/FileChangeEvent.java create mode 100644 booklore-api/src/main/java/org/booklore/service/monitoring/LibraryWatchService.java delete mode 100644 booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringService.java delete mode 100644 booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringTask.java delete mode 100644 booklore-api/src/main/java/org/booklore/service/monitoring/WatchKeyInvalidatedEvent.java create mode 100644 booklore-api/src/main/java/org/booklore/service/watcher/PendingDeletionPool.java create mode 100644 booklore-api/src/main/resources/db/migration/V130__Add_book_per_file_organization_mode.sql create mode 100644 booklore-api/src/test/java/org/booklore/service/library/BookGroupingServiceTest.java create mode 100644 booklore-api/src/test/java/org/booklore/service/monitoring/LibraryWatchServiceTest.java delete mode 100644 booklore-api/src/test/java/org/booklore/service/monitoring/MonitoringServiceTest.java create mode 100644 booklore-api/src/test/java/org/booklore/service/watcher/BookFilePersistenceServiceTest.java create mode 100644 booklore-api/src/test/java/org/booklore/service/watcher/BookFileTransactionalHandlerTest.java create mode 100644 booklore-api/src/test/java/org/booklore/service/watcher/LibraryFileEventProcessorTest.java create mode 100644 booklore-api/src/test/java/org/booklore/service/watcher/PendingDeletionPoolTest.java diff --git a/.gitignore b/.gitignore index 389669cce..829b73fc9 100644 --- a/.gitignore +++ b/.gitignore @@ -45,4 +45,5 @@ local-scripts/ ### Dev config, books, and data ### booklore-ui/test-results/ booklore-api/src/main/resources/application-local.yaml +booklore-api/docs /shared/ diff --git a/booklore-api/src/main/java/org/booklore/config/MonitoringConfig.java b/booklore-api/src/main/java/org/booklore/config/MonitoringConfig.java deleted file mode 100644 index 5b9d34c88..000000000 --- a/booklore-api/src/main/java/org/booklore/config/MonitoringConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.booklore.config; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.WatchService; - -@Slf4j -@Configuration -public class MonitoringConfig { - - @Bean - public WatchService watchService() { - WatchService watchService = null; - try { - watchService = FileSystems.getDefault().newWatchService(); - } catch (IOException e) { - log.error("Error creating WatchService:", e); - } - return watchService; - } -} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/request/CreateLibraryRequest.java b/booklore-api/src/main/java/org/booklore/model/dto/request/CreateLibraryRequest.java index b4c34b4e3..b5043c3d2 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/request/CreateLibraryRequest.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/request/CreateLibraryRequest.java @@ -3,6 +3,7 @@ package org.booklore.model.dto.request; import org.booklore.model.dto.LibraryPath; import org.booklore.model.enums.BookFileType; import org.booklore.model.enums.IconType; +import org.booklore.model.enums.LibraryOrganizationMode; import org.booklore.model.enums.MetadataSource; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import jakarta.validation.constraints.NotBlank; @@ -33,4 +34,5 @@ public class CreateLibraryRequest { private List formatPriority; private List allowedFormats; private MetadataSource metadataSource; + private LibraryOrganizationMode organizationMode; } diff --git a/booklore-api/src/main/java/org/booklore/model/enums/LibraryOrganizationMode.java b/booklore-api/src/main/java/org/booklore/model/enums/LibraryOrganizationMode.java index c3ed689e2..ca9430f47 100644 --- a/booklore-api/src/main/java/org/booklore/model/enums/LibraryOrganizationMode.java +++ b/booklore-api/src/main/java/org/booklore/model/enums/LibraryOrganizationMode.java @@ -1,6 +1,8 @@ package org.booklore.model.enums; public enum LibraryOrganizationMode { + BOOK_PER_FILE, BOOK_PER_FOLDER, + @Deprecated AUTO_DETECT } diff --git a/booklore-api/src/main/java/org/booklore/repository/BookRepository.java b/booklore-api/src/main/java/org/booklore/repository/BookRepository.java index 08ffb61be..7ba0c1ea4 100644 --- a/booklore-api/src/main/java/org/booklore/repository/BookRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/BookRepository.java @@ -27,12 +27,15 @@ public interface BookRepository extends JpaRepository, JpaSpec @Query("SELECT b FROM BookEntity b JOIN b.bookFiles bf WHERE bf.currentHash = :currentHash AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)") Optional findByCurrentHash(@Param("currentHash") String currentHash); + @Query("SELECT b FROM BookEntity b JOIN FETCH b.bookFiles bf WHERE bf.currentHash = :currentHash AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false OR b.deletedAt > :cutoff)") + Optional findByCurrentHashIncludingRecentlyDeleted(@Param("currentHash") String currentHash, @Param("cutoff") Instant cutoff); + Optional findByBookCoverHash(String bookCoverHash); @Query("SELECT b.id FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)") Set findBookIdsByLibraryId(@Param("libraryId") long libraryId); - @Query("SELECT DISTINCT b FROM BookEntity b JOIN b.bookFiles bf WHERE b.libraryPath.id = :libraryPathId AND bf.fileSubPath LIKE CONCAT(:fileSubPathPrefix, '%') AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)") + @Query("SELECT DISTINCT b FROM BookEntity b JOIN b.bookFiles bf WHERE b.libraryPath.id = :libraryPathId AND (bf.fileSubPath = :fileSubPathPrefix OR bf.fileSubPath LIKE CONCAT(:fileSubPathPrefix, '/%')) AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)") List findAllByLibraryPathIdAndFileSubPathStartingWith(@Param("libraryPathId") Long libraryPathId, @Param("fileSubPathPrefix") String fileSubPathPrefix); @Query("SELECT DISTINCT b FROM BookEntity b JOIN b.bookFiles bf WHERE b.libraryPath.id = :libraryPathId AND bf.fileSubPath = :fileSubPath AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)") @@ -129,6 +132,19 @@ public interface BookRepository extends JpaRepository, JpaSpec @Query("SELECT COUNT(b) FROM BookEntity b WHERE b.deleted = TRUE") long countAllSoftDeleted(); + @Query(""" + SELECT DISTINCT b FROM BookEntity b + JOIN FETCH b.bookFiles bf + WHERE b.libraryPath.id = :libraryPathId + AND (bf.fileSubPath = :folderPath + OR bf.fileSubPath LIKE CONCAT(:folderPath, '/%') + OR (bf.folderBased = true AND CONCAT(bf.fileSubPath, '/', bf.fileName) = :folderPath)) + AND bf.isBookFormat = true + AND (b.deleted IS NULL OR b.deleted = false) + """) + List findBooksWithFilesUnderPath(@Param("libraryPathId") Long libraryPathId, + @Param("folderPath") String folderPath); + @Query(value = """ SELECT b.* FROM book b diff --git a/booklore-api/src/main/java/org/booklore/service/library/BookGroupingService.java b/booklore-api/src/main/java/org/booklore/service/library/BookGroupingService.java index 85ba83ccd..5a1ac266f 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/BookGroupingService.java +++ b/booklore-api/src/main/java/org/booklore/service/library/BookGroupingService.java @@ -4,6 +4,7 @@ import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.LibraryEntity; +import org.booklore.model.enums.BookFileType; import org.booklore.model.enums.LibraryOrganizationMode; import org.booklore.repository.BookRepository; import org.booklore.util.BookFileGroupingUtils; @@ -31,6 +32,7 @@ public class BookGroupingService { LibraryOrganizationMode mode = getOrganizationMode(libraryEntity); return switch (mode) { + case BOOK_PER_FILE -> groupByFile(newFiles); case BOOK_PER_FOLDER -> groupByFolder(newFiles); case AUTO_DETECT -> BookFileGroupingUtils.groupByBaseName(newFiles); }; @@ -56,6 +58,7 @@ public class BookGroupingService { newBookGroups = Collections.emptyMap(); } else { newBookGroups = switch (mode) { + case BOOK_PER_FILE -> groupByFile(unmatched); case BOOK_PER_FOLDER -> groupByFolder(unmatched); case AUTO_DETECT -> BookFileGroupingUtils.groupByBaseName(unmatched); }; @@ -64,27 +67,97 @@ public class BookGroupingService { return new GroupingResult(filesToAttach, newBookGroups); } - private Map> groupByFolder(List files) { + private Map> groupByFile(List files) { Map> result = new LinkedHashMap<>(); for (LibraryFile file : files) { - String folderKey = file.getLibraryPathEntity().getId() + ":" + - (file.getFileSubPath() == null ? "" : file.getFileSubPath()); - result.computeIfAbsent(folderKey, k -> new ArrayList<>()).add(file); + String key = file.getLibraryPathEntity().getId() + ":" + + (file.getFileSubPath() == null ? "" : file.getFileSubPath()) + ":" + + file.getFileName(); + result.computeIfAbsent(key, k -> new ArrayList<>()).add(file); + } + + log.debug("BOOK_PER_FILE grouping: {} files into {} groups", files.size(), result.size()); + return result; + } + + private Map> groupByFolder(List files) { + Map> result = new LinkedHashMap<>(); + + Set ebookFolders = new HashSet<>(); + for (LibraryFile file : files) { + if (file.getBookFileType() != BookFileType.AUDIOBOOK) { + String folderKey = file.getLibraryPathEntity().getId() + ":" + + (file.getFileSubPath() == null ? "" : file.getFileSubPath()); + ebookFolders.add(folderKey); + } + } + + for (LibraryFile file : files) { + Long pathId = file.getLibraryPathEntity().getId(); + String subPath = file.getFileSubPath() == null ? "" : file.getFileSubPath(); + + if (subPath.isEmpty()) { + String key = pathId + "::" + file.getFileName(); + result.computeIfAbsent(key, k -> new ArrayList<>()).add(file); + } else if (file.getBookFileType() == BookFileType.AUDIOBOOK) { + // Folder-based audiobook entries represent a collapsed directory (e.g., subPath="Author", + // fileName="audiobook-folder"). Their subPath points to the parent because getRelativeSubPath + // takes .getParent() (designed for files, not directories). Reconstruct the actual folder path + // so sibling audiobook folders stay separate and absorption searches from the correct level. + String effectiveSubPath = file.isFolderBased() + ? subPath + "/" + file.getFileName() + : subPath; + String ancestorKey = findNearestEbookAncestor(pathId, effectiveSubPath, ebookFolders); + if (ancestorKey != null) { + result.computeIfAbsent(ancestorKey, k -> new ArrayList<>()).add(file); + } else { + String key = pathId + ":" + effectiveSubPath; + result.computeIfAbsent(key, k -> new ArrayList<>()).add(file); + } + } else { + String key = pathId + ":" + subPath; + result.computeIfAbsent(key, k -> new ArrayList<>()).add(file); + } } log.debug("BOOK_PER_FOLDER grouping: {} files into {} groups", files.size(), result.size()); return result; } + private String findNearestEbookAncestor(Long pathId, String subPath, Set ebookFolders) { + String current = subPath; + while (true) { + int lastSep = current.lastIndexOf('/'); + if (lastSep == -1) { + lastSep = current.lastIndexOf('\\'); + } + if (lastSep <= 0) { + break; + } + current = current.substring(0, lastSep); + String candidateKey = pathId + ":" + current; + if (ebookFolders.contains(candidateKey)) { + return candidateKey; + } + } + return null; + } + private BookEntity findMatchingBook(LibraryFile file, LibraryOrganizationMode mode) { - BookEntity filelessMatch = findMatchingFilelessBook(file, file.getLibraryEntity()); + BookEntity filelessMatch = switch (mode) { + case BOOK_PER_FILE, BOOK_PER_FOLDER -> findExactFilelessMatch(file, file.getLibraryEntity()); + case AUTO_DETECT -> findMatchingFilelessBook(file, file.getLibraryEntity()); + }; if (filelessMatch != null) { return filelessMatch; } - String fileSubPath = file.getFileSubPath(); + if (mode == LibraryOrganizationMode.BOOK_PER_FILE) { + return null; + } + String fileSubPath = file.getFileSubPath(); if (fileSubPath == null || fileSubPath.isEmpty()) { return null; } @@ -97,15 +170,45 @@ public class BookGroupingService { .toList(); if (activeBooksInDirectory.isEmpty()) { + if (mode == LibraryOrganizationMode.BOOK_PER_FOLDER && file.getBookFileType() == BookFileType.AUDIOBOOK) { + return findNearestAncestorBookWithEbook(libraryPathId, fileSubPath); + } return null; } return switch (mode) { - case BOOK_PER_FOLDER -> findMatchBookPerFolder(file, activeBooksInDirectory); + case BOOK_PER_FILE -> null; + case BOOK_PER_FOLDER -> findMatchBookPerFolderWithAbsorption(file, activeBooksInDirectory); case AUTO_DETECT -> findMatchAutoDetect(file, activeBooksInDirectory); }; } + private BookEntity findExactFilelessMatch(LibraryFile file, LibraryEntity library) { + List filelessBooks = bookRepository.findFilelessBooksByLibraryId(library.getId()); + if (filelessBooks.isEmpty()) { + return null; + } + + String fileBaseName = BookFileGroupingUtils.extractGroupingKey(file.getFileName()); + Long fileLibraryPathId = file.getLibraryPathEntity().getId(); + + for (BookEntity book : filelessBooks) { + if (book.getLibraryPath() != null && !book.getLibraryPath().getId().equals(fileLibraryPathId)) { + continue; + } + + if (book.getMetadata() != null && book.getMetadata().getTitle() != null) { + String bookTitle = BookFileGroupingUtils.extractGroupingKey(book.getMetadata().getTitle()); + if (fileBaseName.equals(bookTitle)) { + log.debug("Exact matched file '{}' to fileless book '{}' (title: {})", + file.getFileName(), book.getId(), book.getMetadata().getTitle()); + return book; + } + } + } + return null; + } + private BookEntity findMatchingFilelessBook(LibraryFile file, LibraryEntity library) { List filelessBooks = bookRepository.findFilelessBooksByLibraryId(library.getId()); if (filelessBooks.isEmpty()) { @@ -133,7 +236,7 @@ public class BookGroupingService { return null; } - private BookEntity findMatchBookPerFolder(LibraryFile file, List booksInDirectory) { + private BookEntity findMatchBookPerFolderWithAbsorption(LibraryFile file, List booksInDirectory) { List booksWithFiles = booksInDirectory.stream() .filter(BookEntity::hasFiles) .toList(); @@ -143,18 +246,40 @@ public class BookGroupingService { } if (booksWithFiles.size() == 1) { - BookEntity book = booksWithFiles.get(0); - if (isFileNameCompatible(file, book)) { - log.debug("BOOK_PER_FOLDER: Attaching '{}' to single book in folder: '{}'", - file.getFileName(), book.getPrimaryBookFile().getFileName()); - return book; - } - return null; + return booksWithFiles.getFirst(); } - log.warn("BOOK_PER_FOLDER: Multiple books ({}) in folder '{}', using filename match", - booksWithFiles.size(), file.getFileSubPath()); - return findBestMatch(file, booksWithFiles); + return booksWithFiles.stream() + .max(Comparator.comparingLong(book -> book.getBookFiles() != null ? book.getBookFiles().size() : 0)) + .orElse(null); + } + + private BookEntity findNearestAncestorBookWithEbook(Long libraryPathId, String subPath) { + String current = subPath; + while (true) { + int lastSep = current.lastIndexOf('/'); + if (lastSep == -1) { + lastSep = current.lastIndexOf('\\'); + } + if (lastSep <= 0) { + break; + } + current = current.substring(0, lastSep); + + List booksAtLevel = bookRepository.findAllByLibraryPathIdAndFileSubPath(libraryPathId, current); + for (BookEntity book : booksAtLevel) { + if (book.getDeleted() != null && book.getDeleted()) { + continue; + } + if (book.getBookFiles() != null && book.getBookFiles().stream() + .anyMatch(bf -> bf.getBookType() != BookFileType.AUDIOBOOK)) { + log.debug("BOOK_PER_FOLDER: Audio absorption matched to ancestor book id={} at '{}'", + book.getId(), current); + return book; + } + } + } + return null; } private BookEntity findMatchAutoDetect(LibraryFile file, List booksInDirectory) { @@ -167,7 +292,7 @@ public class BookGroupingService { } if (booksWithFiles.size() == 1) { - BookEntity book = booksWithFiles.get(0); + BookEntity book = booksWithFiles.getFirst(); if (isFileNameCompatible(file, book)) { log.debug("AUTO_DETECT: Single book in folder '{}', attaching '{}' to '{}'", file.getFileSubPath(), file.getFileName(), book.getPrimaryBookFile().getFileName()); @@ -219,22 +344,6 @@ public class BookGroupingService { return BookFileGroupingUtils.calculateSimilarity(fileKey, bookKey) >= 0.85; } - private BookEntity findExactMatch(LibraryFile file, List books) { - String fileKey = BookFileGroupingUtils.extractGroupingKey(file.getFileName()); - - for (BookEntity book : books) { - BookFileEntity primaryFile = book.getPrimaryBookFile(); - if (primaryFile == null) { - continue; - } - String bookKey = BookFileGroupingUtils.extractGroupingKey(primaryFile.getFileName()); - if (fileKey.equals(bookKey)) { - return book; - } - } - return null; - } - private LibraryOrganizationMode getOrganizationMode(LibraryEntity library) { LibraryOrganizationMode mode = library.getOrganizationMode(); return mode != null ? mode : LibraryOrganizationMode.AUTO_DETECT; diff --git a/booklore-api/src/main/java/org/booklore/service/library/FileAsBookProcessor.java b/booklore-api/src/main/java/org/booklore/service/library/FileAsBookProcessor.java index 4bcd0886b..a50eb38f3 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/FileAsBookProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/library/FileAsBookProcessor.java @@ -2,6 +2,7 @@ package org.booklore.service.library; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.booklore.exception.ApiError; import org.booklore.model.FileProcessResult; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; @@ -10,6 +11,7 @@ import org.booklore.model.entity.LibraryEntity; import org.booklore.model.enums.BookFileType; import org.booklore.repository.BookAdditionalFileRepository; import org.booklore.repository.BookRepository; +import org.booklore.repository.LibraryRepository; import org.booklore.service.event.BookEventBroadcaster; import org.booklore.service.file.FileFingerprint; import org.booklore.service.fileprocessor.BookFileProcessor; @@ -44,6 +46,7 @@ public class FileAsBookProcessor { private final KoboAutoShelfService koboAutoShelfService; private final BookRepository bookRepository; private final BookAdditionalFileRepository bookAdditionalFileRepository; + private final LibraryRepository libraryRepository; private final FileService fileService; private final MetadataExtractorFactory metadataExtractorFactory; private final AudiobookMetadataExtractor audiobookMetadataExtractor; @@ -56,10 +59,18 @@ public class FileAsBookProcessor { @Transactional public void processLibraryFilesGrouped(Map> groups, LibraryEntity libraryEntity) { + LibraryEntity managedLibrary = ensureManaged(libraryEntity); for (Map.Entry> entry : groups.entrySet()) { - processGroupWithErrorHandling(entry.getValue(), libraryEntity); + entry.getValue().forEach(lf -> lf.setLibraryEntity(managedLibrary)); + processGroupWithErrorHandling(entry.getValue(), managedLibrary); } - log.info("Finished processing library '{}'", libraryEntity.getName()); + log.info("Finished processing library '{}'", managedLibrary.getName()); + } + + private LibraryEntity ensureManaged(LibraryEntity entity) { + if (entity.getId() == null) return entity; + return libraryRepository.findById(entity.getId()) + .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(entity.getId())); } private void processGroupWithErrorHandling(List group, LibraryEntity libraryEntity) { @@ -114,14 +125,14 @@ public class FileAsBookProcessor { List formatPriority = libraryEntity.getFormatPriority(); return group.stream() .filter(f -> f.getBookFileType() != null) - .min(Comparator.comparingInt(f -> { + .min(Comparator.comparing(f -> { BookFileType bookFileType = f.getBookFileType(); if (formatPriority != null && !formatPriority.isEmpty()) { int index = formatPriority.indexOf(bookFileType); return index >= 0 ? index : Integer.MAX_VALUE; } return bookFileType.ordinal(); - })); + }).thenComparing(LibraryFile::getFileName)); } private void createAdditionalBookFile(BookEntity bookEntity, LibraryFile file) { diff --git a/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java b/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java index 84eb155fb..34e920295 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java +++ b/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java @@ -5,6 +5,7 @@ import org.booklore.model.entity.LibraryEntity; import org.booklore.model.entity.LibraryPathEntity; import org.booklore.model.enums.BookFileExtension; import org.booklore.model.enums.BookFileType; +import org.booklore.model.enums.LibraryOrganizationMode; import org.booklore.util.FileUtils; import lombok.extern.slf4j.Slf4j; import org.jspecify.annotations.NonNull; @@ -41,7 +42,110 @@ public class LibraryFileHelper { } public List getLibraryFiles(LibraryEntity libraryEntity) throws IOException { - return filterByAllowedFormats(getAllLibraryFiles(libraryEntity), libraryEntity.getAllowedFormats()); + LibraryOrganizationMode mode = libraryEntity.getOrganizationMode() != null + ? libraryEntity.getOrganizationMode() : LibraryOrganizationMode.AUTO_DETECT; + + List allFiles = switch (mode) { + case BOOK_PER_FILE, BOOK_PER_FOLDER -> getAllLibraryFilesFlat(libraryEntity); + case AUTO_DETECT -> getAllLibraryFiles(libraryEntity); + }; + return filterByAllowedFormats(allFiles, libraryEntity.getAllowedFormats()); + } + + public List getAllLibraryFilesFlat(LibraryEntity libraryEntity) throws IOException { + List allFiles = new ArrayList<>(); + for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) { + allFiles.addAll(findLibraryFilesFlat(pathEntity, libraryEntity)); + } + return allFiles; + } + + private List findLibraryFilesFlat(LibraryPathEntity pathEntity, LibraryEntity libraryEntity) throws IOException { + Path libraryPath = Path.of(pathEntity.getPath()); + List libraryFiles = new ArrayList<>(); + Map> dirAudioFiles = new HashMap<>(); + + Files.walkFileTree(libraryPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<>() { + @Override + @NonNull + public FileVisitResult visitFile(@NonNull Path file, @NonNull BasicFileAttributes attrs) { + if (FileUtils.shouldIgnore(file) || !Files.isReadable(file) || !Files.isRegularFile(file) || attrs.size() == 0) { + return FileVisitResult.CONTINUE; + } + + String fileName = file.getFileName().toString(); + Optional bookExtension = BookFileExtension.fromFileName(fileName); + + if (bookExtension.isEmpty()) { + return FileVisitResult.CONTINUE; + } + + if (bookExtension.get().getType() == BookFileType.AUDIOBOOK) { + dirAudioFiles.computeIfAbsent(file.getParent(), k -> new ArrayList<>()).add(file); + } else { + libraryFiles.add(LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), file)) + .fileName(fileName) + .bookFileType(bookExtension.get().getType()) + .build()); + } + + return FileVisitResult.CONTINUE; + } + + @Override + @NonNull + public FileVisitResult visitFileFailed(@NonNull Path file, IOException e) { + log.error("Failed read path [{}]: {}", file, e.getMessage(), e); + return FileVisitResult.CONTINUE; + } + + @Override + @NonNull + public FileVisitResult preVisitDirectory(@NonNull Path dir, @NonNull BasicFileAttributes attrs) throws IOException { + if (FileUtils.shouldIgnore(dir) || !Files.isReadable(dir)) { + return FileVisitResult.SKIP_SUBTREE; + } + if (!dir.equals(libraryPath) && Files.exists(dir.resolve(".ignore"))) { + log.debug("Skipping directory with .ignore file: {}", dir); + return FileVisitResult.SKIP_SUBTREE; + } + return super.preVisitDirectory(dir, attrs); + } + }); + + // Collapse audio files: 2+ audio files in same directory become a single folder-based audiobook. + // A single audio file (e.g. standalone m4b) stays as an individual file entry. + // Audio files at the library root are always added individually (no folder to name the audiobook after). + for (var entry : dirAudioFiles.entrySet()) { + Path dir = entry.getKey(); + List audioFiles = entry.getValue(); + + if (dir.equals(libraryPath) || audioFiles.size() < MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK) { + for (Path audioFile : audioFiles) { + libraryFiles.add(LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), audioFile)) + .fileName(audioFile.getFileName().toString()) + .bookFileType(BookFileType.AUDIOBOOK) + .build()); + } + } else { + libraryFiles.add(LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), dir)) + .fileName(dir.getFileName().toString()) + .bookFileType(BookFileType.AUDIOBOOK) + .folderBased(true) + .build()); + } + } + + return libraryFiles; } List filterByAllowedFormats(List files, List allowedFormats) { @@ -67,7 +171,7 @@ public class LibraryFileHelper { @Override @NonNull public FileVisitResult visitFile(@NonNull Path file, @NonNull BasicFileAttributes attrs) { - if (FileUtils.shouldIgnore(file) || !Files.isReadable(file) || !Files.isRegularFile(file)) { + if (FileUtils.shouldIgnore(file) || !Files.isReadable(file) || !Files.isRegularFile(file) || attrs.size() == 0) { return FileVisitResult.CONTINUE; } @@ -182,7 +286,10 @@ public class LibraryFileHelper { if (FileUtils.shouldIgnore(dir) || !Files.isReadable(dir)) { return FileVisitResult.SKIP_SUBTREE; } - + if (!dir.equals(libraryPath) && Files.exists(dir.resolve(".ignore"))) { + log.debug("Skipping directory with .ignore file: {}", dir); + return FileVisitResult.SKIP_SUBTREE; + } return super.preVisitDirectory(dir, attrs); } }); diff --git a/booklore-api/src/main/java/org/booklore/service/library/LibraryService.java b/booklore-api/src/main/java/org/booklore/service/library/LibraryService.java index 65e5e58c5..4392e124b 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/LibraryService.java +++ b/booklore-api/src/main/java/org/booklore/service/library/LibraryService.java @@ -24,7 +24,7 @@ import org.booklore.repository.LibraryPathRepository; import org.booklore.repository.LibraryRepository; import org.booklore.repository.UserRepository; import org.booklore.service.NotificationService; -import org.booklore.service.monitoring.MonitoringService; +import org.booklore.service.monitoring.LibraryWatchService; import org.booklore.task.options.RescanLibraryContext; import org.booklore.util.FileService; import org.booklore.util.SecurityContextVirtualThread; @@ -70,7 +70,7 @@ public class LibraryService { private final LibraryMapper libraryMapper; private final NotificationService notificationService; private final FileService fileService; - private final MonitoringService monitoringService; + private final LibraryWatchService libraryWatchService; private final AuthenticationService authenticationService; private final UserRepository userRepository; private final AuditService auditService; @@ -79,7 +79,7 @@ public class LibraryService { @EventListener(ApplicationReadyEvent.class) public void initializeMonitoring() { List libraries = libraryRepository.findAll().stream().map(libraryMapper::toLibrary).collect(Collectors.toList()); - monitoringService.registerLibraries(libraries); + libraryWatchService.registerLibraries(libraries); log.info("Monitoring initialized with {} libraries", libraries.size()); } @@ -96,6 +96,9 @@ public class LibraryService { if (request.getMetadataSource() != null) { library.setMetadataSource(request.getMetadataSource()); } + if (request.getOrganizationMode() != null) { + library.setOrganizationMode(request.getOrganizationMode()); + } Set currentPaths = library.getLibraryPaths().stream() .map(LibraryPathEntity::getPath) @@ -139,9 +142,9 @@ public class LibraryService { LibraryEntity savedLibrary = libraryRepository.save(library); if (request.isWatch()) { - monitoringService.registerLibraries(List.of(libraryMapper.toLibrary(savedLibrary))); + libraryWatchService.registerLibraries(List.of(libraryMapper.toLibrary(savedLibrary))); } else { - monitoringService.unregisterLibrary(libraryId); + libraryWatchService.unregisterLibrary(libraryId); } if (!newPaths.isEmpty()) { @@ -184,6 +187,7 @@ public class LibraryService { .formatPriority(request.getFormatPriority()) .allowedFormats(request.getAllowedFormats()) .metadataSource(request.getMetadataSource()) + .organizationMode(request.getOrganizationMode()) .users(List.of(user.get())) .build(); @@ -193,7 +197,7 @@ public class LibraryService { if (request.isWatch()) { for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) { Path path = Paths.get(pathEntity.getPath()); - monitoringService.registerPath(path, libraryId); + libraryWatchService.registerPath(path, libraryId); } } @@ -268,7 +272,7 @@ public class LibraryService { public void deleteLibrary(long id) { LibraryEntity library = libraryRepository.findById(id) .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(id)); - monitoringService.unregisterLibrary(id); + libraryWatchService.unregisterLibrary(id); Set bookIds = library.getBookEntities().stream().map(BookEntity::getId).collect(Collectors.toSet()); fileService.deleteBookCovers(bookIds); String libraryName = library.getName(); diff --git a/booklore-api/src/main/java/org/booklore/service/monitoring/DirectoryCreateEvent.java b/booklore-api/src/main/java/org/booklore/service/monitoring/DirectoryCreateEvent.java deleted file mode 100644 index 54b96ffdc..000000000 --- a/booklore-api/src/main/java/org/booklore/service/monitoring/DirectoryCreateEvent.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.booklore.service.monitoring; - -import lombok.Getter; -import org.springframework.context.ApplicationEvent; - -import java.nio.file.Path; - -@Getter -public class DirectoryCreateEvent extends ApplicationEvent { - private final Path newDirectory; - - public DirectoryCreateEvent(Object source, Path newDirectory) { - super(source); - this.newDirectory = newDirectory; - } -} diff --git a/booklore-api/src/main/java/org/booklore/service/monitoring/FileChangeEvent.java b/booklore-api/src/main/java/org/booklore/service/monitoring/FileChangeEvent.java deleted file mode 100644 index 3d3d35ed8..000000000 --- a/booklore-api/src/main/java/org/booklore/service/monitoring/FileChangeEvent.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.booklore.service.monitoring; - -import java.nio.file.Path; -import java.nio.file.WatchEvent; - -import lombok.Getter; -import org.springframework.context.ApplicationEvent; - -@Getter -public class FileChangeEvent extends ApplicationEvent { - - private final Path filePath; - private final WatchEvent.Kind eventKind; - private final Path watchedFolder; - - public FileChangeEvent(Object source, Path filePath, WatchEvent.Kind eventKind, Path watchedFolder) { - super(source); - this.filePath = filePath; - this.eventKind = eventKind; - this.watchedFolder = watchedFolder; - } -} \ No newline at end of file diff --git a/booklore-api/src/main/java/org/booklore/service/monitoring/LibraryWatchService.java b/booklore-api/src/main/java/org/booklore/service/monitoring/LibraryWatchService.java new file mode 100644 index 000000000..5faee6903 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/service/monitoring/LibraryWatchService.java @@ -0,0 +1,288 @@ +package org.booklore.service.monitoring; + +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import lombok.extern.slf4j.Slf4j; +import org.booklore.model.dto.Library; +import org.booklore.model.enums.BookFileExtension; +import org.booklore.service.watcher.LibraryFileEventProcessor; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.nio.file.*; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Slf4j +@Service +public class LibraryWatchService { + + private final LibraryFileEventProcessor eventProcessor; + private final WatchService watchService; + private final ExecutorService registrationExecutor; + + private final ConcurrentHashMap watches = new ConcurrentHashMap<>(); + private final Map libraryWatchStatus = new ConcurrentHashMap<>(); + + private record WatchEntry(WatchKey key, long libraryId) {} + + public LibraryWatchService(LibraryFileEventProcessor eventProcessor) throws IOException { + this.eventProcessor = eventProcessor; + this.watchService = FileSystems.getDefault().newWatchService(); + this.registrationExecutor = Executors.newSingleThreadExecutor( + Thread.ofVirtual().name("watch-registrar").factory()); + } + + @PostConstruct + public void start() { + Thread.ofVirtual().name("watch-poll").start(this::pollLoop); + } + + private void pollLoop() { + try { + while (!Thread.currentThread().isInterrupted()) { + WatchKey key; + try { + key = watchService.take(); + } catch (ClosedWatchServiceException e) { + log.warn("WatchService closed, stopping poll loop."); + break; + } + + Path directory = (Path) key.watchable(); + + for (WatchEvent event : key.pollEvents()) { + WatchEvent.Kind kind = event.kind(); + + if (kind == StandardWatchEventKinds.OVERFLOW) { + handleOverflow(directory); + continue; + } + + Path fileName = (Path) event.context(); + Path fullPath = directory.resolve(fileName); + + boolean isDir = kind == StandardWatchEventKinds.ENTRY_CREATE + ? Files.isDirectory(fullPath) + : watches.containsKey(fullPath); + + boolean isRelevantFile = !isDir && isRelevantBookFile(fullPath); + if (!isDir && !isRelevantFile) continue; + + if (isDir && kind == StandardWatchEventKinds.ENTRY_CREATE) { + WatchEntry parentEntry = watches.get(directory); + if (parentEntry != null) { + registrationExecutor.submit(() -> registerRecursive(fullPath, parentEntry.libraryId())); + } + } + + if (isDir && kind == StandardWatchEventKinds.ENTRY_DELETE) { + registrationExecutor.submit(() -> unregisterRecursive(fullPath)); + } + + WatchEntry entry = watches.get(directory); + if (entry != null) { + eventProcessor.processEvent(kind, entry.libraryId(), fullPath, isDir); + } else { + log.warn("No library ID found for watched directory: {}", directory); + } + } + + boolean valid = key.reset(); + if (!valid) { + log.warn("WatchKey no longer valid: {}", directory); + registrationExecutor.submit(() -> unregisterRecursive(directory)); + } + } + } catch (InterruptedException e) { + log.warn("Poll loop interrupted"); + Thread.currentThread().interrupt(); + } + } + + private void handleOverflow(Path directory) { + WatchEntry entry = watches.get(directory); + if (entry != null) { + log.warn("OVERFLOW for directory: {}. Queuing rescan for library {}.", directory, entry.libraryId()); + eventProcessor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, entry.libraryId(), directory, true); + } else { + log.warn("OVERFLOW event for untracked directory: {}", directory); + } + } + + public void registerLibraries(List libraries) { + libraries.forEach(lib -> libraryWatchStatus.put(lib.getId(), lib.isWatch())); + libraries.stream().filter(Library::isWatch).forEach(this::registerLibrary); + log.info("Registered {} libraries for monitoring", libraries.size()); + } + + public void registerLibrary(Library library) { + libraryWatchStatus.put(library.getId(), library.isWatch()); + if (!library.isWatch()) return; + + int[] count = {0}; + library.getPaths().forEach(libraryPath -> { + Path rootPath = Paths.get(libraryPath.getPath()); + if (Files.isDirectory(rootPath)) { + try (Stream pathStream = Files.walk(rootPath)) { + pathStream.filter(Files::isDirectory).forEach(path -> { + if (registerPath(path, library.getId())) { + count[0]++; + } + }); + } catch (IOException e) { + log.error("Failed to register paths for library '{}': {}", library.getName(), e.getMessage(), e); + } + } + }); + + log.info("Registered {} folders for library '{}'", count[0], library.getName()); + } + + public void unregisterLibrary(Long libraryId) { + Set pathsToRemove = watches.entrySet().stream() + .filter(e -> e.getValue().libraryId() == libraryId) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + + for (Path path : pathsToRemove) { + unregisterPath(path); + } + + libraryWatchStatus.put(libraryId, false); + log.debug("Unregistered library {} from monitoring", libraryId); + } + + public synchronized boolean registerPath(Path path, long libraryId) { + if (!Files.exists(path)) { + log.warn("Cannot register path that does not exist: {}", path); + return false; + } + if (!Files.isDirectory(path)) { + log.warn("Cannot register path that is not a directory: {}", path); + return false; + } + try { + if (!watches.containsKey(path)) { + WatchKey key = path.register(watchService, + StandardWatchEventKinds.ENTRY_CREATE, + StandardWatchEventKinds.ENTRY_DELETE); + watches.put(path, new WatchEntry(key, libraryId)); + return true; + } + } catch (IOException e) { + log.error("Error registering path: {}", path, e); + } + return false; + } + + public synchronized void unregisterPath(Path path) { + WatchEntry entry = watches.remove(path); + if (entry != null) { + entry.key().cancel(); + log.debug("Unregistered path: {}", path); + } + } + + private void registerRecursive(Path root, long libraryId) { + try (Stream stream = Files.walk(root)) { + stream.filter(Files::isDirectory) + .forEach(p -> registerPath(p, libraryId)); + } catch (IOException e) { + log.warn("Failed to register paths under: {}", root, e); + } + } + + private void unregisterRecursive(Path root) { + Set toRemove = watches.keySet().stream() + .filter(p -> p.startsWith(root)) + .collect(Collectors.toSet()); + + for (Path path : toRemove) { + unregisterPath(path); + } + } + + public void registerLibraryPaths(long libraryId, Path libraryRoot) { + if (!Files.exists(libraryRoot) || !Files.isDirectory(libraryRoot)) { + return; + } + try { + log.debug("Registering library paths for libraryId {} at {}", libraryId, libraryRoot); + registerPath(libraryRoot, libraryId); + try (var stream = Files.walk(libraryRoot)) { + stream.filter(Files::isDirectory) + .filter(path -> !path.equals(libraryRoot)) + .forEach(path -> registerPath(path, libraryId)); + } + } catch (Exception e) { + log.error("Failed to register library paths for libraryId {} at {}", libraryId, libraryRoot, e); + } + } + + public boolean isRelevantBookFile(Path path) { + return BookFileExtension.fromFileName(path.getFileName().toString()).isPresent(); + } + + public boolean isPathMonitored(Path path) { + return watches.containsKey(path.toAbsolutePath().normalize()); + } + + public boolean isLibraryMonitored(long libraryId) { + return libraryWatchStatus.getOrDefault(libraryId, false); + } + + public Set getPathsForLibraries(Set libraryIds) { + return watches.entrySet().stream() + .filter(e -> libraryIds.contains(e.getValue().libraryId())) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + } + + public boolean waitForEventsDrained(Set libraryIds, long timeoutMs) { + if (libraryIds == null || libraryIds.isEmpty()) { + return true; + } + Set libraryPaths = getPathsForLibraries(libraryIds); + return waitForEventsDrainedByPaths(libraryPaths, timeoutMs); + } + + public boolean waitForEventsDrainedByPaths(Set paths, long timeoutMs) { + if (paths == null || paths.isEmpty()) { + return true; + } + + final long pollIntervalMs = 50; + long deadline = System.currentTimeMillis() + timeoutMs; + while (System.currentTimeMillis() < deadline) { + if (!eventProcessor.hasPendingEventsForPaths(paths)) { + log.debug("Events drained for {} paths", paths.size()); + return true; + } + try { + Thread.sleep(pollIntervalMs); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + + log.warn("Timeout waiting for events to drain for {} paths", paths.size()); + return false; + } + + @PreDestroy + public void shutdown() { + log.info("Shutting down LibraryWatchService..."); + registrationExecutor.shutdownNow(); + try { + watchService.close(); + } catch (IOException e) { + log.error("Failed to close WatchService", e); + } + } +} diff --git a/booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringRegistrationService.java b/booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringRegistrationService.java index c6a21e266..9c1577b6b 100644 --- a/booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringRegistrationService.java +++ b/booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringRegistrationService.java @@ -17,21 +17,21 @@ import java.util.Set; @AllArgsConstructor public class MonitoringRegistrationService { - private final MonitoringService monitoringService; + private final LibraryWatchService libraryWatchService; public boolean isPathMonitored(Path path) { - return monitoringService.isPathMonitored(path); + return libraryWatchService.isPathMonitored(path); } public boolean isLibraryMonitored(Long libraryId) { - return monitoringService.isLibraryMonitored(libraryId); + return libraryWatchService.isLibraryMonitored(libraryId); } public void unregisterSpecificPath(Path path) { if (!Files.exists(path)) { log.debug("Path does not exist, attempting to unregister anyway: {}", path); } - monitoringService.unregisterPath(path); + libraryWatchService.unregisterPath(path); } public void registerSpecificPath(Path path, Long libraryId) { @@ -43,32 +43,19 @@ public class MonitoringRegistrationService { log.warn("Cannot register path that is not a directory: {}", path); return; } - monitoringService.registerPath(path, libraryId); + libraryWatchService.registerPath(path, libraryId); } public void registerLibrary(Library library) { - monitoringService.registerLibrary(library); + libraryWatchService.registerLibrary(library); } public void unregisterLibrary(Long libraryId) { - monitoringService.unregisterLibrary(libraryId); + libraryWatchService.unregisterLibrary(libraryId); } public void registerLibraryPaths(Long libraryId, Path libraryRoot) { - if (!Files.exists(libraryRoot) || !Files.isDirectory(libraryRoot)) { - return; - } - try { - log.debug("Registering library paths for libraryId {} at {}", libraryId, libraryRoot); - monitoringService.registerPath(libraryRoot, libraryId); - try (var stream = Files.walk(libraryRoot)) { - stream.filter(Files::isDirectory) - .filter(path -> !path.equals(libraryRoot)) - .forEach(path -> monitoringService.registerPath(path, libraryId)); - } - } catch (Exception e) { - log.error("Failed to register library paths for libraryId {} at {}", libraryId, libraryRoot, e); - } + libraryWatchService.registerLibraryPaths(libraryId, libraryRoot); } public void registerLibraries(Map libraries) { @@ -89,17 +76,17 @@ public class MonitoringRegistrationService { if (libraryIds == null || libraryIds.isEmpty()) { return Set.of(); } - return monitoringService.getPathsForLibraries(new HashSet<>(libraryIds)); + return libraryWatchService.getPathsForLibraries(new HashSet<>(libraryIds)); } public boolean waitForEventsDrainedByPaths(Set paths, long timeoutMs) { - return monitoringService.waitForEventsDrainedByPaths(paths, timeoutMs); + return libraryWatchService.waitForEventsDrainedByPaths(paths, timeoutMs); } public boolean waitForEventsDrained(Collection libraryIds, long timeoutMs) { if (libraryIds == null || libraryIds.isEmpty()) { return true; } - return monitoringService.waitForEventsDrained(new HashSet<>(libraryIds), timeoutMs); + return libraryWatchService.waitForEventsDrained(new HashSet<>(libraryIds), timeoutMs); } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringService.java b/booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringService.java deleted file mode 100644 index 1876592de..000000000 --- a/booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringService.java +++ /dev/null @@ -1,301 +0,0 @@ -package org.booklore.service.monitoring; - -import org.booklore.model.dto.Library; -import org.booklore.model.enums.BookFileExtension; -import org.booklore.service.watcher.LibraryFileEventProcessor; -import jakarta.annotation.PostConstruct; -import jakarta.annotation.PreDestroy; -import lombok.extern.slf4j.Slf4j; -import org.springframework.context.event.EventListener; -import org.springframework.dao.InvalidDataAccessApiUsageException; -import org.springframework.stereotype.Service; - -import java.io.IOException; -import java.nio.file.*; -import java.util.*; -import java.util.concurrent.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -@Slf4j -@Service -public class MonitoringService { - - private final LibraryFileEventProcessor libraryFileEventProcessor; - private final WatchService watchService; - private final MonitoringTask monitoringTask; - - private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); - private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); - - private final Set monitoredPaths = ConcurrentHashMap.newKeySet(); - private final Map registeredWatchKeys = new ConcurrentHashMap<>(); - private final Map pathToLibraryIdMap = new ConcurrentHashMap<>(); - private final Map libraryWatchStatusMap = new ConcurrentHashMap<>(); - - public MonitoringService(LibraryFileEventProcessor libraryFileEventProcessor, WatchService watchService, MonitoringTask monitoringTask) { - this.libraryFileEventProcessor = libraryFileEventProcessor; - this.watchService = watchService; - this.monitoringTask = monitoringTask; - } - - @PostConstruct - public void initializeMonitoring() { - monitoringTask.monitor(); - startProcessingThread(); - } - - @PreDestroy - public void stopMonitoring() { - log.info("Shutting down monitoring service..."); - singleThreadExecutor.shutdownNow(); - try { - watchService.close(); - } catch (IOException e) { - log.error("Failed to close WatchService", e); - } - } - - public void registerLibraries(List libraries) { - libraries.forEach(lib -> libraryWatchStatusMap.put(lib.getId(), lib.isWatch())); - libraries.stream().filter(Library::isWatch).forEach(this::registerLibrary); - log.info("Registered {} libraries for recursive monitoring", libraries.size()); - } - - public void registerLibrary(Library library) { - libraryWatchStatusMap.put(library.getId(), library.isWatch()); - if (!library.isWatch()) return; - - int[] registeredCount = {0}; - - library.getPaths().forEach(libraryPath -> { - Path rootPath = Paths.get(libraryPath.getPath()); - if (Files.isDirectory(rootPath)) { - try (Stream pathStream = Files.walk(rootPath)) { - pathStream.filter(Files::isDirectory).forEach(path -> { - if (registerPath(path, library.getId())) { - registeredCount[0]++; - } - }); - } catch (IOException e) { - log.error("Failed to register paths for library '{}': {}", library.getName(), e.getMessage(), e); - } - } - }); - - log.info("Registered {} folders for library '{}'", registeredCount[0], library.getName()); - } - - public void unregisterLibrary(Long libraryId) { - Set pathsToRemove = pathToLibraryIdMap.entrySet().stream() - .filter(entry -> entry.getValue().equals(libraryId)) - .map(Map.Entry::getKey) - .collect(Collectors.toSet()); - - for (Path path : pathsToRemove) { - unregisterPath(path); - } - - libraryWatchStatusMap.put(libraryId, false); - log.debug("Unregistered library {} from monitoring", libraryId); - } - - public synchronized boolean registerPath(Path path, Long libraryId) { - if (!Files.exists(path)) { - log.warn("Cannot register path that does not exist: {}", path); - return false; - } - if (!Files.isDirectory(path)) { - log.warn("Cannot register path that is not a directory: {}", path); - return false; - } - try { - if (monitoredPaths.add(path)) { - WatchKey key = path.register(watchService, - StandardWatchEventKinds.ENTRY_CREATE, - StandardWatchEventKinds.ENTRY_MODIFY, - StandardWatchEventKinds.ENTRY_DELETE); - registeredWatchKeys.put(path, key); - pathToLibraryIdMap.put(path, libraryId); - return true; - } - } catch (IOException e) { - log.error("Error registering path: {}", path, e); - } - return false; - } - - public synchronized void unregisterPath(Path path) { - unregisterPath(path, true); - } - - public synchronized void unregisterPath(Path path, boolean logUnregister) { - if (!Files.exists(path)) { - log.debug("Path does not exist, removing from monitoring if present: {}", path); - } - if (monitoredPaths.remove(path)) { - WatchKey key = registeredWatchKeys.remove(path); - if (key != null) key.cancel(); - pathToLibraryIdMap.remove(path); - if (logUnregister) { - log.debug("Unregistered path: {}", path); - } - } - } - - private void unregisterSubPaths(Path deletedPath) { - Set toRemove = monitoredPaths.stream() - .filter(p -> p.startsWith(deletedPath)) - .collect(Collectors.toSet()); - - for (Path path : toRemove) { - unregisterPath(path); - } - } - - @EventListener - public void handleFileChangeEvent(FileChangeEvent event) { - Path fullPath = event.getFilePath(); - WatchEvent.Kind kind = event.getEventKind(); - - if (kind != StandardWatchEventKinds.ENTRY_CREATE && kind != StandardWatchEventKinds.ENTRY_DELETE) return; - - boolean isDir = kind == StandardWatchEventKinds.ENTRY_CREATE - ? Files.isDirectory(fullPath) - : monitoredPaths.contains(fullPath); - - boolean isRelevantFile = isRelevantBookFile(fullPath); - if (!(isDir || isRelevantFile)) return; - - handleDirectoryEvents(event, fullPath, kind, isDir); - queueEvent(event, fullPath, kind); - } - - @EventListener - public void handleWatchKeyInvalidation(WatchKeyInvalidatedEvent event) { - Path invalidPath = event.getInvalidPath(); - if (monitoredPaths.remove(invalidPath)) { - log.warn("Removing invalid path from monitoring: {}", invalidPath); - pathToLibraryIdMap.remove(invalidPath); - WatchKey key = registeredWatchKeys.remove(invalidPath); - if (key != null) key.cancel(); - } - } - - private void startProcessingThread() { - log.info("Starting file change processor..."); - singleThreadExecutor.submit(() -> { - while (!Thread.currentThread().isInterrupted()) { - try { - FileChangeEvent event = eventQueue.take(); - processFileChangeEvent(event); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - break; - } catch (Exception e) { - log.error("Error in processing thread", e); - } - } - }); - } - - private void processFileChangeEvent(FileChangeEvent event) { - Path filePath = event.getFilePath(); - Path watchedFolder = event.getWatchedFolder(); - Long libraryId = pathToLibraryIdMap.get(watchedFolder); - - if (libraryId != null) { - try { - libraryFileEventProcessor.processFile(event.getEventKind(), libraryId, watchedFolder.toString(), filePath.toString()); - } catch (InvalidDataAccessApiUsageException e) { - log.debug("InvalidDataAccessApiUsageException for libraryId={}", libraryId); - } - } else { - log.warn("No library ID found for folder: {}", watchedFolder); - } - } - - private void handleDirectoryEvents(FileChangeEvent event, Path fullPath, WatchEvent.Kind kind, boolean isDir) { - if (isDir && kind == StandardWatchEventKinds.ENTRY_CREATE) { - Long parentLibraryId = pathToLibraryIdMap.get(event.getWatchedFolder()); - if (parentLibraryId != null) { - try (Stream stream = Files.walk(fullPath)) { - stream.filter(Files::isDirectory).forEach(path -> registerPath(path, parentLibraryId)); - } catch (IOException e) { - log.warn("Failed to register nested paths: {}", fullPath, e); - } - } - } - - if (isDir && kind == StandardWatchEventKinds.ENTRY_DELETE) { - unregisterSubPaths(fullPath); - } - } - - private void queueEvent(FileChangeEvent event, Path fullPath, WatchEvent.Kind kind) { - if (!eventQueue.offer(event)) { - log.warn("Event queue full, dropping: {}", fullPath); - } else { - log.debug("Queued: {} [{}]", fullPath, kind.name()); - } - } - - public boolean isRelevantBookFile(Path path) { - return BookFileExtension.fromFileName(path.getFileName().toString()).isPresent(); - } - - public boolean isPathMonitored(Path path) { - return monitoredPaths.contains(path.toAbsolutePath().normalize()); - } - - public boolean isLibraryMonitored(Long libraryId) { - return libraryWatchStatusMap.getOrDefault(libraryId, false); - } - - public Set getPathsForLibraries(Set libraryIds) { - return pathToLibraryIdMap.entrySet().stream() - .filter(entry -> libraryIds.contains(entry.getValue())) - .map(Map.Entry::getKey) - .collect(Collectors.toSet()); - } - - public boolean waitForEventsDrained(Set libraryIds, long timeoutMs) { - if (libraryIds == null || libraryIds.isEmpty()) { - return true; - } - - Set libraryPaths = getPathsForLibraries(libraryIds); - return waitForEventsDrainedByPaths(libraryPaths, timeoutMs); - } - - public boolean waitForEventsDrainedByPaths(Set libraryPaths, long timeoutMs) { - if (libraryPaths == null || libraryPaths.isEmpty()) { - return true; - } - - final long pollIntervalMs = 50; - long deadline = System.currentTimeMillis() + timeoutMs; - while (System.currentTimeMillis() < deadline) { - boolean hasPendingEvents = eventQueue.stream() - .anyMatch(event -> { - Path watchedFolder = event.getWatchedFolder(); - return libraryPaths.stream().anyMatch(watchedFolder::startsWith); - }); - - if (!hasPendingEvents) { - log.debug("Event queue drained for paths: {}", libraryPaths.size()); - return true; - } - - try { - Thread.sleep(pollIntervalMs); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return false; - } - } - - log.warn("Timeout waiting for event queue to drain for {} paths", libraryPaths.size()); - return false; - } -} diff --git a/booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringTask.java b/booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringTask.java deleted file mode 100644 index 035773859..000000000 --- a/booklore-api/src/main/java/org/booklore/service/monitoring/MonitoringTask.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.booklore.service.monitoring; - -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Service; - -import java.nio.file.*; - -@Slf4j -@Service -@AllArgsConstructor -public class MonitoringTask { - - private final WatchService watchService; - private final ApplicationEventPublisher eventPublisher; - - @Async - public void monitor() { - try { - while (!Thread.currentThread().isInterrupted()) { - WatchKey key; - try { - key = watchService.take(); - } catch (ClosedWatchServiceException e) { - log.warn("WatchService has been closed. Stopping monitoring."); - break; - } - - if (key == null) continue; - - Path directory = (Path) key.watchable(); - - for (WatchEvent event : key.pollEvents()) { - WatchEvent.Kind kind = event.kind(); - if (kind == StandardWatchEventKinds.OVERFLOW) continue; - - Path fileName = (Path) event.context(); - Path fullPath = directory.resolve(fileName); - eventPublisher.publishEvent(new FileChangeEvent(this, fullPath, kind, directory)); - } - - boolean valid = key.reset(); - if (!valid) { - log.warn("WatchKey is no longer valid: {}", directory); - // Clean up but DO NOT break - eventPublisher.publishEvent(new WatchKeyInvalidatedEvent(this, directory)); - } - } - } catch (InterruptedException e) { - log.warn("Monitoring task interrupted", e); - Thread.currentThread().interrupt(); - } - } -} \ No newline at end of file diff --git a/booklore-api/src/main/java/org/booklore/service/monitoring/WatchKeyInvalidatedEvent.java b/booklore-api/src/main/java/org/booklore/service/monitoring/WatchKeyInvalidatedEvent.java deleted file mode 100644 index 60982c507..000000000 --- a/booklore-api/src/main/java/org/booklore/service/monitoring/WatchKeyInvalidatedEvent.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.booklore.service.monitoring; - -import lombok.Getter; -import org.springframework.context.ApplicationEvent; - -import java.nio.file.Path; - -@Getter -public class WatchKeyInvalidatedEvent extends ApplicationEvent { - private final Path invalidPath; - - public WatchKeyInvalidatedEvent(Object source, Path invalidPath) { - super(source); - this.invalidPath = invalidPath; - } -} diff --git a/booklore-api/src/main/java/org/booklore/service/watcher/BookFilePersistenceService.java b/booklore-api/src/main/java/org/booklore/service/watcher/BookFilePersistenceService.java index d5686dbdc..bc2f60b47 100644 --- a/booklore-api/src/main/java/org/booklore/service/watcher/BookFilePersistenceService.java +++ b/booklore-api/src/main/java/org/booklore/service/watcher/BookFilePersistenceService.java @@ -6,6 +6,7 @@ import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.LibraryEntity; import org.booklore.model.entity.LibraryPathEntity; +import org.booklore.model.enums.PermissionType; import org.booklore.model.websocket.Topic; import org.booklore.repository.BookFileRepository; import org.booklore.repository.BookRepository; @@ -42,14 +43,24 @@ public class BookFilePersistenceService { newLibraryPath = entityManager.merge(newLibraryPath); String newSubPath = FileUtils.getRelativeSubPath(newLibraryPath.getPath(), path); + String newFileName = path.getFileName().toString(); - var primaryFile = book.getPrimaryBookFile(); - boolean pathChanged = !Objects.equals(newSubPath, primaryFile.getFileSubPath()) || !Objects.equals(newLibraryPath.getId(), book.getLibraryPath().getId()); + BookFileEntity matchedFile = book.getBookFiles().stream() + .filter(bf -> currentHash.equals(bf.getCurrentHash())) + .findFirst() + .orElse(book.getPrimaryBookFile()); - if (pathChanged || Boolean.TRUE.equals(book.getDeleted())) { + boolean changed = !Objects.equals(newSubPath, matchedFile.getFileSubPath()) + || !Objects.equals(newFileName, matchedFile.getFileName()) + || !Objects.equals(newLibraryPath.getId(), book.getLibraryPath().getId()) + || Boolean.TRUE.equals(book.getDeleted()); + + if (changed) { book.setLibraryPath(newLibraryPath); - primaryFile.setFileSubPath(newSubPath); + matchedFile.setFileSubPath(newSubPath); + matchedFile.setFileName(newFileName); book.setDeleted(Boolean.FALSE); + book.setDeletedAt(null); bookRepository.save(book); log.info("[FILE_CREATE] Updated path / undeleted existing book with hash '{}': '{}'", currentHash, path); } else { @@ -82,9 +93,7 @@ public class BookFilePersistenceService { if (relativeFolderPath == null) { throw new IllegalArgumentException("relativeFolderPath cannot be null"); } - String normalizedPrefix = relativeFolderPath.endsWith("/") ? relativeFolderPath : (relativeFolderPath + "/"); - - List books = bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(libraryPathId, normalizedPrefix); + List books = bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(libraryPathId, relativeFolderPath); books.forEach(book -> { book.setDeleted(true); book.setDeletedAt(Instant.now()); @@ -125,4 +134,35 @@ public class BookFilePersistenceService { public long countBookFilesByBookId(Long bookId) { return bookFileRepository.countByBookId(bookId); } + + @Transactional + public void recoverFolderBook(PendingDeletionPool.BookSnapshot bookSnap, LibraryPathEntity newLibraryPath, + Path folderPath, Map fileHashes) { + BookEntity book = bookRepository.findById(bookSnap.bookId()).orElse(null); + if (book == null) return; + + book.setLibraryPath(entityManager.merge(newLibraryPath)); + book.setDeleted(false); + book.setDeletedAt(null); + + for (PendingDeletionPool.FileSnapshot fs : bookSnap.files()) { + bookFileRepository.findById(fs.bookFileId()).ifPresent(bf -> { + for (var entry : fileHashes.entrySet()) { + if (entry.getValue().equals(fs.currentHash())) { + Path filePath = entry.getKey(); + String newSubPath = FileUtils.getRelativeSubPath(newLibraryPath.getPath(), filePath); + bf.setFileSubPath(newSubPath); + bf.setFileName(filePath.getFileName().toString()); + bf.setCurrentHash(entry.getValue()); + break; + } + } + }); + } + + bookRepository.save(book); + notificationService.sendMessageToPermissions(Topic.BOOK_ADD, + bookMapper.toBookWithDescription(book, false), Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY)); + log.info("[RECOVERED] Book id={} recovered from folder move", book.getId()); + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/org/booklore/service/watcher/BookFileTransactionalHandler.java b/booklore-api/src/main/java/org/booklore/service/watcher/BookFileTransactionalHandler.java index 47c00a5fc..903ed9f00 100644 --- a/booklore-api/src/main/java/org/booklore/service/watcher/BookFileTransactionalHandler.java +++ b/booklore-api/src/main/java/org/booklore/service/watcher/BookFileTransactionalHandler.java @@ -8,6 +8,7 @@ import org.booklore.model.entity.LibraryEntity; import org.booklore.model.entity.LibraryPathEntity; import org.booklore.model.enums.BookFileExtension; import org.booklore.model.enums.BookFileType; +import org.booklore.model.enums.LibraryOrganizationMode; import org.booklore.model.websocket.LogNotification; import org.booklore.model.websocket.Topic; import org.booklore.repository.BookAdditionalFileRepository; @@ -25,6 +26,8 @@ import org.springframework.stereotype.Service; import java.nio.file.Path; import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.Set; @@ -45,6 +48,7 @@ public class BookFileTransactionalHandler { private final LibraryRepository libraryRepository; private final BookRepository bookRepository; private final BookAdditionalFileRepository bookAdditionalFileRepository; + private final PendingDeletionPool pendingDeletionPool; @Transactional() public void handleNewBookFile(long libraryId, Path path) { @@ -59,8 +63,52 @@ public class BookFileTransactionalHandler { LibraryPathEntity libraryPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(libraryEntity, libraryPath); String fileSubPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), path); + Optional existingAtPath = bookFilePersistenceService + .findBookFileByLibraryPathSubPathAndFileName(libraryPathEntity.getId(), fileSubPath, fileName); + if (existingAtPath.isPresent()) { + BookFileEntity existing = existingAtPath.get(); + BookEntity existingBook = existing.getBook(); + boolean wasDeleted = Boolean.TRUE.equals(existingBook.getDeleted()); + String existingHash = existing.getCurrentHash(); + String currentHash = FileFingerprint.generateHash(path); + + if (wasDeleted) { + pendingDeletionPool.matchByHash(existingHash); + existingBook.setDeleted(false); + existingBook.setDeletedAt(null); + existing.setCurrentHash(currentHash); + bookFilePersistenceService.save(existingBook); + log.info("[CREATE] File '{}' restored deleted book id={}", filePath, existingBook.getId()); + notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY)); + return; + } + + pendingDeletionPool.cancelByPath(path); + + if (currentHash.equals(existingHash)) { + log.debug("[CREATE] File '{}' unchanged (same hash), skipping", filePath); + notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY)); + return; + } + existing.setCurrentHash(currentHash); + bookFilePersistenceService.save(existingBook); + log.info("[CREATE] File '{}' content changed, updated hash", filePath); + notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY)); + return; + } + String currentHash = FileFingerprint.generateHash(path); - Optional existingByHash = bookRepository.findByCurrentHash(currentHash); + + Optional poolMatch = pendingDeletionPool.matchByHash(currentHash); + if (poolMatch.isPresent()) { + var match = poolMatch.get(); + pendingDeletionPool.recoverBook(match, libraryPathEntity, fileSubPath, fileName, currentHash); + log.info("[CREATE] File '{}' matched pending deletion, recovered book id={}", filePath, match.book().bookId()); + notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY)); + return; + } + + Optional existingByHash = bookRepository.findByCurrentHashIncludingRecentlyDeleted(currentHash, Instant.now().minus(60, ChronoUnit.SECONDS)); if (existingByHash.isPresent()) { bookFilePersistenceService.updatePathIfChanged(existingByHash.get(), libraryEntity, path, currentHash); log.info("[CREATE] File '{}' recognized as moved file, updated existing book's path", filePath); @@ -68,7 +116,13 @@ public class BookFileTransactionalHandler { return; } - BookEntity filelessMatch = findMatchingFilelessBook(libraryEntity, fileName, libraryPathEntity); + var mode = libraryEntity.getOrganizationMode() != null + ? libraryEntity.getOrganizationMode() : LibraryOrganizationMode.AUTO_DETECT; + + BookEntity filelessMatch = (mode == LibraryOrganizationMode.AUTO_DETECT) + ? findMatchingFilelessBook(libraryEntity, fileName, libraryPathEntity) + : findExactFilelessBook(libraryEntity, fileName, libraryPathEntity); + if (filelessMatch != null) { if (filelessMatch.getLibraryPath() == null) { filelessMatch.setLibraryPath(libraryPathEntity); @@ -80,7 +134,22 @@ public class BookFileTransactionalHandler { return; } - BookEntity matchingBook = findMatchingBook(libraryPathEntity.getId(), fileSubPath, fileName); + BookEntity matchingBook = null; + + if (mode == LibraryOrganizationMode.BOOK_PER_FILE) { + // BOOK_PER_FILE: never attach to existing books + } else if (mode == LibraryOrganizationMode.BOOK_PER_FOLDER) { + matchingBook = findBookInSameFolder(libraryPathEntity.getId(), fileSubPath); + if (matchingBook == null) { + BookFileType fileType = BookFileExtension.fromFileName(fileName) + .map(BookFileExtension::getType).orElse(null); + if (fileType == BookFileType.AUDIOBOOK) { + matchingBook = findNearestAncestorBookWithEbook(libraryPathEntity.getId(), fileSubPath); + } + } + } else { + matchingBook = findMatchingBook(libraryPathEntity.getId(), fileSubPath, fileName); + } if (matchingBook != null) { autoAttachFile(matchingBook, fileName, fileSubPath, path); @@ -117,6 +186,18 @@ public class BookFileTransactionalHandler { LibraryPathEntity libraryPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(libraryEntity, libraryPath); String fileSubPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), folderPath); + String folderHash = FileFingerprint.generateFolderHash(folderPath); + Optional poolMatch = pendingDeletionPool.matchByHash(folderHash); + if (poolMatch.isPresent()) { + var match = poolMatch.get(); + pendingDeletionPool.recoverBook(match, libraryPathEntity, fileSubPath, folderName, folderHash); + log.info("[CREATE] Folder audiobook '{}' matched pending deletion, recovered book id={}", + folderName, match.book().bookId()); + notificationService.sendMessageToPermissions(Topic.LOG, + LogNotification.info("Finished processing folder audiobook: " + folderPath), Set.of(ADMIN, MANAGE_LIBRARY)); + return; + } + BookEntity matchingBook = findMatchingBookForFolderAudiobook(libraryPathEntity.getId(), fileSubPath, folderName); if (matchingBook != null) { @@ -163,8 +244,79 @@ public class BookFileTransactionalHandler { return null; } + private BookEntity findExactFilelessBook(LibraryEntity library, String fileName, LibraryPathEntity fileLibraryPath) { + List filelessBooks = bookRepository.findFilelessBooksByLibraryId(library.getId()); + String fileBaseName = BookFileGroupingUtils.extractGroupingKey(fileName); + + for (BookEntity book : filelessBooks) { + if (book.getLibraryPath() != null && !book.getLibraryPath().getId().equals(fileLibraryPath.getId())) { + continue; + } + + if (book.getMetadata() != null && book.getMetadata().getTitle() != null) { + String bookTitle = BookFileGroupingUtils.extractGroupingKey(book.getMetadata().getTitle()); + if (fileBaseName.equals(bookTitle)) { + return book; + } + } + } + return null; + } + + private BookEntity findBookInSameFolder(Long libraryPathId, String fileSubPath) { + if (fileSubPath == null) { + return null; + } + + List booksInDirectory = bookRepository.findAllByLibraryPathIdAndFileSubPath(libraryPathId, fileSubPath); + List activeBooks = booksInDirectory.stream() + .filter(book -> book.getDeleted() == null || !book.getDeleted()) + .filter(BookEntity::hasFiles) + .toList(); + + if (activeBooks.isEmpty()) { + return null; + } + + if (activeBooks.size() == 1) { + return activeBooks.getFirst(); + } + + return activeBooks.stream() + .max(Comparator.comparingLong(book -> book.getBookFiles() != null ? book.getBookFiles().size() : 0)) + .orElse(null); + } + + private BookEntity findNearestAncestorBookWithEbook(Long libraryPathId, String subPath) { + String current = subPath; + while (true) { + int lastSep = current.lastIndexOf('/'); + if (lastSep == -1) { + lastSep = current.lastIndexOf('\\'); + } + if (lastSep <= 0) { + break; + } + current = current.substring(0, lastSep); + + List booksAtLevel = bookRepository.findAllByLibraryPathIdAndFileSubPath(libraryPathId, current); + for (BookEntity book : booksAtLevel) { + if (book.getDeleted() != null && book.getDeleted()) { + continue; + } + if (book.getBookFiles() != null && book.getBookFiles().stream() + .anyMatch(bf -> bf.getBookType() != BookFileType.AUDIOBOOK)) { + log.debug("BOOK_PER_FOLDER: Audio absorption matched to ancestor book id={} at '{}'", + book.getId(), current); + return book; + } + } + } + return null; + } + private BookEntity findMatchingBook(Long libraryPathId, String fileSubPath, String fileName) { - if (fileSubPath == null || fileSubPath.isEmpty()) { + if (fileSubPath == null) { return null; } diff --git a/booklore-api/src/main/java/org/booklore/service/watcher/LibraryFileEventProcessor.java b/booklore-api/src/main/java/org/booklore/service/watcher/LibraryFileEventProcessor.java index bfb3af80d..a2ceed324 100644 --- a/booklore-api/src/main/java/org/booklore/service/watcher/LibraryFileEventProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/watcher/LibraryFileEventProcessor.java @@ -1,14 +1,17 @@ package org.booklore.service.watcher; import org.booklore.exception.ApiError; +import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.LibraryEntity; import org.booklore.model.entity.LibraryPathEntity; +import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.enums.BookFileExtension; import org.booklore.model.enums.BookFileType; -import org.booklore.model.enums.PermissionType; -import org.booklore.model.websocket.Topic; +import org.booklore.model.enums.LibraryOrganizationMode; +import org.booklore.repository.BookRepository; import org.booklore.repository.LibraryRepository; -import org.booklore.service.NotificationService; +import org.booklore.service.file.FileFingerprint; +import org.booklore.service.library.LibraryProcessingService; import org.booklore.util.FileUtils; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; @@ -18,10 +21,10 @@ import org.springframework.stereotype.Service; import java.io.IOException; import java.nio.file.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Set; +import java.nio.file.attribute.FileTime; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.*; import java.util.concurrent.*; @Slf4j @@ -30,14 +33,19 @@ import java.util.concurrent.*; public class LibraryFileEventProcessor { private static final long DEBOUNCE_MS = 500L; - private static final long FOLDER_CREATE_DEBOUNCE_MS = 2000L; // Longer debounce for folder creates to allow file copying + private static final long FOLDER_CREATE_DEBOUNCE_MS = 5000L; + private static final long PENDING_DELETION_GRACE_MS = 8000L; + private static final long STABILITY_CHECK_INTERVAL_MS = 3000L; + private static final long STABILITY_MAX_WAIT_MS = 120000L; private static final int MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK = 2; private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); private final LibraryRepository libraryRepository; + private final BookRepository bookRepository; private final BookFileTransactionalHandler bookFileTransactionalHandler; private final BookFilePersistenceService bookFilePersistenceService; - private final NotificationService notificationService; + private final LibraryProcessingService libraryProcessingService; + private final PendingDeletionPool pendingDeletionPool; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); private final ConcurrentMap> pendingDeletes = new ConcurrentHashMap<>(); @@ -61,61 +69,65 @@ public class LibraryFileEventProcessor { }); } - public void processFile(WatchEvent.Kind eventKind, long libraryId, String libraryPath, String filePath) { - Path path = Paths.get(filePath).toAbsolutePath().normalize(); - boolean isDirectory = Files.isDirectory(path); + public void processEvent(WatchEvent.Kind eventKind, long libraryId, Path fullPath, boolean isDirectory) { + Path path = fullPath.toAbsolutePath().normalize(); if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) { - // Schedule DELETE after debounce ScheduledFuture existing = pendingDeletes.put(path, scheduler.schedule(() -> { - eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath, false)); + eventQueue.offer(new FileEvent(eventKind, libraryId, path, isDirectory)); pendingDeletes.remove(path); }, DEBOUNCE_MS, TimeUnit.MILLISECONDS)); if (existing != null) existing.cancel(false); } else if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) { - // If a DELETE is pending for this path, cancel both DELETE and CREATE ScheduledFuture pendingDelete = pendingDeletes.remove(path); if (pendingDelete != null) { pendingDelete.cancel(false); - log.debug("[DEBOUNCE] CREATE ignored because pending DELETE exists for '{}'", path); - return; + log.debug("[DEBOUNCE] CREATE after pending DELETE for '{}', treating as file modification", path); } if (isDirectory) { - // Debounce folder creates to allow files to be copied first log.debug("[DEBOUNCE] Scheduling folder create for '{}' with {}ms delay", path, FOLDER_CREATE_DEBOUNCE_MS); ScheduledFuture existingFolder = pendingFolderCreates.put(path, scheduler.schedule(() -> { - eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath, true)); + eventQueue.offer(new FileEvent(eventKind, libraryId, path, true)); pendingFolderCreates.remove(path); - // Clear tracked files for this folder after processing filesFromPendingFolder.removeIf(f -> f.startsWith(path)); }, FOLDER_CREATE_DEBOUNCE_MS, TimeUnit.MILLISECONDS)); if (existingFolder != null) existingFolder.cancel(false); } else { - // Check if this file is inside a pending folder - boolean insidePendingFolder = pendingFolderCreates.keySet().stream().anyMatch(path::startsWith); - if (insidePendingFolder) { - // Track this file but don't process it yet - the folder handler will decide - filesFromPendingFolder.add(path); - log.debug("[DEBOUNCE] File '{}' tracked as part of pending folder", path.getFileName()); - } else { - // Process file immediately - eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath, false)); + boolean insidePendingFolder = false; + for (var entry : pendingFolderCreates.entrySet()) { + if (path.startsWith(entry.getKey())) { + insidePendingFolder = true; + filesFromPendingFolder.add(path); + ScheduledFuture oldTimer = entry.getValue(); + if (oldTimer != null) oldTimer.cancel(false); + Path folderPath = entry.getKey(); + pendingFolderCreates.put(folderPath, scheduler.schedule(() -> { + eventQueue.offer(new FileEvent(eventKind, libraryId, folderPath, true)); + pendingFolderCreates.remove(folderPath); + filesFromPendingFolder.removeIf(f -> f.startsWith(folderPath)); + }, FOLDER_CREATE_DEBOUNCE_MS, TimeUnit.MILLISECONDS)); + log.debug("[DEBOUNCE] File '{}' tracked, reset folder debounce for '{}'", path.getFileName(), folderPath); + break; + } + } + if (!insidePendingFolder) { + scheduleWithStabilityCheck(path, () -> + eventQueue.offer(new FileEvent(eventKind, libraryId, path, false))); } } } else { - // Other events - eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath, false)); + eventQueue.offer(new FileEvent(eventKind, libraryId, path, false)); } } private void handleEvent(FileEvent event) { - Path path = Paths.get(event.filePath()).toAbsolutePath().normalize(); + Path path = event.fullPath(); String fileName = path.getFileName().toString(); log.info("[PROCESS] '{}' event for '{}'{}", event.eventKind().name(), fileName, - event.isDebouncedFolder() ? " (debounced folder)" : ""); + event.isDirectory() ? " (directory)" : ""); LibraryEntity library = libraryRepository.findById(event.libraryId()) .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(event.libraryId())); @@ -125,8 +137,7 @@ public class LibraryFileEventProcessor { return; } - // Use isDebouncedFolder flag for debounced events, otherwise fall back to heuristic - boolean isDirectory = event.isDebouncedFolder() || isFolder(path); + boolean isDirectory = event.isDirectory(); if (isDirectory) { switch (event.eventKind().name()) { @@ -150,6 +161,10 @@ public class LibraryFileEventProcessor { } private void handleFileCreate(LibraryEntity library, Path path) { + if (!fileHasContent(path)) { + log.debug("[SKIP] Zero-byte file: '{}'", path); + return; + } log.info("[FILE_CREATE] '{}'", path); bookFileTransactionalHandler.handleNewBookFile(library.getId(), path); } @@ -167,23 +182,12 @@ public class LibraryFileEventProcessor { bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(libPathEntity.getId(), fileSubPath, fileName) .ifPresentOrElse(bookFile -> { var book = bookFile.getBook(); - var remainingFiles = bookFilePersistenceService.countBookFilesByBookId(book.getId()); - - if (remainingFiles <= 1) { - // Last file - mark book as deleted - bookFilePersistenceService.markBookAsDeleted(book); - notificationService.sendMessageToPermissions(Topic.BOOKS_REMOVE, Set.of(book.getId()), - Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY)); - log.info("[MARKED_DELETED] Book '{}' marked as deleted (last file removed)", fileName); - } else { - // Multiple files - just delete this file - bookFilePersistenceService.deleteBookFile(bookFile); - notificationService.sendMessageToPermissions(Topic.BOOK_UPDATE, Set.of(book.getId()), - Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY)); - log.info("[FILE_REMOVED] BookFile '{}' removed from book (id={}), {} files remaining", - fileName, book.getId(), remainingFiles - 1); - } - }, () -> log.warn("[NOT_FOUND] BookFile for deleted path '{}' not found", path)); + ScheduledFuture timer = scheduler.schedule( + () -> pendingDeletionPool.expireFileDeletion(path), + PENDING_DELETION_GRACE_MS, TimeUnit.MILLISECONDS); + pendingDeletionPool.addFileDeletion(path, library.getId(), bookFile, book, timer); + log.info("[PENDING_DELETE] Book '{}' deferred deletion (grace period {}ms)", fileName, PENDING_DELETION_GRACE_MS); + }, () -> log.debug("[NOT_FOUND] BookFile for deleted path '{}' not found (likely renamed/moved)", path)); } catch (Exception e) { log.warn("[ERROR] While handling file delete '{}': {}", path, e.getMessage()); @@ -193,7 +197,30 @@ public class LibraryFileEventProcessor { private void handleFolderCreate(LibraryEntity library, Path folderPath) { log.info("[FOLDER_CREATE] '{}'", folderPath); - // Check if folder is a folder-based audiobook (2+ audio files, no ebook files) + pendingFolderCreates.entrySet().removeIf(entry -> { + if (entry.getKey().startsWith(folderPath) && !entry.getKey().equals(folderPath)) { + entry.getValue().cancel(false); + filesFromPendingFolder.removeIf(f -> f.startsWith(entry.getKey())); + log.debug("[DEBOUNCE] Cancelled child folder debounce for '{}'", entry.getKey()); + return true; + } + return false; + }); + + var mode = library.getOrganizationMode() != null + ? library.getOrganizationMode() : LibraryOrganizationMode.AUTO_DETECT; + + if (mode == LibraryOrganizationMode.BOOK_PER_FILE) { + processFilesInFolderIndividually(library, folderPath); + return; + } + + if (mode == LibraryOrganizationMode.BOOK_PER_FOLDER) { + processFilesInFolderAsOneBook(library, folderPath); + return; + } + + // AUTO_DETECT: existing audiobook folder detection logic FolderAnalysis analysis = analyzeFolderForAudiobook(folderPath); if (analysis.isFolderBasedAudiobook()) { @@ -201,7 +228,6 @@ public class LibraryFileEventProcessor { folderPath.getFileName(), analysis.audioFileCount()); try { bookFileTransactionalHandler.handleNewFolderAudiobook(library.getId(), folderPath); - // Clear any tracked files inside this folder - they're now part of the folder audiobook int cleared = 0; var iterator = filesFromPendingFolder.iterator(); while (iterator.hasNext()) { @@ -217,40 +243,184 @@ public class LibraryFileEventProcessor { log.warn("[ERROR] Processing folder audiobook '{}': {}", folderPath, e.getMessage()); } } else { - // Not a folder-based audiobook - process tracked files individually - var trackedFiles = filesFromPendingFolder.stream() - .filter(p -> p.startsWith(folderPath)) + processTrackedAndWalkedFiles(library, folderPath); + } + } + + private void processFilesInFolderIndividually(LibraryEntity library, Path folderPath) { + if (Files.exists(folderPath.resolve(".ignore"))) { + log.debug("[SKIP] Folder has .ignore file: '{}'", folderPath); + clearTrackedFilesFor(folderPath); + return; + } + clearTrackedFilesFor(folderPath); + try (var stream = Files.walk(folderPath)) { + stream.filter(Files::isRegularFile) + .filter(p -> !isUnderIgnoredDirectory(p, folderPath)) .filter(p -> isBookFile(p.getFileName().toString())) - .toList(); + .filter(this::fileHasContent) + .forEach(p -> { + try { + bookFileTransactionalHandler.handleNewBookFile(library.getId(), p); + } catch (Exception e) { + log.warn("[ERROR] Processing file '{}': {}", p, e.getMessage()); + } + }); + } catch (IOException e) { + log.warn("[ERROR] Walking folder '{}': {}", folderPath, e.getMessage()); + } + } - if (!trackedFiles.isEmpty()) { - log.info("[FOLDER_CREATE] Processing {} tracked files individually", trackedFiles.size()); - for (Path filePath : trackedFiles) { - try { - bookFileTransactionalHandler.handleNewBookFile(library.getId(), filePath); - } catch (Exception e) { - log.warn("[ERROR] Processing tracked file '{}': {}", filePath, e.getMessage()); - } - filesFromPendingFolder.remove(filePath); - } - } + private void processFilesInFolderAsOneBook(LibraryEntity library, Path folderPath) { + if (Files.exists(folderPath.resolve(".ignore"))) { + log.debug("[SKIP] Folder has .ignore file: '{}'", folderPath); + clearTrackedFilesFor(folderPath); + return; + } + clearTrackedFilesFor(folderPath); - // Also walk the folder for any files that weren't tracked (e.g., existing files) - try (var stream = Files.walk(folderPath)) { - stream.filter(Files::isRegularFile) - .filter(p -> isBookFile(p.getFileName().toString())) - .filter(p -> !trackedFiles.contains(p)) // Skip already processed tracked files - .forEach(p -> { - try { - bookFileTransactionalHandler.handleNewBookFile(library.getId(), p); - } catch (Exception e) { - log.warn("[ERROR] Processing file '{}': {}", p, e.getMessage()); - } - }); - } catch (IOException e) { - log.warn("[ERROR] Walking folder '{}': {}", folderPath, e.getMessage()); + List bookFiles = new ArrayList<>(); + try (var stream = Files.walk(folderPath)) { + stream.filter(Files::isRegularFile) + .filter(p -> !isUnderIgnoredDirectory(p, folderPath)) + .filter(p -> isBookFile(p.getFileName().toString())) + .filter(this::fileHasContent) + .forEach(bookFiles::add); + } catch (IOException e) { + log.warn("[ERROR] Walking folder '{}': {}", folderPath, e.getMessage()); + } + + if (bookFiles.isEmpty()) { + return; + } + + // Try folder-level pool matching first + Map fileHashes = new HashMap<>(); + for (Path p : bookFiles) { + try { + fileHashes.put(p, FileFingerprint.generateHash(p)); + } catch (Exception e) { + log.warn("[ERROR] Hash computation for '{}': {}", p, e.getMessage()); } } + + Optional folderMatch = pendingDeletionPool.matchFolderByHashes(fileHashes); + if (folderMatch.isPresent()) { + var match = folderMatch.get(); + String matchedLibPath = bookFilePersistenceService.findMatchingLibraryPath(library, folderPath); + LibraryPathEntity matchedLibPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, matchedLibPath); + + for (var bookEntry : match.pending().affectedBooks().entrySet()) { + var bookSnap = bookEntry.getValue(); + bookFilePersistenceService.recoverFolderBook(bookSnap, matchedLibPathEntity, folderPath, fileHashes); + } + log.info("[FOLDER_CREATE] Folder '{}' matched pending deletion, recovered {} books", + folderPath, match.pending().affectedBooks().size()); + return; + } + + // Try hash-based move detection for each file + List unmatched = new ArrayList<>(); + for (Path p : bookFiles) { + try { + String hash = fileHashes.get(p); + if (hash == null) { + unmatched.add(p); + continue; + } + + Optional poolMatch = pendingDeletionPool.matchByHash(hash); + if (poolMatch.isPresent()) { + var pmatch = poolMatch.get(); + String libPath = bookFilePersistenceService.findMatchingLibraryPath(library, p); + LibraryPathEntity lpEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, libPath); + String subPath = FileUtils.getRelativeSubPath(lpEntity.getPath(), p); + pendingDeletionPool.recoverBook(pmatch, lpEntity, subPath, p.getFileName().toString(), hash); + log.info("[FOLDER_CREATE] File '{}' matched pending deletion, recovered book id={}", p, pmatch.book().bookId()); + continue; + } + + Optional existing = bookRepository.findByCurrentHashIncludingRecentlyDeleted( + hash, Instant.now().minus(60, ChronoUnit.SECONDS)); + if (existing.isPresent()) { + bookFilePersistenceService.updatePathIfChanged(existing.get(), library, p, hash); + log.info("[FOLDER_CREATE] File '{}' recognized as moved file, updated existing book's path", p); + } else { + unmatched.add(p); + } + } catch (Exception e) { + log.warn("[ERROR] Hash check for '{}': {}", p, e.getMessage()); + unmatched.add(p); + } + } + + if (unmatched.isEmpty()) { + return; + } + + String libraryPath = bookFilePersistenceService.findMatchingLibraryPath(library, folderPath); + LibraryPathEntity libPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, libraryPath); + + List libraryFiles = new ArrayList<>(); + for (Path p : unmatched) { + String fileName = p.getFileName().toString(); + var ext = BookFileExtension.fromFileName(fileName); + if (ext.isPresent()) { + libraryFiles.add(LibraryFile.builder() + .libraryEntity(library) + .libraryPathEntity(libPathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(libPathEntity.getPath(), p)) + .fileName(fileName) + .bookFileType(ext.get().getType()) + .build()); + } + } + + if (!libraryFiles.isEmpty()) { + libraryProcessingService.processLibraryFiles(libraryFiles, library); + } + } + + private void processTrackedAndWalkedFiles(LibraryEntity library, Path folderPath) { + var trackedFiles = filesFromPendingFolder.stream() + .filter(p -> p.startsWith(folderPath)) + .filter(p -> !isUnderIgnoredDirectory(p, folderPath)) + .filter(p -> isBookFile(p.getFileName().toString())) + .filter(this::fileHasContent) + .toList(); + + if (!trackedFiles.isEmpty()) { + log.info("[FOLDER_CREATE] Processing {} tracked files individually", trackedFiles.size()); + for (Path filePath : trackedFiles) { + try { + bookFileTransactionalHandler.handleNewBookFile(library.getId(), filePath); + } catch (Exception e) { + log.warn("[ERROR] Processing tracked file '{}': {}", filePath, e.getMessage()); + } + filesFromPendingFolder.remove(filePath); + } + } + + try (var stream = Files.walk(folderPath)) { + stream.filter(Files::isRegularFile) + .filter(p -> !isUnderIgnoredDirectory(p, folderPath)) + .filter(p -> isBookFile(p.getFileName().toString())) + .filter(this::fileHasContent) + .filter(p -> !trackedFiles.contains(p)) + .forEach(p -> { + try { + bookFileTransactionalHandler.handleNewBookFile(library.getId(), p); + } catch (Exception e) { + log.warn("[ERROR] Processing file '{}': {}", p, e.getMessage()); + } + }); + } catch (IOException e) { + log.warn("[ERROR] Walking folder '{}': {}", folderPath, e.getMessage()); + } + } + + private void clearTrackedFilesFor(Path folderPath) { + filesFromPendingFolder.removeIf(p -> p.startsWith(folderPath)); } private FolderAnalysis analyzeFolderForAudiobook(Path folderPath) { @@ -258,7 +428,10 @@ public class LibraryFileEventProcessor { boolean hasNonAudioBook = false; try (var stream = Files.walk(folderPath)) { - var files = stream.filter(Files::isRegularFile).toList(); + var files = stream.filter(Files::isRegularFile) + .filter(p -> !isUnderIgnoredDirectory(p, folderPath)) + .filter(this::fileHasContent) + .toList(); for (Path file : files) { String fileName = file.getFileName().toString(); @@ -293,28 +466,99 @@ public class LibraryFileEventProcessor { String libPath = bookFilePersistenceService.findMatchingLibraryPath(library, folderPath); LibraryPathEntity libPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, libPath); - String relativePrefix = FileUtils.getRelativeSubPath(libPathEntity.getPath(), folderPath); - int count = bookFilePersistenceService.markAllBooksUnderPathAsDeleted(libPathEntity.getId(), relativePrefix); - log.info("[MARKED_DELETED] {} books under '{}'", count, folderPath); + String relativePrefix = Path.of(libPathEntity.getPath()).relativize(folderPath).toString().replace("\\", "/"); + List booksWithFiles = bookRepository.findBooksWithFilesUnderPath(libPathEntity.getId(), relativePrefix); + + if (booksWithFiles.isEmpty()) { + log.debug("[FOLDER_DELETE] No books found under '{}'", folderPath); + return; + } + + ScheduledFuture timer = scheduler.schedule( + () -> pendingDeletionPool.expireFolderDeletion(folderPath), + PENDING_DELETION_GRACE_MS, TimeUnit.MILLISECONDS); + pendingDeletionPool.addFolderDeletion(folderPath, library.getId(), booksWithFiles, timer); + log.info("[PENDING_DELETE] {} books under '{}' deferred deletion (grace period {}ms)", + booksWithFiles.size(), folderPath, PENDING_DELETION_GRACE_MS); } catch (Exception e) { log.warn("[ERROR] Folder delete '{}': {}", folderPath, e.getMessage()); } } - private boolean isFolder(Path path) { - return !path.getFileName().toString().contains("."); + private boolean fileHasContent(Path path) { + try { + return Files.size(path) > 0; + } catch (IOException e) { + return false; + } + } + + private boolean isUnderIgnoredDirectory(Path filePath, Path root) { + Path parent = filePath.getParent(); + while (parent != null && !parent.equals(root)) { + if (Files.exists(parent.resolve(".ignore"))) { + return true; + } + parent = parent.getParent(); + } + return false; } private boolean isBookFile(String fileName) { return BookFileExtension.fromFileName(fileName).isPresent(); } + private void scheduleWithStabilityCheck(Path path, Runnable onStable) { + scheduler.schedule(() -> checkStability(path, onStable, System.currentTimeMillis()), 0, TimeUnit.MILLISECONDS); + } + + private void checkStability(Path path, Runnable onStable, long startTime) { + try { + if (!Files.exists(path)) { + onStable.run(); + return; + } + + long elapsed = System.currentTimeMillis() - startTime; + if (elapsed >= STABILITY_MAX_WAIT_MS) { + log.warn("[STABILITY] Max wait exceeded for '{}', processing anyway", path); + onStable.run(); + return; + } + + FileTime mtime = Files.getLastModifiedTime(path); + long msSinceMod = System.currentTimeMillis() - mtime.toMillis(); + + if (msSinceMod < STABILITY_CHECK_INTERVAL_MS) { + log.debug("[STABILITY] File '{}' modified {}ms ago, rechecking in {}ms", path, msSinceMod, STABILITY_CHECK_INTERVAL_MS); + scheduler.schedule(() -> checkStability(path, onStable, startTime), + STABILITY_CHECK_INTERVAL_MS, TimeUnit.MILLISECONDS); + } else { + onStable.run(); + } + } catch (IOException e) { + log.debug("[STABILITY] Error checking mtime for '{}': {}", path, e.getMessage()); + onStable.run(); + } + } + @PreDestroy public void shutdown() { scheduler.shutdownNow(); log.info("Shutting down LibraryFileEventProcessor..."); } - public record FileEvent(WatchEvent.Kind eventKind, long libraryId, String libraryPath, String filePath, boolean isDebouncedFolder) { + public boolean hasPendingEventsForPaths(Set paths) { + boolean inQueue = eventQueue.stream() + .anyMatch(e -> paths.stream().anyMatch(p -> e.fullPath().startsWith(p))); + boolean inDeletes = pendingDeletes.keySet().stream() + .anyMatch(p -> paths.stream().anyMatch(p::startsWith)); + boolean inFolderCreates = pendingFolderCreates.keySet().stream() + .anyMatch(p -> paths.stream().anyMatch(p::startsWith)); + boolean inPool = pendingDeletionPool.hasPendingForPaths(paths); + return inQueue || inDeletes || inFolderCreates || inPool; + } + + public record FileEvent(WatchEvent.Kind eventKind, long libraryId, Path fullPath, boolean isDirectory) { } } \ No newline at end of file diff --git a/booklore-api/src/main/java/org/booklore/service/watcher/PendingDeletionPool.java b/booklore-api/src/main/java/org/booklore/service/watcher/PendingDeletionPool.java new file mode 100644 index 000000000..c9f3ed83c --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/service/watcher/PendingDeletionPool.java @@ -0,0 +1,305 @@ +package org.booklore.service.watcher; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.booklore.mapper.BookMapper; +import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; +import org.booklore.model.enums.BookFileType; +import org.booklore.model.enums.PermissionType; +import org.booklore.model.websocket.Topic; +import org.booklore.repository.BookFileRepository; +import org.booklore.repository.BookRepository; +import org.booklore.service.NotificationService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.nio.file.Path; +import java.time.Instant; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledFuture; + +@Slf4j +@Service +@AllArgsConstructor +public class PendingDeletionPool { + + private final BookRepository bookRepository; + private final BookFileRepository bookFileRepository; + private final NotificationService notificationService; + private final BookMapper bookMapper; + + private final ConcurrentHashMap pendingByPath = new ConcurrentHashMap<>(); + private final ConcurrentHashMap hashIndex = new ConcurrentHashMap<>(); + + public record FileSnapshot(Long bookFileId, String fileName, String fileSubPath, + String currentHash, boolean folderBased, BookFileType bookType) {} + + public record BookSnapshot(Long bookId, Long libraryPathId, String fileSubPath, + List files) {} + + public record PendingDeletion(Path originalPath, boolean isDirectory, long libraryId, + Instant timestamp, ScheduledFuture timer, + Map hashToBookFileId, + Map affectedBooks) {} + + public record MatchResult(PendingDeletion pending, BookSnapshot book, FileSnapshot file) {} + + public record FolderMatchResult(PendingDeletion pending, Map hashToFile) {} + + public void addFileDeletion(Path path, long libraryId, BookFileEntity bookFile, BookEntity book, ScheduledFuture timer) { + FileSnapshot fileSnapshot = new FileSnapshot( + bookFile.getId(), bookFile.getFileName(), bookFile.getFileSubPath(), + bookFile.getCurrentHash(), bookFile.isFolderBased(), bookFile.getBookType()); + + BookSnapshot bookSnapshot = new BookSnapshot( + book.getId(), book.getLibraryPath() != null ? book.getLibraryPath().getId() : null, + bookFile.getFileSubPath(), List.of(fileSnapshot)); + + Map hashMap = new ConcurrentHashMap<>(); + if (bookFile.getCurrentHash() != null) { + hashMap.put(bookFile.getCurrentHash(), bookFile.getId()); + } + + Map affectedBooks = new ConcurrentHashMap<>(); + affectedBooks.put(book.getId(), bookSnapshot); + + PendingDeletion pending = new PendingDeletion(path, false, libraryId, Instant.now(), timer, hashMap, affectedBooks); + pendingByPath.put(path, pending); + + if (bookFile.getCurrentHash() != null) { + hashIndex.put(bookFile.getCurrentHash(), path); + } + + log.debug("[POOL] Added file deletion: path='{}', hash='{}', bookId={}", path, bookFile.getCurrentHash(), book.getId()); + } + + public void addFolderDeletion(Path folderPath, long libraryId, List booksWithFiles, ScheduledFuture timer) { + Map hashMap = new ConcurrentHashMap<>(); + Map affectedBooks = new ConcurrentHashMap<>(); + + for (BookEntity book : booksWithFiles) { + List fileSnapshots = new ArrayList<>(); + for (BookFileEntity bf : book.getBookFiles()) { + if (!bf.isBookFormat()) continue; + FileSnapshot fs = new FileSnapshot( + bf.getId(), bf.getFileName(), bf.getFileSubPath(), + bf.getCurrentHash(), bf.isFolderBased(), bf.getBookType()); + fileSnapshots.add(fs); + if (bf.getCurrentHash() != null) { + hashMap.put(bf.getCurrentHash(), bf.getId()); + hashIndex.put(bf.getCurrentHash(), folderPath); + } + } + if (!fileSnapshots.isEmpty()) { + BookSnapshot bs = new BookSnapshot( + book.getId(), book.getLibraryPath() != null ? book.getLibraryPath().getId() : null, + book.getBookFiles().getFirst().getFileSubPath(), fileSnapshots); + affectedBooks.put(book.getId(), bs); + } + } + + PendingDeletion pending = new PendingDeletion(folderPath, true, libraryId, Instant.now(), timer, hashMap, affectedBooks); + pendingByPath.put(folderPath, pending); + + log.debug("[POOL] Added folder deletion: path='{}', books={}, hashes={}", folderPath, affectedBooks.size(), hashMap.size()); + } + + public Optional matchByHash(String hash) { + Path path = hashIndex.remove(hash); + if (path == null) return Optional.empty(); + + PendingDeletion pending = pendingByPath.get(path); + if (pending == null) return Optional.empty(); + + for (Map.Entry entry : pending.affectedBooks().entrySet()) { + BookSnapshot bookSnap = entry.getValue(); + for (FileSnapshot fileSnap : bookSnap.files()) { + if (hash.equals(fileSnap.currentHash())) { + pending.hashToBookFileId().remove(hash); + + boolean allConsumed = pending.hashToBookFileId().isEmpty(); + if (allConsumed) { + pending.timer().cancel(false); + pendingByPath.remove(path); + log.debug("[POOL] All files matched for path='{}', cancelled timer", path); + } + + return Optional.of(new MatchResult(pending, bookSnap, fileSnap)); + } + } + } + + return Optional.empty(); + } + + public Optional matchFolderByHashes(Map fileHashes) { + if (fileHashes.isEmpty()) return Optional.empty(); + + PendingDeletion bestMatch = null; + int bestOverlap = 0; + Map bestFileMap = null; + + for (PendingDeletion pending : pendingByPath.values()) { + if (!pending.isDirectory()) continue; + + Map matchedFiles = new HashMap<>(); + int totalPendingFiles = 0; + + for (BookSnapshot bookSnap : pending.affectedBooks().values()) { + for (FileSnapshot fileSnap : bookSnap.files()) { + totalPendingFiles++; + if (fileHashes.containsValue(fileSnap.currentHash())) { + matchedFiles.put(fileSnap.currentHash(), fileSnap); + } + } + } + + if (totalPendingFiles > 0) { + double ratio = (double) matchedFiles.size() / totalPendingFiles; + if (ratio >= 0.5 && matchedFiles.size() > bestOverlap) { + bestOverlap = matchedFiles.size(); + bestMatch = pending; + bestFileMap = matchedFiles; + } + } + } + + if (bestMatch != null) { + bestMatch.timer().cancel(false); + for (String hash : bestMatch.hashToBookFileId().keySet()) { + hashIndex.remove(hash); + } + pendingByPath.remove(bestMatch.originalPath()); + log.debug("[POOL] Folder matched by hashes: path='{}', overlap={}", bestMatch.originalPath(), bestOverlap); + return Optional.of(new FolderMatchResult(bestMatch, bestFileMap)); + } + + return Optional.empty(); + } + + @Transactional + public void expireFileDeletion(Path path) { + PendingDeletion pending = pendingByPath.remove(path); + if (pending == null) return; + + for (String hash : pending.hashToBookFileId().keySet()) { + hashIndex.remove(hash); + } + + for (BookSnapshot bookSnap : pending.affectedBooks().values()) { + Optional bookOpt = bookRepository.findById(bookSnap.bookId()); + if (bookOpt.isEmpty()) continue; + BookEntity book = bookOpt.get(); + + long remainingFiles = bookFileRepository.countByBookId(book.getId()); + if (remainingFiles <= 1) { + book.setDeleted(true); + book.setDeletedAt(Instant.now()); + bookRepository.save(book); + notificationService.sendMessageToPermissions(Topic.BOOKS_REMOVE, Set.of(book.getId()), + Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY)); + log.info("[EXPIRED] Book id={} marked as deleted (last file removed)", book.getId()); + } else { + for (FileSnapshot fs : bookSnap.files()) { + bookFileRepository.findById(fs.bookFileId()).ifPresent(bf -> { + bookFileRepository.delete(bf); + log.info("[EXPIRED] BookFile id={} removed from book id={}", fs.bookFileId(), book.getId()); + }); + } + notificationService.sendMessageToPermissions(Topic.BOOK_UPDATE, Set.of(book.getId()), + Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY)); + } + } + } + + @Transactional + public void expireFolderDeletion(Path path) { + PendingDeletion pending = pendingByPath.remove(path); + if (pending == null) return; + + for (String hash : pending.hashToBookFileId().keySet()) { + hashIndex.remove(hash); + } + + for (BookSnapshot bookSnap : pending.affectedBooks().values()) { + Optional bookOpt = bookRepository.findById(bookSnap.bookId()); + if (bookOpt.isEmpty()) continue; + BookEntity book = bookOpt.get(); + book.setDeleted(true); + book.setDeletedAt(Instant.now()); + bookRepository.save(book); + log.info("[EXPIRED] Book id={} marked as deleted (folder deletion expired)", book.getId()); + } + + Set bookIds = pending.affectedBooks().keySet(); + if (!bookIds.isEmpty()) { + notificationService.sendMessageToPermissions(Topic.BOOKS_REMOVE, bookIds, + Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY)); + } + } + + @Transactional + public void recoverBook(MatchResult match, org.booklore.model.entity.LibraryPathEntity newLibraryPath, String newFileSubPath, String newFileName, String hash) { + BookEntity book = bookRepository.findById(match.book().bookId()) + .orElseThrow(() -> new IllegalStateException("Book not found: " + match.book().bookId())); + + BookFileEntity bookFile = bookFileRepository.findById(match.file().bookFileId()) + .orElseThrow(() -> new IllegalStateException("BookFile not found: " + match.file().bookFileId())); + + book.setLibraryPath(newLibraryPath); + book.setDeleted(false); + book.setDeletedAt(null); + bookFile.setFileSubPath(newFileSubPath); + bookFile.setFileName(newFileName); + bookFile.setCurrentHash(hash); + bookRepository.save(book); + + notificationService.sendMessageToPermissions(Topic.BOOK_ADD, + bookMapper.toBookWithDescription(book, false), Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY)); + log.info("[RECOVERED] Book id={} recovered from pending deletion pool", book.getId()); + } + + public boolean cancelByPath(Path filePath) { + PendingDeletion pending = pendingByPath.get(filePath); + if (pending != null && !pending.isDirectory()) { + pending.timer().cancel(false); + for (String hash : pending.hashToBookFileId().keySet()) { + hashIndex.remove(hash); + } + pendingByPath.remove(filePath); + log.debug("[POOL] Cancelled pending deletion by path='{}'", filePath); + return true; + } + + for (var entry : pendingByPath.entrySet()) { + PendingDeletion pd = entry.getValue(); + if (pd.isDirectory() && filePath.startsWith(entry.getKey())) { + for (BookSnapshot bookSnap : pd.affectedBooks().values()) { + for (FileSnapshot fileSnap : bookSnap.files()) { + String expectedFilePath = bookSnap.fileSubPath() + "/" + fileSnap.fileName(); + String relPath = entry.getKey().getParent() != null + ? entry.getKey().getParent().relativize(filePath).toString() : filePath.toString(); + if (relPath.endsWith(fileSnap.fileName())) { + pd.hashToBookFileId().remove(fileSnap.currentHash()); + hashIndex.remove(fileSnap.currentHash()); + if (pd.hashToBookFileId().isEmpty()) { + pd.timer().cancel(false); + pendingByPath.remove(entry.getKey()); + log.debug("[POOL] All files matched for path='{}', cancelled timer", entry.getKey()); + } + return true; + } + } + } + } + } + return false; + } + + public boolean hasPendingForPaths(Set paths) { + return pendingByPath.keySet().stream() + .anyMatch(p -> paths.stream().anyMatch(p::startsWith)); + } +} diff --git a/booklore-api/src/main/java/org/booklore/util/FileUtils.java b/booklore-api/src/main/java/org/booklore/util/FileUtils.java index dd981d25a..06974011d 100644 --- a/booklore-api/src/main/java/org/booklore/util/FileUtils.java +++ b/booklore-api/src/main/java/org/booklore/util/FileUtils.java @@ -187,14 +187,37 @@ public class FileUtils { "chapter", "track", "part", "disc", "disk", "cd", "side", "intro", "epilogue", "prologue", "outro" ); + private static final Set SINGLE_FILE_AUDIOBOOK_EXTENSIONS = Set.of("m4b", "m4a"); + /** * Determines if a list of audio files represents a series folder (each file is a separate book) * rather than a multi-file audiobook (chapter files for one book). * - * Extracts a "base title" from each file by stripping numbering, part indicators, and extensions, - * then counts distinct non-generic titles. If more than one distinct title exists, it's a series folder. + * Uses two signals: + * 1. File format: .m4b/.m4a files are typically complete audiobooks, so a folder of them + * is likely a series. .mp3 files are typically chapters/tracks of one audiobook. + * 2. Title analysis (for .m4b/.m4a only): extracts base titles by stripping numbering and + * part indicators. If multiple distinct non-generic titles exist, it's a series. + * + * For .mp3 files (the vast majority of chapter-based audiobooks), this always returns false + * regardless of naming convention, avoiding the impossible task of distinguishing descriptive + * chapter names from book titles via pattern matching. */ public boolean isSeriesFolder(List audioFiles) { + if (audioFiles.size() < 2) { + return false; + } + + boolean allSingleFileFormats = audioFiles.stream().allMatch(f -> { + String name = f.getFileName().toString().toLowerCase(); + int dot = name.lastIndexOf('.'); + return dot > 0 && SINGLE_FILE_AUDIOBOOK_EXTENSIONS.contains(name.substring(dot + 1)); + }); + + if (!allSingleFileFormats) { + return false; + } + Set distinctTitles = new HashSet<>(); for (Path file : audioFiles) { String title = extractBaseTitle(file.getFileName().toString()); @@ -243,8 +266,14 @@ public class FileUtils { ".caltrash" ); + private final Set tempExtensions = Set.of( + ".part", ".tmp", ".crdownload", ".download", + ".bak", ".old", ".temp", ".tempfile" + ); + public boolean shouldIgnore(Path path) { - if (!path.getFileName().toString().isEmpty() && path.getFileName().toString().charAt(0) == '.') { + String fileName = path.getFileName().toString(); + if (!fileName.isEmpty() && fileName.charAt(0) == '.') { return true; } for (Path part : path) { @@ -252,6 +281,12 @@ public class FileUtils { return true; } } + String lowerName = fileName.toLowerCase(); + for (String ext : tempExtensions) { + if (lowerName.endsWith(ext)) { + return true; + } + } return false; } } diff --git a/booklore-api/src/main/resources/db/migration/V130__Add_book_per_file_organization_mode.sql b/booklore-api/src/main/resources/db/migration/V130__Add_book_per_file_organization_mode.sql new file mode 100644 index 000000000..034c35bb8 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V130__Add_book_per_file_organization_mode.sql @@ -0,0 +1 @@ +ALTER TABLE library MODIFY COLUMN organization_mode VARCHAR(50) DEFAULT 'BOOK_PER_FILE'; diff --git a/booklore-api/src/test/java/org/booklore/service/library/BookGroupingServiceTest.java b/booklore-api/src/test/java/org/booklore/service/library/BookGroupingServiceTest.java new file mode 100644 index 000000000..0478a1895 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/library/BookGroupingServiceTest.java @@ -0,0 +1,733 @@ +package org.booklore.service.library; + +import org.booklore.model.dto.settings.LibraryFile; +import org.booklore.model.entity.LibraryEntity; +import org.booklore.model.entity.LibraryPathEntity; +import org.booklore.model.enums.BookFileType; +import org.booklore.model.enums.LibraryOrganizationMode; +import org.booklore.repository.BookRepository; +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.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(MockitoExtension.class) +class BookGroupingServiceTest { + + @Mock + BookRepository bookRepository; + + @InjectMocks + BookGroupingService bookGroupingService; + + private LibraryPathEntity pathEntity(Long id, String path) { + var pe = new LibraryPathEntity(); + pe.setId(id); + pe.setPath(path); + return pe; + } + + private LibraryEntity library(LibraryOrganizationMode mode, LibraryPathEntity... paths) { + return LibraryEntity.builder() + .name("Test Library") + .organizationMode(mode) + .libraryPaths(List.of(paths)) + .build(); + } + + private LibraryFile file(LibraryPathEntity path, String subPath, String name, BookFileType type) { + return LibraryFile.builder() + .libraryPathEntity(path) + .fileSubPath(subPath) + .fileName(name) + .bookFileType(type) + .build(); + } + + private LibraryFile file(LibraryPathEntity path, String subPath, String name, BookFileType type, boolean folderBased) { + return LibraryFile.builder() + .libraryPathEntity(path) + .fileSubPath(subPath) + .fileName(name) + .bookFileType(type) + .folderBased(folderBased) + .build(); + } + + private LibraryFile ebook(LibraryPathEntity path, String subPath, String name) { + return file(path, subPath, name, BookFileType.EPUB); + } + + private LibraryFile audiobook(LibraryPathEntity path, String subPath, String name) { + return file(path, subPath, name, BookFileType.AUDIOBOOK); + } + + private LibraryFile folderAudiobook(LibraryPathEntity path, String subPath, String folderName) { + return file(path, subPath, folderName, BookFileType.AUDIOBOOK, true); + } + + private int groupCount(Map> groups) { + return groups.size(); + } + + private int totalFiles(Map> groups) { + return groups.values().stream().mapToInt(List::size).sum(); + } + + private int folderBasedCount(Map> groups) { + return (int) groups.values().stream() + .flatMap(Collection::stream) + .filter(LibraryFile::isFolderBased) + .count(); + } + + @Test + void structure1_bookPerFile_flatRootFiles() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + ebook(path, "", "Salem's Lot (Package May Vary) - Stephen Kingg, Aditya.epub"), + ebook(path, "", "Good Spirits (B.K. Borison) (z-library.sk, 1lib.sk, z-lib.sk).epub"), + ebook(path, "", "Hansel and Gretel - Stephen King (2025).epub"), + audiobook(path, "", "Hansel and Gretel (2025).m4b"), + ebook(path, "", "History of Britain and Ireland The Definitive Visual Guide (DORLING KINDERSLEY.) (Z-Library).epub"), + ebook(path, "", "The Strength of the Few (Hierarchy, Book Two) (James Islington) (z-library.sk, 1lib.sk, z-lib.sk).epub"), + ebook(path, "", "Violet Thistlewaite Is Not a Villain Anymore (Emily Krempholtz) (z-library.sk, 1lib.sk, z-lib.sk).epub") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(7); + assertThat(totalFiles(groups)).isEqualTo(7); + assertThat(folderBasedCount(groups)).isZero(); + } + + @Test + void structure1_bookPerFolder_flatRootFiles() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + ebook(path, "", "Salem's Lot (Package May Vary) - Stephen Kingg, Aditya.epub"), + ebook(path, "", "Good Spirits (B.K. Borison) (z-library.sk, 1lib.sk, z-lib.sk).epub"), + ebook(path, "", "Hansel and Gretel - Stephen King (2025).epub"), + audiobook(path, "", "Hansel and Gretel (2025).m4b"), + ebook(path, "", "History of Britain and Ireland The Definitive Visual Guide (DORLING KINDERSLEY.) (Z-Library).epub"), + ebook(path, "", "The Strength of the Few (Hierarchy, Book Two) (James Islington) (z-library.sk, 1lib.sk, z-lib.sk).epub"), + ebook(path, "", "Violet Thistlewaite Is Not a Villain Anymore (Emily Krempholtz) (z-library.sk, 1lib.sk, z-lib.sk).epub") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(7); + assertThat(totalFiles(groups)).isEqualTo(7); + } + + @Test + void structure2_bookPerFile_authorTitleFolders() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + ebook(path, "Andy Weir/Project Hail Mary", "Project Hail Mary - Andy Weir (2022).pdf"), + ebook(path, "Andy Weir/The Martian", "The Martian - Andy Weir (2020).epub"), + audiobook(path, "Andy Weir/The Martian", "The Martian - Andy Weir (2020).mp3"), + ebook(path, "Christopher Buehlman/The Lesser Dead", "The Lesser Dead - Christopher Buehlman (2014).epub"), + ebook(path, "Christopher Buehlman/Those Across the River", "Those Across the River - Christopher Buehlman (2011).epub"), + ebook(path, "Cormac McCarthy/The Road", "The Road - Cormac McCarthy (2006).epub"), + ebook(path, "Jim Butcher/Twelve Months", "Twelve Months - Jim Butcher (2026).azw3"), + ebook(path, "Jim Butcher/Twelve Months", "Twelve Months - Jim Butcher (2026).epub"), + ebook(path, "Jim Butcher/Twelve Months", "Twelve Months - Jim Butcher (2026).mobi"), + ebook(path, "Neil Gaiman/American Gods", "American Gods - Neil Gaiman (2011).epub"), + ebook(path, "Neil Gaiman/American Gods", "American Gods - Neil Gaiman (2011).mobi"), + ebook(path, "James Islington/The Will of the Many", "The Will of the Many (Hierarchy) - James Islington (2025).epub") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(12); + assertThat(totalFiles(groups)).isEqualTo(12); + assertThat(folderBasedCount(groups)).isZero(); + } + + @Test + void structure2_bookPerFolder_authorTitleFolders() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + ebook(path, "Andy Weir/Project Hail Mary", "Project Hail Mary - Andy Weir (2022).pdf"), + ebook(path, "Andy Weir/The Martian", "The Martian - Andy Weir (2020).epub"), + audiobook(path, "Andy Weir/The Martian", "The Martian - Andy Weir (2020).mp3"), + ebook(path, "Christopher Buehlman/The Lesser Dead", "The Lesser Dead - Christopher Buehlman (2014).epub"), + ebook(path, "Christopher Buehlman/Those Across the River", "Those Across the River - Christopher Buehlman (2011).epub"), + ebook(path, "Cormac McCarthy/The Road", "The Road - Cormac McCarthy (2006).epub"), + ebook(path, "Jim Butcher/Twelve Months", "Twelve Months - Jim Butcher (2026).azw3"), + ebook(path, "Jim Butcher/Twelve Months", "Twelve Months - Jim Butcher (2026).epub"), + ebook(path, "Jim Butcher/Twelve Months", "Twelve Months - Jim Butcher (2026).mobi"), + ebook(path, "Neil Gaiman/American Gods", "American Gods - Neil Gaiman (2011).epub"), + ebook(path, "Neil Gaiman/American Gods", "American Gods - Neil Gaiman (2011).mobi"), + ebook(path, "James Islington/The Will of the Many", "The Will of the Many (Hierarchy) - James Islington (2025).epub") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(8); + assertThat(totalFiles(groups)).isEqualTo(12); + } + + @Test + void structure2_bookPerFolder_twelveMonthsGroupedAsSingleBook() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + ebook(path, "Jim Butcher/Twelve Months", "Twelve Months - Jim Butcher (2026).azw3"), + ebook(path, "Jim Butcher/Twelve Months", "Twelve Months - Jim Butcher (2026).epub"), + ebook(path, "Jim Butcher/Twelve Months", "Twelve Months - Jim Butcher (2026).mobi") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(1); + assertThat(totalFiles(groups)).isEqualTo(3); + } + + @Test + void structure3_bookPerFile_folderBasedAudiobooks() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "1 HARRY POTTER AND THE PHILOSOPHER'S STONE"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "2 HARRY POTTER AND THE CHAMBER OF SECRETS"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "3 HARRY POTTER AND THE PRISONER OF AZKABAN") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(3); + assertThat(folderBasedCount(groups)).isEqualTo(3); + } + + @Test + void structure3_bookPerFolder_folderBasedAudiobooksGroupedUnderParent() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "1 HARRY POTTER AND THE PHILOSOPHER'S STONE"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "2 HARRY POTTER AND THE CHAMBER OF SECRETS"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "3 HARRY POTTER AND THE PRISONER OF AZKABAN") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + // Folder-based audiobooks reconstruct effectiveSubPath = subPath/fileName, giving each a + // unique folder path. With no ebook ancestor to absorb into, each stays separate. + assertThat(groupCount(groups)).isEqualTo(3); + assertThat(totalFiles(groups)).isEqualTo(3); + assertThat(folderBasedCount(groups)).isEqualTo(3); + } + + @Test + void structure4_bookPerFile_mixedMedia() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + ebook(path, "Suzanne Collins/Catching Fire", "Catching Fire - Suzanne Collins.azw3"), + ebook(path, "Suzanne Collins/Catching Fire", "Catching Fire - Suzanne Collins.epub"), + folderAudiobook(path, "Suzanne Collins/Catching Fire/audiobook", "audiobook"), + ebook(path, "Suzanne Collins/The Hunger Games", "The Hunger Games - Suzanne Collins (2010).azw3"), + ebook(path, "Suzanne Collins/The Hunger Games", "The Hunger Games - Suzanne Collins (2010).epub"), + ebook(path, "Suzanne Collins/The Hunger Games", "The Hunger Games - Suzanne Collins (2010).mobi") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(6); + assertThat(totalFiles(groups)).isEqualTo(6); + assertThat(folderBasedCount(groups)).isEqualTo(1); + } + + @Test + void structure4_bookPerFolder_audiobookAbsorbedIntoEbookFolder() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + ebook(path, "Suzanne Collins/Catching Fire", "Catching Fire - Suzanne Collins.azw3"), + ebook(path, "Suzanne Collins/Catching Fire", "Catching Fire - Suzanne Collins.epub"), + folderAudiobook(path, "Suzanne Collins/Catching Fire/audiobook", "audiobook"), + ebook(path, "Suzanne Collins/The Hunger Games", "The Hunger Games - Suzanne Collins (2010).azw3"), + ebook(path, "Suzanne Collins/The Hunger Games", "The Hunger Games - Suzanne Collins (2010).epub"), + ebook(path, "Suzanne Collins/The Hunger Games", "The Hunger Games - Suzanne Collins (2010).mobi") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(2); + assertThat(totalFiles(groups)).isEqualTo(6); + assertThat(folderBasedCount(groups)).isEqualTo(1); + + var catchingFireGroup = groups.values().stream() + .filter(g -> g.stream().anyMatch(f -> f.getFileName().contains("Catching Fire"))) + .findFirst().orElseThrow(); + assertThat(catchingFireGroup).hasSize(3); + } + + @Test + void structure5_bookPerFile_formatSubfolders() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - EPUB", "Brandon Sanderson - Mistborn 01 - The Final Empire.epub"), + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - EPUB", "Brandon Sanderson - Mistborn 02 - The Well of Ascension.epub"), + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - EPUB", "Brandon Sanderson - Mistborn 03 - The Hero of Ages.epub"), + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - MOBI", "Brandon Sanderson - Mistborn 01 - The Final Empire.mobi"), + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - MOBI", "Brandon Sanderson - Mistborn 02 - The Well of Ascension.mobi"), + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - MOBI", "Brandon Sanderson - Mistborn 03 - The Hero of Ages.mobi") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(6); + assertThat(totalFiles(groups)).isEqualTo(6); + } + + @Test + void structure5_bookPerFolder_formatSubfolders() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - EPUB", "Brandon Sanderson - Mistborn 01 - The Final Empire.epub"), + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - EPUB", "Brandon Sanderson - Mistborn 02 - The Well of Ascension.epub"), + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - EPUB", "Brandon Sanderson - Mistborn 03 - The Hero of Ages.epub"), + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - MOBI", "Brandon Sanderson - Mistborn 01 - The Final Empire.mobi"), + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - MOBI", "Brandon Sanderson - Mistborn 02 - The Well of Ascension.mobi"), + ebook(path, "Brandon Sanderson - Mistborn Trilogy/Brandon Sanderson - Mistborn - MOBI", "Brandon Sanderson - Mistborn 03 - The Hero of Ages.mobi") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(2); + assertThat(totalFiles(groups)).isEqualTo(6); + } + + @Test + void structure6_bookPerFile_singleFileAudiobooksWithEbooks() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + ebook(path, "J. M. Barrie/Peter Pan", "Peter Pan - J. M. Barrie (2013).epub"), + audiobook(path, "J. M. Barrie/Peter Pan", "Peter Pan - J. M. Barrie (2013).m4b"), + ebook(path, "J. M. Barrie/Peter Pan", "Peter Pan - J. M. Barrie (2013).mobi"), + ebook(path, "Jonathan Swift/Gulliver's Travels", "Gulliver's Travels - Jonathan Swift (2013).epub"), + audiobook(path, "Jonathan Swift/Gulliver's Travels", "Gulliver's Travels - Jonathan Swift (2013).m4b"), + ebook(path, "Jonathan Swift/Gulliver's Travels", "Gulliver's Travels - Jonathan Swift (2013).mobi"), + ebook(path, "", "Hansel and Gretel - Stephen King (2025).epub"), + audiobook(path, "", "Hansel and Gretel (2025).m4b") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(8); + assertThat(totalFiles(groups)).isEqualTo(8); + } + + @Test + void structure6_bookPerFolder_singleFileAudiobooksGroupedWithEbooks() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + ebook(path, "J. M. Barrie/Peter Pan", "Peter Pan - J. M. Barrie (2013).epub"), + audiobook(path, "J. M. Barrie/Peter Pan", "Peter Pan - J. M. Barrie (2013).m4b"), + ebook(path, "J. M. Barrie/Peter Pan", "Peter Pan - J. M. Barrie (2013).mobi"), + ebook(path, "Jonathan Swift/Gulliver's Travels", "Gulliver's Travels - Jonathan Swift (2013).epub"), + audiobook(path, "Jonathan Swift/Gulliver's Travels", "Gulliver's Travels - Jonathan Swift (2013).m4b"), + ebook(path, "Jonathan Swift/Gulliver's Travels", "Gulliver's Travels - Jonathan Swift (2013).mobi"), + ebook(path, "", "Hansel and Gretel - Stephen King (2025).epub"), + audiobook(path, "", "Hansel and Gretel (2025).m4b") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(4); + assertThat(totalFiles(groups)).isEqualTo(8); + } + + @Test + void structure7_bookPerFile_titleFolders() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + ebook(path, "Oathbringer_ The Stormlight Archive Book Three", "Oathbringer_ The Stormlight Archive Book T - Brandon Sanderson.azw3"), + ebook(path, "Oathbringer_ The Stormlight Archive Book Three", "Oathbringer_ The Stormlight Archive Book T - Brandon Sanderson.epub"), + ebook(path, "Oathbringer_ The Stormlight Archive Book Three", "Oathbringer_ The Stormlight Archive Book T - Brandon Sanderson.mobi"), + ebook(path, "Piranesi by Susanna Clarke", "Piranesi - Susanna Clarke.epub"), + ebook(path, "Piranesi by Susanna Clarke", "Piranesi - Susanna Clarke.mobi"), + ebook(path, "Rhythm of War (Stormlight Archive Book 4) - Brandon Sanderson", "Rhythm of War (The Stormlight Archive Book 4) - Brandon Sanderson.azw3"), + ebook(path, "Rhythm of War (Stormlight Archive Book 4) - Brandon Sanderson", "Rhythm of War (The Stormlight Archive Book 4) - Brandon Sanderson.epub"), + ebook(path, "Rhythm of War (Stormlight Archive Book 4) - Brandon Sanderson", "Rhythm of War (The Stormlight Archive Book 4) - Brandon Sanderson.mobi"), + ebook(path, "The Martian_ A Novel (283)", "The Martian_ A Novel - Andy Weir.azw3"), + ebook(path, "The Martian_ A Novel (283)", "The Martian_ A Novel - Andy Weir.epub"), + ebook(path, "The Martian_ A Novel (283)", "The Martian_ A Novel - Andy Weir.mobi") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(11); + assertThat(totalFiles(groups)).isEqualTo(11); + } + + @Test + void structure7_bookPerFolder_titleFolders() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + ebook(path, "Oathbringer_ The Stormlight Archive Book Three", "Oathbringer_ The Stormlight Archive Book T - Brandon Sanderson.azw3"), + ebook(path, "Oathbringer_ The Stormlight Archive Book Three", "Oathbringer_ The Stormlight Archive Book T - Brandon Sanderson.epub"), + ebook(path, "Oathbringer_ The Stormlight Archive Book Three", "Oathbringer_ The Stormlight Archive Book T - Brandon Sanderson.mobi"), + ebook(path, "Piranesi by Susanna Clarke", "Piranesi - Susanna Clarke.epub"), + ebook(path, "Piranesi by Susanna Clarke", "Piranesi - Susanna Clarke.mobi"), + ebook(path, "Rhythm of War (Stormlight Archive Book 4) - Brandon Sanderson", "Rhythm of War (The Stormlight Archive Book 4) - Brandon Sanderson.azw3"), + ebook(path, "Rhythm of War (Stormlight Archive Book 4) - Brandon Sanderson", "Rhythm of War (The Stormlight Archive Book 4) - Brandon Sanderson.epub"), + ebook(path, "Rhythm of War (Stormlight Archive Book 4) - Brandon Sanderson", "Rhythm of War (The Stormlight Archive Book 4) - Brandon Sanderson.mobi"), + ebook(path, "The Martian_ A Novel (283)", "The Martian_ A Novel - Andy Weir.azw3"), + ebook(path, "The Martian_ A Novel (283)", "The Martian_ A Novel - Andy Weir.epub"), + ebook(path, "The Martian_ A Novel (283)", "The Martian_ A Novel - Andy Weir.mobi") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(4); + assertThat(totalFiles(groups)).isEqualTo(11); + } + + @Test + void structure8_bookPerFile_deepNesting() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + ebook(path, "C. S. Lewis/The Chronicles of Narnia/Prince Caspian", "Prince Caspian - C. S. Lewis (2013).azw3"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/Prince Caspian", "Prince Caspian - C. S. Lewis (2013).epub"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/Prince Caspian", "Prince Caspian - C. S. Lewis (2013).mobi"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Horse and His Boy The Chronicles of Narnia", "The Horse and His Boy - C. S. Lewis.azw3"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Horse and His Boy The Chronicles of Narnia", "The Horse and His Boy - C. S. Lewis.epub"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Horse and His Boy The Chronicles of Narnia", "The Horse and His Boy - C. S. Lewis.mobi"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Magician's Nephew The Chronicles of Narnia", "The Magician's Nephew - C. S. Lewis (2013).epub"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Magician's Nephew The Chronicles of Narnia", "The Magician's Nephew - C. S. Lewis.azw3"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Magician's Nephew The Chronicles of Narnia", "The Magician's Nephew - C. S. Lewis.mobi"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Silver Chair", "The Silver Chair - C. S. Lewis (2013).epub") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(10); + assertThat(totalFiles(groups)).isEqualTo(10); + } + + @Test + void structure8_bookPerFolder_deepNesting() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + ebook(path, "C. S. Lewis/The Chronicles of Narnia/Prince Caspian", "Prince Caspian - C. S. Lewis (2013).azw3"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/Prince Caspian", "Prince Caspian - C. S. Lewis (2013).epub"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/Prince Caspian", "Prince Caspian - C. S. Lewis (2013).mobi"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Horse and His Boy The Chronicles of Narnia", "The Horse and His Boy - C. S. Lewis.azw3"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Horse and His Boy The Chronicles of Narnia", "The Horse and His Boy - C. S. Lewis.epub"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Horse and His Boy The Chronicles of Narnia", "The Horse and His Boy - C. S. Lewis.mobi"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Magician's Nephew The Chronicles of Narnia", "The Magician's Nephew - C. S. Lewis (2013).epub"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Magician's Nephew The Chronicles of Narnia", "The Magician's Nephew - C. S. Lewis.azw3"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Magician's Nephew The Chronicles of Narnia", "The Magician's Nephew - C. S. Lewis.mobi"), + ebook(path, "C. S. Lewis/The Chronicles of Narnia/The Silver Chair", "The Silver Chair - C. S. Lewis (2013).epub") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(4); + assertThat(totalFiles(groups)).isEqualTo(10); + } + + @Test + void structure9_bookPerFile_largeSeries() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = new ArrayList<>(); + for (int i = 1; i <= 19; i++) { + String name = String.format("Dune %02d - Title %d", i, i); + files.add(ebook(path, "Dune/epub", name + ".epub")); + files.add(ebook(path, "Dune/Mobi", name + ".mobi")); + } + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(38); + assertThat(totalFiles(groups)).isEqualTo(38); + } + + @Test + void structure9_bookPerFolder_largeSeries() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = new ArrayList<>(); + for (int i = 1; i <= 19; i++) { + String name = String.format("Dune %02d - Title %d", i, i); + files.add(ebook(path, "Dune/epub", name + ".epub")); + files.add(ebook(path, "Dune/Mobi", name + ".mobi")); + } + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(2); + assertThat(totalFiles(groups)).isEqualTo(38); + } + + @Test + void structure10_bookPerFile_hpEbooks() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + ebook(path, "J.K. Rowling/Harry Potter and the Chamber of Secrets", "Harry Potter and the Chamber of Secrets - J.K. Rowling (2019).fb2"), + ebook(path, "J.K. Rowling/Harry Potter and the Chamber of Secrets", "Harry Potter and the Chamber of Secrets - J.K. Rowling (2019).pdf"), + ebook(path, "J.K. Rowling/Harry Potter and the Chamber of Secrets", "Harry Potter and the Chamber of Secrets - J.K. Rowling.azw3"), + ebook(path, "J.K. Rowling/Harry Potter and the Chamber of Secrets", "Harry Potter and the Chamber of Secrets - J.K. Rowling.epub"), + ebook(path, "J.K. Rowling/Harry Potter and the Cursed Child", "Harry Potter and the Cursed Child - J.K. Rowling (2017).epub"), + ebook(path, "J.K. Rowling/Harry Potter and the Deathly Hallows", "Harry Potter and the Deathly Hallows - J.K. Rowling.azw3"), + ebook(path, "J.K. Rowling/Harry Potter and the Deathly Hallows", "Harry Potter and the Deathly Hallows - J.K. Rowling.epub"), + ebook(path, "J.K. Rowling/Harry Potter and the Goblet of Fire", "Harry Potter and the Goblet of Fire - J.K. Rowling.epub"), + ebook(path, "J.K. Rowling/Harry Potter and the Goblet of Fire", "Harry Potter and the Goblet of Fire - J.K. Rowling.mobi"), + ebook(path, "J.K. Rowling/Harry Potter and the Goblet of Fire", "Harry Potter and the Goblet of Fire - J.K. Rowling.pdf"), + ebook(path, "J.K. Rowling/Harry Potter and the Half-Blood Prince", "Harry Potter and the Half-Blood Prince - J.K. Rowling.epub"), + ebook(path, "J.K. Rowling/Harry Potter and the Philosopher's Stone", "Harry Potter and the Philosopher's Stone - J.K. Rowling.azw3"), + ebook(path, "J.K. Rowling/Harry Potter and the Philosopher's Stone", "Harry Potter and the Philosopher's Stone - J.K. Rowling.epub") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(13); + assertThat(totalFiles(groups)).isEqualTo(13); + } + + @Test + void structure10_bookPerFolder_hpEbooks() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + ebook(path, "J.K. Rowling/Harry Potter and the Chamber of Secrets", "Harry Potter and the Chamber of Secrets - J.K. Rowling (2019).fb2"), + ebook(path, "J.K. Rowling/Harry Potter and the Chamber of Secrets", "Harry Potter and the Chamber of Secrets - J.K. Rowling (2019).pdf"), + ebook(path, "J.K. Rowling/Harry Potter and the Chamber of Secrets", "Harry Potter and the Chamber of Secrets - J.K. Rowling.azw3"), + ebook(path, "J.K. Rowling/Harry Potter and the Chamber of Secrets", "Harry Potter and the Chamber of Secrets - J.K. Rowling.epub"), + ebook(path, "J.K. Rowling/Harry Potter and the Cursed Child", "Harry Potter and the Cursed Child - J.K. Rowling (2017).epub"), + ebook(path, "J.K. Rowling/Harry Potter and the Deathly Hallows", "Harry Potter and the Deathly Hallows - J.K. Rowling.azw3"), + ebook(path, "J.K. Rowling/Harry Potter and the Deathly Hallows", "Harry Potter and the Deathly Hallows - J.K. Rowling.epub"), + ebook(path, "J.K. Rowling/Harry Potter and the Goblet of Fire", "Harry Potter and the Goblet of Fire - J.K. Rowling.epub"), + ebook(path, "J.K. Rowling/Harry Potter and the Goblet of Fire", "Harry Potter and the Goblet of Fire - J.K. Rowling.mobi"), + ebook(path, "J.K. Rowling/Harry Potter and the Goblet of Fire", "Harry Potter and the Goblet of Fire - J.K. Rowling.pdf"), + ebook(path, "J.K. Rowling/Harry Potter and the Half-Blood Prince", "Harry Potter and the Half-Blood Prince - J.K. Rowling.epub"), + ebook(path, "J.K. Rowling/Harry Potter and the Philosopher's Stone", "Harry Potter and the Philosopher's Stone - J.K. Rowling.azw3"), + ebook(path, "J.K. Rowling/Harry Potter and the Philosopher's Stone", "Harry Potter and the Philosopher's Stone - J.K. Rowling.epub") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(6); + assertThat(totalFiles(groups)).isEqualTo(13); + } + + @Test + void structure12_bookPerFile_fullAudiobooks() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "1 HARRY POTTER AND THE PHILOSOPHER'S STONE"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "2 HARRY POTTER AND THE CHAMBER OF SECRETS"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "3 HARRY POTTER AND THE PRISONER OF AZKABAN"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "4 HARRY POTTER AND THE GOBLET OF FIRE"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "5 HARRY POTTER ANND THE ORDER OF THE PHOENIX"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "6 HARRY POTTER AND THE HALF-BLOOD PRINCE"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "7 HARRY POTTER AND THE DEATHLY HALLOWS") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(7); + assertThat(folderBasedCount(groups)).isEqualTo(7); + } + + @Test + void structure12_bookPerFolder_fullAudiobooks() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "1 HARRY POTTER AND THE PHILOSOPHER'S STONE"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "2 HARRY POTTER AND THE CHAMBER OF SECRETS"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "3 HARRY POTTER AND THE PRISONER OF AZKABAN"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "4 HARRY POTTER AND THE GOBLET OF FIRE"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "5 HARRY POTTER ANND THE ORDER OF THE PHOENIX"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "6 HARRY POTTER AND THE HALF-BLOOD PRINCE"), + folderAudiobook(path, "J K Rowling - Harry Potter 1-7 Unabridged Audiobooks Narrated by Stephen Fry", "7 HARRY POTTER AND THE DEATHLY HALLOWS") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + // Each folder-based audiobook reconstructs effectiveSubPath = parentSubPath/folderName, + // so with no ebook ancestor to absorb into, each stays separate + assertThat(groupCount(groups)).isEqualTo(7); + assertThat(totalFiles(groups)).isEqualTo(7); + assertThat(folderBasedCount(groups)).isEqualTo(7); + } + + @Test + void structure13_bookPerFile_mismatchedNames() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + ebook(path, "Wendy Walker/Bladesssss", "Blade - Wendy Walddker.epub"), + ebook(path, "Wendy Walker/Bladesssss", "Blade - Wendy Walker (2026).pdf") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(2); + } + + @Test + void structure13_bookPerFolder_mismatchedNames() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + ebook(path, "Wendy Walker/Bladesssss", "Blade - Wendy Walddker.epub"), + ebook(path, "Wendy Walker/Bladesssss", "Blade - Wendy Walker (2026).pdf") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(1); + assertThat(totalFiles(groups)).isEqualTo(2); + } + + @Test + void nullOrganizationMode_defaultsToAutoDetect() { + var path = pathEntity(1L, "/books"); + var lib = library(null, path); + + List files = List.of( + ebook(path, "Author/Book", "Book - Author.epub"), + ebook(path, "Author/Book", "Book - Author.mobi") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(totalFiles(groups)).isEqualTo(2); + } + + @Test + void bookPerFolder_rootLevelAudiobooksAreIndividual() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + audiobook(path, "", "Audiobook One.m4b"), + audiobook(path, "", "Audiobook Two.m4b"), + ebook(path, "", "Some Book.epub") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(3); + } + + @Test + void bookPerFolder_audiobookAbsorbedIntoNearestEbookAncestor() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + ebook(path, "Author/Title", "Title - Author.epub"), + folderAudiobook(path, "Author/Title/audiobook", "audiobook") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(1); + assertThat(totalFiles(groups)).isEqualTo(2); + } + + @Test + void bookPerFolder_audiobookWithNoEbookAncestorStaysSeparate() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path); + + List files = List.of( + folderAudiobook(path, "Audiobooks/Book One", "Book One"), + ebook(path, "Ebooks/Some Book", "Some Book.epub") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(2); + } + + @Test + void bookPerFile_sameNameDifferentFormatsAreSeparateBooks() { + var path = pathEntity(1L, "/books"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FILE, path); + + List files = List.of( + ebook(path, "Author/Book", "Book.epub"), + ebook(path, "Author/Book", "Book.mobi"), + ebook(path, "Author/Book", "Book.pdf") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(3); + } + + @Test + void bookPerFolder_differentLibraryPathsAreNotMixed() { + var path1 = pathEntity(1L, "/books1"); + var path2 = pathEntity(2L, "/books2"); + var lib = library(LibraryOrganizationMode.BOOK_PER_FOLDER, path1, path2); + + List files = List.of( + ebook(path1, "Author/Title", "Book.epub"), + ebook(path1, "Author/Title", "Book.mobi"), + ebook(path2, "Author/Title", "Book.epub"), + ebook(path2, "Author/Title", "Book.mobi") + ); + + var groups = bookGroupingService.groupForInitialScan(files, lib); + + assertThat(groupCount(groups)).isEqualTo(2); + assertThat(totalFiles(groups)).isEqualTo(4); + } +} diff --git a/booklore-api/src/test/java/org/booklore/service/library/FileAsBookProcessorTest.java b/booklore-api/src/test/java/org/booklore/service/library/FileAsBookProcessorTest.java index 9f9dd29ad..a366da888 100644 --- a/booklore-api/src/test/java/org/booklore/service/library/FileAsBookProcessorTest.java +++ b/booklore-api/src/test/java/org/booklore/service/library/FileAsBookProcessorTest.java @@ -10,6 +10,7 @@ import org.booklore.model.enums.BookFileType; import org.booklore.model.enums.FileProcessStatus; import org.booklore.repository.BookAdditionalFileRepository; import org.booklore.repository.BookRepository; +import org.booklore.repository.LibraryRepository; import org.booklore.service.event.BookEventBroadcaster; import org.booklore.service.file.FileFingerprint; import org.booklore.service.fileprocessor.BookFileProcessor; @@ -50,6 +51,9 @@ class FileAsBookProcessorTest { @Mock private BookAdditionalFileRepository bookAdditionalFileRepository; + @Mock + private LibraryRepository libraryRepository; + @Mock private FileService fileService; @@ -77,6 +81,7 @@ class FileAsBookProcessorTest { koboAutoShelfService, bookRepository, bookAdditionalFileRepository, + libraryRepository, fileService, metadataExtractorFactory, audiobookMetadataExtractor @@ -85,6 +90,7 @@ class FileAsBookProcessorTest { fileFingerprintMock.when(() -> FileFingerprint.generateHash(any(Path.class))).thenReturn("testhash"); fileUtilsMock = mockStatic(FileUtils.class); fileUtilsMock.when(() -> FileUtils.getFileSizeInKb(any(Path.class))).thenReturn(100L); + } @AfterEach diff --git a/booklore-api/src/test/java/org/booklore/service/library/LibraryFileHelperTest.java b/booklore-api/src/test/java/org/booklore/service/library/LibraryFileHelperTest.java index 4b38caaca..f6a159e5e 100644 --- a/booklore-api/src/test/java/org/booklore/service/library/LibraryFileHelperTest.java +++ b/booklore-api/src/test/java/org/booklore/service/library/LibraryFileHelperTest.java @@ -3,6 +3,8 @@ package org.booklore.service.library; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.LibraryEntity; import org.booklore.model.entity.LibraryPathEntity; +import org.booklore.model.enums.BookFileType; +import org.booklore.model.enums.LibraryOrganizationMode; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; @@ -14,6 +16,7 @@ import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermissions; import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; @ExtendWith(MockitoExtension.class) @@ -25,9 +28,9 @@ class LibraryFileHelperTest { void testGetLibraryFiles_HandlesInaccessibleDirectories() throws IOException { LibraryFileHelper libraryFileHelper = new LibraryFileHelper(); - Files.createFile(tempDir.resolve("happy.epub")); + Files.write(tempDir.resolve("happy.epub"), new byte[]{1}); Files.createDirectory(tempDir.resolve("some_other_random_named_dir"), PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("---------"))); - Files.createFile(tempDir.resolve("zzzz_happ.epub")); + Files.write(tempDir.resolve("zzzz_happ.epub"), new byte[]{1}); LibraryPathEntity libraryPath = new LibraryPathEntity(); libraryPath.setId(10L); @@ -43,4 +46,349 @@ class LibraryFileHelperTest { List libraryFiles = libraryFileHelper.getLibraryFiles(testLibrary); assertEquals(libraryFiles.stream().map(LibraryFile::getFileName).sorted().toList(), List.of("happy.epub", "zzzz_happ.epub")); } + + private LibraryEntity createLibrary(Path path) { + LibraryPathEntity libraryPath = new LibraryPathEntity(); + libraryPath.setId(1L); + libraryPath.setPath(path.toString()); + + return LibraryEntity.builder() + .name("Test Library") + .icon("book") + .watch(false) + .organizationMode(LibraryOrganizationMode.BOOK_PER_FILE) + .libraryPaths(List.of(libraryPath)) + .build(); + } + + @Test + void testGetLibraryFiles_skipsDirectoryWithIgnoreFile() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Path ignoredDir = Files.createDirectories(tempDir.resolve("ignored-folder")); + Files.createFile(ignoredDir.resolve(".ignore")); + Files.write(ignoredDir.resolve("hidden-book.epub"), new byte[]{1}); + + Files.write(tempDir.resolve("visible-book.epub"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + assertThat(files).hasSize(1); + assertThat(files.getFirst().getFileName()).isEqualTo("visible-book.epub"); + } + + @Test + void testGetLibraryFiles_doesNotSkipRootWithIgnoreFile() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Files.createFile(tempDir.resolve(".ignore")); + Files.write(tempDir.resolve("root-book.epub"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + assertThat(files).hasSize(1); + assertThat(files.getFirst().getFileName()).isEqualTo("root-book.epub"); + } + + @Test + void testGetLibraryFiles_ignoreFileOnlyAffectsItsDirectory() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Path ignoredDir = Files.createDirectories(tempDir.resolve("ignored")); + Files.createFile(ignoredDir.resolve(".ignore")); + Files.write(ignoredDir.resolve("hidden.epub"), new byte[]{1}); + + Path visibleDir = Files.createDirectories(tempDir.resolve("visible")); + Files.write(visibleDir.resolve("book.epub"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + assertThat(files).hasSize(1); + assertThat(files.getFirst().getFileName()).isEqualTo("book.epub"); + } + + @Test + void testGetLibraryFiles_skipsZeroByteFiles() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Files.createFile(tempDir.resolve("empty.epub")); + Files.write(tempDir.resolve("real.epub"), new byte[]{1, 2, 3}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + assertThat(files).hasSize(1); + assertThat(files.getFirst().getFileName()).isEqualTo("real.epub"); + } + + @Test + void testGetLibraryFiles_includesNonZeroByteFiles() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Files.write(tempDir.resolve("book1.epub"), new byte[]{1}); + Files.write(tempDir.resolve("book2.pdf"), new byte[]{1, 2}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + assertThat(files).hasSize(2); + } + + @Test + void recognizesAllSupportedExtensions() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + for (String ext : List.of("pdf", "epub", "cbz", "cbr", "cb7", "mobi", "azw3", "azw", "fb2", "m4b", "m4a", "mp3")) { + Files.write(tempDir.resolve("book." + ext), new byte[]{1}); + } + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + assertThat(files).hasSize(12); + } + + @Test + void ignoresUnrecognizedExtensions() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Files.write(tempDir.resolve("book.lit"), new byte[]{1}); + Files.write(tempDir.resolve("book.lrf"), new byte[]{1}); + Files.write(tempDir.resolve("book.txt"), new byte[]{1}); + Files.write(tempDir.resolve("cover.jpg"), new byte[]{1}); + Files.write(tempDir.resolve("real.epub"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + assertThat(files).hasSize(1); + assertThat(files.getFirst().getFileName()).isEqualTo("real.epub"); + } + + @Test + void classifiesEbookAndAudiobookTypes() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Files.write(tempDir.resolve("book.epub"), new byte[]{1}); + Files.write(tempDir.resolve("book.m4b"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + assertThat(files).hasSize(2); + + LibraryFile epub = files.stream().filter(f -> f.getFileName().equals("book.epub")).findFirst().orElseThrow(); + LibraryFile m4b = files.stream().filter(f -> f.getFileName().equals("book.m4b")).findFirst().orElseThrow(); + + assertThat(epub.getBookFileType()).isEqualTo(BookFileType.EPUB); + assertThat(m4b.getBookFileType()).isEqualTo(BookFileType.AUDIOBOOK); + } + + @Test + void collapsesMultipleAudioFilesInSubfolderToFolderBased() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Path audioDir = Files.createDirectories(tempDir.resolve("Author/Book/audiobook")); + for (int i = 1; i <= 5; i++) { + Files.write(audioDir.resolve("chapter" + i + ".mp3"), new byte[]{1}); + } + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + + assertThat(files).hasSize(1); + assertThat(files.getFirst().isFolderBased()).isTrue(); + assertThat(files.getFirst().getBookFileType()).isEqualTo(BookFileType.AUDIOBOOK); + assertThat(files.getFirst().getFileName()).isEqualTo("audiobook"); + } + + @Test + void singleAudioFileInSubfolderStaysIndividual() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Path audioDir = Files.createDirectories(tempDir.resolve("Author/Book")); + Files.write(audioDir.resolve("standalone.m4b"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + + assertThat(files).hasSize(1); + assertThat(files.getFirst().isFolderBased()).isFalse(); + assertThat(files.getFirst().getFileName()).isEqualTo("standalone.m4b"); + } + + @Test + void rootLevelAudioFilesNeverCollapse() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Files.write(tempDir.resolve("track1.mp3"), new byte[]{1}); + Files.write(tempDir.resolve("track2.mp3"), new byte[]{1}); + Files.write(tempDir.resolve("track3.mp3"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + + assertThat(files).hasSize(3); + assertThat(files).noneMatch(LibraryFile::isFolderBased); + } + + @Test + void structure3_chapterMp3sCollapsePerSubfolder() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Path parent = Files.createDirectories(tempDir.resolve("J K Rowling - HP Audiobooks")); + Path book1 = Files.createDirectories(parent.resolve("1 Philosopher's Stone")); + Path book2 = Files.createDirectories(parent.resolve("2 Chamber of Secrets")); + + for (int i = 1; i <= 17; i++) { + Files.write(book1.resolve(String.format("CH%02d.mp3", i)), new byte[]{1}); + } + for (int i = 1; i <= 18; i++) { + Files.write(book2.resolve(String.format("CH%02d.mp3", i)), new byte[]{1}); + } + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + + assertThat(files).hasSize(2); + assertThat(files).allMatch(LibraryFile::isFolderBased); + assertThat(files).allMatch(f -> f.getBookFileType() == BookFileType.AUDIOBOOK); + } + + @Test + void structure4_ebooksAndAudiobookSubfolderDiscoveredCorrectly() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Path catchingFire = Files.createDirectories(tempDir.resolve("Suzanne Collins/Catching Fire")); + Files.write(catchingFire.resolve("Catching Fire - Suzanne Collins.azw3"), new byte[]{1}); + Files.write(catchingFire.resolve("Catching Fire - Suzanne Collins.epub"), new byte[]{1}); + + Path audioDir = Files.createDirectories(catchingFire.resolve("audiobook")); + for (int i = 1; i <= 10; i++) { + Files.write(audioDir.resolve(String.format("Catching Fire %03d.mp3", i)), new byte[]{1}); + } + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + + long ebookCount = files.stream().filter(f -> f.getBookFileType() != BookFileType.AUDIOBOOK).count(); + long audiobookCount = files.stream().filter(f -> f.getBookFileType() == BookFileType.AUDIOBOOK).count(); + long folderBasedCount = files.stream().filter(LibraryFile::isFolderBased).count(); + + assertThat(ebookCount).isEqualTo(2); + assertThat(audiobookCount).isEqualTo(1); + assertThat(folderBasedCount).isEqualTo(1); + assertThat(files).hasSize(3); + } + + @Test + void structure1_flatRootFilesAllDiscovered() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Files.write(tempDir.resolve("Salem's Lot.epub"), new byte[]{1}); + Files.write(tempDir.resolve("Good Spirits.epub"), new byte[]{1}); + Files.write(tempDir.resolve("Hansel and Gretel.epub"), new byte[]{1}); + Files.write(tempDir.resolve("Hansel and Gretel.m4b"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + + assertThat(files).hasSize(4); + assertThat(files).noneMatch(LibraryFile::isFolderBased); + assertThat(files).allMatch(f -> f.getFileSubPath() == null || f.getFileSubPath().isEmpty()); + } + + @Test + void nestedFiles_haveCorrectSubPaths() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Path titleDir = Files.createDirectories(tempDir.resolve("Andy Weir/The Martian")); + Files.write(titleDir.resolve("The Martian.epub"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + + assertThat(files).hasSize(1); + assertThat(files.getFirst().getFileSubPath()).isEqualTo("Andy Weir/The Martian"); + } + + @Test + void ignoresHiddenFiles() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Files.write(tempDir.resolve(".DS_Store"), new byte[]{1}); + Files.write(tempDir.resolve(".hidden.epub"), new byte[]{1}); + Files.write(tempDir.resolve("visible.epub"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + + assertThat(files).hasSize(1); + assertThat(files.getFirst().getFileName()).isEqualTo("visible.epub"); + } + + @Test + void ignoresTempFiles() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Files.write(tempDir.resolve("book.epub.part"), new byte[]{1}); + Files.write(tempDir.resolve("book.epub.tmp"), new byte[]{1}); + Files.write(tempDir.resolve("book.epub.crdownload"), new byte[]{1}); + Files.write(tempDir.resolve("real.epub"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + + assertThat(files).hasSize(1); + } + + @Test + void ignoresSystemDirectories() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + for (String sysDir : List.of("#recycle", "@eaDir", ".caltrash")) { + Path dir = Files.createDirectories(tempDir.resolve(sysDir)); + Files.write(dir.resolve("book.epub"), new byte[]{1}); + } + Files.write(tempDir.resolve("real.epub"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + + assertThat(files).hasSize(1); + assertThat(files.getFirst().getFileName()).isEqualTo("real.epub"); + } + + private LibraryEntity createLibraryWithMode(Path path, LibraryOrganizationMode mode) { + LibraryPathEntity libraryPath = new LibraryPathEntity(); + libraryPath.setId(1L); + libraryPath.setPath(path.toString()); + + return LibraryEntity.builder() + .name("Test Library") + .icon("book") + .watch(false) + .organizationMode(mode) + .libraryPaths(List.of(libraryPath)) + .build(); + } + + @Test + void autoDetect_collapsesAudiobookSubfolderSameAsOtherModes() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Path audioDir = Files.createDirectories(tempDir.resolve("HP Book 1")); + for (int i = 1; i <= 5; i++) { + Files.write(audioDir.resolve("ch" + i + ".mp3"), new byte[]{1}); + } + + List files = helper.getLibraryFiles(createLibraryWithMode(tempDir, LibraryOrganizationMode.AUTO_DETECT)); + + assertThat(files).hasSize(1); + assertThat(files.getFirst().isFolderBased()).isTrue(); + } + + @Test + void autoDetect_singleAudioFileStaysIndividual() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Path dir = Files.createDirectories(tempDir.resolve("Book")); + Files.write(dir.resolve("book.m4b"), new byte[]{1}); + Files.write(dir.resolve("book.epub"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibraryWithMode(tempDir, LibraryOrganizationMode.AUTO_DETECT)); + + assertThat(files).hasSize(2); + assertThat(files).noneMatch(LibraryFile::isFolderBased); + } + + @Test + void deeplyNestedFilesAreDiscovered() throws IOException { + LibraryFileHelper helper = new LibraryFileHelper(); + + Path deep = Files.createDirectories(tempDir.resolve("A/B/C/D/E")); + Files.write(deep.resolve("deep.epub"), new byte[]{1}); + + List files = helper.getLibraryFiles(createLibrary(tempDir)); + + assertThat(files).hasSize(1); + assertThat(files.getFirst().getFileSubPath()).isEqualTo("A/B/C/D/E"); + } } diff --git a/booklore-api/src/test/java/org/booklore/service/library/LibraryServiceIconTest.java b/booklore-api/src/test/java/org/booklore/service/library/LibraryServiceIconTest.java index df8af07c8..770b987b9 100644 --- a/booklore-api/src/test/java/org/booklore/service/library/LibraryServiceIconTest.java +++ b/booklore-api/src/test/java/org/booklore/service/library/LibraryServiceIconTest.java @@ -24,7 +24,7 @@ import org.booklore.repository.LibraryPathRepository; import org.booklore.repository.UserRepository; import org.booklore.model.entity.BookLoreUserEntity; import org.booklore.service.NotificationService; -import org.booklore.service.monitoring.MonitoringService; +import org.booklore.service.monitoring.LibraryWatchService; import org.booklore.util.FileService; import java.util.Collections; @@ -56,7 +56,7 @@ class LibraryServiceIconTest { @Mock private FileService fileService; @Mock - private MonitoringService monitoringService; + private LibraryWatchService libraryWatchService; @Mock private AuthenticationService authenticationService; @Mock diff --git a/booklore-api/src/test/java/org/booklore/service/monitoring/LibraryWatchServiceTest.java b/booklore-api/src/test/java/org/booklore/service/monitoring/LibraryWatchServiceTest.java new file mode 100644 index 000000000..65dc20a08 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/monitoring/LibraryWatchServiceTest.java @@ -0,0 +1,153 @@ +package org.booklore.service.monitoring; + +import org.booklore.model.dto.Library; +import org.booklore.model.dto.LibraryPath; +import org.booklore.model.enums.BookFileExtension; +import org.booklore.service.watcher.LibraryFileEventProcessor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; + +class LibraryWatchServiceTest { + + @TempDir + Path tmp; + + LibraryWatchService service; + LibraryFileEventProcessor processor; + + @BeforeEach + void setup() throws Exception { + processor = mock(LibraryFileEventProcessor.class); + service = new LibraryWatchService(processor); + } + + @AfterEach + void teardown() { + try { + service.shutdown(); + } catch (Exception ignored) {} + } + + @Test + void registerLibrary_registersAllDirectoriesUnderLibraryPath() throws Exception { + Path root = tmp.resolve("libroot"); + Path a = root.resolve("a"); + Path b = a.resolve("b"); + Files.createDirectories(b); + + Library lib = mock(Library.class); + LibraryPath lp = mock(LibraryPath.class); + when(lp.getPath()).thenReturn(root.toString()); + when(lib.getPaths()).thenReturn(List.of(lp)); + when(lib.getId()).thenReturn(7L); + when(lib.getName()).thenReturn("my-lib"); + when(lib.isWatch()).thenReturn(true); + + service.registerLibrary(lib); + + assertThat(service.isPathMonitored(root)).isTrue(); + assertThat(service.isPathMonitored(a)).isTrue(); + assertThat(service.isPathMonitored(b)).isTrue(); + } + + @Test + void unregisterLibrary_removesRegisteredPaths() throws Exception { + Path root = tmp.resolve("libroot2"); + Files.createDirectories(root); + + service.registerPath(root, 99L); + assertThat(service.isPathMonitored(root)).isTrue(); + + service.unregisterLibrary(99L); + assertThat(service.isPathMonitored(root)).isFalse(); + } + + @Test + void registerPath_succeedsForDirectories() throws Exception { + Path dir = tmp.resolve("regdir"); + Files.createDirectories(dir); + + boolean registered = service.registerPath(dir, 55L); + assertThat(registered).isTrue(); + assertThat(service.isPathMonitored(dir)).isTrue(); + } + + @Test + void registerPath_failsForFilesAndMissingPaths() throws Exception { + Path file = tmp.resolve("file.txt"); + Files.writeString(file, "content"); + + assertThat(service.registerPath(file, 1L)).isFalse(); + + Path missing = tmp.resolve("missing"); + assertThat(service.registerPath(missing, 1L)).isFalse(); + } + + @Test + void registerPath_duplicateRegistrationReturnsFalse() throws Exception { + Path dir = tmp.resolve("dupdir"); + Files.createDirectories(dir); + + assertThat(service.registerPath(dir, 10L)).isTrue(); + assertThat(service.registerPath(dir, 10L)).isFalse(); + } + + @Test + void isPathMonitored_handlesNonNormalizedPaths() throws Exception { + Path root = tmp.resolve("libroot-norm"); + Path sub = root.resolve("subdir"); + Files.createDirectories(sub); + + service.registerPath(sub, 1L); + + Path nonNormalized = root.resolve("subdir/../subdir/."); + assertThat(service.isPathMonitored(nonNormalized)).isTrue(); + } + + @Test + void getPathsForLibraries_returnsCorrectPaths() throws Exception { + Path dir1 = tmp.resolve("lib1"); + Path dir2 = tmp.resolve("lib2"); + Files.createDirectories(dir1); + Files.createDirectories(dir2); + + service.registerPath(dir1, 1L); + service.registerPath(dir2, 2L); + + Set paths = service.getPathsForLibraries(Set.of(1L)); + assertThat(paths).containsExactly(dir1); + } + + @Test + void isRelevantBookFile_detectsBookExtensions() { + assertThat(service.isRelevantBookFile(Paths.get("book.pdf"))).isTrue(); + assertThat(service.isRelevantBookFile(Paths.get("book.epub"))).isTrue(); + assertThat(service.isRelevantBookFile(Paths.get("notes.txt"))).isFalse(); + } + + @Test + void isLibraryMonitored_reflectsWatchStatus() { + Library lib = mock(Library.class); + when(lib.getId()).thenReturn(5L); + when(lib.isWatch()).thenReturn(true); + when(lib.getPaths()).thenReturn(List.of()); + when(lib.getName()).thenReturn("test"); + + service.registerLibrary(lib); + assertThat(service.isLibraryMonitored(5L)).isTrue(); + + service.unregisterLibrary(5L); + assertThat(service.isLibraryMonitored(5L)).isFalse(); + } +} diff --git a/booklore-api/src/test/java/org/booklore/service/monitoring/MonitoringRegistrationServiceTest.java b/booklore-api/src/test/java/org/booklore/service/monitoring/MonitoringRegistrationServiceTest.java index 86d5b8158..ea6bdafd1 100644 --- a/booklore-api/src/test/java/org/booklore/service/monitoring/MonitoringRegistrationServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/service/monitoring/MonitoringRegistrationServiceTest.java @@ -4,7 +4,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -12,7 +11,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -21,7 +19,7 @@ import static org.mockito.Mockito.*; class MonitoringRegistrationServiceTest { @Mock - MonitoringService monitoringService; + LibraryWatchService libraryWatchService; @InjectMocks MonitoringRegistrationService registrationService; @@ -42,97 +40,45 @@ class MonitoringRegistrationServiceTest { } @Test - void isPathMonitored_delegatesToMonitoringService() { - when(monitoringService.isPathMonitored(root)).thenReturn(true); + void isPathMonitored_delegatesToLibraryWatchService() { + when(libraryWatchService.isPathMonitored(root)).thenReturn(true); assertTrue(registrationService.isPathMonitored(root)); - verify(monitoringService).isPathMonitored(root); + verify(libraryWatchService).isPathMonitored(root); } @Test void unregisterSpecificPath_delegates() { registrationService.unregisterSpecificPath(root); - verify(monitoringService).unregisterPath(root); + verify(libraryWatchService).unregisterPath(root); } @Test void registerSpecificPath_delegates() { registrationService.registerSpecificPath(root, 123L); - verify(monitoringService).registerPath(root, 123L); + verify(libraryWatchService).registerPath(root, 123L); } @Test void unregisterLibrary_delegates() { registrationService.unregisterLibrary(99L); - verify(monitoringService).unregisterLibrary(99L); + verify(libraryWatchService).unregisterLibrary(99L); } @Test void registerLibraryPaths_noopWhenMissingOrNotDirectory() throws IOException { Path missing = tmp.resolve("does-not-exist"); registrationService.registerLibraryPaths(7L, missing); - verifyNoInteractions(monitoringService); + verify(libraryWatchService).registerLibraryPaths(7L, missing); Path file = tmp.resolve("afile.txt"); Files.writeString(file, "x"); registrationService.registerLibraryPaths(7L, file); - verifyNoInteractions(monitoringService); + verify(libraryWatchService).registerLibraryPaths(7L, file); } @Test - void registerLibraryPaths_registersRootAndAllSubdirs() { + void registerLibraryPaths_delegates() { registrationService.registerLibraryPaths(42L, root); - - verify(monitoringService).registerPath(root, 42L); - - // subdirs a and a/b should be registered as well - verify(monitoringService).registerPath(sub1, 42L); - verify(monitoringService).registerPath(sub2, 42L); - - ArgumentCaptor capt = ArgumentCaptor.forClass(Path.class); - verify(monitoringService, atLeast(3)).registerPath(capt.capture(), eq(42L)); - List registered = capt.getAllValues(); - assertTrue(registered.contains(root)); - assertTrue(registered.contains(sub1)); - assertTrue(registered.contains(sub2)); - } - - @Test - void registerLibraryPaths_handlesMonitoringServiceExceptionGracefully() { - doThrow(new RuntimeException("boom")).when(monitoringService).registerPath(eq(root), eq(55L)); - assertDoesNotThrow(() -> registrationService.registerLibraryPaths(55L, root)); - verify(monitoringService).registerPath(root, 55L); - } - - @Test - void registerLibraryPaths_partialFailureStops() { - doAnswer(invocation -> { - Path p = invocation.getArgument(0); - Long id = invocation.getArgument(1); - if (id != null && id.equals(42L) && p.getFileName() != null && "a".equals(p.getFileName().toString())) { - throw new RuntimeException("fail-sub1"); - } - return null; - }).when(monitoringService).registerPath(any(Path.class), anyLong()); - - registrationService.registerLibraryPaths(42L, root); - - verify(monitoringService).registerPath(root, 42L); - verify(monitoringService).registerPath(argThat(p -> p.getFileName() != null && "a".equals(p.getFileName().toString())), eq(42L)); - verify(monitoringService, never()).registerPath(argThat(p -> p.getFileName() != null && "b".equals(p.getFileName().toString())), eq(42L)); - } - - @Test - void registerLibraryPaths_onlyRegistersDirectories() throws IOException { - Path fileInRoot = root.resolve("file.txt"); - Files.createDirectories(root); - Files.writeString(fileInRoot, "content"); - - registrationService.registerLibraryPaths(100L, root); - - verify(monitoringService).registerPath(root, 100L); - verify(monitoringService).registerPath(sub1, 100L); - verify(monitoringService).registerPath(sub2, 100L); - - verify(monitoringService, never()).registerPath(eq(fileInRoot), anyLong()); + verify(libraryWatchService).registerLibraryPaths(42L, root); } } diff --git a/booklore-api/src/test/java/org/booklore/service/monitoring/MonitoringServiceTest.java b/booklore-api/src/test/java/org/booklore/service/monitoring/MonitoringServiceTest.java deleted file mode 100644 index e61e9004d..000000000 --- a/booklore-api/src/test/java/org/booklore/service/monitoring/MonitoringServiceTest.java +++ /dev/null @@ -1,286 +0,0 @@ -package org.booklore.service.monitoring; - -import org.booklore.model.dto.Library; -import org.booklore.model.dto.LibraryPath; -import org.booklore.service.watcher.LibraryFileEventProcessor; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.mockito.Mockito; - -import java.lang.reflect.Field; -import java.nio.file.*; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -class MonitoringServiceTest { - - @TempDir - Path tmp; - - MonitoringService service; - LibraryFileEventProcessor processor; - MonitoringTask monitoringTask; - WatchService watchService; - - @BeforeEach - void setup() throws Exception { - processor = mock(LibraryFileEventProcessor.class); - monitoringTask = mock(MonitoringTask.class); - watchService = FileSystems.getDefault().newWatchService(); - service = Mockito.spy(new MonitoringService(processor, watchService, monitoringTask)); - } - - @AfterEach - void teardown() { - try { - service.stopMonitoring(); - } catch (Exception ignored) {} - try { watchService.close(); } catch (Exception ignored) {} - } - - @Test - void registerLibrary_registersAllDirectoriesUnderLibraryPath() throws Exception { - Path root = tmp.resolve("libroot"); - Path a = root.resolve("a"); - Path b = a.resolve("b"); - Files.createDirectories(b); - - Library lib = mock(Library.class); - LibraryPath lp = mock(LibraryPath.class); - when(lp.getPath()).thenReturn(root.toString()); - when(lib.getPaths()).thenReturn(List.of(lp)); - when(lib.getId()).thenReturn(7L); - when(lib.getName()).thenReturn("my-lib"); - when(lib.isWatch()).thenReturn(true); - - doReturn(true).when(service).registerPath(any(Path.class), eq(7L)); - - service.registerLibrary(lib); - - Files.walk(root).filter(Files::isDirectory).forEach(path -> - verify(service).registerPath(eq(path), eq(7L)) - ); - } - - @Test - void unregisterLibrary_removesRegisteredPathsAndUpdatesMaps() throws Exception { - Path root = tmp.resolve("libroot2"); - Files.createDirectories(root); - - Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap"); - pathToLibraryField.setAccessible(true); - @SuppressWarnings("unchecked") - Map map = (Map) pathToLibraryField.get(service); - map.put(root, 99L); - - Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths"); - monitoredPathsField.setAccessible(true); - @SuppressWarnings("unchecked") - Set monitored = (Set) monitoredPathsField.get(service); - monitored.add(root); - - Field registeredKeysField = MonitoringService.class.getDeclaredField("registeredWatchKeys"); - registeredKeysField.setAccessible(true); - @SuppressWarnings("unchecked") - Map keys = (Map) registeredKeysField.get(service); - WatchKey mockKey = mock(WatchKey.class); - keys.put(root, mockKey); - - service.unregisterLibrary(99L); - - assertFalse(monitored.contains(root), "monitoredPaths should no longer contain root"); - assertFalse(map.containsKey(root), "pathToLibraryIdMap should no longer contain root"); - assertFalse(keys.containsKey(root), "registeredWatchKeys should no longer contain root"); - verify(mockKey).cancel(); - } - - @Test - void handleFileChangeEvent_createDirectory_registersNestedPaths() throws Exception { - Path watched = tmp.resolve("watched"); - Files.createDirectories(watched); - Path newDir = watched.resolve("newdir"); - Files.createDirectories(newDir); - - Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap"); - pathToLibraryField.setAccessible(true); - @SuppressWarnings("unchecked") - Map map = (Map) pathToLibraryField.get(service); - map.put(watched, 5L); - - doReturn(true).when(service).registerPath(any(Path.class), eq(5L)); - - FileChangeEvent ev = mock(FileChangeEvent.class); - when(ev.getFilePath()).thenReturn(newDir); - doReturn(StandardWatchEventKinds.ENTRY_CREATE).when(ev).getEventKind(); - when(ev.getWatchedFolder()).thenReturn(watched); - - service.handleFileChangeEvent(ev); - - Files.walk(newDir).filter(Files::isDirectory).forEach(p -> verify(service).registerPath(eq(p), eq(5L))); - } - - @Test - void backgroundProcessor_processesQueuedEvents_and_callsProcessor() throws Exception { - Path watched = tmp.resolve("wf"); - Files.createDirectories(watched); - Path file = watched.resolve("book.pdf"); - Files.writeString(file, "x"); - - Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap"); - pathToLibraryField.setAccessible(true); - @SuppressWarnings("unchecked") - Map map = (Map) pathToLibraryField.get(service); - map.put(watched, 123L); - - java.lang.reflect.Method startMethod = MonitoringService.class.getDeclaredMethod("startProcessingThread"); - startMethod.setAccessible(true); - startMethod.invoke(service); - - FileChangeEvent ev = mock(FileChangeEvent.class); - when(ev.getFilePath()).thenReturn(file); - doReturn(StandardWatchEventKinds.ENTRY_CREATE).when(ev).getEventKind(); - when(ev.getWatchedFolder()).thenReturn(watched); - - service.handleFileChangeEvent(ev); - - verify(processor, timeout(2_000)).processFile(eq(StandardWatchEventKinds.ENTRY_CREATE), eq(123L), eq(watched.toString()), eq(file.toString())); - } - - @Test - void handleWatchKeyInvalidation_removesInvalidPath_and_cancelsKey() throws Exception { - Path invalid = tmp.resolve("inv"); - Files.createDirectories(invalid); - - Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths"); - monitoredPathsField.setAccessible(true); - @SuppressWarnings("unchecked") - Set monitored = (Set) monitoredPathsField.get(service); - monitored.add(invalid); - - Field registeredKeysField = MonitoringService.class.getDeclaredField("registeredWatchKeys"); - registeredKeysField.setAccessible(true); - @SuppressWarnings("unchecked") - Map keys = (Map) registeredKeysField.get(service); - WatchKey wk = mock(WatchKey.class); - keys.put(invalid, wk); - - WatchKeyInvalidatedEvent ev = mock(WatchKeyInvalidatedEvent.class); - when(ev.getInvalidPath()).thenReturn(invalid); - - service.handleWatchKeyInvalidation(ev); - - assertFalse(monitored.contains(invalid)); - assertFalse(keys.containsKey(invalid)); - verify(wk).cancel(); - } - - @Test - void isRelevantBookFile_detectsBookExtensions() { - Path pdf = Paths.get("somebook.pdf"); - Path txt = Paths.get("notes.txt"); - - assertTrue(service.isRelevantBookFile(pdf)); - assertFalse(service.isRelevantBookFile(txt)); - } - - @Test - void handleFileChangeEvent_ignoresIrrelevantNonBookFile() throws Exception { - Path watched = tmp.resolve("watched-ignore"); - Files.createDirectories(watched); - Path file = watched.resolve("notes.txt"); - Files.writeString(file, "notes"); - - Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap"); - pathToLibraryField.setAccessible(true); - @SuppressWarnings("unchecked") - Map map = (Map) pathToLibraryField.get(service); - map.put(watched, 11L); - - java.lang.reflect.Method startMethod = MonitoringService.class.getDeclaredMethod("startProcessingThread"); - startMethod.setAccessible(true); - startMethod.invoke(service); - - FileChangeEvent ev = mock(FileChangeEvent.class); - when(ev.getFilePath()).thenReturn(file); - doReturn(StandardWatchEventKinds.ENTRY_CREATE).when(ev).getEventKind(); - when(ev.getWatchedFolder()).thenReturn(watched); - - service.handleFileChangeEvent(ev); - - verify(processor, timeout(500).times(0)).processFile(any(), anyLong(), anyString(), anyString()); - } - - @Test - void handleFileChangeEvent_deleteDirectory_unregistersSubPaths() throws Exception { - Path watched = tmp.resolve("watched-del"); - Path a = watched.resolve("a"); - Path b = a.resolve("b"); - Files.createDirectories(b); - - Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths"); - monitoredPathsField.setAccessible(true); - @SuppressWarnings("unchecked") - Set monitored = (Set) monitoredPathsField.get(service); - monitored.add(watched); - monitored.add(a); - monitored.add(b); - - FileChangeEvent ev = mock(FileChangeEvent.class); - when(ev.getFilePath()).thenReturn(a); - doReturn(StandardWatchEventKinds.ENTRY_DELETE).when(ev).getEventKind(); - when(ev.getWatchedFolder()).thenReturn(watched); - - service.handleFileChangeEvent(ev); - - assertFalse(monitored.contains(a)); - assertFalse(monitored.contains(b)); - assertTrue(monitored.contains(watched)); - } - - @Test - void isPathMonitored_handlesNonNormalizedPaths() throws Exception { - Path root = tmp.resolve("libroot-norm"); - Path sub = root.resolve("subdir"); - Files.createDirectories(sub); - - Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths"); - monitoredPathsField.setAccessible(true); - @SuppressWarnings("unchecked") - Set monitored = (Set) monitoredPathsField.get(service); - monitored.add(sub.toAbsolutePath().normalize()); - - Path nonNormalized = root.resolve("subdir/../subdir/."); - assertTrue(service.isPathMonitored(nonNormalized)); - } - - @Test - void registerPath_successful_updatesInternalMapsAndSets() throws Exception { - Path dir = tmp.resolve("regdir"); - Files.createDirectories(dir); - - boolean registered = service.registerPath(dir, 55L); - assertTrue(registered); - - Field pathToLibraryField = MonitoringService.class.getDeclaredField("pathToLibraryIdMap"); - pathToLibraryField.setAccessible(true); - @SuppressWarnings("unchecked") - Map map = (Map) pathToLibraryField.get(service); - assertEquals(55L, map.get(dir)); - - Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths"); - monitoredPathsField.setAccessible(true); - @SuppressWarnings("unchecked") - Set monitored = (Set) monitoredPathsField.get(service); - assertTrue(monitored.contains(dir)); - - Field keysField = MonitoringService.class.getDeclaredField("registeredWatchKeys"); - keysField.setAccessible(true); - @SuppressWarnings("unchecked") - Map keys = (Map) keysField.get(service); - assertTrue(keys.containsKey(dir)); - } -} diff --git a/booklore-api/src/test/java/org/booklore/service/watcher/BookFilePersistenceServiceTest.java b/booklore-api/src/test/java/org/booklore/service/watcher/BookFilePersistenceServiceTest.java new file mode 100644 index 000000000..879ab71f5 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/watcher/BookFilePersistenceServiceTest.java @@ -0,0 +1,432 @@ +package org.booklore.service.watcher; + +import org.booklore.mapper.BookMapper; +import org.booklore.model.entity.*; +import org.booklore.model.enums.BookFileType; +import org.booklore.repository.BookFileRepository; +import org.booklore.repository.BookRepository; +import org.booklore.service.NotificationService; +import org.booklore.util.FileUtils; +import jakarta.persistence.EntityManager; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; + +import java.nio.file.Path; +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.*; + +import org.booklore.service.watcher.PendingDeletionPool.BookSnapshot; +import org.booklore.service.watcher.PendingDeletionPool.FileSnapshot; + +class BookFilePersistenceServiceTest { + + @Mock private EntityManager entityManager; + @Mock private BookRepository bookRepository; + @Mock private BookFileRepository bookFileRepository; + @Mock private NotificationService notificationService; + @Mock private BookMapper bookMapper; + + private BookFilePersistenceService service; + + private AutoCloseable mocks; + private MockedStatic fileUtilsMock; + + private LibraryEntity library; + private LibraryPathEntity libraryPath; + + @BeforeEach + void setUp() { + mocks = MockitoAnnotations.openMocks(this); + service = new BookFilePersistenceService(entityManager, bookRepository, bookFileRepository, notificationService, bookMapper); + + fileUtilsMock = mockStatic(FileUtils.class); + fileUtilsMock.when(() -> FileUtils.getRelativeSubPath(anyString(), any(Path.class))).thenReturn("sub"); + + libraryPath = new LibraryPathEntity(); + libraryPath.setId(1L); + libraryPath.setPath("/library"); + + library = LibraryEntity.builder() + .id(1L) + .name("Test Library") + .libraryPaths(List.of(libraryPath)) + .build(); + } + + @AfterEach + void tearDown() throws Exception { + fileUtilsMock.close(); + mocks.close(); + } + + private BookEntity buildBook(Long id) { + return BookEntity.builder() + .id(id) + .library(library) + .libraryPath(libraryPath) + .deleted(false) + .bookFiles(new ArrayList<>()) + .build(); + } + + private BookFileEntity buildBookFile(Long id, BookEntity book, String fileName, String hash) { + return BookFileEntity.builder() + .id(id) + .book(book) + .fileName(fileName) + .fileSubPath("sub") + .currentHash(hash) + .isBookFormat(true) + .bookType(BookFileType.EPUB) + .build(); + } + + @Nested + class FindMatchingLibraryPath { + + @Test + void matchesFileUnderLibraryPath() { + String result = service.findMatchingLibraryPath(library, Path.of("/library/sub/test.epub")); + + assertThat(result).isEqualTo("/library"); + } + + @Test + void throwsWhenNoMatchingPath() { + assertThatThrownBy(() -> service.findMatchingLibraryPath(library, Path.of("/other/test.epub"))) + .isInstanceOf(Exception.class); + } + + @Test + void matchesDeeperNestedFile() { + String result = service.findMatchingLibraryPath(library, Path.of("/library/a/b/c/test.epub")); + + assertThat(result).isEqualTo("/library"); + } + } + + @Nested + class GetLibraryPathEntityForFile { + + @Test + void returnsMatchingPathEntity() { + LibraryPathEntity result = service.getLibraryPathEntityForFile(library, "/library/sub/test.epub"); + + assertThat(result).isEqualTo(libraryPath); + } + + @Test + void throwsWhenNoMatchingPathEntity() { + assertThatThrownBy(() -> service.getLibraryPathEntityForFile(library, "/other/test.epub")) + .isInstanceOf(Exception.class); + } + + @Test + void picksLongestMatchWhenMultiplePaths() { + LibraryPathEntity deeperPath = new LibraryPathEntity(); + deeperPath.setId(2L); + deeperPath.setPath("/library/sub"); + library.setLibraryPaths(List.of(libraryPath, deeperPath)); + + LibraryPathEntity result = service.getLibraryPathEntityForFile(library, "/library/sub/test.epub"); + + assertThat(result).isEqualTo(deeperPath); + } + } + + @Nested + class UpdatePathIfChanged { + + @Test + void updatesPathWhenSubPathDiffers() { + BookEntity book = buildBook(10L); + BookFileEntity bookFile = buildBookFile(100L, book, "test.epub", "hash123"); + book.setBookFiles(new ArrayList<>(List.of(bookFile))); + + when(entityManager.merge(any(LibraryPathEntity.class))).thenReturn(libraryPath); + fileUtilsMock.when(() -> FileUtils.getRelativeSubPath(anyString(), any(Path.class))).thenReturn("newsub"); + + service.updatePathIfChanged(book, library, Path.of("/library/newsub/test.epub"), "hash123"); + + verify(bookRepository).save(book); + assertThat(bookFile.getFileSubPath()).isEqualTo("newsub"); + } + + @Test + void updatesPathWhenFileNameDiffers() { + BookEntity book = buildBook(10L); + BookFileEntity bookFile = buildBookFile(100L, book, "old.epub", "hash123"); + book.setBookFiles(new ArrayList<>(List.of(bookFile))); + + when(entityManager.merge(any(LibraryPathEntity.class))).thenReturn(libraryPath); + + service.updatePathIfChanged(book, library, Path.of("/library/sub/new.epub"), "hash123"); + + verify(bookRepository).save(book); + assertThat(bookFile.getFileName()).isEqualTo("new.epub"); + } + + @Test + void undeleteBookOnPathUpdate() { + BookEntity book = buildBook(10L); + book.setDeleted(true); + BookFileEntity bookFile = buildBookFile(100L, book, "test.epub", "hash123"); + book.setBookFiles(new ArrayList<>(List.of(bookFile))); + + when(entityManager.merge(any(LibraryPathEntity.class))).thenReturn(libraryPath); + + service.updatePathIfChanged(book, library, Path.of("/library/sub/test.epub"), "hash123"); + + verify(bookRepository).save(book); + assertThat(book.getDeleted()).isFalse(); + assertThat(book.getDeletedAt()).isNull(); + } + + @Test + void skipsSaveWhenNothingChanged() { + BookEntity book = buildBook(10L); + BookFileEntity bookFile = buildBookFile(100L, book, "test.epub", "hash123"); + bookFile.setFileSubPath("sub"); + book.setBookFiles(new ArrayList<>(List.of(bookFile))); + + when(entityManager.merge(any(LibraryPathEntity.class))).thenReturn(libraryPath); + + service.updatePathIfChanged(book, library, Path.of("/library/sub/test.epub"), "hash123"); + + verify(bookRepository, never()).save(any()); + } + + @Test + void matchesFileByHash_notJustPrimary() { + BookEntity book = buildBook(10L); + BookFileEntity primaryFile = buildBookFile(100L, book, "primary.epub", "primaryhash"); + BookFileEntity secondaryFile = buildBookFile(101L, book, "secondary.pdf", "hash123"); + book.setBookFiles(new ArrayList<>(List.of(primaryFile, secondaryFile))); + + when(entityManager.merge(any(LibraryPathEntity.class))).thenReturn(libraryPath); + fileUtilsMock.when(() -> FileUtils.getRelativeSubPath(anyString(), any(Path.class))).thenReturn("newsub"); + + service.updatePathIfChanged(book, library, Path.of("/library/newsub/secondary.pdf"), "hash123"); + + // Should update the secondary file, not primary + assertThat(secondaryFile.getFileSubPath()).isEqualTo("newsub"); + assertThat(secondaryFile.getFileName()).isEqualTo("secondary.pdf"); + verify(bookRepository).save(book); + } + + @Test + void sendsNotificationAfterUpdate() { + BookEntity book = buildBook(10L); + BookFileEntity bookFile = buildBookFile(100L, book, "test.epub", "hash123"); + book.setBookFiles(new ArrayList<>(List.of(bookFile))); + + when(entityManager.merge(any(LibraryPathEntity.class))).thenReturn(libraryPath); + fileUtilsMock.when(() -> FileUtils.getRelativeSubPath(anyString(), any(Path.class))).thenReturn("newsub"); + + service.updatePathIfChanged(book, library, Path.of("/library/newsub/test.epub"), "hash123"); + + verify(notificationService).sendMessageToPermissions(any(), any(), any()); + } + } + + @Nested + class MarkAllBooksUnderPathAsDeleted { + + @Test + void marksAllBooksAsDeleted() { + BookEntity book1 = buildBook(10L); + BookEntity book2 = buildBook(11L); + when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(1L, "sub")) + .thenReturn(List.of(book1, book2)); + + int count = service.markAllBooksUnderPathAsDeleted(1L, "sub"); + + assertThat(count).isEqualTo(2); + assertThat(book1.getDeleted()).isTrue(); + assertThat(book1.getDeletedAt()).isNotNull(); + assertThat(book2.getDeleted()).isTrue(); + verify(bookRepository).saveAll(List.of(book1, book2)); + } + + @Test + void returnsZeroWhenNoBooksFound() { + when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(1L, "empty")) + .thenReturn(List.of()); + + int count = service.markAllBooksUnderPathAsDeleted(1L, "empty"); + + assertThat(count).isZero(); + } + + @Test + void throwsOnNullRelativePath() { + assertThatThrownBy(() -> service.markAllBooksUnderPathAsDeleted(1L, null)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Nested + class DelegationMethods { + + @Test + void findByLibraryPathSubPathAndFileName_delegates() { + when(bookRepository.findByLibraryPath_IdAndFileSubPathAndFileName(1L, "sub", "test.epub")) + .thenReturn(Optional.of(buildBook(10L))); + + Optional result = service.findByLibraryPathSubPathAndFileName(1L, "sub", "test.epub"); + + assertThat(result).isPresent(); + } + + @Test + void findBookFileByLibraryPathSubPathAndFileName_delegates() { + BookFileEntity bookFile = buildBookFile(100L, buildBook(10L), "test.epub", "hash"); + when(bookFileRepository.findByLibraryPathIdAndFileSubPathAndFileName(1L, "sub", "test.epub")) + .thenReturn(Optional.of(bookFile)); + + Optional result = service.findBookFileByLibraryPathSubPathAndFileName(1L, "sub", "test.epub"); + + assertThat(result).isPresent(); + assertThat(result.get().getFileName()).isEqualTo("test.epub"); + } + + @Test + void deleteBookFile_delegates() { + BookFileEntity bookFile = buildBookFile(100L, buildBook(10L), "test.epub", "hash"); + + service.deleteBookFile(bookFile); + + verify(bookFileRepository).delete(bookFile); + } + + @Test + void markBookAsDeleted_setsDeletedFields() { + BookEntity book = buildBook(10L); + + service.markBookAsDeleted(book); + + assertThat(book.getDeleted()).isTrue(); + assertThat(book.getDeletedAt()).isNotNull(); + verify(bookRepository).save(book); + } + + @Test + void save_delegates() { + BookEntity book = buildBook(10L); + + service.save(book); + + verify(bookRepository).save(book); + } + + @Test + void countBookFilesByBookId_delegates() { + when(bookFileRepository.countByBookId(10L)).thenReturn(3L); + + long count = service.countBookFilesByBookId(10L); + + assertThat(count).isEqualTo(3L); + } + } + + @Nested + class RecoverFolderBook { + + @Test + void recoversBookAndUpdatesFiles() { + BookEntity book = buildBook(10L); + book.setDeleted(true); + BookFileEntity bookFile = buildBookFile(100L, book, "old.epub", "filehash1"); + book.setBookFiles(new ArrayList<>(List.of(bookFile))); + + var fileSnap = new FileSnapshot(100L, "old.epub", "sub", "filehash1", false, BookFileType.EPUB); + var bookSnap = new BookSnapshot(10L, 1L, "sub", List.of(fileSnap)); + + when(bookRepository.findById(10L)).thenReturn(Optional.of(book)); + when(bookFileRepository.findById(100L)).thenReturn(Optional.of(bookFile)); + when(entityManager.merge(any(LibraryPathEntity.class))).thenReturn(libraryPath); + fileUtilsMock.when(() -> FileUtils.getRelativeSubPath(anyString(), any(Path.class))).thenReturn("newsub"); + + Map fileHashes = Map.of(Path.of("/library/newsub/new.epub"), "filehash1"); + + service.recoverFolderBook(bookSnap, libraryPath, Path.of("/library/newsub"), fileHashes); + + assertThat(book.getDeleted()).isFalse(); + assertThat(book.getDeletedAt()).isNull(); + assertThat(bookFile.getFileName()).isEqualTo("new.epub"); + assertThat(bookFile.getFileSubPath()).isEqualTo("newsub"); + verify(bookRepository).save(book); + verify(notificationService).sendMessageToPermissions(any(), any(), any()); + } + + @Test + void bookNotFound_doesNothing() { + var bookSnap = new BookSnapshot(999L, 1L, "sub", List.of()); + when(bookRepository.findById(999L)).thenReturn(Optional.empty()); + + service.recoverFolderBook(bookSnap, libraryPath, Path.of("/library"), Map.of()); + + verify(bookRepository, never()).save(any()); + } + + @Test + void multipleFilesRecovered() { + BookEntity book = buildBook(10L); + book.setDeleted(true); + BookFileEntity file1 = buildBookFile(100L, book, "a.epub", "hash1"); + BookFileEntity file2 = buildBookFile(101L, book, "b.epub", "hash2"); + book.setBookFiles(new ArrayList<>(List.of(file1, file2))); + + var snap1 = new FileSnapshot(100L, "a.epub", "sub", "hash1", false, BookFileType.EPUB); + var snap2 = new FileSnapshot(101L, "b.epub", "sub", "hash2", false, BookFileType.EPUB); + var bookSnap = new BookSnapshot(10L, 1L, "sub", List.of(snap1, snap2)); + + when(bookRepository.findById(10L)).thenReturn(Optional.of(book)); + when(bookFileRepository.findById(100L)).thenReturn(Optional.of(file1)); + when(bookFileRepository.findById(101L)).thenReturn(Optional.of(file2)); + when(entityManager.merge(any(LibraryPathEntity.class))).thenReturn(libraryPath); + fileUtilsMock.when(() -> FileUtils.getRelativeSubPath(eq("/library"), eq(Path.of("/new/a.epub")))).thenReturn("newsub1"); + fileUtilsMock.when(() -> FileUtils.getRelativeSubPath(eq("/library"), eq(Path.of("/new/b.epub")))).thenReturn("newsub2"); + + Map fileHashes = Map.of( + Path.of("/new/a.epub"), "hash1", + Path.of("/new/b.epub"), "hash2"); + + service.recoverFolderBook(bookSnap, libraryPath, Path.of("/new"), fileHashes); + + assertThat(book.getDeleted()).isFalse(); + verify(bookRepository).save(book); + } + + @Test + void fileSnapshotWithNoHashMatch_leftUnchanged() { + BookEntity book = buildBook(10L); + BookFileEntity bookFile = buildBookFile(100L, book, "old.epub", "oldhash"); + book.setBookFiles(new ArrayList<>(List.of(bookFile))); + + var fileSnap = new FileSnapshot(100L, "old.epub", "sub", "nomatch", false, BookFileType.EPUB); + var bookSnap = new BookSnapshot(10L, 1L, "sub", List.of(fileSnap)); + + when(bookRepository.findById(10L)).thenReturn(Optional.of(book)); + when(bookFileRepository.findById(100L)).thenReturn(Optional.of(bookFile)); + when(entityManager.merge(any(LibraryPathEntity.class))).thenReturn(libraryPath); + + Map fileHashes = Map.of(Path.of("/new/other.epub"), "differenthash"); + + service.recoverFolderBook(bookSnap, libraryPath, Path.of("/new"), fileHashes); + + // File name should remain unchanged since hash didn't match + assertThat(bookFile.getFileName()).isEqualTo("old.epub"); + verify(bookRepository).save(book); + } + } +} diff --git a/booklore-api/src/test/java/org/booklore/service/watcher/BookFileTransactionalHandlerTest.java b/booklore-api/src/test/java/org/booklore/service/watcher/BookFileTransactionalHandlerTest.java new file mode 100644 index 000000000..ae9307b5f --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/watcher/BookFileTransactionalHandlerTest.java @@ -0,0 +1,623 @@ +package org.booklore.service.watcher; + +import org.booklore.model.entity.*; +import org.booklore.model.enums.BookFileExtension; +import org.booklore.model.enums.BookFileType; +import org.booklore.model.enums.LibraryOrganizationMode; +import org.booklore.repository.BookAdditionalFileRepository; +import org.booklore.repository.BookRepository; +import org.booklore.repository.LibraryRepository; +import org.booklore.service.NotificationService; +import org.booklore.service.file.FileFingerprint; +import org.booklore.service.library.LibraryProcessingService; +import org.booklore.util.BookFileGroupingUtils; +import org.booklore.util.FileUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; + +import java.nio.file.Path; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledFuture; + +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +class BookFileTransactionalHandlerTest { + + @Mock private BookFilePersistenceService bookFilePersistenceService; + @Mock private LibraryProcessingService libraryProcessingService; + @Mock private NotificationService notificationService; + @Mock private LibraryRepository libraryRepository; + @Mock private BookRepository bookRepository; + @Mock private BookAdditionalFileRepository bookAdditionalFileRepository; + @Mock private PendingDeletionPool pendingDeletionPool; + + private BookFileTransactionalHandler handler; + + private AutoCloseable mocks; + private MockedStatic fingerprintMock; + private MockedStatic fileUtilsMock; + private MockedStatic groupingMock; + + private LibraryEntity library; + private LibraryPathEntity libraryPath; + + @BeforeEach + void setUp() { + mocks = MockitoAnnotations.openMocks(this); + handler = new BookFileTransactionalHandler( + bookFilePersistenceService, libraryProcessingService, notificationService, + libraryRepository, bookRepository, bookAdditionalFileRepository, pendingDeletionPool); + + fingerprintMock = mockStatic(FileFingerprint.class); + fileUtilsMock = mockStatic(FileUtils.class); + groupingMock = mockStatic(BookFileGroupingUtils.class); + + fingerprintMock.when(() -> FileFingerprint.generateHash(any(Path.class))).thenReturn("hash123"); + fingerprintMock.when(() -> FileFingerprint.generateFolderHash(any(Path.class))).thenReturn("folderhash"); + fileUtilsMock.when(() -> FileUtils.getRelativeSubPath(anyString(), any(Path.class))).thenReturn("sub"); + fileUtilsMock.when(() -> FileUtils.getFileSizeInKb(any(Path.class))).thenReturn(100L); + fileUtilsMock.when(() -> FileUtils.getFolderSizeInKb(any(Path.class))).thenReturn(500L); + groupingMock.when(() -> BookFileGroupingUtils.extractGroupingKey(anyString())).thenAnswer(inv -> inv.getArgument(0, String.class).toLowerCase()); + groupingMock.when(() -> BookFileGroupingUtils.calculateSimilarity(anyString(), anyString())).thenReturn(0.5); + + libraryPath = new LibraryPathEntity(); + libraryPath.setId(1L); + libraryPath.setPath("/library"); + + library = LibraryEntity.builder() + .id(1L) + .name("Test Library") + .libraryPaths(List.of(libraryPath)) + .organizationMode(LibraryOrganizationMode.AUTO_DETECT) + .build(); + + when(libraryRepository.findById(1L)).thenReturn(Optional.of(library)); + when(bookFilePersistenceService.findMatchingLibraryPath(eq(library), any(Path.class))).thenReturn("/library"); + when(bookFilePersistenceService.getLibraryPathEntityForFile(eq(library), eq("/library"))).thenReturn(libraryPath); + } + + @AfterEach + void tearDown() throws Exception { + groupingMock.close(); + fileUtilsMock.close(); + fingerprintMock.close(); + mocks.close(); + } + + private BookEntity buildBook(Long id, boolean deleted) { + return BookEntity.builder() + .id(id) + .library(library) + .libraryPath(libraryPath) + .deleted(deleted) + .bookFiles(new ArrayList<>()) + .build(); + } + + private BookFileEntity buildBookFile(Long id, BookEntity book, String fileName, String hash) { + return BookFileEntity.builder() + .id(id) + .book(book) + .fileName(fileName) + .fileSubPath("sub") + .currentHash(hash) + .initialHash(hash) + .isBookFormat(true) + .bookType(BookFileType.EPUB) + .build(); + } + + private PendingDeletionPool.FileSnapshot fileSnap(Long id, String fileName, String hash) { + return new PendingDeletionPool.FileSnapshot(id, fileName, "sub", hash, false, BookFileType.EPUB); + } + + private PendingDeletionPool.BookSnapshot bookSnap(Long bookId, List files) { + return new PendingDeletionPool.BookSnapshot(bookId, 1L, "sub", files); + } + + @SuppressWarnings("unchecked") + private PendingDeletionPool.MatchResult matchResult(PendingDeletionPool.BookSnapshot book, PendingDeletionPool.FileSnapshot file) { + var pending = new PendingDeletionPool.PendingDeletion( + Path.of("/library/sub"), false, 1L, Instant.now(), + mock(ScheduledFuture.class), new ConcurrentHashMap<>(), new ConcurrentHashMap<>()); + return new PendingDeletionPool.MatchResult(pending, book, file); + } + + @Nested + class HandleNewBookFile { + + @Test + void libraryNotFound_throws() { + when(libraryRepository.findById(99L)).thenReturn(Optional.empty()); + + org.junit.jupiter.api.Assertions.assertThrows(Exception.class, + () -> handler.handleNewBookFile(99L, Path.of("/library/sub/test.epub"))); + } + + @Test + void existingAtPath_deletedBook_restoresIt() { + BookEntity book = buildBook(10L, true); + BookFileEntity bookFile = buildBookFile(100L, book, "test.epub", "oldhash"); + book.setBookFiles(List.of(bookFile)); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(1L, "sub", "test.epub")) + .thenReturn(Optional.of(bookFile)); + when(pendingDeletionPool.matchByHash("oldhash")).thenReturn(Optional.empty()); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(bookFilePersistenceService).save(book); + org.assertj.core.api.Assertions.assertThat(book.getDeleted()).isFalse(); + org.assertj.core.api.Assertions.assertThat(book.getDeletedAt()).isNull(); + } + + @Test + void existingAtPath_sameHash_skipsProcessing() { + BookEntity book = buildBook(10L, false); + BookFileEntity bookFile = buildBookFile(100L, book, "test.epub", "hash123"); + book.setBookFiles(List.of(bookFile)); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(1L, "sub", "test.epub")) + .thenReturn(Optional.of(bookFile)); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(bookFilePersistenceService, never()).save(any()); + verify(pendingDeletionPool).cancelByPath(any()); + } + + @Test + void existingAtPath_hashChanged_updatesHash() { + BookEntity book = buildBook(10L, false); + BookFileEntity bookFile = buildBookFile(100L, book, "test.epub", "oldhash"); + book.setBookFiles(List.of(bookFile)); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(1L, "sub", "test.epub")) + .thenReturn(Optional.of(bookFile)); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(pendingDeletionPool).cancelByPath(any()); + verify(bookFilePersistenceService).save(book); + org.assertj.core.api.Assertions.assertThat(bookFile.getCurrentHash()).isEqualTo("hash123"); + } + + @Test + void noExistingAtPath_poolMatch_recoversBook() { + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + + var fSnap = fileSnap(100L, "test.epub", "hash123"); + var bSnap = bookSnap(10L, List.of(fSnap)); + var match = matchResult(bSnap, fSnap); + when(pendingDeletionPool.matchByHash("hash123")).thenReturn(Optional.of(match)); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(pendingDeletionPool).recoverBook(eq(match), eq(libraryPath), eq("sub"), eq("test.epub"), eq("hash123")); + verify(libraryProcessingService, never()).processLibraryFiles(any(), any()); + } + + @Test + void noExistingAtPath_hashBasedMoveDetection_updatesPath() { + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + + BookEntity existingBook = buildBook(10L, false); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(eq("hash123"), any())) + .thenReturn(Optional.of(existingBook)); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(bookFilePersistenceService).updatePathIfChanged(eq(existingBook), eq(library), any(), eq("hash123")); + verify(libraryProcessingService, never()).processLibraryFiles(any(), any()); + } + + @Test + void autoDetect_fuzzyMatchesFilelessBook() { + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + + BookMetadataEntity metadata = BookMetadataEntity.builder().bookId(10L).build(); + // Use reflection or setter to set title + metadata.setTitle("test"); + BookEntity filelessBook = buildBook(10L, false); + filelessBook.setMetadata(metadata); + filelessBook.setLibraryPath(libraryPath); + + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of(filelessBook)); + groupingMock.when(() -> BookFileGroupingUtils.calculateSimilarity(anyString(), anyString())).thenReturn(0.90); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(bookAdditionalFileRepository).save(any(BookFileEntity.class)); + } + + @Test + void autoDetect_noFilelessMatch_matchesExistingBookByGroupingKey() { + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of()); + + BookEntity existingBook = buildBook(20L, false); + BookFileEntity primaryFile = buildBookFile(200L, existingBook, "test.epub", "otherhash"); + existingBook.setBookFiles(new ArrayList<>(List.of(primaryFile))); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(1L, "sub")).thenReturn(List.of(existingBook)); + + // Both files should produce the same grouping key (extension stripped) + groupingMock.when(() -> BookFileGroupingUtils.extractGroupingKey("test.pdf")).thenReturn("test"); + groupingMock.when(() -> BookFileGroupingUtils.extractGroupingKey("test.epub")).thenReturn("test"); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.pdf")); + + verify(bookAdditionalFileRepository).save(any(BookFileEntity.class)); + } + + @Test + void autoDetect_noMatch_createsNewBook() { + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of()); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(anyLong(), anyString())).thenReturn(List.of()); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(libraryProcessingService).processLibraryFiles(anyList(), eq(library)); + } + + @Test + void bookPerFile_neverAttachesToExistingBooks() { + library.setOrganizationMode(LibraryOrganizationMode.BOOK_PER_FILE); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of()); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(bookRepository, never()).findAllByLibraryPathIdAndFileSubPath(anyLong(), anyString()); + verify(libraryProcessingService).processLibraryFiles(anyList(), eq(library)); + } + + @Test + void bookPerFolder_attachesToBookInSameFolder() { + library.setOrganizationMode(LibraryOrganizationMode.BOOK_PER_FOLDER); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of()); + + BookEntity existingBook = buildBook(20L, false); + BookFileEntity primaryFile = buildBookFile(200L, existingBook, "existing.epub", "otherhash"); + existingBook.setBookFiles(new ArrayList<>(List.of(primaryFile))); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(1L, "sub")).thenReturn(List.of(existingBook)); + + handler.handleNewBookFile(1L, Path.of("/library/sub/new.pdf")); + + verify(bookAdditionalFileRepository).save(any(BookFileEntity.class)); + verify(libraryProcessingService, never()).processLibraryFiles(any(), any()); + } + + @Test + void bookPerFolder_noBookInFolder_createsNew() { + library.setOrganizationMode(LibraryOrganizationMode.BOOK_PER_FOLDER); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of()); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(1L, "sub")).thenReturn(List.of()); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(libraryProcessingService).processLibraryFiles(anyList(), eq(library)); + } + + @Test + void bookPerFolder_audiobook_findsNearestAncestorWithEbook() { + library.setOrganizationMode(LibraryOrganizationMode.BOOK_PER_FOLDER); + fileUtilsMock.when(() -> FileUtils.getRelativeSubPath(anyString(), any(Path.class))).thenReturn("author/book/audio"); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of()); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(1L, "author/book/audio")).thenReturn(List.of()); + + BookEntity parentBook = buildBook(30L, false); + BookFileEntity ebookFile = buildBookFile(300L, parentBook, "book.epub", "ebookhash"); + ebookFile.setBookType(BookFileType.EPUB); + parentBook.setBookFiles(new ArrayList<>(List.of(ebookFile))); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(1L, "author/book")).thenReturn(List.of(parentBook)); + + handler.handleNewBookFile(1L, Path.of("/library/author/book/audio/chapter1.m4b")); + + verify(bookAdditionalFileRepository).save(any(BookFileEntity.class)); + } + + @Test + void bookPerFile_exactFilelessMatch_usesExactNotFuzzy() { + library.setOrganizationMode(LibraryOrganizationMode.BOOK_PER_FILE); + + BookMetadataEntity metadata = BookMetadataEntity.builder().bookId(10L).build(); + metadata.setTitle("different title"); + BookEntity filelessBook = buildBook(10L, false); + filelessBook.setMetadata(metadata); + filelessBook.setLibraryPath(libraryPath); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of(filelessBook)); + // extractGroupingKey returns lowercase of input, so "different title" != "test.epub" + // No exact match -> should create new + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(libraryProcessingService).processLibraryFiles(anyList(), eq(library)); + } + + @Test + void autoDetect_filelessBook_wrongLibraryPath_skipped() { + LibraryPathEntity otherPath = new LibraryPathEntity(); + otherPath.setId(99L); + otherPath.setPath("/other"); + + BookMetadataEntity metadata = BookMetadataEntity.builder().bookId(10L).build(); + metadata.setTitle("test"); + BookEntity filelessBook = buildBook(10L, false); + filelessBook.setMetadata(metadata); + filelessBook.setLibraryPath(otherPath); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of(filelessBook)); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(anyLong(), anyString())).thenReturn(List.of()); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(libraryProcessingService).processLibraryFiles(anyList(), eq(library)); + } + + @Test + void autoDetect_fuzzyMatchBook_returnsHighSimilarity() { + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of()); + + BookEntity book1 = buildBook(20L, false); + BookFileEntity file1 = buildBookFile(200L, book1, "mybook.epub", "h1"); + book1.setBookFiles(new ArrayList<>(List.of(file1))); + + BookEntity book2 = buildBook(21L, false); + BookFileEntity file2 = buildBookFile(201L, book2, "otherbook.epub", "h2"); + book2.setBookFiles(new ArrayList<>(List.of(file2))); + + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(1L, "sub")).thenReturn(List.of(book1, book2)); + // Make groupingKey different to avoid exact match, but similarity high for book1 + groupingMock.when(() -> BookFileGroupingUtils.extractGroupingKey("mybook.pdf")).thenReturn("mybook"); + groupingMock.when(() -> BookFileGroupingUtils.extractGroupingKey("mybook.epub")).thenReturn("mybook"); + groupingMock.when(() -> BookFileGroupingUtils.extractGroupingKey("otherbook.epub")).thenReturn("otherbook"); + groupingMock.when(() -> BookFileGroupingUtils.calculateSimilarity("mybook", "mybook")).thenReturn(1.0); + groupingMock.when(() -> BookFileGroupingUtils.calculateSimilarity("mybook", "otherbook")).thenReturn(0.3); + + handler.handleNewBookFile(1L, Path.of("/library/sub/mybook.pdf")); + + // Should attach to book1 via exact grouping key match + verify(bookAdditionalFileRepository).save(any(BookFileEntity.class)); + } + + @Test + void nullSubPath_autoDetect_createsNewBook() { + fileUtilsMock.when(() -> FileUtils.getRelativeSubPath(anyString(), any(Path.class))).thenReturn(null); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), any(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of()); + + handler.handleNewBookFile(1L, Path.of("/library/test.epub")); + + // findMatchingBook returns null for null subPath, so new book is created + verify(libraryProcessingService).processLibraryFiles(anyList(), eq(library)); + } + + @Test + void bookPerFolder_multipleActiveBooksInFolder_picksOneWithMostFiles() { + library.setOrganizationMode(LibraryOrganizationMode.BOOK_PER_FOLDER); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of()); + + BookEntity smallBook = buildBook(20L, false); + BookFileEntity f1 = buildBookFile(200L, smallBook, "a.epub", "h1"); + smallBook.setBookFiles(new ArrayList<>(List.of(f1))); + + BookEntity bigBook = buildBook(21L, false); + BookFileEntity f2 = buildBookFile(201L, bigBook, "b.epub", "h2"); + BookFileEntity f3 = buildBookFile(202L, bigBook, "b.pdf", "h3"); + bigBook.setBookFiles(new ArrayList<>(List.of(f2, f3))); + + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(1L, "sub")).thenReturn(List.of(smallBook, bigBook)); + + handler.handleNewBookFile(1L, Path.of("/library/sub/new.mobi")); + + // Should attach to bigBook (more files) + verify(bookAdditionalFileRepository).save(argThat(bf -> bf.getBook().equals(bigBook))); + } + + @Test + void existingAtPath_deletedBook_matchesPendingDeletionHash() { + BookEntity book = buildBook(10L, true); + BookFileEntity bookFile = buildBookFile(100L, book, "test.epub", "oldhash"); + book.setBookFiles(List.of(bookFile)); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(1L, "sub", "test.epub")) + .thenReturn(Optional.of(bookFile)); + when(pendingDeletionPool.matchByHash("oldhash")).thenReturn(Optional.empty()); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(pendingDeletionPool).matchByHash("oldhash"); + verify(bookFilePersistenceService).save(book); + } + + @Test + void nullOrganizationMode_defaultsToAutoDetect() { + library.setOrganizationMode(null); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of()); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(anyLong(), anyString())).thenReturn(List.of()); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + // AUTO_DETECT path: findFilelessBooksByLibraryId is called (fuzzy matching) + verify(bookRepository).findFilelessBooksByLibraryId(1L); + } + + @Test + void autoDetect_deletedBookInDirectory_skipped() { + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of()); + + BookEntity deletedBook = buildBook(20L, true); + BookFileEntity file = buildBookFile(200L, deletedBook, "test.epub", "h1"); + deletedBook.setBookFiles(new ArrayList<>(List.of(file))); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(1L, "sub")).thenReturn(List.of(deletedBook)); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.pdf")); + + verify(libraryProcessingService).processLibraryFiles(anyList(), eq(library)); + } + + @Test + void filelessBook_nullLibraryPath_setsLibraryPath() { + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findByCurrentHashIncludingRecentlyDeleted(anyString(), any())).thenReturn(Optional.empty()); + + BookMetadataEntity metadata = BookMetadataEntity.builder().bookId(10L).build(); + metadata.setTitle("test"); + BookEntity filelessBook = buildBook(10L, false); + filelessBook.setMetadata(metadata); + filelessBook.setLibraryPath(null); + + when(bookRepository.findFilelessBooksByLibraryId(1L)).thenReturn(List.of(filelessBook)); + groupingMock.when(() -> BookFileGroupingUtils.calculateSimilarity(anyString(), anyString())).thenReturn(0.90); + + handler.handleNewBookFile(1L, Path.of("/library/sub/test.epub")); + + verify(bookRepository).save(argThat(b -> b.getLibraryPath() != null)); + verify(bookAdditionalFileRepository).save(any(BookFileEntity.class)); + } + } + + @Nested + class HandleNewFolderAudiobook { + + @Test + void libraryNotFound_throws() { + when(libraryRepository.findById(99L)).thenReturn(Optional.empty()); + + org.junit.jupiter.api.Assertions.assertThrows(Exception.class, + () -> handler.handleNewFolderAudiobook(99L, Path.of("/library/audiobook"))); + } + + @Test + void poolMatch_recoversBook() { + var fSnap = fileSnap(100L, "audiobook", "folderhash"); + var bSnap = bookSnap(10L, List.of(fSnap)); + var match = matchResult(bSnap, fSnap); + when(pendingDeletionPool.matchByHash("folderhash")).thenReturn(Optional.of(match)); + + handler.handleNewFolderAudiobook(1L, Path.of("/library/sub/audiobook")); + + verify(pendingDeletionPool).recoverBook(eq(match), eq(libraryPath), eq("sub"), eq("audiobook"), eq("folderhash")); + verify(libraryProcessingService, never()).processLibraryFiles(any(), any()); + } + + @Test + void matchingBook_autoAttachesFolderAudiobook() { + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + + BookEntity existingBook = buildBook(20L, false); + BookFileEntity primaryFile = buildBookFile(200L, existingBook, "audiobook.epub", "h1"); + existingBook.setBookFiles(new ArrayList<>(List.of(primaryFile))); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(anyLong(), anyString())).thenReturn(List.of(existingBook)); + + // Folder name "audiobook" and file "audiobook.epub" should produce same grouping key + groupingMock.when(() -> BookFileGroupingUtils.extractGroupingKey("audiobook")).thenReturn("audiobook"); + groupingMock.when(() -> BookFileGroupingUtils.extractGroupingKey("audiobook.epub")).thenReturn("audiobook"); + + handler.handleNewFolderAudiobook(1L, Path.of("/library/sub/audiobook")); + + verify(bookAdditionalFileRepository).save(argThat(bf -> + bf.isFolderBased() && bf.getBookType() == BookFileType.AUDIOBOOK)); + } + + @Test + void noMatch_createsNewFolderAudiobook() { + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(anyLong(), anyString())).thenReturn(List.of()); + + handler.handleNewFolderAudiobook(1L, Path.of("/library/sub/audiobook")); + + verify(libraryProcessingService).processLibraryFiles(argThat(files -> + files.size() == 1 && files.getFirst().isFolderBased() && files.getFirst().getBookFileType() == BookFileType.AUDIOBOOK), eq(library)); + } + + @Test + void deletedBookInParent_notMatchedForFolderAudiobook() { + when(pendingDeletionPool.matchByHash(anyString())).thenReturn(Optional.empty()); + + BookEntity deletedBook = buildBook(20L, true); + BookFileEntity file = buildBookFile(200L, deletedBook, "audiobook.epub", "h1"); + deletedBook.setBookFiles(new ArrayList<>(List.of(file))); + when(bookRepository.findAllByLibraryPathIdAndFileSubPath(anyLong(), anyString())).thenReturn(List.of(deletedBook)); + + handler.handleNewFolderAudiobook(1L, Path.of("/library/sub/audiobook")); + + verify(libraryProcessingService).processLibraryFiles(anyList(), eq(library)); + } + } +} diff --git a/booklore-api/src/test/java/org/booklore/service/watcher/LibraryFileEventProcessorTest.java b/booklore-api/src/test/java/org/booklore/service/watcher/LibraryFileEventProcessorTest.java new file mode 100644 index 000000000..148de68b5 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/watcher/LibraryFileEventProcessorTest.java @@ -0,0 +1,405 @@ +package org.booklore.service.watcher; + +import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; +import org.booklore.model.entity.LibraryEntity; +import org.booklore.model.entity.LibraryPathEntity; +import org.booklore.model.enums.BookFileType; +import org.booklore.model.enums.LibraryOrganizationMode; +import org.booklore.repository.BookRepository; +import org.booklore.repository.LibraryRepository; +import org.booklore.service.library.LibraryProcessingService; +import org.booklore.util.FileUtils; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardWatchEventKinds; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +class LibraryFileEventProcessorTest { + + @Mock private LibraryRepository libraryRepository; + @Mock private BookRepository bookRepository; + @Mock private BookFileTransactionalHandler bookFileTransactionalHandler; + @Mock private BookFilePersistenceService bookFilePersistenceService; + @Mock private LibraryProcessingService libraryProcessingService; + @Mock private PendingDeletionPool pendingDeletionPool; + + private LibraryFileEventProcessor processor; + + private AutoCloseable mocks; + + private LibraryEntity library; + private LibraryPathEntity libraryPath; + + @TempDir + Path tempDir; + + @BeforeEach + void setUp() { + mocks = MockitoAnnotations.openMocks(this); + processor = new LibraryFileEventProcessor( + libraryRepository, bookRepository, bookFileTransactionalHandler, + bookFilePersistenceService, libraryProcessingService, pendingDeletionPool); + + libraryPath = new LibraryPathEntity(); + libraryPath.setId(1L); + libraryPath.setPath(tempDir.toString()); + + library = LibraryEntity.builder() + .id(1L) + .name("Test Library") + .libraryPaths(List.of(libraryPath)) + .organizationMode(LibraryOrganizationMode.AUTO_DETECT) + .build(); + + when(libraryRepository.findById(1L)).thenReturn(Optional.of(library)); + when(bookFilePersistenceService.findMatchingLibraryPath(eq(library), any(Path.class))) + .thenReturn(tempDir.toString()); + when(bookFilePersistenceService.getLibraryPathEntityForFile(eq(library), eq(tempDir.toString()))) + .thenReturn(libraryPath); + + // Start the event processing thread (normally done by @PostConstruct) + processor.init(); + } + + @AfterEach + void tearDown() throws Exception { + processor.shutdown(); + mocks.close(); + } + + @Nested + class HasPendingEventsForPaths { + + @Test + void returnsFalseWhenNothingPending() { + assertThat(processor.hasPendingEventsForPaths(Set.of(tempDir))).isFalse(); + } + + @Test + void delegatesToPendingDeletionPool() { + when(pendingDeletionPool.hasPendingForPaths(any())).thenReturn(true); + + assertThat(processor.hasPendingEventsForPaths(Set.of(tempDir))).isTrue(); + } + } + + @Nested + class ProcessEventDebouncing { + + @Test + void createCancelsExistingDelete() throws Exception { + Path file = tempDir.resolve("test.epub"); + Files.writeString(file, "content"); + + // Schedule a DELETE + processor.processEvent(StandardWatchEventKinds.ENTRY_DELETE, 1L, file, false); + + // Immediately follow with CREATE (simulates quick rename) + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, file, false); + + // The DELETE should have been cancelled. Wait a bit for debounce to settle. + Thread.sleep(1000); + + // The DELETE event should not have been processed + verify(bookFilePersistenceService, never()).findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString()); + } + + @Test + void directoryCreateScheduledWithDelay() throws IOException { + Path folder = tempDir.resolve("newFolder"); + Files.createDirectory(folder); + Files.writeString(folder.resolve("test.epub"), "content"); + + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, folder, true); + + // Should not process immediately due to folder debounce + verify(bookFileTransactionalHandler, never()).handleNewBookFile(anyLong(), any()); + } + + @Test + void fileInsidePendingFolderResetsFolderTimer() throws IOException { + Path folder = tempDir.resolve("audioFolder"); + Files.createDirectory(folder); + + // Trigger folder create first + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, folder, true); + + // Then file inside it + Path file = folder.resolve("track01.m4b"); + Files.writeString(file, "audio content"); + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, file, false); + + // The folder debounce should have been reset, not processed yet + verify(bookFileTransactionalHandler, never()).handleNewFolderAudiobook(anyLong(), any()); + } + + @Test + void nonBookFileEventsIgnored() throws Exception { + Path textFile = tempDir.resolve("readme.txt"); + Files.writeString(textFile, "hello"); + + // Queue a modify event for a non-book file + processor.processEvent(StandardWatchEventKinds.ENTRY_MODIFY, 1L, textFile, false); + + // Wait for processing + Thread.sleep(200); + + verify(bookFileTransactionalHandler, never()).handleNewBookFile(anyLong(), any()); + } + } + + @Nested + class FolderCreateHandling { + + @Test + void bookPerFileMode_processesFilesIndividually() throws Exception { + library.setOrganizationMode(LibraryOrganizationMode.BOOK_PER_FILE); + + Path folder = tempDir.resolve("books"); + Files.createDirectory(folder); + Files.writeString(folder.resolve("book1.epub"), "content1"); + Files.writeString(folder.resolve("book2.pdf"), "content2"); + + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, folder, true); + + // Folder debounce is 5s, then queue processing + Thread.sleep(8000); + + verify(bookFileTransactionalHandler, times(2)).handleNewBookFile(eq(1L), any()); + } + + @Test + void bookPerFileMode_ignoresFolderWithIgnoreFile() throws Exception { + library.setOrganizationMode(LibraryOrganizationMode.BOOK_PER_FILE); + + Path folder = tempDir.resolve("ignored"); + Files.createDirectory(folder); + Files.writeString(folder.resolve(".ignore"), ""); + Files.writeString(folder.resolve("book.epub"), "content"); + + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, folder, true); + + Thread.sleep(8000); + + verify(bookFileTransactionalHandler, never()).handleNewBookFile(anyLong(), any()); + } + + @Test + void bookPerFileMode_skipsFilesUnderIgnoredSubdirectory() throws Exception { + library.setOrganizationMode(LibraryOrganizationMode.BOOK_PER_FILE); + + Path folder = tempDir.resolve("parent"); + Files.createDirectory(folder); + Files.writeString(folder.resolve("good.epub"), "content"); + + Path ignoredSub = folder.resolve("skipped"); + Files.createDirectory(ignoredSub); + Files.writeString(ignoredSub.resolve(".ignore"), ""); + Files.writeString(ignoredSub.resolve("hidden.epub"), "content"); + + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, folder, true); + + Thread.sleep(8000); + + // Only good.epub should be processed, not hidden.epub + verify(bookFileTransactionalHandler, times(1)).handleNewBookFile(eq(1L), any()); + } + + @Test + void bookPerFolderMode_emptyFolder_doesNothing() throws Exception { + library.setOrganizationMode(LibraryOrganizationMode.BOOK_PER_FOLDER); + + Path folder = tempDir.resolve("empty"); + Files.createDirectory(folder); + + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, folder, true); + + Thread.sleep(8000); + + verify(libraryProcessingService, never()).processLibraryFiles(any(), any()); + verify(bookFileTransactionalHandler, never()).handleNewBookFile(anyLong(), any()); + } + + @Test + void pathOutsideLibrary_skipped() throws Exception { + Path outsideFolder = Files.createTempDirectory("outside"); + try { + Files.writeString(outsideFolder.resolve("book.epub"), "content"); + + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, outsideFolder, true); + + Thread.sleep(8000); + + // handleEvent should skip because path is outside library + verify(bookFileTransactionalHandler, never()).handleNewBookFile(anyLong(), any()); + } finally { + try (var stream = Files.walk(outsideFolder)) { + stream.sorted(java.util.Comparator.reverseOrder()).forEach(p -> { + try { Files.deleteIfExists(p); } catch (IOException ignored) {} + }); + } + } + } + } + + @Nested + class FolderDeleteHandling { + + @Test + void folderWithBooks_addsToPool() throws Exception { + BookEntity book = BookEntity.builder() + .id(10L) + .library(library) + .libraryPath(libraryPath) + .deleted(false) + .bookFiles(new ArrayList<>(List.of(BookFileEntity.builder() + .id(100L) + .fileName("test.epub") + .fileSubPath("books") + .currentHash("hash") + .isBookFormat(true) + .bookType(BookFileType.EPUB) + .build()))) + .build(); + + when(bookRepository.findBooksWithFilesUnderPath(eq(1L), anyString())) + .thenReturn(List.of(book)); + + Path folder = tempDir.resolve("books"); + + processor.processEvent(StandardWatchEventKinds.ENTRY_DELETE, 1L, folder, true); + + Thread.sleep(2000); + + verify(pendingDeletionPool).addFolderDeletion(any(), eq(1L), eq(List.of(book)), any()); + } + + @Test + void folderWithNoBooks_doesNotAddToPool() throws Exception { + when(bookRepository.findBooksWithFilesUnderPath(eq(1L), anyString())) + .thenReturn(List.of()); + + Path folder = tempDir.resolve("emptybooks"); + + processor.processEvent(StandardWatchEventKinds.ENTRY_DELETE, 1L, folder, true); + + Thread.sleep(2000); + + verify(pendingDeletionPool, never()).addFolderDeletion(any(), anyLong(), any(), any()); + } + } + + @Nested + class FileDeleteHandling { + + @Test + void bookFileFound_addsToPool() throws Exception { + BookEntity book = BookEntity.builder() + .id(10L).library(library).libraryPath(libraryPath).deleted(false) + .bookFiles(new ArrayList<>()).build(); + BookFileEntity bookFile = BookFileEntity.builder() + .id(100L).book(book).fileName("test.epub").fileSubPath("sub") + .currentHash("hash").isBookFormat(true).bookType(BookFileType.EPUB).build(); + + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(eq(1L), anyString(), eq("test.epub"))) + .thenReturn(Optional.of(bookFile)); + + Path file = tempDir.resolve("sub").resolve("test.epub"); + + processor.processEvent(StandardWatchEventKinds.ENTRY_DELETE, 1L, file, false); + + Thread.sleep(2000); + + verify(pendingDeletionPool).addFileDeletion(any(), eq(1L), eq(bookFile), eq(book), any()); + } + + @Test + void bookFileNotFound_logsAndContinues() throws Exception { + when(bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(anyLong(), anyString(), anyString())) + .thenReturn(Optional.empty()); + + Path file = tempDir.resolve("sub").resolve("missing.epub"); + + processor.processEvent(StandardWatchEventKinds.ENTRY_DELETE, 1L, file, false); + + Thread.sleep(2000); + + verify(pendingDeletionPool, never()).addFileDeletion(any(), anyLong(), any(), any(), any()); + } + } + + @Nested + class FileCreateHandling { + + @Test + void zeroByteFile_skipped() throws Exception { + Path file = tempDir.resolve("empty.epub"); + Files.createFile(file); + + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, file, false); + + // Wait for stability check + processing + Thread.sleep(4000); + + verify(bookFileTransactionalHandler, never()).handleNewBookFile(anyLong(), any()); + } + + @Test + void nonBookFile_skipped() throws Exception { + Path file = tempDir.resolve("readme.txt"); + Files.writeString(file, "hello"); + + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, file, false); + + Thread.sleep(4000); + + verify(bookFileTransactionalHandler, never()).handleNewBookFile(anyLong(), any()); + } + + @Test + void validBookFile_processedAfterStabilityCheck() throws Exception { + Path file = tempDir.resolve("book.epub"); + Files.writeString(file, "book content"); + + processor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, 1L, file, false); + + // Stability check needs file to be stable for STABILITY_CHECK_INTERVAL_MS (3s) + // then event goes to queue and is processed by virtual thread + Thread.sleep(7000); + + verify(bookFileTransactionalHandler).handleNewBookFile(eq(1L), any()); + } + } + + @Nested + class Shutdown { + + @Test + void shutdownCompletesCleanly() { + // Just verify shutdown doesn't throw + processor.shutdown(); + + // Reinitialize so tearDown's shutdown doesn't fail + processor = new LibraryFileEventProcessor( + libraryRepository, bookRepository, bookFileTransactionalHandler, + bookFilePersistenceService, libraryProcessingService, pendingDeletionPool); + } + } +} diff --git a/booklore-api/src/test/java/org/booklore/service/watcher/PendingDeletionPoolTest.java b/booklore-api/src/test/java/org/booklore/service/watcher/PendingDeletionPoolTest.java new file mode 100644 index 000000000..6d30c31d8 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/watcher/PendingDeletionPoolTest.java @@ -0,0 +1,226 @@ +package org.booklore.service.watcher; + +import org.booklore.mapper.BookMapper; +import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; +import org.booklore.model.entity.LibraryPathEntity; +import org.booklore.model.enums.BookFileType; +import org.booklore.repository.BookFileRepository; +import org.booklore.repository.BookRepository; +import org.booklore.service.NotificationService; +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.nio.file.Path; +import java.time.Instant; +import java.util.*; +import java.util.concurrent.ScheduledFuture; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class PendingDeletionPoolTest { + + @Mock private BookRepository bookRepository; + @Mock private BookFileRepository bookFileRepository; + @Mock private NotificationService notificationService; + @Mock private BookMapper bookMapper; + + @InjectMocks + private PendingDeletionPool pool; + + private BookFileEntity bookFile; + private BookEntity book; + private LibraryPathEntity libraryPath; + + @BeforeEach + void setUp() { + libraryPath = new LibraryPathEntity(); + libraryPath.setId(1L); + libraryPath.setPath("/library"); + + book = BookEntity.builder() + .id(10L) + .libraryPath(libraryPath) + .deleted(false) + .build(); + + bookFile = BookFileEntity.builder() + .id(100L) + .book(book) + .fileName("test.epub") + .fileSubPath("subfolder") + .currentHash("abc123") + .isBookFormat(true) + .folderBased(false) + .bookType(BookFileType.EPUB) + .build(); + } + + @Test + void matchByHash_findsFileDeletion() { + ScheduledFuture timer = mock(ScheduledFuture.class); + pool.addFileDeletion(Path.of("/library/subfolder/test.epub"), 1L, bookFile, book, timer); + + Optional result = pool.matchByHash("abc123"); + + assertThat(result).isPresent(); + assertThat(result.get().book().bookId()).isEqualTo(10L); + assertThat(result.get().file().bookFileId()).isEqualTo(100L); + verify(timer).cancel(false); + } + + @Test + void matchByHash_returnsEmptyForUnknownHash() { + ScheduledFuture timer = mock(ScheduledFuture.class); + pool.addFileDeletion(Path.of("/library/subfolder/test.epub"), 1L, bookFile, book, timer); + + Optional result = pool.matchByHash("unknown"); + + assertThat(result).isEmpty(); + } + + @Test + void matchByHash_consumesHashOnlyOnce() { + ScheduledFuture timer = mock(ScheduledFuture.class); + pool.addFileDeletion(Path.of("/library/subfolder/test.epub"), 1L, bookFile, book, timer); + + pool.matchByHash("abc123"); + Optional second = pool.matchByHash("abc123"); + + assertThat(second).isEmpty(); + } + + @Test + void addFolderDeletion_indexesAllFileHashes() { + BookFileEntity file2 = BookFileEntity.builder() + .id(101L).book(book).fileName("test2.epub").fileSubPath("subfolder") + .currentHash("def456").isBookFormat(true).folderBased(false).bookType(BookFileType.EPUB).build(); + book.setBookFiles(List.of(bookFile, file2)); + + ScheduledFuture timer = mock(ScheduledFuture.class); + pool.addFolderDeletion(Path.of("/library/subfolder"), 1L, List.of(book), timer); + + assertThat(pool.matchByHash("abc123")).isPresent(); + assertThat(pool.matchByHash("def456")).isPresent(); + } + + @Test + void matchFolderByHashes_matchesWithSufficientOverlap() { + BookFileEntity file2 = BookFileEntity.builder() + .id(101L).book(book).fileName("test2.epub").fileSubPath("subfolder") + .currentHash("def456").isBookFormat(true).folderBased(false).bookType(BookFileType.EPUB).build(); + book.setBookFiles(List.of(bookFile, file2)); + + ScheduledFuture timer = mock(ScheduledFuture.class); + pool.addFolderDeletion(Path.of("/library/subfolder"), 1L, List.of(book), timer); + + Map fileHashes = Map.of( + Path.of("/new/test.epub"), "abc123", + Path.of("/new/test2.epub"), "def456"); + + Optional result = pool.matchFolderByHashes(fileHashes); + + assertThat(result).isPresent(); + assertThat(result.get().hashToFile()).hasSize(2); + verify(timer).cancel(false); + } + + @Test + void matchFolderByHashes_rejectsLowOverlap() { + book.setBookFiles(List.of(bookFile)); + + ScheduledFuture timer = mock(ScheduledFuture.class); + pool.addFolderDeletion(Path.of("/library/subfolder"), 1L, List.of(book), timer); + + Map fileHashes = Map.of(Path.of("/new/other.epub"), "zzz999"); + + Optional result = pool.matchFolderByHashes(fileHashes); + + assertThat(result).isEmpty(); + } + + @Test + void expireFileDeletion_marksLastFileBookAsDeleted() { + ScheduledFuture timer = mock(ScheduledFuture.class); + pool.addFileDeletion(Path.of("/library/subfolder/test.epub"), 1L, bookFile, book, timer); + + when(bookRepository.findById(10L)).thenReturn(Optional.of(book)); + when(bookFileRepository.countByBookId(10L)).thenReturn(1L); + + pool.expireFileDeletion(Path.of("/library/subfolder/test.epub")); + + assertThat(book.getDeleted()).isTrue(); + assertThat(book.getDeletedAt()).isNotNull(); + verify(bookRepository).save(book); + } + + @Test + void expireFileDeletion_deletesFileWhenMultipleRemain() { + ScheduledFuture timer = mock(ScheduledFuture.class); + pool.addFileDeletion(Path.of("/library/subfolder/test.epub"), 1L, bookFile, book, timer); + + when(bookRepository.findById(10L)).thenReturn(Optional.of(book)); + when(bookFileRepository.countByBookId(10L)).thenReturn(3L); + when(bookFileRepository.findById(100L)).thenReturn(Optional.of(bookFile)); + + pool.expireFileDeletion(Path.of("/library/subfolder/test.epub")); + + verify(bookFileRepository).delete(bookFile); + assertThat(book.getDeleted()).isFalse(); + } + + @Test + void expireFolderDeletion_marksAllBooksDeleted() { + book.setBookFiles(List.of(bookFile)); + + ScheduledFuture timer = mock(ScheduledFuture.class); + pool.addFolderDeletion(Path.of("/library/subfolder"), 1L, List.of(book), timer); + + when(bookRepository.findById(10L)).thenReturn(Optional.of(book)); + + pool.expireFolderDeletion(Path.of("/library/subfolder")); + + assertThat(book.getDeleted()).isTrue(); + verify(bookRepository).save(book); + } + + @Test + void hasPendingForPaths_detectsPendingDeletion() { + ScheduledFuture timer = mock(ScheduledFuture.class); + pool.addFileDeletion(Path.of("/library/subfolder/test.epub"), 1L, bookFile, book, timer); + + assertThat(pool.hasPendingForPaths(Set.of(Path.of("/library")))).isTrue(); + assertThat(pool.hasPendingForPaths(Set.of(Path.of("/other")))).isFalse(); + } + + @Test + void recoverBook_undeletesAndUpdatesPath() { + ScheduledFuture timer = mock(ScheduledFuture.class); + pool.addFileDeletion(Path.of("/library/subfolder/test.epub"), 1L, bookFile, book, timer); + var match = pool.matchByHash("abc123").orElseThrow(); + + when(bookRepository.findById(10L)).thenReturn(Optional.of(book)); + when(bookFileRepository.findById(100L)).thenReturn(Optional.of(bookFile)); + + LibraryPathEntity newPath = new LibraryPathEntity(); + newPath.setId(2L); + newPath.setPath("/new-library"); + + pool.recoverBook(match, newPath, "newSub", "renamed.epub", "abc123"); + + assertThat(book.getDeleted()).isFalse(); + assertThat(book.getDeletedAt()).isNull(); + assertThat(book.getLibraryPath()).isEqualTo(newPath); + assertThat(bookFile.getFileSubPath()).isEqualTo("newSub"); + assertThat(bookFile.getFileName()).isEqualTo("renamed.epub"); + verify(bookRepository).save(book); + } +} diff --git a/booklore-api/src/test/java/org/booklore/util/FileUtilsTest.java b/booklore-api/src/test/java/org/booklore/util/FileUtilsTest.java index b1420d4e6..98fcf7dbc 100644 --- a/booklore-api/src/test/java/org/booklore/util/FileUtilsTest.java +++ b/booklore-api/src/test/java/org/booklore/util/FileUtilsTest.java @@ -185,6 +185,37 @@ class FileUtilsTest { assertFalse(FileUtils.shouldIgnore(emptyPath)); } + @Test + void testShouldIgnore_tempFileExtensions_returnsTrue() { + List tempFiles = List.of( + "book.epub.part", "book.epub.tmp", "book.epub.crdownload", + "book.epub.download", "book.epub.bak", "book.epub.old", + "book.epub.temp", "book.epub.tempfile" + ); + for (String name : tempFiles) { + assertTrue(FileUtils.shouldIgnore(tempDir.resolve(name)), "Should ignore: " + name); + } + } + + @Test + void testShouldIgnore_standaloneTempFile_returnsTrue() { + assertTrue(FileUtils.shouldIgnore(tempDir.resolve("something.tmp"))); + assertTrue(FileUtils.shouldIgnore(tempDir.resolve("download.part"))); + } + + @Test + void testShouldIgnore_tempExtensionCaseInsensitive_returnsTrue() { + assertTrue(FileUtils.shouldIgnore(tempDir.resolve("book.epub.PART"))); + assertTrue(FileUtils.shouldIgnore(tempDir.resolve("book.epub.TMP"))); + } + + @Test + void testShouldIgnore_normalBookFile_returnsFalse() { + assertFalse(FileUtils.shouldIgnore(tempDir.resolve("book.epub"))); + assertFalse(FileUtils.shouldIgnore(tempDir.resolve("book.pdf"))); + assertFalse(FileUtils.shouldIgnore(tempDir.resolve("audiobook.m4b"))); + } + @Test void testGetFileSizeInKb_validFile_returnsSize() throws IOException { Path file = tempDir.resolve("test.txt"); @@ -485,13 +516,12 @@ class FileUtilsTest { } @Test - void testIsSeriesFolder_noExtension_returnsTrue() { - // Files without dots in the name (no extension confusion) + void testIsSeriesFolder_noExtension_returnsFalse() { List files = List.of( Path.of("The Lightning Thief"), Path.of("The Sea of Monsters") ); - assertTrue(FileUtils.isSeriesFolder(files)); + assertFalse(FileUtils.isSeriesFolder(files)); } @Test @@ -536,6 +566,27 @@ class FileUtilsTest { assertTrue(FileUtils.isSeriesFolder(files)); } + @Test + void testIsSeriesFolder_descriptiveChapterNames_returnsFalse() { + List files = List.of( + Path.of("CH01 THE BOY WHO LIVED.mp3"), + Path.of("CH02 THE VANISHING GLASS.mp3"), + Path.of("CH03 THE LETTERS FROM NO ONE.mp3"), + Path.of("CH04 THE KEEPER OF THE KEYS.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_numberedChaptersWithTitles_returnsFalse() { + List files = List.of( + Path.of("Suzanne Collins - Catching Fire 001.mp3"), + Path.of("Suzanne Collins - Catching Fire 002.mp3"), + Path.of("Suzanne Collins - Catching Fire 003.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + @Test void testIsSeriesFolder_prologueAndChapters_returnsFalse() { // All generic: prologue, chapter, epilogue diff --git a/booklore-ui/src/app/features/book/model/library.model.ts b/booklore-ui/src/app/features/book/model/library.model.ts index 359889fcc..05a493475 100644 --- a/booklore-ui/src/app/features/book/model/library.model.ts +++ b/booklore-ui/src/app/features/book/model/library.model.ts @@ -3,6 +3,8 @@ import {BookType} from './book.model'; export type MetadataSource = 'EMBEDDED' | 'SIDECAR' | 'PREFER_SIDECAR' | 'PREFER_EMBEDDED' | 'NONE'; +export type OrganizationMode = 'BOOK_PER_FILE' | 'BOOK_PER_FOLDER' | 'AUTO_DETECT'; + export interface Library { id?: number; name: string; @@ -15,6 +17,7 @@ export interface Library { formatPriority?: BookType[]; allowedFormats?: BookType[]; metadataSource?: MetadataSource; + organizationMode?: OrganizationMode; } export interface LibraryPath { diff --git a/booklore-ui/src/app/features/library-creator/library-creator.component.html b/booklore-ui/src/app/features/library-creator/library-creator.component.html index b0eabff4f..acdaef579 100644 --- a/booklore-ui/src/app/features/library-creator/library-creator.component.html +++ b/booklore-ui/src/app/features/library-creator/library-creator.component.html @@ -151,6 +151,25 @@ /> +
+
+ {{ t('organizationMode') }} + +
+
+
diff --git a/booklore-ui/src/app/features/library-creator/library-creator.component.ts b/booklore-ui/src/app/features/library-creator/library-creator.component.ts index 59931c167..7d737c5ce 100644 --- a/booklore-ui/src/app/features/library-creator/library-creator.component.ts +++ b/booklore-ui/src/app/features/library-creator/library-creator.component.ts @@ -5,7 +5,7 @@ import {Router} from '@angular/router'; import {LibraryService} from '../book/service/library.service'; import {FormsModule} from '@angular/forms'; import {InputText} from 'primeng/inputtext'; -import {Library, MetadataSource} from '../book/model/library.model'; +import {Library, MetadataSource, OrganizationMode} from '../book/model/library.model'; import {BookType} from '../book/model/book.model'; import {ToggleSwitch} from 'primeng/toggleswitch'; import {Tooltip} from 'primeng/tooltip'; @@ -41,8 +41,10 @@ export class LibraryCreatorComponent implements OnInit { selectedAllowedFormats: Set = new Set(); formatCounts: Record = {}; metadataSource: MetadataSource = 'EMBEDDED'; + organizationMode: OrganizationMode = 'BOOK_PER_FILE'; metadataSourceOptions: {label: string, value: string}[] = []; + organizationModeOptions: {label: string, value: string}[] = []; readonly allBookFormats: {type: BookType, label: string}[] = [ {type: 'EPUB', label: 'EPUB'}, @@ -73,6 +75,7 @@ export class LibraryCreatorComponent implements OnInit { ]; this.initializeFormatPriority(); this.initializeAllowedFormats(); + this.initializeOrganizationModeOptions(); const data = this.dynamicDialogConfig?.data; if (data?.mode === 'edit') { @@ -117,6 +120,16 @@ export class LibraryCreatorComponent implements OnInit { this.metadataSource = this.library.metadataSource; } + if (this.library.organizationMode) { + this.organizationMode = this.library.organizationMode; + if (this.library.organizationMode === 'AUTO_DETECT') { + this.organizationModeOptions.push({ + label: this.t.translate('libraryCreator.creator.organizationModeAutoDetect'), + value: 'AUTO_DETECT' + }); + } + } + this.libraryService.getBookCountsByFormat(this.library.id!).subscribe(counts => { this.formatCounts = counts; }); @@ -130,6 +143,13 @@ export class LibraryCreatorComponent implements OnInit { this.formatPriority = [...this.allBookFormats]; } + private initializeOrganizationModeOptions(): void { + this.organizationModeOptions = [ + {label: this.t.translate('libraryCreator.creator.organizationModeBookPerFile'), value: 'BOOK_PER_FILE'}, + {label: this.t.translate('libraryCreator.creator.organizationModeBookPerFolder'), value: 'BOOK_PER_FOLDER'} + ]; + } + private initializeAllowedFormats(): void { this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type)); } @@ -237,7 +257,8 @@ export class LibraryCreatorComponent implements OnInit { watch: this.watch, formatPriority: this.formatPriority.map(f => f.type), allowedFormats: this.allowAllFormats ? [] : Array.from(this.selectedAllowedFormats), - metadataSource: this.metadataSource + metadataSource: this.metadataSource, + organizationMode: this.organizationMode }; if (this.mode === 'edit') { diff --git a/booklore-ui/src/i18n/en/library-creator.json b/booklore-ui/src/i18n/en/library-creator.json index 7cdcbea17..d24b60fad 100644 --- a/booklore-ui/src/i18n/en/library-creator.json +++ b/booklore-ui/src/i18n/en/library-creator.json @@ -24,6 +24,11 @@ "metadataSourcePreferSidecar": "Prefer Sidecar", "metadataSourcePreferEmbedded": "Prefer Embedded", "metadataSourceNone": "None", + "organizationMode": "Organization mode", + "organizationModeTooltip": "How files are grouped into books during scanning", + "organizationModeBookPerFile": "One book per file", + "organizationModeBookPerFolder": "One book per folder", + "organizationModeAutoDetect": "Auto-detect (legacy)", "formatPriority": "Format priority", "formatPriorityTooltip": "Drag to reorder preferred format when a book has multiple files", "allowedFormats": "Allowed formats", diff --git a/booklore-ui/src/i18n/es/library-creator.json b/booklore-ui/src/i18n/es/library-creator.json index a5c8995e4..2b43b0d12 100644 --- a/booklore-ui/src/i18n/es/library-creator.json +++ b/booklore-ui/src/i18n/es/library-creator.json @@ -24,6 +24,11 @@ "metadataSourcePreferSidecar": "Preferir sidecar", "metadataSourcePreferEmbedded": "Preferir incrustado", "metadataSourceNone": "Ninguno", + "organizationMode": "Modo de organizacion", + "organizationModeTooltip": "Como se agrupan los archivos en libros durante el escaneo", + "organizationModeBookPerFile": "Un libro por archivo", + "organizationModeBookPerFolder": "Un libro por carpeta", + "organizationModeAutoDetect": "Deteccion automatica (legado)", "formatPriority": "Prioridad de formato", "formatPriorityTooltip": "Arrastra para reordenar el formato preferido cuando un libro tiene multiples archivos", "allowedFormats": "Formatos permitidos",