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
@@ -1,25 +0,0 @@
package org.booklore.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.WatchService;
@Slf4j
@Configuration
public class MonitoringConfig {
@Bean
public WatchService watchService() {
WatchService watchService = null;
try {
watchService = FileSystems.getDefault().newWatchService();
} catch (IOException e) {
log.error("Error creating WatchService:", e);
}
return watchService;
}
}
@@ -3,6 +3,7 @@ package org.booklore.model.dto.request;
import org.booklore.model.dto.LibraryPath;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.IconType;
import org.booklore.model.enums.LibraryOrganizationMode;
import org.booklore.model.enums.MetadataSource;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.validation.constraints.NotBlank;
@@ -33,4 +34,5 @@ public class CreateLibraryRequest {
private List<BookFileType> formatPriority;
private List<BookFileType> allowedFormats;
private MetadataSource metadataSource;
private LibraryOrganizationMode organizationMode;
}
@@ -1,6 +1,8 @@
package org.booklore.model.enums;
public enum LibraryOrganizationMode {
BOOK_PER_FILE,
BOOK_PER_FOLDER,
@Deprecated
AUTO_DETECT
}
@@ -27,12 +27,15 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b JOIN b.bookFiles bf WHERE bf.currentHash = :currentHash AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)")
Optional<BookEntity> findByCurrentHash(@Param("currentHash") String currentHash);
@Query("SELECT b FROM BookEntity b JOIN FETCH b.bookFiles bf WHERE bf.currentHash = :currentHash AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false OR b.deletedAt > :cutoff)")
Optional<BookEntity> findByCurrentHashIncludingRecentlyDeleted(@Param("currentHash") String currentHash, @Param("cutoff") Instant cutoff);
Optional<BookEntity> findByBookCoverHash(String bookCoverHash);
@Query("SELECT b.id FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
Set<Long> findBookIdsByLibraryId(@Param("libraryId") long libraryId);
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.bookFiles bf WHERE b.libraryPath.id = :libraryPathId AND bf.fileSubPath LIKE CONCAT(:fileSubPathPrefix, '%') AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)")
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.bookFiles bf WHERE b.libraryPath.id = :libraryPathId AND (bf.fileSubPath = :fileSubPathPrefix OR bf.fileSubPath LIKE CONCAT(:fileSubPathPrefix, '/%')) AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllByLibraryPathIdAndFileSubPathStartingWith(@Param("libraryPathId") Long libraryPathId, @Param("fileSubPathPrefix") String fileSubPathPrefix);
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.bookFiles bf WHERE b.libraryPath.id = :libraryPathId AND bf.fileSubPath = :fileSubPath AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)")
@@ -129,6 +132,19 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT COUNT(b) FROM BookEntity b WHERE b.deleted = TRUE")
long countAllSoftDeleted();
@Query("""
SELECT DISTINCT b FROM BookEntity b
JOIN FETCH b.bookFiles bf
WHERE b.libraryPath.id = :libraryPathId
AND (bf.fileSubPath = :folderPath
OR bf.fileSubPath LIKE CONCAT(:folderPath, '/%')
OR (bf.folderBased = true AND CONCAT(bf.fileSubPath, '/', bf.fileName) = :folderPath))
AND bf.isBookFormat = true
AND (b.deleted IS NULL OR b.deleted = false)
""")
List<BookEntity> findBooksWithFilesUnderPath(@Param("libraryPathId") Long libraryPathId,
@Param("folderPath") String folderPath);
@Query(value = """
SELECT b.*
FROM book b
@@ -4,6 +4,7 @@ import org.booklore.model.dto.settings.LibraryFile;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.LibraryOrganizationMode;
import org.booklore.repository.BookRepository;
import org.booklore.util.BookFileGroupingUtils;
@@ -31,6 +32,7 @@ public class BookGroupingService {
LibraryOrganizationMode mode = getOrganizationMode(libraryEntity);
return switch (mode) {
case BOOK_PER_FILE -> groupByFile(newFiles);
case BOOK_PER_FOLDER -> groupByFolder(newFiles);
case AUTO_DETECT -> BookFileGroupingUtils.groupByBaseName(newFiles);
};
@@ -56,6 +58,7 @@ public class BookGroupingService {
newBookGroups = Collections.emptyMap();
} else {
newBookGroups = switch (mode) {
case BOOK_PER_FILE -> groupByFile(unmatched);
case BOOK_PER_FOLDER -> groupByFolder(unmatched);
case AUTO_DETECT -> BookFileGroupingUtils.groupByBaseName(unmatched);
};
@@ -64,27 +67,97 @@ public class BookGroupingService {
return new GroupingResult(filesToAttach, newBookGroups);
}
private Map<String, List<LibraryFile>> groupByFolder(List<LibraryFile> files) {
private Map<String, List<LibraryFile>> groupByFile(List<LibraryFile> files) {
Map<String, List<LibraryFile>> result = new LinkedHashMap<>();
for (LibraryFile file : files) {
String folderKey = file.getLibraryPathEntity().getId() + ":" +
(file.getFileSubPath() == null ? "" : file.getFileSubPath());
result.computeIfAbsent(folderKey, k -> new ArrayList<>()).add(file);
String key = file.getLibraryPathEntity().getId() + ":" +
(file.getFileSubPath() == null ? "" : file.getFileSubPath()) + ":" +
file.getFileName();
result.computeIfAbsent(key, k -> new ArrayList<>()).add(file);
}
log.debug("BOOK_PER_FILE grouping: {} files into {} groups", files.size(), result.size());
return result;
}
private Map<String, List<LibraryFile>> groupByFolder(List<LibraryFile> files) {
Map<String, List<LibraryFile>> result = new LinkedHashMap<>();
Set<String> ebookFolders = new HashSet<>();
for (LibraryFile file : files) {
if (file.getBookFileType() != BookFileType.AUDIOBOOK) {
String folderKey = file.getLibraryPathEntity().getId() + ":" +
(file.getFileSubPath() == null ? "" : file.getFileSubPath());
ebookFolders.add(folderKey);
}
}
for (LibraryFile file : files) {
Long pathId = file.getLibraryPathEntity().getId();
String subPath = file.getFileSubPath() == null ? "" : file.getFileSubPath();
if (subPath.isEmpty()) {
String key = pathId + "::" + file.getFileName();
result.computeIfAbsent(key, k -> new ArrayList<>()).add(file);
} else if (file.getBookFileType() == BookFileType.AUDIOBOOK) {
// Folder-based audiobook entries represent a collapsed directory (e.g., subPath="Author",
// fileName="audiobook-folder"). Their subPath points to the parent because getRelativeSubPath
// takes .getParent() (designed for files, not directories). Reconstruct the actual folder path
// so sibling audiobook folders stay separate and absorption searches from the correct level.
String effectiveSubPath = file.isFolderBased()
? subPath + "/" + file.getFileName()
: subPath;
String ancestorKey = findNearestEbookAncestor(pathId, effectiveSubPath, ebookFolders);
if (ancestorKey != null) {
result.computeIfAbsent(ancestorKey, k -> new ArrayList<>()).add(file);
} else {
String key = pathId + ":" + effectiveSubPath;
result.computeIfAbsent(key, k -> new ArrayList<>()).add(file);
}
} else {
String key = pathId + ":" + subPath;
result.computeIfAbsent(key, k -> new ArrayList<>()).add(file);
}
}
log.debug("BOOK_PER_FOLDER grouping: {} files into {} groups", files.size(), result.size());
return result;
}
private String findNearestEbookAncestor(Long pathId, String subPath, Set<String> ebookFolders) {
String current = subPath;
while (true) {
int lastSep = current.lastIndexOf('/');
if (lastSep == -1) {
lastSep = current.lastIndexOf('\\');
}
if (lastSep <= 0) {
break;
}
current = current.substring(0, lastSep);
String candidateKey = pathId + ":" + current;
if (ebookFolders.contains(candidateKey)) {
return candidateKey;
}
}
return null;
}
private BookEntity findMatchingBook(LibraryFile file, LibraryOrganizationMode mode) {
BookEntity filelessMatch = findMatchingFilelessBook(file, file.getLibraryEntity());
BookEntity filelessMatch = switch (mode) {
case BOOK_PER_FILE, BOOK_PER_FOLDER -> findExactFilelessMatch(file, file.getLibraryEntity());
case AUTO_DETECT -> findMatchingFilelessBook(file, file.getLibraryEntity());
};
if (filelessMatch != null) {
return filelessMatch;
}
String fileSubPath = file.getFileSubPath();
if (mode == LibraryOrganizationMode.BOOK_PER_FILE) {
return null;
}
String fileSubPath = file.getFileSubPath();
if (fileSubPath == null || fileSubPath.isEmpty()) {
return null;
}
@@ -97,15 +170,45 @@ public class BookGroupingService {
.toList();
if (activeBooksInDirectory.isEmpty()) {
if (mode == LibraryOrganizationMode.BOOK_PER_FOLDER && file.getBookFileType() == BookFileType.AUDIOBOOK) {
return findNearestAncestorBookWithEbook(libraryPathId, fileSubPath);
}
return null;
}
return switch (mode) {
case BOOK_PER_FOLDER -> findMatchBookPerFolder(file, activeBooksInDirectory);
case BOOK_PER_FILE -> null;
case BOOK_PER_FOLDER -> findMatchBookPerFolderWithAbsorption(file, activeBooksInDirectory);
case AUTO_DETECT -> findMatchAutoDetect(file, activeBooksInDirectory);
};
}
private BookEntity findExactFilelessMatch(LibraryFile file, LibraryEntity library) {
List<BookEntity> filelessBooks = bookRepository.findFilelessBooksByLibraryId(library.getId());
if (filelessBooks.isEmpty()) {
return null;
}
String fileBaseName = BookFileGroupingUtils.extractGroupingKey(file.getFileName());
Long fileLibraryPathId = file.getLibraryPathEntity().getId();
for (BookEntity book : filelessBooks) {
if (book.getLibraryPath() != null && !book.getLibraryPath().getId().equals(fileLibraryPathId)) {
continue;
}
if (book.getMetadata() != null && book.getMetadata().getTitle() != null) {
String bookTitle = BookFileGroupingUtils.extractGroupingKey(book.getMetadata().getTitle());
if (fileBaseName.equals(bookTitle)) {
log.debug("Exact matched file '{}' to fileless book '{}' (title: {})",
file.getFileName(), book.getId(), book.getMetadata().getTitle());
return book;
}
}
}
return null;
}
private BookEntity findMatchingFilelessBook(LibraryFile file, LibraryEntity library) {
List<BookEntity> filelessBooks = bookRepository.findFilelessBooksByLibraryId(library.getId());
if (filelessBooks.isEmpty()) {
@@ -133,7 +236,7 @@ public class BookGroupingService {
return null;
}
private BookEntity findMatchBookPerFolder(LibraryFile file, List<BookEntity> booksInDirectory) {
private BookEntity findMatchBookPerFolderWithAbsorption(LibraryFile file, List<BookEntity> booksInDirectory) {
List<BookEntity> booksWithFiles = booksInDirectory.stream()
.filter(BookEntity::hasFiles)
.toList();
@@ -143,18 +246,40 @@ public class BookGroupingService {
}
if (booksWithFiles.size() == 1) {
BookEntity book = booksWithFiles.get(0);
if (isFileNameCompatible(file, book)) {
log.debug("BOOK_PER_FOLDER: Attaching '{}' to single book in folder: '{}'",
file.getFileName(), book.getPrimaryBookFile().getFileName());
return book;
}
return null;
return booksWithFiles.getFirst();
}
log.warn("BOOK_PER_FOLDER: Multiple books ({}) in folder '{}', using filename match",
booksWithFiles.size(), file.getFileSubPath());
return findBestMatch(file, booksWithFiles);
return booksWithFiles.stream()
.max(Comparator.comparingLong(book -> book.getBookFiles() != null ? book.getBookFiles().size() : 0))
.orElse(null);
}
private BookEntity findNearestAncestorBookWithEbook(Long libraryPathId, String subPath) {
String current = subPath;
while (true) {
int lastSep = current.lastIndexOf('/');
if (lastSep == -1) {
lastSep = current.lastIndexOf('\\');
}
if (lastSep <= 0) {
break;
}
current = current.substring(0, lastSep);
List<BookEntity> booksAtLevel = bookRepository.findAllByLibraryPathIdAndFileSubPath(libraryPathId, current);
for (BookEntity book : booksAtLevel) {
if (book.getDeleted() != null && book.getDeleted()) {
continue;
}
if (book.getBookFiles() != null && book.getBookFiles().stream()
.anyMatch(bf -> bf.getBookType() != BookFileType.AUDIOBOOK)) {
log.debug("BOOK_PER_FOLDER: Audio absorption matched to ancestor book id={} at '{}'",
book.getId(), current);
return book;
}
}
}
return null;
}
private BookEntity findMatchAutoDetect(LibraryFile file, List<BookEntity> booksInDirectory) {
@@ -167,7 +292,7 @@ public class BookGroupingService {
}
if (booksWithFiles.size() == 1) {
BookEntity book = booksWithFiles.get(0);
BookEntity book = booksWithFiles.getFirst();
if (isFileNameCompatible(file, book)) {
log.debug("AUTO_DETECT: Single book in folder '{}', attaching '{}' to '{}'",
file.getFileSubPath(), file.getFileName(), book.getPrimaryBookFile().getFileName());
@@ -219,22 +344,6 @@ public class BookGroupingService {
return BookFileGroupingUtils.calculateSimilarity(fileKey, bookKey) >= 0.85;
}
private BookEntity findExactMatch(LibraryFile file, List<BookEntity> books) {
String fileKey = BookFileGroupingUtils.extractGroupingKey(file.getFileName());
for (BookEntity book : books) {
BookFileEntity primaryFile = book.getPrimaryBookFile();
if (primaryFile == null) {
continue;
}
String bookKey = BookFileGroupingUtils.extractGroupingKey(primaryFile.getFileName());
if (fileKey.equals(bookKey)) {
return book;
}
}
return null;
}
private LibraryOrganizationMode getOrganizationMode(LibraryEntity library) {
LibraryOrganizationMode mode = library.getOrganizationMode();
return mode != null ? mode : LibraryOrganizationMode.AUTO_DETECT;
@@ -2,6 +2,7 @@ package org.booklore.service.library;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.exception.ApiError;
import org.booklore.model.FileProcessResult;
import org.booklore.model.dto.settings.LibraryFile;
import org.booklore.model.entity.BookEntity;
@@ -10,6 +11,7 @@ import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookAdditionalFileRepository;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.event.BookEventBroadcaster;
import org.booklore.service.file.FileFingerprint;
import org.booklore.service.fileprocessor.BookFileProcessor;
@@ -44,6 +46,7 @@ public class FileAsBookProcessor {
private final KoboAutoShelfService koboAutoShelfService;
private final BookRepository bookRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final LibraryRepository libraryRepository;
private final FileService fileService;
private final MetadataExtractorFactory metadataExtractorFactory;
private final AudiobookMetadataExtractor audiobookMetadataExtractor;
@@ -56,10 +59,18 @@ public class FileAsBookProcessor {
@Transactional
public void processLibraryFilesGrouped(Map<String, List<LibraryFile>> groups, LibraryEntity libraryEntity) {
LibraryEntity managedLibrary = ensureManaged(libraryEntity);
for (Map.Entry<String, List<LibraryFile>> entry : groups.entrySet()) {
processGroupWithErrorHandling(entry.getValue(), libraryEntity);
entry.getValue().forEach(lf -> lf.setLibraryEntity(managedLibrary));
processGroupWithErrorHandling(entry.getValue(), managedLibrary);
}
log.info("Finished processing library '{}'", libraryEntity.getName());
log.info("Finished processing library '{}'", managedLibrary.getName());
}
private LibraryEntity ensureManaged(LibraryEntity entity) {
if (entity.getId() == null) return entity;
return libraryRepository.findById(entity.getId())
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(entity.getId()));
}
private void processGroupWithErrorHandling(List<LibraryFile> group, LibraryEntity libraryEntity) {
@@ -114,14 +125,14 @@ public class FileAsBookProcessor {
List<BookFileType> formatPriority = libraryEntity.getFormatPriority();
return group.stream()
.filter(f -> f.getBookFileType() != null)
.min(Comparator.comparingInt(f -> {
.min(Comparator.<LibraryFile, Integer>comparing(f -> {
BookFileType bookFileType = f.getBookFileType();
if (formatPriority != null && !formatPriority.isEmpty()) {
int index = formatPriority.indexOf(bookFileType);
return index >= 0 ? index : Integer.MAX_VALUE;
}
return bookFileType.ordinal();
}));
}).thenComparing(LibraryFile::getFileName));
}
private void createAdditionalBookFile(BookEntity bookEntity, LibraryFile file) {
@@ -5,6 +5,7 @@ import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.model.enums.BookFileExtension;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.LibraryOrganizationMode;
import org.booklore.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.jspecify.annotations.NonNull;
@@ -41,7 +42,110 @@ public class LibraryFileHelper {
}
public List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity) throws IOException {
return filterByAllowedFormats(getAllLibraryFiles(libraryEntity), libraryEntity.getAllowedFormats());
LibraryOrganizationMode mode = libraryEntity.getOrganizationMode() != null
? libraryEntity.getOrganizationMode() : LibraryOrganizationMode.AUTO_DETECT;
List<LibraryFile> allFiles = switch (mode) {
case BOOK_PER_FILE, BOOK_PER_FOLDER -> getAllLibraryFilesFlat(libraryEntity);
case AUTO_DETECT -> getAllLibraryFiles(libraryEntity);
};
return filterByAllowedFormats(allFiles, libraryEntity.getAllowedFormats());
}
public List<LibraryFile> getAllLibraryFilesFlat(LibraryEntity libraryEntity) throws IOException {
List<LibraryFile> allFiles = new ArrayList<>();
for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
allFiles.addAll(findLibraryFilesFlat(pathEntity, libraryEntity));
}
return allFiles;
}
private List<LibraryFile> findLibraryFilesFlat(LibraryPathEntity pathEntity, LibraryEntity libraryEntity) throws IOException {
Path libraryPath = Path.of(pathEntity.getPath());
List<LibraryFile> libraryFiles = new ArrayList<>();
Map<Path, List<Path>> dirAudioFiles = new HashMap<>();
Files.walkFileTree(libraryPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<>() {
@Override
@NonNull
public FileVisitResult visitFile(@NonNull Path file, @NonNull BasicFileAttributes attrs) {
if (FileUtils.shouldIgnore(file) || !Files.isReadable(file) || !Files.isRegularFile(file) || attrs.size() == 0) {
return FileVisitResult.CONTINUE;
}
String fileName = file.getFileName().toString();
Optional<BookFileExtension> bookExtension = BookFileExtension.fromFileName(fileName);
if (bookExtension.isEmpty()) {
return FileVisitResult.CONTINUE;
}
if (bookExtension.get().getType() == BookFileType.AUDIOBOOK) {
dirAudioFiles.computeIfAbsent(file.getParent(), k -> new ArrayList<>()).add(file);
} else {
libraryFiles.add(LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(pathEntity)
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), file))
.fileName(fileName)
.bookFileType(bookExtension.get().getType())
.build());
}
return FileVisitResult.CONTINUE;
}
@Override
@NonNull
public FileVisitResult visitFileFailed(@NonNull Path file, IOException e) {
log.error("Failed read path [{}]: {}", file, e.getMessage(), e);
return FileVisitResult.CONTINUE;
}
@Override
@NonNull
public FileVisitResult preVisitDirectory(@NonNull Path dir, @NonNull BasicFileAttributes attrs) throws IOException {
if (FileUtils.shouldIgnore(dir) || !Files.isReadable(dir)) {
return FileVisitResult.SKIP_SUBTREE;
}
if (!dir.equals(libraryPath) && Files.exists(dir.resolve(".ignore"))) {
log.debug("Skipping directory with .ignore file: {}", dir);
return FileVisitResult.SKIP_SUBTREE;
}
return super.preVisitDirectory(dir, attrs);
}
});
// Collapse audio files: 2+ audio files in same directory become a single folder-based audiobook.
// A single audio file (e.g. standalone m4b) stays as an individual file entry.
// Audio files at the library root are always added individually (no folder to name the audiobook after).
for (var entry : dirAudioFiles.entrySet()) {
Path dir = entry.getKey();
List<Path> audioFiles = entry.getValue();
if (dir.equals(libraryPath) || audioFiles.size() < MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK) {
for (Path audioFile : audioFiles) {
libraryFiles.add(LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(pathEntity)
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), audioFile))
.fileName(audioFile.getFileName().toString())
.bookFileType(BookFileType.AUDIOBOOK)
.build());
}
} else {
libraryFiles.add(LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(pathEntity)
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), dir))
.fileName(dir.getFileName().toString())
.bookFileType(BookFileType.AUDIOBOOK)
.folderBased(true)
.build());
}
}
return libraryFiles;
}
List<LibraryFile> filterByAllowedFormats(List<LibraryFile> files, List<BookFileType> allowedFormats) {
@@ -67,7 +171,7 @@ public class LibraryFileHelper {
@Override
@NonNull
public FileVisitResult visitFile(@NonNull Path file, @NonNull BasicFileAttributes attrs) {
if (FileUtils.shouldIgnore(file) || !Files.isReadable(file) || !Files.isRegularFile(file)) {
if (FileUtils.shouldIgnore(file) || !Files.isReadable(file) || !Files.isRegularFile(file) || attrs.size() == 0) {
return FileVisitResult.CONTINUE;
}
@@ -182,7 +286,10 @@ public class LibraryFileHelper {
if (FileUtils.shouldIgnore(dir) || !Files.isReadable(dir)) {
return FileVisitResult.SKIP_SUBTREE;
}
if (!dir.equals(libraryPath) && Files.exists(dir.resolve(".ignore"))) {
log.debug("Skipping directory with .ignore file: {}", dir);
return FileVisitResult.SKIP_SUBTREE;
}
return super.preVisitDirectory(dir, attrs);
}
});
@@ -24,7 +24,7 @@ import org.booklore.repository.LibraryPathRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.repository.UserRepository;
import org.booklore.service.NotificationService;
import org.booklore.service.monitoring.MonitoringService;
import org.booklore.service.monitoring.LibraryWatchService;
import org.booklore.task.options.RescanLibraryContext;
import org.booklore.util.FileService;
import org.booklore.util.SecurityContextVirtualThread;
@@ -70,7 +70,7 @@ public class LibraryService {
private final LibraryMapper libraryMapper;
private final NotificationService notificationService;
private final FileService fileService;
private final MonitoringService monitoringService;
private final LibraryWatchService libraryWatchService;
private final AuthenticationService authenticationService;
private final UserRepository userRepository;
private final AuditService auditService;
@@ -79,7 +79,7 @@ public class LibraryService {
@EventListener(ApplicationReadyEvent.class)
public void initializeMonitoring() {
List<Library> libraries = libraryRepository.findAll().stream().map(libraryMapper::toLibrary).collect(Collectors.toList());
monitoringService.registerLibraries(libraries);
libraryWatchService.registerLibraries(libraries);
log.info("Monitoring initialized with {} libraries", libraries.size());
}
@@ -96,6 +96,9 @@ public class LibraryService {
if (request.getMetadataSource() != null) {
library.setMetadataSource(request.getMetadataSource());
}
if (request.getOrganizationMode() != null) {
library.setOrganizationMode(request.getOrganizationMode());
}
Set<String> currentPaths = library.getLibraryPaths().stream()
.map(LibraryPathEntity::getPath)
@@ -139,9 +142,9 @@ public class LibraryService {
LibraryEntity savedLibrary = libraryRepository.save(library);
if (request.isWatch()) {
monitoringService.registerLibraries(List.of(libraryMapper.toLibrary(savedLibrary)));
libraryWatchService.registerLibraries(List.of(libraryMapper.toLibrary(savedLibrary)));
} else {
monitoringService.unregisterLibrary(libraryId);
libraryWatchService.unregisterLibrary(libraryId);
}
if (!newPaths.isEmpty()) {
@@ -184,6 +187,7 @@ public class LibraryService {
.formatPriority(request.getFormatPriority())
.allowedFormats(request.getAllowedFormats())
.metadataSource(request.getMetadataSource())
.organizationMode(request.getOrganizationMode())
.users(List.of(user.get()))
.build();
@@ -193,7 +197,7 @@ public class LibraryService {
if (request.isWatch()) {
for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
Path path = Paths.get(pathEntity.getPath());
monitoringService.registerPath(path, libraryId);
libraryWatchService.registerPath(path, libraryId);
}
}
@@ -268,7 +272,7 @@ public class LibraryService {
public void deleteLibrary(long id) {
LibraryEntity library = libraryRepository.findById(id)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(id));
monitoringService.unregisterLibrary(id);
libraryWatchService.unregisterLibrary(id);
Set<Long> bookIds = library.getBookEntities().stream().map(BookEntity::getId).collect(Collectors.toSet());
fileService.deleteBookCovers(bookIds);
String libraryName = library.getName();
@@ -1,16 +0,0 @@
package org.booklore.service.monitoring;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;
import java.nio.file.Path;
@Getter
public class DirectoryCreateEvent extends ApplicationEvent {
private final Path newDirectory;
public DirectoryCreateEvent(Object source, Path newDirectory) {
super(source);
this.newDirectory = newDirectory;
}
}
@@ -1,22 +0,0 @@
package org.booklore.service.monitoring;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;
@Getter
public class FileChangeEvent extends ApplicationEvent {
private final Path filePath;
private final WatchEvent.Kind<?> eventKind;
private final Path watchedFolder;
public FileChangeEvent(Object source, Path filePath, WatchEvent.Kind<?> eventKind, Path watchedFolder) {
super(source);
this.filePath = filePath;
this.eventKind = eventKind;
this.watchedFolder = watchedFolder;
}
}
@@ -0,0 +1,288 @@
package org.booklore.service.monitoring;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.booklore.model.dto.Library;
import org.booklore.model.enums.BookFileExtension;
import org.booklore.service.watcher.LibraryFileEventProcessor;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Slf4j
@Service
public class LibraryWatchService {
private final LibraryFileEventProcessor eventProcessor;
private final WatchService watchService;
private final ExecutorService registrationExecutor;
private final ConcurrentHashMap<Path, WatchEntry> watches = new ConcurrentHashMap<>();
private final Map<Long, Boolean> libraryWatchStatus = new ConcurrentHashMap<>();
private record WatchEntry(WatchKey key, long libraryId) {}
public LibraryWatchService(LibraryFileEventProcessor eventProcessor) throws IOException {
this.eventProcessor = eventProcessor;
this.watchService = FileSystems.getDefault().newWatchService();
this.registrationExecutor = Executors.newSingleThreadExecutor(
Thread.ofVirtual().name("watch-registrar").factory());
}
@PostConstruct
public void start() {
Thread.ofVirtual().name("watch-poll").start(this::pollLoop);
}
private void pollLoop() {
try {
while (!Thread.currentThread().isInterrupted()) {
WatchKey key;
try {
key = watchService.take();
} catch (ClosedWatchServiceException e) {
log.warn("WatchService closed, stopping poll loop.");
break;
}
Path directory = (Path) key.watchable();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
handleOverflow(directory);
continue;
}
Path fileName = (Path) event.context();
Path fullPath = directory.resolve(fileName);
boolean isDir = kind == StandardWatchEventKinds.ENTRY_CREATE
? Files.isDirectory(fullPath)
: watches.containsKey(fullPath);
boolean isRelevantFile = !isDir && isRelevantBookFile(fullPath);
if (!isDir && !isRelevantFile) continue;
if (isDir && kind == StandardWatchEventKinds.ENTRY_CREATE) {
WatchEntry parentEntry = watches.get(directory);
if (parentEntry != null) {
registrationExecutor.submit(() -> registerRecursive(fullPath, parentEntry.libraryId()));
}
}
if (isDir && kind == StandardWatchEventKinds.ENTRY_DELETE) {
registrationExecutor.submit(() -> unregisterRecursive(fullPath));
}
WatchEntry entry = watches.get(directory);
if (entry != null) {
eventProcessor.processEvent(kind, entry.libraryId(), fullPath, isDir);
} else {
log.warn("No library ID found for watched directory: {}", directory);
}
}
boolean valid = key.reset();
if (!valid) {
log.warn("WatchKey no longer valid: {}", directory);
registrationExecutor.submit(() -> unregisterRecursive(directory));
}
}
} catch (InterruptedException e) {
log.warn("Poll loop interrupted");
Thread.currentThread().interrupt();
}
}
private void handleOverflow(Path directory) {
WatchEntry entry = watches.get(directory);
if (entry != null) {
log.warn("OVERFLOW for directory: {}. Queuing rescan for library {}.", directory, entry.libraryId());
eventProcessor.processEvent(StandardWatchEventKinds.ENTRY_CREATE, entry.libraryId(), directory, true);
} else {
log.warn("OVERFLOW event for untracked directory: {}", directory);
}
}
public void registerLibraries(List<Library> libraries) {
libraries.forEach(lib -> libraryWatchStatus.put(lib.getId(), lib.isWatch()));
libraries.stream().filter(Library::isWatch).forEach(this::registerLibrary);
log.info("Registered {} libraries for monitoring", libraries.size());
}
public void registerLibrary(Library library) {
libraryWatchStatus.put(library.getId(), library.isWatch());
if (!library.isWatch()) return;
int[] count = {0};
library.getPaths().forEach(libraryPath -> {
Path rootPath = Paths.get(libraryPath.getPath());
if (Files.isDirectory(rootPath)) {
try (Stream<Path> pathStream = Files.walk(rootPath)) {
pathStream.filter(Files::isDirectory).forEach(path -> {
if (registerPath(path, library.getId())) {
count[0]++;
}
});
} catch (IOException e) {
log.error("Failed to register paths for library '{}': {}", library.getName(), e.getMessage(), e);
}
}
});
log.info("Registered {} folders for library '{}'", count[0], library.getName());
}
public void unregisterLibrary(Long libraryId) {
Set<Path> pathsToRemove = watches.entrySet().stream()
.filter(e -> e.getValue().libraryId() == libraryId)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
for (Path path : pathsToRemove) {
unregisterPath(path);
}
libraryWatchStatus.put(libraryId, false);
log.debug("Unregistered library {} from monitoring", libraryId);
}
public synchronized boolean registerPath(Path path, long libraryId) {
if (!Files.exists(path)) {
log.warn("Cannot register path that does not exist: {}", path);
return false;
}
if (!Files.isDirectory(path)) {
log.warn("Cannot register path that is not a directory: {}", path);
return false;
}
try {
if (!watches.containsKey(path)) {
WatchKey key = path.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
watches.put(path, new WatchEntry(key, libraryId));
return true;
}
} catch (IOException e) {
log.error("Error registering path: {}", path, e);
}
return false;
}
public synchronized void unregisterPath(Path path) {
WatchEntry entry = watches.remove(path);
if (entry != null) {
entry.key().cancel();
log.debug("Unregistered path: {}", path);
}
}
private void registerRecursive(Path root, long libraryId) {
try (Stream<Path> stream = Files.walk(root)) {
stream.filter(Files::isDirectory)
.forEach(p -> registerPath(p, libraryId));
} catch (IOException e) {
log.warn("Failed to register paths under: {}", root, e);
}
}
private void unregisterRecursive(Path root) {
Set<Path> toRemove = watches.keySet().stream()
.filter(p -> p.startsWith(root))
.collect(Collectors.toSet());
for (Path path : toRemove) {
unregisterPath(path);
}
}
public void registerLibraryPaths(long libraryId, Path libraryRoot) {
if (!Files.exists(libraryRoot) || !Files.isDirectory(libraryRoot)) {
return;
}
try {
log.debug("Registering library paths for libraryId {} at {}", libraryId, libraryRoot);
registerPath(libraryRoot, libraryId);
try (var stream = Files.walk(libraryRoot)) {
stream.filter(Files::isDirectory)
.filter(path -> !path.equals(libraryRoot))
.forEach(path -> registerPath(path, libraryId));
}
} catch (Exception e) {
log.error("Failed to register library paths for libraryId {} at {}", libraryId, libraryRoot, e);
}
}
public boolean isRelevantBookFile(Path path) {
return BookFileExtension.fromFileName(path.getFileName().toString()).isPresent();
}
public boolean isPathMonitored(Path path) {
return watches.containsKey(path.toAbsolutePath().normalize());
}
public boolean isLibraryMonitored(long libraryId) {
return libraryWatchStatus.getOrDefault(libraryId, false);
}
public Set<Path> getPathsForLibraries(Set<Long> libraryIds) {
return watches.entrySet().stream()
.filter(e -> libraryIds.contains(e.getValue().libraryId()))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
public boolean waitForEventsDrained(Set<Long> libraryIds, long timeoutMs) {
if (libraryIds == null || libraryIds.isEmpty()) {
return true;
}
Set<Path> libraryPaths = getPathsForLibraries(libraryIds);
return waitForEventsDrainedByPaths(libraryPaths, timeoutMs);
}
public boolean waitForEventsDrainedByPaths(Set<Path> paths, long timeoutMs) {
if (paths == null || paths.isEmpty()) {
return true;
}
final long pollIntervalMs = 50;
long deadline = System.currentTimeMillis() + timeoutMs;
while (System.currentTimeMillis() < deadline) {
if (!eventProcessor.hasPendingEventsForPaths(paths)) {
log.debug("Events drained for {} paths", paths.size());
return true;
}
try {
Thread.sleep(pollIntervalMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
log.warn("Timeout waiting for events to drain for {} paths", paths.size());
return false;
}
@PreDestroy
public void shutdown() {
log.info("Shutting down LibraryWatchService...");
registrationExecutor.shutdownNow();
try {
watchService.close();
} catch (IOException e) {
log.error("Failed to close WatchService", e);
}
}
}
@@ -17,21 +17,21 @@ import java.util.Set;
@AllArgsConstructor
public class MonitoringRegistrationService {
private final MonitoringService monitoringService;
private final LibraryWatchService libraryWatchService;
public boolean isPathMonitored(Path path) {
return monitoringService.isPathMonitored(path);
return libraryWatchService.isPathMonitored(path);
}
public boolean isLibraryMonitored(Long libraryId) {
return monitoringService.isLibraryMonitored(libraryId);
return libraryWatchService.isLibraryMonitored(libraryId);
}
public void unregisterSpecificPath(Path path) {
if (!Files.exists(path)) {
log.debug("Path does not exist, attempting to unregister anyway: {}", path);
}
monitoringService.unregisterPath(path);
libraryWatchService.unregisterPath(path);
}
public void registerSpecificPath(Path path, Long libraryId) {
@@ -43,32 +43,19 @@ public class MonitoringRegistrationService {
log.warn("Cannot register path that is not a directory: {}", path);
return;
}
monitoringService.registerPath(path, libraryId);
libraryWatchService.registerPath(path, libraryId);
}
public void registerLibrary(Library library) {
monitoringService.registerLibrary(library);
libraryWatchService.registerLibrary(library);
}
public void unregisterLibrary(Long libraryId) {
monitoringService.unregisterLibrary(libraryId);
libraryWatchService.unregisterLibrary(libraryId);
}
public void registerLibraryPaths(Long libraryId, Path libraryRoot) {
if (!Files.exists(libraryRoot) || !Files.isDirectory(libraryRoot)) {
return;
}
try {
log.debug("Registering library paths for libraryId {} at {}", libraryId, libraryRoot);
monitoringService.registerPath(libraryRoot, libraryId);
try (var stream = Files.walk(libraryRoot)) {
stream.filter(Files::isDirectory)
.filter(path -> !path.equals(libraryRoot))
.forEach(path -> monitoringService.registerPath(path, libraryId));
}
} catch (Exception e) {
log.error("Failed to register library paths for libraryId {} at {}", libraryId, libraryRoot, e);
}
libraryWatchService.registerLibraryPaths(libraryId, libraryRoot);
}
public void registerLibraries(Map<Long, Path> libraries) {
@@ -89,17 +76,17 @@ public class MonitoringRegistrationService {
if (libraryIds == null || libraryIds.isEmpty()) {
return Set.of();
}
return monitoringService.getPathsForLibraries(new HashSet<>(libraryIds));
return libraryWatchService.getPathsForLibraries(new HashSet<>(libraryIds));
}
public boolean waitForEventsDrainedByPaths(Set<Path> paths, long timeoutMs) {
return monitoringService.waitForEventsDrainedByPaths(paths, timeoutMs);
return libraryWatchService.waitForEventsDrainedByPaths(paths, timeoutMs);
}
public boolean waitForEventsDrained(Collection<Long> libraryIds, long timeoutMs) {
if (libraryIds == null || libraryIds.isEmpty()) {
return true;
}
return monitoringService.waitForEventsDrained(new HashSet<>(libraryIds), timeoutMs);
return libraryWatchService.waitForEventsDrained(new HashSet<>(libraryIds), timeoutMs);
}
}
}
@@ -1,301 +0,0 @@
package org.booklore.service.monitoring;
import org.booklore.model.dto.Library;
import org.booklore.model.enums.BookFileExtension;
import org.booklore.service.watcher.LibraryFileEventProcessor;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Slf4j
@Service
public class MonitoringService {
private final LibraryFileEventProcessor libraryFileEventProcessor;
private final WatchService watchService;
private final MonitoringTask monitoringTask;
private final BlockingQueue<FileChangeEvent> eventQueue = new LinkedBlockingQueue<>();
private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
private final Set<Path> monitoredPaths = ConcurrentHashMap.newKeySet();
private final Map<Path, WatchKey> registeredWatchKeys = new ConcurrentHashMap<>();
private final Map<Path, Long> pathToLibraryIdMap = new ConcurrentHashMap<>();
private final Map<Long, Boolean> libraryWatchStatusMap = new ConcurrentHashMap<>();
public MonitoringService(LibraryFileEventProcessor libraryFileEventProcessor, WatchService watchService, MonitoringTask monitoringTask) {
this.libraryFileEventProcessor = libraryFileEventProcessor;
this.watchService = watchService;
this.monitoringTask = monitoringTask;
}
@PostConstruct
public void initializeMonitoring() {
monitoringTask.monitor();
startProcessingThread();
}
@PreDestroy
public void stopMonitoring() {
log.info("Shutting down monitoring service...");
singleThreadExecutor.shutdownNow();
try {
watchService.close();
} catch (IOException e) {
log.error("Failed to close WatchService", e);
}
}
public void registerLibraries(List<Library> libraries) {
libraries.forEach(lib -> libraryWatchStatusMap.put(lib.getId(), lib.isWatch()));
libraries.stream().filter(Library::isWatch).forEach(this::registerLibrary);
log.info("Registered {} libraries for recursive monitoring", libraries.size());
}
public void registerLibrary(Library library) {
libraryWatchStatusMap.put(library.getId(), library.isWatch());
if (!library.isWatch()) return;
int[] registeredCount = {0};
library.getPaths().forEach(libraryPath -> {
Path rootPath = Paths.get(libraryPath.getPath());
if (Files.isDirectory(rootPath)) {
try (Stream<Path> pathStream = Files.walk(rootPath)) {
pathStream.filter(Files::isDirectory).forEach(path -> {
if (registerPath(path, library.getId())) {
registeredCount[0]++;
}
});
} catch (IOException e) {
log.error("Failed to register paths for library '{}': {}", library.getName(), e.getMessage(), e);
}
}
});
log.info("Registered {} folders for library '{}'", registeredCount[0], library.getName());
}
public void unregisterLibrary(Long libraryId) {
Set<Path> pathsToRemove = pathToLibraryIdMap.entrySet().stream()
.filter(entry -> entry.getValue().equals(libraryId))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
for (Path path : pathsToRemove) {
unregisterPath(path);
}
libraryWatchStatusMap.put(libraryId, false);
log.debug("Unregistered library {} from monitoring", libraryId);
}
public synchronized boolean registerPath(Path path, Long libraryId) {
if (!Files.exists(path)) {
log.warn("Cannot register path that does not exist: {}", path);
return false;
}
if (!Files.isDirectory(path)) {
log.warn("Cannot register path that is not a directory: {}", path);
return false;
}
try {
if (monitoredPaths.add(path)) {
WatchKey key = path.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
registeredWatchKeys.put(path, key);
pathToLibraryIdMap.put(path, libraryId);
return true;
}
} catch (IOException e) {
log.error("Error registering path: {}", path, e);
}
return false;
}
public synchronized void unregisterPath(Path path) {
unregisterPath(path, true);
}
public synchronized void unregisterPath(Path path, boolean logUnregister) {
if (!Files.exists(path)) {
log.debug("Path does not exist, removing from monitoring if present: {}", path);
}
if (monitoredPaths.remove(path)) {
WatchKey key = registeredWatchKeys.remove(path);
if (key != null) key.cancel();
pathToLibraryIdMap.remove(path);
if (logUnregister) {
log.debug("Unregistered path: {}", path);
}
}
}
private void unregisterSubPaths(Path deletedPath) {
Set<Path> toRemove = monitoredPaths.stream()
.filter(p -> p.startsWith(deletedPath))
.collect(Collectors.toSet());
for (Path path : toRemove) {
unregisterPath(path);
}
}
@EventListener
public void handleFileChangeEvent(FileChangeEvent event) {
Path fullPath = event.getFilePath();
WatchEvent.Kind<?> kind = event.getEventKind();
if (kind != StandardWatchEventKinds.ENTRY_CREATE && kind != StandardWatchEventKinds.ENTRY_DELETE) return;
boolean isDir = kind == StandardWatchEventKinds.ENTRY_CREATE
? Files.isDirectory(fullPath)
: monitoredPaths.contains(fullPath);
boolean isRelevantFile = isRelevantBookFile(fullPath);
if (!(isDir || isRelevantFile)) return;
handleDirectoryEvents(event, fullPath, kind, isDir);
queueEvent(event, fullPath, kind);
}
@EventListener
public void handleWatchKeyInvalidation(WatchKeyInvalidatedEvent event) {
Path invalidPath = event.getInvalidPath();
if (monitoredPaths.remove(invalidPath)) {
log.warn("Removing invalid path from monitoring: {}", invalidPath);
pathToLibraryIdMap.remove(invalidPath);
WatchKey key = registeredWatchKeys.remove(invalidPath);
if (key != null) key.cancel();
}
}
private void startProcessingThread() {
log.info("Starting file change processor...");
singleThreadExecutor.submit(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
FileChangeEvent event = eventQueue.take();
processFileChangeEvent(event);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
} catch (Exception e) {
log.error("Error in processing thread", e);
}
}
});
}
private void processFileChangeEvent(FileChangeEvent event) {
Path filePath = event.getFilePath();
Path watchedFolder = event.getWatchedFolder();
Long libraryId = pathToLibraryIdMap.get(watchedFolder);
if (libraryId != null) {
try {
libraryFileEventProcessor.processFile(event.getEventKind(), libraryId, watchedFolder.toString(), filePath.toString());
} catch (InvalidDataAccessApiUsageException e) {
log.debug("InvalidDataAccessApiUsageException for libraryId={}", libraryId);
}
} else {
log.warn("No library ID found for folder: {}", watchedFolder);
}
}
private void handleDirectoryEvents(FileChangeEvent event, Path fullPath, WatchEvent.Kind<?> kind, boolean isDir) {
if (isDir && kind == StandardWatchEventKinds.ENTRY_CREATE) {
Long parentLibraryId = pathToLibraryIdMap.get(event.getWatchedFolder());
if (parentLibraryId != null) {
try (Stream<Path> stream = Files.walk(fullPath)) {
stream.filter(Files::isDirectory).forEach(path -> registerPath(path, parentLibraryId));
} catch (IOException e) {
log.warn("Failed to register nested paths: {}", fullPath, e);
}
}
}
if (isDir && kind == StandardWatchEventKinds.ENTRY_DELETE) {
unregisterSubPaths(fullPath);
}
}
private void queueEvent(FileChangeEvent event, Path fullPath, WatchEvent.Kind<?> kind) {
if (!eventQueue.offer(event)) {
log.warn("Event queue full, dropping: {}", fullPath);
} else {
log.debug("Queued: {} [{}]", fullPath, kind.name());
}
}
public boolean isRelevantBookFile(Path path) {
return BookFileExtension.fromFileName(path.getFileName().toString()).isPresent();
}
public boolean isPathMonitored(Path path) {
return monitoredPaths.contains(path.toAbsolutePath().normalize());
}
public boolean isLibraryMonitored(Long libraryId) {
return libraryWatchStatusMap.getOrDefault(libraryId, false);
}
public Set<Path> getPathsForLibraries(Set<Long> libraryIds) {
return pathToLibraryIdMap.entrySet().stream()
.filter(entry -> libraryIds.contains(entry.getValue()))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
public boolean waitForEventsDrained(Set<Long> libraryIds, long timeoutMs) {
if (libraryIds == null || libraryIds.isEmpty()) {
return true;
}
Set<Path> libraryPaths = getPathsForLibraries(libraryIds);
return waitForEventsDrainedByPaths(libraryPaths, timeoutMs);
}
public boolean waitForEventsDrainedByPaths(Set<Path> libraryPaths, long timeoutMs) {
if (libraryPaths == null || libraryPaths.isEmpty()) {
return true;
}
final long pollIntervalMs = 50;
long deadline = System.currentTimeMillis() + timeoutMs;
while (System.currentTimeMillis() < deadline) {
boolean hasPendingEvents = eventQueue.stream()
.anyMatch(event -> {
Path watchedFolder = event.getWatchedFolder();
return libraryPaths.stream().anyMatch(watchedFolder::startsWith);
});
if (!hasPendingEvents) {
log.debug("Event queue drained for paths: {}", libraryPaths.size());
return true;
}
try {
Thread.sleep(pollIntervalMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
log.warn("Timeout waiting for event queue to drain for {} paths", libraryPaths.size());
return false;
}
}
@@ -1,56 +0,0 @@
package org.booklore.service.monitoring;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.nio.file.*;
@Slf4j
@Service
@AllArgsConstructor
public class MonitoringTask {
private final WatchService watchService;
private final ApplicationEventPublisher eventPublisher;
@Async
public void monitor() {
try {
while (!Thread.currentThread().isInterrupted()) {
WatchKey key;
try {
key = watchService.take();
} catch (ClosedWatchServiceException e) {
log.warn("WatchService has been closed. Stopping monitoring.");
break;
}
if (key == null) continue;
Path directory = (Path) key.watchable();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) continue;
Path fileName = (Path) event.context();
Path fullPath = directory.resolve(fileName);
eventPublisher.publishEvent(new FileChangeEvent(this, fullPath, kind, directory));
}
boolean valid = key.reset();
if (!valid) {
log.warn("WatchKey is no longer valid: {}", directory);
// Clean up but DO NOT break
eventPublisher.publishEvent(new WatchKeyInvalidatedEvent(this, directory));
}
}
} catch (InterruptedException e) {
log.warn("Monitoring task interrupted", e);
Thread.currentThread().interrupt();
}
}
}
@@ -1,16 +0,0 @@
package org.booklore.service.monitoring;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;
import java.nio.file.Path;
@Getter
public class WatchKeyInvalidatedEvent extends ApplicationEvent {
private final Path invalidPath;
public WatchKeyInvalidatedEvent(Object source, Path invalidPath) {
super(source);
this.invalidPath = invalidPath;
}
}
@@ -6,6 +6,7 @@ import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.model.enums.PermissionType;
import org.booklore.model.websocket.Topic;
import org.booklore.repository.BookFileRepository;
import org.booklore.repository.BookRepository;
@@ -42,14 +43,24 @@ public class BookFilePersistenceService {
newLibraryPath = entityManager.merge(newLibraryPath);
String newSubPath = FileUtils.getRelativeSubPath(newLibraryPath.getPath(), path);
String newFileName = path.getFileName().toString();
var primaryFile = book.getPrimaryBookFile();
boolean pathChanged = !Objects.equals(newSubPath, primaryFile.getFileSubPath()) || !Objects.equals(newLibraryPath.getId(), book.getLibraryPath().getId());
BookFileEntity matchedFile = book.getBookFiles().stream()
.filter(bf -> currentHash.equals(bf.getCurrentHash()))
.findFirst()
.orElse(book.getPrimaryBookFile());
if (pathChanged || Boolean.TRUE.equals(book.getDeleted())) {
boolean changed = !Objects.equals(newSubPath, matchedFile.getFileSubPath())
|| !Objects.equals(newFileName, matchedFile.getFileName())
|| !Objects.equals(newLibraryPath.getId(), book.getLibraryPath().getId())
|| Boolean.TRUE.equals(book.getDeleted());
if (changed) {
book.setLibraryPath(newLibraryPath);
primaryFile.setFileSubPath(newSubPath);
matchedFile.setFileSubPath(newSubPath);
matchedFile.setFileName(newFileName);
book.setDeleted(Boolean.FALSE);
book.setDeletedAt(null);
bookRepository.save(book);
log.info("[FILE_CREATE] Updated path / undeleted existing book with hash '{}': '{}'", currentHash, path);
} else {
@@ -82,9 +93,7 @@ public class BookFilePersistenceService {
if (relativeFolderPath == null) {
throw new IllegalArgumentException("relativeFolderPath cannot be null");
}
String normalizedPrefix = relativeFolderPath.endsWith("/") ? relativeFolderPath : (relativeFolderPath + "/");
List<BookEntity> books = bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(libraryPathId, normalizedPrefix);
List<BookEntity> books = bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(libraryPathId, relativeFolderPath);
books.forEach(book -> {
book.setDeleted(true);
book.setDeletedAt(Instant.now());
@@ -125,4 +134,35 @@ public class BookFilePersistenceService {
public long countBookFilesByBookId(Long bookId) {
return bookFileRepository.countByBookId(bookId);
}
@Transactional
public void recoverFolderBook(PendingDeletionPool.BookSnapshot bookSnap, LibraryPathEntity newLibraryPath,
Path folderPath, Map<Path, String> fileHashes) {
BookEntity book = bookRepository.findById(bookSnap.bookId()).orElse(null);
if (book == null) return;
book.setLibraryPath(entityManager.merge(newLibraryPath));
book.setDeleted(false);
book.setDeletedAt(null);
for (PendingDeletionPool.FileSnapshot fs : bookSnap.files()) {
bookFileRepository.findById(fs.bookFileId()).ifPresent(bf -> {
for (var entry : fileHashes.entrySet()) {
if (entry.getValue().equals(fs.currentHash())) {
Path filePath = entry.getKey();
String newSubPath = FileUtils.getRelativeSubPath(newLibraryPath.getPath(), filePath);
bf.setFileSubPath(newSubPath);
bf.setFileName(filePath.getFileName().toString());
bf.setCurrentHash(entry.getValue());
break;
}
}
});
}
bookRepository.save(book);
notificationService.sendMessageToPermissions(Topic.BOOK_ADD,
bookMapper.toBookWithDescription(book, false), Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
log.info("[RECOVERED] Book id={} recovered from folder move", book.getId());
}
}
@@ -8,6 +8,7 @@ import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.model.enums.BookFileExtension;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.LibraryOrganizationMode;
import org.booklore.model.websocket.LogNotification;
import org.booklore.model.websocket.Topic;
import org.booklore.repository.BookAdditionalFileRepository;
@@ -25,6 +26,8 @@ import org.springframework.stereotype.Service;
import java.nio.file.Path;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@@ -45,6 +48,7 @@ public class BookFileTransactionalHandler {
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final PendingDeletionPool pendingDeletionPool;
@Transactional()
public void handleNewBookFile(long libraryId, Path path) {
@@ -59,8 +63,52 @@ public class BookFileTransactionalHandler {
LibraryPathEntity libraryPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(libraryEntity, libraryPath);
String fileSubPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), path);
Optional<BookFileEntity> existingAtPath = bookFilePersistenceService
.findBookFileByLibraryPathSubPathAndFileName(libraryPathEntity.getId(), fileSubPath, fileName);
if (existingAtPath.isPresent()) {
BookFileEntity existing = existingAtPath.get();
BookEntity existingBook = existing.getBook();
boolean wasDeleted = Boolean.TRUE.equals(existingBook.getDeleted());
String existingHash = existing.getCurrentHash();
String currentHash = FileFingerprint.generateHash(path);
if (wasDeleted) {
pendingDeletionPool.matchByHash(existingHash);
existingBook.setDeleted(false);
existingBook.setDeletedAt(null);
existing.setCurrentHash(currentHash);
bookFilePersistenceService.save(existingBook);
log.info("[CREATE] File '{}' restored deleted book id={}", filePath, existingBook.getId());
notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY));
return;
}
pendingDeletionPool.cancelByPath(path);
if (currentHash.equals(existingHash)) {
log.debug("[CREATE] File '{}' unchanged (same hash), skipping", filePath);
notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY));
return;
}
existing.setCurrentHash(currentHash);
bookFilePersistenceService.save(existingBook);
log.info("[CREATE] File '{}' content changed, updated hash", filePath);
notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY));
return;
}
String currentHash = FileFingerprint.generateHash(path);
Optional<BookEntity> existingByHash = bookRepository.findByCurrentHash(currentHash);
Optional<PendingDeletionPool.MatchResult> poolMatch = pendingDeletionPool.matchByHash(currentHash);
if (poolMatch.isPresent()) {
var match = poolMatch.get();
pendingDeletionPool.recoverBook(match, libraryPathEntity, fileSubPath, fileName, currentHash);
log.info("[CREATE] File '{}' matched pending deletion, recovered book id={}", filePath, match.book().bookId());
notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY));
return;
}
Optional<BookEntity> existingByHash = bookRepository.findByCurrentHashIncludingRecentlyDeleted(currentHash, Instant.now().minus(60, ChronoUnit.SECONDS));
if (existingByHash.isPresent()) {
bookFilePersistenceService.updatePathIfChanged(existingByHash.get(), libraryEntity, path, currentHash);
log.info("[CREATE] File '{}' recognized as moved file, updated existing book's path", filePath);
@@ -68,7 +116,13 @@ public class BookFileTransactionalHandler {
return;
}
BookEntity filelessMatch = findMatchingFilelessBook(libraryEntity, fileName, libraryPathEntity);
var mode = libraryEntity.getOrganizationMode() != null
? libraryEntity.getOrganizationMode() : LibraryOrganizationMode.AUTO_DETECT;
BookEntity filelessMatch = (mode == LibraryOrganizationMode.AUTO_DETECT)
? findMatchingFilelessBook(libraryEntity, fileName, libraryPathEntity)
: findExactFilelessBook(libraryEntity, fileName, libraryPathEntity);
if (filelessMatch != null) {
if (filelessMatch.getLibraryPath() == null) {
filelessMatch.setLibraryPath(libraryPathEntity);
@@ -80,7 +134,22 @@ public class BookFileTransactionalHandler {
return;
}
BookEntity matchingBook = findMatchingBook(libraryPathEntity.getId(), fileSubPath, fileName);
BookEntity matchingBook = null;
if (mode == LibraryOrganizationMode.BOOK_PER_FILE) {
// BOOK_PER_FILE: never attach to existing books
} else if (mode == LibraryOrganizationMode.BOOK_PER_FOLDER) {
matchingBook = findBookInSameFolder(libraryPathEntity.getId(), fileSubPath);
if (matchingBook == null) {
BookFileType fileType = BookFileExtension.fromFileName(fileName)
.map(BookFileExtension::getType).orElse(null);
if (fileType == BookFileType.AUDIOBOOK) {
matchingBook = findNearestAncestorBookWithEbook(libraryPathEntity.getId(), fileSubPath);
}
}
} else {
matchingBook = findMatchingBook(libraryPathEntity.getId(), fileSubPath, fileName);
}
if (matchingBook != null) {
autoAttachFile(matchingBook, fileName, fileSubPath, path);
@@ -117,6 +186,18 @@ public class BookFileTransactionalHandler {
LibraryPathEntity libraryPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(libraryEntity, libraryPath);
String fileSubPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), folderPath);
String folderHash = FileFingerprint.generateFolderHash(folderPath);
Optional<PendingDeletionPool.MatchResult> poolMatch = pendingDeletionPool.matchByHash(folderHash);
if (poolMatch.isPresent()) {
var match = poolMatch.get();
pendingDeletionPool.recoverBook(match, libraryPathEntity, fileSubPath, folderName, folderHash);
log.info("[CREATE] Folder audiobook '{}' matched pending deletion, recovered book id={}",
folderName, match.book().bookId());
notificationService.sendMessageToPermissions(Topic.LOG,
LogNotification.info("Finished processing folder audiobook: " + folderPath), Set.of(ADMIN, MANAGE_LIBRARY));
return;
}
BookEntity matchingBook = findMatchingBookForFolderAudiobook(libraryPathEntity.getId(), fileSubPath, folderName);
if (matchingBook != null) {
@@ -163,8 +244,79 @@ public class BookFileTransactionalHandler {
return null;
}
private BookEntity findExactFilelessBook(LibraryEntity library, String fileName, LibraryPathEntity fileLibraryPath) {
List<BookEntity> filelessBooks = bookRepository.findFilelessBooksByLibraryId(library.getId());
String fileBaseName = BookFileGroupingUtils.extractGroupingKey(fileName);
for (BookEntity book : filelessBooks) {
if (book.getLibraryPath() != null && !book.getLibraryPath().getId().equals(fileLibraryPath.getId())) {
continue;
}
if (book.getMetadata() != null && book.getMetadata().getTitle() != null) {
String bookTitle = BookFileGroupingUtils.extractGroupingKey(book.getMetadata().getTitle());
if (fileBaseName.equals(bookTitle)) {
return book;
}
}
}
return null;
}
private BookEntity findBookInSameFolder(Long libraryPathId, String fileSubPath) {
if (fileSubPath == null) {
return null;
}
List<BookEntity> booksInDirectory = bookRepository.findAllByLibraryPathIdAndFileSubPath(libraryPathId, fileSubPath);
List<BookEntity> activeBooks = booksInDirectory.stream()
.filter(book -> book.getDeleted() == null || !book.getDeleted())
.filter(BookEntity::hasFiles)
.toList();
if (activeBooks.isEmpty()) {
return null;
}
if (activeBooks.size() == 1) {
return activeBooks.getFirst();
}
return activeBooks.stream()
.max(Comparator.comparingLong(book -> book.getBookFiles() != null ? book.getBookFiles().size() : 0))
.orElse(null);
}
private BookEntity findNearestAncestorBookWithEbook(Long libraryPathId, String subPath) {
String current = subPath;
while (true) {
int lastSep = current.lastIndexOf('/');
if (lastSep == -1) {
lastSep = current.lastIndexOf('\\');
}
if (lastSep <= 0) {
break;
}
current = current.substring(0, lastSep);
List<BookEntity> booksAtLevel = bookRepository.findAllByLibraryPathIdAndFileSubPath(libraryPathId, current);
for (BookEntity book : booksAtLevel) {
if (book.getDeleted() != null && book.getDeleted()) {
continue;
}
if (book.getBookFiles() != null && book.getBookFiles().stream()
.anyMatch(bf -> bf.getBookType() != BookFileType.AUDIOBOOK)) {
log.debug("BOOK_PER_FOLDER: Audio absorption matched to ancestor book id={} at '{}'",
book.getId(), current);
return book;
}
}
}
return null;
}
private BookEntity findMatchingBook(Long libraryPathId, String fileSubPath, String fileName) {
if (fileSubPath == null || fileSubPath.isEmpty()) {
if (fileSubPath == null) {
return null;
}
@@ -1,14 +1,17 @@
package org.booklore.service.watcher;
import org.booklore.exception.ApiError;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.model.dto.settings.LibraryFile;
import org.booklore.model.enums.BookFileExtension;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.PermissionType;
import org.booklore.model.websocket.Topic;
import org.booklore.model.enums.LibraryOrganizationMode;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.NotificationService;
import org.booklore.service.file.FileFingerprint;
import org.booklore.service.library.LibraryProcessingService;
import org.booklore.util.FileUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
@@ -18,10 +21,10 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.*;
@Slf4j
@@ -30,14 +33,19 @@ import java.util.concurrent.*;
public class LibraryFileEventProcessor {
private static final long DEBOUNCE_MS = 500L;
private static final long FOLDER_CREATE_DEBOUNCE_MS = 2000L; // Longer debounce for folder creates to allow file copying
private static final long FOLDER_CREATE_DEBOUNCE_MS = 5000L;
private static final long PENDING_DELETION_GRACE_MS = 8000L;
private static final long STABILITY_CHECK_INTERVAL_MS = 3000L;
private static final long STABILITY_MAX_WAIT_MS = 120000L;
private static final int MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK = 2;
private final BlockingQueue<FileEvent> eventQueue = new LinkedBlockingQueue<>();
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final BookFileTransactionalHandler bookFileTransactionalHandler;
private final BookFilePersistenceService bookFilePersistenceService;
private final NotificationService notificationService;
private final LibraryProcessingService libraryProcessingService;
private final PendingDeletionPool pendingDeletionPool;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final ConcurrentMap<Path, ScheduledFuture<?>> pendingDeletes = new ConcurrentHashMap<>();
@@ -61,61 +69,65 @@ public class LibraryFileEventProcessor {
});
}
public void processFile(WatchEvent.Kind<?> eventKind, long libraryId, String libraryPath, String filePath) {
Path path = Paths.get(filePath).toAbsolutePath().normalize();
boolean isDirectory = Files.isDirectory(path);
public void processEvent(WatchEvent.Kind<?> eventKind, long libraryId, Path fullPath, boolean isDirectory) {
Path path = fullPath.toAbsolutePath().normalize();
if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {
// Schedule DELETE after debounce
ScheduledFuture<?> existing = pendingDeletes.put(path, scheduler.schedule(() -> {
eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath, false));
eventQueue.offer(new FileEvent(eventKind, libraryId, path, isDirectory));
pendingDeletes.remove(path);
}, DEBOUNCE_MS, TimeUnit.MILLISECONDS));
if (existing != null) existing.cancel(false);
} else if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) {
// If a DELETE is pending for this path, cancel both DELETE and CREATE
ScheduledFuture<?> pendingDelete = pendingDeletes.remove(path);
if (pendingDelete != null) {
pendingDelete.cancel(false);
log.debug("[DEBOUNCE] CREATE ignored because pending DELETE exists for '{}'", path);
return;
log.debug("[DEBOUNCE] CREATE after pending DELETE for '{}', treating as file modification", path);
}
if (isDirectory) {
// Debounce folder creates to allow files to be copied first
log.debug("[DEBOUNCE] Scheduling folder create for '{}' with {}ms delay", path, FOLDER_CREATE_DEBOUNCE_MS);
ScheduledFuture<?> existingFolder = pendingFolderCreates.put(path, scheduler.schedule(() -> {
eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath, true));
eventQueue.offer(new FileEvent(eventKind, libraryId, path, true));
pendingFolderCreates.remove(path);
// Clear tracked files for this folder after processing
filesFromPendingFolder.removeIf(f -> f.startsWith(path));
}, FOLDER_CREATE_DEBOUNCE_MS, TimeUnit.MILLISECONDS));
if (existingFolder != null) existingFolder.cancel(false);
} else {
// Check if this file is inside a pending folder
boolean insidePendingFolder = pendingFolderCreates.keySet().stream().anyMatch(path::startsWith);
if (insidePendingFolder) {
// Track this file but don't process it yet - the folder handler will decide
filesFromPendingFolder.add(path);
log.debug("[DEBOUNCE] File '{}' tracked as part of pending folder", path.getFileName());
} else {
// Process file immediately
eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath, false));
boolean insidePendingFolder = false;
for (var entry : pendingFolderCreates.entrySet()) {
if (path.startsWith(entry.getKey())) {
insidePendingFolder = true;
filesFromPendingFolder.add(path);
ScheduledFuture<?> oldTimer = entry.getValue();
if (oldTimer != null) oldTimer.cancel(false);
Path folderPath = entry.getKey();
pendingFolderCreates.put(folderPath, scheduler.schedule(() -> {
eventQueue.offer(new FileEvent(eventKind, libraryId, folderPath, true));
pendingFolderCreates.remove(folderPath);
filesFromPendingFolder.removeIf(f -> f.startsWith(folderPath));
}, FOLDER_CREATE_DEBOUNCE_MS, TimeUnit.MILLISECONDS));
log.debug("[DEBOUNCE] File '{}' tracked, reset folder debounce for '{}'", path.getFileName(), folderPath);
break;
}
}
if (!insidePendingFolder) {
scheduleWithStabilityCheck(path, () ->
eventQueue.offer(new FileEvent(eventKind, libraryId, path, false)));
}
}
} else {
// Other events
eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath, false));
eventQueue.offer(new FileEvent(eventKind, libraryId, path, false));
}
}
private void handleEvent(FileEvent event) {
Path path = Paths.get(event.filePath()).toAbsolutePath().normalize();
Path path = event.fullPath();
String fileName = path.getFileName().toString();
log.info("[PROCESS] '{}' event for '{}'{}", event.eventKind().name(), fileName,
event.isDebouncedFolder() ? " (debounced folder)" : "");
event.isDirectory() ? " (directory)" : "");
LibraryEntity library = libraryRepository.findById(event.libraryId())
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(event.libraryId()));
@@ -125,8 +137,7 @@ public class LibraryFileEventProcessor {
return;
}
// Use isDebouncedFolder flag for debounced events, otherwise fall back to heuristic
boolean isDirectory = event.isDebouncedFolder() || isFolder(path);
boolean isDirectory = event.isDirectory();
if (isDirectory) {
switch (event.eventKind().name()) {
@@ -150,6 +161,10 @@ public class LibraryFileEventProcessor {
}
private void handleFileCreate(LibraryEntity library, Path path) {
if (!fileHasContent(path)) {
log.debug("[SKIP] Zero-byte file: '{}'", path);
return;
}
log.info("[FILE_CREATE] '{}'", path);
bookFileTransactionalHandler.handleNewBookFile(library.getId(), path);
}
@@ -167,23 +182,12 @@ public class LibraryFileEventProcessor {
bookFilePersistenceService.findBookFileByLibraryPathSubPathAndFileName(libPathEntity.getId(), fileSubPath, fileName)
.ifPresentOrElse(bookFile -> {
var book = bookFile.getBook();
var remainingFiles = bookFilePersistenceService.countBookFilesByBookId(book.getId());
if (remainingFiles <= 1) {
// Last file - mark book as deleted
bookFilePersistenceService.markBookAsDeleted(book);
notificationService.sendMessageToPermissions(Topic.BOOKS_REMOVE, Set.of(book.getId()),
Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
log.info("[MARKED_DELETED] Book '{}' marked as deleted (last file removed)", fileName);
} else {
// Multiple files - just delete this file
bookFilePersistenceService.deleteBookFile(bookFile);
notificationService.sendMessageToPermissions(Topic.BOOK_UPDATE, Set.of(book.getId()),
Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
log.info("[FILE_REMOVED] BookFile '{}' removed from book (id={}), {} files remaining",
fileName, book.getId(), remainingFiles - 1);
}
}, () -> log.warn("[NOT_FOUND] BookFile for deleted path '{}' not found", path));
ScheduledFuture<?> timer = scheduler.schedule(
() -> pendingDeletionPool.expireFileDeletion(path),
PENDING_DELETION_GRACE_MS, TimeUnit.MILLISECONDS);
pendingDeletionPool.addFileDeletion(path, library.getId(), bookFile, book, timer);
log.info("[PENDING_DELETE] Book '{}' deferred deletion (grace period {}ms)", fileName, PENDING_DELETION_GRACE_MS);
}, () -> log.debug("[NOT_FOUND] BookFile for deleted path '{}' not found (likely renamed/moved)", path));
} catch (Exception e) {
log.warn("[ERROR] While handling file delete '{}': {}", path, e.getMessage());
@@ -193,7 +197,30 @@ public class LibraryFileEventProcessor {
private void handleFolderCreate(LibraryEntity library, Path folderPath) {
log.info("[FOLDER_CREATE] '{}'", folderPath);
// Check if folder is a folder-based audiobook (2+ audio files, no ebook files)
pendingFolderCreates.entrySet().removeIf(entry -> {
if (entry.getKey().startsWith(folderPath) && !entry.getKey().equals(folderPath)) {
entry.getValue().cancel(false);
filesFromPendingFolder.removeIf(f -> f.startsWith(entry.getKey()));
log.debug("[DEBOUNCE] Cancelled child folder debounce for '{}'", entry.getKey());
return true;
}
return false;
});
var mode = library.getOrganizationMode() != null
? library.getOrganizationMode() : LibraryOrganizationMode.AUTO_DETECT;
if (mode == LibraryOrganizationMode.BOOK_PER_FILE) {
processFilesInFolderIndividually(library, folderPath);
return;
}
if (mode == LibraryOrganizationMode.BOOK_PER_FOLDER) {
processFilesInFolderAsOneBook(library, folderPath);
return;
}
// AUTO_DETECT: existing audiobook folder detection logic
FolderAnalysis analysis = analyzeFolderForAudiobook(folderPath);
if (analysis.isFolderBasedAudiobook()) {
@@ -201,7 +228,6 @@ public class LibraryFileEventProcessor {
folderPath.getFileName(), analysis.audioFileCount());
try {
bookFileTransactionalHandler.handleNewFolderAudiobook(library.getId(), folderPath);
// Clear any tracked files inside this folder - they're now part of the folder audiobook
int cleared = 0;
var iterator = filesFromPendingFolder.iterator();
while (iterator.hasNext()) {
@@ -217,40 +243,184 @@ public class LibraryFileEventProcessor {
log.warn("[ERROR] Processing folder audiobook '{}': {}", folderPath, e.getMessage());
}
} else {
// Not a folder-based audiobook - process tracked files individually
var trackedFiles = filesFromPendingFolder.stream()
.filter(p -> p.startsWith(folderPath))
processTrackedAndWalkedFiles(library, folderPath);
}
}
private void processFilesInFolderIndividually(LibraryEntity library, Path folderPath) {
if (Files.exists(folderPath.resolve(".ignore"))) {
log.debug("[SKIP] Folder has .ignore file: '{}'", folderPath);
clearTrackedFilesFor(folderPath);
return;
}
clearTrackedFilesFor(folderPath);
try (var stream = Files.walk(folderPath)) {
stream.filter(Files::isRegularFile)
.filter(p -> !isUnderIgnoredDirectory(p, folderPath))
.filter(p -> isBookFile(p.getFileName().toString()))
.toList();
.filter(this::fileHasContent)
.forEach(p -> {
try {
bookFileTransactionalHandler.handleNewBookFile(library.getId(), p);
} catch (Exception e) {
log.warn("[ERROR] Processing file '{}': {}", p, e.getMessage());
}
});
} catch (IOException e) {
log.warn("[ERROR] Walking folder '{}': {}", folderPath, e.getMessage());
}
}
if (!trackedFiles.isEmpty()) {
log.info("[FOLDER_CREATE] Processing {} tracked files individually", trackedFiles.size());
for (Path filePath : trackedFiles) {
try {
bookFileTransactionalHandler.handleNewBookFile(library.getId(), filePath);
} catch (Exception e) {
log.warn("[ERROR] Processing tracked file '{}': {}", filePath, e.getMessage());
}
filesFromPendingFolder.remove(filePath);
}
}
private void processFilesInFolderAsOneBook(LibraryEntity library, Path folderPath) {
if (Files.exists(folderPath.resolve(".ignore"))) {
log.debug("[SKIP] Folder has .ignore file: '{}'", folderPath);
clearTrackedFilesFor(folderPath);
return;
}
clearTrackedFilesFor(folderPath);
// Also walk the folder for any files that weren't tracked (e.g., existing files)
try (var stream = Files.walk(folderPath)) {
stream.filter(Files::isRegularFile)
.filter(p -> isBookFile(p.getFileName().toString()))
.filter(p -> !trackedFiles.contains(p)) // Skip already processed tracked files
.forEach(p -> {
try {
bookFileTransactionalHandler.handleNewBookFile(library.getId(), p);
} catch (Exception e) {
log.warn("[ERROR] Processing file '{}': {}", p, e.getMessage());
}
});
} catch (IOException e) {
log.warn("[ERROR] Walking folder '{}': {}", folderPath, e.getMessage());
List<Path> bookFiles = new ArrayList<>();
try (var stream = Files.walk(folderPath)) {
stream.filter(Files::isRegularFile)
.filter(p -> !isUnderIgnoredDirectory(p, folderPath))
.filter(p -> isBookFile(p.getFileName().toString()))
.filter(this::fileHasContent)
.forEach(bookFiles::add);
} catch (IOException e) {
log.warn("[ERROR] Walking folder '{}': {}", folderPath, e.getMessage());
}
if (bookFiles.isEmpty()) {
return;
}
// Try folder-level pool matching first
Map<Path, String> fileHashes = new HashMap<>();
for (Path p : bookFiles) {
try {
fileHashes.put(p, FileFingerprint.generateHash(p));
} catch (Exception e) {
log.warn("[ERROR] Hash computation for '{}': {}", p, e.getMessage());
}
}
Optional<PendingDeletionPool.FolderMatchResult> folderMatch = pendingDeletionPool.matchFolderByHashes(fileHashes);
if (folderMatch.isPresent()) {
var match = folderMatch.get();
String matchedLibPath = bookFilePersistenceService.findMatchingLibraryPath(library, folderPath);
LibraryPathEntity matchedLibPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, matchedLibPath);
for (var bookEntry : match.pending().affectedBooks().entrySet()) {
var bookSnap = bookEntry.getValue();
bookFilePersistenceService.recoverFolderBook(bookSnap, matchedLibPathEntity, folderPath, fileHashes);
}
log.info("[FOLDER_CREATE] Folder '{}' matched pending deletion, recovered {} books",
folderPath, match.pending().affectedBooks().size());
return;
}
// Try hash-based move detection for each file
List<Path> unmatched = new ArrayList<>();
for (Path p : bookFiles) {
try {
String hash = fileHashes.get(p);
if (hash == null) {
unmatched.add(p);
continue;
}
Optional<PendingDeletionPool.MatchResult> poolMatch = pendingDeletionPool.matchByHash(hash);
if (poolMatch.isPresent()) {
var pmatch = poolMatch.get();
String libPath = bookFilePersistenceService.findMatchingLibraryPath(library, p);
LibraryPathEntity lpEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, libPath);
String subPath = FileUtils.getRelativeSubPath(lpEntity.getPath(), p);
pendingDeletionPool.recoverBook(pmatch, lpEntity, subPath, p.getFileName().toString(), hash);
log.info("[FOLDER_CREATE] File '{}' matched pending deletion, recovered book id={}", p, pmatch.book().bookId());
continue;
}
Optional<BookEntity> existing = bookRepository.findByCurrentHashIncludingRecentlyDeleted(
hash, Instant.now().minus(60, ChronoUnit.SECONDS));
if (existing.isPresent()) {
bookFilePersistenceService.updatePathIfChanged(existing.get(), library, p, hash);
log.info("[FOLDER_CREATE] File '{}' recognized as moved file, updated existing book's path", p);
} else {
unmatched.add(p);
}
} catch (Exception e) {
log.warn("[ERROR] Hash check for '{}': {}", p, e.getMessage());
unmatched.add(p);
}
}
if (unmatched.isEmpty()) {
return;
}
String libraryPath = bookFilePersistenceService.findMatchingLibraryPath(library, folderPath);
LibraryPathEntity libPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, libraryPath);
List<LibraryFile> libraryFiles = new ArrayList<>();
for (Path p : unmatched) {
String fileName = p.getFileName().toString();
var ext = BookFileExtension.fromFileName(fileName);
if (ext.isPresent()) {
libraryFiles.add(LibraryFile.builder()
.libraryEntity(library)
.libraryPathEntity(libPathEntity)
.fileSubPath(FileUtils.getRelativeSubPath(libPathEntity.getPath(), p))
.fileName(fileName)
.bookFileType(ext.get().getType())
.build());
}
}
if (!libraryFiles.isEmpty()) {
libraryProcessingService.processLibraryFiles(libraryFiles, library);
}
}
private void processTrackedAndWalkedFiles(LibraryEntity library, Path folderPath) {
var trackedFiles = filesFromPendingFolder.stream()
.filter(p -> p.startsWith(folderPath))
.filter(p -> !isUnderIgnoredDirectory(p, folderPath))
.filter(p -> isBookFile(p.getFileName().toString()))
.filter(this::fileHasContent)
.toList();
if (!trackedFiles.isEmpty()) {
log.info("[FOLDER_CREATE] Processing {} tracked files individually", trackedFiles.size());
for (Path filePath : trackedFiles) {
try {
bookFileTransactionalHandler.handleNewBookFile(library.getId(), filePath);
} catch (Exception e) {
log.warn("[ERROR] Processing tracked file '{}': {}", filePath, e.getMessage());
}
filesFromPendingFolder.remove(filePath);
}
}
try (var stream = Files.walk(folderPath)) {
stream.filter(Files::isRegularFile)
.filter(p -> !isUnderIgnoredDirectory(p, folderPath))
.filter(p -> isBookFile(p.getFileName().toString()))
.filter(this::fileHasContent)
.filter(p -> !trackedFiles.contains(p))
.forEach(p -> {
try {
bookFileTransactionalHandler.handleNewBookFile(library.getId(), p);
} catch (Exception e) {
log.warn("[ERROR] Processing file '{}': {}", p, e.getMessage());
}
});
} catch (IOException e) {
log.warn("[ERROR] Walking folder '{}': {}", folderPath, e.getMessage());
}
}
private void clearTrackedFilesFor(Path folderPath) {
filesFromPendingFolder.removeIf(p -> p.startsWith(folderPath));
}
private FolderAnalysis analyzeFolderForAudiobook(Path folderPath) {
@@ -258,7 +428,10 @@ public class LibraryFileEventProcessor {
boolean hasNonAudioBook = false;
try (var stream = Files.walk(folderPath)) {
var files = stream.filter(Files::isRegularFile).toList();
var files = stream.filter(Files::isRegularFile)
.filter(p -> !isUnderIgnoredDirectory(p, folderPath))
.filter(this::fileHasContent)
.toList();
for (Path file : files) {
String fileName = file.getFileName().toString();
@@ -293,28 +466,99 @@ public class LibraryFileEventProcessor {
String libPath = bookFilePersistenceService.findMatchingLibraryPath(library, folderPath);
LibraryPathEntity libPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, libPath);
String relativePrefix = FileUtils.getRelativeSubPath(libPathEntity.getPath(), folderPath);
int count = bookFilePersistenceService.markAllBooksUnderPathAsDeleted(libPathEntity.getId(), relativePrefix);
log.info("[MARKED_DELETED] {} books under '{}'", count, folderPath);
String relativePrefix = Path.of(libPathEntity.getPath()).relativize(folderPath).toString().replace("\\", "/");
List<BookEntity> booksWithFiles = bookRepository.findBooksWithFilesUnderPath(libPathEntity.getId(), relativePrefix);
if (booksWithFiles.isEmpty()) {
log.debug("[FOLDER_DELETE] No books found under '{}'", folderPath);
return;
}
ScheduledFuture<?> timer = scheduler.schedule(
() -> pendingDeletionPool.expireFolderDeletion(folderPath),
PENDING_DELETION_GRACE_MS, TimeUnit.MILLISECONDS);
pendingDeletionPool.addFolderDeletion(folderPath, library.getId(), booksWithFiles, timer);
log.info("[PENDING_DELETE] {} books under '{}' deferred deletion (grace period {}ms)",
booksWithFiles.size(), folderPath, PENDING_DELETION_GRACE_MS);
} catch (Exception e) {
log.warn("[ERROR] Folder delete '{}': {}", folderPath, e.getMessage());
}
}
private boolean isFolder(Path path) {
return !path.getFileName().toString().contains(".");
private boolean fileHasContent(Path path) {
try {
return Files.size(path) > 0;
} catch (IOException e) {
return false;
}
}
private boolean isUnderIgnoredDirectory(Path filePath, Path root) {
Path parent = filePath.getParent();
while (parent != null && !parent.equals(root)) {
if (Files.exists(parent.resolve(".ignore"))) {
return true;
}
parent = parent.getParent();
}
return false;
}
private boolean isBookFile(String fileName) {
return BookFileExtension.fromFileName(fileName).isPresent();
}
private void scheduleWithStabilityCheck(Path path, Runnable onStable) {
scheduler.schedule(() -> checkStability(path, onStable, System.currentTimeMillis()), 0, TimeUnit.MILLISECONDS);
}
private void checkStability(Path path, Runnable onStable, long startTime) {
try {
if (!Files.exists(path)) {
onStable.run();
return;
}
long elapsed = System.currentTimeMillis() - startTime;
if (elapsed >= STABILITY_MAX_WAIT_MS) {
log.warn("[STABILITY] Max wait exceeded for '{}', processing anyway", path);
onStable.run();
return;
}
FileTime mtime = Files.getLastModifiedTime(path);
long msSinceMod = System.currentTimeMillis() - mtime.toMillis();
if (msSinceMod < STABILITY_CHECK_INTERVAL_MS) {
log.debug("[STABILITY] File '{}' modified {}ms ago, rechecking in {}ms", path, msSinceMod, STABILITY_CHECK_INTERVAL_MS);
scheduler.schedule(() -> checkStability(path, onStable, startTime),
STABILITY_CHECK_INTERVAL_MS, TimeUnit.MILLISECONDS);
} else {
onStable.run();
}
} catch (IOException e) {
log.debug("[STABILITY] Error checking mtime for '{}': {}", path, e.getMessage());
onStable.run();
}
}
@PreDestroy
public void shutdown() {
scheduler.shutdownNow();
log.info("Shutting down LibraryFileEventProcessor...");
}
public record FileEvent(WatchEvent.Kind<?> eventKind, long libraryId, String libraryPath, String filePath, boolean isDebouncedFolder) {
public boolean hasPendingEventsForPaths(Set<Path> paths) {
boolean inQueue = eventQueue.stream()
.anyMatch(e -> paths.stream().anyMatch(p -> e.fullPath().startsWith(p)));
boolean inDeletes = pendingDeletes.keySet().stream()
.anyMatch(p -> paths.stream().anyMatch(p::startsWith));
boolean inFolderCreates = pendingFolderCreates.keySet().stream()
.anyMatch(p -> paths.stream().anyMatch(p::startsWith));
boolean inPool = pendingDeletionPool.hasPendingForPaths(paths);
return inQueue || inDeletes || inFolderCreates || inPool;
}
public record FileEvent(WatchEvent.Kind<?> eventKind, long libraryId, Path fullPath, boolean isDirectory) {
}
}
@@ -0,0 +1,305 @@
package org.booklore.service.watcher;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.mapper.BookMapper;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.PermissionType;
import org.booklore.model.websocket.Topic;
import org.booklore.repository.BookFileRepository;
import org.booklore.repository.BookRepository;
import org.booklore.service.NotificationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.nio.file.Path;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
@Slf4j
@Service
@AllArgsConstructor
public class PendingDeletionPool {
private final BookRepository bookRepository;
private final BookFileRepository bookFileRepository;
private final NotificationService notificationService;
private final BookMapper bookMapper;
private final ConcurrentHashMap<Path, PendingDeletion> pendingByPath = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Path> hashIndex = new ConcurrentHashMap<>();
public record FileSnapshot(Long bookFileId, String fileName, String fileSubPath,
String currentHash, boolean folderBased, BookFileType bookType) {}
public record BookSnapshot(Long bookId, Long libraryPathId, String fileSubPath,
List<FileSnapshot> files) {}
public record PendingDeletion(Path originalPath, boolean isDirectory, long libraryId,
Instant timestamp, ScheduledFuture<?> timer,
Map<String, Long> hashToBookFileId,
Map<Long, BookSnapshot> affectedBooks) {}
public record MatchResult(PendingDeletion pending, BookSnapshot book, FileSnapshot file) {}
public record FolderMatchResult(PendingDeletion pending, Map<String, FileSnapshot> hashToFile) {}
public void addFileDeletion(Path path, long libraryId, BookFileEntity bookFile, BookEntity book, ScheduledFuture<?> timer) {
FileSnapshot fileSnapshot = new FileSnapshot(
bookFile.getId(), bookFile.getFileName(), bookFile.getFileSubPath(),
bookFile.getCurrentHash(), bookFile.isFolderBased(), bookFile.getBookType());
BookSnapshot bookSnapshot = new BookSnapshot(
book.getId(), book.getLibraryPath() != null ? book.getLibraryPath().getId() : null,
bookFile.getFileSubPath(), List.of(fileSnapshot));
Map<String, Long> hashMap = new ConcurrentHashMap<>();
if (bookFile.getCurrentHash() != null) {
hashMap.put(bookFile.getCurrentHash(), bookFile.getId());
}
Map<Long, BookSnapshot> affectedBooks = new ConcurrentHashMap<>();
affectedBooks.put(book.getId(), bookSnapshot);
PendingDeletion pending = new PendingDeletion(path, false, libraryId, Instant.now(), timer, hashMap, affectedBooks);
pendingByPath.put(path, pending);
if (bookFile.getCurrentHash() != null) {
hashIndex.put(bookFile.getCurrentHash(), path);
}
log.debug("[POOL] Added file deletion: path='{}', hash='{}', bookId={}", path, bookFile.getCurrentHash(), book.getId());
}
public void addFolderDeletion(Path folderPath, long libraryId, List<BookEntity> booksWithFiles, ScheduledFuture<?> timer) {
Map<String, Long> hashMap = new ConcurrentHashMap<>();
Map<Long, BookSnapshot> affectedBooks = new ConcurrentHashMap<>();
for (BookEntity book : booksWithFiles) {
List<FileSnapshot> fileSnapshots = new ArrayList<>();
for (BookFileEntity bf : book.getBookFiles()) {
if (!bf.isBookFormat()) continue;
FileSnapshot fs = new FileSnapshot(
bf.getId(), bf.getFileName(), bf.getFileSubPath(),
bf.getCurrentHash(), bf.isFolderBased(), bf.getBookType());
fileSnapshots.add(fs);
if (bf.getCurrentHash() != null) {
hashMap.put(bf.getCurrentHash(), bf.getId());
hashIndex.put(bf.getCurrentHash(), folderPath);
}
}
if (!fileSnapshots.isEmpty()) {
BookSnapshot bs = new BookSnapshot(
book.getId(), book.getLibraryPath() != null ? book.getLibraryPath().getId() : null,
book.getBookFiles().getFirst().getFileSubPath(), fileSnapshots);
affectedBooks.put(book.getId(), bs);
}
}
PendingDeletion pending = new PendingDeletion(folderPath, true, libraryId, Instant.now(), timer, hashMap, affectedBooks);
pendingByPath.put(folderPath, pending);
log.debug("[POOL] Added folder deletion: path='{}', books={}, hashes={}", folderPath, affectedBooks.size(), hashMap.size());
}
public Optional<MatchResult> matchByHash(String hash) {
Path path = hashIndex.remove(hash);
if (path == null) return Optional.empty();
PendingDeletion pending = pendingByPath.get(path);
if (pending == null) return Optional.empty();
for (Map.Entry<Long, BookSnapshot> entry : pending.affectedBooks().entrySet()) {
BookSnapshot bookSnap = entry.getValue();
for (FileSnapshot fileSnap : bookSnap.files()) {
if (hash.equals(fileSnap.currentHash())) {
pending.hashToBookFileId().remove(hash);
boolean allConsumed = pending.hashToBookFileId().isEmpty();
if (allConsumed) {
pending.timer().cancel(false);
pendingByPath.remove(path);
log.debug("[POOL] All files matched for path='{}', cancelled timer", path);
}
return Optional.of(new MatchResult(pending, bookSnap, fileSnap));
}
}
}
return Optional.empty();
}
public Optional<FolderMatchResult> matchFolderByHashes(Map<Path, String> fileHashes) {
if (fileHashes.isEmpty()) return Optional.empty();
PendingDeletion bestMatch = null;
int bestOverlap = 0;
Map<String, FileSnapshot> bestFileMap = null;
for (PendingDeletion pending : pendingByPath.values()) {
if (!pending.isDirectory()) continue;
Map<String, FileSnapshot> matchedFiles = new HashMap<>();
int totalPendingFiles = 0;
for (BookSnapshot bookSnap : pending.affectedBooks().values()) {
for (FileSnapshot fileSnap : bookSnap.files()) {
totalPendingFiles++;
if (fileHashes.containsValue(fileSnap.currentHash())) {
matchedFiles.put(fileSnap.currentHash(), fileSnap);
}
}
}
if (totalPendingFiles > 0) {
double ratio = (double) matchedFiles.size() / totalPendingFiles;
if (ratio >= 0.5 && matchedFiles.size() > bestOverlap) {
bestOverlap = matchedFiles.size();
bestMatch = pending;
bestFileMap = matchedFiles;
}
}
}
if (bestMatch != null) {
bestMatch.timer().cancel(false);
for (String hash : bestMatch.hashToBookFileId().keySet()) {
hashIndex.remove(hash);
}
pendingByPath.remove(bestMatch.originalPath());
log.debug("[POOL] Folder matched by hashes: path='{}', overlap={}", bestMatch.originalPath(), bestOverlap);
return Optional.of(new FolderMatchResult(bestMatch, bestFileMap));
}
return Optional.empty();
}
@Transactional
public void expireFileDeletion(Path path) {
PendingDeletion pending = pendingByPath.remove(path);
if (pending == null) return;
for (String hash : pending.hashToBookFileId().keySet()) {
hashIndex.remove(hash);
}
for (BookSnapshot bookSnap : pending.affectedBooks().values()) {
Optional<BookEntity> bookOpt = bookRepository.findById(bookSnap.bookId());
if (bookOpt.isEmpty()) continue;
BookEntity book = bookOpt.get();
long remainingFiles = bookFileRepository.countByBookId(book.getId());
if (remainingFiles <= 1) {
book.setDeleted(true);
book.setDeletedAt(Instant.now());
bookRepository.save(book);
notificationService.sendMessageToPermissions(Topic.BOOKS_REMOVE, Set.of(book.getId()),
Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
log.info("[EXPIRED] Book id={} marked as deleted (last file removed)", book.getId());
} else {
for (FileSnapshot fs : bookSnap.files()) {
bookFileRepository.findById(fs.bookFileId()).ifPresent(bf -> {
bookFileRepository.delete(bf);
log.info("[EXPIRED] BookFile id={} removed from book id={}", fs.bookFileId(), book.getId());
});
}
notificationService.sendMessageToPermissions(Topic.BOOK_UPDATE, Set.of(book.getId()),
Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
}
}
}
@Transactional
public void expireFolderDeletion(Path path) {
PendingDeletion pending = pendingByPath.remove(path);
if (pending == null) return;
for (String hash : pending.hashToBookFileId().keySet()) {
hashIndex.remove(hash);
}
for (BookSnapshot bookSnap : pending.affectedBooks().values()) {
Optional<BookEntity> bookOpt = bookRepository.findById(bookSnap.bookId());
if (bookOpt.isEmpty()) continue;
BookEntity book = bookOpt.get();
book.setDeleted(true);
book.setDeletedAt(Instant.now());
bookRepository.save(book);
log.info("[EXPIRED] Book id={} marked as deleted (folder deletion expired)", book.getId());
}
Set<Long> bookIds = pending.affectedBooks().keySet();
if (!bookIds.isEmpty()) {
notificationService.sendMessageToPermissions(Topic.BOOKS_REMOVE, bookIds,
Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
}
}
@Transactional
public void recoverBook(MatchResult match, org.booklore.model.entity.LibraryPathEntity newLibraryPath, String newFileSubPath, String newFileName, String hash) {
BookEntity book = bookRepository.findById(match.book().bookId())
.orElseThrow(() -> new IllegalStateException("Book not found: " + match.book().bookId()));
BookFileEntity bookFile = bookFileRepository.findById(match.file().bookFileId())
.orElseThrow(() -> new IllegalStateException("BookFile not found: " + match.file().bookFileId()));
book.setLibraryPath(newLibraryPath);
book.setDeleted(false);
book.setDeletedAt(null);
bookFile.setFileSubPath(newFileSubPath);
bookFile.setFileName(newFileName);
bookFile.setCurrentHash(hash);
bookRepository.save(book);
notificationService.sendMessageToPermissions(Topic.BOOK_ADD,
bookMapper.toBookWithDescription(book, false), Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
log.info("[RECOVERED] Book id={} recovered from pending deletion pool", book.getId());
}
public boolean cancelByPath(Path filePath) {
PendingDeletion pending = pendingByPath.get(filePath);
if (pending != null && !pending.isDirectory()) {
pending.timer().cancel(false);
for (String hash : pending.hashToBookFileId().keySet()) {
hashIndex.remove(hash);
}
pendingByPath.remove(filePath);
log.debug("[POOL] Cancelled pending deletion by path='{}'", filePath);
return true;
}
for (var entry : pendingByPath.entrySet()) {
PendingDeletion pd = entry.getValue();
if (pd.isDirectory() && filePath.startsWith(entry.getKey())) {
for (BookSnapshot bookSnap : pd.affectedBooks().values()) {
for (FileSnapshot fileSnap : bookSnap.files()) {
String expectedFilePath = bookSnap.fileSubPath() + "/" + fileSnap.fileName();
String relPath = entry.getKey().getParent() != null
? entry.getKey().getParent().relativize(filePath).toString() : filePath.toString();
if (relPath.endsWith(fileSnap.fileName())) {
pd.hashToBookFileId().remove(fileSnap.currentHash());
hashIndex.remove(fileSnap.currentHash());
if (pd.hashToBookFileId().isEmpty()) {
pd.timer().cancel(false);
pendingByPath.remove(entry.getKey());
log.debug("[POOL] All files matched for path='{}', cancelled timer", entry.getKey());
}
return true;
}
}
}
}
}
return false;
}
public boolean hasPendingForPaths(Set<Path> paths) {
return pendingByPath.keySet().stream()
.anyMatch(p -> paths.stream().anyMatch(p::startsWith));
}
}
@@ -187,14 +187,37 @@ public class FileUtils {
"chapter", "track", "part", "disc", "disk", "cd", "side", "intro", "epilogue", "prologue", "outro"
);
private static final Set<String> SINGLE_FILE_AUDIOBOOK_EXTENSIONS = Set.of("m4b", "m4a");
/**
* Determines if a list of audio files represents a series folder (each file is a separate book)
* rather than a multi-file audiobook (chapter files for one book).
*
* Extracts a "base title" from each file by stripping numbering, part indicators, and extensions,
* then counts distinct non-generic titles. If more than one distinct title exists, it's a series folder.
* Uses two signals:
* 1. File format: .m4b/.m4a files are typically complete audiobooks, so a folder of them
* is likely a series. .mp3 files are typically chapters/tracks of one audiobook.
* 2. Title analysis (for .m4b/.m4a only): extracts base titles by stripping numbering and
* part indicators. If multiple distinct non-generic titles exist, it's a series.
*
* For .mp3 files (the vast majority of chapter-based audiobooks), this always returns false
* regardless of naming convention, avoiding the impossible task of distinguishing descriptive
* chapter names from book titles via pattern matching.
*/
public boolean isSeriesFolder(List<Path> audioFiles) {
if (audioFiles.size() < 2) {
return false;
}
boolean allSingleFileFormats = audioFiles.stream().allMatch(f -> {
String name = f.getFileName().toString().toLowerCase();
int dot = name.lastIndexOf('.');
return dot > 0 && SINGLE_FILE_AUDIOBOOK_EXTENSIONS.contains(name.substring(dot + 1));
});
if (!allSingleFileFormats) {
return false;
}
Set<String> distinctTitles = new HashSet<>();
for (Path file : audioFiles) {
String title = extractBaseTitle(file.getFileName().toString());
@@ -243,8 +266,14 @@ public class FileUtils {
".caltrash"
);
private final Set<String> tempExtensions = Set.of(
".part", ".tmp", ".crdownload", ".download",
".bak", ".old", ".temp", ".tempfile"
);
public boolean shouldIgnore(Path path) {
if (!path.getFileName().toString().isEmpty() && path.getFileName().toString().charAt(0) == '.') {
String fileName = path.getFileName().toString();
if (!fileName.isEmpty() && fileName.charAt(0) == '.') {
return true;
}
for (Path part : path) {
@@ -252,6 +281,12 @@ public class FileUtils {
return true;
}
}
String lowerName = fileName.toLowerCase();
for (String ext : tempExtensions) {
if (lowerName.endsWith(ext)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1 @@
ALTER TABLE library MODIFY COLUMN organization_mode VARCHAR(50) DEFAULT 'BOOK_PER_FILE';