diff --git a/booklore-api/src/main/java/org/booklore/model/enums/TaskType.java b/booklore-api/src/main/java/org/booklore/model/enums/TaskType.java index 9b8bbd70c..c4d5f6409 100644 --- a/booklore-api/src/main/java/org/booklore/model/enums/TaskType.java +++ b/booklore-api/src/main/java/org/booklore/model/enums/TaskType.java @@ -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; } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/org/booklore/repository/BookdropFileRepository.java b/booklore-api/src/main/java/org/booklore/repository/BookdropFileRepository.java index 0a666d02d..810b46fc2 100644 --- a/booklore-api/src/main/java/org/booklore/repository/BookdropFileRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/BookdropFileRepository.java @@ -34,5 +34,7 @@ public interface BookdropFileRepository extends JpaRepository findAllIds(); -} + @Query("SELECT f.filePath FROM BookdropFileEntity f WHERE f.filePath IN :filePaths") + List findAllFilePathsIn(@Param("filePaths") List filePaths); +} diff --git a/booklore-api/src/main/java/org/booklore/service/bookdrop/BookdropMonitoringService.java b/booklore-api/src/main/java/org/booklore/service/bookdrop/BookdropMonitoringService.java index 88da81d7c..c74fdc339 100644 --- a/booklore-api/src/main/java/org/booklore/service/bookdrop/BookdropMonitoringService.java +++ b/booklore-api/src/main/java/org/booklore/service/bookdrop/BookdropMonitoringService.java @@ -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 supportedFiles; try (Stream 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 supportedFilePaths = supportedFiles.stream() + .map(Path::toAbsolutePath) + .map(Path::toString) + .toList(); + List knownFilePaths = bookdropFileRepository.findAllFilePathsIn(supportedFilePaths); + Set 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); + }); } } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/org/booklore/task/tasks/BookdropPeriodicScanTask.java b/booklore-api/src/main/java/org/booklore/task/tasks/BookdropPeriodicScanTask.java new file mode 100644 index 000000000..9e3495387 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/task/tasks/BookdropPeriodicScanTask.java @@ -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; + } +} diff --git a/booklore-api/src/main/resources/db/migration/V122__Add_bookdrop_periodic_scanning_task_cron.sql b/booklore-api/src/main/resources/db/migration/V122__Add_bookdrop_periodic_scanning_task_cron.sql new file mode 100644 index 000000000..ae5c1d342 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V122__Add_bookdrop_periodic_scanning_task_cron.sql @@ -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' +); diff --git a/booklore-api/src/test/java/org/booklore/service/bookdrop/BookdropMonitoringServiceTest.java b/booklore-api/src/test/java/org/booklore/service/bookdrop/BookdropMonitoringServiceTest.java index ae2208f25..c1f509a54 100644 --- a/booklore-api/src/test/java/org/booklore/service/bookdrop/BookdropMonitoringServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/service/bookdrop/BookdropMonitoringServiceTest.java @@ -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)); + } } diff --git a/booklore-api/src/test/java/org/booklore/task/tasks/BookdropPeriodicScanTaskTest.java b/booklore-api/src/test/java/org/booklore/task/tasks/BookdropPeriodicScanTaskTest.java new file mode 100644 index 000000000..5572a7d9c --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/task/tasks/BookdropPeriodicScanTaskTest.java @@ -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(); + } +} diff --git a/booklore-ui/src/app/features/settings/task-management/task-management.component.ts b/booklore-ui/src/app/features/settings/task-management/task-management.component.ts index 4713ab745..75ee68bc5 100644 --- a/booklore-ui/src/app/features/settings/task-management/task-management.component.ts +++ b/booklore-ui/src/app/features/settings/task-management/task-management.component.ts @@ -473,6 +473,7 @@ export class TaskManagementComponent implements OnInit, OnDestroy { [TaskType.UPDATE_BOOK_RECOMMENDATIONS]: 'pi-sparkles', [TaskType.CLEANUP_DELETED_BOOKS]: 'pi-trash', [TaskType.SYNC_LIBRARY_FILES]: 'pi-sync', + [TaskType.BOOKDROP_PERIODIC_SCANNING]: 'pi-inbox', [TaskType.CLEANUP_TEMP_METADATA]: 'pi-file' }; return icons[taskType] || 'pi-cog'; diff --git a/booklore-ui/src/app/features/settings/task-management/task.service.ts b/booklore-ui/src/app/features/settings/task-management/task.service.ts index 216451c9b..55e91edb8 100644 --- a/booklore-ui/src/app/features/settings/task-management/task.service.ts +++ b/booklore-ui/src/app/features/settings/task-management/task.service.ts @@ -10,6 +10,7 @@ export enum TaskType { UPDATE_BOOK_RECOMMENDATIONS = 'UPDATE_BOOK_RECOMMENDATIONS', CLEANUP_DELETED_BOOKS = 'CLEANUP_DELETED_BOOKS', SYNC_LIBRARY_FILES = 'SYNC_LIBRARY_FILES', + BOOKDROP_PERIODIC_SCANNING = 'BOOKDROP_PERIODIC_SCANNING', CLEANUP_TEMP_METADATA = 'CLEANUP_TEMP_METADATA', REFRESH_METADATA_MANUAL = 'REFRESH_METADATA_MANUAL' } @@ -17,11 +18,12 @@ export enum TaskType { export const TASK_TYPE_CONFIG: Record = { [TaskType.REFRESH_LIBRARY_METADATA]: {parallel: false, async: true, displayOrder: 1}, [TaskType.SYNC_LIBRARY_FILES]: {parallel: false, async: false, displayOrder: 2}, - [TaskType.UPDATE_BOOK_RECOMMENDATIONS]: {parallel: false, async: true, displayOrder: 3}, - [TaskType.CLEANUP_DELETED_BOOKS]: {parallel: false, async: false, displayOrder: 4}, - [TaskType.CLEANUP_TEMP_METADATA]: {parallel: false, async: false, displayOrder: 5}, - [TaskType.REFRESH_METADATA_MANUAL]: {parallel: false, async: false, displayOrder: 6}, - [TaskType.CLEAR_PDF_CACHE]: {parallel: false, async: false, displayOrder: 7}, + [TaskType.BOOKDROP_PERIODIC_SCANNING]: {parallel: false, async: false, displayOrder: 3}, + [TaskType.UPDATE_BOOK_RECOMMENDATIONS]: {parallel: false, async: true, displayOrder: 4}, + [TaskType.CLEANUP_DELETED_BOOKS]: {parallel: false, async: false, displayOrder: 5}, + [TaskType.CLEANUP_TEMP_METADATA]: {parallel: false, async: false, displayOrder: 6}, + [TaskType.REFRESH_METADATA_MANUAL]: {parallel: false, async: false, displayOrder: 7}, + [TaskType.CLEAR_PDF_CACHE]: {parallel: false, async: false, displayOrder: 8}, }; export enum MetadataReplaceMode {