feat(bookdrop): add ability to poll the bookdrop folder (#2768)

* feat(bookdrop): add ability to poll the bookdrop folder

* fix(bookdrop): Modify bookdrop scan behavior to only enqueue newly seen files to reduce duplicate log messages
This commit is contained in:
arjunsrinivasan1997
2026-02-17 20:19:42 -07:00
committed by GitHub
parent 05d0cc55f3
commit f4d1ba7aae
9 changed files with 218 additions and 17 deletions
@@ -35,6 +35,14 @@ public enum TaskType {
"Sync Library Files", "Sync Library Files",
"Scans your library folders to detect new books and removes entries for files that no longer exist." "Scans your library folders to detect new books and removes entries for files that no longer exist."
), ),
BOOKDROP_PERIODIC_SCANNING(
false,
false,
true,
false,
"Bookdrop Periodic Scanning",
"Scans the bookdrop ingest folder for newly added files and queues them for bookdrop processing."
),
CLEANUP_TEMP_METADATA( CLEANUP_TEMP_METADATA(
false, false,
false, false,
@@ -78,4 +86,4 @@ public enum TaskType {
this.name = name; this.name = name;
this.description = description; this.description = description;
} }
} }
@@ -34,5 +34,7 @@ public interface BookdropFileRepository extends JpaRepository<BookdropFileEntity
@Query("SELECT f.id FROM BookdropFileEntity f") @Query("SELECT f.id FROM BookdropFileEntity f")
List<Long> findAllIds(); List<Long> findAllIds();
}
@Query("SELECT f.filePath FROM BookdropFileEntity f WHERE f.filePath IN :filePaths")
List<String> findAllFilePathsIn(@Param("filePaths") List<String> filePaths);
}
@@ -2,6 +2,7 @@ package org.booklore.service.bookdrop;
import org.booklore.config.AppProperties; import org.booklore.config.AppProperties;
import org.booklore.model.enums.BookFileExtension; import org.booklore.model.enums.BookFileExtension;
import org.booklore.repository.BookdropFileRepository;
import org.booklore.util.FileUtils; import org.booklore.util.FileUtils;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
@@ -10,6 +11,9 @@ import org.springframework.stereotype.Service;
import java.io.IOException; import java.io.IOException;
import java.nio.file.*; import java.nio.file.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
@Slf4j @Slf4j
@@ -18,6 +22,7 @@ public class BookdropMonitoringService {
private final AppProperties appProperties; private final AppProperties appProperties;
private final BookdropEventHandlerService eventHandler; private final BookdropEventHandlerService eventHandler;
private final BookdropFileRepository bookdropFileRepository;
private Path bookdrop; private Path bookdrop;
private WatchService watchService; private WatchService watchService;
@@ -26,9 +31,14 @@ public class BookdropMonitoringService {
private WatchKey watchKey; private WatchKey watchKey;
private volatile boolean paused; private volatile boolean paused;
public BookdropMonitoringService(AppProperties appProperties, BookdropEventHandlerService eventHandler) { public BookdropMonitoringService(
AppProperties appProperties,
BookdropEventHandlerService eventHandler,
BookdropFileRepository bookdropFileRepository
) {
this.appProperties = appProperties; this.appProperties = appProperties;
this.eventHandler = eventHandler; this.eventHandler = eventHandler;
this.bookdropFileRepository = bookdropFileRepository;
} }
@PostConstruct @PostConstruct
@@ -180,21 +190,37 @@ public class BookdropMonitoringService {
} }
public void rescanBookdropFolder() { public void rescanBookdropFolder() {
log.info("Manual rescan of Bookdrop folder triggered."); log.info("Rescan of Bookdrop folder triggered.");
scanExistingBookdropFiles(); scanExistingBookdropFiles();
} }
private void scanExistingBookdropFiles() { private void scanExistingBookdropFiles() {
List<Path> supportedFiles;
try (Stream<Path> files = Files.walk(bookdrop)) { try (Stream<Path> files = Files.walk(bookdrop)) {
files.filter(Files::isRegularFile) supportedFiles = files.filter(Files::isRegularFile)
.filter(path -> !FileUtils.shouldIgnore(path)) .filter(path -> !FileUtils.shouldIgnore(path))
.filter(path -> BookFileExtension.fromFileName(path.getFileName().toString()).isPresent()) .filter(path -> BookFileExtension.fromFileName(path.getFileName().toString()).isPresent())
.forEach(file -> { .toList();
log.info("Found existing supported file on startup: {}", file);
eventHandler.enqueueFile(file, StandardWatchEventKinds.ENTRY_CREATE);
});
} catch (IOException e) { } catch (IOException e) {
log.error("Error scanning bookdrop folder on startup", e); log.error("Error scanning bookdrop folder", e);
return;
}
if (!supportedFiles.isEmpty()) {
List<String> supportedFilePaths = supportedFiles.stream()
.map(Path::toAbsolutePath)
.map(Path::toString)
.toList();
List<String> knownFilePaths = bookdropFileRepository.findAllFilePathsIn(supportedFilePaths);
Set<String> knownPaths = knownFilePaths == null ? Set.of() : new HashSet<>(knownFilePaths);
supportedFilePaths.stream()
.filter(path -> !knownPaths.contains(path))
.map(Path::of)
.forEach(path -> {
log.info("Found existing supported file: {}", path);
eventHandler.enqueueFile(path, StandardWatchEventKinds.ENTRY_CREATE);
});
} }
} }
} }
@@ -0,0 +1,58 @@
package org.booklore.task.tasks;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.request.TaskCreateRequest;
import org.booklore.model.dto.response.TaskCreateResponse;
import org.booklore.model.enums.TaskType;
import org.booklore.model.enums.UserPermission;
import org.booklore.service.bookdrop.BookdropMonitoringService;
import org.booklore.task.TaskStatus;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
@RequiredArgsConstructor
@Slf4j
public class BookdropPeriodicScanTask implements Task {
private final BookdropMonitoringService bookdropMonitoringService;
@Override
public void validatePermissions(BookLoreUser user, TaskCreateRequest request) {
if (!UserPermission.CAN_ACCESS_TASK_MANAGER.isGranted(user.getPermissions())) {
throw ApiError.PERMISSION_DENIED.createException(UserPermission.CAN_ACCESS_TASK_MANAGER);
}
}
@Override
public TaskCreateResponse execute(TaskCreateRequest request) {
TaskCreateResponse.TaskCreateResponseBuilder builder = TaskCreateResponse.builder()
.taskId(UUID.randomUUID().toString())
.taskType(getTaskType());
long startTime = System.currentTimeMillis();
log.info("{}: Task started", getTaskType());
try {
bookdropMonitoringService.rescanBookdropFolder();
builder.status(TaskStatus.COMPLETED);
} catch (Exception e) {
log.error("{}: Error scanning bookdrop ingest folder", getTaskType(), e);
builder.status(TaskStatus.FAILED);
}
long endTime = System.currentTimeMillis();
log.info("{}: Task completed. Duration: {} ms", getTaskType(), endTime - startTime);
return builder.build();
}
@Override
public TaskType getTaskType() {
return TaskType.BOOKDROP_PERIODIC_SCANNING;
}
}
@@ -0,0 +1,5 @@
INSERT INTO task_cron_configuration (task_type, cron_expression, enabled, created_by)
SELECT 'BOOKDROP_PERIODIC_SCANNING', '0 */10 * * * *', FALSE, -1
WHERE NOT EXISTS (
SELECT 1 FROM task_cron_configuration WHERE task_type = 'BOOKDROP_PERIODIC_SCANNING'
);
@@ -1,6 +1,7 @@
package org.booklore.service.bookdrop; package org.booklore.service.bookdrop;
import org.booklore.config.AppProperties; import org.booklore.config.AppProperties;
import org.booklore.repository.BookdropFileRepository;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
@@ -9,6 +10,7 @@ import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds; import java.nio.file.StandardWatchEventKinds;
import java.util.List;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@@ -16,6 +18,7 @@ class BookdropMonitoringServiceTest {
private AppProperties appProperties; private AppProperties appProperties;
private BookdropEventHandlerService eventHandler; private BookdropEventHandlerService eventHandler;
private BookdropFileRepository bookdropFileRepository;
private BookdropMonitoringService monitoringService; private BookdropMonitoringService monitoringService;
@TempDir @TempDir
@@ -25,9 +28,10 @@ class BookdropMonitoringServiceTest {
void setUp() { void setUp() {
appProperties = mock(AppProperties.class); appProperties = mock(AppProperties.class);
eventHandler = mock(BookdropEventHandlerService.class); eventHandler = mock(BookdropEventHandlerService.class);
bookdropFileRepository = mock(BookdropFileRepository.class);
when(appProperties.getBookdropFolder()).thenReturn(tempDir.toString()); when(appProperties.getBookdropFolder()).thenReturn(tempDir.toString());
monitoringService = new BookdropMonitoringService(appProperties, eventHandler); monitoringService = new BookdropMonitoringService(appProperties, eventHandler, bookdropFileRepository);
} }
@Test @Test
@@ -49,6 +53,8 @@ class BookdropMonitoringServiceTest {
Path invalidFileInSubdir = subDir.resolve("._another.epub"); Path invalidFileInSubdir = subDir.resolve("._another.epub");
Files.createFile(invalidFileInSubdir); Files.createFile(invalidFileInSubdir);
when(bookdropFileRepository.findAllFilePathsIn(anyList())).thenReturn(List.of());
monitoringService.start(); monitoringService.start();
monitoringService.stop(); monitoringService.stop();
@@ -60,4 +66,23 @@ class BookdropMonitoringServiceTest {
verify(eventHandler, never()).enqueueFile(eq(hiddenFile), any()); verify(eventHandler, never()).enqueueFile(eq(hiddenFile), any());
verify(eventHandler, never()).enqueueFile(eq(invalidFileInSubdir), any()); verify(eventHandler, never()).enqueueFile(eq(invalidFileInSubdir), any());
} }
@Test
void scanExistingBookdropFiles_ShouldSkipFilesAlreadyTrackedInDatabase() throws IOException {
Path alreadyTracked = tempDir.resolve("already-tracked.epub");
Files.createFile(alreadyTracked);
Path newFile = tempDir.resolve("new-file.epub");
Files.createFile(newFile);
when(bookdropFileRepository.findAllFilePathsIn(anyList()))
.thenReturn(List.of(alreadyTracked.toAbsolutePath().toString()));
monitoringService.start();
monitoringService.stop();
verify(eventHandler, never()).enqueueFile(eq(alreadyTracked), eq(StandardWatchEventKinds.ENTRY_CREATE));
verify(eventHandler).enqueueFile(eq(newFile), eq(StandardWatchEventKinds.ENTRY_CREATE));
}
} }
@@ -0,0 +1,74 @@
package org.booklore.task.tasks;
import org.booklore.exception.APIException;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.request.TaskCreateRequest;
import org.booklore.model.dto.response.TaskCreateResponse;
import org.booklore.model.enums.TaskType;
import org.booklore.service.bookdrop.BookdropMonitoringService;
import org.booklore.task.TaskStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
class BookdropPeriodicScanTaskTest {
@Mock
private BookdropMonitoringService bookdropMonitoringService;
@InjectMocks
private BookdropPeriodicScanTask task;
private BookLoreUser user;
private TaskCreateRequest request;
@BeforeEach
void setUp() {
user = BookLoreUser.builder()
.permissions(new BookLoreUser.UserPermissions())
.build();
request = new TaskCreateRequest();
}
@Test
void validatePermissions_shouldThrowException_whenUserCannotAccessTaskManager() {
user.getPermissions().setCanAccessTaskManager(false);
assertThrows(APIException.class, () -> task.validatePermissions(user, request));
}
@Test
void validatePermissions_shouldPass_whenUserCanAccessTaskManager() {
user.getPermissions().setCanAccessTaskManager(true);
assertDoesNotThrow(() -> task.validatePermissions(user, request));
}
@Test
void execute_shouldTriggerBookdropRescan() {
TaskCreateResponse response = task.execute(request);
assertEquals(TaskType.BOOKDROP_PERIODIC_SCANNING, response.getTaskType());
assertEquals(TaskStatus.COMPLETED, response.getStatus());
verify(bookdropMonitoringService).rescanBookdropFolder();
}
@Test
void execute_shouldReturnFailed_whenRescanThrows() {
doThrow(new RuntimeException("rescan failed")).when(bookdropMonitoringService).rescanBookdropFolder();
TaskCreateResponse response = task.execute(request);
assertEquals(TaskType.BOOKDROP_PERIODIC_SCANNING, response.getTaskType());
assertEquals(TaskStatus.FAILED, response.getStatus());
verify(bookdropMonitoringService).rescanBookdropFolder();
}
}
@@ -473,6 +473,7 @@ export class TaskManagementComponent implements OnInit, OnDestroy {
[TaskType.UPDATE_BOOK_RECOMMENDATIONS]: 'pi-sparkles', [TaskType.UPDATE_BOOK_RECOMMENDATIONS]: 'pi-sparkles',
[TaskType.CLEANUP_DELETED_BOOKS]: 'pi-trash', [TaskType.CLEANUP_DELETED_BOOKS]: 'pi-trash',
[TaskType.SYNC_LIBRARY_FILES]: 'pi-sync', [TaskType.SYNC_LIBRARY_FILES]: 'pi-sync',
[TaskType.BOOKDROP_PERIODIC_SCANNING]: 'pi-inbox',
[TaskType.CLEANUP_TEMP_METADATA]: 'pi-file' [TaskType.CLEANUP_TEMP_METADATA]: 'pi-file'
}; };
return icons[taskType] || 'pi-cog'; return icons[taskType] || 'pi-cog';
@@ -10,6 +10,7 @@ export enum TaskType {
UPDATE_BOOK_RECOMMENDATIONS = 'UPDATE_BOOK_RECOMMENDATIONS', UPDATE_BOOK_RECOMMENDATIONS = 'UPDATE_BOOK_RECOMMENDATIONS',
CLEANUP_DELETED_BOOKS = 'CLEANUP_DELETED_BOOKS', CLEANUP_DELETED_BOOKS = 'CLEANUP_DELETED_BOOKS',
SYNC_LIBRARY_FILES = 'SYNC_LIBRARY_FILES', SYNC_LIBRARY_FILES = 'SYNC_LIBRARY_FILES',
BOOKDROP_PERIODIC_SCANNING = 'BOOKDROP_PERIODIC_SCANNING',
CLEANUP_TEMP_METADATA = 'CLEANUP_TEMP_METADATA', CLEANUP_TEMP_METADATA = 'CLEANUP_TEMP_METADATA',
REFRESH_METADATA_MANUAL = 'REFRESH_METADATA_MANUAL' REFRESH_METADATA_MANUAL = 'REFRESH_METADATA_MANUAL'
} }
@@ -17,11 +18,12 @@ export enum TaskType {
export const TASK_TYPE_CONFIG: Record<TaskType, { parallel: boolean; async: boolean; displayOrder: number }> = { export const TASK_TYPE_CONFIG: Record<TaskType, { parallel: boolean; async: boolean; displayOrder: number }> = {
[TaskType.REFRESH_LIBRARY_METADATA]: {parallel: false, async: true, displayOrder: 1}, [TaskType.REFRESH_LIBRARY_METADATA]: {parallel: false, async: true, displayOrder: 1},
[TaskType.SYNC_LIBRARY_FILES]: {parallel: false, async: false, displayOrder: 2}, [TaskType.SYNC_LIBRARY_FILES]: {parallel: false, async: false, displayOrder: 2},
[TaskType.UPDATE_BOOK_RECOMMENDATIONS]: {parallel: false, async: true, displayOrder: 3}, [TaskType.BOOKDROP_PERIODIC_SCANNING]: {parallel: false, async: false, displayOrder: 3},
[TaskType.CLEANUP_DELETED_BOOKS]: {parallel: false, async: false, displayOrder: 4}, [TaskType.UPDATE_BOOK_RECOMMENDATIONS]: {parallel: false, async: true, displayOrder: 4},
[TaskType.CLEANUP_TEMP_METADATA]: {parallel: false, async: false, displayOrder: 5}, [TaskType.CLEANUP_DELETED_BOOKS]: {parallel: false, async: false, displayOrder: 5},
[TaskType.REFRESH_METADATA_MANUAL]: {parallel: false, async: false, displayOrder: 6}, [TaskType.CLEANUP_TEMP_METADATA]: {parallel: false, async: false, displayOrder: 6},
[TaskType.CLEAR_PDF_CACHE]: {parallel: false, async: false, displayOrder: 7}, [TaskType.REFRESH_METADATA_MANUAL]: {parallel: false, async: false, displayOrder: 7},
[TaskType.CLEAR_PDF_CACHE]: {parallel: false, async: false, displayOrder: 8},
}; };
export enum MetadataReplaceMode { export enum MetadataReplaceMode {