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
This commit is contained in:
ACX
2026-03-09 14:42:44 -06:00
committed by GitHub
parent 40c98e84f2
commit bf1957847c
39 changed files with 4533 additions and 975 deletions
@@ -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<String, List<LibraryFile>> groups) {
return groups.size();
}
private int totalFiles(Map<String, List<LibraryFile>> groups) {
return groups.values().stream().mapToInt(List::size).sum();
}
private int folderBasedCount(Map<String, List<LibraryFile>> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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);
}
}
@@ -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
@@ -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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> 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<LibraryFile> files = helper.getLibraryFiles(createLibrary(tempDir));
assertThat(files).hasSize(1);
assertThat(files.getFirst().getFileSubPath()).isEqualTo("A/B/C/D/E");
}
}
@@ -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
@@ -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<Path> 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();
}
}
@@ -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<Path> capt = ArgumentCaptor.forClass(Path.class);
verify(monitoringService, atLeast(3)).registerPath(capt.capture(), eq(42L));
List<Path> 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);
}
}
@@ -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<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
map.put(root, 99L);
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
monitored.add(root);
Field registeredKeysField = MonitoringService.class.getDeclaredField("registeredWatchKeys");
registeredKeysField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,WatchKey> keys = (Map<Path,WatchKey>) 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<Path,Long> map = (Map<Path,Long>) 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<Path,Long> map = (Map<Path,Long>) 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<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
monitored.add(invalid);
Field registeredKeysField = MonitoringService.class.getDeclaredField("registeredWatchKeys");
registeredKeysField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path,WatchKey> keys = (Map<Path,WatchKey>) 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<Path,Long> map = (Map<Path,Long>) 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<Path> monitored = (Set<Path>) 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<Path> monitored = (Set<Path>) 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<Path,Long> map = (Map<Path,Long>) pathToLibraryField.get(service);
assertEquals(55L, map.get(dir));
Field monitoredPathsField = MonitoringService.class.getDeclaredField("monitoredPaths");
monitoredPathsField.setAccessible(true);
@SuppressWarnings("unchecked")
Set<Path> monitored = (Set<Path>) monitoredPathsField.get(service);
assertTrue(monitored.contains(dir));
Field keysField = MonitoringService.class.getDeclaredField("registeredWatchKeys");
keysField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Path, WatchKey> keys = (Map<Path, WatchKey>) keysField.get(service);
assertTrue(keys.containsKey(dir));
}
}
@@ -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<FileUtils> 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<BookEntity> 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<BookFileEntity> 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<Path, String> 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<Path, String> 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<Path, String> 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);
}
}
}
@@ -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<FileFingerprint> fingerprintMock;
private MockedStatic<FileUtils> fileUtilsMock;
private MockedStatic<BookFileGroupingUtils> 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<PendingDeletionPool.FileSnapshot> 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));
}
}
}
@@ -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);
}
}
}
@@ -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<PendingDeletionPool.MatchResult> 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<PendingDeletionPool.MatchResult> 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<PendingDeletionPool.MatchResult> 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<Path, String> fileHashes = Map.of(
Path.of("/new/test.epub"), "abc123",
Path.of("/new/test2.epub"), "def456");
Optional<PendingDeletionPool.FolderMatchResult> 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<Path, String> fileHashes = Map.of(Path.of("/new/other.epub"), "zzz999");
Optional<PendingDeletionPool.FolderMatchResult> 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);
}
}
@@ -185,6 +185,37 @@ class FileUtilsTest {
assertFalse(FileUtils.shouldIgnore(emptyPath));
}
@Test
void testShouldIgnore_tempFileExtensions_returnsTrue() {
List<String> 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<Path> 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<Path> 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<Path> 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