From 3f334202b6a6c9a6a7434bd140172f03a6ee346c Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Tue, 27 Jan 2026 10:12:50 -0700 Subject: [PATCH 001/191] Introduce multi-format book support, including audiobooks (#2486) * fix: support reading alternative book formats using bookType query param * feat: add streaming reader support for alternative EPUB formats * refactor: extract tabs section into MetadataTabsComponent * feat: implement per-file reading progress tracking * feat: add configurable format priority with cascading fallback * refactor: redesign library creator with single-page layout * refactor: unify reading progress into ReadingProgressService * refactor: improve delete options with clearer file format and book deletion * refactor: improve book format matching with normalization and fuzzy fallback * feat: add folder-based audiobook support with ZIP downloads and preparing state * fix: display unique format types in metadata viewer * refactor: auto-attach files to single book in folder during rescan * feat: implement folder-centric book file grouping with fuzzy matching * refactor: consolidate book grouping with organization mode support * fix: use folder hash for folder-based audiobooks in auto-attach * fix: delete only BookFileEntity on file removal, not entire book * fix: set folderBased flag and correct file size for auto-attached audiobook folders * fix: use count query to avoid lazy initialization in file delete handler * fix: preserve book metadata when file is moved by detecting hash match * fix: skip books with no files in restoration to avoid NPE * fix: round all progress percentages to one decimal place before sending to UI * style: improve library creator dialog spacing and layout * fix: migrate FOLDER_AS_BOOK to BOOK_PER_FOLDER for backwards compatibility * fix: FileMoveService now handles multi-file BookEntity properly * style: redesign metadata-picker and file-mover UI components * style: redesign file-naming-pattern UI and improve theme contrast * style: relax spacing in library-creator component * style: tighten directory-picker layout for consistency * fix: PathPatternResolver now respects folderBased flag for audiobooks * style: move checkmark column to left side and add pending status in file-mover * refactor: consolidate BookFileType into BookType and add audiobook styling * feat: show 'Continue Reading' button for in-progress books * fix: preserve dots in folder names during grouping and prevent duplicate attachments * style: reduce gap between download-all button and primary file section * style: shorten 'Continue Reading' button to 'Read' on mobile * feat: add DISK_TYPE config to disable file moves on network storage * style: standardize settings pages with shared styles and consistent spacing * style: revamp settings pages with modern card-based layouts * style: revamp OPDS, auth, and task management settings layouts * fix: update FileMoveService tests to include AppProperties parameter * fix: derive BookFileType from extension when uploading additional book files * feat: show format type and size in download button with dropdown for alternatives * feat: add audiobook streaming player with HTTP Range support * feat: add M4B chapter extraction and chapter navigation * feat: add audiobook bookmarks and sleep timer * refactor: split AudiobookReaderService into focused services * feat: add Media Session API for background audio playback * feat: display file extensions in format tags with distinct colors and add audiobook upload support * feat: require bookFileId for viewer settings API * fix: show split button for audiobooks with readable alternatives * feat: improve reading sessions table with book type badges and better formatting * feat: add audiobook play button in files tab * feat: use file extension for format display and meaningful tab values * feat: add extension field to BookFile DTO * feat: use extension field for book card format pill * fix: use mixed orientation for format priority drag-drop to support multi-line layout * feat: add attach book files feature to consolidate single-file books * fix: increase drag handle size for format priority chips * fix: add missing BookFileRepository mock to BookServiceDeleteTests * feat: add delete buttons to files tab and move shelf to other items menu * feat: add physical books support for cataloging books without digital files * refactor: redesign icon-picker component with improved styling * refactor: redesign metadata-picker component with improved layout and alignment * refactor: move Add Physical Book to top of library menu * refactor: use p-autoComplete for authors/categories in add-physical-book dialog * feat: add square cover search and display support for audiobooks * fix: navigate to first page when opening unread ebooks * fix: exclude API requests from service worker interception * feat: support fileless books with automatic file attachment * fix: bypass service worker for audiobook streaming requests * refactor: remove alphabetical filter sorting, default to count, limit filters to 100 --------- Co-authored-by: acx10 --- README.md | 3 + booklore-api/build.gradle | 3 + .../booklore/config/AppProperties.java | 8 + .../config/security/SecurityConfig.java | 15 + .../filter/AudiobookStreamingJwtFilter.java | 120 ++ .../controller/AudiobookReaderController.java | 100 ++ .../booklore/controller/BookController.java | 69 +- .../controller/BookMediaController.java | 11 +- .../controller/CbxReaderController.java | 17 +- .../controller/EpubReaderController.java | 19 +- .../booklore/controller/OpdsController.java | 12 +- .../controller/PdfReaderController.java | 17 +- .../convertor/FormatPriorityConverter.java | 46 + .../booklore/mapper/AdditionalFileMapper.java | 16 + .../booklore/mapper/BookMapper.java | 93 +- .../booklore/mapper/komga/KomgaMapper.java | 2 + .../booklore/mapper/v2/BookMapperV2.java | 90 +- .../booklore/model/dto/Book.java | 11 +- .../booklore/model/dto/BookFile.java | 4 + .../booklore/model/dto/BookMark.java | 4 +- .../booklore/model/dto/BookloreTelemetry.java | 1 - .../model/dto/CreateBookMarkRequest.java | 16 +- .../booklore/model/dto/Library.java | 6 +- .../model/dto/progress/AudiobookProgress.java | 16 + .../dto/request/AttachBookFileRequest.java | 15 + .../model/dto/request/BookFileProgress.java | 11 + .../model/dto/request/CoverFetchRequest.java | 1 + .../dto/request/CreateLibraryRequest.java | 4 +- .../request/CreatePhysicalBookRequest.java | 26 + .../dto/request/ReadProgressRequest.java | 12 +- .../dto/request/ReadingSessionRequest.java | 7 +- .../model/dto/response/AudiobookChapter.java | 18 + .../model/dto/response/AudiobookInfo.java | 28 + .../model/dto/response/AudiobookTrack.java | 19 + .../model/dto/settings/AppSettings.java | 1 + .../model/dto/settings/LibraryFile.java | 2 + .../booklore/model/entity/BookEntity.java | 31 +- .../booklore/model/entity/BookFileEntity.java | 42 +- .../booklore/model/entity/BookMarkEntity.java | 10 +- .../booklore/model/entity/LibraryEntity.java | 15 +- .../model/entity/ReadingSessionEntity.java | 13 +- .../entity/UserBookFileProgressEntity.java | 41 + .../model/entity/UserBookProgressEntity.java | 7 + .../model/enums/BookFileExtension.java | 9 +- .../booklore/model/enums/BookFileType.java | 3 +- .../model/enums/LibraryOrganizationMode.java | 34 + .../booklore/model/enums/LibraryScanMode.java | 6 - .../repository/BookFileRepository.java | 27 + .../repository/BookMarkRepository.java | 7 + .../booklore/repository/BookRepository.java | 13 + .../UserBookFileProgressRepository.java | 48 + .../service/FileStreamingService.java | 189 +++ .../service/ReadingSessionService.java | 1 + .../booklore/service/TelemetryService.java | 1 - .../appsettings/AppSettingService.java | 4 +- .../service/book/BookCreatorService.java | 25 +- .../service/book/BookDownloadService.java | 207 ++- .../book/BookFileAttachmentService.java | 400 ++++++ .../service/book/BookMarkService.java | 20 +- .../booklore/service/book/BookService.java | 110 +- .../service/book/BookUpdateService.java | 163 +-- .../service/book/PhysicalBookService.java | 138 ++ .../bookdrop/BookdropMetadataService.java | 3 +- .../service/event/BookEventBroadcaster.java | 2 +- .../service/file/AdditionalFileService.java | 65 +- .../service/file/FileFingerprint.java | 51 + .../booklore/service/file/FileMoveHelper.java | 9 +- .../service/file/FileMoveService.java | 150 +- .../fileprocessor/AbstractFileProcessor.java | 4 +- .../fileprocessor/AudiobookProcessor.java | 149 ++ .../kobo/KoboCompatibilityService.java | 7 +- .../service/kobo/KoboEntitlementService.java | 5 +- .../service/kobo/KoboReadingStateService.java | 51 +- .../service/koreader/KoreaderService.java | 46 +- .../service/library/BookGroupingService.java | 279 ++++ .../library/BookRestorationService.java | 1 + .../service/library/FileAsBookProcessor.java | 144 +- .../library/FolderAsBookFileProcessor.java | 255 ---- .../service/library/LibraryFileHelper.java | 113 +- .../service/library/LibraryFileProcessor.java | 22 - .../library/LibraryFileProcessorRegistry.java | 25 - .../library/LibraryProcessingService.java | 119 +- .../service/library/LibraryRescanHelper.java | 6 + .../service/library/LibraryService.java | 9 +- .../service/metadata/BookCoverService.java | 27 +- .../service/metadata/BookMetadataService.java | 5 +- .../service/metadata/BookMetadataUpdater.java | 12 +- .../metadata/DuckDuckGoCoverService.java | 45 +- .../metadata/MetadataRefreshService.java | 16 +- .../extractor/AudiobookMetadataExtractor.java | 162 +++ .../extractor/MetadataExtractorFactory.java | 4 + .../metadata/parser/AmazonBookParser.java | 4 +- .../metadata/parser/ComicvineBookParser.java | 4 +- .../metadata/parser/DoubanBookParser.java | 6 +- .../metadata/parser/GoodReadsParser.java | 4 +- .../service/metadata/parser/GoogleParser.java | 3 +- .../metadata/parser/RanobeDbParser.java | 4 +- .../migration/AppMigrationStartup.java | 2 + ...igrateProgressToFileProgressMigration.java | 161 +++ .../service/opds/OpdsFeedService.java | 74 +- .../progress/ReadingProgressService.java | 451 ++++++ .../reader/AudioFileUtilityService.java | 123 ++ .../service/reader/AudioMetadataService.java | 435 ++++++ .../reader/AudiobookReaderService.java | 120 ++ .../service/reader/CbxReaderService.java | 30 +- .../service/reader/EpubReaderService.java | 36 +- .../service/reader/PdfReaderService.java | 30 +- .../service/upload/FileUploadService.java | 62 +- .../service/user/UserProgressService.java | 22 - .../watcher/BookFilePersistenceService.java | 25 + .../watcher/BookFileTransactionalHandler.java | 274 +++- .../watcher/LibraryFileEventProcessor.java | 172 ++- .../booklore/util/BookFileGroupingUtils.java | 447 ++++++ .../booklore/util/BookProgressUtil.java | 58 - .../booklore/util/FileService.java | 14 +- .../booklore/util/FileUtils.java | 83 +- .../booklore/util/PathPatternResolver.java | 66 +- .../src/main/resources/application.yaml | 1 + .../V100__Create_user_book_file_progress.sql | 14 + ...default_book_format_to_format_priority.sql | 13 + ...V102__Add_is_folder_based_to_book_file.sql | 2 + ...V103__Add_organization_mode_to_library.sql | 19 + .../V104__Add_audiobook_bookmark_columns.sql | 6 + ..._Make_reading_session_columns_nullable.sql | 20 + .../V106__Add_physical_book_support.sql | 8 + .../booklore/BookServiceDeleteTests.java | 8 +- .../booklore/mapper/BookMapperTest.java | 2 +- .../BookOpdsRepositoryDataJpaTest.java | 2 - .../booklore/service/BookMarkServiceTest.java | 20 +- .../service/FileStreamingServiceTest.java | 409 ++++++ .../service/book/BookServiceTest.java | 24 +- .../service/book/BookUpdateServiceTest.java | 135 +- .../file/FileMoveServiceOrderingTest.java | 383 +++-- .../service/file/FileMoveServiceTest.java | 1257 +++++++++++++--- .../library/FileAsBookProcessorTest.java | 323 ++--- .../FolderAsBookFileProcessorExampleTest.java | 320 ----- .../FolderAsBookFileProcessorSimpleTest.java | 43 - .../FolderAsBookFileProcessorTest.java | 439 ------ .../library/LibraryFileHelperTest.java | 16 +- ...ibraryProcessingServiceRegressionTest.java | 42 +- .../library/LibraryProcessingServiceTest.java | 123 +- .../opds/OpdsFeedServiceMimeTypeTest.java | 28 +- .../service/opds/OpdsFeedServiceTest.java | 13 +- .../progress/ReadingProgressServiceTest.java | 309 ++++ .../reader/AudioFileUtilityServiceTest.java | 309 ++++ .../reader/AudioMetadataServiceTest.java | 556 ++++++++ .../reader/AudiobookReaderServiceTest.java | 423 ++++++ .../util/BookFileGroupingUtilsTest.java | 684 +++++++++ .../util/builder/LibraryTestBuilder.java | 3 +- booklore-ui/ngsw-config.json | 16 + booklore-ui/src/app/app.routes.ts | 6 + booklore-ui/src/app/app.spec.ts | 7 + .../authentication-settings.component.html | 443 +++--- .../authentication-settings.component.scss | 445 +++--- .../add-physical-book-dialog.component.html | 238 ++++ .../add-physical-book-dialog.component.scss | 154 ++ .../add-physical-book-dialog.component.ts | 168 +++ .../book-browser/book-browser.component.html | 13 +- .../book-browser/book-browser.component.ts | 56 + .../book-card/book-card.component.html | 11 +- .../book-card/book-card.component.scss | 49 +- .../book-card/book-card.component.ts | 39 +- .../book-dialog-helper.service.ts | 32 + .../book-filter/book-filter.component.html | 4 +- .../book-filter/book-filter.component.ts | 10 +- .../cover-scale-preference.service.spec.ts | 143 -- .../book-browser/filters/HeaderFilter.spec.ts | 167 --- .../filters/SeriesCollapseFilter.spec.ts | 244 ---- .../filters/SidebarFilter.spec.ts | 629 -------- .../book-browser/filters/SidebarFilter.ts | 2 +- ...sidebar-filter-toggle-pref.service.spec.ts | 119 -- .../book-browser/sorting/BookSorter.spec.ts | 99 -- .../table-column-preference.service.spec.ts | 140 -- .../book-file-attacher.component.html | 116 ++ .../book-file-attacher.component.scss | 180 +++ .../book-file-attacher.component.ts | 148 ++ .../series-page/series-page.component.html | 2 +- .../series-page/series-page.component.ts | 2 + .../src/app/features/book/model/book.model.ts | 45 +- .../app/features/book/model/library.model.ts | 7 +- .../book/service/book-menu.service.spec.ts | 478 ------- .../service/book-navigation.service.spec.ts | 106 -- .../book/service/book-patch.service.spec.ts | 171 --- .../book/service/book-patch.service.ts | 58 +- .../book/service/book.service.spec.ts | 511 ------- .../app/features/book/service/book.service.ts | 189 ++- .../book/service/cbx-reader.service.spec.ts | 96 -- .../book/service/cbx-reader.service.ts | 24 +- .../library-shelf-menu.service.spec.ts | 350 ----- .../service/library-shelf-menu.service.ts | 12 + .../book/service/library.service.spec.ts | 167 --- .../book/service/metadata-task.spec.ts | 123 -- .../service/new-pdf-reader.service.spec.ts | 70 - .../book/service/new-pdf-reader.service.ts | 24 +- .../book/service/shelf.service.spec.ts | 131 -- .../book/service/sort.service.spec.ts | 153 -- .../library-creator.component.html | 532 +++---- .../library-creator.component.scss | 1261 +++++++---------- .../library-creator.component.ts | 75 +- .../book-reading-sessions.component.html | 29 +- .../book-reading-sessions.component.scss | 97 ++ .../book-reading-sessions.component.ts | 69 +- .../metadata-picker.component.html | 769 +++++----- .../metadata-picker.component.scss | 626 +++++--- .../metadata-picker.component.ts | 5 +- .../metadata-tabs.component.html | 310 ++++ .../metadata-tabs.component.scss | 216 +++ .../metadata-tabs/metadata-tabs.component.ts | 164 +++ .../metadata-viewer.component.html | 192 +-- .../metadata-viewer.component.scss | 85 +- .../metadata-viewer.component.ts | 477 +++++-- .../cover-search/cover-search.component.ts | 6 +- .../audiobook-reader.component.html | 399 ++++++ .../audiobook-reader.component.scss | 805 +++++++++++ .../audiobook-reader.component.ts | 966 +++++++++++++ .../audiobook-reader/audiobook.model.ts | 39 + .../audiobook-reader/audiobook.service.ts | 64 + .../readers/audiobook-reader/index.ts | 3 + .../cbx-reader/cbx-reader.component.ts | 48 +- .../layout/sidebar/cbx-sidebar.component.html | 2 +- .../layout/sidebar/cbx-sidebar.service.ts | 10 +- .../core/epub-streaming.service.ts | 5 +- .../ebook-reader/core/view-manager.service.ts | 10 +- .../ebook-reader/ebook-reader.component.ts | 48 +- .../layout/sidebar/sidebar.component.html | 2 +- .../ebook-reader/state/progress.service.ts | 6 +- .../state/reader-state.service.ts | 4 +- .../pdf-reader/pdf-reader.component.ts | 28 +- .../custom-fonts/custom-fonts.component.scss | 12 +- .../hardcover-settings-component.html | 2 +- .../hardcover-settings-component.scss | 66 +- .../hardcover-sync-settings.service.spec.ts | 107 -- .../kobo-sync-settings-component.html | 2 +- .../kobo-sync-settings-component.scss | 66 +- .../kobo-sync-settings/kobo.service.spec.ts | 203 --- .../koreader-settings-component.html | 2 +- .../koreader-settings-component.scss | 89 +- .../koreader.service.spec.ts | 195 --- .../device-settings-component.html | 20 +- .../device-settings-component.scss | 24 +- .../device-settings-component.ts | 4 +- .../email-v2-provider.component.html | 410 +++--- .../email-v2-provider.component.scss | 391 ++--- .../email-v2-provider.component.ts | 3 +- .../email-v2-provider.service.spec.ts | 271 ---- .../email-v2-recipient.component.html | 210 ++- .../email-v2-recipient.component.scss | 323 +++-- .../email-v2-recipient.component.ts | 3 +- .../email-v2-recipient.service.spec.ts | 230 --- .../settings/email-v2/email-v2.component.html | 12 +- .../settings/email-v2/email-v2.component.scss | 67 +- .../settings/email-v2/email-v2.component.ts | 4 +- .../settings/email-v2/email.service.spec.ts | 115 -- .../file-naming-pattern.component.html | 480 ++++--- .../file-naming-pattern.component.scss | 687 ++++----- .../file-naming-pattern.component.ts | 7 +- .../global-preferences.component.html | 2 +- .../global-preferences.component.scss | 70 +- .../metadata-provider-settings.component.scss | 81 +- .../library-metadata-settings.component.html | 2 +- .../library-metadata-settings.component.scss | 76 +- ...tadata-persistence-settings-component.html | 20 +- ...tadata-persistence-settings-component.scss | 185 +-- ...metadata-persistence-settings-component.ts | 4 +- .../metadata-settings-component.html | 11 +- .../metadata-settings-component.scss | 84 +- .../public-reviews-settings-component.scss | 86 +- .../settings/opds-settings/opds-settings.html | 555 ++++---- .../settings/opds-settings/opds-settings.scss | 565 ++++---- .../settings/opds-settings/opds-settings.ts | 24 +- .../opds-settings/opds.service.spec.ts | 238 ---- .../cbx-reader-preferences-component.scss | 54 +- .../epub-reader-preferences-component.scss | 63 +- .../new-pdf-reader-preferences-component.scss | 54 +- .../pdf-reader-preferences-component.scss | 52 +- .../reader-preferences.component.html | 2 +- .../reader-preferences.component.scss | 124 +- .../reader-preferences.service.spec.ts | 236 --- .../task-helper.service.spec.ts | 136 -- .../task-management.component.html | 270 ++-- .../task-management.component.scss | 1089 ++++++-------- .../task-management.component.ts | 4 +- .../task-management/task.service.spec.ts | 338 ----- .../create-user-dialog.component.spec.ts | 150 -- .../user-management.component.html | 686 +++++---- .../user-management.component.scss | 664 ++++----- .../user-management.component.ts | 27 +- .../settings/user-management/user.service.ts | 2 +- .../filter-preferences.component.html | 15 - .../filter-preferences.component.scss | 73 +- .../filter-preferences.component.ts | 13 +- .../meta-center-view-mode-component.scss | 119 +- ...sidebar-sorting-preferences.component.scss | 73 +- .../view-preferences-parent.component.html | 10 + .../view-preferences-parent.component.scss | 25 +- .../view-preferences.component.scss | 131 +- .../book-formats-chart.component.ts | 2 +- .../reading-dna-chart.component.ts | 2 +- .../reading-session-timeline.component.scss | 10 + .../book-uploader.component.html | 4 +- .../directory-picker.component.scss | 50 +- .../directory-picker/utility.service.spec.ts | 102 -- .../download-progress-dialog.component.html | 25 +- .../download-progress-dialog.component.scss | 9 + .../download-progress-dialog.component.ts | 3 +- .../file-mover/file-mover-component.html | 384 ++--- .../file-mover/file-mover-component.scss | 529 +++++-- .../file-mover/file-mover-component.ts | 5 + .../icon-picker/icon-picker-component.html | 283 ++-- .../icon-picker/icon-picker-component.scss | 810 +++++++---- .../components/setup/setup.component.spec.ts | 123 -- .../components/setup/setup.service.spec.ts | 104 -- .../app/shared/model/app-settings.model.ts | 1 + .../app/shared/service/app-config.service.ts | 26 +- .../service/app-settings.service.spec.ts | 534 ------- .../service/audiobook-session.service.ts | 386 +++++ .../app/shared/service/auth.service.spec.ts | 310 ---- .../shared/service/book-mark.service.spec.ts | 264 ---- .../app/shared/service/book-mark.service.ts | 8 +- .../shared/service/book-note.service.spec.ts | 215 --- .../service/custom-font.service.spec.ts | 317 ----- .../service/download-progress.service.spec.ts | 174 --- .../service/download-progress.service.ts | 11 +- .../service/file-download.service.spec.ts | 197 --- .../shared/service/file-download.service.ts | 7 +- .../service/file-operations.service.spec.ts | 139 -- .../service/icon-picker.service.spec.ts | 98 -- .../metadata-match-weights.service.spec.ts | 111 -- .../service/metadata-progress.service.spec.ts | 241 ---- .../shared/service/page-title.service.spec.ts | 84 -- .../app/shared/service/page-title.service.ts | 2 +- .../reading-session-api.service.spec.ts | 252 ---- .../service/settings-helper.service.spec.ts | 70 - .../shared/service/url-helper.service.spec.ts | 362 ----- .../shared/service/version.service.spec.ts | 133 -- .../app/shared/services/book-cover.service.ts | 1 + .../app/shared/styles/_settings-shared.scss | 497 +++++++ .../src/assets/foliate/streaming-loader.js | 18 +- booklore-ui/src/assets/foliate/view.js | 5 +- booklore-ui/src/styles.scss | 20 +- 340 files changed, 23225 insertions(+), 20727 deletions(-) create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AudiobookStreamingJwtFilter.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/controller/AudiobookReaderController.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/convertor/FormatPriorityConverter.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/progress/AudiobookProgress.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/AttachBookFileRequest.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/BookFileProgress.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CreatePhysicalBookRequest.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookChapter.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookInfo.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookTrack.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookFileProgressEntity.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/enums/LibraryOrganizationMode.java delete mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/enums/LibraryScanMode.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/repository/BookFileRepository.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookFileProgressRepository.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/FileStreamingService.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookFileAttachmentService.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/book/PhysicalBookService.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/AudiobookProcessor.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/library/BookGroupingService.java delete mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessor.java delete mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessor.java delete mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessorRegistry.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/AudiobookMetadataExtractor.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/migration/migrations/MigrateProgressToFileProgressMigration.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/progress/ReadingProgressService.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudioFileUtilityService.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudioMetadataService.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudiobookReaderService.java delete mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProgressService.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/util/BookFileGroupingUtils.java delete mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/util/BookProgressUtil.java create mode 100644 booklore-api/src/main/resources/db/migration/V100__Create_user_book_file_progress.sql create mode 100644 booklore-api/src/main/resources/db/migration/V101__Migrate_default_book_format_to_format_priority.sql create mode 100644 booklore-api/src/main/resources/db/migration/V102__Add_is_folder_based_to_book_file.sql create mode 100644 booklore-api/src/main/resources/db/migration/V103__Add_organization_mode_to_library.sql create mode 100644 booklore-api/src/main/resources/db/migration/V104__Add_audiobook_bookmark_columns.sql create mode 100644 booklore-api/src/main/resources/db/migration/V105__Make_reading_session_columns_nullable.sql create mode 100644 booklore-api/src/main/resources/db/migration/V106__Add_physical_book_support.sql create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/FileStreamingServiceTest.java delete mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorExampleTest.java delete mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorSimpleTest.java delete mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorTest.java create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/progress/ReadingProgressServiceTest.java create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudioFileUtilityServiceTest.java create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudioMetadataServiceTest.java create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudiobookReaderServiceTest.java create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/util/BookFileGroupingUtilsTest.java create mode 100644 booklore-ui/src/app/app.spec.ts create mode 100644 booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.html create mode 100644 booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.scss create mode 100644 booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.ts delete mode 100644 booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts delete mode 100644 booklore-ui/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts delete mode 100644 booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts delete mode 100644 booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.spec.ts delete mode 100644 booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts delete mode 100644 booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts delete mode 100644 booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.html create mode 100644 booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.scss create mode 100644 booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.ts delete mode 100644 booklore-ui/src/app/features/book/service/book-menu.service.spec.ts delete mode 100644 booklore-ui/src/app/features/book/service/book-navigation.service.spec.ts delete mode 100644 booklore-ui/src/app/features/book/service/book-patch.service.spec.ts delete mode 100644 booklore-ui/src/app/features/book/service/book.service.spec.ts delete mode 100644 booklore-ui/src/app/features/book/service/cbx-reader.service.spec.ts delete mode 100644 booklore-ui/src/app/features/book/service/library-shelf-menu.service.spec.ts delete mode 100644 booklore-ui/src/app/features/book/service/library.service.spec.ts delete mode 100644 booklore-ui/src/app/features/book/service/metadata-task.spec.ts delete mode 100644 booklore-ui/src/app/features/book/service/new-pdf-reader.service.spec.ts delete mode 100644 booklore-ui/src/app/features/book/service/shelf.service.spec.ts delete mode 100644 booklore-ui/src/app/features/book/service/sort.service.spec.ts create mode 100644 booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.html create mode 100644 booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.scss create mode 100644 booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.ts create mode 100644 booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.html create mode 100644 booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.scss create mode 100644 booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.ts create mode 100644 booklore-ui/src/app/features/readers/audiobook-reader/audiobook.model.ts create mode 100644 booklore-ui/src/app/features/readers/audiobook-reader/audiobook.service.ts create mode 100644 booklore-ui/src/app/features/readers/audiobook-reader/index.ts delete mode 100644 booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.spec.ts delete mode 100644 booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo.service.spec.ts delete mode 100644 booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader.service.spec.ts delete mode 100644 booklore-ui/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.service.spec.ts delete mode 100644 booklore-ui/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.service.spec.ts delete mode 100644 booklore-ui/src/app/features/settings/email-v2/email.service.spec.ts delete mode 100644 booklore-ui/src/app/features/settings/opds-settings/opds.service.spec.ts delete mode 100644 booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts delete mode 100644 booklore-ui/src/app/features/settings/task-management/task-helper.service.spec.ts delete mode 100644 booklore-ui/src/app/features/settings/task-management/task.service.spec.ts delete mode 100644 booklore-ui/src/app/features/settings/user-management/create-user-dialog/create-user-dialog.component.spec.ts delete mode 100644 booklore-ui/src/app/shared/components/directory-picker/utility.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/components/setup/setup.component.spec.ts delete mode 100644 booklore-ui/src/app/shared/components/setup/setup.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/app-settings.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/audiobook-session.service.ts delete mode 100644 booklore-ui/src/app/shared/service/auth.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/book-mark.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/book-note.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/custom-font.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/download-progress.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/file-download.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/file-operations.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/icon-picker.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/metadata-match-weights.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/metadata-progress.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/page-title.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/reading-session-api.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/settings-helper.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/url-helper.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/version.service.spec.ts create mode 100644 booklore-ui/src/app/shared/styles/_settings-shared.scss diff --git a/README.md b/README.md index 7c0425c4f..38be78378 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,9 @@ DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore DB_USER=booklore DB_PASSWORD=ChangeMe_BookLoreApp_2025! +# 💾 Storage type: LOCAL (default) or NETWORK. Set to NETWORK if using NFS/SMB - this disables file reorganization features to prevent data corruption. +DISK_TYPE=LOCAL + # 🔧 MariaDB Container Settings DB_USER_ID=1000 DB_GROUP_ID=1000 diff --git a/booklore-api/build.gradle b/booklore-api/build.gradle index 44ffa7296..45f6bf3ae 100644 --- a/booklore-api/build.gradle +++ b/booklore-api/build.gradle @@ -70,6 +70,9 @@ dependencies { implementation 'io.documentnode:epub4j-core:4.2.2' + // --- Audio Metadata (Audiobook Support) --- + implementation 'net.jthink:jaudiotagger:3.0.1' + // --- UNRAR Support --- implementation 'com.github.junrar:junrar:7.5.7' diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/AppProperties.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/AppProperties.java index 289f2d16e..760756bde 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/AppProperties.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/AppProperties.java @@ -18,6 +18,14 @@ public class AppProperties { private Boolean forceDisableOidc = false; private Telemetry telemetry = new Telemetry(); + /** + * Type of disk storage where library files are stored. + * Defaults to LOCAL. Set to NETWORK if using NFS, SMB/CIFS, or other network-mounted storage. + * Some features like file move/reorganization are disabled on network storage due to + * unreliable atomic operations that can cause data corruption or loss. + */ + private String diskType = "LOCAL"; + @Getter @Setter public static class RemoteAuth { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java index 162d88fc8..dd131d4fe 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java @@ -183,6 +183,21 @@ public class SecurityConfig { @Bean @Order(7) + public SecurityFilterChain audiobookStreamingSecurityChain(HttpSecurity http, AudiobookStreamingJwtFilter audiobookStreamingJwtFilter) throws Exception { + http + .securityMatcher("/api/v1/audiobook/*/stream/**", "/api/v1/audiobook/*/track/*/stream/**", "/api/v1/audiobook/*/cover") + .cors(cors -> cors.configurationSource(corsConfigurationSource())) + .csrf(AbstractHttpConfigurer::disable) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .anyRequest().permitAll() + ) + .addFilterBefore(audiobookStreamingJwtFilter, UsernamePasswordAuthenticationFilter.class); + return http.build(); + } + + @Bean + @Order(8) public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception { List publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS)); if (appProperties.getSwagger().isEnabled()) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AudiobookStreamingJwtFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AudiobookStreamingJwtFilter.java new file mode 100644 index 000000000..62c749af5 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AudiobookStreamingJwtFilter.java @@ -0,0 +1,120 @@ +package com.adityachandel.booklore.config.security.filter; + +import com.adityachandel.booklore.config.security.JwtUtils; +import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor; +import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails; +import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.repository.UserRepository; +import com.adityachandel.booklore.service.appsettings.AppSettingService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.AllArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.time.Instant; +import java.util.regex.Pattern; + +/** + * JWT filter for audiobook streaming endpoints that supports both: + * 1. Authorization header (Bearer token) - for fetch() requests + * 2. Query parameter (token) - for HTML5 audio element compatibility + */ +@Component +@AllArgsConstructor +public class AudiobookStreamingJwtFilter extends OncePerRequestFilter { + + private static final Pattern AUDIOBOOK_STREAMING_ENDPOINT_PATTERN = + Pattern.compile("/api/v1/audiobook/\\d+/(stream|track/\\d+/stream|cover).*"); + + private final JwtUtils jwtUtils; + private final UserRepository userRepository; + private final BookLoreUserTransformer bookLoreUserTransformer; + private final AppSettingService appSettingService; + private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor; + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String path = request.getRequestURI(); + return !AUDIOBOOK_STREAMING_ENDPOINT_PATTERN.matcher(path).matches(); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + + // Try Authorization header first, then fall back to query parameter + String token = extractTokenFromHeader(request); + if (token == null) { + token = request.getParameter("token"); + } + + if (token == null || token.isEmpty()) { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token"); + return; + } + + try { + if (jwtUtils.validateToken(token)) { + authenticateLocalUser(token, request); + } else if (appSettingService.getAppSettings().isOidcEnabled()) { + authenticateOidcUser(token, request); + } else { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token"); + return; + } + } catch (Exception ex) { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage()); + return; + } + + chain.doFilter(request, response); + } + + private String extractTokenFromHeader(HttpServletRequest request) { + String bearer = request.getHeader("Authorization"); + return (bearer != null && bearer.startsWith("Bearer ")) ? bearer.substring(7) : null; + } + + private void authenticateLocalUser(String token, HttpServletRequest request) { + Long userId = jwtUtils.extractUserId(token); + BookLoreUserEntity entity = userRepository.findById(userId) + .orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId)); + BookLoreUser user = bookLoreUserTransformer.toDTO(entity); + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken(user, null, null); + authentication.setDetails(new UserAuthenticationDetails(request, user.getId())); + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + private void authenticateOidcUser(String token, HttpServletRequest request) throws Exception { + var processor = dynamicOidcJwtProcessor.getProcessor(); + var claimsSet = processor.process(token, null); + + if (claimsSet.getExpirationTime() == null || + claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) { + throw new RuntimeException("OIDC token expired or invalid"); + } + + OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails(); + OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping(); + String username = claimsSet.getStringClaim(claimMapping.getUsername()); + BookLoreUserEntity entity = userRepository.findByUsername(username) + .orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username)); + BookLoreUser user = bookLoreUserTransformer.toDTO(entity); + + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken(user, null, null); + authentication.setDetails(new UserAuthenticationDetails(request, user.getId())); + SecurityContextHolder.getContext().setAuthentication(authentication); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/AudiobookReaderController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/AudiobookReaderController.java new file mode 100644 index 000000000..e2cbd6b2d --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/AudiobookReaderController.java @@ -0,0 +1,100 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.config.security.annotation.CheckBookAccess; +import com.adityachandel.booklore.model.dto.response.AudiobookInfo; +import com.adityachandel.booklore.service.reader.AudiobookReaderService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.nio.file.Path; + +@Slf4j +@RestController +@RequestMapping("/api/v1/audiobook") +@RequiredArgsConstructor +@Tag(name = "Audiobook Reader", description = "Endpoints for streaming audiobooks with HTTP Range support") +public class AudiobookReaderController { + + private final AudiobookReaderService audiobookReaderService; + + @Operation(summary = "Get audiobook info", + description = "Retrieve metadata including duration, chapters/tracks, and audio details for an audiobook.") + @ApiResponse(responseCode = "200", description = "Audiobook info returned successfully") + @CheckBookAccess(bookIdParam = "bookId") + @GetMapping("/{bookId}/info") + public ResponseEntity getAudiobookInfo( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Optional book type for alternative format (e.g., AUDIOBOOK)") @RequestParam(required = false) String bookType) { + return ResponseEntity.ok(audiobookReaderService.getAudiobookInfo(bookId, bookType)); + } + + @Operation(summary = "Stream audiobook audio", + description = "Stream the audiobook audio file with HTTP Range support for seeking. " + + "Uses token query parameter for authentication to support HTML5 audio element.") + @ApiResponse(responseCode = "200", description = "Full audio file returned") + @ApiResponse(responseCode = "206", description = "Partial content returned (range request)") + @ApiResponse(responseCode = "416", description = "Range not satisfiable") + @GetMapping("/{bookId}/stream") + public void streamAudiobook( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType, + @Parameter(description = "Track index for folder-based audiobooks (0-indexed)") @RequestParam(required = false) Integer trackIndex, + HttpServletRequest request, + HttpServletResponse response) throws IOException { + + Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, trackIndex); + audiobookReaderService.streamWithRangeSupport(audioPath, request, response); + } + + @Operation(summary = "Stream specific track", description = "Stream a specific track from a folder-based audiobook.") + @ApiResponse(responseCode = "200", description = "Full track file returned") + @ApiResponse(responseCode = "206", description = "Partial content returned (range request)") + @ApiResponse(responseCode = "416", description = "Range not satisfiable") + @GetMapping("/{bookId}/track/{trackIndex}/stream") + public void streamTrack( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Track index (0-indexed)") @PathVariable Integer trackIndex, + @Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType, + HttpServletRequest request, + HttpServletResponse response) throws IOException { + + Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, trackIndex); + audiobookReaderService.streamWithRangeSupport(audioPath, request, response); + } + + @Operation(summary = "Get embedded cover art", + description = "Extract and return the embedded cover art from the audiobook file. " + + "Uses token query parameter for authentication.") + @ApiResponse(responseCode = "200", description = "Cover art returned successfully") + @ApiResponse(responseCode = "404", description = "No embedded cover art found") + @GetMapping("/{bookId}/cover") + public ResponseEntity getEmbeddedCover( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType) { + + byte[] coverData = audiobookReaderService.getEmbeddedCoverArt(bookId, bookType); + if (coverData == null) { + return ResponseEntity.notFound().build(); + } + + String mimeType = audiobookReaderService.getCoverArtMimeType(bookId, bookType); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.parseMediaType(mimeType)); + headers.setContentLength(coverData.length); + headers.setCacheControl("public, max-age=86400"); + + return new ResponseEntity<>(coverData, headers, HttpStatus.OK); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java index 8de9e291c..ed5f7c5bd 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java @@ -5,6 +5,8 @@ import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.BookRecommendation; import com.adityachandel.booklore.model.dto.BookViewerSettings; +import com.adityachandel.booklore.model.dto.request.AttachBookFileRequest; +import com.adityachandel.booklore.model.dto.request.CreatePhysicalBookRequest; import com.adityachandel.booklore.model.dto.request.PersonalRatingUpdateRequest; import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; import com.adityachandel.booklore.model.dto.request.ReadStatusUpdateRequest; @@ -13,15 +15,19 @@ import com.adityachandel.booklore.model.dto.response.BookDeletionResponse; import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse; import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse; import com.adityachandel.booklore.model.enums.ResetProgressType; +import com.adityachandel.booklore.service.book.BookFileAttachmentService; import com.adityachandel.booklore.service.book.BookService; import com.adityachandel.booklore.service.book.BookUpdateService; +import com.adityachandel.booklore.service.book.PhysicalBookService; import com.adityachandel.booklore.service.metadata.BookMetadataService; +import com.adityachandel.booklore.service.progress.ReadingProgressService; import com.adityachandel.booklore.service.recommender.BookRecommendationService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.Valid; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; @@ -45,7 +51,10 @@ public class BookController { private final BookService bookService; private final BookUpdateService bookUpdateService; private final BookRecommendationService bookRecommendationService; + private final BookFileAttachmentService bookFileAttachmentService; private final BookMetadataService bookMetadataService; + private final ReadingProgressService readingProgressService; + private final PhysicalBookService physicalBookService; @Operation(summary = "Get all books", description = "Retrieve a list of all books. Optionally include descriptions.") @ApiResponse(responseCode = "200", description = "List of books returned successfully") @@ -69,6 +78,20 @@ public class BookController { return ResponseEntity.ok(bookService.getBook(bookId, withDescription)); } + @Operation(summary = "Create a physical book", description = "Create a physical book without digital files. Requires library management permission or admin.") + @ApiResponses({ + @ApiResponse(responseCode = "201", description = "Physical book created successfully"), + @ApiResponse(responseCode = "400", description = "Invalid request"), + @ApiResponse(responseCode = "403", description = "Forbidden"), + @ApiResponse(responseCode = "404", description = "Library not found") + }) + @PostMapping("/physical") + @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") + public ResponseEntity createPhysicalBook( + @Parameter(description = "Physical book creation request") @RequestBody @Valid CreatePhysicalBookRequest request) { + return ResponseEntity.status(201).body(physicalBookService.createPhysicalBook(request)); + } + @Operation(summary = "Delete books", description = "Delete one or more books by their IDs. Requires admin or delete permission.") @ApiResponses({ @ApiResponse(responseCode = "200", description = "Books deleted successfully"), @@ -102,8 +125,10 @@ public class BookController { @ApiResponse(responseCode = "200", description = "Book content returned successfully") @GetMapping("/{bookId}/content") @CheckBookAccess(bookIdParam = "bookId") - public ResponseEntity getBookContent(@Parameter(description = "ID of the book") @PathVariable long bookId) throws IOException { - return bookService.getBookContent(bookId); + public ResponseEntity getBookContent( + @Parameter(description = "ID of the book") @PathVariable long bookId, + @Parameter(description = "Optional book type for alternative format (e.g., EPUB, PDF, MOBI)") @RequestParam(required = false) String bookType) throws IOException { + return bookService.getBookContent(bookId, bookType); } @Operation(summary = "Download book", description = "Download the book file. Requires download permission or admin.") @@ -118,12 +143,29 @@ public class BookController { return bookService.downloadBook(bookId); } - @Operation(summary = "Get viewer settings", description = "Retrieve viewer settings for a specific book.") + @Operation(summary = "Download all book files", description = "Download all files for a book as a ZIP archive. For single-file books, downloads the file directly. Requires download permission or admin.") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Files downloaded successfully"), + @ApiResponse(responseCode = "403", description = "Forbidden"), + @ApiResponse(responseCode = "404", description = "Book not found") + }) + @GetMapping("/{bookId}/download-all") + @PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()") + @CheckBookAccess(bookIdParam = "bookId") + public void downloadAllBookFiles( + @Parameter(description = "ID of the book") @PathVariable("bookId") Long bookId, + HttpServletResponse response) { + bookService.downloadAllBookFiles(bookId, response); + } + + @Operation(summary = "Get viewer settings", description = "Retrieve viewer settings for a specific book file.") @ApiResponse(responseCode = "200", description = "Viewer settings returned successfully") @GetMapping("/{bookId}/viewer-setting") @CheckBookAccess(bookIdParam = "bookId") - public ResponseEntity getBookViewerSettings(@Parameter(description = "ID of the book") @PathVariable long bookId) { - return ResponseEntity.ok(bookService.getBookViewerSetting(bookId)); + public ResponseEntity getBookViewerSettings( + @Parameter(description = "ID of the book") @PathVariable long bookId, + @Parameter(description = "ID of the book file") @RequestParam long bookFileId) { + return ResponseEntity.ok(bookService.getBookViewerSetting(bookId, bookFileId)); } @Operation(summary = "Update viewer settings", description = "Update viewer settings for a specific book.") @@ -183,7 +225,7 @@ public class BookController { if (bookIds == null || bookIds.isEmpty()) { throw ApiError.GENERIC_BAD_REQUEST.createException("No book IDs provided"); } - return ResponseEntity.ok(bookUpdateService.resetProgress(bookIds, type)); + return ResponseEntity.ok(readingProgressService.resetProgress(bookIds, type)); } @Operation(summary = "Update personal rating", description = "Update the personal rating for one or more books.") @@ -208,4 +250,19 @@ public class BookController { List updatedBooks = bookUpdateService.resetPersonalRating(bookIds); return ResponseEntity.ok(updatedBooks); } + + @Operation(summary = "Attach book files", description = "Attach book files from single-file source books to a target book as alternative formats.") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Book files attached successfully"), + @ApiResponse(responseCode = "400", description = "Invalid request - books must be in same library, sources must have exactly one file each"), + @ApiResponse(responseCode = "403", description = "Forbidden - requires library management permission"), + @ApiResponse(responseCode = "404", description = "Book not found") + }) + @PostMapping("/{targetBookId}/attach-file") + @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") + public ResponseEntity attachBookFiles( + @Parameter(description = "ID of the target book to attach the files to") @PathVariable Long targetBookId, + @Parameter(description = "Request containing source book IDs and delete option") @RequestBody @Valid AttachBookFileRequest request) { + return ResponseEntity.ok(bookFileAttachmentService.attachBookFiles(targetBookId, request.getSourceBookIds(), request.isDeleteSourceBooks())); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java index 14d801af5..6f0e78e2e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java @@ -14,10 +14,7 @@ import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import java.io.IOException; @@ -52,9 +49,10 @@ public class BookMediaController { public void getPdfPage( @Parameter(description = "ID of the book") @PathVariable Long bookId, @Parameter(description = "Page number to retrieve") @PathVariable int pageNumber, + @Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType, HttpServletResponse response) throws IOException { response.setContentType(MediaType.IMAGE_JPEG_VALUE); - pdfReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream()); + pdfReaderService.streamPageImage(bookId, bookType, pageNumber, response.getOutputStream()); } @Operation(summary = "Get CBX page as image", description = "Retrieve a specific page from a CBX book as an image.") @@ -63,9 +61,10 @@ public class BookMediaController { public void getCbxPage( @Parameter(description = "ID of the book") @PathVariable Long bookId, @Parameter(description = "Page number to retrieve") @PathVariable int pageNumber, + @Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType, HttpServletResponse response) throws IOException { response.setContentType(MediaType.IMAGE_JPEG_VALUE); - cbxReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream()); + cbxReaderService.streamPageImage(bookId, bookType, pageNumber, response.getOutputStream()); } @Operation(summary = "Get bookdrop cover", description = "Retrieve the cover image for a specific bookdrop file.") diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/CbxReaderController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/CbxReaderController.java index 55b642bc6..4fc3ee371 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/CbxReaderController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/CbxReaderController.java @@ -7,10 +7,7 @@ import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import java.util.List; @@ -25,14 +22,18 @@ public class CbxReaderController { @Operation(summary = "List pages in a CBX book", description = "Retrieve a list of available page numbers for a CBX book.") @ApiResponse(responseCode = "200", description = "Page numbers returned successfully") @GetMapping("/{bookId}/pages") - public List listPages(@Parameter(description = "ID of the book") @PathVariable Long bookId) { - return cbxReaderService.getAvailablePages(bookId); + public List listPages( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) { + return cbxReaderService.getAvailablePages(bookId, bookType); } @Operation(summary = "Get page info for a CBX book", description = "Retrieve page information including display names for a CBX book.") @ApiResponse(responseCode = "200", description = "Page info returned successfully") @GetMapping("/{bookId}/page-info") - public List getPageInfo(@Parameter(description = "ID of the book") @PathVariable Long bookId) { - return cbxReaderService.getPageInfo(bookId); + public List getPageInfo( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) { + return cbxReaderService.getPageInfo(bookId, bookType); } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/EpubReaderController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/EpubReaderController.java index 8a8fc654c..2b392f092 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/EpubReaderController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/EpubReaderController.java @@ -10,10 +10,8 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; + import org.springframework.web.servlet.HandlerMapping; import java.io.IOException; @@ -32,8 +30,10 @@ public class EpubReaderController { description = "Retrieve parsed metadata, spine, manifest, and TOC for an EPUB book.") @ApiResponse(responseCode = "200", description = "Book info returned successfully") @GetMapping("/{bookId}/info") - public ResponseEntity getBookInfo(@Parameter(description = "ID of the book") @PathVariable Long bookId) { - return ResponseEntity.ok(epubReaderService.getBookInfo(bookId)); + public ResponseEntity getBookInfo( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Optional book type for alternative format (e.g., EPUB)") @RequestParam(required = false) String bookType) { + return ResponseEntity.ok(epubReaderService.getBookInfo(bookId, bookType)); } @Operation(summary = "Get file from EPUB", description = "Retrieve a specific file from within the EPUB archive (HTML, CSS, images, fonts, etc.).") @@ -41,6 +41,7 @@ public class EpubReaderController { @GetMapping("/{bookId}/file/**") public void getFile( @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Optional book type for alternative format (e.g., EPUB)") @RequestParam(required = false) String bookType, HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -49,10 +50,10 @@ public class EpubReaderController { String filePath = fullPath.substring(prefix.length()); filePath = URLDecoder.decode(filePath, StandardCharsets.UTF_8); - String contentType = epubReaderService.getContentType(bookId, filePath); + String contentType = epubReaderService.getContentType(bookId, bookType, filePath); response.setContentType(contentType); - long fileSize = epubReaderService.getFileSize(bookId, filePath); + long fileSize = epubReaderService.getFileSize(bookId, bookType, filePath); if (fileSize > 0) { response.setContentLengthLong(fileSize); } @@ -66,6 +67,6 @@ public class EpubReaderController { response.setHeader("Cache-Control", "public, max-age=3600"); - epubReaderService.streamFile(bookId, filePath, response.getOutputStream()); + epubReaderService.streamFile(bookId, bookType, filePath, response.getOutputStream()); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/OpdsController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/OpdsController.java index bd1a11f50..57552671c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/OpdsController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/OpdsController.java @@ -1,5 +1,6 @@ package com.adityachandel.booklore.controller; +import com.adityachandel.booklore.service.book.BookDownloadService; import com.adityachandel.booklore.service.book.BookService; import com.adityachandel.booklore.service.opds.OpdsFeedService; import io.swagger.v3.oas.annotations.Operation; @@ -17,6 +18,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @Tag(name = "OPDS", description = "Endpoints for OPDS catalog feeds, book downloads, covers, and search description") @@ -31,14 +33,20 @@ public class OpdsController { private final OpdsFeedService opdsFeedService; private final BookService bookService; + private final BookDownloadService bookDownloadService; - @Operation(summary = "Download book file", description = "Download the book file by its ID.") + @Operation(summary = "Download book file", description = "Download the book file by its ID. Optionally specify a fileId to download a specific format.") @ApiResponses({ @ApiResponse(responseCode = "200", description = "Book file downloaded successfully"), @ApiResponse(responseCode = "404", description = "Book not found") }) @GetMapping("/{bookId}/download") - public ResponseEntity downloadBook(@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) { + public ResponseEntity downloadBook( + @Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId, + @Parameter(description = "Optional ID of a specific file format to download") @RequestParam(required = false) Long fileId) { + if (fileId != null) { + return bookDownloadService.downloadBookFile(bookId, fileId); + } return bookService.downloadBook(bookId); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/PdfReaderController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/PdfReaderController.java index 469d8dcb5..9a335e4e4 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/PdfReaderController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/PdfReaderController.java @@ -7,10 +7,7 @@ import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import java.util.List; @@ -25,14 +22,18 @@ public class PdfReaderController { @Operation(summary = "List pages in a PDF book", description = "Retrieve a list of available page numbers for a PDF book.") @ApiResponse(responseCode = "200", description = "Page numbers returned successfully") @GetMapping("/{bookId}/pages") - public List listPages(@Parameter(description = "ID of the book") @PathVariable Long bookId) { - return pdfReaderService.getAvailablePages(bookId); + public List listPages( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) { + return pdfReaderService.getAvailablePages(bookId, bookType); } @Operation(summary = "Get book info for a PDF book", description = "Retrieve book information including page count and hierarchical outline/table of contents.") @ApiResponse(responseCode = "200", description = "Book info returned successfully") @GetMapping("/{bookId}/info") - public PdfBookInfo getBookInfo(@Parameter(description = "ID of the book") @PathVariable Long bookId) { - return pdfReaderService.getBookInfo(bookId); + public PdfBookInfo getBookInfo( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) { + return pdfReaderService.getBookInfo(bookId, bookType); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/convertor/FormatPriorityConverter.java b/booklore-api/src/main/java/com/adityachandel/booklore/convertor/FormatPriorityConverter.java new file mode 100644 index 000000000..f86bd1e54 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/convertor/FormatPriorityConverter.java @@ -0,0 +1,46 @@ +package com.adityachandel.booklore.convertor; + +import com.adityachandel.booklore.model.enums.BookFileType; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; +import lombok.extern.slf4j.Slf4j; + +import java.util.Collections; +import java.util.List; + +@Converter +@Slf4j +public class FormatPriorityConverter implements AttributeConverter, String> { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + private static final TypeReference> LIST_TYPE_REF = new TypeReference<>() {}; + + @Override + public String convertToDatabaseColumn(List attribute) { + if (attribute == null || attribute.isEmpty()) { + return null; + } + try { + return objectMapper.writeValueAsString(attribute); + } catch (JsonProcessingException e) { + log.error("Error converting format priority list to JSON", e); + return null; + } + } + + @Override + public List convertToEntityAttribute(String dbData) { + if (dbData == null || dbData.isEmpty()) { + return Collections.emptyList(); + } + try { + return objectMapper.readValue(dbData, LIST_TYPE_REF); + } catch (JsonProcessingException e) { + log.error("Error converting JSON to format priority list", e); + return Collections.emptyList(); + } + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/AdditionalFileMapper.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/AdditionalFileMapper.java index f84069606..c8375956b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/AdditionalFileMapper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/AdditionalFileMapper.java @@ -14,6 +14,7 @@ public interface AdditionalFileMapper { @Mapping(source = "book.id", target = "bookId") @Mapping(source = ".", target = "filePath", qualifiedByName = "mapFilePath") @Mapping(source = "bookFormat", target = "isBook") + @Mapping(source = ".", target = "extension", qualifiedByName = "mapExtension") BookFile toAdditionalFile(BookFileEntity entity); List toAdditionalFiles(List entities); @@ -27,4 +28,19 @@ public interface AdditionalFileMapper { return null; } } + + @Named("mapExtension") + default String mapExtension(BookFileEntity entity) { + if (entity == null) return null; + String fileName; + if (entity.isFolderBased()) { + var firstFile = entity.getFirstAudioFile(); + fileName = firstFile != null ? firstFile.getFileName().toString() : null; + } else { + fileName = entity.getFileName(); + } + if (fileName == null) return null; + int lastDot = fileName.lastIndexOf('.'); + return lastDot > 0 ? fileName.substring(lastDot + 1).toLowerCase() : null; + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookMapper.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookMapper.java index 79a6748b2..7a0c4e4fb 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookMapper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookMapper.java @@ -3,8 +3,8 @@ package com.adityachandel.booklore.mapper; import com.adityachandel.booklore.model.dto.BookFile; import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.LibraryPath; -import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.entity.*; +import com.adityachandel.booklore.model.enums.BookFileType; import org.mapstruct.Context; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @@ -23,11 +23,7 @@ public interface BookMapper { @Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly") @Mapping(source = "metadata", target = "metadata") @Mapping(source = "shelves", target = "shelves") - @Mapping(source = "bookFiles", target = "bookType", qualifiedByName = "mapPrimaryBookType") - @Mapping(source = "bookFiles", target = "fileName", qualifiedByName = "mapPrimaryFileName") - @Mapping(source = "bookFiles", target = "filePath", qualifiedByName = "mapPrimaryFilePath") - @Mapping(source = "bookFiles", target = "fileSubPath", qualifiedByName = "mapPrimaryFileSubPath") - @Mapping(source = "bookFiles", target = "fileSizeKb", qualifiedByName = "mapPrimaryFileSizeKb") + @Mapping(source = "bookFiles", target = "primaryFile", qualifiedByName = "mapPrimaryFile") @Mapping(source = "bookFiles", target = "alternativeFormats", qualifiedByName = "mapAlternativeFormats") @Mapping(source = "bookFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles") Book toBook(BookEntity bookEntity); @@ -37,11 +33,7 @@ public interface BookMapper { @Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly") @Mapping(source = "metadata", target = "metadata") @Mapping(source = "shelves", target = "shelves") - @Mapping(source = "bookFiles", target = "bookType", qualifiedByName = "mapPrimaryBookType") - @Mapping(source = "bookFiles", target = "fileName", qualifiedByName = "mapPrimaryFileName") - @Mapping(source = "bookFiles", target = "filePath", qualifiedByName = "mapPrimaryFilePath") - @Mapping(source = "bookFiles", target = "fileSubPath", qualifiedByName = "mapPrimaryFileSubPath") - @Mapping(source = "bookFiles", target = "fileSizeKb", qualifiedByName = "mapPrimaryFileSizeKb") + @Mapping(source = "bookFiles", target = "primaryFile", qualifiedByName = "mapPrimaryFile") @Mapping(source = "bookFiles", target = "alternativeFormats", qualifiedByName = "mapAlternativeFormats") @Mapping(source = "bookFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles") Book toBookWithDescription(BookEntity bookEntity, @Context boolean includeDescription); @@ -82,34 +74,13 @@ public interface BookMapper { .build(); } - @Named("mapPrimaryBookType") - default BookFileType mapPrimaryBookType(List bookFiles) { + @Named("mapPrimaryFile") + default BookFile mapPrimaryFile(List bookFiles) { + if (bookFiles == null || bookFiles.isEmpty()) { + return null; + } BookFileEntity primary = getPrimaryBookFile(bookFiles); - return primary == null ? null : primary.getBookType(); - } - - @Named("mapPrimaryFileName") - default String mapPrimaryFileName(List bookFiles) { - BookFileEntity primary = getPrimaryBookFile(bookFiles); - return primary == null ? null : primary.getFileName(); - } - - @Named("mapPrimaryFilePath") - default String mapPrimaryFilePath(List bookFiles) { - BookFileEntity primary = getPrimaryBookFile(bookFiles); - return primary == null ? null : primary.getFullFilePath().toString(); - } - - @Named("mapPrimaryFileSubPath") - default String mapPrimaryFileSubPath(List bookFiles) { - BookFileEntity primary = getPrimaryBookFile(bookFiles); - return primary == null ? null : primary.getFileSubPath(); - } - - @Named("mapPrimaryFileSizeKb") - default Long mapPrimaryFileSizeKb(List bookFiles) { - BookFileEntity primary = getPrimaryBookFile(bookFiles); - return primary == null ? null : primary.getFileSizeKb(); + return toBookFile(primary); } @Named("mapAlternativeFormats") @@ -132,16 +103,29 @@ public interface BookMapper { .toList(); } - /* - * TODO: evolve the logic so that the user can select the primary book file format to be used. - * For now, we just return the first book file in the list. - */ default BookFileEntity getPrimaryBookFile(List bookFiles) { if (bookFiles == null || bookFiles.isEmpty()) return null; - return bookFiles.stream() - .filter(bf -> bf.isBook()) - .findFirst() - .orElse(null); + + List bookFormats = bookFiles.stream() + .filter(BookFileEntity::isBook) + .toList(); + + if (bookFormats.isEmpty()) return null; + + BookFileEntity firstBook = bookFormats.getFirst(); + LibraryEntity library = firstBook.getBook() != null ? firstBook.getBook().getLibrary() : null; + + if (library != null && library.getFormatPriority() != null && !library.getFormatPriority().isEmpty()) { + for (BookFileType format : library.getFormatPriority()) { + var match = bookFormats.stream() + .filter(bf -> bf.getBookType() == format) + .findFirst(); + if (match.isPresent()) { + return match.get(); + } + } + } + return firstBook; } default BookFile toBookFile(BookFileEntity entity) { @@ -153,10 +137,27 @@ public interface BookMapper { .filePath(entity.getFullFilePath().toString()) .fileSubPath(entity.getFileSubPath()) .isBook(entity.isBook()) + .folderBased(entity.isFolderBased()) .bookType(entity.getBookType()) + .archiveType(entity.getArchiveType()) .fileSizeKb(entity.getFileSizeKb()) + .extension(extractExtension(entity)) .description(entity.getDescription()) .addedOn(entity.getAddedOn()) .build(); } + + default String extractExtension(BookFileEntity entity) { + if (entity == null) return null; + String fileName; + if (entity.isFolderBased()) { + var firstFile = entity.getFirstAudioFile(); + fileName = firstFile != null ? firstFile.getFileName().toString() : null; + } else { + fileName = entity.getFileName(); + } + if (fileName == null) return null; + int lastDot = fileName.lastIndexOf('.'); + return lastDot > 0 ? fileName.substring(lastDot + 1).toLowerCase() : null; + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/komga/KomgaMapper.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/komga/KomgaMapper.java index c590205b7..0c0f96f2f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/komga/KomgaMapper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/komga/KomgaMapper.java @@ -282,6 +282,7 @@ public class KomgaMapper { case FB2 -> "application/fictionbook2+zip"; case MOBI -> "application/x-mobipocket-ebook"; case AZW3 -> "application/vnd.amazon.ebook"; + case AUDIOBOOK -> "audio/mp4"; }; } @@ -297,6 +298,7 @@ public class KomgaMapper { case EPUB -> "EPUB"; case CBX -> "DIVINA"; // DIVINA is for comic books case FB2 -> "DIVINA"; + case AUDIOBOOK -> "AUDIOBOOK"; }; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/v2/BookMapperV2.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/v2/BookMapperV2.java index 94f5e44e9..c34c29702 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/v2/BookMapperV2.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/v2/BookMapperV2.java @@ -2,6 +2,7 @@ package com.adityachandel.booklore.mapper.v2; import com.adityachandel.booklore.mapper.ShelfMapper; import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.BookFile; import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.LibraryPath; import com.adityachandel.booklore.model.entity.*; @@ -21,7 +22,9 @@ public interface BookMapperV2 { @Mapping(source = "library.id", target = "libraryId") @Mapping(source = "library.name", target = "libraryName") @Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly") - @Mapping(source = "bookFiles", target = "bookType", qualifiedByName = "mapPrimaryBookType") + @Mapping(source = "bookFiles", target = "primaryFile", qualifiedByName = "mapPrimaryFile") + @Mapping(source = "bookFiles", target = "alternativeFormats", qualifiedByName = "mapAlternativeFormats") + @Mapping(source = "bookFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles") @Mapping(target = "metadata", qualifiedByName = "mapMetadata") Book toDTO(BookEntity bookEntity); @@ -56,14 +59,87 @@ public interface BookMapperV2 { tags.stream().map(TagEntity::getName).collect(Collectors.toSet()); } - @Named("mapPrimaryBookType") - default BookFileType mapPrimaryBookType(List bookFiles) { - if (bookFiles == null || bookFiles.isEmpty()) return null; + @Named("mapPrimaryFile") + default BookFile mapPrimaryFile(List bookFiles) { + BookFileEntity primary = getPrimaryBookFile(bookFiles); + return toBookFile(primary); + } + + @Named("mapAlternativeFormats") + default List mapAlternativeFormats(List bookFiles) { + if (bookFiles == null) return null; + BookFileEntity primary = getPrimaryBookFile(bookFiles); return bookFiles.stream() .filter(BookFileEntity::isBook) - .map(BookFileEntity::getBookType) - .findFirst() - .orElse(null); + .filter(bf -> !bf.equals(primary)) + .map(this::toBookFile) + .toList(); + } + + @Named("mapSupplementaryFiles") + default List mapSupplementaryFiles(List bookFiles) { + if (bookFiles == null) return null; + return bookFiles.stream() + .filter(bf -> !bf.isBook()) + .map(this::toBookFile) + .toList(); + } + + default BookFileEntity getPrimaryBookFile(List bookFiles) { + if (bookFiles == null || bookFiles.isEmpty()) return null; + + List bookFormats = bookFiles.stream() + .filter(BookFileEntity::isBook) + .toList(); + + if (bookFormats.isEmpty()) return null; + + BookFileEntity firstBook = bookFormats.getFirst(); + LibraryEntity library = firstBook.getBook() != null ? firstBook.getBook().getLibrary() : null; + + if (library != null && library.getFormatPriority() != null && !library.getFormatPriority().isEmpty()) { + for (BookFileType format : library.getFormatPriority()) { + var match = bookFormats.stream() + .filter(bf -> bf.getBookType() == format) + .findFirst(); + if (match.isPresent()) { + return match.get(); + } + } + } + return firstBook; + } + + default BookFile toBookFile(BookFileEntity entity) { + if (entity == null) return null; + return BookFile.builder() + .id(entity.getId()) + .bookId(entity.getBook().getId()) + .fileName(entity.getFileName()) + .filePath(entity.getFullFilePath().toString()) + .fileSubPath(entity.getFileSubPath()) + .isBook(entity.isBook()) + .bookType(entity.getBookType()) + .archiveType(entity.getArchiveType()) + .fileSizeKb(entity.getFileSizeKb()) + .extension(extractExtension(entity)) + .description(entity.getDescription()) + .addedOn(entity.getAddedOn()) + .build(); + } + + default String extractExtension(BookFileEntity entity) { + if (entity == null) return null; + String fileName; + if (entity.isFolderBased()) { + var firstFile = entity.getFirstAudioFile(); + fileName = firstFile != null ? firstFile.getFileName().toString() : null; + } else { + fileName = entity.getFileName(); + } + if (fileName == null) return null; + int lastDot = fileName.lastIndexOf('.'); + return lastDot > 0 ? fileName.substring(lastDot + 1).toLowerCase() : null; } @Named("mapLibraryPathIdOnly") diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java index e0f68ca9c..b88b97a6f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java @@ -1,8 +1,6 @@ package com.adityachandel.booklore.model.dto; import com.adityachandel.booklore.model.dto.progress.*; -import com.adityachandel.booklore.model.enums.BookFileType; -import com.adityachandel.booklore.util.ArchiveUtils; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Builder; import lombok.Data; @@ -15,14 +13,9 @@ import java.util.Set; @JsonInclude(JsonInclude.Include.NON_NULL) public class Book { private Long id; - private BookFileType bookType; - private ArchiveUtils.ArchiveType archiveType; private Long libraryId; private String libraryName; - private String fileName; - private String filePath; - private String fileSubPath; - private Long fileSizeKb; + private BookFile primaryFile; private String title; private Instant lastReadTime; private Instant addedOn; @@ -31,6 +24,7 @@ public class Book { private PdfProgress pdfProgress; private EpubProgress epubProgress; private CbxProgress cbxProgress; + private AudiobookProgress audiobookProgress; private KoProgress koreaderProgress; private KoboProgress koboProgress; private Integer personalRating; @@ -40,4 +34,5 @@ public class Book { private LibraryPath libraryPath; private List alternativeFormats; private List supplementaryFiles; + private Boolean isPhysical; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookFile.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookFile.java index ceb68e72e..e260e3d64 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookFile.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookFile.java @@ -1,6 +1,7 @@ package com.adityachandel.booklore.model.dto; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.util.ArchiveUtils; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Builder; import lombok.Data; @@ -17,8 +18,11 @@ public class BookFile { private String filePath; private String fileSubPath; private boolean isBook; + private boolean folderBased; private BookFileType bookType; + private ArchiveUtils.ArchiveType archiveType; private Long fileSizeKb; + private String extension; private String description; private Instant addedOn; } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMark.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMark.java index eaac438d2..3c9742952 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMark.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMark.java @@ -15,7 +15,9 @@ public class BookMark { private Long id; private Long userId; private Long bookId; - private String cfi; + private String cfi; // For EPUB bookmarks + private Long positionMs; // For audiobook bookmarks + private Integer trackIndex; // For folder-based audiobooks private String title; private String color; private String notes; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookloreTelemetry.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookloreTelemetry.java index 31db744a0..4fd794274 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookloreTelemetry.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookloreTelemetry.java @@ -95,6 +95,5 @@ public class BookloreTelemetry { private int totalLibraryPaths; private boolean watchEnabled; private String iconType; - private String scanMode; } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateBookMarkRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateBookMarkRequest.java index 0cdad434a..e42677db6 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateBookMarkRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateBookMarkRequest.java @@ -1,6 +1,5 @@ package com.adityachandel.booklore.model.dto; -import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Builder; @@ -14,7 +13,20 @@ import lombok.NoArgsConstructor; public class CreateBookMarkRequest { @NotNull private Long bookId; - @NotEmpty + + // For EPUB bookmarks private String cfi; + + // For audiobook bookmarks + private Long positionMs; + private Integer trackIndex; + private String title; + + /** + * Check if this is an audiobook bookmark (has positionMs) vs EPUB bookmark (has cfi) + */ + public boolean isAudiobookBookmark() { + return positionMs != null; + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Library.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Library.java index d930f78ed..0c20279d9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Library.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Library.java @@ -2,7 +2,7 @@ package com.adityachandel.booklore.model.dto; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.IconType; -import com.adityachandel.booklore.model.enums.LibraryScanMode; +import com.adityachandel.booklore.model.enums.LibraryOrganizationMode; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Builder; import lombok.Data; @@ -21,7 +21,7 @@ public class Library { private String fileNamingPattern; private boolean watch; private List paths; - private LibraryScanMode scanMode; - private BookFileType defaultBookFormat; + private List formatPriority; + private LibraryOrganizationMode organizationMode; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/progress/AudiobookProgress.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/progress/AudiobookProgress.java new file mode 100644 index 000000000..f854ccde7 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/progress/AudiobookProgress.java @@ -0,0 +1,16 @@ +package com.adityachandel.booklore.model.dto.progress; + +import jakarta.validation.constraints.NotNull; +import lombok.Builder; +import lombok.Data; + +@Builder +@Data +public class AudiobookProgress { + @NotNull + Long positionMs; + Integer trackIndex; + Long trackPositionMs; + @NotNull + Float percentage; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/AttachBookFileRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/AttachBookFileRequest.java new file mode 100644 index 000000000..53358a005 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/AttachBookFileRequest.java @@ -0,0 +1,15 @@ +package com.adityachandel.booklore.model.dto.request; + +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +import java.util.List; + +@Data +public class AttachBookFileRequest { + @NotNull + @NotEmpty + private List sourceBookIds; + private boolean deleteSourceBooks; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/BookFileProgress.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/BookFileProgress.java new file mode 100644 index 000000000..cafaf958f --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/BookFileProgress.java @@ -0,0 +1,11 @@ +package com.adityachandel.booklore.model.dto.request; + +import jakarta.validation.constraints.NotNull; + +public record BookFileProgress( + @NotNull Long bookFileId, + String positionData, + String positionHref, + @NotNull Float progressPercent +) { +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CoverFetchRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CoverFetchRequest.java index db6ad8647..0ec656a77 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CoverFetchRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CoverFetchRequest.java @@ -9,4 +9,5 @@ public class CoverFetchRequest { private String isbn; private String title; private String author; + private boolean squareCover; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CreateLibraryRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CreateLibraryRequest.java index 167654021..a3b599670 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CreateLibraryRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CreateLibraryRequest.java @@ -3,7 +3,6 @@ package com.adityachandel.booklore.model.dto.request; import com.adityachandel.booklore.model.dto.LibraryPath; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.IconType; -import com.adityachandel.booklore.model.enums.LibraryScanMode; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty; @@ -30,6 +29,5 @@ public class CreateLibraryRequest { private List paths; private boolean watch; - private LibraryScanMode scanMode; - private BookFileType defaultBookFormat; + private List formatPriority; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CreatePhysicalBookRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CreatePhysicalBookRequest.java new file mode 100644 index 000000000..50706cca4 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/CreatePhysicalBookRequest.java @@ -0,0 +1,26 @@ +package com.adityachandel.booklore.model.dto.request; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.validation.constraints.NotNull; +import lombok.Builder; +import lombok.Data; + +import java.util.List; + +@Data +@Builder +@JsonIgnoreProperties(ignoreUnknown = true) +public class CreatePhysicalBookRequest { + @NotNull(message = "Library ID must not be null.") + private Long libraryId; + + private String isbn; + private String title; + private List authors; + private String description; + private String publisher; + private String publishedDate; + private String language; + private Integer pageCount; + private List categories; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadProgressRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadProgressRequest.java index fb49141ba..9d58da696 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadProgressRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadProgressRequest.java @@ -1,5 +1,6 @@ package com.adityachandel.booklore.model.dto.request; +import com.adityachandel.booklore.model.dto.progress.AudiobookProgress; import com.adityachandel.booklore.model.dto.progress.CbxProgress; import com.adityachandel.booklore.model.dto.progress.EpubProgress; import com.adityachandel.booklore.model.dto.progress.PdfProgress; @@ -12,13 +13,22 @@ import java.time.Instant; public class ReadProgressRequest { @NotNull private Long bookId; + + private BookFileProgress fileProgress; + + @Deprecated private EpubProgress epubProgress; + @Deprecated private PdfProgress pdfProgress; + @Deprecated private CbxProgress cbxProgress; + @Deprecated + private AudiobookProgress audiobookProgress; + private Instant dateFinished; @AssertTrue(message = "At least one progress field must be provided") public boolean isProgressValid() { - return epubProgress != null || pdfProgress != null || cbxProgress != null || dateFinished != null; + return fileProgress != null || epubProgress != null || pdfProgress != null || cbxProgress != null || audiobookProgress != null || dateFinished != null; } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadingSessionRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadingSessionRequest.java index 6053bc458..66b43d9bb 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadingSessionRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadingSessionRequest.java @@ -26,18 +26,15 @@ public class ReadingSessionRequest { @NotNull private Integer durationSeconds; - @NotNull + private String durationFormatted; + private Float startProgress; - @NotNull private Float endProgress; - @NotNull private Float progressDelta; - @NotNull private String startLocation; - @NotNull private String endLocation; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookChapter.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookChapter.java new file mode 100644 index 000000000..45fdbd6fd --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookChapter.java @@ -0,0 +1,18 @@ +package com.adityachandel.booklore.model.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AudiobookChapter { + private Integer index; + private String title; + private Long startTimeMs; + private Long endTimeMs; + private Long durationMs; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookInfo.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookInfo.java new file mode 100644 index 000000000..99cabf7d5 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookInfo.java @@ -0,0 +1,28 @@ +package com.adityachandel.booklore.model.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AudiobookInfo { + private Long bookId; + private Long bookFileId; + private String title; + private String author; + private String narrator; + private Long durationMs; + private Integer bitrate; + private String codec; + private Integer sampleRate; + private Integer channels; + private boolean folderBased; + private List chapters; + private List tracks; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookTrack.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookTrack.java new file mode 100644 index 000000000..22cf98f70 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/AudiobookTrack.java @@ -0,0 +1,19 @@ +package com.adityachandel.booklore.model.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AudiobookTrack { + private Integer index; + private String fileName; + private String title; + private Long durationMs; + private Long fileSizeBytes; + private Long cumulativeStartMs; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java index 2105ab0da..38441459b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java @@ -36,4 +36,5 @@ public class AppSettings { private KoboSettings koboSettings; private CoverCroppingSettings coverCroppingSettings; private MetadataProviderSpecificFields metadataProviderSpecificFields; + private String diskType; } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/LibraryFile.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/LibraryFile.java index 56ad61d24..8157ec7d6 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/LibraryFile.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/LibraryFile.java @@ -19,6 +19,8 @@ public class LibraryFile { private String fileSubPath; private String fileName; private BookFileType bookFileType; + @Builder.Default + private boolean folderBased = false; public Path getFullPath() { if (fileSubPath == null || fileSubPath.isEmpty()) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java index bd3627fa3..d980d39ad 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java @@ -45,9 +45,13 @@ public class BookEntity { private LibraryEntity library; @ManyToOne - @JoinColumn(name = "library_path_id", nullable = false) + @JoinColumn(name = "library_path_id") private LibraryPathEntity libraryPath; + @Column(name = "is_physical") + @Builder.Default + private Boolean isPhysical = Boolean.FALSE; + @Column(name = "added_on") private Instant addedOn; @@ -83,9 +87,8 @@ public class BookEntity { public Path getFullFilePath() { BookFileEntity primaryBookFile = getPrimaryBookFile(); - if (libraryPath == null || libraryPath.getPath() == null || primaryBookFile.getFileSubPath() == null || primaryBookFile.getFileName() == null) { - throw new IllegalStateException( - "Cannot construct file path: missing library path, file subpath, or file name"); + if (primaryBookFile == null || libraryPath == null || libraryPath.getPath() == null || primaryBookFile.getFileSubPath() == null || primaryBookFile.getFileName() == null) { + return null; } return Paths.get(libraryPath.getPath(), primaryBookFile.getFileSubPath(), primaryBookFile.getFileName()); @@ -93,22 +96,34 @@ public class BookEntity { public List getFullFilePaths() { if (libraryPath == null || libraryPath.getPath() == null || bookFiles == null || bookFiles.isEmpty()) { - throw new IllegalStateException( - "Cannot construct file path: missing library path, file subpath, or file name"); + return List.of(); } return bookFiles.stream() .map(bookFile -> Paths.get(libraryPath.getPath(), bookFile.getFileSubPath(), bookFile.getFileName())) .collect(Collectors.toList()); } - // TODO: Add support for specifying the preferred format public BookFileEntity getPrimaryBookFile() { if (bookFiles == null) { bookFiles = new ArrayList<>(); } if (bookFiles.isEmpty()) { - throw new IllegalStateException("Book file not found"); + return null; + } + if (library != null && library.getFormatPriority() != null && !library.getFormatPriority().isEmpty()) { + for (BookFileType format : library.getFormatPriority()) { + var match = bookFiles.stream() + .filter(bf -> bf.isBookFormat() && bf.getBookType() == format) + .findFirst(); + if (match.isPresent()) { + return match.get(); + } + } } return bookFiles.getFirst(); } + + public boolean hasFiles() { + return bookFiles != null && !bookFiles.isEmpty(); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookFileEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookFileEntity.java index d8457ad9d..9ba5a853a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookFileEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookFileEntity.java @@ -1,6 +1,7 @@ package com.adityachandel.booklore.model.entity; -import com.adityachandel.booklore.util.ArchiveUtils; + import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.util.ArchiveUtils; import jakarta.persistence.*; import lombok.*; @@ -34,6 +35,10 @@ public class BookFileEntity { @Column(name = "is_book", nullable = false) private boolean isBookFormat; + @Column(name = "is_folder_based", nullable = false) + @Builder.Default + private boolean folderBased = false; + @Enumerated(EnumType.STRING) @Column(name = "book_type", nullable = false) private BookFileType bookType; @@ -72,4 +77,39 @@ public class BookFileEntity { return Paths.get(book.getLibraryPath().getPath(), fileSubPath, fileName); } + + /** + * For folder-based audiobooks, returns the folder path. + * For regular files, returns the file path. + */ + public Path getAudiobookPath() { + Path fullPath = getFullFilePath(); + return folderBased ? fullPath : fullPath; + } + + /** + * For folder-based audiobooks, returns the first audio file in the folder (for metadata extraction). + * For regular files, returns the file itself. + */ + public Path getFirstAudioFile() { + if (!folderBased) { + return getFullFilePath(); + } + Path folderPath = getFullFilePath(); + try { + return java.nio.file.Files.list(folderPath) + .filter(java.nio.file.Files::isRegularFile) + .filter(p -> { + String name = p.getFileName().toString().toLowerCase(); + return name.endsWith(".mp3") || name.endsWith(".m4a") || name.endsWith(".m4b") + || name.endsWith(".flac") || name.endsWith(".ogg") || name.endsWith(".opus") + || name.endsWith(".aac"); + }) + .sorted() + .findFirst() + .orElse(folderPath); + } catch (java.io.IOException e) { + return folderPath; + } + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookMarkEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookMarkEntity.java index 73a87f298..55c934a87 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookMarkEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookMarkEntity.java @@ -34,9 +34,17 @@ public class BookMarkEntity { @Column(name = "book_id", insertable = false, updatable = false) private Long bookId; - @Column(name = "cfi", nullable = false, length = 1000) + // For EPUB bookmarks + @Column(name = "cfi", length = 1000) private String cfi; + // For audiobook bookmarks + @Column(name = "position_ms") + private Long positionMs; + + @Column(name = "track_index") + private Integer trackIndex; + @Column(name = "title") private String title; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java index 0f2fd94ef..a319c3f45 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java @@ -1,13 +1,15 @@ package com.adityachandel.booklore.model.entity; +import com.adityachandel.booklore.convertor.FormatPriorityConverter; import com.adityachandel.booklore.convertor.SortConverter; import com.adityachandel.booklore.model.dto.Sort; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.IconType; -import com.adityachandel.booklore.model.enums.LibraryScanMode; +import com.adityachandel.booklore.model.enums.LibraryOrganizationMode; import jakarta.persistence.*; import lombok.*; +import java.util.ArrayList; import java.util.List; @Entity @@ -49,14 +51,15 @@ public class LibraryEntity { @Column(name = "file_naming_pattern") private String fileNamingPattern; - @Enumerated(EnumType.STRING) - @Column(name = "scan_mode", nullable = false) + @Convert(converter = FormatPriorityConverter.class) + @Column(name = "format_priority") @Builder.Default - private LibraryScanMode scanMode = LibraryScanMode.FILE_AS_BOOK; + private List formatPriority = new ArrayList<>(); @Enumerated(EnumType.STRING) - @Column(name = "default_book_format") - private BookFileType defaultBookFormat; + @Column(name = "organization_mode") + @Builder.Default + private LibraryOrganizationMode organizationMode = LibraryOrganizationMode.AUTO_DETECT; @PrePersist public void ensureIconType() { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/ReadingSessionEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/ReadingSessionEntity.java index 32a29733b..153a76596 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/ReadingSessionEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/ReadingSessionEntity.java @@ -41,19 +41,22 @@ public class ReadingSessionEntity { @Column(name = "duration_seconds", nullable = false) private Integer durationSeconds; - @Column(name = "start_progress", nullable = false) + @Column(name = "duration_formatted") + private String durationFormatted; + + @Column(name = "start_progress") private Float startProgress; - @Column(name = "end_progress", nullable = false) + @Column(name = "end_progress") private Float endProgress; - @Column(name = "progress_delta", nullable = false) + @Column(name = "progress_delta") private Float progressDelta; - @Column(name = "start_location", nullable = false, length = 500) + @Column(name = "start_location", length = 500) private String startLocation; - @Column(name = "end_location", nullable = false, length = 500) + @Column(name = "end_location", length = 500) private String endLocation; @Column(name = "created_at", nullable = false, updatable = false) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookFileProgressEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookFileProgressEntity.java new file mode 100644 index 000000000..d9af905f7 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookFileProgressEntity.java @@ -0,0 +1,41 @@ +package com.adityachandel.booklore.model.entity; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.Instant; + +@Entity +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "user_book_file_progress", + uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "book_file_id"})) +public class UserBookFileProgressEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne + @JoinColumn(name = "user_id", nullable = false) + private BookLoreUserEntity user; + + @ManyToOne + @JoinColumn(name = "book_file_id", nullable = false) + private BookFileEntity bookFile; + + @Column(name = "position_data", length = 1000) + private String positionData; + + @Column(name = "position_href", length = 1000) + private String positionHref; + + @Column(name = "progress_percent") + private Float progressPercent; + + @Column(name = "last_read_time") + private Instant lastReadTime; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookProgressEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookProgressEntity.java index 9823047f4..6a9411937 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookProgressEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookProgressEntity.java @@ -30,24 +30,31 @@ public class UserBookProgressEntity { @Column(name = "last_read_time") private Instant lastReadTime; + @Deprecated @Column(name = "pdf_progress") private Integer pdfProgress; + @Deprecated @Column(name = "pdf_progress_percent") private Float pdfProgressPercent; + @Deprecated @Column(name = "epub_progress", length = 1000) private String epubProgress; + @Deprecated @Column(name = "epub_progress_href", length = 1000) private String epubProgressHref; + @Deprecated @Column(name = "epub_progress_percent") private Float epubProgressPercent; + @Deprecated @Column(name = "cbx_progress") private Integer cbxProgress; + @Deprecated @Column(name = "cbx_progress_percent") private Float cbxProgressPercent; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileExtension.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileExtension.java index b0e12fca7..3847e6cd1 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileExtension.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileExtension.java @@ -17,7 +17,14 @@ public enum BookFileExtension { MOBI("mobi", BookFileType.MOBI), AZW3("azw3", BookFileType.AZW3), AZW("azw", BookFileType.AZW3), - FB2("fb2", BookFileType.FB2); + FB2("fb2", BookFileType.FB2), + M4B("m4b", BookFileType.AUDIOBOOK), + M4A("m4a", BookFileType.AUDIOBOOK), + MP3("mp3", BookFileType.AUDIOBOOK), + AAC("aac", BookFileType.AUDIOBOOK), + FLAC("flac", BookFileType.AUDIOBOOK), + OPUS("opus", BookFileType.AUDIOBOOK), + OGG("ogg", BookFileType.AUDIOBOOK); private final String extension; private final BookFileType type; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java index 44598dbcf..999451b8b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java @@ -14,7 +14,8 @@ public enum BookFileType { CBX(Set.of("cbz", "cbr", "cb7")), FB2(Set.of("fb2")), MOBI(Set.of("mobi")), - AZW3(Set.of("azw3", "azw")); + AZW3(Set.of("azw3", "azw")), + AUDIOBOOK(Set.of("m4b", "m4a", "mp3", "aac", "flac", "opus", "ogg")); private final Set extensions; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/LibraryOrganizationMode.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/LibraryOrganizationMode.java new file mode 100644 index 000000000..4149765af --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/LibraryOrganizationMode.java @@ -0,0 +1,34 @@ +package com.adityachandel.booklore.model.enums; + +/** + * Defines how a library organizes book files into folders. + * This affects how files are grouped together as a single book. + */ +public enum LibraryOrganizationMode { + + /** + * Each book has its own dedicated folder. + * All files within a folder are treated as formats of the same book. + * Simple and deterministic - no fuzzy matching needed. + *

+ * Example: + *

+     * Library/
+     * └── American Gods/
+     *     ├── American Gods.epub
+     *     ├── American Gods.m4b
+     *     └── American Gods - 10th Anniversary.pdf
+     * 
+ * All three files become one book. + */ + BOOK_PER_FOLDER, + + /** + * System automatically detects grouping using folder-centric fuzzy matching. + * Uses folder name as reference, applies similarity matching for variations. + * Handles series detection to keep numbered entries separate. + *

+ * Use this when your library has mixed organization or you're unsure. + */ + AUTO_DETECT +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/LibraryScanMode.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/LibraryScanMode.java deleted file mode 100644 index 51e1e1a9c..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/LibraryScanMode.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.adityachandel.booklore.model.enums; - -public enum LibraryScanMode { - FILE_AS_BOOK, - FOLDER_AS_BOOK -} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookFileRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookFileRepository.java new file mode 100644 index 000000000..85b873576 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookFileRepository.java @@ -0,0 +1,27 @@ +package com.adityachandel.booklore.repository; + +import com.adityachandel.booklore.model.entity.BookFileEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface BookFileRepository extends JpaRepository { + + @Query(""" + SELECT bf FROM BookFileEntity bf + WHERE bf.book.libraryPath.id = :libraryPathId + AND bf.fileSubPath = :fileSubPath + AND bf.fileName = :fileName + """) + Optional findByLibraryPathIdAndFileSubPathAndFileName( + @Param("libraryPathId") Long libraryPathId, + @Param("fileSubPath") String fileSubPath, + @Param("fileName") String fileName); + + @Query("SELECT COUNT(bf) FROM BookFileEntity bf WHERE bf.book.id = :bookId") + long countByBookId(@Param("bookId") Long bookId); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookMarkRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookMarkRepository.java index 64d6e33cb..2563c0f01 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookMarkRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookMarkRepository.java @@ -20,6 +20,13 @@ public interface BookMarkRepository extends JpaRepository @Query("SELECT COUNT(b) > 0 FROM BookMarkEntity b WHERE b.cfi = :cfi AND b.bookId = :bookId AND b.userId = :userId AND b.id != :excludeId") boolean existsByCfiAndBookIdAndUserIdExcludeId(@Param("cfi") String cfi, @Param("bookId") Long bookId, @Param("userId") Long userId, @Param("excludeId") Long excludeId); + // Audiobook bookmark duplicate check (within 5 seconds of position is considered duplicate) + @Query("SELECT COUNT(b) > 0 FROM BookMarkEntity b WHERE b.bookId = :bookId AND b.userId = :userId " + + "AND b.positionMs IS NOT NULL " + + "AND ABS(b.positionMs - :positionMs) < 5000 " + + "AND ((:trackIndex IS NULL AND b.trackIndex IS NULL) OR b.trackIndex = :trackIndex)") + boolean existsByPositionMsNearAndBookIdAndUserId(@Param("positionMs") Long positionMs, @Param("trackIndex") Integer trackIndex, @Param("bookId") Long bookId, @Param("userId") Long userId); + // New: count bookmarks per book long countByBookIdAndUserId(Long bookId, Long userId); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java index 5a3b003eb..0c0c4f4d9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java @@ -35,6 +35,9 @@ public interface BookRepository extends JpaRepository, JpaSpec @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)") List 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)") + List findAllByLibraryPathIdAndFileSubPath(@Param("libraryPathId") Long libraryPathId, @Param("fileSubPath") String fileSubPath); + @Query("SELECT b FROM BookEntity b JOIN b.bookFiles bf WHERE b.libraryPath.id = :libraryPathId AND bf.fileSubPath = :fileSubPath AND bf.fileName = :fileName AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)") Optional findByLibraryPath_IdAndFileSubPathAndFileName(@Param("libraryPathId") Long libraryPathId, @Param("fileSubPath") String fileSubPath, @@ -143,6 +146,16 @@ public interface BookRepository extends JpaRepository, JpaSpec @Query("SELECT COUNT(b) FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)") long countByLibraryId(@Param("libraryId") Long libraryId); + @Query(""" + SELECT b FROM BookEntity b + LEFT JOIN b.bookFiles bf + WHERE b.library.id = :libraryId + AND (b.deleted IS NULL OR b.deleted = false) + GROUP BY b + HAVING COUNT(bf) = 0 + """) + List findFilelessBooksByLibraryId(@Param("libraryId") Long libraryId); + @Query("SELECT b.id as id, m.coverUpdatedOn as coverUpdatedOn FROM BookEntity b LEFT JOIN b.metadata m WHERE b.id IN :bookIds") List findCoverUpdateInfoByIds(@Param("bookIds") Collection bookIds); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookFileProgressRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookFileProgressRepository.java new file mode 100644 index 000000000..d94dc95d6 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookFileProgressRepository.java @@ -0,0 +1,48 @@ +package com.adityachandel.booklore.repository; + +import com.adityachandel.booklore.model.entity.UserBookFileProgressEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface UserBookFileProgressRepository extends JpaRepository { + + Optional findByUserIdAndBookFileId(Long userId, Long bookFileId); + + @Query(""" + SELECT ubfp FROM UserBookFileProgressEntity ubfp + WHERE ubfp.user.id = :userId + AND ubfp.bookFile.book.id = :bookId + """) + List findByUserIdAndBookFileBookId( + @Param("userId") Long userId, + @Param("bookId") Long bookId + ); + + @Query(""" + SELECT ubfp FROM UserBookFileProgressEntity ubfp + WHERE ubfp.user.id = :userId + AND ubfp.bookFile.book.id = :bookId + ORDER BY ubfp.lastReadTime DESC + LIMIT 1 + """) + Optional findMostRecentByUserIdAndBookId( + @Param("userId") Long userId, + @Param("bookId") Long bookId + ); + + @Query(""" + SELECT ubfp FROM UserBookFileProgressEntity ubfp + WHERE ubfp.user.id = :userId + AND ubfp.bookFile.book.id IN :bookIds + """) + List findByUserIdAndBookFileBookIdIn( + @Param("userId") Long userId, + @Param("bookIds") Iterable bookIds + ); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/FileStreamingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/FileStreamingService.java new file mode 100644 index 000000000..415fd3116 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/FileStreamingService.java @@ -0,0 +1,189 @@ +package com.adityachandel.booklore.service; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.RandomAccessFile; +import java.net.SocketTimeoutException; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Generic file streaming service with HTTP Range support. + * Can be used for streaming audio, video, or any binary files. + */ +@Slf4j +@Service +public class FileStreamingService { + + private static final int BUFFER_SIZE = 8192; + + /** + * Stream a file with HTTP Range support for seeking/scrubbing. + * Implements HTTP 206 Partial Content for range requests. + * + * @param filePath Path to the file to stream + * @param contentType MIME type of the file + * @param request HTTP request (to read Range header) + * @param response HTTP response (to write headers and body) + */ + public void streamWithRangeSupport(Path filePath, String contentType, HttpServletRequest request, HttpServletResponse response) throws IOException { + if (!Files.exists(filePath)) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found"); + return; + } + + long fileSize = Files.size(filePath); + String rangeHeader = request.getHeader("Range"); + + // Always indicate we accept range requests + response.setHeader("Accept-Ranges", "bytes"); + response.setContentType(contentType); + response.setHeader("Cache-Control", "public, max-age=3600"); + + try { + if (rangeHeader == null) { + // No Range header - return full file + response.setStatus(HttpServletResponse.SC_OK); + response.setContentLengthLong(fileSize); + streamBytes(filePath, 0, fileSize - 1, response.getOutputStream()); + } else { + // Parse Range header + RangeInfo range = parseRange(rangeHeader, fileSize); + if (range == null) { + // Invalid range + response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); + response.setHeader("Content-Range", "bytes */" + fileSize); + return; + } + + // Return partial content + long contentLength = range.end - range.start + 1; + response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); + response.setContentLengthLong(contentLength); + response.setHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + fileSize); + + streamBytes(filePath, range.start, range.end, response.getOutputStream()); + } + } catch (IOException e) { + // Client disconnected (e.g., during seeking) - this is normal, just log at debug level + if (isClientDisconnect(e)) { + log.debug("Client disconnected during streaming: {}", e.getMessage()); + } else { + throw e; + } + } + } + + /** + * Check if the exception is due to client disconnect (common during seeking). + */ + boolean isClientDisconnect(IOException e) { + // SocketTimeoutException is common when client disconnects + if (e instanceof SocketTimeoutException) { + return true; + } + + String message = e.getMessage(); + if (message == null) { + // Check the exception class name for common disconnect types + String className = e.getClass().getSimpleName(); + return className.contains("Timeout") || className.contains("Closed"); + } + + return message.contains("Connection reset") || + message.contains("Broken pipe") || + message.contains("connection was aborted") || + message.contains("An established connection was aborted") || + message.contains("SocketTimeout") || + message.contains("timed out"); + } + + /** + * Parse HTTP Range header and return start/end byte positions. + * Supports formats: "bytes=start-end", "bytes=start-", "bytes=-suffix" + */ + RangeInfo parseRange(String rangeHeader, long fileSize) { + if (!rangeHeader.startsWith("bytes=")) { + return null; + } + + String rangeSpec = rangeHeader.substring(6).trim(); + String[] ranges = rangeSpec.split(","); + if (ranges.length == 0) { + return null; + } + + // Only handle first range (most common case) + String range = ranges[0].trim(); + String[] parts = range.split("-", -1); + if (parts.length != 2) { + return null; + } + + try { + long start, end; + + if (parts[0].isEmpty()) { + // Suffix range: "-500" means last 500 bytes + long suffix = Long.parseLong(parts[1]); + start = Math.max(0, fileSize - suffix); + end = fileSize - 1; + } else if (parts[1].isEmpty()) { + // Open-ended range: "500-" means from byte 500 to end + start = Long.parseLong(parts[0]); + end = fileSize - 1; + } else { + // Full range: "500-999" + start = Long.parseLong(parts[0]); + end = Long.parseLong(parts[1]); + } + + // Validate range + if (start < 0 || start >= fileSize || end < start) { + return null; + } + + // Clamp end to file size + end = Math.min(end, fileSize - 1); + + return new RangeInfo(start, end); + } catch (NumberFormatException e) { + return null; + } + } + + /** + * Stream bytes from start to end (inclusive) using RandomAccessFile for efficient seeking. + */ + private void streamBytes(Path filePath, long start, long end, OutputStream outputStream) throws IOException { + try (RandomAccessFile raf = new RandomAccessFile(filePath.toFile(), "r")) { + raf.seek(start); + + long bytesToRead = end - start + 1; + byte[] buffer = new byte[BUFFER_SIZE]; + long totalRead = 0; + + while (totalRead < bytesToRead) { + int toRead = (int) Math.min(buffer.length, bytesToRead - totalRead); + int read = raf.read(buffer, 0, toRead); + if (read == -1) { + break; + } + outputStream.write(buffer, 0, read); + totalRead += read; + } + + outputStream.flush(); + } + } + + /** + * Range information holder. + */ + record RangeInfo(long start, long end) {} +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java index 255bcae78..a33bf9393 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java @@ -67,6 +67,7 @@ public class ReadingSessionService { .startTime(request.getStartTime()) .endTime(request.getEndTime()) .durationSeconds(request.getDurationSeconds()) + .durationFormatted(request.getDurationFormatted()) .startProgress(request.getStartProgress()) .endProgress(request.getEndProgress()) .progressDelta(request.getProgressDelta()) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/TelemetryService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/TelemetryService.java index 2bc2d21bd..e100a713f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/TelemetryService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/TelemetryService.java @@ -146,7 +146,6 @@ public class TelemetryService { .bookCount(bookRepository.countByLibraryId(lib.getId())) .watchEnabled(lib.isWatch()) .iconType(lib.getIconType() != null ? lib.getIconType().name() : null) - .scanMode(lib.getScanMode() != null ? lib.getScanMode().name() : null) .build(); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java index 4c501ce3c..11e23273d 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java @@ -138,7 +138,7 @@ public class AppSettingService { ) ); builder.autoBookSearch(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.AUTO_BOOK_SEARCH, "true"))); - builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >{title}< - {authors}>< ({year})>")); + builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >/{title}/{title}< - {authors}>< ({year})>")); builder.similarBookRecommendation(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, "true"))); builder.opdsServerEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false"))); builder.komgaApiEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.KOMGA_API_ENABLED, "false"))); @@ -153,6 +153,8 @@ public class AppSettingService { boolean finalEnabled = settingEnabled && (forceDisable == null || !forceDisable); builder.oidcEnabled(finalEnabled); + builder.diskType(appProperties.getDiskType()); + return builder.build(); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookCreatorService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookCreatorService.java index d7e21c170..ea7b90f06 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookCreatorService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookCreatorService.java @@ -32,18 +32,24 @@ public class BookCreatorService { if (existingBookOpt.isPresent()) { log.warn("Book already exists for file: {}", libraryFile.getFileName()); - String newHash = FileFingerprint.generateHash(libraryFile.getFullPath()); - long fileSizeKb = FileUtils.getFileSizeInKb(libraryFile.getFullPath()); + long fileSizeKb = calculateFileSize(libraryFile); + String newHash = libraryFile.isFolderBased() + ? FileFingerprint.generateFolderHash(libraryFile.getFullPath()) + : FileFingerprint.generateHash(libraryFile.getFullPath()); BookEntity existingBook = existingBookOpt.get(); BookFileEntity primaryFile = existingBook.getPrimaryBookFile(); primaryFile.setCurrentHash(newHash); primaryFile.setInitialHash(newHash); primaryFile.setFileSizeKb(fileSizeKb); + primaryFile.setFolderBased(libraryFile.isFolderBased()); existingBook.setDeleted(false); return existingBook; } - long fileSizeKb = FileUtils.getFileSizeInKb(libraryFile.getFullPath()); + long fileSizeKb = calculateFileSize(libraryFile); + String hash = libraryFile.isFolderBased() + ? FileFingerprint.generateFolderHash(libraryFile.getFullPath()) + : FileFingerprint.generateHash(libraryFile.getFullPath()); BookEntity bookEntity = BookEntity.builder() .library(libraryFile.getLibraryEntity()) @@ -57,8 +63,11 @@ public class BookCreatorService { .fileName(libraryFile.getFileName()) .fileSubPath(libraryFile.getFileSubPath()) .isBookFormat(true) + .folderBased(libraryFile.isFolderBased()) .bookType(bookFileType) .fileSizeKb(fileSizeKb) + .initialHash(hash) + .currentHash(hash) .addedOn(Instant.now()) .build(); bookEntity.getBookFiles().add(bookFileEntity); @@ -71,6 +80,16 @@ public class BookCreatorService { return bookRepository.saveAndFlush(bookEntity); } + private long calculateFileSize(LibraryFile libraryFile) { + if (libraryFile.isFolderBased()) { + Long size = FileUtils.getFolderSizeInKb(libraryFile.getFullPath()); + return size != null ? size : 0L; + } else { + Long size = FileUtils.getFileSizeInKb(libraryFile.getFullPath()); + return size != null ? size : 0L; + } + } + public void addCategoriesToBook(Set categories, BookEntity bookEntity) { if (bookEntity.getMetadata().getCategories() == null) { bookEntity.getMetadata().setCategories(new HashSet<>()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookDownloadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookDownloadService.java index d3b3d36e2..557899a09 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookDownloadService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookDownloadService.java @@ -3,7 +3,9 @@ package com.adityachandel.booklore.service.book; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.model.dto.settings.KoboSettings; import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.repository.BookFileRepository; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.kobo.KepubConversionService; @@ -23,13 +25,18 @@ import org.springframework.util.FileSystemUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.io.UncheckedIOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Comparator; +import java.util.List; import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; @Slf4j @AllArgsConstructor @@ -39,6 +46,7 @@ public class BookDownloadService { private static final Pattern NON_ASCII_PATTERN = Pattern.compile("[^\\x00-\\x7F]"); private final BookRepository bookRepository; + private final BookFileRepository bookFileRepository; private final KepubConversionService kepubConversionService; private final CbxConversionService cbxConversionService; private final AppSettingService appSettingService; @@ -48,12 +56,22 @@ public class BookDownloadService { BookEntity bookEntity = bookRepository.findById(bookId) .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize(); - File bookFile = file.toFile(); - - if (!bookFile.exists()) { + BookFileEntity primaryFile = bookEntity.getPrimaryBookFile(); + if (primaryFile == null) { throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); } + Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize(); + + if (!Files.exists(file)) { + throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); + } + + // Handle folder-based audiobooks - create ZIP + if (primaryFile.isFolderBased() && Files.isDirectory(file)) { + return downloadFolderAsZip(file, primaryFile.getFileName()); + } + + File bookFile = file.toFile(); // Use FileSystemResource which properly handles file resources and closing Resource resource = new FileSystemResource(bookFile); @@ -77,10 +95,152 @@ public class BookDownloadService { } } + public ResponseEntity downloadBookFile(Long bookId, Long fileId) { + try { + BookFileEntity bookFileEntity = bookFileRepository.findById(fileId) + .orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException(fileId)); + + // Verify the file belongs to the specified book + if (!bookFileEntity.getBook().getId().equals(bookId)) { + throw ApiError.FILE_NOT_FOUND.createException(fileId); + } + + Path file = bookFileEntity.getFullFilePath().toAbsolutePath().normalize(); + + if (!Files.exists(file)) { + throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(fileId); + } + + // Handle folder-based audiobooks - create ZIP + if (bookFileEntity.isFolderBased() && Files.isDirectory(file)) { + return downloadFolderAsZip(file, bookFileEntity.getFileName()); + } + + File bookFile = file.toFile(); + Resource resource = new FileSystemResource(bookFile); + + String encodedFilename = URLEncoder.encode(file.getFileName().toString(), StandardCharsets.UTF_8) + .replace("+", "%20"); + String fallbackFilename = NON_ASCII_PATTERN.matcher(file.getFileName().toString()).replaceAll("_"); + String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", + fallbackFilename, encodedFilename); + return ResponseEntity.ok() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .contentLength(bookFile.length()) + .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) + .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") + .header(HttpHeaders.PRAGMA, "no-cache") + .header(HttpHeaders.EXPIRES, "0") + .body(resource); + } catch (Exception e) { + log.error("Failed to download book file {}: {}", fileId, e.getMessage(), e); + throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(fileId); + } + } + + public void downloadAllBookFiles(Long bookId, HttpServletResponse response) { + BookEntity bookEntity = bookRepository.findById(bookId) + .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + List allFiles = bookEntity.getBookFiles(); + if (allFiles == null || allFiles.isEmpty()) { + throw ApiError.FILE_NOT_FOUND.createException(bookId); + } + + // If only one file and it's not folder-based, download it directly + if (allFiles.size() == 1) { + BookFileEntity singleFile = allFiles.get(0); + Path filePath = singleFile.getFullFilePath(); + + if (!Files.exists(filePath)) { + throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); + } + + // For folder-based audiobooks, let it fall through to ZIP creation + if (!singleFile.isFolderBased() || !Files.isDirectory(filePath)) { + File file = filePath.toFile(); + setResponseHeaders(response, file); + streamFileToResponse(file, response); + return; + } + } + + // Sort files by filename for consistent ordering + allFiles.sort(Comparator.comparing(BookFileEntity::getFileName)); + + // Create ZIP with all files + String bookTitle = bookEntity.getMetadata() != null && bookEntity.getMetadata().getTitle() != null + ? bookEntity.getMetadata().getTitle() + : "book-" + bookId; + String safeTitle = bookTitle.replaceAll("[^a-zA-Z0-9\\-_]", "_"); + String zipFileName = safeTitle + ".zip"; + + response.setContentType("application/zip"); + String encodedFilename = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replace("+", "%20"); + String fallbackFilename = NON_ASCII_PATTERN.matcher(zipFileName).replaceAll("_"); + String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", + fallbackFilename, encodedFilename); + response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); + + try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) { + for (BookFileEntity bookFile : allFiles) { + Path filePath = bookFile.getFullFilePath(); + + if (!Files.exists(filePath)) { + log.warn("Skipping missing file during ZIP creation: {}", filePath); + continue; + } + + // Handle folder-based audiobooks - add all files from the folder + if (bookFile.isFolderBased() && Files.isDirectory(filePath)) { + String folderPrefix = bookFile.getFileName() + "/"; + List audioFiles = Files.list(filePath) + .filter(Files::isRegularFile) + .sorted(Comparator.comparing(p -> p.getFileName().toString())) + .toList(); + + for (Path audioFile : audioFiles) { + String entryName = folderPrefix + audioFile.getFileName().toString(); + ZipEntry zipEntry = new ZipEntry(entryName); + zipEntry.setSize(Files.size(audioFile)); + zos.putNextEntry(zipEntry); + + try (InputStream fis = Files.newInputStream(audioFile)) { + fis.transferTo(zos); + } + + zos.closeEntry(); + } + } else { + // Regular file + ZipEntry zipEntry = new ZipEntry(bookFile.getFileName()); + zipEntry.setSize(Files.size(filePath)); + zos.putNextEntry(zipEntry); + + try (InputStream fis = Files.newInputStream(filePath)) { + fis.transferTo(zos); + } + + zos.closeEntry(); + } + } + zos.finish(); + response.getOutputStream().flush(); + + log.info("Successfully created and streamed ZIP for book {} with {} files", bookId, allFiles.size()); + } catch (IOException e) { + log.error("Failed to create ZIP for book {}: {}", bookId, e.getMessage(), e); + throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); + } + } + public void downloadKoboBook(Long bookId, HttpServletResponse response) { BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - + var primaryFile = bookEntity.getPrimaryBookFile(); + if (primaryFile == null) { + throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); + } boolean isEpub = primaryFile.getBookType() == BookFileType.EPUB; boolean isCbx = primaryFile.getBookType() == BookFileType.CBX; @@ -157,4 +317,41 @@ public class BookDownloadService { } } } + + private ResponseEntity downloadFolderAsZip(Path folderPath, String folderName) throws IOException { + java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); + + try (ZipOutputStream zos = new ZipOutputStream(baos)) { + // Get all files in the folder, sorted by name + List files = Files.list(folderPath) + .filter(Files::isRegularFile) + .sorted(Comparator.comparing(p -> p.getFileName().toString())) + .toList(); + + for (Path audioFile : files) { + ZipEntry entry = new ZipEntry(audioFile.getFileName().toString()); + zos.putNextEntry(entry); + Files.copy(audioFile, zos); + zos.closeEntry(); + } + } + + byte[] zipBytes = baos.toByteArray(); + Resource resource = new org.springframework.core.io.ByteArrayResource(zipBytes); + + String zipFileName = folderName + ".zip"; + String encodedFilename = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replace("+", "%20"); + String fallbackFilename = NON_ASCII_PATTERN.matcher(zipFileName).replaceAll("_"); + String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", + fallbackFilename, encodedFilename); + + return ResponseEntity.ok() + .contentType(MediaType.valueOf("application/zip")) + .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) + .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(zipBytes.length)) + .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") + .header(HttpHeaders.PRAGMA, "no-cache") + .header(HttpHeaders.EXPIRES, "0") + .body(resource); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookFileAttachmentService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookFileAttachmentService.java new file mode 100644 index 000000000..e39f0b25b --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookFileAttachmentService.java @@ -0,0 +1,400 @@ +package com.adityachandel.booklore.service.book; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.exception.ApiError; +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.entity.UserBookFileProgressEntity; +import com.adityachandel.booklore.model.entity.UserBookProgressEntity; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.repository.UserBookProgressRepository; +import com.adityachandel.booklore.service.file.FileMoveHelper; +import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; +import com.adityachandel.booklore.service.progress.ReadingProgressService; +import com.adityachandel.booklore.util.PathPatternResolver; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.stream.Collectors; + +@Slf4j +@RequiredArgsConstructor +@Service +public class BookFileAttachmentService { + + private final BookRepository bookRepository; + private final UserBookProgressRepository userBookProgressRepository; + private final AuthenticationService authenticationService; + private final ReadingProgressService readingProgressService; + private final MonitoringRegistrationService monitoringRegistrationService; + private final FileMoveHelper fileMoveHelper; + private final BookMapper bookMapper; + private final BookService bookService; + + @Transactional + public Book attachBookFiles(Long targetBookId, List sourceBookIds, boolean deleteSourceBooks) { + BookEntity targetBook = bookRepository.findByIdWithBookFiles(targetBookId) + .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(targetBookId)); + + // Validate and deduplicate source book IDs + Set uniqueSourceBookIds = new LinkedHashSet<>(sourceBookIds); // Preserves order, removes duplicates + if (uniqueSourceBookIds.contains(targetBookId)) { + throw ApiError.GENERIC_BAD_REQUEST.createException("Cannot attach a book to itself"); + } + + // Load all source books upfront to avoid Hibernate auto-flush issues when loading inside loop + List sourceBooks = new ArrayList<>(); + for (Long sourceBookId : uniqueSourceBookIds) { + BookEntity sourceBook = bookRepository.findByIdWithBookFiles(sourceBookId) + .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(sourceBookId)); + sourceBooks.add(sourceBook); + } + + // === VALIDATION PHASE - Do all validation BEFORE any file operations === + + // Validate target has a primary file + BookFileEntity targetPrimaryFile = targetBook.getBookFiles().stream() + .filter(BookFileEntity::isBookFormat) + .findFirst() + .orElseThrow(() -> ApiError.GENERIC_BAD_REQUEST.createException("Target book has no primary file")); + + // Validate all source books upfront + for (BookEntity sourceBook : sourceBooks) { + // Validate same library + if (!targetBook.getLibrary().getId().equals(sourceBook.getLibrary().getId())) { + throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " must be in the same library as target"); + } + + // Validate source has exactly 1 book format file + List sourceBookFiles = sourceBook.getBookFiles().stream() + .filter(BookFileEntity::isBookFormat) + .collect(Collectors.toList()); + + if (sourceBookFiles.isEmpty()) { + throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " has no book format files to attach"); + } + + if (sourceBookFiles.size() > 1) { + throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " has multiple book format files. Only single-file books can be attached."); + } + + BookFileEntity fileToMove = sourceBookFiles.get(0); + + // Validate not folder-based + if (fileToMove.isFolderBased()) { + throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " is a folder-based audiobook. Folder-based books cannot be attached."); + } + + // Validate source file exists + Path sourceFilePath = fileToMove.getFullFilePath(); + if (!Files.exists(sourceFilePath)) { + throw ApiError.GENERIC_BAD_REQUEST.createException( + "Source file not found at expected location: " + sourceFilePath + + ". The file may have been moved, deleted, or the database record is out of sync."); + } + } + + // === SETUP PHASE - Calculate paths and naming === + + // Get file naming pattern and determine if primary file is at pattern location + String fileNamingPattern = fileMoveHelper.getFileNamingPattern(targetBook.getLibrary()); + String patternResolvedPath = PathPatternResolver.resolvePattern(targetBook, targetPrimaryFile, fileNamingPattern); + Path libraryRootPath = Paths.get(targetBook.getLibraryPath().getPath()); + Path patternFullPath = libraryRootPath.resolve(patternResolvedPath); + + // Check if primary file is at the pattern location + Path actualPrimaryFilePath = targetPrimaryFile.getFullFilePath(); + boolean primaryFileAtPatternLocation = Files.exists(patternFullPath) && + patternFullPath.normalize().equals(actualPrimaryFilePath.normalize()); + + // Determine target directory - use pattern directory, fallback to library root if pattern has no directory + Path targetDirectory = patternFullPath.getParent(); + if (targetDirectory == null) { + // Pattern resolved to just a filename with no directory structure + targetDirectory = libraryRootPath; + } + String targetFileSubPath = libraryRootPath.equals(targetDirectory) + ? "" + : libraryRootPath.relativize(targetDirectory).toString(); + + // Use pattern-resolved filename (without extension) as base + String patternFileName = Paths.get(patternResolvedPath).getFileName().toString(); + int lastDot = patternFileName.lastIndexOf('.'); + String baseFileName = lastDot > 0 ? patternFileName.substring(0, lastDot) : patternFileName; + + // Validate target primary file exists (if not at pattern location) + if (!primaryFileAtPatternLocation && !Files.exists(actualPrimaryFilePath)) { + throw ApiError.GENERIC_BAD_REQUEST.createException( + "Target book's primary file not found at expected location: " + actualPrimaryFilePath + + ". Please ensure the target book's files exist before attaching files."); + } + + // === FILE OPERATION PHASE - All file operations inside try-finally for monitoring cleanup === + + Long libraryId = targetBook.getLibrary().getId(); + List sourceBooksToDelete = new ArrayList<>(); + List sourceDirectoriesToCleanup = new ArrayList<>(); + Set pathsToReregister = new HashSet<>(); + + try { + // Unregister target directory from monitoring + try { + monitoringRegistrationService.unregisterSpecificPath(targetDirectory); + } catch (Exception ex) { + log.warn("Failed to unregister target directory from monitoring: {}", targetDirectory, ex); + } + pathsToReregister.add(targetDirectory); + + // If primary file is NOT at pattern location, move all existing target book files there first + if (!primaryFileAtPatternLocation) { + log.info("Primary file not at pattern location, organizing target book files first"); + + // Unregister source directories for existing files + for (BookFileEntity existingFile : targetBook.getBookFiles()) { + Path currentPath = existingFile.getFullFilePath(); + if (Files.exists(currentPath)) { + Path sourceDir = currentPath.getParent(); + if (sourceDir != null) { + try { + monitoringRegistrationService.unregisterSpecificPath(sourceDir); + } catch (Exception ex) { + log.warn("Failed to unregister source directory from monitoring: {}", sourceDir, ex); + } + pathsToReregister.add(sourceDir); + sourceDirectoriesToCleanup.add(sourceDir); + } + } + } + + // Create target directory if needed + try { + Files.createDirectories(targetDirectory); + } catch (IOException e) { + throw ApiError.INTERNAL_SERVER_ERROR.createException("Failed to create target directory: " + e.getMessage()); + } + + // Move all existing target book files to pattern location + for (BookFileEntity existingFile : targetBook.getBookFiles()) { + Path currentPath = existingFile.getFullFilePath(); + if (!Files.exists(currentPath)) { + log.warn("Skipping missing file during organization: {}", currentPath); + continue; + } + + // Generate pattern-resolved filename for this file + String resolvedPath = PathPatternResolver.resolvePattern(targetBook, existingFile, fileNamingPattern); + String newFileName = Paths.get(resolvedPath).getFileName().toString(); + + // Resolve conflicts if file already exists at destination + newFileName = resolveFilenameConflict(targetDirectory, newFileName); + Path destinationPath = targetDirectory.resolve(newFileName); + + if (!currentPath.normalize().equals(destinationPath.normalize())) { + try { + Files.move(currentPath, destinationPath); + log.info("Organized file from {} to {}", currentPath, destinationPath); + + // Update database record + existingFile.setFileSubPath(targetFileSubPath); + existingFile.setFileName(newFileName); + } catch (IOException e) { + throw ApiError.INTERNAL_SERVER_ERROR.createException( + "Failed to organize file " + currentPath + ": " + e.getMessage()); + } + } + } + } + + // Track extension counts for handling same-extension conflicts + // Initialize with existing extensions in target book + Map extensionCounts = new HashMap<>(); + for (BookFileEntity existingFile : targetBook.getBookFiles()) { + if (existingFile.isBookFormat()) { + String ext = getFileExtension(existingFile.getFileName()).toLowerCase(); + extensionCounts.merge(ext, 1, Integer::sum); + } + } + + // Process each source book + for (BookEntity sourceBook : sourceBooks) { + BookFileEntity fileToMove = sourceBook.getBookFiles().stream() + .filter(BookFileEntity::isBookFormat) + .findFirst() + .orElseThrow(); // Already validated above + + Path sourceFilePath = fileToMove.getFullFilePath(); + Path sourceDirectory = sourceFilePath.getParent(); + + // Unregister source directory from monitoring to prevent spurious DELETE events + if (sourceDirectory != null) { + try { + monitoringRegistrationService.unregisterSpecificPath(sourceDirectory); + } catch (Exception ex) { + log.warn("Failed to unregister source directory from monitoring: {}", sourceDirectory, ex); + } + pathsToReregister.add(sourceDirectory); + } + + // Generate new filename using the base name determined earlier (from pattern or actual primary file) + String extension = getFileExtension(fileToMove.getFileName()).toLowerCase(); + + // Handle same-extension conflicts by adding suffix (_1, _2, etc.) + int existingCount = extensionCounts.getOrDefault(extension, 0); + String newFileName; + if (extension.isEmpty()) { + // File has no extension + newFileName = existingCount > 0 + ? baseFileName + "_" + existingCount + : baseFileName; + } else { + newFileName = existingCount > 0 + ? baseFileName + "_" + existingCount + "." + extension + : baseFileName + "." + extension; + } + extensionCounts.merge(extension, 1, Integer::sum); + + // Final conflict check against filesystem (in case of external files) + newFileName = resolveFilenameConflict(targetDirectory, newFileName); + + // Move the physical file + Path destinationPath = targetDirectory.resolve(newFileName); + try { + Files.move(sourceFilePath, destinationPath); + log.info("Moved file from {} to {}", sourceFilePath, destinationPath); + } catch (IOException e) { + log.error("Failed to move file from {} to {}", sourceFilePath, destinationPath, e); + throw ApiError.INTERNAL_SERVER_ERROR.createException("Failed to move file: " + e.getMessage()); + } + + // Update file entity with new path info - properly manage bidirectional relationship + fileToMove.setFileSubPath(targetFileSubPath); + fileToMove.setFileName(newFileName); + + // Remove from source book's collection and add to target's collection + sourceBook.getBookFiles().remove(fileToMove); + fileToMove.setBook(targetBook); + targetBook.getBookFiles().add(fileToMove); + + // Track source directory for cleanup + if (sourceDirectory != null) { + sourceDirectoriesToCleanup.add(sourceDirectory); + } + + // Track source book for deletion if requested + if (deleteSourceBooks) { + long remainingBookFiles = sourceBook.getBookFiles().stream() + .filter(BookFileEntity::isBookFormat) + .count(); + + if (remainingBookFiles == 0) { + sourceBooksToDelete.add(sourceBook); + } + } + } + + // Delete source books after all files are moved + if (!sourceBooksToDelete.isEmpty()) { + bookRepository.deleteAll(sourceBooksToDelete); + } + + // Cleanup empty source directories + Set libraryRoots = targetBook.getLibrary().getLibraryPaths().stream() + .map(LibraryPathEntity::getPath) + .map(Paths::get) + .map(Path::normalize) + .collect(Collectors.toSet()); + + for (Path sourceDir : sourceDirectoriesToCleanup) { + bookService.deleteEmptyParentDirsUpToLibraryFolders(sourceDir, libraryRoots); + } + } finally { + // Re-register paths for monitoring (only if they still exist) + for (Path path : pathsToReregister) { + if (Files.exists(path) && Files.isDirectory(path)) { + try { + monitoringRegistrationService.registerSpecificPath(path, libraryId); + } catch (Exception ex) { + log.warn("Failed to re-register path for monitoring: {}", path, ex); + } + } + } + } + + // Return updated target book + return getUpdatedBook(targetBookId); + } + + private Book getUpdatedBook(Long bookId) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + BookEntity refreshedTarget = bookRepository.findByIdWithBookFiles(bookId) + .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookId) + .orElse(new UserBookProgressEntity()); + UserBookFileProgressEntity fileProgress = readingProgressService + .fetchUserFileProgress(user.getId(), Set.of(bookId)) + .get(bookId); + + Book book = bookMapper.toBook(refreshedTarget); + book.setShelves(bookService.filterShelvesByUserId(book.getShelves(), user.getId())); + readingProgressService.enrichBookWithProgress(book, userProgress, fileProgress); + + return book; + } + + private String resolveFilenameConflict(Path targetDirectory, String originalFileName) { + Path targetPath = targetDirectory.resolve(originalFileName); + if (!Files.exists(targetPath)) { + return originalFileName; + } + + // Extract base name and extension + String baseName; + String extension; + int lastDotIndex = originalFileName.lastIndexOf('.'); + if (lastDotIndex > 0) { + baseName = originalFileName.substring(0, lastDotIndex); + extension = originalFileName.substring(lastDotIndex); + } else { + baseName = originalFileName; + extension = ""; + } + + // Try with incrementing suffix + int counter = 1; + String newFileName; + do { + newFileName = baseName + "_" + counter + extension; + targetPath = targetDirectory.resolve(newFileName); + counter++; + } while (Files.exists(targetPath) && counter < 1000); + + if (counter >= 1000) { + throw ApiError.GENERIC_BAD_REQUEST.createException("Could not resolve filename conflict for: " + originalFileName); + } + + return newFileName; + } + + private String getFileExtension(String fileName) { + if (fileName == null || fileName.isEmpty()) { + return ""; + } + int lastDotIndex = fileName.lastIndexOf('.'); + if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) { + return fileName.substring(lastDotIndex + 1); + } + return ""; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookMarkService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookMarkService.java index ca018e331..f0c71b357 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookMarkService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookMarkService.java @@ -52,10 +52,18 @@ public class BookMarkService { @Transactional public BookMark createBookmark(CreateBookMarkRequest request) { Long userId = getCurrentUserId(); - validateNoDuplicateBookmark(request.getCfi(), request.getBookId(), userId); + + // Validate no duplicate based on bookmark type + if (request.isAudiobookBookmark()) { + validateNoDuplicateAudiobookBookmark(request.getPositionMs(), request.getTrackIndex(), request.getBookId(), userId); + } else if (request.getCfi() != null) { + validateNoDuplicateBookmark(request.getCfi(), request.getBookId(), userId); + } BookMarkEntity bookmark = BookMarkEntity.builder() .cfi(request.getCfi()) + .positionMs(request.getPositionMs()) + .trackIndex(request.getTrackIndex()) .title(request.getTitle()) .book(findBook(request.getBookId())) .user(findUser(userId)) @@ -126,6 +134,16 @@ public class BookMarkService { } } + /** + * Validate no duplicate audiobook bookmark exists within 5 seconds of the position. + */ + private void validateNoDuplicateAudiobookBookmark(Long positionMs, Integer trackIndex, Long bookId, Long userId) { + boolean exists = bookMarkRepository.existsByPositionMsNearAndBookIdAndUserId(positionMs, trackIndex, bookId, userId); + if (exists) { + throw new APIException("A bookmark already exists near this position", HttpStatus.CONFLICT); + } + } + private void applyUpdates(BookMarkEntity bookmark, UpdateBookMarkRequest request) { Optional.ofNullable(request.getTitle()).ifPresent(bookmark::setTitle); Optional.ofNullable(request.getCfi()).ifPresent(bookmark::setCfi); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java index 13bdeff65..a41a598d9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java @@ -8,15 +8,19 @@ import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; import com.adityachandel.booklore.model.dto.response.BookDeletionResponse; import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse; import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.entity.UserBookFileProgressEntity; import com.adityachandel.booklore.model.entity.UserBookProgressEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.*; +import com.adityachandel.booklore.repository.BookFileRepository; import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; -import com.adityachandel.booklore.service.user.UserProgressService; -import com.adityachandel.booklore.util.BookProgressUtil; +import com.adityachandel.booklore.service.progress.ReadingProgressService; import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileUtils; +import jakarta.servlet.http.HttpServletResponse; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.ByteArrayResource; @@ -45,6 +49,7 @@ import java.util.stream.Collectors; public class BookService { private final BookRepository bookRepository; + private final BookFileRepository bookFileRepository; private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository; private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository; private final NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository; @@ -53,7 +58,7 @@ public class BookService { private final UserBookProgressRepository userBookProgressRepository; private final AuthenticationService authenticationService; private final BookQueryService bookQueryService; - private final UserProgressService userProgressService; + private final ReadingProgressService readingProgressService; private final BookDownloadService bookDownloadService; private final MonitoringRegistrationService monitoringRegistrationService; private final BookUpdateService bookUpdateService; @@ -74,14 +79,18 @@ public class BookService { user.getId() ); + Set bookIds = books.stream().map(Book::getId).collect(Collectors.toSet()); Map progressMap = - userProgressService.fetchUserProgress( - user.getId(), - books.stream().map(Book::getId).collect(Collectors.toSet()) - ); + readingProgressService.fetchUserProgress(user.getId(), bookIds); + Map fileProgressMap = + readingProgressService.fetchUserFileProgress(user.getId(), bookIds); books.forEach(book -> { - BookProgressUtil.enrichBookWithProgress(book, progressMap.get(book.getId())); + readingProgressService.enrichBookWithProgress( + book, + progressMap.get(book.getId()), + fileProgressMap.get(book.getId()) + ); book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId())); }); @@ -92,15 +101,21 @@ public class BookService { BookLoreUser user = authenticationService.getAuthenticatedUser(); List bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds); + Set entityIds = bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet()); - Map progressMap = userProgressService.fetchUserProgress( - user.getId(), bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet())); + Map progressMap = + readingProgressService.fetchUserProgress(user.getId(), entityIds); + Map fileProgressMap = + readingProgressService.fetchUserFileProgress(user.getId(), entityIds); return bookEntities.stream().map(bookEntity -> { Book book = bookMapper.toBook(bookEntity); - book.setFilePath(FileUtils.getBookFullPath(bookEntity)); if (!withDescription) book.getMetadata().setDescription(null); - BookProgressUtil.enrichBookWithProgress(book, progressMap.get(bookEntity.getId())); + readingProgressService.enrichBookWithProgress( + book, + progressMap.get(bookEntity.getId()), + fileProgressMap.get(bookEntity.getId()) + ); return book; }).collect(Collectors.toList()); } @@ -109,13 +124,17 @@ public class BookService { BookLoreUser user = authenticationService.getAuthenticatedUser(); BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookId).orElse(new UserBookProgressEntity()); + UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookId) + .orElse(new UserBookProgressEntity()); + + // Fetch file-level progress for the book (most recent across all files) + UserBookFileProgressEntity fileProgress = readingProgressService + .fetchUserFileProgress(user.getId(), Set.of(bookId)) + .get(bookId); Book book = bookMapper.toBook(bookEntity); book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId())); - book.setLastReadTime(userProgress.getLastReadTime()); - BookProgressUtil.enrichBookWithProgress(book, userProgress); - book.setFilePath(FileUtils.getBookFullPath(bookEntity)); + readingProgressService.enrichBookWithProgress(book, userProgress, fileProgress); if (!withDescription) { book.getMetadata().setDescription(null); @@ -125,13 +144,17 @@ public class BookService { } - public BookViewerSettings getBookViewerSetting(long bookId) { + public BookViewerSettings getBookViewerSetting(long bookId, long bookFileId) { BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); BookLoreUser user = authenticationService.getAuthenticatedUser(); BookViewerSettings.BookViewerSettingsBuilder settingsBuilder = BookViewerSettings.builder(); - BookFileType bookType = bookEntity.getPrimaryBookFile().getBookType(); + BookFileEntity bookFile = bookEntity.getBookFiles().stream() + .filter(bf -> bf.getId().equals(bookFileId)) + .findFirst() + .orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book file not found: " + bookFileId)); + BookFileType bookType = bookFile.getBookType(); if (bookType == BookFileType.EPUB || bookType == BookFileType.FB2 || bookType == BookFileType.MOBI || bookType == BookFileType.AZW3) { @@ -190,7 +213,7 @@ public class BookService { @Transactional public void updateReadProgress(ReadProgressRequest request) { - bookUpdateService.updateReadProgress(request); + readingProgressService.updateReadProgress(request); } @Transactional @@ -239,9 +262,28 @@ public class BookService { return bookDownloadService.downloadBook(bookId); } + public void downloadAllBookFiles(Long bookId, HttpServletResponse response) { + bookDownloadService.downloadAllBookFiles(bookId, response); + } + public ResponseEntity getBookContent(long bookId) throws IOException { + return getBookContent(bookId, null); + } + + public ResponseEntity getBookContent(long bookId, String bookType) throws IOException { BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - try (FileInputStream inputStream = new FileInputStream(FileUtils.getBookFullPath(bookEntity))) { + String filePath; + if (bookType != null) { + BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase()); + BookFileEntity bookFile = bookEntity.getBookFiles().stream() + .filter(bf -> bf.getBookType() == requestedType) + .findFirst() + .orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("No file of type " + bookType + " found for book")); + filePath = bookFile.getFullFilePath().toString(); + } else { + filePath = FileUtils.getBookFullPath(bookEntity); + } + try (FileInputStream inputStream = new FileInputStream(filePath)) { return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(new ByteArrayResource(inputStream.readAllBytes())); @@ -253,8 +295,8 @@ public class BookService { List books = bookQueryService.findAllWithMetadataByIds(ids); List failedFileDeletions = new ArrayList<>(); for (BookEntity book : books) { - List fullFilePaths = book.getFullFilePaths(); - for (Path fullFilePath : fullFilePaths) { + for (BookFileEntity bookFile : book.getBookFiles()) { + Path fullFilePath = bookFile.getFullFilePath(); try { if (Files.exists(fullFilePath)) { try { @@ -262,8 +304,15 @@ public class BookService { } catch (Exception ex) { log.warn("Failed to unregister monitoring for path: {}", fullFilePath.getParent(), ex); } - Files.delete(fullFilePath); - log.info("Deleted book file: {}", fullFilePath); + + // Handle folder-based audiobooks (delete directory recursively) + if (bookFile.isFolderBased() && Files.isDirectory(fullFilePath)) { + deleteDirectoryRecursively(fullFilePath); + log.info("Deleted folder-based audiobook: {}", fullFilePath); + } else { + Files.delete(fullFilePath); + log.info("Deleted book file: {}", fullFilePath); + } Set libraryRoots = book.getLibrary().getLibraryPaths().stream() .map(LibraryPathEntity::getPath) @@ -289,6 +338,16 @@ public class BookService { : ResponseEntity.status(HttpStatus.MULTI_STATUS).body(response); } + private void deleteDirectoryRecursively(Path path) throws IOException { + if (!Files.exists(path)) return; + + try (var walk = Files.walk(path)) { + walk.sorted(java.util.Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(java.io.File::delete); + } + } + public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set libraryRoots) { Path dir = currentDir; Set ignoredFilenames = Set.of(".DS_Store", "Thumbs.db"); @@ -355,11 +414,12 @@ public class BookService { } } - private Set filterShelvesByUserId(Set shelves, Long userId) { + public Set filterShelvesByUserId(Set shelves, Long userId) { if (shelves == null) return Collections.emptySet(); return shelves.stream() .filter(shelf -> userId.equals(shelf.getUserId())) .collect(Collectors.toSet()); } + } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookUpdateService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookUpdateService.java index 18552d9f9..fb29f9d61 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookUpdateService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookUpdateService.java @@ -4,22 +4,14 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.mapper.BookMapper; import com.adityachandel.booklore.model.dto.*; -import com.adityachandel.booklore.model.dto.progress.CbxProgress; -import com.adityachandel.booklore.model.dto.progress.EpubProgress; -import com.adityachandel.booklore.model.dto.progress.PdfProgress; -import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse; import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse; import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.ReadStatus; -import com.adityachandel.booklore.model.enums.ResetProgressType; import com.adityachandel.booklore.model.enums.UserPermission; import com.adityachandel.booklore.repository.*; -import com.adityachandel.booklore.service.kobo.KoboReadingStateService; -import com.adityachandel.booklore.service.user.UserProgressService; -import com.adityachandel.booklore.util.BookProgressUtil; -import com.adityachandel.booklore.util.FileUtils; +import com.adityachandel.booklore.service.progress.ReadingProgressService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.EnumUtils; @@ -36,9 +28,6 @@ import java.util.stream.Collectors; @Service public class BookUpdateService { - private static final float READING_THRESHOLD = 0.5f; - private static final float COMPLETED_THRESHOLD = 99.5f; - private final BookRepository bookRepository; private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository; private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository; @@ -49,17 +38,17 @@ public class BookUpdateService { private final UserBookProgressRepository userBookProgressRepository; private final AuthenticationService authenticationService; private final BookQueryService bookQueryService; - private final UserProgressService userProgressService; - private final KoboReadingStateService koboReadingStateService; + private final ReadingProgressService readingProgressService; private final EbookViewerPreferenceRepository ebookViewerPreferenceRepository; public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) { BookEntity book = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); BookLoreUser user = authenticationService.getAuthenticatedUser(); - if (book.getPrimaryBookFile().getBookType() == null) { + var primaryFile = book.getPrimaryBookFile(); + if (primaryFile == null || primaryFile.getBookType() == null) { throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(); } - switch (book.getPrimaryBookFile().getBookType()) { + switch (primaryFile.getBookType()) { case PDF -> updatePdfViewerSettings(bookId, user.getId(), bookViewerSettings); case EPUB, FB2, MOBI, AZW3 -> updateEbookViewerSettings(bookId, user.getId(), bookViewerSettings); case CBX -> updateCbxViewerSettings(bookId, user.getId(), bookViewerSettings); @@ -67,32 +56,6 @@ public class BookUpdateService { } } - @Transactional - public void updateReadProgress(ReadProgressRequest request) { - BookEntity book = bookRepository.findByIdWithBookFiles(request.getBookId()).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId())); - BookLoreUser user = authenticationService.getAuthenticatedUser(); - - UserBookProgressEntity progress = userBookProgressRepository - .findByUserIdAndBookId(user.getId(), book.getId()) - .orElseGet(UserBookProgressEntity::new); - - BookLoreUserEntity userEntity = findUserOrThrow(user.getId()); - progress.setUser(userEntity); - progress.setBook(book); - progress.setLastReadTime(Instant.now()); - - Float percentage = updateProgressByBookType(progress, book.getPrimaryBookFile().getBookType(), request); - if (percentage != null) { - progress.setReadStatus(calculateReadStatus(percentage)); - setProgressPercent(progress, book.getPrimaryBookFile().getBookType(), percentage); - } - if (request.getDateFinished() != null) { - progress.setDateFinished(request.getDateFinished()); - } - - userBookProgressRepository.save(progress); - } - @Transactional public List updateReadStatus(List bookIds, String status) { BookLoreUser user = authenticationService.getAuthenticatedUser(); @@ -110,21 +73,6 @@ public class BookUpdateService { return buildStatusUpdateResponses(bookIds, readStatus, now, dateFinished); } - @Transactional - public List resetProgress(List bookIds, ResetProgressType type) { - BookLoreUser user = authenticationService.getAuthenticatedUser(); - validateResetPermission(bookIds, user, type); - - Set existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds); - Instant now = Instant.now(); - - if (!existingProgressBookIds.isEmpty()) { - performReset(user.getId(), existingProgressBookIds, type, now); - } - - return buildResetResponses(bookIds, existingProgressBookIds, now); - } - @Transactional public List updatePersonalRating(List bookIds, Integer rating) { BookLoreUser user = authenticationService.getAuthenticatedUser(); @@ -267,40 +215,6 @@ public class BookUpdateService { )); } - private Float updateProgressByBookType(UserBookProgressEntity progress, BookFileType bookType, ReadProgressRequest request) { - return switch (bookType) { - case EPUB, FB2, MOBI, AZW3 -> updateEbookProgress(progress, request.getEpubProgress()); - case PDF -> updatePdfProgress(progress, request.getPdfProgress()); - case CBX -> updateCbxProgress(progress, request.getCbxProgress()); - }; - } - - private Float updateEbookProgress(UserBookProgressEntity progress, EpubProgress epubProgress) { - if (epubProgress == null) return null; - - progress.setEpubProgress(epubProgress.getCfi()); - progress.setEpubProgressHref(epubProgress.getHref()); - - float percentage = epubProgress.getPercentage(); - return Math.round(percentage * 10f) / 10f; - } - - private Float updatePdfProgress(UserBookProgressEntity progress, PdfProgress pdfProgress) { - if (pdfProgress == null) return null; - - progress.setPdfProgress(pdfProgress.getPage()); - float percentage = pdfProgress.getPercentage(); - return Math.round(percentage * 10f) / 10f; - } - - private Float updateCbxProgress(UserBookProgressEntity progress, CbxProgress cbxProgress) { - if (cbxProgress == null) return null; - - progress.setCbxProgress(cbxProgress.getPage()); - float percentage = cbxProgress.getPercentage(); - return Math.round(percentage * 10f) / 10f; - } - private void updateExistingProgress(Long userId, Set bookIds, ReadStatus status, Instant now, Instant dateFinished) { if (!bookIds.isEmpty()) { userBookProgressRepository.bulkUpdateReadStatus(userId, new ArrayList<>(bookIds), status, now, dateFinished); @@ -336,19 +250,6 @@ public class BookUpdateService { return progress; } - private void performReset(Long userId, Set bookIds, ResetProgressType type, Instant now) { - List bookIdList = new ArrayList<>(bookIds); - - switch (type) { - case BOOKLORE -> userBookProgressRepository.bulkResetBookloreProgress(userId, bookIdList, now); - case KOREADER -> userBookProgressRepository.bulkResetKoreaderProgress(userId, bookIdList); - case KOBO -> { - userBookProgressRepository.bulkResetKoboProgress(userId, bookIdList); - bookIds.forEach(koboReadingStateService::deleteReadingState); - } - } - } - private void createProgressForRating(Long userId, List allBookIds, Set existingBookIds, Integer rating) { Set newProgressBookIds = allBookIds.stream() .filter(id -> !existingBookIds.contains(id)) @@ -398,18 +299,24 @@ public class BookUpdateService { private List buildBooksWithProgress(List bookEntities, Long userId) { Set bookIds = bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet()); - Map progressMap = userProgressService.fetchUserProgress(userId, bookIds); + Map progressMap = readingProgressService.fetchUserProgress(userId, bookIds); + Map fileProgressMap = readingProgressService.fetchUserFileProgress(userId, bookIds); return bookEntities.stream() - .map(bookEntity -> buildBook(bookEntity, userId, progressMap)) + .map(bookEntity -> buildBook(bookEntity, userId, progressMap, fileProgressMap)) .collect(Collectors.toList()); } - private Book buildBook(BookEntity bookEntity, Long userId, Map progressMap) { + private Book buildBook(BookEntity bookEntity, Long userId, + Map progressMap, + Map fileProgressMap) { Book book = bookMapper.toBook(bookEntity); book.setShelves(filterShelvesByUserId(book.getShelves(), userId)); - book.setFilePath(FileUtils.getBookFullPath(bookEntity)); - BookProgressUtil.enrichBookWithProgress(book, progressMap.get(bookEntity.getId())); + readingProgressService.enrichBookWithProgress( + book, + progressMap.get(bookEntity.getId()), + fileProgressMap.get(bookEntity.getId()) + ); return book; } @@ -424,18 +331,6 @@ public class BookUpdateService { } } - private void validateResetPermission(List bookIds, BookLoreUser user, ResetProgressType type) { - if (bookIds.size() <= 1) return; - UserPermission permission = switch (type) { - case BOOKLORE -> UserPermission.CAN_BULK_RESET_BOOKLORE_READ_PROGRESS; - case KOREADER -> UserPermission.CAN_BULK_RESET_KOREADER_READ_PROGRESS; - default -> null; - }; - if (permission != null && !permission.isGranted(user.getPermissions())) { - throw ApiError.PERMISSION_DENIED.createException(permission); - } - } - private Set validateBooksAndGetExistingProgress(Long userId, List bookIds) { long existingBooksCount = bookRepository.countByIdIn(bookIds); if (existingBooksCount != bookIds.size()) { @@ -445,20 +340,6 @@ public class BookUpdateService { return userBookProgressRepository.findExistingProgressBookIds(userId, new HashSet<>(bookIds)); } - private void setProgressPercent(UserBookProgressEntity progress, BookFileType type, Float percentage) { - switch (type) { - case EPUB, FB2, MOBI, AZW3 -> progress.setEpubProgressPercent(percentage); - case PDF -> progress.setPdfProgressPercent(percentage); - case CBX -> progress.setCbxProgressPercent(percentage); - } - } - - private ReadStatus calculateReadStatus(Float percentage) { - if (percentage >= COMPLETED_THRESHOLD) return ReadStatus.READ; - if (percentage > READING_THRESHOLD) return ReadStatus.READING; - return ReadStatus.UNREAD; - } - private List buildStatusUpdateResponses(List bookIds, ReadStatus status, Instant now, Instant dateFinished) { return bookIds.stream() .map(bookId -> BookStatusUpdateResponse.builder() @@ -470,17 +351,6 @@ public class BookUpdateService { .collect(Collectors.toList()); } - private List buildResetResponses(List bookIds, Set existingBookIds, Instant now) { - return bookIds.stream() - .map(bookId -> BookStatusUpdateResponse.builder() - .bookId(bookId) - .readStatus(null) - .readStatusModifiedTime(existingBookIds.contains(bookId) ? now : null) - .dateFinished(null) - .build()) - .collect(Collectors.toList()); - } - private List buildRatingUpdateResponses(List bookIds, Integer rating) { return bookIds.stream() .map(bookId -> PersonalRatingUpdateResponse.builder() @@ -497,4 +367,3 @@ public class BookUpdateService { .collect(Collectors.toSet()); } } - diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/PhysicalBookService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/PhysicalBookService.java new file mode 100644 index 000000000..1258bc430 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/PhysicalBookService.java @@ -0,0 +1,138 @@ +package com.adityachandel.booklore.service.book; + +import com.adityachandel.booklore.exception.APIException; +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.request.CreatePhysicalBookRequest; +import com.adityachandel.booklore.model.entity.AuthorEntity; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookMetadataEntity; +import com.adityachandel.booklore.model.entity.CategoryEntity; +import com.adityachandel.booklore.model.entity.LibraryEntity; +import com.adityachandel.booklore.repository.AuthorRepository; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.repository.CategoryRepository; +import com.adityachandel.booklore.repository.LibraryRepository; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +@Slf4j +@Service +@AllArgsConstructor +public class PhysicalBookService { + + private final BookRepository bookRepository; + private final LibraryRepository libraryRepository; + private final AuthorRepository authorRepository; + private final CategoryRepository categoryRepository; + private final BookMapper bookMapper; + + @Transactional + public Book createPhysicalBook(CreatePhysicalBookRequest request) { + LibraryEntity library = libraryRepository.findById(request.getLibraryId()) + .orElseThrow(() -> new APIException("Library not found with id: " + request.getLibraryId(), HttpStatus.NOT_FOUND)); + + BookEntity bookEntity = BookEntity.builder() + .library(library) + .libraryPath(null) + .isPhysical(true) + .addedOn(Instant.now()) + .bookFiles(new ArrayList<>()) + .build(); + + BookMetadataEntity metadata = BookMetadataEntity.builder() + .book(bookEntity) + .title(request.getTitle()) + .description(request.getDescription()) + .publisher(request.getPublisher()) + .publishedDate(parsePublishedDate(request.getPublishedDate())) + .language(request.getLanguage()) + .pageCount(request.getPageCount()) + .isbn13(extractIsbn13(request.getIsbn())) + .isbn10(extractIsbn10(request.getIsbn())) + .build(); + + bookEntity.setMetadata(metadata); + + if (request.getAuthors() != null && !request.getAuthors().isEmpty()) { + addAuthorsToBook(new HashSet<>(request.getAuthors()), bookEntity); + } + + if (request.getCategories() != null && !request.getCategories().isEmpty()) { + addCategoriesToBook(new HashSet<>(request.getCategories()), bookEntity); + } + + BookEntity savedBook = bookRepository.save(bookEntity); + log.info("Created physical book '{}' in library {} with id {}", request.getTitle(), library.getName(), savedBook.getId()); + + return bookMapper.toBook(savedBook); + } + + private LocalDate parsePublishedDate(String publishedDate) { + if (publishedDate == null || publishedDate.isBlank()) { + return null; + } + String trimmed = publishedDate.trim(); + // Try full date format first (YYYY-MM-DD) + try { + return LocalDate.parse(trimmed, DateTimeFormatter.ISO_LOCAL_DATE); + } catch (DateTimeParseException ignored) {} + // Try year only format (YYYY) + try { + int year = Integer.parseInt(trimmed); + return LocalDate.of(year, 1, 1); + } catch (NumberFormatException ignored) {} + return null; + } + + private String extractIsbn13(String isbn) { + if (isbn == null) return null; + String cleaned = isbn.replaceAll("[^0-9X]", ""); + return cleaned.length() == 13 ? cleaned : null; + } + + private String extractIsbn10(String isbn) { + if (isbn == null) return null; + String cleaned = isbn.replaceAll("[^0-9X]", ""); + return cleaned.length() == 10 ? cleaned : null; + } + + private void addAuthorsToBook(Set authors, BookEntity bookEntity) { + if (bookEntity.getMetadata().getAuthors() == null) { + bookEntity.getMetadata().setAuthors(new HashSet<>()); + } + authors.stream() + .map(authorName -> truncate(authorName, 255)) + .map(authorName -> authorRepository.findByName(authorName) + .orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build()))) + .forEach(authorEntity -> bookEntity.getMetadata().getAuthors().add(authorEntity)); + bookEntity.getMetadata().updateSearchText(); + } + + private void addCategoriesToBook(Set categories, BookEntity bookEntity) { + if (bookEntity.getMetadata().getCategories() == null) { + bookEntity.getMetadata().setCategories(new HashSet<>()); + } + categories.stream() + .map(cat -> truncate(cat, 255)) + .map(truncated -> categoryRepository.findByName(truncated) + .orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(truncated).build()))) + .forEach(catEntity -> bookEntity.getMetadata().getCategories().add(catEntity)); + } + + private String truncate(String input, int maxLength) { + if (input == null) return null; + return input.length() <= maxLength ? input : input.substring(0, maxLength); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookdropMetadataService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookdropMetadataService.java index de1dc55a7..c4f3725de 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookdropMetadataService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookdropMetadataService.java @@ -2,6 +2,7 @@ package com.adityachandel.booklore.service.bookdrop; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.BookFile; import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions; import com.adityachandel.booklore.model.dto.settings.AppSettings; @@ -64,7 +65,7 @@ public class BookdropMetadataService { List providers = metadataRefreshService.prepareProviders(refreshOptions); Book book = Book.builder() - .fileName(entity.getFileName()) + .primaryFile(BookFile.builder().fileName(entity.getFileName()).build()) .metadata(initial) .build(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/event/BookEventBroadcaster.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/event/BookEventBroadcaster.java index 63bdb32d4..59bda8804 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/event/BookEventBroadcaster.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/event/BookEventBroadcaster.java @@ -25,7 +25,7 @@ public class BookEventBroadcaster { .forEach(u -> { String username = u.getUsername(); messagingTemplate.convertAndSendToUser(username, Topic.BOOK_ADD.getPath(), book); - messagingTemplate.convertAndSendToUser(username, Topic.LOG.getPath(), LogNotification.info("Book added: " + book.getFileName())); + messagingTemplate.convertAndSendToUser(username, Topic.LOG.getPath(), LogNotification.info("Book added: " + (book.getPrimaryFile() != null ? book.getPrimaryFile().getFileName() : "unknown"))); }); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/AdditionalFileService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/AdditionalFileService.java index 9545a43d7..7b1399a8e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/AdditionalFileService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/AdditionalFileService.java @@ -7,6 +7,7 @@ import com.adityachandel.booklore.repository.BookAdditionalFileRepository; import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; @@ -15,14 +16,18 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; @Slf4j @AllArgsConstructor @@ -57,8 +62,15 @@ public class AdditionalFileService { try { monitoringRegistrationService.unregisterSpecificPath(file.getFullFilePath().getParent()); - Files.deleteIfExists(file.getFullFilePath()); - log.info("Deleted additional file: {}", file.getFullFilePath()); + Path filePath = file.getFullFilePath(); + if (file.isFolderBased() && Files.isDirectory(filePath)) { + // For folder-based audiobooks, delete the entire directory + deleteDirectoryRecursively(filePath); + log.info("Deleted folder-based audiobook: {}", filePath); + } else { + Files.deleteIfExists(filePath); + log.info("Deleted additional file: {}", filePath); + } additionalFileRepository.delete(file); } catch (IOException e) { @@ -67,6 +79,16 @@ public class AdditionalFileService { } } + private void deleteDirectoryRecursively(Path path) throws IOException { + if (!Files.exists(path)) return; + + try (var walk = Files.walk(path)) { + walk.sorted(java.util.Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(java.io.File::delete); + } + } + public ResponseEntity downloadAdditionalFile(Long fileId) throws IOException { Optional fileOpt = additionalFileRepository.findById(fileId); if (fileOpt.isEmpty()) { @@ -80,6 +102,11 @@ public class AdditionalFileService { return ResponseEntity.notFound().build(); } + // Handle folder-based audiobooks - create a ZIP file + if (file.isFolderBased() && Files.isDirectory(filePath)) { + return downloadFolderAsZip(file, filePath); + } + Resource resource = new UrlResource(filePath.toUri()); String encodedFilename = URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8).replace("+", "%20"); @@ -91,4 +118,38 @@ public class AdditionalFileService { .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) .body(resource); } + + private ResponseEntity downloadFolderAsZip(BookFileEntity file, Path folderPath) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + try (ZipOutputStream zos = new ZipOutputStream(baos)) { + // Get all files in the folder, sorted by name + List files = Files.list(folderPath) + .filter(Files::isRegularFile) + .sorted(Comparator.comparing(p -> p.getFileName().toString())) + .toList(); + + for (Path audioFile : files) { + ZipEntry entry = new ZipEntry(audioFile.getFileName().toString()); + zos.putNextEntry(entry); + Files.copy(audioFile, zos); + zos.closeEntry(); + } + } + + byte[] zipBytes = baos.toByteArray(); + Resource resource = new ByteArrayResource(zipBytes); + + String zipFileName = file.getFileName() + ".zip"; + String encodedFilename = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replace("+", "%20"); + String fallbackFilename = NON_ASCII.matcher(zipFileName).replaceAll("_"); + String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", + fallbackFilename, encodedFilename); + + return ResponseEntity.ok() + .contentType(MediaType.valueOf("application/zip")) + .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) + .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(zipBytes.length)) + .body(resource); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileFingerprint.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileFingerprint.java index 72521cdbb..1a49b7145 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileFingerprint.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileFingerprint.java @@ -2,9 +2,12 @@ package com.adityachandel.booklore.service.file; import java.io.IOException; import java.io.RandomAccessFile; +import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Comparator; +import java.util.List; public class FileFingerprint { @@ -38,4 +41,52 @@ public class FileFingerprint { throw new RuntimeException("Failed to compute partial MD5 hash for: " + filePath, e); } } + + /** + * Generate a hash for a folder-based audiobook. + * Uses the first audio file's hash combined with the file count. + */ + public static String generateFolderHash(Path folderPath) { + try { + if (!Files.exists(folderPath) || !Files.isDirectory(folderPath)) { + throw new RuntimeException("Folder does not exist: " + folderPath); + } + + List audioFiles = Files.list(folderPath) + .filter(Files::isRegularFile) + .filter(p -> isAudioFile(p.getFileName().toString())) + .sorted(Comparator.comparing(p -> p.getFileName().toString())) + .toList(); + + if (audioFiles.isEmpty()) { + throw new RuntimeException("No audio files in folder: " + folderPath); + } + + // Hash first file and combine with file count for a representative hash + String firstFileHash = generateHash(audioFiles.getFirst()); + int fileCount = audioFiles.size(); + + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.update(firstFileHash.getBytes()); + md5.update(String.valueOf(fileCount).getBytes()); + + byte[] hash = md5.digest(); + StringBuilder result = new StringBuilder(hash.length * 2); + for (byte b : hash) { + result.append(String.format("%02x", b)); + } + return result.toString(); + + } catch (IOException | NoSuchAlgorithmException e) { + throw new RuntimeException("Failed to compute folder hash for: " + folderPath, e); + } + } + + private static boolean isAudioFile(String fileName) { + if (fileName == null) return false; + String lower = fileName.toLowerCase(); + return lower.endsWith(".mp3") || lower.endsWith(".m4a") || lower.endsWith(".m4b") + || lower.endsWith(".flac") || lower.endsWith(".ogg") || lower.endsWith(".opus") + || lower.endsWith(".aac"); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveHelper.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveHelper.java index d9f8f22b1..68cfadf51 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveHelper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveHelper.java @@ -56,6 +56,13 @@ public class FileMoveHelper { return false; } + public boolean validateSourceExists(Path sourcePath, boolean isFolderBased) { + if (isFolderBased) { + return Files.isDirectory(sourcePath); + } + return Files.exists(sourcePath); + } + public void moveFile(Path source, Path target) throws IOException { if (!waitForFileAccessible(source)) { throw new NoSuchFileException(source.toString(), null, "Source file not accessible after retries"); @@ -161,7 +168,7 @@ public class FileMoveHelper { } public Path generateNewFilePath(BookEntity book, BookFileEntity bookFile, LibraryPathEntity libraryPathEntity, String pattern) { - String newRelativePathStr = PathPatternResolver.resolvePattern(book, bookFile, pattern); + String newRelativePathStr = PathPatternResolver.resolvePattern(book, bookFile, pattern, bookFile.isFolderBased()); if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) { newRelativePathStr = newRelativePathStr.substring(1); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java index deaf46cb5..00bc849be 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java @@ -1,5 +1,6 @@ package com.adityachandel.booklore.service.file; +import com.adityachandel.booklore.config.AppProperties; import com.adityachandel.booklore.mapper.BookMapper; import com.adityachandel.booklore.mapper.LibraryMapper; import com.adityachandel.booklore.model.dto.FileMoveResult; @@ -31,6 +32,7 @@ public class FileMoveService { private static final long EVENT_DRAIN_TIMEOUT_MS = 300; + private final AppProperties appProperties; private final BookRepository bookRepository; private final BookAdditionalFileRepository bookFileRepository; private final LibraryRepository libraryRepository; @@ -45,10 +47,12 @@ public class FileMoveService { @Transactional public void bulkMoveFiles(FileMoveRequest request) { List moves = request.getMoves(); - + + validateLocalStorage(); + Set allAffectedLibraryIds = collectAllAffectedLibraryIds(moves); Set libraryPaths = monitoringRegistrationService.getPathsForLibraries(allAffectedLibraryIds); - + log.info("Unregistering {} libraries before bulk file move", allAffectedLibraryIds.size()); monitoringRegistrationService.unregisterLibraries(allAffectedLibraryIds); monitoringRegistrationService.waitForEventsDrainedByPaths(libraryPaths, EVENT_DRAIN_TIMEOUT_MS); @@ -133,6 +137,16 @@ public class FileMoveService { return; } + // Validate all source paths exist before attempting moves + for (var bookFile : bookEntity.getBookFiles()) { + Path sourcePath = bookFile.getFullFilePath(); + if (!fileMoveHelper.validateSourceExists(sourcePath, bookFile.isFolderBased())) { + log.warn("Source {} not found: bookId={}, path={}", + bookFile.isFolderBased() ? "folder" : "file", bookId, sourcePath); + return; + } + } + for (var bookFile : bookEntity.getBookFiles()) { Path sourcePath = bookFile.getFullFilePath(); Path targetPath; @@ -157,6 +171,13 @@ public class FileMoveService { return; } + // Commit file moves FIRST before updating database + for (PlannedMove planned : plannedMovesByBookFileId.values()) { + fileMoveHelper.commitMove(planned.temp(), planned.target()); + } + plannedMovesByBookFileId.clear(); + + // Only update database after all file commits succeed for (var bookFile : bookEntity.getBookFiles()) { String newFileName; if (bookFile.isBook()) { @@ -170,11 +191,6 @@ public class FileMoveService { bookRepository.updateLibrary(bookEntity.getId(), targetLibrary.getId(), libraryPathEntity); - for (PlannedMove planned : plannedMovesByBookFileId.values()) { - fileMoveHelper.commitMove(planned.temp(), planned.target()); - } - plannedMovesByBookFileId.clear(); - Path libraryRoot = Paths.get(libraryPathEntity.getPath()).toAbsolutePath().normalize(); for (Path sourceParent : sourceParentsToCleanup) { fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(sourceParent, Set.of(libraryRoot)); @@ -197,42 +213,124 @@ public class FileMoveService { @Transactional public FileMoveResult moveSingleFile(BookEntity bookEntity) { + record PlannedMove(Path source, Path temp, Path target) {} + + validateLocalStorage(); Long libraryId = bookEntity.getLibraryPath().getLibrary().getId(); Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize(); boolean isLibraryMonitoredWhenCalled = false; + Map plannedMovesByBookFileId = new HashMap<>(); + Set sourceParentsToCleanup = new HashSet<>(); try { Set existingPaths = monitoringRegistrationService.getPathsForLibraries(Set.of(libraryId)); isLibraryMonitoredWhenCalled = monitoringRegistrationService.isLibraryMonitored(libraryId) || !existingPaths.isEmpty(); - String pattern = fileMoveHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary()); - Path currentFilePath = bookEntity.getFullFilePath(); - Path expectedFilePath = fileMoveHelper.generateNewFilePath(bookEntity, bookEntity.getLibraryPath(), pattern); + // Ensure bookFiles are loaded + BookEntity bookWithFiles = bookEntity; + if (bookEntity.getBookFiles() == null || bookEntity.getBookFiles().isEmpty()) { + Optional optionalBook = bookRepository.findByIdWithBookFiles(bookEntity.getId()); + if (optionalBook.isEmpty()) { + log.warn("Book not found for move operation: bookId={}", bookEntity.getId()); + return FileMoveResult.builder().moved(false).build(); + } + bookWithFiles = optionalBook.get(); + } - if (currentFilePath.equals(expectedFilePath)) { + if (bookWithFiles.getBookFiles() == null || bookWithFiles.getBookFiles().isEmpty()) { + log.warn("Book has no files to move: bookId={}", bookEntity.getId()); return FileMoveResult.builder().moved(false).build(); } - log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, expectedFilePath); + String pattern = fileMoveHelper.getFileNamingPattern(bookWithFiles.getLibraryPath().getLibrary()); + Path currentPrimaryFilePath = bookWithFiles.getFullFilePath(); + Path expectedPrimaryFilePath = fileMoveHelper.generateNewFilePath(bookWithFiles, bookWithFiles.getLibraryPath(), pattern); + + if (currentPrimaryFilePath.equals(expectedPrimaryFilePath)) { + return FileMoveResult.builder().moved(false).build(); + } + + log.info("Files for book ID {} need to be moved to match library pattern", bookWithFiles.getId()); + + String newFileSubPath = fileMoveHelper.extractSubPath(expectedPrimaryFilePath, bookWithFiles.getLibraryPath()); + Path targetParentDir = expectedPrimaryFilePath.getParent(); + + if (targetParentDir == null) { + log.warn("Target parent directory could not be determined for move operation: bookId={}", bookWithFiles.getId()); + return FileMoveResult.builder().moved(false).build(); + } + + // Validate all source paths exist before attempting moves + for (var bookFile : bookWithFiles.getBookFiles()) { + Path sourcePath = bookFile.getFullFilePath(); + if (!fileMoveHelper.validateSourceExists(sourcePath, bookFile.isFolderBased())) { + log.warn("Source {} not found: bookId={}, path={}", + bookFile.isFolderBased() ? "folder" : "file", bookWithFiles.getId(), sourcePath); + return FileMoveResult.builder().moved(false).build(); + } + } if (isLibraryMonitoredWhenCalled) { - log.debug("Unregistering library {} before moving a single file", libraryId); + log.debug("Unregistering library {} before moving files", libraryId); fileMoveHelper.unregisterLibrary(libraryId); monitoringRegistrationService.waitForEventsDrainedByPaths(existingPaths, EVENT_DRAIN_TIMEOUT_MS); } - fileMoveHelper.moveFile(currentFilePath, expectedFilePath); + // Stage all files to temp locations + for (var bookFile : bookWithFiles.getBookFiles()) { + Path sourcePath = bookFile.getFullFilePath(); + Path targetPath; + if (bookFile.isBook()) { + targetPath = fileMoveHelper.generateNewFilePath(bookWithFiles, bookFile, bookWithFiles.getLibraryPath(), pattern); + } else { + targetPath = targetParentDir.resolve(bookFile.getFileName()); + } - fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot)); + if (sourcePath.equals(targetPath)) { + continue; + } + + Path tempPath = fileMoveHelper.moveFileWithBackup(sourcePath); + plannedMovesByBookFileId.put(bookFile.getId(), new PlannedMove(sourcePath, tempPath, targetPath)); + if (sourcePath.getParent() != null) { + sourceParentsToCleanup.add(sourcePath.getParent()); + } + } + + if (plannedMovesByBookFileId.isEmpty()) { + return FileMoveResult.builder().moved(false).build(); + } + + // Commit all file moves FIRST before updating database + for (PlannedMove planned : plannedMovesByBookFileId.values()) { + fileMoveHelper.commitMove(planned.temp(), planned.target()); + } + plannedMovesByBookFileId.clear(); + + // Update database for ALL BookFileEntity records (only after all commits succeed) + for (var bookFile : bookWithFiles.getBookFiles()) { + String newFileName; + if (bookFile.isBook()) { + Path targetPath = fileMoveHelper.generateNewFilePath(bookWithFiles, bookFile, bookWithFiles.getLibraryPath(), pattern); + newFileName = targetPath.getFileName().toString(); + } else { + newFileName = bookFile.getFileName(); + } + bookFileRepository.updateFileNameAndSubPath(bookFile.getId(), newFileName, newFileSubPath); + } + + // Clean up empty parent directories + for (Path sourceParent : sourceParentsToCleanup) { + fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(sourceParent, Set.of(libraryRoot)); + } if (isLibraryMonitoredWhenCalled) { // Ensure any file system events from the move and cleanup are drained/ignored while we are still unregistered sleep(EVENT_DRAIN_TIMEOUT_MS); } - String newFileName = expectedFilePath.getFileName().toString(); - String newFileSubPath = fileMoveHelper.extractSubPath(expectedFilePath, bookEntity.getLibraryPath()); + String newFileName = expectedPrimaryFilePath.getFileName().toString(); return FileMoveResult.builder() .moved(true) @@ -240,8 +338,13 @@ public class FileMoveService { .newFileSubPath(newFileSubPath) .build(); } catch (Exception e) { - log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e); + log.error("Failed to move files for book ID {}: {}", bookEntity.getId(), e.getMessage(), e); } finally { + // Rollback any uncommitted moves + for (PlannedMove planned : plannedMovesByBookFileId.values()) { + fileMoveHelper.rollbackMove(planned.temp(), planned.source()); + } + if (isLibraryMonitoredWhenCalled) { log.debug("Registering library paths for library {} with root {}", libraryId, libraryRoot); LibraryEntity libraryEntity = bookEntity.getLibraryPath().getLibrary(); @@ -262,4 +365,15 @@ public class FileMoveService { throw new RuntimeException("Sleep interrupted", e); } } + + private void validateLocalStorage() { + String diskType = appProperties.getDiskType(); + if (!"LOCAL".equalsIgnoreCase(diskType)) { + throw new IllegalStateException( + "File move operations are only supported on local storage. " + + "Current disk type is configured as: " + diskType + ". " + + "If you are using local storage, set DISK_TYPE=LOCAL in your environment." + ); + } + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/AbstractFileProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/AbstractFileProcessor.java index 2ada8a32d..dbe1cf8f9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/AbstractFileProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/AbstractFileProcessor.java @@ -47,7 +47,9 @@ public abstract class AbstractFileProcessor implements BookFileProcessor { @Override public FileProcessResult processFile(LibraryFile libraryFile) { Path path = libraryFile.getFullPath(); - String hash = FileFingerprint.generateHash(path); + String hash = libraryFile.isFolderBased() + ? FileFingerprint.generateFolderHash(path) + : FileFingerprint.generateHash(path); Book book = createAndMapBook(libraryFile, hash); return new FileProcessResult(book, FileProcessStatus.NEW); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/AudiobookProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/AudiobookProcessor.java new file mode 100644 index 000000000..7970e7690 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/AudiobookProcessor.java @@ -0,0 +1,149 @@ +package com.adityachandel.booklore.service.fileprocessor; + +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.model.dto.BookMetadata; +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookMetadataEntity; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.repository.BookAdditionalFileRepository; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.service.book.BookCreatorService; +import com.adityachandel.booklore.service.metadata.MetadataMatchService; +import com.adityachandel.booklore.service.metadata.extractor.AudiobookMetadataExtractor; +import com.adityachandel.booklore.util.BookCoverUtils; +import com.adityachandel.booklore.util.FileService; +import com.adityachandel.booklore.util.FileUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static com.adityachandel.booklore.util.FileService.truncate; + +@Slf4j +@Service +public class AudiobookProcessor extends AbstractFileProcessor implements BookFileProcessor { + + private final AudiobookMetadataExtractor audiobookMetadataExtractor; + + public AudiobookProcessor(BookRepository bookRepository, + BookAdditionalFileRepository bookAdditionalFileRepository, + BookCreatorService bookCreatorService, + BookMapper bookMapper, + FileService fileService, + MetadataMatchService metadataMatchService, + AudiobookMetadataExtractor audiobookMetadataExtractor) { + super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService); + this.audiobookMetadataExtractor = audiobookMetadataExtractor; + } + + @Override + public BookEntity processNewFile(LibraryFile libraryFile) { + BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.AUDIOBOOK); + setBookMetadata(bookEntity, libraryFile.isFolderBased()); + if (generateCover(bookEntity, libraryFile.isFolderBased())) { + FileService.setBookCoverPath(bookEntity.getMetadata()); + bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash()); + } + return bookEntity; + } + + @Override + public boolean generateCover(BookEntity bookEntity) { + return generateCover(bookEntity, bookEntity.getPrimaryBookFile().isFolderBased()); + } + + public boolean generateCover(BookEntity bookEntity, boolean isFolderBased) { + try { + File audioFile = getAudioFileForMetadata(bookEntity, isFolderBased); + if (audioFile == null || !audioFile.exists()) { + log.debug("Audio file not found for audiobook '{}'", bookEntity.getPrimaryBookFile().getFileName()); + return false; + } + + byte[] coverData = audiobookMetadataExtractor.extractCover(audioFile); + + if (coverData == null) { + log.debug("No cover image found in audiobook '{}'", bookEntity.getPrimaryBookFile().getFileName()); + return false; + } + + boolean saved; + try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) { + BufferedImage originalImage = FileService.readImage(bais); + if (originalImage == null) { + log.warn("Failed to decode cover image for audiobook '{}'", bookEntity.getPrimaryBookFile().getFileName()); + return false; + } + saved = fileService.saveCoverImages(originalImage, bookEntity.getId()); + originalImage.flush(); + } + + return saved; + + } catch (Exception e) { + log.error("Error generating cover for audiobook '{}': {}", bookEntity.getPrimaryBookFile().getFileName(), e.getMessage(), e); + return false; + } + } + + /** + * Get the audio file to use for metadata extraction. + * For folder-based audiobooks, returns the first audio file in the folder. + */ + private File getAudioFileForMetadata(BookEntity bookEntity, boolean isFolderBased) { + if (isFolderBased) { + java.nio.file.Path folderPath = bookEntity.getFullFilePath(); + return FileUtils.getFirstAudioFileInFolder(folderPath) + .map(java.nio.file.Path::toFile) + .orElse(null); + } else { + return new File(FileUtils.getBookFullPath(bookEntity)); + } + } + + @Override + public List getSupportedTypes() { + return List.of(BookFileType.AUDIOBOOK); + } + + private void setBookMetadata(BookEntity bookEntity, boolean isFolderBased) { + File bookFile = getAudioFileForMetadata(bookEntity, isFolderBased); + if (bookFile == null || !bookFile.exists()) { + log.warn("Audio file not found for metadata extraction: {}", bookEntity.getPrimaryBookFile().getFileName()); + return; + } + + BookMetadata audioMetadata = audiobookMetadataExtractor.extractMetadata(bookFile); + if (audioMetadata == null) return; + + BookMetadataEntity metadata = bookEntity.getMetadata(); + + metadata.setTitle(truncate(audioMetadata.getTitle(), 1000)); + metadata.setSubtitle(truncate(audioMetadata.getSubtitle(), 1000)); + metadata.setDescription(truncate(audioMetadata.getDescription(), 2000)); + metadata.setPublisher(truncate(audioMetadata.getPublisher(), 1000)); + metadata.setPublishedDate(audioMetadata.getPublishedDate()); + metadata.setSeriesName(truncate(audioMetadata.getSeriesName(), 1000)); + metadata.setSeriesNumber(audioMetadata.getSeriesNumber()); + metadata.setSeriesTotal(audioMetadata.getSeriesTotal()); + + String lang = audioMetadata.getLanguage(); + metadata.setLanguage(truncate((lang == null || "UND".equalsIgnoreCase(lang)) ? "en" : lang, 1000)); + + bookCreatorService.addAuthorsToBook(audioMetadata.getAuthors(), bookEntity); + + if (audioMetadata.getCategories() != null) { + Set validCategories = audioMetadata.getCategories().stream() + .filter(s -> s != null && !s.isBlank() && s.length() <= 100 && !s.contains("\n") && !s.contains("\r") && !s.contains(" ")) + .collect(Collectors.toSet()); + bookCreatorService.addCategoriesToBook(validCategories, bookEntity); + } + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboCompatibilityService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboCompatibilityService.java index f512a4204..d798ae3ad 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboCompatibilityService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboCompatibilityService.java @@ -17,8 +17,11 @@ public class KoboCompatibilityService { if (book == null) { throw new IllegalArgumentException("Book cannot be null"); } - + var primaryFile = book.getPrimaryBookFile(); + if (primaryFile == null) { + return false; + } BookFileType bookType = primaryFile.getBookType(); if (bookType == null) { return false; @@ -45,7 +48,7 @@ public class KoboCompatibilityService { } public boolean meetsCbxConversionSizeLimit(BookEntity book) { - if (book == null || book.getPrimaryBookFile().getBookType() != BookFileType.CBX) { + if (book == null || book.getPrimaryBookFile() == null || book.getPrimaryBookFile().getBookType() != BookFileType.CBX) { return false; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java index 34303a503..d6d7a3229 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java @@ -86,7 +86,7 @@ public class KoboEntitlementService { .collect(Collectors.toList()); } return books.stream() - .filter(bookEntity -> bookEntity.getPrimaryBookFile().getBookType() == BookFileType.EPUB) + .filter(bookEntity -> bookEntity.getPrimaryBookFile() != null && bookEntity.getPrimaryBookFile().getBookType() == BookFileType.EPUB) .map(book -> ChangedProductMetadata.builder() .changedProductMetadata(BookEntitlementContainer.builder() .bookEntitlement(buildBookEntitlement(book, false)) @@ -233,6 +233,9 @@ public class KoboEntitlementService { KoboSettings koboSettings = appSettingService.getAppSettings().getKoboSettings(); var primaryFile = book.getPrimaryBookFile(); + if (primaryFile == null) { + return null; + } boolean isEpubFile = primaryFile.getBookType() == BookFileType.EPUB; boolean isCbxFile = primaryFile.getBookType() == BookFileType.CBX; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboReadingStateService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboReadingStateService.java index e21461c55..c473aa02f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboReadingStateService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboReadingStateService.java @@ -7,13 +7,11 @@ import com.adityachandel.booklore.model.dto.KoboSyncSettings; import com.adityachandel.booklore.model.dto.kobo.KoboReadingState; import com.adityachandel.booklore.model.dto.kobo.KoboReadingStateWrapper; import com.adityachandel.booklore.model.dto.response.kobo.KoboReadingStateResponse; -import com.adityachandel.booklore.model.entity.BookEntity; -import com.adityachandel.booklore.model.entity.BookLoreUserEntity; -import com.adityachandel.booklore.model.entity.KoboReadingStateEntity; -import com.adityachandel.booklore.model.entity.UserBookProgressEntity; +import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.enums.ReadStatus; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.KoboReadingStateRepository; +import com.adityachandel.booklore.repository.UserBookFileProgressRepository; import com.adityachandel.booklore.repository.UserBookProgressRepository; import com.adityachandel.booklore.repository.UserRepository; import com.adityachandel.booklore.service.hardcover.HardcoverSyncService; @@ -37,6 +35,7 @@ public class KoboReadingStateService { private final KoboReadingStateRepository repository; private final KoboReadingStateMapper mapper; private final UserBookProgressRepository progressRepository; + private final UserBookFileProgressRepository fileProgressRepository; private final BookRepository bookRepository; private final UserRepository userRepository; private final AuthenticationService authenticationService; @@ -124,20 +123,20 @@ public class KoboReadingStateService { private void syncKoboProgressToUserBookProgress(KoboReadingState readingState, Long userId) { try { Long bookId = Long.parseLong(readingState.getEntitlementId()); - + Optional bookOpt = bookRepository.findById(bookId); if (bookOpt.isEmpty()) { log.warn("Book not found for entitlement ID: {}", readingState.getEntitlementId()); return; } - + BookEntity book = bookOpt.get(); Optional userOpt = userRepository.findById(userId); if (userOpt.isEmpty()) { log.warn("User not found: {}", userId); return; } - + UserBookProgressEntity progress = progressRepository.findByUserIdAndBookId(userId, bookId) .orElseGet(() -> { UserBookProgressEntity newProgress = new UserBookProgressEntity(); @@ -145,16 +144,16 @@ public class KoboReadingStateService { newProgress.setBook(book); return newProgress; }); - + KoboReadingState.CurrentBookmark bookmark = readingState.getCurrentBookmark(); if (bookmark != null) { if (bookmark.getProgressPercent() != null) { progress.setKoboProgressPercent(bookmark.getProgressPercent().floatValue()); } - + KoboReadingState.CurrentBookmark.Location location = bookmark.getLocation(); if (location != null) { - log.debug("Kobo location data: value={}, type={}, source={} (length={})", + log.debug("Kobo location data: value={}, type={}, source={} (length={})", location.getValue(), location.getType(), location.getSource(), location.getSource() != null ? location.getSource().length() : 0); progress.setKoboLocation(location.getValue()); @@ -162,24 +161,48 @@ public class KoboReadingStateService { progress.setKoboLocationSource(location.getSource()); } } - + Instant now = Instant.now(); progress.setKoboProgressReceivedTime(now); progress.setLastReadTime(now); - + if (progress.getKoboProgressPercent() != null) { updateReadStatusFromKoboProgress(progress, now); } - + progressRepository.save(progress); + + // Also save to file-level progress table (dual-write) + saveToFileProgress(userOpt.get(), book, progress); + log.debug("Synced Kobo progress: bookId={}, progress={}%", bookId, progress.getKoboProgressPercent()); - + // Sync progress to Hardcover asynchronously (if enabled for this user) hardcoverSyncService.syncProgressToHardcover(book.getId(), progress.getKoboProgressPercent(), userId); } catch (NumberFormatException e) { log.warn("Invalid entitlement ID format: {}", readingState.getEntitlementId()); } } + + private void saveToFileProgress(BookLoreUserEntity user, BookEntity book, UserBookProgressEntity progress) { + try { + BookFileEntity primaryFile = book.getPrimaryBookFile(); + UserBookFileProgressEntity fileProgress = fileProgressRepository + .findByUserIdAndBookFileId(user.getId(), primaryFile.getId()) + .orElseGet(UserBookFileProgressEntity::new); + + fileProgress.setUser(user); + fileProgress.setBookFile(primaryFile); + fileProgress.setLastReadTime(progress.getLastReadTime()); + + // For Kobo, we store the progress percent (Kobo doesn't provide position data) + fileProgress.setProgressPercent(progress.getKoboProgressPercent()); + + fileProgressRepository.save(fileProgress); + } catch (Exception e) { + log.warn("Failed to save file-level progress for book {}: {}", book.getId(), e.getMessage()); + } + } private void updateReadStatusFromKoboProgress(UserBookProgressEntity userProgress, Instant now) { if (shouldPreserveCurrentStatus(userProgress, now)) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java index 2e18258be..a8478eb06 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java @@ -3,13 +3,11 @@ package com.adityachandel.booklore.service.koreader; import com.adityachandel.booklore.config.security.userdetails.KoreaderUserDetails; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.model.dto.progress.KoreaderProgress; -import com.adityachandel.booklore.model.entity.BookEntity; -import com.adityachandel.booklore.model.entity.BookLoreUserEntity; -import com.adityachandel.booklore.model.entity.KoreaderUserEntity; -import com.adityachandel.booklore.model.entity.UserBookProgressEntity; +import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.enums.ReadStatus; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.KoreaderUserRepository; +import com.adityachandel.booklore.repository.UserBookFileProgressRepository; import com.adityachandel.booklore.repository.UserBookProgressRepository; import com.adityachandel.booklore.repository.UserRepository; import com.adityachandel.booklore.service.hardcover.HardcoverSyncService; @@ -31,6 +29,7 @@ import java.util.Map; public class KoreaderService { private final UserBookProgressRepository progressRepository; + private final UserBookFileProgressRepository fileProgressRepository; private final BookRepository bookRepository; private final UserRepository userRepository; private final KoreaderUserRepository koreaderUserRepository; @@ -79,12 +78,51 @@ public class KoreaderService { progressRepository.save(userProgress); + // Also save to file-level progress table (dual-write) + saveToFileProgress(user, book, userProgress); + log.info("saveProgress: saved progress='{}' percentage={} for userId={} bookHash={}", koProgress.getProgress(), koProgress.getPercentage(), authDetails.getBookLoreUserId(), bookHash); Float progressPercent = normalizeProgressPercent(koProgress.getPercentage()); hardcoverSyncService.syncProgressToHardcover(book.getId(), progressPercent, authDetails.getBookLoreUserId()); } + private void saveToFileProgress(BookLoreUserEntity user, BookEntity book, UserBookProgressEntity progress) { + try { + BookFileEntity primaryFile = book.getPrimaryBookFile(); + UserBookFileProgressEntity fileProgress = fileProgressRepository + .findByUserIdAndBookFileId(user.getId(), primaryFile.getId()) + .orElseGet(UserBookFileProgressEntity::new); + + fileProgress.setUser(user); + fileProgress.setBookFile(primaryFile); + fileProgress.setLastReadTime(progress.getLastReadTime()); + + // Map progress based on book type + switch (primaryFile.getBookType()) { + case EPUB, FB2, MOBI, AZW3 -> { + fileProgress.setPositionData(progress.getEpubProgress()); + fileProgress.setPositionHref(progress.getEpubProgressHref()); + fileProgress.setProgressPercent(progress.getEpubProgressPercent()); + } + case PDF -> { + fileProgress.setPositionData(progress.getPdfProgress() != null ? + String.valueOf(progress.getPdfProgress()) : null); + fileProgress.setProgressPercent(progress.getPdfProgressPercent()); + } + case CBX -> { + fileProgress.setPositionData(progress.getCbxProgress() != null ? + String.valueOf(progress.getCbxProgress()) : null); + fileProgress.setProgressPercent(progress.getCbxProgressPercent()); + } + } + + fileProgressRepository.save(fileProgress); + } catch (Exception e) { + log.warn("Failed to save file-level progress for book {}: {}", book.getId(), e.getMessage()); + } + } + private void updateProgressData(UserBookProgressEntity userProgress, KoreaderProgress koProgress, boolean syncWithBookloreReader, BookEntity book) { userProgress.setKoreaderProgress(koProgress.getProgress()); userProgress.setKoreaderProgressPercent(koProgress.getPercentage()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/BookGroupingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/BookGroupingService.java new file mode 100644 index 000000000..b888d450e --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/BookGroupingService.java @@ -0,0 +1,279 @@ +package com.adityachandel.booklore.service.library; + +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; +import com.adityachandel.booklore.model.entity.LibraryEntity; +import com.adityachandel.booklore.model.enums.LibraryOrganizationMode; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.util.BookFileGroupingUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.*; + +/** + * Unified service for grouping book files. + * Handles both initial scan (grouping new files) and rescan (matching to existing books). + * Organization mode determines the grouping strategy. + */ +@Service +@Slf4j +@RequiredArgsConstructor +public class BookGroupingService { + + private static final double FILELESS_MATCH_THRESHOLD = 0.85; + + private final BookRepository bookRepository; + + /** + * Result of grouping operation for rescan. + * Contains files to attach to existing books and files that need new book entities. + */ + public record GroupingResult( + Map> filesToAttach, + Map> newBookGroups + ) {} + + /** + * Groups new files for initial library scan. + * Returns groups of files that should become a single book entity. + * + * @param newFiles files to group + * @param libraryEntity the library being processed + * @return map of group key to list of files in that group + */ + public Map> groupForInitialScan(List newFiles, LibraryEntity libraryEntity) { + LibraryOrganizationMode mode = getOrganizationMode(libraryEntity); + + return switch (mode) { + case BOOK_PER_FOLDER -> groupByFolder(newFiles); + case AUTO_DETECT -> BookFileGroupingUtils.groupByBaseName(newFiles); + }; + } + + /** + * Groups new files for rescan, considering existing books. + * Returns files to attach to existing books and new groups to create. + * + * @param newFiles files to process + * @param libraryEntity the library being processed + * @return grouping result with attach map and new groups + */ + public GroupingResult groupForRescan(List newFiles, LibraryEntity libraryEntity) { + LibraryOrganizationMode mode = getOrganizationMode(libraryEntity); + + Map> filesToAttach = new LinkedHashMap<>(); + List unmatched = new ArrayList<>(); + + for (LibraryFile file : newFiles) { + BookEntity match = findMatchingBook(file, mode); + if (match != null) { + filesToAttach.computeIfAbsent(match, k -> new ArrayList<>()).add(file); + } else { + unmatched.add(file); + } + } + + // Group unmatched files into new book groups + Map> newBookGroups; + if (unmatched.isEmpty()) { + newBookGroups = Collections.emptyMap(); + } else { + newBookGroups = switch (mode) { + case BOOK_PER_FOLDER -> groupByFolder(unmatched); + case AUTO_DETECT -> BookFileGroupingUtils.groupByBaseName(unmatched); + }; + } + + return new GroupingResult(filesToAttach, newBookGroups); + } + + /** + * Simple folder-based grouping: all files in the same folder become one book. + */ + private Map> groupByFolder(List files) { + Map> 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); + } + + log.debug("BOOK_PER_FOLDER grouping: {} files into {} groups", files.size(), result.size()); + return result; + } + + /** + * Finds an existing book that matches the given file. + * Strategy depends on organization mode. + */ + private BookEntity findMatchingBook(LibraryFile file, LibraryOrganizationMode mode) { + // First check for fileless books by metadata matching + BookEntity filelessMatch = findMatchingFilelessBook(file, file.getLibraryEntity()); + if (filelessMatch != null) { + return filelessMatch; + } + + String fileSubPath = file.getFileSubPath(); + + // Root-level files: don't auto-attach + if (fileSubPath == null || fileSubPath.isEmpty()) { + return null; + } + + Long libraryPathId = file.getLibraryPathEntity().getId(); + List booksInDirectory = bookRepository.findAllByLibraryPathIdAndFileSubPath(libraryPathId, fileSubPath); + + // Filter to non-deleted books only + List activeBooksInDirectory = booksInDirectory.stream() + .filter(book -> book.getDeleted() == null || !book.getDeleted()) + .toList(); + + if (activeBooksInDirectory.isEmpty()) { + return null; + } + + return switch (mode) { + case BOOK_PER_FOLDER -> findMatchBookPerFolder(file, activeBooksInDirectory); + case AUTO_DETECT -> findMatchAutoDetect(file, activeBooksInDirectory); + }; + } + + /** + * Finds a fileless book that matches the given file by metadata title. + * Only matches books that either have no libraryPath or have the same libraryPath as the file. + */ + private BookEntity findMatchingFilelessBook(LibraryFile file, LibraryEntity library) { + List 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) { + // Skip books that already have a different libraryPath + 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()); + double similarity = BookFileGroupingUtils.calculateSimilarity(fileBaseName, bookTitle); + if (similarity >= FILELESS_MATCH_THRESHOLD) { + log.debug("Matched file '{}' to fileless book '{}' (title: {})", + file.getFileName(), book.getId(), book.getMetadata().getTitle()); + return book; + } + } + } + return null; + } + + /** + * BOOK_PER_FOLDER: If exactly one book in folder, attach to it. + * If multiple books exist (edge case), use filename matching. + */ + private BookEntity findMatchBookPerFolder(LibraryFile file, List booksInDirectory) { + // Filter to books with files for filename-based matching + List booksWithFiles = booksInDirectory.stream() + .filter(BookEntity::hasFiles) + .toList(); + + if (booksWithFiles.size() == 1) { + BookEntity book = booksWithFiles.get(0); + log.debug("BOOK_PER_FOLDER: Attaching '{}' to single book in folder: '{}'", + file.getFileName(), book.getPrimaryBookFile().getFileName()); + return book; + } + + if (booksWithFiles.isEmpty()) { + return null; + } + + // Multiple books in folder - shouldn't happen with BOOK_PER_FOLDER mode + // Fall back to exact filename matching + log.warn("BOOK_PER_FOLDER: Multiple books ({}) in folder '{}', using filename match", + booksWithFiles.size(), file.getFileSubPath()); + return findExactMatch(file, booksWithFiles); + } + + /** + * AUTO_DETECT: Use fuzzy matching to find best match. + */ + private BookEntity findMatchAutoDetect(LibraryFile file, List booksInDirectory) { + // Filter to books with files for filename-based matching + List booksWithFiles = booksInDirectory.stream() + .filter(BookEntity::hasFiles) + .toList(); + + if (booksWithFiles.isEmpty()) { + return null; + } + + // If exactly one book with files in folder, attach to it + if (booksWithFiles.size() == 1) { + BookEntity book = booksWithFiles.get(0); + log.debug("AUTO_DETECT: Single book in folder '{}', attaching '{}' to '{}'", + file.getFileSubPath(), file.getFileName(), book.getPrimaryBookFile().getFileName()); + return book; + } + + // Multiple books: use fuzzy matching + String fileGroupingKey = BookFileGroupingUtils.extractGroupingKey(file.getFileName()); + BookEntity bestMatch = null; + double bestSimilarity = 0; + + for (BookEntity book : booksWithFiles) { + BookFileEntity primaryFile = book.getPrimaryBookFile(); + String existingGroupingKey = BookFileGroupingUtils.extractGroupingKey(primaryFile.getFileName()); + + // Exact match + if (fileGroupingKey.equals(existingGroupingKey)) { + return book; + } + + // Track best fuzzy match + double similarity = BookFileGroupingUtils.calculateSimilarity(fileGroupingKey, existingGroupingKey); + if (similarity >= 0.85 && similarity > bestSimilarity) { + bestSimilarity = similarity; + bestMatch = book; + } + } + + if (bestMatch != null) { + log.debug("AUTO_DETECT: Fuzzy matched '{}' to '{}' (similarity: {})", + file.getFileName(), bestMatch.getPrimaryBookFile().getFileName(), bestSimilarity); + } + return bestMatch; + } + + /** + * Finds a book with exact filename match. + * Assumes books list contains only books with files. + */ + private BookEntity findExactMatch(LibraryFile file, List 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; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/BookRestorationService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/BookRestorationService.java index 6ed935e8e..20a899567 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/BookRestorationService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/BookRestorationService.java @@ -39,6 +39,7 @@ public class BookRestorationService { List toRestore = libraryEntity.getBookEntities().stream() .filter(book -> Boolean.TRUE.equals(book.getDeleted())) + .filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty()) .filter(book -> currentPaths.contains(book.getFullFilePath())) .collect(Collectors.toList()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/FileAsBookProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/FileAsBookProcessor.java index 9195ad11d..cd0adcfe7 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/FileAsBookProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/FileAsBookProcessor.java @@ -2,66 +2,160 @@ package com.adityachandel.booklore.service.library; import com.adityachandel.booklore.model.FileProcessResult; import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.enums.BookFileType; -import com.adityachandel.booklore.model.enums.LibraryScanMode; +import com.adityachandel.booklore.repository.BookAdditionalFileRepository; +import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.event.BookEventBroadcaster; +import com.adityachandel.booklore.service.file.FileFingerprint; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; import com.adityachandel.booklore.service.kobo.KoboAutoShelfService; +import com.adityachandel.booklore.util.BookFileGroupingUtils; +import com.adityachandel.booklore.util.FileUtils; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; +import java.time.Instant; +import java.util.Comparator; import java.util.List; +import java.util.Map; +import java.util.Optional; @AllArgsConstructor @Component @Slf4j -public class FileAsBookProcessor implements LibraryFileProcessor { +public class FileAsBookProcessor { private final BookEventBroadcaster bookEventBroadcaster; private final BookFileProcessorRegistry processorRegistry; private final KoboAutoShelfService koboAutoShelfService; + private final BookRepository bookRepository; + private final BookAdditionalFileRepository bookAdditionalFileRepository; - @Override - public LibraryScanMode getScanMode() { - return LibraryScanMode.FILE_AS_BOOK; - } - - @Override @Transactional public void processLibraryFiles(List libraryFiles, LibraryEntity libraryEntity) { - for (LibraryFile libraryFile : libraryFiles) { - processFileWithErrorHandling(libraryFile); + Map> groups = BookFileGroupingUtils.groupByBaseName(libraryFiles); + processLibraryFilesGrouped(groups, libraryEntity); + } + + /** + * Process pre-grouped library files. Use this when grouping has already been done + * (e.g., by BookGroupingService during rescan). + */ + @Transactional + public void processLibraryFilesGrouped(Map> groups, LibraryEntity libraryEntity) { + for (Map.Entry> entry : groups.entrySet()) { + processGroupWithErrorHandling(entry.getValue(), libraryEntity); } log.info("Finished processing library '{}'", libraryEntity.getName()); } - private void processFileWithErrorHandling(LibraryFile libraryFile) { - log.info("Processing file: {}", libraryFile.getFileName()); + private void processGroupWithErrorHandling(List group, LibraryEntity libraryEntity) { try { - FileProcessResult result = processLibraryFile(libraryFile); - if (result != null) { - bookEventBroadcaster.broadcastBookAddEvent(result.getBook()); - koboAutoShelfService.autoAddBookToKoboShelves(result.getBook().getId()); - } + processGroup(group, libraryEntity); } catch (Exception e) { - log.error("Failed to process file '{}': {}", libraryFile.getFileName(), e.getMessage()); + String fileNames = group.stream().map(LibraryFile::getFileName).toList().toString(); + log.error("Failed to process file group {}: {}", fileNames, e.getMessage()); } } - @Transactional - protected FileProcessResult processLibraryFile(LibraryFile libraryFile) { - BookFileType type = libraryFile.getBookFileType(); + private void processGroup(List group, LibraryEntity libraryEntity) { + Optional primaryFile = findBestPrimaryFile(group, libraryEntity); + if (primaryFile.isEmpty()) { + log.warn("No suitable book file found in group"); + return; + } + + LibraryFile primary = primaryFile.get(); + log.info("Processing file: {}", primary.getFileName()); + + BookFileType type = primary.getBookFileType(); if (type == null) { - log.warn("Unsupported file type for file: {}", libraryFile.getFileName()); - return null; + log.warn("Unsupported file type for file: {}", primary.getFileName()); + return; } BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type); - return processor.processFile(libraryFile); + FileProcessResult result = processor.processFile(primary); + + if (result == null || result.getBook() == null) { + log.warn("Failed to process primary file: {}", primary.getFileName()); + return; + } + + bookEventBroadcaster.broadcastBookAddEvent(result.getBook()); + koboAutoShelfService.autoAddBookToKoboShelves(result.getBook().getId()); + + List additionalFiles = group.stream() + .filter(f -> !f.equals(primary)) + .toList(); + + if (!additionalFiles.isEmpty()) { + BookEntity bookEntity = bookRepository.getReferenceById(result.getBook().getId()); + for (LibraryFile additionalFile : additionalFiles) { + createAdditionalBookFile(bookEntity, additionalFile); + } + } } -} \ No newline at end of file + private Optional findBestPrimaryFile(List group, LibraryEntity libraryEntity) { + List formatPriority = libraryEntity.getFormatPriority(); + return group.stream() + .filter(f -> f.getBookFileType() != null) + .min(Comparator.comparingInt(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(); + })); + } + + private void createAdditionalBookFile(BookEntity bookEntity, LibraryFile file) { + Optional existing = bookAdditionalFileRepository + .findByLibraryPath_IdAndFileSubPathAndFileName( + file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName()); + + if (existing.isPresent()) { + log.debug("Additional file already exists: {}", file.getFileName()); + return; + } + + // Handle folder-based audiobooks vs regular files + String hash; + Long fileSizeKb; + if (file.isFolderBased()) { + hash = FileFingerprint.generateFolderHash(file.getFullPath()); + fileSizeKb = FileUtils.getFolderSizeInKb(file.getFullPath()); + } else { + hash = FileFingerprint.generateHash(file.getFullPath()); + fileSizeKb = FileUtils.getFileSizeInKb(file.getFullPath()); + } + + BookFileEntity additionalFile = BookFileEntity.builder() + .book(bookEntity) + .fileName(file.getFileName()) + .fileSubPath(file.getFileSubPath()) + .isBookFormat(true) + .folderBased(file.isFolderBased()) + .bookType(file.getBookFileType()) + .fileSizeKb(fileSizeKb) + .initialHash(hash) + .currentHash(hash) + .addedOn(Instant.now()) + .build(); + + try { + bookAdditionalFileRepository.save(additionalFile); + log.info("Attached additional format {} to book: {}", file.getFileName(), bookEntity.getPrimaryBookFile().getFileName()); + } catch (Exception e) { + log.error("Error creating additional file {}: {}", file.getFileName(), e.getMessage()); + } + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessor.java deleted file mode 100644 index ab1e38ebe..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessor.java +++ /dev/null @@ -1,255 +0,0 @@ -package com.adityachandel.booklore.service.library; - -import com.adityachandel.booklore.model.FileProcessResult; -import com.adityachandel.booklore.model.dto.settings.LibraryFile; -import com.adityachandel.booklore.model.entity.BookFileEntity; -import com.adityachandel.booklore.model.entity.BookEntity; -import com.adityachandel.booklore.model.entity.LibraryEntity; -import com.adityachandel.booklore.model.entity.LibraryPathEntity; -import com.adityachandel.booklore.model.enums.BookFileExtension; -import com.adityachandel.booklore.model.enums.BookFileType; -import com.adityachandel.booklore.model.enums.LibraryScanMode; -import com.adityachandel.booklore.repository.BookAdditionalFileRepository; -import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.file.FileFingerprint; -import com.adityachandel.booklore.service.event.AdminEventBroadcaster; -import com.adityachandel.booklore.service.event.BookEventBroadcaster; -import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; -import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; -import com.adityachandel.booklore.util.FileUtils; -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; - -import java.nio.file.Path; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -@Service -@AllArgsConstructor -@Slf4j -public class FolderAsBookFileProcessor implements LibraryFileProcessor { - - private final BookRepository bookRepository; - private final BookAdditionalFileRepository bookAdditionalFileRepository; - private final BookEventBroadcaster bookEventBroadcaster; - private final AdminEventBroadcaster adminEventBroadcaster; - private final BookFileProcessorRegistry bookFileProcessorRegistry; - - @Override - public LibraryScanMode getScanMode() { - return LibraryScanMode.FOLDER_AS_BOOK; - } - - @Override - public boolean supportsSupplementaryFiles() { - return true; - } - - @Override - public void processLibraryFiles(List libraryFiles, LibraryEntity libraryEntity) { - Map> filesByDirectory = libraryFiles.stream() - .collect(Collectors.groupingBy(libraryFile -> libraryFile.getFullPath().getParent())); - - log.info("Processing {} directories with {} total files for library: {}", - filesByDirectory.size(), libraryFiles.size(), libraryEntity.getName()); - - var sortedDirectories = filesByDirectory.entrySet() - .stream() - .sorted(Map.Entry.comparingByKey()) - .toList(); - for (Map.Entry> entry : sortedDirectories) { - Path directoryPath = entry.getKey(); - List filesInDirectory = entry.getValue(); - - log.debug("Processing directory: {} with {} files", directoryPath, filesInDirectory.size()); - processDirectory(directoryPath, filesInDirectory, libraryEntity); - } - } - - private void processDirectory(Path directoryPath, List filesInDirectory, LibraryEntity libraryEntity) { - var bookCreationResult = getOrCreateBookInDirectory(directoryPath, filesInDirectory, libraryEntity); - if (bookCreationResult.bookEntity.isEmpty()) { - log.warn("No book created for directory: {}", directoryPath); - return; - } - - processAdditionalFiles(bookCreationResult.bookEntity.get(), bookCreationResult.remainingFiles); - } - - private GetOrCreateBookResult getOrCreateBookInDirectory(Path directoryPath, List filesInDirectory, LibraryEntity libraryEntity) { - var existingBook = findExistingBookInDirectory(directoryPath, libraryEntity); - if (existingBook.isPresent()) { - log.debug("Found existing book in directory {}: {}", directoryPath, existingBook.get().getPrimaryBookFile().getFileName()); - return new GetOrCreateBookResult(existingBook, filesInDirectory); - } - - Optional parentBook = findBookInParentDirectories(directoryPath, libraryEntity); - if (parentBook.isPresent()) { - log.debug("Found parent book for directory {}: {}", directoryPath, parentBook.get().getPrimaryBookFile().getFileName()); - return new GetOrCreateBookResult(parentBook, filesInDirectory); - } - - log.debug("No existing book found, creating new book from directory: {}", directoryPath); - Optional newBook = createNewBookFromDirectory(directoryPath, filesInDirectory, libraryEntity); - if (newBook.isPresent()) { - log.info("Created new book: {}", newBook.get().bookEntity.getPrimaryBookFile().getFileName()); - var remainingFiles = filesInDirectory.stream() - .filter(file -> !file.equals(newBook.get().libraryFile)) - .toList(); - return new GetOrCreateBookResult(Optional.of(newBook.get().bookEntity), remainingFiles); - } else { - log.warn("Failed to create book from directory: {}", directoryPath); - return new GetOrCreateBookResult(Optional.empty(), filesInDirectory); - } - } - - private Optional findExistingBookInDirectory(Path directoryPath, LibraryEntity libraryEntity) { - return libraryEntity.getLibraryPaths().stream() - .flatMap(libPath -> { - String filesSearchPath = Path.of(libPath.getPath()) - .relativize(directoryPath) - .toString() - .replace("\\", "/"); - return bookRepository - .findAllByLibraryPathIdAndFileSubPathStartingWith(libPath.getId(), filesSearchPath) - .stream(); - }) - .filter(book -> book.getFullFilePath().getParent().equals(directoryPath)) - .findFirst(); - } - - private Optional findBookInParentDirectories(Path directoryPath, LibraryEntity libraryEntity) { - Path parent = directoryPath.getParent(); - LibraryPathEntity directoryLibraryPathEntity = libraryEntity.getLibraryPaths().stream() - .filter(libPath -> directoryPath.startsWith(libPath.getPath())) - .findFirst() - .orElseThrow(() -> new IllegalStateException("No library path found for directory: " + directoryPath)); - Path directoryLibraryPath = Path.of(directoryLibraryPathEntity.getPath()); - - while (parent != null) { - final String parentPath = directoryLibraryPath - .relativize(parent) - .toString() - .replace("\\", "/"); - - Optional parentBook = - bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith( - directoryLibraryPathEntity.getId(), parentPath).stream() - .filter(book -> book.getPrimaryBookFile().getFileSubPath().equals(parentPath)) - .findFirst(); - if (parentBook.isPresent()) { - return parentBook; - } - parent = parent.getParent(); - } - - return Optional.empty(); - } - - private Optional createNewBookFromDirectory(Path directoryPath, List filesInDirectory, LibraryEntity libraryEntity) { - Optional mainBookFile = findBestMainBookFile(filesInDirectory, libraryEntity); - - if (mainBookFile.isEmpty()) { - log.debug("No suitable book file found in directory: {}", directoryPath); - return Optional.empty(); - } - - LibraryFile bookFile = mainBookFile.get(); - - try { - log.info("Creating new book from file: {}", bookFile.getFileName()); - - BookFileProcessor processor = bookFileProcessorRegistry.getProcessorOrThrow(bookFile.getBookFileType()); - FileProcessResult result = processor.processFile(bookFile); - - if (result.getBook() != null) { - bookEventBroadcaster.broadcastBookAddEvent(result.getBook()); - - BookEntity bookEntity = bookRepository.getReferenceById(result.getBook().getId()); - if (bookEntity.getFullFilePath().equals(bookFile.getFullPath())) { - log.info("Successfully created new book: {}", bookEntity.getPrimaryBookFile().getFileName()); - } else { - log.warn("Found duplicate book with different path: {} vs {}", bookEntity.getFullFilePath(), bookFile.getFullPath()); - } - - return Optional.of(new CreateBookResult(bookEntity, bookFile)); - } else { - log.warn("Book processor returned null for file: {}", bookFile.getFileName()); - adminEventBroadcaster.broadcastAdminEvent("Failed to create book from file: " + bookFile.getFileName()); - return Optional.empty(); - } - } catch (Exception e) { - log.error("Error processing book file {}: {}", bookFile.getFileName(), e.getMessage(), e); - adminEventBroadcaster.broadcastAdminEvent("Error processing book file: " + bookFile.getFileName() + " - " + e.getMessage()); - return Optional.empty(); - } - } - - private Optional findBestMainBookFile(List filesInDirectory, LibraryEntity libraryEntity) { - var defaultBookFormat = libraryEntity.getDefaultBookFormat(); - return filesInDirectory.stream() - .filter(f -> f.getBookFileType() != null) - .min(Comparator.comparingInt(f -> { - BookFileType bookFileType = f.getBookFileType(); - return bookFileType == defaultBookFormat - ? -1 - : bookFileType.ordinal(); - })); - } - - private void processAdditionalFiles(BookEntity existingBook, List filesInDirectory) { - for (LibraryFile file : filesInDirectory) { - Optional extension = BookFileExtension.fromFileName(file.getFileName()); - boolean isBook = extension.isPresent(); - BookFileType bookType = extension.map(BookFileExtension::getType).orElse(null); - - createAdditionalFileIfNotExists(existingBook, file, isBook, bookType); - } - } - - private void createAdditionalFileIfNotExists(BookEntity bookEntity, LibraryFile file, boolean isBook, BookFileType bookType) { - Optional existingFile = bookAdditionalFileRepository - .findByLibraryPath_IdAndFileSubPathAndFileName( - file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName()); - - if (existingFile.isPresent()) { - log.debug("Additional file already exists: {}", file.getFileName()); - return; - } - - String hash = FileFingerprint.generateHash(file.getFullPath()); - BookFileEntity additionalFile = BookFileEntity.builder() - .book(bookEntity) - .fileName(file.getFileName()) - .fileSubPath(file.getFileSubPath()) - .isBookFormat(isBook) - .bookType(bookType) - .fileSizeKb(FileUtils.getFileSizeInKb(file.getFullPath())) - .initialHash(hash) - .currentHash(hash) - .addedOn(java.time.Instant.now()) - .build(); - - try { - log.debug("Creating additional file: {} (isBook: {}, type: {})", file.getFileName(), isBook, bookType); - bookAdditionalFileRepository.save(additionalFile); - - log.debug("Successfully created additional file: {}", file.getFileName()); - } catch (Exception e) { - bookEntity.getBookFiles().removeIf(a -> a.equals(additionalFile)); - - log.error("Error creating additional file {}: {}", file.getFileName(), e.getMessage(), e); - } - } - - public record GetOrCreateBookResult(Optional bookEntity, List remainingFiles) { - } - - public record CreateBookResult(BookEntity bookEntity, LibraryFile libraryFile) { - } - -} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileHelper.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileHelper.java index ff0052ed6..ffb2aa682 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileHelper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileHelper.java @@ -4,6 +4,7 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; import com.adityachandel.booklore.model.enums.BookFileExtension; +import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.util.FileUtils; import lombok.extern.slf4j.Slf4j; import org.jspecify.annotations.NonNull; @@ -18,26 +19,36 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.Set; @Component @Slf4j public class LibraryFileHelper { - public List getLibraryFiles(LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException { + private static final int MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK = 2; + + public List getLibraryFiles(LibraryEntity libraryEntity) throws IOException { List allFiles = new ArrayList<>(); for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) { - allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity, processor)); + allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity)); } return allFiles; } - private List findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException { + private List findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity) throws IOException { Path libraryPath = Path.of(pathEntity.getPath()); - boolean supportsSupplementaryFiles = processor.supportsSupplementaryFiles(); List libraryFiles = new ArrayList<>(); + // Track directories that contain audio files for folder-based audiobook detection + Map> dirAudioFiles = new HashMap<>(); + Map dirHasNonAudioBooks = new HashMap<>(); + Set processedAsFolderAudiobook = new HashSet<>(); + Files.walkFileTree(libraryPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<>() { @Override @NonNull @@ -49,20 +60,98 @@ public class LibraryFileHelper { String fileName = file.getFileName().toString(); Optional bookExtension = BookFileExtension.fromFileName(fileName); - if (bookExtension.isEmpty() && !supportsSupplementaryFiles) { + if (bookExtension.isEmpty()) { return FileVisitResult.CONTINUE; } - libraryFiles.add(LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(pathEntity) - .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), file)) - .fileName(fileName) - .bookFileType(bookExtension.map(BookFileExtension::getType).orElse(null)) - .build()); + Path parentDir = file.getParent(); + BookFileType fileType = bookExtension.get().getType(); + + if (fileType == BookFileType.AUDIOBOOK) { + // Track audio files per directory for folder-based detection + dirAudioFiles.computeIfAbsent(parentDir, k -> new ArrayList<>()).add(file); + } else { + // Track that this directory has non-audio book files + dirHasNonAudioBooks.put(parentDir, true); + + // Add non-audio files immediately + libraryFiles.add(LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), file)) + .fileName(fileName) + .bookFileType(fileType) + .build()); + } + return FileVisitResult.CONTINUE; } + @Override + @NonNull + public FileVisitResult postVisitDirectory(@NonNull Path dir, IOException exc) throws IOException { + // Check if this directory should be treated as a folder-based audiobook + List audioFiles = dirAudioFiles.get(dir); + boolean hasNonAudioBooks = dirHasNonAudioBooks.getOrDefault(dir, false); + + if (audioFiles != null && audioFiles.size() >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBooks) { + // This is a folder-based audiobook: contains 2+ audio files and no ebook files + // Don't treat library root as audiobook folder + if (!dir.equals(libraryPath)) { + log.info("Detected folder-based audiobook: {} ({} audio files)", dir.getFileName(), audioFiles.size()); + + processedAsFolderAudiobook.add(dir); + + // Add a single LibraryFile representing the folder + libraryFiles.add(LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), dir)) + .fileName(dir.getFileName().toString()) + .bookFileType(BookFileType.AUDIOBOOK) + .folderBased(true) + .build()); + } else { + // Library root - add individual audio files + addIndividualAudioFiles(audioFiles, libraryEntity, pathEntity, libraryFiles); + } + } else if (audioFiles != null) { + // Not a folder-based audiobook - add individual audio files + // But skip if parent was already processed as folder-based audiobook + boolean parentIsAudiobookFolder = false; + Path parent = dir.getParent(); + while (parent != null && parent.startsWith(libraryPath)) { + if (processedAsFolderAudiobook.contains(parent)) { + parentIsAudiobookFolder = true; + break; + } + parent = parent.getParent(); + } + + if (!parentIsAudiobookFolder) { + addIndividualAudioFiles(audioFiles, libraryEntity, pathEntity, libraryFiles); + } + } + + return FileVisitResult.CONTINUE; + } + + private void addIndividualAudioFiles(List audioFiles, LibraryEntity libraryEntity, + LibraryPathEntity pathEntity, List libraryFiles) { + for (Path audioFile : audioFiles) { + String fileName = audioFile.getFileName().toString(); + Optional ext = BookFileExtension.fromFileName(fileName); + + libraryFiles.add(LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), audioFile)) + .fileName(fileName) + .bookFileType(ext.map(BookFileExtension::getType).orElse(BookFileType.AUDIOBOOK)) + .build()); + } + } + @Override @NonNull public FileVisitResult visitFileFailed(@NonNull Path file, IOException e) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessor.java deleted file mode 100644 index be7788555..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessor.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.adityachandel.booklore.service.library; - -import com.adityachandel.booklore.model.dto.settings.LibraryFile; -import com.adityachandel.booklore.model.entity.LibraryEntity; - -import java.util.List; - -import com.adityachandel.booklore.model.enums.LibraryScanMode; - -public interface LibraryFileProcessor { - LibraryScanMode getScanMode(); - void processLibraryFiles(List libraryFiles, LibraryEntity libraryEntity); - - /** - * Indicates whether this processor supports supplementary files (any file type) - * in addition to book files. - * @return true if supplementary files are supported, false otherwise - */ - default boolean supportsSupplementaryFiles() { - return false; - } -} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessorRegistry.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessorRegistry.java deleted file mode 100644 index d117e7283..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessorRegistry.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.adityachandel.booklore.service.library; - -import com.adityachandel.booklore.model.entity.LibraryEntity; -import com.adityachandel.booklore.model.enums.LibraryScanMode; -import org.springframework.stereotype.Component; - -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; - -@Component -public class LibraryFileProcessorRegistry { - - private final Map processorMap; - - public LibraryFileProcessorRegistry(List processors) { - this.processorMap = processors.stream() - .collect(Collectors.toMap(LibraryFileProcessor::getScanMode, Function.identity())); - } - - public LibraryFileProcessor getProcessor(LibraryEntity libraryEntity) { - return processorMap.get(libraryEntity.getScanMode()); - } -} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java index 69b1dc44b..07d405a2b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java @@ -5,12 +5,15 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookFileEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; import com.adityachandel.booklore.model.websocket.LogNotification; import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.BookAdditionalFileRepository; import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.file.FileFingerprint; import com.adityachandel.booklore.task.options.RescanLibraryContext; +import com.adityachandel.booklore.util.FileUtils; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import lombok.AllArgsConstructor; @@ -22,7 +25,9 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @@ -34,10 +39,11 @@ public class LibraryProcessingService { private final LibraryRepository libraryRepository; private final NotificationService notificationService; private final BookAdditionalFileRepository bookAdditionalFileRepository; - private final LibraryFileProcessorRegistry fileProcessorRegistry; + private final FileAsBookProcessor fileAsBookProcessor; private final BookRestorationService bookRestorationService; private final BookDeletionService bookDeletionService; private final LibraryFileHelper libraryFileHelper; + private final BookGroupingService bookGroupingService; @PersistenceContext private final EntityManager entityManager; @@ -45,10 +51,14 @@ public class LibraryProcessingService { public void processLibrary(long libraryId) { LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); notificationService.sendMessage(Topic.LOG, LogNotification.info("Started processing library: " + libraryEntity.getName())); - LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity); try { - List libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity, processor); - processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity); + List libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity); + List newFiles = detectNewBookPaths(libraryFiles, libraryEntity); + + // Use BookGroupingService for consistent grouping based on organization mode + Map> groups = bookGroupingService.groupForInitialScan(newFiles, libraryEntity); + fileAsBookProcessor.processLibraryFilesGrouped(groups, libraryEntity); + notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished processing library: " + libraryEntity.getName())); } catch (IOException e) { log.error("Failed to process library {}: {}", libraryEntity.getName(), e.getMessage(), e); @@ -61,23 +71,22 @@ public class LibraryProcessingService { public void rescanLibrary(RescanLibraryContext context) throws IOException { LibraryEntity libraryEntity = libraryRepository.findById(context.getLibraryId()).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(context.getLibraryId())); notificationService.sendMessage(Topic.LOG, LogNotification.info("Started refreshing library: " + libraryEntity.getName())); - LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity); - + validateLibraryPathsAccessible(libraryEntity); - - List libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity, processor); - + + List libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity); + int existingBookCount = libraryEntity.getBookEntities().size(); if (existingBookCount > 0 && libraryFiles.isEmpty()) { String paths = libraryEntity.getLibraryPaths().stream() - .map(p -> p.getPath()) + .map(LibraryPathEntity::getPath) .collect(Collectors.joining(", ")); - log.error("Library '{}' has {} existing books but scan found 0 files. Paths may be offline: {}", + log.error("Library '{}' has {} existing books but scan found 0 files. Paths may be offline: {}", libraryEntity.getName(), existingBookCount, paths); throw ApiError.LIBRARY_PATH_NOT_ACCESSIBLE.createException(paths); } - - List additionalFileIds = detectDeletedAdditionalFiles(libraryFiles, libraryEntity, processor); + + List additionalFileIds = detectDeletedAdditionalFiles(libraryFiles, libraryEntity); if (!additionalFileIds.isEmpty()) { log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName()); bookDeletionService.deleteRemovedAdditionalFiles(additionalFileIds); @@ -89,14 +98,27 @@ public class LibraryProcessingService { } bookRestorationService.restoreDeletedBooks(libraryFiles); entityManager.clear(); - processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity); + + List newFiles = detectNewBookPaths(libraryFiles, libraryEntity); + + // Use BookGroupingService to determine what to attach vs create new + BookGroupingService.GroupingResult groupingResult = bookGroupingService.groupForRescan(newFiles, libraryEntity); + + // Auto-attach files to existing books + for (Map.Entry> entry : groupingResult.filesToAttach().entrySet()) { + for (LibraryFile file : entry.getValue()) { + autoAttachFile(entry.getKey(), file); + } + } + + // Process new book groups + fileAsBookProcessor.processLibraryFilesGrouped(groupingResult.newBookGroups(), libraryEntity); notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished refreshing library: " + libraryEntity.getName())); } public void processLibraryFiles(List libraryFiles, LibraryEntity libraryEntity) { - LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity); - processor.processLibraryFiles(libraryFiles, libraryEntity); + fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); } private void validateLibraryPathsAccessible(LibraryEntity libraryEntity) { @@ -117,8 +139,9 @@ public class LibraryProcessingService { return libraryEntity.getBookEntities().stream() .filter(book -> (book.getDeleted() == null || !book.getDeleted())) .filter(book -> { - if (book.getBookFiles() == null || book.getBookFiles().isEmpty()) { - return true; + // Don't mark fileless books as deleted - they're intentionally without files + if (!book.hasFiles()) { + return false; } return !currentFullPaths.contains(book.getFullFilePath()); }) @@ -143,12 +166,63 @@ public class LibraryProcessingService { .collect(Collectors.toList()); } + private void autoAttachFile(BookEntity book, LibraryFile file) { + // Check if file already exists to prevent duplicates during concurrent rescans + var existing = bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName( + file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName()); + if (existing.isPresent()) { + log.debug("Additional file already exists, skipping: {}", file.getFileName()); + return; + } + + // Set libraryPath if not set (fileless books like physical books don't have one) + if (book.getLibraryPath() == null) { + book.setLibraryPath(file.getLibraryPathEntity()); + } else if (!book.getLibraryPath().getId().equals(file.getLibraryPathEntity().getId())) { + // Book already has a different libraryPath - cannot attach files from different paths + log.warn("Cannot attach file '{}' to book id={}: file is in libraryPath {} but book is in libraryPath {}", + file.getFileName(), book.getId(), file.getLibraryPathEntity().getId(), book.getLibraryPath().getId()); + return; + } + + String hash = file.isFolderBased() + ? FileFingerprint.generateFolderHash(file.getFullPath()) + : FileFingerprint.generateHash(file.getFullPath()); + Long fileSizeKb = file.isFolderBased() + ? FileUtils.getFolderSizeInKb(file.getFullPath()) + : FileUtils.getFileSizeInKb(file.getFullPath()); + BookFileEntity additionalFile = BookFileEntity.builder() + .book(book) + .fileName(file.getFileName()) + .fileSubPath(file.getFileSubPath()) + .isBookFormat(true) + .bookType(file.getBookFileType()) + .folderBased(file.isFolderBased()) + .fileSizeKb(fileSizeKb) + .initialHash(hash) + .currentHash(hash) + .addedOn(Instant.now()) + .build(); + + try { + bookAdditionalFileRepository.save(additionalFile); + String primaryFileName = book.hasFiles() ? book.getPrimaryBookFile().getFileName() : "book#" + book.getId(); + log.info("Auto-attached new format {} to existing book: {}", file.getFileName(), primaryFileName); + } catch (Exception e) { + log.error("Error auto-attaching file {}: {}", file.getFileName(), e.getMessage()); + } + } + private String generateUniqueKey(BookEntity book) { - return generateKey(book.getLibraryPath().getId(), book.getPrimaryBookFile().getFileSubPath(), book.getPrimaryBookFile().getFileName()); + BookFileEntity primaryFile = book.getPrimaryBookFile(); + if (primaryFile == null) { + // Fileless book - use a unique key that won't match any file + return "fileless:" + book.getId(); + } + return generateKey(book.getLibraryPath().getId(), primaryFile.getFileSubPath(), primaryFile.getFileName()); } private String generateUniqueKey(BookFileEntity file) { - // Additional files inherit library path from their parent book return generateKey(file.getBook().getLibraryPath().getId(), file.getFileSubPath(), file.getFileName()); } @@ -161,7 +235,7 @@ public class LibraryProcessingService { return libraryPathId + ":" + safeSubPath + ":" + fileName; } - protected List detectDeletedAdditionalFiles(List libraryFiles, LibraryEntity libraryEntity, LibraryFileProcessor processor) { + protected List detectDeletedAdditionalFiles(List libraryFiles, LibraryEntity libraryEntity) { Set currentFileKeys = libraryFiles.stream() .map(this::generateUniqueKey) .collect(Collectors.toSet()); @@ -169,8 +243,7 @@ public class LibraryProcessingService { List allAdditionalFiles = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId()); return allAdditionalFiles.stream() - // Only check files that would be scanned: book formats always, non-book files only if processor supports them - .filter(additionalFile -> additionalFile.isBookFormat() || processor.supportsSupplementaryFiles()) + .filter(BookFileEntity::isBookFormat) .filter(additionalFile -> !currentFileKeys.contains(generateUniqueKey(additionalFile))) .map(BookFileEntity::getId) .collect(Collectors.toList()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryRescanHelper.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryRescanHelper.java index e132314d4..5f0b2a8de 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryRescanHelper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryRescanHelper.java @@ -63,6 +63,12 @@ public class LibraryRescanHelper { continue; } + // Skip fileless books (e.g., physical books) - they have no file to extract metadata from + if (!bookEntity.hasFiles()) { + processedBooks++; + continue; + } + if (taskId != null && cancellationManager.isTaskCancelled(taskId)) { log.info("Library rescan for library {} was cancelled", library.getId()); sendTaskProgressNotification(taskId, (processedBooks * 100) / totalBooks, diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java index 0dad29efb..bd47bd3c3 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java @@ -14,7 +14,6 @@ import com.adityachandel.booklore.model.entity.BookLoreUserEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; import com.adityachandel.booklore.model.enums.BookFileType; -import com.adityachandel.booklore.model.enums.LibraryScanMode; import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.LibraryPathRepository; @@ -77,10 +76,7 @@ public class LibraryService { library.setIcon(request.getIcon()); library.setIconType(request.getIconType()); library.setWatch(request.isWatch()); - if (request.getScanMode() != null) { - library.setScanMode(request.getScanMode()); - } - library.setDefaultBookFormat(request.getDefaultBookFormat()); + library.setFormatPriority(request.getFormatPriority()); Set currentPaths = library.getLibraryPaths().stream() .map(LibraryPathEntity::getPath) @@ -159,8 +155,7 @@ public class LibraryService { .icon(request.getIcon()) .iconType(request.getIconType()) .watch(request.isWatch()) - .scanMode(request.getScanMode() != null ? request.getScanMode() : LibraryScanMode.FILE_AS_BOOK) - .defaultBookFormat(request.getDefaultBookFormat()) + .formatPriority(request.getFormatPriority()) .users(List.of(user.get())) .build(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookCoverService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookCoverService.java index 049504797..f766aceba 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookCoverService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookCoverService.java @@ -140,7 +140,11 @@ public class BookCoverService { if (isCoverLocked(bookEntity)) { throw ApiError.METADATA_LOCKED.createException(); } - BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookEntity.getPrimaryBookFile().getBookType()); + var primaryFile = bookEntity.getPrimaryBookFile(); + if (primaryFile == null) { + throw ApiError.FAILED_TO_REGENERATE_COVER.createException(); + } + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(primaryFile.getBookType()); boolean success = processor.generateCover(bookEntity); if (!success) { throw ApiError.FAILED_TO_REGENERATE_COVER.createException(); @@ -173,6 +177,7 @@ public class BookCoverService { try { List books = bookQueryService.getAllFullBookEntities().stream() .filter(book -> !isCoverLocked(book)) + .filter(book -> book.getPrimaryBookFile() != null) .map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getPrimaryBookFile().getBookType(), false)) .toList(); int total = books.size(); @@ -188,7 +193,12 @@ public class BookCoverService { transactionTemplate.execute(status -> { bookRepository.findById(bookInfo.id()).ifPresent(book -> { - BookFileProcessor processor = processorRegistry.getProcessorOrThrow(book.getPrimaryBookFile().getBookType()); + var primaryFile = book.getPrimaryBookFile(); + if (primaryFile == null) { + log.warn("{}Skipping physical book ID {} ({}) - no file to regenerate cover from", progress, book.getId(), bookInfo.title()); + return; + } + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(primaryFile.getBookType()); boolean success = processor.generateCover(book); if (success) { @@ -382,6 +392,7 @@ public class BookCoverService { private List getUnlockedBookRegenerationInfos(Set bookIds) { return bookQueryService.findAllWithMetadataByIds(bookIds).stream() .filter(book -> !isCoverLocked(book)) + .filter(book -> book.getPrimaryBookFile() != null) .map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getPrimaryBookFile().getBookType(), false)) .toList(); } @@ -400,15 +411,21 @@ public class BookCoverService { } private void writeCoverToBookFile(BookEntity bookEntity, BiConsumer writerAction) { + var primaryFile = bookEntity.getPrimaryBookFile(); + if (primaryFile == null) { + // Physical book with no files - skip writing cover to file + return; + } + MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz(); - if ((bookEntity.getPrimaryBookFile().getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) { - metadataWriterFactory.getWriter(bookEntity.getPrimaryBookFile().getBookType()) + if ((primaryFile.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) { + metadataWriterFactory.getWriter(primaryFile.getBookType()) .ifPresent(writer -> { writerAction.accept(writer, bookEntity); String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); - bookEntity.getPrimaryBookFile().setCurrentHash(newHash); + primaryFile.setCurrentHash(newHash); }); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java index 99e954839..05d3bb86c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java @@ -125,8 +125,9 @@ public class BookMetadataService { public BookMetadata getComicInfoMetadata(long bookId) { log.info("Extracting ComicInfo metadata for book ID: {}", bookId); BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - if (bookEntity.getPrimaryBookFile().getBookType() != BookFileType.CBX) { - log.info("Unsupported operation for file type: {}", bookEntity.getPrimaryBookFile().getBookType().name()); + var primaryFile = bookEntity.getPrimaryBookFile(); + if (primaryFile == null || primaryFile.getBookType() != BookFileType.CBX) { + log.info("Unsupported operation for book ID {} - no file or not CBX type", bookId); return null; } return cbxMetadataExtractor.extractMetadata(new File(FileUtils.getBookFullPath(bookEntity))); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java index 4e9338023..ecef2dd44 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java @@ -87,7 +87,7 @@ public class BookMetadataUpdater { MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); MetadataPersistenceSettings.SaveToOriginalFile writeToFile = settings.getSaveToOriginalFile(); var primaryFile = bookEntity.getPrimaryBookFile(); - BookFileType bookType = primaryFile.getBookType(); + BookFileType bookType = primaryFile != null ? primaryFile.getBookType() : null; boolean hasValueChangesForFileWrite = MetadataChangeDetector.hasValueChangesForFileWrite(newMetadata, metadata, clearFlags); @@ -109,7 +109,7 @@ public class BookMetadataUpdater { log.warn("Failed to calculate metadata match score for book ID {}: {}", bookId, e.getMessage()); } - if ((writeToFile.isAnyFormatEnabled() && hasValueChangesForFileWrite) || thumbnailRequiresUpdate) { + if (primaryFile != null && bookType != null && ((writeToFile.isAnyFormatEnabled() && hasValueChangesForFileWrite) || thumbnailRequiresUpdate)) { metadataWriterFactory.getWriter(bookType).ifPresent(writer -> { try { String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null; @@ -130,14 +130,16 @@ public class BookMetadataUpdater { } boolean moveFilesToLibraryPattern = settings.isMoveFilesToLibraryPattern(); - if (moveFilesToLibraryPattern) { + if (moveFilesToLibraryPattern && primaryFile != null) { try { BookEntity book = metadata.getBook(); FileMoveResult result = fileMoveService.moveSingleFile(book); if (result.isMoved()) { var bookPrimaryFile = book.getPrimaryBookFile(); - bookPrimaryFile.setFileName(result.getNewFileName()); - bookPrimaryFile.setFileSubPath(result.getNewFileSubPath()); + if (bookPrimaryFile != null) { + bookPrimaryFile.setFileName(result.getNewFileName()); + bookPrimaryFile.setFileSubPath(result.getNewFileSubPath()); + } } } catch (Exception e) { log.warn("Failed to move files for book ID {} after metadata update: {}", bookId, e.getMessage()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/DuckDuckGoCoverService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/DuckDuckGoCoverService.java index 3ea7d277f..d308fd745 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/DuckDuckGoCoverService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/DuckDuckGoCoverService.java @@ -27,8 +27,10 @@ public class DuckDuckGoCoverService implements BookCoverProvider { private static final String SEARCH_BASE_URL = "https://duckduckgo.com/?q="; private static final String JSON_BASE_URL = "https://duckduckgo.com/i.js?o=json&q="; private static final String SITE_FILTER = "+(site%3Aamazon.com+OR+site%3Agoodreads.com)"; - private static final String SEARCH_PARAMS = "&iar=images&iaf=size%3ALarge%2Clayout%3ATall"; - private static final String JSON_PARAMS = "&iar=images&iaf=size%3ALarge%2Clayout%3ATall"; + private static final String SEARCH_PARAMS_TALL = "&iar=images&iaf=size%3ALarge%2Clayout%3ATall"; + private static final String JSON_PARAMS_TALL = "&iar=images&iaf=size%3ALarge%2Clayout%3ATall"; + private static final String SEARCH_PARAMS_SQUARE = "&iar=images&iaf=size%3ALarge%2Clayout%3ASquare"; + private static final String JSON_PARAMS_SQUARE = "&iar=images&iaf=size%3ALarge%2Clayout%3ASquare"; private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"; private static final String REFERRER = "https://duckduckgo.com/"; @@ -63,12 +65,17 @@ public class DuckDuckGoCoverService implements BookCoverProvider { public List getCovers(CoverFetchRequest request) { String title = request.getTitle(); String author = request.getAuthor(); + boolean squareCover = request.isSquareCover(); + String bookType = squareCover ? "audiobook" : "book"; String searchTerm = (author != null && !author.isEmpty()) - ? title + " " + author + " book" - : title + " book"; + ? title + " " + author + " " + bookType + : title + " " + bookType; + + String searchParams = squareCover ? SEARCH_PARAMS_SQUARE : SEARCH_PARAMS_TALL; + String jsonParams = squareCover ? JSON_PARAMS_SQUARE : JSON_PARAMS_TALL; String encodedSiteQuery = URLEncoder.encode(searchTerm, StandardCharsets.UTF_8); - String siteUrl = SEARCH_BASE_URL + encodedSiteQuery + SITE_FILTER + SEARCH_PARAMS; + String siteUrl = SEARCH_BASE_URL + encodedSiteQuery + SITE_FILTER + searchParams; Connection.Response siteResponse = getResponse(siteUrl); Document siteDoc = parseResponse(siteResponse); Map cookies = siteResponse.cookies(); @@ -79,15 +86,19 @@ public class DuckDuckGoCoverService implements BookCoverProvider { return Collections.emptyList(); } String siteSearchToken = siteMatcher.group(1); - List siteFilteredImages = fetchImagesFromApi(searchTerm + " (site:amazon.com OR site:goodreads.com)", siteSearchToken, cookies, siteUrl); + List siteFilteredImages = fetchImagesFromApi(searchTerm + " (site:amazon.com OR site:goodreads.com)", siteSearchToken, cookies, siteUrl, jsonParams); siteFilteredImages.removeIf(dto -> dto.getWidth() < 350); - siteFilteredImages.removeIf(dto -> dto.getWidth() >= dto.getHeight()); + if (squareCover) { + siteFilteredImages.removeIf(dto -> !isApproximatelySquare(dto.getWidth(), dto.getHeight())); + } else { + siteFilteredImages.removeIf(dto -> dto.getWidth() >= dto.getHeight()); + } if (siteFilteredImages.size() > 7) { siteFilteredImages = siteFilteredImages.subList(0, 7); } String encodedGeneralQuery = URLEncoder.encode(searchTerm, StandardCharsets.UTF_8); - String generalUrl = SEARCH_BASE_URL + encodedGeneralQuery + SEARCH_PARAMS; + String generalUrl = SEARCH_BASE_URL + encodedGeneralQuery + searchParams; Connection.Response generalResponse = getResponse(generalUrl); Document generalDoc = parseResponse(generalResponse); Map generalCookies = generalResponse.cookies(); @@ -95,9 +106,13 @@ public class DuckDuckGoCoverService implements BookCoverProvider { List generalBookImages = new ArrayList<>(); if (generalMatcher.find()) { String generalSearchToken = generalMatcher.group(1); - generalBookImages = fetchImagesFromApi(searchTerm, generalSearchToken, generalCookies, generalUrl); + generalBookImages = fetchImagesFromApi(searchTerm, generalSearchToken, generalCookies, generalUrl, jsonParams); generalBookImages.removeIf(dto -> dto.getWidth() < 350); - generalBookImages.removeIf(dto -> dto.getWidth() >= dto.getHeight()); + if (squareCover) { + generalBookImages.removeIf(dto -> !isApproximatelySquare(dto.getWidth(), dto.getHeight())); + } else { + generalBookImages.removeIf(dto -> dto.getWidth() >= dto.getHeight()); + } Set siteUrls = siteFilteredImages.stream().map(CoverImage::getUrl).collect(Collectors.toSet()); generalBookImages.removeIf(dto -> siteUrls.contains(dto.getUrl())); if (generalBookImages.size() > 10) { @@ -121,13 +136,13 @@ public class DuckDuckGoCoverService implements BookCoverProvider { return allImages; } - private List fetchImagesFromApi(String query, String searchToken, Map cookies, String referrerUrl) { + private List fetchImagesFromApi(String query, String searchToken, Map cookies, String referrerUrl, String jsonParams) { List priority = new ArrayList<>(); List others = new ArrayList<>(); try { String url = JSON_BASE_URL + URLEncoder.encode(query, StandardCharsets.UTF_8) - + JSON_PARAMS + + jsonParams + "&vqd=" + searchToken; Connection.Response resp = Jsoup.connect(url) @@ -185,4 +200,10 @@ public class DuckDuckGoCoverService implements BookCoverProvider { throw new RuntimeException(e); } } + + private boolean isApproximatelySquare(int width, int height) { + if (width == 0 || height == 0) return false; + double ratio = (double) width / height; + return ratio >= 0.85 && ratio <= 1.15; + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataRefreshService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataRefreshService.java index bc81b0855..4b5d529e0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataRefreshService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataRefreshService.java @@ -115,7 +115,7 @@ public class MetadataRefreshService { .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); try { if (book.getMetadata().areAllFieldsLocked()) { - log.info("Skipping locked book: {}", book.getPrimaryBookFile().getFileName()); + log.info("Skipping locked book: {}", getBookIdentifier(book)); sendBatchProgressNotification(jobId, finalCompletedCount, totalBooks, "Skipped locked book: " + book.getMetadata().getTitle(), MetadataFetchTaskStatus.IN_PROGRESS, isReviewMode); return null; } @@ -165,11 +165,11 @@ public class MetadataRefreshService { sendBatchProgressNotification(jobId, finalCompletedCount + 1, totalBooks, "Processed: " + book.getMetadata().getTitle(), MetadataFetchTaskStatus.IN_PROGRESS, bookReviewMode); } catch (Exception e) { if (Thread.currentThread().isInterrupted()) { - log.info("Processing interrupted for book: {}", book.getPrimaryBookFile().getFileName()); + log.info("Processing interrupted for book: {}", getBookIdentifier(book)); status.setRollbackOnly(); return null; } - log.error("Metadata update failed for book: {}", book.getPrimaryBookFile().getFileName(), e); + log.error("Metadata update failed for book: {}", getBookIdentifier(book), e); sendBatchProgressNotification(jobId, finalCompletedCount, totalBooks, String.format("Failed to process: %s - %s", book.getMetadata().getTitle(), e.getMessage()), MetadataFetchTaskStatus.ERROR, isReviewMode); } bookRepository.saveAndFlush(book); @@ -246,6 +246,16 @@ public class MetadataRefreshService { sendBatchProgressNotification(taskId, completedCount, total, message, MetadataFetchTaskStatus.IN_PROGRESS, isReviewMode); } + private String getBookIdentifier(BookEntity book) { + if (book.getPrimaryBookFile() != null && book.getPrimaryBookFile().getFileName() != null) { + return book.getPrimaryBookFile().getFileName(); + } + if (book.getMetadata() != null && book.getMetadata().getTitle() != null) { + return book.getMetadata().getTitle(); + } + return "Book ID: " + book.getId(); + } + private void sendBatchProgressNotification(String taskId, int current, int total, String message, MetadataFetchTaskStatus status, boolean isReview) { notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_PROGRESS, new MetadataBatchProgressNotification(taskId, current, total, message, status.name(), isReview)); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/AudiobookMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/AudiobookMetadataExtractor.java new file mode 100644 index 000000000..bbedcd9bd --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/AudiobookMetadataExtractor.java @@ -0,0 +1,162 @@ +package com.adityachandel.booklore.service.metadata.extractor; + +import com.adityachandel.booklore.model.dto.BookMetadata; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang3.StringUtils; +import org.jaudiotagger.audio.AudioFile; +import org.jaudiotagger.audio.AudioFileIO; +import org.jaudiotagger.tag.FieldKey; +import org.jaudiotagger.tag.Tag; +import org.jaudiotagger.tag.images.Artwork; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.time.LocalDate; +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +@Slf4j +@Component +public class AudiobookMetadataExtractor implements FileMetadataExtractor { + + static { + // Suppress verbose JAudioTagger logging + Logger.getLogger("org.jaudiotagger").setLevel(Level.WARNING); + } + + @Override + public BookMetadata extractMetadata(File audioFile) { + try { + AudioFile f = AudioFileIO.read(audioFile); + Tag tag = f.getTag(); + + if (tag == null) { + return BookMetadata.builder() + .title(FilenameUtils.getBaseName(audioFile.getName())) + .build(); + } + + BookMetadata.BookMetadataBuilder builder = BookMetadata.builder(); + + // Title - prefer album for audiobooks, fallback to title, then filename + String album = tag.getFirst(FieldKey.ALBUM); + String title = tag.getFirst(FieldKey.TITLE); + if (StringUtils.isNotBlank(album)) { + builder.title(album); + } else if (StringUtils.isNotBlank(title)) { + builder.title(title); + } else { + builder.title(FilenameUtils.getBaseName(audioFile.getName())); + } + + // Author - use album artist or artist + String albumArtist = tag.getFirst(FieldKey.ALBUM_ARTIST); + String artist = tag.getFirst(FieldKey.ARTIST); + Set authors = new HashSet<>(); + if (StringUtils.isNotBlank(albumArtist)) { + authors.add(albumArtist); + } else if (StringUtils.isNotBlank(artist)) { + authors.add(artist); + } + if (!authors.isEmpty()) { + builder.authors(authors); + } + + // Description - use comment field + String comment = tag.getFirst(FieldKey.COMMENT); + if (StringUtils.isNotBlank(comment)) { + builder.description(comment); + } + + // Publisher - use record label or publisher + String publisher = tag.getFirst(FieldKey.RECORD_LABEL); + if (StringUtils.isNotBlank(publisher)) { + builder.publisher(publisher); + } + + // Year/Date + String year = tag.getFirst(FieldKey.YEAR); + if (StringUtils.isNotBlank(year)) { + try { + int yearInt = Integer.parseInt(year.trim().substring(0, Math.min(4, year.trim().length()))); + if (yearInt >= 1 && yearInt <= 9999) { + builder.publishedDate(LocalDate.of(yearInt, 1, 1)); + } + } catch (NumberFormatException ignored) { + } + } + + // Genre as category + String genre = tag.getFirst(FieldKey.GENRE); + if (StringUtils.isNotBlank(genre)) { + Set categories = new HashSet<>(); + categories.add(genre); + builder.categories(categories); + } + + // Language + String language = tag.getFirst(FieldKey.LANGUAGE); + if (StringUtils.isNotBlank(language)) { + builder.language(language); + } + + // Series info from grouping or custom tags + String grouping = tag.getFirst(FieldKey.GROUPING); + if (StringUtils.isNotBlank(grouping)) { + builder.seriesName(grouping); + } + + // Try to extract track number as series number for multi-part audiobooks + String trackNo = tag.getFirst(FieldKey.TRACK); + if (StringUtils.isNotBlank(trackNo)) { + try { + String trackNum = trackNo.contains("/") ? trackNo.split("/")[0] : trackNo; + builder.seriesNumber((float) Integer.parseInt(trackNum.trim())); + } catch (NumberFormatException ignored) { + } + } + + // Try to get total tracks + String trackTotal = tag.getFirst(FieldKey.TRACK_TOTAL); + if (StringUtils.isNotBlank(trackTotal)) { + try { + builder.seriesTotal(Integer.parseInt(trackTotal.trim())); + } catch (NumberFormatException ignored) { + } + } + + return builder.build(); + + } catch (Exception e) { + log.error("Failed to read metadata from audio file {}: {}", audioFile.getName(), e.getMessage(), e); + return BookMetadata.builder() + .title(FilenameUtils.getBaseName(audioFile.getName())) + .build(); + } + } + + @Override + public byte[] extractCover(File audioFile) { + try { + AudioFile f = AudioFileIO.read(audioFile); + Tag tag = f.getTag(); + + if (tag == null) { + return null; + } + + Artwork artwork = tag.getFirstArtwork(); + if (artwork != null) { + return artwork.getBinaryData(); + } + + return null; + } catch (Exception e) { + log.warn("Failed to extract cover from audio file {}: {}", audioFile.getName(), e.getMessage()); + return null; + } + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/MetadataExtractorFactory.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/MetadataExtractorFactory.java index c99471a10..21e171813 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/MetadataExtractorFactory.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/MetadataExtractorFactory.java @@ -18,6 +18,7 @@ public class MetadataExtractorFactory { private final Fb2MetadataExtractor fb2MetadataExtractor; private final MobiMetadataExtractor mobiMetadataExtractor; private final Azw3MetadataExtractor azw3MetadataExtractor; + private final AudiobookMetadataExtractor audiobookMetadataExtractor; public BookMetadata extractMetadata(BookFileType bookFileType, File file) { return switch (bookFileType) { @@ -27,6 +28,7 @@ public class MetadataExtractorFactory { case FB2 -> fb2MetadataExtractor.extractMetadata(file); case MOBI -> mobiMetadataExtractor.extractMetadata(file); case AZW3 -> azw3MetadataExtractor.extractMetadata(file); + case AUDIOBOOK -> audiobookMetadataExtractor.extractMetadata(file); }; } @@ -38,6 +40,7 @@ public class MetadataExtractorFactory { case FB2 -> fb2MetadataExtractor.extractMetadata(file); case MOBI -> mobiMetadataExtractor.extractMetadata(file); case AZW3, AZW -> azw3MetadataExtractor.extractMetadata(file); + case M4B, M4A, MP3, AAC, FLAC, OPUS, OGG -> audiobookMetadataExtractor.extractMetadata(file); }; } @@ -49,6 +52,7 @@ public class MetadataExtractorFactory { case FB2 -> fb2MetadataExtractor.extractCover(file); case MOBI -> mobiMetadataExtractor.extractCover(file); case AZW3, AZW -> azw3MetadataExtractor.extractCover(file); + case M4B, M4A, MP3, AAC, FLAC, OPUS, OGG -> audiobookMetadataExtractor.extractCover(file); }; } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java index 5dac65f9f..aa9e161ad 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java @@ -276,8 +276,8 @@ public class AmazonBookParser implements BookParser { String title = fetchMetadataRequest.getTitle(); if (title != null && !title.isEmpty()) { searchTerm.append(cleanSearchTerm(title)); - } else { - String filename = BookUtils.cleanAndTruncateSearchTerm(BookUtils.cleanFileName(book.getFileName())); + } else if (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null) { + String filename = BookUtils.cleanAndTruncateSearchTerm(BookUtils.cleanFileName(book.getPrimaryFile().getFileName())); if (!filename.isEmpty()) { searchTerm.append(cleanSearchTerm(filename)); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/ComicvineBookParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/ComicvineBookParser.java index 1b7184568..48aa45d54 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/ComicvineBookParser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/ComicvineBookParser.java @@ -800,9 +800,9 @@ public class ComicvineBookParser implements BookParser { private String getSearchTerm(Book book, FetchMetadataRequest request) { if (request.getTitle() != null && !request.getTitle().isEmpty()) { return request.getTitle(); - } else if (book.getFileName() != null && !book.getFileName().isEmpty()) { + } else if (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null && !book.getPrimaryFile().getFileName().isEmpty()) { // Use filename but preserve parentheses for year extraction - String name = book.getFileName(); + String name = book.getPrimaryFile().getFileName(); // Remove extension only int dotIndex = name.lastIndexOf('.'); if (dotIndex > 0) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/DoubanBookParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/DoubanBookParser.java index eaaecf8da..64a10d093 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/DoubanBookParser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/DoubanBookParser.java @@ -116,7 +116,7 @@ public class DoubanBookParser implements BookParser { } private List getDoubanSearchResults(Book book, FetchMetadataRequest request) { - log.debug("Douban: Querying metadata for ISBN: {}, Title: {}, Author: {}, FileName: {}", request.getIsbn(), request.getTitle(), request.getAuthor(), book.getFileName()); + log.debug("Douban: Querying metadata for ISBN: {}, Title: {}, Author: {}, FileName: {}", request.getIsbn(), request.getTitle(), request.getAuthor(), book.getPrimaryFile() != null ? book.getPrimaryFile().getFileName() : null); String queryUrl = buildQueryUrl(request, book); if (queryUrl == null) { log.error("Query URL is null, cannot proceed."); @@ -309,8 +309,8 @@ public class DoubanBookParser implements BookParser { .filter(word -> !word.isEmpty()) .collect(Collectors.joining(" ")); searchTerm.append(cleanedTitle); - } else { - String filename = BookUtils.cleanAndTruncateSearchTerm(BookUtils.cleanFileName(book.getFileName())); + } else if (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null) { + String filename = BookUtils.cleanAndTruncateSearchTerm(BookUtils.cleanFileName(book.getPrimaryFile().getFileName())); if (!filename.isEmpty()) { String cleanedFilename = Arrays.stream(filename.split(" ")) .map(word -> NON_ALPHANUMERIC_CJK_PATTERN.matcher(word).replaceAll("").trim()) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java index e370c4c48..93bcd4da9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java @@ -497,8 +497,8 @@ public class GoodReadsParser implements BookParser { private String getSearchTerm(Book book, FetchMetadataRequest request) { return (request.getTitle() != null && !request.getTitle().isEmpty()) ? request.getTitle() - : (book.getFileName() != null && !book.getFileName().isEmpty() - ? BookUtils.cleanFileName(book.getFileName()) + : (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null && !book.getPrimaryFile().getFileName().isEmpty() + ? BookUtils.cleanFileName(book.getPrimaryFile().getFileName()) : null); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoogleParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoogleParser.java index 0ab702b15..202b344ff 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoogleParser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoogleParser.java @@ -444,7 +444,8 @@ public class GoogleParser implements BookParser { private String getSearchTerm(Book book, FetchMetadataRequest request) { String searchTerm = Optional.ofNullable(request.getTitle()) .filter(title -> !title.isEmpty()) - .orElseGet(() -> Optional.ofNullable(book.getFileName()) + .orElseGet(() -> Optional.ofNullable(book.getPrimaryFile()) + .map(pf -> pf.getFileName()) .filter(fileName -> !fileName.isEmpty()) .map(BookUtils::cleanFileName) .orElse(null)); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/RanobeDbParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/RanobeDbParser.java index 50fcc2ed9..66dbe875c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/RanobeDbParser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/RanobeDbParser.java @@ -157,8 +157,8 @@ public class RanobeDbParser implements BookParser { private String getSearchTerm(Book book, FetchMetadataRequest request) { if (request.getTitle() != null && !request.getTitle().isEmpty()) { return request.getTitle(); - } else if (book.getFileName() != null && !book.getFileName().isEmpty()) { - return BookUtils.cleanFileName(book.getFileName()); + } else if (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null && !book.getPrimaryFile().getFileName().isEmpty()) { + return BookUtils.cleanFileName(book.getPrimaryFile().getFileName()); } return null; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationStartup.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationStartup.java index 85a62e05d..71c147d7d 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationStartup.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/AppMigrationStartup.java @@ -20,6 +20,7 @@ public class AppMigrationStartup { private final PopulateSearchTextMigration populateSearchTextMigration; private final MoveIconsToDataFolderMigration moveIconsToDataFolderMigration; private final GenerateCoverHashMigration generateCoverHashMigration; + private final MigrateProgressToFileProgressMigration migrateProgressToFileProgressMigration; @EventListener(ApplicationReadyEvent.class) public void runMigrationsOnce() { @@ -32,5 +33,6 @@ public class AppMigrationStartup { appMigrationService.executeMigration(populateSearchTextMigration); appMigrationService.executeMigration(moveIconsToDataFolderMigration); appMigrationService.executeMigration(generateCoverHashMigration); + appMigrationService.executeMigration(migrateProgressToFileProgressMigration); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/migrations/MigrateProgressToFileProgressMigration.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/migrations/MigrateProgressToFileProgressMigration.java new file mode 100644 index 000000000..907f3efbc --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/migration/migrations/MigrateProgressToFileProgressMigration.java @@ -0,0 +1,161 @@ +package com.adityachandel.booklore.service.migration.migrations; + +import com.adityachandel.booklore.model.entity.BookFileEntity; +import com.adityachandel.booklore.model.entity.UserBookFileProgressEntity; +import com.adityachandel.booklore.model.entity.UserBookProgressEntity; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.repository.UserBookFileProgressRepository; +import com.adityachandel.booklore.repository.UserBookProgressRepository; +import com.adityachandel.booklore.service.migration.Migration; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Optional; + +@Slf4j +@Component +@RequiredArgsConstructor +public class MigrateProgressToFileProgressMigration implements Migration { + + private final UserBookProgressRepository userBookProgressRepository; + private final UserBookFileProgressRepository userBookFileProgressRepository; + + @Override + public String getKey() { + return "migrateProgressToFileProgress"; + } + + @Override + public String getDescription() { + return "Migrate existing reading progress from UserBookProgressEntity to UserBookFileProgressEntity"; + } + + @Override + @Transactional + public void execute() { + log.info("Starting migration: {}", getKey()); + + List allProgress = userBookProgressRepository.findAll(); + int migratedCount = 0; + int skippedCount = 0; + + for (UserBookProgressEntity progress : allProgress) { + if (!hasAnyProgress(progress)) { + skippedCount++; + continue; + } + + try { + Optional bookFileOpt = findBookFileForProgress(progress); + if (bookFileOpt.isEmpty()) { + log.debug("No matching book file found for progress id={}, bookId={}", + progress.getId(), progress.getBook().getId()); + skippedCount++; + continue; + } + + BookFileEntity bookFile = bookFileOpt.get(); + + // Check if file progress already exists + Optional existingFileProgress = + userBookFileProgressRepository.findByUserIdAndBookFileId( + progress.getUser().getId(), bookFile.getId()); + + if (existingFileProgress.isPresent()) { + log.debug("File progress already exists for userId={}, bookFileId={}", + progress.getUser().getId(), bookFile.getId()); + skippedCount++; + continue; + } + + UserBookFileProgressEntity fileProgress = createFileProgress(progress, bookFile); + userBookFileProgressRepository.save(fileProgress); + migratedCount++; + } catch (Exception e) { + log.warn("Failed to migrate progress for progressId={}: {}", + progress.getId(), e.getMessage()); + skippedCount++; + } + } + + log.info("Migration '{}' completed. Migrated: {}, Skipped: {}", + getKey(), migratedCount, skippedCount); + } + + private boolean hasAnyProgress(UserBookProgressEntity progress) { + return progress.getPdfProgress() != null || + progress.getEpubProgress() != null || + progress.getCbxProgress() != null; + } + + private Optional findBookFileForProgress(UserBookProgressEntity progress) { + if (progress.getBook() == null || progress.getBook().getBookFiles() == null) { + return Optional.empty(); + } + + List bookFiles = progress.getBook().getBookFiles(); + if (bookFiles.isEmpty()) { + return Optional.empty(); + } + + // Determine which type of progress we have and find matching book file + if (progress.getPdfProgress() != null) { + return findBookFileByType(bookFiles, BookFileType.PDF); + } else if (progress.getEpubProgress() != null) { + // EPUB progress can apply to EPUB, FB2, MOBI, AZW3 + return findBookFileByTypes(bookFiles, BookFileType.EPUB, BookFileType.FB2, + BookFileType.MOBI, BookFileType.AZW3); + } else if (progress.getCbxProgress() != null) { + return findBookFileByType(bookFiles, BookFileType.CBX); + } + + return Optional.empty(); + } + + private Optional findBookFileByType(List bookFiles, BookFileType type) { + return bookFiles.stream() + .filter(bf -> bf.isBookFormat() && bf.getBookType() == type) + .findFirst(); + } + + private Optional findBookFileByTypes(List bookFiles, BookFileType... types) { + for (BookFileType type : types) { + Optional found = findBookFileByType(bookFiles, type); + if (found.isPresent()) { + return found; + } + } + return Optional.empty(); + } + + private UserBookFileProgressEntity createFileProgress(UserBookProgressEntity progress, BookFileEntity bookFile) { + UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity(); + fileProgress.setUser(progress.getUser()); + fileProgress.setBookFile(bookFile); + fileProgress.setLastReadTime(progress.getLastReadTime()); + + // Map progress data based on book type + switch (bookFile.getBookType()) { + case PDF -> { + fileProgress.setPositionData(progress.getPdfProgress() != null ? + String.valueOf(progress.getPdfProgress()) : null); + fileProgress.setProgressPercent(progress.getPdfProgressPercent()); + } + case EPUB, FB2, MOBI, AZW3 -> { + fileProgress.setPositionData(progress.getEpubProgress()); + fileProgress.setPositionHref(progress.getEpubProgressHref()); + fileProgress.setProgressPercent(progress.getEpubProgressPercent()); + } + case CBX -> { + fileProgress.setPositionData(progress.getCbxProgress() != null ? + String.valueOf(progress.getCbxProgress()) : null); + fileProgress.setProgressPercent(progress.getCbxProgressPercent()); + } + } + + return fileProgress; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsFeedService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsFeedService.java index ae8ed01bc..8d64c6700 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsFeedService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsFeedService.java @@ -3,11 +3,11 @@ package com.adityachandel.booklore.service.opds; import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails; import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.BookFile; import com.adityachandel.booklore.model.dto.Library; import com.adityachandel.booklore.model.enums.OpdsSortOrder; import com.adityachandel.booklore.service.MagicShelfService; import com.adityachandel.booklore.util.ArchiveUtils; -import com.adityachandel.booklore.util.FileUtils; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -543,9 +543,17 @@ public class OpdsFeedService { } private void appendLinks(StringBuilder feed, Book book) { - String mimeType = fileMimeType(book); - feed.append(" \n"); + // Add acquisition link for primary file + if (book.getPrimaryFile() != null) { + appendAcquisitionLink(feed, book.getId(), book.getPrimaryFile()); + } + + // Add acquisition links for alternative formats + if (book.getAlternativeFormats() != null) { + for (BookFile altFormat : book.getAlternativeFormats()) { + appendAcquisitionLink(feed, book.getId(), altFormat); + } + } if (book.getMetadata() != null && book.getMetadata().getCoverUpdatedOn() != null) { String coverUrl = "/api/v1/opds/" + book.getId() + "/cover?" + book.getMetadata().getCoverUpdatedOn(); @@ -556,6 +564,26 @@ public class OpdsFeedService { } } + private void appendAcquisitionLink(StringBuilder feed, Long bookId, BookFile bookFile) { + if (bookFile == null || bookFile.getId() == null) return; + + String mimeType = fileMimeType(bookFile); + feed.append(" \n"); + } + private String determineFeedTitle(Long libraryId, Set shelfIds, Long magicShelfId, String author, String series) { if (magicShelfId != null) { return magicShelfBookService.getMagicShelfName(magicShelfId); @@ -604,23 +632,22 @@ public class OpdsFeedService { return DateTimeFormatter.ISO_INSTANT.format(java.time.Instant.now()); } - private boolean hasValidFilePath(Book book) { - return book.getFileName() != null - && book.getLibraryPath() != null - && book.getLibraryPath().getPath() != null - && book.getFileSubPath() != null; + private boolean hasValidFilePath(BookFile bookFile) { + return bookFile != null + && bookFile.getFileName() != null + && bookFile.getFilePath() != null; } - private String fileMimeType(Book book) { - if (book == null || book.getBookType() == null) { + private String fileMimeType(BookFile bookFile) { + if (bookFile == null || bookFile.getBookType() == null) { return "application/octet-stream"; } - return switch (book.getBookType()) { + return switch (bookFile.getBookType()) { case PDF -> "application/pdf"; case EPUB -> "application/epub+zip"; case FB2 -> { - if (hasValidFilePath(book)) { - ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(new File(FileUtils.getBookFullPath(book))); + if (hasValidFilePath(bookFile)) { + ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(new File(bookFile.getFilePath())); if (type == ArchiveUtils.ArchiveType.ZIP) { yield "application/zip"; } @@ -630,8 +657,8 @@ public class OpdsFeedService { case MOBI -> "application/x-mobipocket-ebook"; case AZW3 -> "application/vnd.amazon.ebook"; case CBX -> { - if (book.getArchiveType() != null) { - yield switch (book.getArchiveType()) { + if (bookFile.getArchiveType() != null) { + yield switch (bookFile.getArchiveType()) { case RAR -> "application/vnd.comicbook-rar"; case ZIP -> "application/vnd.comicbook+zip"; case SEVEN_ZIP -> "application/x-7z-compressed"; @@ -639,14 +666,14 @@ public class OpdsFeedService { }; } - if (hasValidFilePath(book)) { - ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(new File(FileUtils.getBookFullPath(book))); + if (hasValidFilePath(bookFile)) { + ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(new File(bookFile.getFilePath())); yield switch (type) { case RAR -> "application/vnd.comicbook-rar"; case ZIP -> "application/vnd.comicbook+zip"; case SEVEN_ZIP -> "application/x-7z-compressed"; default -> { - String lower = book.getFileName().toLowerCase(); + String lower = bookFile.getFileName().toLowerCase(); if (lower.endsWith(".cbr")) yield "application/vnd.comicbook-rar"; if (lower.endsWith(".cbz")) yield "application/vnd.comicbook+zip"; if (lower.endsWith(".cb7")) yield "application/x-7z-compressed"; @@ -657,6 +684,15 @@ public class OpdsFeedService { } yield "application/vnd.comicbook+zip"; } + case AUDIOBOOK -> { + String lower = bookFile.getFileName().toLowerCase(); + if (lower.endsWith(".m4b") || lower.endsWith(".m4a")) yield "audio/mp4"; + if (lower.endsWith(".mp3")) yield "audio/mpeg"; + if (lower.endsWith(".flac")) yield "audio/flac"; + if (lower.endsWith(".ogg") || lower.endsWith(".opus")) yield "audio/ogg"; + if (lower.endsWith(".aac")) yield "audio/aac"; + yield "audio/mp4"; + } }; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/progress/ReadingProgressService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/progress/ReadingProgressService.java new file mode 100644 index 000000000..6a7940d7b --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/progress/ReadingProgressService.java @@ -0,0 +1,451 @@ +package com.adityachandel.booklore.service.progress; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.exception.ApiError; +import com.adityachandel.booklore.model.dto.*; +import com.adityachandel.booklore.model.dto.progress.AudiobookProgress; +import com.adityachandel.booklore.model.dto.progress.CbxProgress; +import com.adityachandel.booklore.model.dto.progress.EpubProgress; +import com.adityachandel.booklore.model.dto.progress.KoboProgress; +import com.adityachandel.booklore.model.dto.progress.KoProgress; +import com.adityachandel.booklore.model.dto.progress.PdfProgress; +import com.adityachandel.booklore.model.dto.request.BookFileProgress; +import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; +import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse; +import com.adityachandel.booklore.model.entity.*; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.model.enums.ReadStatus; +import com.adityachandel.booklore.model.enums.ResetProgressType; +import com.adityachandel.booklore.model.enums.UserPermission; +import com.adityachandel.booklore.repository.*; +import com.adityachandel.booklore.service.kobo.KoboReadingStateService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; +import java.util.*; +import java.util.stream.Collectors; + +@Slf4j +@RequiredArgsConstructor +@Service +public class ReadingProgressService { + + private static final float READING_THRESHOLD = 0.5f; + private static final float COMPLETED_THRESHOLD = 99.5f; + + private final UserBookProgressRepository userBookProgressRepository; + private final UserBookFileProgressRepository userBookFileProgressRepository; + private final BookRepository bookRepository; + private final BookFileRepository bookFileRepository; + private final UserRepository userRepository; + private final AuthenticationService authenticationService; + private final KoboReadingStateService koboReadingStateService; + + // ==================== Methods from UserProgressService ==================== + + public Map fetchUserProgress(Long userId, Set bookIds) { + return userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds).stream() + .collect(Collectors.toMap(p -> p.getBook().getId(), p -> p)); + } + + public Map fetchUserFileProgress(Long userId, Set bookIds) { + if (bookIds.isEmpty()) { + return Collections.emptyMap(); + } + + List fileProgressList = + userBookFileProgressRepository.findByUserIdAndBookFileBookIdIn(userId, bookIds); + + return fileProgressList.stream() + .collect(Collectors.toMap( + p -> p.getBookFile().getBook().getId(), + p -> p, + (existing, replacement) -> { + if (existing.getLastReadTime() == null) return replacement; + if (replacement.getLastReadTime() == null) return existing; + return replacement.getLastReadTime().isAfter(existing.getLastReadTime()) + ? replacement : existing; + } + )); + } + + public Optional fetchUserFileProgressForFile(Long userId, Long bookFileId) { + return userBookFileProgressRepository.findByUserIdAndBookFileId(userId, bookFileId); + } + + // ==================== Methods from BookProgressUtil ==================== + + public void enrichBookWithProgress(Book book, UserBookProgressEntity progress) { + enrichBookWithProgress(book, progress, null); + } + + public void enrichBookWithProgress(Book book, UserBookProgressEntity progress, + UserBookFileProgressEntity fileProgress) { + if (progress != null) { + book.setReadStatus(progress.getReadStatus() == null ? + String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus())); + book.setDateFinished(progress.getDateFinished()); + book.setPersonalRating(progress.getPersonalRating()); + + setBookProgress(book, progress); + book.setLastReadTime(progress.getLastReadTime()); + } + + if (fileProgress != null) { + setBookProgressFromFileProgress(book, fileProgress); + if (progress == null || fileProgress.getLastReadTime() != null && + (progress.getLastReadTime() == null || + fileProgress.getLastReadTime().isAfter(progress.getLastReadTime()))) { + book.setLastReadTime(fileProgress.getLastReadTime()); + } + } + } + + private void setBookProgress(Book book, UserBookProgressEntity progress) { + if (progress.getKoboProgressPercent() != null) { + book.setKoboProgress(KoboProgress.builder() + .percentage(roundToOneDecimal(progress.getKoboProgressPercent())) + .build()); + } + + if (progress.getKoreaderProgressPercent() != null) { + book.setKoreaderProgress(KoProgress.builder() + .percentage(roundToOneDecimal(progress.getKoreaderProgressPercent() * 100)) + .build()); + } + + if (progress.getEpubProgress() != null || progress.getEpubProgressPercent() != null) { + book.setEpubProgress(EpubProgress.builder() + .cfi(progress.getEpubProgress()) + .href(progress.getEpubProgressHref()) + .percentage(roundToOneDecimal(progress.getEpubProgressPercent())) + .build()); + } + + if (progress.getPdfProgress() != null || progress.getPdfProgressPercent() != null) { + book.setPdfProgress(PdfProgress.builder() + .page(progress.getPdfProgress()) + .percentage(roundToOneDecimal(progress.getPdfProgressPercent())) + .build()); + } + + if (progress.getCbxProgress() != null || progress.getCbxProgressPercent() != null) { + book.setCbxProgress(CbxProgress.builder() + .page(progress.getCbxProgress()) + .percentage(roundToOneDecimal(progress.getCbxProgressPercent())) + .build()); + } + } + + private void setBookProgressFromFileProgress(Book book, UserBookFileProgressEntity fileProgress) { + BookFileType type = fileProgress.getBookFile() != null ? fileProgress.getBookFile().getBookType() : null; + if (type == null) return; + + switch (type) { + case EPUB, FB2, MOBI, AZW3 -> book.setEpubProgress(EpubProgress.builder() + .cfi(fileProgress.getPositionData()) + .href(fileProgress.getPositionHref()) + .percentage(roundToOneDecimal(fileProgress.getProgressPercent())) + .build()); + case PDF -> book.setPdfProgress(PdfProgress.builder() + .page(parseIntOrNull(fileProgress.getPositionData())) + .percentage(roundToOneDecimal(fileProgress.getProgressPercent())) + .build()); + case CBX -> book.setCbxProgress(CbxProgress.builder() + .page(parseIntOrNull(fileProgress.getPositionData())) + .percentage(roundToOneDecimal(fileProgress.getProgressPercent())) + .build()); + case AUDIOBOOK -> book.setAudiobookProgress(AudiobookProgress.builder() + .positionMs(parseLongOrNull(fileProgress.getPositionData())) + .trackIndex(parseIntOrNull(fileProgress.getPositionHref())) + .percentage(roundToOneDecimal(fileProgress.getProgressPercent())) + .build()); + } + } + + private Integer parseIntOrNull(String value) { + if (value == null) return null; + try { + return Integer.parseInt(value); + } catch (NumberFormatException e) { + return null; + } + } + + private Long parseLongOrNull(String value) { + if (value == null) return null; + try { + return Long.parseLong(value); + } catch (NumberFormatException e) { + return null; + } + } + + private Float roundToOneDecimal(Float value) { + return value != null ? Math.round(value * 10f) / 10f : null; + } + + // ==================== Methods from BookUpdateService ==================== + + @Transactional + public void updateReadProgress(ReadProgressRequest request) { + BookEntity book = bookRepository.findByIdWithBookFiles(request.getBookId()) + .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId())); + BookLoreUser user = authenticationService.getAuthenticatedUser(); + BookLoreUserEntity userEntity = findUserOrThrow(user.getId()); + Instant now = Instant.now(); + + UserBookProgressEntity progress = userBookProgressRepository + .findByUserIdAndBookId(user.getId(), book.getId()) + .orElseGet(UserBookProgressEntity::new); + + progress.setUser(userEntity); + progress.setBook(book); + progress.setLastReadTime(now); + + Float percentage; + + if (request.getFileProgress() != null) { + BookFileProgress fileProgress = request.getFileProgress(); + percentage = fileProgress.progressPercent(); + + saveToUserBookFileProgress(userEntity, fileProgress, now); + + BookFileEntity bookFile = bookFileRepository.findById(fileProgress.bookFileId()) + .orElseThrow(() -> ApiError.GENERIC_NOT_FOUND.createException("Book file not found")); + updateProgressFromFileProgress(progress, bookFile.getBookType(), fileProgress); + } else { + BookFileEntity primaryFile = book.getPrimaryBookFile(); + if (primaryFile == null) { + throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(); + } + percentage = updateProgressByBookType(progress, primaryFile.getBookType(), request); + + if (percentage != null) { + saveToUserBookFileProgressFromLegacy(userEntity, primaryFile, progress, now); + } + } + + if (percentage != null) { + progress.setReadStatus(calculateReadStatus(percentage)); + BookFileEntity primaryFile = book.getPrimaryBookFile(); + if (primaryFile != null) { + setProgressPercent(progress, primaryFile.getBookType(), percentage); + } + } + if (request.getDateFinished() != null) { + progress.setDateFinished(request.getDateFinished()); + } + + userBookProgressRepository.save(progress); + } + + @Transactional + public List resetProgress(List bookIds, ResetProgressType type) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + validateResetPermission(bookIds, user, type); + + Set existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds); + Instant now = Instant.now(); + + if (!existingProgressBookIds.isEmpty()) { + performReset(user.getId(), existingProgressBookIds, type, now); + } + + return buildResetResponses(bookIds, existingProgressBookIds, now); + } + + private void saveToUserBookFileProgress(BookLoreUserEntity user, BookFileProgress fileProgress, Instant now) { + UserBookFileProgressEntity entity = userBookFileProgressRepository + .findByUserIdAndBookFileId(user.getId(), fileProgress.bookFileId()) + .orElseGet(UserBookFileProgressEntity::new); + + BookFileEntity bookFile = bookFileRepository.findById(fileProgress.bookFileId()) + .orElseThrow(() -> ApiError.GENERIC_NOT_FOUND.createException("Book file not found")); + + entity.setUser(user); + entity.setBookFile(bookFile); + entity.setPositionData(fileProgress.positionData()); + entity.setPositionHref(fileProgress.positionHref()); + entity.setProgressPercent(fileProgress.progressPercent()); + entity.setLastReadTime(now); + + userBookFileProgressRepository.save(entity); + } + + private void saveToUserBookFileProgressFromLegacy(BookLoreUserEntity user, BookFileEntity bookFile, + UserBookProgressEntity progress, Instant now) { + UserBookFileProgressEntity entity = userBookFileProgressRepository + .findByUserIdAndBookFileId(user.getId(), bookFile.getId()) + .orElseGet(UserBookFileProgressEntity::new); + + entity.setUser(user); + entity.setBookFile(bookFile); + entity.setLastReadTime(now); + + switch (bookFile.getBookType()) { + case PDF -> { + entity.setPositionData(progress.getPdfProgress() != null ? + String.valueOf(progress.getPdfProgress()) : null); + entity.setProgressPercent(progress.getPdfProgressPercent()); + } + case EPUB, FB2, MOBI, AZW3 -> { + entity.setPositionData(progress.getEpubProgress()); + entity.setPositionHref(progress.getEpubProgressHref()); + entity.setProgressPercent(progress.getEpubProgressPercent()); + } + case CBX -> { + entity.setPositionData(progress.getCbxProgress() != null ? + String.valueOf(progress.getCbxProgress()) : null); + entity.setProgressPercent(progress.getCbxProgressPercent()); + } + case AUDIOBOOK -> { + // Audiobook progress is handled via new file-level progress system + // No legacy book-level progress columns exist for audiobooks + } + } + + userBookFileProgressRepository.save(entity); + } + + private void updateProgressFromFileProgress(UserBookProgressEntity progress, BookFileType bookType, + BookFileProgress fileProgress) { + switch (bookType) { + case PDF -> { + progress.setPdfProgress(fileProgress.positionData() != null ? + Integer.parseInt(fileProgress.positionData()) : null); + progress.setPdfProgressPercent(fileProgress.progressPercent()); + } + case EPUB, FB2, MOBI, AZW3 -> { + progress.setEpubProgress(fileProgress.positionData()); + progress.setEpubProgressHref(fileProgress.positionHref()); + progress.setEpubProgressPercent(fileProgress.progressPercent()); + } + case CBX -> { + progress.setCbxProgress(fileProgress.positionData() != null ? + Integer.parseInt(fileProgress.positionData()) : null); + progress.setCbxProgressPercent(fileProgress.progressPercent()); + } + case AUDIOBOOK -> { + // Audiobook progress is stored only in UserBookFileProgressEntity + // No legacy columns in UserBookProgressEntity for audiobooks + } + } + } + + private Float updateProgressByBookType(UserBookProgressEntity progress, BookFileType bookType, ReadProgressRequest request) { + return switch (bookType) { + case EPUB, FB2, MOBI, AZW3 -> updateEbookProgress(progress, request.getEpubProgress()); + case PDF -> updatePdfProgress(progress, request.getPdfProgress()); + case CBX -> updateCbxProgress(progress, request.getCbxProgress()); + case AUDIOBOOK -> updateAudiobookProgress(request.getAudiobookProgress()); + }; + } + + private Float updateEbookProgress(UserBookProgressEntity progress, EpubProgress epubProgress) { + if (epubProgress == null) return null; + + progress.setEpubProgress(epubProgress.getCfi()); + progress.setEpubProgressHref(epubProgress.getHref()); + + float percentage = epubProgress.getPercentage(); + return Math.round(percentage * 10f) / 10f; + } + + private Float updatePdfProgress(UserBookProgressEntity progress, PdfProgress pdfProgress) { + if (pdfProgress == null) return null; + + progress.setPdfProgress(pdfProgress.getPage()); + float percentage = pdfProgress.getPercentage(); + return Math.round(percentage * 10f) / 10f; + } + + private Float updateCbxProgress(UserBookProgressEntity progress, CbxProgress cbxProgress) { + if (cbxProgress == null) return null; + + progress.setCbxProgress(cbxProgress.getPage()); + float percentage = cbxProgress.getPercentage(); + return Math.round(percentage * 10f) / 10f; + } + + private Float updateAudiobookProgress(AudiobookProgress audiobookProgress) { + if (audiobookProgress == null) return null; + + // Audiobook progress is stored in file-level progress (UserBookFileProgressEntity) + // Legacy book-level progress entity doesn't have audiobook-specific columns + float percentage = audiobookProgress.getPercentage(); + return Math.round(percentage * 10f) / 10f; + } + + private void setProgressPercent(UserBookProgressEntity progress, BookFileType type, Float percentage) { + switch (type) { + case EPUB, FB2, MOBI, AZW3 -> progress.setEpubProgressPercent(percentage); + case PDF -> progress.setPdfProgressPercent(percentage); + case CBX -> progress.setCbxProgressPercent(percentage); + case AUDIOBOOK -> { + // Audiobook progress percentage is stored in UserBookFileProgressEntity + // No legacy column exists in UserBookProgressEntity for audiobooks + } + } + } + + private ReadStatus calculateReadStatus(Float percentage) { + if (percentage >= COMPLETED_THRESHOLD) return ReadStatus.READ; + if (percentage > READING_THRESHOLD) return ReadStatus.READING; + return ReadStatus.UNREAD; + } + + private void performReset(Long userId, Set bookIds, ResetProgressType type, Instant now) { + List bookIdList = new ArrayList<>(bookIds); + + switch (type) { + case BOOKLORE -> userBookProgressRepository.bulkResetBookloreProgress(userId, bookIdList, now); + case KOREADER -> userBookProgressRepository.bulkResetKoreaderProgress(userId, bookIdList); + case KOBO -> { + userBookProgressRepository.bulkResetKoboProgress(userId, bookIdList); + bookIds.forEach(koboReadingStateService::deleteReadingState); + } + } + } + + private void validateResetPermission(List bookIds, BookLoreUser user, ResetProgressType type) { + if (bookIds.size() <= 1) return; + UserPermission permission = switch (type) { + case BOOKLORE -> UserPermission.CAN_BULK_RESET_BOOKLORE_READ_PROGRESS; + case KOREADER -> UserPermission.CAN_BULK_RESET_KOREADER_READ_PROGRESS; + default -> null; + }; + if (permission != null && !permission.isGranted(user.getPermissions())) { + throw ApiError.PERMISSION_DENIED.createException(permission); + } + } + + private Set validateBooksAndGetExistingProgress(Long userId, List bookIds) { + long existingBooksCount = bookRepository.countByIdIn(bookIds); + if (existingBooksCount != bookIds.size()) { + throw ApiError.BOOK_NOT_FOUND.createException("One or more books not found"); + } + + return userBookProgressRepository.findExistingProgressBookIds(userId, new HashSet<>(bookIds)); + } + + private List buildResetResponses(List bookIds, Set existingBookIds, Instant now) { + return bookIds.stream() + .map(bookId -> BookStatusUpdateResponse.builder() + .bookId(bookId) + .readStatus(null) + .readStatusModifiedTime(existingBookIds.contains(bookId) ? now : null) + .dateFinished(null) + .build()) + .collect(Collectors.toList()); + } + + private BookLoreUserEntity findUserOrThrow(Long userId) { + return userRepository.findById(userId) + .orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId)); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudioFileUtilityService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudioFileUtilityService.java new file mode 100644 index 000000000..83d9740b4 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudioFileUtilityService.java @@ -0,0 +1,123 @@ +package com.adityachandel.booklore.service.reader; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; + +/** + * Utility service for audio file operations. + * Provides file listing, sorting, content type detection, and other audio file utilities. + */ +@Slf4j +@Service +public class AudioFileUtilityService { + + private static final Set AUDIO_EXTENSIONS = Set.of( + ".mp3", ".m4a", ".m4b", ".aac", ".flac", ".ogg", ".opus" + ); + + /** + * List all audio files in a folder, sorted naturally (Track 1, Track 2, ... Track 10). + */ + public List listAudioFiles(Path folderPath) { + try (Stream files = Files.list(folderPath)) { + return files.filter(Files::isRegularFile) + .filter(this::isAudioFile) + .sorted(this::naturalCompare) + .toList(); + } catch (IOException e) { + log.error("Failed to list audio files in folder: {}", folderPath, e); + return Collections.emptyList(); + } + } + + /** + * Check if a file is an audio file based on its extension. + */ + public boolean isAudioFile(Path path) { + String fileName = path.getFileName().toString().toLowerCase(); + return AUDIO_EXTENSIONS.stream().anyMatch(fileName::endsWith); + } + + /** + * Get the MIME content type for an audio file. + */ + public String getContentType(Path audioPath) { + String fileName = audioPath.getFileName().toString().toLowerCase(); + if (fileName.endsWith(".m4b") || fileName.endsWith(".m4a")) { + return "audio/mp4"; + } else if (fileName.endsWith(".mp3")) { + return "audio/mpeg"; + } else if (fileName.endsWith(".aac")) { + return "audio/aac"; + } else if (fileName.endsWith(".flac")) { + return "audio/flac"; + } else if (fileName.endsWith(".ogg")) { + return "audio/ogg"; + } else if (fileName.endsWith(".opus")) { + return "audio/opus"; + } + return "application/octet-stream"; + } + + /** + * Extract a readable track title from a filename. + * Removes extension and replaces underscores/hyphens with spaces. + */ + public String getTrackTitleFromFilename(String filename) { + int lastDot = filename.lastIndexOf('.'); + if (lastDot > 0) { + filename = filename.substring(0, lastDot); + } + return filename.replaceAll("[_-]+", " ").trim(); + } + + /** + * Get the set of supported audio file extensions. + */ + public Set getSupportedExtensions() { + return AUDIO_EXTENSIONS; + } + + private int naturalCompare(Path p1, Path p2) { + return naturalCompare(p1.getFileName().toString(), p2.getFileName().toString()); + } + + /** + * Natural alphanumeric sort comparison. + * Handles filenames like "Track 1.mp3", "Track 2.mp3", ..., "Track 10.mp3" correctly. + */ + private int naturalCompare(String s1, String s2) { + int i1 = 0, i2 = 0; + while (i1 < s1.length() && i2 < s2.length()) { + char c1 = s1.charAt(i1); + char c2 = s2.charAt(i2); + + if (Character.isDigit(c1) && Character.isDigit(c2)) { + StringBuilder num1 = new StringBuilder(); + StringBuilder num2 = new StringBuilder(); + while (i1 < s1.length() && Character.isDigit(s1.charAt(i1))) { + num1.append(s1.charAt(i1++)); + } + while (i2 < s2.length() && Character.isDigit(s2.charAt(i2))) { + num2.append(s2.charAt(i2++)); + } + int cmp = Long.compare(Long.parseLong(num1.toString()), Long.parseLong(num2.toString())); + if (cmp != 0) return cmp; + } else { + int cmp = Character.compare(Character.toLowerCase(c1), Character.toLowerCase(c2)); + if (cmp != 0) return cmp; + i1++; + i2++; + } + } + return s1.length() - s2.length(); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudioMetadataService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudioMetadataService.java new file mode 100644 index 000000000..9e78b8abe --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudioMetadataService.java @@ -0,0 +1,435 @@ +package com.adityachandel.booklore.service.reader; + +import com.adityachandel.booklore.model.dto.response.AudiobookChapter; +import com.adityachandel.booklore.model.dto.response.AudiobookInfo; +import com.adityachandel.booklore.model.dto.response.AudiobookTrack; +import com.adityachandel.booklore.model.entity.BookFileEntity; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.jaudiotagger.audio.AudioFile; +import org.jaudiotagger.audio.AudioFileIO; +import org.jaudiotagger.audio.AudioHeader; +import org.jaudiotagger.tag.FieldKey; +import org.jaudiotagger.tag.Tag; +import org.jaudiotagger.tag.images.Artwork; +import org.springframework.stereotype.Service; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Stream; + +/** + * Service for extracting and caching audiobook metadata. + * Handles single-file (M4B) and folder-based audiobooks. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class AudioMetadataService { + + private static final int MAX_CACHE_ENTRIES = 50; + + private final AudioFileUtilityService audioFileUtility; + private final Map metadataCache = new ConcurrentHashMap<>(); + + private static class CachedAudiobookMetadata { + final AudiobookInfo info; + final long lastModified; + volatile long lastAccessed; + + CachedAudiobookMetadata(AudiobookInfo info, long lastModified) { + this.info = info; + this.lastModified = lastModified; + this.lastAccessed = System.currentTimeMillis(); + } + } + + /** + * Get audiobook metadata, using cache if available and valid. + */ + public AudiobookInfo getMetadata(BookFileEntity bookFile, Path audioPath) throws Exception { + CachedAudiobookMetadata metadata = getCachedMetadata(bookFile, audioPath); + return metadata.info; + } + + /** + * Extract embedded cover art from an audio file. + */ + public byte[] getEmbeddedCoverArt(Path audioPath) { + try { + AudioFile audioFile = AudioFileIO.read(audioPath.toFile()); + Tag tag = audioFile.getTag(); + if (tag != null) { + Artwork artwork = tag.getFirstArtwork(); + if (artwork != null) { + return artwork.getBinaryData(); + } + } + } catch (Exception e) { + log.debug("No embedded cover art found: {}", e.getMessage()); + } + return null; + } + + /** + * Get the MIME type of embedded cover art. + */ + public String getCoverArtMimeType(Path audioPath) { + try { + AudioFile audioFile = AudioFileIO.read(audioPath.toFile()); + Tag tag = audioFile.getTag(); + if (tag != null) { + Artwork artwork = tag.getFirstArtwork(); + if (artwork != null) { + String mimeType = artwork.getMimeType(); + if (mimeType != null && !mimeType.isEmpty()) { + return mimeType; + } + // Fallback based on binary data magic bytes + byte[] data = artwork.getBinaryData(); + if (data != null && data.length > 2) { + if (data[0] == (byte) 0xFF && data[1] == (byte) 0xD8) { + return "image/jpeg"; + } else if (data[0] == (byte) 0x89 && data[1] == (byte) 0x50) { + return "image/png"; + } + } + return "image/jpeg"; + } + } + } catch (Exception e) { + log.debug("Could not determine cover art MIME type: {}", e.getMessage()); + } + return "image/jpeg"; + } + + private CachedAudiobookMetadata getCachedMetadata(BookFileEntity bookFile, Path audioPath) throws Exception { + String cacheKey = audioPath.toString(); + long currentModified = getLastModified(bookFile, audioPath); + CachedAudiobookMetadata cached = metadataCache.get(cacheKey); + + if (cached != null && cached.lastModified == currentModified) { + cached.lastAccessed = System.currentTimeMillis(); + log.debug("Cache hit for audiobook: {}", audioPath.getFileName()); + return cached; + } + + log.debug("Cache miss for audiobook: {}, parsing...", audioPath.getFileName()); + AudiobookInfo info = parseAudiobookMetadata(bookFile, audioPath); + CachedAudiobookMetadata newMetadata = new CachedAudiobookMetadata(info, currentModified); + metadataCache.put(cacheKey, newMetadata); + evictOldestCacheEntries(); + return newMetadata; + } + + private long getLastModified(BookFileEntity bookFile, Path audioPath) throws IOException { + if (bookFile.isFolderBased()) { + try (Stream files = Files.list(audioPath)) { + return files.filter(audioFileUtility::isAudioFile) + .mapToLong(p -> { + try { + return Files.getLastModifiedTime(p).toMillis(); + } catch (IOException e) { + return 0; + } + }) + .max() + .orElse(Files.getLastModifiedTime(audioPath).toMillis()); + } + } + return Files.getLastModifiedTime(audioPath).toMillis(); + } + + private void evictOldestCacheEntries() { + if (metadataCache.size() <= MAX_CACHE_ENTRIES) { + return; + } + List keysToRemove = metadataCache.entrySet().stream() + .sorted(Comparator.comparingLong(e -> e.getValue().lastAccessed)) + .limit(metadataCache.size() - MAX_CACHE_ENTRIES) + .map(Map.Entry::getKey) + .toList(); + keysToRemove.forEach(key -> { + metadataCache.remove(key); + log.debug("Evicted audiobook cache entry: {}", key); + }); + } + + private AudiobookInfo parseAudiobookMetadata(BookFileEntity bookFile, Path audioPath) throws Exception { + AudiobookInfo.AudiobookInfoBuilder builder = AudiobookInfo.builder() + .bookId(bookFile.getBook().getId()) + .bookFileId(bookFile.getId()) + .folderBased(bookFile.isFolderBased()); + + if (bookFile.isFolderBased()) { + return parseFolderBasedAudiobook(builder, audioPath); + } else { + return parseSingleFileAudiobook(builder, audioPath); + } + } + + private AudiobookInfo parseSingleFileAudiobook(AudiobookInfo.AudiobookInfoBuilder builder, Path audioPath) throws Exception { + AudioFile audioFile = AudioFileIO.read(audioPath.toFile()); + AudioHeader header = audioFile.getAudioHeader(); + Tag tag = audioFile.getTag(); + + long durationMs = (long) (header.getPreciseTrackLength() * 1000); + long bitrateValue = header.getBitRateAsNumber(); + builder.durationMs(durationMs) + .bitrate(bitrateValue > 0 ? (int) bitrateValue : null) + .codec(header.getEncodingType()) + .sampleRate(header.getSampleRateAsNumber()) + .channels(parseChannels(header.getChannels())); + + if (tag != null) { + builder.title(getTagValue(tag, FieldKey.TITLE, FieldKey.ALBUM)) + .author(getTagValue(tag, FieldKey.ARTIST, FieldKey.ALBUM_ARTIST)) + .narrator(getTagValue(tag, FieldKey.COMPOSER)); + } + + List chapters = extractChapters(audioPath, durationMs); + builder.chapters(chapters); + + return builder.build(); + } + + private AudiobookInfo parseFolderBasedAudiobook(AudiobookInfo.AudiobookInfoBuilder builder, Path folderPath) throws Exception { + List audioFiles = audioFileUtility.listAudioFiles(folderPath); + if (audioFiles.isEmpty()) { + throw new IllegalStateException("No audio files found in folder: " + folderPath); + } + + List tracks = new ArrayList<>(); + long totalDurationMs = 0; + String title = null; + String author = null; + String narrator = null; + Integer bitrate = null; + String codec = null; + Integer sampleRate = null; + Integer channels = null; + + for (int i = 0; i < audioFiles.size(); i++) { + Path trackPath = audioFiles.get(i); + try { + AudioFile audioFile = AudioFileIO.read(trackPath.toFile()); + AudioHeader header = audioFile.getAudioHeader(); + Tag tag = audioFile.getTag(); + + long trackDurationMs = (long) (header.getPreciseTrackLength() * 1000); + long fileSizeBytes = Files.size(trackPath); + + String trackTitle = null; + if (tag != null) { + trackTitle = tag.getFirst(FieldKey.TITLE); + } + if (trackTitle == null || trackTitle.isEmpty()) { + trackTitle = audioFileUtility.getTrackTitleFromFilename(trackPath.getFileName().toString()); + } + + tracks.add(AudiobookTrack.builder() + .index(i) + .fileName(trackPath.getFileName().toString()) + .title(trackTitle) + .durationMs(trackDurationMs) + .fileSizeBytes(fileSizeBytes) + .cumulativeStartMs(totalDurationMs) + .build()); + + totalDurationMs += trackDurationMs; + + if (i == 0) { + long bitrateValue = header.getBitRateAsNumber(); + bitrate = bitrateValue > 0 ? (int) bitrateValue : null; + codec = header.getEncodingType(); + sampleRate = header.getSampleRateAsNumber(); + channels = parseChannels(header.getChannels()); + if (tag != null) { + title = getTagValue(tag, FieldKey.ALBUM, FieldKey.TITLE); + author = getTagValue(tag, FieldKey.ALBUM_ARTIST, FieldKey.ARTIST); + narrator = getTagValue(tag, FieldKey.COMPOSER); + } + } + } catch (Exception e) { + log.warn("Failed to read track metadata: {}", trackPath, e); + tracks.add(AudiobookTrack.builder() + .index(i) + .fileName(trackPath.getFileName().toString()) + .title(audioFileUtility.getTrackTitleFromFilename(trackPath.getFileName().toString())) + .fileSizeBytes(Files.size(trackPath)) + .cumulativeStartMs(totalDurationMs) + .build()); + } + } + + return builder + .title(title) + .author(author) + .narrator(narrator) + .durationMs(totalDurationMs) + .bitrate(bitrate) + .codec(codec) + .sampleRate(sampleRate) + .channels(channels) + .tracks(tracks) + .build(); + } + + private List extractChapters(Path audioPath, long totalDurationMs) { + List chapters = new ArrayList<>(); + + try { + chapters = extractChaptersWithFFprobe(audioPath); + if (!chapters.isEmpty()) { + log.debug("Extracted {} chapters from {} using FFprobe", chapters.size(), audioPath.getFileName()); + return chapters; + } + } catch (Exception e) { + log.debug("FFprobe chapter extraction failed for {}: {}", audioPath.getFileName(), e.getMessage()); + } + + chapters.add(AudiobookChapter.builder() + .index(0) + .title("Full Audiobook") + .startTimeMs(0L) + .endTimeMs(totalDurationMs) + .durationMs(totalDurationMs) + .build()); + + return chapters; + } + + private List extractChaptersWithFFprobe(Path audioPath) throws Exception { + List chapters = new ArrayList<>(); + + ProcessBuilder pb = new ProcessBuilder( + "ffprobe", + "-v", "quiet", + "-print_format", "json", + "-show_chapters", + audioPath.toAbsolutePath().toString() + ); + pb.redirectErrorStream(true); + + Process process = pb.start(); + StringBuilder output = new StringBuilder(); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { + String line; + while ((line = reader.readLine()) != null) { + output.append(line); + } + } + + int exitCode = process.waitFor(); + if (exitCode != 0) { + log.debug("FFprobe exited with code {} for {}", exitCode, audioPath.getFileName()); + return chapters; + } + + String jsonOutput = output.toString().trim(); + if (jsonOutput.isEmpty() || jsonOutput.equals("{}")) { + return chapters; + } + + ObjectMapper mapper = new ObjectMapper(); + JsonNode root = mapper.readTree(jsonOutput); + JsonNode chaptersNode = root.get("chapters"); + + if (chaptersNode == null || !chaptersNode.isArray() || chaptersNode.isEmpty()) { + return chapters; + } + + for (int i = 0; i < chaptersNode.size(); i++) { + JsonNode chapterNode = chaptersNode.get(i); + + double startTime = 0; + double endTime = 0; + + if (chapterNode.has("start_time")) { + startTime = chapterNode.get("start_time").asDouble(); + } else if (chapterNode.has("start")) { + long start = chapterNode.get("start").asLong(); + String timeBase = chapterNode.has("time_base") ? chapterNode.get("time_base").asText() : "1/1000"; + startTime = convertTimebaseToSeconds(start, timeBase); + } + + if (chapterNode.has("end_time")) { + endTime = chapterNode.get("end_time").asDouble(); + } else if (chapterNode.has("end")) { + long end = chapterNode.get("end").asLong(); + String timeBase = chapterNode.has("time_base") ? chapterNode.get("time_base").asText() : "1/1000"; + endTime = convertTimebaseToSeconds(end, timeBase); + } + + long startTimeMs = Math.round(startTime * 1000); + long endTimeMs = Math.round(endTime * 1000); + long durationMs = endTimeMs - startTimeMs; + + String title = "Chapter " + (i + 1); + JsonNode tagsNode = chapterNode.get("tags"); + if (tagsNode != null && tagsNode.has("title")) { + title = tagsNode.get("title").asText(); + } + + chapters.add(AudiobookChapter.builder() + .index(i) + .title(title) + .startTimeMs(startTimeMs) + .endTimeMs(endTimeMs) + .durationMs(durationMs) + .build()); + } + + return chapters; + } + + private double convertTimebaseToSeconds(long value, String timeBase) { + String[] parts = timeBase.split("/"); + if (parts.length == 2) { + try { + double numerator = Double.parseDouble(parts[0]); + double denominator = Double.parseDouble(parts[1]); + return value * (numerator / denominator); + } catch (NumberFormatException e) { + return value / 1000.0; + } + } + return value / 1000.0; + } + + private String getTagValue(Tag tag, FieldKey... keys) { + for (FieldKey key : keys) { + try { + String value = tag.getFirst(key); + if (value != null && !value.isEmpty()) { + return value; + } + } catch (Exception e) { + // Field not supported for this tag type + } + } + return null; + } + + private Integer parseChannels(String channels) { + if (channels == null) return null; + if (channels.toLowerCase().contains("stereo")) return 2; + if (channels.toLowerCase().contains("mono")) return 1; + try { + return Integer.parseInt(channels.replaceAll("[^0-9]", "")); + } catch (NumberFormatException e) { + return null; + } + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudiobookReaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudiobookReaderService.java new file mode 100644 index 000000000..b5c52fb3c --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/AudiobookReaderService.java @@ -0,0 +1,120 @@ +package com.adityachandel.booklore.service.reader; + +import com.adityachandel.booklore.exception.ApiError; +import com.adityachandel.booklore.model.dto.response.AudiobookInfo; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.service.FileStreamingService; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; + +/** + * Service for audiobook reader operations. + * Orchestrates metadata extraction, file access, and streaming. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class AudiobookReaderService { + + private final BookRepository bookRepository; + private final AudioMetadataService audioMetadataService; + private final AudioFileUtilityService audioFileUtility; + private final FileStreamingService fileStreamingService; + + /** + * Get audiobook information including metadata, chapters, and tracks. + */ + public AudiobookInfo getAudiobookInfo(Long bookId, String bookType) { + BookFileEntity bookFile = getAudiobookFile(bookId, bookType); + Path audioPath = bookFile.getFullFilePath(); + + try { + return audioMetadataService.getMetadata(bookFile, audioPath); + } catch (Exception e) { + log.error("Failed to read audiobook metadata for book {}", bookId, e); + throw ApiError.FILE_READ_ERROR.createException("Failed to read audiobook: " + e.getMessage()); + } + } + + /** + * Get the path to an audio file for streaming. + * For folder-based audiobooks, returns the path to a specific track. + */ + public Path getAudioFilePath(Long bookId, String bookType, Integer trackIndex) { + BookFileEntity bookFile = getAudiobookFile(bookId, bookType); + + if (bookFile.isFolderBased()) { + if (trackIndex == null) { + trackIndex = 0; + } + List tracks = audioFileUtility.listAudioFiles(bookFile.getFullFilePath()); + if (trackIndex < 0 || trackIndex >= tracks.size()) { + throw ApiError.FILE_NOT_FOUND.createException("Track index out of range: " + trackIndex); + } + return tracks.get(trackIndex); + } else { + return bookFile.getFullFilePath(); + } + } + + /** + * Stream an audio file with HTTP Range support for seeking. + */ + public void streamWithRangeSupport(Path filePath, HttpServletRequest request, HttpServletResponse response) throws IOException { + String contentType = audioFileUtility.getContentType(filePath); + fileStreamingService.streamWithRangeSupport(filePath, contentType, request, response); + } + + /** + * Get embedded cover art from an audiobook file. + */ + public byte[] getEmbeddedCoverArt(Long bookId, String bookType) { + BookFileEntity bookFile = getAudiobookFile(bookId, bookType); + Path audioPath = bookFile.isFolderBased() ? bookFile.getFirstAudioFile() : bookFile.getFullFilePath(); + return audioMetadataService.getEmbeddedCoverArt(audioPath); + } + + /** + * Get the MIME type of embedded cover art. + */ + public String getCoverArtMimeType(Long bookId, String bookType) { + BookFileEntity bookFile = getAudiobookFile(bookId, bookType); + Path audioPath = bookFile.isFolderBased() ? bookFile.getFirstAudioFile() : bookFile.getFullFilePath(); + return audioMetadataService.getCoverArtMimeType(audioPath); + } + + /** + * Get the content type for an audio file. + */ + public String getContentType(Path audioPath) { + return audioFileUtility.getContentType(audioPath); + } + + private BookFileEntity getAudiobookFile(Long bookId, String bookType) { + BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId) + .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + if (bookType != null) { + BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase()); + return bookEntity.getBookFiles().stream() + .filter(bf -> bf.getBookType() == requestedType) + .findFirst() + .orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("No file of type " + bookType + " found for book")); + } + + return bookEntity.getBookFiles().stream() + .filter(bf -> bf.getBookType() == BookFileType.AUDIOBOOK && bf.isBookFormat()) + .findFirst() + .orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("No audiobook file found for book " + bookId)); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java index 3e0b61aa6..2ff2a01be 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java @@ -3,6 +3,8 @@ package com.adityachandel.booklore.service.reader; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.model.dto.response.CbxPageInfo; import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; +import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.util.FileUtils; import com.github.junrar.Archive; @@ -70,7 +72,11 @@ public class CbxReaderService { } public List getAvailablePages(Long bookId) { - Path cbxPath = getBookPath(bookId); + return getAvailablePages(bookId, null); + } + + public List getAvailablePages(Long bookId, String bookType) { + Path cbxPath = getBookPath(bookId, bookType); try { List imageEntries = getImageEntriesFromArchiveCached(cbxPath); return IntStream.rangeClosed(1, imageEntries.size()) @@ -83,7 +89,11 @@ public class CbxReaderService { } public List getPageInfo(Long bookId) { - Path cbxPath = getBookPath(bookId); + return getPageInfo(bookId, null); + } + + public List getPageInfo(Long bookId, String bookType) { + Path cbxPath = getBookPath(bookId, bookType); try { List imageEntries = getImageEntriesFromArchiveCached(cbxPath); List pageInfoList = new ArrayList<>(); @@ -112,15 +122,27 @@ public class CbxReaderService { } public void streamPageImage(Long bookId, int page, OutputStream outputStream) throws IOException { - Path cbxPath = getBookPath(bookId); + streamPageImage(bookId, null, page, outputStream); + } + + public void streamPageImage(Long bookId, String bookType, int page, OutputStream outputStream) throws IOException { + Path cbxPath = getBookPath(bookId, bookType); CachedArchiveMetadata metadata = getCachedMetadata(cbxPath); validatePageRequest(bookId, page, metadata.imageEntries); String entryName = metadata.imageEntries.get(page - 1); streamEntryFromArchive(cbxPath, entryName, outputStream, metadata.successfulEncoding); } - private Path getBookPath(Long bookId) { + private Path getBookPath(Long bookId, String bookType) { BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + if (bookType != null) { + BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase()); + BookFileEntity bookFile = bookEntity.getBookFiles().stream() + .filter(bf -> bf.getBookType() == requestedType) + .findFirst() + .orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("No file of type " + bookType + " found for book")); + return bookFile.getFullFilePath(); + } String bookFullPath = FileUtils.getBookFullPath(bookEntity); return Path.of(bookFullPath); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/EpubReaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/EpubReaderService.java index 615eaefed..1ae0ab5e4 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/EpubReaderService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/EpubReaderService.java @@ -6,6 +6,8 @@ import com.adityachandel.booklore.model.dto.response.EpubManifestItem; import com.adityachandel.booklore.model.dto.response.EpubSpineItem; import com.adityachandel.booklore.model.dto.response.EpubTocItem; import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; +import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.util.FileUtils; import lombok.RequiredArgsConstructor; @@ -71,7 +73,11 @@ public class EpubReaderService { } public EpubBookInfo getBookInfo(Long bookId) { - Path epubPath = getBookPath(bookId); + return getBookInfo(bookId, null); + } + + public EpubBookInfo getBookInfo(Long bookId, String bookType) { + Path epubPath = getBookPath(bookId, bookType); try { CachedEpubMetadata metadata = getCachedMetadata(epubPath); return metadata.bookInfo; @@ -82,7 +88,11 @@ public class EpubReaderService { } public void streamFile(Long bookId, String filePath, OutputStream outputStream) throws IOException { - Path epubPath = getBookPath(bookId); + streamFile(bookId, null, filePath, outputStream); + } + + public void streamFile(Long bookId, String bookType, String filePath, OutputStream outputStream) throws IOException { + Path epubPath = getBookPath(bookId, bookType); CachedEpubMetadata metadata = getCachedMetadata(epubPath); String cleanPath = filePath.startsWith("/") ? filePath.substring(1) : filePath; @@ -101,7 +111,11 @@ public class EpubReaderService { } public String getContentType(Long bookId, String filePath) { - Path epubPath = getBookPath(bookId); + return getContentType(bookId, null, filePath); + } + + public String getContentType(Long bookId, String bookType, String filePath) { + Path epubPath = getBookPath(bookId, bookType); try { CachedEpubMetadata metadata = getCachedMetadata(epubPath); String normalizedPath = normalizePath(filePath, metadata.bookInfo.getRootPath()); @@ -117,7 +131,11 @@ public class EpubReaderService { } public long getFileSize(Long bookId, String filePath) { - Path epubPath = getBookPath(bookId); + return getFileSize(bookId, null, filePath); + } + + public long getFileSize(Long bookId, String bookType, String filePath) { + Path epubPath = getBookPath(bookId, bookType); try { CachedEpubMetadata metadata = getCachedMetadata(epubPath); String normalizedPath = normalizePath(filePath, metadata.bookInfo.getRootPath()); @@ -132,9 +150,17 @@ public class EpubReaderService { } } - private Path getBookPath(Long bookId) { + private Path getBookPath(Long bookId, String bookType) { BookEntity bookEntity = bookRepository.findById(bookId) .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + if (bookType != null) { + BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase()); + BookFileEntity bookFile = bookEntity.getBookFiles().stream() + .filter(bf -> bf.getBookType() == requestedType) + .findFirst() + .orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("No file of type " + bookType + " found for book")); + return bookFile.getFullFilePath(); + } String bookFullPath = FileUtils.getBookFullPath(bookEntity); return Path.of(bookFullPath); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/PdfReaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/PdfReaderService.java index 24317cdef..66002b665 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/PdfReaderService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/PdfReaderService.java @@ -4,6 +4,8 @@ import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.model.dto.response.PdfBookInfo; import com.adityachandel.booklore.model.dto.response.PdfOutlineItem; import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; +import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.util.FileUtils; import lombok.RequiredArgsConstructor; @@ -56,7 +58,11 @@ public class PdfReaderService { } public List getAvailablePages(Long bookId) { - Path pdfPath = getBookPath(bookId); + return getAvailablePages(bookId, null); + } + + public List getAvailablePages(Long bookId, String bookType) { + Path pdfPath = getBookPath(bookId, bookType); try { CachedPdfMetadata metadata = getCachedMetadata(pdfPath); return IntStream.rangeClosed(1, metadata.pageCount) @@ -69,7 +75,11 @@ public class PdfReaderService { } public PdfBookInfo getBookInfo(Long bookId) { - Path pdfPath = getBookPath(bookId); + return getBookInfo(bookId, null); + } + + public PdfBookInfo getBookInfo(Long bookId, String bookType) { + Path pdfPath = getBookPath(bookId, bookType); try { CachedPdfMetadata metadata = getCachedMetadata(pdfPath); return PdfBookInfo.builder() @@ -83,15 +93,27 @@ public class PdfReaderService { } public void streamPageImage(Long bookId, int page, OutputStream outputStream) throws IOException { - Path pdfPath = getBookPath(bookId); + streamPageImage(bookId, null, page, outputStream); + } + + public void streamPageImage(Long bookId, String bookType, int page, OutputStream outputStream) throws IOException { + Path pdfPath = getBookPath(bookId, bookType); CachedPdfMetadata metadata = getCachedMetadata(pdfPath); validatePageRequest(bookId, page, metadata.pageCount); renderPageToStream(pdfPath, page, outputStream); } - private Path getBookPath(Long bookId) { + private Path getBookPath(Long bookId, String bookType) { BookEntity bookEntity = bookRepository.findById(bookId) .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + if (bookType != null) { + BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase()); + BookFileEntity bookFile = bookEntity.getBookFiles().stream() + .filter(bf -> bf.getBookType() == requestedType) + .findFirst() + .orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("No file of type " + bookType + " found for book")); + return bookFile.getFullFilePath(); + } String bookFullPath = FileUtils.getBookFullPath(bookEntity); return Path.of(bookFullPath); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java index c4b364368..69e5d1268 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java @@ -93,6 +93,7 @@ public class FileUploadService { final String originalFileName = getValidatedFileName(file); final Long libraryId = book.getLibrary() != null ? book.getLibrary().getId() : null; final String sanitizedFileName = PathPatternResolver.truncateFilenameWithExtension(originalFileName); + final boolean wasPhysicalBook = Boolean.TRUE.equals(book.getIsPhysical()); Path tempPath = null; boolean monitoringUnregistered = false; @@ -107,14 +108,39 @@ public class FileUploadService { final Path finalPath; final String finalFileName; - if (isBook) { + final String fileSubPath; + final BookFileType effectiveBookType; + + // Handle physical books that are getting their first file + if (wasPhysicalBook) { + // Physical book - determine library path and subpath + LibraryPathEntity libraryPath = determineLibraryPathForPhysicalBook(book); + book.setLibraryPath(libraryPath); + String pattern = fileMovingHelper.getFileNamingPattern(book.getLibrary()); String resolvedRelativePath = PathPatternResolver.resolvePattern(book.getMetadata(), pattern, sanitizedFileName); finalFileName = Paths.get(resolvedRelativePath).getFileName().toString(); + fileSubPath = Paths.get(resolvedRelativePath).getParent() != null + ? Paths.get(resolvedRelativePath).getParent().toString() + : ""; + finalPath = Paths.get(libraryPath.getPath(), resolvedRelativePath); + String extension = sanitizedFileName.substring(sanitizedFileName.lastIndexOf('.') + 1); + effectiveBookType = BookFileType.fromExtension(extension) + .orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported book file extension: " + extension)); + } else if (isBook) { + String pattern = fileMovingHelper.getFileNamingPattern(book.getLibrary()); + String resolvedRelativePath = PathPatternResolver.resolvePattern(book.getMetadata(), pattern, sanitizedFileName); + finalFileName = Paths.get(resolvedRelativePath).getFileName().toString(); + fileSubPath = book.getPrimaryBookFile().getFileSubPath(); finalPath = buildAdditionalFilePath(book, finalFileName); + String extension = sanitizedFileName.substring(sanitizedFileName.lastIndexOf('.') + 1); + effectiveBookType = BookFileType.fromExtension(extension) + .orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported book file extension: " + extension)); } else { finalFileName = sanitizedFileName; + fileSubPath = book.getPrimaryBookFile().getFileSubPath(); finalPath = buildAdditionalFilePath(book, sanitizedFileName); + effectiveBookType = bookType; } validateFinalPath(finalPath); @@ -127,16 +153,23 @@ public class FileUploadService { log.info("Additional file uploaded to final location: {}", finalPath); - final BookFileEntity entity = createAdditionalFileEntity(book, finalFileName, isBook, bookType, file.getSize(), fileHash, description); + final BookFileEntity entity = createAdditionalFileEntityWithSubPath(book, finalFileName, fileSubPath, isBook, effectiveBookType, file.getSize(), fileHash, description); final BookFileEntity savedEntity = additionalFileRepository.save(entity); + // Promote physical book to digital if this is a book file + if (wasPhysicalBook && isBook) { + book.setIsPhysical(false); + bookRepository.save(book); + log.info("Physical book {} promoted to digital book after file upload", bookId); + } + return additionalFileMapper.toAdditionalFile(savedEntity); } catch (IOException e) { log.error("Failed to upload additional file for book {}: {}", bookId, sanitizedFileName, e); throw ApiError.FILE_READ_ERROR.createException(e.getMessage()); } finally { - if (monitoringUnregistered && libraryId != null) { + if (monitoringUnregistered) { try { if (book.getLibrary() != null && book.getLibrary().getLibraryPaths() != null) { for (LibraryPathEntity libPath : book.getLibrary().getLibraryPaths()) { @@ -153,6 +186,29 @@ public class FileUploadService { } } + private LibraryPathEntity determineLibraryPathForPhysicalBook(BookEntity book) { + if (book.getLibrary() == null || book.getLibrary().getLibraryPaths() == null || book.getLibrary().getLibraryPaths().isEmpty()) { + throw new IllegalStateException("Cannot upload file to physical book: library has no paths configured"); + } + // Use the first library path for physical books + return book.getLibrary().getLibraryPaths().iterator().next(); + } + + private BookFileEntity createAdditionalFileEntityWithSubPath(BookEntity book, String fileName, String fileSubPath, boolean isBook, BookFileType bookType, long fileSize, String fileHash, String description) { + return BookFileEntity.builder() + .book(book) + .fileName(fileName) + .fileSubPath(fileSubPath) + .isBookFormat(isBook) + .bookType(bookType) + .fileSizeKb(fileSize / BYTES_TO_KB_DIVISOR) + .initialHash(fileHash) + .currentHash(fileHash) + .description(description) + .addedOn(Instant.now()) + .build(); + } + public Book uploadFileBookDrop(MultipartFile file) throws IOException { validateFile(file); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProgressService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProgressService.java deleted file mode 100644 index e19cb97e9..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProgressService.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.adityachandel.booklore.service.user; - -import com.adityachandel.booklore.model.entity.UserBookProgressEntity; -import com.adityachandel.booklore.repository.UserBookProgressRepository; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -@RequiredArgsConstructor -@Service -public class UserProgressService { - - private final UserBookProgressRepository userBookProgressRepository; - - public Map fetchUserProgress(Long userId, Set bookIds) { - return userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds).stream() - .collect(Collectors.toMap(p -> p.getBook().getId(), p -> p)); - } -} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFilePersistenceService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFilePersistenceService.java index bf94378a8..69bcfa22f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFilePersistenceService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFilePersistenceService.java @@ -3,9 +3,11 @@ package com.adityachandel.booklore.service.watcher; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.mapper.BookMapper; import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; import com.adityachandel.booklore.model.websocket.Topic; +import com.adityachandel.booklore.repository.BookFileRepository; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.util.FileUtils; @@ -30,6 +32,7 @@ public class BookFilePersistenceService { private final EntityManager entityManager; private final BookRepository bookRepository; + private final BookFileRepository bookFileRepository; private final NotificationService notificationService; private final BookMapper bookMapper; @@ -96,8 +99,30 @@ public class BookFilePersistenceService { return bookRepository.findByLibraryPath_IdAndFileSubPathAndFileName(libraryPathId, fileSubPath, fileName); } + @Transactional(readOnly = true) + public Optional findBookFileByLibraryPathSubPathAndFileName(long libraryPathId, String fileSubPath, String fileName) { + return bookFileRepository.findByLibraryPathIdAndFileSubPathAndFileName(libraryPathId, fileSubPath, fileName); + } + + @Transactional + public void deleteBookFile(BookFileEntity bookFile) { + bookFileRepository.delete(bookFile); + } + + @Transactional + public void markBookAsDeleted(BookEntity book) { + book.setDeleted(true); + book.setDeletedAt(Instant.now()); + bookRepository.save(book); + } + @Transactional public void save(BookEntity book) { bookRepository.save(book); } + + @Transactional(readOnly = true) + public long countBookFilesByBookId(Long bookId) { + return bookFileRepository.countByBookId(bookId); + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFileTransactionalHandler.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFileTransactionalHandler.java index 4c48844f4..88a5e7096 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFileTransactionalHandler.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFileTransactionalHandler.java @@ -2,14 +2,21 @@ package com.adityachandel.booklore.service.watcher; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; import com.adityachandel.booklore.model.enums.BookFileExtension; +import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.websocket.LogNotification; import com.adityachandel.booklore.model.websocket.Topic; +import com.adityachandel.booklore.repository.BookAdditionalFileRepository; +import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.file.FileFingerprint; import com.adityachandel.booklore.service.library.LibraryProcessingService; +import com.adityachandel.booklore.util.BookFileGroupingUtils; import com.adityachandel.booklore.util.FileUtils; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; @@ -17,7 +24,9 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.nio.file.Path; +import java.time.Instant; import java.util.List; +import java.util.Optional; import java.util.Set; import static com.adityachandel.booklore.model.enums.PermissionType.ADMIN; @@ -28,10 +37,14 @@ import static com.adityachandel.booklore.model.enums.PermissionType.MANAGE_LIBRA @RequiredArgsConstructor public class BookFileTransactionalHandler { + private static final double FILELESS_MATCH_THRESHOLD = 0.85; + private final BookFilePersistenceService bookFilePersistenceService; private final LibraryProcessingService libraryProcessingService; private final NotificationService notificationService; private final LibraryRepository libraryRepository; + private final BookRepository bookRepository; + private final BookAdditionalFileRepository bookAdditionalFileRepository; @Transactional() public void handleNewBookFile(long libraryId, Path path) { @@ -44,20 +57,259 @@ public class BookFileTransactionalHandler { notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Started processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY)); LibraryPathEntity libraryPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(libraryEntity, libraryPath); + String fileSubPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), path); - LibraryFile libraryFile = LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(libraryPathEntity) - .fileSubPath(FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), path)) - .fileName(fileName) - .bookFileType(BookFileExtension.fromFileName(fileName) - .map(BookFileExtension::getType) - .orElseThrow(() -> new IllegalArgumentException("Unsupported book file type: " + fileName))) - .build(); + // Check if this is a moved file by looking for existing book with same content hash + String currentHash = FileFingerprint.generateHash(path); + Optional existingByHash = bookRepository.findByCurrentHash(currentHash); + if (existingByHash.isPresent()) { + // File was moved - update the existing book's path instead of creating a duplicate + bookFilePersistenceService.updatePathIfChanged(existingByHash.get(), libraryEntity, path, currentHash); + log.info("[CREATE] File '{}' recognized as moved file, updated existing book's path", filePath); + notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY)); + return; + } - libraryProcessingService.processLibraryFiles(List.of(libraryFile), libraryEntity); + // Check for fileless books that match by metadata + BookEntity filelessMatch = findMatchingFilelessBook(libraryEntity, fileName, libraryPathEntity); + if (filelessMatch != null) { + // Set libraryPath if not set (fileless books like physical books don't have one) + if (filelessMatch.getLibraryPath() == null) { + filelessMatch.setLibraryPath(libraryPathEntity); + bookRepository.save(filelessMatch); + } + autoAttachFile(filelessMatch, fileName, fileSubPath, path); + log.info("[CREATE] Attached file '{}' to fileless book id={}", filePath, filelessMatch.getId()); + notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY)); + return; + } + + BookEntity matchingBook = findMatchingBook(libraryPathEntity.getId(), fileSubPath, fileName); + + if (matchingBook != null) { + autoAttachFile(matchingBook, fileName, fileSubPath, path); + log.info("[CREATE] Auto-attached file '{}' to existing book", filePath); + } else { + LibraryFile libraryFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileSubPath(fileSubPath) + .fileName(fileName) + .bookFileType(BookFileExtension.fromFileName(fileName) + .map(BookFileExtension::getType) + .orElseThrow(() -> new IllegalArgumentException("Unsupported book file type: " + fileName))) + .build(); + + libraryProcessingService.processLibraryFiles(List.of(libraryFile), libraryEntity); + log.info("[CREATE] Completed processing for file '{}'", filePath); + } notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY)); - log.info("[CREATE] Completed processing for file '{}'", filePath); + } + + @Transactional + public void handleNewFolderAudiobook(long libraryId, Path folderPath) { + LibraryEntity libraryEntity = libraryRepository.findById(libraryId) + .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); + + String folderName = folderPath.getFileName().toString(); + String libraryPath = bookFilePersistenceService.findMatchingLibraryPath(libraryEntity, folderPath); + + notificationService.sendMessageToPermissions(Topic.LOG, + LogNotification.info("Started processing folder audiobook: " + folderPath), Set.of(ADMIN, MANAGE_LIBRARY)); + + LibraryPathEntity libraryPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(libraryEntity, libraryPath); + String fileSubPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), folderPath); + + // For folder-based audiobooks, try to match with book in parent folder + BookEntity matchingBook = findMatchingBookForFolderAudiobook(libraryPathEntity.getId(), fileSubPath, folderName); + + if (matchingBook != null) { + autoAttachFolderAudiobook(matchingBook, folderName, fileSubPath, folderPath); + String primaryFileName = matchingBook.hasFiles() ? matchingBook.getPrimaryBookFile().getFileName() : "book#" + matchingBook.getId(); + log.info("[CREATE] Auto-attached folder audiobook '{}' to existing book '{}'", folderName, primaryFileName); + } else { + LibraryFile libraryFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileSubPath(fileSubPath) + .fileName(folderName) + .bookFileType(BookFileType.AUDIOBOOK) + .folderBased(true) + .build(); + + libraryProcessingService.processLibraryFiles(List.of(libraryFile), libraryEntity); + log.info("[CREATE] Completed processing folder audiobook '{}'", folderPath); + } + + notificationService.sendMessageToPermissions(Topic.LOG, + LogNotification.info("Finished processing folder audiobook: " + folderPath), Set.of(ADMIN, MANAGE_LIBRARY)); + } + + private static final double FUZZY_MATCH_THRESHOLD = 0.85; + + /** + * Finds a fileless book that matches the given file by metadata title. + * Only matches books that either have no libraryPath or have the same libraryPath as the file. + */ + private BookEntity findMatchingFilelessBook(LibraryEntity library, String fileName, LibraryPathEntity fileLibraryPath) { + List filelessBooks = bookRepository.findFilelessBooksByLibraryId(library.getId()); + String fileBaseName = BookFileGroupingUtils.extractGroupingKey(fileName); + + for (BookEntity book : filelessBooks) { + // Skip books that already have a different libraryPath + 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()); + double similarity = BookFileGroupingUtils.calculateSimilarity(fileBaseName, bookTitle); + if (similarity >= FILELESS_MATCH_THRESHOLD) { + return book; + } + } + } + return null; + } + + private BookEntity findMatchingBook(Long libraryPathId, String fileSubPath, String fileName) { + // Skip root-level files + if (fileSubPath == null || fileSubPath.isEmpty()) { + return null; + } + + String fileGroupingKey = BookFileGroupingUtils.extractGroupingKey(fileName); + + List booksInDirectory = bookRepository.findAllByLibraryPathIdAndFileSubPath(libraryPathId, fileSubPath); + + BookEntity fuzzyMatch = null; + double bestSimilarity = 0; + + for (BookEntity book : booksInDirectory) { + if (book.getDeleted() != null && book.getDeleted()) { + continue; + } + BookFileEntity primaryFile = book.getPrimaryBookFile(); + if (primaryFile == null) { + continue; // Skip fileless books + } + String existingGroupingKey = BookFileGroupingUtils.extractGroupingKey(primaryFile.getFileName()); + + // Try exact match first + if (fileGroupingKey.equals(existingGroupingKey)) { + return book; + } + + // Track best fuzzy match + double similarity = BookFileGroupingUtils.calculateSimilarity(fileGroupingKey, existingGroupingKey); + if (similarity >= FUZZY_MATCH_THRESHOLD && similarity > bestSimilarity) { + bestSimilarity = similarity; + fuzzyMatch = book; + } + } + + // Return fuzzy match if found + if (fuzzyMatch != null) { + String primaryFileName = fuzzyMatch.hasFiles() ? fuzzyMatch.getPrimaryBookFile().getFileName() : "book#" + fuzzyMatch.getId(); + log.debug("Fuzzy matched '{}' to '{}' with similarity {}", fileName, primaryFileName, bestSimilarity); + } + return fuzzyMatch; + } + + /** + * Find matching book for a folder-based audiobook. + * Looks in the parent folder since audiobook folders are typically nested inside book folders. + */ + private BookEntity findMatchingBookForFolderAudiobook(Long libraryPathId, String fileSubPath, String folderName) { + // Get parent folder path for matching + String parentPath = Optional.ofNullable(fileSubPath) + .filter(p -> !p.isEmpty()) + .map(p -> { + int lastSep = p.lastIndexOf('/'); + if (lastSep == -1) { + lastSep = p.lastIndexOf('\\'); + } + return lastSep > 0 ? p.substring(0, lastSep) : ""; + }) + .orElse(""); + + String folderGroupingKey = BookFileGroupingUtils.extractGroupingKey(folderName); + + // Search in parent folder + List booksInParent = bookRepository.findAllByLibraryPathIdAndFileSubPath(libraryPathId, parentPath); + + BookEntity fuzzyMatch = null; + double bestSimilarity = 0; + + for (BookEntity book : booksInParent) { + if (book.getDeleted() != null && book.getDeleted()) { + continue; + } + BookFileEntity primaryFile = book.getPrimaryBookFile(); + if (primaryFile == null) { + continue; // Skip fileless books + } + String existingGroupingKey = BookFileGroupingUtils.extractGroupingKey(primaryFile.getFileName()); + + // Try exact match first + if (folderGroupingKey.equals(existingGroupingKey)) { + return book; + } + + // Track best fuzzy match + double similarity = BookFileGroupingUtils.calculateSimilarity(folderGroupingKey, existingGroupingKey); + if (similarity >= FUZZY_MATCH_THRESHOLD && similarity > bestSimilarity) { + bestSimilarity = similarity; + fuzzyMatch = book; + } + } + + if (fuzzyMatch != null) { + String primaryFileName = fuzzyMatch.hasFiles() ? fuzzyMatch.getPrimaryBookFile().getFileName() : "book#" + fuzzyMatch.getId(); + log.debug("Fuzzy matched folder '{}' to '{}' with similarity {}", folderName, primaryFileName, bestSimilarity); + } + return fuzzyMatch; + } + + private void autoAttachFolderAudiobook(BookEntity book, String folderName, String fileSubPath, Path folderPath) { + String hash = FileFingerprint.generateFolderHash(folderPath); + BookFileEntity additionalFile = BookFileEntity.builder() + .book(book) + .fileName(folderName) + .fileSubPath(fileSubPath) + .isBookFormat(true) + .folderBased(true) + .bookType(BookFileType.AUDIOBOOK) + .fileSizeKb(FileUtils.getFolderSizeInKb(folderPath)) + .initialHash(hash) + .currentHash(hash) + .addedOn(Instant.now()) + .build(); + + bookAdditionalFileRepository.save(additionalFile); + String primaryFileName = book.hasFiles() ? book.getPrimaryBookFile().getFileName() : "book#" + book.getId(); + log.info("Auto-attached folder audiobook {} to existing book: {}", folderName, primaryFileName); + } + + private void autoAttachFile(BookEntity book, String fileName, String fileSubPath, Path fullPath) { + String hash = FileFingerprint.generateHash(fullPath); + BookFileEntity additionalFile = BookFileEntity.builder() + .book(book) + .fileName(fileName) + .fileSubPath(fileSubPath) + .isBookFormat(true) + .bookType(BookFileExtension.fromFileName(fileName) + .map(BookFileExtension::getType) + .orElse(null)) + .fileSizeKb(FileUtils.getFileSizeInKb(fullPath)) + .initialHash(hash) + .currentHash(hash) + .addedOn(Instant.now()) + .build(); + + bookAdditionalFileRepository.save(additionalFile); + String primaryFileName = book.hasFiles() ? book.getPrimaryBookFile().getFileName() : "book#" + book.getId(); + log.info("Auto-attached new format {} to existing book: {}", fileName, primaryFileName); } } 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 3ce8a6af3..cecab46a3 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 @@ -4,6 +4,7 @@ import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; import com.adityachandel.booklore.model.enums.BookFileExtension; +import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.PermissionType; import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.LibraryRepository; @@ -20,6 +21,7 @@ import java.nio.file.*; import java.util.Optional; import java.util.Set; import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; @Slf4j @Service @@ -27,6 +29,8 @@ 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 int MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK = 2; private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); private final LibraryRepository libraryRepository; @@ -36,6 +40,8 @@ public class LibraryFileEventProcessor { private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); private final ConcurrentMap> pendingDeletes = new ConcurrentHashMap<>(); + private final ConcurrentMap> pendingFolderCreates = new ConcurrentHashMap<>(); + private final Set filesFromPendingFolder = ConcurrentHashMap.newKeySet(); @PostConstruct public void init() { @@ -56,11 +62,12 @@ 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); if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) { // Schedule DELETE after debounce ScheduledFuture existing = pendingDeletes.put(path, scheduler.schedule(() -> { - eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath)); + eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath, false)); pendingDeletes.remove(path); }, DEBOUNCE_MS, TimeUnit.MILLISECONDS)); @@ -73,18 +80,41 @@ public class LibraryFileEventProcessor { log.debug("[DEBOUNCE] CREATE ignored because pending DELETE exists for '{}'", path); return; } - // Otherwise process CREATE immediately - eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath)); + + 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)); + 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)); + } + } } else { // Other events - eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath)); + eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath, false)); } } private void handleEvent(FileEvent event) { Path path = Paths.get(event.filePath()).toAbsolutePath().normalize(); String fileName = path.getFileName().toString(); - log.info("[PROCESS] '{}' event for '{}'", event.eventKind().name(), fileName); + log.info("[PROCESS] '{}' event for '{}'{}", event.eventKind().name(), fileName, + event.isDebouncedFolder() ? " (debounced folder)" : ""); LibraryEntity library = libraryRepository.findById(event.libraryId()) .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(event.libraryId())); @@ -94,7 +124,10 @@ public class LibraryFileEventProcessor { return; } - if (isFolder(path)) { + // Use isDebouncedFolder flag for debounced events, otherwise fall back to heuristic + boolean isDirectory = event.isDebouncedFolder() || isFolder(path); + + if (isDirectory) { switch (event.eventKind().name()) { case "ENTRY_CREATE" -> handleFolderCreate(library, path); case "ENTRY_DELETE" -> handleFolderDelete(library, path); @@ -130,14 +163,26 @@ public class LibraryFileEventProcessor { String fileName = relPath.getFileName().toString(); String fileSubPath = Optional.ofNullable(relPath.getParent()).map(Path::toString).orElse(""); - bookFilePersistenceService.findByLibraryPathSubPathAndFileName(libPathEntity.getId(), fileSubPath, fileName) - .ifPresentOrElse(book -> { - book.setDeleted(true); - bookFilePersistenceService.save(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", fileName); - }, () -> log.warn("[NOT_FOUND] Book for deleted path '{}' not found", path)); + 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)); } catch (Exception e) { log.warn("[ERROR] While handling file delete '{}': {}", path, e.getMessage()); @@ -146,18 +191,95 @@ public class LibraryFileEventProcessor { private void handleFolderCreate(LibraryEntity library, Path folderPath) { log.info("[FOLDER_CREATE] '{}'", folderPath); - try (var stream = Files.walk(folderPath)) { - stream.filter(Files::isRegularFile) + + // Check if folder is a folder-based audiobook (2+ audio files, no ebook files) + FolderAnalysis analysis = analyzeFolderForAudiobook(folderPath); + + if (analysis.isFolderBasedAudiobook()) { + log.info("[FOLDER_AUDIOBOOK] Detected folder-based audiobook: {} ({} audio files)", + 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()) { + if (iterator.next().startsWith(folderPath)) { + iterator.remove(); + cleared++; + } + } + if (cleared > 0) { + log.debug("[FOLDER_AUDIOBOOK] Cleared {} tracked files that are now part of folder audiobook", cleared); + } + } catch (Exception e) { + 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)) .filter(p -> isBookFile(p.getFileName().toString())) - .forEach(p -> { - try { - bookFileTransactionalHandler.handleNewBookFile(library.getId(), p); - } catch (Exception e) { - log.warn("[ERROR] Processing file '{}': {}", p, e.getMessage()); - } - }); + .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); + } + } + + // 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()); + } + } + } + + private FolderAnalysis analyzeFolderForAudiobook(Path folderPath) { + int audioFileCount = 0; + boolean hasNonAudioBook = false; + + try (var stream = Files.walk(folderPath)) { + var files = stream.filter(Files::isRegularFile).toList(); + + for (Path file : files) { + String fileName = file.getFileName().toString(); + var ext = BookFileExtension.fromFileName(fileName); + if (ext.isPresent()) { + if (ext.get().getType() == BookFileType.AUDIOBOOK) { + audioFileCount++; + } else { + hasNonAudioBook = true; + } + } + } } catch (IOException e) { - log.warn("[ERROR] Walking folder '{}': {}", folderPath, e.getMessage()); + log.warn("[ERROR] Analyzing folder '{}': {}", folderPath, e.getMessage()); + } + + return new FolderAnalysis(audioFileCount, hasNonAudioBook); + } + + private record FolderAnalysis(int audioFileCount, boolean hasNonAudioBook) { + boolean isFolderBasedAudiobook() { + return audioFileCount >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBook; } } @@ -189,6 +311,6 @@ public class LibraryFileEventProcessor { log.info("Shutting down LibraryFileEventProcessor..."); } - public record FileEvent(WatchEvent.Kind eventKind, long libraryId, String libraryPath, String filePath) { + public record FileEvent(WatchEvent.Kind eventKind, long libraryId, String libraryPath, String filePath, boolean isDebouncedFolder) { } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/BookFileGroupingUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/BookFileGroupingUtils.java new file mode 100644 index 000000000..1b586fc7d --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/BookFileGroupingUtils.java @@ -0,0 +1,447 @@ +package com.adityachandel.booklore.util; + +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import lombok.experimental.UtilityClass; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.text.similarity.FuzzyScore; + +import java.util.*; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@UtilityClass +@Slf4j +public class BookFileGroupingUtils { + + private static final Pattern FORMAT_INDICATOR_PATTERN = Pattern.compile( + "[\\(\\[]\\s*(?:pdf|epub|mobi|azw3?|fb2|cbz|cbr|cb7|m4b|m4a|mp3|audiobook|audio)\\s*[\\)\\]]", + Pattern.CASE_INSENSITIVE + ); + + private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+"); + + private static final Pattern UNDERSCORE_PATTERN = Pattern.compile("_"); + + // Matches trailing author: " - J.R.R. Tolkien", " - George Orwell", " - J.K. Rowling" + private static final Pattern TRAILING_AUTHOR_PATTERN = Pattern.compile( + "\\s*[-–—]\\s+(?:[A-Z](?:\\.[A-Z])*\\.\\s+)?[A-Z][a-z]+(?:\\s+[A-Z](?:\\.[A-Z])*\\.?)?(?:\\s+[A-Z][a-z]+)*\\s*$" + ); + + // Matches ", The" or ", A" or ", An" at end + private static final Pattern ARTICLE_SUFFIX_PATTERN = Pattern.compile( + ",\\s*(The|A|An)\\s*$", Pattern.CASE_INSENSITIVE + ); + + // Series patterns: "Book 1", "Vol. 2", "Part 3", "#4", etc. + private static final Pattern SERIES_NUMBER_PATTERN = Pattern.compile( + "(?:book|vol(?:ume)?|part|chapter|episode|#|no\\.?)\\s*(\\d+)", + Pattern.CASE_INSENSITIVE + ); + + // Trailing number pattern: "book1", "book 2", "title_03" + private static final Pattern TRAILING_NUMBER_PATTERN = Pattern.compile( + "[\\s_-]?(\\d{1,3})\\s*$" + ); + + // Edition/version patterns that should NOT prevent grouping + // Includes format indicators (audiobook, ebook) and edition descriptors + private static final Pattern EDITION_PATTERN = Pattern.compile( + "(?:tenth|first|second|third|\\d+(?:st|nd|rd|th)?)\\s*(?:anniversary|edition|ed\\.?)|" + + "(?:unabridged|abridged|complete|full\\s*cast|deluxe|special|collector)|" + + "(?:audiobook|audio\\s*book|ebook|e-book)", + Pattern.CASE_INSENSITIVE + ); + + private static final double FOLDER_MATCH_THRESHOLD = 0.6; + private static final double FUZZY_CLUSTER_THRESHOLD = 0.7; + + // Known book file extensions - only strip these, not arbitrary dots in folder names + private static final Set KNOWN_EXTENSIONS = Set.of( + "pdf", "epub", "cbz", "cbr", "cb7", "mobi", "azw3", "azw", "fb2", + "m4b", "m4a", "mp3", "aac", "flac", "opus", "ogg" + ); + + public String extractGroupingKey(String fileName) { + if (fileName == null || fileName.isEmpty()) { + return ""; + } + + int lastDot = fileName.lastIndexOf('.'); + String baseName; + if (lastDot > 0) { + String possibleExtension = fileName.substring(lastDot + 1).toLowerCase(); + // Only strip if it's a known book file extension + if (KNOWN_EXTENSIONS.contains(possibleExtension)) { + baseName = fileName.substring(0, lastDot); + } else { + baseName = fileName; + } + } else { + baseName = fileName; + } + + // Convert underscores to spaces + baseName = UNDERSCORE_PATTERN.matcher(baseName).replaceAll(" "); + + baseName = FORMAT_INDICATOR_PATTERN.matcher(baseName).replaceAll(""); + + // Strip trailing author names (after dash) + baseName = TRAILING_AUTHOR_PATTERN.matcher(baseName).replaceAll(""); + + // Reposition articles ("Hobbit, The" -> "The Hobbit") + Matcher articleMatcher = ARTICLE_SUFFIX_PATTERN.matcher(baseName); + if (articleMatcher.find()) { + String article = articleMatcher.group(1); + baseName = article + " " + baseName.substring(0, articleMatcher.start()); + } + + baseName = WHITESPACE_PATTERN.matcher(baseName.trim()).replaceAll(" "); + + return baseName.toLowerCase().trim(); + } + + public double calculateSimilarity(String s1, String s2) { + if (s1 == null || s2 == null || s1.isEmpty() || s2.isEmpty()) { + return 0; + } + FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH); + int score = fuzzyScore.fuzzyScore(s1, s2); + int maxScore = Math.max( + fuzzyScore.fuzzyScore(s1, s1), + fuzzyScore.fuzzyScore(s2, s2) + ); + return maxScore > 0 ? (double) score / maxScore : 0; + } + + public String generateDirectoryGroupKey(String fileSubPath, String fileName) { + String safeSubPath = (fileSubPath == null) ? "" : fileSubPath; + return safeSubPath + ":" + extractGroupingKey(fileName); + } + + /** + * Groups library files using folder-centric strategy with fuzzy matching. + *

+ * Strategy: + * 1. Group files by folder (libraryPathId + fileSubPath) + * 2. For files in subfolders: use folder name as reference title + * - Files matching folder name (substring/fuzzy) → group together + * - Series entries (numbered) → keep separate + * - Unrelated files → separate books + * 3. For root-level files: use exact grouping key matching + */ + public Map> groupByBaseName(List libraryFiles) { + Map> result = new LinkedHashMap<>(); + + // First, group files by folder + Map> byFolder = new LinkedHashMap<>(); + for (LibraryFile file : libraryFiles) { + String folderKey = file.getLibraryPathEntity().getId() + ":" + + (file.getFileSubPath() == null ? "" : file.getFileSubPath()); + byFolder.computeIfAbsent(folderKey, k -> new ArrayList<>()).add(file); + } + + // Process each folder + for (Map.Entry> folderEntry : byFolder.entrySet()) { + List filesInFolder = folderEntry.getValue(); + String folderKey = folderEntry.getKey(); + + if (filesInFolder.isEmpty()) { + continue; + } + + String fileSubPath = filesInFolder.get(0).getFileSubPath(); + Long libraryPathId = filesInFolder.get(0).getLibraryPathEntity().getId(); + + // Root-level files: use exact grouping + if (fileSubPath == null || fileSubPath.isEmpty()) { + for (LibraryFile file : filesInFolder) { + String key = libraryPathId + "::" + extractGroupingKey(file.getFileName()); + result.computeIfAbsent(key, k -> new ArrayList<>()).add(file); + } + continue; + } + + // Files in subfolder: use folder-centric grouping + Map> folderGroups = groupFilesInFolder(filesInFolder, fileSubPath, libraryPathId); + result.putAll(folderGroups); + } + + return result; + } + + /** + * Groups files within a folder using the folder name as reference. + */ + private Map> groupFilesInFolder(List files, String fileSubPath, Long libraryPathId) { + Map> result = new LinkedHashMap<>(); + + // Extract folder name (last component of subPath) + String folderName = extractFolderName(fileSubPath); + String folderKey = extractGroupingKey(folderName); + + // Categorize files + Map> matchesFolderByNumber = new LinkedHashMap<>(); + Map> seriesEntries = new LinkedHashMap<>(); + List unmatched = new ArrayList<>(); + + for (LibraryFile file : files) { + String fileKey = extractGroupingKey(file.getFileName()); + + // Check for series numbering (e.g., "Harry Potter Book 1") + SeriesInfo seriesInfo = extractSeriesInfo(fileKey); + if (seriesInfo != null && seriesInfo.number != null) { + // Check if the base title (without number) matches folder + if (matchesFolderName(seriesInfo.baseTitle, folderKey)) { + // This is a series entry - keep separate by number + String seriesGroupKey = libraryPathId + ":" + fileSubPath + ":series:" + seriesInfo.baseTitle + ":" + seriesInfo.number; + seriesEntries.computeIfAbsent(seriesGroupKey, k -> new ArrayList<>()).add(file); + continue; + } + } + + // Check if file matches folder name + if (matchesFolderName(fileKey, folderKey)) { + // Extract trailing number to differentiate "book1" vs "book2" + String trailingNum = extractTrailingNumber(fileKey); + String numberKey = trailingNum != null ? trailingNum : "none"; + matchesFolderByNumber.computeIfAbsent(numberKey, k -> new ArrayList<>()).add(file); + } else { + unmatched.add(file); + } + } + + // Group files that match folder name, separating by trailing number + for (Map.Entry> entry : matchesFolderByNumber.entrySet()) { + List filesWithNumber = entry.getValue(); + String numberSuffix = "none".equals(entry.getKey()) ? "" : ":" + entry.getKey(); + String groupKey = libraryPathId + ":" + fileSubPath + ":folder:" + folderKey + numberSuffix; + result.put(groupKey, filesWithNumber); + log.debug("Grouped {} files matching folder '{}'{}: {}", filesWithNumber.size(), folderName, + numberSuffix.isEmpty() ? "" : " (num=" + entry.getKey() + ")", + filesWithNumber.stream().map(LibraryFile::getFileName).toList()); + } + + // Add series entries as separate groups + result.putAll(seriesEntries); + + // Handle unmatched files - try to cluster by similarity + if (!unmatched.isEmpty()) { + Map> clusters = clusterBySimilarity(unmatched, libraryPathId, fileSubPath); + result.putAll(clusters); + } + + return result; + } + + /** + * Extracts the trailing number from a key, if present. + */ + private String extractTrailingNumber(String key) { + Matcher m = TRAILING_NUMBER_PATTERN.matcher(key); + if (m.find()) { + return m.group(1); + } + return null; + } + + /** + * Extracts the folder name from a subPath (last component). + */ + private String extractFolderName(String fileSubPath) { + if (fileSubPath == null || fileSubPath.isEmpty()) { + return ""; + } + int lastSlash = fileSubPath.lastIndexOf('/'); + if (lastSlash >= 0 && lastSlash < fileSubPath.length() - 1) { + return fileSubPath.substring(lastSlash + 1); + } + return fileSubPath; + } + + /** + * Checks if a file's grouping key matches the folder name. + * Uses substring matching and fuzzy similarity. + */ + private boolean matchesFolderName(String fileKey, String folderKey) { + if (fileKey.isEmpty() || folderKey.isEmpty()) { + return false; + } + + // Exact match + if (fileKey.equals(folderKey)) { + return true; + } + + // Substring match (either direction) + if (fileKey.contains(folderKey) || folderKey.contains(fileKey)) { + return true; + } + + // Strip edition info and compare + String fileKeyClean = stripEditionInfo(fileKey); + String folderKeyClean = stripEditionInfo(folderKey); + if (fileKeyClean.equals(folderKeyClean)) { + return true; + } + if (fileKeyClean.contains(folderKeyClean) || folderKeyClean.contains(fileKeyClean)) { + return true; + } + + // Fuzzy match + double similarity = calculateSimilarity(fileKeyClean, folderKeyClean); + return similarity >= FOLDER_MATCH_THRESHOLD; + } + + /** + * Strips edition/version information from a key for comparison. + */ + private String stripEditionInfo(String key) { + String result = EDITION_PATTERN.matcher(key).replaceAll(""); + return WHITESPACE_PATTERN.matcher(result.trim()).replaceAll(" ").trim(); + } + + /** + * Extracts series information (base title and number) from a grouping key. + */ + private SeriesInfo extractSeriesInfo(String key) { + Matcher matcher = SERIES_NUMBER_PATTERN.matcher(key); + if (matcher.find()) { + String number = matcher.group(1) != null ? matcher.group(1) : matcher.group(2); + if (number != null) { + // Remove the series number pattern to get base title + String baseTitle = SERIES_NUMBER_PATTERN.matcher(key).replaceAll("").trim(); + baseTitle = WHITESPACE_PATTERN.matcher(baseTitle).replaceAll(" ").trim(); + // Only consider it a series if there's a meaningful base title + if (baseTitle.length() >= 3) { + return new SeriesInfo(baseTitle, number); + } + } + } + return null; + } + + /** + * Clusters unmatched files by fuzzy similarity. + * Uses union-find to group similar files together. + * Files with different trailing numbers are kept separate (e.g., "book1" vs "book2"). + */ + private Map> clusterBySimilarity(List files, Long libraryPathId, String fileSubPath) { + Map> result = new LinkedHashMap<>(); + + if (files.size() == 1) { + LibraryFile file = files.get(0); + String key = libraryPathId + ":" + fileSubPath + ":single:" + extractGroupingKey(file.getFileName()); + result.put(key, new ArrayList<>(List.of(file))); + return result; + } + + // Extract keys for all files + List keys = files.stream() + .map(f -> extractGroupingKey(f.getFileName())) + .toList(); + + // Union-Find for clustering + int[] parent = new int[files.size()]; + for (int i = 0; i < parent.length; i++) { + parent[i] = i; + } + + // Compare each pair and union if similar + for (int i = 0; i < files.size(); i++) { + for (int j = i + 1; j < files.size(); j++) { + String key1 = stripEditionInfo(keys.get(i)); + String key2 = stripEditionInfo(keys.get(j)); + + // Don't cluster files that have different trailing numbers + // This prevents "book1" and "book2" from being grouped + if (hasDifferentTrailingNumbers(key1, key2)) { + continue; + } + + // Check substring match or fuzzy similarity + boolean shouldGroup = key1.contains(key2) || key2.contains(key1) || + calculateSimilarity(key1, key2) >= FUZZY_CLUSTER_THRESHOLD; + + if (shouldGroup) { + union(parent, i, j); + } + } + } + + // Group files by their root + Map> clusters = new LinkedHashMap<>(); + for (int i = 0; i < files.size(); i++) { + int root = find(parent, i); + clusters.computeIfAbsent(root, k -> new ArrayList<>()).add(files.get(i)); + } + + // Convert to result format + for (Map.Entry> cluster : clusters.entrySet()) { + List clusterFiles = cluster.getValue(); + // Use the first file's key as the group key + String groupKey = libraryPathId + ":" + fileSubPath + ":cluster:" + + extractGroupingKey(clusterFiles.get(0).getFileName()); + result.put(groupKey, clusterFiles); + + if (clusterFiles.size() > 1) { + log.debug("Clustered {} unmatched files: {}", clusterFiles.size(), + clusterFiles.stream().map(LibraryFile::getFileName).toList()); + } + } + + return result; + } + + /** + * Checks if two keys have different trailing numbers. + * Returns true if both have trailing numbers AND they're different. + * This prevents grouping "book1" with "book2". + */ + private boolean hasDifferentTrailingNumbers(String key1, String key2) { + Matcher m1 = TRAILING_NUMBER_PATTERN.matcher(key1); + Matcher m2 = TRAILING_NUMBER_PATTERN.matcher(key2); + + boolean has1 = m1.find(); + boolean has2 = m2.find(); + + // If both have trailing numbers, check if they're different + if (has1 && has2) { + String num1 = m1.group(1); + String num2 = m2.group(1); + return !num1.equals(num2); + } + + // If only one has a number, they might still be different books + // e.g., "book" vs "book2" - let other heuristics decide + return false; + } + + private int find(int[] parent, int i) { + if (parent[i] != i) { + parent[i] = find(parent, parent[i]); + } + return parent[i]; + } + + private void union(int[] parent, int i, int j) { + int rootI = find(parent, i); + int rootJ = find(parent, j); + if (rootI != rootJ) { + parent[rootJ] = rootI; + } + } + + /** + * Helper class to hold series information. + */ + private static class SeriesInfo { + final String baseTitle; + final String number; + + SeriesInfo(String baseTitle, String number) { + this.baseTitle = baseTitle; + this.number = number; + } + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/BookProgressUtil.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/BookProgressUtil.java deleted file mode 100644 index 8ba9ac735..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/BookProgressUtil.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.adityachandel.booklore.util; - -import com.adityachandel.booklore.model.dto.*; -import com.adityachandel.booklore.model.dto.progress.*; -import com.adityachandel.booklore.model.entity.UserBookProgressEntity; -import com.adityachandel.booklore.model.enums.BookFileType; -import com.adityachandel.booklore.model.enums.ReadStatus; - -public class BookProgressUtil { - - public static void setBookProgress(Book book, UserBookProgressEntity progress) { - if (progress.getKoboProgressPercent() != null) { - book.setKoboProgress(KoboProgress.builder() - .percentage(progress.getKoboProgressPercent()) - .build()); - } - - BookFileType type = book.getBookType(); - if (type == null) return; - - switch (type) { - case EPUB -> { - book.setEpubProgress(EpubProgress.builder() - .cfi(progress.getEpubProgress()) - .href(progress.getEpubProgressHref()) - .percentage(progress.getEpubProgressPercent()) - .build()); - book.setKoreaderProgress(KoProgress.builder() - .percentage(progress.getKoreaderProgressPercent() != null ? progress.getKoreaderProgressPercent() * 100 : null) - .build()); - } - case FB2, MOBI, AZW3 -> book.setEpubProgress(EpubProgress.builder() - .cfi(progress.getEpubProgress()) - .href(progress.getEpubProgressHref()) - .percentage(progress.getEpubProgressPercent()) - .build()); - case PDF -> book.setPdfProgress(PdfProgress.builder() - .page(progress.getPdfProgress()) - .percentage(progress.getPdfProgressPercent()) - .build()); - case CBX -> book.setCbxProgress(CbxProgress.builder() - .page(progress.getCbxProgress()) - .percentage(progress.getCbxProgressPercent()) - .build()); - } - } - - public static void enrichBookWithProgress(Book book, UserBookProgressEntity progress) { - if (progress != null) { - setBookProgress(book, progress); - book.setLastReadTime(progress.getLastReadTime()); - book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus())); - book.setDateFinished(progress.getDateFinished()); - book.setPersonalRating(progress.getPersonalRating()); - } - } -} - diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java index bc74a9bb0..9f34fe1ea 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java @@ -324,7 +324,19 @@ public class FileService { File originalFile = new File(folder, COVER_FILENAME); boolean originalSaved = ImageIO.write(rgbImage, IMAGE_FORMAT, originalFile); - thumb = resizeImage(rgbImage, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT); + // Determine thumbnail dimensions based on source aspect ratio + int thumbWidth, thumbHeight; + double aspectRatio = (double) rgbImage.getWidth() / rgbImage.getHeight(); + if (aspectRatio >= 0.85 && aspectRatio <= 1.15) { + // Square-ish image (e.g., audiobook covers) - keep square + thumbWidth = THUMBNAIL_WIDTH; + thumbHeight = THUMBNAIL_WIDTH; + } else { + // Portrait/landscape - use standard dimensions + thumbWidth = THUMBNAIL_WIDTH; + thumbHeight = THUMBNAIL_HEIGHT; + } + thumb = resizeImage(rgbImage, thumbWidth, thumbHeight); File thumbnailFile = new File(folder, THUMBNAIL_FILENAME); boolean thumbnailSaved = ImageIO.write(thumb, IMAGE_FORMAT, thumbnailFile); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java index aa360d784..ff275baa3 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java @@ -24,6 +24,9 @@ public class FileUtils { public String getBookFullPath(BookEntity bookEntity) { BookFileEntity bookFile = bookEntity.getPrimaryBookFile(); + if (bookFile == null || bookEntity.getLibraryPath() == null) { + return null; + } return Path.of(bookEntity.getLibraryPath().getPath(), bookFile.getFileSubPath(), bookFile.getFileName()) .normalize() @@ -32,10 +35,7 @@ public class FileUtils { } public String getBookFullPath(Book book) { - return Path.of(book.getLibraryPath().getPath(), book.getFileSubPath(), book.getFileName()) - .normalize() - .toString() - .replace("\\", "/"); + return book.getPrimaryFile().getFilePath(); } public String getRelativeSubPath(String basePath, Path fullFilePath) { @@ -64,6 +64,81 @@ public class FileUtils { } } + /** + * Calculate total size of all files in a folder (for folder-based audiobooks). + */ + public Long getFolderSizeInKb(Path folderPath) { + try { + if (!Files.exists(folderPath) || !Files.isDirectory(folderPath)) { + log.warn("Folder does not exist or is not a directory: {}", folderPath.toAbsolutePath()); + return null; + } + long totalBytes = Files.walk(folderPath) + .filter(Files::isRegularFile) + .mapToLong(p -> { + try { + return Files.size(p); + } catch (IOException e) { + return 0L; + } + }) + .sum(); + return totalBytes / 1024; + } catch (IOException e) { + log.error("Failed to get folder size for path [{}]: {}", folderPath, e.getMessage(), e); + return null; + } + } + + /** + * Get the first audio file in a folder (sorted alphabetically). + */ + public Optional getFirstAudioFileInFolder(Path folderPath) { + try { + if (!Files.exists(folderPath) || !Files.isDirectory(folderPath)) { + return Optional.empty(); + } + return Files.list(folderPath) + .filter(Files::isRegularFile) + .filter(p -> isAudioFile(p.getFileName().toString())) + .sorted(Comparator.comparing(p -> p.getFileName().toString())) + .findFirst(); + } catch (IOException e) { + log.error("Failed to list folder [{}]: {}", folderPath, e.getMessage(), e); + return Optional.empty(); + } + } + + /** + * Check if a filename is an audio file. + */ + public boolean isAudioFile(String fileName) { + if (fileName == null) return false; + String lower = fileName.toLowerCase(); + return lower.endsWith(".mp3") || lower.endsWith(".m4a") || lower.endsWith(".m4b") + || lower.endsWith(".flac") || lower.endsWith(".ogg") || lower.endsWith(".opus") + || lower.endsWith(".aac"); + } + + /** + * List all audio files in a folder, sorted alphabetically. + */ + public List listAudioFilesInFolder(Path folderPath) { + try { + if (!Files.exists(folderPath) || !Files.isDirectory(folderPath)) { + return List.of(); + } + return Files.list(folderPath) + .filter(Files::isRegularFile) + .filter(p -> isAudioFile(p.getFileName().toString())) + .sorted(Comparator.comparing(p -> p.getFileName().toString())) + .toList(); + } catch (IOException e) { + log.error("Failed to list audio files in folder [{}]: {}", folderPath, e.getMessage(), e); + return List.of(); + } + } + public void deleteDirectoryRecursively(Path path) throws IOException { if (!Files.exists(path)) return; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/PathPatternResolver.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/PathPatternResolver.java index d1b901727..86b1b723b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/PathPatternResolver.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/PathPatternResolver.java @@ -36,36 +36,50 @@ public class PathPatternResolver { private final Pattern SLASH_PATTERN = Pattern.compile("/"); public String resolvePattern(BookEntity book, String pattern) { - return resolvePattern(book, book.getPrimaryBookFile(), pattern); + BookFileEntity primaryFile = book.getPrimaryBookFile(); + return resolvePattern(book, primaryFile, pattern, primaryFile != null && primaryFile.isFolderBased()); } public String resolvePattern(BookEntity book, BookFileEntity bookFile, String pattern) { + return resolvePattern(book, bookFile, pattern, bookFile != null && bookFile.isFolderBased()); + } + + public String resolvePattern(BookEntity book, BookFileEntity bookFile, String pattern, boolean folderBased) { String currentFilename = bookFile != null && bookFile.getFileName() != null ? bookFile.getFileName().trim() : ""; - return resolvePattern(book.getMetadata(), pattern, currentFilename); + return resolvePattern(book.getMetadata(), pattern, currentFilename, folderBased); } public String resolvePattern(BookMetadata metadata, String pattern, String filename) { MetadataProvider metadataProvider = MetadataProvider.from(metadata); - return resolvePattern(metadataProvider, pattern, filename); + return resolvePattern(metadataProvider, pattern, filename, false); } public String resolvePattern(BookMetadataEntity metadata, String pattern, String filename) { - MetadataProvider metadataProvider = MetadataProvider.from(metadata); - return resolvePattern(metadataProvider, pattern, filename); + return resolvePattern(metadata, pattern, filename, false); } - private String resolvePattern(MetadataProvider metadata, String pattern, String filename) { + public String resolvePattern(BookMetadataEntity metadata, String pattern, String filename, boolean folderBased) { + MetadataProvider metadataProvider = MetadataProvider.from(metadata); + return resolvePattern(metadataProvider, pattern, filename, folderBased); + } + + private String resolvePattern(MetadataProvider metadata, String pattern, String filename, boolean folderBased) { if (pattern == null || pattern.isBlank()) { return filename; } String filenameBase = "Untitled"; if (filename != null && !filename.isBlank()) { - int lastDot = filename.lastIndexOf('.'); - if (lastDot > 0) { - filenameBase = filename.substring(0, lastDot); - } else { + if (folderBased) { + // For folder-based items, don't strip extension from folder name filenameBase = filename; + } else { + int lastDot = filename.lastIndexOf('.'); + if (lastDot > 0) { + filenameBase = filename.substring(0, lastDot); + } else { + filenameBase = filename; + } } } @@ -118,14 +132,17 @@ public class PathPatternResolver { values.put("isbn", isbn); values.put("currentFilename", filename); - return resolvePatternWithValues(pattern, values, filename); + return resolvePatternWithValues(pattern, values, filename, folderBased); } - private String resolvePatternWithValues(String pattern, Map values, String currentFilename) { + private String resolvePatternWithValues(String pattern, Map values, String currentFilename, boolean folderBased) { String extension = ""; - int lastDot = currentFilename.lastIndexOf('.'); - if (lastDot >= 0 && lastDot < currentFilename.length() - 1) { - extension = sanitize(currentFilename.substring(lastDot + 1)); // e.g. "epub" + if (!folderBased) { + // Only extract extension for regular files, not for folder-based items + int lastDot = currentFilename.lastIndexOf('.'); + if (lastDot >= 0 && lastDot < currentFilename.length() - 1) { + extension = sanitize(currentFilename.substring(lastDot + 1)); // e.g. "epub" + } } values.put("extension", extension); @@ -190,12 +207,13 @@ public class PathPatternResolver { boolean patternIncludesExtension = pattern.contains("{extension}"); boolean patternIncludesFullFilename = pattern.contains("{currentFilename}"); - - if (!usedFallbackFilename && !patternIncludesExtension && !patternIncludesFullFilename && !extension.isBlank()) { + + // Don't auto-append extension for folder-based items + if (!folderBased && !usedFallbackFilename && !patternIncludesExtension && !patternIncludesFullFilename && !extension.isBlank()) { result += "." + extension; } - return validateFinalPath(result); + return validateFinalPath(result, folderBased); } private String sanitize(String input) { @@ -268,7 +286,7 @@ public class PathPatternResolver { } - private String validateFinalPath(String path) { + private String validateFinalPath(String path, boolean folderBased) { String[] components = SLASH_PATTERN.split(path); StringBuilder result = new StringBuilder(512); boolean first = true; @@ -281,14 +299,18 @@ public class PathPatternResolver { boolean isLastComponent = (i == components.length - 1); - if (isLastComponent && component.contains(".")) { + // For folder-based items, don't treat dots as extension separators + if (isLastComponent && component.contains(".") && !folderBased) { component = truncateFilenameWithExtension(component); } else { if (component.getBytes(StandardCharsets.UTF_8).length > MAX_FILESYSTEM_COMPONENT_BYTES) { component = truncatePathComponent(component, MAX_FILESYSTEM_COMPONENT_BYTES); } - while (component != null && !component.isEmpty() && component.endsWith(".")) { - component = component.substring(0, component.length() - 1); + // Don't strip trailing dots from folder names for folder-based items + if (!folderBased) { + while (component != null && !component.isEmpty() && component.endsWith(".")) { + component = component.substring(0, component.length() - 1); + } } } diff --git a/booklore-api/src/main/resources/application.yaml b/booklore-api/src/main/resources/application.yaml index cda011067..c22afd9a9 100644 --- a/booklore-api/src/main/resources/application.yaml +++ b/booklore-api/src/main/resources/application.yaml @@ -16,6 +16,7 @@ app: force-disable-oidc: ${FORCE_DISABLE_OIDC:false} telemetry: base-url: ${TELEMETRY_BASE_URL:https://telemetry.booklore.org} + disk-type: ${DISK_TYPE:LOCAL} server: forward-headers-strategy: native diff --git a/booklore-api/src/main/resources/db/migration/V100__Create_user_book_file_progress.sql b/booklore-api/src/main/resources/db/migration/V100__Create_user_book_file_progress.sql new file mode 100644 index 000000000..efd586dee --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V100__Create_user_book_file_progress.sql @@ -0,0 +1,14 @@ +CREATE TABLE user_book_file_progress ( + id BIGINT AUTO_INCREMENT PRIMARY KEY, + user_id BIGINT NOT NULL, + book_file_id BIGINT NOT NULL, + position_data VARCHAR(1000), + position_href VARCHAR(1000), + progress_percent FLOAT, + last_read_time TIMESTAMP, + CONSTRAINT uk_user_book_file UNIQUE (user_id, book_file_id), + CONSTRAINT fk_ubfp_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + CONSTRAINT fk_ubfp_book_file FOREIGN KEY (book_file_id) REFERENCES book_file(id) ON DELETE CASCADE +); + +CREATE INDEX idx_ubfp_user_book_file ON user_book_file_progress(user_id, book_file_id); diff --git a/booklore-api/src/main/resources/db/migration/V101__Migrate_default_book_format_to_format_priority.sql b/booklore-api/src/main/resources/db/migration/V101__Migrate_default_book_format_to_format_priority.sql new file mode 100644 index 000000000..b9d1305cd --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V101__Migrate_default_book_format_to_format_priority.sql @@ -0,0 +1,13 @@ +-- Migrate default_book_format (single value) to format_priority (JSON array) +-- This allows users to set a prioritized list of preferred formats with cascading fallback + +-- Add new column +ALTER TABLE library ADD COLUMN IF NOT EXISTS format_priority TEXT NULL; + +-- Migrate existing data: convert single format to JSON array with that format as first element +UPDATE library +SET format_priority = CONCAT('["', default_book_format, '"]') +WHERE default_book_format IS NOT NULL AND default_book_format != ''; + +-- Drop old column +ALTER TABLE library DROP COLUMN IF EXISTS default_book_format; diff --git a/booklore-api/src/main/resources/db/migration/V102__Add_is_folder_based_to_book_file.sql b/booklore-api/src/main/resources/db/migration/V102__Add_is_folder_based_to_book_file.sql new file mode 100644 index 000000000..f6b7ce3e9 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V102__Add_is_folder_based_to_book_file.sql @@ -0,0 +1,2 @@ +-- Add is_folder_based column to book_file table for folder-based audiobooks +ALTER TABLE book_file ADD COLUMN is_folder_based BOOLEAN NOT NULL DEFAULT FALSE; diff --git a/booklore-api/src/main/resources/db/migration/V103__Add_organization_mode_to_library.sql b/booklore-api/src/main/resources/db/migration/V103__Add_organization_mode_to_library.sql new file mode 100644 index 000000000..6b2abbc12 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V103__Add_organization_mode_to_library.sql @@ -0,0 +1,19 @@ +-- Add organization_mode column and migrate from legacy scan_mode +-- FOLDER_AS_BOOK -> BOOK_PER_FOLDER (preserves existing behavior) +-- FILE_AS_BOOK/NULL/unknown -> AUTO_DETECT (new default) + +ALTER TABLE library ADD COLUMN organization_mode VARCHAR(50); + +-- Migrate known values +UPDATE library SET organization_mode = 'BOOK_PER_FOLDER' WHERE scan_mode = 'FOLDER_AS_BOOK'; +UPDATE library SET organization_mode = 'AUTO_DETECT' WHERE scan_mode IS NULL OR scan_mode = 'FILE_AS_BOOK'; + +-- Safety net: set any remaining NULL values (handles unexpected scan_mode values) +UPDATE library SET organization_mode = 'AUTO_DETECT' WHERE organization_mode IS NULL; + +-- Set default and make non-null for future inserts +ALTER TABLE library ALTER COLUMN organization_mode SET DEFAULT 'AUTO_DETECT'; +ALTER TABLE library MODIFY COLUMN organization_mode VARCHAR(50) NOT NULL DEFAULT 'AUTO_DETECT'; + +-- Remove legacy column +ALTER TABLE library DROP COLUMN scan_mode; diff --git a/booklore-api/src/main/resources/db/migration/V104__Add_audiobook_bookmark_columns.sql b/booklore-api/src/main/resources/db/migration/V104__Add_audiobook_bookmark_columns.sql new file mode 100644 index 000000000..1e1af6fef --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V104__Add_audiobook_bookmark_columns.sql @@ -0,0 +1,6 @@ +-- Add columns for audiobook bookmarks +ALTER TABLE book_marks ADD COLUMN IF NOT EXISTS position_ms BIGINT; +ALTER TABLE book_marks ADD COLUMN IF NOT EXISTS track_index INTEGER; + +-- Make cfi nullable (audiobook bookmarks don't use cfi) +ALTER TABLE book_marks MODIFY COLUMN cfi VARCHAR(1000) NULL; diff --git a/booklore-api/src/main/resources/db/migration/V105__Make_reading_session_columns_nullable.sql b/booklore-api/src/main/resources/db/migration/V105__Make_reading_session_columns_nullable.sql new file mode 100644 index 000000000..56f9b552a --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V105__Make_reading_session_columns_nullable.sql @@ -0,0 +1,20 @@ +-- Make reading session columns nullable for audiobook support +-- Audiobooks may not have progress percentage data + +ALTER TABLE reading_sessions + ADD COLUMN duration_formatted VARCHAR(50) NULL; + +ALTER TABLE reading_sessions + MODIFY COLUMN start_progress FLOAT NULL; + +ALTER TABLE reading_sessions + MODIFY COLUMN end_progress FLOAT NULL; + +ALTER TABLE reading_sessions + MODIFY COLUMN progress_delta FLOAT NULL; + +ALTER TABLE reading_sessions + MODIFY COLUMN start_location VARCHAR(500) NULL; + +ALTER TABLE reading_sessions + MODIFY COLUMN end_location VARCHAR(500) NULL; diff --git a/booklore-api/src/main/resources/db/migration/V106__Add_physical_book_support.sql b/booklore-api/src/main/resources/db/migration/V106__Add_physical_book_support.sql new file mode 100644 index 000000000..59e878ea2 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V106__Add_physical_book_support.sql @@ -0,0 +1,8 @@ +-- Add is_physical column to book table for physical book support +ALTER TABLE book ADD COLUMN is_physical BOOLEAN NOT NULL DEFAULT FALSE; + +-- Make library_path_id nullable for physical books (they don't have a file path) +ALTER TABLE book MODIFY COLUMN library_path_id BIGINT NULL; + +-- Add index for physical books +CREATE INDEX idx_book_is_physical ON book(is_physical); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java b/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java index e07be5a5d..564640cd3 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java @@ -7,7 +7,7 @@ import com.adityachandel.booklore.service.book.BookDownloadService; import com.adityachandel.booklore.service.book.BookQueryService; import com.adityachandel.booklore.service.book.BookService; import com.adityachandel.booklore.service.book.BookUpdateService; -import com.adityachandel.booklore.service.user.UserProgressService; +import com.adityachandel.booklore.service.progress.ReadingProgressService; import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; import com.adityachandel.booklore.util.FileService; import org.junit.jupiter.api.BeforeEach; @@ -37,6 +37,7 @@ class BookServiceDeleteTests { @BeforeEach void setUp() { BookRepository bookRepository = Mockito.mock(BookRepository.class); + BookFileRepository bookFileRepository = Mockito.mock(BookFileRepository.class); PdfViewerPreferencesRepository pdfViewerPreferencesRepository = Mockito.mock(PdfViewerPreferencesRepository.class); EbookViewerPreferenceRepository ebookViewerPreferenceRepository = Mockito.mock(EbookViewerPreferenceRepository.class); CbxViewerPreferencesRepository cbxViewerPreferencesRepository = Mockito.mock(CbxViewerPreferencesRepository.class); @@ -46,13 +47,14 @@ class BookServiceDeleteTests { UserBookProgressRepository userBookProgressRepository = Mockito.mock(UserBookProgressRepository.class); AuthenticationService authenticationService = Mockito.mock(AuthenticationService.class); BookQueryService bookQueryService = Mockito.mock(BookQueryService.class); - UserProgressService userProgressService = Mockito.mock(UserProgressService.class); + ReadingProgressService readingProgressService = Mockito.mock(ReadingProgressService.class); BookDownloadService bookDownloadService = Mockito.mock(BookDownloadService.class); MonitoringRegistrationService monitoringRegistrationService = Mockito.mock(MonitoringRegistrationService.class); BookUpdateService bookUpdateService = Mockito.mock(BookUpdateService.class); bookService = new BookService( bookRepository, + bookFileRepository, pdfViewerPreferencesRepository, cbxViewerPreferencesRepository, newPdfViewerPreferencesRepository, @@ -61,7 +63,7 @@ class BookServiceDeleteTests { userBookProgressRepository, authenticationService, bookQueryService, - userProgressService, + readingProgressService, bookDownloadService, monitoringRegistrationService, bookUpdateService, diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/mapper/BookMapperTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/mapper/BookMapperTest.java index 1c2dec944..4171d38c0 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/mapper/BookMapperTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/mapper/BookMapperTest.java @@ -48,7 +48,7 @@ class BookMapperTest { assertThat(dto.getLibraryName()).isEqualTo("Test Library"); assertThat(dto.getLibraryPath()).isNotNull(); assertThat(dto.getLibraryPath().getId()).isEqualTo(1L); - assertThat(dto.getBookType()).isEqualTo(BookFileType.EPUB); + assertThat(dto.getPrimaryFile().getBookType()).isEqualTo(BookFileType.EPUB); assertThat(dto.getAlternativeFormats()).isEmpty(); assertThat(dto.getSupplementaryFiles()).isEmpty(); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/repository/BookOpdsRepositoryDataJpaTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/repository/BookOpdsRepositoryDataJpaTest.java index 133427eb6..cec307758 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/repository/BookOpdsRepositoryDataJpaTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/repository/BookOpdsRepositoryDataJpaTest.java @@ -4,7 +4,6 @@ import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; -import com.adityachandel.booklore.model.enums.LibraryScanMode; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; @@ -39,7 +38,6 @@ class BookOpdsRepositoryDataJpaTest { LibraryEntity library = LibraryEntity.builder() .name("Test Library") .icon("book") - .scanMode(LibraryScanMode.FILE_AS_BOOK) .watch(false) .build(); library = entityManager.persistAndFlush(library); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/BookMarkServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/BookMarkServiceTest.java index edb8740de..975e3b70b 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/BookMarkServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/BookMarkServiceTest.java @@ -80,8 +80,12 @@ class BookMarkServiceTest { @Test void createBookmark_Success() { - CreateBookMarkRequest request = new CreateBookMarkRequest(bookId, "new-cfi", "New Bookmark"); - + CreateBookMarkRequest request = CreateBookMarkRequest.builder() + .bookId(bookId) + .cfi("new-cfi") + .title("New Bookmark") + .build(); + when(authenticationService.getAuthenticatedUser()).thenReturn(userDto); when(bookmarkProperties.getDefaultPriority()).thenReturn(3); when(bookMarkRepository.existsByCfiAndBookIdAndUserId("new-cfi", bookId, userId)).thenReturn(false); @@ -99,7 +103,11 @@ class BookMarkServiceTest { @Test void createBookmark_Duplicate() { - CreateBookMarkRequest request = new CreateBookMarkRequest(bookId, "new-cfi", "New Bookmark"); + CreateBookMarkRequest request = CreateBookMarkRequest.builder() + .bookId(bookId) + .cfi("new-cfi") + .title("New Bookmark") + .build(); when(authenticationService.getAuthenticatedUser()).thenReturn(userDto); when(bookMarkRepository.existsByCfiAndBookIdAndUserId("new-cfi", bookId, userId)).thenReturn(true); // Duplicate exists @@ -110,7 +118,11 @@ class BookMarkServiceTest { @Test void createBookmark_BookNotFound() { - CreateBookMarkRequest request = new CreateBookMarkRequest(bookId, "new-cfi", "New Bookmark"); + CreateBookMarkRequest request = CreateBookMarkRequest.builder() + .bookId(bookId) + .cfi("new-cfi") + .title("New Bookmark") + .build(); when(authenticationService.getAuthenticatedUser()).thenReturn(userDto); when(bookMarkRepository.existsByCfiAndBookIdAndUserId("new-cfi", bookId, userId)).thenReturn(false); // No duplicate diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/FileStreamingServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/FileStreamingServiceTest.java new file mode 100644 index 000000000..a18f15306 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/FileStreamingServiceTest.java @@ -0,0 +1,409 @@ +package com.adityachandel.booklore.service; + +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class FileStreamingServiceTest { + + private FileStreamingService fileStreamingService; + + @TempDir + Path tempDir; + + Path testFile; + byte[] testContent; + + @BeforeEach + void setUp() throws IOException { + fileStreamingService = new FileStreamingService(); + + // Create a test file with known content + testContent = new byte[10000]; + for (int i = 0; i < testContent.length; i++) { + testContent[i] = (byte) (i % 256); + } + testFile = tempDir.resolve("test.bin"); + Files.write(testFile, testContent); + } + + // ==================== streamWithRangeSupport - Full file tests ==================== + + @Test + void streamWithRangeSupport_noRangeHeader_streamsFullFile() throws IOException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ServletOutputStream servletOutputStream = createServletOutputStream(outputStream); + + when(request.getHeader("Range")).thenReturn(null); + when(response.getOutputStream()).thenReturn(servletOutputStream); + + fileStreamingService.streamWithRangeSupport(testFile, "application/octet-stream", request, response); + + verify(response).setStatus(HttpServletResponse.SC_OK); + verify(response).setContentLengthLong(testContent.length); + verify(response).setHeader("Accept-Ranges", "bytes"); + verify(response).setContentType("application/octet-stream"); + assertArrayEquals(testContent, outputStream.toByteArray()); + } + + @Test + void streamWithRangeSupport_fileNotFound_sends404() throws IOException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + + Path nonexistent = tempDir.resolve("nonexistent.bin"); + + fileStreamingService.streamWithRangeSupport(nonexistent, "audio/mp4", request, response); + + verify(response).sendError(HttpServletResponse.SC_NOT_FOUND, "File not found"); + } + + // ==================== streamWithRangeSupport - Range request tests ==================== + + @Test + void streamWithRangeSupport_fullRange_streamsPartialContent() throws IOException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ServletOutputStream servletOutputStream = createServletOutputStream(outputStream); + + when(request.getHeader("Range")).thenReturn("bytes=0-99"); + when(response.getOutputStream()).thenReturn(servletOutputStream); + + fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response); + + verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); + verify(response).setContentLengthLong(100); + verify(response).setHeader("Content-Range", "bytes 0-99/" + testContent.length); + + byte[] expected = new byte[100]; + System.arraycopy(testContent, 0, expected, 0, 100); + assertArrayEquals(expected, outputStream.toByteArray()); + } + + @Test + void streamWithRangeSupport_openEndedRange_streamsToEnd() throws IOException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ServletOutputStream servletOutputStream = createServletOutputStream(outputStream); + + when(request.getHeader("Range")).thenReturn("bytes=9900-"); + when(response.getOutputStream()).thenReturn(servletOutputStream); + + fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response); + + verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); + verify(response).setContentLengthLong(100); + verify(response).setHeader("Content-Range", "bytes 9900-9999/" + testContent.length); + + byte[] expected = new byte[100]; + System.arraycopy(testContent, 9900, expected, 0, 100); + assertArrayEquals(expected, outputStream.toByteArray()); + } + + @Test + void streamWithRangeSupport_suffixRange_streamsLastNBytes() throws IOException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ServletOutputStream servletOutputStream = createServletOutputStream(outputStream); + + when(request.getHeader("Range")).thenReturn("bytes=-500"); + when(response.getOutputStream()).thenReturn(servletOutputStream); + + fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response); + + verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); + verify(response).setContentLengthLong(500); + verify(response).setHeader("Content-Range", "bytes 9500-9999/" + testContent.length); + + byte[] expected = new byte[500]; + System.arraycopy(testContent, 9500, expected, 0, 500); + assertArrayEquals(expected, outputStream.toByteArray()); + } + + @Test + void streamWithRangeSupport_invalidRange_sends416() throws IOException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + + when(request.getHeader("Range")).thenReturn("bytes=50000-60000"); // Beyond file size + + fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response); + + verify(response).setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); + verify(response).setHeader("Content-Range", "bytes */" + testContent.length); + } + + @Test + void streamWithRangeSupport_rangeEndBeyondFileSize_clampsToFileSize() throws IOException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ServletOutputStream servletOutputStream = createServletOutputStream(outputStream); + + when(request.getHeader("Range")).thenReturn("bytes=9990-99999"); // End beyond file + when(response.getOutputStream()).thenReturn(servletOutputStream); + + fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response); + + verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); + verify(response).setContentLengthLong(10); // 9990 to 9999 + verify(response).setHeader("Content-Range", "bytes 9990-9999/" + testContent.length); + } + + @Test + void streamWithRangeSupport_setsCacheControlHeader() throws IOException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ServletOutputStream servletOutputStream = createServletOutputStream(outputStream); + + when(request.getHeader("Range")).thenReturn(null); + when(response.getOutputStream()).thenReturn(servletOutputStream); + + fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response); + + verify(response).setHeader("Cache-Control", "public, max-age=3600"); + } + + // ==================== parseRange tests ==================== + + @Test + void parseRange_fullRange_parsesCorrectly() { + var result = fileStreamingService.parseRange("bytes=100-199", 1000); + + assertNotNull(result); + assertEquals(100, result.start()); + assertEquals(199, result.end()); + } + + @Test + void parseRange_openEndedRange_parsesCorrectly() { + var result = fileStreamingService.parseRange("bytes=500-", 1000); + + assertNotNull(result); + assertEquals(500, result.start()); + assertEquals(999, result.end()); + } + + @Test + void parseRange_suffixRange_parsesCorrectly() { + var result = fileStreamingService.parseRange("bytes=-200", 1000); + + assertNotNull(result); + assertEquals(800, result.start()); + assertEquals(999, result.end()); + } + + @Test + void parseRange_suffixRangeLargerThanFile_startsAtZero() { + var result = fileStreamingService.parseRange("bytes=-2000", 1000); + + assertNotNull(result); + assertEquals(0, result.start()); + assertEquals(999, result.end()); + } + + @Test + void parseRange_clampsEndToFileSize() { + var result = fileStreamingService.parseRange("bytes=900-2000", 1000); + + assertNotNull(result); + assertEquals(900, result.start()); + assertEquals(999, result.end()); + } + + @ParameterizedTest + @ValueSource(strings = { + "invalid", + "bytes", + "bytes=", + "bytes=abc-def", + "bytes=100-50", // End before start + "characters=0-100" + }) + void parseRange_invalidFormats_returnsNull(String rangeHeader) { + var result = fileStreamingService.parseRange(rangeHeader, 1000); + assertNull(result); + } + + @Test + void parseRange_startBeyondFileSize_returnsNull() { + var result = fileStreamingService.parseRange("bytes=2000-3000", 1000); + assertNull(result); + } + + @Test + void parseRange_multipleRanges_usesFirstOnly() { + var result = fileStreamingService.parseRange("bytes=0-99, 200-299", 1000); + + assertNotNull(result); + assertEquals(0, result.start()); + assertEquals(99, result.end()); + } + + @Test + void parseRange_withLeadingTrailingWhitespace_parsesCorrectly() { + // Leading/trailing whitespace around the range spec is trimmed + var result = fileStreamingService.parseRange("bytes=100-199", 1000); + + assertNotNull(result); + assertEquals(100, result.start()); + assertEquals(199, result.end()); + } + + @Test + void parseRange_withWhitespaceAroundComma_parsesFirstRange() { + var result = fileStreamingService.parseRange("bytes= 100-199 , 300-399", 1000); + + assertNotNull(result); + assertEquals(100, result.start()); + assertEquals(199, result.end()); + } + + // ==================== isClientDisconnect tests ==================== + + @Test + void isClientDisconnect_socketTimeoutException_returnsTrue() { + assertTrue(fileStreamingService.isClientDisconnect(new SocketTimeoutException("timeout"))); + } + + @ParameterizedTest + @ValueSource(strings = { + "Connection reset", + "Broken pipe", + "connection was aborted", + "An established connection was aborted", + "SocketTimeout occurred", + "Connection timed out" + }) + void isClientDisconnect_knownMessages_returnsTrue(String message) { + assertTrue(fileStreamingService.isClientDisconnect(new IOException(message))); + } + + @Test + void isClientDisconnect_unknownMessage_returnsFalse() { + assertFalse(fileStreamingService.isClientDisconnect(new IOException("Unknown error"))); + } + + @Test + void isClientDisconnect_nullMessage_checksClassName() { + // Create an IOException with null message but class name containing "Timeout" + IOException timeoutException = new SocketTimeoutException(); + assertTrue(fileStreamingService.isClientDisconnect(timeoutException)); + } + + @Test + void isClientDisconnect_regularIOException_returnsFalse() { + assertFalse(fileStreamingService.isClientDisconnect(new IOException("Read failed"))); + } + + // ==================== Edge cases ==================== + + @Test + void streamWithRangeSupport_emptyFile_handlesCorrectly() throws IOException { + Path emptyFile = tempDir.resolve("empty.bin"); + Files.createFile(emptyFile); + + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ServletOutputStream servletOutputStream = createServletOutputStream(outputStream); + + when(request.getHeader("Range")).thenReturn(null); + when(response.getOutputStream()).thenReturn(servletOutputStream); + + // This should handle empty file gracefully - the stream will be empty + fileStreamingService.streamWithRangeSupport(emptyFile, "audio/mp4", request, response); + + verify(response).setStatus(HttpServletResponse.SC_OK); + verify(response).setContentLengthLong(0); + } + + @Test + void streamWithRangeSupport_singleByteRange_streamsOneByte() throws IOException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ServletOutputStream servletOutputStream = createServletOutputStream(outputStream); + + when(request.getHeader("Range")).thenReturn("bytes=50-50"); + when(response.getOutputStream()).thenReturn(servletOutputStream); + + fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response); + + verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); + verify(response).setContentLengthLong(1); + assertEquals(1, outputStream.size()); + assertEquals(testContent[50], outputStream.toByteArray()[0]); + } + + @ParameterizedTest + @CsvSource({ + "0, 0", + "0, 9999", + "5000, 5000", + "9999, 9999" + }) + void streamWithRangeSupport_variousValidRanges_streamsCorrectContent(int start, int end) throws IOException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ServletOutputStream servletOutputStream = createServletOutputStream(outputStream); + + when(request.getHeader("Range")).thenReturn("bytes=" + start + "-" + end); + when(response.getOutputStream()).thenReturn(servletOutputStream); + + fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response); + + int expectedLength = end - start + 1; + assertEquals(expectedLength, outputStream.size()); + + byte[] expected = new byte[expectedLength]; + System.arraycopy(testContent, start, expected, 0, expectedLength); + assertArrayEquals(expected, outputStream.toByteArray()); + } + + // Helper method to create a mock ServletOutputStream + private ServletOutputStream createServletOutputStream(ByteArrayOutputStream outputStream) { + return new ServletOutputStream() { + @Override + public boolean isReady() { + return true; + } + + @Override + public void setWriteListener(jakarta.servlet.WriteListener writeListener) { + } + + @Override + public void write(int b) throws IOException { + outputStream.write(b); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + outputStream.write(b, off, len); + } + }; + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookServiceTest.java index 3acc0f326..10f3ec3d3 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookServiceTest.java @@ -11,7 +11,7 @@ import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.*; import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; -import com.adityachandel.booklore.service.user.UserProgressService; +import com.adityachandel.booklore.service.progress.ReadingProgressService; import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileUtils; import org.junit.jupiter.api.BeforeEach; @@ -63,7 +63,7 @@ class BookServiceTest { @Mock private BookQueryService bookQueryService; @Mock - private UserProgressService userProgressService; + private ReadingProgressService readingProgressService; @Mock private BookDownloadService bookDownloadService; @Mock @@ -89,9 +89,9 @@ class BookServiceTest { @Test void getBookDTOs_adminUser_returnsBooksWithProgress() { - Book book = Book.builder().id(1L).bookType(BookFileType.PDF).shelves(Set.of()).build(); + Book book = Book.builder().id(1L).primaryFile(BookFile.builder().bookType(BookFileType.PDF).build()).shelves(Set.of()).build(); when(bookQueryService.getAllBooks(anyBoolean())).thenReturn(List.of(book)); - when(userProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(1L, new UserBookProgressEntity())); + when(readingProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(1L, new UserBookProgressEntity())); when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); List result = bookService.getBookDTOs(true); @@ -114,8 +114,8 @@ class BookServiceTest { library.setLibraryPaths(List.of(libPath)); entity.setLibrary(library); when(bookQueryService.findAllWithMetadataByIds(anySet())).thenReturn(List.of(entity)); - when(userProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(2L, new UserBookProgressEntity())); - Book mappedBook = Book.builder().id(2L).bookType(BookFileType.EPUB).metadata(BookMetadata.builder().build()).build(); + when(readingProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(2L, new UserBookProgressEntity())); + Book mappedBook = Book.builder().id(2L).primaryFile(BookFile.builder().bookType(BookFileType.EPUB).build()).metadata(BookMetadata.builder().build()).build(); when(bookMapper.toBook(entity)).thenReturn(mappedBook); when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); @@ -143,7 +143,7 @@ class BookServiceTest { entity.setLibrary(library); when(bookRepository.findByIdWithBookFiles(3L)).thenReturn(Optional.of(entity)); when(userBookProgressRepository.findByUserIdAndBookId(anyLong(), eq(3L))).thenReturn(Optional.of(new UserBookProgressEntity())); - Book mappedBook = Book.builder().id(3L).bookType(BookFileType.PDF).metadata(BookMetadata.builder().build()).shelves(Set.of()).build(); + Book mappedBook = Book.builder().id(3L).primaryFile(BookFile.builder().bookType(BookFileType.PDF).build()).metadata(BookMetadata.builder().build()).shelves(Set.of()).build(); when(bookMapper.toBook(entity)).thenReturn(mappedBook); when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); @@ -167,6 +167,7 @@ class BookServiceTest { BookEntity entity = new BookEntity(); entity.setId(4L); BookFileEntity primaryFile = new BookFileEntity(); + primaryFile.setId(1L); primaryFile.setBook(entity); primaryFile.setBookType(BookFileType.EPUB); entity.setBookFiles(List.of(primaryFile)); @@ -186,7 +187,7 @@ class BookServiceTest { when(ebookViewerPreferenceRepository.findByBookIdAndUserId(4L, testUser.getId())).thenReturn(Optional.of(epubPref)); when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); - BookViewerSettings settings = bookService.getBookViewerSetting(4L); + BookViewerSettings settings = bookService.getBookViewerSetting(4L, 1L); assertNotNull(settings.getEbookSettings()); assertEquals("Arial", settings.getEbookSettings().getFontFamily()); @@ -207,12 +208,13 @@ class BookServiceTest { BookEntity entity = new BookEntity(); entity.setId(5L); BookFileEntity primaryFile = new BookFileEntity(); + primaryFile.setId(1L); primaryFile.setBook(entity); primaryFile.setBookType(null); entity.setBookFiles(List.of(primaryFile)); when(bookRepository.findByIdWithBookFiles(5L)).thenReturn(Optional.of(entity)); when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); - assertThrows(APIException.class, () -> bookService.getBookViewerSetting(5L)); + assertThrows(APIException.class, () -> bookService.getBookViewerSetting(5L, 1L)); } @Test @@ -223,10 +225,10 @@ class BookServiceTest { } @Test - void updateReadProgress_delegatesToUpdateService() { + void updateReadProgress_delegatesToReadingProgressService() { ReadProgressRequest req = new ReadProgressRequest(); bookService.updateReadProgress(req); - verify(bookUpdateService).updateReadProgress(req); + verify(readingProgressService).updateReadProgress(req); } @Test diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookUpdateServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookUpdateServiceTest.java index d54acbc4b..30e44e6e8 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookUpdateServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookUpdateServiceTest.java @@ -4,18 +4,13 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.exception.APIException; import com.adityachandel.booklore.mapper.BookMapper; import com.adityachandel.booklore.model.dto.*; -import com.adityachandel.booklore.model.dto.progress.EpubProgress; -import com.adityachandel.booklore.model.dto.progress.PdfProgress; -import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse; import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse; import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.ReadStatus; -import com.adityachandel.booklore.model.enums.ResetProgressType; import com.adityachandel.booklore.repository.*; -import com.adityachandel.booklore.service.kobo.KoboReadingStateService; -import com.adityachandel.booklore.service.user.UserProgressService; +import com.adityachandel.booklore.service.progress.ReadingProgressService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; @@ -50,9 +45,7 @@ class BookUpdateServiceTest { @Mock private BookQueryService bookQueryService; @Mock - private UserProgressService userProgressService; - @Mock - private KoboReadingStateService koboReadingStateService; + private ReadingProgressService readingProgressService; @Mock private EbookViewerPreferenceRepository ebookViewerPreferenceRepository; @@ -73,8 +66,7 @@ class BookUpdateServiceTest { userBookProgressRepository, authenticationService, bookQueryService, - userProgressService, - koboReadingStateService, + readingProgressService, ebookViewerPreferenceRepository ); } @@ -175,70 +167,6 @@ class BookUpdateServiceTest { assertThrows(APIException.class, () -> bookUpdateService.updateBookViewerSetting(bookId, settings)); } - @Test - void updateReadProgress_epub_shouldUpdateProgress() { - long bookId = 1L; - BookEntity book = new BookEntity(); - book.setId(bookId); - BookFileEntity primaryFile = new BookFileEntity(); - primaryFile.setBook(book); - primaryFile.setBookType(BookFileType.EPUB); - book.setBookFiles(List.of(primaryFile)); - BookLoreUser user = mock(BookLoreUser.class); - when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book)); - when(authenticationService.getAuthenticatedUser()).thenReturn(user); - when(user.getId()).thenReturn(2L); - - UserBookProgressEntity progress = new UserBookProgressEntity(); - when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress)); - BookLoreUserEntity userEntity = new BookLoreUserEntity(); - when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity)); - - ReadProgressRequest req = new ReadProgressRequest(); - req.setBookId(bookId); - EpubProgress epubProgress = EpubProgress.builder().cfi("cfi").percentage(100f).build(); - req.setEpubProgress(epubProgress); - - bookUpdateService.updateReadProgress(req); - - verify(userBookProgressRepository).save(progress); - assertEquals("cfi", progress.getEpubProgress()); - assertEquals(ReadStatus.READ, progress.getReadStatus()); - assertEquals(100f, progress.getEpubProgressPercent()); - } - - @Test - void updateReadProgress_pdf_shouldUpdateProgress() { - long bookId = 1L; - BookEntity book = new BookEntity(); - book.setId(bookId); - BookFileEntity primaryFile = new BookFileEntity(); - primaryFile.setBook(book); - primaryFile.setBookType(BookFileType.PDF); - book.setBookFiles(List.of(primaryFile)); - BookLoreUser user = mock(BookLoreUser.class); - when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book)); - when(authenticationService.getAuthenticatedUser()).thenReturn(user); - when(user.getId()).thenReturn(2L); - - UserBookProgressEntity progress = new UserBookProgressEntity(); - when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress)); - BookLoreUserEntity userEntity = new BookLoreUserEntity(); - when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity)); - - ReadProgressRequest req = new ReadProgressRequest(); - req.setBookId(bookId); - PdfProgress pdfProgress = PdfProgress.builder().page(5).percentage(50f).build(); - req.setPdfProgress(pdfProgress); - - bookUpdateService.updateReadProgress(req); - - verify(userBookProgressRepository).save(progress); - assertEquals(5, progress.getPdfProgress()); - assertEquals(ReadStatus.READING, progress.getReadStatus()); - assertEquals(50f, progress.getPdfProgressPercent()); - } - @Test void updateReadStatus_shouldUpdateExistingAndCreateNew() { BookLoreUser user = mock(BookLoreUser.class); @@ -280,60 +208,6 @@ class BookUpdateServiceTest { assertThrows(APIException.class, () -> bookUpdateService.updateReadStatus(bookIds, "READ")); } - @Test - void resetProgress_shouldCallBulkReset() { - BookLoreUser user = mock(BookLoreUser.class); - when(authenticationService.getAuthenticatedUser()).thenReturn(user); - when(user.getId()).thenReturn(1L); - - BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class); - when(user.getPermissions()).thenReturn(permissions); - when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(true); - - List bookIds = Arrays.asList(1L, 2L); - when(bookRepository.countByIdIn(bookIds)).thenReturn(2L); - Set existing = new HashSet<>(bookIds); - when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing); - - List result = bookUpdateService.resetProgress(bookIds, ResetProgressType.BOOKLORE); - verify(userBookProgressRepository).bulkResetBookloreProgress(eq(1L), eq(new ArrayList<>(bookIds)), any()); - assertEquals(2, result.size()); - } - - @Test - void resetProgress_shouldThrowIfNoBulkPermission() { - BookLoreUser user = mock(BookLoreUser.class); - when(authenticationService.getAuthenticatedUser()).thenReturn(user); - when(user.getId()).thenReturn(1L); - - BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class); - when(user.getPermissions()).thenReturn(permissions); - when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(false); - - List bookIds = Arrays.asList(1L, 2L); - when(bookRepository.countByIdIn(bookIds)).thenReturn(2L); - - assertThrows(APIException.class, () -> bookUpdateService.resetProgress(bookIds, ResetProgressType.BOOKLORE)); - } - - @Test - void resetProgress_shouldAllowSingleBookWithoutPermission() { - BookLoreUser user = mock(BookLoreUser.class); - when(authenticationService.getAuthenticatedUser()).thenReturn(user); - when(user.getId()).thenReturn(1L); - - BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class); - when(user.getPermissions()).thenReturn(permissions); - when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(false); - - List bookIds = Collections.singletonList(1L); - when(bookRepository.countByIdIn(bookIds)).thenReturn(1L); - Set existing = new HashSet<>(bookIds); - when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing); - - assertDoesNotThrow(() -> bookUpdateService.resetProgress(bookIds, ResetProgressType.BOOKLORE)); - } - @Test void updateReadStatus_shouldAllowSingleBookWithoutPermission() { BookLoreUser user = mock(BookLoreUser.class); @@ -442,7 +316,8 @@ class BookUpdateServiceTest { Book mockBook = mock(Book.class); when(bookMapper.toBook(any())).thenReturn(mockBook); - when(userProgressService.fetchUserProgress(eq(1L), anySet())).thenReturn(Collections.emptyMap()); + when(readingProgressService.fetchUserProgress(eq(1L), anySet())).thenReturn(Collections.emptyMap()); + when(readingProgressService.fetchUserFileProgress(eq(1L), anySet())).thenReturn(Collections.emptyMap()); List result = bookUpdateService.assignShelvesToBooks(bookIds, assignIds, unassignIds); verify(bookRepository).saveAll(anyList()); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceOrderingTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceOrderingTest.java index b9a0b0d37..4337e7ccd 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceOrderingTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceOrderingTest.java @@ -1,12 +1,15 @@ package com.adityachandel.booklore.service.file; +import com.adityachandel.booklore.config.AppProperties; import com.adityachandel.booklore.mapper.BookMapper; import com.adityachandel.booklore.mapper.LibraryMapper; import com.adityachandel.booklore.model.dto.FileMoveResult; import com.adityachandel.booklore.model.dto.Library; import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.BookAdditionalFileRepository; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.LibraryRepository; @@ -14,191 +17,295 @@ import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.Set; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anySet; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) class FileMoveServiceOrderingTest { - @Mock - private BookRepository bookRepository; - @Mock - private BookAdditionalFileRepository bookFileRepository; - @Mock - private LibraryRepository libraryRepository; - @Mock - private FileMoveHelper fileMoveHelper; - @Mock - private MonitoringRegistrationService monitoringRegistrationService; - @Mock - private LibraryMapper libraryMapper; - @Mock - private BookMapper bookMapper; - @Mock - private NotificationService notificationService; - @Mock - private EntityManager entityManager; + @Mock private AppProperties appProperties; + @Mock private BookRepository bookRepository; + @Mock private BookAdditionalFileRepository bookFileRepository; + @Mock private LibraryRepository libraryRepository; + @Mock private FileMoveHelper fileMoveHelper; + @Mock private MonitoringRegistrationService monitoringRegistrationService; + @Mock private LibraryMapper libraryMapper; + @Mock private BookMapper bookMapper; + @Mock private NotificationService notificationService; + @Mock private EntityManager entityManager; - private TestableFileMoveService fileMoveService; + private FileMoveService service; + private LibraryEntity library; + private LibraryPathEntity libraryPath; - private BookEntity bookEntity; - private Path expectedFilePath; - - // Subclass to mock sleep static class TestableFileMoveService extends FileMoveService { - public TestableFileMoveService(BookRepository bookRepository, BookAdditionalFileRepository bookFileRepository, LibraryRepository libraryRepository, FileMoveHelper fileMoveHelper, MonitoringRegistrationService monitoringRegistrationService, LibraryMapper libraryMapper, BookMapper bookMapper, NotificationService notificationService, EntityManager entityManager) { - super(bookRepository, bookFileRepository, libraryRepository, fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager); + TestableFileMoveService(AppProperties appProperties, BookRepository bookRepository, BookAdditionalFileRepository bookFileRepository, + LibraryRepository libraryRepository, FileMoveHelper fileMoveHelper, + MonitoringRegistrationService monitoringRegistrationService, LibraryMapper libraryMapper, + BookMapper bookMapper, NotificationService notificationService, EntityManager entityManager) { + super(appProperties, bookRepository, bookFileRepository, libraryRepository, fileMoveHelper, + monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager); } @Override protected void sleep(long millis) { - // No-op for test, but can be verified by spy + // No-op } } @BeforeEach - void setUp() throws Exception { - fileMoveService = spy(new TestableFileMoveService( - bookRepository, bookFileRepository, libraryRepository, fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager)); + void setUp() { + when(appProperties.getDiskType()).thenReturn("LOCAL"); + service = spy(new TestableFileMoveService(appProperties, bookRepository, bookFileRepository, libraryRepository, + fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager)); - LibraryEntity library = new LibraryEntity(); - library.setId(42L); + library = new LibraryEntity(); + library.setId(1L); - LibraryPathEntity libraryPath = new LibraryPathEntity(); - libraryPath.setId(77L); - libraryPath.setPath("/library/root"); + libraryPath = new LibraryPathEntity(); + libraryPath.setId(10L); + libraryPath.setPath("/library"); libraryPath.setLibrary(library); + library.setLibraryPaths(List.of(libraryPath)); + } - bookEntity = new BookEntity(); - bookEntity.setId(999L); - bookEntity.setLibrary(library); - bookEntity.setLibraryPath(libraryPath); - var primaryFile = new com.adityachandel.booklore.model.entity.BookFileEntity(); - primaryFile.setBook(bookEntity); - primaryFile.setFileSubPath("SciFi"); - primaryFile.setFileName("Original.epub"); - bookEntity.setBookFiles(java.util.List.of(primaryFile)); + private BookEntity createBook() { + BookEntity book = new BookEntity(); + book.setId(100L); + book.setLibrary(library); + book.setLibraryPath(libraryPath); - expectedFilePath = Paths.get(libraryPath.getPath(), primaryFile.getFileSubPath(), "Renamed.epub"); + BookFileEntity file = new BookFileEntity(); + file.setId(1L); + file.setBook(book); + file.setFileName("Book.epub"); + file.setFileSubPath("path"); + file.setBookFormat(true); + file.setBookType(BookFileType.EPUB); - when(fileMoveHelper.getFileNamingPattern(library)).thenReturn("{title}"); - when(fileMoveHelper.generateNewFilePath(bookEntity, libraryPath, "{title}")).thenReturn(expectedFilePath); - when(fileMoveHelper.extractSubPath(expectedFilePath, libraryPath)).thenReturn(primaryFile.getFileSubPath()); - doNothing().when(fileMoveHelper).moveFile(any(Path.class), any(Path.class)); - doNothing().when(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(Path.class), anySet()); + book.setBookFiles(new ArrayList<>(List.of(file))); + return book; + } + + private void mockStandardBehavior(BookEntity book, Path targetPath) throws IOException { + when(fileMoveHelper.getFileNamingPattern(any())).thenReturn("{title}"); + when(fileMoveHelper.generateNewFilePath(eq(book), any(LibraryPathEntity.class), anyString())).thenReturn(targetPath); + when(fileMoveHelper.generateNewFilePath(eq(book), any(BookFileEntity.class), any(LibraryPathEntity.class), anyString())) + .thenReturn(targetPath); + when(fileMoveHelper.extractSubPath(any(), any())).thenReturn("new/path"); + when(fileMoveHelper.validateSourceExists(any(), anyBoolean())).thenReturn(true); + when(fileMoveHelper.moveFileWithBackup(any())).thenAnswer(inv -> ((Path) inv.getArgument(0)).resolveSibling("temp")); + doNothing().when(fileMoveHelper).commitMove(any(), any()); + doNothing().when(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(), anySet()); } @Test - void moveSingleFile_guaranteesCorrectOrderOfOperations_WhenMonitored() throws Exception { - // Arrange - when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(true); - when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/library/root"))); - - Library libraryDto = Library.builder().watch(true).build(); - when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto); + @DisplayName("moveSingleFile: commits files before updating database") + void commitsBeforeDatabaseUpdate() throws IOException { + BookEntity book = createBook(); + Path target = Paths.get("/library/new/path/NewName.epub"); - // Act - FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); + mockStandardBehavior(book, target); + when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet()); - // Assert - assertTrue(result.isMoved()); + FileMoveResult result = service.moveSingleFile(book); - InOrder inOrder = inOrder(monitoringRegistrationService, fileMoveHelper, fileMoveService); + assertThat(result.isMoved()).isTrue(); - // 1. Unregister library - inOrder.verify(fileMoveHelper).unregisterLibrary(42L); + InOrder inOrder = inOrder(fileMoveHelper, bookFileRepository); + inOrder.verify(fileMoveHelper).moveFileWithBackup(any()); + inOrder.verify(fileMoveHelper).commitMove(any(), any()); + inOrder.verify(bookFileRepository).updateFileNameAndSubPath(anyLong(), anyString(), anyString()); + } - // 2. Wait for initial events to drain (before move) + @Test + @DisplayName("moveSingleFile: validates sources before staging") + void validatesBeforeStaging() throws IOException { + BookEntity book = createBook(); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet()); + + service.moveSingleFile(book); + + InOrder inOrder = inOrder(fileMoveHelper); + inOrder.verify(fileMoveHelper).validateSourceExists(any(), anyBoolean()); + inOrder.verify(fileMoveHelper).moveFileWithBackup(any()); + } + + @Test + @DisplayName("moveSingleFile: when monitored - unregisters before move, registers after") + void monitoredOrderUnregisterMoveRegister() throws IOException { + BookEntity book = createBook(); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library"))); + Library dto = Library.builder().build(); + when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isTrue(); + + InOrder inOrder = inOrder(fileMoveHelper, monitoringRegistrationService, service); + inOrder.verify(fileMoveHelper).unregisterLibrary(1L); inOrder.verify(monitoringRegistrationService).waitForEventsDrainedByPaths(anySet(), anyLong()); - - // 3. Perform the move - inOrder.verify(fileMoveHelper).moveFile(any(Path.class), any(Path.class)); - - // 4. Perform cleanup - inOrder.verify(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(Path.class), anySet()); - - // 5. CRITICAL: Sleep/Wait for events generated by move/cleanup to drain *before* re-registering - inOrder.verify(fileMoveService).sleep(anyLong()); - - // 6. Register library *last* - inOrder.verify(monitoringRegistrationService).registerLibrary(libraryDto); - } - - @Test - void moveSingleFile_guaranteesCorrectOrderOfOperations_WhenStatusNotMonitoredButHasPaths() throws Exception { - // Arrange: status says FALSE, but getPaths returns paths. Should still unregister. - when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(false); - when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/library/root"))); - - Library libraryDto = Library.builder().watch(true).build(); - when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto); - - // Act - FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); - - // Assert - assertTrue(result.isMoved()); - - InOrder inOrder = inOrder(monitoringRegistrationService, fileMoveHelper, fileMoveService); - - // 1. Unregister library - inOrder.verify(fileMoveHelper).unregisterLibrary(42L); - - // 2. Wait for initial events to drain - inOrder.verify(monitoringRegistrationService).waitForEventsDrainedByPaths(anySet(), anyLong()); - - // 3. Move - inOrder.verify(fileMoveHelper).moveFile(any(Path.class), any(Path.class)); - - // 4. Sleep - inOrder.verify(fileMoveService).sleep(anyLong()); - - // 5. Register - inOrder.verify(monitoringRegistrationService).registerLibrary(libraryDto); + inOrder.verify(fileMoveHelper).moveFileWithBackup(any()); + inOrder.verify(fileMoveHelper).commitMove(any(), any()); + inOrder.verify(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(), anySet()); + inOrder.verify(service).sleep(anyLong()); + inOrder.verify(monitoringRegistrationService).registerLibrary(dto); } @Test - void moveSingleFile_skipsMonitoringOps_WhenNotMonitoredAndNoPaths() throws Exception { - // Arrange - when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(false); - when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Collections.emptySet()); + @DisplayName("moveSingleFile: when not monitored - no monitoring calls") + void notMonitoredSkipsMonitoringCalls() throws IOException { + BookEntity book = createBook(); + Path target = Paths.get("/library/new/path/NewName.epub"); - // Act - FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); + mockStandardBehavior(book, target); + when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet()); - // Assert - assertTrue(result.isMoved()); + FileMoveResult result = service.moveSingleFile(book); - // Verify NO unregister/register happens + assertThat(result.isMoved()).isTrue(); verify(fileMoveHelper, never()).unregisterLibrary(anyLong()); - verify(monitoringRegistrationService, never()).waitForEventsDrainedByPaths(anySet(), anyLong()); - - // Move happens - verify(fileMoveHelper).moveFile(any(Path.class), any(Path.class)); - - // NO sleep - verify(fileMoveService, never()).sleep(anyLong()); - - // NO register verify(monitoringRegistrationService, never()).registerLibrary(any()); + verify(service, never()).sleep(anyLong()); } -} \ No newline at end of file + + @Test + @DisplayName("moveSingleFile: cleans up directories after database update") + void cleansUpAfterDatabaseUpdate() throws IOException { + BookEntity book = createBook(); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet()); + + service.moveSingleFile(book); + + InOrder inOrder = inOrder(bookFileRepository, fileMoveHelper); + inOrder.verify(bookFileRepository).updateFileNameAndSubPath(anyLong(), anyString(), anyString()); + inOrder.verify(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(), anySet()); + } + + @Test + @DisplayName("moveSingleFile: all files staged before any commits") + void allFilesStagedBeforeCommits() throws IOException { + BookEntity book = new BookEntity(); + book.setId(100L); + book.setLibrary(library); + book.setLibraryPath(libraryPath); + + BookFileEntity file1 = new BookFileEntity(); + file1.setId(1L); + file1.setBook(book); + file1.setFileName("Book.epub"); + file1.setFileSubPath("path"); + file1.setBookFormat(true); + + BookFileEntity file2 = new BookFileEntity(); + file2.setId(2L); + file2.setBook(book); + file2.setFileName("Book.pdf"); + file2.setFileSubPath("path"); + file2.setBookFormat(true); + file2.setBookType(BookFileType.PDF); + + book.setBookFiles(new ArrayList<>(List.of(file1, file2))); + + Path target = Paths.get("/library/new/path/NewName.epub"); + mockStandardBehavior(book, target); + when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet()); + + service.moveSingleFile(book); + + InOrder inOrder = inOrder(fileMoveHelper); + // Both files staged first + inOrder.verify(fileMoveHelper, times(2)).moveFileWithBackup(any()); + // Then both committed + inOrder.verify(fileMoveHelper, times(2)).commitMove(any(), any()); + } + + @Test + @DisplayName("moveSingleFile: rollback happens on commit failure") + void rollbackOnCommitFailure() throws IOException { + BookEntity book = createBook(); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any()); + when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet()); + + service.moveSingleFile(book); + + InOrder inOrder = inOrder(fileMoveHelper); + inOrder.verify(fileMoveHelper).moveFileWithBackup(any()); + inOrder.verify(fileMoveHelper).commitMove(any(), any()); + inOrder.verify(fileMoveHelper).rollbackMove(any(), any()); + } + + @Test + @DisplayName("moveSingleFile: database not updated when commit fails") + void noDatabaseUpdateOnCommitFailure() throws IOException { + BookEntity book = createBook(); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any()); + when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet()); + + service.moveSingleFile(book); + + verify(bookFileRepository, never()).updateFileNameAndSubPath(anyLong(), anyString(), anyString()); + } + + @Test + @DisplayName("moveSingleFile: library re-registered even on failure") + void libraryReRegisteredOnFailure() throws IOException { + BookEntity book = createBook(); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any()); + when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library"))); + Library dto = Library.builder().build(); + when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto); + + service.moveSingleFile(book); + + verify(fileMoveHelper).unregisterLibrary(1L); + verify(monitoringRegistrationService).registerLibrary(dto); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceTest.java index 8f58e183e..a55bde944 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceTest.java @@ -1,10 +1,11 @@ package com.adityachandel.booklore.service.file; +import com.adityachandel.booklore.config.AppProperties; import com.adityachandel.booklore.mapper.BookMapper; import com.adityachandel.booklore.mapper.LibraryMapper; import com.adityachandel.booklore.model.dto.FileMoveResult; -import com.adityachandel.booklore.model.dto.request.FileMoveRequest; import com.adityachandel.booklore.model.dto.Library; +import com.adityachandel.booklore.model.dto.request.FileMoveRequest; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookFileEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; @@ -18,6 +19,8 @@ import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; @@ -25,256 +28,1078 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; +import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; -import java.util.HashSet; -import java.util.Collections; -import java.util.Set; import java.util.List; import java.util.Optional; import java.util.Set; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anySet; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) class FileMoveServiceTest { - @Mock - private BookRepository bookRepository; - @Mock - private BookAdditionalFileRepository bookFileRepository; - @Mock - private LibraryRepository libraryRepository; - @Mock - private FileMoveHelper fileMoveHelper; - @Mock - private MonitoringRegistrationService monitoringRegistrationService; - @Mock - private LibraryMapper libraryMapper; - @Mock - private BookMapper bookMapper; - @Mock - private NotificationService notificationService; - @Mock - private EntityManager entityManager; + @Mock private AppProperties appProperties; + @Mock private BookRepository bookRepository; + @Mock private BookAdditionalFileRepository bookFileRepository; + @Mock private LibraryRepository libraryRepository; + @Mock private FileMoveHelper fileMoveHelper; + @Mock private MonitoringRegistrationService monitoringRegistrationService; + @Mock private LibraryMapper libraryMapper; + @Mock private BookMapper bookMapper; + @Mock private NotificationService notificationService; + @Mock private EntityManager entityManager; - private FileMoveService fileMoveService; + private FileMoveService service; + private LibraryEntity library; + private LibraryPathEntity libraryPath; - private BookEntity bookEntity; - private Path expectedFilePath; - - // Subclass to mock sleep for tests static class TestableFileMoveService extends FileMoveService { - public TestableFileMoveService(BookRepository bookRepository, BookAdditionalFileRepository bookFileRepository, LibraryRepository libraryRepository, FileMoveHelper fileMoveHelper, MonitoringRegistrationService monitoringRegistrationService, LibraryMapper libraryMapper, BookMapper bookMapper, NotificationService notificationService, EntityManager entityManager) { - super(bookRepository, bookFileRepository, libraryRepository, fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager); + TestableFileMoveService(AppProperties appProperties, BookRepository bookRepository, BookAdditionalFileRepository bookFileRepository, + LibraryRepository libraryRepository, FileMoveHelper fileMoveHelper, + MonitoringRegistrationService monitoringRegistrationService, LibraryMapper libraryMapper, + BookMapper bookMapper, NotificationService notificationService, EntityManager entityManager) { + super(appProperties, bookRepository, bookFileRepository, libraryRepository, fileMoveHelper, + monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager); } @Override protected void sleep(long millis) { - // No-op for test + // No-op } } @BeforeEach - void setUp() throws Exception { - // Use spy/subclass to avoid actual sleep - fileMoveService = spy(new TestableFileMoveService( - bookRepository, bookFileRepository, libraryRepository, fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager)); + void setUp() { + when(appProperties.getDiskType()).thenReturn("LOCAL"); + service = spy(new TestableFileMoveService(appProperties, bookRepository, bookFileRepository, libraryRepository, + fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager)); - LibraryEntity library = new LibraryEntity(); - library.setId(42L); + library = new LibraryEntity(); + library.setId(1L); - LibraryPathEntity libraryPath = new LibraryPathEntity(); - libraryPath.setId(77L); - libraryPath.setPath("/library/root"); + libraryPath = new LibraryPathEntity(); + libraryPath.setId(10L); + libraryPath.setPath("/library"); libraryPath.setLibrary(library); - - bookEntity = new BookEntity(); - bookEntity.setId(999L); - bookEntity.setLibrary(library); - bookEntity.setLibraryPath(libraryPath); - - BookFileEntity primaryFile = new BookFileEntity(); - primaryFile.setBook(bookEntity); - primaryFile.setBookType(BookFileType.EPUB); - primaryFile.setBookFormat(true); - primaryFile.setFileSubPath("SciFi"); - primaryFile.setFileName("Original.epub"); - bookEntity.setBookFiles(new ArrayList<>(List.of(primaryFile))); - - expectedFilePath = Paths.get(libraryPath.getPath(), bookEntity.getPrimaryBookFile().getFileSubPath(), "Renamed.epub"); - - when(fileMoveHelper.getFileNamingPattern(library)).thenReturn("{title}"); - when(fileMoveHelper.generateNewFilePath(bookEntity, libraryPath, "{title}")).thenReturn(expectedFilePath); - when(fileMoveHelper.extractSubPath(expectedFilePath, libraryPath)).thenReturn(bookEntity.getPrimaryBookFile().getFileSubPath()); - doNothing().when(fileMoveHelper).moveFile(any(Path.class), any(Path.class)); - doNothing().when(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(Path.class), anySet()); + library.setLibraryPaths(List.of(libraryPath)); } - @Test - void moveSingleFile_whenLibraryMonitored_reRegistersLibraryPaths() throws Exception { - when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(true); - when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/library/root"))); - Library libraryDto = Library.builder().watch(true).build(); - when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto); - - FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); - - assertTrue(result.isMoved()); - - verify(fileMoveHelper).unregisterLibrary(42L); - verify(monitoringRegistrationService).registerLibrary(libraryDto); - assertTrue(libraryDto.isWatch()); - verify(fileMoveHelper, never()).registerLibraryPaths(anyLong(), any(Path.class)); + private BookEntity createBook(List files) { + BookEntity book = new BookEntity(); + book.setId(100L); + book.setLibrary(library); + book.setLibraryPath(libraryPath); + files.forEach(f -> f.setBook(book)); + book.setBookFiles(new ArrayList<>(files)); + return book; } - @Test - void moveSingleFile_ensuresLibraryWatchStatusIsRestored() throws Exception { - when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(true); - when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/library/root"))); - - Library libraryDto = Library.builder().watch(false).build(); - when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto); - - fileMoveService.moveSingleFile(bookEntity); - - verify(monitoringRegistrationService).registerLibrary(libraryDto); - assertTrue(libraryDto.isWatch(), "Library watch status must be set to true before re-registering"); + private BookFileEntity createBookFile(Long id, String name, String subPath, boolean isBook, boolean folderBased) { + BookFileEntity file = new BookFileEntity(); + file.setId(id); + file.setFileName(name); + file.setFileSubPath(subPath); + file.setBookFormat(isBook); + file.setFolderBased(folderBased); + if (isBook && name.contains(".")) { + file.setBookType(name.endsWith(".pdf") ? BookFileType.PDF : BookFileType.EPUB); + } + return file; } - @Test - void moveSingleFile_whenLibraryNotMonitored_skipsMonitoringCalls() throws Exception { - when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(false); - when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Collections.emptySet()); - - FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); - - assertTrue(result.isMoved()); - - verify(fileMoveHelper, never()).unregisterLibrary(anyLong()); - verify(fileMoveHelper, never()).registerLibraryPaths(anyLong(), any(Path.class)); + private void mockStandardBehavior(BookEntity book, Path targetPath) throws IOException { + when(fileMoveHelper.getFileNamingPattern(any())).thenReturn("{title}"); + when(fileMoveHelper.generateNewFilePath(eq(book), any(LibraryPathEntity.class), anyString())).thenReturn(targetPath); + when(fileMoveHelper.generateNewFilePath(eq(book), any(BookFileEntity.class), any(LibraryPathEntity.class), anyString())) + .thenAnswer(inv -> { + BookFileEntity bf = inv.getArgument(1); + String ext = bf.getFileName().contains(".") ? bf.getFileName().substring(bf.getFileName().lastIndexOf('.')) : ""; + return targetPath.getParent().resolve("NewName" + ext); + }); + when(fileMoveHelper.extractSubPath(any(), any())).thenReturn("new/subpath"); + when(fileMoveHelper.validateSourceExists(any(), anyBoolean())).thenReturn(true); + when(fileMoveHelper.moveFileWithBackup(any())).thenAnswer(inv -> ((Path) inv.getArgument(0)).resolveSibling("temp")); + doNothing().when(fileMoveHelper).commitMove(any(), any()); + doNothing().when(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(), anySet()); } - @Test - void bulkMoveFiles_movesAllBookFilesForBook() throws Exception { - LibraryEntity targetLibrary = new LibraryEntity(); - targetLibrary.setId(43L); - - LibraryPathEntity targetLibraryPath = new LibraryPathEntity(); - targetLibraryPath.setId(88L); - targetLibraryPath.setPath("/target/root"); - targetLibraryPath.setLibrary(targetLibrary); - targetLibrary.setLibraryPaths(List.of(targetLibraryPath)); - - BookFileEntity primary = bookEntity.getPrimaryBookFile(); - primary.setId(1L); - - BookFileEntity pdfAlt = new BookFileEntity(); - pdfAlt.setId(2L); - pdfAlt.setBook(bookEntity); - pdfAlt.setBookType(BookFileType.PDF); - pdfAlt.setBookFormat(true); - pdfAlt.setFileSubPath("SciFi"); - pdfAlt.setFileName("Original.pdf"); - - BookFileEntity cover = new BookFileEntity(); - cover.setId(3L); - cover.setBook(bookEntity); - cover.setBookFormat(false); - cover.setFileSubPath("SciFi"); - cover.setFileName("cover.png"); - - bookEntity.setBookFiles(new ArrayList<>(List.of(primary, pdfAlt, cover))); - pdfAlt.setBook(bookEntity); - cover.setBook(bookEntity); - - Path sourcePrimary = Paths.get("/library/root", "SciFi", "Original.epub"); - Path sourcePdfAlt = Paths.get("/library/root", "SciFi", "Original.pdf"); - Path sourceCover = Paths.get("/library/root", "SciFi", "cover.png"); - - Path targetPrimary = Paths.get("/target/root", "SciFi", "Renamed.epub"); - Path targetPdfAlt = Paths.get("/target/root", "SciFi", "Renamed.pdf"); - Path targetCover = Paths.get("/target/root", "SciFi", "cover.png"); - - when(fileMoveHelper.getFileNamingPattern(targetLibrary)).thenReturn("{title}"); - when(fileMoveHelper.generateNewFilePath(bookEntity, targetLibraryPath, "{title}")).thenReturn(targetPrimary); - when(fileMoveHelper.generateNewFilePath(bookEntity, primary, targetLibraryPath, "{title}")).thenReturn(targetPrimary); - when(fileMoveHelper.generateNewFilePath(bookEntity, pdfAlt, targetLibraryPath, "{title}")).thenReturn(targetPdfAlt); - when(fileMoveHelper.extractSubPath(targetPrimary, targetLibraryPath)).thenReturn("SciFi"); - - when(bookRepository.findByIdWithBookFiles(bookEntity.getId())).thenReturn(Optional.of(bookEntity)); - - when(fileMoveHelper.moveFileWithBackup(sourcePrimary)).thenReturn(sourcePrimary.resolveSibling("Original.epub.tmp_move")); - when(fileMoveHelper.moveFileWithBackup(sourcePdfAlt)).thenReturn(sourcePdfAlt.resolveSibling("Original.pdf.tmp_move")); - when(fileMoveHelper.moveFileWithBackup(sourceCover)).thenReturn(sourceCover.resolveSibling("cover.png.tmp_move")); - - doNothing().when(fileMoveHelper).commitMove(any(Path.class), any(Path.class)); - doNothing().when(entityManager).clear(); - when(bookMapper.toBookWithDescription(any(BookEntity.class), eq(false))).thenReturn(null); - - Set affected = new HashSet<>(); - affected.add(42L); - affected.add(43L); - - when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library/root"), Paths.get("/target/root"))); - doNothing().when(monitoringRegistrationService).unregisterLibraries(anySet()); - when(monitoringRegistrationService.waitForEventsDrainedByPaths(anySet(), anyLong())).thenReturn(true); - - when(bookRepository.findById(anyLong())).thenReturn(Optional.of(bookEntity)); - when(libraryRepository.findById(anyLong())).thenReturn(Optional.of(targetLibrary)); - when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(null); - doNothing().when(monitoringRegistrationService).registerLibrary(any()); - - FileMoveRequest.Move m = new FileMoveRequest.Move(); - m.setBookId(bookEntity.getId()); - m.setTargetLibraryId(targetLibrary.getId()); - m.setTargetLibraryPathId(targetLibraryPath.getId()); - FileMoveRequest req = new FileMoveRequest(); - req.setMoves(List.of(m)); - - fileMoveService.bulkMoveFiles(req); - - verify(fileMoveHelper).moveFileWithBackup(sourcePrimary); - verify(fileMoveHelper).moveFileWithBackup(sourcePdfAlt); - verify(fileMoveHelper).moveFileWithBackup(sourceCover); - - verify(fileMoveHelper).commitMove(any(Path.class), eq(targetPrimary)); - verify(fileMoveHelper).commitMove(any(Path.class), eq(targetPdfAlt)); - verify(fileMoveHelper).commitMove(any(Path.class), eq(targetCover)); - - verify(bookFileRepository).updateFileNameAndSubPath(eq(primary.getId()), any(String.class), any(String.class)); - verify(bookFileRepository).updateFileNameAndSubPath(eq(pdfAlt.getId()), any(String.class), any(String.class)); - verify(bookFileRepository).updateFileNameAndSubPath(eq(cover.getId()), any(String.class), any(String.class)); - verify(bookRepository).updateLibrary(eq(bookEntity.getId()), eq(targetLibrary.getId()), eq(targetLibraryPath)); - verify(entityManager).clear(); - - verify(notificationService).sendMessage(eq(Topic.BOOK_UPDATE), any()); + private void mockUnmonitoredLibrary() { + when(monitoringRegistrationService.isLibraryMonitored(anyLong())).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet()); } - @Test - void moveSingleFile_whenLibraryNotMonitoredStatusButHasPaths_triggersUnregister() throws Exception { - when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(false); - when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/some/path"))); - Library libraryDto = Library.builder().watch(true).build(); - when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto); - - FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); - - assertTrue(result.isMoved()); - - verify(fileMoveHelper).unregisterLibrary(42L); - verify(monitoringRegistrationService).registerLibrary(libraryDto); + private void mockMonitoredLibrary() { + when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library"))); + when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build()); } -} \ No newline at end of file + + @Nested + @DisplayName("moveSingleFile - Success Cases") + class MoveSingleFileSuccess { + + @Test + @DisplayName("moves single EPUB file and returns correct result") + void movesSingleEpubFile() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "old/path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isTrue(); + assertThat(result.getNewFileName()).isEqualTo("NewName.epub"); + assertThat(result.getNewFileSubPath()).isEqualTo("new/subpath"); + verify(fileMoveHelper).moveFileWithBackup(any()); + verify(fileMoveHelper).commitMove(any(), any()); + verify(bookFileRepository).updateFileNameAndSubPath(eq(1L), anyString(), eq("new/subpath")); + } + + @Test + @DisplayName("moves single PDF file") + void movesSinglePdfFile() throws IOException { + BookFileEntity pdf = createBookFile(1L, "Book.pdf", "path", true, false); + BookEntity book = createBook(List.of(pdf)); + Path target = Paths.get("/library/new/path/NewName.pdf"); + + mockStandardBehavior(book, target); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isTrue(); + } + + @Test + @DisplayName("moves multi-format book (EPUB + PDF) atomically") + void movesMultiFormatBook() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookFileEntity pdf = createBookFile(2L, "Book.pdf", "path", true, false); + BookEntity book = createBook(List.of(epub, pdf)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isTrue(); + verify(fileMoveHelper, times(2)).moveFileWithBackup(any()); + verify(fileMoveHelper, times(2)).commitMove(any(), any()); + verify(bookFileRepository, times(2)).updateFileNameAndSubPath(anyLong(), anyString(), anyString()); + } + + @Test + @DisplayName("moves book with cover image") + void movesBookWithCover() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookFileEntity cover = createBookFile(2L, "cover.jpg", "path", false, false); + BookEntity book = createBook(List.of(epub, cover)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isTrue(); + verify(fileMoveHelper, times(2)).moveFileWithBackup(any()); + verify(fileMoveHelper, times(2)).commitMove(any(), any()); + } + + @Test + @DisplayName("moves book with multiple additional files (cover, metadata, etc)") + void movesBookWithMultipleAdditionalFiles() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookFileEntity cover = createBookFile(2L, "cover.jpg", "path", false, false); + BookFileEntity metadata = createBookFile(3L, "metadata.opf", "path", false, false); + BookFileEntity thumbnail = createBookFile(4L, "thumb.png", "path", false, false); + BookEntity book = createBook(List.of(epub, cover, metadata, thumbnail)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isTrue(); + verify(fileMoveHelper, times(4)).moveFileWithBackup(any()); + verify(fileMoveHelper, times(4)).commitMove(any(), any()); + verify(bookFileRepository, times(4)).updateFileNameAndSubPath(anyLong(), anyString(), anyString()); + } + + @Test + @DisplayName("moves folder-based audiobook") + void movesFolderBasedAudiobook() throws IOException { + BookFileEntity folder = createBookFile(1L, "Dr. Who Season 1", "audiobooks", true, true); + BookEntity book = createBook(List.of(folder)); + Path target = Paths.get("/library/new/audiobooks/Dr. Who Season 1"); + + mockStandardBehavior(book, target); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isTrue(); + verify(fileMoveHelper).validateSourceExists(any(), eq(true)); + } + + @Test + @DisplayName("moves folder with dots in name (e.g., 'Dr. Who')") + void movesFolderWithDotsInName() throws IOException { + BookFileEntity folder = createBookFile(1L, "Dr. Strange Vol. 1", "audiobooks", true, true); + BookEntity book = createBook(List.of(folder)); + Path target = Paths.get("/library/new/audiobooks/Dr. Strange Vol. 1"); + + mockStandardBehavior(book, target); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isTrue(); + } + + @Test + @DisplayName("cleans up empty parent directories after move") + void cleansUpEmptyParentDirs() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "deep/nested/path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + mockUnmonitoredLibrary(); + + service.moveSingleFile(book); + + verify(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(), anySet()); + } + } + + @Nested + @DisplayName("moveSingleFile - No Move Required Cases") + class MoveSingleFileNoMoveRequired { + + @Test + @DisplayName("returns false when source and target paths are identical") + void returnsFalseWhenPathsIdentical() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + + when(fileMoveHelper.getFileNamingPattern(any())).thenReturn("{title}"); + when(fileMoveHelper.generateNewFilePath(eq(book), any(LibraryPathEntity.class), anyString())) + .thenReturn(book.getFullFilePath()); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isFalse(); + verify(fileMoveHelper, never()).moveFileWithBackup(any()); + verify(fileMoveHelper, never()).commitMove(any(), any()); + verify(bookFileRepository, never()).updateFileNameAndSubPath(anyLong(), anyString(), anyString()); + } + + @Test + @DisplayName("returns false when book has empty file list") + void returnsFalseWhenEmptyFileList() { + BookEntity book = createBook(List.of()); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isFalse(); + } + + @Test + @DisplayName("returns false when book has null file list") + void returnsFalseWhenNullFileList() { + BookEntity book = new BookEntity(); + book.setId(100L); + book.setLibrary(library); + book.setLibraryPath(libraryPath); + book.setBookFiles(null); + + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.empty()); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isFalse(); + } + + @Test + @DisplayName("returns false when all individual file paths are already correct") + void returnsFalseWhenAllFilesAlreadyCorrect() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookFileEntity pdf = createBookFile(2L, "Book.pdf", "path", true, false); + BookEntity book = createBook(List.of(epub, pdf)); + + when(fileMoveHelper.getFileNamingPattern(any())).thenReturn("{title}"); + // Primary path differs so we enter the move logic + when(fileMoveHelper.generateNewFilePath(eq(book), any(LibraryPathEntity.class), anyString())) + .thenReturn(Paths.get("/library/new/path/NewName.epub")); + when(fileMoveHelper.extractSubPath(any(), any())).thenReturn("path"); + // But individual file paths are the same + when(fileMoveHelper.generateNewFilePath(eq(book), any(BookFileEntity.class), any(LibraryPathEntity.class), anyString())) + .thenAnswer(inv -> { + BookFileEntity bf = inv.getArgument(1); + return bf.getFullFilePath(); + }); + when(fileMoveHelper.validateSourceExists(any(), anyBoolean())).thenReturn(true); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isFalse(); + verify(fileMoveHelper, never()).moveFileWithBackup(any()); + } + } + + @Nested + @DisplayName("moveSingleFile - Validation Failure Cases") + class MoveSingleFileValidationFailure { + + @Test + @DisplayName("returns false when source file does not exist") + void returnsFalseWhenSourceFileNotFound() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + when(fileMoveHelper.getFileNamingPattern(any())).thenReturn("{title}"); + when(fileMoveHelper.generateNewFilePath(eq(book), any(LibraryPathEntity.class), anyString())).thenReturn(target); + when(fileMoveHelper.extractSubPath(any(), any())).thenReturn("new/path"); + when(fileMoveHelper.validateSourceExists(any(), eq(false))).thenReturn(false); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isFalse(); + verify(fileMoveHelper, never()).moveFileWithBackup(any()); + } + + @Test + @DisplayName("returns false when folder-based audiobook directory does not exist") + void returnsFalseWhenFolderNotFound() throws IOException { + BookFileEntity folder = createBookFile(1L, "Audiobook", "path", true, true); + BookEntity book = createBook(List.of(folder)); + Path target = Paths.get("/library/new/path/Audiobook"); + + when(fileMoveHelper.getFileNamingPattern(any())).thenReturn("{title}"); + when(fileMoveHelper.generateNewFilePath(eq(book), any(LibraryPathEntity.class), anyString())).thenReturn(target); + when(fileMoveHelper.extractSubPath(any(), any())).thenReturn("new/path"); + when(fileMoveHelper.validateSourceExists(any(), eq(true))).thenReturn(false); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isFalse(); + verify(fileMoveHelper, never()).moveFileWithBackup(any()); + } + + @Test + @DisplayName("aborts entire operation if any file in multi-file book is missing") + void abortsIfAnyFileInMultiFileBookMissing() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookFileEntity pdf = createBookFile(2L, "Book.pdf", "path", true, false); + BookFileEntity cover = createBookFile(3L, "cover.jpg", "path", false, false); + BookEntity book = createBook(List.of(epub, pdf, cover)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + when(fileMoveHelper.getFileNamingPattern(any())).thenReturn("{title}"); + when(fileMoveHelper.generateNewFilePath(eq(book), any(LibraryPathEntity.class), anyString())).thenReturn(target); + when(fileMoveHelper.extractSubPath(any(), any())).thenReturn("new/path"); + // First two files exist, third doesn't + when(fileMoveHelper.validateSourceExists(any(), eq(false))) + .thenReturn(true) + .thenReturn(true) + .thenReturn(false); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isFalse(); + verify(fileMoveHelper, never()).moveFileWithBackup(any()); + } + + @Test + @DisplayName("returns false when book not found in repository during lazy load") + void returnsFalseWhenBookNotFoundInRepository() { + BookEntity book = new BookEntity(); + book.setId(100L); + book.setLibrary(library); + book.setLibraryPath(libraryPath); + book.setBookFiles(null); + + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.empty()); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isFalse(); + verify(bookRepository).findByIdWithBookFiles(100L); + } + + @Test + @DisplayName("returns false when loaded book has no files") + void returnsFalseWhenLoadedBookHasNoFiles() { + BookEntity bookWithoutFiles = new BookEntity(); + bookWithoutFiles.setId(100L); + bookWithoutFiles.setLibrary(library); + bookWithoutFiles.setLibraryPath(libraryPath); + bookWithoutFiles.setBookFiles(null); + + BookEntity loadedBook = createBook(List.of()); + + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(loadedBook)); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(bookWithoutFiles); + + assertThat(result.isMoved()).isFalse(); + } + } + + @Nested + @DisplayName("moveSingleFile - Failure and Rollback Cases") + class MoveSingleFileFailureAndRollback { + + @Test + @DisplayName("rolls back when staging fails") + void rollsBackWhenStagingFails() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + when(fileMoveHelper.getFileNamingPattern(any())).thenReturn("{title}"); + when(fileMoveHelper.generateNewFilePath(eq(book), any(LibraryPathEntity.class), anyString())).thenReturn(target); + when(fileMoveHelper.generateNewFilePath(eq(book), any(BookFileEntity.class), any(LibraryPathEntity.class), anyString())).thenReturn(target); + when(fileMoveHelper.extractSubPath(any(), any())).thenReturn("new/path"); + when(fileMoveHelper.validateSourceExists(any(), anyBoolean())).thenReturn(true); + when(fileMoveHelper.moveFileWithBackup(any())).thenThrow(new IOException("Disk full")); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isFalse(); + verify(bookFileRepository, never()).updateFileNameAndSubPath(anyLong(), anyString(), anyString()); + } + + @Test + @DisplayName("rolls back staged file when commit fails") + void rollsBackWhenCommitFails() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + doThrow(new IOException("Permission denied")).when(fileMoveHelper).commitMove(any(), any()); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isFalse(); + verify(fileMoveHelper).rollbackMove(any(), any()); + verify(bookFileRepository, never()).updateFileNameAndSubPath(anyLong(), anyString(), anyString()); + } + + @Test + @DisplayName("rolls back all staged files when one commit fails in multi-file book") + void rollsBackAllStagedFilesWhenOneCommitFails() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookFileEntity pdf = createBookFile(2L, "Book.pdf", "path", true, false); + BookEntity book = createBook(List.of(epub, pdf)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + // First commit succeeds, second fails + doNothing().doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any()); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(book); + + assertThat(result.isMoved()).isFalse(); + // Should attempt to rollback the remaining uncommitted file + verify(fileMoveHelper, atLeastOnce()).rollbackMove(any(), any()); + } + + @Test + @DisplayName("database not updated when commit fails") + void databaseNotUpdatedWhenCommitFails() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any()); + mockUnmonitoredLibrary(); + + service.moveSingleFile(book); + + verify(bookFileRepository, never()).updateFileNameAndSubPath(anyLong(), anyString(), anyString()); + } + } + + @Nested + @DisplayName("moveSingleFile - Monitoring Cases") + class MoveSingleFileMonitoring { + + @Test + @DisplayName("unregisters library before move when monitored") + void unregistersBeforeMove() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + mockMonitoredLibrary(); + + service.moveSingleFile(book); + + verify(fileMoveHelper).unregisterLibrary(1L); + } + + @Test + @DisplayName("waits for events to drain after unregistering") + void waitsForEventsDrain() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + mockMonitoredLibrary(); + + service.moveSingleFile(book); + + verify(monitoringRegistrationService).waitForEventsDrainedByPaths(anySet(), anyLong()); + } + + @Test + @DisplayName("re-registers library after successful move") + void reRegistersAfterSuccess() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + mockMonitoredLibrary(); + + service.moveSingleFile(book); + + verify(monitoringRegistrationService).registerLibrary(any()); + } + + @Test + @DisplayName("re-registers library even after failure") + void reRegistersAfterFailure() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any()); + mockMonitoredLibrary(); + + service.moveSingleFile(book); + + verify(monitoringRegistrationService).registerLibrary(any()); + } + + @Test + @DisplayName("sets watch=true before re-registering") + void setsWatchTrueBeforeReRegistering() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library"))); + Library dto = Library.builder().watch(false).build(); + when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto); + + service.moveSingleFile(book); + + assertThat(dto.isWatch()).isTrue(); + verify(monitoringRegistrationService).registerLibrary(dto); + } + + @Test + @DisplayName("skips monitoring operations when library not monitored") + void skipsMonitoringWhenNotMonitored() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + mockUnmonitoredLibrary(); + + service.moveSingleFile(book); + + verify(fileMoveHelper, never()).unregisterLibrary(anyLong()); + verify(monitoringRegistrationService, never()).registerLibrary(any()); + verify(service, never()).sleep(anyLong()); + } + + @Test + @DisplayName("treats library as monitored when has paths but status is false") + void treatsAsMonitoredWhenHasPathsButStatusFalse() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library"))); + when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build()); + + service.moveSingleFile(book); + + verify(fileMoveHelper).unregisterLibrary(1L); + verify(monitoringRegistrationService).registerLibrary(any()); + } + + @Test + @DisplayName("sleeps after move when monitored to allow events to drain") + void sleepsAfterMoveWhenMonitored() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + mockMonitoredLibrary(); + + service.moveSingleFile(book); + + verify(service).sleep(anyLong()); + } + } + + @Nested + @DisplayName("moveSingleFile - Lazy Loading Cases") + class MoveSingleFileLazyLoading { + + @Test + @DisplayName("fetches book files from repository when null") + void fetchesWhenNull() throws IOException { + BookEntity bookWithoutFiles = new BookEntity(); + bookWithoutFiles.setId(100L); + bookWithoutFiles.setLibrary(library); + bookWithoutFiles.setLibraryPath(libraryPath); + bookWithoutFiles.setBookFiles(null); + + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity loadedBook = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(loadedBook)); + mockStandardBehavior(loadedBook, target); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(bookWithoutFiles); + + assertThat(result.isMoved()).isTrue(); + verify(bookRepository).findByIdWithBookFiles(100L); + } + + @Test + @DisplayName("fetches book files from repository when empty list") + void fetchesWhenEmpty() throws IOException { + BookEntity bookWithEmptyFiles = new BookEntity(); + bookWithEmptyFiles.setId(100L); + bookWithEmptyFiles.setLibrary(library); + bookWithEmptyFiles.setLibraryPath(libraryPath); + bookWithEmptyFiles.setBookFiles(new ArrayList<>()); + + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity loadedBook = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(loadedBook)); + mockStandardBehavior(loadedBook, target); + mockUnmonitoredLibrary(); + + FileMoveResult result = service.moveSingleFile(bookWithEmptyFiles); + + assertThat(result.isMoved()).isTrue(); + verify(bookRepository).findByIdWithBookFiles(100L); + } + + @Test + @DisplayName("does not fetch when book files already loaded") + void doesNotFetchWhenLoaded() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/library/new/path/NewName.epub"); + + mockStandardBehavior(book, target); + mockUnmonitoredLibrary(); + + service.moveSingleFile(book); + + verify(bookRepository, never()).findByIdWithBookFiles(anyLong()); + } + } + + @Nested + @DisplayName("bulkMoveFiles - Success Cases") + class BulkMoveFilesSuccess { + + private LibraryEntity targetLibrary; + private LibraryPathEntity targetLibraryPath; + + @BeforeEach + void setUpTarget() { + targetLibrary = new LibraryEntity(); + targetLibrary.setId(2L); + + targetLibraryPath = new LibraryPathEntity(); + targetLibraryPath.setId(20L); + targetLibraryPath.setPath("/target"); + targetLibraryPath.setLibrary(targetLibrary); + targetLibrary.setLibraryPaths(List.of(targetLibraryPath)); + } + + private void mockBulkMoveSetup(BookEntity book, Path targetPath) throws IOException { + when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); + when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary)); + + when(fileMoveHelper.getFileNamingPattern(targetLibrary)).thenReturn("{title}"); + when(fileMoveHelper.generateNewFilePath(eq(book), eq(targetLibraryPath), anyString())).thenReturn(targetPath); + when(fileMoveHelper.generateNewFilePath(eq(book), any(BookFileEntity.class), eq(targetLibraryPath), anyString())) + .thenAnswer(inv -> { + BookFileEntity bf = inv.getArgument(1); + String ext = bf.getFileName().contains(".") ? bf.getFileName().substring(bf.getFileName().lastIndexOf('.')) : ""; + return targetPath.getParent().resolve("NewName" + ext); + }); + when(fileMoveHelper.extractSubPath(any(), eq(targetLibraryPath))).thenReturn("new"); + when(fileMoveHelper.validateSourceExists(any(), anyBoolean())).thenReturn(true); + when(fileMoveHelper.moveFileWithBackup(any())).thenAnswer(inv -> ((Path) inv.getArgument(0)).resolveSibling("temp")); + doNothing().when(fileMoveHelper).commitMove(any(), any()); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"), Paths.get("/target"))); + } + + @Test + @DisplayName("moves single book to target library") + void movesSingleBook() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/target/new/NewName.epub"); + + mockBulkMoveSetup(book, target); + + FileMoveRequest request = new FileMoveRequest(); + FileMoveRequest.Move move = new FileMoveRequest.Move(); + move.setBookId(100L); + move.setTargetLibraryId(2L); + move.setTargetLibraryPathId(20L); + request.setMoves(List.of(move)); + + service.bulkMoveFiles(request); + + verify(fileMoveHelper).commitMove(any(), any()); + verify(bookRepository).updateLibrary(100L, 2L, targetLibraryPath); + verify(notificationService).sendMessage(eq(Topic.BOOK_UPDATE), any()); + } + + @Test + @DisplayName("moves multi-format book with all files") + void movesMultiFormatBook() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookFileEntity pdf = createBookFile(2L, "Book.pdf", "path", true, false); + BookFileEntity cover = createBookFile(3L, "cover.jpg", "path", false, false); + BookEntity book = createBook(List.of(epub, pdf, cover)); + Path target = Paths.get("/target/new/NewName.epub"); + + mockBulkMoveSetup(book, target); + + FileMoveRequest request = new FileMoveRequest(); + FileMoveRequest.Move move = new FileMoveRequest.Move(); + move.setBookId(100L); + move.setTargetLibraryId(2L); + move.setTargetLibraryPathId(20L); + request.setMoves(List.of(move)); + + service.bulkMoveFiles(request); + + verify(fileMoveHelper, times(3)).moveFileWithBackup(any()); + verify(fileMoveHelper, times(3)).commitMove(any(), any()); + verify(bookFileRepository, times(3)).updateFileNameAndSubPath(anyLong(), anyString(), anyString()); + } + + @Test + @DisplayName("updates database after all file moves") + void updatesDatabaseAfterMoves() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/target/new/NewName.epub"); + + mockBulkMoveSetup(book, target); + + FileMoveRequest request = new FileMoveRequest(); + FileMoveRequest.Move move = new FileMoveRequest.Move(); + move.setBookId(100L); + move.setTargetLibraryId(2L); + move.setTargetLibraryPathId(20L); + request.setMoves(List.of(move)); + + service.bulkMoveFiles(request); + + verify(bookFileRepository).updateFileNameAndSubPath(anyLong(), anyString(), anyString()); + verify(bookRepository).updateLibrary(eq(100L), eq(2L), eq(targetLibraryPath)); + } + + @Test + @DisplayName("sends notification after successful move") + void sendsNotification() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/target/new/NewName.epub"); + + mockBulkMoveSetup(book, target); + + FileMoveRequest request = new FileMoveRequest(); + FileMoveRequest.Move move = new FileMoveRequest.Move(); + move.setBookId(100L); + move.setTargetLibraryId(2L); + move.setTargetLibraryPathId(20L); + request.setMoves(List.of(move)); + + service.bulkMoveFiles(request); + + verify(notificationService).sendMessage(eq(Topic.BOOK_UPDATE), any()); + } + + @Test + @DisplayName("clears entity manager after move") + void clearsEntityManager() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + Path target = Paths.get("/target/new/NewName.epub"); + + mockBulkMoveSetup(book, target); + + FileMoveRequest request = new FileMoveRequest(); + FileMoveRequest.Move move = new FileMoveRequest.Move(); + move.setBookId(100L); + move.setTargetLibraryId(2L); + move.setTargetLibraryPathId(20L); + request.setMoves(List.of(move)); + + service.bulkMoveFiles(request); + + verify(entityManager).clear(); + } + } + + @Nested + @DisplayName("bulkMoveFiles - Failure Cases") + class BulkMoveFilesFailure { + + @BeforeEach + void setUpMonitoring() { + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Collections.emptySet()); + } + + @Test + @DisplayName("skips gracefully when book not found") + void skipsWhenBookNotFound() throws IOException { + when(bookRepository.findById(100L)).thenReturn(Optional.empty()); + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.empty()); + + FileMoveRequest request = new FileMoveRequest(); + FileMoveRequest.Move move = new FileMoveRequest.Move(); + move.setBookId(100L); + move.setTargetLibraryId(2L); + move.setTargetLibraryPathId(20L); + request.setMoves(List.of(move)); + + service.bulkMoveFiles(request); + + verify(fileMoveHelper, never()).moveFileWithBackup(any()); + verify(bookRepository, never()).updateLibrary(anyLong(), anyLong(), any()); + } + + @Test + @DisplayName("skips gracefully when target library not found") + void skipsWhenTargetLibraryNotFound() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + + when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); + when(libraryRepository.findById(2L)).thenReturn(Optional.empty()); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"))); + + FileMoveRequest request = new FileMoveRequest(); + FileMoveRequest.Move move = new FileMoveRequest.Move(); + move.setBookId(100L); + move.setTargetLibraryId(2L); + move.setTargetLibraryPathId(20L); + request.setMoves(List.of(move)); + + service.bulkMoveFiles(request); + + verify(fileMoveHelper, never()).moveFileWithBackup(any()); + } + + @Test + @DisplayName("skips gracefully when target library path not found") + void skipsWhenLibraryPathNotFound() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + + LibraryEntity targetLibrary = new LibraryEntity(); + targetLibrary.setId(2L); + LibraryPathEntity differentPath = new LibraryPathEntity(); + differentPath.setId(99L); // Different ID than requested + differentPath.setPath("/other"); + differentPath.setLibrary(targetLibrary); + targetLibrary.setLibraryPaths(List.of(differentPath)); + + when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); + when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary)); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"))); + + FileMoveRequest request = new FileMoveRequest(); + FileMoveRequest.Move move = new FileMoveRequest.Move(); + move.setBookId(100L); + move.setTargetLibraryId(2L); + move.setTargetLibraryPathId(20L); // Doesn't exist in target library + request.setMoves(List.of(move)); + + service.bulkMoveFiles(request); + + verify(fileMoveHelper, never()).moveFileWithBackup(any()); + } + + @Test + @DisplayName("skips when book has no files") + void skipsWhenBookHasNoFiles() throws IOException { + BookEntity book = createBook(List.of()); + + LibraryEntity targetLibrary = new LibraryEntity(); + targetLibrary.setId(2L); + LibraryPathEntity targetPath = new LibraryPathEntity(); + targetPath.setId(20L); + targetPath.setPath("/target"); + targetPath.setLibrary(targetLibrary); + targetLibrary.setLibraryPaths(List.of(targetPath)); + + when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); + when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary)); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"))); + + FileMoveRequest request = new FileMoveRequest(); + FileMoveRequest.Move move = new FileMoveRequest.Move(); + move.setBookId(100L); + move.setTargetLibraryId(2L); + move.setTargetLibraryPathId(20L); + request.setMoves(List.of(move)); + + service.bulkMoveFiles(request); + + verify(fileMoveHelper, never()).moveFileWithBackup(any()); + } + } + + @Nested + @DisplayName("bulkMoveFiles - Monitoring Cases") + class BulkMoveFilesMonitoring { + + @Test + @DisplayName("unregisters all affected libraries before moves") + void unregistersAllLibraries() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + + LibraryEntity targetLibrary = new LibraryEntity(); + targetLibrary.setId(2L); + LibraryPathEntity targetPath = new LibraryPathEntity(); + targetPath.setId(20L); + targetPath.setPath("/target"); + targetPath.setLibrary(targetLibrary); + targetLibrary.setLibraryPaths(List.of(targetPath)); + + when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); + when(libraryRepository.findById(1L)).thenReturn(Optional.of(library)); + when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary)); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"), Paths.get("/target"))); + when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build()); + + when(fileMoveHelper.getFileNamingPattern(targetLibrary)).thenReturn("{title}"); + when(fileMoveHelper.generateNewFilePath(eq(book), eq(targetPath), anyString())).thenReturn(Paths.get("/target/new/NewName.epub")); + when(fileMoveHelper.generateNewFilePath(eq(book), any(BookFileEntity.class), eq(targetPath), anyString())).thenReturn(Paths.get("/target/new/NewName.epub")); + when(fileMoveHelper.extractSubPath(any(), eq(targetPath))).thenReturn("new"); + when(fileMoveHelper.validateSourceExists(any(), anyBoolean())).thenReturn(true); + when(fileMoveHelper.moveFileWithBackup(any())).thenAnswer(inv -> ((Path) inv.getArgument(0)).resolveSibling("temp")); + doNothing().when(fileMoveHelper).commitMove(any(), any()); + + FileMoveRequest request = new FileMoveRequest(); + FileMoveRequest.Move move = new FileMoveRequest.Move(); + move.setBookId(100L); + move.setTargetLibraryId(2L); + move.setTargetLibraryPathId(20L); + request.setMoves(List.of(move)); + + service.bulkMoveFiles(request); + + verify(monitoringRegistrationService).unregisterLibraries(anySet()); + } + + @Test + @DisplayName("re-registers all affected libraries after moves") + void reRegistersAllLibraries() throws IOException { + BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false); + BookEntity book = createBook(List.of(epub)); + + LibraryEntity targetLibrary = new LibraryEntity(); + targetLibrary.setId(2L); + LibraryPathEntity targetPath = new LibraryPathEntity(); + targetPath.setId(20L); + targetPath.setPath("/target"); + targetPath.setLibrary(targetLibrary); + targetLibrary.setLibraryPaths(List.of(targetPath)); + + when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); + when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); + when(libraryRepository.findById(1L)).thenReturn(Optional.of(library)); + when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary)); + when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"), Paths.get("/target"))); + when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build()); + + when(fileMoveHelper.getFileNamingPattern(targetLibrary)).thenReturn("{title}"); + when(fileMoveHelper.generateNewFilePath(eq(book), eq(targetPath), anyString())).thenReturn(Paths.get("/target/new/NewName.epub")); + when(fileMoveHelper.generateNewFilePath(eq(book), any(BookFileEntity.class), eq(targetPath), anyString())).thenReturn(Paths.get("/target/new/NewName.epub")); + when(fileMoveHelper.extractSubPath(any(), eq(targetPath))).thenReturn("new"); + when(fileMoveHelper.validateSourceExists(any(), anyBoolean())).thenReturn(true); + when(fileMoveHelper.moveFileWithBackup(any())).thenAnswer(inv -> ((Path) inv.getArgument(0)).resolveSibling("temp")); + doNothing().when(fileMoveHelper).commitMove(any(), any()); + + FileMoveRequest request = new FileMoveRequest(); + FileMoveRequest.Move move = new FileMoveRequest.Move(); + move.setBookId(100L); + move.setTargetLibraryId(2L); + move.setTargetLibraryPathId(20L); + request.setMoves(List.of(move)); + + service.bulkMoveFiles(request); + + // Both source and target libraries should be re-registered + verify(monitoringRegistrationService, times(2)).registerLibrary(any()); + } + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FileAsBookProcessorTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FileAsBookProcessorTest.java index 21b923b0c..ac99543d2 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FileAsBookProcessorTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FileAsBookProcessorTest.java @@ -1,24 +1,33 @@ package com.adityachandel.booklore.service.library; -import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.FileProcessResult; -import com.adityachandel.booklore.model.enums.FileProcessStatus; +import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.BookFile; import com.adityachandel.booklore.model.dto.settings.LibraryFile; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.model.enums.FileProcessStatus; +import com.adityachandel.booklore.repository.BookAdditionalFileRepository; +import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.event.BookEventBroadcaster; +import com.adityachandel.booklore.service.file.FileFingerprint; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; +import com.adityachandel.booklore.service.kobo.KoboAutoShelfService; +import com.adityachandel.booklore.util.FileUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.*; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; class FileAsBookProcessorTest { @@ -29,36 +38,63 @@ class FileAsBookProcessorTest { @Mock private BookFileProcessorRegistry processorRegistry; + @Mock + private KoboAutoShelfService koboAutoShelfService; + + @Mock + private BookRepository bookRepository; + + @Mock + private BookAdditionalFileRepository bookAdditionalFileRepository; + @Mock private BookFileProcessor bookFileProcessor; - @InjectMocks private FileAsBookProcessor fileAsBookProcessor; - @Captor - private ArgumentCaptor bookCaptor; - private AutoCloseable mocks; + private MockedStatic fileFingerprintMock; + private MockedStatic fileUtilsMock; @BeforeEach void setUp() { mocks = MockitoAnnotations.openMocks(this); + fileAsBookProcessor = new FileAsBookProcessor( + bookEventBroadcaster, + processorRegistry, + koboAutoShelfService, + bookRepository, + bookAdditionalFileRepository + ); + fileFingerprintMock = mockStatic(FileFingerprint.class); + fileFingerprintMock.when(() -> FileFingerprint.generateHash(any(Path.class))).thenReturn("testhash"); + fileUtilsMock = mockStatic(FileUtils.class); + fileUtilsMock.when(() -> FileUtils.getFileSizeInKb(any(Path.class))).thenReturn(100L); } @AfterEach void tearDown() throws Exception { - if (mocks != null) { - mocks.close(); - } + if (fileFingerprintMock != null) fileFingerprintMock.close(); + if (fileUtilsMock != null) fileUtilsMock.close(); + if (mocks != null) mocks.close(); } @Test - void processLibraryFiles_shouldProcessAllValidFiles() { - // Given + void staticMocksShouldWork() { + // Verify static mocks are working + Path testPath = Path.of("/test/path"); + String hash = FileFingerprint.generateHash(testPath); + Long size = FileUtils.getFileSizeInKb(testPath); + assert hash.equals("testhash") : "Expected 'testhash' but got: " + hash; + assert size.equals(100L) : "Expected 100L but got: " + size; + } + + @Test + void processLibraryFiles_shouldProcessDifferentNamedFilesSeparately() { LibraryEntity libraryEntity = new LibraryEntity(); LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setId(1L); libraryPathEntity.setPath("/library/path"); - List libraryFiles = new ArrayList<>(); LibraryFile file1 = LibraryFile.builder() .libraryEntity(libraryEntity) @@ -76,54 +112,36 @@ class FileAsBookProcessorTest { .bookFileType(BookFileType.PDF) .build(); - libraryFiles.add(file1); - libraryFiles.add(file2); - - Book book1 = Book.builder() - .fileName("book1.epub") - .title("Book 1") - .bookType(BookFileType.EPUB) - .build(); - - Book book2 = Book.builder() - .fileName("book2.pdf") - .title("Book 2") - .bookType(BookFileType.PDF) - .build(); + Book book1 = Book.builder().id(1L).primaryFile(BookFile.builder().fileName("book1.epub").bookType(BookFileType.EPUB).build()).build(); + Book book2 = Book.builder().id(2L).primaryFile(BookFile.builder().fileName("book2.pdf").bookType(BookFileType.PDF).build()).build(); when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor); when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor); - when(bookFileProcessor.processFile(file1)) - .thenReturn(new FileProcessResult(book1, FileProcessStatus.NEW)); - when(bookFileProcessor.processFile(file2)) - .thenReturn(new FileProcessResult(book2, FileProcessStatus.NEW)); + when(bookFileProcessor.processFile(file1)).thenReturn(new FileProcessResult(book1, FileProcessStatus.NEW)); + when(bookFileProcessor.processFile(file2)).thenReturn(new FileProcessResult(book2, FileProcessStatus.NEW)); - // When - fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); + fileAsBookProcessor.processLibraryFiles(List.of(file1, file2), libraryEntity); - // Then - verify(bookEventBroadcaster, times(2)).broadcastBookAddEvent(bookCaptor.capture()); - - List capturedBooks = bookCaptor.getAllValues(); - assertThat(capturedBooks).hasSize(2); - assertThat(capturedBooks).containsExactly(book1, book2); + verify(bookEventBroadcaster, times(2)).broadcastBookAddEvent(any()); + verify(bookFileProcessor, times(2)).processFile(any()); } @Test - void processLibraryFiles_shouldSkipFilesWithUnsupportedExtensions() { - // Given + void processLibraryFiles_shouldHandleEmptyList() { + LibraryEntity libraryEntity = new LibraryEntity(); + + fileAsBookProcessor.processLibraryFiles(new ArrayList<>(), libraryEntity); + + verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any()); + verify(processorRegistry, never()).getProcessorOrThrow(any()); + } + + @Test + void processLibraryFiles_shouldSkipFilesWithNullBookFileType() { LibraryEntity libraryEntity = new LibraryEntity(); LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setId(1L); libraryPathEntity.setPath("/library/path"); - List libraryFiles = new ArrayList<>(); - - LibraryFile validFile = LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(libraryPathEntity) - .fileName("book.epub") - .fileSubPath("books") - .bookFileType(BookFileType.EPUB) - .build(); LibraryFile invalidFile = LibraryFile.builder() .libraryEntity(libraryEntity) @@ -133,133 +151,19 @@ class FileAsBookProcessorTest { .bookFileType(null) .build(); - libraryFiles.add(validFile); - libraryFiles.add(invalidFile); + fileAsBookProcessor.processLibraryFiles(List.of(invalidFile), libraryEntity); - Book book = Book.builder() - .fileName("book.epub") - .title("Valid Book") - .bookType(BookFileType.EPUB) - .build(); - - when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor); - when(bookFileProcessor.processFile(validFile)) - .thenReturn(new FileProcessResult(book, FileProcessStatus.NEW)); - - // When - fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); - - // Then - verify(bookEventBroadcaster, times(1)).broadcastBookAddEvent(book); - verify(processorRegistry, times(1)).getProcessorOrThrow(any()); - } - - @Test - void processLibraryFiles_shouldHandleEmptyList() { - // Given - LibraryEntity libraryEntity = new LibraryEntity(); - List libraryFiles = new ArrayList<>(); - - // When - fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); - - // Then verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any()); verify(processorRegistry, never()).getProcessorOrThrow(any()); } @Test - void processLibraryFile_shouldReturnNullForUnsupportedFileType() { - // Given + void processLibraryFiles_shouldNotBroadcastWhenProcessorReturnsNull() { LibraryEntity libraryEntity = new LibraryEntity(); LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setId(1L); libraryPathEntity.setPath("/library/path"); - LibraryFile libraryFile = LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(libraryPathEntity) - .fileName("document.txt") - .fileSubPath("docs") - .bookFileType(null) - .build(); - - // When - FileProcessResult result = fileAsBookProcessor.processLibraryFile(libraryFile); - - // Then - assertThat(result).isNull(); - verify(processorRegistry, never()).getProcessorOrThrow(any()); - } - - @Test - void processLibraryFile_shouldProcessSupportedFileTypes() { - // Given - LibraryEntity libraryEntity = new LibraryEntity(); - LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); - libraryPathEntity.setPath("/library/path"); - - LibraryFile libraryFile = LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(libraryPathEntity) - .fileName("book.epub") - .fileSubPath("books") - .bookFileType(BookFileType.EPUB) - .build(); - - Book expectedBook = Book.builder() - .fileName("book.epub") - .title("Test Book") - .bookType(BookFileType.EPUB) - .build(); - - when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor); - when(bookFileProcessor.processFile(libraryFile)) - .thenReturn(new FileProcessResult(expectedBook, FileProcessStatus.NEW)); - - // When - FileProcessResult result = fileAsBookProcessor.processLibraryFile(libraryFile); - - // Then - assertThat(result).isNotNull(); - assertThat(result.getBook()).isEqualTo(expectedBook); - - verify(processorRegistry).getProcessorOrThrow(BookFileType.EPUB); - verify(bookFileProcessor).processFile(libraryFile); - } - - @Test - void processLibraryFile_shouldHandleNullReturnFromProcessor() { - // Given - LibraryEntity libraryEntity = new LibraryEntity(); - LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); - libraryPathEntity.setPath("/library/path"); - - LibraryFile libraryFile = LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(libraryPathEntity) - .fileName("book.pdf") - .fileSubPath("books") - .bookFileType(BookFileType.PDF) - .build(); - - when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor); - when(bookFileProcessor.processFile(libraryFile)).thenReturn(null); - - // When - FileProcessResult result = fileAsBookProcessor.processLibraryFile(libraryFile); - - // Then - assertThat(result).isNull(); - } - - @Test - void processLibraryFiles_shouldNotSendNotificationWhenProcessorReturnsNull() { - // Given - LibraryEntity libraryEntity = new LibraryEntity(); - LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); - libraryPathEntity.setPath("/library/path"); - List libraryFiles = new ArrayList<>(); - LibraryFile file = LibraryFile.builder() .libraryEntity(libraryEntity) .libraryPathEntity(libraryPathEntity) @@ -268,100 +172,49 @@ class FileAsBookProcessorTest { .bookFileType(BookFileType.EPUB) .build(); - libraryFiles.add(file); - when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor); when(bookFileProcessor.processFile(file)).thenReturn(null); - // When - fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); + fileAsBookProcessor.processLibraryFiles(List.of(file), libraryEntity); - // Then verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any()); } @Test - void processLibraryFiles_shouldProcessAllSupportedFileExtensions() { - // Given + void processLibraryFiles_shouldNotGroupFilesInDifferentDirectories() { LibraryEntity libraryEntity = new LibraryEntity(); LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setId(1L); libraryPathEntity.setPath("/library/path"); - List libraryFiles = new ArrayList<>(); - LibraryFile epubFile = LibraryFile.builder() + LibraryFile file1 = LibraryFile.builder() .libraryEntity(libraryEntity) .libraryPathEntity(libraryPathEntity) .fileName("book.epub") - .fileSubPath("books") + .fileSubPath("dir1") .bookFileType(BookFileType.EPUB) .build(); - LibraryFile pdfFile = LibraryFile.builder() + LibraryFile file2 = LibraryFile.builder() .libraryEntity(libraryEntity) .libraryPathEntity(libraryPathEntity) .fileName("book.pdf") - .fileSubPath("books") + .fileSubPath("dir2") .bookFileType(BookFileType.PDF) .build(); - LibraryFile cbzFile = LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(libraryPathEntity) - .fileName("comic.cbz") - .fileSubPath("comics") - .bookFileType(BookFileType.CBX) - .build(); - - LibraryFile cbrFile = LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(libraryPathEntity) - .fileName("comic.cbr") - .fileSubPath("comics") - .bookFileType(BookFileType.CBX) - .build(); - - libraryFiles.add(epubFile); - libraryFiles.add(pdfFile); - libraryFiles.add(cbzFile); - libraryFiles.add(cbrFile); - - Book epubBook = Book.builder() - .fileName("book.epub") - .bookType(BookFileType.EPUB) - .build(); - - Book pdfBook = Book.builder() - .fileName("book.pdf") - .bookType(BookFileType.PDF) - .build(); - - Book cbzBook = Book.builder() - .fileName("comic.cbz") - .bookType(BookFileType.CBX) - .build(); - - Book cbrBook = Book.builder() - .fileName("comic.cbr") - .bookType(BookFileType.CBX) - .build(); + Book book1 = Book.builder().id(1L).primaryFile(BookFile.builder().fileName("book.epub").bookType(BookFileType.EPUB).build()).build(); + Book book2 = Book.builder().id(2L).primaryFile(BookFile.builder().fileName("book.pdf").bookType(BookFileType.PDF).build()).build(); when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor); when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor); - when(processorRegistry.getProcessorOrThrow(BookFileType.CBX)).thenReturn(bookFileProcessor); + when(bookFileProcessor.processFile(file1)).thenReturn(new FileProcessResult(book1, FileProcessStatus.NEW)); + when(bookFileProcessor.processFile(file2)).thenReturn(new FileProcessResult(book2, FileProcessStatus.NEW)); - when(bookFileProcessor.processFile(epubFile)) - .thenReturn(new FileProcessResult(epubBook, FileProcessStatus.NEW)); - when(bookFileProcessor.processFile(pdfFile)) - .thenReturn(new FileProcessResult(pdfBook, FileProcessStatus.NEW)); - when(bookFileProcessor.processFile(cbzFile)) - .thenReturn(new FileProcessResult(cbzBook, FileProcessStatus.NEW)); - when(bookFileProcessor.processFile(cbrFile)) - .thenReturn(new FileProcessResult(cbrBook, FileProcessStatus.NEW)); + fileAsBookProcessor.processLibraryFiles(List.of(file1, file2), libraryEntity); - // When - fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); - - // Then - verify(bookEventBroadcaster, times(4)).broadcastBookAddEvent(any(Book.class)); + // Both should be processed as separate books + verify(bookFileProcessor, times(2)).processFile(any()); + verify(bookEventBroadcaster, times(2)).broadcastBookAddEvent(any()); } -} \ No newline at end of file +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorExampleTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorExampleTest.java deleted file mode 100644 index 2308d1dce..000000000 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorExampleTest.java +++ /dev/null @@ -1,320 +0,0 @@ -package com.adityachandel.booklore.service.library; - -import com.adityachandel.booklore.model.entity.BookFileEntity; -import com.adityachandel.booklore.model.enums.BookFileType; -import com.adityachandel.booklore.repository.BookAdditionalFileRepository; -import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.file.FileFingerprint; -import com.adityachandel.booklore.service.event.AdminEventBroadcaster; -import com.adityachandel.booklore.service.event.BookEventBroadcaster; -import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; -import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; -import com.adityachandel.booklore.util.FileUtils; -import com.adityachandel.booklore.util.builder.LibraryTestBuilder; -import static com.adityachandel.booklore.util.builder.LibraryTestBuilderAssert.assertThat; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.*; -import org.mockito.junit.jupiter.MockitoExtension; - -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) -class FolderAsBookFileProcessorExampleTest { - - @Mock - private BookRepository bookRepository; - - @Mock - private BookAdditionalFileRepository bookAdditionalFileRepository; - - @Mock - private BookEventBroadcaster bookEventBroadcaster; - - @Mock - private AdminEventBroadcaster adminEventBroadcaster; - - @Mock - private BookFileProcessorRegistry bookFileProcessorRegistry; - - @Mock - private BookFileProcessor mockBookFileProcessor; - - @InjectMocks - private FolderAsBookFileProcessor processor; - - @Captor - private ArgumentCaptor additionalFileCaptor; - - private MockedStatic fileUtilsMock; - private MockedStatic fileFingerprintMock; - private LibraryTestBuilder libraryTestBuilder; - - @BeforeEach - void setUp() { - fileUtilsMock = mockStatic(FileUtils.class); - fileFingerprintMock = mockStatic(FileFingerprint.class); - libraryTestBuilder = new LibraryTestBuilder(fileUtilsMock, fileFingerprintMock, bookFileProcessorRegistry, mockBookFileProcessor, bookRepository, bookAdditionalFileRepository); - } - - @AfterEach - void tearDown() { - fileUtilsMock.close(); - fileFingerprintMock.close(); - } - - @Test - void processLibraryFiles_shouldCreateNewBookFromDirectory() { - // Given - libraryTestBuilder - .addDefaultLibrary() - .addLibraryFile("/101/Accounting", "Accounting 101.pdf") - .addLibraryFile("/101/Anatomy", "Anatomy 101.pdf"); - - // When - processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity()); - - // Then - assertThat(libraryTestBuilder) - .hasBooks("Accounting 101", "Anatomy 101") - .hasNoAdditionalFiles(); - } - - @Test - void processLibraryFiles_shouldCreateNewBookFromDirectoryWithAdditionalBookFormats() { - // Given - libraryTestBuilder - .addDefaultLibrary() - .addLibraryFile("/101/Accounting", "Accounting 101.pdf") - .addLibraryFile("/101/Accounting", "Accounting 101.epub") - .addLibraryFile("/101/Anatomy", "Anatomy 101.pdf"); - - // When - processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity()); - - // Then - assertThat(libraryTestBuilder) - .hasBooks("Accounting 101", "Anatomy 101") - .bookHasAdditionalFormats("Accounting 101", BookFileType.PDF) - .bookHasNoSupplementaryFiles("Accounting 101") - .bookHasNoAdditionalFiles("Anatomy 101"); - } - - @Test - void processLibraryFiles_shouldCreateNewBookFromDirectoryWithAdditionalBookFormatsAndSupplementaryFiles() { - // Given - libraryTestBuilder - .addDefaultLibrary() - .addLibraryFile("/101/Accounting", "Accounting 101.pdf") - .addLibraryFile("/101/Accounting", "Accounting 101.epub") - .addLibraryFile("/101/Accounting", "Accounting 101.zip") - .addLibraryFile("/101/Anatomy", "Anatomy 101.pdf"); - - // When - processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity()); - - // Then - assertThat(libraryTestBuilder) - .hasBooks("Accounting 101", "Anatomy 101") - .bookHasAdditionalFormats("Accounting 101", BookFileType.PDF) - .bookHasSupplementaryFiles("Accounting 101", "Accounting 101.zip") - .bookHasNoAdditionalFiles("Anatomy 101"); - } - - @Test - void processLibraryFiles_shouldCreateNewBookFromDirectoryWithSameSupplementaryFilesByHash() { - // Given - String supplementaryFileHash = "hash-accounting-101"; - libraryTestBuilder - .addDefaultLibrary() - .addLibraryFile("/101/Accounting", "Accounting 101.pdf") - .addLibraryFile( - "/101/Accounting", - "Accounting 101.zip", - supplementaryFileHash) - .addLibraryFile("/101/Accounting 2nd Edition", "Accounting 101 2nd Edition.pdf") - .addLibraryFile( - "/101/Accounting 2nd Edition", - "Accounting 101 2nd Edition.zip", - supplementaryFileHash); - - // When - processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity()); - - // Then - assertThat(libraryTestBuilder) - .hasBooks("Accounting 101", "Accounting 101 2nd Edition") - .bookHasSupplementaryFiles("Accounting 101", "Accounting 101.zip") - .bookHasSupplementaryFiles("Accounting 101 2nd Edition", "Accounting 101 2nd Edition.zip"); - } - - @Test - void processLibraryFiles_shouldIgnoreAdditionalFormatWithTheSameHashUsedInOtherBook() { - // Given - String additionalFormatHash = "hash-accounting-101"; - libraryTestBuilder - .addDefaultLibrary() - .addLibraryFile("/101/Accounting", "Accounting 101.epub") - .addLibraryFile( - "/101/Accounting", - "Accounting 101.pdf", - additionalFormatHash) - .addLibraryFile("/101/Accounting 2nd Edition", "Accounting 101 2nd Edition.epub") - .addLibraryFile( - "/101/Accounting 2nd Edition", - "Accounting 101 2nd Edition.pdf", - additionalFormatHash); - - // When - processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity()); - - // Then - assertThat(libraryTestBuilder) - .hasBooks("Accounting 101", "Accounting 101 2nd Edition") - .bookHasAdditionalFormats("Accounting 101", BookFileType.PDF) - .bookHasNoAdditionalFiles("Accounting 101 2nd Edition"); - } - - @Test - void processLibraryFiles_shouldAddAdditionalFormatsToExistingBook() { - // Given - libraryTestBuilder - .addDefaultLibrary() - .addBook("/101/Accounting", "Accounting 101.pdf") - .addLibraryFile("/101/Accounting", "Accounting 101.epub"); - - // When - processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity()); - - // Then - assertThat(libraryTestBuilder) - .hasBooks("Accounting 101") - .bookHasAdditionalFormats("Accounting 101", BookFileType.EPUB) - .bookHasNoSupplementaryFiles("Accounting 101"); - } - - @Test - void processLibraryFiles_shouldAddSupplementaryFilesToExistingBook() { - // Given - libraryTestBuilder - .addDefaultLibrary() - .addBook("/101/Accounting", "Accounting 101.pdf") - .addLibraryFile("/101/Accounting", "sources.zip"); - - // When - processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity()); - - // Then - assertThat(libraryTestBuilder) - .hasBooks("Accounting 101") - .bookHasNoAdditionalFormats("Accounting 101") - .bookHasSupplementaryFiles("Accounting 101", "sources.zip"); - } - - @Test - void processLibraryFiles_shouldAddAdditionalFilesToExistingBook() { - // Given - libraryTestBuilder - .addDefaultLibrary() - .addBook("/101/Accounting", "Accounting 101.pdf") - .addLibraryFile("/101/Accounting", "Accounting 101.epub") - .addLibraryFile("/101/Accounting", "sources.zip"); - - // When - processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity()); - - // Then - assertThat(libraryTestBuilder) - .hasBooks("Accounting 101") - .bookHasAdditionalFormats("Accounting 101", BookFileType.EPUB) - .bookHasSupplementaryFiles("Accounting 101", "sources.zip"); - } - - @Test - void processLibraryFiles_shouldProcessDeepSubfolders() { - var javaSourcesSameHash = "hash-java-sources"; - - libraryTestBuilder - .addDefaultLibrary() - // Basic books - .addLibraryFile("/Basic/101/Accounting", "Accounting 101.epub") - .addLibraryFile("/Basic/101/Accounting", "Accounting 101.pdf") - .addLibraryFile("/Basic/101/Anatomy", "Anatomy 101.pdf") - .addLibraryFile("/Basic/How-To/Repair", "How to Repair.epub") - .addLibraryFile("/Basic/How-To/Repair", "How to Repair.pdf") - // Software Engineering books - .addLibraryFile("/Software Engineering/Java/Design Patterns", "Design Patterns.pdf") - .addLibraryFile("/Software Engineering/Java/Design Patterns", "Design Patterns.epub") - .addLibraryFile("/Software Engineering/Java/Design Patterns", "Design Patterns.zip", javaSourcesSameHash) - .addLibraryFile("/Software Engineering/Java/Effective Java", "Effective Java.pdf") - .addLibraryFile("/Software Engineering/Java/Effective Java", "Effective Java.epub") - .addLibraryFile("/Software Engineering/Java/Effective Java", "Effective Java.zip", javaSourcesSameHash) - .addLibraryFile("/Software Engineering/Python/AI/Machine Learning/Pytorch", "PyTorch for Machine Learning.pdf") - .addLibraryFile("/Software Engineering/Python/AI/Machine Learning/Pytorch", "PyTorch for Machine Learning.epub") - .addLibraryFile("/Software Engineering/Python/AI/Machine Learning/Pytorch", "sources.zip") - .addLibraryFile("/Software Engineering/Python/AI/Machine Learning/TensorFlow", "TensorFlow for Machine Learning.pdf") - .addLibraryFile("/Software Engineering/Python/AI/Machine Learning/TensorFlow", "TensorFlow for Machine Learning.epub") - .addLibraryFile("/Software Engineering/Python/AI/Machine Learning/TensorFlow", "sources.zip") - .addLibraryFile("/Software Engineering/Python/Flask/Flask Web Development", "Flask Web Development.pdf") - .addLibraryFile("/Software Engineering/Python/Flask/Flask Web Development", "Flask Web Development.epub") - // Comics Marvel - .addLibraryFile("/Comics/Marvel/Batman/Volume 1", "Batman v1.cbr") - .addLibraryFile("/Comics/Marvel/Batman/Volume 2", "Batman v2.cbr") - .addLibraryFile("/Comics/Marvel/Spiderman/Volume 1", "Spiderman v1.cbz") - .addLibraryFile("/Comics/Marvel/Spiderman/Volume 2", "Spiderman v2.cbz") - // Comics DC - .addLibraryFile("/Comics/DC/Superman/Volume 1", "Superman v1.cbr") - .addLibraryFile("/Comics/DC/Superman/Volume 1", "Poster.jpg") - .addLibraryFile("/Comics/DC/Superman/Volume 2", "Superman v2.cbr") - // Manga - .addLibraryFile("/Manga/One Piece/Volume 1", "One Piece v1.cbz") - .addLibraryFile("/Manga/One Piece/Volume 2", "One Piece v2.cbz") - .addLibraryFile("/Manga/Naruto/Volume 1", "Naruto v1.cbr") - .addLibraryFile("/Manga/Naruto/Volume 2", "Naruto v2.cbr"); - - // When - processor.processLibraryFiles(libraryTestBuilder.getLibraryFiles(), libraryTestBuilder.getLibraryEntity()); - - // Then - assertThat(libraryTestBuilder) - .hasBooks( - "Accounting 101", "Anatomy 101", "How to Repair", - "Design Patterns", "Effective Java", - "PyTorch for Machine Learning", "TensorFlow for Machine Learning", - "Flask Web Development", - "Batman v1", "Batman v2", - "Spiderman v1", "Spiderman v2", - "Superman v1", "Superman v2", - "One Piece v1", "One Piece v2", - "Naruto v1", "Naruto v2") - // Basic books - .bookHasAdditionalFormats("Accounting 101", BookFileType.PDF) - .bookHasNoSupplementaryFiles("Anatomy 101") - .bookHasAdditionalFormats("How to Repair", BookFileType.PDF) - // Software Engineering books - .bookHasAdditionalFormats("Design Patterns", BookFileType.PDF) - .bookHasSupplementaryFiles("Design Patterns", "Design Patterns.zip") - .bookHasAdditionalFormats("Effective Java", BookFileType.PDF) - .bookHasSupplementaryFiles("Effective Java", "Effective Java.zip") - .bookHasAdditionalFormats("PyTorch for Machine Learning", BookFileType.PDF) - .bookHasSupplementaryFiles("PyTorch for Machine Learning", "sources.zip") - .bookHasAdditionalFormats("TensorFlow for Machine Learning", BookFileType.PDF) - .bookHasSupplementaryFiles("TensorFlow for Machine Learning", "sources.zip") - .bookHasAdditionalFormats("Flask Web Development", BookFileType.PDF) - // Comics Marvel - .bookHasNoAdditionalFiles("Batman v1") - .bookHasNoAdditionalFiles("Batman v2") - .bookHasNoAdditionalFiles("Spiderman v1") - .bookHasNoAdditionalFiles("Spiderman v2") - // Comics DC - .bookHasSupplementaryFiles("Superman v1", "Poster.jpg") - .bookHasNoAdditionalFiles("Superman v2") - // Manga - .bookHasNoAdditionalFiles("One Piece v1") - .bookHasNoAdditionalFiles("One Piece v2") - .bookHasNoAdditionalFiles("Naruto v1") - .bookHasNoAdditionalFiles("Naruto v2"); - } -} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorSimpleTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorSimpleTest.java deleted file mode 100644 index f3ac2af29..000000000 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorSimpleTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.adityachandel.booklore.service.library; - -import com.adityachandel.booklore.model.enums.LibraryScanMode; -import com.adityachandel.booklore.repository.BookAdditionalFileRepository; -import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.event.AdminEventBroadcaster; -import com.adityachandel.booklore.service.event.BookEventBroadcaster; -import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -class FolderAsBookFileProcessorSimpleTest { - - @Test - void getScanMode_shouldReturnFolderAsBook() { - BookRepository bookRepository = mock(BookRepository.class); - BookAdditionalFileRepository bookAdditionalFileRepository = mock(BookAdditionalFileRepository.class); - AdminEventBroadcaster adminEventBroadcaster = mock(AdminEventBroadcaster.class); - BookEventBroadcaster bookEventBroadcaster = mock(BookEventBroadcaster.class); - BookFileProcessorRegistry bookFileProcessorRegistry = mock(BookFileProcessorRegistry.class); - - FolderAsBookFileProcessor processor = new FolderAsBookFileProcessor( - bookRepository, bookAdditionalFileRepository, bookEventBroadcaster, adminEventBroadcaster, bookFileProcessorRegistry); - - assertThat(processor.getScanMode()).isEqualTo(LibraryScanMode.FOLDER_AS_BOOK); - } - - @Test - void supportsSupplementaryFiles_shouldReturnTrue() { - BookRepository bookRepository = mock(BookRepository.class); - BookAdditionalFileRepository bookAdditionalFileRepository = mock(BookAdditionalFileRepository.class); - AdminEventBroadcaster adminEventBroadcaster = mock(AdminEventBroadcaster.class); - BookEventBroadcaster bookEventBroadcaster = mock(BookEventBroadcaster.class); - BookFileProcessorRegistry bookFileProcessorRegistry = mock(BookFileProcessorRegistry.class); - - FolderAsBookFileProcessor processor = new FolderAsBookFileProcessor( - bookRepository, bookAdditionalFileRepository, bookEventBroadcaster, adminEventBroadcaster, bookFileProcessorRegistry); - - assertThat(processor.supportsSupplementaryFiles()).isTrue(); - } -} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorTest.java deleted file mode 100644 index 4fabeafef..000000000 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FolderAsBookFileProcessorTest.java +++ /dev/null @@ -1,439 +0,0 @@ -package com.adityachandel.booklore.service.library; - -import com.adityachandel.booklore.model.FileProcessResult; -import com.adityachandel.booklore.model.dto.Book; -import com.adityachandel.booklore.model.dto.settings.LibraryFile; -import com.adityachandel.booklore.model.entity.*; -import com.adityachandel.booklore.model.enums.BookFileType; -import com.adityachandel.booklore.model.enums.FileProcessStatus; -import com.adityachandel.booklore.model.enums.LibraryScanMode; -import com.adityachandel.booklore.service.event.BookEventBroadcaster; -import com.adityachandel.booklore.service.event.AdminEventBroadcaster; -import com.adityachandel.booklore.repository.BookAdditionalFileRepository; -import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.file.FileFingerprint; -import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; -import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; -import com.adityachandel.booklore.util.FileUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.*; -import org.mockito.junit.jupiter.MockitoExtension; - -import java.nio.file.Path; -import java.security.MessageDigest; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) -class FolderAsBookFileProcessorTest { - - @Mock - private BookRepository bookRepository; - - @Mock - private BookAdditionalFileRepository bookAdditionalFileRepository; - - @Mock - private BookEventBroadcaster bookEventBroadcaster; - - @Mock - private AdminEventBroadcaster adminEventBroadcaster; - - @Mock - private BookFileProcessorRegistry bookFileProcessorRegistry; - - @Mock - private BookFileProcessor mockBookFileProcessor; - - @InjectMocks - private FolderAsBookFileProcessor processor; - - @Captor - private ArgumentCaptor additionalFileCaptor; - - private MockedStatic fileUtilsMock; - private MockedStatic fileFingerprintMock; - - @BeforeEach - void setUp() { - fileUtilsMock = mockStatic(FileUtils.class); - fileFingerprintMock = mockStatic(FileFingerprint.class); - // Setup common FileUtils mocks for all tests - fileUtilsMock.when(() -> FileUtils.getFileSizeInKb(any(Path.class))).thenReturn(100L); - fileFingerprintMock.when(() -> FileFingerprint.generateHash(any(Path.class))) - .then(invocation -> { - MessageDigest digest = MessageDigest.getInstance("MD5"); - Path path = invocation.getArgument(0); - byte[] hash = digest.digest(path.toString().getBytes()); - StringBuilder hexString = new StringBuilder(); - for (byte b : hash) { - String hex = Integer.toHexString(0xff & b); - if (hex.length() == 1) hexString.append('0'); - hexString.append(hex); - } - return hexString.toString(); - }); - } - - @AfterEach - void tearDown() { - fileUtilsMock.close(); - fileFingerprintMock.close(); - } - - @Test - void getScanMode_shouldReturnFolderAsBook() { - assertThat(processor.getScanMode()).isEqualTo(LibraryScanMode.FOLDER_AS_BOOK); - } - - @Test - void supportsSupplementaryFiles_shouldReturnTrue() { - assertThat(processor.supportsSupplementaryFiles()).isTrue(); - } - - @Test - void processLibraryFiles_shouldCreateNewBookFromDirectory() { - // Given - LibraryEntity libraryEntity = createLibraryEntity(); - List libraryFiles = createLibraryFilesInSameDirectory(); - - Book createdBook = Book.builder() - .id(1L) - .fileName("book.pdf") - .bookType(BookFileType.PDF) - .build(); - - BookEntity bookEntity = createBookEntity(1L, "book.pdf", "books"); - - when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), anyString())) - .thenReturn(new ArrayList<>()); - when(bookFileProcessorRegistry.getProcessorOrThrow(BookFileType.PDF)) - .thenReturn(mockBookFileProcessor); - when(mockBookFileProcessor.processFile(any(LibraryFile.class))) - .thenReturn(new FileProcessResult(createdBook, FileProcessStatus.NEW)); - when(bookRepository.getReferenceById(createdBook.getId())) - .thenReturn(bookEntity); - when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString())) - .thenReturn(Optional.empty()); - - // When - processor.processLibraryFiles(libraryFiles, libraryEntity); - - // Then - verify(mockBookFileProcessor).processFile(any(LibraryFile.class)); - verify(bookEventBroadcaster).broadcastBookAddEvent(createdBook); - verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString()); - verify(bookAdditionalFileRepository, times(2)).save(additionalFileCaptor.capture()); - - List capturedFiles = additionalFileCaptor.getAllValues(); - assertThat(capturedFiles).hasSize(2); - assertThat(capturedFiles).extracting(BookFileEntity::getFileName) - .containsExactlyInAnyOrder("book.epub", "cover.jpg"); - assertThat(capturedFiles).extracting(BookFileEntity::isBookFormat) - .containsExactlyInAnyOrder(true, false); - } - - @Test - void processLibraryFiles_shouldProcessExistingBook() { - // Given - LibraryEntity libraryEntity = createLibraryEntity(); - List libraryFiles = createLibraryFilesInSameDirectory() - .stream() - .filter(f -> !f.getFileName().equals("book.pdf")) - .toList(); - - BookEntity existingBook = createBookEntity(1L, "book.pdf", "books"); - - when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), eq("books"))) - .thenReturn(List.of(existingBook)); - when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString())) - .thenReturn(Optional.empty()); - - // When - processor.processLibraryFiles(libraryFiles, libraryEntity); - - // Then - verify(mockBookFileProcessor, never()).processFile(any()); - verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any()); - verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString()); - verify(bookAdditionalFileRepository, times(2)).save(additionalFileCaptor.capture()); - - List capturedFiles = additionalFileCaptor.getAllValues(); - assertThat(capturedFiles).hasSize(2); - assertThat(capturedFiles).extracting(BookFileEntity::getFileName) - .containsExactlyInAnyOrder("book.epub", "cover.jpg"); - } - - @Test - void processLibraryFiles_shouldProcessFilesWithParentBook() { - // Given - LibraryEntity libraryEntity = createLibraryEntity(); - List libraryFiles = List.of( - createLibraryFile("file1.txt", "books/chapter1"), - createLibraryFile("file2.txt", "books/chapter1") - ); - - BookEntity parentBook = createBookEntity(1L, "book.pdf", "books"); - - when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), eq("books/chapter1"))) - .thenReturn(new ArrayList<>()); - when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), eq("books"))) - .thenReturn(List.of(parentBook)); - when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString())) - .thenReturn(Optional.empty()); - - // When - processor.processLibraryFiles(libraryFiles, libraryEntity); - - // Then - verify(mockBookFileProcessor, never()).processFile(any()); - verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any()); - verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString()); - verify(bookAdditionalFileRepository, times(2)).save(additionalFileCaptor.capture()); - - List capturedFiles = additionalFileCaptor.getAllValues(); - assertThat(capturedFiles).hasSize(2); - assertThat(capturedFiles).extracting(BookFileEntity::isBookFormat) - .containsOnly(false); - } - - @Test - void processLibraryFiles_shouldRespectDefaultBookFormat() { - // Given - LibraryEntity libraryEntity = createLibraryEntity(); - libraryEntity.setDefaultBookFormat(BookFileType.EPUB); - - List libraryFiles = List.of( - createLibraryFile("book.pdf", "books", BookFileType.PDF), - createLibraryFile("book.epub", "books", BookFileType.EPUB), - createLibraryFile("book.cbz", "books", BookFileType.CBX) - ); - - Book createdBook = Book.builder() - .id(1L) - .fileName("book.epub") - .bookType(BookFileType.EPUB) - .build(); - - BookEntity bookEntity = createBookEntity(1L, "book.epub", "books"); - - when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), anyString())) - .thenReturn(new ArrayList<>()); - when(bookFileProcessorRegistry.getProcessorOrThrow(BookFileType.EPUB)) - .thenReturn(mockBookFileProcessor); - when(mockBookFileProcessor.processFile(argThat(file -> file.getFileName().equals("book.epub")))) - .thenReturn(new FileProcessResult(createdBook, FileProcessStatus.NEW)); - when(bookRepository.getReferenceById(createdBook.getId())) - .thenReturn(bookEntity); - when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString())) - .thenReturn(Optional.empty()); - - // When - processor.processLibraryFiles(libraryFiles, libraryEntity); - - // Then - verify(mockBookFileProcessor).processFile(argThat(file -> file.getFileName().equals("book.epub"))); - verify(bookEventBroadcaster).broadcastBookAddEvent(createdBook); - verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString()); - verify(bookAdditionalFileRepository, times(2)).save(additionalFileCaptor.capture()); - - List capturedFiles = additionalFileCaptor.getAllValues(); - assertThat(capturedFiles).extracting(BookFileEntity::getFileName) - .containsExactlyInAnyOrder("book.pdf", "book.cbz"); - } - - @Test - void processLibraryFiles_shouldUseDefaultPriorityWhenNoDefaultFormat() { - // Given - LibraryEntity libraryEntity = createLibraryEntity(); - libraryEntity.setDefaultBookFormat(null); - - List libraryFiles = List.of( - createLibraryFile("book.epub", "books", BookFileType.EPUB), - createLibraryFile("book.cbz", "books", BookFileType.CBX), - createLibraryFile("book.pdf", "books", BookFileType.PDF) - ); - - Book createdBook = Book.builder() - .id(1L) - .fileName("book.pdf") - .bookType(BookFileType.PDF) - .build(); - - BookEntity bookEntity = createBookEntity(1L, "book.pdf", "books"); - - when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), anyString())) - .thenReturn(new ArrayList<>()); - when(bookFileProcessorRegistry.getProcessorOrThrow(BookFileType.PDF)) - .thenReturn(mockBookFileProcessor); - when(mockBookFileProcessor.processFile(argThat(file -> file.getFileName().equals("book.pdf")))) - .thenReturn(new FileProcessResult(createdBook, FileProcessStatus.NEW)); - when(bookRepository.getReferenceById(createdBook.getId())) - .thenReturn(bookEntity); - when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString())) - .thenReturn(Optional.empty()); - - // When - processor.processLibraryFiles(libraryFiles, libraryEntity); - - // Then - verify(mockBookFileProcessor).processFile(argThat(file -> file.getFileName().equals("book.pdf"))); - verify(bookEventBroadcaster).broadcastBookAddEvent(createdBook); - verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString()); - } - - @Test - void processLibraryFiles_shouldSkipExistingAdditionalFiles() { - // Given - LibraryEntity libraryEntity = createLibraryEntity(); - List libraryFiles = createLibraryFilesInSameDirectory() - .stream() - .filter(f -> !f.getFileName().equals("book.pdf")) - .toList(); - - BookEntity existingBook = createBookEntity(1L, "book.pdf", "books"); - BookFileEntity existingAdditionalFile = BookFileEntity.builder() - .id(1L) - .book(existingBook) - .fileName("book.epub") - .fileSubPath("books") - .isBookFormat(true) - .bookType(BookFileType.EPUB) - .build(); - - when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), eq("books"))) - .thenReturn(List.of(existingBook)); - when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), eq("books"), eq("book.epub"))) - .thenReturn(Optional.of(existingAdditionalFile)); - when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), eq("books"), eq("cover.jpg"))) - .thenReturn(Optional.empty()); - - // When - processor.processLibraryFiles(libraryFiles, libraryEntity); - - // Then - verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any()); - verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString()); - verify(bookAdditionalFileRepository, times(1)).save(additionalFileCaptor.capture()); - - BookFileEntity capturedFile = additionalFileCaptor.getValue(); - assertThat(capturedFile.getFileName()).isEqualTo("cover.jpg"); - } - - @Test - void processLibraryFiles_shouldHandleEmptyDirectory() { - // Given - LibraryEntity libraryEntity = createLibraryEntity(); - List libraryFiles = List.of( - createLibraryFile("readme.txt", "docs"), - createLibraryFile("notes.txt", "docs") - ); - - when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), anyString())) - .thenReturn(new ArrayList<>()); - - // When - processor.processLibraryFiles(libraryFiles, libraryEntity); - - // Then - verify(mockBookFileProcessor, never()).processFile(any()); - verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any()); - verify(adminEventBroadcaster, never()).broadcastAdminEvent(anyString()); - verify(bookAdditionalFileRepository, never()).save(any()); - } - - @Test - void processLibraryFiles_shouldHandleProcessorError() { - // Given - LibraryEntity libraryEntity = createLibraryEntity(); - List libraryFiles = List.of( - createLibraryFile("book.pdf", "books", BookFileType.PDF) - ); - - when(bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(anyLong(), anyString())) - .thenReturn(new ArrayList<>()); - when(bookFileProcessorRegistry.getProcessorOrThrow(BookFileType.PDF)) - .thenReturn(mockBookFileProcessor); - when(mockBookFileProcessor.processFile(any(LibraryFile.class))) - .thenThrow(new RuntimeException("Processing error")); - - // When - processor.processLibraryFiles(libraryFiles, libraryEntity); - - // Then - verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any()); - verify(bookAdditionalFileRepository, never()).save(any()); - verify(adminEventBroadcaster).broadcastAdminEvent(anyString()); - } - - // Helper methods - private LibraryEntity createLibraryEntity() { - LibraryEntity library = new LibraryEntity(); - library.setId(1L); - library.setName("Test Library"); - library.setScanMode(LibraryScanMode.FOLDER_AS_BOOK); - - LibraryPathEntity path = new LibraryPathEntity(); - path.setId(1L); - path.setPath("/test/library"); - library.setLibraryPaths(List.of(path)); - - return library; - } - - private List createLibraryFilesInSameDirectory() { - return List.of( - createLibraryFile("book.pdf", "books", BookFileType.PDF), - createLibraryFile("book.epub", "books", BookFileType.EPUB), - createLibraryFile("cover.jpg", "books") - ); - } - - private LibraryFile createLibraryFile(String fileName, String subPath) { - return createLibraryFile(fileName, subPath, null); - } - - private LibraryFile createLibraryFile(String fileName, String subPath, BookFileType bookFileType) { - LibraryPathEntity libraryPath = new LibraryPathEntity(); - libraryPath.setId(1L); - libraryPath.setPath("/test/library"); - - return LibraryFile.builder() - .libraryEntity(new LibraryEntity()) - .libraryPathEntity(libraryPath) - .fileName(fileName) - .fileSubPath(subPath) - .bookFileType(bookFileType) - .build(); - } - - private BookEntity createBookEntity(Long id, String fileName, String subPath) { - BookEntity book = new BookEntity(); - book.setId(id); - book.setAddedOn(Instant.parse("2025-01-01T12:00:00Z")); - - book.setBookFiles(new ArrayList<>()); - - LibraryPathEntity libraryPath = new LibraryPathEntity(); - libraryPath.setId(1L); - libraryPath.setPath("/test/library"); - book.setLibraryPath(libraryPath); - - BookFileEntity primaryFile = new BookFileEntity(); - primaryFile.setBook(book); - primaryFile.setFileName(fileName); - primaryFile.setFileSubPath(subPath); - primaryFile.setBookType(BookFileType.PDF); - book.getBookFiles().add(primaryFile); - - return book; - } -} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryFileHelperTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryFileHelperTest.java index fe2c3f795..efc36127f 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryFileHelperTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryFileHelperTest.java @@ -1,25 +1,17 @@ package com.adityachandel.booklore.service.library; -import com.adityachandel.booklore.model.dto.LibraryPath; import com.adityachandel.booklore.model.dto.settings.LibraryFile; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; -import com.adityachandel.booklore.model.enums.LibraryScanMode; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; -import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFilePermissions; -import java.util.Collection; -import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -29,9 +21,6 @@ class LibraryFileHelperTest { @TempDir Path tempDir; - @Mock - private LibraryFileProcessor processor; - @Test void testGetLibraryFiles_HandlesInaccessibleDirectories() throws IOException { LibraryFileHelper libraryFileHelper = new LibraryFileHelper(); @@ -47,12 +36,11 @@ class LibraryFileHelperTest { LibraryEntity testLibrary = LibraryEntity.builder() .name("Test Library") .icon("book") - .scanMode(LibraryScanMode.FILE_AS_BOOK) .watch(false) .libraryPaths(List.of(libraryPath)) .build(); - List libraryFiles = libraryFileHelper.getLibraryFiles(testLibrary, processor); + List libraryFiles = libraryFileHelper.getLibraryFiles(testLibrary); assertEquals(libraryFiles.stream().map(LibraryFile::getFileName).sorted().toList(), List.of("happy.epub", "zzzz_happ.epub")); } -} \ No newline at end of file +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryProcessingServiceRegressionTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryProcessingServiceRegressionTest.java index 6c31bb9e6..7957a259c 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryProcessingServiceRegressionTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryProcessingServiceRegressionTest.java @@ -3,7 +3,6 @@ package com.adityachandel.booklore.service.library; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; -import com.adityachandel.booklore.model.enums.LibraryScanMode; import com.adityachandel.booklore.repository.BookAdditionalFileRepository; import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.service.NotificationService; @@ -21,6 +20,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Optional; import static org.mockito.ArgumentMatchers.any; @@ -36,7 +36,7 @@ class LibraryProcessingServiceRegressionTest { @Mock private BookAdditionalFileRepository bookAdditionalFileRepository; @Mock - private LibraryFileProcessorRegistry fileProcessorRegistry; + private FileAsBookProcessor fileAsBookProcessor; @Mock private BookRestorationService bookRestorationService; @Mock @@ -44,9 +44,9 @@ class LibraryProcessingServiceRegressionTest { @Mock private LibraryFileHelper libraryFileHelper; @Mock - private EntityManager entityManager; + private BookGroupingService bookGroupingService; @Mock - private LibraryFileProcessor libraryFileProcessor; + private EntityManager entityManager; private LibraryProcessingService libraryProcessingService; @@ -56,16 +56,17 @@ class LibraryProcessingServiceRegressionTest { libraryRepository, notificationService, bookAdditionalFileRepository, - fileProcessorRegistry, + fileAsBookProcessor, bookRestorationService, bookDeletionService, libraryFileHelper, + bookGroupingService, entityManager ); } @Test - void rescanLibrary_shouldThrowException_whenBookHasNoFiles(@TempDir Path tempDir) throws IOException { + void rescanLibrary_shouldNotDeleteFilelessBooks(@TempDir Path tempDir) throws IOException { long libraryId = 1L; Path accessiblePath = tempDir.resolve("accessible"); Files.createDirectory(accessiblePath); @@ -73,40 +74,37 @@ class LibraryProcessingServiceRegressionTest { LibraryEntity libraryEntity = new LibraryEntity(); libraryEntity.setId(libraryId); libraryEntity.setName("Test Library"); - libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK); LibraryPathEntity pathEntity = new LibraryPathEntity(); pathEntity.setId(10L); pathEntity.setPath(accessiblePath.toString()); libraryEntity.setLibraryPaths(List.of(pathEntity)); - BookEntity bookWithNoFiles = new BookEntity(); - bookWithNoFiles.setId(1L); - bookWithNoFiles.setLibraryPath(pathEntity); - bookWithNoFiles.setBookFiles(Collections.emptyList()); // Empty files list - - libraryEntity.setBookEntities(List.of(bookWithNoFiles)); + // Create a fileless book (e.g., physical book) + BookEntity filelessBook = new BookEntity(); + filelessBook.setId(1L); + filelessBook.setLibraryPath(pathEntity); + filelessBook.setBookFiles(Collections.emptyList()); + + libraryEntity.setBookEntities(List.of(filelessBook)); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor); - // We need at least one file so it doesn't think the library is offline - when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of( + when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of( com.adityachandel.booklore.model.dto.settings.LibraryFile.builder() .libraryPathEntity(pathEntity) .fileName("other.epub") .fileSubPath("") .build() )); + when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class))) + .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build(); - // Should not throw exception anymore libraryProcessingService.rescanLibrary(context); - // Verify that the book with no files (ID 1) was detected as deleted - verify(bookDeletionService).processDeletedLibraryFiles( - argThat(list -> list.contains(1L)), - any() - ); + // Fileless books should NOT be marked as deleted - they are intentionally without files + verify(bookDeletionService, never()).processDeletedLibraryFiles(any(), any()); } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryProcessingServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryProcessingServiceTest.java index b8fed3270..ed63da732 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryProcessingServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryProcessingServiceTest.java @@ -6,7 +6,6 @@ import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookFileEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; -import com.adityachandel.booklore.model.enums.LibraryScanMode; import com.adityachandel.booklore.repository.BookAdditionalFileRepository; import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.service.NotificationService; @@ -24,7 +23,9 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @@ -42,7 +43,7 @@ class LibraryProcessingServiceTest { @Mock private BookAdditionalFileRepository bookAdditionalFileRepository; @Mock - private LibraryFileProcessorRegistry fileProcessorRegistry; + private FileAsBookProcessor fileAsBookProcessor; @Mock private BookRestorationService bookRestorationService; @Mock @@ -50,9 +51,9 @@ class LibraryProcessingServiceTest { @Mock private LibraryFileHelper libraryFileHelper; @Mock - private EntityManager entityManager; + private BookGroupingService bookGroupingService; @Mock - private LibraryFileProcessor libraryFileProcessor; + private EntityManager entityManager; private LibraryProcessingService libraryProcessingService; @@ -62,10 +63,11 @@ class LibraryProcessingServiceTest { libraryRepository, notificationService, bookAdditionalFileRepository, - fileProcessorRegistry, + fileAsBookProcessor, bookRestorationService, bookDeletionService, libraryFileHelper, + bookGroupingService, entityManager ); } @@ -76,7 +78,6 @@ class LibraryProcessingServiceTest { LibraryEntity libraryEntity = new LibraryEntity(); libraryEntity.setId(libraryId); libraryEntity.setName("Test Library"); - libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK); LibraryPathEntity pathEntity = new LibraryPathEntity(); pathEntity.setId(10L); @@ -92,9 +93,7 @@ class LibraryProcessingServiceTest { libraryEntity.setBookEntities(List.of(existingBook)); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor); - // Library files found on disk (1 existing, 1 new) LibraryFile existingFile = LibraryFile.builder() .libraryEntity(libraryEntity) .libraryPathEntity(pathEntity) @@ -109,13 +108,24 @@ class LibraryProcessingServiceTest { .fileName("book2.epub") .build(); - when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(existingFile, newFile)); + when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(existingFile, newFile)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + // Mock grouping service to pass through the files + when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity))) + .thenAnswer(invocation -> { + List files = invocation.getArgument(0); + Map> result = new LinkedHashMap<>(); + for (LibraryFile f : files) { + result.put(f.getFileName(), List.of(f)); + } + return result; + }); + libraryProcessingService.processLibrary(libraryId); ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); - verify(libraryFileProcessor).processLibraryFiles(captor.capture(), eq(libraryEntity)); + verify(bookGroupingService).groupForInitialScan(captor.capture(), eq(libraryEntity)); List processedFiles = captor.getValue(); @@ -129,7 +139,6 @@ class LibraryProcessingServiceTest { LibraryEntity libraryEntity = new LibraryEntity(); libraryEntity.setId(libraryId); libraryEntity.setName("Test Library"); - libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK); LibraryPathEntity pathEntity = new LibraryPathEntity(); pathEntity.setId(10L); @@ -145,7 +154,6 @@ class LibraryProcessingServiceTest { libraryEntity.setBookEntities(List.of(existingBook)); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor); LibraryFile existingFile = LibraryFile.builder() .libraryEntity(libraryEntity) @@ -154,13 +162,14 @@ class LibraryProcessingServiceTest { .fileName("book1.epub") .build(); - when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(existingFile)); + when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(existingFile)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity))).thenReturn(Collections.emptyMap()); libraryProcessingService.processLibrary(libraryId); ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); - verify(libraryFileProcessor).processLibraryFiles(captor.capture(), eq(libraryEntity)); + verify(bookGroupingService).groupForInitialScan(captor.capture(), eq(libraryEntity)); assertThat(captor.getValue()).isEmpty(); } @@ -171,15 +180,13 @@ class LibraryProcessingServiceTest { LibraryEntity libraryEntity = new LibraryEntity(); libraryEntity.setId(libraryId); libraryEntity.setName("Test Library"); - libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK); - libraryEntity.setBookEntities(Collections.emptyList()); // No existing books + libraryEntity.setBookEntities(Collections.emptyList()); LibraryPathEntity pathEntity = new LibraryPathEntity(); pathEntity.setId(10L); pathEntity.setPath("/library"); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor); LibraryFile newFile1 = LibraryFile.builder() .libraryEntity(libraryEntity) @@ -194,13 +201,22 @@ class LibraryProcessingServiceTest { .fileName("book2.epub") .build(); - when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(newFile1, newFile2)); + when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(newFile1, newFile2)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity))) + .thenAnswer(invocation -> { + List files = invocation.getArgument(0); + Map> result = new LinkedHashMap<>(); + for (LibraryFile f : files) { + result.put(f.getFileName(), List.of(f)); + } + return result; + }); libraryProcessingService.processLibrary(libraryId); ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); - verify(libraryFileProcessor).processLibraryFiles(captor.capture(), eq(libraryEntity)); + verify(bookGroupingService).groupForInitialScan(captor.capture(), eq(libraryEntity)); assertThat(captor.getValue()).hasSize(2); } @@ -211,7 +227,6 @@ class LibraryProcessingServiceTest { LibraryEntity libraryEntity = new LibraryEntity(); libraryEntity.setId(libraryId); libraryEntity.setName("Test Library"); - libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK); libraryEntity.setBookEntities(Collections.emptyList()); LibraryPathEntity pathEntity = new LibraryPathEntity(); @@ -219,7 +234,6 @@ class LibraryProcessingServiceTest { pathEntity.setPath("/library"); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor); LibraryFile newFileInSub = LibraryFile.builder() .libraryEntity(libraryEntity) @@ -228,13 +242,22 @@ class LibraryProcessingServiceTest { .fileName("book1.epub") .build(); - when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(newFileInSub)); + when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(newFileInSub)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity))) + .thenAnswer(invocation -> { + List files = invocation.getArgument(0); + Map> result = new LinkedHashMap<>(); + for (LibraryFile f : files) { + result.put(f.getFileName(), List.of(f)); + } + return result; + }); libraryProcessingService.processLibrary(libraryId); ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); - verify(libraryFileProcessor).processLibraryFiles(captor.capture(), eq(libraryEntity)); + verify(bookGroupingService).groupForInitialScan(captor.capture(), eq(libraryEntity)); List processedFiles = captor.getValue(); assertThat(processedFiles).hasSize(1); @@ -248,7 +271,6 @@ class LibraryProcessingServiceTest { LibraryEntity libraryEntity = new LibraryEntity(); libraryEntity.setId(libraryId); libraryEntity.setName("Test Library"); - libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK); libraryEntity.setBookEntities(Collections.emptyList()); LibraryPathEntity pathEntity = new LibraryPathEntity(); @@ -256,9 +278,7 @@ class LibraryProcessingServiceTest { pathEntity.setPath("/library"); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor); - // A file that exists as an additional file (e.g. cover.jpg, or a misidentified book) LibraryFile additionalFileAsLibraryFile = LibraryFile.builder() .libraryEntity(libraryEntity) .libraryPathEntity(pathEntity) @@ -268,25 +288,26 @@ class LibraryProcessingServiceTest { BookEntity parentBook = new BookEntity(); parentBook.setLibraryPath(pathEntity); - + BookFileEntity additionalFileEntity = new BookFileEntity(); - additionalFileEntity.setBook(parentBook); // Links to library path + additionalFileEntity.setBook(parentBook); additionalFileEntity.setFileSubPath(""); additionalFileEntity.setFileName("extra.pdf"); - when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(additionalFileAsLibraryFile)); + when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(additionalFileAsLibraryFile)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(List.of(additionalFileEntity)); + when(bookGroupingService.groupForInitialScan(anyList(), eq(libraryEntity))).thenReturn(Collections.emptyMap()); libraryProcessingService.processLibrary(libraryId); ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); - verify(libraryFileProcessor).processLibraryFiles(captor.capture(), eq(libraryEntity)); + verify(bookGroupingService).groupForInitialScan(captor.capture(), eq(libraryEntity)); assertThat(captor.getValue()).isEmpty(); } @Test - void rescanLibrary_shouldNotDeleteNonBookFiles_whenProcessorDoesNotSupportSupplementaryFiles(@TempDir Path tempDir) throws IOException { + void rescanLibrary_shouldDeleteRemovedBookFormatAdditionalFiles(@TempDir Path tempDir) throws IOException { long libraryId = 1L; Path accessiblePath = tempDir.resolve("library"); Files.createDirectory(accessiblePath); @@ -294,7 +315,6 @@ class LibraryProcessingServiceTest { LibraryEntity libraryEntity = new LibraryEntity(); libraryEntity.setId(libraryId); libraryEntity.setName("Test Library"); - libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK); LibraryPathEntity pathEntity = new LibraryPathEntity(); pathEntity.setId(10L); @@ -331,9 +351,8 @@ class LibraryProcessingServiceTest { libraryEntity.setBookEntities(List.of(book)); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor); - when(libraryFileProcessor.supportsSupplementaryFiles()).thenReturn(false); + // Only epub exists on disk, pdf was removed LibraryFile epubOnDisk = LibraryFile.builder() .libraryEntity(libraryEntity) .libraryPathEntity(pathEntity) @@ -341,30 +360,27 @@ class LibraryProcessingServiceTest { .fileName("book.epub") .build(); - LibraryFile pdfOnDisk = LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(pathEntity) - .fileSubPath("author/title") - .fileName("book.pdf") - .build(); - - when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(epubOnDisk, pdfOnDisk)); + when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(epubOnDisk)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(List.of(epub, pdf, image)); + when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity))) + .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); libraryProcessingService.rescanLibrary(RescanLibraryContext.builder().libraryId(libraryId).build()); - verify(bookDeletionService, never()).deleteRemovedAdditionalFiles(any()); + // pdf (book format) should be deleted; image (non-book format) should NOT be deleted + ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); + verify(bookDeletionService).deleteRemovedAdditionalFiles(captor.capture()); + assertThat(captor.getValue()).containsExactly(2L); } @Test - void rescanLibrary_shouldAbortWhenPathNotAccessible(@TempDir Path tempDir) throws IOException { + void rescanLibrary_shouldAbortWhenPathNotAccessible(@TempDir Path tempDir) { long libraryId = 1L; Path nonExistentPath = tempDir.resolve("non_existent_path"); LibraryEntity libraryEntity = new LibraryEntity(); libraryEntity.setId(libraryId); libraryEntity.setName("Test Library"); - libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK); LibraryPathEntity pathEntity = new LibraryPathEntity(); pathEntity.setId(10L); @@ -373,7 +389,6 @@ class LibraryProcessingServiceTest { libraryEntity.setBookEntities(Collections.emptyList()); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor); RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build(); @@ -394,7 +409,6 @@ class LibraryProcessingServiceTest { LibraryEntity libraryEntity = new LibraryEntity(); libraryEntity.setId(libraryId); libraryEntity.setName("Test Library"); - libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK); LibraryPathEntity pathEntity = new LibraryPathEntity(); pathEntity.setId(10L); @@ -412,8 +426,7 @@ class LibraryProcessingServiceTest { libraryEntity.setBookEntities(List.of(existingBook)); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor); - when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(Collections.emptyList()); + when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList()); RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build(); @@ -434,7 +447,6 @@ class LibraryProcessingServiceTest { LibraryEntity libraryEntity = new LibraryEntity(); libraryEntity.setId(libraryId); libraryEntity.setName("Test Library"); - libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK); LibraryPathEntity pathEntity = new LibraryPathEntity(); pathEntity.setId(10L); @@ -459,9 +471,10 @@ class LibraryProcessingServiceTest { .build(); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor); - when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(List.of(fileOnDisk)); + when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk)); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity))) + .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build(); @@ -479,7 +492,6 @@ class LibraryProcessingServiceTest { LibraryEntity libraryEntity = new LibraryEntity(); libraryEntity.setId(libraryId); libraryEntity.setName("Test Library"); - libraryEntity.setScanMode(LibraryScanMode.FILE_AS_BOOK); LibraryPathEntity pathEntity = new LibraryPathEntity(); pathEntity.setId(10L); @@ -488,9 +500,10 @@ class LibraryProcessingServiceTest { libraryEntity.setBookEntities(Collections.emptyList()); when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); - when(fileProcessorRegistry.getProcessor(libraryEntity)).thenReturn(libraryFileProcessor); - when(libraryFileHelper.getLibraryFiles(libraryEntity, libraryFileProcessor)).thenReturn(Collections.emptyList()); + when(libraryFileHelper.getLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList()); when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity))) + .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build(); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/opds/OpdsFeedServiceMimeTypeTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/opds/OpdsFeedServiceMimeTypeTest.java index 5991a0c9d..2207b7a32 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/opds/OpdsFeedServiceMimeTypeTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/opds/OpdsFeedServiceMimeTypeTest.java @@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.opds; import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails; import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.BookFile; import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.LibraryPath; import com.adityachandel.booklore.model.dto.OpdsUserV2; @@ -190,27 +191,36 @@ class OpdsFeedServiceMimeTypeTest { @Test void testMimeTypeFromCachedArchiveType() { - Book book = createBook(BookFileType.CBX, "whatever.cbz"); - book.setArchiveType(ArchiveUtils.ArchiveType.RAR); // Simulate mismatched but cached type - + Book book = createBookWithArchiveType(BookFileType.CBX, "whatever.cbz", ArchiveUtils.ArchiveType.RAR); + mockBooksPage(book); String xml = opdsFeedService.generateCatalogFeed(request); - + // Should use cached type (RAR) even if filename is .cbz and no file exists (mocked logic) // Note: The logic in OpdsFeedService prioritizes cached type. - // However, my test creates a real file in other tests, but here I can skip file creation + // However, my test creates a real file in other tests, but here I can skip file creation // because the cached type check happens first. - + assertThat(xml).contains("type=\"application/vnd.comicbook-rar\""); } private Book createBook(BookFileType type, String fileName) { + return createBookWithArchiveType(type, fileName, null); + } + + private Book createBookWithArchiveType(BookFileType type, String fileName, ArchiveUtils.ArchiveType archiveType) { + String filePath = tempDir.resolve(fileName).toString(); return Book.builder() .id(1L) - .bookType(type) - .fileName(fileName) - .fileSubPath("") + .primaryFile(BookFile.builder() + .id(1L) + .bookType(type) + .fileName(fileName) + .filePath(filePath) + .fileSubPath("") + .archiveType(archiveType) + .build()) .libraryPath(LibraryPath.builder().path(tempDir.toString()).build()) .addedOn(Instant.now()) .metadata(BookMetadata.builder().title("Test Book").build()) diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/opds/OpdsFeedServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/opds/OpdsFeedServiceTest.java index 02ba4266a..3f3d232de 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/opds/OpdsFeedServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/opds/OpdsFeedServiceTest.java @@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.opds; import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails; import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.BookFile; import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.Library; import com.adityachandel.booklore.model.dto.OpdsUserV2; @@ -139,7 +140,7 @@ class OpdsFeedServiceTest { Book book = Book.builder() .id(10L) - .bookType(BookFileType.EPUB) + .primaryFile(BookFile.builder().id(1L).bookType(BookFileType.EPUB).build()) .addedOn(FIXED_INSTANT) .metadata(BookMetadata.builder() .title("Book Title") @@ -193,7 +194,7 @@ class OpdsFeedServiceTest { Book book = Book.builder() .id(11L) - .bookType(BookFileType.PDF) + .primaryFile(BookFile.builder().id(1L).bookType(BookFileType.PDF).build()) .addedOn(FIXED_INSTANT) .metadata(BookMetadata.builder().title("Recent Book").build()) .build(); @@ -231,7 +232,7 @@ class OpdsFeedServiceTest { Book book = Book.builder() .id(12L) - .bookType(BookFileType.EPUB) + .primaryFile(BookFile.builder().id(1L).bookType(BookFileType.EPUB).build()) .addedOn(FIXED_INSTANT) .metadata(BookMetadata.builder().title("Surprise Book").build()) .build(); @@ -391,7 +392,7 @@ class OpdsFeedServiceTest { Book book = Book.builder() .id(1L) - .bookType(BookFileType.EPUB) + .primaryFile(BookFile.builder().id(1L).bookType(BookFileType.EPUB).build()) .addedOn(FIXED_INSTANT) .metadata(BookMetadata.builder().title("Shelf Book").build()) .build(); @@ -426,7 +427,7 @@ class OpdsFeedServiceTest { Book book = Book.builder() .id(1L) - .bookType(BookFileType.EPUB) + .primaryFile(BookFile.builder().id(1L).bookType(BookFileType.EPUB).build()) .addedOn(FIXED_INSTANT) .metadata(BookMetadata.builder().title("Multi Shelf Book").build()) .build(); @@ -460,7 +461,7 @@ class OpdsFeedServiceTest { Book book = Book.builder() .id(1L) - .bookType(BookFileType.EPUB) + .primaryFile(BookFile.builder().id(1L).bookType(BookFileType.EPUB).build()) .addedOn(FIXED_INSTANT) .metadata(BookMetadata.builder().title("Fantasy Book").build()) .build(); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/progress/ReadingProgressServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/progress/ReadingProgressServiceTest.java new file mode 100644 index 000000000..662116379 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/progress/ReadingProgressServiceTest.java @@ -0,0 +1,309 @@ +package com.adityachandel.booklore.service.progress; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.exception.APIException; +import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.progress.EpubProgress; +import com.adityachandel.booklore.model.dto.progress.PdfProgress; +import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; +import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse; +import com.adityachandel.booklore.model.entity.*; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.model.enums.ReadStatus; +import com.adityachandel.booklore.model.enums.ResetProgressType; +import com.adityachandel.booklore.repository.*; +import com.adityachandel.booklore.service.kobo.KoboReadingStateService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.time.Instant; +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ReadingProgressServiceTest { + + @Mock + private UserBookProgressRepository userBookProgressRepository; + @Mock + private UserBookFileProgressRepository userBookFileProgressRepository; + @Mock + private BookRepository bookRepository; + @Mock + private BookFileRepository bookFileRepository; + @Mock + private UserRepository userRepository; + @Mock + private AuthenticationService authenticationService; + @Mock + private KoboReadingStateService koboReadingStateService; + + @InjectMocks + private ReadingProgressService readingProgressService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void fetchUserProgress_shouldReturnProgressMap() { + Long userId = 1L; + Set bookIds = Set.of(1L, 2L); + + BookEntity book1 = new BookEntity(); + book1.setId(1L); + BookEntity book2 = new BookEntity(); + book2.setId(2L); + + UserBookProgressEntity progress1 = new UserBookProgressEntity(); + progress1.setBook(book1); + UserBookProgressEntity progress2 = new UserBookProgressEntity(); + progress2.setBook(book2); + + when(userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds)) + .thenReturn(List.of(progress1, progress2)); + + Map result = readingProgressService.fetchUserProgress(userId, bookIds); + + assertEquals(2, result.size()); + assertEquals(progress1, result.get(1L)); + assertEquals(progress2, result.get(2L)); + } + + @Test + void fetchUserFileProgress_emptyBookIds_shouldReturnEmptyMap() { + Map result = + readingProgressService.fetchUserFileProgress(1L, Collections.emptySet()); + + assertTrue(result.isEmpty()); + verify(userBookFileProgressRepository, never()).findByUserIdAndBookFileBookIdIn(anyLong(), anySet()); + } + + @Test + void fetchUserFileProgress_shouldReturnMostRecentPerBook() { + Long userId = 1L; + Set bookIds = Set.of(1L); + + BookEntity book = new BookEntity(); + book.setId(1L); + + BookFileEntity bookFile1 = new BookFileEntity(); + bookFile1.setBook(book); + + BookFileEntity bookFile2 = new BookFileEntity(); + bookFile2.setBook(book); + + UserBookFileProgressEntity progress1 = new UserBookFileProgressEntity(); + progress1.setBookFile(bookFile1); + progress1.setLastReadTime(Instant.now().minusSeconds(100)); + + UserBookFileProgressEntity progress2 = new UserBookFileProgressEntity(); + progress2.setBookFile(bookFile2); + progress2.setLastReadTime(Instant.now()); + + when(userBookFileProgressRepository.findByUserIdAndBookFileBookIdIn(userId, bookIds)) + .thenReturn(List.of(progress1, progress2)); + + Map result = + readingProgressService.fetchUserFileProgress(userId, bookIds); + + assertEquals(1, result.size()); + assertEquals(progress2, result.get(1L)); + } + + @Test + void enrichBookWithProgress_shouldSetProgressFields() { + Book book = Book.builder().id(1L).build(); + UserBookProgressEntity progress = new UserBookProgressEntity(); + progress.setReadStatus(ReadStatus.READING); + progress.setEpubProgress("cfi"); + progress.setEpubProgressPercent(50.0f); + progress.setLastReadTime(Instant.now()); + + readingProgressService.enrichBookWithProgress(book, progress); + + assertEquals("READING", book.getReadStatus()); + assertNotNull(book.getEpubProgress()); + assertEquals("cfi", book.getEpubProgress().getCfi()); + assertEquals(50.0f, book.getEpubProgress().getPercentage()); + } + + @Test + void enrichBookWithProgress_withFileProgress_shouldOverlayFileProgress() { + Book book = Book.builder().id(1L).build(); + + UserBookProgressEntity progress = new UserBookProgressEntity(); + progress.setReadStatus(ReadStatus.READING); + progress.setEpubProgress("old-cfi"); + progress.setEpubProgressPercent(30.0f); + progress.setLastReadTime(Instant.now().minusSeconds(100)); + + BookFileEntity bookFile = new BookFileEntity(); + bookFile.setBookType(BookFileType.EPUB); + + UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity(); + fileProgress.setBookFile(bookFile); + fileProgress.setPositionData("new-cfi"); + fileProgress.setProgressPercent(50.0f); + fileProgress.setLastReadTime(Instant.now()); + + readingProgressService.enrichBookWithProgress(book, progress, fileProgress); + + assertEquals("new-cfi", book.getEpubProgress().getCfi()); + assertEquals(50.0f, book.getEpubProgress().getPercentage()); + } + + @Test + void updateReadProgress_epub_shouldSaveProgress() { + long bookId = 1L; + BookEntity book = new BookEntity(); + book.setId(bookId); + BookFileEntity primaryFile = new BookFileEntity(); + primaryFile.setId(1L); + primaryFile.setBook(book); + primaryFile.setBookType(BookFileType.EPUB); + book.setBookFiles(List.of(primaryFile)); + + BookLoreUser user = mock(BookLoreUser.class); + when(user.getId()).thenReturn(2L); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book)); + + BookLoreUserEntity userEntity = new BookLoreUserEntity(); + userEntity.setId(2L); + when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity)); + + UserBookProgressEntity progress = new UserBookProgressEntity(); + when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress)); + + when(userBookFileProgressRepository.findByUserIdAndBookFileId(2L, 1L)).thenReturn(Optional.empty()); + + ReadProgressRequest req = new ReadProgressRequest(); + req.setBookId(bookId); + EpubProgress epubProgress = EpubProgress.builder().cfi("cfi").percentage(100f).build(); + req.setEpubProgress(epubProgress); + + readingProgressService.updateReadProgress(req); + + verify(userBookProgressRepository).save(progress); + assertEquals("cfi", progress.getEpubProgress()); + assertEquals(ReadStatus.READ, progress.getReadStatus()); + assertEquals(100f, progress.getEpubProgressPercent()); + } + + @Test + void updateReadProgress_pdf_shouldSaveProgress() { + long bookId = 1L; + BookEntity book = new BookEntity(); + book.setId(bookId); + BookFileEntity primaryFile = new BookFileEntity(); + primaryFile.setId(1L); + primaryFile.setBook(book); + primaryFile.setBookType(BookFileType.PDF); + book.setBookFiles(List.of(primaryFile)); + + BookLoreUser user = mock(BookLoreUser.class); + when(user.getId()).thenReturn(2L); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book)); + + BookLoreUserEntity userEntity = new BookLoreUserEntity(); + userEntity.setId(2L); + when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity)); + + UserBookProgressEntity progress = new UserBookProgressEntity(); + when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress)); + + when(userBookFileProgressRepository.findByUserIdAndBookFileId(2L, 1L)).thenReturn(Optional.empty()); + + ReadProgressRequest req = new ReadProgressRequest(); + req.setBookId(bookId); + PdfProgress pdfProgress = PdfProgress.builder().page(5).percentage(50f).build(); + req.setPdfProgress(pdfProgress); + + readingProgressService.updateReadProgress(req); + + verify(userBookProgressRepository).save(progress); + assertEquals(5, progress.getPdfProgress()); + assertEquals(ReadStatus.READING, progress.getReadStatus()); + assertEquals(50f, progress.getPdfProgressPercent()); + } + + @Test + void resetProgress_booklore_shouldCallBulkReset() { + BookLoreUser user = mock(BookLoreUser.class); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(1L); + + BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class); + when(user.getPermissions()).thenReturn(permissions); + when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(true); + + List bookIds = Arrays.asList(1L, 2L); + when(bookRepository.countByIdIn(bookIds)).thenReturn(2L); + Set existing = new HashSet<>(bookIds); + when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing); + + List result = readingProgressService.resetProgress(bookIds, ResetProgressType.BOOKLORE); + + verify(userBookProgressRepository).bulkResetBookloreProgress(eq(1L), eq(new ArrayList<>(bookIds)), any()); + assertEquals(2, result.size()); + } + + @Test + void resetProgress_shouldAllowSingleBookWithoutPermission() { + BookLoreUser user = mock(BookLoreUser.class); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(1L); + + BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class); + when(user.getPermissions()).thenReturn(permissions); + when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(false); + + List bookIds = Collections.singletonList(1L); + when(bookRepository.countByIdIn(bookIds)).thenReturn(1L); + Set existing = new HashSet<>(bookIds); + when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing); + + assertDoesNotThrow(() -> readingProgressService.resetProgress(bookIds, ResetProgressType.BOOKLORE)); + } + + @Test + void resetProgress_shouldThrowIfNoBulkPermission() { + BookLoreUser user = mock(BookLoreUser.class); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(1L); + + BookLoreUser.UserPermissions permissions = mock(BookLoreUser.UserPermissions.class); + when(user.getPermissions()).thenReturn(permissions); + when(permissions.isCanBulkResetBookloreReadProgress()).thenReturn(false); + + List bookIds = Arrays.asList(1L, 2L); + when(bookRepository.countByIdIn(bookIds)).thenReturn(2L); + + assertThrows(APIException.class, () -> readingProgressService.resetProgress(bookIds, ResetProgressType.BOOKLORE)); + } + + @Test + void resetProgress_kobo_shouldCallKoboService() { + BookLoreUser user = mock(BookLoreUser.class); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(1L); + + List bookIds = Collections.singletonList(1L); + when(bookRepository.countByIdIn(bookIds)).thenReturn(1L); + Set existing = new HashSet<>(bookIds); + when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing); + + readingProgressService.resetProgress(bookIds, ResetProgressType.KOBO); + + verify(userBookProgressRepository).bulkResetKoboProgress(eq(1L), anyList()); + verify(koboReadingStateService).deleteReadingState(1L); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudioFileUtilityServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudioFileUtilityServiceTest.java new file mode 100644 index 000000000..c7f4fa7f2 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudioFileUtilityServiceTest.java @@ -0,0 +1,309 @@ +package com.adityachandel.booklore.service.reader; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class AudioFileUtilityServiceTest { + + private AudioFileUtilityService audioFileUtility; + + @TempDir + Path tempDir; + + @BeforeEach + void setUp() { + audioFileUtility = new AudioFileUtilityService(); + } + + // ==================== listAudioFiles tests ==================== + + @Test + void listAudioFiles_returnsEmptyListForEmptyFolder() { + List result = audioFileUtility.listAudioFiles(tempDir); + assertTrue(result.isEmpty()); + } + + @Test + void listAudioFiles_returnsOnlyAudioFiles() throws IOException { + // Create audio files + Files.createFile(tempDir.resolve("track1.mp3")); + Files.createFile(tempDir.resolve("track2.m4b")); + Files.createFile(tempDir.resolve("track3.flac")); + + // Create non-audio files + Files.createFile(tempDir.resolve("readme.txt")); + Files.createFile(tempDir.resolve("cover.jpg")); + Files.createFile(tempDir.resolve("metadata.xml")); + + List result = audioFileUtility.listAudioFiles(tempDir); + + assertEquals(3, result.size()); + assertTrue(result.stream().anyMatch(p -> p.getFileName().toString().equals("track1.mp3"))); + assertTrue(result.stream().anyMatch(p -> p.getFileName().toString().equals("track2.m4b"))); + assertTrue(result.stream().anyMatch(p -> p.getFileName().toString().equals("track3.flac"))); + } + + @Test + void listAudioFiles_sortsNaturally() throws IOException { + // Create files in non-natural order + Files.createFile(tempDir.resolve("Track 10.mp3")); + Files.createFile(tempDir.resolve("Track 2.mp3")); + Files.createFile(tempDir.resolve("Track 1.mp3")); + Files.createFile(tempDir.resolve("Track 20.mp3")); + Files.createFile(tempDir.resolve("Track 3.mp3")); + + List result = audioFileUtility.listAudioFiles(tempDir); + + assertEquals(5, result.size()); + assertEquals("Track 1.mp3", result.get(0).getFileName().toString()); + assertEquals("Track 2.mp3", result.get(1).getFileName().toString()); + assertEquals("Track 3.mp3", result.get(2).getFileName().toString()); + assertEquals("Track 10.mp3", result.get(3).getFileName().toString()); + assertEquals("Track 20.mp3", result.get(4).getFileName().toString()); + } + + @Test + void listAudioFiles_handlesNumericPrefixes() throws IOException { + Files.createFile(tempDir.resolve("01 - Introduction.mp3")); + Files.createFile(tempDir.resolve("02 - Chapter One.mp3")); + Files.createFile(tempDir.resolve("10 - Chapter Nine.mp3")); + Files.createFile(tempDir.resolve("11 - Epilogue.mp3")); + + List result = audioFileUtility.listAudioFiles(tempDir); + + assertEquals(4, result.size()); + assertEquals("01 - Introduction.mp3", result.get(0).getFileName().toString()); + assertEquals("02 - Chapter One.mp3", result.get(1).getFileName().toString()); + assertEquals("10 - Chapter Nine.mp3", result.get(2).getFileName().toString()); + assertEquals("11 - Epilogue.mp3", result.get(3).getFileName().toString()); + } + + @Test + void listAudioFiles_excludesDirectories() throws IOException { + Files.createFile(tempDir.resolve("track1.mp3")); + Files.createDirectory(tempDir.resolve("subfolder.mp3")); // Directory with mp3 extension + + List result = audioFileUtility.listAudioFiles(tempDir); + + assertEquals(1, result.size()); + assertEquals("track1.mp3", result.get(0).getFileName().toString()); + } + + @Test + void listAudioFiles_returnsEmptyListForNonexistentFolder() { + Path nonexistent = tempDir.resolve("nonexistent"); + List result = audioFileUtility.listAudioFiles(nonexistent); + assertTrue(result.isEmpty()); + } + + @Test + void listAudioFiles_handlesAllSupportedExtensions() throws IOException { + Files.createFile(tempDir.resolve("track.mp3")); + Files.createFile(tempDir.resolve("track.m4a")); + Files.createFile(tempDir.resolve("track.m4b")); + Files.createFile(tempDir.resolve("track.aac")); + Files.createFile(tempDir.resolve("track.flac")); + Files.createFile(tempDir.resolve("track.ogg")); + Files.createFile(tempDir.resolve("track.opus")); + + List result = audioFileUtility.listAudioFiles(tempDir); + + assertEquals(7, result.size()); + } + + // ==================== isAudioFile tests ==================== + + @ParameterizedTest + @ValueSource(strings = {"track.mp3", "book.m4b", "audio.m4a", "sound.aac", "music.flac", "song.ogg", "voice.opus"}) + void isAudioFile_returnsTrueForAudioExtensions(String filename) throws IOException { + Path file = tempDir.resolve(filename); + Files.createFile(file); + assertTrue(audioFileUtility.isAudioFile(file)); + } + + @ParameterizedTest + @ValueSource(strings = {"TRACK.MP3", "Book.M4B", "Audio.M4A", "SOUND.AAC", "Music.FLAC", "Song.OGG", "Voice.OPUS"}) + void isAudioFile_isCaseInsensitive(String filename) throws IOException { + Path file = tempDir.resolve(filename); + Files.createFile(file); + assertTrue(audioFileUtility.isAudioFile(file)); + } + + @ParameterizedTest + @ValueSource(strings = {"image.jpg", "document.pdf", "video.mp4", "text.txt", "archive.zip", "cover.png"}) + void isAudioFile_returnsFalseForNonAudioExtensions(String filename) throws IOException { + Path file = tempDir.resolve(filename); + Files.createFile(file); + assertFalse(audioFileUtility.isAudioFile(file)); + } + + @Test + void isAudioFile_returnsFalseForFileWithoutExtension() throws IOException { + Path file = tempDir.resolve("noextension"); + Files.createFile(file); + assertFalse(audioFileUtility.isAudioFile(file)); + } + + // ==================== getContentType tests ==================== + + @ParameterizedTest + @CsvSource({ + "track.m4b, audio/mp4", + "track.m4a, audio/mp4", + "track.mp3, audio/mpeg", + "track.aac, audio/aac", + "track.flac, audio/flac", + "track.ogg, audio/ogg", + "track.opus, audio/opus" + }) + void getContentType_returnsCorrectMimeType(String filename, String expectedMimeType) { + Path file = tempDir.resolve(filename); + assertEquals(expectedMimeType, audioFileUtility.getContentType(file)); + } + + @ParameterizedTest + @CsvSource({ + "TRACK.M4B, audio/mp4", + "TRACK.MP3, audio/mpeg", + "Track.Flac, audio/flac" + }) + void getContentType_isCaseInsensitive(String filename, String expectedMimeType) { + Path file = tempDir.resolve(filename); + assertEquals(expectedMimeType, audioFileUtility.getContentType(file)); + } + + @Test + void getContentType_returnsOctetStreamForUnknownExtension() { + Path file = tempDir.resolve("unknown.xyz"); + assertEquals("application/octet-stream", audioFileUtility.getContentType(file)); + } + + @Test + void getContentType_returnsOctetStreamForNoExtension() { + Path file = tempDir.resolve("noextension"); + assertEquals("application/octet-stream", audioFileUtility.getContentType(file)); + } + + // ==================== getTrackTitleFromFilename tests ==================== + + @Test + void getTrackTitleFromFilename_removesExtension() { + assertEquals("Track Title", audioFileUtility.getTrackTitleFromFilename("Track Title.mp3")); + } + + @Test + void getTrackTitleFromFilename_replacesUnderscoresWithSpaces() { + assertEquals("Chapter One Introduction", audioFileUtility.getTrackTitleFromFilename("Chapter_One_Introduction.mp3")); + } + + @Test + void getTrackTitleFromFilename_replacesHyphensWithSpaces() { + assertEquals("Chapter One Introduction", audioFileUtility.getTrackTitleFromFilename("Chapter-One-Introduction.mp3")); + } + + @Test + void getTrackTitleFromFilename_replacesMultipleUnderscoresAndHyphens() { + assertEquals("Chapter One", audioFileUtility.getTrackTitleFromFilename("Chapter___One---.mp3")); + } + + @Test + void getTrackTitleFromFilename_trimsWhitespace() { + assertEquals("Track", audioFileUtility.getTrackTitleFromFilename(" Track .mp3")); + } + + @Test + void getTrackTitleFromFilename_handlesNoExtension() { + assertEquals("Track Title", audioFileUtility.getTrackTitleFromFilename("Track_Title")); + } + + @Test + void getTrackTitleFromFilename_handlesMultipleDots() { + assertEquals("Track.v2", audioFileUtility.getTrackTitleFromFilename("Track.v2.mp3")); + } + + @Test + void getTrackTitleFromFilename_preservesNumbers() { + assertEquals("01 Chapter One", audioFileUtility.getTrackTitleFromFilename("01_Chapter_One.mp3")); + } + + // ==================== getSupportedExtensions tests ==================== + + @Test + void getSupportedExtensions_returnsAllExpectedExtensions() { + var extensions = audioFileUtility.getSupportedExtensions(); + + assertEquals(7, extensions.size()); + assertTrue(extensions.contains(".mp3")); + assertTrue(extensions.contains(".m4a")); + assertTrue(extensions.contains(".m4b")); + assertTrue(extensions.contains(".aac")); + assertTrue(extensions.contains(".flac")); + assertTrue(extensions.contains(".ogg")); + assertTrue(extensions.contains(".opus")); + } + + @Test + void getSupportedExtensions_returnsUnmodifiableSet() { + var extensions = audioFileUtility.getSupportedExtensions(); + assertThrows(UnsupportedOperationException.class, () -> extensions.add(".wav")); + } + + // ==================== Natural sorting edge cases ==================== + + @Test + void listAudioFiles_handlesMixedAlphanumericNames() throws IOException { + Files.createFile(tempDir.resolve("a1.mp3")); + Files.createFile(tempDir.resolve("a10.mp3")); + Files.createFile(tempDir.resolve("a2.mp3")); + Files.createFile(tempDir.resolve("b1.mp3")); + + List result = audioFileUtility.listAudioFiles(tempDir); + + assertEquals(4, result.size()); + assertEquals("a1.mp3", result.get(0).getFileName().toString()); + assertEquals("a2.mp3", result.get(1).getFileName().toString()); + assertEquals("a10.mp3", result.get(2).getFileName().toString()); + assertEquals("b1.mp3", result.get(3).getFileName().toString()); + } + + @Test + void listAudioFiles_handlesLeadingZeros() throws IOException { + Files.createFile(tempDir.resolve("001.mp3")); + Files.createFile(tempDir.resolve("002.mp3")); + Files.createFile(tempDir.resolve("010.mp3")); + Files.createFile(tempDir.resolve("100.mp3")); + + List result = audioFileUtility.listAudioFiles(tempDir); + + assertEquals(4, result.size()); + assertEquals("001.mp3", result.get(0).getFileName().toString()); + assertEquals("002.mp3", result.get(1).getFileName().toString()); + assertEquals("010.mp3", result.get(2).getFileName().toString()); + assertEquals("100.mp3", result.get(3).getFileName().toString()); + } + + @Test + void listAudioFiles_sortsCaseInsensitively() throws IOException { + Files.createFile(tempDir.resolve("Alpha.mp3")); + Files.createFile(tempDir.resolve("beta.mp3")); + Files.createFile(tempDir.resolve("GAMMA.mp3")); + + List result = audioFileUtility.listAudioFiles(tempDir); + + assertEquals(3, result.size()); + assertEquals("Alpha.mp3", result.get(0).getFileName().toString()); + assertEquals("beta.mp3", result.get(1).getFileName().toString()); + assertEquals("GAMMA.mp3", result.get(2).getFileName().toString()); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudioMetadataServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudioMetadataServiceTest.java new file mode 100644 index 000000000..fb8b4bee3 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudioMetadataServiceTest.java @@ -0,0 +1,556 @@ +package com.adityachandel.booklore.service.reader; + +import com.adityachandel.booklore.model.dto.response.AudiobookChapter; +import com.adityachandel.booklore.model.dto.response.AudiobookInfo; +import com.adityachandel.booklore.model.dto.response.AudiobookTrack; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; +import org.jaudiotagger.audio.AudioFile; +import org.jaudiotagger.audio.AudioFileIO; +import org.jaudiotagger.audio.AudioHeader; +import org.jaudiotagger.tag.FieldKey; +import org.jaudiotagger.tag.Tag; +import org.jaudiotagger.tag.images.Artwork; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class AudioMetadataServiceTest { + + @Mock + AudioFileUtilityService audioFileUtility; + + @InjectMocks + AudioMetadataService audioMetadataService; + + @TempDir + Path tempDir; + + BookEntity bookEntity; + BookFileEntity bookFileEntity; + Path audioPath; + + @BeforeEach + void setUp() throws Exception { + bookEntity = new BookEntity(); + bookEntity.setId(1L); + + bookFileEntity = new BookFileEntity(); + bookFileEntity.setId(10L); + bookFileEntity.setBook(bookEntity); + bookFileEntity.setFolderBased(false); + + audioPath = tempDir.resolve("audiobook.m4b"); + Files.createFile(audioPath); + } + + // ==================== getMetadata tests for single file ==================== + + @Test + void getMetadata_singleFile_extractsBasicInfo() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + AudioHeader header = mock(AudioHeader.class); + Tag tag = mock(Tag.class); + + when(audioFile.getAudioHeader()).thenReturn(header); + when(audioFile.getTag()).thenReturn(tag); + when(header.getPreciseTrackLength()).thenReturn(3600.0); // 1 hour + when(header.getBitRateAsNumber()).thenReturn(128L); + when(header.getEncodingType()).thenReturn("AAC"); + when(header.getSampleRateAsNumber()).thenReturn(44100); + when(header.getChannels()).thenReturn("Stereo"); + + when(tag.getFirst(FieldKey.TITLE)).thenReturn("Test Audiobook"); + when(tag.getFirst(FieldKey.ARTIST)).thenReturn("Test Author"); + when(tag.getFirst(FieldKey.COMPOSER)).thenReturn("Test Narrator"); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath); + + assertNotNull(info); + assertEquals(1L, info.getBookId()); + assertEquals(10L, info.getBookFileId()); + assertFalse(info.isFolderBased()); + assertEquals(3600000L, info.getDurationMs()); // 1 hour in ms + assertEquals(128, info.getBitrate()); + assertEquals("AAC", info.getCodec()); + assertEquals(44100, info.getSampleRate()); + assertEquals(2, info.getChannels()); // Stereo = 2 + assertEquals("Test Audiobook", info.getTitle()); + assertEquals("Test Author", info.getAuthor()); + assertEquals("Test Narrator", info.getNarrator()); + } + } + + @Test + void getMetadata_singleFile_handlesNullTag() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + AudioHeader header = mock(AudioHeader.class); + + when(audioFile.getAudioHeader()).thenReturn(header); + when(audioFile.getTag()).thenReturn(null); + when(header.getPreciseTrackLength()).thenReturn(1800.0); + when(header.getBitRateAsNumber()).thenReturn(256L); + when(header.getEncodingType()).thenReturn("MP3"); + when(header.getSampleRateAsNumber()).thenReturn(48000); + when(header.getChannels()).thenReturn("Mono"); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath); + + assertNotNull(info); + assertEquals(1800000L, info.getDurationMs()); + assertEquals(1, info.getChannels()); // Mono = 1 + assertNull(info.getTitle()); + assertNull(info.getAuthor()); + assertNull(info.getNarrator()); + } + } + + @Test + void getMetadata_singleFile_createsDefaultChapterWhenNoChapters() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + AudioHeader header = mock(AudioHeader.class); + + when(audioFile.getAudioHeader()).thenReturn(header); + when(audioFile.getTag()).thenReturn(null); + when(header.getPreciseTrackLength()).thenReturn(7200.0); // 2 hours + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath); + + assertNotNull(info.getChapters()); + assertEquals(1, info.getChapters().size()); + AudiobookChapter chapter = info.getChapters().get(0); + assertEquals(0, chapter.getIndex()); + assertEquals("Full Audiobook", chapter.getTitle()); + assertEquals(0L, chapter.getStartTimeMs()); + assertEquals(7200000L, chapter.getEndTimeMs()); + assertEquals(7200000L, chapter.getDurationMs()); + } + } + + @Test + void getMetadata_cachesResult() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + AudioHeader header = mock(AudioHeader.class); + + when(audioFile.getAudioHeader()).thenReturn(header); + when(audioFile.getTag()).thenReturn(null); + when(header.getPreciseTrackLength()).thenReturn(100.0); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + // First call + AudiobookInfo info1 = audioMetadataService.getMetadata(bookFileEntity, audioPath); + // Second call should use cache + AudiobookInfo info2 = audioMetadataService.getMetadata(bookFileEntity, audioPath); + + assertSame(info1, info2); + // AudioFileIO.read should only be called once + audioFileIOMock.verify(() -> AudioFileIO.read(audioPath.toFile()), times(1)); + } + } + + // ==================== getMetadata tests for folder-based ==================== + + @Test + void getMetadata_folderBased_extractsTracksInfo() throws Exception { + bookFileEntity.setFolderBased(true); + Path folderPath = tempDir.resolve("audiobook_folder"); + Files.createDirectory(folderPath); + + Path track1 = folderPath.resolve("01 - Chapter One.mp3"); + Path track2 = folderPath.resolve("02 - Chapter Two.mp3"); + Files.createFile(track1); + Files.createFile(track2); + + when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1, track2)); + when(audioFileUtility.getTrackTitleFromFilename("01 - Chapter One.mp3")).thenReturn("01 - Chapter One"); + when(audioFileUtility.getTrackTitleFromFilename("02 - Chapter Two.mp3")).thenReturn("02 - Chapter Two"); + when(audioFileUtility.isAudioFile(any())).thenReturn(true); + + AudioFile audioFile1 = mock(AudioFile.class); + AudioFile audioFile2 = mock(AudioFile.class); + AudioHeader header1 = mock(AudioHeader.class); + AudioHeader header2 = mock(AudioHeader.class); + Tag tag1 = mock(Tag.class); + + when(audioFile1.getAudioHeader()).thenReturn(header1); + when(audioFile1.getTag()).thenReturn(tag1); + when(header1.getPreciseTrackLength()).thenReturn(1800.0); // 30 min + when(header1.getBitRateAsNumber()).thenReturn(192L); + when(header1.getEncodingType()).thenReturn("MP3"); + when(header1.getSampleRateAsNumber()).thenReturn(44100); + when(header1.getChannels()).thenReturn("Stereo"); + when(tag1.getFirst(FieldKey.ALBUM)).thenReturn("Test Album"); + when(tag1.getFirst(FieldKey.ALBUM_ARTIST)).thenReturn("Test Author"); + when(tag1.getFirst(FieldKey.TITLE)).thenReturn("Chapter One"); + + when(audioFile2.getAudioHeader()).thenReturn(header2); + when(audioFile2.getTag()).thenReturn(null); + when(header2.getPreciseTrackLength()).thenReturn(2400.0); // 40 min + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(track1.toFile())).thenReturn(audioFile1); + audioFileIOMock.when(() -> AudioFileIO.read(track2.toFile())).thenReturn(audioFile2); + + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, folderPath); + + assertNotNull(info); + assertTrue(info.isFolderBased()); + assertEquals(4200000L, info.getDurationMs()); // 30 + 40 min = 70 min + assertEquals("Test Album", info.getTitle()); + assertEquals("Test Author", info.getAuthor()); + + List tracks = info.getTracks(); + assertNotNull(tracks); + assertEquals(2, tracks.size()); + + assertEquals(0, tracks.get(0).getIndex()); + assertEquals("Chapter One", tracks.get(0).getTitle()); + assertEquals(1800000L, tracks.get(0).getDurationMs()); + assertEquals(0L, tracks.get(0).getCumulativeStartMs()); + + assertEquals(1, tracks.get(1).getIndex()); + assertEquals(2400000L, tracks.get(1).getDurationMs()); + assertEquals(1800000L, tracks.get(1).getCumulativeStartMs()); + } + } + + @Test + void getMetadata_folderBased_throwsExceptionForEmptyFolder() throws Exception { + bookFileEntity.setFolderBased(true); + Path folderPath = tempDir.resolve("empty_folder"); + Files.createDirectory(folderPath); + + when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of()); + when(audioFileUtility.isAudioFile(any())).thenReturn(false); + + assertThrows(IllegalStateException.class, + () -> audioMetadataService.getMetadata(bookFileEntity, folderPath)); + } + + @Test + void getMetadata_folderBased_usesFallbackTitleFromFilename() throws Exception { + bookFileEntity.setFolderBased(true); + Path folderPath = tempDir.resolve("audiobook_folder2"); + Files.createDirectory(folderPath); + + Path track1 = folderPath.resolve("track.mp3"); + Files.createFile(track1); + + when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1)); + when(audioFileUtility.getTrackTitleFromFilename("track.mp3")).thenReturn("track"); + when(audioFileUtility.isAudioFile(any())).thenReturn(true); + + AudioFile audioFile = mock(AudioFile.class); + AudioHeader header = mock(AudioHeader.class); + Tag tag = mock(Tag.class); + + when(audioFile.getAudioHeader()).thenReturn(header); + when(audioFile.getTag()).thenReturn(tag); + when(header.getPreciseTrackLength()).thenReturn(600.0); + when(tag.getFirst(FieldKey.TITLE)).thenReturn(""); // Empty title + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(track1.toFile())).thenReturn(audioFile); + + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, folderPath); + + assertEquals("track", info.getTracks().get(0).getTitle()); + } + } + + // ==================== getEmbeddedCoverArt tests ==================== + + @Test + void getEmbeddedCoverArt_returnsArtworkData() throws Exception { + byte[] expectedData = new byte[]{(byte) 0xFF, (byte) 0xD8, 0x00, 0x01}; + + AudioFile audioFile = mock(AudioFile.class); + Tag tag = mock(Tag.class); + Artwork artwork = mock(Artwork.class); + + when(audioFile.getTag()).thenReturn(tag); + when(tag.getFirstArtwork()).thenReturn(artwork); + when(artwork.getBinaryData()).thenReturn(expectedData); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + byte[] result = audioMetadataService.getEmbeddedCoverArt(audioPath); + + assertArrayEquals(expectedData, result); + } + } + + @Test + void getEmbeddedCoverArt_returnsNullWhenNoArtwork() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + Tag tag = mock(Tag.class); + + when(audioFile.getTag()).thenReturn(tag); + when(tag.getFirstArtwork()).thenReturn(null); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + byte[] result = audioMetadataService.getEmbeddedCoverArt(audioPath); + + assertNull(result); + } + } + + @Test + void getEmbeddedCoverArt_returnsNullWhenNoTag() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + when(audioFile.getTag()).thenReturn(null); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + byte[] result = audioMetadataService.getEmbeddedCoverArt(audioPath); + + assertNull(result); + } + } + + @Test + void getEmbeddedCoverArt_returnsNullOnException() { + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenThrow(new RuntimeException("Read error")); + + byte[] result = audioMetadataService.getEmbeddedCoverArt(audioPath); + + assertNull(result); + } + } + + // ==================== getCoverArtMimeType tests ==================== + + @Test + void getCoverArtMimeType_returnsMimeTypeFromArtwork() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + Tag tag = mock(Tag.class); + Artwork artwork = mock(Artwork.class); + + when(audioFile.getTag()).thenReturn(tag); + when(tag.getFirstArtwork()).thenReturn(artwork); + when(artwork.getMimeType()).thenReturn("image/png"); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + String result = audioMetadataService.getCoverArtMimeType(audioPath); + + assertEquals("image/png", result); + } + } + + @Test + void getCoverArtMimeType_detectsJpegFromMagicBytes() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + Tag tag = mock(Tag.class); + Artwork artwork = mock(Artwork.class); + + when(audioFile.getTag()).thenReturn(tag); + when(tag.getFirstArtwork()).thenReturn(artwork); + when(artwork.getMimeType()).thenReturn(null); + when(artwork.getBinaryData()).thenReturn(new byte[]{(byte) 0xFF, (byte) 0xD8, 0x00}); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + String result = audioMetadataService.getCoverArtMimeType(audioPath); + + assertEquals("image/jpeg", result); + } + } + + @Test + void getCoverArtMimeType_detectsPngFromMagicBytes() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + Tag tag = mock(Tag.class); + Artwork artwork = mock(Artwork.class); + + when(audioFile.getTag()).thenReturn(tag); + when(tag.getFirstArtwork()).thenReturn(artwork); + when(artwork.getMimeType()).thenReturn(""); + when(artwork.getBinaryData()).thenReturn(new byte[]{(byte) 0x89, (byte) 0x50, 0x4E, 0x47}); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + String result = audioMetadataService.getCoverArtMimeType(audioPath); + + assertEquals("image/png", result); + } + } + + @Test + void getCoverArtMimeType_returnsDefaultJpegWhenCannotDetermine() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + Tag tag = mock(Tag.class); + Artwork artwork = mock(Artwork.class); + + when(audioFile.getTag()).thenReturn(tag); + when(tag.getFirstArtwork()).thenReturn(artwork); + when(artwork.getMimeType()).thenReturn(null); + when(artwork.getBinaryData()).thenReturn(new byte[]{0x00, 0x01}); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + String result = audioMetadataService.getCoverArtMimeType(audioPath); + + assertEquals("image/jpeg", result); + } + } + + @Test + void getCoverArtMimeType_returnsJpegOnException() { + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenThrow(new RuntimeException("Error")); + + String result = audioMetadataService.getCoverArtMimeType(audioPath); + + assertEquals("image/jpeg", result); + } + } + + // ==================== Channel parsing tests ==================== + + @Test + void getMetadata_parsesStereoChannels() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + AudioHeader header = mock(AudioHeader.class); + + when(audioFile.getAudioHeader()).thenReturn(header); + when(audioFile.getTag()).thenReturn(null); + when(header.getPreciseTrackLength()).thenReturn(100.0); + when(header.getChannels()).thenReturn("Stereo"); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath); + assertEquals(2, info.getChannels()); + } + } + + @Test + void getMetadata_parsesMonoChannels() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + AudioHeader header = mock(AudioHeader.class); + + when(audioFile.getAudioHeader()).thenReturn(header); + when(audioFile.getTag()).thenReturn(null); + when(header.getPreciseTrackLength()).thenReturn(100.0); + when(header.getChannels()).thenReturn("Mono"); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath); + assertEquals(1, info.getChannels()); + } + } + + @Test + void getMetadata_parsesNumericChannels() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + AudioHeader header = mock(AudioHeader.class); + + when(audioFile.getAudioHeader()).thenReturn(header); + when(audioFile.getTag()).thenReturn(null); + when(header.getPreciseTrackLength()).thenReturn(100.0); + when(header.getChannels()).thenReturn("6 channels"); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath); + assertEquals(6, info.getChannels()); + } + } + + @Test + void getMetadata_handlesNullChannels() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + AudioHeader header = mock(AudioHeader.class); + + when(audioFile.getAudioHeader()).thenReturn(header); + when(audioFile.getTag()).thenReturn(null); + when(header.getPreciseTrackLength()).thenReturn(100.0); + when(header.getChannels()).thenReturn(null); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath); + assertNull(info.getChannels()); + } + } + + // ==================== Bitrate handling ==================== + + @Test + void getMetadata_handlesZeroBitrate() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + AudioHeader header = mock(AudioHeader.class); + + when(audioFile.getAudioHeader()).thenReturn(header); + when(audioFile.getTag()).thenReturn(null); + when(header.getPreciseTrackLength()).thenReturn(100.0); + when(header.getBitRateAsNumber()).thenReturn(0L); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath); + assertNull(info.getBitrate()); + } + } + + @Test + void getMetadata_handlesNegativeBitrate() throws Exception { + AudioFile audioFile = mock(AudioFile.class); + AudioHeader header = mock(AudioHeader.class); + + when(audioFile.getAudioHeader()).thenReturn(header); + when(audioFile.getTag()).thenReturn(null); + when(header.getPreciseTrackLength()).thenReturn(100.0); + when(header.getBitRateAsNumber()).thenReturn(-1L); + + try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { + audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath); + assertNull(info.getBitrate()); + } + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudiobookReaderServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudiobookReaderServiceTest.java new file mode 100644 index 000000000..1ca6a9ca0 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/AudiobookReaderServiceTest.java @@ -0,0 +1,423 @@ +package com.adityachandel.booklore.service.reader; + +import com.adityachandel.booklore.exception.ApiError; +import com.adityachandel.booklore.model.dto.response.AudiobookInfo; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookFileEntity; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.service.FileStreamingService; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class AudiobookReaderServiceTest { + + @Mock + BookRepository bookRepository; + + @Mock + AudioMetadataService audioMetadataService; + + @Mock + AudioFileUtilityService audioFileUtility; + + @Mock + FileStreamingService fileStreamingService; + + @InjectMocks + AudiobookReaderService audiobookReaderService; + + @TempDir + Path tempDir; + + BookEntity bookEntity; + BookFileEntity audiobookFileEntity; + BookFileEntity folderAudiobookFileEntity; + Path audioPath; + Path folderPath; + + @BeforeEach + void setUp() throws Exception { + audioPath = tempDir.resolve("audiobook.m4b"); + Files.createFile(audioPath); + + folderPath = tempDir.resolve("audiobook_folder"); + Files.createDirectory(folderPath); + + bookEntity = mock(BookEntity.class); + when(bookEntity.getId()).thenReturn(1L); + + audiobookFileEntity = mock(BookFileEntity.class); + when(audiobookFileEntity.getId()).thenReturn(10L); + when(audiobookFileEntity.getBook()).thenReturn(bookEntity); + when(audiobookFileEntity.getBookType()).thenReturn(BookFileType.AUDIOBOOK); + when(audiobookFileEntity.isFolderBased()).thenReturn(false); + when(audiobookFileEntity.isBookFormat()).thenReturn(true); + when(audiobookFileEntity.getFullFilePath()).thenReturn(audioPath); + when(audiobookFileEntity.getFirstAudioFile()).thenReturn(audioPath); + + folderAudiobookFileEntity = mock(BookFileEntity.class); + when(folderAudiobookFileEntity.getId()).thenReturn(20L); + when(folderAudiobookFileEntity.getBook()).thenReturn(bookEntity); + when(folderAudiobookFileEntity.getBookType()).thenReturn(BookFileType.AUDIOBOOK); + when(folderAudiobookFileEntity.isFolderBased()).thenReturn(true); + when(folderAudiobookFileEntity.isBookFormat()).thenReturn(true); + when(folderAudiobookFileEntity.getFullFilePath()).thenReturn(folderPath); + + List bookFiles = new ArrayList<>(); + bookFiles.add(audiobookFileEntity); + when(bookEntity.getBookFiles()).thenReturn(bookFiles); + } + + // ==================== getAudiobookInfo tests ==================== + + @Test + void getAudiobookInfo_returnsInfoFromMetadataService() throws Exception { + AudiobookInfo expectedInfo = AudiobookInfo.builder() + .bookId(1L) + .bookFileId(10L) + .title("Test Audiobook") + .author("Test Author") + .durationMs(3600000L) + .build(); + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioMetadataService.getMetadata(audiobookFileEntity, audioPath)).thenReturn(expectedInfo); + + AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, null); + + assertEquals(expectedInfo, result); + verify(audioMetadataService).getMetadata(audiobookFileEntity, audioPath); + } + + @Test + void getAudiobookInfo_withBookType_selectsCorrectFile() throws Exception { + BookFileEntity epubFile = mock(BookFileEntity.class); + when(epubFile.getId()).thenReturn(30L); + when(epubFile.getBookType()).thenReturn(BookFileType.EPUB); + + List bookFiles = new ArrayList<>(); + bookFiles.add(audiobookFileEntity); + bookFiles.add(epubFile); + when(bookEntity.getBookFiles()).thenReturn(bookFiles); + + AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build(); + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioMetadataService.getMetadata(audiobookFileEntity, audioPath)).thenReturn(expectedInfo); + + AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, "AUDIOBOOK"); + + assertEquals(expectedInfo, result); + verify(audioMetadataService).getMetadata(eq(audiobookFileEntity), any()); + } + + @Test + void getAudiobookInfo_throwsExceptionWhenBookNotFound() { + when(bookRepository.findByIdWithBookFiles(999L)).thenReturn(Optional.empty()); + + assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(), + () -> audiobookReaderService.getAudiobookInfo(999L, null)); + } + + @Test + void getAudiobookInfo_throwsExceptionWhenNoAudiobookFile() { + BookFileEntity epubFile = mock(BookFileEntity.class); + when(epubFile.getBookType()).thenReturn(BookFileType.EPUB); + + List bookFiles = new ArrayList<>(); + bookFiles.add(epubFile); + when(bookEntity.getBookFiles()).thenReturn(bookFiles); + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + + assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(), + () -> audiobookReaderService.getAudiobookInfo(1L, null)); + } + + @Test + void getAudiobookInfo_throwsExceptionWhenRequestedTypeNotFound() { + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + + assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(), + () -> audiobookReaderService.getAudiobookInfo(1L, "EPUB")); + } + + @Test + void getAudiobookInfo_wrapsMetadataServiceException() throws Exception { + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioMetadataService.getMetadata(any(), any())).thenThrow(new RuntimeException("Parse error")); + + assertThrows(ApiError.FILE_READ_ERROR.createException().getClass(), + () -> audiobookReaderService.getAudiobookInfo(1L, null)); + } + + // ==================== getAudioFilePath tests ==================== + + @Test + void getAudioFilePath_singleFile_returnsFilePath() { + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + + Path result = audiobookReaderService.getAudioFilePath(1L, null, null); + + assertEquals(audioPath, result); + } + + @Test + void getAudioFilePath_singleFile_ignoresTrackIndex() { + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + + Path result = audiobookReaderService.getAudioFilePath(1L, null, 5); + + assertEquals(audioPath, result); + } + + @Test + void getAudioFilePath_folderBased_returnsTrackPath() throws IOException { + List bookFiles = new ArrayList<>(); + bookFiles.add(folderAudiobookFileEntity); + when(bookEntity.getBookFiles()).thenReturn(bookFiles); + + Path track1 = folderPath.resolve("track1.mp3"); + Path track2 = folderPath.resolve("track2.mp3"); + Files.createFile(track1); + Files.createFile(track2); + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1, track2)); + + Path result = audiobookReaderService.getAudioFilePath(1L, null, 1); + + assertEquals(track2, result); + } + + @Test + void getAudioFilePath_folderBased_defaultsToFirstTrack() throws IOException { + List bookFiles = new ArrayList<>(); + bookFiles.add(folderAudiobookFileEntity); + when(bookEntity.getBookFiles()).thenReturn(bookFiles); + + Path track1 = folderPath.resolve("track1.mp3"); + Files.createFile(track1); + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1)); + + Path result = audiobookReaderService.getAudioFilePath(1L, null, null); + + assertEquals(track1, result); + } + + @Test + void getAudioFilePath_folderBased_throwsExceptionForInvalidIndex() throws IOException { + List bookFiles = new ArrayList<>(); + bookFiles.add(folderAudiobookFileEntity); + when(bookEntity.getBookFiles()).thenReturn(bookFiles); + + Path track1 = folderPath.resolve("track1.mp3"); + Files.createFile(track1); + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1)); + + assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(), + () -> audiobookReaderService.getAudioFilePath(1L, null, 10)); + } + + @Test + void getAudioFilePath_folderBased_throwsExceptionForNegativeIndex() throws IOException { + List bookFiles = new ArrayList<>(); + bookFiles.add(folderAudiobookFileEntity); + when(bookEntity.getBookFiles()).thenReturn(bookFiles); + + Path track1 = folderPath.resolve("track1.mp3"); + Files.createFile(track1); + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1)); + + assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(), + () -> audiobookReaderService.getAudioFilePath(1L, null, -1)); + } + + // ==================== streamWithRangeSupport tests ==================== + + @Test + void streamWithRangeSupport_delegatesToFileStreamingService() throws IOException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + + when(audioFileUtility.getContentType(audioPath)).thenReturn("audio/mp4"); + + audiobookReaderService.streamWithRangeSupport(audioPath, request, response); + + verify(audioFileUtility).getContentType(audioPath); + verify(fileStreamingService).streamWithRangeSupport(audioPath, "audio/mp4", request, response); + } + + @Test + void streamWithRangeSupport_usesCorrectContentType() throws IOException { + Path mp3Path = tempDir.resolve("audio.mp3"); + Files.createFile(mp3Path); + + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + + when(audioFileUtility.getContentType(mp3Path)).thenReturn("audio/mpeg"); + + audiobookReaderService.streamWithRangeSupport(mp3Path, request, response); + + verify(fileStreamingService).streamWithRangeSupport(mp3Path, "audio/mpeg", request, response); + } + + // ==================== getEmbeddedCoverArt tests ==================== + + @Test + void getEmbeddedCoverArt_delegatesToMetadataService() { + byte[] expectedData = new byte[]{0x01, 0x02, 0x03}; + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioMetadataService.getEmbeddedCoverArt(audioPath)).thenReturn(expectedData); + + byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null); + + assertArrayEquals(expectedData, result); + verify(audioMetadataService).getEmbeddedCoverArt(audioPath); + } + + @Test + void getEmbeddedCoverArt_folderBased_usesFirstAudioFile() throws IOException { + List bookFiles = new ArrayList<>(); + bookFiles.add(folderAudiobookFileEntity); + when(bookEntity.getBookFiles()).thenReturn(bookFiles); + + Path track1 = folderPath.resolve("track1.mp3"); + Files.createFile(track1); + when(folderAudiobookFileEntity.getFirstAudioFile()).thenReturn(track1); + + byte[] expectedData = new byte[]{0x04, 0x05}; + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioMetadataService.getEmbeddedCoverArt(track1)).thenReturn(expectedData); + + byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null); + + assertArrayEquals(expectedData, result); + verify(audioMetadataService).getEmbeddedCoverArt(track1); + } + + @Test + void getEmbeddedCoverArt_returnsNullWhenNoCoverArt() { + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioMetadataService.getEmbeddedCoverArt(audioPath)).thenReturn(null); + + byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null); + + assertNull(result); + } + + // ==================== getCoverArtMimeType tests ==================== + + @Test + void getCoverArtMimeType_delegatesToMetadataService() { + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioMetadataService.getCoverArtMimeType(audioPath)).thenReturn("image/png"); + + String result = audiobookReaderService.getCoverArtMimeType(1L, null); + + assertEquals("image/png", result); + verify(audioMetadataService).getCoverArtMimeType(audioPath); + } + + @Test + void getCoverArtMimeType_folderBased_usesFirstAudioFile() throws IOException { + List bookFiles = new ArrayList<>(); + bookFiles.add(folderAudiobookFileEntity); + when(bookEntity.getBookFiles()).thenReturn(bookFiles); + + Path track1 = folderPath.resolve("track1.mp3"); + Files.createFile(track1); + when(folderAudiobookFileEntity.getFirstAudioFile()).thenReturn(track1); + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioMetadataService.getCoverArtMimeType(track1)).thenReturn("image/jpeg"); + + String result = audiobookReaderService.getCoverArtMimeType(1L, null); + + assertEquals("image/jpeg", result); + } + + // ==================== getContentType tests ==================== + + @Test + void getContentType_delegatesToAudioFileUtility() { + when(audioFileUtility.getContentType(audioPath)).thenReturn("audio/mp4"); + + String result = audiobookReaderService.getContentType(audioPath); + + assertEquals("audio/mp4", result); + verify(audioFileUtility).getContentType(audioPath); + } + + // ==================== Book file selection tests ==================== + + @Test + void getAudiobookInfo_selectsAudiobookWithBookFormat() throws Exception { + BookFileEntity audiobookWithoutBookFormat = mock(BookFileEntity.class); + when(audiobookWithoutBookFormat.getId()).thenReturn(40L); + when(audiobookWithoutBookFormat.getBookType()).thenReturn(BookFileType.AUDIOBOOK); + when(audiobookWithoutBookFormat.isBookFormat()).thenReturn(false); + + List bookFiles = new ArrayList<>(); + bookFiles.add(audiobookFileEntity); + bookFiles.add(audiobookWithoutBookFormat); + when(bookEntity.getBookFiles()).thenReturn(bookFiles); + + AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build(); + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioMetadataService.getMetadata(eq(audiobookFileEntity), any())).thenReturn(expectedInfo); + + AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, null); + + assertEquals(expectedInfo, result); + verify(audioMetadataService).getMetadata(eq(audiobookFileEntity), any()); + } + + @Test + void getAudiobookInfo_bookTypeIsCaseInsensitive() throws Exception { + AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build(); + + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + when(audioMetadataService.getMetadata(any(), any())).thenReturn(expectedInfo); + + // Test lowercase + audiobookReaderService.getAudiobookInfo(1L, "audiobook"); + verify(audioMetadataService, times(1)).getMetadata(any(), any()); + + // Test mixed case + audiobookReaderService.getAudiobookInfo(1L, "AudioBook"); + verify(audioMetadataService, times(2)).getMetadata(any(), any()); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/BookFileGroupingUtilsTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/BookFileGroupingUtilsTest.java new file mode 100644 index 000000000..59fecdbcb --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/BookFileGroupingUtilsTest.java @@ -0,0 +1,684 @@ +package com.adityachandel.booklore.util; + +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.enums.BookFileType; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class BookFileGroupingUtilsTest { + + @Test + void extractGroupingKey_shouldStripExtension() { + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit.pdf")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit.epub")).isEqualTo("the hobbit"); + } + + @Test + void extractGroupingKey_shouldStripFormatIndicators() { + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (PDF).pdf")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (EPUB).epub")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [pdf].pdf")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [EPUB].epub")).isEqualTo("the hobbit"); + } + + @Test + void extractGroupingKey_shouldBeCaseInsensitive() { + assertThat(BookFileGroupingUtils.extractGroupingKey("THE HOBBIT.pdf")) + .isEqualTo(BookFileGroupingUtils.extractGroupingKey("the hobbit.epub")); + } + + @Test + void extractGroupingKey_shouldNormalizeWhitespace() { + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit.pdf")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey(" The Hobbit .pdf")).isEqualTo("the hobbit"); + } + + @Test + void extractGroupingKey_shouldHandleNullAndEmpty() { + assertThat(BookFileGroupingUtils.extractGroupingKey(null)).isEqualTo(""); + assertThat(BookFileGroupingUtils.extractGroupingKey("")).isEqualTo(""); + } + + @Test + void extractGroupingKey_shouldHandleFileWithNoExtension() { + assertThat(BookFileGroupingUtils.extractGroupingKey("noextension")).isEqualTo("noextension"); + } + + @Test + void extractGroupingKey_shouldNotStripDotsThatAreNotExtensions() { + // Folder names with dots (like "1. American Gods") should not be stripped + // The dot after "1" is NOT a file extension + assertThat(BookFileGroupingUtils.extractGroupingKey("1. American Gods - Neil Gaiman (2011)")) + .isEqualTo("1. american gods - neil gaiman (2011)"); + // Series numbering with dots + assertThat(BookFileGroupingUtils.extractGroupingKey("Vol. 1 - Adventures (2020)")) + .isEqualTo("vol. 1 - adventures (2020)"); + // Title with dots + assertThat(BookFileGroupingUtils.extractGroupingKey("Dr. Seuss Collection")) + .isEqualTo("dr. seuss collection"); + // Multiple dots that are not extensions + assertThat(BookFileGroupingUtils.extractGroupingKey("U.S.A. History")) + .isEqualTo("u.s.a. history"); + } + + @Test + void extractGroupingKey_shouldHandleMultipleFormatIndicators() { + assertThat(BookFileGroupingUtils.extractGroupingKey("Book (PDF) (EPUB).pdf")).isEqualTo("book"); + } + + @Test + void extractGroupingKey_shouldNotStripNonFormatParentheses() { + assertThat(BookFileGroupingUtils.extractGroupingKey("Book (Extended Edition).pdf")).isEqualTo("book (extended edition)"); + } + + @Test + void generateDirectoryGroupKey_shouldCombineSubPathAndGroupingKey() { + String key = BookFileGroupingUtils.generateDirectoryGroupKey("fantasy/tolkien", "The Hobbit.pdf"); + assertThat(key).isEqualTo("fantasy/tolkien:the hobbit"); + } + + @Test + void generateDirectoryGroupKey_shouldHandleNullSubPath() { + String key = BookFileGroupingUtils.generateDirectoryGroupKey(null, "The Hobbit.pdf"); + assertThat(key).isEqualTo(":the hobbit"); + } + + @Test + void groupByBaseName_shouldGroupFilesWithSameBaseNameInSameDirectory() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("books") + .fileName("The Hobbit.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile pdf = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("books") + .fileName("The Hobbit.pdf") + .bookFileType(BookFileType.PDF) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, pdf)); + + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, pdf); + } + + @Test + void groupByBaseName_shouldSeparateFilesInDifferentDirectories() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile file1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("dir1") + .fileName("book.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile file2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("dir2") + .fileName("book.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2)); + + assertThat(groups).hasSize(2); + } + + @Test + void groupByBaseName_shouldSeparateFilesFromDifferentLibraryPaths() { + LibraryPathEntity path1 = new LibraryPathEntity(); + path1.setId(1L); + path1.setPath("/library1"); + + LibraryPathEntity path2 = new LibraryPathEntity(); + path2.setId(2L); + path2.setPath("/library2"); + + LibraryFile file1 = LibraryFile.builder() + .libraryPathEntity(path1) + .fileSubPath("books") + .fileName("book.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile file2 = LibraryFile.builder() + .libraryPathEntity(path2) + .fileSubPath("books") + .fileName("book.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2)); + + assertThat(groups).hasSize(2); + } + + @Test + void groupByBaseName_shouldGroupFormatIndicatorVariants() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("books") + .fileName("The Hobbit.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile pdf = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("books") + .fileName("The Hobbit (PDF).pdf") + .bookFileType(BookFileType.PDF) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, pdf)); + + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, pdf); + } + + @Test + void extractGroupingKey_shouldConvertUnderscoresToSpaces() { + assertThat(BookFileGroupingUtils.extractGroupingKey("The_Hobbit.pdf")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("Lord_of_the_Rings.epub")).isEqualTo("lord of the rings"); + } + + @Test + void extractGroupingKey_shouldStripTrailingAuthor() { + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit - J.R.R. Tolkien.pdf")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("1984 - George Orwell.epub")).isEqualTo("1984"); + assertThat(BookFileGroupingUtils.extractGroupingKey("Pride and Prejudice - Jane Austen.pdf")).isEqualTo("pride and prejudice"); + } + + @Test + void extractGroupingKey_shouldRepositionArticles() { + assertThat(BookFileGroupingUtils.extractGroupingKey("Hobbit, The.pdf")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("Tale of Two Cities, A.epub")).isEqualTo("a tale of two cities"); + assertThat(BookFileGroupingUtils.extractGroupingKey("Unexpected Journey, An.pdf")).isEqualTo("an unexpected journey"); + } + + @Test + void extractGroupingKey_shouldHandleCombinedNormalizations() { + // Underscores + author + assertThat(BookFileGroupingUtils.extractGroupingKey("The_Hobbit - J.R.R. Tolkien.pdf")).isEqualTo("the hobbit"); + // Article + author + assertThat(BookFileGroupingUtils.extractGroupingKey("Hobbit, The - J.R.R. Tolkien.pdf")).isEqualTo("the hobbit"); + // Underscores + article + assertThat(BookFileGroupingUtils.extractGroupingKey("Hobbit,_The.pdf")).isEqualTo("the hobbit"); + } + + @Test + void calculateSimilarity_shouldReturnHighScoreForSimilarStrings() { + double similarity = BookFileGroupingUtils.calculateSimilarity("the hobbit", "the hobit"); + assertThat(similarity).isGreaterThan(0.8); + } + + @Test + void calculateSimilarity_shouldReturnPerfectScoreForIdenticalStrings() { + double similarity = BookFileGroupingUtils.calculateSimilarity("the hobbit", "the hobbit"); + assertThat(similarity).isEqualTo(1.0); + } + + @Test + void calculateSimilarity_shouldReturnLowScoreForDifferentStrings() { + double similarity = BookFileGroupingUtils.calculateSimilarity("the hobbit", "1984"); + assertThat(similarity).isLessThan(0.5); + } + + @Test + void calculateSimilarity_shouldHandleNullAndEmptyStrings() { + assertThat(BookFileGroupingUtils.calculateSimilarity(null, "test")).isEqualTo(0); + assertThat(BookFileGroupingUtils.calculateSimilarity("test", null)).isEqualTo(0); + assertThat(BookFileGroupingUtils.calculateSimilarity("", "test")).isEqualTo(0); + assertThat(BookFileGroupingUtils.calculateSimilarity("test", "")).isEqualTo(0); + } + + // ========== Folder-Centric Grouping Tests ========== + + @Test + void groupByBaseName_shouldGroupExtendedNamesMatchingFolderName() { + // The "American Gods" case - files with extended names should group with folder + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("American Gods") + .fileName("American Gods.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile mobi = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("American Gods") + .fileName("American Gods.mobi") + .bookFileType(BookFileType.MOBI) + .build(); + + LibraryFile m4b = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("American Gods") + .fileName("American Gods The Tenth Anniversary Edition (A Full Cast Production).m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, mobi, m4b)); + + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, mobi, m4b); + } + + @Test + void groupByBaseName_shouldGroupEditionVariantsWithFolderName() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile regular = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("The Hobbit") + .fileName("The Hobbit.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile anniversary = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("The Hobbit") + .fileName("The Hobbit 50th Anniversary Edition.pdf") + .bookFileType(BookFileType.PDF) + .build(); + + LibraryFile unabridged = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("The Hobbit") + .fileName("The Hobbit Unabridged.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(regular, anniversary, unabridged)); + + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(regular, anniversary, unabridged); + } + + @Test + void groupByBaseName_shouldKeepSeriesEntriesSeparate() { + // Harry Potter series should remain as separate books + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile book1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Harry Potter") + .fileName("Harry Potter Book 1.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile book2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Harry Potter") + .fileName("Harry Potter Book 2.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile book3 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Harry Potter") + .fileName("Harry Potter Book 3.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(book1, book2, book3)); + + assertThat(groups).hasSize(3); + } + + @Test + void groupByBaseName_shouldKeepSeriesWithNumbersSeparate() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile vol1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Lord of the Rings") + .fileName("Lord of the Rings Vol 1.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile vol2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Lord of the Rings") + .fileName("Lord of the Rings Vol 2.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(vol1, vol2)); + + assertThat(groups).hasSize(2); + } + + @Test + void groupByBaseName_shouldGroupSeriesFormatsWithSameNumber() { + // Same series entry in different formats should group + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile book1epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Harry Potter") + .fileName("Harry Potter Book 1.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile book1pdf = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Harry Potter") + .fileName("Harry Potter Book 1.pdf") + .bookFileType(BookFileType.PDF) + .build(); + + LibraryFile book2epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Harry Potter") + .fileName("Harry Potter Book 2.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(book1epub, book1pdf, book2epub)); + + assertThat(groups).hasSize(2); + // Book 1 should have 2 files + boolean foundBook1Group = groups.values().stream() + .anyMatch(list -> list.size() == 2 && list.containsAll(List.of(book1epub, book1pdf))); + assertThat(foundBook1Group).isTrue(); + } + + @Test + void groupByBaseName_shouldSeparateUnrelatedBooksInAuthorFolder() { + // Multiple different books by same author should stay separate + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile americanGods = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Neil Gaiman") + .fileName("American Gods.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile coraline = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Neil Gaiman") + .fileName("Coraline.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile stardust = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Neil Gaiman") + .fileName("Stardust.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(americanGods, coraline, stardust)); + + assertThat(groups).hasSize(3); + } + + @Test + void groupByBaseName_shouldUseExactMatchingForRootLevelFiles() { + // Files at root level (no subfolder) should use exact key matching + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath(null) + .fileName("The Hobbit.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile pdf = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath(null) + .fileName("The Hobbit.pdf") + .bookFileType(BookFileType.PDF) + .build(); + + LibraryFile other = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath(null) + .fileName("1984.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, pdf, other)); + + assertThat(groups).hasSize(2); + // Hobbit files should be grouped + boolean foundHobbitGroup = groups.values().stream() + .anyMatch(list -> list.size() == 2 && list.containsAll(List.of(epub, pdf))); + assertThat(foundHobbitGroup).isTrue(); + } + + @Test + void groupByBaseName_shouldGroupFilesWithAuthorVariationsMatchingFolder() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile basic = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("American Gods") + .fileName("American Gods.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile withAuthor = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("American Gods") + .fileName("American Gods - Neil Gaiman.mobi") + .bookFileType(BookFileType.MOBI) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(basic, withAuthor)); + + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(basic, withAuthor); + } + + @Test + void groupByBaseName_shouldHandleFolderBasedAudiobook() { + // Folder-based audiobook (MP3 folder) with ebook files + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("American Gods") + .fileName("American Gods.epub") + .bookFileType(BookFileType.EPUB) + .folderBased(false) + .build(); + + // Folder-based audiobook appears as "American Gods" subfolder + LibraryFile mp3Folder = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("American Gods") + .fileName("American Gods") + .bookFileType(BookFileType.AUDIOBOOK) + .folderBased(true) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, mp3Folder)); + + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, mp3Folder); + } + + @Test + void groupByBaseName_shouldHandleNestedFolderPath() { + // Files in nested folder like "Neil Gaiman/American Gods" + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Neil Gaiman/American Gods") + .fileName("American Gods.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile m4b = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Neil Gaiman/American Gods") + .fileName("American Gods 10th Anniversary.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, m4b)); + + // Should use last folder component "American Gods" as reference + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, m4b); + } + + @Test + void groupByBaseName_shouldGroupNestedAudiobookFolderWithEbooks() { + // Nested audiobook folder should group with ebooks in same parent folder + // Book Folder/ + // ├── Book.pdf + // ├── Book.epub + // └── Book Audiobook/ (folder-based audiobook) + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile pdf = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Book Folder") + .fileName("Book.pdf") + .bookFileType(BookFileType.PDF) + .build(); + + LibraryFile epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Book Folder") + .fileName("Book.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + // Folder-based audiobook appears as a file with folderBased=true + LibraryFile audiobookFolder = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Book Folder") + .fileName("Book Audiobook") + .bookFileType(BookFileType.AUDIOBOOK) + .folderBased(true) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(pdf, epub, audiobookFolder)); + + // All should be grouped together + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(pdf, epub, audiobookFolder); + } + + @Test + void groupByBaseName_shouldGroupAudiobookVariantNames() { + // Different audiobook naming conventions should all group + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("The Hobbit") + .fileName("The Hobbit.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile audiobook1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("The Hobbit") + .fileName("The Hobbit Audiobook") + .bookFileType(BookFileType.AUDIOBOOK) + .folderBased(true) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, audiobook1)); + + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, audiobook1); + } + + @Test + void groupByBaseName_shouldGroupFolderWithDotInName() { + // Folder-based audiobook with dot in name like "1. American Gods - Neil Gaiman (2011)" + // should group with ebooks in the same folder + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Neil Gaiman/American Gods") + .fileName("1. American Gods - Neil Gaiman (2011).epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile mobi = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Neil Gaiman/American Gods") + .fileName("1. American Gods - Neil Gaiman (2011).mobi") + .bookFileType(BookFileType.MOBI) + .build(); + + LibraryFile m4b = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Neil Gaiman/American Gods") + .fileName("1. American Gods - Neil Gaiman (2011).m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + // Folder-based audiobook - note: fileName is folder name without extension + LibraryFile mp3Folder = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Neil Gaiman/American Gods") + .fileName("1. American Gods - Neil Gaiman (2011)") + .bookFileType(BookFileType.AUDIOBOOK) + .folderBased(true) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, mobi, m4b, mp3Folder)); + + // All 4 files should be grouped as one book + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, mobi, m4b, mp3Folder); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/builder/LibraryTestBuilder.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/builder/LibraryTestBuilder.java index ffe905f1e..dc563242b 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/builder/LibraryTestBuilder.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/builder/LibraryTestBuilder.java @@ -110,8 +110,7 @@ public class LibraryTestBuilder { LibraryEntity library = new LibraryEntity(); library.setId(libraryId++); library.setName(name); - library.setScanMode(LibraryScanMode.FOLDER_AS_BOOK); - library.setDefaultBookFormat(BookFileType.EPUB); + library.setFormatPriority(List.of(BookFileType.EPUB)); library.setLibraryPaths(new ArrayList<>()); libraries.add(library); diff --git a/booklore-ui/ngsw-config.json b/booklore-ui/ngsw-config.json index a5814f5f2..d91195e14 100644 --- a/booklore-ui/ngsw-config.json +++ b/booklore-ui/ngsw-config.json @@ -1,6 +1,10 @@ { "$schema": "./node_modules/@angular/service-worker/config/schema.json", "index": "/index.html", + "navigationUrls": [ + "/**", + "!/api/**" + ], "assetGroups": [ { "name": "app", @@ -27,5 +31,17 @@ ] } } + ], + "dataGroups": [ + { + "name": "api-passthrough", + "urls": ["/api/**"], + "cacheConfig": { + "strategy": "freshness", + "maxSize": 0, + "maxAge": "0u", + "timeout": "0u" + } + } ] } diff --git a/booklore-ui/src/app/app.routes.ts b/booklore-ui/src/app/app.routes.ts index e3e8987a0..7afd536be 100644 --- a/booklore-ui/src/app/app.routes.ts +++ b/booklore-ui/src/app/app.routes.ts @@ -25,6 +25,7 @@ import {UserStatsGuard} from './core/security/guards/user-stats.guard'; import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard'; import {EbookReaderComponent} from './features/readers/ebook-reader'; import {LibraryStatsComponent} from './features/stats/component/library-stats/library-stats.component'; +import {AudiobookReaderComponent} from './features/readers/audiobook-reader/audiobook-reader.component'; export const routes: Routes = [ { @@ -73,6 +74,11 @@ export const routes: Routes = [ component: CbxReaderComponent, canActivate: [AuthGuard] }, + { + path: 'audiobook-reader/book/:bookId', + component: AudiobookReaderComponent, + canActivate: [AuthGuard] + }, { path: 'login', component: LoginComponent, diff --git a/booklore-ui/src/app/app.spec.ts b/booklore-ui/src/app/app.spec.ts new file mode 100644 index 000000000..25d9f2a65 --- /dev/null +++ b/booklore-ui/src/app/app.spec.ts @@ -0,0 +1,7 @@ +import {describe, expect, it} from 'vitest'; + +describe('App', () => { + it('should pass', () => { + expect(true).toBe(true); + }); +}); diff --git a/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html b/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html index 73e5a0a82..da3e8fd1a 100644 --- a/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html +++ b/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html @@ -1,4 +1,4 @@ -

+

@@ -10,233 +10,262 @@

-
-
-
-

- - Internal Authentication -

-

- Internal authentication is always enabled and cannot be disabled. However, OIDC can be used alongside internal authentication if OIDC is enabled. -

+
+
+

+ + Authentication Methods +

+

+ Choose which authentication methods are available for users to sign in. +

+
+ +
+
+
+
+
+
+ +
+
+ Internal Authentication + Always Enabled +
+
+

+ Built-in username and password authentication. This is the default method and cannot be disabled. +

+
+ + +
+ +
+
+
+
+ +
+
+ + OIDC Authentication + Experimental + + + {{ oidcEnabled ? 'Enabled' : 'Disabled' }} + +
+
+

+ OpenID Connect for single sign-on with external providers (Authentik, Keycloak, etc.). + + @if (!isOidcFormComplete() && !oidcEnabled) { + Configure settings below to enable. + } +

+
+ + +
+
+
+
+ +
+
+
+
+

+ + OIDC Provider Configuration +

+

+ Configure your OIDC provider settings. All fields are required to enable OIDC authentication. +

+
+ + +
+
+ +
+
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + + Required scopes for OIDC login. Must be supported by your provider. +
-
-
-
- - - +
+

Claim Mappings

+

+ Map OIDC token claims to Booklore user fields. These must match your provider's token claims. +

+
+
+ + +
+
+ + +
+
+ +
+
-
+ @if (oidcEnabled) { +
-

- - OIDC Authentication (Experimental) - -

-

- Configure external authentication providers using OpenID Connect (OIDC) protocol for seamless single sign-on integration. -

+
+
+

+ + User Provisioning +

+

+ Configure how new OIDC users are created and what permissions they receive. +

+
+ + +
-
-
-
- - - - @if (!isOidcFormComplete()) { -
- (Fill all required fields to enable) -
- } +
+
+
+
+ Automatic User Provisioning + + {{ autoUserProvisioningEnabled ? 'Enabled' : 'Disabled' }} + +
+

+ When enabled, new users are automatically created on first OIDC login with the permissions below. + When disabled, users must be manually created in Booklore before they can log in via OIDC. +

+ +
-
-

OIDC Provider Settings

-
-
-
- - -
-
- - -
-
- - -
- - - Required scopes for OIDC login and token exchange. Must be supported and advertised in the provider's discovery metadata. - + @if (autoUserProvisioningEnabled) { +
+
+

Default Permissions

+
+
+ + +
-
-
- - -
-
-
-
- - + @for (perm of availablePermissions; track perm) { +
+ + +
-
- - -
-
- - -
-
-
- - - These claims are used by Booklore to provision new OIDC users with their name, username, and email. Ensure they match the claims provided by your OIDC provider. - -
-
-
- - + }
-
-
- @if (oidcEnabled) { -
-

OIDC User Provisioning

-
-
-
- - - -
-
- - - Enabling auto-provisioning ensures that new users are automatically created with the selected default permissions. If turned off, users must be manually created in Booklore before they can log in. - -
-
- - @if (autoUserProvisioningEnabled) { -
-
Default permissions for auto-provisioned users
-
-
- - - -
- @for (perm of availablePermissions; track perm) { -
- - - -
- } -
- -
Default libraries for auto-provisioned users
-
- - -
- -
- - -
-
- } +
+

Default Library Access

+ +
}
-
+ }
diff --git a/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.scss b/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.scss index c796a33e5..05c517ca2 100644 --- a/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.scss +++ b/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.scss @@ -1,179 +1,204 @@ +@use '../../../shared/styles/settings-shared' as settings; + .main-container { - width: 100%; - padding: 1rem; - height: calc(100dvh - 10.5rem); - overflow-y: auto; - border-width: 1px; - border-radius: 0.5rem; - - @media (min-width: 768px) { - height: calc(100dvh - 11.65rem); - } + @include settings.settings-page-container; } -.enclosing-container { - border-color: var(--p-content-border-color); - background: var(--p-content-background); -} - -.settings-header { - margin-top: 1rem; - margin-bottom: 2rem; -} +@include settings.settings-page-header; .settings-title { - display: flex; - align-items: center; - gap: 0.75rem; - font-size: 1.25rem; - font-weight: 700; - color: var(--p-text-color); - margin: 0 0 0.75rem 0; - - .pi { - color: var(--p-primary-color); - font-size: 1.25rem; - } + @include settings.settings-page-title; + margin-bottom: 0.75rem; } .settings-description { - color: var(--p-text-muted-color); - font-size: 0.875rem; - line-height: 1.5; - margin-bottom: 1rem; -} - -.settings-content { - display: flex; - flex-direction: column; - gap: 3rem; -} - -.preferences-section { - @media (min-width: 768px) { - padding: 0 1rem; - } -} - -.section-header { - margin-bottom: 1rem; -} - -.section-title { - display: flex; - align-items: center; - gap: 0.5rem; - font-size: 1.125rem; - font-weight: 600; - color: var(--p-text-color); - margin: 0 0 0.5rem 0; - - .pi { - color: var(--p-primary-color); - } -} - -.section-description { - display: flex; - align-items: flex-start; - gap: 0.5rem; - color: var(--p-text-muted-color); - font-size: 0.875rem; - line-height: 1.5; - margin: 0; - - .pi { - color: var(--p-primary-color); - margin-top: 0.125rem; - flex-shrink: 0; - } + @include settings.settings-page-description; } .settings-card { - border: 1px solid var(--p-content-border-color); - border-radius: 8px; - background: var(--p-content-background); - padding: 1.5rem; - display: flex; - flex-direction: column; - gap: 1.5rem; + @include settings.settings-card; } -.auth-option { +.section-header { + @include settings.settings-section-header; +} + +.section-header-row { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + + @media (max-width: 767px) { + flex-direction: column; + align-items: stretch; + + p-button { + align-self: flex-end; + } + } +} + +.section-header-text { + flex: 1; +} + +.section-title { + @include settings.settings-section-title; +} + +.section-description { + @include settings.settings-section-description; +} + +.section-body { + @include settings.settings-section-body; +} + +// Authentication Methods List +.auth-methods-list { display: flex; flex-direction: column; gap: 0.75rem; } -.auth-control { - display: flex; - align-items: center; - gap: 1rem; -} - -.auth-label { - font-weight: 500; - color: var(--p-text-color); - min-width: 6rem; -} - -.auth-info { +.auth-method-item { display: flex; align-items: flex-start; - gap: 0.5rem; - font-size: 0.875rem; - color: var(--p-text-muted-color); - padding-left: 1rem; + justify-content: space-between; + gap: 1rem; + background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%); + border: 1px solid var(--p-content-border-color); + border-left: 3px solid var(--p-content-border-color); + border-radius: 6px; + padding: 1rem; + transition: border-color 0.2s ease, background 0.2s ease; + + &:hover:not(.is-locked) { + background: color-mix(in srgb, var(--ground-background) 40%, var(--p-surface-800) 60%); + } + + &.is-active { + border-left-color: var(--p-green-500); + } + + &.is-locked { + opacity: 0.8; + } + + @media (max-width: 600px) { + flex-direction: column; + gap: 0.75rem; + } +} + +.auth-method-content { + flex: 1; + min-width: 0; +} + +.auth-method-header { + display: flex; + align-items: center; + gap: 0.75rem; + margin-bottom: 0.5rem; +} + +.auth-method-icon { + display: flex; + align-items: center; + justify-content: center; + width: 36px; + height: 36px; + background: color-mix(in srgb, var(--p-primary-color) 15%, transparent); + color: var(--p-primary-color); + border-radius: 8px; + flex-shrink: 0; .pi { - margin-top: 0.125rem; - flex-shrink: 0; + font-size: 1rem; + } + + &.oidc { + background: color-mix(in srgb, var(--p-orange-500) 15%, transparent); + color: var(--p-orange-500); } } -.auth-status { - font-size: 0.875rem; - color: var(--p-text-muted-color); -} - -.provider-section, -.provisioning-section { - margin-top: 1rem; -} - -.subsection-title { - font-size: 1rem; - font-weight: 600; - color: var(--p-text-color); - margin-bottom: 1rem; -} - -.provider-form, -.provisioning-form { +.auth-method-info { display: flex; flex-direction: column; - gap: 1.5rem; + gap: 0.125rem; } -.form-grid { - display: grid; - grid-template-columns: 1fr; - gap: 1rem; +.auth-method-label { + display: flex; + align-items: center; + gap: 0.5rem; + font-weight: 600; + font-size: 0.9375rem; + color: var(--p-text-color); +} - @media (min-width: 768px) { - grid-template-columns: repeat(2, 1fr); +.experimental-badge { + display: inline-flex; + align-items: center; + padding: 0.125rem 0.5rem; + background: color-mix(in srgb, var(--p-orange-500) 15%, transparent); + color: var(--p-orange-500); + border-radius: 12px; + font-size: 0.625rem; + font-weight: 700; + text-transform: uppercase; +} + +.auth-method-status { + font-size: 0.8125rem; + font-weight: 600; + color: var(--p-text-muted-color); + + &.active { + color: var(--p-green-400); } } -.form-field { +.auth-method-description { + font-size: 0.875rem; + color: var(--p-text-muted-color); + line-height: 1.5; + margin: 0; + padding-left: calc(36px + 0.75rem); + + @media (max-width: 600px) { + padding-left: 0; + } +} + +.config-hint { + display: block; + color: var(--p-orange-400); + font-weight: 500; + margin-top: 0.25rem; +} + +// Configuration Grid +.config-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 1rem; + + @media (max-width: 768px) { + grid-template-columns: 1fr; + } +} + +.config-item { display: flex; flex-direction: column; gap: 0.5rem; - &.form-field-full { - @media (min-width: 768px) { - grid-column: 1 / -1; - } + &.full-width { + grid-column: 1 / -1; } label { @@ -181,57 +206,135 @@ color: var(--p-text-color); font-size: 0.875rem; } + + input { + width: 100%; + } +} + +.field-hint { + font-size: 0.8125rem; + color: var(--p-text-muted-color); + line-height: 1.4; +} + +// Claims Section +.claims-section { + margin-top: 1.5rem; + padding-top: 1.5rem; + border-top: 1px dashed var(--p-content-border-color); +} + +.subsection-title { + font-size: 0.9375rem; + font-weight: 600; + color: var(--p-text-color); + margin: 0 0 0.5rem 0; +} + +.subsection-description { + font-size: 0.875rem; + color: var(--p-text-muted-color); + line-height: 1.5; + margin: 0 0 1rem 0; } .claims-grid { display: grid; - grid-template-columns: 1fr; + grid-template-columns: repeat(3, 1fr); gap: 1rem; - @media (min-width: 768px) { - grid-template-columns: repeat(3, 1fr); + @media (max-width: 900px) { + grid-template-columns: 1fr 1fr; + } + + @media (max-width: 600px) { + grid-template-columns: 1fr; } } -.field-info { +// Provisioning Toggle +.provisioning-toggle { display: flex; align-items: flex-start; - gap: 0.5rem; - font-size: 0.875rem; - color: var(--p-text-muted-color); - margin-top: 0.5rem; + justify-content: space-between; + gap: 1rem; + background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%); + border: 1px solid var(--p-content-border-color); + border-left: 3px solid var(--p-primary-color); + border-radius: 6px; + padding: 1rem; - .pi { - margin-top: 0.125rem; - flex-shrink: 0; + @media (max-width: 600px) { + flex-direction: column; + gap: 0.75rem; } } -.form-actions { - display: flex; - justify-content: flex-start; - margin-top: 1rem; +.toggle-content { + flex: 1; + min-width: 0; } -.permissions-section { +.toggle-info { display: flex; flex-direction: column; - gap: 1rem; - margin-top: 1rem; -} - -.permissions-title { - font-size: 0.875rem; - font-weight: 600; - color: var(--p-text-color); + gap: 0.125rem; margin-bottom: 0.5rem; } -.permissions-list { +.toggle-label { + font-weight: 600; + font-size: 0.9375rem; + color: var(--p-text-color); +} + +.toggle-status { + font-size: 0.8125rem; + font-weight: 600; + color: var(--p-text-muted-color); + + &.active { + color: var(--p-green-400); + } +} + +.toggle-description { + font-size: 0.875rem; + color: var(--p-text-muted-color); + line-height: 1.5; + margin: 0; +} + +// Default Settings (Permissions & Libraries) +.default-settings { + display: flex; + flex-direction: column; + gap: 1.5rem; + margin-top: 1rem; + padding-top: 1rem; + border-top: 1px dashed var(--p-content-border-color); +} + +.permissions-group, +.libraries-group { display: flex; flex-direction: column; gap: 0.75rem; - padding-left: 1rem; +} + +.group-title { + font-size: 0.9375rem; + font-weight: 600; + color: var(--p-text-color); + margin: 0; +} + +.permissions-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); + gap: 0.625rem; + padding-left: 0.5rem; } .permission-item { @@ -246,15 +349,7 @@ } } -.libraries-section { - padding-left: 1rem; - margin-bottom: 1rem; -} - -.full-width { +.libraries-select { width: 100%; -} - -.info-icon { - color: #3b82f6; + max-width: 400px; } diff --git a/booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.html b/booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.html new file mode 100644 index 000000000..7f0fc2f50 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.html @@ -0,0 +1,238 @@ +
+
+
+ +
+
+

Add Physical Book

+

Catalog a physical book without a digital file

+
+ +
+ +
+
+ + +
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+ +
+
+
+ +
+ +
+ +
+ + +
+
+ +
+ +
+ + +
+ +
+ +
+
+ + +
+ +
+ + +
+
+ +
+
+ + +
+ +
+ + + +
+
+ +
+ +
+ +
+ + +
+
+
+ + +
diff --git a/booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.scss b/booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.scss new file mode 100644 index 000000000..c355b6284 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.scss @@ -0,0 +1,154 @@ +@use '../../../../shared/styles/panel-shared' as panel; + +.add-physical-book { + display: flex; + flex-direction: column; + min-width: 700px; + max-height: 90vh; + + @media (max-width: 768px) { + min-width: auto; + width: 100%; + } +} + +.panel-header { + @include panel.panel-header; +} + +.form-container { + display: flex; + flex-direction: column; + gap: 0.5rem; + padding: 1.25rem; + background: var(--card-background); + border: 1px solid var(--border-color); + border-top: none; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08); + overflow-y: auto; + max-height: calc(90vh - 200px); + + @media (max-width: 480px) { + padding: 0.75rem; + gap: 0.375rem; + } +} + +.form-row { + display: flex; + gap: 0.75rem; + + @media (max-width: 640px) { + flex-direction: column; + gap: 0.5rem; + } +} + +.flex-1 { + flex: 1; +} + +.flex-2 { + flex: 2; +} + +.form-group { + display: flex; + flex-direction: column; + gap: 0.25rem; + + &.highlight-group { + padding: 0.5rem; + } + + @media (max-width: 480px) { + gap: 0.25rem; + + &.highlight-group { + padding: 0.375rem; + } + } +} + +.form-label { + display: flex; + align-items: center; + gap: 0.375rem; + font-size: 0.9rem; + font-weight: 600; + color: var(--text-color); + + .label-icon { + color: var(--primary-color); + } + + .required-indicator { + color: var(--p-red-500); + margin-left: 0.125rem; + } + + @media (max-width: 480px) { + font-size: 0.85rem; + } +} + +.input-wrapper { + position: relative; + + .input-full { + width: 100%; + box-sizing: border-box; + } +} + +.input-full { + width: 100%; + box-sizing: border-box; +} + +.autocomplete-wrapper { + width: 100%; + + p-autocomplete { + width: 100%; + } +} + +.dialog-footer { + @include panel.dialog-footer; + border-top: none; +} + +.validation-message { + @include panel.validation-message; +} + +::ng-deep { + .p-inputnumber { + width: 100%; + } + + .p-inputnumber-input { + width: 100%; + } + + .p-autocomplete .p-chip .p-chip-label { + font-size: 12px; + } + + .p-autocomplete-input-chip { + width: 2rem; + } + + .p-autocomplete-clearable ul { + padding-inline-end: 2rem !important; + } + + .p-autocomplete-clearable .p-autocomplete-clear-icon { + right: 0px; + margin-top: -1rem; + width: 2rem; + height: 2rem; + padding: 0.5rem; + } +} diff --git a/booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.ts b/booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.ts new file mode 100644 index 000000000..59642a0f7 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/add-physical-book-dialog/add-physical-book-dialog.component.ts @@ -0,0 +1,168 @@ +import {Component, DestroyRef, inject, OnInit} from '@angular/core'; +import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {FormsModule} from '@angular/forms'; +import {Button} from 'primeng/button'; +import {InputText} from 'primeng/inputtext'; +import {Tooltip} from 'primeng/tooltip'; +import {Select} from 'primeng/select'; +import {Textarea} from 'primeng/textarea'; +import {InputNumber} from 'primeng/inputnumber'; +import {AutoComplete, AutoCompleteCompleteEvent} from 'primeng/autocomplete'; +import {BookService} from '../../service/book.service'; +import {LibraryService} from '../../service/library.service'; +import {Library} from '../../model/library.model'; +import {CreatePhysicalBookRequest} from '../../model/book.model'; +import {filter, take} from 'rxjs/operators'; +import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; + +@Component({ + selector: 'app-add-physical-book-dialog', + standalone: true, + templateUrl: './add-physical-book-dialog.component.html', + imports: [ + FormsModule, + Button, + InputText, + Tooltip, + Select, + Textarea, + InputNumber, + AutoComplete + ], + styleUrl: './add-physical-book-dialog.component.scss', +}) +export class AddPhysicalBookDialogComponent implements OnInit { + private dynamicDialogRef = inject(DynamicDialogRef); + private dialogConfig = inject(DynamicDialogConfig); + private bookService = inject(BookService); + private libraryService = inject(LibraryService); + private destroyRef = inject(DestroyRef); + + libraries: Library[] = []; + selectedLibraryId: number | null = null; + title: string = ''; + isbn: string = ''; + authors: string[] = []; + description: string = ''; + publisher: string = ''; + publishedDate: string = ''; + language: string = ''; + pageCount: number | null = null; + categories: string[] = []; + + allAuthors: string[] = []; + allCategories: string[] = []; + filteredAuthors: string[] = []; + filteredCategories: string[] = []; + + isLoading: boolean = false; + + ngOnInit(): void { + this.libraryService.libraryState$ + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(state => { + if (state.loaded && state.libraries) { + this.libraries = state.libraries; + if (this.dialogConfig.data?.libraryId) { + this.selectedLibraryId = this.dialogConfig.data.libraryId; + } else if (this.libraries.length > 0 && this.libraries[0].id !== undefined) { + this.selectedLibraryId = this.libraries[0].id; + } + } + }); + this.prepareAutoComplete(); + } + + private prepareAutoComplete(): void { + this.bookService.bookState$ + .pipe( + filter((bookState) => bookState.loaded), + take(1) + ) + .subscribe((bookState) => { + const authors = new Set(); + const categories = new Set(); + + (bookState.books ?? []).forEach((book) => { + book.metadata?.authors?.forEach((author) => authors.add(author)); + book.metadata?.categories?.forEach((category) => categories.add(category)); + }); + + this.allAuthors = Array.from(authors); + this.allCategories = Array.from(categories); + }); + } + + filterAuthors(event: AutoCompleteCompleteEvent): void { + const query = event.query.toLowerCase(); + this.filteredAuthors = this.allAuthors.filter((author) => + author.toLowerCase().includes(query) + ); + } + + filterCategories(event: AutoCompleteCompleteEvent): void { + const query = event.query.toLowerCase(); + this.filteredCategories = this.allCategories.filter((category) => + category.toLowerCase().includes(query) + ); + } + + onAutoCompleteKeyUp(fieldName: 'authors' | 'categories', event: KeyboardEvent): void { + if (event.key === 'Enter') { + const input = event.target as HTMLInputElement; + const value = input.value?.trim(); + if (value) { + const values = this[fieldName]; + if (!values.includes(value)) { + this[fieldName] = [...values, value]; + } + input.value = ''; + } + } + } + + onAutoCompleteSelect(fieldName: 'authors' | 'categories', event: { value: string, originalEvent: Event }): void { + const values = this[fieldName]; + if (!values.includes(event.value)) { + this[fieldName] = [...values, event.value]; + } + (event.originalEvent.target as HTMLInputElement).value = ''; + } + + cancel(): void { + this.dynamicDialogRef.close(); + } + + canCreate(): boolean { + return !!this.selectedLibraryId && (!!this.title.trim() || !!this.isbn.trim()); + } + + createBook(): void { + if (!this.canCreate() || this.isLoading) return; + + this.isLoading = true; + + const request: CreatePhysicalBookRequest = { + libraryId: this.selectedLibraryId!, + title: this.title.trim() || undefined, + isbn: this.isbn.trim() || undefined, + authors: this.authors.length > 0 ? this.authors : undefined, + description: this.description.trim() || undefined, + publisher: this.publisher.trim() || undefined, + publishedDate: this.publishedDate.trim() || undefined, + language: this.language.trim() || undefined, + pageCount: this.pageCount ?? undefined, + categories: this.categories.length > 0 ? this.categories : undefined + }; + + this.bookService.createPhysicalBook(request).subscribe({ + next: (book) => { + this.isLoading = false; + this.dynamicDialogRef.close(book); + }, + error: () => { + this.isLoading = false; + } + }); + } +} diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html index e7fd54092..229303017 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html @@ -370,7 +370,7 @@ tooltipPosition="top"> } - @if (userState.user!.permissions.canMoveOrganizeFiles) { + @if (userState.user!.permissions.canMoveOrganizeFiles && (appSettingsService.appSettings$ | async)?.diskType === 'LOCAL') { } + @if (userState.user!.permissions.canManageLibrary || userState.user!.permissions.admin) { + + + } @if (hasBulkReadActionsItems) {
+ selectedBookIds.includes(book.id) && !book.alternativeFormats?.length + ); + + if (sourceBooks.length === 0) { + this.messageService.add({ + severity: 'warn', + summary: 'No Eligible Books', + detail: 'Selected books must be single-file books (no alternative formats).' + }); + return; + } + + // Check if all books are from the same library + const libraryIds = new Set(sourceBooks.map(b => b.libraryId)); + if (libraryIds.size > 1) { + this.messageService.add({ + severity: 'warn', + summary: 'Multiple Libraries', + detail: 'All selected books must be from the same library.' + }); + return; + } + + this.dynamicDialogRef = this.dialogHelperService.openBulkBookFileAttacherDialog(sourceBooks); + if (this.dynamicDialogRef) { + this.dynamicDialogRef.onClose.subscribe(result => { + if (result?.success) { + this.bookSelectionService.deselectAll(); + } + }); + } + } + + canAttachFiles(): boolean { + if (this.selectedBooks.size === 0) return false; + + const currentState = this.bookService.getCurrentBookState(); + const selectedBookIds = Array.from(this.selectedBooks); + const eligibleBooks = (currentState.books || []).filter(book => + selectedBookIds.includes(book.id) && !book.alternativeFormats?.length + ); + + if (eligibleBooks.length === 0) return false; + + // Check if all eligible books are from the same library + const libraryIds = new Set(eligibleBooks.map(b => b.libraryId)); + return libraryIds.size === 1; + } + user() { return this.userService.getCurrentUser(); } diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html index 6868f66f3..aa651915f 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html +++ b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html @@ -2,20 +2,21 @@ [class.selected]="isSelected" (click)="onCardClick($event)"> -
+
- @if (showBookTypePill && book.bookType) { -
- {{ book.bookType }} + @if (showBookTypePill && getDisplayFormat(); as displayFormat) { +
+ {{ displayFormat }}
} @if (!book.seriesCount && book.metadata?.seriesNumber != null) { @@ -36,7 +37,7 @@ } - @if (!_isSeriesViewActive) { + @if (!_isSeriesViewActive && hasDigitalFile()) { } diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss index 7a4c01036..0c5fede8b 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss +++ b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss @@ -24,7 +24,6 @@ .book-cover { width: 100%; height: 100%; - object-fit: cover; border-radius: 8px 8px 0 0; opacity: 0; transition: opacity 0.2s ease-in; @@ -34,6 +33,14 @@ opacity: 1; } +.book-cover.square-cover { + object-fit: contain; +} + +.cover-container.audiobook-cover { + background-color: var(--surface-ground); +} + .cover-container::after { content: ""; position: absolute; @@ -288,6 +295,46 @@ color: #fff; } +.book-type-audiobook { + background: var(--book-type-audiobook-color); + color: #fff; +} + +.book-type-m4b { + background: var(--book-type-m4b-color); + color: #fff; +} + +.book-type-mp3 { + background: var(--book-type-mp3-color); + color: #fff; +} + +.book-type-m4a { + background: var(--book-type-m4a-color); + color: #fff; +} + +.book-type-cbz { + background: var(--book-type-cbz-color); + color: #fff; +} + +.book-type-cbr { + background: var(--book-type-cbr-color); + color: #fff; +} + +.book-type-cb7 { + background: var(--book-type-cb7-color); + color: #fff; +} + +.book-type-physical { + background: var(--book-type-physical-color); + color: #fff; +} + .read-status-indicator { display: flex; align-items: center; diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts index b459effe9..0ff7b181c 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts @@ -24,6 +24,7 @@ import {BookDialogHelperService} from '../book-dialog-helper.service'; import {TaskHelperService} from '../../../../settings/task-management/task-helper.service'; import {BookNavigationService} from '../../../service/book-navigation.service'; import {BookCardOverlayPreferenceService} from '../book-card-overlay-preference.service'; +import {AppSettingsService} from '../../../../../shared/service/app-settings.service'; @Component({ selector: 'app-book-card', @@ -66,6 +67,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { private bookDialogHelperService = inject(BookDialogHelperService); private bookNavigationService = inject(BookNavigationService); private cdr = inject(ChangeDetectorRef); + private appSettingsService = inject(AppSettingsService); protected _progressPercentage: number | null = null; protected _koProgressPercentage: number | null = null; @@ -80,11 +82,13 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { protected _seriesCountTooltip: string = ''; protected _titleTooltip: string = ''; protected _hasProgress: boolean = false; + protected _isAudiobook: boolean = false; private metadataCenterViewMode: 'route' | 'dialog' = 'route'; private destroy$ = new Subject(); protected readStatusHelper = inject(ReadStatusHelper); private user: User | null = null; + private diskType: string = 'LOCAL'; private menuInitialized = false; showBookTypePill = true; @@ -104,6 +108,16 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { this.metadataCenterViewMode = userState.user?.userSettings?.metadataCenterViewMode ?? 'route'; }); + this.appSettingsService.appSettings$ + .pipe( + filter(settings => !!settings), + take(1), + takeUntil(this.destroy$) + ) + .subscribe(settings => { + this.diskType = settings?.diskType ?? 'LOCAL'; + }); + if (this.overlayPreferenceService) { this.overlayPrefSub = this.overlayPreferenceService.showBookTypePill$.subscribe(val => { this.showBookTypePill = val; @@ -152,6 +166,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { this._seriesCountTooltip = 'Series collapsed: ' + this.book.seriesCount + ' books'; this._titleTooltip = 'Title: ' + this._displayTitle; + this._isAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK'; } get hasProgress(): boolean { @@ -446,7 +461,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { const items: MenuItem[] = []; const moreActions: MenuItem[] = []; - if (this.user?.permissions.canMoveOrganizeFiles) { + if (this.user?.permissions.canMoveOrganizeFiles && this.diskType === 'LOCAL') { moreActions.push({ label: 'Organize File', icon: 'pi pi-arrows-h', @@ -713,13 +728,28 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { }); } - private getFileExtension(filePath?: string): string | null { + getFileExtension(filePath?: string): string | null { if (!filePath) return null; const parts = filePath.split('.'); if (parts.length < 2) return null; return parts.pop()?.toUpperCase() || null; } + getDisplayFormat(): string | null { + if (!this.book?.primaryFile) { + return 'PHYSICAL'; + } + const ext = this.book?.primaryFile?.extension; + if (ext) { + return ext.toUpperCase(); + } + return this.getFileExtension(this.book?.primaryFile?.filePath); + } + + hasDigitalFile(): boolean { + return !!this.book?.primaryFile; + } + private getFileIcon(fileType: string | null): string { if (!fileType) return 'pi pi-file'; switch (fileType.toLowerCase()) { @@ -734,6 +764,11 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { case 'cbr': case 'cbx': return 'pi pi-image'; + case 'audiobook': + case 'm4b': + case 'm4a': + case 'mp3': + return 'pi pi-headphones'; default: return 'pi pi-file'; } diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts b/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts index 01f298b1e..afc45c391 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts @@ -15,6 +15,8 @@ import {BookMetadataCenterComponent} from '../../../metadata/component/book-meta import {CoverSearchComponent} from '../../../metadata/component/cover-search/cover-search.component'; import {Book} from '../../model/book.model'; import {AdditionalFileUploaderComponent} from '../additional-file-uploader/additional-file-uploader.component'; +import {BookFileAttacherComponent} from '../book-file-attacher/book-file-attacher.component'; +import {AddPhysicalBookDialogComponent} from '../add-physical-book-dialog/add-physical-book-dialog.component'; @Injectable({providedIn: 'root'}) export class BookDialogHelperService { @@ -152,4 +154,34 @@ export class BookDialogHelperService { }, }); } + + openBookFileAttacherDialog(sourceBook: Book): DynamicDialogRef | null { + return this.openDialog(BookFileAttacherComponent, { + showHeader: false, + styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`, + data: { + sourceBook: sourceBook, + }, + }); + } + + openBulkBookFileAttacherDialog(sourceBooks: Book[]): DynamicDialogRef | null { + return this.openDialog(BookFileAttacherComponent, { + showHeader: false, + styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`, + data: { + sourceBooks: sourceBooks, + }, + }); + } + + openAddPhysicalBookDialog(libraryId?: number): DynamicDialogRef | null { + return this.openDialog(AddPhysicalBookDialogComponent, { + showHeader: false, + styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`, + data: { + libraryId: libraryId, + }, + }); + } } diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.html b/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.html index 8a3411164..5d57bc649 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.html +++ b/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.html @@ -48,7 +48,7 @@ @if (truncatedFilters[filterType]) {
- Showing first 500 items + Showing first 100 items
} } @@ -60,7 +60,7 @@
diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.ts index aef33bfaf..493e48c05 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.ts @@ -142,7 +142,7 @@ function getMatchScoreRangeFilters(score?: number | null): { id: string; name: s } function getBookTypeFilter(book: Book): { id: string; name: string }[] { - return book.bookType ? [{id: book.bookType, name: book.bookType}] : []; + return book.primaryFile?.bookType ? [{id: book.primaryFile.bookType, name: book.primaryFile.bookType}] : []; } export const readStatusLabels: Record = { @@ -230,14 +230,14 @@ export class BookFilterComponent implements OnInit, OnDestroy { userService = inject(UserService); bookRuleEvaluatorService = inject(BookRuleEvaluatorService); userData$: Observable = this.userService.userState$; - filterSortingMode: FilterSortingMode = 'alphabetical'; + filterSortingMode: FilterSortingMode = 'count'; ngOnInit(): void { this.userData$.pipe( filter(userState => !!userState?.user && userState.loaded), takeUntil(this.destroy$) ).subscribe(userState => { - this.filterSortingMode = userState.user!.userSettings.filterSortingMode ?? 'alphabetical'; + this.filterSortingMode = userState.user!.userSettings.filterSortingMode ?? 'count'; }); combineLatest([ @@ -344,8 +344,8 @@ export class BookFilterComponent implements OnInit, OnDestroy { return aKey.localeCompare(bKey); }); - const isTruncated = sorted.length > 500; - const truncated = sorted.slice(0, 500); + const isTruncated = sorted.length > 100; + const truncated = sorted.slice(0, 100); return {items: truncated, isTruncated}; }), diff --git a/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts deleted file mode 100644 index 1582f91c5..000000000 --- a/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts +++ /dev/null @@ -1,143 +0,0 @@ -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {CoverScalePreferenceService} from './cover-scale-preference.service'; -import {MessageService} from 'primeng/api'; -import {LocalStorageService} from '../../../../shared/service/local-storage.service'; -import {take} from 'rxjs/operators'; - -describe('CoverScalePreferenceService', () => { - let messageServiceMock: any; - let localStorageServiceMock: any; - - beforeEach(() => { - messageServiceMock = {add: vi.fn()}; - localStorageServiceMock = { - set: vi.fn(), - get: vi.fn() - }; - - TestBed.configureTestingModule({ - providers: [ - CoverScalePreferenceService, - {provide: MessageService, useValue: messageServiceMock}, - {provide: LocalStorageService, useValue: localStorageServiceMock} - ] - }); - - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.clearAllMocks(); - vi.useRealTimers(); - }); - - it('should initialize with default scale if nothing in storage', () => { - localStorageServiceMock.get.mockReturnValueOnce(null); - const injector = TestBed.inject(EnvironmentInjector); - const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); - expect(service.scaleFactor).toBe(1.0); - }); - - it('should initialize with saved scale from storage', () => { - localStorageServiceMock.get.mockReturnValueOnce(1.5); - const injector = TestBed.inject(EnvironmentInjector); - const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); - expect(service.scaleFactor).toBe(1.5); - }); - - it('should ignore NaN value from storage', () => { - localStorageServiceMock.get.mockReturnValueOnce(NaN); - const injector = TestBed.inject(EnvironmentInjector); - const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); - expect(service.scaleFactor).toBe(1.0); - }); - - it('initScaleValue sets scaleFactor', () => { - localStorageServiceMock.get.mockReturnValue(null); - const injector = TestBed.inject(EnvironmentInjector); - const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); - service.initScaleValue(2.2); - expect(service.scaleFactor).toBe(2.2); - service.initScaleValue(undefined); - expect(service.scaleFactor).toBe(1.0); - }); - - it('setScale updates scaleFactor and emits on scaleChange$', () => { - localStorageServiceMock.get.mockReturnValue(null); - const injector = TestBed.inject(EnvironmentInjector); - const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); - const spy = vi.fn(); - service.scaleChange$.pipe(take(1)).subscribe(spy); - service.setScale(1.8); - expect(service.scaleFactor).toBe(1.8); - expect(spy).toHaveBeenCalledWith(1.8); - }); - - it('currentCardSize returns correct dimensions', () => { - localStorageServiceMock.get.mockReturnValue(null); - const injector = TestBed.inject(EnvironmentInjector); - const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); - service.scaleFactor = 2; - expect(service.currentCardSize).toEqual({width: 270, height: 440}); - service.scaleFactor = 0.5; - expect(service.currentCardSize).toEqual({width: 68, height: 110}); - }); - - it('gridColumnMinWidth returns correct string', () => { - localStorageServiceMock.get.mockReturnValue(null); - const injector = TestBed.inject(EnvironmentInjector); - const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); - service.scaleFactor = 1.23; - expect(service.gridColumnMinWidth).toBe(`${Math.round(135 * 1.23)}px`); - }); - - it('saveScalePreference saves to localStorage and shows success message', () => { - localStorageServiceMock.get.mockReturnValue(null); - const injector = TestBed.inject(EnvironmentInjector); - const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); - service['saveScalePreference'](1.25); - expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.25); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ - severity: 'success', - summary: 'Cover Size Saved', - detail: expect.stringContaining('1.25') - })); - }); - - it('saveScalePreference handles errors and shows error message', () => { - localStorageServiceMock.get.mockReturnValue(null); - localStorageServiceMock.set.mockImplementation(() => { - throw new Error('fail'); - }); - const injector = TestBed.inject(EnvironmentInjector); - const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); - service['saveScalePreference'](1.1); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ - severity: 'error', - summary: 'Save Failed' - })); - }); - - it('setScale triggers debounced saveScalePreference', () => { - localStorageServiceMock.get.mockReturnValue(null); - const injector = TestBed.inject(EnvironmentInjector); - const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); - service.setScale(1.7); - vi.advanceTimersByTime(1000); - expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.7); - }); - - it('debounced save only triggers once for rapid setScale calls', () => { - localStorageServiceMock.get.mockReturnValue(null); - const injector = TestBed.inject(EnvironmentInjector); - const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); - service.setScale(1.1); - service.setScale(1.2); - service.setScale(1.3); - vi.advanceTimersByTime(1000); - expect(localStorageServiceMock.set).toHaveBeenCalledTimes(1); - expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.3); - }); -}); diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts deleted file mode 100644 index 621ed0f25..000000000 --- a/booklore-ui/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts +++ /dev/null @@ -1,167 +0,0 @@ -import {beforeEach, describe, expect, it} from 'vitest'; -import {Subject} from 'rxjs'; -import {HeaderFilter} from './HeaderFilter'; -import {BookState} from '../../../model/state/book-state.model'; - -const makeBook = (overrides: any = {}) => ({ - id: 1, - metadata: { - bookId: 1, - title: 'Test Title', - authors: ['John Doe'], - seriesName: 'Test Series', - categories: ['Fiction'], - isbn10: '1234567890', - isbn13: '9781234567897', - ...overrides.metadata - }, - ...overrides -}); - -const baseState: BookState = { - books: [ - makeBook(), - makeBook({id: 2, metadata: {bookId: 2, title: 'Another Book', authors: ['Jane Smith'], seriesName: 'Another Series', categories: ['Nonfiction'], isbn10: '0987654321', isbn13: '9780987654321'}}), - makeBook({id: 3, metadata: {bookId: 3, title: 'Éxample Łatin', authors: ['Åuthor Æther'], seriesName: 'Série', categories: ['Categøry'], isbn10: 'ø123', isbn13: 'æ456'}}), - makeBook({id: 4, metadata: {bookId: 4, title: 'Special!@#$', authors: ['O\'Connor'], seriesName: '', categories: [], isbn10: '', isbn13: ''}}) - ], - loaded: true, - error: null -}; - -describe('HeaderFilter', () => { - let search$: Subject; - let filter: HeaderFilter; - - beforeEach(() => { - search$ = new Subject(); - filter = new HeaderFilter(search$.asObservable()); - }); - - it('returns original state if search term is less than 2 chars', () => { - filter.filter(baseState).subscribe(result => { - expect(result).toBe(baseState); - }); - search$.next('a'); - }); - - it('filters by title (case-insensitive, normalized)', () => { - filter.filter(baseState).subscribe(result => { - expect(result.books?.length).toBe(1); - expect(result.books?.[0]?.metadata?.title).toBe('Test Title'); - }); - search$.next('test'); - }); - - it('filters by author', () => { - filter.filter(baseState).subscribe(result => { - expect(result.books?.length).toBe(1); - expect(result.books?.[0]?.metadata?.authors?.[0]).toBe('Jane Smith'); - }); - search$.next('smith'); - }); - - const expectBooksWithTitles = (searchTerm: string, expectedCount: number, expectedTitles: string[]) => { - filter.filter(baseState).subscribe(result => { - expect(result.books?.length).toBe(expectedCount); - const titles = result.books?.map(b => b.metadata?.title); - expectedTitles.forEach(title => expect(titles).toContain(title)); - }); - search$.next(searchTerm); - }; - - it('filters by series', () => { - expectBooksWithTitles('series', 2, ['Test Title', 'Another Book']); - }); - - it('filters by category', () => { - expectBooksWithTitles('fiction', 2, ['Test Title', 'Another Book']); - }); - - it('filters by isbn10', () => { - filter.filter(baseState).subscribe(result => { - expect(result.books?.length).toBe(1); - expect(result.books?.[0]?.metadata?.isbn10).toBe('1234567890'); - }); - search$.next('1234567890'); - }); - - it('filters by isbn13', () => { - filter.filter(baseState).subscribe(result => { - expect(result.books?.length).toBe(1); - expect(result.books?.[0]?.metadata?.isbn13).toBe('9780987654321'); - }); - search$.next('9780987654321'); - }); - - it('normalizes diacritics and special chars', () => { - filter.filter(baseState).subscribe(result => { - expect(result.books?.length).toBe(1); - expect(result.books?.[0]?.metadata?.title).toBe('Éxample Łatin'); - }); - search$.next('example latin'); - }); - - it('normalizes special Unicode chars in categories (ø -> o)', () => { - filter.filter(baseState).subscribe(result => { - expect(result.books?.length).toBe(1); - expect(result.books?.[0]?.metadata?.categories?.[0]).toBe('Categøry'); - }); - search$.next('category'); - }); - - it('removes punctuation and matches', () => { - filter.filter(baseState).subscribe(result => { - expect(result.books?.length).toBe(1); - expect(result.books?.[0]?.metadata?.title).toBe('Special!@#$'); - }); - search$.next('special'); - }); - - it('returns empty books if no match', () => { - filter.filter(baseState).subscribe(result => { - expect(result.books).toEqual([]); - }); - search$.next('notfound'); - }); - - it('handles undefined fields gracefully', () => { - const state: BookState = { - books: [ - { - id: 5, - bookType: 'EPUB', - libraryId: 1, - libraryName: 'Test Library', - metadata: { - bookId: 5, - title: undefined, - authors: undefined, - seriesName: undefined, - categories: undefined, - isbn10: undefined, - isbn13: undefined - } - } - ], - loaded: true, - error: null - }; - filter.filter(state).subscribe(result => { - expect(result.books).toEqual([]); - }); - search$.next('anything'); - }); - - it('distinctUntilChanged prevents duplicate emissions for same search term', async () => { - const emissions: any[] = []; - const subscription = filter.filter(baseState).subscribe(result => { - emissions.push(result); - }); - search$.next('test'); - search$.next('test'); - await new Promise(resolve => setTimeout(resolve, 600)); - expect(emissions.length).toBe(1); - subscription.unsubscribe(); - }); -}); diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts deleted file mode 100644 index ac667c032..000000000 --- a/booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts +++ /dev/null @@ -1,244 +0,0 @@ -import {beforeEach, describe, expect, it, vi, afterEach} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {BehaviorSubject, firstValueFrom, of, Subject} from 'rxjs'; -import {SeriesCollapseFilter} from './SeriesCollapseFilter'; -import {MessageService} from 'primeng/api'; -import {UserService} from '../../../../settings/user-management/user.service'; -import {BookState} from '../../../model/state/book-state.model'; -import {Book} from '../../../model/book.model'; - -describe('SeriesCollapseFilter', () => { - let userServiceMock: any; - let messageServiceMock: any; - let userStateSubject: BehaviorSubject; - let currentUser: any; - - beforeEach(() => { - userStateSubject = new BehaviorSubject({ - user: null, - loaded: false, - error: null - }); - - currentUser = { - id: 1, - userSettings: { - entityViewPreferences: { - global: {seriesCollapsed: false}, - overrides: [] - } - } - }; - - userServiceMock = { - userState$: userStateSubject.asObservable(), - getCurrentUser: vi.fn(() => currentUser), - updateUserSetting: vi.fn() - }; - - messageServiceMock = {add: vi.fn()}; - - TestBed.configureTestingModule({ - providers: [ - SeriesCollapseFilter, - {provide: UserService, useValue: userServiceMock}, - {provide: MessageService, useValue: messageServiceMock} - ] - }); - - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.clearAllMocks(); - vi.useRealTimers(); - }); - - function createService(): SeriesCollapseFilter { - const injector = TestBed.inject(EnvironmentInjector); - return runInInjectionContext(injector, () => TestBed.inject(SeriesCollapseFilter)); - } - - it('should initialize with default collapsed=false', () => { - const service = createService(); - expect(service.isSeriesCollapsed).toBe(false); - }); - - it('should apply global preference on userState$ emit', () => { - currentUser.userSettings.entityViewPreferences.global.seriesCollapsed = true; - userServiceMock.getCurrentUser.mockReturnValue(currentUser); - const service = createService(); - userStateSubject.next({user: currentUser, loaded: true, error: null}); - expect(service.isSeriesCollapsed).toBe(true); - }); - - it('should apply override preference for context', () => { - currentUser.userSettings.entityViewPreferences.overrides = [ - {entityType: 'LIBRARY', entityId: 42, preferences: {seriesCollapsed: true}} - ]; - userServiceMock.getCurrentUser.mockReturnValue(currentUser); - const service = createService(); - service.setContext('LIBRARY', 42); - userStateSubject.next({user: currentUser, loaded: true, error: null}); - expect(service.isSeriesCollapsed).toBe(true); - }); - - it('should fallback to old seriesCollapse field for global', () => { - currentUser.userSettings.entityViewPreferences.global = {seriesCollapse: true}; - delete currentUser.userSettings.entityViewPreferences.global.seriesCollapsed; - userServiceMock.getCurrentUser.mockReturnValue(currentUser); - const service = createService(); - userStateSubject.next({user: currentUser, loaded: true, error: null}); - expect(service.isSeriesCollapsed).toBe(true); - }); - - it('should fallback to old seriesCollapse field for override', () => { - currentUser.userSettings.entityViewPreferences.overrides = [ - {entityType: 'SHELF', entityId: 99, preferences: {seriesCollapse: true}} - ]; - userServiceMock.getCurrentUser.mockReturnValue(currentUser); - const service = createService(); - service.setContext('SHELF', 99); - userStateSubject.next({user: currentUser, loaded: true, error: null}); - expect(service.isSeriesCollapsed).toBe(true); - }); - - it('setCollapsed should update value and trigger persistence after debounce', () => { - const service = createService(); - service.setCollapsed(true); - expect(service.isSeriesCollapsed).toBe(true); - vi.advanceTimersByTime(500); - expect(userServiceMock.updateUserSetting).toHaveBeenCalled(); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ - severity: 'success', - summary: 'Preference Saved', - detail: expect.stringContaining('enabled') - })); - }); - - it('setCollapsed should persist override if context set', () => { - const service = createService(); - service.setContext('MAGIC_SHELF', 123); - service.setCollapsed(true); - vi.advanceTimersByTime(500); - expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith( - 1, - 'entityViewPreferences', - expect.objectContaining({ - overrides: expect.arrayContaining([ - expect.objectContaining({ - entityType: 'MAGIC_SHELF', - entityId: 123, - preferences: expect.objectContaining({seriesCollapsed: true}) - }) - ]) - }) - ); - }); - - it('setCollapsed should persist global if no context', () => { - const service = createService(); - service.setCollapsed(true); - vi.advanceTimersByTime(500); - expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith( - 1, - 'entityViewPreferences', - expect.objectContaining({ - global: expect.objectContaining({seriesCollapsed: true}) - }) - ); - }); - - it('should not persist if no user', () => { - userServiceMock.getCurrentUser.mockReturnValue(null); - const service = createService(); - service.setCollapsed(true); - vi.advanceTimersByTime(500); - expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled(); - }); - - it('should filter books and collapse series', async () => { - const service = createService(); - service.setCollapsed(true); - - const books: Book[] = [ - {id: 1, metadata: {seriesName: 'A', seriesNumber: 2}, title: 'B1'} as any, - {id: 2, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B2'} as any, - {id: 3, metadata: {seriesName: 'B', seriesNumber: 1}, title: 'B3'} as any, - {id: 4, metadata: {}, title: 'B4'} as any - ]; - const state: BookState = {books, loaded: true, error: null}; - - const result = await firstValueFrom(service.filter(state)); - expect(result && result.books).toBeTruthy(); - if (!result || !result.books) throw new Error('No books in result'); - expect(result.books.length).toBe(3); - // Series A collapsed to one book with seriesBooks of length 2 - const a = result.books.find(b => b.metadata?.seriesName === 'A'); - expect(a).toBeDefined(); - expect(a?.seriesBooks?.length).toBe(2); - expect(a?.seriesCount).toBe(2); - // Series B collapsed to one book with seriesBooks of length 1 - const b = result.books.find(b => b.metadata?.seriesName === 'B'); - expect(b).toBeDefined(); - expect(b?.seriesBooks?.length).toBe(1); - expect(b?.seriesCount).toBe(1); - // Non-series book remains - expect(result.books.some(b => b['title'] === 'B4')).toBe(true); - }); - - it('should not collapse series if forceExpandSeries=true', async () => { - const service = createService(); - service.setCollapsed(true); - - const books: Book[] = [ - {id: 1, metadata: {seriesName: 'A', seriesNumber: 2}, title: 'B1'} as any, - {id: 2, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B2'} as any - ]; - const state: BookState = {books, loaded: true, error: null}; - - const result = await firstValueFrom(service.filter(state, true)); - expect(result && result.books).toBeTruthy(); - if (!result || !result.books) throw new Error('No books in result'); - expect(result.books.length).toBe(2); - }); - - it('should return original state if books is null', async () => { - const service = createService(); - service.setCollapsed(true); - const state: BookState = {books: null, loaded: true, error: null}; - const result = await firstValueFrom(service.filter(state)); - expect(result).toBe(state); - }); - - it('should not collapse if isSeriesCollapsed is false', async () => { - const service = createService(); - service.setCollapsed(false); - const books: Book[] = [ - {id: 1, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B1'} as any - ]; - const state: BookState = {books, loaded: true, error: null}; - const result = await firstValueFrom(service.filter(state)); - expect(result && result.books).toBeTruthy(); - if (!result || !result.books) throw new Error('No books in result'); - expect(result.books.length).toBe(1); - expect(result.books[0]?.seriesBooks).toBeUndefined(); - }); - - it('should clean up destroy$ on ngOnDestroy', () => { - const service = createService(); - const spy = vi.spyOn(service['destroy$'], 'next'); - service.ngOnDestroy(); - expect(spy).toHaveBeenCalled(); - }); - - it('setContext(null, null) resets context and applies preference', () => { - const service = createService(); - const applyPrefSpy = vi.spyOn(service as any, 'applyPreference'); - service.setContext(null, null); - expect((service as any).currentContext).toBeNull(); - expect(applyPrefSpy).toHaveBeenCalled(); - }); -}); - diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.spec.ts deleted file mode 100644 index 83095478f..000000000 --- a/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.spec.ts +++ /dev/null @@ -1,629 +0,0 @@ -import {beforeEach, describe, expect, it} from 'vitest'; -import {BehaviorSubject, firstValueFrom} from 'rxjs'; -import {doesBookMatchReadStatus, isFileSizeInRange, isMatchScoreInRange, isPageCountInRange, isRatingInRange, isRatingInRange10, SideBarFilter} from './SidebarFilter'; -import {BookState} from '../../../model/state/book-state.model'; -import {Book, ReadStatus} from '../../../model/book.model'; -import {Shelf} from '../../../model/shelf.model'; - -describe('SidebarFilter helpers', () => { - it('isRatingInRange returns true for value in range', () => { - expect(isRatingInRange(3.0, '3to4')).toBe(true); - expect(isRatingInRange(3.99, '3to4')).toBe(true); - expect(isRatingInRange(4.0, '3to4')).toBe(false); - }); - it('isRatingInRange returns false for value out of range', () => { - expect(isRatingInRange(4.5, '3to4')).toBe(false); - expect(isRatingInRange(2.9, '3to4')).toBe(false); - }); - it('isRatingInRange10 matches rounded rating', () => { - expect(isRatingInRange10(7.2, '7')).toBe(true); - expect(isRatingInRange10(7.7, '8')).toBe(true); - expect(isRatingInRange10(7.2, '8')).toBe(false); - }); - it('isFileSizeInRange returns true for value in range', () => { - expect(isFileSizeInRange(0, '<1mb')).toBe(true); - expect(isFileSizeInRange(1023, '<1mb')).toBe(true); - expect(isFileSizeInRange(1024, '<1mb')).toBe(false); - }); - it('isFileSizeInRange returns false for value out of range', () => { - expect(isFileSizeInRange(2000, '<1mb')).toBe(false); - expect(isFileSizeInRange(-1, '<1mb')).toBe(false); - }); - it('isPageCountInRange returns true for value in range', () => { - expect(isPageCountInRange(100, '100to200')).toBe(true); - expect(isPageCountInRange(199, '100to200')).toBe(true); - expect(isPageCountInRange(200, '100to200')).toBe(false); - }); - it('isPageCountInRange returns false for value out of range', () => { - expect(isPageCountInRange(50, '100to200')).toBe(false); - expect(isPageCountInRange(200, '100to200')).toBe(false); - }); - it('isMatchScoreInRange returns true for value in range', () => { - expect(isMatchScoreInRange(0.80, '0.80-0.89')).toBe(true); - expect(isMatchScoreInRange(0.89, '0.80-0.89')).toBe(true); - expect(isMatchScoreInRange(0.90, '0.80-0.89')).toBe(false); - expect(isMatchScoreInRange(85, '0.80-0.89')).toBe(true); - }); - it('isMatchScoreInRange returns false for value out of range', () => { - expect(isMatchScoreInRange(0.5, '0.80-0.89')).toBe(false); - expect(isMatchScoreInRange(0.95, '0.80-0.89')).toBe(false); - }); - it('doesBookMatchReadStatus returns true if status matches', () => { - const book = {readStatus: ReadStatus.READ} as Book; - expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(true); - }); - it('doesBookMatchReadStatus returns false if status does not match', () => { - const book = {readStatus: ReadStatus.UNREAD} as Book; - expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(false); - }); - it('doesBookMatchReadStatus returns true for unset if included', () => { - const book = {} as Book; - expect(doesBookMatchReadStatus(book, [ReadStatus.UNSET])).toBe(true); - }); - it('isRatingInRange returns false for unknown rangeId', () => { - expect(isRatingInRange(3.5, 'not-a-range')).toBe(false); - }); - it('isRatingInRange returns false for null/undefined rating', () => { - expect(isRatingInRange(undefined, '3to4')).toBe(false); - expect(isRatingInRange(null, '3to4')).toBe(false); - }); - it('isRatingInRange10 returns false for null/undefined rating', () => { - expect(isRatingInRange10(undefined, '7')).toBe(false); - expect(isRatingInRange10(null, '7')).toBe(false); - }); - it('isFileSizeInRange returns false for unknown rangeId', () => { - expect(isFileSizeInRange(500, 'not-a-range')).toBe(false); - }); - it('isFileSizeInRange returns false for null/undefined fileSize', () => { - expect(isFileSizeInRange(undefined, '<1mb')).toBe(false); - }); - it('isPageCountInRange returns false for unknown rangeId', () => { - expect(isPageCountInRange(150, 'not-a-range')).toBe(false); - }); - it('isPageCountInRange returns false for null/undefined pageCount', () => { - expect(isPageCountInRange(undefined, '100to200')).toBe(false); - }); - it('isMatchScoreInRange returns false for unknown rangeId', () => { - expect(isMatchScoreInRange(0.85, 'not-a-range')).toBe(false); - }); - it('isMatchScoreInRange returns false for null/undefined score', () => { - expect(isMatchScoreInRange(undefined, '0.80-0.89')).toBe(false); - expect(isMatchScoreInRange(null, '0.80-0.89')).toBe(false); - }); - it('doesBookMatchReadStatus returns false if selected is empty', () => { - const book = {readStatus: ReadStatus.READ} as Book; - expect(doesBookMatchReadStatus(book, [])).toBe(false); - }); - it('doesBookMatchReadStatus returns false if status is not in selected', () => { - const book = {readStatus: ReadStatus.READING} as Book; - expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(false); - }); -}); - -describe('SideBarFilter', () => { - let books: Book[]; - let bookState: BookState; - - beforeEach(() => { - // Create fresh book objects for each test to prevent mutation pollution - books = [ - { - id: 1, - libraryId: 1, - libraryName: 'Lib1', - metadata: { - bookId: 1, - authors: ['A1'], - categories: ['C1'], - moods: ['M1'], - tags: ['T1'], - publisher: 'P1', - seriesName: 'S1', - amazonRating: 4.2, - goodreadsRating: 3.8, - hardcoverRating: 4.0, - ranobedbRating: 3.5, - publishedDate: '2020-01-01', - pageCount: 150, - language: 'en' - }, - personalRating: 7, - fileSizeKb: 500, - shelves: [{name: 'shelf1', icon: 'icon1'}] as Shelf[], - metadataMatchScore: 0.8, - bookType: 'EPUB', - readStatus: ReadStatus.READ - } as Book, - { - id: 2, - libraryId: 1, - libraryName: 'Lib1', - metadata: { - bookId: 2, - authors: ['A2'], - categories: ['C2'], - moods: ['M2'], - tags: ['T2'], - publisher: 'P2', - seriesName: 'S2', - amazonRating: 2.5, - goodreadsRating: 2.8, - hardcoverRating: 2.0, - ranobedbRating: 2.4, - publishedDate: '2019-01-01', - pageCount: 50, - language: 'fr' - }, - personalRating: 3, - fileSizeKb: 2000, - shelves: [] as Shelf[], - metadataMatchScore: 0.5, - bookType: 'PDF', - readStatus: ReadStatus.UNREAD - } as Book - ]; - bookState = {books, loaded: true, error: null}; - }); - - function filterWith(activeFilters: any, mode: 'and' | 'or' = 'and') { - const filter$ = new BehaviorSubject(activeFilters); - const mode$ = new BehaviorSubject(mode); - const filter = new SideBarFilter(filter$, mode$); - return filter.filter(bookState); - } - - it('filters by author (and mode)', async () => { - const result = await firstValueFrom(filterWith({author: ['A1']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.authors).toContain('A1'); - }); - - it('filters by author (or mode)', async () => { - const result = await firstValueFrom(filterWith({author: ['A1', 'A2']}, 'or')); - expect(result?.books?.length).toBe(2); - }); - - it('filters by category', async () => { - const result = await firstValueFrom(filterWith({category: ['C2']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.categories).toContain('C2'); - }); - - it('filters by mood', async () => { - const result = await firstValueFrom(filterWith({mood: ['M1']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.moods).toContain('M1'); - }); - - it('filters by tag', async () => { - const result = await firstValueFrom(filterWith({tag: ['T2']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.tags).toContain('T2'); - }); - - it('filters by publisher', async () => { - const result = await firstValueFrom(filterWith({publisher: ['P1']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.publisher).toBe('P1'); - }); - - it('filters by series', async () => { - const result = await firstValueFrom(filterWith({series: ['S2']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.seriesName).toBe('S2'); - }); - - it('filters by readStatus', async () => { - const result = await firstValueFrom(filterWith({readStatus: [ReadStatus.READ]}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.readStatus).toBe(ReadStatus.READ); - }); - - it('filters by amazonRating', async () => { - const result = await firstValueFrom(filterWith({amazonRating: ['4to4.5']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.amazonRating).toBeGreaterThanOrEqual(4); - }); - - it('filters by goodreadsRating', async () => { - const result = await firstValueFrom(filterWith({goodreadsRating: ['3to4']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.goodreadsRating).toBeGreaterThanOrEqual(3); - }); - - it('filters by hardcoverRating', async () => { - const result = await firstValueFrom(filterWith({hardcoverRating: ['2to3']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.hardcoverRating).toBeGreaterThanOrEqual(2); - }); - - it('filters by ranobedbRating', async () => { - const result = await firstValueFrom(filterWith({ranobedbRating: ['3to4']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.ranobedbRating).toBeGreaterThanOrEqual(3); - }); - - it('filters by personalRating', async () => { - const result = await firstValueFrom(filterWith({personalRating: ['7']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.personalRating).toBe(7); - }); - - it('filters by shelfStatus unshelved', async () => { - const result = await firstValueFrom(filterWith({shelfStatus: ['unshelved']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.shelves?.length).toBe(0); - }); - - it('filters by fileSize', async () => { - const result = await firstValueFrom(filterWith({fileSize: ['<1mb']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.fileSizeKb).toBeLessThan(1024); - }); - - it('filters by language', async () => { - const result = await firstValueFrom(filterWith({language: ['fr']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.language).toBe('fr'); - }); - - it('filters by pageCount', async () => { - const result = await firstValueFrom(filterWith({pageCount: ['100to200']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadata?.pageCount).toBeGreaterThanOrEqual(100); - }); - - it('filters by matchScore', async () => { - const result = await firstValueFrom(filterWith({matchScore: ['0.80-0.89']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.metadataMatchScore).toBeGreaterThanOrEqual(0.8); - }); - - it('filters by bookType', async () => { - const result = await firstValueFrom(filterWith({bookType: ['PDF']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.bookType).toBe('PDF'); - }); - - it('returns all books if no filters', async () => { - const result = await firstValueFrom(filterWith({}, 'and')); - expect(result?.books?.length).toBe(2); - }); - - it('returns all books if filters is null', async () => { - const filter$ = new BehaviorSubject(null); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(bookState)); - expect(result?.books?.length).toBe(2); - }); - - it('returns original state if books is null', async () => { - bookState.books = null as any; - const result = await firstValueFrom(filterWith({author: ['A1']}, 'and')); - expect(result).toBe(bookState); - expect(result.books).toBeNull(); - }); - - it('returns original state if books is undefined', async () => { - bookState.books = undefined as any; - const result = await firstValueFrom(filterWith({author: ['A1']}, 'and')); - expect(result).toBe(bookState); - expect(result.books).toBeUndefined(); - }); - - it('returns empty books array for empty bookState', async () => { - bookState.books = []; - const result = await firstValueFrom(filterWith({author: ['A1']}, 'and')); - expect(result?.books?.length).toBe(0); - }); - - it('filters by multiple authors in OR mode', async () => { - const result = await firstValueFrom(filterWith({author: ['A1', 'A2']}, 'or')); - expect(result?.books?.length).toBe(2); - }); - - it('filters by multiple categories in OR mode', async () => { - const result = await firstValueFrom(filterWith({category: ['C1', 'C2']}, 'or')); - expect(result?.books?.length).toBe(2); - }); - - it('filters by multiple moods in OR mode', async () => { - const result = await firstValueFrom(filterWith({mood: ['M1', 'M2']}, 'or')); - expect(result?.books?.length).toBe(2); - }); - - it('filters by multiple tags in OR mode', async () => { - const result = await firstValueFrom(filterWith({tag: ['T1', 'T2']}, 'or')); - expect(result?.books?.length).toBe(2); - }); - - it('filters by multiple publishers in OR mode', async () => { - const result = await firstValueFrom(filterWith({publisher: ['P1', 'P2']}, 'or')); - expect(result?.books?.length).toBe(2); - }); - - it('filters by multiple series in OR mode', async () => { - const result = await firstValueFrom(filterWith({series: ['S1', 'S2']}, 'or')); - expect(result?.books?.length).toBe(2); - }); - - it('returns true for empty filter values in OR mode', async () => { - const result = await firstValueFrom(filterWith({author: []}, 'or')); - expect(result?.books?.length).toBe(2); - }); - - it('returns false for empty filter values in AND mode', async () => { - const result = await firstValueFrom(filterWith({author: []}, 'and')); - expect(result?.books?.length).toBe(0); - }); - - it('filters with multiple filter types in AND mode', async () => { - const result = await firstValueFrom(filterWith({ - author: ['A1'], - category: ['C1'], - readStatus: [ReadStatus.READ] - }, 'and')); - expect(result?.books?.length).toBe(1); - }); - - it('filters with multiple filter types in OR mode', async () => { - const result = await firstValueFrom(filterWith({ - author: ['A1'], - category: ['C2'] - }, 'or')); - expect(result?.books?.length).toBe(2); - }); - - it('returns false for unknown filter type', async () => { - const result = await firstValueFrom(filterWith({unknownFilter: ['value']}, 'and')); - expect(result?.books?.length).toBe(0); - }); - - it('filters by shelfStatus shelved', async () => { - const result = await firstValueFrom(filterWith({shelfStatus: ['shelved']}, 'and')); - expect(result?.books?.length).toBe(1); - expect(result?.books?.[0]?.shelves?.length).toBeGreaterThan(0); - }); - - it('returns false for book without publishedDate', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, publishedDate: undefined}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({publishedDate: [2020]}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - expect(result?.books?.length).toBe(0); - }); - - it('filters by multiple authors in AND mode - all must match', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, authors: ['A1', 'A3']}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({author: ['A1', 'A3']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - expect(result?.books?.length).toBe(1); - }); - - it('filters by multiple categories in AND mode - all must match', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, categories: ['C1', 'C3']}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({category: ['C1', 'C3']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - expect(result?.books?.length).toBe(1); - }); - - it('filters by multiple moods in AND mode - all must match', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, moods: ['M1', 'M3']}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({mood: ['M1', 'M3']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - expect(result?.books?.length).toBe(1); - }); - - it('filters by multiple tags in AND mode - all must match', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, tags: ['T1', 'T3']}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({tag: ['T1', 'T3']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - expect(result?.books?.length).toBe(1); - }); - - it('filters by multiple publishers in AND mode - returns books matching all', async () => { - // Publisher can only have one value, so AND with multiple should return nothing - const result = await firstValueFrom(filterWith({publisher: ['P1', 'P2']}, 'and')); - expect(result?.books?.length).toBe(0); - }); - - it('filters by multiple series in AND mode - returns books matching all', async () => { - // Series can only have one value, so AND with multiple should return nothing - const result = await firstValueFrom(filterWith({series: ['S1', 'S2']}, 'and')); - expect(result?.books?.length).toBe(0); - }); - - it('handles book with null metadata', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: null as any}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({author: ['A1']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - // Book 1 has null metadata, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1' - expect(result?.books?.length).toBe(0); - }); - - it('handles book with undefined metadata', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: undefined as any}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({author: ['A1']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - // Book 1 has undefined metadata, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1' - expect(result?.books?.length).toBe(0); - }); - - it('handles book with null authors array', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, authors: null as any}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({author: ['A1']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - // Book 1 has null authors, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1' - expect(result?.books?.length).toBe(0); - }); - - it('handles book with undefined authors array', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, authors: undefined as any}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({author: ['A1']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - // Book 1 has undefined authors, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1' - expect(result?.books?.length).toBe(0); - }); - - it('handles book with null categories array', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, categories: null as any}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({category: ['C1']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - // Book 1 has null categories, so it doesn't match. Book 2 has category 'C2', doesn't match 'C1' - expect(result?.books?.length).toBe(0); - }); - - it('handles book with null moods array', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, moods: null as any}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({mood: ['M1']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - // Book 1 has null moods, so it doesn't match. Book 2 has mood 'M2', doesn't match 'M1' - expect(result?.books?.length).toBe(0); - }); - - it('handles book with null tags array', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, tags: null as any}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({tag: ['T1']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - // Book 1 has null tags, so it doesn't match. Book 2 has tag 'T2', doesn't match 'T1' - expect(result?.books?.length).toBe(0); - }); - - it('handles book with null publisher', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, publisher: null as any}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({publisher: ['P1']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - // Book 1 has null publisher, so it doesn't match. Book 2 has publisher 'P2', doesn't match 'P1' - expect(result?.books?.length).toBe(0); - }); - - it('handles book with null series', async () => { - const testBooks: Book[] = [ - {...books[0], metadata: {...books[0].metadata!, seriesName: null as any}}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({series: ['S1']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - // Book 1 has null series, so it doesn't match. Book 2 has series 'S2', doesn't match 'S1' - expect(result?.books?.length).toBe(0); - }); - - it('handles book with null shelves', async () => { - const testBooks: Book[] = [ - {...books[0], shelves: null as any}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({shelfStatus: ['unshelved']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - // Book 1 has null shelves (unshelved), book 2 has empty shelves array (also unshelved) - expect(result?.books?.length).toBe(2); - }); - - it('handles book with undefined shelves', async () => { - const testBooks: Book[] = [ - {...books[0], shelves: undefined as any}, - {...books[1]} - ]; - const testState = {...bookState, books: testBooks}; - const filter$ = new BehaviorSubject({shelfStatus: ['unshelved']}); - const mode$ = new BehaviorSubject<'and' | 'or'>('and'); - const filter = new SideBarFilter(filter$, mode$); - const result = await firstValueFrom(filter.filter(testState)); - // Book 1 has undefined shelves (unshelved), book 2 has empty shelves array (also unshelved) - expect(result?.books?.length).toBe(2); - }); - - it('filters by multiple readStatus values', async () => { - const result = await firstValueFrom(filterWith({readStatus: [ReadStatus.READ, ReadStatus.UNREAD]}, 'and')); - expect(result?.books?.length).toBe(2); - }); - - it('handles non-array filter values', async () => { - const result = await firstValueFrom(filterWith({author: 'A1' as any}, 'and')); - expect(result?.books?.length).toBe(0); - }); -}); diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.ts index 96d59f4d7..45060eece 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.ts @@ -123,7 +123,7 @@ export class SideBarFilter implements BookFilter { case 'matchScore': return filterValues.some(range => isMatchScoreInRange(book.metadataMatchScore, range)); case 'bookType': - return filterValues.includes(book.bookType); + return filterValues.includes(book.primaryFile?.bookType); default: return false; } diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts deleted file mode 100644 index 17fdc7a0e..000000000 --- a/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts +++ /dev/null @@ -1,119 +0,0 @@ -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {SidebarFilterTogglePrefService} from './sidebar-filter-toggle-pref.service'; -import {MessageService} from 'primeng/api'; -import {LocalStorageService} from '../../../../../shared/service/local-storage.service'; -import {take} from 'rxjs/operators'; - -describe('SidebarFilterTogglePrefService', () => { - let messageServiceMock: any; - let localStorageServiceMock: any; - let originalInnerWidth: number; - - beforeEach(() => { - messageServiceMock = {add: vi.fn()}; - localStorageServiceMock = { - set: vi.fn(), - get: vi.fn() - }; - originalInnerWidth = window.innerWidth; - Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 1024}); - - TestBed.configureTestingModule({ - providers: [ - SidebarFilterTogglePrefService, - {provide: MessageService, useValue: messageServiceMock}, - {provide: LocalStorageService, useValue: localStorageServiceMock} - ] - }); - }); - - afterEach(() => { - vi.clearAllMocks(); - Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: originalInnerWidth}); - }); - - function createService(): SidebarFilterTogglePrefService { - const injector = TestBed.inject(EnvironmentInjector); - return runInInjectionContext(injector, () => TestBed.inject(SidebarFilterTogglePrefService)); - } - - it('should initialize with true if no saved value and not narrow', () => { - localStorageServiceMock.get.mockReturnValueOnce(null); - const service = createService(); - expect(service.selectedShowFilter).toBe(true); - }); - - it('should initialize with saved value if present and not narrow', () => { - localStorageServiceMock.get.mockReturnValueOnce(false); - const service = createService(); - expect(service.selectedShowFilter).toBe(false); - }); - - it('should initialize with false if window is narrow', () => { - Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 600}); - const service = createService(); - expect(service.selectedShowFilter).toBe(false); - }); - - it('should emit value on showFilter$', async () => { - localStorageServiceMock.get.mockReturnValueOnce(null); - const service = createService(); - const val = await service.showFilter$.pipe(take(1)).toPromise(); - expect(val).toBe(true); - }); - - it('should update selectedShowFilter and persist preference', () => { - localStorageServiceMock.get.mockReturnValueOnce(null); - const service = createService(); - service.selectedShowFilter = false; - expect(service.selectedShowFilter).toBe(false); - expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', false); - }); - - it('should not persist if value is unchanged', () => { - localStorageServiceMock.get.mockReturnValueOnce(true); - const service = createService(); - localStorageServiceMock.set.mockClear(); - service.selectedShowFilter = true; - expect(localStorageServiceMock.set).not.toHaveBeenCalled(); - }); - - it('should toggle selectedShowFilter', () => { - localStorageServiceMock.get.mockReturnValueOnce(true); - const service = createService(); - service.toggle(); - expect(service.selectedShowFilter).toBe(false); - expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', false); - service.toggle(); - expect(service.selectedShowFilter).toBe(true); - expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', true); - }); - - it('should handle error in savePreference and show error message', () => { - localStorageServiceMock.get.mockReturnValueOnce(null); - localStorageServiceMock.set.mockImplementation(() => { - throw new Error('fail'); - }); - const service = createService(); - service.selectedShowFilter = false; - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ - severity: 'error', - summary: 'Save Failed' - })); - }); - - it('should call loadFromStorage and set correct value for wide screen', () => { - localStorageServiceMock.get.mockReturnValueOnce(true); - const service = createService(); - expect(service.selectedShowFilter).toBe(true); - }); - - it('should call loadFromStorage and set correct value for narrow screen', () => { - Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 500}); - const service = createService(); - expect(service.selectedShowFilter).toBe(false); - }); -}); - diff --git a/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts deleted file mode 100644 index 115b27567..000000000 --- a/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts +++ /dev/null @@ -1,99 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {BookSorter} from './BookSorter'; -import {SortDirection, SortOption} from '../../../model/sort.model'; - -describe('BookSorter', () => { - let applySortOption: (sort: SortOption) => void; - let sorter: BookSorter; - - beforeEach(() => { - applySortOption = vi.fn(); - sorter = new BookSorter(applySortOption); - }); - - it('should initialize with undefined selectedSort', () => { - expect(sorter.selectedSort).toBeUndefined(); - }); - - it('should have all default sort options', () => { - expect(sorter.sortOptions).toBeInstanceOf(Array); - expect(sorter.sortOptions.length).toBeGreaterThan(0); - expect(sorter.sortOptions.some(opt => opt.field === 'title')).toBe(true); - }); - - it('should set selectedSort and call applySortOption on sortBooks (first time)', () => { - sorter.sortBooks('author'); - expect(sorter.selectedSort).toMatchObject({ - field: 'author', - direction: SortDirection.ASCENDING - }); - expect(applySortOption).toHaveBeenCalledWith(sorter.selectedSort); - }); - - it('should toggle direction when sorting the same field again', () => { - sorter.sortBooks('title'); - const firstSort = {...sorter.selectedSort!}; - sorter.sortBooks('title'); - expect(sorter.selectedSort?.field).toBe('title'); - expect(sorter.selectedSort?.direction).not.toBe(firstSort.direction); - expect(applySortOption).toHaveBeenCalledTimes(2); - }); - - it('should reset direction to ASCENDING when sorting a new field', () => { - sorter.sortBooks('title'); - sorter.sortBooks('author'); - expect(sorter.selectedSort?.field).toBe('author'); - expect(sorter.selectedSort?.direction).toBe(SortDirection.ASCENDING); - }); - - it('should not change selectedSort or call applySortOption for unknown field', () => { - sorter.sortBooks('notAField'); - expect(sorter.selectedSort).toBeUndefined(); - expect(applySortOption).not.toHaveBeenCalled(); - }); - - it('should update sortOptions with correct icon for selected field and direction', () => { - sorter.sortBooks('title'); - const upIcon = 'pi pi-arrow-up'; - expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe(upIcon); - expect(sorter.sortOptions.filter(opt => opt.field !== 'title').every(opt => !(opt as any).icon)).toBe(true); - - sorter.sortBooks('title'); // toggle direction - const downIcon = 'pi pi-arrow-down'; - expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe(downIcon); - }); - - it('should only set icon for the selected field', () => { - sorter.sortBooks('author'); - sorter.sortBooks('title'); - expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe('pi pi-arrow-up'); - expect((sorter.sortOptions.find(opt => opt.field === 'author') as any)?.icon).toBe(''); - }); - - it('should preserve label and field when toggling direction', () => { - sorter.sortBooks('fileName'); - const {label, field} = sorter.selectedSort!; - sorter.sortBooks('fileName'); - expect(sorter.selectedSort?.label).toBe(label); - expect(sorter.selectedSort?.field).toBe(field); - }); - - it('should not throw if updateSortOptions is called with no selectedSort', () => { - // @ts-ignore - sorter.selectedSort = undefined; - expect(() => sorter.updateSortOptions()).toThrow(); - }); - - it('should not mutate original sortOptions array reference on updateSortOptions', () => { - const original = sorter.sortOptions; - sorter.sortBooks('title'); - expect(sorter.sortOptions).not.toBe(original); - }); - - it('should handle sorting "random" field', () => { - sorter.sortBooks('random'); - expect(sorter.selectedSort?.field).toBe('random'); - expect(sorter.selectedSort?.direction).toBe(SortDirection.ASCENDING); - expect(applySortOption).toHaveBeenCalledWith(sorter.selectedSort); - }); -}); diff --git a/booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts deleted file mode 100644 index 3b1a84c30..000000000 --- a/booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts +++ /dev/null @@ -1,140 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {MessageService} from 'primeng/api'; -import {TableColumnPreferenceService} from './table-column-preference.service'; -import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service'; - -describe('TableColumnPreferenceService', () => { - let service: TableColumnPreferenceService; - let userServiceMock: any; - let messageServiceMock: any; - - const allColumns = [ - {field: 'readStatus', header: 'Read'}, - {field: 'title', header: 'Title'}, - {field: 'authors', header: 'Authors'}, - {field: 'publisher', header: 'Publisher'}, - {field: 'seriesName', header: 'Series'}, - {field: 'seriesNumber', header: 'Series #'}, - {field: 'categories', header: 'Genres'}, - {field: 'publishedDate', header: 'Published'}, - {field: 'lastReadTime', header: 'Last Read'}, - {field: 'addedOn', header: 'Added'}, - {field: 'fileSizeKb', header: 'File Size'}, - {field: 'language', header: 'Language'}, - {field: 'isbn', header: 'ISBN'}, - {field: 'pageCount', header: 'Pages'}, - {field: 'amazonRating', header: 'Amazon'}, - {field: 'amazonReviewCount', header: 'AZ #'}, - {field: 'goodreadsRating', header: 'Goodreads'}, - {field: 'goodreadsReviewCount', header: 'GR #'}, - {field: 'hardcoverRating', header: 'Hardcover'}, - {field: 'hardcoverReviewCount', header: 'HC #'}, - {field: 'ranobedbRating', header: 'Ranobedb'}, - ]; - - const fallbackPreferences: TableColumnPreference[] = allColumns.map((col, index) => ({ - field: col.field, - visible: true, - order: index - })); - - beforeEach(() => { - userServiceMock = { - getCurrentUser: vi.fn(), - updateUserSetting: vi.fn() - }; - messageServiceMock = { - add: vi.fn() - }; - - TestBed.configureTestingModule({ - providers: [ - TableColumnPreferenceService, - {provide: UserService, useValue: userServiceMock}, - {provide: MessageService, useValue: messageServiceMock} - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - service = runInInjectionContext(injector, () => TestBed.inject(TableColumnPreferenceService)); - }); - - it('should initialize with fallback preferences if none provided', () => { - service.initPreferences(undefined); - expect(service.preferences).toEqual(fallbackPreferences); - }); - - it('should initialize with provided preferences', () => { - const savedPrefs: TableColumnPreference[] = [ - {field: 'title', visible: true, order: 0}, - {field: 'authors', visible: false, order: 1} - ]; - service.initPreferences(savedPrefs); - expect(service.preferences.find(p => p.field === 'title')?.visible).toBe(true); - expect(service.preferences.find(p => p.field === 'authors')?.visible).toBe(false); - expect(service.preferences.length).toBe(allColumns.length); - }); - - it('should return all columns', () => { - expect(service.allColumns).toEqual(allColumns); - }); - - it('should return visible columns sorted by order', () => { - const prefs: TableColumnPreference[] = [ - {field: 'title', visible: true, order: 1}, - {field: 'authors', visible: true, order: 0}, - {field: 'publisher', visible: false, order: 2} - ]; - service['preferencesSubject'].next([ - ...prefs, - ...fallbackPreferences.filter(p => !prefs.some(fp => fp.field === p.field)) - ]); - const visible = service.visibleColumns; - const fields = visible.map(col => col.field); - expect(fields.indexOf('authors')).toBeLessThan(fields.indexOf('title')); - expect(fields).not.toContain('publisher'); - }); - - it('should save visible columns and update preferences', () => { - const selectedColumns = [ - {field: 'title'}, - {field: 'authors'} - ]; - userServiceMock.getCurrentUser.mockReturnValue({id: 42}); - service.saveVisibleColumns(selectedColumns); - const prefs = service.preferences; - expect(prefs.find(p => p.field === 'title')?.visible).toBe(true); - expect(prefs.find(p => p.field === 'authors')?.visible).toBe(true); - expect(prefs.find(p => p.field === 'publisher')?.visible).toBe(false); - expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(42, 'tableColumnPreference', prefs); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ - severity: 'success', - summary: 'Preferences Saved' - })); - }); - - it('should not call updateUserSetting if no current user', () => { - userServiceMock.getCurrentUser.mockReturnValue(undefined); - service.saveVisibleColumns([{field: 'title'}]); - expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled(); - expect(messageServiceMock.add).not.toHaveBeenCalled(); - }); - - it('should get column header for known and unknown fields', () => { - expect(service['getColumnHeader']('title')).toBe('Title'); - expect(service['getColumnHeader']('unknown')).toBe('unknown'); - }); - - it('should merge saved preferences with all columns', () => { - const savedPrefs: TableColumnPreference[] = [ - {field: 'title', visible: false, order: 5} - ]; - const merged = service['mergeWithAllColumns'](savedPrefs); - expect(merged.find(p => p.field === 'title')?.visible).toBe(false); - expect(merged.length).toBe(allColumns.length); - expect(merged.find(p => p.field === 'authors')?.visible).toBe(true); - }); -}); - diff --git a/booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.html b/booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.html new file mode 100644 index 000000000..1df0743c0 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.html @@ -0,0 +1,116 @@ +
+
+
+ +
+
+

Attach {{ isBulkMode ? 'Files' : 'File' }} to Another Book

+

Move {{ isBulkMode ? 'these books\' files' : 'this book\'s file' }} to another book as alternative format{{ isBulkMode ? 's' : '' }}

+
+ + +
+ +
+ +
+

Source Book{{ isBulkMode ? 's' : '' }} ({{ sourceBooks.length }})

+
+ @for (book of sourceBooks; track book.id) { +
+
{{ book.metadata?.title || 'Unknown Title' }}
+ @if (book.metadata?.authors?.length) { +
{{ book.metadata?.authors?.join(', ') }}
+ } +
+ + {{ getSourceFileInfo(book) }} +
+
+ } +
+
+ + +
+

Select Target Book

+ + +
+
{{ book.metadata?.title || 'Unknown Title' }}
+ @if (book.metadata?.authors?.length) { +
{{ book.metadata.authors.join(', ') }}
+ } + @if (book.primaryFile) { +
{{ book.primaryFile.extension?.toUpperCase() || book.primaryFile.bookType }}
+ } +
+
+ + {{ getBookDisplayName(book) }} + +
+
+ + +
+ + + +
+ + +
+ +
+

This will move {{ isBulkMode ? 'the files from the selected books' : 'the file from the source book' }} to the target book as alternative format{{ isBulkMode ? 's' : '' }}.

+ @if (deleteSourceBooks) { +

The source book{{ isBulkMode ? ' records' : ' record' }} will be deleted (file{{ isBulkMode ? 's' : '' }} will be preserved in target book).

+ } @else { +

The source book{{ isBulkMode ? ' records' : ' record' }} will remain but will have no readable files.

+ } +
+
+ + +
+ + + + +
+
+
diff --git a/booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.scss b/booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.scss new file mode 100644 index 000000000..53ef2f125 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.scss @@ -0,0 +1,180 @@ +@use '../../../../shared/styles/panel-shared' as panel; + +.book-file-attacher-container { + display: flex; + flex-direction: column; + height: 100%; +} + +.panel-header { + @include panel.panel-header; + flex-shrink: 0; +} + +.dialog-content { + flex: 1; + overflow-y: auto; + min-height: 0; + padding: 1.5rem; + background: var(--card-background); + border: 1px solid var(--border-color); + border-top: none; + border-radius: 0 0 10px 10px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08); + display: flex; + flex-direction: column; + gap: 1.5rem; +} + +.section-title { + font-size: 0.875rem; + font-weight: 600; + color: var(--p-text-muted-color); + margin-bottom: 0.75rem; + text-transform: uppercase; + letter-spacing: 0.05em; +} + +.source-info { + .source-books-list { + display: flex; + flex-direction: column; + gap: 0.5rem; + max-height: 200px; + overflow-y: auto; + } + + .book-info-card { + background: var(--p-surface-100); + border-radius: 8px; + padding: 0.75rem 1rem; + border: 1px solid var(--border-color); + } + + .book-title { + font-weight: 600; + font-size: 0.9375rem; + margin-bottom: 0.125rem; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .book-authors { + color: var(--p-text-muted-color); + font-size: 0.8125rem; + margin-bottom: 0.375rem; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .file-info { + display: flex; + align-items: center; + gap: 0.5rem; + color: var(--p-primary-color); + font-size: 0.8125rem; + font-weight: 500; + + i { + font-size: 0.8125rem; + } + + span { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + } +} + +.target-selection { + :host ::ng-deep { + .full-width { + width: 100%; + } + } +} + +.book-suggestion { + padding: 0.25rem 0; + + .suggestion-title { + font-weight: 500; + margin-bottom: 0.125rem; + } + + .suggestion-authors { + font-size: 0.8125rem; + color: var(--p-text-muted-color); + } + + .suggestion-format { + font-size: 0.75rem; + color: var(--p-primary-color); + font-weight: 600; + margin-top: 0.25rem; + } +} + +.delete-option { + display: flex; + align-items: center; + gap: 0.75rem; + + .delete-label { + font-size: 0.9375rem; + cursor: pointer; + user-select: none; + } +} + +.warning-message { + display: flex; + gap: 0.75rem; + padding: 1rem; + background: var(--p-yellow-50); + border: 1px solid var(--p-yellow-200); + border-radius: 8px; + color: var(--p-yellow-800); + + i { + flex-shrink: 0; + font-size: 1.25rem; + margin-top: 0.125rem; + } + + .warning-text { + font-size: 0.875rem; + line-height: 1.5; + + p { + margin: 0; + + &:not(:last-child) { + margin-bottom: 0.5rem; + } + } + } +} + +:host-context(.p-dark) { + .warning-message { + background: rgba(234, 179, 8, 0.1); + border-color: rgba(234, 179, 8, 0.3); + color: var(--p-yellow-400); + } + + .source-info .book-info-card { + background: var(--p-surface-800); + } +} + +.action-buttons { + display: flex; + justify-content: flex-end; + gap: 0.75rem; + margin-top: auto; + padding-top: 0.5rem; +} diff --git a/booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.ts b/booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.ts new file mode 100644 index 000000000..cda270f25 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-file-attacher/book-file-attacher.component.ts @@ -0,0 +1,148 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/dynamicdialog'; +import { AutoComplete, AutoCompleteSelectEvent } from 'primeng/autocomplete'; +import { Button } from 'primeng/button'; +import { Checkbox } from 'primeng/checkbox'; +import { Subject, takeUntil } from 'rxjs'; +import { filter, take } from 'rxjs/operators'; +import { BookService } from '../../service/book.service'; +import { Book } from '../../model/book.model'; +import { MessageService } from 'primeng/api'; + +@Component({ + selector: 'app-book-file-attacher', + standalone: true, + imports: [ + FormsModule, + AutoComplete, + Button, + Checkbox + ], + templateUrl: './book-file-attacher.component.html', + styleUrls: ['./book-file-attacher.component.scss'] +}) +export class BookFileAttacherComponent implements OnInit, OnDestroy { + sourceBooks: Book[] = []; + targetBook: Book | null = null; + deleteSourceBooks = true; + isAttaching = false; + searchQuery = ''; + filteredBooks: Book[] = []; + + private destroy$ = new Subject(); + private allBooks: Book[] = []; + + constructor( + private dialogRef: DynamicDialogRef, + private config: DynamicDialogConfig, + private bookService: BookService, + private messageService: MessageService + ) {} + + ngOnInit(): void { + // Support both single book and multiple books + if (this.config.data.sourceBook) { + this.sourceBooks = [this.config.data.sourceBook]; + } else if (this.config.data.sourceBooks) { + this.sourceBooks = this.config.data.sourceBooks; + } + + if (this.sourceBooks.length === 0) { + this.closeDialog(); + return; + } + + // Get the library ID from first source book (all should be same library) + const libraryId = this.sourceBooks[0].libraryId; + const sourceBookIds = new Set(this.sourceBooks.map(b => b.id)); + + // Load all books from state and filter for same library, excluding source books + this.bookService.bookState$.pipe( + filter(state => state.loaded && !!state.books), + take(1), + takeUntil(this.destroy$) + ).subscribe(state => { + this.allBooks = (state.books || []).filter(book => + book.libraryId === libraryId && !sourceBookIds.has(book.id) + ); + }); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + get isBulkMode(): boolean { + return this.sourceBooks.length > 1; + } + + filterBooks(event: { query: string }): void { + const query = event.query.toLowerCase().trim(); + if (!query) { + this.filteredBooks = this.allBooks.slice(0, 20); + return; + } + + this.filteredBooks = this.allBooks + .filter(book => { + const title = book.metadata?.title?.toLowerCase() || ''; + const authors = book.metadata?.authors?.join(' ').toLowerCase() || ''; + return title.includes(query) || authors.includes(query); + }) + .slice(0, 20); + } + + onBookSelect(event: AutoCompleteSelectEvent): void { + this.targetBook = event.value as Book; + } + + onBookClear(): void { + this.targetBook = null; + } + + getBookDisplayName(book: Book): string { + const title = book.metadata?.title || `Book #${book.id}`; + const authors = book.metadata?.authors?.join(', '); + return authors ? `${title} - ${authors}` : title; + } + + getSourceFileInfo(book: Book): string { + const file = book.primaryFile; + if (!file) return 'Unknown file'; + const format = file.extension?.toUpperCase() || file.bookType || 'Unknown'; + return `${format} - ${file.fileName || 'Unknown filename'}`; + } + + canAttach(): boolean { + return !!this.targetBook && !this.isAttaching; + } + + attach(): void { + if (!this.targetBook) return; + + this.isAttaching = true; + + const sourceBookIds = this.sourceBooks.map(b => b.id); + + this.bookService.attachBookFiles( + this.targetBook.id, + sourceBookIds, + this.deleteSourceBooks + ).pipe( + takeUntil(this.destroy$) + ).subscribe({ + next: () => { + this.dialogRef.close({ success: true, deletedSourceBooks: this.deleteSourceBooks }); + }, + error: () => { + this.isAttaching = false; + } + }); + } + + closeDialog(): void { + this.dialogRef.close(); + } +} diff --git a/booklore-ui/src/app/features/book/components/series-page/series-page.component.html b/booklore-ui/src/app/features/book/components/series-page/series-page.component.html index 35177a01b..5a10df3ca 100644 --- a/booklore-ui/src/app/features/book/components/series-page/series-page.component.html +++ b/booklore-ui/src/app/features/book/components/series-page/series-page.component.html @@ -162,7 +162,7 @@ tooltipPosition="top"> } - @if (userState.user!.permissions.canMoveOrganizeFiles) { + @if (userState.user!.permissions.canMoveOrganizeFiles && (appSettingsService.appSettings$ | async)?.diskType === 'LOCAL') { { - let service: BookMenuService; - let confirmationService: any; - let messageService: any; - let bookService: any; - let loadingService: any; - - const mockUser: User = { - id: 1, - username: 'testuser', - email: 'test@example.com', - permissions: { - canBulkAutoFetchMetadata: true, - canBulkCustomFetchMetadata: true, - canBulkEditMetadata: true, - canBulkRegenerateCover: true, - canBulkResetBookReadStatus: true, - canBulkResetBookloreReadProgress: true, - canBulkResetKoReaderReadProgress: true - } - } as User; - - const mockUserNoPermissions: User = { - id: 2, - username: 'limiteduser', - email: 'limited@example.com', - permissions: { - canBulkAutoFetchMetadata: false, - canBulkCustomFetchMetadata: false, - canBulkEditMetadata: false, - canBulkRegenerateCover: false, - canBulkResetBookReadStatus: false, - canBulkResetBookloreReadProgress: false, - canBulkResetKoReaderReadProgress: false - } - } as User; - - beforeEach(() => { - confirmationService = { - confirm: vi.fn() - }; - - messageService = { - add: vi.fn() - }; - - bookService = { - updateBookReadStatus: vi.fn(), - resetProgress: vi.fn() - }; - - loadingService = { - show: vi.fn().mockReturnValue('loader-id'), - hide: vi.fn() - }; - - TestBed.configureTestingModule({ - providers: [ - BookMenuService, - {provide: ConfirmationService, useValue: confirmationService}, - {provide: MessageService, useValue: messageService}, - {provide: BookService, useValue: bookService}, - {provide: LoadingService, useValue: loadingService} - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - - service = runInInjectionContext( - injector, - () => TestBed.inject(BookMenuService) - ); - }); - - describe('getMetadataMenuItems', () => { - it('should return all metadata menu items when user has all permissions', () => { - const autoFetch = vi.fn(); - const fetch = vi.fn(); - const bulkEdit = vi.fn(); - const multiEdit = vi.fn(); - const regenerate = vi.fn(); - const generateCustomCovers = vi.fn(); - - const items = service.getMetadataMenuItems( - autoFetch, - fetch, - bulkEdit, - multiEdit, - regenerate, - generateCustomCovers, - mockUser - ); - - expect(items).toHaveLength(6); - expect(items[0].label).toBe('Auto Fetch Metadata'); - expect(items[0].icon).toBe('pi pi-bolt'); - expect(items[1].label).toBe('Custom Fetch Metadata'); - expect(items[1].icon).toBe('pi pi-sync'); - expect(items[2].label).toBe('Bulk Metadata Editor'); - expect(items[2].icon).toBe('pi pi-table'); - expect(items[3].label).toBe('Multi-Book Metadata Editor'); - expect(items[3].icon).toBe('pi pi-clone'); - expect(items[4].label).toBe('Regenerate Covers'); - expect(items[4].icon).toBe('pi pi-image'); - expect(items[5].label).toBe('Generate Custom Covers'); - expect(items[5].icon).toBe('pi pi-palette'); - }); - - it('should return empty array when user has no permissions', () => { - const items = service.getMetadataMenuItems( - vi.fn(), - vi.fn(), - vi.fn(), - vi.fn(), - vi.fn(), - vi.fn(), - mockUserNoPermissions - ); - - expect(items).toHaveLength(0); - }); - - it('should return empty array when user is null', () => { - const items = service.getMetadataMenuItems( - vi.fn(), - vi.fn(), - vi.fn(), - vi.fn(), - vi.fn(), - vi.fn(), - null - ); - - expect(items).toHaveLength(0); - }); - - it('should call command functions when menu items are clicked', () => { - const autoFetch = vi.fn(); - const fetch = vi.fn(); - const bulkEdit = vi.fn(); - const multiEdit = vi.fn(); - const regenerate = vi.fn(); - const generateCustomCovers = vi.fn(); - - const items = service.getMetadataMenuItems( - autoFetch, - fetch, - bulkEdit, - multiEdit, - regenerate, - generateCustomCovers, - mockUser - ); - - items[0].command!({} as any); - expect(autoFetch).toHaveBeenCalledOnce(); - - items[1].command!({} as any); - expect(fetch).toHaveBeenCalledOnce(); - - items[2].command!({} as any); - expect(bulkEdit).toHaveBeenCalledOnce(); - - items[3].command!({} as any); - expect(multiEdit).toHaveBeenCalledOnce(); - - items[4].command!({} as any); - expect(regenerate).toHaveBeenCalledOnce(); - - items[5].command!({} as any); - expect(generateCustomCovers).toHaveBeenCalledOnce(); - }); - - it('should return only items for granted permissions', () => { - const partialUser: User = { - ...mockUser, - permissions: { - ...mockUser.permissions, - canBulkAutoFetchMetadata: true, - canBulkCustomFetchMetadata: false, - canBulkEditMetadata: true, - canBulkRegenerateCover: false - } - } as User; - - const items = service.getMetadataMenuItems( - vi.fn(), - vi.fn(), - vi.fn(), - vi.fn(), - vi.fn(), - vi.fn(), - partialUser - ); - - expect(items).toHaveLength(3); - expect(items[0].label).toBe('Auto Fetch Metadata'); - expect(items[1].label).toBe('Bulk Metadata Editor'); - expect(items[2].label).toBe('Multi-Book Metadata Editor'); - }); - }); - - describe('getBulkReadActionsMenu', () => { - it('should return all read action items when user has all permissions', () => { - const selectedBooks = new Set([1, 2, 3]); - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - - expect(items).toHaveLength(3); - expect(items[0].label).toBe('Update Read Status'); - expect(items[0].icon).toBe('pi pi-book'); - expect(items[0].items).toBeDefined(); - expect(items[0].items!.length).toBeGreaterThan(0); - expect(items[1].label).toBe('Reset Booklore Progress'); - expect(items[1].icon).toBe('pi pi-undo'); - expect(items[2].label).toBe('Reset KOReader Progress'); - expect(items[2].icon).toBe('pi pi-undo'); - }); - - it('should return empty array when user has no permissions', () => { - const selectedBooks = new Set([1, 2, 3]); - const items = service.getBulkReadActionsMenu(selectedBooks, mockUserNoPermissions); - - expect(items).toHaveLength(0); - }); - - it('should return empty array when user is null', () => { - const selectedBooks = new Set([1, 2, 3]); - const items = service.getBulkReadActionsMenu(selectedBooks, null); - - expect(items).toHaveLength(0); - }); - - it('should show confirmation dialog when updating read status', () => { - const selectedBooks = new Set([1, 2, 3]); - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - - const readStatusItems = items[0].items!; - readStatusItems[0].command!({} as any); - - expect(confirmationService.confirm).toHaveBeenCalledOnce(); - const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; - expect(confirmCall.message).toContain('3 book(s)'); - expect(confirmCall.header).toBe('Confirm Read Status Update'); - }); - - it('should update read status on confirmation accept', () => { - const selectedBooks = new Set([1, 2, 3]); - vi.mocked(bookService.updateBookReadStatus).mockReturnValue(of([])); - - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - const readStatusItems = items[0].items!; - - const readItem = readStatusItems.find(item => item.label === 'Read'); - expect(readItem).toBeDefined(); - - readItem!.command!({} as any); - - const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; - confirmCall.accept!(); - - expect(loadingService.show).toHaveBeenCalledWith('Updating read status for 3 book(s)...'); - expect(bookService.updateBookReadStatus).toHaveBeenCalledWith([1, 2, 3], ReadStatus.READ); - expect(loadingService.hide).toHaveBeenCalledWith('loader-id'); - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'success', - summary: 'Read Status Updated', - detail: 'Marked as "Read"', - life: 2000 - }); - }); - - it('should show error message when read status update fails', () => { - const selectedBooks = new Set([1, 2]); - const errorResponse = new HttpErrorResponse({ - error: {message: 'Update failed'} as APIException, - status: 500 - }); - vi.mocked(bookService.updateBookReadStatus).mockReturnValue(throwError(() => errorResponse)); - - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - const readStatusItems = items[0].items!; - - readStatusItems[0].command!({} as any); - - const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; - confirmCall.accept!(); - - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'Update Failed', - detail: 'Update failed', - life: 3000 - }); - }); - - it('should show confirmation dialog when resetting Booklore progress', () => { - const selectedBooks = new Set([1, 2, 3]); - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - - items[1].command!({} as any); - - expect(confirmationService.confirm).toHaveBeenCalledOnce(); - const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; - expect(confirmCall.message).toContain('3 book(s)'); - expect(confirmCall.header).toBe('Confirm Reset'); - }); - - it('should reset Booklore progress on confirmation accept', () => { - const selectedBooks = new Set([5, 6]); - vi.mocked(bookService.resetProgress).mockReturnValue(of([])); - - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - items[1].command!({} as any); - - const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; - confirmCall.accept!(); - - expect(loadingService.show).toHaveBeenCalledWith('Resetting Booklore progress for 2 book(s)...'); - expect(bookService.resetProgress).toHaveBeenCalledWith([5, 6], ResetProgressTypes.BOOKLORE); - expect(loadingService.hide).toHaveBeenCalledWith('loader-id'); - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'success', - summary: 'Progress Reset', - detail: 'Booklore reading progress has been reset.', - life: 1500 - }); - }); - - it('should show error message when Booklore progress reset fails', () => { - const selectedBooks = new Set([1]); - const errorResponse = new HttpErrorResponse({ - error: {message: 'Reset failed'} as APIException, - status: 500 - }); - vi.mocked(bookService.resetProgress).mockReturnValue(throwError(() => errorResponse)); - - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - items[1].command!({} as any); - - const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; - confirmCall.accept!(); - - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'Failed', - detail: 'Reset failed', - life: 3000 - }); - }); - - it('should show confirmation dialog when resetting KOReader progress', () => { - const selectedBooks = new Set([7, 8]); - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - - items[2].command!({} as any); - - expect(confirmationService.confirm).toHaveBeenCalledOnce(); - const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; - expect(confirmCall.message).toContain('2 book(s)'); - expect(confirmCall.message).toContain('KOReader'); - expect(confirmCall.header).toBe('Confirm Reset'); - }); - - it('should reset KOReader progress on confirmation accept', () => { - const selectedBooks = new Set([9]); - vi.mocked(bookService.resetProgress).mockReturnValue(of([])); - - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - items[2].command!({} as any); - - const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; - confirmCall.accept!(); - - expect(loadingService.show).toHaveBeenCalledWith('Resetting KOReader progress for 1 book(s)...'); - expect(bookService.resetProgress).toHaveBeenCalledWith([9], ResetProgressTypes.KOREADER); - expect(loadingService.hide).toHaveBeenCalledWith('loader-id'); - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'success', - summary: 'Progress Reset', - detail: 'KOReader reading progress has been reset.', - life: 1500 - }); - }); - - it('should show error message when KOReader progress reset fails', () => { - const selectedBooks = new Set([10]); - const errorResponse = new HttpErrorResponse({ - error: {message: 'KOReader reset failed'} as APIException, - status: 500 - }); - vi.mocked(bookService.resetProgress).mockReturnValue(throwError(() => errorResponse)); - - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - items[2].command!({} as any); - - const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; - confirmCall.accept!(); - - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'Failed', - detail: 'KOReader reset failed', - life: 3000 - }); - }); - - it('should handle API error without message gracefully', () => { - const selectedBooks = new Set([1]); - const errorResponse = new HttpErrorResponse({ - error: {} as APIException, - status: 500 - }); - vi.mocked(bookService.updateBookReadStatus).mockReturnValue(throwError(() => errorResponse)); - - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - const readStatusItems = items[0].items!; - - readStatusItems[0].command!({} as any); - - const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; - confirmCall.accept!(); - - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'Update Failed', - detail: 'Could not update read status.', - life: 3000 - }); - }); - - it('should return only items for granted read permissions', () => { - const partialUser: User = { - ...mockUser, - permissions: { - ...mockUser.permissions, - canBulkResetBookReadStatus: true, - canBulkResetBookloreReadProgress: false, - canBulkResetKoReaderReadProgress: true - } - } as User; - - const selectedBooks = new Set([1, 2]); - const items = service.getBulkReadActionsMenu(selectedBooks, partialUser); - - expect(items).toHaveLength(2); - expect(items[0].label).toBe('Update Read Status'); - expect(items[1].label).toBe('Reset KOReader Progress'); - }); - - it('should not call bookService when confirmation is rejected', () => { - const selectedBooks = new Set([1, 2]); - const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); - - items[1].command!({} as any); - - const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; - confirmCall.reject?.(); - - expect(bookService.resetProgress).not.toHaveBeenCalled(); - expect(loadingService.show).not.toHaveBeenCalled(); - }); - }); -}); - diff --git a/booklore-ui/src/app/features/book/service/book-navigation.service.spec.ts b/booklore-ui/src/app/features/book/service/book-navigation.service.spec.ts deleted file mode 100644 index 96945fbc3..000000000 --- a/booklore-ui/src/app/features/book/service/book-navigation.service.spec.ts +++ /dev/null @@ -1,106 +0,0 @@ -import {beforeEach, describe, expect, it} from 'vitest'; -import {firstValueFrom} from 'rxjs'; -import {BookNavigationService} from './book-navigation.service'; - -describe('BookNavigationService', () => { - let service: BookNavigationService; - const bookIds = [10, 20, 30, 40]; - - beforeEach(() => { - service = new BookNavigationService(); - }); - - it('should set and get available book ids', () => { - service.setAvailableBookIds(bookIds); - expect(service.getAvailableBookIds()).toEqual(bookIds); - }); - - it('should set navigation context and emit state', async () => { - service.setNavigationContext(bookIds, 30); - - const state = await firstValueFrom(service.getNavigationState()); - - expect(state).not.toBeNull(); - expect(state!.bookIds).toEqual(bookIds); - expect(state!.currentIndex).toBe(2); - }); - - it('should emit null if currentBookId not in bookIds', async () => { - service.setNavigationContext(bookIds, 99); - - const state = await firstValueFrom(service.getNavigationState()); - - expect(state).toBeNull(); - }); - - it('should determine canNavigatePrevious correctly', () => { - service.setNavigationContext(bookIds, 10); - expect(service.canNavigatePrevious()).toBe(false); - - service.setNavigationContext(bookIds, 30); - expect(service.canNavigatePrevious()).toBe(true); - }); - - it('should determine canNavigateNext correctly', () => { - service.setNavigationContext(bookIds, 40); - expect(service.canNavigateNext()).toBe(false); - - service.setNavigationContext(bookIds, 20); - expect(service.canNavigateNext()).toBe(true); - }); - - it('should get previous book id', () => { - service.setNavigationContext(bookIds, 30); - expect(service.getPreviousBookId()).toBe(20); - - service.setNavigationContext(bookIds, 10); - expect(service.getPreviousBookId()).toBeNull(); - }); - - it('should get next book id', () => { - service.setNavigationContext(bookIds, 20); - expect(service.getNextBookId()).toBe(30); - - service.setNavigationContext(bookIds, 40); - expect(service.getNextBookId()).toBeNull(); - }); - - it('should update current book and emit new index', async () => { - service.setNavigationContext(bookIds, 10); - service.updateCurrentBook(30); - - const state = await firstValueFrom(service.getNavigationState()); - - expect(state!.currentIndex).toBe(2); - expect(state!.bookIds[state!.currentIndex]).toBe(30); - }); - - it('should not update current book if id not in list', async () => { - service.setNavigationContext(bookIds, 10); - service.updateCurrentBook(99); - - const state = await firstValueFrom(service.getNavigationState()); - - expect(state!.currentIndex).toBe(0); - expect(state!.bookIds[state!.currentIndex]).toBe(10); - }); - - it('should return current position', () => { - service.setNavigationContext(bookIds, 30); - expect(service.getCurrentPosition()).toEqual({current: 3, total: 4}); - }); - - it('should return null for current position if no state', () => { - expect(service.getCurrentPosition()).toBeNull(); - }); - - it('should handle navigation methods gracefully if state is null', () => { - expect(service.canNavigatePrevious()).toBe(false); - expect(service.canNavigateNext()).toBe(false); - expect(service.getPreviousBookId()).toBeNull(); - expect(service.getNextBookId()).toBeNull(); - - service.updateCurrentBook(10); - expect(service.getCurrentPosition()).toBeNull(); - }); -}); diff --git a/booklore-ui/src/app/features/book/service/book-patch.service.spec.ts b/booklore-ui/src/app/features/book/service/book-patch.service.spec.ts deleted file mode 100644 index 6c2b91e10..000000000 --- a/booklore-ui/src/app/features/book/service/book-patch.service.spec.ts +++ /dev/null @@ -1,171 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {HttpClient, HttpParams} from '@angular/common/http'; -import {of, throwError} from 'rxjs'; - -import {BookPatchService} from './book-patch.service'; -import {BookStateService} from './book-state.service'; -import {Book, ReadStatus} from '../model/book.model'; - -describe('BookPatchService', () => { - let service: BookPatchService; - let httpMock: any; - let bookStateServiceMock: any; - - const mockBooks: Book[] = [ - {id: 1, bookType: 'PDF', libraryId: 1, libraryName: 'Lib', dateFinished: undefined} as Book, - {id: 2, bookType: 'EPUB', libraryId: 1, libraryName: 'Lib', dateFinished: undefined} as Book, - ]; - - beforeEach(() => { - httpMock = { - post: vi.fn(), - put: vi.fn(), - }; - bookStateServiceMock = { - getCurrentBookState: vi.fn(), - updateBookState: vi.fn(), - }; - - TestBed.configureTestingModule({ - providers: [ - BookPatchService, - {provide: HttpClient, useValue: httpMock}, - {provide: BookStateService, useValue: bookStateServiceMock}, - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - service = runInInjectionContext( - injector, - () => TestBed.inject(BookPatchService) - ); - }); - - it('should update book shelves and update state', () => { - const updatedBooks = [{...mockBooks[0], id: 1, libraryName: 'Updated'}]; - httpMock.post.mockReturnValue(of(updatedBooks)); - bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); - service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])).subscribe(result => { - expect(result).toEqual(updatedBooks); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({ - books: expect.arrayContaining([expect.objectContaining({id: 1, libraryName: 'Updated'})]) - })); - }); - }); - - it('should save PDF progress', () => { - httpMock.post.mockReturnValue(of(void 0)); - service.savePdfProgress(1, 10, 0.5).subscribe(result => { - expect(result).toBeUndefined(); - expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), { - bookId: 1, - pdfProgress: {page: 10, percentage: 0.5} - }); - }); - }); - - it('should save EPUB progress', () => { - httpMock.post.mockReturnValue(of(void 0)); - service.saveEpubProgress(2, 'cfi123', 'href123', 0.8); - expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), { - bookId: 2, - epubProgress: {cfi: 'cfi123', href: 'href123', percentage: 0.8} - }); - }); - - it('should save CBX progress', () => { - httpMock.post.mockReturnValue(of(void 0)); - service.saveCbxProgress(3, 5, 0.2).subscribe(result => { - expect(result).toBeUndefined(); - expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), { - bookId: 3, - cbxProgress: {page: 5, percentage: 0.2} - }); - }); - }); - - it('should update date finished and update state', () => { - httpMock.post.mockReturnValue(of(void 0)); - bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); - service.updateDateFinished(1, '2023-01-01').subscribe(() => { - expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({ - books: expect.arrayContaining([expect.objectContaining({id: 1, dateFinished: '2023-01-01'})]) - })); - }); - }); - - it('should reset progress and update state', () => { - const responses = [{bookId: 1, readStatus: ReadStatus.UNREAD, readStatusModifiedTime: 'now', dateFinished: undefined}]; - httpMock.post.mockReturnValue(of(responses)); - bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); - service.resetProgress([1], 'BOOKLORE').subscribe(result => { - expect(result).toEqual(responses); - expect(httpMock.post).toHaveBeenCalledWith( - expect.stringContaining('/reset-progress'), - [1], - {params: expect.any(HttpParams)} - ); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); - }); - }); - - it('should update book read status and update state', () => { - const responses = [{bookId: 2, readStatus: ReadStatus.READING, readStatusModifiedTime: 'now', dateFinished: '2023-01-01'}]; - httpMock.post.mockReturnValue(of(responses)); - bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); - service.updateBookReadStatus([2], ReadStatus.READING).subscribe(result => { - expect(result).toEqual(responses); - expect(httpMock.post).toHaveBeenCalledWith( - expect.stringContaining('/status'), - {bookIds: [2], status: ReadStatus.READING} - ); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); - }); - }); - - it('should reset personal rating and update state', () => { - const responses = [{bookId: 1, personalRating: null}]; - httpMock.post.mockReturnValue(of(responses)); - bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); - service.resetPersonalRating([1]).subscribe(result => { - expect(result).toEqual(responses); - expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/reset-personal-rating'), [1]); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); - }); - }); - - it('should update personal rating and update state', () => { - const responses = [{bookId: 2, personalRating: 5}]; - httpMock.put.mockReturnValue(of(responses)); - bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); - service.updatePersonalRating([2], 5).subscribe(result => { - expect(result).toEqual(responses); - expect(httpMock.put).toHaveBeenCalledWith(expect.stringContaining('/personal-rating'), {ids: [2], rating: 5}); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); - }); - }); - - it('should update last read time in state', () => { - const now = new Date().toISOString(); - vi.useFakeTimers().setSystemTime(new Date(now)); - bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); - service.updateLastReadTime(1); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({ - books: expect.arrayContaining([expect.objectContaining({id: 1, lastReadTime: now})]) - })); - vi.useRealTimers(); - }); - - it('should handle errors from http.post gracefully', () => { - httpMock.post.mockReturnValue(throwError(() => new Error('fail'))); - service.savePdfProgress(1, 1, 1).subscribe({ - error: (err: any) => { - expect(err).toBeInstanceOf(Error); - expect(err.message).toBe('fail'); - } - }); - }); -}); - diff --git a/booklore-ui/src/app/features/book/service/book-patch.service.ts b/booklore-ui/src/app/features/book/service/book-patch.service.ts index 9b8529fb4..44f74ace0 100644 --- a/booklore-ui/src/app/features/book/service/book-patch.service.ts +++ b/booklore-ui/src/app/features/book/service/book-patch.service.ts @@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core'; import {HttpClient, HttpParams} from '@angular/common/http'; import {Observable, Subject} from 'rxjs'; import {distinctUntilChanged, exhaustMap, share, tap} from 'rxjs/operators'; -import {Book, ReadStatus} from '../model/book.model'; +import {Book, BookFileProgress, ReadStatus} from '../model/book.model'; import {BookStateService} from './book-state.service'; import {API_CONFIG} from '../../../core/config/api-config'; import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type'; @@ -17,17 +17,18 @@ export class BookPatchService { private http = inject(HttpClient); private bookStateService = inject(BookStateService); - private epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number }>(); + private epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number; bookFileId?: number }>(); private epubProgress$ = this.epubProgressSubject.pipe( distinctUntilChanged((prev, curr) => prev.bookId === curr.bookId && prev.cfi === curr.cfi && prev.href === curr.href && - prev.percentage === curr.percentage + prev.percentage === curr.percentage && + prev.bookFileId === curr.bookFileId ), exhaustMap(payload => { - const body = { + const body: any = { bookId: payload.bookId, epubProgress: { cfi: payload.cfi, @@ -35,6 +36,15 @@ export class BookPatchService { percentage: payload.percentage } }; + // Add file-level progress if bookFileId is provided + if (payload.bookFileId) { + body.fileProgress = { + bookFileId: payload.bookFileId, + positionData: payload.cfi, + positionHref: payload.href, + progressPercent: payload.percentage + }; + } return this.http.post(`${this.url}/progress`, body); }), share() @@ -65,29 +75,57 @@ export class BookPatchService { ); } - savePdfProgress(bookId: number, page: number, percentage: number): Observable { - const body = { + savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable { + const body: any = { bookId: bookId, pdfProgress: { page: page, percentage: percentage } }; + // Add file-level progress if bookFileId is provided + if (bookFileId) { + body.fileProgress = { + bookFileId: bookFileId, + positionData: String(page), + progressPercent: percentage + }; + } return this.http.post(`${this.url}/progress`, body); } - saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number): void { - this.epubProgressSubject.next({bookId, cfi, href, percentage}); + saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number, bookFileId?: number): void { + this.epubProgressSubject.next({bookId, cfi, href, percentage, bookFileId}); } - saveCbxProgress(bookId: number, page: number, percentage: number): Observable { - const body = { + saveCbxProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable { + const body: any = { bookId: bookId, cbxProgress: { page: page, percentage: percentage } }; + // Add file-level progress if bookFileId is provided + if (bookFileId) { + body.fileProgress = { + bookFileId: bookFileId, + positionData: String(page), + progressPercent: percentage + }; + } + return this.http.post(`${this.url}/progress`, body); + } + + /** + * Save file-level progress directly using the new API. + * This is the preferred method for per-file progress tracking. + */ + saveFileProgress(bookId: number, fileProgress: BookFileProgress): Observable { + const body = { + bookId: bookId, + fileProgress: fileProgress + }; return this.http.post(`${this.url}/progress`, body); } diff --git a/booklore-ui/src/app/features/book/service/book.service.spec.ts b/booklore-ui/src/app/features/book/service/book.service.spec.ts deleted file mode 100644 index 8ea737d70..000000000 --- a/booklore-ui/src/app/features/book/service/book.service.spec.ts +++ /dev/null @@ -1,511 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {HttpClient} from '@angular/common/http'; -import {firstValueFrom, of, throwError} from 'rxjs'; -import {BookService} from './book.service'; -import {BookStateService} from './book-state.service'; -import {BookSocketService} from './book-socket.service'; -import {BookPatchService} from './book-patch.service'; -import {MessageService} from 'primeng/api'; -import {AuthService} from '../../../shared/service/auth.service'; -import {FileDownloadService} from '../../../shared/service/file-download.service'; -import {Router} from '@angular/router'; -import {AdditionalFileType, Book, BookMetadata, ReadStatus} from '../model/book.model'; - -describe('BookService', () => { - let service: BookService; - let httpMock: any; - let messageServiceMock: any; - let authServiceMock: any; - let fileDownloadServiceMock: any; - let routerMock: any; - let bookStateServiceMock: any; - let bookSocketServiceMock: any; - let bookPatchServiceMock: any; - - beforeEach(() => { - httpMock = { - get: vi.fn(), - post: vi.fn(), - put: vi.fn(), - delete: vi.fn() - }; - messageServiceMock = {add: vi.fn()}; - authServiceMock = {token$: of('token')}; - fileDownloadServiceMock = {downloadFile: vi.fn()}; - routerMock = {navigate: vi.fn()}; - bookStateServiceMock = { - bookState$: of({books: [{id: 1, bookType: 'PDF', shelves: [], metadata: {seriesName: 'S'}}], loaded: true, error: null}), - getCurrentBookState: vi.fn(), - updateBookState: vi.fn(), - resetBookState: vi.fn() - }; - bookSocketServiceMock = { - handleNewlyCreatedBook: vi.fn(), - handleRemovedBookIds: vi.fn(), - handleBookUpdate: vi.fn(), - handleMultipleBookUpdates: vi.fn(), - handleBookMetadataUpdate: vi.fn(), - handleMultipleBookCoverPatches: vi.fn() - }; - bookPatchServiceMock = { - updateBookShelves: vi.fn(), - updateLastReadTime: vi.fn(), - savePdfProgress: vi.fn(), - saveEpubProgress: vi.fn(), - saveCbxProgress: vi.fn(), - updateDateFinished: vi.fn(), - resetProgress: vi.fn(), - updateBookReadStatus: vi.fn(), - resetPersonalRating: vi.fn(), - updatePersonalRating: vi.fn() - }; - - bookStateServiceMock.getCurrentBookState.mockReturnValue({ - books: [ - {id: 1, bookType: 'PDF', shelves: [{id: 10}], metadata: {seriesName: 'S'}, alternativeFormats: [], supplementaryFiles: [], fileName: 'file.pdf'}, - {id: 2, bookType: 'EPUB', shelves: [], metadata: {}, alternativeFormats: [], supplementaryFiles: [], fileName: 'file2.epub'} - ], - loaded: true, - error: null - }); - - TestBed.configureTestingModule({ - providers: [ - BookService, - {provide: HttpClient, useValue: httpMock}, - {provide: MessageService, useValue: messageServiceMock}, - {provide: AuthService, useValue: authServiceMock}, - {provide: FileDownloadService, useValue: fileDownloadServiceMock}, - {provide: Router, useValue: routerMock}, - {provide: BookStateService, useValue: bookStateServiceMock}, - {provide: BookSocketService, useValue: bookSocketServiceMock}, - {provide: BookPatchService, useValue: bookPatchServiceMock} - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - service = runInInjectionContext(injector, () => TestBed.inject(BookService)); - }); - - describe('State Management', () => { - it('should get current book state', () => { - expect(service.getCurrentBookState()).toEqual(bookStateServiceMock.getCurrentBookState()); - }); - - it('should fetch books and update state', async () => { - const books = [{id: 1}]; - httpMock.get.mockReturnValue(of(books)); - await firstValueFrom(service['fetchBooks']()); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({ - books, - loaded: true, - error: null - }); - }); - - it('should handle fetchBooks error', async () => { - httpMock.get.mockReturnValue(throwError(() => ({message: 'fail'}))); - bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: false, error: null}); - await expect(firstValueFrom(service['fetchBooks']())).rejects.toBeTruthy(); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({ - books: [], - loaded: true, - error: 'fail' - }); - }); - - it('should refreshBooks and update state', () => { - httpMock.get.mockReturnValue(of([{id: 1}])); - service.refreshBooks(); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({ - books: [{id: 1}], - loaded: true, - error: null - }); - }); - - it('should handle refreshBooks error', () => { - httpMock.get.mockReturnValue(throwError(() => ({message: 'fail'}))); - service.refreshBooks(); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({ - books: null, - loaded: true, - error: 'fail' - }); - }); - - it('should remove books by library id', () => { - bookStateServiceMock.getCurrentBookState.mockReturnValue({ - books: [{id: 1, libraryId: 2}, {id: 2, libraryId: 3}], - loaded: true, - error: null - }); - service.removeBooksByLibraryId(2); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({ - books: [{id: 2, libraryId: 3}], - loaded: true, - error: null - }); - }); - - it('should remove books from shelf', () => { - bookStateServiceMock.getCurrentBookState.mockReturnValue({ - books: [{id: 1, shelves: [{id: 10}, {id: 20}]}, {id: 2, shelves: [{id: 20}]}], - loaded: true, - error: null - }); - service.removeBooksFromShelf(20); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); - }); - }); - - describe('Book Retrieval', () => { - it('should get book by id from state', () => { - expect(service.getBookByIdFromState(1)).toEqual(expect.objectContaining({id: 1})); - expect(service.getBookByIdFromState(999)).toBeUndefined(); - }); - - it('should get books by ids from state', () => { - expect(service.getBooksByIdsFromState([1, 2])).toHaveLength(2); - expect(service.getBooksByIdsFromState([])).toEqual([]); - }); - - it('should get book by id from API', async () => { - httpMock.get.mockReturnValue(of({id: 1})); - const result = await firstValueFrom(service.getBookByIdFromAPI(1, true)); - expect(result).toEqual({id: 1}); - }); - - it('should get books in series', async () => { - const result = await firstValueFrom(service.getBooksInSeries(1)); - expect(result).toEqual([expect.objectContaining({id: 1})]); - }); - - it('should get book recommendations', async () => { - httpMock.get.mockReturnValue(of([{id: 1}])); - const result = await firstValueFrom(service.getBookRecommendations(1)); - expect(result).toEqual([{id: 1}]); - }); - }); - - describe('Book Operations', () => { - it('should delete books and update state', async () => { - httpMock.delete.mockReturnValue(of({failedFileDeletions: []})); - bookStateServiceMock.getCurrentBookState.mockReturnValue({ - books: [{id: 1}, {id: 2}], - loaded: true, - error: null - }); - await firstValueFrom(service.deleteBooks(new Set([1]))); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); - }); - - it('should show warning if some files could not be deleted', async () => { - httpMock.delete.mockReturnValue(of({failedFileDeletions: ['file.pdf']})); - bookStateServiceMock.getCurrentBookState.mockReturnValue({ - books: [{id: 1, fileName: 'file.pdf'}], - loaded: true, - error: null - }); - await firstValueFrom(service.deleteBooks(new Set([1]))); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'warn'})); - }); - - it('should handle deleteBooks error', async () => { - httpMock.delete.mockReturnValue(throwError(() => ({error: {message: 'fail'}}))); - await expect(firstValueFrom(service.deleteBooks(new Set([1])))).rejects.toBeTruthy(); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); - }); - - it('should update book shelves', async () => { - bookPatchServiceMock.updateBookShelves.mockReturnValue(of([{id: 1}])); - const result = await firstValueFrom(service.updateBookShelves(new Set([1]), new Set([2]), new Set([3]))); - expect(result).toEqual([{id: 1}]); - }); - - it('should handle updateBookShelves error', async () => { - bookPatchServiceMock.updateBookShelves.mockReturnValue(throwError(() => ({message: 'fail'}))); - await expect(firstValueFrom(service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])))).rejects.toBeTruthy(); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); - }); - }); - - describe('Reading & Viewer Settings', () => { - it('should navigate to correct reader and update last read time', () => { - service.readBook(1); - expect(routerMock.navigate).toHaveBeenCalledWith(['/pdf-reader/book/1'], undefined); - expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1); - }); - - it('should not navigate if book not found', () => { - bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: true, error: null}); - service.readBook(999); - expect(routerMock.navigate).not.toHaveBeenCalled(); - }); - - it('should get book setting', async () => { - httpMock.get.mockReturnValue(of({fontSize: 12})); - const result = await firstValueFrom(service.getBookSetting(1)); - expect(result).toEqual({fontSize: 12}); - }); - - it('should update viewer setting', async () => { - httpMock.put.mockReturnValue(of(void 0)); - const result = await firstValueFrom(service.updateViewerSetting({fontSize: 12}, 1)); - expect(result).toBeUndefined(); - }); - }); - - describe('File Operations', () => { - it('should get file content', async () => { - httpMock.get.mockReturnValue(of(new Blob(['abc']))); - const result = await firstValueFrom(service.getFileContent(1)); - expect(result).toBeInstanceOf(Blob); - }); - - it('should download file', () => { - const book = {id: 1, fileName: 'file.pdf'}; - service.downloadFile(book as Book); - expect(fileDownloadServiceMock.downloadFile).toHaveBeenCalled(); - }); - - it('should delete additional file and update state', async () => { - httpMock.delete.mockReturnValue(of(void 0)); - bookStateServiceMock.getCurrentBookState.mockReturnValue({ - books: [{id: 1, alternativeFormats: [{id: 2}], supplementaryFiles: [{id: 3}]}], - loaded: true, - error: null - }); - await firstValueFrom(service.deleteAdditionalFile(1, 2)); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); - }); - - it('should handle deleteAdditionalFile error', async () => { - httpMock.delete.mockReturnValue(throwError(() => ({error: {message: 'fail'}}))); - await expect(firstValueFrom(service.deleteAdditionalFile(1, 2))).rejects.toBeTruthy(); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); - }); - - it('should upload additional file and update state', async () => { - httpMock.post.mockReturnValue(of({id: 2})); - bookStateServiceMock.getCurrentBookState.mockReturnValue({ - books: [{id: 1, alternativeFormats: [], supplementaryFiles: []}], - loaded: true, - error: null - }); - const file = new File(['abc'], 'file.txt'); - await firstValueFrom(service.uploadAdditionalFile(1, file, AdditionalFileType.ALTERNATIVE_FORMAT)); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); - }); - - it('should handle uploadAdditionalFile error', async () => { - httpMock.post.mockReturnValue(throwError(() => ({error: {message: 'fail'}}))); - const file = new File(['abc'], 'file.txt'); - await expect(firstValueFrom(service.uploadAdditionalFile(1, file, AdditionalFileType.ALTERNATIVE_FORMAT))).rejects.toBeTruthy(); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); - }); - - it('should download additional file', () => { - const book = {id: 1, alternativeFormats: [{id: 2, fileName: 'f.txt'}]}; - service.downloadAdditionalFile(book as Book, 2); - expect(fileDownloadServiceMock.downloadFile).toHaveBeenCalled(); - }); - }); - - describe('Progress & Status Tracking', () => { - it('should update last read time', () => { - service.updateLastReadTime(1); - expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1); - }); - - it('should save pdf progress', async () => { - bookPatchServiceMock.savePdfProgress.mockReturnValue(of(void 0)); - const result = await firstValueFrom(service.savePdfProgress(1, 2, 0.5)); - expect(result).toBeUndefined(); - }); - - it('should save cbx progress', async () => { - bookPatchServiceMock.saveCbxProgress.mockReturnValue(of(void 0)); - const result = await firstValueFrom(service.saveCbxProgress(1, 2, 0.5)); - expect(result).toBeUndefined(); - }); - - it('should update date finished', async () => { - bookPatchServiceMock.updateDateFinished.mockReturnValue(of(void 0)); - const result = await firstValueFrom(service.updateDateFinished(1, '2020-01-01')); - expect(result).toBeUndefined(); - }); - - it('should reset progress', async () => { - bookPatchServiceMock.resetProgress.mockReturnValue(of([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}])); - const result = await firstValueFrom(service.resetProgress([1], 'BOOKLORE')); - expect(result).toEqual([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]); - }); - - it('should update book read status', async () => { - bookPatchServiceMock.updateBookReadStatus.mockReturnValue(of([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}])); - const result = await firstValueFrom(service.updateBookReadStatus([1], ReadStatus.READ)); - expect(result).toEqual([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]); - }); - }); - - describe('Personal Rating', () => { - it('should reset personal rating', async () => { - bookPatchServiceMock.resetPersonalRating.mockReturnValue(of([{bookId: 1}])); - const result = await firstValueFrom(service.resetPersonalRating([1])); - expect(result).toEqual([{bookId: 1}]); - }); - - it('should update personal rating', async () => { - bookPatchServiceMock.updatePersonalRating.mockReturnValue(of([{bookId: 1, personalRating: 5}])); - const result = await firstValueFrom(service.updatePersonalRating([1], 5)); - expect(result).toEqual([{bookId: 1, personalRating: 5}]); - }); - }); - - describe('Metadata Operations', () => { - - it('should update book metadata', async () => { - httpMock.put.mockReturnValue(of({bookId: 1})); - const spy = vi.spyOn(BookService.prototype, 'handleBookMetadataUpdate'); - const result = await firstValueFrom(service.updateBookMetadata(1, {} as any, true)); - expect(result).toEqual({bookId: 1}); - expect(spy).toHaveBeenCalledWith(1, {bookId: 1}); - spy.mockRestore(); - }); - - it('should update books metadata', async () => { - httpMock.put.mockReturnValue(of(void 0)); - const result = await firstValueFrom(service.updateBooksMetadata({} as any)); - expect(result).toBeUndefined(); - }); - - it('should toggle all lock', async () => { - httpMock.put.mockReturnValue(of([{bookId: 1}])); - bookStateServiceMock.getCurrentBookState.mockReturnValue({ - books: [{id: 1, metadata: {bookId: 1}}], - loaded: true, - error: null - }); - const result = await firstValueFrom(service.toggleAllLock(new Set([1]), 'lock')); - expect(result).toBeUndefined(); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); - }); - - it('should handle toggle all lock error', async () => { - httpMock.put.mockReturnValue(throwError(() => ({message: 'fail'}))); - await expect(firstValueFrom(service.toggleAllLock(new Set([1]), 'lock'))).rejects.toBeTruthy(); - }); - - it('should toggle field locks', async () => { - httpMock.put.mockReturnValue(of(void 0)); - bookStateServiceMock.getCurrentBookState.mockReturnValue({ - books: [{id: 1, metadata: {}}], - loaded: true, - error: null - }); - const result = await firstValueFrom(service.toggleFieldLocks([1], {title: 'LOCK'})); - expect(result).toBeUndefined(); - expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); - }); - - it('should handle toggle field locks error', async () => { - httpMock.put.mockReturnValue(throwError(() => ({message: 'fail'}))); - await expect(firstValueFrom(service.toggleFieldLocks([1], {title: 'LOCK'}))).rejects.toBeTruthy(); - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); - }); - - it('should consolidate metadata', async () => { - httpMock.post.mockReturnValue(of({})); - service.refreshBooks = vi.fn(); - await firstValueFrom(service.consolidateMetadata('authors', ['a'], ['b'])); - expect(service.refreshBooks).toHaveBeenCalled(); - }); - - it('should delete metadata', async () => { - httpMock.post.mockReturnValue(of({})); - service.refreshBooks = vi.fn(); - await firstValueFrom(service.deleteMetadata('authors', ['a'])); - expect(service.refreshBooks).toHaveBeenCalled(); - }); - }); - - describe('Cover Operations', () => { - it('should get upload cover url', () => { - expect(service.getUploadCoverUrl(1)).toContain('/1/metadata/cover/upload'); - }); - - it('should regenerate covers', async () => { - httpMock.post.mockReturnValue(of(void 0)); - const result = await firstValueFrom(service.regenerateCovers()); - expect(result).toBeUndefined(); - }); - - it('should regenerate cover', async () => { - httpMock.post.mockReturnValue(of(void 0)); - const result = await firstValueFrom(service.regenerateCover(1)); - expect(result).toBeUndefined(); - }); - - it('should generate custom cover', async () => { - httpMock.post.mockReturnValue(of(void 0)); - const result = await firstValueFrom(service.generateCustomCover(1)); - expect(result).toBeUndefined(); - }); - - it('should regenerate covers for books', async () => { - httpMock.post.mockReturnValue(of(void 0)); - const result = await firstValueFrom(service.regenerateCoversForBooks([1, 2])); - expect(result).toBeUndefined(); - }); - - it('should bulk upload cover', async () => { - httpMock.post.mockReturnValue(of(void 0)); - const file = new File(['abc'], 'cover.jpg'); - const result = await firstValueFrom(service.bulkUploadCover([1, 2], file)); - expect(result).toBeUndefined(); - }); - }); - - describe('Websocket Handlers', () => { - it('should handle newly created book', () => { - const book = {id: 1}; - service.handleNewlyCreatedBook(book as Book); - expect(bookSocketServiceMock.handleNewlyCreatedBook).toHaveBeenCalledWith(book); - }); - - it('should handle removed book ids', () => { - service.handleRemovedBookIds([1, 2]); - expect(bookSocketServiceMock.handleRemovedBookIds).toHaveBeenCalledWith([1, 2]); - }); - - it('should handle book update', () => { - const book = {id: 1}; - service.handleBookUpdate(book as Book); - expect(bookSocketServiceMock.handleBookUpdate).toHaveBeenCalledWith(book); - }); - - it('should handle multiple book updates', () => { - const books = [{id: 1}, {id: 2}]; - service.handleMultipleBookUpdates(books as Book[]); - expect(bookSocketServiceMock.handleMultipleBookUpdates).toHaveBeenCalledWith(books); - }); - - it('should handle book metadata update', () => { - service.handleBookMetadataUpdate(1, {bookId: 1} as BookMetadata); - expect(bookSocketServiceMock.handleBookMetadataUpdate).toHaveBeenCalledWith(1, {bookId: 1}); - }); - - it('should handle multiple book cover patches', () => { - const patches = [{id: 1, coverUpdatedOn: 'now'}]; - service.handleMultipleBookCoverPatches(patches); - expect(bookSocketServiceMock.handleMultipleBookCoverPatches).toHaveBeenCalledWith(patches); - }); - }); -}); - diff --git a/booklore-ui/src/app/features/book/service/book.service.ts b/booklore-ui/src/app/features/book/service/book.service.ts index 416daff00..10f6bdeb4 100644 --- a/booklore-ui/src/app/features/book/service/book.service.ts +++ b/booklore-ui/src/app/features/book/service/book.service.ts @@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core'; import {first, Observable, of, throwError} from 'rxjs'; import {HttpClient, HttpParams} from '@angular/common/http'; import {catchError, distinctUntilChanged, filter, finalize, map, shareReplay, tap} from 'rxjs/operators'; -import {AdditionalFile, AdditionalFileType, Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model'; +import {AdditionalFile, AdditionalFileType, Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BookType, BulkMetadataUpdateRequest, CreatePhysicalBookRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model'; import {BookState} from '../model/state/book-state.model'; import {API_CONFIG} from '../../../core/config/api-config'; import {MessageService} from 'primeng/api'; @@ -242,9 +242,35 @@ export class BookService { ); } + createPhysicalBook(request: CreatePhysicalBookRequest): Observable { + return this.http.post(`${this.url}/physical`, request).pipe( + tap(newBook => { + const currentState = this.bookStateService.getCurrentBookState(); + const updatedBooks = [...(currentState.books || []), newBook]; + this.bookStateService.updateBookState({ + ...currentState, + books: updatedBooks + }); + this.messageService.add({ + severity: 'success', + summary: 'Physical Book Created', + detail: `"${newBook.metadata?.title || 'Book'}" has been added to your library.` + }); + }), + catchError(error => { + this.messageService.add({ + severity: 'error', + summary: 'Creation Failed', + detail: error?.error?.message || error?.message || 'An error occurred while creating the physical book.' + }); + return throwError(() => error); + }) + ); + } + /*------------------ Reading & Viewer Settings ------------------*/ - readBook(bookId: number, reader?: 'pdf-streaming' | 'epub-streaming'): void { + readBook(bookId: number, reader?: 'pdf-streaming' | 'epub-streaming', explicitBookType?: BookType): void { const book = this.bookStateService .getCurrentBookState() .books?.find(b => b.id === bookId); @@ -254,10 +280,14 @@ export class BookService { return; } - let baseUrl: string | null = null; - let queryParams: Record | undefined; + // Determine the book type - use explicit type if provided, otherwise use primary + const bookType: BookType | undefined = explicitBookType ?? book.primaryFile?.bookType; + const isAlternativeFormat = explicitBookType && explicitBookType !== book.primaryFile?.bookType; - switch (book.bookType) { + let baseUrl: string | null = null; + let queryParams: Record = {}; + + switch (bookType) { case 'PDF': baseUrl = reader === 'pdf-streaming' ? 'cbx-reader' : 'pdf-reader'; break; @@ -265,7 +295,7 @@ export class BookService { case 'EPUB': baseUrl = 'ebook-reader'; if (reader === 'epub-streaming') { - queryParams = { streaming: true }; + queryParams['streaming'] = true; } break; @@ -278,20 +308,30 @@ export class BookService { case 'CBX': baseUrl = 'cbx-reader'; break; + + case 'AUDIOBOOK': + baseUrl = 'audiobook-reader'; + break; } if (!baseUrl) { - console.error('Unsupported book type:', book.bookType); + console.error('Unsupported book type:', bookType); return; } - this.router.navigate([`/${baseUrl}/book/${book.id}`], queryParams ? { queryParams } : undefined); + // Add bookType to query params if reading an alternative format + if (isAlternativeFormat) { + queryParams['bookType'] = bookType; + } + + const hasQueryParams = Object.keys(queryParams).length > 0; + this.router.navigate([`/${baseUrl}/book/${book.id}`], hasQueryParams ? { queryParams } : undefined); this.updateLastReadTime(book.id); } - getBookSetting(bookId: number): Observable { - return this.http.get(`${this.url}/${bookId}/viewer-setting`); + getBookSetting(bookId: number, bookFileId: number): Observable { + return this.http.get(`${this.url}/${bookId}/viewer-setting?bookFileId=${bookFileId}`); } updateViewerSetting(bookSetting: BookSetting, bookId: number): Observable { @@ -300,13 +340,25 @@ export class BookService { /*------------------ File Operations ------------------*/ - getFileContent(bookId: number): Observable { - return this.http.get(`${this.url}/${bookId}/content`, {responseType: 'blob' as 'json'}); + getFileContent(bookId: number, bookType?: string): Observable { + let url = `${this.url}/${bookId}/content`; + if (bookType) { + url += `?bookType=${bookType}`; + } + return this.http.get(url, {responseType: 'blob' as 'json'}); } downloadFile(book: Book): void { const downloadUrl = `${this.url}/${book.id}/download`; - this.fileDownloadService.downloadFile(downloadUrl, book.fileName!); + this.fileDownloadService.downloadFile(downloadUrl, book.primaryFile?.fileName ?? 'book'); + } + + downloadAllFiles(book: Book): void { + const downloadUrl = `${this.url}/${book.id}/download-all`; + const fileName = book.metadata?.title + ? `${book.metadata.title.replace(/[^a-zA-Z0-9\-_]/g, '_')}.zip` + : `book-${book.id}.zip`; + this.fileDownloadService.downloadFile(downloadUrl, fileName); } deleteAdditionalFile(bookId: number, fileId: number): Observable { @@ -347,6 +399,63 @@ export class BookService { ); } + deleteBookFile(bookId: number, fileId: number, isPrimary: boolean): Observable { + const deleteUrl = `${this.url}/${bookId}/files/${fileId}`; + return this.http.delete(deleteUrl).pipe( + tap(() => { + const currentState = this.bookStateService.getCurrentBookState(); + const updatedBooks = (currentState.books || []).map(book => { + if (book.id === bookId) { + if (isPrimary) { + // Primary file was deleted - promote first alternative to primary, or set null + const remainingAlternatives = book.alternativeFormats?.filter(file => file.id !== fileId) || []; + if (remainingAlternatives.length > 0) { + const [newPrimary, ...restAlternatives] = remainingAlternatives; + return { + ...book, + primaryFile: newPrimary, + alternativeFormats: restAlternatives + }; + } else { + return { + ...book, + primaryFile: undefined, + alternativeFormats: [] + }; + } + } else { + // Alternative file was deleted + return { + ...book, + alternativeFormats: book.alternativeFormats?.filter(file => file.id !== fileId) + }; + } + } + return book; + }); + + this.bookStateService.updateBookState({ + ...currentState, + books: updatedBooks + }); + + this.messageService.add({ + severity: 'success', + summary: 'File Deleted', + detail: 'Book file deleted successfully.' + }); + }), + catchError(error => { + this.messageService.add({ + severity: 'error', + summary: 'Delete Failed', + detail: error?.error?.message || error?.message || 'An error occurred while deleting the file.' + }); + return throwError(() => error); + }) + ); + } + uploadAdditionalFile(bookId: number, file: File, fileType: AdditionalFileType, description?: string): Observable { const formData = new FormData(); formData.append('file', file); @@ -363,7 +472,9 @@ export class BookService { ? 'EPUB' : (ext === 'cbz' || ext === 'cbr' || ext === 'cb7' || ext === 'cbt') ? 'CBX' - : null; + : (ext === 'm4b' || ext === 'm4a' || ext === 'mp3') + ? 'AUDIOBOOK' + : null; if (bookType) { formData.append('bookType', bookType); @@ -426,16 +537,16 @@ export class BookService { this.bookPatchService.updateLastReadTime(bookId); } - savePdfProgress(bookId: number, page: number, percentage: number): Observable { - return this.bookPatchService.savePdfProgress(bookId, page, percentage); + savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable { + return this.bookPatchService.savePdfProgress(bookId, page, percentage, bookFileId); } /*saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number): Observable { return this.bookPatchService.saveEpubProgress(bookId, cfi, href, percentage); }*/ - saveCbxProgress(bookId: number, page: number, percentage: number): Observable { - return this.bookPatchService.saveCbxProgress(bookId, page, percentage); + saveCbxProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable { + return this.bookPatchService.saveCbxProgress(bookId, page, percentage, bookFileId); } updateDateFinished(bookId: number, dateFinished: string | null): Observable { @@ -621,4 +732,46 @@ export class BookService { handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void { this.bookSocketService.handleMultipleBookCoverPatches(patches); } + + /*------------------ Book File Attachment ------------------*/ + + attachBookFiles(targetBookId: number, sourceBookIds: number[], deleteSourceBooks: boolean): Observable { + return this.http.post(`${this.url}/${targetBookId}/attach-file`, { + sourceBookIds, + deleteSourceBooks + }).pipe( + tap(updatedBook => { + const currentState = this.bookStateService.getCurrentBookState(); + let updatedBooks = (currentState.books || []).map(book => + book.id === targetBookId ? updatedBook : book + ); + + // If deleteSourceBooks, remove source books from state + if (deleteSourceBooks) { + const sourceIdSet = new Set(sourceBookIds); + updatedBooks = updatedBooks.filter(book => !sourceIdSet.has(book.id)); + } + + this.bookStateService.updateBookState({ + ...currentState, + books: updatedBooks + }); + + const fileCount = sourceBookIds.length; + this.messageService.add({ + severity: 'success', + summary: 'Files Attached', + detail: `${fileCount} book file${fileCount > 1 ? 's have' : ' has'} been attached successfully.` + }); + }), + catchError(error => { + this.messageService.add({ + severity: 'error', + summary: 'Attachment Failed', + detail: error?.error?.message || error?.message || 'An error occurred while attaching the files.' + }); + return throwError(() => error); + }) + ); + } } diff --git a/booklore-ui/src/app/features/book/service/cbx-reader.service.spec.ts b/booklore-ui/src/app/features/book/service/cbx-reader.service.spec.ts deleted file mode 100644 index 10654f131..000000000 --- a/booklore-ui/src/app/features/book/service/cbx-reader.service.spec.ts +++ /dev/null @@ -1,96 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {HttpClient} from '@angular/common/http'; -import {of, throwError} from 'rxjs'; - -import {CbxReaderService} from './cbx-reader.service'; -import {AuthService} from '../../../shared/service/auth.service'; - -describe('CbxReaderService', () => { - let service: CbxReaderService; - let httpClientMock: any; - let authServiceMock: any; - - beforeEach(() => { - httpClientMock = { - get: vi.fn() - }; - - authServiceMock = { - getOidcAccessToken: vi.fn(), - getInternalAccessToken: vi.fn() - }; - - TestBed.configureTestingModule({ - providers: [ - CbxReaderService, - {provide: HttpClient, useValue: httpClientMock}, - {provide: AuthService, useValue: authServiceMock} - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - - service = runInInjectionContext( - injector, - () => TestBed.inject(CbxReaderService) - ); - }); - - it('should get available pages with token', () => { - authServiceMock.getOidcAccessToken.mockReturnValue('abc123'); - authServiceMock.getInternalAccessToken.mockReturnValue(null); - httpClientMock.get.mockReturnValue(of([1, 2, 3])); - service.getAvailablePages(42).subscribe(pages => { - expect(pages).toEqual([1, 2, 3]); - expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('token=abc123')); - }); - }); - - it('should get available pages without token', () => { - authServiceMock.getOidcAccessToken.mockReturnValue(null); - authServiceMock.getInternalAccessToken.mockReturnValue(null); - httpClientMock.get.mockReturnValue(of([4, 5])); - service.getAvailablePages(99).subscribe(pages => { - expect(pages).toEqual([4, 5]); - expect(httpClientMock.get).toHaveBeenCalledWith(expect.not.stringContaining('token=')); - }); - }); - - it('should handle error when getting available pages', () => { - authServiceMock.getOidcAccessToken.mockReturnValue('tok'); - httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); - service.getAvailablePages(1).subscribe({ - error: (err: any) => { - expect(err).toBeInstanceOf(Error); - expect(err.message).toBe('fail'); - } - }); - }); - - it('should return correct page image url with oidc token', () => { - authServiceMock.getOidcAccessToken.mockReturnValue('tok'); - authServiceMock.getInternalAccessToken.mockReturnValue(null); - const url = service.getPageImageUrl(5, 7); - expect(url).toContain('/api/v1/media/book/5/cbx/pages/7'); - expect(url).toContain('token=tok'); - }); - - it('should return correct page image url with internal token', () => { - authServiceMock.getOidcAccessToken.mockReturnValue(null); - authServiceMock.getInternalAccessToken.mockReturnValue('inttok'); - const url = service.getPageImageUrl(8, 2); - expect(url).toContain('/api/v1/media/book/8/cbx/pages/2'); - expect(url).toContain('token=inttok'); - }); - - it('should return correct page image url without token', () => { - authServiceMock.getOidcAccessToken.mockReturnValue(null); - authServiceMock.getInternalAccessToken.mockReturnValue(null); - const url = service.getPageImageUrl(3, 1); - expect(url).toContain('/api/v1/media/book/3/cbx/pages/1'); - expect(url).not.toContain('token='); - }); -}); - diff --git a/booklore-ui/src/app/features/book/service/cbx-reader.service.ts b/booklore-ui/src/app/features/book/service/cbx-reader.service.ts index 17746b5b9..8c56ee213 100644 --- a/booklore-ui/src/app/features/book/service/cbx-reader.service.ts +++ b/booklore-ui/src/app/features/book/service/cbx-reader.service.ts @@ -25,15 +25,27 @@ export class CbxReaderService { return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url; } - getAvailablePages(bookId: number) { - return this.http.get(this.appendToken(`${this.pagesUrl}/${bookId}/pages`)); + getAvailablePages(bookId: number, bookType?: string) { + let url = `${this.pagesUrl}/${bookId}/pages`; + if (bookType) { + url += `?bookType=${bookType}`; + } + return this.http.get(this.appendToken(url)); } - getPageInfo(bookId: number) { - return this.http.get(this.appendToken(`${this.pagesUrl}/${bookId}/page-info`)); + getPageInfo(bookId: number, bookType?: string) { + let url = `${this.pagesUrl}/${bookId}/page-info`; + if (bookType) { + url += `?bookType=${bookType}`; + } + return this.http.get(this.appendToken(url)); } - getPageImageUrl(bookId: number, page: number): string { - return this.appendToken(`${this.imageUrl}/${bookId}/cbx/pages/${page}`); + getPageImageUrl(bookId: number, page: number, bookType?: string): string { + let url = `${this.imageUrl}/${bookId}/cbx/pages/${page}`; + if (bookType) { + url += `?bookType=${bookType}`; + } + return this.appendToken(url); } } diff --git a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.spec.ts b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.spec.ts deleted file mode 100644 index 449efcbd6..000000000 --- a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.spec.ts +++ /dev/null @@ -1,350 +0,0 @@ -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {ConfirmationService, MessageService} from 'primeng/api'; -import {Router} from '@angular/router'; -import {LibraryService} from './library.service'; -import {ShelfService} from './shelf.service'; -import {TaskHelperService} from '../../settings/task-management/task-helper.service'; -import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service'; -import {MagicShelf, MagicShelfService} from '../../magic-shelf/service/magic-shelf.service'; -import {UserService} from "../../settings/user-management/user.service"; -import {LoadingService} from '../../../core/services/loading.service'; -import {LibraryShelfMenuService} from './library-shelf-menu.service'; -import {Library} from '../model/library.model'; -import {Shelf} from '../model/shelf.model'; -import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum'; -import {of, throwError} from 'rxjs'; -import {beforeEach, describe, expect, it, vi} from 'vitest'; - -describe('LibraryShelfMenuService', () => { - let service: LibraryShelfMenuService; - let confirmationService: any; - let messageService: any; - let libraryService: any; - let shelfService: any; - let taskHelperService: any; - let router: any; - let dialogLauncherService: any; - let magicShelfService: any; - let userService: any; - let loadingService: any; - - const mockLibrary: Library = {id: 1, name: 'Lib1'} as Library; - const mockShelf: Shelf = {id: 2, name: 'Shelf1'} as Shelf; - const mockMagicShelf: MagicShelf = {id: 3, name: 'Magic1', isPublic: false} as MagicShelf; - - beforeEach(() => { - confirmationService = {confirm: vi.fn()}; - messageService = {add: vi.fn()}; - libraryService = { - refreshLibrary: vi.fn(), - deleteLibrary: vi.fn() - }; - shelfService = { - deleteShelf: vi.fn() - }; - taskHelperService = { - refreshMetadataTask: vi.fn() - }; - router = {navigate: vi.fn()}; - dialogLauncherService = { - openLibraryEditDialog: vi.fn(), - openLibraryMetadataFetchDialog: vi.fn(), - openShelfEditDialog: vi.fn(), - openMagicShelfEditDialog: vi.fn() - }; - magicShelfService = { - deleteShelf: vi.fn() - }; - userService = { - getCurrentUser: vi.fn() - }; - loadingService = { - show: vi.fn().mockReturnValue('loader-id'), - hide: vi.fn() - }; - - TestBed.configureTestingModule({ - providers: [ - LibraryShelfMenuService, - {provide: ConfirmationService, useValue: confirmationService}, - {provide: MessageService, useValue: messageService}, - {provide: LibraryService, useValue: libraryService}, - {provide: ShelfService, useValue: shelfService}, - {provide: TaskHelperService, useValue: taskHelperService}, - {provide: Router, useValue: router}, - {provide: DialogLauncherService, useValue: dialogLauncherService}, - {provide: MagicShelfService, useValue: magicShelfService}, - {provide: UserService, useValue: userService}, - {provide: LoadingService, useValue: loadingService} - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - service = runInInjectionContext(injector, () => TestBed.inject(LibraryShelfMenuService)); - }); - - describe('initializeLibraryMenuItems', () => { - it('should provide all menu items for a library', () => { - const items = service.initializeLibraryMenuItems(mockLibrary); - expect(items.length).toBe(1); - const options = items[0].items!; - expect(options.some(i => i.label === 'Edit Library')).toBe(true); - expect(options.some(i => i.label === 'Re-scan Library')).toBe(true); - expect(options.some(i => i.label === 'Custom Fetch Metadata')).toBe(true); - expect(options.some(i => i.label === 'Auto Fetch Metadata')).toBe(true); - expect(options.some(i => i.label === 'Delete Library')).toBe(true); - }); - - it('should call openLibraryEditDialog when Edit Library is clicked', () => { - const items = service.initializeLibraryMenuItems(mockLibrary); - const edit = items[0].items!.find(i => i.label === 'Edit Library'); - edit!.command!({}); - expect(dialogLauncherService.openLibraryEditDialog).toHaveBeenCalledWith(mockLibrary.id); - }); - - it('should call openLibraryMetadataFetchDialog when Custom Fetch Metadata is clicked', () => { - const items = service.initializeLibraryMenuItems(mockLibrary); - const fetch = items[0].items!.find(i => i.label === 'Custom Fetch Metadata'); - fetch!.command!({}); - expect(dialogLauncherService.openLibraryMetadataFetchDialog).toHaveBeenCalledWith(mockLibrary.id); - }); - - it('should call refreshMetadataTask when Auto Fetch Metadata is clicked', () => { - taskHelperService.refreshMetadataTask.mockReturnValue(of({})); - const items = service.initializeLibraryMenuItems(mockLibrary); - const auto = items[0].items!.find(i => i.label === 'Auto Fetch Metadata'); - auto!.command!({}); - expect(taskHelperService.refreshMetadataTask).toHaveBeenCalledWith({ - refreshType: MetadataRefreshType.LIBRARY, - libraryId: mockLibrary.id - }); - }); - - it('should show confirmation dialog for Re-scan Library', () => { - libraryService.refreshLibrary.mockReturnValue(of({})); - const items = service.initializeLibraryMenuItems(mockLibrary); - const rescan = items[0].items!.find(i => i.label === 'Re-scan Library'); - rescan!.command!({}); - expect(confirmationService.confirm).toHaveBeenCalledTimes(1); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - expect(confirmCall.message).toContain(mockLibrary.name); - expect(confirmCall.header).toBe('Confirmation'); - }); - - it('should refresh library and show success message on accept', () => { - libraryService.refreshLibrary.mockReturnValue(of({})); - const items = service.initializeLibraryMenuItems(mockLibrary); - const rescan = items[0].items!.find(i => i.label === 'Re-scan Library'); - rescan!.command!({}); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - confirmCall.accept(); - expect(libraryService.refreshLibrary).toHaveBeenCalledWith(mockLibrary.id); - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'info', - summary: 'Success', - detail: 'Library refresh scheduled' - }); - }); - - it('should show error message if refreshLibrary fails', () => { - libraryService.refreshLibrary.mockReturnValue(throwError(() => ({}))); - const items = service.initializeLibraryMenuItems(mockLibrary); - const rescan = items[0].items!.find(i => i.label === 'Re-scan Library'); - rescan!.command!({}); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - confirmCall.accept(); - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'Failed', - detail: 'Failed to refresh library' - }); - }); - - it('should show confirmation dialog for Delete Library', () => { - libraryService.deleteLibrary.mockReturnValue(of({})); - const items = service.initializeLibraryMenuItems(mockLibrary); - const del = items[0].items!.find(i => i.label === 'Delete Library'); - del!.command!({}); - expect(confirmationService.confirm).toHaveBeenCalledTimes(1); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - expect(confirmCall.message).toContain(mockLibrary.name); - expect(confirmCall.header).toBe('Confirmation'); - }); - - it('should delete library, navigate, and show success message on accept', () => { - libraryService.deleteLibrary.mockReturnValue(of({})); - const items = service.initializeLibraryMenuItems(mockLibrary); - const del = items[0].items!.find(i => i.label === 'Delete Library'); - del!.command!({}); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - confirmCall.accept(); - expect(loadingService.show).toHaveBeenCalledWith(expect.stringContaining(mockLibrary.name)); - expect(libraryService.deleteLibrary).toHaveBeenCalledWith(mockLibrary.id); - expect(router.navigate).toHaveBeenCalledWith(['/']); - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'info', - summary: 'Success', - detail: 'Library was deleted' - }); - expect(loadingService.hide).toHaveBeenCalledWith('loader-id'); - }); - - it('should show error message if deleteLibrary fails', () => { - libraryService.deleteLibrary.mockReturnValue(throwError(() => ({}))); - const items = service.initializeLibraryMenuItems(mockLibrary); - const del = items[0].items!.find(i => i.label === 'Delete Library'); - del!.command!({}); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - confirmCall.accept(); - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'Failed', - detail: 'Failed to delete library' - }); - expect(loadingService.hide).toHaveBeenCalledWith('loader-id'); - }); - }); - - describe('initializeShelfMenuItems', () => { - it('should provide all menu items for a shelf', () => { - const items = service.initializeShelfMenuItems(mockShelf); - expect(items.length).toBe(1); - const options = items[0].items!; - expect(options.some(i => i.label === 'Edit Shelf')).toBe(true); - expect(options.some(i => i.label === 'Delete Shelf')).toBe(true); - }); - - it('should call openShelfEditDialog when Edit Shelf is clicked', () => { - const items = service.initializeShelfMenuItems(mockShelf); - const edit = items[0].items!.find(i => i.label === 'Edit Shelf'); - edit!.command!({}); - expect(dialogLauncherService.openShelfEditDialog).toHaveBeenCalledWith(mockShelf.id); - }); - - it('should show confirmation dialog for Delete Shelf', () => { - shelfService.deleteShelf.mockReturnValue(of({})); - const items = service.initializeShelfMenuItems(mockShelf); - const del = items[0].items!.find(i => i.label === 'Delete Shelf'); - del!.command!({}); - expect(confirmationService.confirm).toHaveBeenCalledTimes(1); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - expect(confirmCall.message).toContain(mockShelf.name); - expect(confirmCall.header).toBe('Confirmation'); - }); - - it('should delete shelf, navigate, and show success message on accept', () => { - shelfService.deleteShelf.mockReturnValue(of({})); - const items = service.initializeShelfMenuItems(mockShelf); - const del = items[0].items!.find(i => i.label === 'Delete Shelf'); - del!.command!({}); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - confirmCall.accept(); - expect(shelfService.deleteShelf).toHaveBeenCalledWith(mockShelf.id); - expect(router.navigate).toHaveBeenCalledWith(['/']); - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'info', - summary: 'Success', - detail: 'Shelf was deleted' - }); - }); - - it('should show error message if deleteShelf fails', () => { - shelfService.deleteShelf.mockReturnValue(throwError(() => ({}))); - const items = service.initializeShelfMenuItems(mockShelf); - const del = items[0].items!.find(i => i.label === 'Delete Shelf'); - del!.command!({}); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - confirmCall.accept(); - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'Failed', - detail: 'Failed to delete shelf' - }); - }); - }); - - describe('initializeMagicShelfMenuItems', () => { - it('should provide all menu items for a magic shelf', () => { - userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); - const items = service.initializeMagicShelfMenuItems(mockMagicShelf); - expect(items.length).toBe(1); - const options = items[0].items!; - expect(options.some(i => i.label === 'Edit Magic Shelf')).toBe(true); - expect(options.some(i => i.label === 'Delete Magic Shelf')).toBe(true); - }); - - it('should call openMagicShelfEditDialog when Edit Magic Shelf is clicked', () => { - userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); - const items = service.initializeMagicShelfMenuItems(mockMagicShelf); - const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf'); - edit!.command!({}); - expect(dialogLauncherService.openMagicShelfEditDialog).toHaveBeenCalledWith(mockMagicShelf.id); - }); - - it('should show confirmation dialog for Delete Magic Shelf', () => { - userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); - magicShelfService.deleteShelf.mockReturnValue(of({})); - const items = service.initializeMagicShelfMenuItems(mockMagicShelf); - const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf'); - del!.command!({}); - expect(confirmationService.confirm).toHaveBeenCalledTimes(1); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - expect(confirmCall.message).toContain(mockMagicShelf.name); - expect(confirmCall.header).toBe('Confirmation'); - }); - - it('should delete magic shelf, navigate, and show success message on accept', () => { - userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); - magicShelfService.deleteShelf.mockReturnValue(of({})); - const items = service.initializeMagicShelfMenuItems(mockMagicShelf); - const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf'); - del!.command!({}); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - confirmCall.accept(); - expect(magicShelfService.deleteShelf).toHaveBeenCalledWith(mockMagicShelf.id); - expect(router.navigate).toHaveBeenCalledWith(['/']); - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'info', - summary: 'Success', - detail: 'Magic shelf was deleted' - }); - }); - - it('should show error message if deleteMagicShelf fails', () => { - userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); - magicShelfService.deleteShelf.mockReturnValue(throwError(() => ({}))); - const items = service.initializeMagicShelfMenuItems(mockMagicShelf); - const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf'); - del!.command!({}); - const confirmCall = confirmationService.confirm.mock.calls[0][0]; - confirmCall.accept(); - expect(messageService.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'Failed', - detail: 'Failed to delete shelf' - }); - }); - - it('should disable options for public shelf if not admin', () => { - userService.getCurrentUser.mockReturnValue({permissions: {admin: false}}); - const publicMagicShelf = {...mockMagicShelf, isPublic: true}; - const items = service.initializeMagicShelfMenuItems(publicMagicShelf); - const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf'); - const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf'); - expect(edit!.disabled).toBe(true); - expect(del!.disabled).toBe(true); - }); - - it('should not disable options for public shelf if admin', () => { - userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); - const publicMagicShelf = {...mockMagicShelf, isPublic: true}; - const items = service.initializeMagicShelfMenuItems(publicMagicShelf); - const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf'); - const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf'); - expect(edit!.disabled).toBe(false); - expect(del!.disabled).toBe(false); - }); - }); -}); - diff --git a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts index 77baca8d2..79ac095bc 100644 --- a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts +++ b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts @@ -12,6 +12,7 @@ import {UserService} from "../../settings/user-management/user.service"; import {LoadingService} from '../../../core/services/loading.service'; import {finalize} from 'rxjs'; import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service'; +import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service'; @Injectable({ providedIn: 'root', @@ -28,12 +29,23 @@ export class LibraryShelfMenuService { private magicShelfService = inject(MagicShelfService); private userService = inject(UserService); private loadingService = inject(LoadingService); + private bookDialogHelperService = inject(BookDialogHelperService); initializeLibraryMenuItems(entity: Library | Shelf | MagicShelf | null): MenuItem[] { return [ { label: 'Options', items: [ + { + label: 'Add Physical Book', + icon: 'pi pi-book', + command: () => { + this.bookDialogHelperService.openAddPhysicalBookDialog(entity?.id as number); + } + }, + { + separator: true + }, { label: 'Edit Library', icon: 'pi pi-pen-to-square', diff --git a/booklore-ui/src/app/features/book/service/library.service.spec.ts b/booklore-ui/src/app/features/book/service/library.service.spec.ts deleted file mode 100644 index e06c30c05..000000000 --- a/booklore-ui/src/app/features/book/service/library.service.spec.ts +++ /dev/null @@ -1,167 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {HttpClient} from '@angular/common/http'; -import {firstValueFrom, of, throwError} from 'rxjs'; - -import {LibraryService} from './library.service'; -import {BookService} from './book.service'; -import {AuthService} from '../../../shared/service/auth.service'; -import {Library} from '../model/library.model'; - -describe('LibraryService', () => { - let service: LibraryService; - let httpClientMock: any; - let bookServiceMock: any; - let authServiceMock: any; - - beforeEach(() => { - httpClientMock = { - get: vi.fn(), - post: vi.fn(), - put: vi.fn(), - patch: vi.fn(), - delete: vi.fn() - }; - - bookServiceMock = { - removeBooksByLibraryId: vi.fn(), - bookState$: of({ - books: [ - {id: 1, libraryId: 10}, - {id: 2, libraryId: 20}, - {id: 3, libraryId: 10}, - {id: 4} - ] - }) - }; - - authServiceMock = { - token$: of('token') - }; - - TestBed.configureTestingModule({ - providers: [ - LibraryService, - {provide: HttpClient, useValue: httpClientMock}, - {provide: BookService, useValue: bookServiceMock}, - {provide: AuthService, useValue: authServiceMock} - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - - service = runInInjectionContext( - injector, - () => TestBed.inject(LibraryService) - ); - }); - - it('should fetch libraries and update state', () => { - const libraries: Library[] = [{id: 1, name: 'LibA', icon: 'icon', watch: true, paths: []}]; - httpClientMock.get.mockReturnValue(of(libraries)); - service['fetchLibraries']().subscribe(result => { - expect(result).toEqual(libraries); - expect(service['libraryStateSubject'].value.libraries).toEqual(libraries); - expect(service['libraryStateSubject'].value.loaded).toBe(true); - }); - }); - - it('should handle fetch libraries error', () => { - httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); - service['libraryStateSubject'].next({libraries: null, loaded: false, error: null}); - service['fetchLibraries']().subscribe({ - error: (err: any) => { - expect(service['libraryStateSubject'].value.error).toBe('fail'); - } - }); - }); - - it('should create a library and update state', () => { - const library: Library = {id: 2, name: 'LibB', icon: 'icon', watch: true, paths: []}; - httpClientMock.post.mockReturnValue(of(library)); - service['libraryStateSubject'].next({libraries: [], loaded: true, error: null}); - service.createLibrary(library).subscribe(result => { - expect(result).toEqual(library); - expect(service['libraryStateSubject'].value.libraries).toContain(library); - }); - }); - - it('should update a library and update state', () => { - const library: Library = {id: 3, name: 'LibC', icon: 'icon', watch: true, paths: []}; - httpClientMock.put.mockReturnValue(of({...library, name: 'LibC2'})); - service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null}); - service.updateLibrary({...library, name: 'LibC2'}, 3).subscribe(result => { - expect(result.name).toBe('LibC2'); - expect(service['libraryStateSubject'].value.libraries?.find(l => l.id === 3)?.name).toBe('LibC2'); - }); - }); - - it('should delete a library and update state', () => { - httpClientMock.delete.mockReturnValue(of(void 0)); - const library: Library = {id: 4, name: 'LibD', icon: 'icon', watch: true, paths: []}; - service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null}); - service.deleteLibrary(4).subscribe(() => { - expect(service['libraryStateSubject'].value.libraries).toEqual([]); - expect(bookServiceMock.removeBooksByLibraryId).toHaveBeenCalledWith(4); - }); - }); - - it('should handle delete library error', () => { - httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error'))); - service['libraryStateSubject'].next({libraries: [{id: 5, name: 'LibE', icon: 'icon', watch: true, paths: []}], loaded: true, error: null}); - service.deleteLibrary(5).subscribe({ - error: () => { - expect(service['libraryStateSubject'].value.error).toBe('delete error'); - } - }); - }); - - it('should refresh a library and handle error', () => { - httpClientMock.put.mockReturnValue(throwError(() => new Error('refresh error'))); - service['libraryStateSubject'].next({libraries: [{id: 6, name: 'LibF', icon: 'icon', watch: true, paths: []}], loaded: true, error: null}); - service.refreshLibrary(6).subscribe({ - error: () => { - expect(service['libraryStateSubject'].value.error).toBe('refresh error'); - } - }); - }); - - it('should update library file naming pattern', () => { - const library: Library = {id: 7, name: 'LibG', icon: 'icon', watch: true, paths: [], fileNamingPattern: 'old'}; - const updatedLibrary = {...library, fileNamingPattern: 'new'}; - httpClientMock.patch.mockReturnValue(of(updatedLibrary)); - service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null}); - service.updateLibraryFileNamingPattern(7, 'new').subscribe(result => { - expect(result.fileNamingPattern).toBe('new'); - expect(service['libraryStateSubject'].value.libraries?.find(l => l.id === 7)?.fileNamingPattern).toBe('new'); - }); - }); - - it('should check if library exists by name', () => { - const library: Library = {id: 8, name: 'LibH', icon: 'icon', watch: true, paths: []}; - service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null}); - expect(service.doesLibraryExistByName('LibH')).toBe(true); - expect(service.doesLibraryExistByName('NonExistent')).toBe(false); - }); - - it('should find library by id', () => { - const library: Library = {id: 9, name: 'LibI', icon: 'icon', watch: true, paths: []}; - service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null}); - expect(service.findLibraryById(9)).toEqual(library); - expect(service.findLibraryById(999)).toBeUndefined(); - }); - - it('should get libraries from state', () => { - const libraries: Library[] = [ - {id: 10, name: 'LibJ', icon: 'icon', watch: true, paths: []} - ]; - service['libraryStateSubject'].next({libraries, loaded: true, error: null}); - expect(service.getLibrariesFromState()).toEqual(libraries); - }); - - it('should get book count for library', async () => { - const count = await firstValueFrom(service.getBookCount(10)); - expect(count).toBe(2); - }); -}); diff --git a/booklore-ui/src/app/features/book/service/metadata-task.spec.ts b/booklore-ui/src/app/features/book/service/metadata-task.spec.ts deleted file mode 100644 index e167f6c04..000000000 --- a/booklore-ui/src/app/features/book/service/metadata-task.spec.ts +++ /dev/null @@ -1,123 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {HttpClient} from '@angular/common/http'; -import {firstValueFrom, of, throwError} from 'rxjs'; - -import {MetadataFetchTask, MetadataTaskService} from './metadata-task'; -import {API_CONFIG} from '../../../core/config/api-config'; -import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../../../shared/model/metadata-batch-progress.model'; - -describe('MetadataTaskService', () => { - let service: MetadataTaskService; - let httpClientMock: any; - - beforeEach(() => { - httpClientMock = { - get: vi.fn(), - delete: vi.fn(), - post: vi.fn() - }; - - TestBed.configureTestingModule({ - providers: [ - MetadataTaskService, - { provide: HttpClient, useValue: httpClientMock } - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - - service = runInInjectionContext( - injector, - () => TestBed.inject(MetadataTaskService) - ); - }); - - it('should get task with proposals', async () => { - const task: MetadataFetchTask = { - id: 'task1', - status: 'IN_PROGRESS', - completed: 1, - totalBooks: 2, - startedAt: '2024-01-01T00:00:00Z', - completedAt: null, - initiatedBy: 'user1', - errorMessage: null, - proposals: [] - }; - httpClientMock.get.mockReturnValue(of({ task })); - const result = await firstValueFrom(service.getTaskWithProposals('task1')); - expect(result).toEqual(task); - expect(httpClientMock.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/task1`); - }); - - it('should handle error in getTaskWithProposals', async () => { - httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); - try { - await firstValueFrom(service.getTaskWithProposals('task2')); - } catch (e: any) { - expect(e.message).toBe('fail'); - } - }); - - it('should delete a task', async () => { - httpClientMock.delete.mockReturnValue(of(void 0)); - await firstValueFrom(service.deleteTask('task3')); - expect(httpClientMock.delete).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/task3`); - }); - - it('should handle error in deleteTask', async () => { - httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error'))); - try { - await firstValueFrom(service.deleteTask('task4')); - } catch (e: any) { - expect(e.message).toBe('delete error'); - } - }); - - it('should update proposal status', async () => { - httpClientMock.post.mockReturnValue(of(void 0)); - await firstValueFrom(service.updateProposalStatus('task5', 123, 'ACCEPTED')); - expect(httpClientMock.post).toHaveBeenCalledWith( - `${API_CONFIG.BASE_URL}/api/metadata/tasks/task5/proposals/123/status`, - null, - { params: { status: 'ACCEPTED' } } - ); - }); - - it('should handle error in updateProposalStatus', async () => { - httpClientMock.post.mockReturnValue(throwError(() => new Error('status error'))); - try { - await firstValueFrom(service.updateProposalStatus('task6', 456, 'REJECTED')); - } catch (e: any) { - expect(e.message).toBe('status error'); - } - }); - - it('should get active tasks', async () => { - const notifications: MetadataBatchProgressNotification[] = [ - { - taskId: 't1', - completed: 1, - total: 2, - message: 'Running', - status: MetadataBatchStatus.IN_PROGRESS, - review: false - } - ]; - httpClientMock.get.mockReturnValue(of(notifications)); - const result = await firstValueFrom(service.getActiveTasks()); - expect(result).toEqual(notifications); - expect(httpClientMock.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/active`); - }); - - it('should handle error in getActiveTasks', async () => { - httpClientMock.get.mockReturnValue(throwError(() => new Error('active error'))); - try { - await firstValueFrom(service.getActiveTasks()); - } catch (e: any) { - expect(e.message).toBe('active error'); - } - }); -}); diff --git a/booklore-ui/src/app/features/book/service/new-pdf-reader.service.spec.ts b/booklore-ui/src/app/features/book/service/new-pdf-reader.service.spec.ts deleted file mode 100644 index e76f2a994..000000000 --- a/booklore-ui/src/app/features/book/service/new-pdf-reader.service.spec.ts +++ /dev/null @@ -1,70 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {HttpClient} from '@angular/common/http'; - -import {NewPdfReaderService} from './new-pdf-reader.service'; -import {AuthService} from '../../../shared/service/auth.service'; -import {API_CONFIG} from '../../../core/config/api-config'; - -describe('NewPdfReaderService', () => { - let service: NewPdfReaderService; - let authServiceMock: any; - let httpClientMock: any; - - beforeEach(() => { - authServiceMock = { - getOidcAccessToken: vi.fn(), - getInternalAccessToken: vi.fn() - }; - - httpClientMock = { - get: vi.fn() - }; - - TestBed.configureTestingModule({ - providers: [ - NewPdfReaderService, - {provide: AuthService, useValue: authServiceMock}, - {provide: HttpClient, useValue: httpClientMock} - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - - service = runInInjectionContext( - injector, - () => TestBed.inject(NewPdfReaderService) - ); - }); - - it('should append token from OIDC access token', () => { - authServiceMock.getOidcAccessToken.mockReturnValue('oidc-token'); - authServiceMock.getInternalAccessToken.mockReturnValue(null); - - const url = 'http://test.com/resource'; - const result = (service as any).appendToken(url); - - expect(result).toContain('token=oidc-token'); - }); - - it('should not append token if both tokens are null', () => { - authServiceMock.getOidcAccessToken.mockReturnValue(null); - authServiceMock.getInternalAccessToken.mockReturnValue(null); - - const url = 'http://test.com/resource'; - const result = (service as any).appendToken(url); - - expect(result).toBe(url); - }); - - it('should call http.get with correct URL', () => { - authServiceMock.getOidcAccessToken.mockReturnValue('token123'); - - service.getAvailablePages(42); - - expect(httpClientMock.get).toHaveBeenCalledWith( - `${API_CONFIG.BASE_URL}/api/v1/pdf/42/pages?token=token123` - ); - }); -}); diff --git a/booklore-ui/src/app/features/book/service/new-pdf-reader.service.ts b/booklore-ui/src/app/features/book/service/new-pdf-reader.service.ts index 40552a228..6d2c167a0 100644 --- a/booklore-ui/src/app/features/book/service/new-pdf-reader.service.ts +++ b/booklore-ui/src/app/features/book/service/new-pdf-reader.service.ts @@ -38,15 +38,27 @@ export class NewPdfReaderService { return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url; } - getAvailablePages(bookId: number) { - return this.http.get(this.appendToken(`${this.pagesUrl}/${bookId}/pages`)); + getAvailablePages(bookId: number, bookType?: string) { + let url = `${this.pagesUrl}/${bookId}/pages`; + if (bookType) { + url += `?bookType=${bookType}`; + } + return this.http.get(this.appendToken(url)); } - getPageInfo(bookId: number) { - return this.http.get(this.appendToken(`${this.pagesUrl}/${bookId}/info`)); + getPageInfo(bookId: number, bookType?: string) { + let url = `${this.pagesUrl}/${bookId}/info`; + if (bookType) { + url += `?bookType=${bookType}`; + } + return this.http.get(this.appendToken(url)); } - getPageImageUrl(bookId: number, page: number): string { - return this.appendToken(`${this.imageUrl}/${bookId}/pdf/pages/${page}`); + getPageImageUrl(bookId: number, page: number, bookType?: string): string { + let url = `${this.imageUrl}/${bookId}/pdf/pages/${page}`; + if (bookType) { + url += `?bookType=${bookType}`; + } + return this.appendToken(url); } } diff --git a/booklore-ui/src/app/features/book/service/shelf.service.spec.ts b/booklore-ui/src/app/features/book/service/shelf.service.spec.ts deleted file mode 100644 index 5681b749c..000000000 --- a/booklore-ui/src/app/features/book/service/shelf.service.spec.ts +++ /dev/null @@ -1,131 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {HttpClient} from '@angular/common/http'; -import {firstValueFrom, of, throwError} from 'rxjs'; - -import {ShelfService} from './shelf.service'; -import {BookService} from './book.service'; -import {UserService} from '../../settings/user-management/user.service'; -import {Shelf} from '../model/shelf.model'; - -describe('ShelfService', () => { - let service: ShelfService; - let httpClientMock: any; - let bookServiceMock: any; - let userServiceMock: any; - - beforeEach(() => { - httpClientMock = { - get: vi.fn(), - post: vi.fn(), - put: vi.fn(), - delete: vi.fn() - }; - - bookServiceMock = { - removeBooksFromShelf: vi.fn(), - bookState$: of({ - books: [ - {id: 1, shelves: [{id: 10}]}, - {id: 2, shelves: [{id: 20}]}, - {id: 3, shelves: []}, - {id: 4} - ] - }) - }; - - userServiceMock = { - userState$: of({user: {id: 1}}) - }; - - TestBed.configureTestingModule({ - providers: [ - ShelfService, - {provide: HttpClient, useValue: httpClientMock}, - {provide: BookService, useValue: bookServiceMock}, - {provide: UserService, useValue: userServiceMock}, - {provide: 'OAuthService', useValue: {}} - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - - service = runInInjectionContext( - injector, - () => TestBed.inject(ShelfService) - ); - }); - - it('should fetch shelves and update state', () => { - const shelves: Shelf[] = [{id: 1, name: 'A', icon: 'icon'}]; - httpClientMock.get.mockReturnValue(of(shelves)); - service['fetchShelves']().subscribe(result => { - expect(result).toEqual(shelves); - expect(service['shelfStateSubject'].value.shelves).toEqual(shelves); - expect(service['shelfStateSubject'].value.loaded).toBe(true); - }); - }); - - it('should handle fetch shelves error', () => { - httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); - service['shelfStateSubject'].next({shelves: null, loaded: false, error: null}); - service['fetchShelves']().subscribe({ - error: (err: any) => { - expect(service['shelfStateSubject'].value.error).toBe('fail'); - } - }); - }); - - it('should create a shelf and update state', () => { - const shelf: Shelf = {id: 2, name: 'B', icon: 'icon'}; - httpClientMock.post.mockReturnValue(of(shelf)); - service['shelfStateSubject'].next({shelves: [], loaded: true, error: null}); - service.createShelf(shelf).subscribe(result => { - expect(result).toEqual(shelf); - expect(service['shelfStateSubject'].value.shelves).toContain(shelf); - }); - }); - - it('should update a shelf and update state', () => { - const shelf: Shelf = {id: 3, name: 'C', icon: 'icon'}; - httpClientMock.put.mockReturnValue(of({...shelf, name: 'C2'})); - service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null}); - service.updateShelf({...shelf, name: 'C2'}, 3).subscribe(result => { - expect(result.name).toBe('C2'); - expect(service['shelfStateSubject'].value.shelves?.find(s => s.id === 3)?.name).toBe('C2'); - }); - }); - - it('should delete a shelf and update state', () => { - httpClientMock.delete.mockReturnValue(of(void 0)); - const shelf: Shelf = {id: 4, name: 'D', icon: 'icon'}; - service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null}); - service.deleteShelf(4).subscribe(() => { - expect(service['shelfStateSubject'].value.shelves).toEqual([]); - expect(bookServiceMock.removeBooksFromShelf).toHaveBeenCalledWith(4); - }); - }); - - it('should handle delete shelf error', () => { - httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error'))); - service['shelfStateSubject'].next({shelves: [{id: 5, name: 'E', icon: 'icon'}], loaded: true, error: null}); - service.deleteShelf(5).subscribe({ - error: () => { - expect(service['shelfStateSubject'].value.error).toBe('delete error'); - } - }); - }); - - it('should get shelf by id', () => { - const shelf: Shelf = {id: 6, name: 'F', icon: 'icon'}; - service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null}); - expect(service.getShelfById(6)).toEqual(shelf); - expect(service.getShelfById(999)).toBeUndefined(); - }); - - it('should get unshelved book count', async () => { - const count = await firstValueFrom(service.getUnshelvedBookCount()); - expect(count).toBe(2); - }); -}); diff --git a/booklore-ui/src/app/features/book/service/sort.service.spec.ts b/booklore-ui/src/app/features/book/service/sort.service.spec.ts deleted file mode 100644 index 415b5cab3..000000000 --- a/booklore-ui/src/app/features/book/service/sort.service.spec.ts +++ /dev/null @@ -1,153 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {SortService} from './sort.service'; -import {Book} from '../model/book.model'; -import {SortDirection} from '../model/sort.model'; - -function makeBook(partial: Partial): Book { - return { - id: 1, - bookType: "PDF", - libraryId: 1, - libraryName: "Lib", - ...partial, - } as Book; -} - -describe('SortService', () => { - let service: SortService; - let books: Book[]; - - beforeEach(() => { - service = new SortService(); - books = [ - makeBook({ - id: 1, - fileName: 'Book10.pdf', - metadata: { - bookId: 1, - title: 'Book 10', - authors: ['Alice'], - publishedDate: '2020-01-01', - seriesName: 'Series A', - seriesNumber: 2, - rating: 4.5, - reviewCount: 10, - }, - personalRating: 3, - addedOn: '2021-01-01T00:00:00Z', - lastReadTime: '2022-01-01T00:00:00Z', - fileSizeKb: 1000, - }), - makeBook({ - id: 2, - fileName: 'Book2.pdf', - metadata: { - bookId: 2, - title: 'Book 2', - authors: ['Bob'], - publishedDate: '2019-01-01', - seriesName: 'Series A', - seriesNumber: 1, - rating: 4.8, - reviewCount: 20, - }, - personalRating: 5, - addedOn: '2020-01-01T00:00:00Z', - lastReadTime: '2023-01-01T00:00:00Z', - fileSizeKb: 2000, - }), - makeBook({ - id: 3, - fileName: 'Book1.pdf', - metadata: { - bookId: 3, - title: 'Book 1', - authors: ['Alice'], - publishedDate: '2021-01-01', - rating: 4.0, - reviewCount: 5, - }, - personalRating: 4, - addedOn: '2022-01-01T00:00:00Z', - lastReadTime: '2021-01-01T00:00:00Z', - fileSizeKb: 500, - }), - ]; - }); - - it('should sort by title (natural order)', () => { - const sorted = service.applySort(books, {field: 'title', direction: SortDirection.ASCENDING, label: 'Title'}); - expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 2', 'Book 10']); - }); - - it('should sort by author', () => { - const sorted = service.applySort(books, {field: 'author', direction: SortDirection.ASCENDING, label: 'Author'}); - expect(sorted.map(b => b.metadata?.authors?.[0])).toEqual(['Alice', 'Alice', 'Bob']); - }); - - it('should sort by author surname', () => { - const testBooks = [ - makeBook({ id: 1, metadata: { bookId: 1, title: 'T1', authors: ['Terry Pratchett'] } }), - makeBook({ id: 2, metadata: { bookId: 2, title: 'T2', authors: ['Neil Gaiman'] } }), - makeBook({ id: 3, metadata: { bookId: 3, title: 'T3', authors: ['Stephen King'] } }), - ]; - - const sorted = service.applySort(testBooks, { field: 'authorSurnameVorname', direction: SortDirection.ASCENDING, label: 'Author (Surname)' }); - expect(sorted.map(b => b.metadata?.authors?.[0])).toEqual(['Neil Gaiman', 'Stephen King', 'Terry Pratchett']); - }); - - it('should sort by publishedDate descending', () => { - const sorted = service.applySort(books, {field: 'publishedDate', direction: SortDirection.DESCENDING, label: 'Published Date'}); - expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 10', 'Book 2']); - }); - - it('should sort by series (titleSeries)', () => { - const sorted = service.applySort(books, {field: 'titleSeries', direction: SortDirection.ASCENDING, label: 'Series'}); - expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 2', 'Book 10']); - }); - - it('should sort by personalRating descending', () => { - const sorted = service.applySort(books, {field: 'personalRating', direction: SortDirection.DESCENDING, label: 'Personal Rating'}); - expect(sorted.map(b => b.personalRating)).toEqual([5, 4, 3]); - }); - - it('should sort by fileName (natural order)', () => { - const sorted = service.applySort(books, {field: 'fileName', direction: SortDirection.ASCENDING, label: 'File Name'}); - expect(sorted.map(b => b.fileName)).toEqual(['Book1.pdf', 'Book2.pdf', 'Book10.pdf']); - }); - - it('should sort by fileSizeKb ascending', () => { - const sorted = service.applySort(books, {field: 'fileSizeKb', direction: SortDirection.ASCENDING, label: 'File Size'}); - expect(sorted.map(b => b.fileSizeKb)).toEqual([500, 1000, 2000]); - }); - - it('should sort by addedOn descending', () => { - const sorted = service.applySort(books, {field: 'addedOn', direction: SortDirection.DESCENDING, label: 'Added On'}); - expect(sorted.map(b => b.addedOn)).toEqual([ - '2022-01-01T00:00:00Z', - '2021-01-01T00:00:00Z', - '2020-01-01T00:00:00Z', - ]); - }); - - it('should handle missing extractor gracefully', () => { - const spy = vi.spyOn(console, 'warn').mockImplementation(() => { - }); - const sorted = service.applySort(books, {field: 'nonexistent', direction: SortDirection.ASCENDING, label: 'Nonexistent'} as any); - expect(sorted).toBe(books); - expect(spy).toHaveBeenCalled(); - spy.mockRestore(); - }); - - it('should return original array if no sort option', () => { - const sorted = service.applySort(books, null); - expect(sorted).toBe(books); - }); - - it('should sort by random (order is not predictable)', () => { - const sorted = service.applySort(books, {field: 'random', direction: SortDirection.ASCENDING, label: 'Random'}); - expect(sorted.length).toBe(3); - // Can't assert order, but should be a permutation of the input - expect(sorted.map(b => b.id).sort()).toEqual([1, 2, 3]); - }); -}); diff --git a/booklore-ui/src/app/features/library-creator/library-creator.component.html b/booklore-ui/src/app/features/library-creator/library-creator.component.html index 7bf1874d3..66d1da5ee 100644 --- a/booklore-ui/src/app/features/library-creator/library-creator.component.html +++ b/booklore-ui/src/app/features/library-creator/library-creator.component.html @@ -1,13 +1,13 @@
-
-
- -
-
-

- {{ mode === 'edit' ? 'Edit Library' : 'Create New Library' }} -

-

Set up a new library to organize and manage your book collection

+
+
+
+ +
+
+

{{ mode === 'edit' ? 'Edit Library' : 'New Library' }}

+

Configure your book collection

+
+
+ +
+
+
+ + Library Details +
+ +
+
+ +
+ + @if (chosenLibraryName.trim()) { + + } +
+
+ +
+ + @if (!selectedIcon) { + + } @else { +
+
+ +
+ + @if (selectedIcon.type === 'PRIME_NG') { + {{ selectedIcon.value }} + } @else { + Custom SVG + } + + +
+ } +
+
+
+ +
+
+ + Book Folders + {{ folders.length }} +
+ +
+ + + @if (folders.length > 0) { +
+ @for (folder of folders; track folder; let i = $index) { +
+
+ + + {{ folder }} + +
+ +
+ } +
+ } @else { +
+ + Add folders containing your book files +
+ } +
+
+ +
+
+ + Options +
+ +
+
+
+ Watch folders + +
+ +
+ +
+
+ Format priority + +
+
+ @for (format of formatPriority; track format.type; let i = $index) { +
+ {{ i + 1 }} + {{ format.type }} + +
+ } +
+
+
+
- - - -
-
- Library Details -
+
+
+ @if (!isLibraryDetailsValid() || !isDirectorySelectionValid()) { +
+ + + @if (!chosenLibraryName.trim()) { + Enter library name + } @else if (!selectedIcon) { + Select an icon + } @else { + Add at least one folder + } +
- - -
-
- Select Directories -
+ } @else { +
+ + Ready to {{ mode === 'edit' ? 'update' : 'create' }}
- - - - - - -
-
-
-
- -
-
-

Step 1: Library Information

-

Set up your library name, icon, and import preferences

-
-
- -
-
-
- -
- - @if (chosenLibraryName.trim()) { - - } -
-
- -
- -
- - @if (!selectedIcon) { - - } @else { -
-
- -
-
- Selected Icon - - @if (selectedIcon.type === 'PRIME_NG') { - {{ selectedIcon.value }} - } @else { - {{ selectedIcon.value }} (Custom) - } - -
- -
- } -
-
- -
- -
-
- -
- -
- -
-
-
- - @if (scanMode === 'FOLDER_AS_BOOK') { -
- -
- -
- -
-
-
- } -
- -
- -
-
- -
-
- - -
-
- -
-
-
-
-
-
- - -
-
-
- - - -
-
-
-
- -
-
-

Step 2: Book Directories

-

Add folders containing your book files

-
-
- -
-
- - -
- Add Book Folder - Browse for directories -
-
-
- - @if (folders.length === 0) { -
-
- -
-

No Folders Added Yet

-

- Click the button above to add folders containing your books.
- You can add multiple folders from different locations. -

-
- } @else { -
-
- - - {{ folders.length }} {{ folders.length === 1 ? 'folder' : 'folders' }} added - -
- -
- @for (folder of folders; track folder; let i = $index) { -
-
-
- -
-
{{ i + 1 }}
-
-
-
- {{ folder }} -
-
- - {{ getFolderName(folder) }} -
-
- -
- } -
-
- } -
-
- - -
-
-
- -
- + } +
+ +
diff --git a/booklore-ui/src/app/features/library-creator/library-creator.component.scss b/booklore-ui/src/app/features/library-creator/library-creator.component.scss index 42feb3b3c..cd48d4161 100644 --- a/booklore-ui/src/app/features/library-creator/library-creator.component.scss +++ b/booklore-ui/src/app/features/library-creator/library-creator.component.scss @@ -1,365 +1,37 @@ -@use '../../shared/styles/panel-shared' as panel; - .library-creator { - width: 700px; - max-width: 700px; + max-width: 90vw; display: flex; flex-direction: column; - height: 100%; + max-height: 85vh; background: var(--card-background); border: 1px solid var(--border-color); - border-radius: 10px; - box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08); - - @media (max-width: 768px) { - width: 100%; - max-width: 100%; - } - - @media (max-width: 640px) { - padding: 0.5rem; - } - - @media (max-width: 480px) { - padding: 0.25rem; - } + border-radius: 12px; + overflow: hidden; } -.main-header { - @include panel.panel-header; - padding: 1.75rem 1.75rem 1.25rem 1.75rem; +// Header +.dialog-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 1.25rem 1.5rem; background: var(--overlay-background); border-bottom: 1px solid var(--border-color); - margin-bottom: 1.5rem; - .header-icon-wrapper { - box-shadow: 0 3px 8px rgba(0, 0, 0, 0.3); - } - - @media (max-width: 768px) { - padding: 1.25rem; - } - - @media (max-width: 640px) { - padding: 1.25rem; - } - - @media (max-width: 480px) { - padding: 1rem; - } -} - -::ng-deep .custom-stepper { - display: flex; - flex-direction: column; - height: 100%; - width: 100%; - - .p-steppanels { - padding: 0 !important; - width: 100%; - } - - .p-steplist { - padding: 0 1rem !important; - width: 100%; - } - - .p-stepper-header { - padding: 0.875rem 1rem; - background: transparent; - border: 1px solid var(--border-color); - border-radius: 8px; - margin-bottom: 1.25rem; - transition: all 0.3s ease; - - &.p-stepper-header-active { - background: var(--overlay-background); - border-color: var(--primary-color); - - .step-title { - color: var(--primary-color); - font-weight: 600; - } - } - - .p-stepper-separator { - background: var(--p-surface-700); - height: 2px; - margin: 0 0.75rem; - } - } - - .p-stepper-panels { - background: transparent; - padding: 0 !important; - flex: 1; + .header-content { display: flex; - flex-direction: column; + align-items: center; + gap: 0.875rem; } - .p-stepper-panel { - flex: 1; - display: flex; - flex-direction: column; - } - - @media (max-width: 480px) { - .p-stepper-header { - padding: 0.5rem; - margin-bottom: 0.75rem; - } - - .p-steplist { - padding: 0 0.5rem !important; - } - } -} - -.step-content { - display: flex; - align-items: center; - gap: 0.625rem; - - .step-labels { - display: flex; - flex-direction: column; - - .step-title { - font-size: 0.875rem; - font-weight: 500; - color: var(--text-color); - transition: all 0.3s ease; - } - } - - @media (max-width: 640px) { - gap: 0.375rem; - - .step-labels { - display: none; - } - } -} - -.step-panel-wrapper { - display: flex; - flex-direction: column; - height: 100%; -} - -.step-panel-container { - width: 100%; - display: flex; - flex-direction: column; - padding: 1rem 2rem; - flex: 1; - overflow-y: auto; - - @media (max-width: 768px) { - padding: 1rem; - } - - @media (max-width: 480px) { - padding: 0.75rem 0.5rem 1.25rem; - } -} - -.panel-header { - @include panel.panel-header; -} - -.form-container { - display: flex; - flex-direction: column; - padding: 2rem 1.5rem 1.5rem; - background: var(--card-background); - border: 1px solid var(--border-color); - border-top: none; - width: 100%; - box-sizing: border-box; - - @media (max-width: 768px) { - padding: 1.5rem 1rem; - } - - @media (max-width: 640px) { - padding: 1rem; - } - - @media (max-width: 480px) { - min-width: 0; - } -} - -.form-section { - display: flex; - flex-direction: column; - gap: 1.5rem; - padding: 1.5rem 0; - - &:first-child { - padding-top: 0; - } - - &:last-child { - padding-bottom: 0; - } -} - -.form-group { - display: flex; - flex-direction: column; - gap: 0.5rem; - - &.highlight-group { - background: var(--overlay-background); - border-radius: 8px; - transition: all 0.3s ease; - } - - &.nested-group { - padding-left: 1rem; - border-left: 3px solid var(--primary-color); - margin-top: 0.5rem; - } - - @media (max-width: 480px) { - gap: 0.25rem; - - &.highlight-group { - padding: 0.5rem; - } - - &.nested-group { - padding-left: 0.5rem; - } - } -} - -.form-label { - display: flex; - align-items: center; - gap: 0.375rem; - font-size: 0.95rem; - font-weight: 600; - color: var(--text-color); - - .label-icon { - color: var(--primary-color); - } - - .required-indicator { - color: var(--p-red-500); - margin-left: 0.125rem; - } -} - -.input-wrapper { - position: relative; - - .input-full { - width: 100%; - padding-right: 2.5rem; - box-sizing: border-box; - } - - .input-icon { - position: absolute; - right: 0.75rem; - top: 50%; - transform: translateY(-50%); - font-size: 1rem; - pointer-events: none; - - &.success { - color: var(--p-green-500); - } - } -} - -::ng-deep .icon-select-btn { - display: flex; - align-items: center; - justify-content: center; - gap: 0.75rem; - width: 100%; - padding: 1rem; - background: var(--ground-background); - border: 1px dashed var(--border-color); - border-radius: 8px; - color: var(--text-color); - font-size: 0.875rem; - font-weight: 500; - cursor: pointer; - transition: all 0.3s ease; - - &:hover { - background: var(--overlay-background); - border-color: var(--primary-color); - color: var(--primary-color); - transform: translateY(-1px); - box-shadow: 0 3px 8px rgba(0, 0, 0, 0.2); - } - - i { - font-size: 1.25rem; - } - - .btn-content { - display: flex; - flex-direction: column; - align-items: flex-start; - gap: 0.125rem; - - .btn-title { - font-size: 0.9375rem; - font-weight: 600; - } - - .btn-subtitle { - font-size: 0.8rem; - opacity: 0.85; - } - } - - @media (max-width: 480px) { - padding: 0.75rem; - gap: 0.5rem; - - i { - font-size: 1.125rem; - } - - .btn-content { - .btn-title { - font-size: 0.875rem; - } - - .btn-subtitle { - font-size: 0.75rem; - } - } - } -} - -.selected-icon-display { - display: flex; - align-items: center; - gap: 0.75rem; - padding: 0.875rem; - border: 1px solid var(--border-color); - border-radius: 8px; - background: var(--ground-background); - - .icon-preview { + .header-icon { display: flex; align-items: center; justify-content: center; - width: 40px; - height: 40px; + width: 42px; + height: 42px; background: var(--primary-color); - border-radius: 8px; + border-radius: 10px; i { font-size: 1.25rem; @@ -367,488 +39,571 @@ } } - .icon-info { - flex: 1; - display: flex; - flex-direction: column; - gap: 0.125rem; - - .icon-label { - font-size: 0.8rem; - color: var(--text-secondary-color); - } - - .icon-name { - font-size: 0.875rem; - font-weight: 500; - color: var(--text-color); - font-family: monospace; - } - } - - @media (max-width: 480px) { - padding: 0.5rem; - gap: 0.5rem; - - .icon-preview { - width: 32px; - height: 32px; - - i { - font-size: 1rem; - } - } - - .icon-info { - .icon-label { - font-size: 0.75rem; - } - - .icon-name { - font-size: 0.8rem; - } - } - } -} - -.input-with-info { - display: flex; - align-items: center; - gap: 0.75rem; - - .info-tooltip { - display: flex; - align-items: center; - justify-content: center; - border-radius: 50%; - color: var(--p-blue-500); - transition: all 0.2s ease; - - i { - font-size: 1.125rem; - transition: all 0.2s ease; - - &:hover { - color: var(--primary-color); - transform: scale(1.1); - } - } - - &.large i { + .header-text { + h1 { + margin: 0; font-size: 1.25rem; - } - } -} - -.toggle-group { - display: flex; - align-items: center; - gap: 0.75rem; - - .toggle-wrapper { - display: flex; - align-items: center; - gap: 0.5rem; - padding: 0.5rem 0.875rem; - background: var(--ground-background); - border-radius: 8px; - border: 1px solid var(--border-color); - transition: all 0.3s ease; - - .toggle-label { - cursor: pointer; - user-select: none; - - .toggle-status { - font-size: 0.9rem; - font-weight: 500; - - &.active { - color: var(--p-green-500); - } - - &.inactive { - color: var(--text-secondary-color); - } - } - } - } -} - -.divider { - height: 2px; - background: linear-gradient(90deg, transparent, var(--border-color), transparent); -} - -.directories-container { - display: flex; - flex-direction: column; - gap: 0.5rem; - padding: 1.25rem; - background: var(--card-background); - border: 1px solid var(--border-color); - border-top: none; - min-height: 300px; - width: 100%; - box-sizing: border-box; - - @media (max-width: 768px) { - padding: 1rem; - } - - @media (max-width: 480px) { - min-width: 0; - } -} - -.add-folder-section { - ::ng-deep .add-folder-btn { - display: flex; - justify-content: center; - align-items: center; - gap: 1rem; - width: 100%; - padding: 0.5rem 1rem 0; - border: none; - border-radius: 8px; - cursor: pointer; - transition: all 0.3s ease; - - &:hover { - transform: translateY(-1px); - } - - i { - font-size: 1.5rem; - } - - .btn-content { - display: flex; - flex-direction: column; - align-items: flex-start; - gap: 0.125rem; - - .btn-title { - font-size: 0.9375rem; - font-weight: 600; - } - - .btn-subtitle { - font-size: 0.8rem; - opacity: 0.9; - } - } - - @media (max-width: 480px) { - gap: 0.5rem; - padding: 0.25rem 0.5rem 0; - - .btn-title { - font-size: 0.8rem; - } - - .btn-subtitle { - font-size: 0.7rem; - } - } - } -} - -.empty-state { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - text-align: center; - padding-bottom: 2rem; - - .empty-icon-wrapper { - display: flex; - align-items: center; - justify-content: center; - width: 80px; - height: 80px; - background: var(--overlay-background); - border-radius: 50%; - margin-bottom: 1rem; - - .empty-icon { - font-size: 2.5rem; - color: var(--text-secondary-color); - opacity: 0.5; - } - } - - .empty-title { - margin: 0 0 0.5rem 0; - font-size: 1.125rem; - font-weight: 600; - color: var(--text-color); - } - - .empty-description { - margin: 0; - font-size: 0.875rem; - color: var(--text-secondary-color); - max-width: 400px; - line-height: 1.5; - } - - @media (max-width: 480px) { - padding-bottom: 1rem; - - .empty-icon-wrapper { - width: 48px; - height: 48px; - - .empty-icon { - font-size: 1.5rem; - } - } - - .empty-title { - font-size: 0.95rem; - } - - .empty-description { - font-size: 0.75rem; - max-width: 90vw; - } - } -} - -.folders-list { - display: flex; - flex-direction: column; - gap: 0.5rem; - - .list-header { - display: flex; - align-items: center; - justify-content: space-between; - padding: 0.5rem 0.75rem; - background: var(--overlay-background); - border-radius: 6px; - - .folder-count { - display: flex; - align-items: center; - gap: 0.375rem; - font-size: 0.9rem; font-weight: 600; color: var(--text-color); + } - i { - color: var(--primary-color); - } + p { + margin: 0.125rem 0 0; + font-size: 0.875rem; + color: var(--text-secondary-color); } } } -.folders-grid { +// Body +.dialog-body { + flex: 1; + overflow-y: auto; + padding: 1.75rem 2rem; display: flex; flex-direction: column; - gap: 0.5rem; - max-height: 400px; - overflow-y: auto; - overflow-x: hidden; - padding-right: 0.25rem; - width: 100%; + gap: 2rem; &::-webkit-scrollbar { width: 6px; } &::-webkit-scrollbar-track { - background: var(--overlay-background); - border-radius: 3px; + background: transparent; } &::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 3px; - transition: background 0.2s ease; &:hover { background: var(--primary-color); } } - - scrollbar-width: thin; - scrollbar-color: var(--border-color) var(--overlay-background); } -.folder-card { +// Sections +.form-section { + .section-header { + display: flex; + align-items: center; + gap: 0.5rem; + margin-bottom: 1.125rem; + font-size: 0.85rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.03em; + color: var(--text-secondary-color); + + i { + font-size: 0.9rem; + color: var(--primary-color); + } + + .section-badge { + display: flex; + align-items: center; + justify-content: center; + min-width: 20px; + height: 20px; + padding: 0 0.375rem; + background: var(--primary-color); + color: var(--primary-contrast-color); + border-radius: 10px; + font-size: 0.7rem; + font-weight: 600; + } + } +} + +// Form Fields +.form-row { + display: flex; + gap: 1.25rem; + + &.two-col { + .form-field { + flex: 1; + min-width: 0; + } + } + + @media (max-width: 520px) { + flex-direction: column; + } +} + +.form-field { + display: flex; + flex-direction: column; + gap: 0.75rem; + + label { + font-size: 0.9rem; + font-weight: 500; + color: var(--text-color); + + .required { + color: var(--p-red-400); + } + } + + .input-container { + position: relative; + + .input-full { + width: 100%; + padding-right: 2.25rem; + } + + .field-status { + position: absolute; + right: 0.75rem; + top: 50%; + transform: translateY(-50%); + font-size: 0.9rem; + + &.success { + color: var(--p-green-500); + } + } + } +} + +// Icon picker +.icon-picker-trigger { display: flex; align-items: center; - gap: 0.75rem; - padding: 0.875rem; - background: var(--ground-background); - border: 1px solid var(--border-color); - border-radius: 8px; - transition: all 0.3s ease; + justify-content: center; + gap: 0.5rem; width: 100%; - max-width: 100%; - overflow: hidden; - min-height: 70px; + padding: 0.875rem 1rem; + background: var(--ground-background); + border: 1px dashed var(--border-color); + border-radius: 8px; + color: var(--text-secondary-color); + font-size: 0.875rem; + cursor: pointer; + transition: all 0.2s ease; &:hover { border-color: var(--primary-color); - transform: translateX(3px); - box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1); - - .folder-icon { - color: var(--primary-color); - transform: scale(1.08); - } + color: var(--primary-color); + background: var(--overlay-background); } - .folder-icon-section { - position: relative; + i { + font-size: 0.875rem; + } +} + +.icon-selected { + display: flex; + align-items: center; + gap: 0.625rem; + padding: 0.625rem 0.875rem; + background: var(--ground-background); + border: 1px solid var(--border-color); + border-radius: 8px; + + .icon-preview { display: flex; align-items: center; justify-content: center; - flex-shrink: 0; + width: 24px; + height: 24px; + background: var(--primary-color); + border-radius: 5px; + color: var(--primary-contrast-color); + } - .folder-icon-wrapper { - display: flex; - align-items: center; - justify-content: center; - width: 38px; - height: 38px; - background: var(--overlay-background); - border-radius: 8px; - flex-shrink: 0; + .icon-value { + flex: 1; + font-size: 0.875rem; + font-family: monospace; + color: var(--text-color); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } - .folder-icon { - font-size: 1.125rem; - color: var(--text-secondary-color); - transition: all 0.3s ease; - } + .icon-clear { + display: flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + background: transparent; + border: none; + border-radius: 4px; + color: var(--text-secondary-color); + cursor: pointer; + transition: all 0.2s ease; + + &:hover { + background: rgba(239, 68, 68, 0.15); + color: var(--p-red-400); } - .folder-number { - position: absolute; - bottom: -3px; - right: -3px; - display: flex; - align-items: center; - justify-content: center; - width: 18px; - height: 18px; - background: var(--primary-color); - color: var(--primary-contrast-color); - border-radius: 50%; - font-size: 0.6875rem; - font-weight: 600; - border: 1px solid var(--ground-background); + i { + font-size: 0.75rem; + } + } +} + +// Folders zone +.folders-zone { + display: flex; + flex-direction: column; + gap: 1rem; + padding: 1.25rem; + background: var(--ground-background); + border: 1px solid var(--border-color); + border-radius: 8px; +} + +.add-folder-trigger { + display: flex; + align-items: center; + justify-content: center; + gap: 0.5rem; + width: 100%; + padding: 0.875rem; + background: transparent; + border: 1px dashed var(--border-color); + border-radius: 6px; + color: var(--primary-color); + font-size: 0.875rem; + font-weight: 500; + cursor: pointer; + transition: all 0.2s ease; + + &:hover { + background: var(--overlay-background); + border-color: var(--primary-color); + } + + i { + font-size: 1rem; + } +} + +.folders-list { + display: flex; + flex-direction: column; + gap: 0.625rem; + max-height: 180px; + overflow-y: auto; + + &::-webkit-scrollbar { + width: 4px; + } + + &::-webkit-scrollbar-thumb { + background: var(--border-color); + border-radius: 2px; + } +} + +.folder-item { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.75rem 0.875rem; + background: var(--card-background); + border: 1px solid var(--border-color); + border-radius: 6px; + transition: all 0.2s ease; + + &:hover { + border-color: var(--primary-color); + + .folder-info i { + color: var(--primary-color); } } - .folder-details { + .folder-info { flex: 1; display: flex; - flex-direction: column; - gap: 0.375rem; + align-items: center; + gap: 0.5rem; min-width: 0; - overflow: hidden; + + i { + font-size: 0.875rem; + color: var(--text-secondary-color); + flex-shrink: 0; + transition: color 0.2s ease; + } .folder-path { - font-size: 0.9rem; + font-size: 0.875rem; color: var(--text-color); - font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; - max-width: 100%; - line-height: 1.3; - } - - .folder-meta { - display: flex; - align-items: center; - gap: 0.25rem; - font-size: 0.75rem; - color: var(--text-secondary-color); - line-height: 1.3; - - i { - font-size: 0.6875rem; - flex-shrink: 0; - } - - span { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - min-width: 0; - flex: 1; - } } } - ::ng-deep .p-button { - flex-shrink: 0; + .folder-remove { + display: flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + background: transparent; + border: none; + border-radius: 4px; + color: var(--text-secondary-color); + cursor: pointer; + opacity: 0.6; + transition: all 0.2s ease; + + &:hover { + opacity: 1; + background: rgba(239, 68, 68, 0.15); + color: var(--p-red-400); + } + + i { + font-size: 0.6875rem; + } + } +} + +.empty-hint { + display: flex; + align-items: center; + justify-content: center; + gap: 0.5rem; + padding: 1rem; + color: var(--text-secondary-color); + font-size: 0.875rem; + + i { + font-size: 0.9rem; + opacity: 0.7; + } +} + +// Options section +.options-grid { + display: flex; + flex-direction: column; + gap: 1.5rem; + padding: 1.25rem; + background: var(--ground-background); + border: 1px solid var(--border-color); + border-radius: 8px; +} + +.option-item { + display: flex; + align-items: center; + gap: 0.75rem; + + p-toggleswitch { + --p-toggleswitch-checked-background: var(--p-green-500); + --p-toggleswitch-checked-hover-background: var(--p-green-600); } - @media (max-width: 640px) { + &.format-priority-option { flex-direction: column; align-items: flex-start; - - .folder-icon-section { - align-self: flex-start; - } - - .folder-details { - width: 100%; - } } - @media (max-width: 480px) { - padding: 0.5rem; - gap: 0.5rem; + .option-label { + display: flex; + align-items: center; + gap: 0.375rem; + font-size: 0.9rem; + font-weight: 500; + color: var(--text-color); - .folder-icon-section { - .folder-icon-wrapper { - width: 28px; - height: 28px; + .info-icon { + font-size: 0.9rem; + color: var(--p-blue-400); + cursor: help; + transition: color 0.2s ease; - .folder-icon { - font-size: 0.95rem; - } - } - - .folder-number { - width: 14px; - height: 14px; - font-size: 0.6rem; - } - } - - .folder-details { - .folder-path { - font-size: 0.8rem; - } - - .folder-meta { - font-size: 0.65rem; + &:hover { + color: var(--primary-color); } } } } -.panel-footer { - @include panel.dialog-footer; +// Format chips +.format-chips { + display: flex; + flex-wrap: wrap; + gap: 0.625rem; + width: 100%; +} + +.format-chip { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.5rem 0.75rem; + background: var(--card-background); + border: 1px solid var(--border-color); + border-radius: 6px; + cursor: grab; + transition: all 0.2s ease; + + &:hover { + border-color: var(--primary-color); + } + + .chip-rank { + display: flex; + align-items: center; + justify-content: center; + width: 16px; + height: 16px; + background: var(--primary-color); + color: var(--primary-contrast-color); + border-radius: 50%; + font-size: 0.625rem; + font-weight: 600; + } + + .chip-label { + font-size: 0.8rem; + font-weight: 500; + color: var(--text-color); + } + + .drag-indicator { + font-size: 0.875rem; + color: var(--text-secondary-color); + opacity: 0.7; + padding: 0.25rem; + margin: -0.25rem; + cursor: grab; + + &:hover { + opacity: 1; + color: var(--primary-color); + } + } +} + +.cdk-drag-preview { + box-sizing: border-box; + border-radius: 6px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25); + background: var(--overlay-background); + border: 1px solid var(--primary-color); +} + +.cdk-drag-placeholder { + opacity: 0.3; +} + +.cdk-drag-animating { + transition: transform 150ms cubic-bezier(0, 0, 0.2, 1); +} + +// Footer +.dialog-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + padding: 1rem 1.5rem; + background: var(--overlay-background); border-top: 1px solid var(--border-color); - border-left: none; - border-right: none; +} + +.validation-status { + flex: 1; + min-width: 0; + + .status-message { + display: flex; + align-items: center; + gap: 0.375rem; + font-size: 0.875rem; + font-weight: 500; + + i { + font-size: 0.9rem; + } + + &.warning { + color: var(--p-orange-400); + } + + &.ready { + color: var(--p-green-500); + } + } +} + +.footer-actions { + display: flex; + gap: 0.75rem; flex-shrink: 0; } -.validation-message { - @include panel.validation-message; -} +// Responsive +@media (max-width: 520px) { + .library-creator { + width: 100%; + max-width: 100%; + border-radius: 0; + max-height: 100vh; + } -.full-width { - width: 100%; + .dialog-header { + padding: 1rem; + + .header-icon { + width: 36px; + height: 36px; + + i { + font-size: 1rem; + } + } + + .header-text h1 { + font-size: 1rem; + } + } + + .dialog-body { + padding: 1.5rem; + gap: 1.75rem; + } + + .dialog-footer { + flex-direction: column; + padding: 1rem; + gap: 0.75rem; + + .validation-status { + width: 100%; + } + + .footer-actions { + width: 100%; + justify-content: flex-end; + } + } + + .format-chips { + gap: 0.375rem; + } + + .format-chip { + padding: 0.375rem 0.5rem; + + .chip-label { + font-size: 0.6875rem; + } + } } diff --git a/booklore-ui/src/app/features/library-creator/library-creator.component.ts b/booklore-ui/src/app/features/library-creator/library-creator.component.ts index d0b4773dd..c2cf3e473 100644 --- a/booklore-ui/src/app/features/library-creator/library-creator.component.ts +++ b/booklore-ui/src/app/features/library-creator/library-creator.component.ts @@ -3,26 +3,25 @@ import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; import {MessageService} from 'primeng/api'; import {Router} from '@angular/router'; import {LibraryService} from '../book/service/library.service'; -import {TableModule} from 'primeng/table'; -import {Step, StepList, StepPanel, StepPanels, Stepper} from 'primeng/stepper'; import {FormsModule} from '@angular/forms'; import {InputText} from 'primeng/inputtext'; -import {BookFileType, Library, LibraryScanMode} from '../book/model/library.model'; +import {Library} from '../book/model/library.model'; +import {BookType} from '../book/model/book.model'; import {ToggleSwitch} from 'primeng/toggleswitch'; import {Tooltip} from 'primeng/tooltip'; import {IconPickerService, IconSelection} from '../../shared/service/icon-picker.service'; -import {Select} from 'primeng/select'; import {Button} from 'primeng/button'; import {IconDisplayComponent} from '../../shared/components/icon-display/icon-display.component'; import {DialogLauncherService} from '../../shared/services/dialog-launcher.service'; import {switchMap} from 'rxjs/operators'; -import {map, of} from 'rxjs'; +import {map} from 'rxjs'; +import {CdkDragDrop, DragDropModule, moveItemInArray} from '@angular/cdk/drag-drop'; @Component({ selector: 'app-library-creator', standalone: true, templateUrl: './library-creator.component.html', - imports: [TableModule, StepPanel, FormsModule, InputText, Stepper, StepList, Step, StepPanels, ToggleSwitch, Tooltip, Select, Button, IconDisplayComponent], + imports: [FormsModule, InputText, ToggleSwitch, Tooltip, Button, IconDisplayComponent, DragDropModule], styleUrl: './library-creator.component.scss' }) export class LibraryCreatorComponent implements OnInit { @@ -34,19 +33,16 @@ export class LibraryCreatorComponent implements OnInit { library!: Library | undefined; editModeLibraryName: string = ''; watch: boolean = false; - scanMode: LibraryScanMode = 'FILE_AS_BOOK'; - defaultBookFormat: BookFileType | undefined = undefined; + formatPriority: {type: BookType, label: string}[] = []; - readonly scanModeOptions = [ - {label: 'Each file is a book (Recommended)', value: 'FILE_AS_BOOK'}, - {label: 'Each folder is a book with extras (Deprecated)', value: 'FOLDER_AS_BOOK'} - ]; - - readonly bookFormatOptions = [ - {label: 'None', value: undefined}, - {label: 'EPUB', value: 'EPUB'}, - {label: 'PDF', value: 'PDF'}, - {label: 'CBX/CBZ/CBR', value: 'CBX'} + readonly allBookFormats: {type: BookType, label: string}[] = [ + {type: 'EPUB', label: 'EPUB'}, + {type: 'PDF', label: 'PDF'}, + {type: 'CBX', label: 'CBX (CBZ/CBR/CB7)'}, + {type: 'MOBI', label: 'MOBI'}, + {type: 'AZW3', label: 'AZW3'}, + {type: 'FB2', label: 'FB2'}, + {type: 'AUDIOBOOK', label: 'Audiobook'} ]; private dialogLauncherService = inject(DialogLauncherService); @@ -58,12 +54,14 @@ export class LibraryCreatorComponent implements OnInit { private iconPicker = inject(IconPickerService); ngOnInit(): void { + this.initializeFormatPriority(); + const data = this.dynamicDialogConfig?.data; if (data?.mode === 'edit') { this.mode = data.mode; this.library = this.libraryService.findLibraryById(data.libraryId); if (this.library) { - const {name, icon, iconType, paths, watch, scanMode, defaultBookFormat} = this.library; + const {name, icon, iconType, paths, watch, formatPriority} = this.library; this.chosenLibraryName = name; this.editModeLibraryName = name; @@ -75,13 +73,26 @@ export class LibraryCreatorComponent implements OnInit { } this.watch = watch; - this.scanMode = scanMode || 'FILE_AS_BOOK'; - this.defaultBookFormat = defaultBookFormat || undefined; + if (formatPriority && formatPriority.length > 0) { + this.formatPriority = formatPriority.map(type => + this.allBookFormats.find(f => f.type === type)! + ).filter(f => f !== undefined); + const existingTypes = new Set(formatPriority); + this.allBookFormats.forEach(f => { + if (!existingTypes.has(f.type)) { + this.formatPriority.push(f); + } + }); + } this.folders = paths.map(path => path.path); } } } + private initializeFormatPriority(): void { + this.formatPriority = [...this.allBookFormats]; + } + closeDialog(): void { this.dynamicDialogRef.close(); } @@ -127,9 +138,9 @@ export class LibraryCreatorComponent implements OnInit { return this.folders.length > 0; } - validateLibraryNameAndProceed(activateCallback: Function): void { + createOrUpdateLibrary(): void { const trimmedLibraryName = this.chosenLibraryName.trim(); - if (trimmedLibraryName && trimmedLibraryName != this.editModeLibraryName) { + if (trimmedLibraryName && trimmedLibraryName !== this.editModeLibraryName) { const exists = this.libraryService.doesLibraryExistByName(trimmedLibraryName); if (exists) { this.messageService.add({ @@ -137,15 +148,10 @@ export class LibraryCreatorComponent implements OnInit { summary: 'Library Name Exists', detail: 'This library name is already taken.', }); - } else { - activateCallback(2); + return; } - } else { - activateCallback(2); } - } - createOrUpdateLibrary(): void { const iconValue = this.selectedIcon?.value || 'heart'; const iconType = this.selectedIcon?.type || 'PRIME_NG'; @@ -155,8 +161,7 @@ export class LibraryCreatorComponent implements OnInit { iconType: iconType, paths: this.folders.map(folder => ({path: folder})), watch: this.watch, - scanMode: this.scanMode, - defaultBookFormat: this.defaultBookFormat + formatPriority: this.formatPriority.map(f => f.type) }; if (this.mode === 'edit') { @@ -208,11 +213,7 @@ export class LibraryCreatorComponent implements OnInit { } } - getFolderName(path: string): string { - if (!path || typeof path !== 'string') { - return ''; - } - const parts = path.split('/').filter(p => p); - return parts[parts.length - 1] || path; + onFormatPriorityDrop(event: CdkDragDrop<{type: BookType, label: string}[]>): void { + moveItemInArray(this.formatPriority, event.previousIndex, event.currentIndex); } } diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.html index 223baecd9..10eb8216f 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.html @@ -24,8 +24,8 @@ class="p-datatable-sm"> - Start Time - End Time + Session + Type Duration Progress Progress Delta @@ -34,8 +34,18 @@ - {{ formatDate(session.startTime) }} - {{ formatDate(session.endTime) }} + +
+ {{ formatSessionDate(session.startTime) }} + {{ formatTime(session.startTime) }} → {{ formatTime(session.endTime) }} +
+ + + + + {{ formatBookType(session.bookType) }} + + {{ getActualDuration(session) }} @if (session.startProgress !== null && session.startProgress !== undefined && session.endProgress !== null && session.endProgress !== undefined) { @@ -46,14 +56,17 @@ @if (session.progressDelta !== null && session.progressDelta !== undefined) { - + + + {{ (session.progressDelta > 0 ? '+' : '') + session.progressDelta }}% + } @else { - N/A + - } - @if (session.startLocation && session.endLocation && isPageNumber(session.startLocation)) { - Page {{ session.startLocation }} → Page {{ session.endLocation }} + @if (session.startLocation && session.endLocation) { + {{ formatLocation(session) }} } @else { - } diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.scss b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.scss index 41289dce5..fc7226345 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.scss +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.scss @@ -27,6 +27,103 @@ color: var(--text-color); } +.session-time { + display: flex; + flex-direction: column; + gap: 0.125rem; + + .session-date { + font-weight: 500; + color: var(--text-color); + } + + .session-range { + font-size: 0.8rem; + color: var(--text-color-secondary); + } +} + +.book-type-badge { + display: inline-flex; + align-items: center; + gap: 0.375rem; + padding: 0.25rem 0.5rem; + border-radius: 0.375rem; + font-size: 0.8rem; + font-weight: 600; + + i { + font-size: 0.8rem; + } + + &.book-type-pdf { + color: var(--book-type-pdf-color); + background-color: rgba(220, 38, 38, 0.1); + } + + &.book-type-epub { + color: var(--book-type-epub-color); + background-color: rgba(22, 163, 74, 0.1); + } + + &.book-type-cbx, + &.book-type-cbz, + &.book-type-cbr, + &.book-type-cb7 { + color: var(--book-type-cbx-color); + background-color: rgba(59, 130, 246, 0.1); + } + + &.book-type-fb2 { + color: var(--book-type-fb2-color); + background-color: rgba(236, 72, 153, 0.1); + } + + &.book-type-mobi { + color: var(--book-type-mobi-color); + background-color: rgba(99, 102, 241, 0.1); + } + + &.book-type-azw3 { + color: var(--book-type-azw3-color); + background-color: rgba(20, 184, 166, 0.1); + } + + &.book-type-audiobook { + color: var(--book-type-audiobook-color); + background-color: rgba(234, 179, 8, 0.1); + } +} + +.progress-delta-badge { + display: inline-flex; + align-items: center; + gap: 0.375rem; + padding: 0.25rem 0.5rem; + border-radius: 0.375rem; + font-size: 0.8rem; + font-weight: 600; + + i { + font-size: 0.8rem; + } + + &.progress-positive { + color: #16a34a; + background-color: rgba(22, 163, 74, 0.1); + } + + &.progress-negative { + color: #dc2626; + background-color: rgba(220, 38, 38, 0.1); + } + + &.progress-neutral { + color: var(--text-color-secondary); + background-color: rgba(128, 128, 128, 0.1); + } +} + :host ::ng-deep { .p-datatable { .p-datatable-thead > tr > th { diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.ts index 910812827..2eada332b 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.ts @@ -3,12 +3,10 @@ import {CommonModule} from '@angular/common'; import {ReadingSessionApiService, ReadingSessionResponse} from '../../../../../shared/service/reading-session-api.service'; import {TableModule} from 'primeng/table'; import {ProgressSpinnerModule} from 'primeng/progressspinner'; -import {TagModule} from 'primeng/tag'; - @Component({ selector: 'app-book-reading-sessions', standalone: true, - imports: [CommonModule, TableModule, ProgressSpinnerModule, TagModule], + imports: [CommonModule, TableModule, ProgressSpinnerModule], templateUrl: './book-reading-sessions.component.html', styleUrls: ['./book-reading-sessions.component.scss'] }) @@ -91,14 +89,79 @@ export class BookReadingSessionsComponent implements OnInit, OnChanges { return new Date(dateString).toLocaleString(); } + formatSessionDate(dateString: string): string { + return new Date(dateString).toLocaleDateString(undefined, { + month: 'short', + day: 'numeric', + year: 'numeric' + }); + } + + formatTime(dateString: string): string { + return new Date(dateString).toLocaleTimeString(undefined, { + hour: 'numeric', + minute: '2-digit' + }); + } + + getBookTypeIcon(bookType: string): string { + const iconMap: Record = { + 'PDF': 'pi pi-file-pdf', + 'EPUB': 'pi pi-book', + 'CBX': 'pi pi-images', + 'CBZ': 'pi pi-images', + 'CBR': 'pi pi-images', + 'CB7': 'pi pi-images', + 'FB2': 'pi pi-file', + 'MOBI': 'pi pi-book', + 'AZW3': 'pi pi-book', + 'AUDIOBOOK': 'pi pi-headphones' + }; + return iconMap[bookType] || 'pi pi-file'; + } + + formatBookType(bookType: string): string { + if (bookType === 'AUDIOBOOK') return 'Audio'; + return bookType; + } + getProgressColor(delta: number): 'success' | 'secondary' | 'danger' { if (delta > 0) return 'success'; if (delta < 0) return 'danger'; return 'secondary'; } + getProgressDeltaClass(delta: number): string { + if (delta > 0) return 'progress-positive'; + if (delta < 0) return 'progress-negative'; + return 'progress-neutral'; + } + + getProgressDeltaIcon(delta: number): string { + if (delta > 0) return 'pi pi-arrow-up'; + if (delta < 0) return 'pi pi-arrow-down'; + return 'pi pi-minus'; + } + isPageNumber(location: string | undefined): boolean { if (!location) return false; return !isNaN(Number(location)) && location.trim() !== ''; } + + formatLocation(session: ReadingSessionResponse): string { + const start = session.startLocation; + const end = session.endLocation; + + if (!start || !end) return '-'; + + if (session.bookType === 'AUDIOBOOK') { + return `${start} → ${end}`; + } + + if (this.isPageNumber(start)) { + return `Page ${start} → ${end}`; + } + + return '-'; + } } diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.html index 0943ccc4a..7d9d64bc2 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.html @@ -1,465 +1,354 @@ @if (book$ | async; as book) { -
-
- - - - -
- -
- -
- - - @if (!metadataForm.get('coverLocked')?.value) { - - } - @if (metadataForm.get('coverLocked')?.value) { - - } - - - -
- -
- @if (!metadataForm.get('coverLocked')?.value) { - - } - @if (metadataForm.get('coverLocked')?.value) { - - } - - - - - - - -
+ +
+ +
+
+ + Current +
+
+ + +
+
+ + Fetched
- @for (field of metadataFieldsTop; track field) { -
- -
- -
- @if (!metadataForm.get(field.lockedKey)?.value) { - - } - @if (metadataForm.get(field.lockedKey)?.value) { - - } - @if (field.controlName === 'publishedDate') { - - } @else { - - } -
-
- - -
- -
- @if (!metadataForm.get(field.lockedKey)?.value) { - - } - @if (metadataForm.get(field.lockedKey)?.value) { - - } - @if (field.controlName === 'publishedDate') { - - } @else { - - } - - -
-
+ +
+
+ + Cover Image
- } - @for (field of metadataChips; track field) { -
- -
- -
- @if (!metadataForm.get(field.lockedKey)?.value) { - - } - @if (metadataForm.get(field.lockedKey)?.value) { - - } -
- - +
+
+ +
+
+ Current +
+ + +
-
-
-
- - -
- -
- -
- @if (!metadataForm.get(field.lockedKey)?.value) { - - } - @if (metadataForm.get(field.lockedKey)?.value) { - - } -
- - -
- -
- - + + + +
+ Fetched +
+ +
- } +
- @for (field of metadataDescription; track field) { -
- -
- -
- @if (!metadataForm.get(field.lockedKey)?.value) { - - } - @if (metadataForm.get(field.lockedKey)?.value) { - - } - -
-
- - -
- -
- @if (!metadataForm.get(field.lockedKey)?.value) { - - } - @if (metadataForm.get(field.lockedKey)?.value) { - - } - - - -
-
+ +
+
+ + Basic Information
- } - @for (field of metadataFieldsBottom; track field) { -
- -
- -
- @if (!metadataForm.get(field.lockedKey)?.value) { - - } - @if (metadataForm.get(field.lockedKey)?.value) { - - } - +
+ @for (field of metadataFieldsTop; track field) { +
+ +
+
+ + @if (field.controlName === 'publishedDate') { + + } @else { + + } +
+ + + +
+ +
+
-
- - -
- -
- @if (!metadataForm.get(field.lockedKey)?.value) { - - } - @if (metadataForm.get(field.lockedKey)?.value) { - - } - - - -
-
+ }
- } +
- + +
+
+ + Tags & Categories +
+ +
+ @for (field of metadataChips; track field) { +
+ +
+
+ + +
+ + + +
+ +
+
+
+ } +
+
+ + +
+
+ + Description +
+ +
+ @for (field of metadataDescription; track field) { +
+ +
+
+ + +
+ + + +
+ +
+
+
+ } +
+
+ + + @if (metadataFieldsBottom.length > 0) { +
+
+ + Additional Details +
+ +
+ @for (field of metadataFieldsBottom; track field) { +
+ +
+
+ + +
+ + + +
+ +
+
+
+ } +
+
+ }
- @if (!reviewMode) { - - -
- - - @if (showFilePath) { - {{ book?.filePath }} + @if (hasDigitalFile(book)) { + }
+ + @if (hasDigitalFile(book)) { +
+ + + @if (showFilePath) { + {{ book?.primaryFile?.filePath }} + } +
+ }
@if (userService.userState$ | async; as userState) { @@ -554,34 +566,31 @@
} - @if (book!.bookType === 'PDF') { - @if (pdfReadMenuItems$ | async; as readItems) { - - } - } - @if (book!.bookType === 'EPUB') { - @if (epubReadMenuItems$ | async; as readItems) { - - } - } - @if (book!.bookType !== 'PDF' && book!.bookType !== 'EPUB') { - - } - - - @if (userState.user!.permissions.canDownload || userState.user!.permissions.admin) { - @if ((book!.alternativeFormats && book!.alternativeFormats.length > 0) || (book!.supplementaryFiles && book!.supplementaryFiles.length > 0)) { - @if (downloadMenuItems$ | async; as downloadItems) { - + @if (hasDigitalFile(book)) { + @if (readMenuItems$ | async; as readItems) { + @if (readItems.length > 0) { + + } @else { + } } @else { - + + } + + } + @if ((userState.user!.permissions.canDownload || userState.user!.permissions.admin) && hasAnyFiles(book)) { + @if ((book!.alternativeFormats && book!.alternativeFormats.length > 0) || (book!.supplementaryFiles && book!.supplementaryFiles.length > 0)) { + @if (downloadMenuItems$ | async; as downloadItems) { + + } + } @else { + } } @if (userState.user!.permissions.canEditMetadata || userState.user!.permissions.admin) { @if (refreshMenuItems$ | async; as refreshItems) { 0) { - + } } @@ -625,76 +634,17 @@ }
- - - @if (bookInSeries.length > 1) { - - More in Series - - } - - Similar Books - - - Notes - - - Reading Sessions - - - Reviews - - - - - -
- @if (bookInSeries.length > 1) { -
- @for (bookInSeriesItem of bookInSeries; track bookInSeriesItem) { - @if (bookInSeriesItem.id !== book.id) { -
- -
- } - } -
- } -
-
-
- - -
- @if (recommendedBooks.length > 0) { -
- @for (book of recommendedBooks; track book.book.id) { -
- -
- } -
- } -
-
-
- - - - - - - - - - - - - - - -
-
+ +
} @else {
diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.scss b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.scss index fe956dc6b..03c6b26b9 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.scss +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.scss @@ -413,6 +413,10 @@ gap: 0.375rem; } +.format-tags { + flex-wrap: wrap; +} + .metadata-link { color: var(--primary-text-color); cursor: pointer; @@ -504,6 +508,17 @@ min-width: auto !important; padding: 10px !important; } + + ::ng-deep .read-button-responsive .p-button-label, + ::ng-deep .read-button-responsive.p-splitbutton .p-button-label { + font-size: 0 !important; + } + + ::ng-deep .read-button-responsive .p-button-label::after, + ::ng-deep .read-button-responsive.p-splitbutton .p-button-label::after { + content: "Read"; + font-size: 0.875rem; + } } .navigation-buttons-desktop { @@ -586,76 +601,6 @@ font-size: 0.875rem !important; } -.custom-p-tabs ::ng-deep .p-tabpanels { - padding: 0.5rem 0 0 0 !important; -} - -.tab-content { - padding: 0.5rem 0; -} - -.dashboard-scroller-infinite { - display: flex; - overflow-x: auto; - overflow-y: hidden; - scroll-snap-type: x mandatory; - padding: 0.5rem; - gap: 1rem; - width: 100%; - scrollbar-width: thin; - scrollbar-color: var(--border-color) transparent; -} - -.dashboard-scroller-infinite::-webkit-scrollbar { - height: 8px; -} - -.dashboard-scroller-infinite::-webkit-scrollbar-track { - background: transparent; -} - -.dashboard-scroller-infinite::-webkit-scrollbar-thumb { - background: var(--border-color); - border-radius: 4px; -} - -.dashboard-scroller-infinite::-webkit-scrollbar-thumb:hover { - background: var(--text-secondary-color); -} - -.dashboard-scroller-card { - width: 115px; - flex-basis: 115px; - flex-shrink: 0; - flex-grow: 0; - scroll-snap-align: start; - transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); - position: relative; - border-radius: 0.5rem; -} - -.dashboard-scroller-card:hover { - transform: translateY(-6px); -} - -.dashboard-scroller-card:hover::after { - opacity: 1; -} - -.dashboard-scroller-card::after { - content: ''; - position: absolute; - bottom: -4px; - left: 10%; - right: 10%; - height: 4px; - background: linear-gradient(90deg, transparent, var(--primary-color), transparent); - border-radius: 50%; - opacity: 0; - transition: opacity 0.3s ease; - filter: blur(4px); -} - .loading-state { display: flex; flex-direction: column; diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts index 7a78da7d8..a22de61a6 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts @@ -1,11 +1,11 @@ import {Component, DestroyRef, inject, Input, OnChanges, OnInit, SimpleChanges, ViewChild} from '@angular/core'; import {Button} from 'primeng/button'; -import {AsyncPipe, DecimalPipe, NgClass, UpperCasePipe} from '@angular/common'; -import {Observable} from 'rxjs'; +import {AsyncPipe, DecimalPipe, NgClass} from '@angular/common'; +import {combineLatest, Observable} from 'rxjs'; import {BookService} from '../../../../book/service/book.service'; import {Rating, RatingRateEvent} from 'primeng/rating'; import {FormsModule} from '@angular/forms'; -import {Book, BookMetadata, BookRecommendation, FileInfo, ReadStatus} from '../../../../book/model/book.model'; +import {Book, BookFile, BookMetadata, BookRecommendation, BookType, FileInfo, ReadStatus} from '../../../../book/model/book.model'; import {UrlHelperService} from '../../../../../shared/service/url-helper.service'; import {UserService} from '../../../../settings/user-management/user.service'; import {SplitButton} from 'primeng/splitbutton'; @@ -20,36 +20,28 @@ import {MetadataRefreshType} from '../../../model/request/metadata-refresh-type. import {Router} from '@angular/router'; import {filter, map, switchMap, take, tap} from 'rxjs/operators'; import {Menu} from 'primeng/menu'; -import {InfiniteScrollDirective} from 'ngx-infinite-scroll'; -import {BookCardLiteComponent} from '../../../../book/components/book-card-lite/book-card-lite-component'; import {ResetProgressType, ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type'; import {DatePicker} from 'primeng/datepicker'; -import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs'; -import {BookReviewsComponent} from '../../../../book/components/book-reviews/book-reviews.component'; import {ProgressSpinner} from 'primeng/progressspinner'; import {TieredMenu} from 'primeng/tieredmenu'; import {Image} from 'primeng/image'; import {BookDialogHelperService} from '../../../../book/components/book-browser/book-dialog-helper.service'; import {TagColor, TagComponent} from '../../../../../shared/components/tag/tag.component'; -import {BookNotesComponent} from '../../../../book/components/book-notes/book-notes-component'; import {TaskHelperService} from '../../../../settings/task-management/task-helper.service'; -import { - fileSizeRanges, - matchScoreRanges, - pageCountRanges -} from '../../../../book/components/book-browser/book-filter/book-filter.component'; +import {fileSizeRanges, matchScoreRanges, pageCountRanges} from '../../../../book/components/book-browser/book-filter/book-filter.component'; import {BookNavigationService} from '../../../../book/service/book-navigation.service'; import {Divider} from 'primeng/divider'; import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host.service'; -import { BookReadingSessionsComponent } from '../book-reading-sessions/book-reading-sessions.component'; import {AppSettingsService} from '../../../../../shared/service/app-settings.service'; +import {DeleteBookFileEvent, DeleteSupplementaryFileEvent, DownloadAdditionalFileEvent, DownloadAllFilesEvent, DownloadEvent, MetadataTabsComponent, ReadEvent} from './metadata-tabs/metadata-tabs.component'; + @Component({ selector: 'app-metadata-viewer', standalone: true, templateUrl: './metadata-viewer.component.html', styleUrl: './metadata-viewer.component.scss', - imports: [Button, AsyncPipe, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, Editor, ProgressBar, Menu, InfiniteScrollDirective, BookCardLiteComponent, DatePicker, Tab, TabList, TabPanel, TabPanels, Tabs, BookReviewsComponent, BookNotesComponent, ProgressSpinner, TieredMenu, Image, TagComponent, UpperCasePipe, Divider, BookReadingSessionsComponent] + imports: [Button, AsyncPipe, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, Editor, ProgressBar, Menu, DatePicker, ProgressSpinner, TieredMenu, Image, TagComponent, Divider, MetadataTabsComponent] }) export class MetadataViewerComponent implements OnInit, OnChanges { @Input() book$!: Observable; @@ -70,8 +62,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges { private destroyRef = inject(DestroyRef); private dialogRef?: DynamicDialogRef; - pdfReadMenuItems$!: Observable; - epubReadMenuItems$!: Observable; + readMenuItems$!: Observable; refreshMenuItems$!: Observable; otherItems$!: Observable; downloadMenuItems$!: Observable; @@ -117,24 +108,72 @@ export class MetadataViewerComponent implements OnInit, OnChanges { ]) ); - this.pdfReadMenuItems$ = this.book$.pipe( + this.readMenuItems$ = this.book$.pipe( filter((book): book is Book => book !== null), - map((book): MenuItem[] => [ - { - label: 'Streaming Reader', - command: () => this.read(book.id, 'pdf-streaming') - } - ]) - ); + map((book): MenuItem[] => { + const items: MenuItem[] = []; + const primaryType = book.primaryFile?.bookType; - this.epubReadMenuItems$ = this.book$.pipe( - filter((book): book is Book => book !== null), - map((book): MenuItem[] => [ - { - label: 'Streaming Reader (Beta)', - command: () => this.read(book.id, 'epub-streaming') + // Add streaming reader option for primary file + if (primaryType === 'PDF') { + items.push({ + label: 'Streaming Reader', + icon: 'pi pi-play', + command: () => this.read(book.id, 'pdf-streaming') + }); + } else if (primaryType === 'EPUB') { + items.push({ + label: 'Streaming Reader', + icon: 'pi pi-play', + command: () => this.read(book.id, 'epub-streaming') + }); } - ]) + + // Get readable alternative formats and group by type + const readableAlternatives = book.alternativeFormats?.filter(f => + f.bookType && ['PDF', 'EPUB', 'FB2', 'MOBI', 'AZW3', 'CBX', 'AUDIOBOOK'].includes(f.bookType) + ) ?? []; + + // Get unique format types from alternatives + const uniqueAltTypes = [...new Set(readableAlternatives.map(f => f.bookType))]; + + if (uniqueAltTypes.length > 0) { + if (items.length > 0) { + items.push({separator: true}); + } + + uniqueAltTypes.forEach(formatType => { + if (formatType === 'PDF' || formatType === 'EPUB') { + // For PDF/EPUB, offer both standard and streaming readers + items.push({ + label: formatType, + icon: this.getFileIcon(formatType), + items: [ + { + label: 'Standard Reader', + icon: 'pi pi-book', + command: () => this.read(book.id, undefined, formatType) + }, + { + label: 'Streaming Reader', + icon: 'pi pi-play', + command: () => this.read(book.id, formatType === 'PDF' ? 'pdf-streaming' : 'epub-streaming', formatType) + } + ] + }); + } else { + // For other formats, just show the type + items.push({ + label: formatType, + icon: this.getFileIcon(formatType ?? null), + command: () => this.read(book.id, undefined, formatType) + }); + } + }); + } + + return items; + }) ); this.downloadMenuItems$ = this.book$.pipe( @@ -144,13 +183,12 @@ export class MetadataViewerComponent implements OnInit, OnChanges { map((book): MenuItem[] => { const items: MenuItem[] = []; - // Add alternative formats + // Add alternative formats with type and size if (book.alternativeFormats && book.alternativeFormats.length > 0) { book.alternativeFormats.forEach(format => { - const extension = this.getFileExtension(format.filePath); items.push({ - label: `${format.fileName} (${this.getFileSizeInMB(format)})`, - icon: this.getFileIcon(extension), + label: `${format.bookType ?? 'File'} · ${this.formatFileSize(format)}`, + icon: this.getFileIcon(format.bookType ?? null), command: () => this.downloadAdditionalFile(book, format.id) }); }); @@ -167,8 +205,9 @@ export class MetadataViewerComponent implements OnInit, OnChanges { book.supplementaryFiles.forEach(file => { const extension = this.getFileExtension(file.filePath); items.push({ - label: `${file.fileName} (${this.getFileSizeInMB(file)})`, + label: `${this.truncateFileName(file.fileName, 20)} · ${this.formatFileSize(file)}`, icon: this.getFileIcon(extension), + tooltipOptions: {tooltipLabel: file.fileName, tooltipPosition: 'left'}, command: () => this.downloadAdditionalFile(book, file.id) }); }); @@ -181,11 +220,19 @@ export class MetadataViewerComponent implements OnInit, OnChanges { this.otherItems$ = this.book$.pipe( filter((book): book is Book => book !== null), switchMap(book => - this.userService.userState$.pipe( - take(1), - map(userState => { + combineLatest([ + this.userService.userState$.pipe(take(1)), + this.appSettingsService.appSettings$.pipe(take(1)) + ]).pipe( + map(([userState, appSettings]) => { const items: MenuItem[] = []; + items.push({ + label: 'Shelf', + icon: 'pi pi-folder', + command: () => this.assignShelf(book.id) + }); + // Add allowed submenus based on user permissions if (userState?.user?.permissions.canUpload || userState?.user?.permissions.admin) { @@ -198,7 +245,9 @@ export class MetadataViewerComponent implements OnInit, OnChanges { }); } - if (userState?.user?.permissions.canManageLibrary || userState?.user?.permissions.admin) { + const hasFiles = this.hasAnyFiles(book); + + if (hasFiles && (userState?.user?.permissions.canManageLibrary || userState?.user?.permissions.admin) && appSettings?.diskType === 'LOCAL') { items.push({ label: 'Organize Files', icon: 'pi pi-arrows-h', @@ -208,7 +257,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges { }); } - if (userState?.user?.permissions.canEmailBook || userState?.user?.permissions.admin) { + if (hasFiles && (userState?.user?.permissions.canEmailBook || userState?.user?.permissions.admin)) { items.push({ label: 'Send Book', icon: 'pi pi-send', @@ -229,18 +278,113 @@ export class MetadataViewerComponent implements OnInit, OnChanges { }); } - if (userState?.user?.permissions.canDeleteBook || userState?.user?.permissions.admin) { + // Show "Attach to Another Book" for single-file books (detached books) - not for physical books + const isSingleFileBook = hasFiles && !book.alternativeFormats?.length; + if (isSingleFileBook && (userState?.user?.permissions.canManageLibrary || userState?.user?.permissions.admin)) { items.push({ - label: 'Delete Book', + label: 'Attach to Another Book', + icon: 'pi pi-link', + command: () => { + this.bookDialogHelperService.openBookFileAttacherDialog(book); + }, + }); + } + + if (userState?.user?.permissions.canDeleteBook || userState?.user?.permissions.admin) { + // Delete File Formats submenu - allows deleting individual book format files + const deleteFormatItems: MenuItem[] = []; + const hasMultipleFormats = (book.alternativeFormats?.length ?? 0) > 0; + + // Add primary file if it exists + if (book.primaryFile) { + const extension = this.getFileExtension(book.primaryFile.filePath); + const isPrimaryOnly = !hasMultipleFormats; + const truncatedName = this.truncateFileName(book.primaryFile.fileName, 25); + deleteFormatItems.push({ + label: `${truncatedName} (${this.formatFileSize(book.primaryFile)}) [Primary]`, + icon: this.getFileIcon(extension), + tooltipOptions: {tooltipLabel: book.primaryFile.fileName, tooltipPosition: 'left'}, + command: () => this.deleteBookFile(book, book.primaryFile!.id, book.primaryFile!.fileName || 'file', true, isPrimaryOnly) + }); + } + + // Add alternative formats + if (book.alternativeFormats && book.alternativeFormats.length > 0) { + book.alternativeFormats.forEach(format => { + const extension = this.getFileExtension(format.filePath); + const truncatedName = this.truncateFileName(format.fileName, 25); + deleteFormatItems.push({ + label: `${truncatedName} (${this.formatFileSize(format)})`, + icon: this.getFileIcon(extension), + tooltipOptions: {tooltipLabel: format.fileName, tooltipPosition: 'left'}, + command: () => this.deleteBookFile(book, format.id, format.fileName || 'file', false, false) + }); + }); + } + + if (deleteFormatItems.length > 0) { + items.push({ + label: 'Delete File Formats', + icon: 'pi pi-file', + items: deleteFormatItems + }); + } + + // Delete Supplementary Files submenu - for non-book files + if (book.supplementaryFiles && book.supplementaryFiles.length > 0) { + const deleteSupplementaryItems: MenuItem[] = []; + book.supplementaryFiles.forEach(file => { + const extension = this.getFileExtension(file.filePath); + const truncatedName = this.truncateFileName(file.fileName, 25); + deleteSupplementaryItems.push({ + label: `${truncatedName} (${this.formatFileSize(file)})`, + icon: this.getFileIcon(extension), + tooltipOptions: {tooltipLabel: file.fileName, tooltipPosition: 'left'}, + command: () => this.deleteAdditionalFile(book.id, file.id, file.fileName || 'file') + }); + }); + + items.push({ + label: 'Delete Supplementary Files', + icon: 'pi pi-paperclip', + items: deleteSupplementaryItems + }); + } + + // Delete Book & All Files - deletes the entire book entity + const allFormats: string[] = []; + if (book.primaryFile?.fileName) { + allFormats.push(book.primaryFile.fileName); + } + book.alternativeFormats?.forEach(f => { + if (f.fileName) allFormats.push(f.fileName); + }); + book.supplementaryFiles?.forEach(f => { + if (f.fileName) allFormats.push(f.fileName); + }); + + const isPhysical = !hasFiles; + const fileListMessage = allFormats.length > 0 + ? `\n\nThe following files will be permanently deleted:\n• ${allFormats.join('\n• ')}` + : ''; + + const deleteLabel = isPhysical ? 'Delete Book' : 'Delete Book & All Files'; + const deleteMessage = isPhysical + ? `Are you sure you want to delete "${book.metadata?.title}"?\n\nThis will permanently remove the book record from your library.\n\nThis action cannot be undone.` + : `Are you sure you want to delete "${book.metadata?.title}"?\n\nThis will permanently remove the book record AND all associated files from your filesystem.${fileListMessage}\n\nThis action cannot be undone.`; + const deleteAcceptLabel = isPhysical ? 'Delete' : 'Delete Everything'; + + items.push({ + label: deleteLabel, icon: 'pi pi-trash', command: () => { this.confirmationService.confirm({ - message: `Are you sure you want to delete "${book.metadata?.title}"?\n\nThis will permanently remove the book file from your filesystem.\n\nThis action cannot be undone.`, - header: 'Confirm Deletion', + message: deleteMessage, + header: deleteLabel, icon: 'pi pi-exclamation-triangle', acceptIcon: 'pi pi-trash', rejectIcon: 'pi pi-times', - acceptLabel: 'Delete', + acceptLabel: deleteAcceptLabel, rejectLabel: 'Cancel', acceptButtonStyleClass: 'p-button-danger', rejectButtonStyleClass: 'p-button-outlined', @@ -260,48 +404,6 @@ export class MetadataViewerComponent implements OnInit, OnChanges { }); }, }); - - // Add delete additional files menu if there are any additional files - if ((book.alternativeFormats && book.alternativeFormats.length > 0) || - (book.supplementaryFiles && book.supplementaryFiles.length > 0)) { - const deleteFileItems: MenuItem[] = []; - - // Add alternative formats - if (book.alternativeFormats && book.alternativeFormats.length > 0) { - book.alternativeFormats.forEach(format => { - const extension = this.getFileExtension(format.filePath); - deleteFileItems.push({ - label: `${format.fileName} (${this.getFileSizeInMB(format)})`, - icon: this.getFileIcon(extension), - command: () => this.deleteAdditionalFile(book.id, format.id, format.fileName || 'file') - }); - }); - } - - // Add separator if both types exist - if (book.alternativeFormats && book.alternativeFormats.length > 0 && - book.supplementaryFiles && book.supplementaryFiles.length > 0) { - deleteFileItems.push({separator: true}); - } - - // Add supplementary files - if (book.supplementaryFiles && book.supplementaryFiles.length > 0) { - book.supplementaryFiles.forEach(file => { - const extension = this.getFileExtension(file.filePath); - deleteFileItems.push({ - label: `${file.fileName} (${this.getFileSizeInMB(file)})`, - icon: this.getFileIcon(extension), - command: () => this.deleteAdditionalFile(book.id, file.id, file.fileName || 'file') - }); - }); - } - - items.push({ - label: 'Delete Additional Files', - icon: 'pi pi-trash', - items: deleteFileItems - }); - } } return items; @@ -375,16 +477,29 @@ export class MetadataViewerComponent implements OnInit, OnChanges { ); } - get defaultTabValue(): number { - return this.bookInSeries && this.bookInSeries.length > 1 ? 1 : 2; - } - toggleExpand(): void { this.isExpanded = !this.isExpanded; } - read(bookId: number | undefined, reader?: "pdf-streaming" | "epub-streaming"): void { - if (bookId) this.bookService.readBook(bookId, reader); + read(bookId: number | undefined, reader?: "pdf-streaming" | "epub-streaming", bookType?: BookType): void { + if (bookId) this.bookService.readBook(bookId, reader, bookType); + } + + isInProgressStatus(): boolean { + return [ReadStatus.READING, ReadStatus.PAUSED, ReadStatus.RE_READING].includes(this.selectedReadStatus); + } + + getReadButtonLabel(book: Book): string { + const isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK'; + if (this.isInProgressStatus()) { + return isAudiobook ? 'Continue' : 'Continue Reading'; + } + return isAudiobook ? 'Play' : 'Read'; + } + + getReadButtonIcon(book: Book): string { + const isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK'; + return (isAudiobook || this.isInProgressStatus()) ? 'pi pi-play' : 'pi pi-book'; } download(book: Book) { @@ -395,13 +510,39 @@ export class MetadataViewerComponent implements OnInit, OnChanges { this.bookService.downloadAdditionalFile(book, fileId); } + // Event handlers for MetadataTabsComponent + onReadBook(event: ReadEvent): void { + this.read(event.bookId, event.reader, event.bookType); + } + + onDownloadBook(event: DownloadEvent): void { + this.download(event.book); + } + + onDownloadFile(event: DownloadAdditionalFileEvent): void { + this.downloadAdditionalFile(event.book, event.fileId); + } + + onDownloadAllFiles(event: DownloadAllFilesEvent): void { + this.bookService.downloadAllFiles(event.book); + } + + onDeleteBookFile(event: DeleteBookFileEvent): void { + this.deleteBookFile(event.book, event.fileId, event.fileName, event.isPrimary, event.isOnlyFormat); + } + + onDeleteSupplementaryFile(event: DeleteSupplementaryFileEvent): void { + this.deleteAdditionalFile(event.bookId, event.fileId, event.fileName); + } + deleteAdditionalFile(bookId: number, fileId: number, fileName: string) { this.confirmationService.confirm({ - message: `Are you sure you want to delete the additional file "${fileName}"?`, - header: 'Confirm File Deletion', + message: `Are you sure you want to delete the supplementary file "${fileName}"?\n\nThis file will be permanently removed from your filesystem.`, + header: 'Delete Supplementary File', icon: 'pi pi-exclamation-triangle', acceptIcon: 'pi pi-trash', rejectIcon: 'pi pi-times', + rejectButtonStyleClass: 'p-button-secondary', acceptButtonStyleClass: 'p-button-danger', accept: () => { this.bookService.deleteAdditionalFile(bookId, fileId).subscribe({ @@ -409,14 +550,63 @@ export class MetadataViewerComponent implements OnInit, OnChanges { this.messageService.add({ severity: 'success', summary: 'Success', - detail: `Additional file "${fileName}" deleted successfully` + detail: `Supplementary file "${fileName}" deleted successfully` }); }, error: (error) => { this.messageService.add({ severity: 'error', summary: 'Error', - detail: `Failed to delete additional file: ${error.message || 'Unknown error'}` + detail: `Failed to delete supplementary file: ${error.message || 'Unknown error'}` + }); + } + }); + } + }); + } + + deleteBookFile(book: Book, fileId: number, fileName: string, isPrimary: boolean, isOnlyFormat: boolean) { + let message: string; + let header: string; + + if (isOnlyFormat) { + // This is the only book format file - warn user strongly + message = `Are you sure you want to delete "${fileName}"?\n\nThis is the ONLY book format file for this book. After deletion, the book will have no readable content.\n\nConsider using "Delete Book & All Files" instead to completely remove the book.\n\nThis file will be permanently removed from your filesystem.`; + header = 'Delete Only Book Format'; + } else if (isPrimary) { + // This is the primary format but there are alternatives + message = `Are you sure you want to delete "${fileName}"?\n\nThis is currently the PRIMARY format for this book. After deletion, an alternative format will become the new primary.\n\nThis file will be permanently removed from your filesystem.`; + header = 'Delete Primary Format'; + } else { + // This is an alternative format + message = `Are you sure you want to delete "${fileName}"?\n\nThis file will be permanently removed from your filesystem.`; + header = 'Delete Book Format'; + } + + this.confirmationService.confirm({ + message, + header, + icon: 'pi pi-exclamation-triangle', + acceptIcon: 'pi pi-trash', + rejectIcon: 'pi pi-times', + acceptLabel: 'Delete File', + rejectLabel: 'Cancel', + rejectButtonStyleClass: 'p-button-secondary', + acceptButtonStyleClass: 'p-button-danger', + accept: () => { + this.bookService.deleteBookFile(book.id, fileId, isPrimary).subscribe({ + next: () => { + this.messageService.add({ + severity: 'success', + summary: 'Success', + detail: `Book format "${fileName}" deleted successfully` + }); + }, + error: (error) => { + this.messageService.add({ + severity: 'error', + summary: 'Error', + detail: `Failed to delete book format: ${error.message || 'Unknown error'}` }); } }); @@ -674,9 +864,42 @@ export class MetadataViewerComponent implements OnInit, OnChanges { return lockedKeys.length > 0 && lockedKeys.every(k => metadata[k] === true); } - getFileSizeInMB(fileInfo: FileInfo | null | undefined): string { + formatFileSize(fileInfo: FileInfo | null | undefined): string { const sizeKb = fileInfo?.fileSizeKb; - return sizeKb != null ? `${(sizeKb / 1024).toFixed(2)} MB` : '-'; + if (sizeKb == null) return '-'; + + const units = ['KB', 'MB', 'GB', 'TB']; + let size = sizeKb; + let unitIndex = 0; + + while (size >= 1024 && unitIndex < units.length - 1) { + size /= 1024; + unitIndex++; + } + + const decimals = size >= 100 ? 0 : size >= 10 ? 1 : 2; + return `${size.toFixed(decimals)} ${units[unitIndex]}`; + } + + truncateFileName(fileName: string | undefined, maxLength: number = 30): string { + if (!fileName) return ''; + if (fileName.length <= maxLength) return fileName; + + const lastDotIndex = fileName.lastIndexOf('.'); + if (lastDotIndex === -1) { + // No extension - just truncate + return fileName.substring(0, maxLength - 3) + '...'; + } + + const extension = fileName.substring(lastDotIndex); + const nameWithoutExt = fileName.substring(0, lastDotIndex); + const availableLength = maxLength - extension.length - 3; // 3 for "..." + + if (availableLength <= 0) { + return '...' + extension; + } + + return nameWithoutExt.substring(0, availableLength) + '...' + extension; } getProgressPercent(book: Book): number | null { @@ -689,6 +912,9 @@ export class MetadataViewerComponent implements OnInit, OnChanges { if (book.cbxProgress?.percentage != null) { return book.cbxProgress.percentage; } + if (book.audiobookProgress?.percentage != null) { + return book.audiobookProgress.percentage; + } return null; } @@ -721,6 +947,38 @@ export class MetadataViewerComponent implements OnInit, OnChanges { return parts.pop()?.toUpperCase() || null; } + getUniqueAlternativeFormatTypes(book: Book): BookType[] { + if (!book.alternativeFormats?.length) return []; + const primaryType = book.primaryFile?.bookType; + const uniqueTypes = new Set(); + for (const format of book.alternativeFormats) { + if (format.bookType && format.bookType !== primaryType) { + uniqueTypes.add(format.bookType); + } + } + return [...uniqueTypes]; + } + + getDisplayFormat(bookFile?: BookFile | null): string | null { + if (bookFile?.extension) { + return bookFile.extension.toUpperCase(); + } + return this.getFileExtension(bookFile?.filePath); + } + + getUniqueAlternativeFormats(book: Book): string[] { + if (!book.alternativeFormats?.length) return []; + const primaryFormat = this.getDisplayFormat(book.primaryFile); + const uniqueFormats = new Set(); + for (const format of book.alternativeFormats) { + const formatType = this.getDisplayFormat(format); + if (formatType && formatType !== primaryFormat) { + uniqueFormats.add(formatType); + } + } + return [...uniqueFormats]; + } + getFileIcon(fileType: string | null): string { if (!fileType) return 'pi pi-file'; switch (fileType.toLowerCase()) { @@ -734,6 +992,11 @@ export class MetadataViewerComponent implements OnInit, OnChanges { case 'cbr': case 'cbx': return 'pi pi-image'; + case 'audiobook': + case 'm4b': + case 'm4a': + case 'mp3': + return 'pi pi-headphones'; default: return 'pi pi-file'; } @@ -956,4 +1219,16 @@ export class MetadataViewerComponent implements OnInit, OnChanges { const position = this.bookNavigationService.getCurrentPosition(); return position ? `${position.current} of ${position.total}` : ''; } + + hasDigitalFile(book: Book): boolean { + return !!book?.primaryFile; + } + + hasAnyFiles(book: Book): boolean { + return !!book?.primaryFile || (book?.alternativeFormats?.length ?? 0) > 0; + } + + isPhysicalBook(book: Book): boolean { + return !this.hasAnyFiles(book); + } } diff --git a/booklore-ui/src/app/features/metadata/component/cover-search/cover-search.component.ts b/booklore-ui/src/app/features/metadata/component/cover-search/cover-search.component.ts index d71fc44d3..25fda8437 100644 --- a/booklore-ui/src/app/features/metadata/component/cover-search/cover-search.component.ts +++ b/booklore-ui/src/app/features/metadata/component/cover-search/cover-search.component.ts @@ -1,5 +1,4 @@ import {Component, inject, Input, OnInit} from '@angular/core'; -import {Toast} from 'primeng/toast'; import {MessageService} from 'primeng/api'; import {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators} from '@angular/forms'; import {BookCoverService, CoverFetchRequest, CoverImage} from '../../../../shared/services/book-cover.service'; @@ -32,6 +31,7 @@ export class CoverSearchComponent implements OnInit { coverImages: CoverImage[] = []; loading = false; hasSearched = false; + isAudiobook = false; private fb = inject(FormBuilder); private bookCoverService = inject(BookCoverService); @@ -52,6 +52,7 @@ export class CoverSearchComponent implements OnInit { const book = this.bookService.getBookByIdFromState(this.bookId); if (book) { + this.isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK'; this.searchForm.patchValue({ title: book.metadata?.title || '', author: book.metadata?.authors && book.metadata?.authors.length > 0 ? book.metadata?.authors[0] : '' @@ -68,7 +69,8 @@ export class CoverSearchComponent implements OnInit { this.loading = true; const request: CoverFetchRequest = { title: this.searchForm.value.title, - author: this.searchForm.value.author + author: this.searchForm.value.author, + squareCover: this.isAudiobook }; this.bookCoverService.fetchBookCovers(request) diff --git a/booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.html b/booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.html new file mode 100644 index 000000000..28d253237 --- /dev/null +++ b/booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.html @@ -0,0 +1,399 @@ +@if (isLoading) { +
+ + Loading audiobook... +
+} @else { +
+ + + + +
+ +
+

{{ audiobookInfo.title || 'Untitled' }}

+ {{ audiobookInfo.author || 'Unknown Author' }} +
+
+ + +
+
+ + +
+ +
+
+ @if (coverUrl) { + Cover + } @else { +
+ +
+ } + @if (audioLoading) { +
+ +
+ } +
+
+ + +
+ @if (audiobookInfo.folderBased && currentTrack) { + {{ currentTrack.title }} + Track {{ currentTrackIndex + 1 }} of {{ audiobookInfo.tracks?.length }} + } @else if (getCurrentChapter()) { + {{ getCurrentChapter()?.title }} + @if (hasMultipleChapters()) { + Chapter {{ getCurrentChapterIndex() + 1 }} of {{ audiobookInfo.chapters?.length }} + } + } +
+ + +
+
+ {{ formatTime(currentTime) }} + {{ formatTime(duration) }} +
+
+
+ +
+
+ + +
+ @if (audiobookInfo.folderBased) { + + } @else if (hasMultipleChapters()) { + + } + + + + + + + + @if (audiobookInfo.folderBased) { + + } @else if (hasMultipleChapters()) { + + } +
+ + +
+ +
+ + +
+ + +
+ +
+
+ + +
+ + + + + + +
+ + +
+ @if (audiobookInfo.narrator) { + + + Narrated by {{ audiobookInfo.narrator }} + + } + @if (audiobookInfo.bitrate) { + + + {{ audiobookInfo.bitrate }} kbps + + } + @if (audiobookInfo.durationMs) { + + + {{ formatDuration(audiobookInfo.durationMs) }} total + + } +
+
+ + + @if (showTrackList) { + + } + + + @if (showBookmarkList) { + + } +
+} diff --git a/booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.scss b/booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.scss new file mode 100644 index 000000000..5e2e8574d --- /dev/null +++ b/booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.scss @@ -0,0 +1,805 @@ +@use 'sass:color'; + +// Variables - More vibrant color palette +$bg-primary: #0f0f1a; +$bg-secondary: #1a1a2e; +$bg-tertiary: #252542; +$bg-darker: #0a0a12; +$text-primary: #ffffff; +$text-secondary: rgba(255, 255, 255, 0.8); +$text-tertiary: rgba(255, 255, 255, 0.5); +$accent-secondary: #ec4899; +$accent-tertiary: #06b6d4; +$border-color: rgba(255, 255, 255, 0.1); + +// CSS variable for primary color from theme +:host { + --accent-color: var(--primary-color, #8b5cf6); + --accent-hover: var(--primary-hover-color, #a78bfa); +} + +// Gradient mixins +@mixin gradient-bg { + background: linear-gradient(135deg, $bg-secondary 0%, $bg-primary 50%, $bg-darker 100%); +} + +@mixin accent-gradient { + background: linear-gradient(135deg, var(--accent-color) 0%, $accent-secondary 100%); +} + +@mixin glow-effect($color, $intensity: 0.4) { + box-shadow: 0 0 40px rgba($color, $intensity), + 0 0 80px rgba($color, $intensity * 0.5); +} + +// Loading container +.loading-container { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + height: 100vh; + @include gradient-bg; + gap: 1rem; + + .loading-text { + color: $text-secondary; + font-size: 0.9rem; + } + + ::ng-deep .p-progress-spinner-circle { + stroke: var(--accent-color) !important; + } +} + +// Main container +.audiobook-reader { + display: flex; + flex-direction: column; + height: 100vh; + @include gradient-bg; + color: $text-primary; + overflow: hidden; + position: relative; + + // Subtle animated gradient overlay + &::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: radial-gradient(ellipse at 20% 0%, color-mix(in srgb, var(--accent-color) 15%, transparent) 0%, transparent 50%), + radial-gradient(ellipse at 80% 100%, rgba($accent-secondary, 0.1) 0%, transparent 50%); + pointer-events: none; + z-index: 0; + } +} + +// Header +.reader-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 1rem 1.5rem; + background: rgba(0, 0, 0, 0.4); + backdrop-filter: blur(20px); + border-bottom: 1px solid $border-color; + z-index: 10; + position: relative; + + .header-info { + flex: 1; + text-align: center; + padding: 0 1rem; + overflow: hidden; + + .book-title { + font-size: 1.1rem; + font-weight: 600; + margin: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + background: linear-gradient(90deg, $text-primary, var(--accent-color)); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + background-clip: text; + } + + .book-author { + font-size: 0.85rem; + color: $text-secondary; + } + } + + .header-actions { + display: flex; + gap: 0.25rem; + } + + ::ng-deep .p-button { + &.p-button-text { + color: $text-secondary; + + &:hover { + color: $text-primary; + background: color-mix(in srgb, var(--accent-color) 20%, transparent); + } + } + } +} + +// Main content +.reader-main { + flex: 1; + display: flex; + flex-direction: column; + align-items: center; + padding: 2rem 1.5rem; + overflow-y: auto; + gap: 1.5rem; + position: relative; + z-index: 1; +} + +// Cover art +.cover-container { + flex-shrink: 0; + width: 100%; + max-width: 480px; + aspect-ratio: 1; + margin-top: 1.5rem; + + .cover-wrapper { + position: relative; + width: 100%; + height: 100%; + border-radius: 16px; + overflow: hidden; + box-shadow: + 0 25px 60px -12px rgba(0, 0, 0, 0.6), + 0 0 0 1px rgba(255, 255, 255, 0.1), + 0 0 60px color-mix(in srgb, var(--accent-color) 20%, transparent), + 0 0 100px rgba($accent-secondary, 0.1); + transition: transform 0.3s ease, box-shadow 0.3s ease; + + &:hover { + transform: scale(1.02); + box-shadow: + 0 30px 70px -12px rgba(0, 0, 0, 0.7), + 0 0 0 1px rgba(255, 255, 255, 0.15), + 0 0 80px color-mix(in srgb, var(--accent-color) 30%, transparent), + 0 0 120px rgba($accent-secondary, 0.15); + } + + .cover-image { + width: 100%; + height: 100%; + object-fit: cover; + } + + .cover-loading { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + background: rgba(0, 0, 0, 0.7); + backdrop-filter: blur(4px); + } + + .cover-placeholder { + width: 100%; + height: 100%; + display: flex; + align-items: center; + justify-content: center; + @include accent-gradient; + opacity: 0.8; + + i { + font-size: 5rem; + color: rgba(255, 255, 255, 0.9); + text-shadow: 0 0 30px rgba(255, 255, 255, 0.5); + } + } + } +} + +// Track info +.track-info { + text-align: center; + min-height: 3rem; + + .track-title { + display: block; + font-size: 1.1rem; + font-weight: 600; + color: $text-primary; + margin-bottom: 0.25rem; + } + + .track-number { + font-size: 0.85rem; + color: var(--accent-color); + font-weight: 500; + } +} + +// Progress bar +.progress-container { + width: 100%; + max-width: 500px; + + .time-display { + display: flex; + justify-content: space-between; + margin-bottom: 0.75rem; + font-size: 0.85rem; + color: $text-secondary; + font-variant-numeric: tabular-nums; + font-weight: 500; + } + + .progress-bar-wrapper { + position: relative; + height: 8px; + background: rgba(255, 255, 255, 0.1); + border-radius: 4px; + overflow: visible; + + .buffered-bar { + position: absolute; + top: 0; + left: 0; + height: 100%; + background: rgba(255, 255, 255, 0.15); + border-radius: 4px; + transition: width 0.3s ease; + } + + ::ng-deep .progress-slider { + position: absolute; + top: 50%; + left: 0; + right: 0; + transform: translateY(-50%); + + .p-slider { + background: transparent; + height: 8px; + + .p-slider-range { + @include accent-gradient; + border-radius: 4px; + box-shadow: 0 0 10px color-mix(in srgb, var(--accent-color) 50%, transparent); + } + + .p-slider-handle { + width: 18px; + height: 18px; + background: $text-primary; + border: 3px solid var(--accent-color); + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.4), + 0 0 15px color-mix(in srgb, var(--accent-color) 40%, transparent); + transition: transform 0.15s ease, box-shadow 0.15s ease; + + &:hover { + transform: scale(1.2); + box-shadow: 0 2px 15px rgba(0, 0, 0, 0.5), + 0 0 25px color-mix(in srgb, var(--accent-color) 60%, transparent); + } + } + } + } + } +} + +// Playback controls +.playback-controls { + display: flex; + align-items: center; + justify-content: center; + gap: 1rem; + + ::ng-deep .play-button { + .p-button { + width: 72px; + height: 72px; + font-size: 1.75rem; + @include accent-gradient; + border: none; + box-shadow: 0 8px 30px color-mix(in srgb, var(--accent-color) 40%, transparent), + 0 0 50px color-mix(in srgb, var(--accent-color) 20%, transparent); + transition: transform 0.2s ease, box-shadow 0.2s ease; + + &:hover { + transform: scale(1.05); + box-shadow: 0 10px 40px color-mix(in srgb, var(--accent-color) 50%, transparent), + 0 0 70px color-mix(in srgb, var(--accent-color) 30%, transparent); + } + + &:active { + transform: scale(0.98); + } + + .p-button-icon { + font-size: 1.75rem; + } + } + } + + ::ng-deep .p-button { + &.p-button-text { + color: $text-secondary; + transition: all 0.2s ease; + + &:hover { + color: $text-primary; + background: color-mix(in srgb, var(--accent-color) 20%, transparent); + transform: scale(1.1); + } + + &:disabled { + color: $text-tertiary; + opacity: 0.4; + transform: none; + } + } + + &.p-button-lg { + width: 48px; + height: 48px; + } + } +} + +// Secondary controls +.secondary-controls { + display: flex; + align-items: center; + justify-content: center; + gap: 2rem; + width: 100%; + max-width: 500px; + padding: 1rem 0; +} + +.volume-control { + display: flex; + align-items: center; + gap: 0.75rem; + + ::ng-deep .p-button.p-button-text { + color: $text-secondary; + + &:hover { + color: var(--accent-color); + background: color-mix(in srgb, var(--accent-color) 15%, transparent); + } + } + + ::ng-deep .volume-slider { + width: 100px; + + .p-slider { + background: rgba(255, 255, 255, 0.15); + height: 5px; + border-radius: 3px; + + .p-slider-range { + background: $accent-tertiary; + border-radius: 3px; + } + + .p-slider-handle { + width: 14px; + height: 14px; + background: $text-primary; + border: 2px solid $accent-tertiary; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3); + } + } + } +} + +.speed-control { + ::ng-deep .p-selectbutton { + .p-button { + padding: 0.5rem 0.75rem; + font-size: 0.8rem; + font-weight: 600; + background: rgba(255, 255, 255, 0.08); + border: 1px solid rgba(255, 255, 255, 0.1); + color: $text-secondary; + transition: all 0.2s ease; + + &:hover { + background: rgba(255, 255, 255, 0.12); + color: $text-primary; + border-color: rgba(255, 255, 255, 0.2); + } + + &.p-highlight { + @include accent-gradient; + color: $text-primary; + border-color: transparent; + box-shadow: 0 4px 15px color-mix(in srgb, var(--accent-color) 30%, transparent); + } + } + } +} + +// Audio details +.audio-details { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 1.25rem; + padding: 1rem 1rem 0; + color: $text-tertiary; + font-size: 0.8rem; + background: rgba(255, 255, 255, 0.03); + border-radius: 12px; + margin-top: 0.5rem; + + .detail-item { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.5rem 0.75rem; + background: rgba(255, 255, 255, 0.05); + border-radius: 8px; + white-space: nowrap; + + i { + font-size: 0.9rem; + color: $accent-tertiary; + } + } +} + +// Extra controls (bookmark, sleep timer) +.extra-controls { + display: flex; + align-items: center; + justify-content: center; + gap: 1rem; + padding-top: 0.5rem; + + ::ng-deep .p-button { + &.p-button-text { + color: $text-secondary; + font-size: 0.85rem; + + &:hover { + color: $text-primary; + background: color-mix(in srgb, var(--accent-color) 15%, transparent); + } + + .p-button-icon { + font-size: 1rem; + } + } + + &.sleep-timer-active { + color: #fbbf24 !important; + + &:hover { + background: rgba(251, 191, 36, 0.15) !important; + } + } + } +} + +// Empty bookmarks +.empty-bookmarks { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 3rem 1.5rem; + text-align: center; + color: $text-tertiary; + + i { + font-size: 3rem; + margin-bottom: 1rem; + opacity: 0.5; + } + + p { + margin: 0 0 0.5rem; + font-size: 1rem; + font-weight: 500; + color: $text-secondary; + } + + span { + font-size: 0.85rem; + } +} + +// Bookmark item +.bookmark-item { + .bookmark-icon { + color: var(--accent-color); + font-size: 1.1rem; + flex-shrink: 0; + } + + ::ng-deep .p-button { + opacity: 0; + transition: opacity 0.2s ease; + } + + &:hover { + ::ng-deep .p-button { + opacity: 1; + } + } +} + +// Track list sidebar +.track-list-sidebar { + position: fixed; + top: 0; + right: 0; + width: 100%; + max-width: 400px; + height: 100vh; + background: linear-gradient(180deg, $bg-tertiary 0%, $bg-secondary 100%); + border-left: 1px solid color-mix(in srgb, var(--accent-color) 20%, transparent); + z-index: 100; + display: flex; + flex-direction: column; + animation: slideIn 0.25s ease-out; + box-shadow: -10px 0 40px rgba(0, 0, 0, 0.5); + + @keyframes slideIn { + from { + transform: translateX(100%); + opacity: 0.5; + } + to { + transform: translateX(0); + opacity: 1; + } + } + + .sidebar-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 1.25rem 1.5rem; + border-bottom: 1px solid $border-color; + background: rgba(0, 0, 0, 0.2); + + h2 { + margin: 0; + font-size: 1.2rem; + font-weight: 600; + background: linear-gradient(90deg, $text-primary, var(--accent-color)); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + background-clip: text; + } + + ::ng-deep .p-button.p-button-text { + color: $text-secondary; + + &:hover { + color: $text-primary; + background: color-mix(in srgb, var(--accent-color) 20%, transparent); + } + } + } + + .sidebar-content { + flex: 1; + overflow-y: auto; + padding: 0.5rem 0; + + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background: transparent; + } + + &::-webkit-scrollbar-thumb { + background: color-mix(in srgb, var(--accent-color) 30%, transparent); + border-radius: 3px; + + &:hover { + background: color-mix(in srgb, var(--accent-color) 50%, transparent); + } + } + } +} + +.track-list { + list-style: none; + margin: 0; + padding: 0; + + .track-item { + display: flex; + align-items: center; + padding: 1rem 1.5rem; + cursor: pointer; + transition: all 0.2s ease; + gap: 1rem; + border-left: 3px solid transparent; + + &:hover { + background: color-mix(in srgb, var(--accent-color) 10%, transparent); + border-left-color: color-mix(in srgb, var(--accent-color) 50%, transparent); + } + + &.active { + background: linear-gradient(90deg, color-mix(in srgb, var(--accent-color) 20%, transparent) 0%, transparent 100%); + border-left-color: var(--accent-color); + + .track-index { + color: var(--accent-color); + font-weight: 700; + } + + .track-name { + color: var(--accent-color); + } + } + + .track-index { + width: 2rem; + text-align: center; + font-size: 0.9rem; + color: $text-tertiary; + flex-shrink: 0; + font-weight: 600; + } + + .track-details { + flex: 1; + min-width: 0; + + .track-name { + display: block; + font-size: 0.95rem; + color: $text-primary; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-weight: 500; + } + + .track-duration { + font-size: 0.8rem; + color: $text-tertiary; + margin-top: 0.2rem; + } + } + + .playing-indicator { + color: var(--accent-color); + animation: pulse 1.5s ease-in-out infinite; + font-size: 1.1rem; + } + + @keyframes pulse { + 0%, 100% { + opacity: 1; + transform: scale(1); + } + 50% { + opacity: 0.6; + transform: scale(0.95); + } + } + } +} + +// Responsive adjustments +@media (max-width: 768px) { + .reader-main { + padding: 1rem; + gap: 1rem; + } + + .cover-container { + max-width: 360px; + margin-top: 1rem; + } + + .secondary-controls { + flex-direction: column; + gap: 1rem; + } + + .volume-control { + ::ng-deep .volume-slider { + width: 150px; + } + } + + .track-list-sidebar { + max-width: 75%; + } + + .audio-details { + gap: 0.75rem; + padding: 0.75rem; + + .detail-item { + padding: 0.4rem 0.6rem; + font-size: 0.75rem; + + i { + font-size: 0.8rem; + } + } + } +} + +@media (max-width: 480px) { + .cover-container { + max-width: 300px; + margin-top: 0.5rem; + } + + .playback-controls { + gap: 0.5rem; + + ::ng-deep .play-button { + .p-button { + width: 64px; + height: 64px; + } + } + + ::ng-deep .p-button.p-button-lg { + width: 40px; + height: 40px; + } + } + + .audio-details { + flex-direction: row; + flex-wrap: wrap; + justify-content: center; + gap: 0.5rem; + + .detail-item { + flex: 0 1 auto; + } + } +} + +// Landscape mode optimization +@media (max-height: 600px) and (orientation: landscape) { + .reader-main { + flex-direction: row; + flex-wrap: wrap; + justify-content: center; + gap: 1rem; + } + + .cover-container { + max-width: 180px; + } + + .track-info, + .progress-container, + .playback-controls, + .secondary-controls { + width: auto; + } + + .audio-details { + flex-direction: row; + } +} diff --git a/booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.ts b/booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.ts new file mode 100644 index 000000000..2a3c25025 --- /dev/null +++ b/booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.ts @@ -0,0 +1,966 @@ +import { Component, ElementRef, inject, OnDestroy, OnInit, ViewChild } from '@angular/core'; +import { CommonModule, Location } from '@angular/common'; +import { ActivatedRoute, Router } from '@angular/router'; +import { FormsModule } from '@angular/forms'; +import { forkJoin, Subject } from 'rxjs'; +import { takeUntil } from 'rxjs/operators'; + +import { Button } from 'primeng/button'; +import { Slider, SliderChangeEvent } from 'primeng/slider'; +import { ProgressSpinner } from 'primeng/progressspinner'; +import { Tooltip } from 'primeng/tooltip'; +import { MessageService } from 'primeng/api'; +import { SelectButton } from 'primeng/selectbutton'; +import { Menu } from 'primeng/menu'; +import { MenuItem } from 'primeng/api'; + +import { AudiobookService } from './audiobook.service'; +import { AudiobookInfo, AudiobookChapter, AudiobookTrack, AudiobookProgress } from './audiobook.model'; +import { BookService } from '../../book/service/book.service'; +import { BookMarkService, BookMark, CreateBookMarkRequest } from '../../../shared/service/book-mark.service'; +import { AudiobookSessionService } from '../../../shared/service/audiobook-session.service'; +import { PageTitleService } from '../../../shared/service/page-title.service'; +import { AuthService } from '../../../shared/service/auth.service'; +import { API_CONFIG } from '../../../core/config/api-config'; + +@Component({ + selector: 'app-audiobook-reader', + standalone: true, + imports: [ + CommonModule, + FormsModule, + Button, + Slider, + ProgressSpinner, + Tooltip, + SelectButton, + Menu + ], + templateUrl: './audiobook-reader.component.html', + styleUrls: ['./audiobook-reader.component.scss'] +}) +export class AudiobookReaderComponent implements OnInit, OnDestroy { + @ViewChild('audioElement') audioElement!: ElementRef; + + private destroy$ = new Subject(); + private audiobookService = inject(AudiobookService); + private bookService = inject(BookService); + private bookMarkService = inject(BookMarkService); + private authService = inject(AuthService); + private route = inject(ActivatedRoute); + private router = inject(Router); + private location = inject(Location); + private messageService = inject(MessageService); + private audiobookSessionService = inject(AudiobookSessionService); + private pageTitle = inject(PageTitleService); + + // Loading state + isLoading = true; + audioLoading = true; + + // Book data + bookId!: number; + audiobookInfo!: AudiobookInfo; + coverUrl?: string; + bookCoverUrl?: string; + + // Audio state + isPlaying = false; + currentTime = 0; + duration = 0; + volume = 1; + previousVolume = 1; + isMuted = false; + playbackRate = 1; + buffered = 0; + + // Saved position to restore after audio loads + private savedPosition = 0; + + // Track state (for folder-based audiobooks) + currentTrackIndex = 0; + audioSrc = ''; + + // UI state + showTrackList = false; + showBookmarkList = false; + + // Sleep timer + sleepTimerActive = false; + sleepTimerRemaining = 0; // seconds remaining + sleepTimerEndOfChapter = false; + private sleepTimerInterval?: ReturnType; + private originalVolume = 1; + + sleepTimerOptions: MenuItem[] = [ + { label: '15 minutes', command: () => this.setSleepTimer(15) }, + { label: '30 minutes', command: () => this.setSleepTimer(30) }, + { label: '45 minutes', command: () => this.setSleepTimer(45) }, + { label: '60 minutes', command: () => this.setSleepTimer(60) }, + { label: 'End of chapter', command: () => this.setSleepTimerEndOfChapter() }, + { separator: true }, + { label: 'Cancel timer', command: () => this.cancelSleepTimer(), visible: false } + ]; + + // Bookmarks + bookmarks: BookMark[] = []; + + // Playback speed options + playbackRates = [ + { label: '0.5x', value: 0.5 }, + { label: '0.75x', value: 0.75 }, + { label: '1x', value: 1 }, + { label: '1.25x', value: 1.25 }, + { label: '1.5x', value: 1.5 }, + { label: '2x', value: 2 } + ]; + + // Progress save interval + private progressSaveInterval?: ReturnType; + + ngOnInit(): void { + this.route.paramMap.pipe(takeUntil(this.destroy$)).subscribe(params => { + this.bookId = +params.get('bookId')!; + this.loadAudiobook(); + }); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + + if (this.progressSaveInterval) { + clearInterval(this.progressSaveInterval); + } + + if (this.sleepTimerInterval) { + clearInterval(this.sleepTimerInterval); + } + + this.saveProgress(); + + if (this.audiobookSessionService.isSessionActive()) { + this.audiobookSessionService.endSession(Math.round(this.currentTime * 1000)); + } + } + + private loadAudiobook(): void { + // Reset all state when loading a new audiobook + this.resetState(); + this.isLoading = true; + + const audiobookInfo$ = this.audiobookService.getAudiobookInfo(this.bookId); + const book$ = this.bookService.getBookByIdFromAPI(this.bookId, false); + + forkJoin([audiobookInfo$, book$]).subscribe({ + next: ([info, book]) => { + this.audiobookInfo = info; + this.pageTitle.setBookPageTitle(book); + + // Set cover URL with auth token + const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken(); + this.bookCoverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/cover/${this.bookId}?token=${encodeURIComponent(token || '')}`; + this.coverUrl = this.audiobookService.getEmbeddedCoverUrl(this.bookId); + + // Restore progress and load audio + if (book.audiobookProgress) { + // Store saved position - will be applied when audio loads + this.savedPosition = book.audiobookProgress.positionMs + ? book.audiobookProgress.positionMs / 1000 + : 0; + } + + if (info.folderBased && info.tracks && info.tracks.length > 0) { + // Folder-based audiobook + const trackIndex = book.audiobookProgress?.trackIndex ?? 0; + this.currentTrackIndex = trackIndex; + this.loadTrack(trackIndex); + } else { + // Single-file audiobook + this.audioSrc = this.audiobookService.getStreamUrl(this.bookId); + } + + this.isLoading = false; + + // Load bookmarks + this.loadBookmarks(); + }, + error: () => { + this.messageService.add({ + severity: 'error', + summary: 'Error', + detail: 'Failed to load audiobook' + }); + this.isLoading = false; + } + }); + } + + private loadTrack(index: number): void { + if (!this.audiobookInfo.tracks || index < 0 || index >= this.audiobookInfo.tracks.length) { + return; + } + this.currentTrackIndex = index; + this.audioSrc = this.audiobookService.getTrackStreamUrl(this.bookId, index); + this.audioLoading = true; + // Reset buffered since it's a new track + this.buffered = 0; + } + + private resetState(): void { + // Stop any existing intervals + this.stopProgressSaveInterval(); + + // Reset audio state + this.isPlaying = false; + this.currentTime = 0; + this.duration = 0; + this.buffered = 0; + this.savedPosition = 0; + this.currentTrackIndex = 0; + this.audioSrc = ''; + this.audioLoading = true; + + // Reset UI state + this.showTrackList = false; + this.coverUrl = undefined; + this.bookCoverUrl = undefined; + } + + // Audio event handlers + onAudioLoaded(): void { + this.audioLoading = false; + const audio = this.audioElement?.nativeElement; + if (audio) { + this.duration = audio.duration; + audio.volume = this.volume; + audio.playbackRate = this.playbackRate; + + // Apply saved position now that we know the duration + if (this.savedPosition > 0 && this.savedPosition < this.duration) { + audio.currentTime = this.savedPosition; + this.currentTime = this.savedPosition; + } + + // Setup Media Session for background playback + this.setupMediaSession(); + + // Note: Session will be started when user presses play, not on load + } + } + + onTimeUpdate(): void { + const audio = this.audioElement?.nativeElement; + if (audio) { + const previousChapterIndex = this.getCurrentChapterIndex(); + this.currentTime = audio.currentTime; + + // Update audiobook session position + this.audiobookSessionService.updatePosition( + Math.round(this.currentTime * 1000), + this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined + ); + + // Update Media Session position state (throttled to every 5 seconds) + if (Math.floor(this.currentTime) % 5 === 0) { + this.updateMediaSessionPositionState(); + } + + // Update metadata if chapter changed (for single-file audiobooks) + if (!this.audiobookInfo.folderBased && this.getCurrentChapterIndex() !== previousChapterIndex) { + this.updateMediaSessionMetadata(); + } + + // Check sleep timer end of chapter + this.checkSleepTimerEndOfChapter(); + } + } + + onProgress(): void { + const audio = this.audioElement?.nativeElement; + if (audio && audio.buffered.length > 0) { + this.buffered = audio.buffered.end(audio.buffered.length - 1); + } + } + + onAudioEnded(): void { + // For folder-based audiobooks, play next track + if (this.audiobookInfo.folderBased && this.audiobookInfo.tracks) { + if (this.currentTrackIndex < this.audiobookInfo.tracks.length - 1) { + this.nextTrack(); + } else { + this.isPlaying = false; + this.stopProgressSaveInterval(); + this.saveProgress(); + this.updateMediaSessionPlaybackState(); + // Pause session when audiobook ends + this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000)); + } + } else { + this.isPlaying = false; + this.stopProgressSaveInterval(); + this.saveProgress(); + this.updateMediaSessionPlaybackState(); + // Pause session when audiobook ends + this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000)); + } + } + + onAudioError(): void { + this.audioLoading = false; + this.messageService.add({ + severity: 'error', + summary: 'Error', + detail: 'Failed to load audio' + }); + } + + // Media Session API for background playback + private setupMediaSession(): void { + if (!('mediaSession' in navigator)) return; + + this.updateMediaSessionMetadata(); + + navigator.mediaSession.setActionHandler('play', () => { + if (!this.isPlaying) this.togglePlay(); + }); + navigator.mediaSession.setActionHandler('pause', () => { + if (this.isPlaying) this.togglePlay(); + }); + navigator.mediaSession.setActionHandler('seekbackward', () => this.seekRelative(-30)); + navigator.mediaSession.setActionHandler('seekforward', () => this.seekRelative(30)); + navigator.mediaSession.setActionHandler('previoustrack', () => { + this.audiobookInfo.folderBased ? this.previousTrack() : this.previousChapter(); + }); + navigator.mediaSession.setActionHandler('nexttrack', () => { + this.audiobookInfo.folderBased ? this.nextTrack() : this.nextChapter(); + }); + navigator.mediaSession.setActionHandler('seekto', (details) => { + if (details.seekTime !== undefined) { + const audio = this.audioElement?.nativeElement; + if (audio) { + audio.currentTime = details.seekTime; + this.currentTime = details.seekTime; + } + } + }); + } + + private updateMediaSessionMetadata(): void { + if (!('mediaSession' in navigator)) return; + + const title = this.audiobookInfo.folderBased + ? this.currentTrack?.title + : this.getCurrentChapter()?.title || this.audiobookInfo.title; + + navigator.mediaSession.metadata = new MediaMetadata({ + title: title || 'Untitled', + artist: this.audiobookInfo.author || 'Unknown Author', + album: this.audiobookInfo.title, + artwork: this.coverUrl + ? [{ src: this.coverUrl, sizes: '512x512', type: 'image/png' }] + : [] + }); + } + + private updateMediaSessionPlaybackState(): void { + if ('mediaSession' in navigator) { + navigator.mediaSession.playbackState = this.isPlaying ? 'playing' : 'paused'; + } + } + + private updateMediaSessionPositionState(): void { + if ('mediaSession' in navigator && 'setPositionState' in navigator.mediaSession) { + try { + navigator.mediaSession.setPositionState({ + duration: this.duration, + playbackRate: this.playbackRate, + position: this.currentTime + }); + } catch { + // Ignore errors from invalid position state + } + } + } + + // Playback controls + togglePlay(): void { + const audio = this.audioElement?.nativeElement; + if (!audio) return; + + if (this.isPlaying) { + audio.pause(); + this.stopProgressSaveInterval(); + this.saveProgress(); + // Pause the listening session + this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000)); + } else { + audio.play(); + this.startProgressSaveInterval(); + // Start or resume the listening session + if (this.audiobookSessionService.isSessionActive()) { + this.audiobookSessionService.resumeSession(Math.round(this.currentTime * 1000)); + } else { + this.audiobookSessionService.startSession( + this.bookId, + Math.round(this.currentTime * 1000), + this.playbackRate, + this.audiobookInfo?.bookFileId, + this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined + ); + } + } + this.isPlaying = !this.isPlaying; + this.updateMediaSessionPlaybackState(); + } + + seek(event: SliderChangeEvent): void { + const audio = this.audioElement?.nativeElement; + if (audio && this.duration > 0 && event.value !== undefined) { + audio.currentTime = event.value as number; + this.currentTime = event.value as number; + } + } + + seekRelative(seconds: number): void { + const audio = this.audioElement?.nativeElement; + if (audio) { + const newTime = Math.max(0, Math.min(this.duration, audio.currentTime + seconds)); + audio.currentTime = newTime; + this.currentTime = newTime; + } + } + + // Volume controls + setVolume(event: SliderChangeEvent): void { + const audio = this.audioElement?.nativeElement; + if (event.value !== undefined) { + this.volume = event.value as number; + this.isMuted = this.volume === 0; + if (audio) { + audio.volume = this.volume; + } + } + } + + toggleMute(): void { + const audio = this.audioElement?.nativeElement; + if (!audio) return; + + if (this.isMuted) { + this.volume = this.previousVolume || 0.5; + audio.volume = this.volume; + this.isMuted = false; + } else { + this.previousVolume = this.volume; + this.volume = 0; + audio.volume = 0; + this.isMuted = true; + } + } + + // Playback rate + setPlaybackRate(rate: number): void { + if (rate === undefined || rate === null) return; + const audio = this.audioElement?.nativeElement; + this.playbackRate = rate; + if (audio) { + audio.playbackRate = rate; + } + this.updateMediaSessionPositionState(); + // Update session with new playback rate + this.audiobookSessionService.updatePlaybackRate(rate); + } + + // Track navigation (folder-based) + previousTrack(): void { + if (this.currentTrackIndex > 0) { + this.loadTrack(this.currentTrackIndex - 1); + this.currentTime = 0; + this.savedPosition = 0; // Reset saved position for new track + if (this.isPlaying) { + setTimeout(() => { + this.audioElement?.nativeElement?.play(); + this.updateMediaSessionMetadata(); + }, 100); + } + } + } + + nextTrack(): void { + if (this.audiobookInfo.tracks && this.currentTrackIndex < this.audiobookInfo.tracks.length - 1) { + this.loadTrack(this.currentTrackIndex + 1); + this.currentTime = 0; + this.savedPosition = 0; // Reset saved position for new track + if (this.isPlaying) { + setTimeout(() => { + this.audioElement?.nativeElement?.play(); + this.updateMediaSessionMetadata(); + }, 100); + } + } + } + + selectTrack(track: AudiobookTrack): void { + this.loadTrack(track.index); + this.currentTime = 0; + this.savedPosition = 0; // Reset saved position for new track + this.showTrackList = false; + setTimeout(() => { + this.audioElement?.nativeElement?.play(); + this.isPlaying = true; + this.startProgressSaveInterval(); + this.updateMediaSessionMetadata(); + this.updateMediaSessionPlaybackState(); + // Start or resume listening session + if (this.audiobookSessionService.isSessionActive()) { + this.audiobookSessionService.resumeSession(0); + } else { + this.audiobookSessionService.startSession( + this.bookId, 0, this.playbackRate, + this.audiobookInfo?.bookFileId, track.index + ); + } + }, 100); + } + + // Chapter navigation (single-file) + selectChapter(chapter: AudiobookChapter): void { + const audio = this.audioElement?.nativeElement; + if (audio) { + audio.currentTime = chapter.startTimeMs / 1000; + this.currentTime = chapter.startTimeMs / 1000; + this.showTrackList = false; + this.updateMediaSessionMetadata(); + if (!this.isPlaying) { + audio.play(); + this.isPlaying = true; + this.startProgressSaveInterval(); + this.updateMediaSessionPlaybackState(); + // Start or resume listening session + if (this.audiobookSessionService.isSessionActive()) { + this.audiobookSessionService.resumeSession(chapter.startTimeMs); + } else { + this.audiobookSessionService.startSession( + this.bookId, chapter.startTimeMs, this.playbackRate, + this.audiobookInfo?.bookFileId + ); + } + } + } + } + + getCurrentChapter(): AudiobookChapter | undefined { + if (!this.audiobookInfo?.chapters) return undefined; + const currentMs = this.currentTime * 1000; + return this.audiobookInfo.chapters.find( + ch => currentMs >= ch.startTimeMs && currentMs < ch.endTimeMs + ); + } + + getCurrentChapterIndex(): number { + const chapter = this.getCurrentChapter(); + return chapter?.index ?? 0; + } + + hasMultipleChapters(): boolean { + return (this.audiobookInfo?.chapters?.length ?? 0) > 1; + } + + canGoPreviousChapter(): boolean { + return this.getCurrentChapterIndex() > 0; + } + + canGoNextChapter(): boolean { + const chapters = this.audiobookInfo?.chapters; + if (!chapters) return false; + return this.getCurrentChapterIndex() < chapters.length - 1; + } + + previousChapter(): void { + const chapters = this.audiobookInfo?.chapters; + if (!chapters) return; + + const currentIndex = this.getCurrentChapterIndex(); + if (currentIndex > 0) { + const prevChapter = chapters[currentIndex - 1]; + this.selectChapter(prevChapter); + } + } + + nextChapter(): void { + const chapters = this.audiobookInfo?.chapters; + if (!chapters) return; + + const currentIndex = this.getCurrentChapterIndex(); + if (currentIndex < chapters.length - 1) { + const nextChapter = chapters[currentIndex + 1]; + this.selectChapter(nextChapter); + } + } + + // Progress management - save every 5 seconds while playing + private startProgressSaveInterval(): void { + if (this.progressSaveInterval) return; // Already running + + this.progressSaveInterval = setInterval(() => { + if (this.isPlaying) { + this.saveProgress(); + } + }, 5000); + } + + private stopProgressSaveInterval(): void { + if (this.progressSaveInterval) { + clearInterval(this.progressSaveInterval); + this.progressSaveInterval = undefined; + } + } + + private saveProgress(): void { + if (!this.audiobookInfo) return; + + const totalDuration = this.getTotalDuration(); + const currentPosition = this.getCurrentTotalPosition(); + const percentage = totalDuration > 0 ? (currentPosition / totalDuration) * 100 : 0; + + // For folder-based: positionMs = track position (for seeking within track) + // For single-file: positionMs = absolute position + const positionMs = this.audiobookInfo.folderBased + ? Math.round(this.currentTime * 1000) // Track position + : Math.round(currentPosition * 1000); // Absolute position + + const progress: AudiobookProgress = { + positionMs: positionMs, + trackIndex: this.audiobookInfo.folderBased ? this.currentTrackIndex : undefined, + percentage: Math.round(percentage * 10) / 10 + }; + + this.audiobookService.saveProgress( + this.bookId, + progress, + this.audiobookInfo.bookFileId + ).subscribe(); + } + + private getTotalDuration(): number { + if (this.audiobookInfo.folderBased && this.audiobookInfo.tracks) { + return this.audiobookInfo.tracks.reduce((sum, t) => sum + t.durationMs, 0) / 1000; + } + return this.duration; + } + + private getCurrentTotalPosition(): number { + if (this.audiobookInfo.folderBased && this.audiobookInfo.tracks) { + const currentTrack = this.audiobookInfo.tracks[this.currentTrackIndex]; + return (currentTrack?.cumulativeStartMs || 0) / 1000 + this.currentTime; + } + return this.currentTime; + } + + // Utility methods + formatTime(seconds: number): string { + if (!seconds || !isFinite(seconds)) return '0:00'; + const h = Math.floor(seconds / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = Math.floor(seconds % 60); + + if (h > 0) { + return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`; + } + return `${m}:${s.toString().padStart(2, '0')}`; + } + + formatDuration(ms: number): string { + return this.formatTime(ms / 1000); + } + + getProgressPercent(): number { + return this.duration > 0 ? (this.currentTime / this.duration) * 100 : 0; + } + + getBufferedPercent(): number { + return this.duration > 0 ? (this.buffered / this.duration) * 100 : 0; + } + + onCoverError(): void { + // Fallback to book cover if embedded cover fails + // Only fallback once to prevent infinite loop + if (this.coverUrl !== this.bookCoverUrl) { + this.coverUrl = this.bookCoverUrl; + } else { + // Both covers failed, use a placeholder + this.coverUrl = undefined; + } + } + + toggleTrackList(): void { + this.showTrackList = !this.showTrackList; + } + + closeReader(): void { + this.saveProgress(); + if (this.audiobookSessionService.isSessionActive()) { + this.audiobookSessionService.endSession(Math.round(this.currentTime * 1000)); + } + this.location.back(); + } + + getVolumeIcon(): string { + if (this.isMuted || this.volume === 0) return 'pi pi-volume-off'; + if (this.volume < 0.5) return 'pi pi-volume-down'; + return 'pi pi-volume-up'; + } + + get currentTrack(): AudiobookTrack | undefined { + return this.audiobookInfo?.tracks?.[this.currentTrackIndex]; + } + + // ==================== SLEEP TIMER ==================== + + setSleepTimer(minutes: number): void { + this.cancelSleepTimer(); + this.sleepTimerRemaining = minutes * 60; + this.sleepTimerActive = true; + this.sleepTimerEndOfChapter = false; + this.originalVolume = this.volume; + this.updateSleepTimerMenuVisibility(); + + this.sleepTimerInterval = setInterval(() => { + this.sleepTimerRemaining--; + + // Fade out volume in last 30 seconds + if (this.sleepTimerRemaining <= 30 && this.sleepTimerRemaining > 0) { + const fadeRatio = this.sleepTimerRemaining / 30; + const audio = this.audioElement?.nativeElement; + if (audio) { + audio.volume = this.originalVolume * fadeRatio; + } + } + + if (this.sleepTimerRemaining <= 0) { + this.triggerSleepTimerStop(); + } + }, 1000); + + this.messageService.add({ + severity: 'info', + summary: 'Sleep Timer', + detail: `Playback will stop in ${minutes} minutes` + }); + } + + setSleepTimerEndOfChapter(): void { + this.cancelSleepTimer(); + this.sleepTimerActive = true; + this.sleepTimerEndOfChapter = true; + this.sleepTimerRemaining = 0; + this.originalVolume = this.volume; + this.updateSleepTimerMenuVisibility(); + + this.messageService.add({ + severity: 'info', + summary: 'Sleep Timer', + detail: 'Playback will stop at end of chapter' + }); + } + + cancelSleepTimer(): void { + if (this.sleepTimerInterval) { + clearInterval(this.sleepTimerInterval); + this.sleepTimerInterval = undefined; + } + + // Restore original volume if we were fading + if (this.sleepTimerActive && this.originalVolume > 0) { + const audio = this.audioElement?.nativeElement; + if (audio) { + audio.volume = this.originalVolume; + this.volume = this.originalVolume; + } + } + + this.sleepTimerActive = false; + this.sleepTimerRemaining = 0; + this.sleepTimerEndOfChapter = false; + this.updateSleepTimerMenuVisibility(); + } + + private triggerSleepTimerStop(): void { + const audio = this.audioElement?.nativeElement; + if (audio) { + audio.pause(); + audio.volume = this.originalVolume; + this.volume = this.originalVolume; + } + this.isPlaying = false; + this.stopProgressSaveInterval(); + this.saveProgress(); + this.cancelSleepTimer(); + this.updateMediaSessionPlaybackState(); + // Pause the listening session + this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000)); + + this.messageService.add({ + severity: 'info', + summary: 'Sleep Timer', + detail: 'Playback stopped by sleep timer' + }); + } + + private updateSleepTimerMenuVisibility(): void { + // Show/hide cancel option based on timer state + const cancelItem = this.sleepTimerOptions.find(item => item.label === 'Cancel timer'); + if (cancelItem) { + cancelItem.visible = this.sleepTimerActive; + } + } + + formatSleepTimerRemaining(): string { + if (this.sleepTimerEndOfChapter) { + return 'End of chapter'; + } + const minutes = Math.floor(this.sleepTimerRemaining / 60); + const seconds = this.sleepTimerRemaining % 60; + return `${minutes}:${seconds.toString().padStart(2, '0')}`; + } + + // Check for end of chapter in onTimeUpdate for sleep timer + private checkSleepTimerEndOfChapter(): void { + if (!this.sleepTimerEndOfChapter || !this.sleepTimerActive) return; + + const currentChapter = this.getCurrentChapter(); + if (currentChapter) { + const currentMs = this.currentTime * 1000; + // If we're within 1 second of chapter end, trigger stop + if (currentMs >= currentChapter.endTimeMs - 1000) { + this.triggerSleepTimerStop(); + } + } + } + + // ==================== BOOKMARKS ==================== + + loadBookmarks(): void { + this.bookMarkService.getBookmarksForBook(this.bookId) + .pipe(takeUntil(this.destroy$)) + .subscribe(bookmarks => { + this.bookmarks = bookmarks; + }); + } + + toggleBookmarkList(): void { + this.showBookmarkList = !this.showBookmarkList; + if (this.showBookmarkList && this.bookmarks.length === 0) { + this.loadBookmarks(); + } + } + + addBookmark(): void { + const currentChapter = this.getCurrentChapter(); + const currentTrack = this.currentTrack; + + let title: string; + if (this.audiobookInfo.folderBased && currentTrack) { + title = `${currentTrack.title} - ${this.formatTime(this.currentTime)}`; + } else if (currentChapter) { + title = `${currentChapter.title} - ${this.formatTime(this.currentTime)}`; + } else { + title = `Bookmark at ${this.formatTime(this.currentTime)}`; + } + + const request: CreateBookMarkRequest = { + bookId: this.bookId, + title: title, + positionMs: Math.round(this.currentTime * 1000), + trackIndex: this.audiobookInfo.folderBased ? this.currentTrackIndex : undefined + }; + + this.bookMarkService.createBookmark(request) + .pipe(takeUntil(this.destroy$)) + .subscribe({ + next: (bookmark) => { + this.bookmarks = [...this.bookmarks, bookmark]; + this.messageService.add({ + severity: 'success', + summary: 'Bookmark Added', + detail: title + }); + }, + error: (err) => { + const isDuplicate = err?.status === 409; + this.messageService.add({ + severity: isDuplicate ? 'warn' : 'error', + summary: isDuplicate ? 'Bookmark Exists' : 'Error', + detail: isDuplicate ? 'A bookmark already exists at this position' : 'Failed to add bookmark' + }); + } + }); + } + + goToBookmark(bookmark: BookMark): void { + // Handle track switching for folder-based audiobooks + if (this.audiobookInfo.folderBased && bookmark.trackIndex !== undefined && bookmark.trackIndex !== null) { + if (bookmark.trackIndex !== this.currentTrackIndex) { + this.loadTrack(bookmark.trackIndex); + // Wait for track to load, then seek + this.savedPosition = (bookmark.positionMs || 0) / 1000; + } else { + // Same track, just seek + const audio = this.audioElement?.nativeElement; + if (audio && bookmark.positionMs) { + audio.currentTime = bookmark.positionMs / 1000; + this.currentTime = bookmark.positionMs / 1000; + } + } + } else { + // Single-file audiobook + const audio = this.audioElement?.nativeElement; + if (audio && bookmark.positionMs) { + audio.currentTime = bookmark.positionMs / 1000; + this.currentTime = bookmark.positionMs / 1000; + } + } + + this.showBookmarkList = false; + + if (!this.isPlaying) { + setTimeout(() => { + this.audioElement?.nativeElement?.play(); + this.isPlaying = true; + this.startProgressSaveInterval(); + // Start or resume listening session + const positionMs = bookmark.positionMs || 0; + if (this.audiobookSessionService.isSessionActive()) { + this.audiobookSessionService.resumeSession(positionMs); + } else { + this.audiobookSessionService.startSession( + this.bookId, positionMs, this.playbackRate, + this.audiobookInfo?.bookFileId, + this.audiobookInfo?.folderBased ? bookmark.trackIndex : undefined + ); + } + }, 100); + } + } + + deleteBookmark(event: MouseEvent, bookmarkId: number): void { + event.stopPropagation(); + this.bookMarkService.deleteBookmark(bookmarkId) + .pipe(takeUntil(this.destroy$)) + .subscribe(() => { + this.bookmarks = this.bookmarks.filter(b => b.id !== bookmarkId); + this.messageService.add({ + severity: 'info', + summary: 'Bookmark Deleted' + }); + }); + } + + formatBookmarkPosition(bookmark: BookMark): string { + if (bookmark.positionMs) { + return this.formatTime(bookmark.positionMs / 1000); + } + return ''; + } +} diff --git a/booklore-ui/src/app/features/readers/audiobook-reader/audiobook.model.ts b/booklore-ui/src/app/features/readers/audiobook-reader/audiobook.model.ts new file mode 100644 index 000000000..f9a2d96eb --- /dev/null +++ b/booklore-ui/src/app/features/readers/audiobook-reader/audiobook.model.ts @@ -0,0 +1,39 @@ +export interface AudiobookInfo { + bookId: number; + bookFileId: number; + title?: string; + author?: string; + narrator?: string; + durationMs: number; + bitrate?: number; + codec?: string; + sampleRate?: number; + channels?: number; + folderBased: boolean; + chapters?: AudiobookChapter[]; + tracks?: AudiobookTrack[]; +} + +export interface AudiobookChapter { + index: number; + title: string; + startTimeMs: number; + endTimeMs: number; + durationMs: number; +} + +export interface AudiobookTrack { + index: number; + fileName: string; + title: string; + durationMs: number; + fileSizeBytes: number; + cumulativeStartMs: number; +} + +export interface AudiobookProgress { + positionMs: number; + trackIndex?: number; + trackPositionMs?: number; + percentage: number; +} diff --git a/booklore-ui/src/app/features/readers/audiobook-reader/audiobook.service.ts b/booklore-ui/src/app/features/readers/audiobook-reader/audiobook.service.ts new file mode 100644 index 000000000..a6fcb51e7 --- /dev/null +++ b/booklore-ui/src/app/features/readers/audiobook-reader/audiobook.service.ts @@ -0,0 +1,64 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import { API_CONFIG } from '../../../core/config/api-config'; +import { AudiobookInfo, AudiobookProgress } from './audiobook.model'; +import { AuthService } from '../../../shared/service/auth.service'; +import { BookFileProgress } from '../../book/model/book.model'; + +@Injectable({ + providedIn: 'root' +}) +export class AudiobookService { + private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/audiobook`; + private readonly booksUrl = `${API_CONFIG.BASE_URL}/api/v1/books`; + + private http = inject(HttpClient); + private authService = inject(AuthService); + + getAudiobookInfo(bookId: number, bookType?: string): Observable { + const params: Record = {}; + if (bookType) { + params['bookType'] = bookType; + } + return this.http.get(`${this.baseUrl}/${bookId}/info`, { params }); + } + + getStreamUrl(bookId: number, trackIndex?: number): string { + const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken(); + let url = `${this.baseUrl}/${bookId}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`; + if (trackIndex !== undefined && trackIndex !== null) { + url += `&trackIndex=${trackIndex}`; + } + return url; + } + + getTrackStreamUrl(bookId: number, trackIndex: number): string { + const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken(); + return `${this.baseUrl}/${bookId}/track/${trackIndex}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`; + } + + getEmbeddedCoverUrl(bookId: number): string { + const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken(); + return `${this.baseUrl}/${bookId}/cover?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`; + } + + saveProgress(bookId: number, progress: AudiobookProgress, bookFileId?: number): Observable { + if (bookFileId) { + const fileProgress: BookFileProgress = { + bookFileId: bookFileId, + positionData: progress.positionMs.toString(), + positionHref: progress.trackIndex?.toString(), + progressPercent: progress.percentage + }; + return this.http.post(`${this.booksUrl}/progress`, { + bookId, + fileProgress + }); + } + return this.http.post(`${this.booksUrl}/progress`, { + bookId, + audiobookProgress: progress + }); + } +} diff --git a/booklore-ui/src/app/features/readers/audiobook-reader/index.ts b/booklore-ui/src/app/features/readers/audiobook-reader/index.ts new file mode 100644 index 000000000..225942a39 --- /dev/null +++ b/booklore-ui/src/app/features/readers/audiobook-reader/index.ts @@ -0,0 +1,3 @@ +export * from './audiobook-reader.component'; +export * from './audiobook.service'; +export * from './audiobook.model'; diff --git a/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.ts b/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.ts index f7f8dee7c..70af178e6 100644 --- a/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.ts +++ b/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.ts @@ -2,7 +2,7 @@ import {Component, HostListener, inject, OnDestroy, OnInit} from '@angular/core' import {ActivatedRoute, Router} from '@angular/router'; import {CommonModule} from '@angular/common'; import {forkJoin, Subject} from 'rxjs'; -import {filter, first, takeUntil, timeout} from 'rxjs/operators'; +import {filter, first, map, switchMap, takeUntil, timeout} from 'rxjs/operators'; import {PageTitleService} from "../../../shared/service/page-title.service"; import {CbxReaderService} from '../../book/service/cbx-reader.service'; import {BookService} from '../../book/service/book.service'; @@ -55,6 +55,8 @@ export class CbxReaderComponent implements OnInit, OnDestroy { bookType!: BookType; bookId!: number; + bookFileId?: number; + altBookType?: string; pages: number[] = []; currentPage = 0; isLoading = true; @@ -129,34 +131,48 @@ export class CbxReaderComponent implements OnInit, OnDestroy { this.route.paramMap.subscribe((params) => { this.isLoading = true; this.bookId = +params.get('bookId')!; + this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined; this.previousBookInSeries = null; this.nextBookInSeries = null; this.currentBook = null; - forkJoin([ - this.bookService.getBookByIdFromAPI(this.bookId, false), - this.bookService.getBookSetting(this.bookId), - this.userService.getMyself() - ]).subscribe({ - next: ([book, bookSettings, myself]) => { - const userSettings = myself.userSettings; - this.bookType = book.bookType; + this.bookService.getBookByIdFromAPI(this.bookId, false).pipe( + switchMap((book) => { + // Use alternative bookType from query param if provided, otherwise use primary + this.bookType = (this.altBookType as BookType) ?? book.primaryFile?.bookType!; this.currentBook = book; + // Determine which file ID to use for progress tracking + if (this.altBookType) { + const altFile = book.alternativeFormats?.find(f => f.bookType === this.altBookType); + this.bookFileId = altFile?.id; + } else { + this.bookFileId = book.primaryFile?.id; + } + + return forkJoin([ + this.bookService.getBookSetting(this.bookId, this.bookFileId!), + this.userService.getMyself() + ]).pipe(map(([bookSettings, myself]) => ({ book, bookSettings, myself }))); + }) + ).subscribe({ + next: ({ book, bookSettings, myself }) => { + const userSettings = myself.userSettings; + this.pageTitle.setBookPageTitle(book); const title = book.metadata?.title || book.fileName; this.headerService.initialize(this.bookId, title, this.destroy$); - this.sidebarService.initialize(this.bookId, book, this.destroy$); + this.sidebarService.initialize(this.bookId, book, this.destroy$, this.altBookType); if (book.metadata?.seriesName) { this.loadSeriesNavigationAsync(book); } const pagesObservable = this.bookType === CbxReaderComponent.TYPE_PDF - ? this.pdfReaderService.getAvailablePages(this.bookId) - : this.cbxReaderService.getAvailablePages(this.bookId); + ? this.pdfReaderService.getAvailablePages(this.bookId, this.altBookType) + : this.cbxReaderService.getAvailablePages(this.bookId, this.altBookType); pagesObservable.subscribe({ next: (pages) => { @@ -728,8 +744,8 @@ export class CbxReaderComponent implements OnInit, OnDestroy { private getPageImageUrl(pageIndex: number): string { return this.bookType === CbxReaderComponent.TYPE_PDF - ? this.pdfReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex]) - : this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex]); + ? this.pdfReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex], this.altBookType) + : this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex], this.altBookType); } get infiniteScrollImageUrls(): string[] { @@ -765,10 +781,10 @@ export class CbxReaderComponent implements OnInit, OnDestroy { : 0; if (this.bookType === CbxReaderComponent.TYPE_CBX) { - this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe(); + this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage, this.bookFileId).subscribe(); } if (this.bookType === CbxReaderComponent.TYPE_PDF) { - this.bookService.savePdfProgress(this.bookId, this.currentPage + 1, percentage).subscribe(); + this.bookService.savePdfProgress(this.bookId, this.currentPage + 1, percentage, this.bookFileId).subscribe(); } } diff --git a/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.html b/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.html index e3beb8d5a..324f7ace8 100644 --- a/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.html +++ b/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.html @@ -109,7 +109,7 @@ @if (bookmarks.length > 0) {
diff --git a/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.ts b/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.ts index 7d4581225..8f5807c78 100644 --- a/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.ts +++ b/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.component.ts @@ -1,6 +1,7 @@ import {Component, inject, OnDestroy, OnInit} from '@angular/core'; import {CommonModule, DatePipe} from '@angular/common'; import {FormsModule} from '@angular/forms'; +import {TranslocoPipe} from '@jsverse/transloco'; import {Subject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {CbxSidebarService, CbxSidebarTab, SidebarBookInfo} from './cbx-sidebar.service'; @@ -14,7 +15,7 @@ import {ReaderIconComponent} from '../../../ebook-reader'; standalone: true, templateUrl: './cbx-sidebar.component.html', styleUrls: ['./cbx-sidebar.component.scss'], - imports: [CommonModule, FormsModule, ReaderIconComponent, DatePipe] + imports: [CommonModule, FormsModule, TranslocoPipe, ReaderIconComponent, DatePipe] }) export class CbxSidebarComponent implements OnInit, OnDestroy { private sidebarService = inject(CbxSidebarService); diff --git a/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.service.ts b/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.service.ts index 5b1a749ea..f052787bf 100644 --- a/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.service.ts +++ b/booklore-ui/src/app/features/readers/cbx-reader/layout/sidebar/cbx-sidebar.service.ts @@ -1,6 +1,7 @@ import {inject, Injectable} from '@angular/core'; import {BehaviorSubject, Subject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; +import {TranslocoService} from '@jsverse/transloco'; import {CbxPageInfo, CbxReaderService} from '../../../../book/service/cbx-reader.service'; import {UrlHelperService} from '../../../../../shared/service/url-helper.service'; import {Book} from '../../../../book/model/book.model'; @@ -22,6 +23,7 @@ export class CbxSidebarService { private cbxReaderService = inject(CbxReaderService); private bookMarkService = inject(BookMarkService); private bookNoteV2Service = inject(BookNoteV2Service); + private readonly t = inject(TranslocoService); private destroy$ = new Subject(); private bookId!: number; @@ -63,7 +65,7 @@ export class CbxSidebarService { this._bookInfo.next({ id: book.id, - title: book.metadata?.title || book.fileName || 'Untitled', + title: book.metadata?.title || book.fileName || this.t.translate('readerCbx.sidebar.untitled'), authors: (book.metadata?.authors || []).join(', '), coverUrl: this.urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn) }); @@ -129,7 +131,7 @@ export class CbxSidebarService { const request: CreateBookMarkRequest = { bookId: this.bookId, cfi: pageNumber.toString(), - title: title || `Page ${pageNumber}` + title: title || `${this.t.translate('readerCbx.sidebar.page')} ${pageNumber}` }; this.bookMarkService.createBookmark(request) @@ -177,7 +179,7 @@ export class CbxSidebarService { cfi: pageNumber.toString(), noteContent, color: color || '#FFC107', - chapterTitle: `Page ${pageNumber}` + chapterTitle: `${this.t.translate('readerCbx.sidebar.page')} ${pageNumber}` }; this.bookNoteV2Service.createNote(request) diff --git a/booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts index a64fe2d9e..e720c6942 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts @@ -184,9 +184,9 @@ export class ReaderViewManagerService { this.annotationService.addAnnotations(this.view, annotations); } - updateHeadersAndFooters(chapterName: string, pageInfo?: PageInfo, theme?: ThemeInfo): void { + updateHeadersAndFooters(chapterName: string, pageInfo?: PageInfo, theme?: ThemeInfo, timeRemainingLabel?: string): void { const renderer = this.getRenderer(); - PageDecorator.updateHeadersAndFooters(renderer, chapterName, pageInfo, theme); + PageDecorator.updateHeadersAndFooters(renderer, chapterName, pageInfo, theme, timeRemainingLabel); } getChapters(): TocItem[] { diff --git a/booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.html b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.html index 6df807f2d..7df5f1167 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.html +++ b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.html @@ -1,67 +1,68 @@ +
-

Book Information

- +

{{ t('title') }}

+