diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java index b949cad22..9049012e0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java @@ -26,6 +26,7 @@ import com.adityachandel.booklore.service.file.FileMovingHelper; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; import com.adityachandel.booklore.service.metadata.MetadataRefreshService; +import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; import com.adityachandel.booklore.util.FileUtils; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; @@ -44,9 +45,11 @@ import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.time.Instant; import java.util.Comparator; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; @@ -69,6 +72,7 @@ public class BookDropService { private final BookdropFileMapper mapper; private final ObjectMapper objectMapper; private final FileMovingHelper fileMovingHelper; + private final MonitoringRegistrationService monitoringRegistrationService; private static final int CHUNK_SIZE = 100; @@ -206,27 +210,86 @@ public class BookDropService { BookdropFinalizeResult results, AtomicInteger failedCount, AtomicInteger totalFilesProcessed) { - for (int i = 0; i < ids.size(); i += CHUNK_SIZE) { - int end = Math.min(i + CHUNK_SIZE, ids.size()); - List chunk = ids.subList(i, end); - log.info("Processing chunk {}/{} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) ids.size() / CHUNK_SIZE), chunk.size(), chunk); + // Collect all libraries that will be affected by moves + Set affectedLibraries = collectAffectedLibraries(ids, metadataById, defaultLibraryId, defaultPathId); - List chunkFiles = bookdropFileRepository.findAllById(chunk); - Map fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity())); + // Unregister monitoring for all affected libraries + unregisterAffectedLibraries(affectedLibraries); - for (Long id : chunk) { - BookdropFileEntity file = fileMap.get(id); - if (file == null) { - log.warn("File ID {} missing in DB during finalizeImport chunk processing", id); - failedCount.incrementAndGet(); + try { + for (int i = 0; i < ids.size(); i += CHUNK_SIZE) { + int end = Math.min(i + CHUNK_SIZE, ids.size()); + List chunk = ids.subList(i, end); + + log.info("Processing chunk {}/{} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) ids.size() / CHUNK_SIZE), chunk.size(), chunk); + + List chunkFiles = bookdropFileRepository.findAllById(chunk); + Map fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity())); + + for (Long id : chunk) { + BookdropFileEntity file = fileMap.get(id); + if (file == null) { + log.warn("File ID {} missing in DB during finalizeImport chunk processing", id); + failedCount.incrementAndGet(); + totalFilesProcessed.incrementAndGet(); + continue; + } + processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount); totalFilesProcessed.incrementAndGet(); - continue; } - processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount); - totalFilesProcessed.incrementAndGet(); + } + } finally { + // Re-register monitoring for all affected libraries + reregisterAffectedLibraries(affectedLibraries); + } + } + + private Set collectAffectedLibraries(List ids, + Map metadataById, + Long defaultLibraryId, + Long defaultPathId) { + Set affectedLibraries = new HashSet<>(); + + List files = bookdropFileRepository.findAllById(ids); + + for (BookdropFileEntity fileEntity : files) { + try { + FileProcessingContext context = prepareFileProcessingContext(fileEntity, metadataById.get(fileEntity.getId()), defaultLibraryId, defaultPathId); + affectedLibraries.add(context.libraryId()); + } catch (Exception e) { + log.warn("Failed to determine library for file {}: {}", fileEntity.getId(), e.getMessage()); } } + + log.info("Collected {} unique libraries for monitoring unregistration: {}", affectedLibraries.size(), affectedLibraries); + return affectedLibraries; + } + + private void unregisterAffectedLibraries(Set libraryIds) { + for (Long libraryId : libraryIds) { + monitoringRegistrationService.unregisterLibrary(libraryId); + log.debug("Unregistered library {} from monitoring", libraryId); + } + log.info("Unregistered {} libraries from monitoring", libraryIds.size()); + } + + private void reregisterAffectedLibraries(Set libraryIds) { + for (Long libraryId : libraryIds) { + try { + LibraryEntity library = libraryRepository.findById(libraryId).orElse(null); + if (library != null) { + for (LibraryPathEntity libPath : library.getLibraryPaths()) { + Path libraryRoot = Path.of(libPath.getPath()); + monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot); + log.debug("Re-registered library {} path {} for monitoring", libraryId, libraryRoot); + } + } + } catch (Exception e) { + log.warn("Failed to re-register library {} for monitoring: {}", libraryId, e.getMessage()); + } + } + log.info("Re-registered {} libraries for monitoring", libraryIds.size()); } private void updateFinalResults(BookdropFinalizeResult results, AtomicInteger totalFilesProcessed, AtomicInteger failedCount) { @@ -302,7 +365,7 @@ public class BookDropService { .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); LibraryPathEntity path = library.getLibraryPaths().stream() - .filter(p -> p.getId() == pathId) + .filter(p -> p.getId().equals(pathId)) .findFirst() .orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId)); @@ -328,8 +391,7 @@ public class BookDropService { return performFileMove(bookdropFile, source, target, library, path, metadata); } - private BookdropFileResult performFileMove(BookdropFileEntity bookdropFile, Path source, Path target, - LibraryEntity library, LibraryPathEntity path, BookMetadata metadata) { + private BookdropFileResult performFileMove(BookdropFileEntity bookdropFile, Path source, Path target, LibraryEntity library, LibraryPathEntity path, BookMetadata metadata) { Path tempPath = null; try { tempPath = Files.createTempFile("bookdrop-finalize-", bookdropFile.getFileName()); @@ -487,4 +549,5 @@ public class BookDropService { private record FileProcessingContext(Long libraryId, Long pathId, BookMetadata metadata) { } -} \ No newline at end of file +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookdropMonitoringService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookdropMonitoringService.java index 667203a24..a2f3450a3 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookdropMonitoringService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookdropMonitoringService.java @@ -49,8 +49,7 @@ public class BookdropMonitoringService { this.watchService = FileSystems.getDefault().newWatchService(); this.watchKey = bookdrop.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, - StandardWatchEventKinds.ENTRY_DELETE, - StandardWatchEventKinds.ENTRY_MODIFY); + StandardWatchEventKinds.ENTRY_DELETE); this.running = true; this.paused = false; this.watchThread = new Thread(this::processEvents, "BookdropFolderWatcher"); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/UnifiedFileMoveService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/UnifiedFileMoveService.java index a5b89234b..a3b602f28 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/UnifiedFileMoveService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/UnifiedFileMoveService.java @@ -39,33 +39,44 @@ public class UnifiedFileMoveService { } Path currentFilePath = bookEntity.getFullFilePath(); - if (!Files.exists(currentFilePath)) { - log.warn("File does not exist for book ID {}: {}. Skipping file move.", bookEntity.getId(), currentFilePath); - return; - } + Path expectedFilePath = fileMovingHelper.generateNewFilePath(bookEntity, pattern); // Check if current path differs from expected pattern - Path expectedFilePath = fileMovingHelper.generateNewFilePath(bookEntity, pattern); if (currentFilePath.equals(expectedFilePath)) { log.debug("File for book ID {} is already in the correct location according to library pattern. No move needed.", bookEntity.getId()); return; } - log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, expectedFilePath); + log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", + bookEntity.getId(), currentFilePath, expectedFilePath); - // For single file moves, use targeted path protection - monitoredFileOperationService.executeWithMonitoringSuspended(currentFilePath, expectedFilePath, bookEntity.getLibraryPath().getLibrary().getId(), () -> { - try { - boolean moved = fileMovingHelper.moveBookFileIfNeeded(bookEntity, pattern); - if (moved) { - log.info("Successfully moved file for book ID {} from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, bookEntity.getFullFilePath()); - } - return moved; - } catch (IOException e) { - log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e); - throw new RuntimeException("File move failed", e); - } - }); + Long libraryId = bookEntity.getLibraryPath().getLibrary().getId(); + Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()) + .toAbsolutePath().normalize(); + + // unregister the entire library to suppress all watch events during the move + monitoringRegistrationService.unregisterLibrary(libraryId); + + try { + monitoredFileOperationService.executeWithMonitoringSuspended( + currentFilePath, expectedFilePath, libraryId, () -> { + try { + boolean moved = fileMovingHelper.moveBookFileIfNeeded(bookEntity, pattern); + if (moved) { + log.info("Successfully moved file for book ID {} from {} to {}", + bookEntity.getId(), currentFilePath, bookEntity.getFullFilePath()); + } + return moved; + } catch (IOException e) { + log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e); + throw new RuntimeException("File move failed", e); + } + } + ); + } finally { + // re-register all folders under the library after the move + monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot); + } } /** @@ -178,7 +189,7 @@ public class UnifiedFileMoveService { */ public interface BatchMoveCallback { void onBookMoved(BookEntity book); + void onBookMoveFailed(BookEntity book, Exception error); } -} - +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/HardcoverParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/HardcoverParser.java index 9fb32fa5f..b313832ec 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/HardcoverParser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/HardcoverParser.java @@ -96,8 +96,17 @@ public class HardcoverParser implements BookParser { metadata.setCategories(doc.getGenres()); if (doc.getIsbns() != null) { - metadata.setIsbn10(doc.getIsbns().stream().filter(isbn -> isbn.length() == 10).findFirst().orElse(null)); - metadata.setIsbn13(doc.getIsbns().stream().filter(isbn -> isbn.length() == 13).findFirst().orElse(null)); + String inputIsbn = fetchMetadataRequest.getIsbn(); + if (inputIsbn != null && inputIsbn.length() == 10 && doc.getIsbns().contains(inputIsbn)) { + metadata.setIsbn10(inputIsbn); + } else { + metadata.setIsbn10(doc.getIsbns().stream().filter(isbn -> isbn.length() == 10).findFirst().orElse(null)); + } + if (inputIsbn != null && inputIsbn.length() == 13 && doc.getIsbns().contains(inputIsbn)) { + metadata.setIsbn13(inputIsbn); + } else { + metadata.setIsbn13(doc.getIsbns().stream().filter(isbn -> isbn.length() == 13).findFirst().orElse(null)); + } } metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/LibraryFileEventProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/LibraryFileEventProcessor.java index e05ba5624..7bbc41986 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/LibraryFileEventProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/LibraryFileEventProcessor.java @@ -72,7 +72,7 @@ public class LibraryFileEventProcessor { ScheduledFuture pendingDelete = pendingDeletes.remove(path); if (pendingDelete != null) { pendingDelete.cancel(false); - log.info("[DEBOUNCE] CREATE ignored because pending DELETE exists for '{}'", path); + log.debug("[DEBOUNCE] CREATE ignored because pending DELETE exists for '{}'", path); return; } // Otherwise process CREATE immediately diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/bookdrop/BookDropServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/bookdrop/BookDropServiceTest.java index afca34213..a742f7795 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/bookdrop/BookDropServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/bookdrop/BookDropServiceTest.java @@ -23,6 +23,7 @@ import com.adityachandel.booklore.service.file.FileMovingHelper; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; import com.adityachandel.booklore.service.metadata.MetadataRefreshService; +import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Ignore; import org.junit.jupiter.api.BeforeEach; @@ -57,6 +58,8 @@ class BookDropServiceTest { @Mock private BookdropFileRepository bookdropFileRepository; @Mock + private MonitoringRegistrationService monitoringRegistrationService; + @Mock private LibraryRepository libraryRepository; @Mock private BookRepository bookRepository; diff --git a/booklore-ui/src/app/book/components/epub-viewer/component/epub-viewer.component.scss b/booklore-ui/src/app/book/components/epub-viewer/component/epub-viewer.component.scss index 3145406c8..bd5f7f752 100644 --- a/booklore-ui/src/app/book/components/epub-viewer/component/epub-viewer.component.scss +++ b/booklore-ui/src/app/book/components/epub-viewer/component/epub-viewer.component.scss @@ -55,7 +55,6 @@ flex-direction: column; height: 100dvh; overflow: hidden; - background-color: #171717; } #epubContainer { @@ -165,8 +164,3 @@ ::ng-deep .p-divider.p-divider-horizontal { margin: 0.25rem 0 0.5rem 0 !important; } - -::ng-deep .p-drawer-left, -::ng-deep .p-drawer-right { - background-color: #171717 !important; -} diff --git a/booklore-ui/src/app/dashboard/components/main-dashboard/main-dashboard.component.ts b/booklore-ui/src/app/dashboard/components/main-dashboard/main-dashboard.component.ts index 9b6e4cbff..b9f26c98b 100644 --- a/booklore-ui/src/app/dashboard/components/main-dashboard/main-dashboard.component.ts +++ b/booklore-ui/src/app/dashboard/components/main-dashboard/main-dashboard.component.ts @@ -9,7 +9,7 @@ import {AsyncPipe} from '@angular/common'; import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component'; import {BookService} from '../../../book/service/book.service'; import {BookState} from '../../../book/model/state/book-state.model'; -import {Book} from '../../../book/model/book.model'; +import {Book, ReadStatus} from '../../../book/model/book.model'; import {UserService} from '../../../settings/user-management/user.service'; import {ProgressSpinner} from 'primeng/progressspinner'; @@ -47,7 +47,7 @@ export class MainDashboardComponent implements OnInit { this.lastReadBooks$ = this.bookService.bookState$.pipe( map((state: BookState) => ( - (state.books || []).filter(book => book.lastReadTime) + (state.books || []).filter(book => book.lastReadTime && (book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED)) .sort((a, b) => { const aTime = new Date(a.lastReadTime!).getTime(); const bTime = new Date(b.lastReadTime!).getTime();