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",
"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(
false,
false,
@@ -78,4 +86,4 @@ public enum TaskType {
this.name = name;
this.description = description;
}
}
}
@@ -34,5 +34,7 @@ public interface BookdropFileRepository extends JpaRepository<BookdropFileEntity
@Query("SELECT f.id FROM BookdropFileEntity f")
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.model.enums.BookFileExtension;
import org.booklore.repository.BookdropFileRepository;
import org.booklore.util.FileUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
@@ -10,6 +11,9 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
@Slf4j
@@ -18,6 +22,7 @@ public class BookdropMonitoringService {
private final AppProperties appProperties;
private final BookdropEventHandlerService eventHandler;
private final BookdropFileRepository bookdropFileRepository;
private Path bookdrop;
private WatchService watchService;
@@ -26,9 +31,14 @@ public class BookdropMonitoringService {
private WatchKey watchKey;
private volatile boolean paused;
public BookdropMonitoringService(AppProperties appProperties, BookdropEventHandlerService eventHandler) {
public BookdropMonitoringService(
AppProperties appProperties,
BookdropEventHandlerService eventHandler,
BookdropFileRepository bookdropFileRepository
) {
this.appProperties = appProperties;
this.eventHandler = eventHandler;
this.bookdropFileRepository = bookdropFileRepository;
}
@PostConstruct
@@ -180,21 +190,37 @@ public class BookdropMonitoringService {
}
public void rescanBookdropFolder() {
log.info("Manual rescan of Bookdrop folder triggered.");
log.info("Rescan of Bookdrop folder triggered.");
scanExistingBookdropFiles();
}
private void scanExistingBookdropFiles() {
List<Path> supportedFiles;
try (Stream<Path> files = Files.walk(bookdrop)) {
files.filter(Files::isRegularFile)
supportedFiles = files.filter(Files::isRegularFile)
.filter(path -> !FileUtils.shouldIgnore(path))
.filter(path -> BookFileExtension.fromFileName(path.getFileName().toString()).isPresent())
.forEach(file -> {
log.info("Found existing supported file on startup: {}", file);
eventHandler.enqueueFile(file, StandardWatchEventKinds.ENTRY_CREATE);
});
.toList();
} 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;
import org.booklore.config.AppProperties;
import org.booklore.repository.BookdropFileRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -9,6 +10,7 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.util.List;
import static org.mockito.Mockito.*;
@@ -16,6 +18,7 @@ class BookdropMonitoringServiceTest {
private AppProperties appProperties;
private BookdropEventHandlerService eventHandler;
private BookdropFileRepository bookdropFileRepository;
private BookdropMonitoringService monitoringService;
@TempDir
@@ -25,9 +28,10 @@ class BookdropMonitoringServiceTest {
void setUp() {
appProperties = mock(AppProperties.class);
eventHandler = mock(BookdropEventHandlerService.class);
bookdropFileRepository = mock(BookdropFileRepository.class);
when(appProperties.getBookdropFolder()).thenReturn(tempDir.toString());
monitoringService = new BookdropMonitoringService(appProperties, eventHandler);
monitoringService = new BookdropMonitoringService(appProperties, eventHandler, bookdropFileRepository);
}
@Test
@@ -49,6 +53,8 @@ class BookdropMonitoringServiceTest {
Path invalidFileInSubdir = subDir.resolve("._another.epub");
Files.createFile(invalidFileInSubdir);
when(bookdropFileRepository.findAllFilePathsIn(anyList())).thenReturn(List.of());
monitoringService.start();
monitoringService.stop();
@@ -60,4 +66,23 @@ class BookdropMonitoringServiceTest {
verify(eventHandler, never()).enqueueFile(eq(hiddenFile), 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();
}
}