refactor(api): move detect deleted/new books to LibraryFileHelper (#555)

This commit is contained in:
James Ward
2026-04-22 17:27:42 -04:00
committed by Zach Yale
parent 11e6a35e2b
commit 11caa916cf
4 changed files with 481 additions and 140 deletions
@@ -1,6 +1,8 @@
package org.booklore.service.library;
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.entity.LibraryPathEntity;
import org.booklore.model.enums.BookFileExtension;
@@ -26,6 +28,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Component
@Slf4j
@@ -33,6 +36,75 @@ public class LibraryFileHelper {
private static final int MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK = 2;
public List<Long> detectDeletedBookIds(List<LibraryFile> libraryFiles, List<BookEntity> books) {
Set<Path> currentFullPaths = libraryFiles.stream()
.map(LibraryFile::getFullPath)
.collect(Collectors.toSet());
return books.stream()
.filter(book -> (book.getDeleted() == null || !book.getDeleted()))
.filter(book -> {
// Don't mark fileless books as deleted - they're intentionally without files
if (!book.hasFiles()) {
return false;
}
return !currentFullPaths.contains(book.getFullFilePath());
})
.map(BookEntity::getId)
.collect(Collectors.toList());
}
public List<Long> detectDeletedAdditionalFiles(List<LibraryFile> libraryFiles, List<BookFileEntity> allAdditionalFiles) {
Set<String> currentFileKeys = libraryFiles.stream()
.map(this::generateUniqueKey)
.collect(Collectors.toSet());
return allAdditionalFiles.stream()
.filter(BookFileEntity::isBookFormat)
.filter(additionalFile -> !currentFileKeys.contains(generateUniqueKey(additionalFile)))
.map(BookFileEntity::getId)
.collect(Collectors.toList());
}
public List<LibraryFile> detectNewBookPaths(List<LibraryFile> libraryFiles, List<BookEntity> books, List<BookFileEntity> allAdditionalFiles) {
Set<String> existingKeys = books.stream()
.filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty())
.map(this::generateUniqueKey)
.collect(Collectors.toSet());
Set<String> additionalFileKeys = allAdditionalFiles.stream()
.map(this::generateUniqueKey)
.collect(Collectors.toSet());
existingKeys.addAll(additionalFileKeys);
return libraryFiles.stream()
.filter(file -> !existingKeys.contains(generateUniqueKey(file)))
.collect(Collectors.toList());
}
private String generateUniqueKey(BookEntity book) {
BookFileEntity primaryFile = book.getPrimaryBookFile();
if (primaryFile == null) {
// Fileless book - use a unique key that won't match any file
return "fileless:" + book.getId();
}
return generateKey(book.getLibraryPath().getId(), primaryFile.getFileSubPath(), primaryFile.getFileName());
}
private String generateUniqueKey(BookFileEntity file) {
return generateKey(file.getBook().getLibraryPath().getId(), file.getFileSubPath(), file.getFileName());
}
private String generateUniqueKey(LibraryFile file) {
return generateKey(file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName());
}
private String generateKey(Long libraryPathId, String subPath, String fileName) {
String safeSubPath = (subPath == null) ? "" : subPath;
return libraryPathId + ":" + safeSubPath + ":" + fileName;
}
public List<LibraryFile> getAllLibraryFiles(LibraryEntity libraryEntity) throws IOException {
List<LibraryFile> allFiles = new ArrayList<>();
for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
@@ -57,7 +57,9 @@ public class LibraryProcessingService {
try {
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity);
List<BookEntity> existingBooks = bookRepository.findAllByLibraryIdForRescan(libraryId);
List<LibraryFile> newFiles = detectNewBookPaths(libraryFiles, existingBooks, libraryId);
List<BookFileEntity> allAdditionalFiles = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId());
List<LibraryFile> newFiles = libraryFileHelper.detectNewBookPaths(libraryFiles, existingBooks, allAdditionalFiles);
// Use BookGroupingService for consistent grouping based on organization mode
Map<String, List<LibraryFile>> groups = bookGroupingService.groupForInitialScan(newFiles, libraryEntity);
@@ -96,12 +98,14 @@ public class LibraryProcessingService {
throw ApiError.LIBRARY_PATH_NOT_ACCESSIBLE.createException(paths);
}
List<Long> additionalFileIds = detectDeletedAdditionalFiles(allLibraryFiles, libraryEntity);
List<BookFileEntity> allAdditionalFiles = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId());
List<Long> additionalFileIds = libraryFileHelper.detectDeletedAdditionalFiles(allLibraryFiles, allAdditionalFiles);
if (!additionalFileIds.isEmpty()) {
log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName());
bookDeletionService.deleteRemovedAdditionalFiles(additionalFileIds);
}
List<Long> bookIds = detectDeletedBookIds(allLibraryFiles, books);
List<Long> bookIds = libraryFileHelper.detectDeletedBookIds(allLibraryFiles, books);
if (!bookIds.isEmpty()) {
log.info("Detected {} removed books in library: {}", bookIds.size(), libraryEntity.getName());
bookDeletionService.processDeletedLibraryFiles(bookIds, allLibraryFiles);
@@ -114,7 +118,7 @@ public class LibraryProcessingService {
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
books = bookRepository.findAllByLibraryIdForRescan(libraryId);
List<LibraryFile> newFiles = detectNewBookPaths(filteredFiles, books, libraryId);
List<LibraryFile> newFiles = libraryFileHelper.detectNewBookPaths(filteredFiles, books, allAdditionalFiles);
// Use BookGroupingService to determine what to attach vs create new
BookGroupingService.GroupingResult groupingResult = bookGroupingService.groupForRescan(newFiles, libraryEntity);
@@ -146,41 +150,6 @@ public class LibraryProcessingService {
}
}
protected static List<Long> detectDeletedBookIds(List<LibraryFile> libraryFiles, List<BookEntity> books) {
Set<Path> currentFullPaths = libraryFiles.stream()
.map(LibraryFile::getFullPath)
.collect(Collectors.toSet());
return books.stream()
.filter(book -> (book.getDeleted() == null || !book.getDeleted()))
.filter(book -> {
// Don't mark fileless books as deleted - they're intentionally without files
if (!book.hasFiles()) {
return false;
}
return !currentFullPaths.contains(book.getFullFilePath());
})
.map(BookEntity::getId)
.collect(Collectors.toList());
}
protected List<LibraryFile> detectNewBookPaths(List<LibraryFile> libraryFiles, List<BookEntity> books, Long libraryId) {
Set<String> existingKeys = books.stream()
.filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty())
.map(this::generateUniqueKey)
.collect(Collectors.toSet());
Set<String> additionalFileKeys = bookAdditionalFileRepository.findByLibraryId(libraryId).stream()
.map(this::generateUniqueKey)
.collect(Collectors.toSet());
existingKeys.addAll(additionalFileKeys);
return libraryFiles.stream()
.filter(file -> !existingKeys.contains(generateUniqueKey(file)))
.collect(Collectors.toList());
}
private void autoAttachFile(BookEntity book, LibraryFile file) {
// Check if file already exists to prevent duplicates during concurrent rescans
var existing = bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(
@@ -228,40 +197,4 @@ public class LibraryProcessingService {
log.error("Error auto-attaching file {}: {}", file.getFileName(), e.getMessage());
}
}
private String generateUniqueKey(BookEntity book) {
BookFileEntity primaryFile = book.getPrimaryBookFile();
if (primaryFile == null) {
// Fileless book - use a unique key that won't match any file
return "fileless:" + book.getId();
}
return generateKey(book.getLibraryPath().getId(), primaryFile.getFileSubPath(), primaryFile.getFileName());
}
private String generateUniqueKey(BookFileEntity file) {
return generateKey(file.getBook().getLibraryPath().getId(), file.getFileSubPath(), file.getFileName());
}
private String generateUniqueKey(LibraryFile file) {
return generateKey(file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName());
}
private String generateKey(Long libraryPathId, String subPath, String fileName) {
String safeSubPath = (subPath == null) ? "" : subPath;
return libraryPathId + ":" + safeSubPath + ":" + fileName;
}
protected List<Long> detectDeletedAdditionalFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
Set<String> currentFileKeys = libraryFiles.stream()
.map(this::generateUniqueKey)
.collect(Collectors.toSet());
List<BookFileEntity> allAdditionalFiles = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId());
return allAdditionalFiles.stream()
.filter(BookFileEntity::isBookFormat)
.filter(additionalFile -> !currentFileKeys.contains(generateUniqueKey(additionalFile)))
.map(BookFileEntity::getId)
.collect(Collectors.toList());
}
}
@@ -1,6 +1,8 @@
package org.booklore.service.library;
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.entity.LibraryPathEntity;
import org.booklore.model.enums.BookFileType;
@@ -8,12 +10,14 @@ 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;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@@ -24,10 +28,53 @@ class LibraryFileHelperTest {
@TempDir
Path tempDir;
@InjectMocks
private LibraryFileHelper libraryFileHelper;
@Test
void testGetAllLibraryFiles_IncludesAudiobookFolderFiles() throws IOException {
Path authorFolder = tempDir.resolve("author");
Path bookFolder = authorFolder.resolve("title");
Path otherBookFolder = authorFolder.resolve("other");
Files.createDirectories(bookFolder);
Files.createDirectories(otherBookFolder);
Files.write(bookFolder.resolve("a.mp3"), new byte[]{1});
Files.write(bookFolder.resolve("b.mp3"), new byte[]{1});
Files.write(otherBookFolder.resolve("c.mp3"), new byte[]{1});
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setId(10L);
libraryPath.setPath(tempDir.toString());
LibraryEntity testLibrary = LibraryEntity.builder()
.name("Test Library")
.icon("book")
.watch(false)
.libraryPaths(List.of(libraryPath))
.build();
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(testLibrary);
List<String> actual = libraryFiles
.stream()
.map(LibraryFile::getFullPath)
.map(p -> tempDir.relativize(p))
.map(Path::toString)
.sorted()
.toList();
List<String> expected = List.of(
"author/other/c.mp3",
"author/title"
);
assertEquals(expected, actual);
}
@Test
void testGetLibraryFiles_HandlesInaccessibleDirectories() throws IOException {
LibraryFileHelper libraryFileHelper = new LibraryFileHelper();
Files.write(tempDir.resolve("happy.epub"), new byte[]{1});
Files.createDirectory(tempDir.resolve("some_other_random_named_dir"), PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("---------")));
Files.write(tempDir.resolve("zzzz_happ.epub"), new byte[]{1});
@@ -63,35 +110,29 @@ class LibraryFileHelperTest {
@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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.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});
@@ -99,69 +140,59 @@ class LibraryFileHelperTest {
Path visibleDir = Files.createDirectories(tempDir.resolve("visible"));
Files.write(visibleDir.resolve("book.epub"), new byte[]{1});
List<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibrary(tempDir));
assertThat(files).hasSize(2);
LibraryFile epub = files.stream().filter(f -> f.getFileName().equals("book.epub")).findFirst().orElseThrow();
@@ -173,14 +204,12 @@ class LibraryFileHelperTest {
@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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibrary(tempDir));
assertThat(files).hasSize(1);
assertThat(files.getFirst().isFolderBased()).isTrue();
@@ -190,12 +219,10 @@ class LibraryFileHelperTest {
@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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibrary(tempDir));
assertThat(files).hasSize(1);
assertThat(files.getFirst().isFolderBased()).isFalse();
@@ -204,13 +231,11 @@ class LibraryFileHelperTest {
@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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibrary(tempDir));
assertThat(files).hasSize(3);
assertThat(files).noneMatch(LibraryFile::isFolderBased);
@@ -218,8 +243,6 @@ class LibraryFileHelperTest {
@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"));
@@ -231,7 +254,7 @@ class LibraryFileHelperTest {
Files.write(book2.resolve(String.format("CH%02d.mp3", i)), new byte[]{1});
}
List<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibrary(tempDir));
assertThat(files).hasSize(2);
assertThat(files).allMatch(LibraryFile::isFolderBased);
@@ -240,8 +263,6 @@ class LibraryFileHelperTest {
@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});
@@ -251,7 +272,7 @@ class LibraryFileHelperTest {
Files.write(audioDir.resolve(String.format("Catching Fire %03d.mp3", i)), new byte[]{1});
}
List<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.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();
@@ -265,14 +286,12 @@ class LibraryFileHelperTest {
@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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibrary(tempDir));
assertThat(files).hasSize(4);
assertThat(files).noneMatch(LibraryFile::isFolderBased);
@@ -281,12 +300,10 @@ class LibraryFileHelperTest {
@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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibrary(tempDir));
assertThat(files).hasSize(1);
assertThat(files.getFirst().getFileSubPath()).isEqualTo("Andy Weir/The Martian");
@@ -294,13 +311,11 @@ class LibraryFileHelperTest {
@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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibrary(tempDir));
assertThat(files).hasSize(1);
assertThat(files.getFirst().getFileName()).isEqualTo("visible.epub");
@@ -308,29 +323,25 @@ class LibraryFileHelperTest {
@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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibrary(tempDir));
assertThat(files).hasSize(1);
assertThat(files.getFirst().getFileName()).isEqualTo("real.epub");
@@ -352,14 +363,12 @@ class LibraryFileHelperTest {
@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<LibraryFile> files = helper.getLibraryFiles(createLibraryWithMode(tempDir, LibraryOrganizationMode.AUTO_DETECT));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibraryWithMode(tempDir, LibraryOrganizationMode.AUTO_DETECT));
assertThat(files).hasSize(1);
assertThat(files.getFirst().isFolderBased()).isTrue();
@@ -367,13 +376,11 @@ class LibraryFileHelperTest {
@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<LibraryFile> files = helper.getLibraryFiles(createLibraryWithMode(tempDir, LibraryOrganizationMode.AUTO_DETECT));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibraryWithMode(tempDir, LibraryOrganizationMode.AUTO_DETECT));
assertThat(files).hasSize(2);
assertThat(files).noneMatch(LibraryFile::isFolderBased);
@@ -381,14 +388,339 @@ class LibraryFileHelperTest {
@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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
List<LibraryFile> files = libraryFileHelper.getLibraryFiles(createLibrary(tempDir));
assertThat(files).hasSize(1);
assertThat(files.getFirst().getFileSubPath()).isEqualTo("A/B/C/D/E");
}
@Test
void detectDeletedBookIds_shouldIgnoreBooksWithoutFiles() {
BookEntity book = BookEntity.builder()
.id(1L)
.bookFiles(Collections.emptyList())
.build();
List<Long> actual = libraryFileHelper.detectDeletedBookIds(Collections.emptyList(), List.of(book));
assertThat(actual).hasSize(0);
}
@Test
void detectDeletedBookIds_shouldIgnoreDeletedBooks() {
BookEntity book = BookEntity.builder()
.id(1L)
.bookFiles(List.of(BookFileEntity.builder().build()))
.deleted(true)
.build();
List<Long> actual = libraryFileHelper.detectDeletedBookIds(Collections.emptyList(), List.of(book));
assertThat(actual).hasSize(0);
}
@Test
void detectDeletedBookIds_shouldHandleFolderBasedAudiobooks() {
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path("/books")
.build();
LibraryFile bookLibraryFolder = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.folderBased(true)
.fileSubPath("example")
.fileName("a")
.build();
BookFileEntity existing = BookFileEntity.builder()
.folderBased(true)
.fileSubPath("example")
.fileName("a")
.build();
BookEntity book = BookEntity.builder()
.id(1L)
.libraryPath(libraryPathEntity)
.bookFiles(List.of(existing))
.build();
existing.setBook(book);
List<Long> actual = libraryFileHelper.detectDeletedBookIds(
List.of(bookLibraryFolder),
List.of(book)
);
assertThat(actual).hasSize(0);
}
@Test
void detectDeletedBookIds_shouldOnlyDetectBooksMissingFiles() {
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path("/books")
.build();
LibraryFile bookLibraryFile = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.fileSubPath("example")
.fileName("file.epub")
.build();
BookFileEntity existing = BookFileEntity.builder()
.fileSubPath("example")
.fileName("file.epub")
.build();
BookEntity book = BookEntity.builder()
.id(1L)
.libraryPath(libraryPathEntity)
.bookFiles(List.of(existing))
.build();
existing.setBook(book);
BookFileEntity expectedMissingBookFileEntity = BookFileEntity.builder()
.fileSubPath("missing")
.fileName("missing.epub")
.build();
BookEntity expectedMissingBook = BookEntity.builder()
.id(2L)
.libraryPath(libraryPathEntity)
.bookFiles(List.of(expectedMissingBookFileEntity))
.build();
expectedMissingBookFileEntity.setBook(expectedMissingBook);
List<Long> actual = libraryFileHelper.detectDeletedBookIds(
List.of(bookLibraryFile),
List.of(book, expectedMissingBook)
);
assertThat(actual).isEqualTo(List.of(2L));
}
@Test
void detectNewBooks_shouldReturnAllFilesWhenNoBooks() {
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path("/books")
.build();
LibraryFile fileA = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.fileSubPath("example")
.fileName("a.epub")
.build();
LibraryFile fileB = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.fileSubPath("example")
.fileName("b.epub")
.build();
List<LibraryFile> actual = libraryFileHelper.detectNewBookPaths(
List.of(fileA, fileB),
Collections.emptyList(),
Collections.emptyList()
);
assertThat(actual).isEqualTo(List.of(fileA, fileB));
}
@Test
void detectNewBooks_shouldNotReturnFilesAssociatedWithBooks() {
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path("/books")
.build();
LibraryFile fileA = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.fileSubPath("example")
.fileName("a.epub")
.build();
LibraryFile fileB = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.fileSubPath("example")
.fileName("b.epub")
.build();
BookFileEntity bookFile = BookFileEntity.builder()
.fileSubPath("example")
.fileName("a.epub")
.build();
BookEntity book = BookEntity.builder()
.libraryPath(libraryPathEntity)
.bookFiles(List.of(bookFile))
.build();
bookFile.setBook(book);
List<LibraryFile> actual = libraryFileHelper.detectNewBookPaths(
List.of(fileA, fileB),
List.of(book),
Collections.emptyList()
);
assertThat(actual).isEqualTo(List.of(fileB));
}
@Test
void detectNewBooks_shouldHandleFolderAudiobooks() {
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path("/books")
.build();
LibraryFile folderA = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.folderBased(true)
.fileSubPath("example")
.fileName("a")
.build();
LibraryFile fileB = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.fileSubPath("example")
.fileName("b.epub")
.build();
BookFileEntity audiobookFolder = BookFileEntity.builder()
.folderBased(true)
.fileSubPath("example")
.fileName("a")
.build();
BookEntity audiobook = BookEntity.builder()
.libraryPath(libraryPathEntity)
.bookFiles(List.of(audiobookFolder))
.build();
audiobookFolder.setBook(audiobook);
List<LibraryFile> actual = libraryFileHelper.detectNewBookPaths(
List.of(folderA, fileB),
List.of(audiobook),
Collections.emptyList()
);
assertThat(actual).isEqualTo(List.of(fileB));
}
@Test
void detectNewBooks_shouldHandleAdditionalFiles() {
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path("/books")
.build();
LibraryFile fileA = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.fileSubPath("example")
.fileName("a.epub")
.build();
LibraryFile fileB = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.fileSubPath("example")
.fileName("b.epub")
.build();
LibraryFile fileC = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.fileSubPath("example")
.fileName("c.epub")
.build();
BookFileEntity bookFile = BookFileEntity.builder()
.fileSubPath("example")
.fileName("a.epub")
.build();
BookEntity book = BookEntity.builder()
.libraryPath(libraryPathEntity)
.bookFiles(List.of(bookFile))
.build();
bookFile.setBook(book);
BookFileEntity additionalFile = BookFileEntity.builder()
.fileSubPath("example")
.fileName("b.epub")
.book(book)
.build();
List<LibraryFile> actual = libraryFileHelper.detectNewBookPaths(
List.of(fileA, fileB, fileC),
List.of(book),
List.of(additionalFile)
);
assertThat(actual).isEqualTo(List.of(fileC));
}
@Test
void detectDeletedAdditionalFiles_shouldIgnoreNonBookFormat() {
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path("/books")
.build();
BookEntity book = BookEntity.builder()
.libraryPath(libraryPathEntity)
.build();
BookFileEntity additionalFile = BookFileEntity.builder()
.id(1L)
.isBookFormat(false)
.fileSubPath("example")
.fileName("b.epub")
.book(book)
.build();
List<Long> actual = libraryFileHelper.detectDeletedAdditionalFiles(
Collections.emptyList(),
List.of(additionalFile)
);
assertThat(actual).hasSize(0);
}
@Test
void detectDeletedAdditionalFiles_shouldFindMissingAdditionalFiles() {
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
.path("/books")
.build();
LibraryFile fileA = LibraryFile.builder()
.libraryPathEntity(libraryPathEntity)
.fileSubPath("example")
.fileName("a.epub")
.build();
BookEntity book = BookEntity.builder()
.libraryPath(libraryPathEntity)
.build();
BookFileEntity additionalFileA = BookFileEntity.builder()
.id(1L)
.isBookFormat(true)
.fileSubPath("example")
.fileName("a.epub")
.book(book)
.build();
BookFileEntity additionalFileB = BookFileEntity.builder()
.id(2L)
.isBookFormat(true)
.fileSubPath("example")
.fileName("b.epub")
.book(book)
.build();
List<Long> actual = libraryFileHelper.detectDeletedAdditionalFiles(
List.of(fileA),
List.of(additionalFileA, additionalFileB)
);
assertThat(actual).isEqualTo(List.of(2L));
}
}
@@ -113,6 +113,7 @@ class LibraryProcessingServiceTest {
.build();
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(existingFile, newFile));
when(libraryFileHelper.detectNewBookPaths(any(), any(), any())).thenReturn(List.of(newFile));
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
// Mock grouping service to pass through the files
@@ -208,6 +209,7 @@ class LibraryProcessingServiceTest {
.build();
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(newFile1, newFile2));
when(libraryFileHelper.detectNewBookPaths(any(), any(), any())).thenReturn(List.of(newFile1, newFile2));
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity)))
.thenAnswer(invocation -> {
@@ -250,6 +252,7 @@ class LibraryProcessingServiceTest {
.build();
when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(newFileInSub));
when(libraryFileHelper.detectNewBookPaths(any(), any(), any())).thenReturn(List.of(newFileInSub));
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity)))
.thenAnswer(invocation -> {
@@ -370,6 +373,7 @@ class LibraryProcessingServiceTest {
.build();
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(epubOnDisk));
when(libraryFileHelper.detectDeletedAdditionalFiles(any(), any())).thenReturn(List.of(pdf.getId()));
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(List.of(epub, pdf, image));
when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity)))